From 743caea3a6624796a0809537f5ecbd7663b6c241 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 19 Feb 2026 13:49:12 +0000 Subject: [PATCH 1/9] feat: add shell snapshot failure reason (#12233) --- codex-rs/core/src/shell_snapshot.rs | 58 +++++++++++++++-------------- 1 file changed, 31 insertions(+), 27 deletions(-) diff --git a/codex-rs/core/src/shell_snapshot.rs b/codex-rs/core/src/shell_snapshot.rs index 6eb1ef71da..4e5ddd2e40 100644 --- a/codex-rs/core/src/shell_snapshot.rs +++ b/codex-rs/core/src/shell_snapshot.rs @@ -95,10 +95,15 @@ impl ShellSnapshot { ) .await .map(Arc::new); - let success = if snapshot.is_some() { "true" } else { "false" }; - let _ = timer.map(|timer| timer.record(&[("success", success)])); - otel_manager.counter("codex.shell_snapshot", 1, &[("success", success)]); - let _ = shell_snapshot_tx.send(snapshot); + let success = snapshot.is_ok(); + let success_tag = if success { "true" } else { "false" }; + let _ = timer.map(|timer| timer.record(&[("success", success_tag)])); + let mut counter_tags = vec![("success", success_tag)]; + if let Some(failure_reason) = snapshot.as_ref().err() { + counter_tags.push(("failure_reason", *failure_reason)); + } + otel_manager.counter("codex.shell_snapshot", 1, &counter_tags); + let _ = shell_snapshot_tx.send(snapshot.ok()); } .instrument(snapshot_span), ); @@ -109,7 +114,7 @@ impl ShellSnapshot { session_id: ThreadId, session_cwd: &Path, shell: &Shell, - ) -> Option { + ) -> std::result::Result { // File to store the snapshot let extension = match shell.shell_type { ShellType::PowerShell => "ps1", @@ -129,32 +134,31 @@ impl ShellSnapshot { }); // Make the new snapshot. - let snapshot = - match write_shell_snapshot(shell.shell_type.clone(), &path, session_cwd).await { - Ok(path) => { - tracing::info!("Shell snapshot successfully created: {}", path.display()); - Some(Self { - path, - cwd: session_cwd.to_path_buf(), - }) - } - Err(err) => { - tracing::warn!( - "Failed to create shell snapshot for {}: {err:?}", - shell.name() - ); - None - } - }; + let path = match write_shell_snapshot(shell.shell_type.clone(), &path, session_cwd).await { + Ok(path) => { + tracing::info!("Shell snapshot successfully created: {}", path.display()); + path + } + Err(err) => { + tracing::warn!( + "Failed to create shell snapshot for {}: {err:?}", + shell.name() + ); + return Err("write_failed"); + } + }; - if let Some(snapshot) = snapshot.as_ref() - && let Err(err) = validate_snapshot(shell, &snapshot.path, session_cwd).await - { + let snapshot = Self { + path, + cwd: session_cwd.to_path_buf(), + }; + + if let Err(err) = validate_snapshot(shell, &snapshot.path, session_cwd).await { tracing::error!("Shell snapshot validation failed: {err:?}"); - return None; + return Err("validation_failed"); } - snapshot + Ok(snapshot) } } From f595e11723d21ee193804d243ee7b8a16725d8fa Mon Sep 17 00:00:00 2001 From: viyatb-oai Date: Thu, 19 Feb 2026 09:12:59 -0800 Subject: [PATCH 2/9] docs: add codex security policy (#12193) ## Summary Adds SECURITY.MD with Codex security policy and Bugcrowd reporting guidance --- SECURITY.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000000..d6dd568910 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,13 @@ +# Security Policy + +Thank you for helping us keep Codex secure! + +## Reporting Security Issues + +The security is essential to OpenAI's mission. We appreciate the work of security researchers acting in good faith to identify and responsibly report potential vulnerabilities, helping us maintain strong privacy and security standards for our users and technology. + +Our security program is managed through Bugcrowd, and we ask that any validated vulnerabilities be reported via the [Bugcrowd program](https://bugcrowd.com/engagements/openai). + +## Vulnerability Disclosure Program + +Our Vulnerability Program Guidelines are defined on our [Bugcrowd program page](https://bugcrowd.com/engagements/openai). From 547f46238550992dc02bf3cc4526733965344930 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 19 Feb 2026 17:22:13 +0000 Subject: [PATCH 3/9] feat: add configurable write_stdin timeout (#12228) Add max timeout as config for `write_stdin`. This is only used for empty `write_stdin`. Also increased the default value from 30s to 5mins. --- codex-rs/core/config.schema.json | 6 ++++++ codex-rs/core/src/codex.rs | 12 +++++++++--- codex-rs/core/src/config/mod.rs | 19 +++++++++++++++++++ codex-rs/core/src/unified_exec/mod.rs | 16 +++++++++++++--- .../core/src/unified_exec/process_manager.rs | 9 ++++++--- 5 files changed, 53 insertions(+), 9 deletions(-) diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 592e5ed932..5408d37d73 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1295,6 +1295,12 @@ "default": null, "description": "Settings for app-specific controls." }, + "background_terminal_timeout": { + "description": "Maximum poll window for background terminal output (`write_stdin`), in milliseconds. Default: `300000` (5 minutes).", + "format": "uint64", + "minimum": 0.0, + "type": "integer" + }, "chatgpt_base_url": { "description": "Base URL for requests to ChatGPT (as opposed to the OpenAI API).", "type": "string" diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 46a2087f27..3ba06cba4b 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -1287,7 +1287,9 @@ impl Session { let services = SessionServices { mcp_connection_manager: Arc::new(RwLock::new(McpConnectionManager::default())), mcp_startup_cancellation_token: Mutex::new(CancellationToken::new()), - unified_exec_manager: UnifiedExecProcessManager::default(), + unified_exec_manager: UnifiedExecProcessManager::new( + config.background_terminal_max_timeout, + ), zsh_exec_bridge, analytics_events_client: AnalyticsEventsClient::new( Arc::clone(&config), @@ -7376,7 +7378,9 @@ mod tests { let services = SessionServices { mcp_connection_manager: Arc::new(RwLock::new(McpConnectionManager::default())), mcp_startup_cancellation_token: Mutex::new(CancellationToken::new()), - unified_exec_manager: UnifiedExecProcessManager::default(), + unified_exec_manager: UnifiedExecProcessManager::new( + config.background_terminal_max_timeout, + ), zsh_exec_bridge: ZshExecBridge::default(), analytics_events_client: AnalyticsEventsClient::new( Arc::clone(&config), @@ -7525,7 +7529,9 @@ mod tests { let services = SessionServices { mcp_connection_manager: Arc::new(RwLock::new(McpConnectionManager::default())), mcp_startup_cancellation_token: Mutex::new(CancellationToken::new()), - unified_exec_manager: UnifiedExecProcessManager::default(), + unified_exec_manager: UnifiedExecProcessManager::new( + config.background_terminal_max_timeout, + ), zsh_exec_bridge: ZshExecBridge::default(), analytics_events_client: AnalyticsEventsClient::new( Arc::clone(&config), diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index b0656c788b..ec4e378948 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -51,6 +51,8 @@ use crate::protocol::ReadOnlyAccess; use crate::protocol::SandboxPolicy; #[cfg(target_os = "macos")] use crate::seatbelt_permissions::MacOsSeatbeltProfileExtensions; +use crate::unified_exec::DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS; +use crate::unified_exec::MIN_EMPTY_YIELD_TIME_MS; use crate::windows_sandbox::WindowsSandboxLevelExt; use crate::windows_sandbox::resolve_windows_sandbox_mode; use codex_app_server_protocol::Tools; @@ -380,6 +382,10 @@ pub struct Config { /// If set to `true`, used only the experimental unified exec tool. pub use_experimental_unified_exec_tool: bool, + /// Maximum poll window for background terminal output (`write_stdin`), in milliseconds. + /// Default: `300000` (5 minutes). + pub background_terminal_max_timeout: u64, + /// Settings for ghost snapshots (used for undo). pub ghost_snapshot: GhostSnapshotConfig, @@ -982,6 +988,10 @@ pub struct ConfigToml { /// Token budget applied when storing tool/function outputs in the context manager. pub tool_output_token_limit: Option, + /// Maximum poll window for background terminal output (`write_stdin`), in milliseconds. + /// Default: `300000` (5 minutes). + pub background_terminal_timeout: Option, + /// Optional absolute path to the Node runtime used by `js_repl`. pub js_repl_node_path: Option, @@ -1675,6 +1685,10 @@ impl Config { }) .transpose()? .unwrap_or_default(); + let background_terminal_max_timeout = cfg + .background_terminal_timeout + .unwrap_or(DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS) + .max(MIN_EMPTY_YIELD_TIME_MS); let ghost_snapshot = { let mut config = GhostSnapshotConfig::default(); @@ -1925,6 +1939,7 @@ impl Config { include_apply_patch_tool: include_apply_patch_tool_flag, web_search_mode: constrained_web_search_mode.value, use_experimental_unified_exec_tool, + background_terminal_max_timeout, ghost_snapshot, features, suppress_unstable_features_warning: cfg @@ -4346,6 +4361,7 @@ model_verbosity = "high" include_apply_patch_tool: false, web_search_mode: Constrained::allow_any(WebSearchMode::Cached), use_experimental_unified_exec_tool: !cfg!(windows), + background_terminal_max_timeout: DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS, ghost_snapshot: GhostSnapshotConfig::default(), features: Features::with_defaults(), suppress_unstable_features_warning: false, @@ -4460,6 +4476,7 @@ model_verbosity = "high" include_apply_patch_tool: false, web_search_mode: Constrained::allow_any(WebSearchMode::Cached), use_experimental_unified_exec_tool: !cfg!(windows), + background_terminal_max_timeout: DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS, ghost_snapshot: GhostSnapshotConfig::default(), features: Features::with_defaults(), suppress_unstable_features_warning: false, @@ -4572,6 +4589,7 @@ model_verbosity = "high" include_apply_patch_tool: false, web_search_mode: Constrained::allow_any(WebSearchMode::Cached), use_experimental_unified_exec_tool: !cfg!(windows), + background_terminal_max_timeout: DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS, ghost_snapshot: GhostSnapshotConfig::default(), features: Features::with_defaults(), suppress_unstable_features_warning: false, @@ -4670,6 +4688,7 @@ model_verbosity = "high" include_apply_patch_tool: false, web_search_mode: Constrained::allow_any(WebSearchMode::Cached), use_experimental_unified_exec_tool: !cfg!(windows), + background_terminal_max_timeout: DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS, ghost_snapshot: GhostSnapshotConfig::default(), features: Features::with_defaults(), suppress_unstable_features_warning: false, diff --git a/codex-rs/core/src/unified_exec/mod.rs b/codex-rs/core/src/unified_exec/mod.rs index a907f348f2..4339d25ace 100644 --- a/codex-rs/core/src/unified_exec/mod.rs +++ b/codex-rs/core/src/unified_exec/mod.rs @@ -54,6 +54,7 @@ pub(crate) const MIN_YIELD_TIME_MS: u64 = 250; // Minimum yield time for an empty `write_stdin`. pub(crate) const MIN_EMPTY_YIELD_TIME_MS: u64 = 5_000; pub(crate) const MAX_YIELD_TIME_MS: u64 = 30_000; +pub(crate) const DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS: u64 = 300_000; pub(crate) const DEFAULT_MAX_OUTPUT_TOKENS: usize = 10_000; pub(crate) const UNIFIED_EXEC_OUTPUT_MAX_BYTES: usize = 1024 * 1024; // 1 MiB pub(crate) const UNIFIED_EXEC_OUTPUT_MAX_TOKENS: usize = UNIFIED_EXEC_OUTPUT_MAX_BYTES / 4; @@ -129,13 +130,22 @@ impl ProcessStore { pub(crate) struct UnifiedExecProcessManager { process_store: Mutex, + max_write_stdin_yield_time_ms: u64, +} + +impl UnifiedExecProcessManager { + pub(crate) fn new(max_write_stdin_yield_time_ms: u64) -> Self { + Self { + process_store: Mutex::new(ProcessStore::default()), + max_write_stdin_yield_time_ms: max_write_stdin_yield_time_ms + .max(MIN_EMPTY_YIELD_TIME_MS), + } + } } impl Default for UnifiedExecProcessManager { fn default() -> Self { - Self { - process_store: Mutex::new(ProcessStore::default()), - } + Self::new(DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS) } } diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index 6896df14b4..f2468583d2 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -33,6 +33,7 @@ use crate::unified_exec::ExecCommandRequest; use crate::unified_exec::MAX_UNIFIED_EXEC_PROCESSES; use crate::unified_exec::MAX_YIELD_TIME_MS; use crate::unified_exec::MIN_EMPTY_YIELD_TIME_MS; +use crate::unified_exec::MIN_YIELD_TIME_MS; use crate::unified_exec::ProcessEntry; use crate::unified_exec::ProcessStore; use crate::unified_exec::UnifiedExecContext; @@ -351,11 +352,13 @@ impl UnifiedExecProcessManager { let max_tokens = resolve_max_tokens(request.max_output_tokens); let yield_time_ms = { - let time_ms = clamp_yield_time(request.yield_time_ms); + // Empty polls use configurable background timeout bounds. Non-empty + // writes keep a fixed max cap so interactive stdin remains responsive. + let time_ms = request.yield_time_ms.max(MIN_YIELD_TIME_MS); if request.input.is_empty() { - time_ms.clamp(MIN_EMPTY_YIELD_TIME_MS, MAX_YIELD_TIME_MS) + time_ms.clamp(MIN_EMPTY_YIELD_TIME_MS, self.max_write_stdin_yield_time_ms) } else { - time_ms + time_ms.min(MAX_YIELD_TIME_MS) } }; let start = Instant::now(); From f6fd4cb3f57a8fcc709541686322db689b9172ae Mon Sep 17 00:00:00 2001 From: colby-oai <228809017+colby-oai@users.noreply.github.com> Date: Thu, 19 Feb 2026 12:52:42 -0500 Subject: [PATCH 4/9] Adjust MCP tool approval handling for custom servers (#11787) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary This PR expands MCP client-side approval behavior beyond codex_apps and tightens elicitation capability signaling. - Removed the codex_apps-only gate in MCP tool approval checks, so local/custom MCP servers are now eligible for the same client-side approval prompt flow when tool annotations indicate side effects. - Updated approval memory keying to support tools without a connector ID (connector_id: Option), allowing “Approve this Session” to be remembered even when connector metadata is missing. - Updated prompt text for non-codex_apps tools to identify origin as The MCP server instead of This app. - Added MCP initialization capability policy so only codex_apps advertises MCP elicitation capability; other servers advertise no elicitation support. - Added regression tests for: server-specific prompt copy behavior codex-apps-only elicitation capability advertisement Testing - Not run (not requested) --- codex-rs/core/src/mcp_connection_manager.rs | 42 ++++++++-- codex-rs/core/src/mcp_tool_call.rs | 86 ++++++++++++++++----- 2 files changed, 99 insertions(+), 29 deletions(-) diff --git a/codex-rs/core/src/mcp_connection_manager.rs b/codex-rs/core/src/mcp_connection_manager.rs index 589be7aac2..62c4dedd47 100644 --- a/codex-rs/core/src/mcp_connection_manager.rs +++ b/codex-rs/core/src/mcp_connection_manager.rs @@ -1006,6 +1006,21 @@ impl From for StartupOutcomeError { } } +fn elicitation_capability_for_server(server_name: &str) -> Option { + if server_name == CODEX_APPS_MCP_SERVER_NAME { + // https://modelcontextprotocol.io/specification/2025-06-18/client/elicitation#capabilities + // indicates this should be an empty object. + Some(ElicitationCapability { + form: Some(FormElicitationCapability { + schema_validation: None, + }), + url: None, + }) + } else { + None + } +} + async fn start_server_task( server_name: String, client: Arc, @@ -1015,6 +1030,8 @@ async fn start_server_task( tx_event: Sender, elicitation_requests: ElicitationRequestManager, ) -> Result { + let elicitation = elicitation_capability_for_server(&server_name); + let params = InitializeRequestParams { meta: None, capabilities: ClientCapabilities { @@ -1022,14 +1039,7 @@ async fn start_server_task( extensions: None, roots: None, sampling: None, - // https://modelcontextprotocol.io/specification/2025-06-18/client/elicitation#capabilities - // indicates this should be an empty object. - elicitation: Some(ElicitationCapability { - form: Some(FormElicitationCapability { - schema_validation: None, - }), - url: None, - }), + elicitation, tasks: None, }, client_info: Implementation { @@ -1541,6 +1551,22 @@ mod tests { }); } + #[test] + fn elicitation_capability_enabled_only_for_codex_apps() { + let codex_apps_capability = elicitation_capability_for_server(CODEX_APPS_MCP_SERVER_NAME); + assert!(matches!( + codex_apps_capability, + Some(ElicitationCapability { + form: Some(FormElicitationCapability { + schema_validation: None + }), + url: None, + }) + )); + + assert!(elicitation_capability_for_server("custom_mcp").is_none()); + } + #[test] fn mcp_init_error_display_prompts_for_github_pat() { let server_name = "github"; diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 745633b148..5f7734118c 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -282,7 +282,7 @@ const MCP_TOOL_APPROVAL_CANCEL: &str = "Cancel"; #[derive(Debug, Serialize)] struct McpToolApprovalKey { server: String, - connector_id: String, + connector_id: Option, tool_name: String, } @@ -296,36 +296,29 @@ async fn maybe_request_mcp_tool_approval( if is_full_access_mode(turn_context) { return None; } - if server != CODEX_APPS_MCP_SERVER_NAME { - return None; - } let metadata = lookup_mcp_tool_metadata(sess, server, tool_name).await?; if !requires_mcp_tool_approval(&metadata.annotations) { return None; } - let approval_key = metadata - .connector_id - .as_deref() - .map(|connector_id| McpToolApprovalKey { - server: server.to_string(), - connector_id: connector_id.to_string(), - tool_name: tool_name.to_string(), - }); - if let Some(key) = approval_key.as_ref() - && mcp_tool_approval_is_remembered(sess, key).await - { + let approval_key = McpToolApprovalKey { + server: server.to_string(), + connector_id: metadata.connector_id.clone(), + tool_name: tool_name.to_string(), + }; + if mcp_tool_approval_is_remembered(sess, &approval_key).await { return Some(McpToolApprovalDecision::Accept); } let question_id = format!("{MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX}_{call_id}"); let question = build_mcp_tool_approval_question( question_id.clone(), + server, tool_name, metadata.tool_title.as_deref(), metadata.connector_name.as_deref(), &metadata.annotations, - approval_key.is_some(), + true, ); let args = RequestUserInputArgs { questions: vec![question], @@ -334,10 +327,8 @@ async fn maybe_request_mcp_tool_approval( .request_user_input(turn_context, call_id.to_string(), args) .await; let decision = parse_mcp_tool_approval_response(response, &question_id); - if matches!(decision, McpToolApprovalDecision::AcceptAndRemember) - && let Some(key) = approval_key - { - remember_mcp_tool_approval(sess, key).await; + if matches!(decision, McpToolApprovalDecision::AcceptAndRemember) { + remember_mcp_tool_approval(sess, approval_key).await; } Some(decision) } @@ -407,6 +398,7 @@ async fn lookup_mcp_app_usage_metadata( fn build_mcp_tool_approval_question( question_id: String, + server: &str, tool_name: &str, tool_title: Option<&str>, connector_name: Option<&str>, @@ -425,7 +417,13 @@ fn build_mcp_tool_approval_question( let tool_label = tool_title.unwrap_or(tool_name); let app_label = connector_name .map(|name| format!("The {name} app")) - .unwrap_or_else(|| "This app".to_string()); + .unwrap_or_else(|| { + if server == CODEX_APPS_MCP_SERVER_NAME { + "This app".to_string() + } else { + format!("The {server} MCP server") + } + }); let question = format!( "{app_label} wants to run the tool \"{tool_label}\", which {reason}. Allow this action?" ); @@ -570,6 +568,52 @@ mod tests { assert_eq!(requires_mcp_tool_approval(&annotations), false); } + #[test] + fn custom_mcp_tool_question_mentions_server_name() { + let question = build_mcp_tool_approval_question( + "q".to_string(), + "custom_server", + "run_action", + Some("Run Action"), + None, + &annotations(Some(false), Some(true), None), + true, + ); + + assert_eq!(question.header, "Approve app tool call?"); + assert_eq!( + question.question, + "The custom_server MCP server wants to run the tool \"Run Action\", which may modify or delete data. Allow this action?" + ); + assert!( + question + .options + .expect("options") + .into_iter() + .map(|option| option.label) + .any(|label| label == MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER) + ); + } + + #[test] + fn codex_apps_tool_question_keeps_legacy_app_label() { + let question = build_mcp_tool_approval_question( + "q".to_string(), + CODEX_APPS_MCP_SERVER_NAME, + "run_action", + Some("Run Action"), + None, + &annotations(Some(false), Some(true), None), + true, + ); + + assert!( + question + .question + .starts_with("This app wants to run the tool \"Run Action\"") + ); + } + #[test] fn sanitize_mcp_tool_result_for_model_rewrites_image_content() { let result = Ok(CallToolResult { From f2d5842ed1a14519dab545c6e15dfa9964f55254 Mon Sep 17 00:00:00 2001 From: Charley Cunningham Date: Thu, 19 Feb 2026 09:56:20 -0800 Subject: [PATCH 5/9] Move previous turn context tracking into ContextManager history (#12179) ## Summary - add `previous_context_item: Option` to `ContextManager` - expose session/state accessors for reading and updating the stored previous context item - switch settings diffing to use `TurnContextItem` instead of `TurnContext` - remove submission-loop local `previous_context` and persist the previous context item in history ## Testing - `just fmt` - `just fix -p codex-core` - `cargo test -p codex-core --test all model_switching::` - `cargo test -p codex-core --test all collaboration_instructions::` - `cargo test -p codex-core --test all personality::` - `cargo test -p codex-core --test all permissions_messages::permissions_message_not_added_when_no_change` --- codex-rs/core/src/codex.rs | 77 +++++++++----------- codex-rs/core/src/compact.rs | 8 +- codex-rs/core/src/context_manager/history.rs | 16 ++++ codex-rs/core/src/context_manager/updates.rs | 28 +++---- codex-rs/core/src/environment_context.rs | 31 +++++++- codex-rs/core/src/state/session.rs | 9 +++ 6 files changed, 103 insertions(+), 66 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 3ba06cba4b..0e1e49ba78 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -660,10 +660,7 @@ impl TurnContext { .unwrap_or(compact::SUMMARIZATION_PROMPT) } - pub(crate) fn to_turn_context_item( - &self, - collaboration_mode: CollaborationMode, - ) -> TurnContextItem { + pub(crate) fn to_turn_context_item(&self) -> TurnContextItem { TurnContextItem { turn_id: Some(self.sub_id.clone()), cwd: self.cwd.clone(), @@ -672,7 +669,7 @@ impl TurnContext { network: self.turn_context_network_item(), model: self.model_info.slug.clone(), personality: self.personality, - collaboration_mode: Some(collaboration_mode), + collaboration_mode: Some(self.collaboration_mode.clone()), effort: self.reasoning_effort, summary: self.reasoning_summary, user_instructions: self.user_instructions.clone(), @@ -1995,11 +1992,6 @@ impl Session { .await } - pub(crate) async fn current_collaboration_mode(&self) -> CollaborationMode { - let state = self.state.lock().await; - state.session_configuration.collaboration_mode.clone() - } - pub(crate) fn is_model_switch_developer_message(item: &ResponseItem) -> bool { let ResponseItem::Message { role, content, .. } = item else { return false; @@ -2014,7 +2006,7 @@ impl Session { } fn build_settings_update_items( &self, - previous_context: Option<&Arc>, + previous_context: Option<&TurnContextItem>, resumed_model: Option<&str>, current_context: &TurnContext, ) -> Vec { @@ -2025,7 +2017,7 @@ impl Session { let shell = self.user_shell(); let exec_policy = self.services.exec_policy.current(); crate::context_manager::updates::build_settings_update_items( - previous_context.map(Arc::as_ref), + previous_context, resumed_model, current_context, shell.as_ref(), @@ -2660,6 +2652,16 @@ impl Session { state.clone_history() } + pub(crate) async fn previous_context_item(&self) -> Option { + let state = self.state.lock().await; + state.previous_context_item() + } + + pub(crate) async fn set_previous_context_item(&self, item: Option) { + let mut state = self.state.lock().await; + state.set_previous_context_item(item); + } + pub(crate) async fn update_token_usage_info( &self, turn_context: &TurnContext, @@ -3123,7 +3125,9 @@ impl Session { async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiver) { // Seed with context in case there is an OverrideTurnContext first. - let mut previous_context: Option> = Some(sess.new_default_turn().await); + let initial_context = sess.new_default_turn().await; + sess.set_previous_context_item(Some(initial_context.to_turn_context_item())) + .await; // To break out of this loop, send Op::Shutdown. while let Ok(sub) = rx_sub.recv().await { @@ -3173,8 +3177,7 @@ async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiv .await; } Op::UserInput { .. } | Op::UserTurn { .. } => { - handlers::user_input_or_turn(&sess, sub.id.clone(), sub.op, &mut previous_context) - .await; + handlers::user_input_or_turn(&sess, sub.id.clone(), sub.op).await; } Op::ExecApproval { id: approval_id, @@ -3251,13 +3254,7 @@ async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiv handlers::set_thread_name(&sess, sub.id.clone(), name).await; } Op::RunUserShellCommand { command } => { - handlers::run_user_shell_command( - &sess, - sub.id.clone(), - command, - &mut previous_context, - ) - .await; + handlers::run_user_shell_command(&sess, sub.id.clone(), command).await; } Op::ResolveElicitation { server_name, @@ -3285,7 +3282,6 @@ mod handlers { use crate::codex::Session; use crate::codex::SessionSettingsUpdate; use crate::codex::SteerInputError; - use crate::codex::TurnContext; use crate::codex::spawn_review_thread; use crate::config::Config; @@ -3362,12 +3358,7 @@ mod handlers { } } - pub async fn user_input_or_turn( - sess: &Arc, - sub_id: String, - op: Op, - previous_context: &mut Option>, - ) { + pub async fn user_input_or_turn(sess: &Arc, sub_id: String, op: Op) { let (items, updates) = match op { Op::UserTurn { cwd, @@ -3430,8 +3421,9 @@ mod handlers { if let Err(SteerInputError::NoActiveTurn(items)) = sess.steer_input(items, None).await { sess.seed_initial_context_if_needed(¤t_context).await; let previous_model = sess.previous_model().await; + let previous_context_item = sess.previous_context_item().await; let update_items = sess.build_settings_update_items( - previous_context.as_ref(), + previous_context_item.as_ref(), previous_model.as_deref(), ¤t_context, ); @@ -3445,16 +3437,12 @@ mod handlers { let regular_task = sess.take_startup_regular_task().await.unwrap_or_default(); sess.spawn_task(Arc::clone(¤t_context), items, regular_task) .await; - *previous_context = Some(current_context); + sess.set_previous_context_item(Some(current_context.to_turn_context_item())) + .await; } } - pub async fn run_user_shell_command( - sess: &Arc, - sub_id: String, - command: String, - previous_context: &mut Option>, - ) { + pub async fn run_user_shell_command(sess: &Arc, sub_id: String, command: String) { if let Some((turn_context, cancellation_token)) = sess.active_turn_context_and_cancellation_token().await { @@ -3479,7 +3467,8 @@ mod handlers { UserShellCommandTask::new(command), ) .await; - *previous_context = Some(turn_context); + sess.set_previous_context_item(Some(turn_context.to_turn_context_item())) + .await; } pub async fn resolve_elicitation( @@ -5465,9 +5454,7 @@ async fn try_run_sampling_request( prompt: &Prompt, cancellation_token: CancellationToken, ) -> CodexResult { - let collaboration_mode = sess.current_collaboration_mode().await; - let rollout_item = - RolloutItem::TurnContext(turn_context.to_turn_context_item(collaboration_mode)); + let rollout_item = RolloutItem::TurnContext(turn_context.to_turn_context_item()); feedback_tags!( model = turn_context.model_info.slug.clone(), @@ -7738,8 +7725,12 @@ mod tests { .expect("rebuild config layer stack with network requirements"); current_context.config = Arc::new(config); - let update_items = - session.build_settings_update_items(Some(&previous_context), None, ¤t_context); + let previous_context_item = previous_context.to_turn_context_item(); + let update_items = session.build_settings_update_items( + Some(&previous_context_item), + None, + ¤t_context, + ); let environment_update = update_items .iter() diff --git a/codex-rs/core/src/compact.rs b/codex-rs/core/src/compact.rs index a40f1a0b8e..4065251425 100644 --- a/codex-rs/core/src/compact.rs +++ b/codex-rs/core/src/compact.rs @@ -118,13 +118,7 @@ async fn run_compact_task_inner( // Reuse one client session so turn-scoped state (sticky routing, websocket append tracking) // survives retries within this compact turn. - // TODO: If we need to guarantee the persisted mode always matches the prompt used for this - // turn, capture it in TurnContext at creation time. Using SessionConfiguration here avoids - // duplicating model settings on TurnContext, but an Op after turn start could update the - // session config before this write occurs. - let collaboration_mode = sess.current_collaboration_mode().await; - let rollout_item = - RolloutItem::TurnContext(turn_context.to_turn_context_item(collaboration_mode)); + let rollout_item = RolloutItem::TurnContext(turn_context.to_turn_context_item()); sess.persist_rollout_items(&[rollout_item]).await; loop { diff --git a/codex-rs/core/src/context_manager/history.rs b/codex-rs/core/src/context_manager/history.rs index b6b3ceae5a..0cd935523e 100644 --- a/codex-rs/core/src/context_manager/history.rs +++ b/codex-rs/core/src/context_manager/history.rs @@ -18,6 +18,7 @@ use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::InputModality; use codex_protocol::protocol::TokenUsage; use codex_protocol::protocol::TokenUsageInfo; +use codex_protocol::protocol::TurnContextItem; use std::ops::Deref; /// Transcript of thread history @@ -26,6 +27,12 @@ pub(crate) struct ContextManager { /// The oldest items are at the beginning of the vector. items: Vec, token_info: Option, + /// Previous turn context snapshot used for diffing context and producing + /// model-visible settings update items. + /// + /// When this is `None`, settings diffing treats the next turn as having no + /// baseline and emits a full reinjection of context state. + previous_context_item: Option, } #[derive(Debug, Clone, Copy, Default)] @@ -41,6 +48,7 @@ impl ContextManager { Self { items: Vec::new(), token_info: TokenUsageInfo::new_or_append(&None, &None, None), + previous_context_item: None, } } @@ -52,6 +60,14 @@ impl ContextManager { self.token_info = info; } + pub(crate) fn set_previous_context_item(&mut self, item: Option) { + self.previous_context_item = item; + } + + pub(crate) fn previous_context_item(&self) -> Option { + self.previous_context_item.clone() + } + pub(crate) fn set_token_usage_full(&mut self, context_window: i64) { match &mut self.token_info { Some(info) => info.fill_to_context_window(context_window), diff --git a/codex-rs/core/src/context_manager/updates.rs b/codex-rs/core/src/context_manager/updates.rs index 4a3f0c15e5..217889a724 100644 --- a/codex-rs/core/src/context_manager/updates.rs +++ b/codex-rs/core/src/context_manager/updates.rs @@ -6,26 +6,27 @@ use codex_protocol::config_types::Personality; use codex_protocol::models::DeveloperInstructions; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ModelInfo; +use codex_protocol::protocol::TurnContextItem; fn build_environment_update_item( - previous: Option<&TurnContext>, + previous: Option<&TurnContextItem>, next: &TurnContext, shell: &Shell, ) -> Option { let prev = previous?; - let prev_context = EnvironmentContext::from_turn_context(prev, shell); + let prev_context = EnvironmentContext::from_turn_context_item(prev, shell); let next_context = EnvironmentContext::from_turn_context(next, shell); if prev_context.equals_except_shell(&next_context) { return None; } - Some(ResponseItem::from(EnvironmentContext::diff( - prev, next, shell, - ))) + Some(ResponseItem::from( + EnvironmentContext::diff_from_turn_context_item(prev, next, shell), + )) } fn build_permissions_update_item( - previous: Option<&TurnContext>, + previous: Option<&TurnContextItem>, next: &TurnContext, exec_policy: &Policy, ) -> Option { @@ -46,11 +47,11 @@ fn build_permissions_update_item( } fn build_collaboration_mode_update_item( - previous: Option<&TurnContext>, + previous: Option<&TurnContextItem>, next: &TurnContext, ) -> Option { let prev = previous?; - if prev.collaboration_mode != next.collaboration_mode { + if prev.collaboration_mode.as_ref() != Some(&next.collaboration_mode) { // If the next mode has empty developer instructions, this returns None and we emit no // update, so prior collaboration instructions remain in the prompt history. Some(DeveloperInstructions::from_collaboration_mode(&next.collaboration_mode)?.into()) @@ -60,7 +61,7 @@ fn build_collaboration_mode_update_item( } fn build_personality_update_item( - previous: Option<&TurnContext>, + previous: Option<&TurnContextItem>, next: &TurnContext, personality_feature_enabled: bool, ) -> Option { @@ -68,7 +69,7 @@ fn build_personality_update_item( return None; } let previous = previous?; - if next.model_info.slug != previous.model_info.slug { + if next.model_info.slug != previous.model { return None; } @@ -96,12 +97,11 @@ pub(crate) fn personality_message_for( } pub(crate) fn build_model_instructions_update_item( - previous: Option<&TurnContext>, + previous: Option<&TurnContextItem>, resumed_model: Option<&str>, next: &TurnContext, ) -> Option { - let previous_model = - resumed_model.or_else(|| previous.map(|prev| prev.model_info.slug.as_str()))?; + let previous_model = resumed_model.or_else(|| previous.map(|prev| prev.model.as_str()))?; if previous_model == next.model_info.slug { return None; } @@ -115,7 +115,7 @@ pub(crate) fn build_model_instructions_update_item( } pub(crate) fn build_settings_update_items( - previous: Option<&TurnContext>, + previous: Option<&TurnContextItem>, resumed_model: Option<&str>, next: &TurnContext, shell: &Shell, diff --git a/codex-rs/core/src/environment_context.rs b/codex-rs/core/src/environment_context.rs index e6995b7a95..3c6df40adb 100644 --- a/codex-rs/core/src/environment_context.rs +++ b/codex-rs/core/src/environment_context.rs @@ -4,6 +4,8 @@ use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; use codex_protocol::protocol::ENVIRONMENT_CONTEXT_CLOSE_TAG; use codex_protocol::protocol::ENVIRONMENT_CONTEXT_OPEN_TAG; +use codex_protocol::protocol::TurnContextItem; +use codex_protocol::protocol::TurnContextNetworkItem; use serde::Deserialize; use serde::Serialize; use std::path::PathBuf; @@ -44,8 +46,12 @@ impl EnvironmentContext { self.cwd == *cwd && self.network == *network } - pub fn diff(before: &TurnContext, after: &TurnContext, shell: &Shell) -> Self { - let before_network = Self::network_from_turn_context(before); + pub fn diff_from_turn_context_item( + before: &TurnContextItem, + after: &TurnContext, + shell: &Shell, + ) -> Self { + let before_network = Self::network_from_turn_context_item(before); let after_network = Self::network_from_turn_context(after); let cwd = if before.cwd != after.cwd { Some(after.cwd.clone()) @@ -68,6 +74,14 @@ impl EnvironmentContext { ) } + pub fn from_turn_context_item(turn_context_item: &TurnContextItem, shell: &Shell) -> Self { + Self::new( + Some(turn_context_item.cwd.clone()), + shell.clone(), + Self::network_from_turn_context_item(turn_context_item), + ) + } + fn network_from_turn_context(turn_context: &TurnContext) -> Option { let network = turn_context .config @@ -81,6 +95,19 @@ impl EnvironmentContext { denied_domains: network.denied_domains.clone().unwrap_or_default(), }) } + + fn network_from_turn_context_item( + turn_context_item: &TurnContextItem, + ) -> Option { + let TurnContextNetworkItem { + allowed_domains, + denied_domains, + } = turn_context_item.network.as_ref()?; + Some(NetworkContext { + allowed_domains: allowed_domains.clone(), + denied_domains: denied_domains.clone(), + }) + } } impl EnvironmentContext { diff --git a/codex-rs/core/src/state/session.rs b/codex-rs/core/src/state/session.rs index c86f0cdfd2..76c365ab5b 100644 --- a/codex-rs/core/src/state/session.rs +++ b/codex-rs/core/src/state/session.rs @@ -11,6 +11,7 @@ use crate::protocol::TokenUsage; use crate::protocol::TokenUsageInfo; use crate::tasks::RegularTask; use crate::truncate::TruncationPolicy; +use codex_protocol::protocol::TurnContextItem; /// Persistent, session-scoped state previously stored directly on `Session`. pub(crate) struct SessionState { @@ -80,6 +81,14 @@ impl SessionState { self.history.set_token_info(info); } + pub(crate) fn set_previous_context_item(&mut self, item: Option) { + self.history.set_previous_context_item(item); + } + + pub(crate) fn previous_context_item(&self) -> Option { + self.history.previous_context_item() + } + // Token/rate limit helpers pub(crate) fn update_token_info_from_usage( &mut self, From 3a951f809651ddf876cf9b8ea565e55985942b98 Mon Sep 17 00:00:00 2001 From: Jack Mousseau Date: Thu, 19 Feb 2026 09:56:56 -0800 Subject: [PATCH 6/9] Restore phase when loading from history (#12244) --- .../schema/json/EventMsg.json | 22 +++++++++ .../schema/json/ServerNotification.json | 11 +++++ .../codex_app_server_protocol.schemas.json | 11 +++++ .../json/v1/ForkConversationResponse.json | 11 +++++ .../json/v1/ResumeConversationResponse.json | 11 +++++ .../v1/SessionConfiguredNotification.json | 11 +++++ .../schema/typescript/AgentMessageEvent.ts | 3 +- .../src/protocol/thread_history.rs | 46 +++++++++++++++++-- codex-rs/core/src/rollout/recorder.rs | 1 + .../src/event_processor_with_human_output.rs | 2 +- .../tests/event_processor_with_json_output.rs | 1 + codex-rs/protocol/src/items.rs | 3 +- codex-rs/protocol/src/protocol.rs | 3 ++ codex-rs/tui/src/chatwidget.rs | 4 +- codex-rs/tui/src/chatwidget/tests.rs | 13 +++++- 15 files changed, 144 insertions(+), 9 deletions(-) diff --git a/codex-rs/app-server-protocol/schema/json/EventMsg.json b/codex-rs/app-server-protocol/schema/json/EventMsg.json index f38c9b9944..5ca7c850f8 100644 --- a/codex-rs/app-server-protocol/schema/json/EventMsg.json +++ b/codex-rs/app-server-protocol/schema/json/EventMsg.json @@ -649,6 +649,17 @@ "message": { "type": "string" }, + "phase": { + "anyOf": [ + { + "$ref": "#/definitions/MessagePhase" + }, + { + "type": "null" + } + ], + "default": null + }, "type": { "enum": [ "agent_message" @@ -5596,6 +5607,17 @@ "message": { "type": "string" }, + "phase": { + "anyOf": [ + { + "$ref": "#/definitions/MessagePhase" + }, + { + "type": "null" + } + ], + "default": null + }, "type": { "enum": [ "agent_message" diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 5bd76ffee0..f3e71b70e8 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -1465,6 +1465,17 @@ "message": { "type": "string" }, + "phase": { + "anyOf": [ + { + "$ref": "#/definitions/MessagePhase2" + }, + { + "type": "null" + } + ], + "default": null + }, "type": { "enum": [ "agent_message" diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 741f50da18..06b0c773f8 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -2693,6 +2693,17 @@ "message": { "type": "string" }, + "phase": { + "anyOf": [ + { + "$ref": "#/definitions/v2/MessagePhase" + }, + { + "type": "null" + } + ], + "default": null + }, "type": { "enum": [ "agent_message" diff --git a/codex-rs/app-server-protocol/schema/json/v1/ForkConversationResponse.json b/codex-rs/app-server-protocol/schema/json/v1/ForkConversationResponse.json index f460c4a288..c7018d5b7a 100644 --- a/codex-rs/app-server-protocol/schema/json/v1/ForkConversationResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v1/ForkConversationResponse.json @@ -649,6 +649,17 @@ "message": { "type": "string" }, + "phase": { + "anyOf": [ + { + "$ref": "#/definitions/MessagePhase" + }, + { + "type": "null" + } + ], + "default": null + }, "type": { "enum": [ "agent_message" diff --git a/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationResponse.json b/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationResponse.json index a39f1fd8e2..2d7cc7e701 100644 --- a/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v1/ResumeConversationResponse.json @@ -649,6 +649,17 @@ "message": { "type": "string" }, + "phase": { + "anyOf": [ + { + "$ref": "#/definitions/MessagePhase" + }, + { + "type": "null" + } + ], + "default": null + }, "type": { "enum": [ "agent_message" diff --git a/codex-rs/app-server-protocol/schema/json/v1/SessionConfiguredNotification.json b/codex-rs/app-server-protocol/schema/json/v1/SessionConfiguredNotification.json index 20f4771e5e..efd614139d 100644 --- a/codex-rs/app-server-protocol/schema/json/v1/SessionConfiguredNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v1/SessionConfiguredNotification.json @@ -649,6 +649,17 @@ "message": { "type": "string" }, + "phase": { + "anyOf": [ + { + "$ref": "#/definitions/MessagePhase" + }, + { + "type": "null" + } + ], + "default": null + }, "type": { "enum": [ "agent_message" diff --git a/codex-rs/app-server-protocol/schema/typescript/AgentMessageEvent.ts b/codex-rs/app-server-protocol/schema/typescript/AgentMessageEvent.ts index ee436566e0..b32680055f 100644 --- a/codex-rs/app-server-protocol/schema/typescript/AgentMessageEvent.ts +++ b/codex-rs/app-server-protocol/schema/typescript/AgentMessageEvent.ts @@ -1,5 +1,6 @@ // GENERATED CODE! DO NOT MODIFY BY HAND! // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { MessagePhase } from "./MessagePhase"; -export type AgentMessageEvent = { message: string, }; +export type AgentMessageEvent = { message: string, phase: MessagePhase | null, }; diff --git a/codex-rs/app-server-protocol/src/protocol/thread_history.rs b/codex-rs/app-server-protocol/src/protocol/thread_history.rs index bb80010321..e5005077e5 100644 --- a/codex-rs/app-server-protocol/src/protocol/thread_history.rs +++ b/codex-rs/app-server-protocol/src/protocol/thread_history.rs @@ -16,6 +16,7 @@ use crate::protocol::v2::TurnError; use crate::protocol::v2::TurnStatus; use crate::protocol::v2::UserInput; use crate::protocol::v2::WebSearchAction; +use codex_protocol::models::MessagePhase as CoreMessagePhase; use codex_protocol::protocol::AgentReasoningEvent; use codex_protocol::protocol::AgentReasoningRawContentEvent; use codex_protocol::protocol::AgentStatus; @@ -81,7 +82,9 @@ impl ThreadHistoryBuilder { fn handle_event(&mut self, event: &EventMsg) { match event { EventMsg::UserMessage(payload) => self.handle_user_message(payload), - EventMsg::AgentMessage(payload) => self.handle_agent_message(payload.message.clone()), + EventMsg::AgentMessage(payload) => { + self.handle_agent_message(payload.message.clone(), payload.phase.clone()) + } EventMsg::AgentReasoning(payload) => self.handle_agent_reasoning(payload), EventMsg::AgentReasoningRawContent(payload) => { self.handle_agent_reasoning_raw_content(payload) @@ -143,7 +146,7 @@ impl ThreadHistoryBuilder { self.current_turn = Some(turn); } - fn handle_agent_message(&mut self, text: String) { + fn handle_agent_message(&mut self, text: String, phase: Option) { if text.is_empty() { return; } @@ -152,7 +155,7 @@ impl ThreadHistoryBuilder { self.ensure_turn().items.push(ThreadItem::AgentMessage { id, text, - phase: None, + phase: phase.map(Into::into), }); } @@ -758,6 +761,7 @@ impl From for Turn { mod tests { use super::*; use codex_protocol::ThreadId; + use codex_protocol::models::MessagePhase as CoreMessagePhase; use codex_protocol::models::WebSearchAction as CoreWebSearchAction; use codex_protocol::parse_command::ParsedCommand; use codex_protocol::protocol::AgentMessageEvent; @@ -792,6 +796,7 @@ mod tests { }), EventMsg::AgentMessage(AgentMessageEvent { message: "Hi there".into(), + phase: None, }), EventMsg::AgentReasoning(AgentReasoningEvent { text: "thinking".into(), @@ -807,6 +812,7 @@ mod tests { }), EventMsg::AgentMessage(AgentMessageEvent { message: "Reply two".into(), + phase: None, }), ]; @@ -877,6 +883,29 @@ mod tests { ); } + #[test] + fn preserves_agent_message_phase_in_history() { + let events = vec![EventMsg::AgentMessage(AgentMessageEvent { + message: "Final reply".into(), + phase: Some(CoreMessagePhase::FinalAnswer), + })]; + + let items = events + .into_iter() + .map(RolloutItem::EventMsg) + .collect::>(); + let turns = build_turns_from_rollout_items(&items); + assert_eq!(turns.len(), 1); + assert_eq!( + turns[0].items[0], + ThreadItem::AgentMessage { + id: "item-1".into(), + text: "Final reply".into(), + phase: Some(crate::protocol::v2::MessagePhase::FinalAnswer), + } + ); + } + #[test] fn splits_reasoning_when_interleaved() { let events = vec![ @@ -894,6 +923,7 @@ mod tests { }), EventMsg::AgentMessage(AgentMessageEvent { message: "interlude".into(), + phase: None, }), EventMsg::AgentReasoning(AgentReasoningEvent { text: "second summary".into(), @@ -938,6 +968,7 @@ mod tests { }), EventMsg::AgentMessage(AgentMessageEvent { message: "Working...".into(), + phase: None, }), EventMsg::TurnAborted(TurnAbortedEvent { turn_id: Some("turn-1".into()), @@ -951,6 +982,7 @@ mod tests { }), EventMsg::AgentMessage(AgentMessageEvent { message: "Second attempt complete.".into(), + phase: None, }), ]; @@ -1017,6 +1049,7 @@ mod tests { }), EventMsg::AgentMessage(AgentMessageEvent { message: "A1".into(), + phase: None, }), EventMsg::UserMessage(UserMessageEvent { message: "Second".into(), @@ -1026,6 +1059,7 @@ mod tests { }), EventMsg::AgentMessage(AgentMessageEvent { message: "A2".into(), + phase: None, }), EventMsg::ThreadRolledBack(ThreadRolledBackEvent { num_turns: 1 }), EventMsg::UserMessage(UserMessageEvent { @@ -1036,6 +1070,7 @@ mod tests { }), EventMsg::AgentMessage(AgentMessageEvent { message: "A3".into(), + phase: None, }), ]; @@ -1097,6 +1132,7 @@ mod tests { }), EventMsg::AgentMessage(AgentMessageEvent { message: "A1".into(), + phase: None, }), EventMsg::UserMessage(UserMessageEvent { message: "Two".into(), @@ -1106,6 +1142,7 @@ mod tests { }), EventMsg::AgentMessage(AgentMessageEvent { message: "A2".into(), + phase: None, }), EventMsg::ThreadRolledBack(ThreadRolledBackEvent { num_turns: 99 }), ]; @@ -1469,6 +1506,7 @@ mod tests { }), EventMsg::AgentMessage(AgentMessageEvent { message: "still in b".into(), + phase: None, }), EventMsg::TurnComplete(TurnCompleteEvent { turn_id: "turn-b".into(), @@ -1522,6 +1560,7 @@ mod tests { }), EventMsg::AgentMessage(AgentMessageEvent { message: "still in b".into(), + phase: None, }), ]; @@ -1626,6 +1665,7 @@ mod tests { }), EventMsg::AgentMessage(AgentMessageEvent { message: "done".into(), + phase: None, }), EventMsg::Error(ErrorEvent { message: "rollback failed".into(), diff --git a/codex-rs/core/src/rollout/recorder.rs b/codex-rs/core/src/rollout/recorder.rs index d0df0828a5..eab442743e 100644 --- a/codex-rs/core/src/rollout/recorder.rs +++ b/codex-rs/core/src/rollout/recorder.rs @@ -1073,6 +1073,7 @@ mod tests { .record_items(&[RolloutItem::EventMsg(EventMsg::AgentMessage( AgentMessageEvent { message: "buffered-event".to_string(), + phase: None, }, ))]) .await?; diff --git a/codex-rs/exec/src/event_processor_with_human_output.rs b/codex-rs/exec/src/event_processor_with_human_output.rs index 26861af7c8..f77a4ec16a 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -299,7 +299,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { ); } } - EventMsg::AgentMessage(AgentMessageEvent { message }) => { + EventMsg::AgentMessage(AgentMessageEvent { message, .. }) => { ts_msg!( self, "{}\n{}", diff --git a/codex-rs/exec/tests/event_processor_with_json_output.rs b/codex-rs/exec/tests/event_processor_with_json_output.rs index 46cd615457..35cb962ee7 100644 --- a/codex-rs/exec/tests/event_processor_with_json_output.rs +++ b/codex-rs/exec/tests/event_processor_with_json_output.rs @@ -738,6 +738,7 @@ fn agent_message_produces_item_completed_agent_message() { "e1", EventMsg::AgentMessage(AgentMessageEvent { message: "hello".to_string(), + phase: None, }), ); let out = ep.collect_thread_events(&ev); diff --git a/codex-rs/protocol/src/items.rs b/codex-rs/protocol/src/items.rs index 35bed2ab47..9284bbddf4 100644 --- a/codex-rs/protocol/src/items.rs +++ b/codex-rs/protocol/src/items.rs @@ -190,13 +190,12 @@ impl AgentMessageItem { } pub fn as_legacy_events(&self) -> Vec { - // Legacy events only preserve visible assistant text; `phase` has no - // representation in the v1 event stream. self.content .iter() .map(|c| match c { AgentMessageContent::Text { text } => EventMsg::AgentMessage(AgentMessageEvent { message: text.clone(), + phase: self.phase.clone(), }), }) .collect() diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 5676dc3e2d..b7e4b547fd 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -32,6 +32,7 @@ use crate::mcp::Tool as McpTool; use crate::message_history::HistoryEntry; use crate::models::BaseInstructions; use crate::models::ContentItem; +use crate::models::MessagePhase; use crate::models::ResponseItem; use crate::models::WebSearchAction; use crate::num_format::format_with_separators; @@ -1580,6 +1581,8 @@ impl fmt::Display for FinalOutput { #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct AgentMessageEvent { pub message: String, + #[serde(default)] + pub phase: Option, } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 6d112f5ad4..9e746b4c57 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -3986,7 +3986,9 @@ impl ChatWidget { match msg { EventMsg::SessionConfigured(e) => self.on_session_configured(e), EventMsg::ThreadNameUpdated(e) => self.on_thread_name_updated(e), - EventMsg::AgentMessage(AgentMessageEvent { message }) => self.on_agent_message(message), + EventMsg::AgentMessage(AgentMessageEvent { message, .. }) => { + self.on_agent_message(message) + } EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { delta }) => { self.on_agent_message_delta(delta) } diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 99cb96407a..15f1057cf8 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -169,6 +169,7 @@ async fn resumed_initial_messages_render_history() { }), EventMsg::AgentMessage(AgentMessageEvent { message: "assistant reply".to_string(), + phase: None, }), ]), network_proxy: None, @@ -3322,6 +3323,7 @@ async fn unified_exec_wait_after_final_agent_message_snapshot() { id: "turn-1".into(), msg: EventMsg::AgentMessage(AgentMessageEvent { message: "Final response.".into(), + phase: None, }), }); chat.handle_codex_event(Event { @@ -7013,6 +7015,7 @@ async fn multiple_agent_messages_in_single_turn_emit_multiple_headers() { id: "s1".into(), msg: EventMsg::AgentMessage(AgentMessageEvent { message: "First message".into(), + phase: None, }), }); @@ -7021,6 +7024,7 @@ async fn multiple_agent_messages_in_single_turn_emit_multiple_headers() { id: "s1".into(), msg: EventMsg::AgentMessage(AgentMessageEvent { message: "Second message".into(), + phase: None, }), }); @@ -7066,6 +7070,7 @@ async fn final_reasoning_then_message_without_deltas_are_rendered() { id: "s1".into(), msg: EventMsg::AgentMessage(AgentMessageEvent { message: "Here is the result.".into(), + phase: None, }), }); @@ -7126,6 +7131,7 @@ async fn deltas_then_same_final_message_are_rendered_snapshot() { id: "s1".into(), msg: EventMsg::AgentMessage(AgentMessageEvent { message: "Here is the result.".into(), + phase: None, }), }); @@ -7147,7 +7153,12 @@ async fn chatwidget_exec_and_status_layout_vt100_snapshot() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await; chat.handle_codex_event(Event { id: "t1".into(), - msg: EventMsg::AgentMessage(AgentMessageEvent { message: "I’m going to search the repo for where “Change Approved” is rendered to update that view.".into() }), + msg: EventMsg::AgentMessage(AgentMessageEvent { + message: + "I’m going to search the repo for where “Change Approved” is rendered to update that view." + .into(), + phase: None, + }), }); let command = vec!["bash".into(), "-lc".into(), "rg \"Change Approved\"".into()]; From d54999d0069714cf1192e9c5c1eb7d667d24b4b3 Mon Sep 17 00:00:00 2001 From: sayan-oai Date: Thu, 19 Feb 2026 10:38:57 -0800 Subject: [PATCH 7/9] client side modelinfo overrides (#12101) TL;DR Add top-level `model_catalog_json` config support so users can supply a local model catalog override from a JSON file path (including adding new models) without backend changes. ### Problem Codex previously had no clean client-side way to replace/overlay model catalog data for local testing of model metadata and new model entries. ### Fix - Add top-level `model_catalog_json` config field (JSON file path). - Apply catalog entries when resolving `ModelInfo`: 1. Base resolved model metadata (remote/fallback) 2. Catalog overlay from `model_catalog_json` 3. Existing global top-level overrides (`model_context_window`, `model_supports_reasoning_summaries`, etc.) ### Note Will revisit per-field overrides in a follow-up ### Tests Added tests --- codex-rs/app-server/src/message_processor.rs | 1 + codex-rs/core/config.schema.json | 8 ++ codex-rs/core/src/codex.rs | 3 + codex-rs/core/src/config/mod.rs | 63 ++++++++++ codex-rs/core/src/models_manager/manager.rs | 108 ++++++++++++++---- codex-rs/core/src/thread_manager.rs | 8 +- codex-rs/core/tests/suite/client.rs | 1 + .../core/tests/suite/model_info_overrides.rs | 4 +- codex-rs/exec/src/lib.rs | 1 + codex-rs/mcp-server/src/message_processor.rs | 1 + codex-rs/protocol/Cargo.toml | 6 +- codex-rs/tui/src/app.rs | 1 + codex-rs/tui/src/chatwidget/tests.rs | 3 +- 13 files changed, 178 insertions(+), 30 deletions(-) diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index cb645ff3f8..f1c6029a21 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -173,6 +173,7 @@ impl MessageProcessor { config.codex_home.clone(), auth_manager.clone(), SessionSource::VSCode, + config.model_catalog.clone(), )); let cloud_requirements = Arc::new(RwLock::new(cloud_requirements)); let codex_message_processor = CodexMessageProcessor::new(CodexMessageProcessorArgs { diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 5408d37d73..aef21f5d45 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1594,6 +1594,14 @@ "format": "int64", "type": "integer" }, + "model_catalog_json": { + "allOf": [ + { + "$ref": "#/definitions/AbsolutePathBuf" + } + ], + "description": "Optional path to a JSON file containing a complete model catalog. When set, this replaces the bundled catalog for this process." + }, "model_context_window": { "description": "Size of the context window for the model, in tokens.", "format": "int64", diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 0e1e49ba78..d67318d12e 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -7231,6 +7231,7 @@ mod tests { let models_manager = Arc::new(ModelsManager::new( config.codex_home.clone(), auth_manager.clone(), + None, )); let model = ModelsManager::get_model_offline_for_tests(config.model.as_deref()); let model_info = @@ -7305,6 +7306,7 @@ mod tests { let models_manager = Arc::new(ModelsManager::new( config.codex_home.clone(), auth_manager.clone(), + None, )); let agent_control = AgentControl::default(); let exec_policy = ExecPolicyManager::default(); @@ -7456,6 +7458,7 @@ mod tests { let models_manager = Arc::new(ModelsManager::new( config.codex_home.clone(), auth_manager.clone(), + None, )); let agent_control = AgentControl::default(); let exec_policy = ExecPolicyManager::default(); diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index ec4e378948..0d4ee60f00 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -66,6 +66,7 @@ use codex_protocol::config_types::TrustLevel; use codex_protocol::config_types::Verbosity; use codex_protocol::config_types::WebSearchMode; use codex_protocol::config_types::WindowsSandboxLevel; +use codex_protocol::openai_models::ModelsResponse; use codex_protocol::openai_models::ReasoningEffort; use codex_rmcp_client::OAuthCredentialsStoreMode; use codex_utils_absolute_path::AbsolutePathBuf; @@ -359,6 +360,10 @@ pub struct Config { /// Optional override to force-enable reasoning summaries for the configured model. pub model_supports_reasoning_summaries: Option, + /// Optional full model catalog loaded from `model_catalog_json`. + /// When set, this replaces the bundled catalog for the current process. + pub model_catalog: Option, + /// Optional verbosity control for GPT-5 models (Responses API `text.verbosity`). pub model_verbosity: Option, @@ -618,6 +623,27 @@ pub(crate) fn deserialize_config_toml_with_base( .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e)) } +fn load_catalog_json(path: &AbsolutePathBuf) -> std::io::Result { + let file_contents = std::fs::read_to_string(path)?; + serde_json::from_str::(&file_contents).map_err(|err| { + std::io::Error::new( + ErrorKind::InvalidData, + format!( + "failed to parse model_catalog_json path `{}` as JSON: {err}", + path.display() + ), + ) + }) +} + +fn load_model_catalog( + model_catalog_json: Option, +) -> std::io::Result> { + model_catalog_json + .map(|path| load_catalog_json(&path)) + .transpose() +} + fn filter_mcp_servers_by_requirements( mcp_servers: &mut HashMap, mcp_requirements: Option<&Sourced>>, @@ -1039,6 +1065,10 @@ pub struct ConfigToml { /// Override to force-enable reasoning summaries for the configured model. pub model_supports_reasoning_summaries: Option, + /// Optional path to a JSON file containing a complete model catalog. + /// When set, this replaces the bundled catalog for this process. + pub model_catalog_json: Option, + /// Optionally specify a personality for the model pub personality: Option, @@ -1793,6 +1823,7 @@ impl Config { let review_model = override_review_model.or(cfg.review_model); let check_for_update_on_startup = cfg.check_for_update_on_startup.unwrap_or(true); + let model_catalog = load_model_catalog(cfg.model_catalog_json.clone())?; let log_dir = cfg .log_dir @@ -1929,6 +1960,7 @@ impl Config { .or(cfg.model_reasoning_summary) .unwrap_or_default(), model_supports_reasoning_summaries: cfg.model_supports_reasoning_summaries, + model_catalog, model_verbosity: config_profile.model_verbosity.or(cfg.model_verbosity), chatgpt_base_url: config_profile .chatgpt_base_url @@ -4177,6 +4209,33 @@ config_file = "./agents/researcher.toml" Ok(()) } + #[test] + fn model_catalog_json_loads_from_path() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + let catalog_path = codex_home.path().join("catalog.json"); + let mut catalog: ModelsResponse = + serde_json::from_str(include_str!("../../models.json")).expect("valid models.json"); + catalog.models = catalog.models.into_iter().take(1).collect(); + std::fs::write( + &catalog_path, + serde_json::to_string(&catalog).expect("serialize catalog"), + )?; + + let cfg = ConfigToml { + model_catalog_json: Some(AbsolutePathBuf::from_absolute_path(catalog_path)?), + ..Default::default() + }; + + let config = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + codex_home.path().to_path_buf(), + )?; + + assert_eq!(config.model_catalog, Some(catalog)); + Ok(()) + } + fn create_test_fixture() -> std::io::Result { let toml = r#" model = "o3" @@ -4349,6 +4408,7 @@ model_verbosity = "high" model_reasoning_effort: Some(ReasoningEffort::High), model_reasoning_summary: ReasoningSummary::Detailed, model_supports_reasoning_summaries: None, + model_catalog: None, model_verbosity: None, personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), @@ -4464,6 +4524,7 @@ model_verbosity = "high" model_reasoning_effort: None, model_reasoning_summary: ReasoningSummary::default(), model_supports_reasoning_summaries: None, + model_catalog: None, model_verbosity: None, personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), @@ -4577,6 +4638,7 @@ model_verbosity = "high" model_reasoning_effort: None, model_reasoning_summary: ReasoningSummary::default(), model_supports_reasoning_summaries: None, + model_catalog: None, model_verbosity: None, personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), @@ -4676,6 +4738,7 @@ model_verbosity = "high" model_reasoning_effort: Some(ReasoningEffort::High), model_reasoning_summary: ReasoningSummary::Detailed, model_supports_reasoning_summaries: None, + model_catalog: None, model_verbosity: Some(Verbosity::High), personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), diff --git a/codex-rs/core/src/models_manager/manager.rs b/codex-rs/core/src/models_manager/manager.rs index 457351995f..080532714e 100644 --- a/codex-rs/core/src/models_manager/manager.rs +++ b/codex-rs/core/src/models_manager/manager.rs @@ -47,6 +47,7 @@ pub enum RefreshStrategy { pub struct ModelsManager { local_models: Vec, remote_models: RwLock>, + has_custom_model_catalog: bool, auth_manager: Arc, etag: RwLock>, cache_manager: ModelsCacheManager, @@ -57,12 +58,23 @@ impl ModelsManager { /// Construct a manager scoped to the provided `AuthManager`. /// /// Uses `codex_home` to store cached model metadata and initializes with built-in presets. - pub fn new(codex_home: PathBuf, auth_manager: Arc) -> Self { + /// When `model_catalog` is provided, it becomes the authoritative remote model list and + /// background refreshes from `/models` are disabled. + pub fn new( + codex_home: PathBuf, + auth_manager: Arc, + model_catalog: Option, + ) -> Self { let cache_path = codex_home.join(MODEL_CACHE_FILE); let cache_manager = ModelsCacheManager::new(cache_path, DEFAULT_MODEL_CACHE_TTL); + let has_custom_model_catalog = model_catalog.is_some(); + let remote_models = model_catalog + .map(|catalog| catalog.models) + .unwrap_or_else(|| Self::load_remote_models_from_file().unwrap_or_default()); Self { local_models: builtin_model_presets(auth_manager.auth_mode()), - remote_models: RwLock::new(Self::load_remote_models_from_file().unwrap_or_default()), + remote_models: RwLock::new(remote_models), + has_custom_model_catalog, auth_manager, etag: RwLock::new(None), cache_manager, @@ -125,7 +137,34 @@ impl ModelsManager { // todo(aibrahim): look if we can tighten it to pub(crate) /// Look up model metadata, applying remote overrides and config adjustments. pub async fn get_model_info(&self, model: &str, config: &Config) -> ModelInfo { - let remote = self.find_remote_model_by_longest_prefix(model).await; + let remote_models = self.get_remote_models().await; + Self::construct_model_info_from_candidates(model, &remote_models, config) + } + + fn find_model_by_longest_prefix(model: &str, candidates: &[ModelInfo]) -> Option { + let mut best: Option = None; + for candidate in candidates { + if !model.starts_with(&candidate.slug) { + continue; + } + let is_better_match = if let Some(current) = best.as_ref() { + candidate.slug.len() > current.slug.len() + } else { + true + }; + if is_better_match { + best = Some(candidate.clone()); + } + } + best + } + + fn construct_model_info_from_candidates( + model: &str, + candidates: &[ModelInfo], + config: &Config, + ) -> ModelInfo { + let remote = Self::find_model_by_longest_prefix(model, candidates); let model_info = if let Some(remote) = remote { ModelInfo { slug: model.to_string(), @@ -138,24 +177,6 @@ impl ModelsManager { model_info::with_config_overrides(model_info, config) } - async fn find_remote_model_by_longest_prefix(&self, model: &str) -> Option { - let mut best: Option = None; - for candidate in self.get_remote_models().await { - if !model.starts_with(&candidate.slug) { - continue; - } - let is_better_match = if let Some(current) = best.as_ref() { - candidate.slug.len() > current.slug.len() - } else { - true - }; - if is_better_match { - best = Some(candidate); - } - } - best - } - /// Refresh models if the provided ETag differs from the cached ETag. /// /// Uses `Online` strategy to fetch latest models when ETags differ. @@ -174,6 +195,11 @@ impl ModelsManager { /// Refresh available models according to the specified strategy. async fn refresh_available_models(&self, refresh_strategy: RefreshStrategy) -> CoreResult<()> { + // don't override the custom model catalog if one was provided by the user + if self.has_custom_model_catalog { + return Ok(()); + } + if self.auth_manager.auth_mode() != Some(AuthMode::Chatgpt) { if matches!( refresh_strategy, @@ -327,6 +353,7 @@ impl ModelsManager { Self { local_models: builtin_model_presets(auth_manager.auth_mode()), remote_models: RwLock::new(Self::load_remote_models_from_file().unwrap_or_default()), + has_custom_model_catalog: false, auth_manager, etag: RwLock::new(None), cache_manager, @@ -353,7 +380,12 @@ impl ModelsManager { model: &str, config: &Config, ) -> ModelInfo { - model_info::with_config_overrides(model_info::model_info_from_slug(model), config) + let candidates: &[ModelInfo] = if let Some(model_catalog) = config.model_catalog.as_ref() { + &model_catalog.models + } else { + &[] + }; + Self::construct_model_info_from_candidates(model, candidates, config) } } @@ -446,7 +478,7 @@ mod tests { .expect("load default test config"); let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key")); - let manager = ModelsManager::new(codex_home.path().to_path_buf(), auth_manager); + let manager = ModelsManager::new(codex_home.path().to_path_buf(), auth_manager, None); let known_slug = manager .get_remote_models() .await @@ -466,6 +498,36 @@ mod tests { assert_eq!(unknown.slug, "model-that-does-not-exist"); } + #[tokio::test] + async fn get_model_info_uses_custom_catalog() { + let codex_home = tempdir().expect("temp dir"); + let config = ConfigBuilder::default() + .codex_home(codex_home.path().to_path_buf()) + .build() + .await + .expect("load default test config"); + + let auth_manager = + AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key")); + let manager = ModelsManager::new( + codex_home.path().to_path_buf(), + auth_manager, + Some(ModelsResponse { + models: vec![remote_model("gpt-overlay", "Overlay", 0)], + }), + ); + + let model_info = manager + .get_model_info("gpt-overlay-experiment", &config) + .await; + + assert_eq!(model_info.slug, "gpt-overlay-experiment"); + assert_eq!(model_info.display_name, "Overlay"); + assert_eq!(model_info.context_window, Some(272_000)); + assert!(!model_info.supports_parallel_tool_calls); + assert!(!model_info.used_fallback_model_metadata); + } + #[tokio::test] async fn refresh_available_models_sorts_by_priority() { let server = MockServer::start().await; diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index 28cb8e4785..cb7c464362 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -21,6 +21,7 @@ use crate::skills::SkillsManager; use codex_protocol::ThreadId; use codex_protocol::config_types::CollaborationModeMask; use codex_protocol::openai_models::ModelPreset; +use codex_protocol::openai_models::ModelsResponse; use codex_protocol::protocol::InitialHistory; use codex_protocol::protocol::McpServerRefreshConfig; use codex_protocol::protocol::Op; @@ -141,6 +142,7 @@ impl ThreadManager { codex_home: PathBuf, auth_manager: Arc, session_source: SessionSource, + model_catalog: Option, ) -> Self { let (thread_created_tx, _) = broadcast::channel(THREAD_CREATED_CHANNEL_CAPACITY); let skills_manager = Arc::new(SkillsManager::new(codex_home.clone())); @@ -149,7 +151,11 @@ impl ThreadManager { state: Arc::new(ThreadManagerState { threads: Arc::new(RwLock::new(HashMap::new())), thread_created_tx, - models_manager: Arc::new(ModelsManager::new(codex_home, auth_manager.clone())), + models_manager: Arc::new(ModelsManager::new( + codex_home, + auth_manager.clone(), + model_catalog, + )), skills_manager, file_watcher, auth_manager, diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index bbdbc73233..cc5fee3066 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -582,6 +582,7 @@ async fn prefers_apikey_when_config_prefers_apikey_even_with_chatgpt_tokens() { codex_home.path().to_path_buf(), auth_manager, SessionSource::Exec, + config.model_catalog.clone(), ); let NewThread { thread: codex, .. } = thread_manager .start_thread(config) diff --git a/codex-rs/core/tests/suite/model_info_overrides.rs b/codex-rs/core/tests/suite/model_info_overrides.rs index 2b085a004f..7a92e99f1e 100644 --- a/codex-rs/core/tests/suite/model_info_overrides.rs +++ b/codex-rs/core/tests/suite/model_info_overrides.rs @@ -12,7 +12,7 @@ async fn offline_model_info_without_tool_output_override() { let auth_manager = codex_core::test_support::auth_manager_from_auth( CodexAuth::create_dummy_chatgpt_auth_for_testing(), ); - let manager = ModelsManager::new(config.codex_home.clone(), auth_manager); + let manager = ModelsManager::new(config.codex_home.clone(), auth_manager, None); let model_info = manager.get_model_info("gpt-5.1", &config).await; @@ -30,7 +30,7 @@ async fn offline_model_info_with_tool_output_override() { let auth_manager = codex_core::test_support::auth_manager_from_auth( CodexAuth::create_dummy_chatgpt_auth_for_testing(), ); - let manager = ModelsManager::new(config.codex_home.clone(), auth_manager); + let manager = ModelsManager::new(config.codex_home.clone(), auth_manager, None); let model_info = manager.get_model_info("gpt-5.1-codex", &config).await; diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index c4964cc803..70ddb70f13 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -373,6 +373,7 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any config.codex_home.clone(), auth_manager.clone(), SessionSource::Exec, + config.model_catalog.clone(), )); let default_model = thread_manager .get_models_manager() diff --git a/codex-rs/mcp-server/src/message_processor.rs b/codex-rs/mcp-server/src/message_processor.rs index 612582dae4..3b18f2fd43 100644 --- a/codex-rs/mcp-server/src/message_processor.rs +++ b/codex-rs/mcp-server/src/message_processor.rs @@ -61,6 +61,7 @@ impl MessageProcessor { config.codex_home.clone(), auth_manager, SessionSource::Mcp, + config.model_catalog.clone(), )); Self { outgoing, diff --git a/codex-rs/protocol/Cargo.toml b/codex-rs/protocol/Cargo.toml index b58393936b..02db92d095 100644 --- a/codex-rs/protocol/Cargo.toml +++ b/codex-rs/protocol/Cargo.toml @@ -1,8 +1,8 @@ [package] -name = "codex-protocol" -version.workspace = true edition.workspace = true license.workspace = true +name = "codex-protocol" +version.workspace = true [lib] name = "codex_protocol" @@ -12,8 +12,8 @@ path = "src/lib.rs" workspace = true [dependencies] -codex-git = { workspace = true } codex-execpolicy = { workspace = true } +codex-git = { workspace = true } codex-utils-absolute-path = { workspace = true } codex-utils-image = { workspace = true } icu_decimal = { workspace = true } diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 323769dab3..a46a927fbc 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -1026,6 +1026,7 @@ impl App { config.codex_home.clone(), auth_manager.clone(), SessionSource::Cli, + config.model_catalog.clone(), )); let mut model = thread_manager .get_models_manager() diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 15f1057cf8..829c39d0a0 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -1580,7 +1580,7 @@ async fn make_chatwidget_manual( let auth_manager = codex_core::test_support::auth_manager_from_auth(CodexAuth::from_api_key("test")); let codex_home = cfg.codex_home.clone(); - let models_manager = Arc::new(ModelsManager::new(codex_home, auth_manager.clone())); + let models_manager = Arc::new(ModelsManager::new(codex_home, auth_manager.clone(), None)); let reasoning_effort = None; let base_mode = CollaborationMode { mode: ModeKind::Default, @@ -1699,6 +1699,7 @@ fn set_chatgpt_auth(chat: &mut ChatWidget) { chat.models_manager = Arc::new(ModelsManager::new( chat.config.codex_home.clone(), chat.auth_manager.clone(), + None, )); } From d87cf7794c0cbff93310021ab3a159ae87b0eca7 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 19 Feb 2026 18:40:41 +0000 Subject: [PATCH 8/9] Add configurable agent spawn depth (#12251) Summary - expose `agents.max_depth` in config schema and toml parsing, with defaults and validation - thread-spawn depth guards and multi-agent handler now respect the configured limit instead of a hardcoded value - ensure documentation and helpers account for agent depth limits --- codex-rs/core/config.schema.json | 6 ++ codex-rs/core/src/agent/guards.rs | 11 ++-- codex-rs/core/src/agent/mod.rs | 1 - codex-rs/core/src/codex.rs | 3 +- codex-rs/core/src/config/mod.rs | 26 +++++++++ .../core/src/tools/handlers/multi_agents.rs | 55 +++++++++++++++++-- 6 files changed, 86 insertions(+), 16 deletions(-) diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index aef21f5d45..af2ba45656 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -29,6 +29,12 @@ "$ref": "#/definitions/AgentRoleToml" }, "properties": { + "max_depth": { + "description": "Maximum nesting depth allowed for spawned agent threads. Root sessions start at depth 0.", + "format": "int32", + "minimum": 1.0, + "type": "integer" + }, "max_threads": { "description": "Maximum number of agent threads that can be open concurrently. When unset, no limit is enforced.", "format": "uint", diff --git a/codex-rs/core/src/agent/guards.rs b/codex-rs/core/src/agent/guards.rs index 2f146f2f80..1964169cd7 100644 --- a/codex-rs/core/src/agent/guards.rs +++ b/codex-rs/core/src/agent/guards.rs @@ -21,9 +21,6 @@ pub(crate) struct Guards { total_count: AtomicUsize, } -/// Initial agent is depth 0. -pub(crate) const MAX_THREAD_SPAWN_DEPTH: i32 = 1; - fn session_depth(session_source: &SessionSource) -> i32 { match session_source { SessionSource::SubAgent(SubAgentSource::ThreadSpawn { depth, .. }) => *depth, @@ -36,8 +33,8 @@ pub(crate) fn next_thread_spawn_depth(session_source: &SessionSource) -> i32 { session_depth(session_source).saturating_add(1) } -pub(crate) fn exceeds_thread_spawn_depth_limit(depth: i32) -> bool { - depth > MAX_THREAD_SPAWN_DEPTH +pub(crate) fn exceeds_thread_spawn_depth_limit(depth: i32, max_depth: i32) -> bool { + depth > max_depth } impl Guards { @@ -136,7 +133,7 @@ mod tests { }); let child_depth = next_thread_spawn_depth(&session_source); assert_eq!(child_depth, 2); - assert!(exceeds_thread_spawn_depth_limit(child_depth)); + assert!(exceeds_thread_spawn_depth_limit(child_depth, 1)); } #[test] @@ -144,7 +141,7 @@ mod tests { let session_source = SessionSource::SubAgent(SubAgentSource::Review); assert_eq!(session_depth(&session_source), 0); assert_eq!(next_thread_spawn_depth(&session_source), 1); - assert!(!exceeds_thread_spawn_depth_limit(1)); + assert!(!exceeds_thread_spawn_depth_limit(1, 1)); } #[test] diff --git a/codex-rs/core/src/agent/mod.rs b/codex-rs/core/src/agent/mod.rs index d9a8361848..15be909c3d 100644 --- a/codex-rs/core/src/agent/mod.rs +++ b/codex-rs/core/src/agent/mod.rs @@ -5,7 +5,6 @@ pub(crate) mod status; pub(crate) use codex_protocol::protocol::AgentStatus; pub(crate) use control::AgentControl; -pub(crate) use guards::MAX_THREAD_SPAWN_DEPTH; pub(crate) use guards::exceeds_thread_spawn_depth_limit; pub(crate) use guards::next_thread_spawn_depth; pub(crate) use status::agent_status_from_event; diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index d67318d12e..0ff60c4647 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -11,7 +11,6 @@ use crate::CodexAuth; use crate::SandboxState; use crate::agent::AgentControl; use crate::agent::AgentStatus; -use crate::agent::MAX_THREAD_SPAWN_DEPTH; use crate::agent::agent_status_from_event; use crate::analytics_client::AnalyticsEventsClient; use crate::analytics_client::AppInvocation; @@ -315,7 +314,7 @@ impl Codex { } if let SessionSource::SubAgent(SubAgentSource::ThreadSpawn { depth, .. }) = session_source - && depth >= MAX_THREAD_SPAWN_DEPTH + && depth >= config.agent_max_depth { config.features.disable(Feature::Collab); } diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 0d4ee60f00..f11026ede0 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -111,6 +111,7 @@ pub use codex_git::GhostSnapshotConfig; /// the context window. pub(crate) const PROJECT_DOC_MAX_BYTES: usize = 32 * 1024; // 32 KiB pub(crate) const DEFAULT_AGENT_MAX_THREADS: Option = Some(6); +pub(crate) const DEFAULT_AGENT_MAX_DEPTH: i32 = 1; pub const CONFIG_TOML_FILE: &str = "config.toml"; @@ -309,6 +310,9 @@ pub struct Config { /// Maximum number of agent threads that can be open concurrently. pub agent_max_threads: Option, + /// Maximum nesting depth allowed for spawned agent threads. + pub agent_max_depth: i32, + /// User-defined role declarations keyed by role name. pub agent_roles: BTreeMap, @@ -1217,6 +1221,11 @@ pub struct AgentsToml { #[schemars(range(min = 1))] pub max_threads: Option, + /// Maximum nesting depth allowed for spawned agent threads. + /// Root sessions start at depth 0. + #[schemars(range(min = 1))] + pub max_depth: Option, + /// User-defined role declarations keyed by role name. /// /// Example: @@ -1692,6 +1701,17 @@ impl Config { "agents.max_threads must be at least 1", )); } + let agent_max_depth = cfg + .agents + .as_ref() + .and_then(|agents| agents.max_depth) + .unwrap_or(DEFAULT_AGENT_MAX_DEPTH); + if agent_max_depth < 1 { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "agents.max_depth must be at least 1", + )); + } let agent_roles = cfg .agents .as_ref() @@ -1934,6 +1954,7 @@ impl Config { .collect(), tool_output_token_limit: cfg.tool_output_token_limit, agent_max_threads, + agent_max_depth, agent_roles, memories: cfg.memories.unwrap_or_default().into(), codex_home, @@ -4148,6 +4169,7 @@ model = "gpt-5.1-codex" let cfg = ConfigToml { agents: Some(AgentsToml { max_threads: None, + max_depth: None, roles: BTreeMap::from([( "researcher".to_string(), AgentRoleToml { @@ -4390,6 +4412,7 @@ model_verbosity = "high" project_doc_fallback_filenames: Vec::new(), tool_output_token_limit: None, agent_max_threads: DEFAULT_AGENT_MAX_THREADS, + agent_max_depth: DEFAULT_AGENT_MAX_DEPTH, agent_roles: BTreeMap::new(), memories: MemoriesConfig::default(), codex_home: fixture.codex_home(), @@ -4506,6 +4529,7 @@ model_verbosity = "high" project_doc_fallback_filenames: Vec::new(), tool_output_token_limit: None, agent_max_threads: DEFAULT_AGENT_MAX_THREADS, + agent_max_depth: DEFAULT_AGENT_MAX_DEPTH, agent_roles: BTreeMap::new(), memories: MemoriesConfig::default(), codex_home: fixture.codex_home(), @@ -4620,6 +4644,7 @@ model_verbosity = "high" project_doc_fallback_filenames: Vec::new(), tool_output_token_limit: None, agent_max_threads: DEFAULT_AGENT_MAX_THREADS, + agent_max_depth: DEFAULT_AGENT_MAX_DEPTH, agent_roles: BTreeMap::new(), memories: MemoriesConfig::default(), codex_home: fixture.codex_home(), @@ -4720,6 +4745,7 @@ model_verbosity = "high" project_doc_fallback_filenames: Vec::new(), tool_output_token_limit: None, agent_max_threads: DEFAULT_AGENT_MAX_THREADS, + agent_max_depth: DEFAULT_AGENT_MAX_DEPTH, agent_roles: BTreeMap::new(), memories: MemoriesConfig::default(), codex_home: fixture.codex_home(), diff --git a/codex-rs/core/src/tools/handlers/multi_agents.rs b/codex-rs/core/src/tools/handlers/multi_agents.rs index 7a2b62d562..2180574cc5 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents.rs @@ -124,7 +124,7 @@ mod spawn { let prompt = input_preview(&input_items); let session_source = turn.session_source.clone(); let child_depth = next_thread_spawn_depth(&session_source); - if exceeds_thread_spawn_depth_limit(child_depth) { + if exceeds_thread_spawn_depth_limit(child_depth, turn.config.agent_max_depth) { return Err(FunctionCallError::RespondToModel( "Agent depth limit reached. Solve the task yourself.".to_string(), )); @@ -306,7 +306,7 @@ mod resume_agent { let args: ResumeAgentArgs = parse_arguments(&arguments)?; let receiver_thread_id = agent_id(&args.id)?; let child_depth = next_thread_spawn_depth(&turn.session_source); - if exceeds_thread_spawn_depth_limit(child_depth) { + if exceeds_thread_spawn_depth_limit(child_depth, turn.config.agent_max_depth) { return Err(FunctionCallError::RespondToModel( "Agent depth limit reached. Solve the task yourself.".to_string(), )); @@ -840,7 +840,7 @@ fn build_agent_shared_config( fn apply_spawn_agent_overrides(config: &mut Config, child_depth: i32) { config.permissions.approval_policy = Constrained::allow_only(AskForApproval::Never); - if exceeds_thread_spawn_depth_limit(child_depth + 1) { + if exceeds_thread_spawn_depth_limit(child_depth + 1, config.agent_max_depth) { config.features.disable(Feature::Collab); } } @@ -851,9 +851,9 @@ mod tests { use crate::AuthManager; use crate::CodexAuth; use crate::ThreadManager; - use crate::agent::MAX_THREAD_SPAWN_DEPTH; use crate::built_in_model_providers; use crate::codex::make_session_and_context; + use crate::config::DEFAULT_AGENT_MAX_DEPTH; use crate::config::types::ShellEnvironmentPolicy; use crate::function_tool::FunctionCallError; use crate::protocol::AskForApproval; @@ -1066,7 +1066,7 @@ mod tests { turn.session_source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn { parent_thread_id: session.conversation_id, - depth: MAX_THREAD_SPAWN_DEPTH, + depth: DEFAULT_AGENT_MAX_DEPTH, }); let invocation = invocation( @@ -1086,6 +1086,49 @@ mod tests { ); } + #[tokio::test] + async fn spawn_agent_allows_depth_up_to_configured_max_depth() { + #[derive(Debug, Deserialize)] + struct SpawnAgentResult { + agent_id: String, + } + + let (mut session, mut turn) = make_session_and_context().await; + let manager = thread_manager(); + session.services.agent_control = manager.agent_control(); + + let mut config = (*turn.config).clone(); + config.agent_max_depth = DEFAULT_AGENT_MAX_DEPTH + 1; + turn.config = Arc::new(config); + turn.session_source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id: session.conversation_id, + depth: DEFAULT_AGENT_MAX_DEPTH, + }); + + let invocation = invocation( + Arc::new(session), + Arc::new(turn), + "spawn_agent", + function_payload(json!({"message": "hello"})), + ); + let output = MultiAgentHandler + .handle(invocation) + .await + .expect("spawn should succeed within configured depth"); + let ToolOutput::Function { + body: FunctionCallOutputBody::Text(content), + success, + .. + } = output + else { + panic!("expected function output"); + }; + let result: SpawnAgentResult = + serde_json::from_str(&content).expect("spawn_agent result should be json"); + assert!(!result.agent_id.is_empty()); + assert_eq!(success, Some(true)); + } + #[tokio::test] async fn send_input_rejects_empty_message() { let (session, turn) = make_session_and_context().await; @@ -1442,7 +1485,7 @@ mod tests { turn.session_source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn { parent_thread_id: session.conversation_id, - depth: MAX_THREAD_SPAWN_DEPTH, + depth: DEFAULT_AGENT_MAX_DEPTH, }); let invocation = invocation( From dae26c9e8b0c1a1fab325d73b598f8f9ae9d3834 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 19 Feb 2026 18:44:48 +0000 Subject: [PATCH 9/9] chore: increase stack size for everyone (#12254) --- codex-rs/arg0/src/lib.rs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/codex-rs/arg0/src/lib.rs b/codex-rs/arg0/src/lib.rs index 9563737839..dd89baeff3 100644 --- a/codex-rs/arg0/src/lib.rs +++ b/codex-rs/arg0/src/lib.rs @@ -12,8 +12,7 @@ const LINUX_SANDBOX_ARG0: &str = "codex-linux-sandbox"; const APPLY_PATCH_ARG0: &str = "apply_patch"; const MISSPELLED_APPLY_PATCH_ARG0: &str = "applypatch"; const LOCK_FILENAME: &str = ".lock"; -#[cfg(target_os = "windows")] -const WINDOWS_TOKIO_WORKER_STACK_SIZE_BYTES: usize = 16 * 1024 * 1024; +const TOKIO_WORKER_STACK_SIZE_BYTES: usize = 16 * 1024 * 1024; /// Keeps the per-session PATH entry alive and locked for the process lifetime. pub struct Arg0PathEntryGuard { @@ -129,12 +128,7 @@ where fn build_runtime() -> anyhow::Result { let mut builder = tokio::runtime::Builder::new_multi_thread(); builder.enable_all(); - #[cfg(target_os = "windows")] - { - // Defensive hardening: Windows worker threads have lower effective - // stack headroom, so use a larger stack for runtime workers. - builder.thread_stack_size(WINDOWS_TOKIO_WORKER_STACK_SIZE_BYTES); - } + builder.thread_stack_size(TOKIO_WORKER_STACK_SIZE_BYTES); Ok(builder.build()?) }