From 8858012fd1a3577b7b0d9d4a5a81f77e3f3fa331 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 6 Jan 2026 13:12:54 +0000 Subject: [PATCH 1/9] chore: emit unified exec begin only when PTY exist (#8780) --- .../core/src/tools/handlers/unified_exec.rs | 18 ------------------ .../core/src/unified_exec/session_manager.rs | 17 +++++++++++++++++ 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/codex-rs/core/src/tools/handlers/unified_exec.rs b/codex-rs/core/src/tools/handlers/unified_exec.rs index 00418d8a65..bda8f985a7 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec.rs @@ -1,7 +1,6 @@ use crate::function_tool::FunctionCallError; use crate::is_safe_command::is_known_safe_command; use crate::protocol::EventMsg; -use crate::protocol::ExecCommandSource; use crate::protocol::TerminalInteractionEvent; use crate::sandboxing::SandboxPermissions; use crate::shell::Shell; @@ -9,9 +8,6 @@ use crate::shell::get_shell_by_model_provided_path; use crate::tools::context::ToolInvocation; use crate::tools::context::ToolOutput; use crate::tools::context::ToolPayload; -use crate::tools::events::ToolEmitter; -use crate::tools::events::ToolEventCtx; -use crate::tools::events::ToolEventStage; use crate::tools::handlers::apply_patch::intercept_apply_patch; use crate::tools::registry::ToolHandler; use crate::tools::registry::ToolKind; @@ -172,20 +168,6 @@ impl ToolHandler for UnifiedExecHandler { return Ok(output); } - let event_ctx = ToolEventCtx::new( - context.session.as_ref(), - context.turn.as_ref(), - &context.call_id, - None, - ); - let emitter = ToolEmitter::unified_exec( - &command, - cwd.clone(), - ExecCommandSource::UnifiedExecStartup, - Some(process_id.clone()), - ); - emitter.emit(event_ctx, ToolEventStage::Begin).await; - manager .exec_command( ExecCommandRequest { diff --git a/codex-rs/core/src/unified_exec/session_manager.rs b/codex-rs/core/src/unified_exec/session_manager.rs index 0a1e29e8fb..df473959d2 100644 --- a/codex-rs/core/src/unified_exec/session_manager.rs +++ b/codex-rs/core/src/unified_exec/session_manager.rs @@ -16,8 +16,12 @@ use crate::codex::TurnContext; use crate::exec_env::create_env; use crate::protocol::BackgroundEventEvent; use crate::protocol::EventMsg; +use crate::protocol::ExecCommandSource; use crate::sandboxing::ExecEnv; use crate::sandboxing::SandboxPermissions; +use crate::tools::events::ToolEmitter; +use crate::tools::events::ToolEventCtx; +use crate::tools::events::ToolEventStage; use crate::tools::orchestrator::ToolOrchestrator; use crate::tools::runtimes::unified_exec::UnifiedExecRequest as UnifiedExecToolRequest; use crate::tools::runtimes::unified_exec::UnifiedExecRuntime; @@ -141,6 +145,19 @@ impl UnifiedExecSessionManager { }; let transcript = Arc::new(tokio::sync::Mutex::new(CommandTranscript::default())); + let event_ctx = ToolEventCtx::new( + context.session.as_ref(), + context.turn.as_ref(), + &context.call_id, + None, + ); + let emitter = ToolEmitter::unified_exec( + &request.command, + cwd.clone(), + ExecCommandSource::UnifiedExecStartup, + Some(request.process_id.clone()), + ); + emitter.emit(event_ctx, ToolEventStage::Begin).await; start_streaming_output(&session, context, Arc::clone(&transcript)); let max_tokens = resolve_max_tokens(request.max_output_tokens); From 7ecd0dc9b384a5372f195de093d4089b4358fb45 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Tue, 6 Jan 2026 07:10:27 -0800 Subject: [PATCH 2/9] fix: stop honoring CODEX_MANAGED_CONFIG_PATH environment variable in production (#8762) --- .../app-server/src/codex_message_processor.rs | 2 +- codex-rs/app-server/src/config_api.rs | 9 ++++- codex-rs/app-server/src/lib.rs | 12 +++++- codex-rs/app-server/src/main.rs | 34 ++++++++++++++++- codex-rs/app-server/src/message_processor.rs | 4 +- .../app-server/tests/suite/v2/config_rpc.rs | 5 ++- codex-rs/cli/src/main.rs | 7 +++- codex-rs/core/src/config/service.rs | 37 +++++++++---------- codex-rs/core/src/config_loader/layer_io.rs | 6 +-- 9 files changed, 83 insertions(+), 33 deletions(-) diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 5930fe4355..c1166d9508 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -1103,7 +1103,7 @@ impl CodexMessageProcessor { } async fn get_user_saved_config(&self, request_id: RequestId) { - let service = ConfigService::new(self.config.codex_home.clone(), Vec::new()); + let service = ConfigService::new_with_defaults(self.config.codex_home.clone()); let user_saved_config: UserSavedConfig = match service.load_user_saved_config().await { Ok(config) => config, Err(err) => { diff --git a/codex-rs/app-server/src/config_api.rs b/codex-rs/app-server/src/config_api.rs index 98e0f108e9..b06de3f1e4 100644 --- a/codex-rs/app-server/src/config_api.rs +++ b/codex-rs/app-server/src/config_api.rs @@ -9,6 +9,7 @@ use codex_app_server_protocol::ConfigWriteResponse; use codex_app_server_protocol::JSONRPCErrorError; use codex_core::config::ConfigService; use codex_core::config::ConfigServiceError; +use codex_core::config_loader::LoaderOverrides; use serde_json::json; use std::path::PathBuf; use toml::Value as TomlValue; @@ -19,9 +20,13 @@ pub(crate) struct ConfigApi { } impl ConfigApi { - pub(crate) fn new(codex_home: PathBuf, cli_overrides: Vec<(String, TomlValue)>) -> Self { + pub(crate) fn new( + codex_home: PathBuf, + cli_overrides: Vec<(String, TomlValue)>, + loader_overrides: LoaderOverrides, + ) -> Self { Self { - service: ConfigService::new(codex_home, cli_overrides), + service: ConfigService::new(codex_home, cli_overrides, loader_overrides), } } diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index 224e0da10b..68663a991d 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -1,7 +1,8 @@ #![deny(clippy::print_stdout, clippy::print_stderr)] use codex_common::CliConfigOverrides; -use codex_core::config::Config; +use codex_core::config::ConfigBuilder; +use codex_core::config_loader::LoaderOverrides; use std::io::ErrorKind; use std::io::Result as IoResult; use std::path::PathBuf; @@ -42,6 +43,7 @@ const CHANNEL_CAPACITY: usize = 128; pub async fn run_main( codex_linux_sandbox_exe: Option, cli_config_overrides: CliConfigOverrides, + loader_overrides: LoaderOverrides, ) -> IoResult<()> { // Set up channels. let (incoming_tx, mut incoming_rx) = mpsc::channel::(CHANNEL_CAPACITY); @@ -78,7 +80,11 @@ pub async fn run_main( format!("error parsing -c overrides: {e}"), ) })?; - let config = Config::load_with_cli_overrides(cli_kv_overrides.clone()) + let loader_overrides_for_config_api = loader_overrides.clone(); + let config = ConfigBuilder::default() + .cli_overrides(cli_kv_overrides.clone()) + .loader_overrides(loader_overrides) + .build() .await .map_err(|e| { std::io::Error::new(ErrorKind::InvalidData, format!("error loading config: {e}")) @@ -120,11 +126,13 @@ pub async fn run_main( let processor_handle = tokio::spawn({ let outgoing_message_sender = OutgoingMessageSender::new(outgoing_tx); let cli_overrides: Vec<(String, TomlValue)> = cli_kv_overrides.clone(); + let loader_overrides = loader_overrides_for_config_api; let mut processor = MessageProcessor::new( outgoing_message_sender, codex_linux_sandbox_exe, std::sync::Arc::new(config), cli_overrides, + loader_overrides, feedback.clone(), ); async move { diff --git a/codex-rs/app-server/src/main.rs b/codex-rs/app-server/src/main.rs index 689ec0877a..be57311e83 100644 --- a/codex-rs/app-server/src/main.rs +++ b/codex-rs/app-server/src/main.rs @@ -1,10 +1,42 @@ use codex_app_server::run_main; use codex_arg0::arg0_dispatch_or_else; use codex_common::CliConfigOverrides; +use codex_core::config_loader::LoaderOverrides; +use std::path::PathBuf; + +// Debug-only test hook: lets integration tests point the server at a temporary +// managed config file without writing to /etc. +const MANAGED_CONFIG_PATH_ENV_VAR: &str = "CODEX_APP_SERVER_MANAGED_CONFIG_PATH"; fn main() -> anyhow::Result<()> { arg0_dispatch_or_else(|codex_linux_sandbox_exe| async move { - run_main(codex_linux_sandbox_exe, CliConfigOverrides::default()).await?; + let managed_config_path = managed_config_path_from_debug_env(); + let loader_overrides = LoaderOverrides { + managed_config_path, + ..Default::default() + }; + + run_main( + codex_linux_sandbox_exe, + CliConfigOverrides::default(), + loader_overrides, + ) + .await?; Ok(()) }) } + +fn managed_config_path_from_debug_env() -> Option { + #[cfg(debug_assertions)] + { + if let Ok(value) = std::env::var(MANAGED_CONFIG_PATH_ENV_VAR) { + return if value.is_empty() { + None + } else { + Some(PathBuf::from(value)) + }; + } + } + + None +} diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 6a6cf5edb2..be57ad3970 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -20,6 +20,7 @@ use codex_app_server_protocol::RequestId; use codex_core::AuthManager; use codex_core::ConversationManager; use codex_core::config::Config; +use codex_core::config_loader::LoaderOverrides; use codex_core::default_client::USER_AGENT_SUFFIX; use codex_core::default_client::get_codex_user_agent; use codex_feedback::CodexFeedback; @@ -41,6 +42,7 @@ impl MessageProcessor { codex_linux_sandbox_exe: Option, config: Arc, cli_overrides: Vec<(String, TomlValue)>, + loader_overrides: LoaderOverrides, feedback: CodexFeedback, ) -> Self { let outgoing = Arc::new(outgoing); @@ -62,7 +64,7 @@ impl MessageProcessor { cli_overrides.clone(), feedback, ); - let config_api = ConfigApi::new(config.codex_home.clone(), cli_overrides); + let config_api = ConfigApi::new(config.codex_home.clone(), cli_overrides, loader_overrides); Self { outgoing, diff --git a/codex-rs/app-server/tests/suite/v2/config_rpc.rs b/codex-rs/app-server/tests/suite/v2/config_rpc.rs index c0be58f50c..18311d324b 100644 --- a/codex-rs/app-server/tests/suite/v2/config_rpc.rs +++ b/codex-rs/app-server/tests/suite/v2/config_rpc.rs @@ -184,7 +184,10 @@ writable_roots = [{}] let mut mcp = McpProcess::new_with_env( codex_home.path(), - &[("CODEX_MANAGED_CONFIG_PATH", Some(&managed_path_str))], + &[( + "CODEX_APP_SERVER_MANAGED_CONFIG_PATH", + Some(&managed_path_str), + )], ) .await?; timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index ae6dabe672..5cf4678bfc 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -480,7 +480,12 @@ async fn cli_main(codex_linux_sandbox_exe: Option) -> anyhow::Result<() } Some(Subcommand::AppServer(app_server_cli)) => match app_server_cli.subcommand { None => { - codex_app_server::run_main(codex_linux_sandbox_exe, root_config_overrides).await?; + codex_app_server::run_main( + codex_linux_sandbox_exe, + root_config_overrides, + codex_core::config_loader::LoaderOverrides::default(), + ) + .await?; } Some(AppServerSubcommand::GenerateTs(gen_cli)) => { codex_app_server_protocol::generate_ts( diff --git a/codex-rs/core/src/config/service.rs b/codex-rs/core/src/config/service.rs index 211a12fa03..d65ed10a05 100644 --- a/codex-rs/core/src/config/service.rs +++ b/codex-rs/core/src/config/service.rs @@ -106,16 +106,7 @@ pub struct ConfigService { } impl ConfigService { - pub fn new(codex_home: PathBuf, cli_overrides: Vec<(String, TomlValue)>) -> Self { - Self { - codex_home, - cli_overrides, - loader_overrides: LoaderOverrides::default(), - } - } - - #[cfg(test)] - fn with_overrides( + pub fn new( codex_home: PathBuf, cli_overrides: Vec<(String, TomlValue)>, loader_overrides: LoaderOverrides, @@ -127,6 +118,14 @@ impl ConfigService { } } + pub fn new_with_defaults(codex_home: PathBuf) -> Self { + Self { + codex_home, + cli_overrides: Vec::new(), + loader_overrides: LoaderOverrides::default(), + } + } + pub async fn read( &self, params: ConfigReadParams, @@ -707,7 +706,7 @@ unified_exec = true "#; std::fs::write(tmp.path().join(CONFIG_TOML_FILE), original)?; - let service = ConfigService::new(tmp.path().to_path_buf(), vec![]); + let service = ConfigService::new_with_defaults(tmp.path().to_path_buf()); service .write_value(ConfigValueWriteParams { file_path: Some(tmp.path().join(CONFIG_TOML_FILE).display().to_string()), @@ -748,7 +747,7 @@ remote_compaction = true std::fs::write(&managed_path, "approval_policy = \"never\"").unwrap(); let managed_file = AbsolutePathBuf::try_from(managed_path.clone()).expect("managed file"); - let service = ConfigService::with_overrides( + let service = ConfigService::new( tmp.path().to_path_buf(), vec![], LoaderOverrides { @@ -829,7 +828,7 @@ remote_compaction = true std::fs::write(&managed_path, "approval_policy = \"never\"").unwrap(); let managed_file = AbsolutePathBuf::try_from(managed_path.clone()).expect("managed file"); - let service = ConfigService::with_overrides( + let service = ConfigService::new( tmp.path().to_path_buf(), vec![], LoaderOverrides { @@ -881,7 +880,7 @@ remote_compaction = true let user_path = tmp.path().join(CONFIG_TOML_FILE); std::fs::write(&user_path, "model = \"user\"").unwrap(); - let service = ConfigService::new(tmp.path().to_path_buf(), vec![]); + let service = ConfigService::new_with_defaults(tmp.path().to_path_buf()); let error = service .write_value(ConfigValueWriteParams { file_path: Some(tmp.path().join(CONFIG_TOML_FILE).display().to_string()), @@ -904,7 +903,7 @@ remote_compaction = true let tmp = tempdir().expect("tempdir"); std::fs::write(tmp.path().join(CONFIG_TOML_FILE), "").unwrap(); - let service = ConfigService::new(tmp.path().to_path_buf(), vec![]); + let service = ConfigService::new_with_defaults(tmp.path().to_path_buf()); service .write_value(ConfigValueWriteParams { file_path: None, @@ -932,7 +931,7 @@ remote_compaction = true let managed_path = tmp.path().join("managed_config.toml"); std::fs::write(&managed_path, "approval_policy = \"never\"").unwrap(); - let service = ConfigService::with_overrides( + let service = ConfigService::new( tmp.path().to_path_buf(), vec![], LoaderOverrides { @@ -980,7 +979,7 @@ remote_compaction = true TomlValue::String("session".to_string()), )]; - let service = ConfigService::with_overrides( + let service = ConfigService::new( tmp.path().to_path_buf(), cli_overrides, LoaderOverrides { @@ -1026,7 +1025,7 @@ remote_compaction = true std::fs::write(&managed_path, "approval_policy = \"never\"").unwrap(); let managed_file = AbsolutePathBuf::try_from(managed_path.clone()).expect("managed file"); - let service = ConfigService::with_overrides( + let service = ConfigService::new( tmp.path().to_path_buf(), vec![], LoaderOverrides { @@ -1085,7 +1084,7 @@ alpha = "a" std::fs::write(&path, base)?; - let service = ConfigService::new(tmp.path().to_path_buf(), vec![]); + let service = ConfigService::new_with_defaults(tmp.path().to_path_buf()); service .write_value(ConfigValueWriteParams { file_path: Some(path.display().to_string()), diff --git a/codex-rs/core/src/config_loader/layer_io.rs b/codex-rs/core/src/config_loader/layer_io.rs index 84a29a6119..0ece69b471 100644 --- a/codex-rs/core/src/config_loader/layer_io.rs +++ b/codex-rs/core/src/config_loader/layer_io.rs @@ -93,12 +93,8 @@ pub(super) async fn read_config_from_path( } } -/// Return the default managed config path (honoring `CODEX_MANAGED_CONFIG_PATH`). +/// Return the default managed config path. pub(super) fn managed_config_default_path(codex_home: &Path) -> PathBuf { - if let Ok(path) = std::env::var("CODEX_MANAGED_CONFIG_PATH") { - return PathBuf::from(path); - } - #[cfg(unix)] { let _ = codex_home; From 06e21c7a6505216c27cdc346b2146e993b4d8b2b Mon Sep 17 00:00:00 2001 From: Abdelkader Boudih Date: Tue, 6 Jan 2026 16:47:29 +0100 Subject: [PATCH 3/9] fix: update model examples to gpt-5.2 (#8566) The models are outdated and sometime get used by GPT when it to try delegate. I have read the CLA Document and I hereby sign the CLA --- codex-rs/mcp-server/src/codex_tool_config.rs | 52 ++++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/codex-rs/mcp-server/src/codex_tool_config.rs b/codex-rs/mcp-server/src/codex_tool_config.rs index 16d38da45e..26fdc07320 100644 --- a/codex-rs/mcp-server/src/codex_tool_config.rs +++ b/codex-rs/mcp-server/src/codex_tool_config.rs @@ -21,7 +21,7 @@ pub struct CodexToolCallParam { /// The *initial user prompt* to start the Codex conversation. pub prompt: String, - /// Optional override for the model name (e.g. "o3", "o4-mini"). + /// Optional override for the model name (e.g. 'gpt-5.2', 'gpt-5.2-codex'). #[serde(default, skip_serializing_if = "Option::is_none")] pub model: Option, @@ -245,11 +245,8 @@ mod tests { let tool = create_tool_for_codex_tool_call_param(); let tool_json = serde_json::to_value(&tool).expect("tool serializes"); let expected_tool_json = serde_json::json!({ - "name": "codex", - "title": "Codex", "description": "Run a Codex session. Accepts configuration parameters matching the Codex Config struct.", "inputSchema": { - "type": "object", "properties": { "approval-policy": { "description": "Approval policy for shell commands generated by the model: `untrusted`, `on-failure`, `on-request`, `never`.", @@ -261,26 +258,29 @@ mod tests { ], "type": "string" }, - "sandbox": { - "description": "Sandbox mode: `read-only`, `workspace-write`, or `danger-full-access`.", - "enum": [ - "read-only", - "workspace-write", - "danger-full-access" - ], + "base-instructions": { + "description": "The set of instructions to use instead of the default ones.", + "type": "string" + }, + "compact-prompt": { + "description": "Prompt used when compacting the conversation.", "type": "string" }, "config": { - "description": "Individual config settings that will override what is in CODEX_HOME/config.toml.", "additionalProperties": true, + "description": "Individual config settings that will override what is in CODEX_HOME/config.toml.", "type": "object" }, "cwd": { "description": "Working directory for the session. If relative, it is resolved against the server process's current working directory.", "type": "string" }, + "developer-instructions": { + "description": "Developer instructions that should be injected as a developer role message.", + "type": "string" + }, "model": { - "description": "Optional override for the model name (e.g. \"o3\", \"o4-mini\").", + "description": "Optional override for the model name (e.g. 'gpt-5.2', 'gpt-5.2-codex').", "type": "string" }, "profile": { @@ -291,23 +291,23 @@ mod tests { "description": "The *initial user prompt* to start the Codex conversation.", "type": "string" }, - "base-instructions": { - "description": "The set of instructions to use instead of the default ones.", + "sandbox": { + "description": "Sandbox mode: `read-only`, `workspace-write`, or `danger-full-access`.", + "enum": [ + "read-only", + "workspace-write", + "danger-full-access" + ], "type": "string" - }, - "developer-instructions": { - "description": "Developer instructions that should be injected as a developer role message.", - "type": "string" - }, - "compact-prompt": { - "description": "Prompt used when compacting the conversation.", - "type": "string" - }, + } }, "required": [ "prompt" - ] - } + ], + "type": "object" + }, + "name": "codex", + "title": "Codex" }); assert_eq!(expected_tool_json, tool_json); } From 32db8ea5cae5ce0cbca02afb46abb3d666e5c07b Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 6 Jan 2026 15:48:44 +0000 Subject: [PATCH 4/9] feat: add head-tail buffer for `unified_exec` (#8735) --- .../core/src/unified_exec/async_watcher.rs | 23 +- .../core/src/unified_exec/head_tail_buffer.rs | 272 ++++++++++++++++++ codex-rs/core/src/unified_exec/mod.rs | 55 ++-- codex-rs/core/src/unified_exec/session.rs | 52 +--- .../core/src/unified_exec/session_manager.rs | 50 ++-- 5 files changed, 338 insertions(+), 114 deletions(-) create mode 100644 codex-rs/core/src/unified_exec/head_tail_buffer.rs diff --git a/codex-rs/core/src/unified_exec/async_watcher.rs b/codex-rs/core/src/unified_exec/async_watcher.rs index 53b6b7c77d..22aca62aa2 100644 --- a/codex-rs/core/src/unified_exec/async_watcher.rs +++ b/codex-rs/core/src/unified_exec/async_watcher.rs @@ -7,6 +7,8 @@ use tokio::time::Duration; use tokio::time::Instant; use tokio::time::Sleep; +use super::UnifiedExecContext; +use super::session::UnifiedExecSession; use crate::codex::Session; use crate::codex::TurnContext; use crate::exec::ExecToolCallOutput; @@ -19,10 +21,7 @@ use crate::protocol::ExecOutputStream; use crate::tools::events::ToolEmitter; use crate::tools::events::ToolEventCtx; use crate::tools::events::ToolEventStage; - -use super::CommandTranscript; -use super::UnifiedExecContext; -use super::session::UnifiedExecSession; +use crate::unified_exec::head_tail_buffer::HeadTailBuffer; pub(crate) const TRAILING_OUTPUT_GRACE: Duration = Duration::from_millis(100); @@ -40,7 +39,7 @@ const UNIFIED_EXEC_OUTPUT_DELTA_MAX_BYTES: usize = 8192; pub(crate) fn start_streaming_output( session: &UnifiedExecSession, context: &UnifiedExecContext, - transcript: Arc>, + transcript: Arc>, ) { let mut receiver = session.output_receiver(); let output_drained = session.output_drained_notify(); @@ -112,7 +111,7 @@ pub(crate) fn spawn_exit_watcher( command: Vec, cwd: PathBuf, process_id: String, - transcript: Arc>, + transcript: Arc>, started_at: Instant, ) { let exit_token = session.cancellation_token(); @@ -142,7 +141,7 @@ pub(crate) fn spawn_exit_watcher( async fn process_chunk( pending: &mut Vec, - transcript: &Arc>, + transcript: &Arc>, call_id: &str, session_ref: &Arc, turn_ref: &Arc, @@ -153,7 +152,7 @@ async fn process_chunk( while let Some(prefix) = split_valid_utf8_prefix(pending) { { let mut guard = transcript.lock().await; - guard.append(&prefix); + guard.push_chunk(prefix.to_vec()); } if *emitted_deltas >= MAX_EXEC_OUTPUT_DELTAS_PER_CALL { @@ -183,7 +182,7 @@ pub(crate) async fn emit_exec_end_for_unified_exec( command: Vec, cwd: PathBuf, process_id: Option, - transcript: Arc>, + transcript: Arc>, fallback_output: String, exit_code: i32, duration: Duration, @@ -240,15 +239,15 @@ fn split_valid_utf8_prefix_with_max(buffer: &mut Vec, max_bytes: usize) -> O } async fn resolve_aggregated_output( - transcript: &Arc>, + transcript: &Arc>, fallback: String, ) -> String { let guard = transcript.lock().await; - if guard.data.is_empty() { + if guard.retained_bytes() == 0 { return fallback; } - String::from_utf8_lossy(&guard.data).to_string() + String::from_utf8_lossy(&guard.to_bytes()).to_string() } #[cfg(test)] diff --git a/codex-rs/core/src/unified_exec/head_tail_buffer.rs b/codex-rs/core/src/unified_exec/head_tail_buffer.rs new file mode 100644 index 0000000000..8524466048 --- /dev/null +++ b/codex-rs/core/src/unified_exec/head_tail_buffer.rs @@ -0,0 +1,272 @@ +use crate::unified_exec::UNIFIED_EXEC_OUTPUT_MAX_BYTES; +use std::collections::VecDeque; + +/// A capped buffer that preserves a stable prefix ("head") and suffix ("tail"), +/// dropping the middle once it exceeds the configured maximum. The buffer is +/// symmetric meaning 50% of the capacity is allocated to the head and 50% is +/// allocated to the tail. +#[derive(Debug)] +pub(crate) struct HeadTailBuffer { + max_bytes: usize, + head_budget: usize, + tail_budget: usize, + head: VecDeque>, + tail: VecDeque>, + head_bytes: usize, + tail_bytes: usize, + omitted_bytes: usize, +} + +impl Default for HeadTailBuffer { + fn default() -> Self { + Self::new(UNIFIED_EXEC_OUTPUT_MAX_BYTES) + } +} + +impl HeadTailBuffer { + /// Create a new buffer that retains at most `max_bytes` of output. + /// + /// The retained output is split across a prefix ("head") and suffix ("tail") + /// budget, dropping bytes from the middle once the limit is exceeded. + pub(crate) fn new(max_bytes: usize) -> Self { + let head_budget = max_bytes / 2; + let tail_budget = max_bytes.saturating_sub(head_budget); + Self { + max_bytes, + head_budget, + tail_budget, + head: VecDeque::new(), + tail: VecDeque::new(), + head_bytes: 0, + tail_bytes: 0, + omitted_bytes: 0, + } + } + + // Used for tests. + #[allow(dead_code)] + /// Total bytes currently retained by the buffer (head + tail). + pub(crate) fn retained_bytes(&self) -> usize { + self.head_bytes.saturating_add(self.tail_bytes) + } + + // Used for tests. + #[allow(dead_code)] + /// Total bytes that were dropped from the middle due to the size cap. + pub(crate) fn omitted_bytes(&self) -> usize { + self.omitted_bytes + } + + /// Append a chunk of bytes to the buffer. + /// + /// Bytes are first added to the head until the head budget is full; any + /// remaining bytes are added to the tail, with older tail bytes being + /// dropped to preserve the tail budget. + pub(crate) fn push_chunk(&mut self, chunk: Vec) { + if self.max_bytes == 0 { + self.omitted_bytes = self.omitted_bytes.saturating_add(chunk.len()); + return; + } + + // Fill the head budget first, then keep a capped tail. + if self.head_bytes < self.head_budget { + let remaining_head = self.head_budget.saturating_sub(self.head_bytes); + if chunk.len() <= remaining_head { + self.head_bytes = self.head_bytes.saturating_add(chunk.len()); + self.head.push_back(chunk); + return; + } + + // Split the chunk: part goes to head, remainder goes to tail. + let (head_part, tail_part) = chunk.split_at(remaining_head); + if !head_part.is_empty() { + self.head_bytes = self.head_bytes.saturating_add(head_part.len()); + self.head.push_back(head_part.to_vec()); + } + self.push_to_tail(tail_part.to_vec()); + return; + } + + self.push_to_tail(chunk); + } + + /// Snapshot the retained output as a list of chunks. + /// + /// The returned chunks are ordered as: head chunks first, then tail chunks. + /// Omitted bytes are not represented in the snapshot. + pub(crate) fn snapshot_chunks(&self) -> Vec> { + let mut out = Vec::new(); + out.extend(self.head.iter().cloned()); + out.extend(self.tail.iter().cloned()); + out + } + + /// Return the retained output as a single byte vector. + /// + /// The output is formed by concatenating head chunks, then tail chunks. + /// Omitted bytes are not represented in the returned value. + pub(crate) fn to_bytes(&self) -> Vec { + let mut out = Vec::with_capacity(self.retained_bytes()); + for chunk in self.head.iter() { + out.extend_from_slice(chunk); + } + for chunk in self.tail.iter() { + out.extend_from_slice(chunk); + } + out + } + + /// Drain all retained chunks from the buffer and reset its state. + /// + /// The drained chunks are returned in head-then-tail order. Omitted bytes + /// are discarded along with the retained content. + pub(crate) fn drain_chunks(&mut self) -> Vec> { + let mut out: Vec> = self.head.drain(..).collect(); + out.extend(self.tail.drain(..)); + self.head_bytes = 0; + self.tail_bytes = 0; + self.omitted_bytes = 0; + out + } + + fn push_to_tail(&mut self, chunk: Vec) { + if self.tail_budget == 0 { + self.omitted_bytes = self.omitted_bytes.saturating_add(chunk.len()); + return; + } + + if chunk.len() >= self.tail_budget { + // This single chunk is larger than the whole tail budget. Keep only the last + // tail_budget bytes and drop everything else. + let start = chunk.len().saturating_sub(self.tail_budget); + let kept = chunk[start..].to_vec(); + let dropped = chunk.len().saturating_sub(kept.len()); + self.omitted_bytes = self + .omitted_bytes + .saturating_add(self.tail_bytes) + .saturating_add(dropped); + self.tail.clear(); + self.tail_bytes = kept.len(); + self.tail.push_back(kept); + return; + } + + self.tail_bytes = self.tail_bytes.saturating_add(chunk.len()); + self.tail.push_back(chunk); + self.trim_tail_to_budget(); + } + + fn trim_tail_to_budget(&mut self) { + let mut excess = self.tail_bytes.saturating_sub(self.tail_budget); + while excess > 0 { + match self.tail.front_mut() { + Some(front) if excess >= front.len() => { + excess -= front.len(); + self.tail_bytes = self.tail_bytes.saturating_sub(front.len()); + self.omitted_bytes = self.omitted_bytes.saturating_add(front.len()); + self.tail.pop_front(); + } + Some(front) => { + front.drain(..excess); + self.tail_bytes = self.tail_bytes.saturating_sub(excess); + self.omitted_bytes = self.omitted_bytes.saturating_add(excess); + break; + } + None => break, + } + } + } +} + +#[cfg(test)] +mod tests { + use super::HeadTailBuffer; + + use pretty_assertions::assert_eq; + + #[test] + fn keeps_prefix_and_suffix_when_over_budget() { + let mut buf = HeadTailBuffer::new(10); + + buf.push_chunk(b"0123456789".to_vec()); + assert_eq!(buf.omitted_bytes(), 0); + + // Exceeds max by 2; we should keep head+tail and omit the middle. + buf.push_chunk(b"ab".to_vec()); + assert!(buf.omitted_bytes() > 0); + + let rendered = String::from_utf8_lossy(&buf.to_bytes()).to_string(); + assert!(rendered.starts_with("01234")); + assert!(rendered.ends_with("89ab")); + } + + #[test] + fn max_bytes_zero_drops_everything() { + let mut buf = HeadTailBuffer::new(0); + buf.push_chunk(b"abc".to_vec()); + + assert_eq!(buf.retained_bytes(), 0); + assert_eq!(buf.omitted_bytes(), 3); + assert_eq!(buf.to_bytes(), b"".to_vec()); + assert_eq!(buf.snapshot_chunks(), Vec::>::new()); + } + + #[test] + fn head_budget_zero_keeps_only_last_byte_in_tail() { + let mut buf = HeadTailBuffer::new(1); + buf.push_chunk(b"abc".to_vec()); + + assert_eq!(buf.retained_bytes(), 1); + assert_eq!(buf.omitted_bytes(), 2); + assert_eq!(buf.to_bytes(), b"c".to_vec()); + } + + #[test] + fn draining_resets_state() { + let mut buf = HeadTailBuffer::new(10); + buf.push_chunk(b"0123456789".to_vec()); + buf.push_chunk(b"ab".to_vec()); + + let drained = buf.drain_chunks(); + assert!(!drained.is_empty()); + + assert_eq!(buf.retained_bytes(), 0); + assert_eq!(buf.omitted_bytes(), 0); + assert_eq!(buf.to_bytes(), b"".to_vec()); + } + + #[test] + fn chunk_larger_than_tail_budget_keeps_only_tail_end() { + let mut buf = HeadTailBuffer::new(10); + buf.push_chunk(b"0123456789".to_vec()); + + // Tail budget is 5 bytes. This chunk should replace the tail and keep only its last 5 bytes. + buf.push_chunk(b"ABCDEFGHIJK".to_vec()); + + let out = String::from_utf8_lossy(&buf.to_bytes()).to_string(); + assert!(out.starts_with("01234")); + assert!(out.ends_with("GHIJK")); + assert!(buf.omitted_bytes() > 0); + } + + #[test] + fn fills_head_then_tail_across_multiple_chunks() { + let mut buf = HeadTailBuffer::new(10); + + // Fill the 5-byte head budget across multiple chunks. + buf.push_chunk(b"01".to_vec()); + buf.push_chunk(b"234".to_vec()); + assert_eq!(buf.to_bytes(), b"01234".to_vec()); + + // Then fill the 5-byte tail budget. + buf.push_chunk(b"567".to_vec()); + buf.push_chunk(b"89".to_vec()); + assert_eq!(buf.to_bytes(), b"0123456789".to_vec()); + assert_eq!(buf.omitted_bytes(), 0); + + // One more byte causes the tail to drop its oldest byte. + buf.push_chunk(b"a".to_vec()); + assert_eq!(buf.to_bytes(), b"012346789a".to_vec()); + assert_eq!(buf.omitted_bytes(), 1); + } +} diff --git a/codex-rs/core/src/unified_exec/mod.rs b/codex-rs/core/src/unified_exec/mod.rs index 2cb30e5aa3..c88238fe5e 100644 --- a/codex-rs/core/src/unified_exec/mod.rs +++ b/codex-rs/core/src/unified_exec/mod.rs @@ -37,6 +37,7 @@ use crate::sandboxing::SandboxPermissions; mod async_watcher; mod errors; +mod head_tail_buffer; mod session; mod session_manager; @@ -53,24 +54,6 @@ pub(crate) const MAX_UNIFIED_EXEC_SESSIONS: usize = 64; // Send a warning message to the models when it reaches this number of sessions. pub(crate) const WARNING_UNIFIED_EXEC_SESSIONS: usize = 60; -#[derive(Debug, Default)] -pub(crate) struct CommandTranscript { - pub data: Vec, -} - -impl CommandTranscript { - pub fn append(&mut self, bytes: &[u8]) { - self.data.extend_from_slice(bytes); - if self.data.len() > UNIFIED_EXEC_OUTPUT_MAX_BYTES { - let excess = self - .data - .len() - .saturating_sub(UNIFIED_EXEC_OUTPUT_MAX_BYTES); - self.data.drain(..excess); - } - } -} - pub(crate) struct UnifiedExecContext { pub session: Arc, pub turn: Arc, @@ -173,6 +156,7 @@ pub(crate) fn generate_chunk_id() -> String { #[cfg(test)] #[cfg(unix)] mod tests { + use super::head_tail_buffer::HeadTailBuffer; use super::*; use crate::codex::Session; use crate::codex::TurnContext; @@ -185,8 +169,6 @@ mod tests { use std::sync::Arc; use tokio::time::Duration; - use super::session::OutputBufferState; - async fn test_session_and_turn() -> (Arc, Arc) { let (session, mut turn) = make_session_and_context().await; turn.approval_policy = AskForApproval::Never; @@ -245,21 +227,36 @@ mod tests { } #[test] - fn push_chunk_trims_only_excess_bytes() { - let mut buffer = OutputBufferState::default(); + fn push_chunk_preserves_prefix_and_suffix() { + let mut buffer = HeadTailBuffer::default(); buffer.push_chunk(vec![b'a'; UNIFIED_EXEC_OUTPUT_MAX_BYTES]); buffer.push_chunk(vec![b'b']); buffer.push_chunk(vec![b'c']); - assert_eq!(buffer.total_bytes, UNIFIED_EXEC_OUTPUT_MAX_BYTES); - let snapshot = buffer.snapshot(); - assert_eq!(snapshot.len(), 3); + assert_eq!(buffer.retained_bytes(), UNIFIED_EXEC_OUTPUT_MAX_BYTES); + let snapshot = buffer.snapshot_chunks(); + + let first = snapshot.first().expect("expected at least one chunk"); + assert_eq!(first.first(), Some(&b'a')); + assert!(snapshot.iter().any(|chunk| chunk.as_slice() == b"b")); assert_eq!( - snapshot.first().unwrap().len(), - UNIFIED_EXEC_OUTPUT_MAX_BYTES - 2 + snapshot + .last() + .expect("expected at least one chunk") + .as_slice(), + b"c" ); - assert_eq!(snapshot.get(2).unwrap(), &vec![b'c']); - assert_eq!(snapshot.get(1).unwrap(), &vec![b'b']); + } + + #[test] + fn head_tail_buffer_default_preserves_prefix_and_suffix() { + let mut buffer = HeadTailBuffer::default(); + buffer.push_chunk(vec![b'a'; UNIFIED_EXEC_OUTPUT_MAX_BYTES]); + buffer.push_chunk(b"bc".to_vec()); + + let rendered = buffer.to_bytes(); + assert_eq!(rendered.first(), Some(&b'a')); + assert!(rendered.ends_with(b"bc")); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/codex-rs/core/src/unified_exec/session.rs b/codex-rs/core/src/unified_exec/session.rs index 4973a1a641..0e08c59903 100644 --- a/codex-rs/core/src/unified_exec/session.rs +++ b/codex-rs/core/src/unified_exec/session.rs @@ -1,6 +1,5 @@ #![allow(clippy::module_inception)] -use std::collections::VecDeque; use std::sync::Arc; use tokio::sync::Mutex; use tokio::sync::Notify; @@ -19,54 +18,11 @@ use crate::truncate::formatted_truncate_text; use codex_utils_pty::ExecCommandSession; use codex_utils_pty::SpawnedPty; -use super::UNIFIED_EXEC_OUTPUT_MAX_BYTES; use super::UNIFIED_EXEC_OUTPUT_MAX_TOKENS; use super::UnifiedExecError; +use super::head_tail_buffer::HeadTailBuffer; -#[derive(Debug, Default)] -pub(crate) struct OutputBufferState { - chunks: VecDeque>, - pub(crate) total_bytes: usize, -} - -impl OutputBufferState { - pub(super) fn push_chunk(&mut self, chunk: Vec) { - self.total_bytes = self.total_bytes.saturating_add(chunk.len()); - self.chunks.push_back(chunk); - - let mut excess = self - .total_bytes - .saturating_sub(UNIFIED_EXEC_OUTPUT_MAX_BYTES); - - while excess > 0 { - match self.chunks.front_mut() { - Some(front) if excess >= front.len() => { - excess -= front.len(); - self.total_bytes = self.total_bytes.saturating_sub(front.len()); - self.chunks.pop_front(); - } - Some(front) => { - front.drain(..excess); - self.total_bytes = self.total_bytes.saturating_sub(excess); - break; - } - None => break, - } - } - } - - pub(super) fn drain(&mut self) -> Vec> { - let drained: Vec> = self.chunks.drain(..).collect(); - self.total_bytes = 0; - drained - } - - pub(super) fn snapshot(&self) -> Vec> { - self.chunks.iter().cloned().collect() - } -} - -pub(crate) type OutputBuffer = Arc>; +pub(crate) type OutputBuffer = Arc>; pub(crate) struct OutputHandles { pub(crate) output_buffer: OutputBuffer, pub(crate) output_notify: Arc, @@ -90,7 +46,7 @@ impl UnifiedExecSession { initial_output_rx: tokio::sync::broadcast::Receiver>, sandbox_type: SandboxType, ) -> Self { - let output_buffer = Arc::new(Mutex::new(OutputBufferState::default())); + let output_buffer = Arc::new(Mutex::new(HeadTailBuffer::default())); let output_notify = Arc::new(Notify::new()); let cancellation_token = CancellationToken::new(); let output_drained = Arc::new(Notify::new()); @@ -163,7 +119,7 @@ impl UnifiedExecSession { async fn snapshot_output(&self) -> Vec> { let guard = self.output_buffer.lock().await; - guard.snapshot() + guard.snapshot_chunks() } pub(crate) fn sandbox_type(&self) -> SandboxType { diff --git a/codex-rs/core/src/unified_exec/session_manager.rs b/codex-rs/core/src/unified_exec/session_manager.rs index df473959d2..1d524c23d4 100644 --- a/codex-rs/core/src/unified_exec/session_manager.rs +++ b/codex-rs/core/src/unified_exec/session_manager.rs @@ -29,27 +29,26 @@ use crate::tools::sandboxing::ToolCtx; use crate::truncate::TruncationPolicy; use crate::truncate::approx_token_count; use crate::truncate::formatted_truncate_text; - -use super::CommandTranscript; -use super::ExecCommandRequest; -use super::MAX_UNIFIED_EXEC_SESSIONS; -use super::SessionEntry; -use super::SessionStore; -use super::UnifiedExecContext; -use super::UnifiedExecError; -use super::UnifiedExecResponse; -use super::UnifiedExecSessionManager; -use super::WARNING_UNIFIED_EXEC_SESSIONS; -use super::WriteStdinRequest; -use super::async_watcher::emit_exec_end_for_unified_exec; -use super::async_watcher::spawn_exit_watcher; -use super::async_watcher::start_streaming_output; -use super::clamp_yield_time; -use super::generate_chunk_id; -use super::resolve_max_tokens; -use super::session::OutputBuffer; -use super::session::OutputHandles; -use super::session::UnifiedExecSession; +use crate::unified_exec::ExecCommandRequest; +use crate::unified_exec::MAX_UNIFIED_EXEC_SESSIONS; +use crate::unified_exec::SessionEntry; +use crate::unified_exec::SessionStore; +use crate::unified_exec::UnifiedExecContext; +use crate::unified_exec::UnifiedExecError; +use crate::unified_exec::UnifiedExecResponse; +use crate::unified_exec::UnifiedExecSessionManager; +use crate::unified_exec::WARNING_UNIFIED_EXEC_SESSIONS; +use crate::unified_exec::WriteStdinRequest; +use crate::unified_exec::async_watcher::emit_exec_end_for_unified_exec; +use crate::unified_exec::async_watcher::spawn_exit_watcher; +use crate::unified_exec::async_watcher::start_streaming_output; +use crate::unified_exec::clamp_yield_time; +use crate::unified_exec::generate_chunk_id; +use crate::unified_exec::head_tail_buffer::HeadTailBuffer; +use crate::unified_exec::resolve_max_tokens; +use crate::unified_exec::session::OutputBuffer; +use crate::unified_exec::session::OutputHandles; +use crate::unified_exec::session::UnifiedExecSession; const UNIFIED_EXEC_ENV: [(&str, &str); 9] = [ ("NO_COLOR", "1"), @@ -144,7 +143,7 @@ impl UnifiedExecSessionManager { } }; - let transcript = Arc::new(tokio::sync::Mutex::new(CommandTranscript::default())); + let transcript = Arc::new(tokio::sync::Mutex::new(HeadTailBuffer::default())); let event_ctx = ToolEventCtx::new( context.session.as_ref(), context.turn.as_ref(), @@ -158,6 +157,7 @@ impl UnifiedExecSessionManager { Some(request.process_id.clone()), ); emitter.emit(event_ctx, ToolEventStage::Begin).await; + start_streaming_output(&session, context, Arc::clone(&transcript)); let max_tokens = resolve_max_tokens(request.max_output_tokens); @@ -408,7 +408,7 @@ impl UnifiedExecSessionManager { cwd: PathBuf, started_at: Instant, process_id: String, - transcript: Arc>, + transcript: Arc>, ) { let entry = SessionEntry { session: Arc::clone(&session), @@ -550,11 +550,11 @@ impl UnifiedExecSessionManager { let mut collected: Vec = Vec::with_capacity(4096); let mut exit_signal_received = cancellation_token.is_cancelled(); loop { - let drained_chunks; + let drained_chunks: Vec>; let mut wait_for_output = None; { let mut guard = output_buffer.lock().await; - drained_chunks = guard.drain(); + drained_chunks = guard.drain_chunks(); if drained_chunks.is_empty() { wait_for_output = Some(output_notify.notified()); } From cab7136fb38eb3534b233e7da78cd0916448e345 Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Tue, 6 Jan 2026 09:50:17 -0800 Subject: [PATCH 5/9] chore: add model/list call to app-server-test-client (#8331) Allows us to run `cargo run -p codex-app-server-test-client -- model-list` to return the list of models over app-server. --- codex-rs/app-server-test-client/src/main.rs | 28 +++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/codex-rs/app-server-test-client/src/main.rs b/codex-rs/app-server-test-client/src/main.rs index b66c59d55a..eefd123182 100644 --- a/codex-rs/app-server-test-client/src/main.rs +++ b/codex-rs/app-server-test-client/src/main.rs @@ -35,6 +35,8 @@ use codex_app_server_protocol::JSONRPCRequest; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::LoginChatGptCompleteNotification; use codex_app_server_protocol::LoginChatGptResponse; +use codex_app_server_protocol::ModelListParams; +use codex_app_server_protocol::ModelListResponse; use codex_app_server_protocol::NewConversationParams; use codex_app_server_protocol::NewConversationResponse; use codex_app_server_protocol::RequestId; @@ -113,6 +115,9 @@ enum CliCommand { TestLogin, /// Fetch the current account rate limits from the Codex app-server. GetAccountRateLimits, + /// List the available models from the Codex app-server. + #[command(name = "model-list")] + ModelList, } fn main() -> Result<()> { @@ -134,6 +139,7 @@ fn main() -> Result<()> { } => send_follow_up_v2(codex_bin, first_message, follow_up_message), CliCommand::TestLogin => test_login(codex_bin), CliCommand::GetAccountRateLimits => get_account_rate_limits(codex_bin), + CliCommand::ModelList => model_list(codex_bin), } } @@ -301,6 +307,18 @@ fn get_account_rate_limits(codex_bin: String) -> Result<()> { Ok(()) } +fn model_list(codex_bin: String) -> Result<()> { + let mut client = CodexClient::spawn(codex_bin)?; + + let initialize = client.initialize()?; + println!("< initialize response: {initialize:?}"); + + let response = client.model_list(ModelListParams::default())?; + println!("< model/list response: {response:?}"); + + Ok(()) +} + struct CodexClient { child: Child, stdin: Option, @@ -452,6 +470,16 @@ impl CodexClient { self.send_request(request, request_id, "account/rateLimits/read") } + fn model_list(&mut self, params: ModelListParams) -> Result { + let request_id = self.request_id(); + let request = ClientRequest::ModelList { + request_id: request_id.clone(), + params, + }; + + self.send_request(request, request_id, "model/list") + } + fn stream_conversation(&mut self, conversation_id: &ConversationId) -> Result<()> { loop { let notification = self.next_notification()?; From d1c6329c32a4ce2c42a68a9c1ba0d5f32a97e50b Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 6 Jan 2026 18:02:05 +0000 Subject: [PATCH 6/9] feat: forced tool tips (#8752) Force an announcement tooltip in the CLI. This query the gh repo on this [file](https://raw.githubusercontent.com/openai/codex/main/announcement_tip.toml) which contains announcements in TOML looking like this: ``` # Example announcement tips for Codex TUI. # Each [[announcements]] entry is evaluated in order; the last matching one is shown. # Dates are UTC, formatted as YYYY-MM-DD. The from_date is inclusive and the to_date is exclusive. # version_regex matches against the CLI version (env!("CARGO_PKG_VERSION")); omit to apply to all versions. # target_app specify which app should display the announcement (cli, vsce, ...). [[announcements]] content = "Welcome to Codex! Check out the new onboarding flow." from_date = "2024-10-01" to_date = "2024-10-15" version_regex = "^0\\.0\\.0$" target_app = "cli" ``` To make this efficient, the announcement is queried on a best effort basis at the launch of the CLI (no refresh made after this). This is done in an async way and we display the announcement (with 100% probability) iff the announcement is available, the cache is correctly warmed and there is a matching announcement (matching is recomputed for each new session). --- announcement_tip.toml | 16 ++ codex-rs/tui/src/history_cell.rs | 4 +- codex-rs/tui/src/lib.rs | 3 +- codex-rs/tui/src/tooltips.rs | 264 ++++++++++++++++++++++++++++- codex-rs/tui2/src/history_cell.rs | 4 +- codex-rs/tui2/src/lib.rs | 2 + codex-rs/tui2/src/tooltips.rs | 270 +++++++++++++++++++++++++++++- 7 files changed, 545 insertions(+), 18 deletions(-) create mode 100644 announcement_tip.toml diff --git a/announcement_tip.toml b/announcement_tip.toml new file mode 100644 index 0000000000..3ad4a76590 --- /dev/null +++ b/announcement_tip.toml @@ -0,0 +1,16 @@ +# Example announcement tips for Codex TUI. +# Each [[announcements]] entry is evaluated in order; the last matching one is shown. +# Dates are UTC, formatted as YYYY-MM-DD. The from_date is inclusive and the to_date is exclusive. +# version_regex matches against the CLI version (env!("CARGO_PKG_VERSION")); omit to apply to all versions. +# target_app specify which app should display the announcement (cli, vsce, ...). + +[[announcements]] +content = "Welcome to Codex! Check out the new onboarding flow." +from_date = "2024-10-01" +to_date = "2024-10-15" +target_app = "cli" + +[[announcements]] +content = "This is a test announcement" +version_regex = "^0\\.0\\.0$" +to_date = "2026-01-10" diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index b487c6aeff..4e6f598775 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -816,11 +816,11 @@ pub(crate) fn padded_emoji(emoji: &str) -> String { #[derive(Debug)] struct TooltipHistoryCell { - tip: &'static str, + tip: String, } impl TooltipHistoryCell { - fn new(tip: &'static str) -> Self { + fn new(tip: String) -> Self { Self { tip } } } diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 6b784affce..4eb487f1da 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -97,7 +97,6 @@ pub use markdown_render::render_markdown_text; pub use public_widgets::composer_input::ComposerAction; pub use public_widgets::composer_input::ComposerInput; use std::io::Write as _; - // (tests access modules directly within the crate) pub async fn run_main( @@ -344,6 +343,8 @@ async fn run_ratatui_app( ) -> color_eyre::Result { color_eyre::install()?; + tooltips::announcement::prewarm(); + // Forward panic reports through tracing so they appear in the UI status // line, but do not swallow the default/color-eyre panic handler. // Chain to the previous hook so users still get a rich panic report diff --git a/codex-rs/tui/src/tooltips.rs b/codex-rs/tui/src/tooltips.rs index 8a3a1c1e96..402a18ba2b 100644 --- a/codex-rs/tui/src/tooltips.rs +++ b/codex-rs/tui/src/tooltips.rs @@ -2,15 +2,10 @@ use codex_core::features::FEATURES; use lazy_static::lazy_static; use rand::Rng; +const ANNOUNCEMENT_TIP_URL: &str = + "https://raw.githubusercontent.com/openai/codex/main/announcement_tip.toml"; const RAW_TOOLTIPS: &str = include_str!("../tooltips.txt"); -fn beta_tooltips() -> Vec<&'static str> { - FEATURES - .iter() - .filter_map(|spec| spec.stage.beta_announcement()) - .collect() -} - lazy_static! { static ref TOOLTIPS: Vec<&'static str> = RAW_TOOLTIPS .lines() @@ -25,9 +20,20 @@ lazy_static! { }; } -pub(crate) fn random_tooltip() -> Option<&'static str> { +fn beta_tooltips() -> Vec<&'static str> { + FEATURES + .iter() + .filter_map(|spec| spec.stage.beta_announcement()) + .collect() +} + +/// Pick a random tooltip to show to the user when starting Codex. +pub(crate) fn random_tooltip() -> Option { + if let Some(announcement) = announcement::fetch_announcement_tip() { + return Some(announcement); + } let mut rng = rand::rng(); - pick_tooltip(&mut rng) + pick_tooltip(&mut rng).map(str::to_string) } fn pick_tooltip(rng: &mut R) -> Option<&'static str> { @@ -40,9 +46,149 @@ fn pick_tooltip(rng: &mut R) -> Option<&'static str> { } } +pub(crate) mod announcement { + use crate::tooltips::ANNOUNCEMENT_TIP_URL; + use crate::version::CODEX_CLI_VERSION; + use chrono::NaiveDate; + use chrono::Utc; + use regex_lite::Regex; + use serde::Deserialize; + use std::sync::OnceLock; + use std::thread; + use std::time::Duration; + + static ANNOUNCEMENT_TIP: OnceLock> = OnceLock::new(); + + /// Prewarm the cache of the announcement tip. + pub(crate) fn prewarm() { + let _ = thread::spawn(|| ANNOUNCEMENT_TIP.get_or_init(init_announcement_tip_in_thread)); + } + + /// Fetch the announcement tip, return None if the prewarm is not done yet. + pub(crate) fn fetch_announcement_tip() -> Option { + ANNOUNCEMENT_TIP + .get() + .cloned() + .flatten() + .and_then(|raw| parse_announcement_tip_toml(&raw)) + } + + #[derive(Debug, Deserialize)] + struct AnnouncementTipRaw { + content: String, + from_date: Option, + to_date: Option, + version_regex: Option, + target_app: Option, + } + + #[derive(Debug, Deserialize)] + struct AnnouncementTipDocument { + announcements: Vec, + } + + #[derive(Debug)] + struct AnnouncementTip { + content: String, + from_date: Option, + to_date: Option, + version_regex: Option, + target_app: String, + } + + fn init_announcement_tip_in_thread() -> Option { + thread::spawn(blocking_init_announcement_tip) + .join() + .ok() + .flatten() + } + + fn blocking_init_announcement_tip() -> Option { + let response = reqwest::blocking::Client::new() + .get(ANNOUNCEMENT_TIP_URL) + .timeout(Duration::from_millis(2000)) + .send() + .ok()?; + response.error_for_status().ok()?.text().ok() + } + + pub(crate) fn parse_announcement_tip_toml(text: &str) -> Option { + let announcements = toml::from_str::(text) + .map(|doc| doc.announcements) + .or_else(|_| toml::from_str::>(text)) + .ok()?; + + let mut latest_match = None; + let today = Utc::now().date_naive(); + for raw in announcements { + let Some(tip) = AnnouncementTip::from_raw(raw) else { + continue; + }; + if tip.version_matches(CODEX_CLI_VERSION) + && tip.date_matches(today) + && tip.target_app == "cli" + { + latest_match = Some(tip.content); + } + } + latest_match + } + + impl AnnouncementTip { + fn from_raw(raw: AnnouncementTipRaw) -> Option { + let content = raw.content.trim(); + if content.is_empty() { + return None; + } + + let from_date = match raw.from_date { + Some(date) => Some(NaiveDate::parse_from_str(&date, "%Y-%m-%d").ok()?), + None => None, + }; + let to_date = match raw.to_date { + Some(date) => Some(NaiveDate::parse_from_str(&date, "%Y-%m-%d").ok()?), + None => None, + }; + let version_regex = match raw.version_regex { + Some(pattern) => Some(Regex::new(&pattern).ok()?), + None => None, + }; + + Some(Self { + content: content.to_string(), + from_date, + to_date, + version_regex, + target_app: raw.target_app.unwrap_or("cli".to_string()).to_lowercase(), + }) + } + + fn version_matches(&self, version: &str) -> bool { + self.version_regex + .as_ref() + .is_none_or(|regex| regex.is_match(version)) + } + + fn date_matches(&self, today: NaiveDate) -> bool { + if let Some(from) = self.from_date + && today < from + { + return false; + } + if let Some(to) = self.to_date + && today >= to + { + return false; + } + true + } + } +} + #[cfg(test)] mod tests { use super::*; + use crate::tooltips::announcement::parse_announcement_tip_toml; use rand::SeedableRng; use rand::rngs::StdRng; @@ -62,4 +208,104 @@ mod tests { let mut rng = StdRng::seed_from_u64(7); assert_eq!(expected, pick_tooltip(&mut rng)); } + + #[test] + fn announcement_tip_toml_picks_last_matching() { + let toml = r#" +[[announcements]] +content = "first" +from_date = "2000-01-01" + +[[announcements]] +content = "latest match" +version_regex = ".*" +target_app = "cli" + +[[announcements]] +content = "should not match" +to_date = "2000-01-01" + "#; + + assert_eq!( + Some("latest match".to_string()), + parse_announcement_tip_toml(toml) + ); + + let toml = r#" +[[announcements]] +content = "first" +from_date = "2000-01-01" +target_app = "cli" + +[[announcements]] +content = "latest match" +version_regex = ".*" + +[[announcements]] +content = "should not match" +to_date = "2000-01-01" + "#; + + assert_eq!( + Some("latest match".to_string()), + parse_announcement_tip_toml(toml) + ); + } + + #[test] + fn announcement_tip_toml_picks_no_match() { + let toml = r#" +[[announcements]] +content = "first" +from_date = "2000-01-01" +to_date = "2000-01-05" + +[[announcements]] +content = "latest match" +version_regex = "invalid_version_name" + +[[announcements]] +content = "should not match either " +target_app = "vsce" + "#; + + assert_eq!(None, parse_announcement_tip_toml(toml)); + } + + #[test] + fn announcement_tip_toml_bad_deserialization() { + let toml = r#" +[[announcements]] +content = 123 +from_date = "2000-01-01" + "#; + + assert_eq!(None, parse_announcement_tip_toml(toml)); + } + + #[test] + fn announcement_tip_toml_parse_comments() { + let toml = r#" +# Example announcement tips for Codex TUI. +# Each [[announcements]] entry is evaluated in order; the last matching one is shown. +# Dates are UTC, formatted as YYYY-MM-DD. The from_date is inclusive and the to_date is exclusive. +# version_regex matches against the CLI version (env!("CARGO_PKG_VERSION")); omit to apply to all versions. +# target_app specify which app should display the announcement (cli, vsce, ...). + +[[announcements]] +content = "Welcome to Codex! Check out the new onboarding flow." +from_date = "2024-10-01" +to_date = "2024-10-15" +target_app = "cli" +version_regex = "^0\\.0\\.0$" + +[[announcements]] +content = "This is a test announcement" + "#; + + assert_eq!( + Some("This is a test announcement".to_string()), + parse_announcement_tip_toml(toml) + ); + } } diff --git a/codex-rs/tui2/src/history_cell.rs b/codex-rs/tui2/src/history_cell.rs index 4d96b389bc..3124d0fc31 100644 --- a/codex-rs/tui2/src/history_cell.rs +++ b/codex-rs/tui2/src/history_cell.rs @@ -817,11 +817,11 @@ pub(crate) fn padded_emoji(emoji: &str) -> String { #[derive(Debug)] struct TooltipHistoryCell { - tip: &'static str, + tip: String, } impl TooltipHistoryCell { - fn new(tip: &'static str) -> Self { + fn new(tip: String) -> Self { Self { tip } } } diff --git a/codex-rs/tui2/src/lib.rs b/codex-rs/tui2/src/lib.rs index 8cd3fde133..c8106e0877 100644 --- a/codex-rs/tui2/src/lib.rs +++ b/codex-rs/tui2/src/lib.rs @@ -361,6 +361,8 @@ async fn run_ratatui_app( ) -> color_eyre::Result { color_eyre::install()?; + tooltips::announcement::prewarm(); + // Forward panic reports through tracing so they appear in the UI status // line, but do not swallow the default/color-eyre panic handler. // Chain to the previous hook so users still get a rich panic report diff --git a/codex-rs/tui2/src/tooltips.rs b/codex-rs/tui2/src/tooltips.rs index eb419c2ea3..402a18ba2b 100644 --- a/codex-rs/tui2/src/tooltips.rs +++ b/codex-rs/tui2/src/tooltips.rs @@ -1,6 +1,9 @@ +use codex_core::features::FEATURES; use lazy_static::lazy_static; use rand::Rng; +const ANNOUNCEMENT_TIP_URL: &str = + "https://raw.githubusercontent.com/openai/codex/main/announcement_tip.toml"; const RAW_TOOLTIPS: &str = include_str!("../tooltips.txt"); lazy_static! { @@ -9,24 +12,183 @@ lazy_static! { .map(str::trim) .filter(|line| !line.is_empty() && !line.starts_with('#')) .collect(); + static ref ALL_TOOLTIPS: Vec<&'static str> = { + let mut tips = Vec::new(); + tips.extend(TOOLTIPS.iter().copied()); + tips.extend(beta_tooltips()); + tips + }; } -pub(crate) fn random_tooltip() -> Option<&'static str> { +fn beta_tooltips() -> Vec<&'static str> { + FEATURES + .iter() + .filter_map(|spec| spec.stage.beta_announcement()) + .collect() +} + +/// Pick a random tooltip to show to the user when starting Codex. +pub(crate) fn random_tooltip() -> Option { + if let Some(announcement) = announcement::fetch_announcement_tip() { + return Some(announcement); + } let mut rng = rand::rng(); - pick_tooltip(&mut rng) + pick_tooltip(&mut rng).map(str::to_string) } fn pick_tooltip(rng: &mut R) -> Option<&'static str> { - if TOOLTIPS.is_empty() { + if ALL_TOOLTIPS.is_empty() { None } else { - TOOLTIPS.get(rng.random_range(0..TOOLTIPS.len())).copied() + ALL_TOOLTIPS + .get(rng.random_range(0..ALL_TOOLTIPS.len())) + .copied() + } +} + +pub(crate) mod announcement { + use crate::tooltips::ANNOUNCEMENT_TIP_URL; + use crate::version::CODEX_CLI_VERSION; + use chrono::NaiveDate; + use chrono::Utc; + use regex_lite::Regex; + use serde::Deserialize; + use std::sync::OnceLock; + use std::thread; + use std::time::Duration; + + static ANNOUNCEMENT_TIP: OnceLock> = OnceLock::new(); + + /// Prewarm the cache of the announcement tip. + pub(crate) fn prewarm() { + let _ = thread::spawn(|| ANNOUNCEMENT_TIP.get_or_init(init_announcement_tip_in_thread)); + } + + /// Fetch the announcement tip, return None if the prewarm is not done yet. + pub(crate) fn fetch_announcement_tip() -> Option { + ANNOUNCEMENT_TIP + .get() + .cloned() + .flatten() + .and_then(|raw| parse_announcement_tip_toml(&raw)) + } + + #[derive(Debug, Deserialize)] + struct AnnouncementTipRaw { + content: String, + from_date: Option, + to_date: Option, + version_regex: Option, + target_app: Option, + } + + #[derive(Debug, Deserialize)] + struct AnnouncementTipDocument { + announcements: Vec, + } + + #[derive(Debug)] + struct AnnouncementTip { + content: String, + from_date: Option, + to_date: Option, + version_regex: Option, + target_app: String, + } + + fn init_announcement_tip_in_thread() -> Option { + thread::spawn(blocking_init_announcement_tip) + .join() + .ok() + .flatten() + } + + fn blocking_init_announcement_tip() -> Option { + let response = reqwest::blocking::Client::new() + .get(ANNOUNCEMENT_TIP_URL) + .timeout(Duration::from_millis(2000)) + .send() + .ok()?; + response.error_for_status().ok()?.text().ok() + } + + pub(crate) fn parse_announcement_tip_toml(text: &str) -> Option { + let announcements = toml::from_str::(text) + .map(|doc| doc.announcements) + .or_else(|_| toml::from_str::>(text)) + .ok()?; + + let mut latest_match = None; + let today = Utc::now().date_naive(); + for raw in announcements { + let Some(tip) = AnnouncementTip::from_raw(raw) else { + continue; + }; + if tip.version_matches(CODEX_CLI_VERSION) + && tip.date_matches(today) + && tip.target_app == "cli" + { + latest_match = Some(tip.content); + } + } + latest_match + } + + impl AnnouncementTip { + fn from_raw(raw: AnnouncementTipRaw) -> Option { + let content = raw.content.trim(); + if content.is_empty() { + return None; + } + + let from_date = match raw.from_date { + Some(date) => Some(NaiveDate::parse_from_str(&date, "%Y-%m-%d").ok()?), + None => None, + }; + let to_date = match raw.to_date { + Some(date) => Some(NaiveDate::parse_from_str(&date, "%Y-%m-%d").ok()?), + None => None, + }; + let version_regex = match raw.version_regex { + Some(pattern) => Some(Regex::new(&pattern).ok()?), + None => None, + }; + + Some(Self { + content: content.to_string(), + from_date, + to_date, + version_regex, + target_app: raw.target_app.unwrap_or("cli".to_string()).to_lowercase(), + }) + } + + fn version_matches(&self, version: &str) -> bool { + self.version_regex + .as_ref() + .is_none_or(|regex| regex.is_match(version)) + } + + fn date_matches(&self, today: NaiveDate) -> bool { + if let Some(from) = self.from_date + && today < from + { + return false; + } + if let Some(to) = self.to_date + && today >= to + { + return false; + } + true + } } } #[cfg(test)] mod tests { use super::*; + use crate::tooltips::announcement::parse_announcement_tip_toml; use rand::SeedableRng; use rand::rngs::StdRng; @@ -46,4 +208,104 @@ mod tests { let mut rng = StdRng::seed_from_u64(7); assert_eq!(expected, pick_tooltip(&mut rng)); } + + #[test] + fn announcement_tip_toml_picks_last_matching() { + let toml = r#" +[[announcements]] +content = "first" +from_date = "2000-01-01" + +[[announcements]] +content = "latest match" +version_regex = ".*" +target_app = "cli" + +[[announcements]] +content = "should not match" +to_date = "2000-01-01" + "#; + + assert_eq!( + Some("latest match".to_string()), + parse_announcement_tip_toml(toml) + ); + + let toml = r#" +[[announcements]] +content = "first" +from_date = "2000-01-01" +target_app = "cli" + +[[announcements]] +content = "latest match" +version_regex = ".*" + +[[announcements]] +content = "should not match" +to_date = "2000-01-01" + "#; + + assert_eq!( + Some("latest match".to_string()), + parse_announcement_tip_toml(toml) + ); + } + + #[test] + fn announcement_tip_toml_picks_no_match() { + let toml = r#" +[[announcements]] +content = "first" +from_date = "2000-01-01" +to_date = "2000-01-05" + +[[announcements]] +content = "latest match" +version_regex = "invalid_version_name" + +[[announcements]] +content = "should not match either " +target_app = "vsce" + "#; + + assert_eq!(None, parse_announcement_tip_toml(toml)); + } + + #[test] + fn announcement_tip_toml_bad_deserialization() { + let toml = r#" +[[announcements]] +content = 123 +from_date = "2000-01-01" + "#; + + assert_eq!(None, parse_announcement_tip_toml(toml)); + } + + #[test] + fn announcement_tip_toml_parse_comments() { + let toml = r#" +# Example announcement tips for Codex TUI. +# Each [[announcements]] entry is evaluated in order; the last matching one is shown. +# Dates are UTC, formatted as YYYY-MM-DD. The from_date is inclusive and the to_date is exclusive. +# version_regex matches against the CLI version (env!("CARGO_PKG_VERSION")); omit to apply to all versions. +# target_app specify which app should display the announcement (cli, vsce, ...). + +[[announcements]] +content = "Welcome to Codex! Check out the new onboarding flow." +from_date = "2024-10-01" +to_date = "2024-10-15" +target_app = "cli" +version_regex = "^0\\.0\\.0$" + +[[announcements]] +content = "This is a test announcement" + "#; + + assert_eq!( + Some("This is a test announcement".to_string()), + parse_announcement_tip_toml(toml) + ); + } } From 740bf0e7557297213da62b34624ce64a178e5006 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 6 Jan 2026 19:01:07 +0000 Subject: [PATCH 7/9] chore: clear background terminals on interrupt (#8786) --- codex-rs/tui/src/chatwidget.rs | 2 ++ codex-rs/tui/src/chatwidget/tests.rs | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 41ab0087ea..c83629976c 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -801,6 +801,8 @@ impl ChatWidget { fn on_interrupted_turn(&mut self, reason: TurnAbortReason) { // Finalize, log a gentle prompt, and clear running state. self.finalize_turn(); + self.unified_exec_sessions.clear(); + self.sync_unified_exec_footer(); if reason != TurnAbortReason::ReviewEnded { self.add_to_history(history_cell::new_error_event( diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index a0ff8d42e9..b1356bd6c5 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -2580,6 +2580,26 @@ async fn interrupt_prepends_queued_messages_before_existing_composer_text() { let _ = drain_insert_history(&mut rx); } +#[tokio::test] +async fn interrupt_clears_unified_exec_sessions() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await; + + begin_unified_exec_startup(&mut chat, "call-1", "process-1", "sleep 5"); + begin_unified_exec_startup(&mut chat, "call-2", "process-2", "sleep 6"); + assert_eq!(chat.unified_exec_sessions.len(), 2); + + chat.handle_codex_event(Event { + id: "turn-1".into(), + msg: EventMsg::TurnAborted(codex_core::protocol::TurnAbortedEvent { + reason: TurnAbortReason::Interrupted, + }), + }); + + assert!(chat.unified_exec_sessions.is_empty()); + + let _ = drain_insert_history(&mut rx); +} + // Snapshot test: ChatWidget at very small heights (idle) // Ensures overall layout behaves when terminal height is extremely constrained. #[tokio::test] From 915352b10cf708fa5e48f3bd80a30fb6ac5046cd Mon Sep 17 00:00:00 2001 From: Javi <666807+JaviSoto@users.noreply.github.com> Date: Tue, 6 Jan 2026 11:04:13 -0800 Subject: [PATCH 8/9] feat: add analytics config setting (#8350) --- .../app-server-protocol/src/protocol/v2.rs | 10 ++++++++ codex-rs/core/src/config/mod.rs | 24 +++++++++++++++++++ codex-rs/core/src/config/profile.rs | 1 + codex-rs/core/src/config/types.rs | 9 +++++++ 4 files changed, 44 insertions(+) diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 13a6545359..4311baba5f 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -330,6 +330,15 @@ pub struct ProfileV2 { pub additional: HashMap, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "snake_case")] +#[ts(export_to = "v2/")] +pub struct AnalyticsConfig { + pub enabled: Option, + #[serde(default, flatten)] + pub additional: HashMap, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "snake_case")] #[ts(export_to = "v2/")] @@ -354,6 +363,7 @@ pub struct Config { pub model_reasoning_effort: Option, pub model_reasoning_summary: Option, pub model_verbosity: Option, + pub analytics: Option, #[serde(default, flatten)] pub additional: HashMap, } diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 8eac13fd2e..035794f4aa 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -353,6 +353,10 @@ pub struct Config { /// or placeholder replacement will occur for fast keypress bursts. pub disable_paste_burst: bool, + /// When `false`, disables analytics across Codex product surfaces in this machine. + /// Defaults to `true`. + pub analytics: bool, + /// OTEL configuration (exporter type, endpoint, headers, etc.). pub otel: crate::config::types::OtelConfig, } @@ -813,6 +817,10 @@ pub struct ConfigToml { /// or placeholder replacement will occur for fast keypress bursts. pub disable_paste_burst: Option, + /// When `false`, disables analytics across Codex product surfaces in this machine. + /// Defaults to `true`. + pub analytics: Option, + /// OTEL configuration. pub otel: Option, @@ -1390,6 +1398,12 @@ impl Config { notices: cfg.notice.unwrap_or_default(), check_for_update_on_startup, disable_paste_burst: cfg.disable_paste_burst.unwrap_or(false), + analytics: config_profile + .analytics + .as_ref() + .and_then(|a| a.enabled) + .or(cfg.analytics.as_ref().and_then(|a| a.enabled)) + .unwrap_or(true), tui_notifications: cfg .tui .as_ref() @@ -3039,6 +3053,9 @@ approval_policy = "untrusted" # `ConfigOverrides`. profile = "gpt3" +[analytics] +enabled = true + [model_providers.openai-chat-completions] name = "OpenAI using Chat Completions" base_url = "https://api.openai.com/v1" @@ -3064,6 +3081,9 @@ model = "o3" model_provider = "openai" approval_policy = "on-failure" +[profiles.zdr.analytics] +enabled = false + [profiles.gpt5] model = "gpt-5.1" model_provider = "openai" @@ -3204,6 +3224,7 @@ model_verbosity = "high" tui_notifications: Default::default(), animations: true, show_tooltips: true, + analytics: true, tui_scroll_events_per_tick: None, tui_scroll_wheel_lines: None, tui_scroll_trackpad_lines: None, @@ -3287,6 +3308,7 @@ model_verbosity = "high" tui_notifications: Default::default(), animations: true, show_tooltips: true, + analytics: true, tui_scroll_events_per_tick: None, tui_scroll_wheel_lines: None, tui_scroll_trackpad_lines: None, @@ -3385,6 +3407,7 @@ model_verbosity = "high" tui_notifications: Default::default(), animations: true, show_tooltips: true, + analytics: false, tui_scroll_events_per_tick: None, tui_scroll_wheel_lines: None, tui_scroll_trackpad_lines: None, @@ -3469,6 +3492,7 @@ model_verbosity = "high" tui_notifications: Default::default(), animations: true, show_tooltips: true, + analytics: true, tui_scroll_events_per_tick: None, tui_scroll_wheel_lines: None, tui_scroll_trackpad_lines: None, diff --git a/codex-rs/core/src/config/profile.rs b/codex-rs/core/src/config/profile.rs index 9007064905..e1c45c1f16 100644 --- a/codex-rs/core/src/config/profile.rs +++ b/codex-rs/core/src/config/profile.rs @@ -29,6 +29,7 @@ pub struct ConfigProfile { pub experimental_use_freeform_apply_patch: Option, pub tools_web_search: Option, pub tools_view_image: Option, + pub analytics: Option, /// Optional feature toggles scoped to this profile. #[serde(default)] pub features: Option, diff --git a/codex-rs/core/src/config/types.rs b/codex-rs/core/src/config/types.rs index 3aa72d5ce5..6c421d4608 100644 --- a/codex-rs/core/src/config/types.rs +++ b/codex-rs/core/src/config/types.rs @@ -273,6 +273,15 @@ pub enum HistoryPersistence { None, } +// ===== Analytics configuration ===== + +/// Analytics settings loaded from config.toml. Fields are optional so we can apply defaults. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)] +pub struct AnalyticsConfigToml { + /// When `false`, disables analytics across Codex product surfaces in this profile. + pub enabled: Option, +} + // ===== OTEL configuration ===== #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] From 1dd1355df3b4d33fe84de77b8a3efba1ce940d92 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 6 Jan 2026 19:08:02 +0000 Subject: [PATCH 9/9] feat: agent controller (#8783) Added an agent control plane that lets sessions spawn or message other conversations via `AgentControl`. `AgentBus` (core/src/agent/bus.rs) keeps track of the last known status of a conversation. ConversationManager now holds shared state behind an Arc so AgentControl keeps only a weak back-reference, the goal is just to avoid explicit cycle reference. Follow-ups: * Build a small tool in the TUI to be able to see every agent and send manual message to each of them * Handle approval requests in this TUI * Add tools to spawn/communicate between agents (see related design) * Define agent types --- codex-rs/core/src/agent/bus.rs | 61 +++++ codex-rs/core/src/agent/control.rs | 254 ++++++++++++++++++ codex-rs/core/src/agent/mod.rs | 6 + codex-rs/core/src/codex.rs | 16 +- codex-rs/core/src/codex_delegate.rs | 1 + codex-rs/core/src/conversation_manager.rs | 290 ++++++++++++--------- codex-rs/core/src/lib.rs | 1 + codex-rs/core/src/state/service.rs | 2 + codex-rs/core/tests/common/test_codex.rs | 3 +- codex-rs/core/tests/suite/remote_models.rs | 3 +- 10 files changed, 511 insertions(+), 126 deletions(-) create mode 100644 codex-rs/core/src/agent/bus.rs create mode 100644 codex-rs/core/src/agent/control.rs create mode 100644 codex-rs/core/src/agent/mod.rs diff --git a/codex-rs/core/src/agent/bus.rs b/codex-rs/core/src/agent/bus.rs new file mode 100644 index 0000000000..0b15f415f1 --- /dev/null +++ b/codex-rs/core/src/agent/bus.rs @@ -0,0 +1,61 @@ +use codex_protocol::ConversationId; +use codex_protocol::protocol::EventMsg; +use std::collections::HashMap; +use std::sync::Arc; +use tokio::sync::RwLock; + +/// Status store for globally-tracked agents. +#[derive(Clone, Default)] +pub(crate) struct AgentBus { + /// In-memory map of conversation id to the latest derived status. + statuses: Arc>>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum AgentStatus { + PendingInit, + Running, + Completed(Option), + Errored(String), + Shutdown, + #[allow(dead_code)] // Used by upcoming multi-agent tooling. + NotFound, +} + +impl AgentBus { + /// Fetch the last known status for `agent_id`, returning `NotFound` if unseen. + #[allow(dead_code)] // Used by upcoming multi-agent tooling. + pub(crate) async fn status(&self, agent_id: ConversationId) -> AgentStatus { + let statuses = self.statuses.read().await; + statuses + .get(&agent_id) + .cloned() + .unwrap_or(AgentStatus::NotFound) + } + + /// Derive and record agent status from a single emitted event. + pub(crate) async fn on_event(&self, conversation_id: ConversationId, msg: &EventMsg) { + let next_status = match msg { + EventMsg::TaskStarted(_) => Some(AgentStatus::Running), + EventMsg::TaskComplete(ev) => { + Some(AgentStatus::Completed(ev.last_agent_message.clone())) + } + EventMsg::TurnAborted(ev) => Some(AgentStatus::Errored(format!("{:?}", ev.reason))), + EventMsg::Error(ev) => Some(AgentStatus::Errored(ev.message.clone())), + EventMsg::ShutdownComplete => Some(AgentStatus::Shutdown), + _ => None, + }; + if let Some(status) = next_status { + self.record_status(&conversation_id, status).await; + } + } + + /// Force-set the tracked status for an agent conversation. + pub(crate) async fn record_status( + &self, + conversation_id: &ConversationId, + status: AgentStatus, + ) { + self.statuses.write().await.insert(*conversation_id, status); + } +} diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs new file mode 100644 index 0000000000..181051b46c --- /dev/null +++ b/codex-rs/core/src/agent/control.rs @@ -0,0 +1,254 @@ +use crate::CodexConversation; +use crate::agent::AgentBus; +use crate::agent::AgentStatus; +use crate::conversation_manager::ConversationManagerState; +use crate::error::CodexErr; +use crate::error::Result as CodexResult; +use codex_protocol::ConversationId; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::user_input::UserInput; +use std::sync::Arc; +use std::sync::Weak; + +/// Control-plane handle for multi-agent operations. +/// `AgentControl` is held by each session (via `SessionServices`). It provides capability to +/// spawn new agents and the inter-agent communication layer. +#[derive(Clone, Default)] +pub(crate) struct AgentControl { + /// Weak handle back to the global conversation registry/state. + /// This is `Weak` to avoid reference cycles and shadow persistence of the form + /// `ConversationManagerState -> CodexConversation -> Session -> SessionServices -> ConversationManagerState`. + manager: Weak, + /// Shared agent status store updated from emitted events. + pub(crate) bus: AgentBus, +} + +impl AgentControl { + /// Construct a new `AgentControl` that can spawn/message agents via the given manager state. + pub(crate) fn new(manager: Weak, bus: AgentBus) -> Self { + Self { manager, bus } + } + + #[allow(dead_code)] // Used by upcoming multi-agent tooling. + /// Spawn a new agent conversation and submit the initial prompt. + /// + /// If `headless` is true, a background drain task is spawned to prevent unbounded event growth + /// of the channel queue when there is no client actively reading the conversation events. + pub(crate) async fn spawn_agent( + &self, + config: crate::config::Config, + prompt: String, + headless: bool, + ) -> CodexResult { + let state = self.upgrade()?; + let new_conversation = state.spawn_new_conversation(config, self.clone()).await?; + + self.bus + .record_status(&new_conversation.conversation_id, AgentStatus::PendingInit) + .await; + + if headless { + spawn_headless_drain( + Arc::clone(&new_conversation.conversation), + new_conversation.conversation_id, + self.clone(), + ); + } + + self.send_prompt(new_conversation.conversation_id, prompt) + .await?; + + self.bus + .record_status(&new_conversation.conversation_id, AgentStatus::Running) + .await; + + Ok(new_conversation.conversation_id) + } + + #[allow(dead_code)] // Used by upcoming multi-agent tooling. + /// Send a `user` prompt to an existing agent conversation. + pub(crate) async fn send_prompt( + &self, + agent_id: ConversationId, + prompt: String, + ) -> CodexResult { + let state = self.upgrade()?; + state + .send_op( + agent_id, + Op::UserInput { + items: vec![UserInput::Text { text: prompt }], + final_output_json_schema: None, + }, + ) + .await + } + + fn upgrade(&self) -> CodexResult> { + self.manager.upgrade().ok_or_else(|| { + CodexErr::UnsupportedOperation("conversation manager dropped".to_string()) + }) + } +} + +/// When an agent is spawned "headless" (no UI/view attached), there may be no consumer polling +/// `CodexConversation::next_event()`. The underlying event channel is unbounded, so the producer can +/// accumulate events indefinitely. This drain task prevents that memory growth by polling and +/// discarding events until shutdown. +fn spawn_headless_drain( + conversation: Arc, + conversation_id: ConversationId, + agent_control: AgentControl, +) { + tokio::spawn(async move { + loop { + match conversation.next_event().await { + Ok(event) => { + if matches!(event.msg, EventMsg::ShutdownComplete) { + break; + } + } + Err(err) => { + agent_control + .bus + .record_status(&conversation_id, AgentStatus::Errored(err.to_string())) + .await; + break; + } + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use codex_protocol::protocol::ErrorEvent; + use codex_protocol::protocol::TaskCompleteEvent; + use codex_protocol::protocol::TaskStartedEvent; + use codex_protocol::protocol::TurnAbortReason; + use codex_protocol::protocol::TurnAbortedEvent; + use pretty_assertions::assert_eq; + + #[tokio::test] + async fn send_prompt_errors_when_manager_dropped() { + let control = AgentControl::default(); + let err = control + .send_prompt(ConversationId::new(), "hello".to_string()) + .await + .expect_err("send_prompt should fail without a manager"); + assert_eq!( + err.to_string(), + "unsupported operation: conversation manager dropped" + ); + } + + #[tokio::test] + async fn record_status_persists_to_bus() { + let control = AgentControl::default(); + let conversation_id = ConversationId::new(); + + control + .bus + .record_status(&conversation_id, AgentStatus::PendingInit) + .await; + + let got = control.bus.status(conversation_id).await; + assert_eq!(got, AgentStatus::PendingInit); + } + + #[tokio::test] + async fn on_event_updates_status_from_task_started() { + let control = AgentControl::default(); + let conversation_id = ConversationId::new(); + + control + .bus + .on_event( + conversation_id, + &EventMsg::TaskStarted(TaskStartedEvent { + model_context_window: None, + }), + ) + .await; + + let got = control.bus.status(conversation_id).await; + assert_eq!(got, AgentStatus::Running); + } + + #[tokio::test] + async fn on_event_updates_status_from_task_complete() { + let control = AgentControl::default(); + let conversation_id = ConversationId::new(); + + control + .bus + .on_event( + conversation_id, + &EventMsg::TaskComplete(TaskCompleteEvent { + last_agent_message: Some("done".to_string()), + }), + ) + .await; + + let expected = AgentStatus::Completed(Some("done".to_string())); + let got = control.bus.status(conversation_id).await; + assert_eq!(got, expected); + } + + #[tokio::test] + async fn on_event_updates_status_from_error() { + let control = AgentControl::default(); + let conversation_id = ConversationId::new(); + + control + .bus + .on_event( + conversation_id, + &EventMsg::Error(ErrorEvent { + message: "boom".to_string(), + codex_error_info: None, + }), + ) + .await; + + let expected = AgentStatus::Errored("boom".to_string()); + let got = control.bus.status(conversation_id).await; + assert_eq!(got, expected); + } + + #[tokio::test] + async fn on_event_updates_status_from_turn_aborted() { + let control = AgentControl::default(); + let conversation_id = ConversationId::new(); + + control + .bus + .on_event( + conversation_id, + &EventMsg::TurnAborted(TurnAbortedEvent { + reason: TurnAbortReason::Interrupted, + }), + ) + .await; + + let expected = AgentStatus::Errored("Interrupted".to_string()); + let got = control.bus.status(conversation_id).await; + assert_eq!(got, expected); + } + + #[tokio::test] + async fn on_event_updates_status_from_shutdown_complete() { + let control = AgentControl::default(); + let conversation_id = ConversationId::new(); + + control + .bus + .on_event(conversation_id, &EventMsg::ShutdownComplete) + .await; + + let got = control.bus.status(conversation_id).await; + assert_eq!(got, AgentStatus::Shutdown); + } +} diff --git a/codex-rs/core/src/agent/mod.rs b/codex-rs/core/src/agent/mod.rs new file mode 100644 index 0000000000..29eb9577a2 --- /dev/null +++ b/codex-rs/core/src/agent/mod.rs @@ -0,0 +1,6 @@ +pub(crate) mod bus; +pub(crate) mod control; + +pub(crate) use bus::AgentBus; +pub(crate) use bus::AgentStatus; +pub(crate) use control::AgentControl; diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index bb4a45a75d..2d73b47f5a 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -8,6 +8,7 @@ use std::sync::atomic::Ordering; use crate::AuthManager; use crate::SandboxState; +use crate::agent::AgentControl; use crate::client_common::REVIEW_PROMPT; use crate::compact; use crate::compact::run_inline_auto_compact_task; @@ -207,13 +208,14 @@ fn maybe_push_chat_wire_api_deprecation( impl Codex { /// Spawn a new [`Codex`] and initialize the session. - pub async fn spawn( + pub(crate) async fn spawn( config: Config, auth_manager: Arc, models_manager: Arc, skills_manager: Arc, conversation_history: InitialHistory, session_source: SessionSource, + agent_control: AgentControl, ) -> CodexResult { let (tx_sub, rx_sub) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY); let (tx_event, rx_event) = async_channel::unbounded(); @@ -284,6 +286,7 @@ impl Codex { conversation_history, session_source_clone, skills_manager, + agent_control, ) .await .map_err(|e| { @@ -549,6 +552,7 @@ impl Session { initial_history: InitialHistory, session_source: SessionSource, skills_manager: Arc, + agent_control: AgentControl, ) -> anyhow::Result> { debug!( "Configuring session: model={}; provider={:?}", @@ -670,6 +674,7 @@ impl Session { models_manager: Arc::clone(&models_manager), tool_approvals: Mutex::new(ApprovalStore::default()), skills_manager, + agent_control, }; let sess = Arc::new(Session { @@ -995,6 +1000,11 @@ impl Session { } pub(crate) async fn send_event_raw(&self, event: Event) { + self.services + .agent_control + .bus + .on_event(self.conversation_id, &event.msg) + .await; // Persist the event into rollout (recorder filters as needed) let rollout_items = vec![RolloutItem::EventMsg(event.msg.clone())]; self.persist_rollout_items(&rollout_items).await; @@ -3225,6 +3235,7 @@ mod tests { let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key")); let models_manager = Arc::new(ModelsManager::new(auth_manager.clone())); + let agent_control = AgentControl::default(); let exec_policy = ExecPolicyManager::default(); let model = ModelsManager::get_model_offline(config.model.as_deref()); let session_configuration = SessionConfiguration { @@ -3271,6 +3282,7 @@ mod tests { models_manager: Arc::clone(&models_manager), tool_approvals: Mutex::new(ApprovalStore::default()), skills_manager, + agent_control, }; let turn_context = Session::make_turn_context( @@ -3312,6 +3324,7 @@ mod tests { let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key")); let models_manager = Arc::new(ModelsManager::new(auth_manager.clone())); + let agent_control = AgentControl::default(); let exec_policy = ExecPolicyManager::default(); let model = ModelsManager::get_model_offline(config.model.as_deref()); let session_configuration = SessionConfiguration { @@ -3358,6 +3371,7 @@ mod tests { models_manager: Arc::clone(&models_manager), tool_approvals: Mutex::new(ApprovalStore::default()), skills_manager, + agent_control, }; let turn_context = Arc::new(Session::make_turn_context( diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index e767abf4ad..10d45190d2 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -52,6 +52,7 @@ pub(crate) async fn run_codex_conversation_interactive( Arc::clone(&parent_session.services.skills_manager), initial_history.unwrap_or(InitialHistory::New), SessionSource::SubAgent(SubAgentSource::Review), + parent_session.services.agent_control.clone(), ) .await?; let codex = Arc::new(codex); diff --git a/codex-rs/core/src/conversation_manager.rs b/codex-rs/core/src/conversation_manager.rs index 5093e03c60..1092a488b4 100644 --- a/codex-rs/core/src/conversation_manager.rs +++ b/codex-rs/core/src/conversation_manager.rs @@ -3,6 +3,8 @@ use crate::AuthManager; use crate::CodexAuth; #[cfg(any(test, feature = "test-support"))] use crate::ModelProviderInfo; +use crate::agent::AgentBus; +use crate::agent::AgentControl; use crate::codex::Codex; use crate::codex::CodexSpawnOk; use crate::codex::INITIAL_SUBMIT_ID; @@ -21,6 +23,7 @@ use codex_protocol::items::TurnItem; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ModelPreset; use codex_protocol::protocol::InitialHistory; +use codex_protocol::protocol::Op; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::SessionSource; use std::collections::HashMap; @@ -41,24 +44,36 @@ pub struct NewConversation { /// [`ConversationManager`] is responsible for creating conversations and /// maintaining them in memory. pub struct ConversationManager { + state: Arc, + #[cfg(any(test, feature = "test-support"))] + _test_codex_home_guard: Option, +} + +/// Shared, `Arc`-owned state for [`ConversationManager`]. This `Arc` is required to have a single +/// `Arc` reference that can be downgraded to by `AgentControl` while preventing every single +/// function to require an `Arc<&Self>`. +pub(crate) struct ConversationManagerState { conversations: Arc>>>, auth_manager: Arc, models_manager: Arc, skills_manager: Arc, session_source: SessionSource, - #[cfg(any(test, feature = "test-support"))] - _test_codex_home_guard: Option, + agent_bus: AgentBus, } impl ConversationManager { pub fn new(auth_manager: Arc, session_source: SessionSource) -> Self { - let skills_manager = Arc::new(SkillsManager::new(auth_manager.codex_home().to_path_buf())); Self { - conversations: Arc::new(RwLock::new(HashMap::new())), - auth_manager: auth_manager.clone(), - session_source, - models_manager: Arc::new(ModelsManager::new(auth_manager)), - skills_manager, + state: Arc::new(ConversationManagerState { + conversations: Arc::new(RwLock::new(HashMap::new())), + models_manager: Arc::new(ModelsManager::new(auth_manager.clone())), + skills_manager: Arc::new(SkillsManager::new( + auth_manager.codex_home().to_path_buf(), + )), + auth_manager, + session_source, + agent_bus: AgentBus::default(), + }), #[cfg(any(test, feature = "test-support"))] _test_codex_home_guard: None, } @@ -83,40 +98,166 @@ impl ConversationManager { provider: ModelProviderInfo, codex_home: PathBuf, ) -> Self { - let auth_manager = crate::AuthManager::from_auth_for_testing_with_home(auth, codex_home); - let skills_manager = Arc::new(SkillsManager::new(auth_manager.codex_home().to_path_buf())); + let auth_manager = AuthManager::from_auth_for_testing_with_home(auth, codex_home); Self { - conversations: Arc::new(RwLock::new(HashMap::new())), - auth_manager: auth_manager.clone(), - session_source: SessionSource::Exec, - models_manager: Arc::new(ModelsManager::with_provider(auth_manager, provider)), - skills_manager, + state: Arc::new(ConversationManagerState { + conversations: Arc::new(RwLock::new(HashMap::new())), + models_manager: Arc::new(ModelsManager::with_provider( + auth_manager.clone(), + provider, + )), + skills_manager: Arc::new(SkillsManager::new( + auth_manager.codex_home().to_path_buf(), + )), + auth_manager, + session_source: SessionSource::Exec, + agent_bus: AgentBus::default(), + }), _test_codex_home_guard: None, } } pub fn session_source(&self) -> SessionSource { - self.session_source.clone() + self.state.session_source.clone() } pub fn skills_manager(&self) -> Arc { - self.skills_manager.clone() + self.state.skills_manager.clone() + } + + pub fn get_models_manager(&self) -> Arc { + self.state.models_manager.clone() + } + + pub async fn list_models(&self, config: &Config) -> Vec { + self.state.models_manager.list_models(config).await + } + + pub async fn get_conversation( + &self, + conversation_id: ConversationId, + ) -> CodexResult> { + self.state.get_conversation(conversation_id).await } pub async fn new_conversation(&self, config: Config) -> CodexResult { + self.state + .spawn_conversation( + config, + InitialHistory::New, + Arc::clone(&self.state.auth_manager), + self.agent_control(), + ) + .await + } + + pub async fn resume_conversation_from_rollout( + &self, + config: Config, + rollout_path: PathBuf, + auth_manager: Arc, + ) -> CodexResult { + let initial_history = RolloutRecorder::get_rollout_history(&rollout_path).await?; + self.resume_conversation_with_history(config, initial_history, auth_manager) + .await + } + + pub async fn resume_conversation_with_history( + &self, + config: Config, + initial_history: InitialHistory, + auth_manager: Arc, + ) -> CodexResult { + self.state + .spawn_conversation(config, initial_history, auth_manager, self.agent_control()) + .await + } + + /// Removes the conversation from the manager's internal map, though the conversation is stored + /// as `Arc`, it is possible that other references to it exist elsewhere. + /// Returns the conversation if the conversation was found and removed. + pub async fn remove_conversation( + &self, + conversation_id: &ConversationId, + ) -> Option> { + self.state + .conversations + .write() + .await + .remove(conversation_id) + } + + /// Fork an existing conversation by taking messages up to the given position (not including + /// the message at the given position) and starting a new conversation with identical + /// configuration (unless overridden by the caller's `config`). The new conversation will have + /// a fresh id. + pub async fn fork_conversation( + &self, + nth_user_message: usize, + config: Config, + path: PathBuf, + ) -> CodexResult { + let history = RolloutRecorder::get_rollout_history(&path).await?; + let history = truncate_before_nth_user_message(history, nth_user_message); + self.state + .spawn_conversation( + config, + history, + Arc::clone(&self.state.auth_manager), + self.agent_control(), + ) + .await + } + + fn agent_control(&self) -> AgentControl { + AgentControl::new(Arc::downgrade(&self.state), self.state.agent_bus.clone()) + } +} + +impl ConversationManagerState { + pub(crate) async fn get_conversation( + &self, + conversation_id: ConversationId, + ) -> CodexResult> { + let conversations = self.conversations.read().await; + conversations + .get(&conversation_id) + .cloned() + .ok_or_else(|| CodexErr::ConversationNotFound(conversation_id)) + } + + pub(crate) async fn send_op( + &self, + conversation_id: ConversationId, + op: Op, + ) -> CodexResult { + self.get_conversation(conversation_id) + .await? + .submit(op) + .await + } + + #[allow(dead_code)] // Used by upcoming multi-agent tooling. + pub(crate) async fn spawn_new_conversation( + &self, + config: Config, + agent_control: AgentControl, + ) -> CodexResult { self.spawn_conversation( config, - self.auth_manager.clone(), - self.models_manager.clone(), + InitialHistory::New, + Arc::clone(&self.auth_manager), + agent_control, ) .await } - async fn spawn_conversation( + pub(crate) async fn spawn_conversation( &self, config: Config, + initial_history: InitialHistory, auth_manager: Arc, - models_manager: Arc, + agent_control: AgentControl, ) -> CodexResult { let CodexSpawnOk { codex, @@ -124,10 +265,11 @@ impl ConversationManager { } = Codex::spawn( config, auth_manager, - models_manager, - self.skills_manager.clone(), - InitialHistory::New, + Arc::clone(&self.models_manager), + Arc::clone(&self.skills_manager), + initial_history, self.session_source.clone(), + agent_control, ) .await?; self.finalize_spawn(codex, conversation_id).await @@ -138,9 +280,6 @@ impl ConversationManager { codex: Codex, conversation_id: ConversationId, ) -> CodexResult { - // The first event must be `SessionInitialized`. Validate and forward it - // to the caller so that they can display it in the conversation - // history. let event = codex.next_event().await?; let session_configured = match event { Event { @@ -167,100 +306,6 @@ impl ConversationManager { session_configured, }) } - - pub async fn get_conversation( - &self, - conversation_id: ConversationId, - ) -> CodexResult> { - let conversations = self.conversations.read().await; - conversations - .get(&conversation_id) - .cloned() - .ok_or_else(|| CodexErr::ConversationNotFound(conversation_id)) - } - - pub async fn resume_conversation_from_rollout( - &self, - config: Config, - rollout_path: PathBuf, - auth_manager: Arc, - ) -> CodexResult { - let initial_history = RolloutRecorder::get_rollout_history(&rollout_path).await?; - self.resume_conversation_with_history(config, initial_history, auth_manager) - .await - } - - pub async fn resume_conversation_with_history( - &self, - config: Config, - initial_history: InitialHistory, - auth_manager: Arc, - ) -> CodexResult { - let CodexSpawnOk { - codex, - conversation_id, - } = Codex::spawn( - config, - auth_manager, - self.models_manager.clone(), - self.skills_manager.clone(), - initial_history, - self.session_source.clone(), - ) - .await?; - self.finalize_spawn(codex, conversation_id).await - } - - /// Removes the conversation from the manager's internal map, though the - /// conversation is stored as `Arc`, it is possible that - /// other references to it exist elsewhere. Returns the conversation if the - /// conversation was found and removed. - pub async fn remove_conversation( - &self, - conversation_id: &ConversationId, - ) -> Option> { - self.conversations.write().await.remove(conversation_id) - } - - /// Fork an existing conversation by taking messages up to the given position - /// (not including the message at the given position) and starting a new - /// conversation with identical configuration (unless overridden by the - /// caller's `config`). The new conversation will have a fresh id. - pub async fn fork_conversation( - &self, - nth_user_message: usize, - config: Config, - path: PathBuf, - ) -> CodexResult { - // Compute the prefix up to the cut point. - let history = RolloutRecorder::get_rollout_history(&path).await?; - let history = truncate_before_nth_user_message(history, nth_user_message); - - // Spawn a new conversation with the computed initial history. - let auth_manager = self.auth_manager.clone(); - let CodexSpawnOk { - codex, - conversation_id, - } = Codex::spawn( - config, - auth_manager, - self.models_manager.clone(), - self.skills_manager.clone(), - history, - self.session_source.clone(), - ) - .await?; - - self.finalize_spawn(codex, conversation_id).await - } - - pub async fn list_models(&self, config: &Config) -> Vec { - self.models_manager.list_models(config).await - } - - pub fn get_models_manager(&self) -> Arc { - self.models_manager.clone() - } } /// Return a prefix of `items` obtained by cutting strictly before the nth user message @@ -345,14 +390,13 @@ mod tests { }, ResponseItem::FunctionCall { id: None, + call_id: "c1".to_string(), name: "tool".to_string(), arguments: "{}".to_string(), - call_id: "c1".to_string(), }, assistant_msg("a4"), ]; - // Wrap as InitialHistory::Forked with response items only. let initial: Vec = items .iter() .cloned() diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 8794484083..b9f2645b13 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -15,6 +15,7 @@ pub mod codex; mod codex_conversation; mod compact_remote; pub use codex_conversation::CodexConversation; +mod agent; mod codex_delegate; mod command_safety; pub mod config; diff --git a/codex-rs/core/src/state/service.rs b/codex-rs/core/src/state/service.rs index 63b66647e5..8520dbb252 100644 --- a/codex-rs/core/src/state/service.rs +++ b/codex-rs/core/src/state/service.rs @@ -2,6 +2,7 @@ use std::sync::Arc; use crate::AuthManager; use crate::RolloutRecorder; +use crate::agent::AgentControl; use crate::exec_policy::ExecPolicyManager; use crate::mcp_connection_manager::McpConnectionManager; use crate::models_manager::manager::ModelsManager; @@ -28,4 +29,5 @@ pub(crate) struct SessionServices { pub(crate) otel_manager: OtelManager, pub(crate) tool_approvals: Mutex, pub(crate) skills_manager: Arc, + pub(crate) agent_control: AgentControl, } diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index a081a6bf12..7ae3ea159f 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -143,6 +143,7 @@ impl TestCodexBuilder { config.model_provider.clone(), config.codex_home.clone(), ); + let conversation_manager = Arc::new(conversation_manager); let new_conversation = match resume_from { Some(path) => { @@ -164,7 +165,7 @@ impl TestCodexBuilder { config, codex: new_conversation.conversation, session_configured: new_conversation.session_configured, - conversation_manager: Arc::new(conversation_manager), + conversation_manager, }) } diff --git a/codex-rs/core/tests/suite/remote_models.rs b/codex-rs/core/tests/suite/remote_models.rs index 201d61c9e0..e4db774ddb 100644 --- a/codex-rs/core/tests/suite/remote_models.rs +++ b/codex-rs/core/tests/suite/remote_models.rs @@ -442,7 +442,8 @@ where mutate_config(&mut config); - let conversation_manager = Arc::new(ConversationManager::with_models_provider(auth, provider)); + let conversation_manager = ConversationManager::with_models_provider(auth, provider); + let conversation_manager = Arc::new(conversation_manager); let new_conversation = conversation_manager .new_conversation(config.clone())