From 2794e278497e7e604a512ce877d16ed8e8fe6be9 Mon Sep 17 00:00:00 2001 From: canvrno-oai Date: Wed, 25 Mar 2026 17:03:18 -0700 Subject: [PATCH 001/212] Add ReloadUserConfig to tui_app_server (#15806) - Adds ReloadUserConfig to `tui_app_server` --- codex-rs/tui_app_server/src/app.rs | 4 ++++ .../tui_app_server/src/app_server_session.rs | 20 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/codex-rs/tui_app_server/src/app.rs b/codex-rs/tui_app_server/src/app.rs index 3ec29039de..452a1cfbd3 100644 --- a/codex-rs/tui_app_server/src/app.rs +++ b/codex-rs/tui_app_server/src/app.rs @@ -2183,6 +2183,10 @@ impl App { .await?; Ok(true) } + AppCommandView::ReloadUserConfig => { + app_server.reload_user_config().await?; + Ok(true) + } AppCommandView::OverrideTurnContext { .. } => Ok(true), _ => Ok(false), } diff --git a/codex-rs/tui_app_server/src/app_server_session.rs b/codex-rs/tui_app_server/src/app_server_session.rs index bd34404913..cf325786be 100644 --- a/codex-rs/tui_app_server/src/app_server_session.rs +++ b/codex-rs/tui_app_server/src/app_server_session.rs @@ -5,6 +5,8 @@ use codex_app_server_client::TypedRequestError; use codex_app_server_protocol::Account; use codex_app_server_protocol::AuthMode; use codex_app_server_protocol::ClientRequest; +use codex_app_server_protocol::ConfigBatchWriteParams; +use codex_app_server_protocol::ConfigWriteResponse; use codex_app_server_protocol::GetAccountParams; use codex_app_server_protocol::GetAccountRateLimitsResponse; use codex_app_server_protocol::GetAccountResponse; @@ -608,6 +610,24 @@ impl AppServerSession { .wrap_err("skills/list failed in app-server TUI") } + pub(crate) async fn reload_user_config(&mut self) -> Result<()> { + let request_id = self.next_request_id(); + let _: ConfigWriteResponse = self + .client + .request_typed(ClientRequest::ConfigBatchWrite { + request_id, + params: ConfigBatchWriteParams { + edits: Vec::new(), + file_path: None, + expected_version: None, + reload_user_config: true, + }, + }) + .await + .wrap_err("config/batchWrite failed while reloading user config in app-server TUI")?; + Ok(()) + } + pub(crate) async fn thread_realtime_start( &mut self, thread_id: ThreadId, From d7e35e56cff9157e4f1ba8da50a44a7bc6353028 Mon Sep 17 00:00:00 2001 From: Ruslan Nigmatullin Date: Wed, 25 Mar 2026 17:11:22 -0700 Subject: [PATCH 002/212] app-server: Organize app-server to allow more transports (#15810) Make `run_main_with_transport` slightly more flexible by consolidating logic spread across stdio and websocket transports. --- codex-rs/app-server/src/lib.rs | 77 +++++++++++++--------------------- 1 file changed, 28 insertions(+), 49 deletions(-) diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index 0a2b6f386b..e85a8f1290 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -363,38 +363,6 @@ pub async fn run_main_with_transport( let (outbound_control_tx, mut outbound_control_rx) = mpsc::channel::(CHANNEL_CAPACITY); - enum TransportRuntime { - Stdio, - WebSocket { - accept_handle: JoinHandle<()>, - shutdown_token: CancellationToken, - }, - } - - let mut stdio_handles = Vec::>::new(); - let transport_runtime = match transport { - AppServerTransport::Stdio => { - start_stdio_connection(transport_event_tx.clone(), &mut stdio_handles).await?; - TransportRuntime::Stdio - } - AppServerTransport::WebSocket { bind_address } => { - let shutdown_token = CancellationToken::new(); - let accept_handle = start_websocket_acceptor( - bind_address, - transport_event_tx.clone(), - shutdown_token.clone(), - policy_from_settings(&auth)?, - ) - .await?; - TransportRuntime::WebSocket { - accept_handle, - shutdown_token, - } - } - }; - let single_client_mode = matches!(&transport_runtime, TransportRuntime::Stdio); - let shutdown_when_no_connections = single_client_mode; - let graceful_signal_restart_enabled = !single_client_mode; // Parse CLI overrides once and derive the base Config eagerly so later // components do not need to work with raw TOML values. let cli_kv_overrides = cli_config_overrides.parse_overrides().map_err(|e| { @@ -558,6 +526,30 @@ pub async fn run_main_with_transport( } } + let transport_shutdown_token = CancellationToken::new(); + let mut transport_accept_handles = Vec::>::new(); + + let single_client_mode = matches!(&transport, AppServerTransport::Stdio); + let shutdown_when_no_connections = single_client_mode; + let graceful_signal_restart_enabled = !single_client_mode; + + match transport { + AppServerTransport::Stdio => { + start_stdio_connection(transport_event_tx.clone(), &mut transport_accept_handles) + .await?; + } + AppServerTransport::WebSocket { bind_address } => { + let accept_handle = start_websocket_acceptor( + bind_address, + transport_event_tx.clone(), + transport_shutdown_token.clone(), + policy_from_settings(&auth)?, + ) + .await?; + transport_accept_handles.push(accept_handle); + } + } + let outbound_handle = tokio::spawn(async move { let mut outbound_connections = HashMap::::new(); loop { @@ -635,10 +627,7 @@ pub async fn run_main_with_transport( let mut thread_created_rx = processor.thread_created_receiver(); let mut running_turn_count_rx = processor.subscribe_running_assistant_turn_count(); let mut connections = HashMap::::new(); - let websocket_accept_shutdown = match &transport_runtime { - TransportRuntime::WebSocket { shutdown_token, .. } => Some(shutdown_token.clone()), - TransportRuntime::Stdio => None, - }; + let transport_shutdown_token = transport_shutdown_token.clone(); async move { let mut listen_for_threads = true; let mut shutdown_state = ShutdownState::default(); @@ -651,9 +640,7 @@ pub async fn run_main_with_transport( shutdown_state.update(running_turn_count, connections.len()), ShutdownAction::Finish ) { - if let Some(shutdown_token) = &websocket_accept_shutdown { - shutdown_token.cancel(); - } + transport_shutdown_token.cancel(); let _ = outbound_control_tx .send(OutboundControlEvent::DisconnectAll) .await; @@ -847,16 +834,8 @@ pub async fn run_main_with_transport( let _ = processor_handle.await; let _ = outbound_handle.await; - if let TransportRuntime::WebSocket { - accept_handle, - shutdown_token, - } = transport_runtime - { - shutdown_token.cancel(); - let _ = accept_handle.await; - } - - for handle in stdio_handles { + transport_shutdown_token.cancel(); + for handle in transport_accept_handles { let _ = handle.await; } From 78799c1bcfb997c7f39625d6f47f33e55fe82708 Mon Sep 17 00:00:00 2001 From: Matthew Zeng Date: Wed, 25 Mar 2026 18:02:37 -0700 Subject: [PATCH 003/212] [mcp] Improve custom MCP elicitation (#15800) - [x] Support don't ask again for custom MCP tool calls. - [x] Don't run arc in yolo mode. - [x] Run arc for custom MCP tools in always allow mode. --- codex-rs/app-server/README.md | 5 + codex-rs/app-server/src/config_api.rs | 2 +- codex-rs/app-server/src/message_processor.rs | 90 +++++- .../app-server/tests/suite/v2/app_list.rs | 104 +++++++ codex-rs/cli/src/mcp_cmd.rs | 1 + codex-rs/core/config.schema.json | 31 +- codex-rs/core/src/config/config_tests.rs | 97 ++++++ codex-rs/core/src/config/edit.rs | 24 ++ codex-rs/core/src/config/edit_tests.rs | 55 ++++ codex-rs/core/src/config/types.rs | 27 ++ codex-rs/core/src/mcp/mod.rs | 1 + codex-rs/core/src/mcp/mod_tests.rs | 1 + codex-rs/core/src/mcp/skill_dependencies.rs | 2 + .../core/src/mcp/skill_dependencies_tests.rs | 2 + .../core/src/mcp_connection_manager_tests.rs | 2 + codex-rs/core/src/mcp_tool_call.rs | 136 +++++++-- codex-rs/core/src/mcp_tool_call_tests.rs | 276 +++++++++++++++--- codex-rs/core/src/plugins/manager_tests.rs | 4 + codex-rs/core/tests/suite/code_mode.rs | 1 + codex-rs/core/tests/suite/rmcp_client.rs | 6 + codex-rs/core/tests/suite/sqlite_state.rs | 1 + codex-rs/core/tests/suite/truncation.rs | 3 + codex-rs/tui/src/history_cell.rs | 2 + codex-rs/tui_app_server/src/history_cell.rs | 3 + docs/config.md | 10 + 25 files changed, 814 insertions(+), 72 deletions(-) diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index a1856af46d..1ca4688272 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -1012,6 +1012,11 @@ Order of messages: `turnId` is best-effort. When the elicitation is correlated with an active turn, the request includes that turn id; otherwise it is `null`. +For MCP tool approval elicitations, form request `meta` includes +`codex_approval_kind: "mcp_tool_call"` and may include `persist: "session"`, +`persist: "always"`, or `persist: ["session", "always"]` to advertise whether +the client can offer session-scoped and/or persistent approval choices. + ### Permission requests The built-in `request_permissions` tool sends an `item/permissions/requestApproval` JSON-RPC request to the client with the requested permission profile. This v2 payload mirrors the standalone tool's narrower permission shape, so it can request network access and additional filesystem access but does not include the broader `macos` branch used by command-execution `additionalPermissions`. diff --git a/codex-rs/app-server/src/config_api.rs b/codex-rs/app-server/src/config_api.rs index 2be0bb859c..7f6acc54d1 100644 --- a/codex-rs/app-server/src/config_api.rs +++ b/codex-rs/app-server/src/config_api.rs @@ -130,7 +130,7 @@ impl ConfigApi { .unwrap_or_default() } - async fn load_latest_config( + pub(crate) async fn load_latest_config( &self, fallback_cwd: Option, ) -> Result { diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 9a9a145f65..301ef9992c 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -20,6 +20,7 @@ use crate::outgoing_message::OutgoingMessageSender; use crate::outgoing_message::RequestContext; use crate::transport::AppServerTransport; use async_trait::async_trait; +use codex_app_server_protocol::AppListUpdatedNotification; use codex_app_server_protocol::ChatgptAuthTokensRefreshParams; use codex_app_server_protocol::ChatgptAuthTokensRefreshReason; use codex_app_server_protocol::ChatgptAuthTokensRefreshResponse; @@ -53,6 +54,7 @@ use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequestPayload; use codex_app_server_protocol::experimental_required_message; use codex_arg0::Arg0DispatchPaths; +use codex_chatgpt::connectors; use codex_core::AnalyticsEventsClient; use codex_core::AuthManager; use codex_core::ThreadManager; @@ -880,13 +882,87 @@ impl MessageProcessor { request_id: ConnectionRequestId, params: ExperimentalFeatureEnablementSetParams, ) { - self.handle_config_mutation_result( - request_id, - self.config_api - .set_experimental_feature_enablement(params) - .await, - ) - .await; + let should_refresh_apps_list = params.enablement.get("apps").copied() == Some(true); + match self + .config_api + .set_experimental_feature_enablement(params) + .await + { + Ok(response) => { + self.codex_message_processor.clear_plugin_related_caches(); + self.codex_message_processor + .maybe_start_plugin_startup_tasks_for_latest_config() + .await; + self.outgoing.send_response(request_id, response).await; + if should_refresh_apps_list { + self.refresh_apps_list_after_experimental_feature_enablement_set() + .await; + } + } + Err(error) => self.outgoing.send_error(request_id, error).await, + } + } + + async fn refresh_apps_list_after_experimental_feature_enablement_set(&self) { + let config = match self + .config_api + .load_latest_config(/*fallback_cwd*/ None) + .await + { + Ok(config) => config, + Err(error) => { + tracing::warn!( + "failed to load config for apps list refresh after experimental feature enablement: {}", + error.message + ); + return; + } + }; + if !config.features.apps_enabled(Some(&self.auth_manager)).await { + return; + } + + let outgoing = Arc::clone(&self.outgoing); + tokio::spawn(async move { + let (all_connectors_result, accessible_connectors_result) = tokio::join!( + connectors::list_all_connectors_with_options(&config, /*force_refetch*/ true), + connectors::list_accessible_connectors_from_mcp_tools_with_options( + &config, /*force_refetch*/ true, + ), + ); + let all_connectors = match all_connectors_result { + Ok(connectors) => connectors, + Err(err) => { + tracing::warn!( + "failed to force-refresh directory apps after experimental feature enablement: {err:#}" + ); + return; + } + }; + let accessible_connectors = match accessible_connectors_result { + Ok(connectors) => connectors, + Err(err) => { + tracing::warn!( + "failed to force-refresh accessible apps after experimental feature enablement: {err:#}" + ); + return; + } + }; + + let data = connectors::with_app_enabled_state( + connectors::merge_connectors_with_accessible( + all_connectors, + accessible_connectors, + /*all_connectors_loaded*/ true, + ), + &config, + ); + outgoing + .send_server_notification(ServerNotification::AppListUpdated( + AppListUpdatedNotification { data }, + )) + .await; + }); } async fn handle_config_mutation_result( diff --git a/codex-rs/app-server/tests/suite/v2/app_list.rs b/codex-rs/app-server/tests/suite/v2/app_list.rs index a19cdad857..23ffa80a67 100644 --- a/codex-rs/app-server/tests/suite/v2/app_list.rs +++ b/codex-rs/app-server/tests/suite/v2/app_list.rs @@ -1,4 +1,5 @@ use std::borrow::Cow; +use std::collections::BTreeMap; use std::collections::HashMap; use std::sync::Arc; use std::sync::Mutex as StdMutex; @@ -27,6 +28,7 @@ use codex_app_server_protocol::AppScreenshot; use codex_app_server_protocol::AppsListParams; use codex_app_server_protocol::AppsListResponse; use codex_app_server_protocol::AuthMode; +use codex_app_server_protocol::ExperimentalFeatureEnablementSetParams; use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; @@ -1201,6 +1203,108 @@ async fn list_apps_force_refetch_patches_updates_from_cached_snapshots() -> Resu Ok(()) } +#[tokio::test] +async fn experimental_feature_enablement_set_refreshes_apps_list_when_apps_turn_on() -> Result<()> { + let initial_connectors = vec![AppInfo { + id: "alpha".to_string(), + name: "Alpha".to_string(), + description: Some("Alpha v1".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + branding: None, + app_metadata: None, + labels: None, + install_url: None, + is_accessible: false, + is_enabled: true, + plugin_display_names: Vec::new(), + }]; + let (server_url, server_handle, server_control) = start_apps_server_with_delays_and_control( + initial_connectors, + Vec::new(), + Duration::ZERO, + Duration::ZERO, + ) + .await?; + + let codex_home = TempDir::new()?; + write_connectors_config(codex_home.path(), &server_url)?; + write_chatgpt_auth( + codex_home.path(), + ChatGptAuthFixture::new("chatgpt-token") + .account_id("account-123") + .chatgpt_user_id("user-enable-refresh") + .chatgpt_account_id("account-123"), + AuthCredentialsStoreMode::File, + )?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + + let disable_request = mcp + .send_experimental_feature_enablement_set_request(ExperimentalFeatureEnablementSetParams { + enablement: BTreeMap::from([("apps".to_string(), false)]), + }) + .await?; + let _disable_response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(disable_request)), + ) + .await??; + + server_control.set_connectors(vec![AppInfo { + id: "alpha".to_string(), + name: "Alpha".to_string(), + description: Some("Alpha v2".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + branding: None, + app_metadata: None, + labels: None, + install_url: None, + is_accessible: false, + is_enabled: true, + plugin_display_names: Vec::new(), + }]); + server_control.set_tools(vec![connector_tool("alpha", "Alpha App")?]); + + let enable_request = mcp + .send_experimental_feature_enablement_set_request(ExperimentalFeatureEnablementSetParams { + enablement: BTreeMap::from([("apps".to_string(), true)]), + }) + .await?; + let _enable_response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(enable_request)), + ) + .await??; + + let update = read_app_list_updated_notification(&mut mcp).await?; + assert_eq!( + update.data, + vec![AppInfo { + id: "alpha".to_string(), + name: "Alpha".to_string(), + description: Some("Alpha v2".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + branding: None, + app_metadata: None, + labels: None, + install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), + is_accessible: true, + is_enabled: true, + plugin_display_names: Vec::new(), + }] + ); + + server_handle.abort(); + Ok(()) +} + async fn read_app_list_updated_notification( mcp: &mut McpProcess, ) -> Result { diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs index 30a911cb63..52707f1da9 100644 --- a/codex-rs/cli/src/mcp_cmd.rs +++ b/codex-rs/cli/src/mcp_cmd.rs @@ -306,6 +306,7 @@ async fn run_add(config_overrides: &CliConfigOverrides, add_args: AddArgs) -> Re disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }; servers.insert(name.clone(), new_entry); diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 853f0235e0..1d1d6dd9a4 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -745,6 +745,21 @@ } ] }, + "McpServerToolConfig": { + "additionalProperties": false, + "description": "Per-tool approval settings for a single MCP server tool.", + "properties": { + "approval_mode": { + "allOf": [ + { + "$ref": "#/definitions/AppToolApproval" + } + ], + "description": "Approval mode for this tool." + } + }, + "type": "object" + }, "MemoriesToml": { "additionalProperties": false, "description": "Memories settings loaded from config.toml.", @@ -1246,7 +1261,9 @@ "type": "object" }, "RawMcpServerConfig": { - "additionalProperties": false, + "additionalProperties": { + "$ref": "#/definitions/McpServerToolConfig" + }, "properties": { "args": { "default": null, @@ -1313,6 +1330,11 @@ }, "type": "object" }, + "name": { + "default": null, + "description": "Legacy display-name field accepted for backward compatibility.", + "type": "string" + }, "oauth_resource": { "default": null, "type": "string" @@ -1344,6 +1366,13 @@ "format": "double", "type": "number" }, + "tools": { + "additionalProperties": { + "$ref": "#/definitions/McpServerToolConfig" + }, + "default": null, + "type": "object" + }, "url": { "type": "string" } diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index 34c41d44b0..84ac6d71bc 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -1,10 +1,12 @@ use crate::config::edit::ConfigEdit; use crate::config::edit::ConfigEditsBuilder; use crate::config::edit::apply_blocking; +use crate::config::types::AppToolApproval; use crate::config::types::ApprovalsReviewer; use crate::config::types::BundledSkillsConfig; use crate::config::types::FeedbackConfigToml; use crate::config::types::HistoryPersistence; +use crate::config::types::McpServerToolConfig; use crate::config::types::McpServerTransportConfig; use crate::config::types::MemoriesConfig; use crate::config::types::MemoriesToml; @@ -57,6 +59,7 @@ fn stdio_mcp(command: &str) -> McpServerConfig { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), } } @@ -77,6 +80,7 @@ fn http_mcp(url: &str) -> McpServerConfig { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), } } @@ -1853,6 +1857,7 @@ async fn replace_mcp_servers_round_trips_entries() -> anyhow::Result<()> { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); @@ -1958,6 +1963,85 @@ startup_timeout_ms = 2500 Ok(()) } +#[test] +fn mcp_servers_toml_parses_per_tool_approval_overrides() { + let config = toml::from_str::( + r#" +[mcp_servers.docs] +command = "docs-server" +name = "Docs" + +[mcp_servers.docs.tools.search] +approval_mode = "approve" +"#, + ) + .expect("TOML deserialization should succeed"); + let tool = config + .mcp_servers + .get("docs") + .and_then(|server| server.tools.get("search")) + .expect("docs/search tool config exists"); + + assert_eq!( + tool, + &McpServerToolConfig { + approval_mode: Some(AppToolApproval::Approve), + } + ); +} + +#[test] +fn mcp_servers_toml_parses_legacy_flattened_per_tool_approval_overrides() { + let config = toml::from_str::( + r#" +[mcp_servers.docs] +command = "docs-server" + +[mcp_servers.docs.search] +approval_mode = "approve" +"#, + ) + .expect("legacy TOML deserialization should succeed"); + let tool = config + .mcp_servers + .get("docs") + .and_then(|server| server.tools.get("search")) + .expect("docs/search tool config exists"); + + assert_eq!( + tool, + &McpServerToolConfig { + approval_mode: Some(AppToolApproval::Approve), + } + ); +} + +#[test] +fn mcp_servers_toml_parses_tool_approval_override_for_reserved_name() { + let config = toml::from_str::( + r#" +[mcp_servers.docs] +command = "docs-server" + +[mcp_servers.docs.tools.command] +approval_mode = "approve" +"#, + ) + .expect("TOML deserialization should succeed"); + let tool = config + .mcp_servers + .get("docs") + .and_then(|server| server.tools.get("command")) + .expect("docs/command tool config exists"); + + assert_eq!( + tool, + &McpServerToolConfig { + approval_mode: Some(AppToolApproval::Approve), + } + ); +} + #[tokio::test] async fn load_global_mcp_servers_rejects_inline_bearer_token() -> anyhow::Result<()> { let codex_home = TempDir::new()?; @@ -2009,6 +2093,7 @@ async fn replace_mcp_servers_serializes_env_sorted() -> anyhow::Result<()> { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, )]); @@ -2081,6 +2166,7 @@ async fn replace_mcp_servers_serializes_env_vars() -> anyhow::Result<()> { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, )]); @@ -2133,6 +2219,7 @@ async fn replace_mcp_servers_serializes_cwd() -> anyhow::Result<()> { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, )]); @@ -2183,6 +2270,7 @@ async fn replace_mcp_servers_streamable_http_serializes_bearer_token() -> anyhow disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, )]); @@ -2249,6 +2337,7 @@ async fn replace_mcp_servers_streamable_http_serializes_custom_headers() -> anyh disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, )]); apply_blocking( @@ -2327,6 +2416,7 @@ async fn replace_mcp_servers_streamable_http_removes_optional_sections() -> anyh disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, )]); @@ -2358,6 +2448,7 @@ async fn replace_mcp_servers_streamable_http_removes_optional_sections() -> anyh disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); apply_blocking( @@ -2424,6 +2515,7 @@ async fn replace_mcp_servers_streamable_http_isolates_headers_between_servers() disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ), ( @@ -2445,6 +2537,7 @@ async fn replace_mcp_servers_streamable_http_isolates_headers_between_servers() disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ), ]); @@ -2529,6 +2622,7 @@ async fn replace_mcp_servers_serializes_disabled_flag() -> anyhow::Result<()> { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, )]); @@ -2575,6 +2669,7 @@ async fn replace_mcp_servers_serializes_required_flag() -> anyhow::Result<()> { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, )]); @@ -2621,6 +2716,7 @@ async fn replace_mcp_servers_serializes_tool_filters() -> anyhow::Result<()> { disabled_tools: Some(vec!["blocked".to_string()]), scopes: None, oauth_resource: None, + tools: HashMap::new(), }, )]); @@ -2671,6 +2767,7 @@ async fn replace_mcp_servers_streamable_http_serializes_oauth_resource() -> anyh disabled_tools: None, scopes: None, oauth_resource: Some("https://resource.example.com".to_string()), + tools: HashMap::new(), }, )]); diff --git a/codex-rs/core/src/config/edit.rs b/codex-rs/core/src/config/edit.rs index 3f7e3b1170..370c46ce4c 100644 --- a/codex-rs/core/src/config/edit.rs +++ b/codex-rs/core/src/config/edit.rs @@ -125,7 +125,9 @@ pub fn model_availability_nux_count_edits(shown_count: &HashMap) -> // TODO(jif) move to a dedicated file mod document_helpers { + use crate::config::types::AppToolApproval; use crate::config::types::McpServerConfig; + use crate::config::types::McpServerToolConfig; use crate::config::types::McpServerTransportConfig; use toml_edit::Array as TomlArray; use toml_edit::InlineTable; @@ -248,10 +250,32 @@ mod document_helpers { { entry["oauth_resource"] = value(resource.clone()); } + if !config.tools.is_empty() { + let mut tools = new_implicit_table(); + let mut tool_entries: Vec<_> = config.tools.iter().collect(); + tool_entries.sort_by(|(left, _), (right, _)| left.cmp(right)); + for (name, tool_config) in tool_entries { + tools.insert(name, serialize_mcp_server_tool(tool_config)); + } + entry.insert("tools", TomlItem::Table(tools)); + } entry } + fn serialize_mcp_server_tool(config: &McpServerToolConfig) -> TomlItem { + let mut entry = TomlTable::new(); + entry.set_implicit(false); + if let Some(approval_mode) = config.approval_mode { + entry["approval_mode"] = value(match approval_mode { + AppToolApproval::Auto => "auto", + AppToolApproval::Prompt => "prompt", + AppToolApproval::Approve => "approve", + }); + } + TomlItem::Table(entry) + } + pub(super) fn serialize_mcp_server(config: &McpServerConfig) -> TomlItem { TomlItem::Table(serialize_mcp_server_table(config)) } diff --git a/codex-rs/core/src/config/edit_tests.rs b/codex-rs/core/src/config/edit_tests.rs index 632716f00d..d7386c546c 100644 --- a/codex-rs/core/src/config/edit_tests.rs +++ b/codex-rs/core/src/config/edit_tests.rs @@ -1,4 +1,6 @@ use super::*; +use crate::config::types::AppToolApproval; +use crate::config::types::McpServerToolConfig; use crate::config::types::McpServerTransportConfig; use codex_protocol::openai_models::ReasoningEffort; use pretty_assertions::assert_eq; @@ -582,6 +584,7 @@ fn blocking_replace_mcp_servers_round_trips() { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); @@ -607,6 +610,7 @@ fn blocking_replace_mcp_servers_round_trips() { disabled_tools: Some(vec!["forbidden".to_string()]), scopes: None, oauth_resource: Some("https://resource.example.com".to_string()), + tools: HashMap::new(), }, ); @@ -643,6 +647,53 @@ B = \"2\" assert_eq!(raw, expected); } +#[test] +fn blocking_replace_mcp_servers_serializes_tool_approval_overrides() { + let tmp = tempdir().expect("tmpdir"); + let codex_home = tmp.path(); + + let mut servers = BTreeMap::new(); + servers.insert( + "docs".to_string(), + McpServerConfig { + transport: McpServerTransportConfig::Stdio { + command: "docs-server".to_string(), + args: Vec::new(), + env: None, + env_vars: Vec::new(), + cwd: None, + }, + enabled: true, + required: false, + disabled_reason: None, + startup_timeout_sec: None, + tool_timeout_sec: None, + enabled_tools: None, + disabled_tools: None, + scopes: None, + oauth_resource: None, + tools: HashMap::from([( + "search".to_string(), + McpServerToolConfig { + approval_mode: Some(AppToolApproval::Approve), + }, + )]), + }, + ); + + apply_blocking(codex_home, None, &[ConfigEdit::ReplaceMcpServers(servers)]).expect("persist"); + + let raw = std::fs::read_to_string(codex_home.join(CONFIG_TOML_FILE)).expect("read config"); + let expected = "\ +[mcp_servers.docs] +command = \"docs-server\" + +[mcp_servers.docs.tools.search] +approval_mode = \"approve\" +"; + assert_eq!(raw, expected); +} + #[test] fn blocking_replace_mcp_servers_preserves_inline_comments() { let tmp = tempdir().expect("tmpdir"); @@ -676,6 +727,7 @@ foo = { command = "cmd" } disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); @@ -721,6 +773,7 @@ foo = { command = "cmd" } # keep me disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); @@ -765,6 +818,7 @@ foo = { command = "cmd", args = ["--flag"] } # keep me disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); @@ -810,6 +864,7 @@ foo = { command = "cmd" } disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); diff --git a/codex-rs/core/src/config/types.rs b/codex-rs/core/src/config/types.rs index c9f83482aa..a69fec3431 100644 --- a/codex-rs/core/src/config/types.rs +++ b/codex-rs/core/src/config/types.rs @@ -108,6 +108,10 @@ pub struct McpServerConfig { /// Optional OAuth resource parameter to include during MCP login (RFC 8707). #[serde(default, skip_serializing_if = "Option::is_none")] pub oauth_resource: Option, + + /// Per-tool approval settings keyed by tool name. + #[serde(default, skip_serializing_if = "HashMap::is_empty")] + pub tools: HashMap, } // Raw MCP config shape used for deserialization and JSON Schema generation. @@ -154,6 +158,15 @@ pub(crate) struct RawMcpServerConfig { pub scopes: Option>, #[serde(default)] pub oauth_resource: Option, + /// Legacy display-name field accepted for backward compatibility. + #[serde(default, rename = "name")] + pub _name: Option, + #[serde(default)] + pub tools: Option>, + /// Legacy flattened per-tool approval settings accepted for backward compatibility. + #[serde(default)] + #[serde(flatten)] + pub legacy_tools: HashMap, } impl<'de> Deserialize<'de> for McpServerConfig { @@ -178,6 +191,10 @@ impl<'de> Deserialize<'de> for McpServerConfig { let disabled_tools = raw.disabled_tools.clone(); let scopes = raw.scopes.clone(); let oauth_resource = raw.oauth_resource.clone(); + let mut tools = raw.legacy_tools.clone(); + if let Some(nested_tools) = raw.tools.clone() { + tools.extend(nested_tools); + } fn throw_if_set(transport: &str, field: &str, value: Option<&T>) -> Result<(), E> where @@ -236,6 +253,7 @@ impl<'de> Deserialize<'de> for McpServerConfig { disabled_tools, scopes, oauth_resource, + tools, }) } } @@ -496,6 +514,15 @@ pub enum AppToolApproval { Approve, } +/// Per-tool approval settings for a single MCP server tool. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct McpServerToolConfig { + /// Approval mode for this tool. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub approval_mode: Option, +} + /// Default settings that apply to all apps. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] #[schemars(deny_unknown_fields)] diff --git a/codex-rs/core/src/mcp/mod.rs b/codex-rs/core/src/mcp/mod.rs index 81ee0c7fe8..a9d2388f70 100644 --- a/codex-rs/core/src/mcp/mod.rs +++ b/codex-rs/core/src/mcp/mod.rs @@ -176,6 +176,7 @@ fn codex_apps_mcp_server_config(config: &Config, auth: Option<&CodexAuth>) -> Mc disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), } } diff --git a/codex-rs/core/src/mcp/mod_tests.rs b/codex-rs/core/src/mcp/mod_tests.rs index dc9465e103..855e71e1f2 100644 --- a/codex-rs/core/src/mcp/mod_tests.rs +++ b/codex-rs/core/src/mcp/mod_tests.rs @@ -235,6 +235,7 @@ async fn effective_mcp_servers_include_plugins_without_overriding_user_config() disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); config diff --git a/codex-rs/core/src/mcp/skill_dependencies.rs b/codex-rs/core/src/mcp/skill_dependencies.rs index 489dc2e438..ba4ef26488 100644 --- a/codex-rs/core/src/mcp/skill_dependencies.rs +++ b/codex-rs/core/src/mcp/skill_dependencies.rs @@ -428,6 +428,7 @@ fn mcp_dependency_to_server_config( disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }); } @@ -453,6 +454,7 @@ fn mcp_dependency_to_server_config( disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }); } diff --git a/codex-rs/core/src/mcp/skill_dependencies_tests.rs b/codex-rs/core/src/mcp/skill_dependencies_tests.rs index ebabe16f80..34c6a767f5 100644 --- a/codex-rs/core/src/mcp/skill_dependencies_tests.rs +++ b/codex-rs/core/src/mcp/skill_dependencies_tests.rs @@ -48,6 +48,7 @@ fn collect_missing_respects_canonical_installed_key() { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, )]); @@ -97,6 +98,7 @@ fn collect_missing_dedupes_by_canonical_key_but_preserves_original_name() { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, )]); diff --git a/codex-rs/core/src/mcp_connection_manager_tests.rs b/codex-rs/core/src/mcp_connection_manager_tests.rs index c5f7fc4a40..2331d0c1fe 100644 --- a/codex-rs/core/src/mcp_connection_manager_tests.rs +++ b/codex-rs/core/src/mcp_connection_manager_tests.rs @@ -542,6 +542,7 @@ fn mcp_init_error_display_prompts_for_github_pat() { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, auth_status: McpAuthStatus::Unsupported, }; @@ -590,6 +591,7 @@ fn mcp_init_error_display_reports_generic_errors() { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, auth_status: McpAuthStatus::Unsupported, }; diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 04341bdad8..9855481b01 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -1,7 +1,10 @@ use std::collections::BTreeMap; +use std::collections::HashMap; +use std::path::PathBuf; use std::time::Duration; use std::time::Instant; +use codex_app_server_protocol::ConfigLayerSource; use codex_app_server_protocol::McpElicitationObjectType; use codex_app_server_protocol::McpElicitationSchema; use codex_app_server_protocol::McpServerElicitationRequest; @@ -12,8 +15,10 @@ use crate::arc_monitor::ArcMonitorOutcome; use crate::arc_monitor::monitor_action; use crate::codex::Session; use crate::codex::TurnContext; +use crate::config::Config; use crate::config::edit::ConfigEdit; use crate::config::edit::ConfigEditsBuilder; +use crate::config::load_global_mcp_servers; use crate::config::types::AppToolApproval; use crate::connectors; use crate::guardian::GuardianApprovalRequest; @@ -46,6 +51,7 @@ use codex_protocol::request_user_input::RequestUserInputResponse; use codex_rmcp_client::ElicitationAction; use codex_rmcp_client::ElicitationResponse; use rmcp::model::ToolAnnotations; +use serde::Deserialize; use serde::Serialize; use std::path::Path; use std::sync::Arc; @@ -104,6 +110,11 @@ pub(crate) async fn handle_mcp_tool_call( } else { connectors::AppToolPolicy::default() }; + let approval_mode = if server == CODEX_APPS_MCP_SERVER_NAME { + app_tool_policy.approval + } else { + custom_mcp_tool_approval_mode(turn_context.as_ref(), &server, &tool_name) + }; if server == CODEX_APPS_MCP_SERVER_NAME && !app_tool_policy.enabled { let result = notify_mcp_tool_call_skip( @@ -151,7 +162,7 @@ pub(crate) async fn handle_mcp_tool_call( &call_id, &invocation, metadata.as_ref(), - app_tool_policy.approval, + approval_mode, ) .await { @@ -491,6 +502,27 @@ pub(crate) struct McpToolApprovalMetadata { const MCP_TOOL_CODEX_APPS_META_KEY: &str = "_codex_apps"; +fn custom_mcp_tool_approval_mode( + turn_context: &TurnContext, + server: &str, + tool_name: &str, +) -> AppToolApproval { + turn_context + .config + .config_layer_stack + .effective_config() + .as_table() + .and_then(|table| table.get("mcp_servers")) + .cloned() + .and_then(|value| { + HashMap::::deserialize(value).ok() + }) + .and_then(|servers| servers.get(server).cloned()) + .and_then(|server| server.tools.get(tool_name).cloned()) + .and_then(|tool| tool.approval_mode) + .unwrap_or_default() +} + fn build_mcp_tool_call_request_meta( turn_context: &TurnContext, server: &str, @@ -560,7 +592,6 @@ const MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY: &str = "tool_params"; const MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY: &str = "tool_params_display"; const MCP_TOOL_CALL_ARC_MONITOR_CALLSITE_DEFAULT: &str = "mcp_tool_call__default"; const MCP_TOOL_CALL_ARC_MONITOR_CALLSITE_ALWAYS_ALLOW: &str = "mcp_tool_call__always_allow"; -const MCP_TOOL_CALL_ARC_MONITOR_CALLSITE_FULL_ACCESS: &str = "mcp_tool_call__full_access"; pub(crate) fn is_mcp_tool_approval_question_id(question_id: &str) -> bool { question_id @@ -595,11 +626,14 @@ async fn maybe_request_mcp_tool_approval( metadata: Option<&McpToolApprovalMetadata>, approval_mode: AppToolApproval, ) -> Option { + if is_full_access_mode(turn_context) { + return None; + } + let annotations = metadata.and_then(|metadata| metadata.annotations.as_ref()); let approval_required = requires_mcp_tool_approval(annotations); let mut monitor_reason = None; - let auto_approved_by_policy = approval_mode == AppToolApproval::Approve - || (approval_mode == AppToolApproval::Auto && is_full_access_mode(turn_context)); + let auto_approved_by_policy = approval_mode == AppToolApproval::Approve; if auto_approved_by_policy { if !approval_required { @@ -812,12 +846,7 @@ fn persistent_mcp_tool_approval_key( metadata: Option<&McpToolApprovalMetadata>, approval_mode: AppToolApproval, ) -> Option { - if invocation.server != CODEX_APPS_MCP_SERVER_NAME { - return None; - } - session_mcp_tool_approval_key(invocation, metadata, approval_mode) - .filter(|key| key.connector_id.is_some()) } pub(crate) fn build_guardian_mcp_tool_review_request( @@ -865,16 +894,12 @@ fn is_full_access_mode(turn_context: &TurnContext) -> bool { fn mcp_tool_approval_callsite_mode( approval_mode: AppToolApproval, - turn_context: &TurnContext, + _turn_context: &TurnContext, ) -> &'static str { match approval_mode { AppToolApproval::Approve => MCP_TOOL_CALL_ARC_MONITOR_CALLSITE_ALWAYS_ALLOW, AppToolApproval::Auto | AppToolApproval::Prompt => { - if approval_mode == AppToolApproval::Auto && is_full_access_mode(turn_context) { - MCP_TOOL_CALL_ARC_MONITOR_CALLSITE_FULL_ACCESS - } else { - MCP_TOOL_CALL_ARC_MONITOR_CALLSITE_DEFAULT - } + MCP_TOOL_CALL_ARC_MONITOR_CALLSITE_DEFAULT } } } @@ -1356,21 +1381,25 @@ async fn maybe_persist_mcp_tool_approval( turn_context: &TurnContext, key: McpToolApprovalKey, ) { - let Some(connector_id) = key.connector_id.clone() else { - remember_mcp_tool_approval(sess, key).await; - return; - }; let tool_name = key.tool_name.clone(); - if let Err(err) = + let persist_result = if key.server == CODEX_APPS_MCP_SERVER_NAME { + let Some(connector_id) = key.connector_id.clone() else { + remember_mcp_tool_approval(sess, key).await; + return; + }; persist_codex_app_tool_approval(&turn_context.config.codex_home, &connector_id, &tool_name) .await - { + } else { + persist_custom_mcp_tool_approval(&turn_context.config, &key.server, &tool_name).await + }; + + if let Err(err) = persist_result { error!( error = %err, - connector_id, + server = key.server, tool_name, - "failed to persist codex app tool approval" + "failed to persist MCP tool approval" ); remember_mcp_tool_approval(sess, key).await; return; @@ -1400,6 +1429,67 @@ async fn persist_codex_app_tool_approval( .await } +async fn persist_custom_mcp_tool_approval( + config: &Config, + server: &str, + tool_name: &str, +) -> anyhow::Result<()> { + let config_folder = if let Some(project_config_folder) = + project_mcp_tool_approval_config_folder(config, server) + { + project_config_folder + } else { + let servers = load_global_mcp_servers(&config.codex_home).await?; + if !servers.contains_key(server) { + anyhow::bail!("MCP server `{server}` is not configured in config.toml"); + } + config.codex_home.clone() + }; + + ConfigEditsBuilder::new(&config_folder) + .with_edits([ConfigEdit::SetPath { + segments: vec![ + "mcp_servers".to_string(), + server.to_string(), + "tools".to_string(), + tool_name.to_string(), + "approval_mode".to_string(), + ], + value: value("approve"), + }]) + .apply() + .await +} + +fn project_mcp_tool_approval_config_folder(config: &Config, server: &str) -> Option { + config + .config_layer_stack + .layers_high_to_low() + .into_iter() + .find_map(|layer| { + if !matches!(layer.name, ConfigLayerSource::Project { .. }) { + return None; + } + + let servers = layer + .config + .as_table() + .and_then(|table| table.get("mcp_servers")) + .cloned() + .and_then(|value| { + HashMap::::deserialize(value) + .ok() + })?; + if servers.contains_key(server) { + layer + .config_folder() + .map(|folder| folder.as_path().to_path_buf()) + } else { + None + } + }) +} + fn requires_mcp_tool_approval(annotations: Option<&ToolAnnotations>) -> bool { let destructive_hint = annotations.and_then(|annotations| annotations.destructive_hint); if destructive_hint == Some(true) { diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index edd698c134..cf3c761faf 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -1,11 +1,14 @@ use super::*; use crate::codex::make_session_and_context; use crate::config::ApprovalsReviewer; +use crate::config::ConfigBuilder; use crate::config::ConfigToml; use crate::config::types::AppConfig; use crate::config::types::AppToolConfig; use crate::config::types::AppToolsConfig; use crate::config::types::AppsConfigToml; +use crate::config::types::McpServerConfig; +use crate::config::types::McpServerToolConfig; use codex_config::CONFIG_TOML_FILE; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; @@ -378,13 +381,13 @@ fn codex_apps_tool_question_without_elicitation_omits_always_allow() { } #[test] -fn custom_mcp_tool_question_offers_session_remember_without_always_allow() { +fn custom_mcp_tool_question_offers_session_remember_and_always_allow() { let question = build_mcp_tool_approval_question( "q".to_string(), "custom_server", "run_action", None, - prompt_options(true, false), + prompt_options(true, true), None, ); @@ -398,13 +401,14 @@ fn custom_mcp_tool_question_offers_session_remember_without_always_allow() { vec![ MCP_TOOL_APPROVAL_ACCEPT.to_string(), MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION.to_string(), + MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER.to_string(), MCP_TOOL_APPROVAL_CANCEL.to_string(), ] ); } #[test] -fn custom_servers_keep_session_remember_without_persistent_approval() { +fn custom_servers_support_session_and_persistent_approval() { let invocation = McpInvocation { server: "custom_server".to_string(), tool: "run_action".to_string(), @@ -418,11 +422,11 @@ fn custom_servers_keep_session_remember_without_persistent_approval() { assert_eq!( session_mcp_tool_approval_key(&invocation, None, AppToolApproval::Auto), - Some(expected) + Some(expected.clone()) ); assert_eq!( persistent_mcp_tool_approval_key(&invocation, None, AppToolApproval::Auto), - None + Some(expected) ); } @@ -612,7 +616,7 @@ fn approval_elicitation_meta_marks_tool_approvals() { } #[test] -fn approval_elicitation_meta_keeps_session_persist_behavior_for_custom_servers() { +fn approval_elicitation_meta_merges_session_and_always_persist_for_custom_servers() { assert_eq!( build_mcp_tool_approval_elicitation_meta( "custom_server", @@ -625,11 +629,14 @@ fn approval_elicitation_meta_keeps_session_persist_behavior_for_custom_servers() )), Some(&serde_json::json!({"id": 1})), None, - prompt_options(true, false), + prompt_options(true, true), ), Some(serde_json::json!({ MCP_TOOL_APPROVAL_KIND_KEY: MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL, - MCP_TOOL_APPROVAL_PERSIST_KEY: MCP_TOOL_APPROVAL_PERSIST_SESSION, + MCP_TOOL_APPROVAL_PERSIST_KEY: [ + MCP_TOOL_APPROVAL_PERSIST_SESSION, + MCP_TOOL_APPROVAL_PERSIST_ALWAYS, + ], MCP_TOOL_APPROVAL_TOOL_TITLE_KEY: "Run Action", MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY: "Runs the selected action.", MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY: { @@ -843,8 +850,8 @@ fn approval_elicitation_meta_merges_session_and_always_persist_with_connector_so } #[tokio::test] -async fn approval_callsite_mode_distinguishes_default_always_allow_and_full_access() { - let (_session, mut turn_context) = make_session_and_context().await; +async fn approval_callsite_mode_distinguishes_default_and_always_allow() { + let (_session, turn_context) = make_session_and_context().await; assert_eq!( mcp_tool_approval_callsite_mode(AppToolApproval::Auto, &turn_context), @@ -858,20 +865,6 @@ async fn approval_callsite_mode_distinguishes_default_always_allow_and_full_acce mcp_tool_approval_callsite_mode(AppToolApproval::Approve, &turn_context), "mcp_tool_call__always_allow" ); - - turn_context - .approval_policy - .set(AskForApproval::Never) - .expect("test setup should allow updating approval policy"); - turn_context - .sandbox_policy - .set(SandboxPolicy::DangerFullAccess) - .expect("test setup should allow updating sandbox policy"); - - assert_eq!( - mcp_tool_approval_callsite_mode(AppToolApproval::Auto, &turn_context), - "mcp_tool_call__full_access" - ); } #[test] @@ -992,6 +985,41 @@ async fn persist_codex_app_tool_approval_writes_tool_override() { assert!(contents.contains("[apps.calendar.tools.\"calendar/list_events\"]")); } +#[tokio::test] +async fn persist_custom_mcp_tool_approval_writes_tool_override() { + let tmp = tempdir().expect("tempdir"); + std::fs::write( + tmp.path().join(CONFIG_TOML_FILE), + "[mcp_servers.docs]\ncommand = \"docs-server\"\n", + ) + .expect("seed config"); + let config = ConfigBuilder::default() + .codex_home(tmp.path().to_path_buf()) + .build() + .await + .expect("load config"); + + persist_custom_mcp_tool_approval(&config, "docs", "search") + .await + .expect("persist approval"); + + let contents = std::fs::read_to_string(tmp.path().join(CONFIG_TOML_FILE)).expect("read config"); + let parsed: ConfigToml = toml::from_str(&contents).expect("parse config"); + let tool = parsed + .mcp_servers + .get("docs") + .and_then(|server| server.tools.get("search")) + .expect("docs/search tool config exists"); + + assert_eq!( + tool, + &McpServerToolConfig { + approval_mode: Some(AppToolApproval::Approve), + } + ); + assert!(contents.contains("[mcp_servers.docs.tools.search]")); +} + #[tokio::test] async fn maybe_persist_mcp_tool_approval_reloads_session_config() { let (session, turn_context) = make_session_and_context().await; @@ -1031,6 +1059,104 @@ async fn maybe_persist_mcp_tool_approval_reloads_session_config() { assert_eq!(mcp_tool_approval_is_remembered(&session, &key).await, true); } +#[tokio::test] +async fn maybe_persist_mcp_tool_approval_reloads_session_config_for_custom_server() { + let (session, turn_context) = make_session_and_context().await; + let codex_home = session.codex_home().await; + std::fs::create_dir_all(&codex_home).expect("create codex home"); + std::fs::write( + codex_home.join(CONFIG_TOML_FILE), + "[mcp_servers.docs]\ncommand = \"docs-server\"\n", + ) + .expect("seed config"); + let key = McpToolApprovalKey { + server: "docs".to_string(), + connector_id: None, + tool_name: "search".to_string(), + }; + + maybe_persist_mcp_tool_approval(&session, &turn_context, key.clone()).await; + + let config = session.get_config().await; + let mcp_servers_toml = config + .config_layer_stack + .effective_config() + .as_table() + .and_then(|table| table.get("mcp_servers")) + .cloned() + .expect("mcp_servers table"); + let mcp_servers = HashMap::::deserialize(mcp_servers_toml) + .expect("deserialize MCP servers"); + let tool = mcp_servers + .get("docs") + .and_then(|server| server.tools.get("search")) + .expect("docs/search tool config exists"); + + assert_eq!( + tool, + &McpServerToolConfig { + approval_mode: Some(AppToolApproval::Approve), + } + ); + assert_eq!(mcp_tool_approval_is_remembered(&session, &key).await, true); +} + +#[tokio::test] +async fn maybe_persist_mcp_tool_approval_writes_project_config_for_project_server() { + let (session, mut turn_context) = make_session_and_context().await; + let codex_home = session.codex_home().await; + let project_dir = tempdir().expect("tempdir"); + std::fs::write(project_dir.path().join(".git"), "gitdir: nowhere").expect("seed git marker"); + let project_codex_dir = project_dir.path().join(".codex"); + std::fs::create_dir_all(&project_codex_dir).expect("create project .codex dir"); + std::fs::write( + project_codex_dir.join(CONFIG_TOML_FILE), + "[mcp_servers.docs]\ncommand = \"docs-server\"\n", + ) + .expect("seed project config"); + ConfigEditsBuilder::new(&codex_home) + .set_project_trust_level( + project_dir.path(), + codex_protocol::config_types::TrustLevel::Trusted, + ) + .apply() + .await + .expect("trust project"); + let config = ConfigBuilder::default() + .codex_home(codex_home) + .fallback_cwd(Some(project_dir.path().to_path_buf())) + .build() + .await + .expect("load project config"); + turn_context.cwd = config.cwd.clone(); + turn_context.config = Arc::new(config); + let key = McpToolApprovalKey { + server: "docs".to_string(), + connector_id: None, + tool_name: "search".to_string(), + }; + + maybe_persist_mcp_tool_approval(&session, &turn_context, key.clone()).await; + + let contents = std::fs::read_to_string(project_codex_dir.join(CONFIG_TOML_FILE)) + .expect("read project config"); + let parsed: ConfigToml = toml::from_str(&contents).expect("parse project config"); + let tool = parsed + .mcp_servers + .get("docs") + .and_then(|server| server.tools.get("search")) + .expect("docs/search tool config exists"); + + assert_eq!( + tool, + &McpServerToolConfig { + approval_mode: Some(AppToolApproval::Approve), + } + ); + assert!(contents.contains("[mcp_servers.docs.tools.search]")); + assert_eq!(mcp_tool_approval_is_remembered(&session, &key).await, true); +} + #[tokio::test] async fn approve_mode_skips_when_annotations_do_not_require_approval() { let (session, turn_context) = make_session_and_context().await; @@ -1133,6 +1259,75 @@ async fn approve_mode_blocks_when_arc_returns_interrupt_for_model() { ); } +#[tokio::test] +async fn custom_approve_mode_blocks_when_arc_returns_interrupt_for_model() { + use wiremock::Mock; + use wiremock::MockServer; + use wiremock::ResponseTemplate; + use wiremock::matchers::method; + use wiremock::matchers::path; + + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/codex/safety/arc")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "outcome": "steer-model", + "short_reason": "needs approval", + "rationale": "high-risk action", + "risk_score": 96, + "risk_level": "critical", + "evidence": [{ + "message": "dangerous_tool", + "why": "high-risk action", + }], + }))) + .expect(1) + .mount(&server) + .await; + + let (session, mut turn_context) = make_session_and_context().await; + turn_context.auth_manager = Some(crate::test_support::auth_manager_from_auth( + crate::CodexAuth::create_dummy_chatgpt_auth_for_testing(), + )); + let mut config = (*turn_context.config).clone(); + config.chatgpt_base_url = server.uri(); + turn_context.config = Arc::new(config); + + let session = Arc::new(session); + let turn_context = Arc::new(turn_context); + let invocation = McpInvocation { + server: "docs".to_string(), + tool: "dangerous_tool".to_string(), + arguments: Some(serde_json::json!({ "id": 1 })), + }; + let metadata = McpToolApprovalMetadata { + annotations: Some(annotations(Some(false), Some(true), Some(true))), + connector_id: None, + connector_name: None, + connector_description: None, + tool_title: Some("Dangerous Tool".to_string()), + tool_description: Some("Performs a risky action.".to_string()), + codex_apps_meta: None, + }; + + let decision = maybe_request_mcp_tool_approval( + &session, + &turn_context, + "call-2-custom", + &invocation, + Some(&metadata), + AppToolApproval::Approve, + ) + .await; + + assert_eq!( + decision, + Some(McpToolApprovalDecision::BlockedBySafetyMonitor( + "Tool call was cancelled because of safety risks: high-risk action".to_string(), + )) + ); +} + #[tokio::test] async fn approve_mode_blocks_when_arc_returns_interrupt_without_annotations() { use wiremock::Mock; @@ -1203,7 +1398,7 @@ async fn approve_mode_blocks_when_arc_returns_interrupt_without_annotations() { } #[tokio::test] -async fn full_access_auto_mode_blocks_when_arc_returns_interrupt_for_model() { +async fn full_access_mode_skips_arc_monitor_for_all_approval_modes() { use wiremock::Mock; use wiremock::MockServer; use wiremock::ResponseTemplate; @@ -1224,7 +1419,7 @@ async fn full_access_auto_mode_blocks_when_arc_returns_interrupt_for_model() { "why": "high-risk action", }], }))) - .expect(1) + .expect(0) .mount(&server) .await; @@ -1261,22 +1456,23 @@ async fn full_access_auto_mode_blocks_when_arc_returns_interrupt_for_model() { codex_apps_meta: None, }; - let decision = maybe_request_mcp_tool_approval( - &session, - &turn_context, - "call-2", - &invocation, - Some(&metadata), + for approval_mode in [ AppToolApproval::Auto, - ) - .await; + AppToolApproval::Prompt, + AppToolApproval::Approve, + ] { + let decision = maybe_request_mcp_tool_approval( + &session, + &turn_context, + "call-2", + &invocation, + Some(&metadata), + approval_mode, + ) + .await; - assert_eq!( - decision, - Some(McpToolApprovalDecision::BlockedBySafetyMonitor( - "Tool call was cancelled because of safety risks: high-risk action".to_string(), - )) - ); + assert_eq!(decision, None); + } } #[tokio::test] diff --git a/codex-rs/core/src/plugins/manager_tests.rs b/codex-rs/core/src/plugins/manager_tests.rs index af33f90179..b845e085fb 100644 --- a/codex-rs/core/src/plugins/manager_tests.rs +++ b/codex-rs/core/src/plugins/manager_tests.rs @@ -164,6 +164,7 @@ fn load_plugins_loads_default_skills_and_mcp_servers() { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, )]), apps: vec![AppConnectorId("connector_example".to_string())], @@ -483,6 +484,7 @@ fn load_plugins_uses_manifest_configured_component_paths() { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, )]) ); @@ -586,6 +588,7 @@ fn load_plugins_ignores_manifest_component_paths_without_dot_slash() { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, )]) ); @@ -735,6 +738,7 @@ fn capability_index_filters_inactive_and_zero_capability_plugins() { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }; let plugin = |config_name: &str, dir_name: &str, manifest_name: &str| LoadedPlugin { config_name: config_name.to_string(), diff --git a/codex-rs/core/tests/suite/code_mode.rs b/codex-rs/core/tests/suite/code_mode.rs index fa8229ecc3..ae38261f1d 100644 --- a/codex-rs/core/tests/suite/code_mode.rs +++ b/codex-rs/core/tests/suite/code_mode.rs @@ -207,6 +207,7 @@ async fn run_code_mode_turn_with_rmcp( disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); config diff --git a/codex-rs/core/tests/suite/rmcp_client.rs b/codex-rs/core/tests/suite/rmcp_client.rs index 6cbf9521ba..431895e2e8 100644 --- a/codex-rs/core/tests/suite/rmcp_client.rs +++ b/codex-rs/core/tests/suite/rmcp_client.rs @@ -108,6 +108,7 @@ async fn stdio_server_round_trip() -> anyhow::Result<()> { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); config @@ -253,6 +254,7 @@ async fn stdio_image_responses_round_trip() -> anyhow::Result<()> { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); config @@ -476,6 +478,7 @@ async fn stdio_image_responses_are_sanitized_for_text_only_model() -> anyhow::Re disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); config @@ -597,6 +600,7 @@ async fn stdio_server_propagates_whitelisted_env_vars() -> anyhow::Result<()> { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); config @@ -759,6 +763,7 @@ async fn streamable_http_tool_call_round_trip() -> anyhow::Result<()> { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); config @@ -981,6 +986,7 @@ async fn streamable_http_with_oauth_round_trip_impl() -> anyhow::Result<()> { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); config diff --git a/codex-rs/core/tests/suite/sqlite_state.rs b/codex-rs/core/tests/suite/sqlite_state.rs index 2df92dbf95..d955f342ad 100644 --- a/codex-rs/core/tests/suite/sqlite_state.rs +++ b/codex-rs/core/tests/suite/sqlite_state.rs @@ -375,6 +375,7 @@ async fn mcp_call_marks_thread_memory_mode_polluted_when_configured() -> Result< disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); config diff --git a/codex-rs/core/tests/suite/truncation.rs b/codex-rs/core/tests/suite/truncation.rs index f10567de24..c3f019dd33 100644 --- a/codex-rs/core/tests/suite/truncation.rs +++ b/codex-rs/core/tests/suite/truncation.rs @@ -371,6 +371,7 @@ async fn mcp_tool_call_output_exceeds_limit_truncated_for_model() -> Result<()> disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); config @@ -466,6 +467,7 @@ async fn mcp_image_output_preserves_image_and_no_text_summary() -> Result<()> { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); config @@ -734,6 +736,7 @@ async fn mcp_tool_call_output_not_truncated_with_custom_limit() -> Result<()> { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, ); config diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 157e5feec9..2dee1e846b 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -2914,6 +2914,7 @@ mod tests { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }; let mut servers = config.mcp_servers.get().clone(); servers.insert("docs".to_string(), stdio_config); @@ -2938,6 +2939,7 @@ mod tests { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }; servers.insert("http".to_string(), http_config); config diff --git a/codex-rs/tui_app_server/src/history_cell.rs b/codex-rs/tui_app_server/src/history_cell.rs index 445d684469..7e37a6bf98 100644 --- a/codex-rs/tui_app_server/src/history_cell.rs +++ b/codex-rs/tui_app_server/src/history_cell.rs @@ -3143,6 +3143,7 @@ mod tests { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }; let mut servers = config.mcp_servers.get().clone(); servers.insert("docs".to_string(), stdio_config); @@ -3167,6 +3168,7 @@ mod tests { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }; servers.insert("http".to_string(), http_config); config @@ -3237,6 +3239,7 @@ mod tests { disabled_tools: None, scopes: None, oauth_resource: None, + tools: HashMap::new(), }, )]); config diff --git a/docs/config.md b/docs/config.md index d03fb98434..71f3548deb 100644 --- a/docs/config.md +++ b/docs/config.md @@ -12,6 +12,16 @@ Codex can connect to MCP servers configured in `~/.codex/config.toml`. See the c - https://developers.openai.com/codex/config-reference +## MCP tool approvals + +Codex stores per-tool approval overrides for custom MCP servers under +`mcp_servers` in `~/.codex/config.toml`: + +```toml +[mcp_servers.docs.tools.search] +approval_mode = "approve" +``` + ## Apps (Connectors) Use `$` in the composer to insert a ChatGPT connector; the popover lists accessible From c4d9887f9a11965221bb2b2dc98f68e46b2681e8 Mon Sep 17 00:00:00 2001 From: Andrei Eternal Date: Wed, 25 Mar 2026 19:18:03 -0700 Subject: [PATCH 004/212] [hooks] add non-streaming (non-stdin style) shell-only PostToolUse support (#15531) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CHAINED PR - note that base is eternal/hooks-pretooluse-bash, not main -- so the following PR should be first Matching post-tool hook to the pre-tool functionality here: https://github.com/openai/codex/pull/15211 So, PreToolUse calls for plain shell calls, allows blocking. This PostToolUse call runs after the command executed example run: ``` › as a test, run in parallel the following commands: - echo 'one' - echo '[block-pre-tool-use]' - echo '[block-post-tool-use]' ⚠ MCP startup incomplete (failed: notion, linear) • Cruising through those three commands in parallel now, and I’ll share the exact outputs right after they land. • Running PreToolUse hook: checking the observatory runes • Running PreToolUse hook: checking the observatory runes • Running PreToolUse hook: checking the observatory runes PreToolUse hook (blocked) warning: wizard-tower PreToolUse demo blocked a Bash command on purpose. feedback: PreToolUse demo blocked the command. Remove [block-pre-tool-use] to continue. PreToolUse hook (completed) warning: wizard-tower PreToolUse demo inspected Bash: echo 'one' PreToolUse hook (completed) warning: wizard-tower PreToolUse demo inspected Bash: echo '[block-post-tool-use]' • Ran echo '[block-post-tool-use]' └ [block-post-tool-use] • Ran echo 'one' └ one • Running PostToolUse hook: reading the observatory aftermath • Running PostToolUse hook: reading the observatory aftermath PostToolUse hook (blocked) warning: wizard-tower PostToolUse demo blocked the Bash follow-through on purpose. feedback: PostToolUse demo blocked the result after execution. Remove [block-post-tool-use] to continue. PostToolUse hook (completed) warning: wizard-tower PostToolUse demo inspected Bash: echo 'one' hook context: PostToolUse demo saw the Bash result. Response preview: one ────────────────────────────────────────────────────────────────────────────────────────────────────── • Ran them in parallel. Little wave report: - echo 'one' completed and returned one. - echo '[block-pre-tool-use]' was blocked before execution by the PreToolUse hook. - echo '[block-post-tool-use]' ran, but its result was blocked afterward by the PostToolUse hook. The hook messages were: - PreToolUse demo blocked the command. Remove [block-pre-tool-use] to continue. - PostToolUse demo blocked the result after execution. Remove [block-post-tool-use] to continue. › for the blocked messages (correctly blocked in this test) did the tool output land back into context? • Yeah, from this run: - PreToolUse block: the command itself did not execute, so no command output landed in context. Only the block message did. - PostToolUse block: the command did execute, but the actual stdout did not come back into context. Only the post-tool block message did. So the blocked notifications landed in context, but the blocked command payloads themselves did not. Nice clean guardrail, aloha. ``` --- .../schema/json/ServerNotification.json | 1 + .../codex_app_server_protocol.schemas.json | 1 + .../codex_app_server_protocol.v2.schemas.json | 1 + .../json/v2/HookCompletedNotification.json | 1 + .../json/v2/HookStartedNotification.json | 1 + .../schema/typescript/v2/HookEventName.ts | 2 +- .../app-server-protocol/src/protocol/v2.rs | 2 +- codex-rs/core/src/hook_runtime.rs | 30 + codex-rs/core/src/tools/context.rs | 19 + codex-rs/core/src/tools/handlers/shell.rs | 75 ++- .../core/src/tools/handlers/shell_tests.rs | 93 +++ .../core/src/tools/handlers/unified_exec.rs | 41 +- .../src/tools/handlers/unified_exec_tests.rs | 138 +++++ codex-rs/core/src/tools/registry.rs | 147 +++-- codex-rs/core/src/tools/registry_tests.rs | 63 -- codex-rs/core/tests/suite/hooks.rs | 542 +++++++++++++++++- codex-rs/deny.toml | 7 + .../post-tool-use.command.input.schema.json | 82 +++ .../post-tool-use.command.output.schema.json | 81 +++ .../pre-tool-use.command.output.schema.json | 1 + .../session-start.command.output.schema.json | 1 + ...r-prompt-submit.command.output.schema.json | 1 + codex-rs/hooks/src/engine/config.rs | 2 + codex-rs/hooks/src/engine/discovery.rs | 126 ++-- codex-rs/hooks/src/engine/dispatcher.rs | 24 +- codex-rs/hooks/src/engine/mod.rs | 17 + codex-rs/hooks/src/engine/output_parser.rs | 63 ++ codex-rs/hooks/src/engine/schema_loader.rs | 12 + codex-rs/hooks/src/events/common.rs | 8 +- codex-rs/hooks/src/events/mod.rs | 1 + codex-rs/hooks/src/events/post_tool_use.rs | 489 ++++++++++++++++ codex-rs/hooks/src/lib.rs | 2 + codex-rs/hooks/src/registry.rs | 13 + codex-rs/hooks/src/schema.rs | 93 ++- codex-rs/protocol/src/protocol.rs | 1 + codex-rs/tui/src/chatwidget.rs | 1 + ..._tool_use_hook_events_render_snapshot.snap | 9 + codex-rs/tui/src/chatwidget/tests.rs | 11 + .../tui/tests/suite/model_availability_nux.rs | 10 +- codex-rs/tui_app_server/src/chatwidget.rs | 1 + ..._tool_use_hook_events_render_snapshot.snap | 9 + .../tui_app_server/src/chatwidget/tests.rs | 11 + .../tests/suite/model_availability_nux.rs | 10 +- 43 files changed, 2078 insertions(+), 165 deletions(-) create mode 100644 codex-rs/hooks/schema/generated/post-tool-use.command.input.schema.json create mode 100644 codex-rs/hooks/schema/generated/post-tool-use.command.output.schema.json create mode 100644 codex-rs/hooks/src/events/post_tool_use.rs create mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__post_tool_use_hook_events_render_snapshot.snap create mode 100644 codex-rs/tui_app_server/src/chatwidget/snapshots/codex_tui_app_server__chatwidget__tests__post_tool_use_hook_events_render_snapshot.snap diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 37f7ff8c5f..8ca93137c6 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -1206,6 +1206,7 @@ "HookEventName": { "enum": [ "preToolUse", + "postToolUse", "sessionStart", "userPromptSubmit", "stop" 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 d4269f5239..6253c39297 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 @@ -8221,6 +8221,7 @@ "HookEventName": { "enum": [ "preToolUse", + "postToolUse", "sessionStart", "userPromptSubmit", "stop" diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index acf36d6c3c..5d053604f5 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -4892,6 +4892,7 @@ "HookEventName": { "enum": [ "preToolUse", + "postToolUse", "sessionStart", "userPromptSubmit", "stop" diff --git a/codex-rs/app-server-protocol/schema/json/v2/HookCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/HookCompletedNotification.json index 881c343601..bce797086c 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/HookCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/HookCompletedNotification.json @@ -4,6 +4,7 @@ "HookEventName": { "enum": [ "preToolUse", + "postToolUse", "sessionStart", "userPromptSubmit", "stop" diff --git a/codex-rs/app-server-protocol/schema/json/v2/HookStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/HookStartedNotification.json index 18fdb5008d..72f32d0d9d 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/HookStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/HookStartedNotification.json @@ -4,6 +4,7 @@ "HookEventName": { "enum": [ "preToolUse", + "postToolUse", "sessionStart", "userPromptSubmit", "stop" diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/HookEventName.ts b/codex-rs/app-server-protocol/schema/typescript/v2/HookEventName.ts index b75ee3930a..b97c709b98 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/HookEventName.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/HookEventName.ts @@ -2,4 +2,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type HookEventName = "preToolUse" | "sessionStart" | "userPromptSubmit" | "stop"; +export type HookEventName = "preToolUse" | "postToolUse" | "sessionStart" | "userPromptSubmit" | "stop"; diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 67c4e95856..147c91db2c 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -377,7 +377,7 @@ v2_enum_from_core!( v2_enum_from_core!( pub enum HookEventName from CoreHookEventName { - PreToolUse, SessionStart, UserPromptSubmit, Stop + PreToolUse, PostToolUse, SessionStart, UserPromptSubmit, Stop } ); diff --git a/codex-rs/core/src/hook_runtime.rs b/codex-rs/core/src/hook_runtime.rs index 744db4886b..ece93b1da1 100644 --- a/codex-rs/core/src/hook_runtime.rs +++ b/codex-rs/core/src/hook_runtime.rs @@ -1,6 +1,8 @@ use std::future::Future; use std::sync::Arc; +use codex_hooks::PostToolUseOutcome; +use codex_hooks::PostToolUseRequest; use codex_hooks::PreToolUseOutcome; use codex_hooks::PreToolUseRequest; use codex_hooks::SessionStartOutcome; @@ -15,6 +17,7 @@ use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::HookCompletedEvent; use codex_protocol::protocol::HookRunSummary; use codex_protocol::user_input::UserInput; +use serde_json::Value; use crate::codex::Session; use crate::codex::TurnContext; @@ -141,6 +144,33 @@ pub(crate) async fn run_pre_tool_use_hooks( if should_block { block_reason } else { None } } +pub(crate) async fn run_post_tool_use_hooks( + sess: &Arc, + turn_context: &Arc, + tool_use_id: String, + command: String, + tool_response: Value, +) -> PostToolUseOutcome { + let request = PostToolUseRequest { + session_id: sess.conversation_id, + turn_id: turn_context.sub_id.clone(), + cwd: turn_context.cwd.to_path_buf(), + transcript_path: sess.hook_transcript_path().await, + model: turn_context.model_info.slug.clone(), + permission_mode: hook_permission_mode(turn_context), + tool_name: "Bash".to_string(), + tool_use_id, + command, + tool_response, + }; + let preview_runs = sess.hooks().preview_post_tool_use(&request); + emit_hook_started_events(sess, turn_context, preview_runs).await; + + let outcome = sess.hooks().run_post_tool_use(request).await; + emit_hook_completed_events(sess, turn_context, outcome.hook_events.clone()).await; + outcome +} + pub(crate) async fn run_user_prompt_submit_hooks( sess: &Arc, turn_context: &Arc, diff --git a/codex-rs/core/src/tools/context.rs b/codex-rs/core/src/tools/context.rs index 12db451027..58d040cbe6 100644 --- a/codex-rs/core/src/tools/context.rs +++ b/codex-rs/core/src/tools/context.rs @@ -84,6 +84,10 @@ pub trait ToolOutput: Send { fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem; + fn post_tool_use_response(&self, _call_id: &str, _payload: &ToolPayload) -> Option { + None + } + fn code_mode_result(&self, payload: &ToolPayload) -> JsonValue { response_input_to_code_mode_result(self.to_response_item("", payload)) } @@ -158,6 +162,7 @@ impl ToolOutput for ToolSearchOutput { pub struct FunctionToolOutput { pub body: Vec, pub success: Option, + pub post_tool_use_response: Option, } impl FunctionToolOutput { @@ -165,6 +170,7 @@ impl FunctionToolOutput { Self { body: vec![FunctionCallOutputContentItem::InputText { text }], success, + post_tool_use_response: None, } } @@ -175,6 +181,7 @@ impl FunctionToolOutput { Self { body: content, success, + post_tool_use_response: None, } } @@ -197,6 +204,10 @@ impl ToolOutput for FunctionToolOutput { fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem { function_tool_response(call_id, payload, self.body.clone(), self.success) } + + fn post_tool_use_response(&self, _call_id: &str, _payload: &ToolPayload) -> Option { + self.post_tool_use_response.clone() + } } pub struct ApplyPatchToolOutput { @@ -305,6 +316,14 @@ impl ToolOutput for ExecCommandToolOutput { ) } + fn post_tool_use_response(&self, _call_id: &str, _payload: &ToolPayload) -> Option { + if self.process_id.is_some() || self.session_command.is_none() { + return None; + } + + Some(JsonValue::String(self.truncated_output())) + } + fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue { #[derive(Serialize)] struct UnifiedExecCodeModeResult { diff --git a/codex-rs/core/src/tools/handlers/shell.rs b/codex-rs/core/src/tools/handlers/shell.rs index 3c8bbe1320..7f97f419d9 100644 --- a/codex-rs/core/src/tools/handlers/shell.rs +++ b/codex-rs/core/src/tools/handlers/shell.rs @@ -2,6 +2,7 @@ use async_trait::async_trait; use codex_protocol::ThreadId; use codex_protocol::models::ShellCommandToolCallParams; use codex_protocol::models::ShellToolCallParams; +use serde_json::Value as JsonValue; use std::sync::Arc; use crate::codex::TurnContext; @@ -16,6 +17,7 @@ use crate::protocol::ExecCommandSource; use crate::shell::Shell; use crate::tools::context::FunctionToolOutput; 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; @@ -23,9 +25,12 @@ use crate::tools::handlers::apply_granted_turn_permissions; use crate::tools::handlers::apply_patch::intercept_apply_patch; use crate::tools::handlers::implicit_granted_permissions; use crate::tools::handlers::normalize_and_validate_additional_permissions; +use crate::tools::handlers::parse_arguments; use crate::tools::handlers::parse_arguments_with_base_path; use crate::tools::handlers::resolve_workdir_base_path; use crate::tools::orchestrator::ToolOrchestrator; +use crate::tools::registry::PostToolUsePayload; +use crate::tools::registry::PreToolUsePayload; use crate::tools::registry::ToolHandler; use crate::tools::registry::ToolKind; use crate::tools::runtimes::shell::ShellRequest; @@ -48,6 +53,28 @@ pub struct ShellCommandHandler { backend: ShellCommandBackend, } +fn shell_payload_command(payload: &ToolPayload) -> Option { + match payload { + ToolPayload::Function { arguments } => parse_arguments::(arguments) + .ok() + .map(|params| codex_shell_command::parse_command::shlex_join(¶ms.command)), + ToolPayload::LocalShell { params } => Some(codex_shell_command::parse_command::shlex_join( + ¶ms.command, + )), + _ => None, + } +} + +fn shell_command_payload_command(payload: &ToolPayload) -> Option { + let ToolPayload::Function { arguments } = payload else { + return None; + }; + + parse_arguments::(arguments) + .ok() + .map(|params| params.command) +} + struct RunExecLikeArgs { tool_name: String, exec_params: ExecParams, @@ -178,6 +205,23 @@ impl ToolHandler for ShellHandler { } } + fn pre_tool_use_payload(&self, invocation: &ToolInvocation) -> Option { + shell_payload_command(&invocation.payload).map(|command| PreToolUsePayload { command }) + } + + fn post_tool_use_payload( + &self, + call_id: &str, + payload: &ToolPayload, + result: &dyn ToolOutput, + ) -> Option { + let tool_response = result.post_tool_use_response(call_id, payload)?; + Some(PostToolUsePayload { + command: shell_payload_command(payload)?, + tool_response, + }) + } + async fn handle(&self, invocation: ToolInvocation) -> Result { let ToolInvocation { session, @@ -268,6 +312,24 @@ impl ToolHandler for ShellCommandHandler { .unwrap_or(true) } + fn pre_tool_use_payload(&self, invocation: &ToolInvocation) -> Option { + shell_command_payload_command(&invocation.payload) + .map(|command| PreToolUsePayload { command }) + } + + fn post_tool_use_payload( + &self, + call_id: &str, + payload: &ToolPayload, + result: &dyn ToolOutput, + ) -> Option { + let tool_response = result.post_tool_use_response(call_id, payload)?; + Some(PostToolUsePayload { + command: shell_command_payload_command(payload)?, + tool_response, + }) + } + async fn handle(&self, invocation: ToolInvocation) -> Result { let ToolInvocation { session, @@ -493,8 +555,19 @@ impl ShellHandler { &call_id, /*turn_diff_tracker*/ None, ); + let post_tool_use_response = out + .as_ref() + .ok() + .map(|output| crate::tools::format_exec_output_str(output, turn.truncation_policy)) + .map(JsonValue::String); let content = emitter.finish(event_ctx, out).await?; - Ok(FunctionToolOutput::from_text(content, Some(true))) + Ok(FunctionToolOutput { + body: vec![ + codex_protocol::models::FunctionCallOutputContentItem::InputText { text: content }, + ], + success: Some(true), + post_tool_use_response, + }) } } diff --git a/codex-rs/core/src/tools/handlers/shell_tests.rs b/codex-rs/core/src/tools/handlers/shell_tests.rs index b69f3be230..fdc015c5e7 100644 --- a/codex-rs/core/src/tools/handlers/shell_tests.rs +++ b/codex-rs/core/src/tools/handlers/shell_tests.rs @@ -13,7 +13,15 @@ use crate::sandboxing::SandboxPermissions; use crate::shell::Shell; use crate::shell::ShellType; use crate::shell_snapshot::ShellSnapshot; +use crate::tools::context::FunctionToolOutput; +use crate::tools::context::ToolInvocation; +use crate::tools::context::ToolPayload; use crate::tools::handlers::ShellCommandHandler; +use crate::tools::handlers::ShellHandler; +use crate::tools::registry::ToolHandler; +use crate::turn_diff_tracker::TurnDiffTracker; +use serde_json::json; +use tokio::sync::Mutex; use tokio::sync::watch; /// The logic for is_known_safe_command() has heuristics for known shells, @@ -178,3 +186,88 @@ fn shell_command_handler_rejects_login_when_disallowed() { "unexpected error: {err}" ); } + +#[tokio::test] +async fn shell_pre_tool_use_payload_uses_joined_command() { + let payload = ToolPayload::LocalShell { + params: codex_protocol::models::ShellToolCallParams { + command: vec![ + "bash".to_string(), + "-lc".to_string(), + "printf hi".to_string(), + ], + workdir: None, + timeout_ms: None, + sandbox_permissions: None, + prefix_rule: None, + additional_permissions: None, + justification: None, + }, + }; + let (session, turn) = make_session_and_context().await; + let handler = ShellHandler; + + assert_eq!( + handler.pre_tool_use_payload(&ToolInvocation { + session: session.into(), + turn: turn.into(), + tracker: Arc::new(Mutex::new(TurnDiffTracker::new())), + call_id: "call-41".to_string(), + tool_name: "shell".to_string(), + tool_namespace: None, + payload, + }), + Some(crate::tools::registry::PreToolUsePayload { + command: "bash -lc 'printf hi'".to_string(), + }) + ); +} + +#[tokio::test] +async fn shell_command_pre_tool_use_payload_uses_raw_command() { + let payload = ToolPayload::Function { + arguments: json!({ "command": "printf shell command" }).to_string(), + }; + let (session, turn) = make_session_and_context().await; + let handler = ShellCommandHandler { + backend: super::ShellCommandBackend::Classic, + }; + + assert_eq!( + handler.pre_tool_use_payload(&ToolInvocation { + session: session.into(), + turn: turn.into(), + tracker: Arc::new(Mutex::new(TurnDiffTracker::new())), + call_id: "call-42".to_string(), + tool_name: "shell_command".to_string(), + tool_namespace: None, + payload, + }), + Some(crate::tools::registry::PreToolUsePayload { + command: "printf shell command".to_string(), + }) + ); +} + +#[test] +fn build_post_tool_use_payload_uses_tool_output_wire_value() { + let payload = ToolPayload::Function { + arguments: json!({ "command": "printf shell command" }).to_string(), + }; + let output = FunctionToolOutput { + body: vec![], + success: Some(true), + post_tool_use_response: Some(json!("shell output")), + }; + let handler = ShellCommandHandler { + backend: super::ShellCommandBackend::Classic, + }; + + assert_eq!( + handler.post_tool_use_payload("call-42", &payload, &output), + Some(crate::tools::registry::PostToolUsePayload { + command: "printf shell command".to_string(), + tool_response: json!("shell output"), + }) + ); +} diff --git a/codex-rs/core/src/tools/handlers/unified_exec.rs b/codex-rs/core/src/tools/handlers/unified_exec.rs index 463168808e..b512a878b6 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec.rs @@ -8,6 +8,7 @@ use crate::shell::Shell; use crate::shell::get_shell_by_model_provided_path; use crate::tools::context::ExecCommandToolOutput; use crate::tools::context::ToolInvocation; +use crate::tools::context::ToolOutput; use crate::tools::context::ToolPayload; use crate::tools::handlers::apply_granted_turn_permissions; use crate::tools::handlers::apply_patch::intercept_apply_patch; @@ -16,6 +17,8 @@ use crate::tools::handlers::normalize_and_validate_additional_permissions; use crate::tools::handlers::parse_arguments; use crate::tools::handlers::parse_arguments_with_base_path; use crate::tools::handlers::resolve_workdir_base_path; +use crate::tools::registry::PostToolUsePayload; +use crate::tools::registry::PreToolUsePayload; use crate::tools::registry::ToolHandler; use crate::tools::registry::ToolKind; use crate::tools::spec::UnifiedExecShellMode; @@ -104,7 +107,7 @@ impl ToolHandler for UnifiedExecHandler { return true; }; - let Ok(params) = serde_json::from_str::(arguments) else { + let Ok(params) = parse_arguments::(arguments) else { return true; }; let command = match get_command( @@ -119,6 +122,42 @@ impl ToolHandler for UnifiedExecHandler { !is_known_safe_command(&command) } + fn pre_tool_use_payload(&self, invocation: &ToolInvocation) -> Option { + if invocation.tool_name != "exec_command" { + return None; + } + + let ToolPayload::Function { arguments } = &invocation.payload else { + return None; + }; + + parse_arguments::(arguments) + .ok() + .map(|args| PreToolUsePayload { command: args.cmd }) + } + + fn post_tool_use_payload( + &self, + call_id: &str, + payload: &ToolPayload, + result: &dyn ToolOutput, + ) -> Option { + let ToolPayload::Function { arguments } = payload else { + return None; + }; + + let args = parse_arguments::(arguments).ok()?; + if args.tty { + return None; + } + + let tool_response = result.post_tool_use_response(call_id, payload)?; + Some(PostToolUsePayload { + command: args.cmd, + tool_response, + }) + } + async fn handle(&self, invocation: ToolInvocation) -> Result { let ToolInvocation { session, diff --git a/codex-rs/core/src/tools/handlers/unified_exec_tests.rs b/codex-rs/core/src/tools/handlers/unified_exec_tests.rs index fbd2cb1081..2390068cc5 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec_tests.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec_tests.rs @@ -11,6 +11,14 @@ use std::fs; use std::sync::Arc; use tempfile::tempdir; +use crate::codex::make_session_and_context; +use crate::tools::context::ExecCommandToolOutput; +use crate::tools::context::ToolInvocation; +use crate::tools::context::ToolPayload; +use crate::tools::registry::ToolHandler; +use crate::turn_diff_tracker::TurnDiffTracker; +use tokio::sync::Mutex; + #[test] fn test_get_command_uses_default_shell_when_unspecified() -> anyhow::Result<()> { let json = r#"{"cmd": "echo hello"}"#; @@ -182,3 +190,133 @@ fn exec_command_args_resolve_relative_additional_permissions_against_workdir() - ); Ok(()) } + +#[tokio::test] +async fn exec_command_pre_tool_use_payload_uses_raw_command() { + let payload = ToolPayload::Function { + arguments: serde_json::json!({ "cmd": "printf exec command" }).to_string(), + }; + let (session, turn) = make_session_and_context().await; + let handler = UnifiedExecHandler; + + assert_eq!( + handler.pre_tool_use_payload(&ToolInvocation { + session: session.into(), + turn: turn.into(), + tracker: Arc::new(Mutex::new(TurnDiffTracker::new())), + call_id: "call-43".to_string(), + tool_name: "exec_command".to_string(), + tool_namespace: None, + payload, + }), + Some(crate::tools::registry::PreToolUsePayload { + command: "printf exec command".to_string(), + }) + ); +} + +#[tokio::test] +async fn exec_command_pre_tool_use_payload_skips_write_stdin() { + let payload = ToolPayload::Function { + arguments: serde_json::json!({ "chars": "echo hi" }).to_string(), + }; + let (session, turn) = make_session_and_context().await; + let handler = UnifiedExecHandler; + + assert_eq!( + handler.pre_tool_use_payload(&ToolInvocation { + session: session.into(), + turn: turn.into(), + tracker: Arc::new(Mutex::new(TurnDiffTracker::new())), + call_id: "call-44".to_string(), + tool_name: "write_stdin".to_string(), + tool_namespace: None, + payload, + }), + None + ); +} + +#[test] +fn exec_command_post_tool_use_payload_uses_output_for_noninteractive_one_shot_commands() { + let payload = ToolPayload::Function { + arguments: serde_json::json!({ "cmd": "echo three", "tty": false }).to_string(), + }; + let output = ExecCommandToolOutput { + event_call_id: "event-43".to_string(), + chunk_id: "chunk-1".to_string(), + wall_time: std::time::Duration::from_millis(498), + raw_output: b"three".to_vec(), + max_output_tokens: None, + process_id: None, + exit_code: Some(0), + original_token_count: None, + session_command: Some(vec![ + "/bin/zsh".to_string(), + "-lc".to_string(), + "echo three".to_string(), + ]), + }; + + assert_eq!( + UnifiedExecHandler.post_tool_use_payload("call-43", &payload, &output), + Some(crate::tools::registry::PostToolUsePayload { + command: "echo three".to_string(), + tool_response: serde_json::json!("three"), + }) + ); +} + +#[test] +fn exec_command_post_tool_use_payload_skips_interactive_exec() { + let payload = ToolPayload::Function { + arguments: serde_json::json!({ "cmd": "echo three", "tty": true }).to_string(), + }; + let output = ExecCommandToolOutput { + event_call_id: "event-44".to_string(), + chunk_id: "chunk-1".to_string(), + wall_time: std::time::Duration::from_millis(498), + raw_output: b"three".to_vec(), + max_output_tokens: None, + process_id: None, + exit_code: Some(0), + original_token_count: None, + session_command: Some(vec![ + "/bin/zsh".to_string(), + "-lc".to_string(), + "echo three".to_string(), + ]), + }; + + assert_eq!( + UnifiedExecHandler.post_tool_use_payload("call-44", &payload, &output), + None + ); +} + +#[test] +fn exec_command_post_tool_use_payload_skips_running_sessions() { + let payload = ToolPayload::Function { + arguments: serde_json::json!({ "cmd": "echo three", "tty": false }).to_string(), + }; + let output = ExecCommandToolOutput { + event_call_id: "event-45".to_string(), + chunk_id: "chunk-1".to_string(), + wall_time: std::time::Duration::from_millis(498), + raw_output: b"three".to_vec(), + max_output_tokens: None, + process_id: Some(45), + exit_code: None, + original_token_count: None, + session_command: Some(vec![ + "/bin/zsh".to_string(), + "-lc".to_string(), + "echo three".to_string(), + ]), + }; + + assert_eq!( + UnifiedExecHandler.post_tool_use_payload("call-45", &payload, &output), + None + ); +} diff --git a/codex-rs/core/src/tools/registry.rs b/codex-rs/core/src/tools/registry.rs index df97d7128d..aa7f401099 100644 --- a/codex-rs/core/src/tools/registry.rs +++ b/codex-rs/core/src/tools/registry.rs @@ -5,10 +5,13 @@ use std::time::Instant; use crate::client_common::tools::ToolSpec; use crate::function_tool::FunctionCallError; +use crate::hook_runtime::record_additional_contexts; +use crate::hook_runtime::run_post_tool_use_hooks; use crate::hook_runtime::run_pre_tool_use_hooks; use crate::memories::usage::emit_metric_for_tool_read; use crate::protocol::SandboxPolicy; use crate::sandbox_tags::sandbox_tag; +use crate::tools::context::FunctionToolOutput; use crate::tools::context::ToolInvocation; use crate::tools::context::ToolOutput; use crate::tools::context::ToolPayload; @@ -21,10 +24,8 @@ use codex_hooks::HookToolInput; use codex_hooks::HookToolInputLocalShell; use codex_hooks::HookToolKind; use codex_protocol::models::ResponseInputItem; -use codex_protocol::models::ShellCommandToolCallParams; -use codex_protocol::models::ShellToolCallParams; use codex_utils_readiness::Readiness; -use serde::Deserialize; +use serde_json::Value; use tracing::warn; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -56,6 +57,19 @@ pub trait ToolHandler: Send + Sync { false } + fn pre_tool_use_payload(&self, _invocation: &ToolInvocation) -> Option { + None + } + + fn post_tool_use_payload( + &self, + _call_id: &str, + _payload: &ToolPayload, + _result: &dyn ToolOutput, + ) -> Option { + None + } + /// Perform the actual [ToolInvocation] and returns a [ToolOutput] containing /// the final output to return to the model. async fn handle(&self, invocation: ToolInvocation) -> Result; @@ -73,6 +87,7 @@ impl AnyToolResult { call_id, payload, result, + .. } = self; result.to_response_item(&call_id, &payload) } @@ -85,12 +100,32 @@ impl AnyToolResult { } } +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct PreToolUsePayload { + pub(crate) command: String, +} + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct PostToolUsePayload { + pub(crate) command: String, + pub(crate) tool_response: Value, +} + #[async_trait] trait AnyToolHandler: Send + Sync { fn matches_kind(&self, payload: &ToolPayload) -> bool; async fn is_mutating(&self, invocation: &ToolInvocation) -> bool; + fn pre_tool_use_payload(&self, invocation: &ToolInvocation) -> Option; + + fn post_tool_use_payload( + &self, + call_id: &str, + payload: &ToolPayload, + result: &dyn ToolOutput, + ) -> Option; + async fn handle_any( &self, invocation: ToolInvocation, @@ -110,6 +145,19 @@ where ToolHandler::is_mutating(self, invocation).await } + fn pre_tool_use_payload(&self, invocation: &ToolInvocation) -> Option { + ToolHandler::pre_tool_use_payload(self, invocation) + } + + fn post_tool_use_payload( + &self, + call_id: &str, + payload: &ToolPayload, + result: &dyn ToolOutput, + ) -> Option { + ToolHandler::post_tool_use_payload(self, call_id, payload, result) + } + async fn handle_any( &self, invocation: ToolInvocation, @@ -247,17 +295,18 @@ impl ToolRegistry { return Err(FunctionCallError::Fatal(message)); } - if let Some(command) = pre_tool_use_command(tool_name.as_ref(), &invocation.payload) + if let Some(pre_tool_use_payload) = handler.pre_tool_use_payload(&invocation) && let Some(reason) = run_pre_tool_use_hooks( &invocation.session, &invocation.turn, invocation.call_id.clone(), - command.clone(), + pre_tool_use_payload.command.clone(), ) .await { return Err(FunctionCallError::RespondToModel(format!( - "Bash command blocked by hook: {reason}. Command: {command}" + "Command blocked by PreToolUse hook: {reason}. Command: {}", + pre_tool_use_payload.command ))); } @@ -303,6 +352,33 @@ impl ToolRegistry { Err(err) => (err.to_string(), false), }; emit_metric_for_tool_read(&invocation, success).await; + let post_tool_use_payload = if success { + let guard = response_cell.lock().await; + guard.as_ref().and_then(|result| { + handler.post_tool_use_payload( + &result.call_id, + &result.payload, + result.result.as_ref(), + ) + }) + } else { + None + }; + let post_tool_use_outcome = if let Some(post_tool_use_payload) = post_tool_use_payload { + Some( + run_post_tool_use_hooks( + &invocation.session, + &invocation.turn, + invocation.call_id.clone(), + post_tool_use_payload.command, + post_tool_use_payload.tool_response, + ) + .await, + ) + } else { + None + }; + // Deprecated: this is the legacy AfterToolUse hook. Prefer the new PostToolUse let hook_abort_error = dispatch_after_tool_use_hook(AfterToolUseHookDispatch { invocation: &invocation, output_preview, @@ -317,6 +393,36 @@ impl ToolRegistry { return Err(err); } + if let Some(outcome) = &post_tool_use_outcome { + record_additional_contexts( + &invocation.session, + &invocation.turn, + outcome.additional_contexts.clone(), + ) + .await; + + let replacement_text = if outcome.should_stop { + Some( + outcome + .feedback_message + .clone() + .or_else(|| outcome.stop_reason.clone()) + .unwrap_or_else(|| "PostToolUse hook stopped execution".to_string()), + ) + } else { + outcome.feedback_message.clone() + }; + if let Some(replacement_text) = replacement_text { + let mut guard = response_cell.lock().await; + if let Some(result) = guard.as_mut() { + result.result = Box::new(FunctionToolOutput::from_text( + replacement_text, + /*success*/ None, + )); + } + } + } + match result { Ok(_) => { let mut guard = response_cell.lock().await; @@ -431,35 +537,6 @@ fn sandbox_policy_tag(policy: &SandboxPolicy) -> &'static str { } } -#[derive(Deserialize)] -struct PreToolUseExecCommandArgs { - cmd: String, -} - -fn pre_tool_use_command(tool_name: &str, payload: &ToolPayload) -> Option { - match (tool_name, payload) { - ("shell" | "container.exec", ToolPayload::Function { arguments }) => { - serde_json::from_str::(arguments) - .ok() - .map(|params| codex_shell_command::parse_command::shlex_join(¶ms.command)) - } - ("local_shell", ToolPayload::LocalShell { params }) => Some( - codex_shell_command::parse_command::shlex_join(¶ms.command), - ), - ("shell_command", ToolPayload::Function { arguments }) => { - serde_json::from_str::(arguments) - .ok() - .map(|params| params.command) - } - ("exec_command", ToolPayload::Function { arguments }) => { - serde_json::from_str::(arguments) - .ok() - .map(|params| params.cmd) - } - _ => None, - } -} - // Hooks use a separate wire-facing input type so hook payload JSON stays stable // and decoupled from core's internal tool runtime representation. impl From<&ToolPayload> for HookToolInput { diff --git a/codex-rs/core/src/tools/registry_tests.rs b/codex-rs/core/src/tools/registry_tests.rs index 46e7d0c3f6..301828206e 100644 --- a/codex-rs/core/src/tools/registry_tests.rs +++ b/codex-rs/core/src/tools/registry_tests.rs @@ -1,8 +1,5 @@ use super::*; -use crate::tools::context::ToolInvocation; -use crate::tools::context::ToolPayload; use async_trait::async_trait; -use codex_protocol::models::ShellToolCallParams; use pretty_assertions::assert_eq; struct TestHandler; @@ -50,63 +47,3 @@ fn handler_looks_up_namespaced_aliases_explicitly() { .is_some_and(|handler| Arc::ptr_eq(handler, &namespaced_handler)) ); } - -#[test] -fn pre_tool_use_command_uses_raw_shell_command_input() { - let payload = ToolPayload::Function { - arguments: serde_json::json!({ "command": "printf shell command" }).to_string(), - }; - - assert_eq!( - pre_tool_use_command("shell_command", &payload), - Some("printf shell command".to_string()) - ); -} - -#[test] -fn pre_tool_use_command_shell_joins_vector_input() { - let payload = ToolPayload::LocalShell { - params: ShellToolCallParams { - command: vec![ - "bash".to_string(), - "-lc".to_string(), - "printf hi".to_string(), - ], - workdir: None, - timeout_ms: None, - sandbox_permissions: None, - prefix_rule: None, - additional_permissions: None, - justification: None, - }, - }; - - assert_eq!( - pre_tool_use_command("local_shell", &payload), - Some("bash -lc 'printf hi'".to_string()) - ); -} - -#[test] -fn pre_tool_use_command_uses_raw_exec_command_input() { - let payload = ToolPayload::Function { - arguments: serde_json::json!({ "cmd": "printf exec command" }).to_string(), - }; - - assert_eq!( - pre_tool_use_command("exec_command", &payload), - Some("printf exec command".to_string()) - ); -} - -#[test] -fn pre_tool_use_command_skips_non_shell_tools() { - let payload = ToolPayload::Function { - arguments: serde_json::json!({ - "plan": [{ "step": "watch the tide", "status": "pending" }] - }) - .to_string(), - }; - - assert_eq!(pre_tool_use_command("update_plan", &payload), None); -} diff --git a/codex-rs/core/tests/suite/hooks.rs b/codex-rs/core/tests/suite/hooks.rs index c7de5dcb26..5172097bf3 100644 --- a/codex-rs/core/tests/suite/hooks.rs +++ b/codex-rs/core/tests/suite/hooks.rs @@ -237,6 +237,78 @@ elif mode == "exit_2": Ok(()) } +fn write_post_tool_use_hook( + home: &Path, + matcher: Option<&str>, + mode: &str, + reason: &str, +) -> Result<()> { + let script_path = home.join("post_tool_use_hook.py"); + let log_path = home.join("post_tool_use_hook_log.jsonl"); + let mode_json = serde_json::to_string(mode).context("serialize post tool use mode")?; + let reason_json = serde_json::to_string(reason).context("serialize post tool use reason")?; + let script = format!( + r#"import json +from pathlib import Path +import sys + +log_path = Path(r"{log_path}") +mode = {mode_json} +reason = {reason_json} + +payload = json.load(sys.stdin) + +with log_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(payload) + "\n") + +if mode == "context": + print(json.dumps({{ + "hookSpecificOutput": {{ + "hookEventName": "PostToolUse", + "additionalContext": reason + }} + }})) +elif mode == "decision_block": + print(json.dumps({{ + "decision": "block", + "reason": reason + }})) +elif mode == "continue_false": + print(json.dumps({{ + "continue": False, + "stopReason": reason + }})) +elif mode == "exit_2": + sys.stderr.write(reason + "\n") + raise SystemExit(2) +"#, + log_path = log_path.display(), + mode_json = mode_json, + reason_json = reason_json, + ); + + let mut group = serde_json::json!({ + "hooks": [{ + "type": "command", + "command": format!("python3 {}", script_path.display()), + "statusMessage": "running post tool use hook", + }] + }); + if let Some(matcher) = matcher { + group["matcher"] = Value::String(matcher.to_string()); + } + + let hooks = serde_json::json!({ + "hooks": { + "PostToolUse": [group] + } + }); + + fs::write(&script_path, script).context("write post tool use hook script")?; + fs::write(home.join("hooks.json"), hooks.to_string()).context("write hooks.json")?; + Ok(()) +} + fn write_session_start_hook_recording_transcript(home: &Path) -> Result<()> { let script_path = home.join("session_start_hook.py"); let log_path = home.join("session_start_hook_log.jsonl"); @@ -325,6 +397,15 @@ fn read_pre_tool_use_hook_inputs(home: &Path) -> Result> .collect() } +fn read_post_tool_use_hook_inputs(home: &Path) -> Result> { + fs::read_to_string(home.join("post_tool_use_hook_log.jsonl")) + .context("read post tool use hook log")? + .lines() + .filter(|line| !line.trim().is_empty()) + .map(|line| serde_json::from_str(line).context("parse post tool use hook log line")) + .collect() +} + fn read_session_start_hook_inputs(home: &Path) -> Result> { fs::read_to_string(home.join("session_start_hook_log.jsonl")) .context("read session start hook log")? @@ -986,7 +1067,7 @@ async fn pre_tool_use_blocks_shell_command_before_execution() -> Result<()> { .and_then(Value::as_str) .expect("shell command output string"); assert!( - output.contains("Bash command blocked by hook: blocked by pre hook"), + output.contains("Command blocked by PreToolUse hook: blocked by pre hook"), "blocked tool output should surface the hook reason", ); assert!( @@ -1088,7 +1169,7 @@ async fn pre_tool_use_blocks_local_shell_before_execution() -> Result<()> { .and_then(Value::as_str) .expect("local shell output string"); assert!( - output.contains("Bash command blocked by hook: blocked local shell"), + output.contains("Command blocked by PreToolUse hook: blocked local shell"), "blocked local shell output should surface the hook reason", ); assert!( @@ -1183,7 +1264,7 @@ async fn pre_tool_use_blocks_exec_command_before_execution() -> Result<()> { .and_then(Value::as_str) .expect("exec command output string"); assert!( - output.contains("Bash command blocked by hook: blocked exec command"), + output.contains("Command blocked by PreToolUse hook: blocked exec command"), "blocked exec command output should surface the hook reason", ); assert!( @@ -1275,3 +1356,458 @@ async fn pre_tool_use_does_not_fire_for_non_shell_tools() -> Result<()> { Ok(()) } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn post_tool_use_records_additional_context_for_shell_command() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let call_id = "posttooluse-shell-command"; + let command = "printf post-tool-output".to_string(); + let args = serde_json::json!({ "command": command }); + let responses = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-1"), + core_test_support::responses::ev_function_call( + call_id, + "shell_command", + &serde_json::to_string(&args)?, + ), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_response_created("resp-2"), + ev_assistant_message("msg-1", "post hook context observed"), + ev_completed("resp-2"), + ]), + ], + ) + .await; + + let post_context = "Remember the bash post-tool note."; + let mut builder = test_codex() + .with_pre_build_hook(|home| { + if let Err(error) = + write_post_tool_use_hook(home, Some("^Bash$"), "context", post_context) + { + panic!("failed to write post tool use hook test fixture: {error}"); + } + }) + .with_config(|config| { + config + .features + .enable(Feature::CodexHooks) + .expect("test config should allow feature update"); + }); + let test = builder.build(&server).await?; + + test.submit_turn("run the shell command with post hook") + .await?; + + let requests = responses.requests(); + assert_eq!(requests.len(), 2); + assert!( + requests[1] + .message_input_texts("developer") + .contains(&post_context.to_string()), + "follow-up request should include post tool use additional context", + ); + let output_item = requests[1].function_call_output(call_id); + let output = output_item + .get("output") + .and_then(Value::as_str) + .expect("shell command output string"); + assert!( + output.contains("post-tool-output"), + "shell command output should still reach the model", + ); + + let hook_inputs = read_post_tool_use_hook_inputs(test.codex_home_path())?; + assert_eq!(hook_inputs.len(), 1); + assert_eq!(hook_inputs[0]["hook_event_name"], "PostToolUse"); + assert_eq!(hook_inputs[0]["tool_name"], "Bash"); + assert_eq!(hook_inputs[0]["tool_use_id"], call_id); + assert_eq!(hook_inputs[0]["tool_input"]["command"], command); + assert_eq!( + hook_inputs[0]["tool_response"], + Value::String("post-tool-output".to_string()) + ); + let transcript_path = hook_inputs[0]["transcript_path"] + .as_str() + .expect("post tool use hook transcript_path"); + assert!( + !transcript_path.is_empty(), + "post tool use hook should receive a non-empty transcript_path", + ); + assert!( + Path::new(transcript_path).exists(), + "post tool use hook transcript_path should be materialized on disk", + ); + assert!( + hook_inputs[0]["turn_id"] + .as_str() + .is_some_and(|turn_id| !turn_id.is_empty()) + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn post_tool_use_block_decision_replaces_shell_command_output_with_reason() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let call_id = "posttooluse-shell-command-block"; + let command = "printf blocked-output".to_string(); + let args = serde_json::json!({ "command": command }); + let responses = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-1"), + core_test_support::responses::ev_function_call( + call_id, + "shell_command", + &serde_json::to_string(&args)?, + ), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_response_created("resp-2"), + ev_assistant_message("msg-1", "post hook feedback observed"), + ev_completed("resp-2"), + ]), + ], + ) + .await; + + let reason = "bash output looked sketchy"; + let mut builder = test_codex() + .with_pre_build_hook(|home| { + if let Err(error) = + write_post_tool_use_hook(home, Some("^Bash$"), "decision_block", reason) + { + panic!("failed to write post tool use hook test fixture: {error}"); + } + }) + .with_config(|config| { + config + .features + .enable(Feature::CodexHooks) + .expect("test config should allow feature update"); + }); + let test = builder.build(&server).await?; + + test.submit_turn("run the shell command with blocking post hook") + .await?; + + let requests = responses.requests(); + assert_eq!(requests.len(), 2); + let output_item = requests[1].function_call_output(call_id); + let output = output_item + .get("output") + .and_then(Value::as_str) + .expect("shell command output string"); + assert_eq!(output, reason); + + let hook_inputs = read_post_tool_use_hook_inputs(test.codex_home_path())?; + assert_eq!(hook_inputs.len(), 1); + assert_eq!( + hook_inputs[0]["tool_response"], + Value::String("blocked-output".to_string()) + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn post_tool_use_continue_false_replaces_shell_command_output_with_stop_reason() -> Result<()> +{ + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let call_id = "posttooluse-shell-command-stop"; + let command = "printf stop-output".to_string(); + let args = serde_json::json!({ "command": command }); + let responses = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-1"), + core_test_support::responses::ev_function_call( + call_id, + "shell_command", + &serde_json::to_string(&args)?, + ), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_response_created("resp-2"), + ev_assistant_message("msg-1", "post hook stop observed"), + ev_completed("resp-2"), + ]), + ], + ) + .await; + + let stop_reason = "Execution halted by post-tool hook"; + let mut builder = test_codex() + .with_pre_build_hook(|home| { + if let Err(error) = + write_post_tool_use_hook(home, Some("^Bash$"), "continue_false", stop_reason) + { + panic!("failed to write post tool use hook test fixture: {error}"); + } + }) + .with_config(|config| { + config + .features + .enable(Feature::CodexHooks) + .expect("test config should allow feature update"); + }); + let test = builder.build(&server).await?; + + test.submit_turn("run the shell command with stop-style post hook") + .await?; + + let requests = responses.requests(); + assert_eq!(requests.len(), 2); + let output_item = requests[1].function_call_output(call_id); + let output = output_item + .get("output") + .and_then(Value::as_str) + .expect("shell command output string"); + assert_eq!(output, stop_reason); + + let hook_inputs = read_post_tool_use_hook_inputs(test.codex_home_path())?; + assert_eq!(hook_inputs.len(), 1); + assert_eq!( + hook_inputs[0]["tool_response"], + Value::String("stop-output".to_string()) + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn post_tool_use_records_additional_context_for_local_shell() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let call_id = "posttooluse-local-shell"; + let command = vec![ + "/bin/sh".to_string(), + "-c".to_string(), + "printf local-post-tool-output".to_string(), + ]; + let responses = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-1"), + core_test_support::responses::ev_local_shell_call( + call_id, + "completed", + command.iter().map(String::as_str).collect(), + ), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_response_created("resp-2"), + ev_assistant_message("msg-1", "local shell post hook context observed"), + ev_completed("resp-2"), + ]), + ], + ) + .await; + + let post_context = "Remember the local shell post-tool note."; + let mut builder = test_codex() + .with_pre_build_hook(|home| { + if let Err(error) = + write_post_tool_use_hook(home, Some("^Bash$"), "context", post_context) + { + panic!("failed to write post tool use hook test fixture: {error}"); + } + }) + .with_config(|config| { + config + .features + .enable(Feature::CodexHooks) + .expect("test config should allow feature update"); + }); + let test = builder.build(&server).await?; + + test.submit_turn("run the local shell command with post hook") + .await?; + + let requests = responses.requests(); + assert_eq!(requests.len(), 2); + assert!( + requests[1] + .message_input_texts("developer") + .contains(&post_context.to_string()), + "follow-up request should include local shell post tool use additional context", + ); + let hook_inputs = read_post_tool_use_hook_inputs(test.codex_home_path())?; + assert_eq!(hook_inputs.len(), 1); + assert_eq!( + hook_inputs[0]["tool_input"]["command"], + codex_shell_command::parse_command::shlex_join(&command), + ); + assert_eq!( + hook_inputs[0]["tool_response"], + Value::String("local-post-tool-output".to_string()), + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn post_tool_use_exit_two_replaces_one_shot_exec_command_output_with_feedback() -> Result<()> +{ + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let call_id = "posttooluse-exec-command"; + let command = "printf post-hook-output".to_string(); + let args = serde_json::json!({ "cmd": command, "tty": false }); + let responses = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-1"), + core_test_support::responses::ev_function_call( + call_id, + "exec_command", + &serde_json::to_string(&args)?, + ), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_response_created("resp-2"), + ev_assistant_message("msg-1", "post hook blocked the exec result"), + ev_completed("resp-2"), + ]), + ], + ) + .await; + + let mut builder = test_codex() + .with_pre_build_hook(|home| { + if let Err(error) = + write_post_tool_use_hook(home, Some("^Bash$"), "exit_2", "blocked by post hook") + { + panic!("failed to write post tool use hook test fixture: {error}"); + } + }) + .with_config(|config| { + config.use_experimental_unified_exec_tool = true; + config + .features + .enable(Feature::CodexHooks) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::UnifiedExec) + .expect("test config should allow feature update"); + }); + let test = builder.build(&server).await?; + + test.submit_turn("run the exec command with post hook") + .await?; + + let requests = responses.requests(); + assert_eq!(requests.len(), 2); + let output_item = requests[1].function_call_output(call_id); + let output = output_item + .get("output") + .and_then(Value::as_str) + .expect("exec command output string"); + assert_eq!(output, "blocked by post hook"); + + let hook_inputs = read_post_tool_use_hook_inputs(test.codex_home_path())?; + assert_eq!(hook_inputs.len(), 1); + assert_eq!(hook_inputs[0]["tool_use_id"], call_id); + assert_eq!(hook_inputs[0]["tool_input"]["command"], command); + assert_eq!( + hook_inputs[0]["tool_response"], + Value::String("post-hook-output".to_string()) + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn post_tool_use_does_not_fire_for_non_shell_tools() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let call_id = "posttooluse-update-plan"; + let args = serde_json::json!({ + "plan": [{ + "step": "watch the tide", + "status": "pending", + }] + }); + let responses = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-1"), + core_test_support::responses::ev_function_call( + call_id, + "update_plan", + &serde_json::to_string(&args)?, + ), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_response_created("resp-2"), + ev_assistant_message("msg-1", "plan updated"), + ev_completed("resp-2"), + ]), + ], + ) + .await; + + let mut builder = test_codex() + .with_pre_build_hook(|home| { + if let Err(error) = + write_post_tool_use_hook(home, None, "decision_block", "should not fire") + { + panic!("failed to write post tool use hook test fixture: {error}"); + } + }) + .with_config(|config| { + config + .features + .enable(Feature::CodexHooks) + .expect("test config should allow feature update"); + }); + let test = builder.build(&server).await?; + + test.submit_turn("update the plan").await?; + + let requests = responses.requests(); + assert_eq!(requests.len(), 2); + let output_item = requests[1].function_call_output(call_id); + let output = output_item + .get("output") + .and_then(Value::as_str) + .expect("update plan output string"); + assert!( + !output.contains("should not fire"), + "non-shell tool output should not be affected by PostToolUse", + ); + + let hook_log_path = test.codex_home_path().join("post_tool_use_hook_log.jsonl"); + assert!( + !hook_log_path.exists(), + "non-shell tools should not trigger post tool use hooks", + ); + + Ok(()) +} diff --git a/codex-rs/deny.toml b/codex-rs/deny.toml index bad1c8f92e..f91e11e25b 100644 --- a/codex-rs/deny.toml +++ b/codex-rs/deny.toml @@ -73,6 +73,13 @@ ignore = [ { id = "RUSTSEC-2024-0388", reason = "derivative is unmaintained; pulled in via starlark v0.13.0 used by execpolicy/cli/core; no fixed release yet" }, { id = "RUSTSEC-2025-0057", reason = "fxhash is unmaintained; pulled in via starlark_map/starlark v0.13.0 used by execpolicy/cli/core; no fixed release yet" }, { id = "RUSTSEC-2024-0436", reason = "paste is unmaintained; pulled in via ratatui/rmcp/starlark used by tui/execpolicy; no fixed release yet" }, + # TODO: remove these exceptions once the workspace updates aws-lc-rs/aws-lc-sys past the affected releases. + { id = "RUSTSEC-2026-0044", reason = "aws-lc-rs/aws-lc-sys are pulled in transitively via rustls stack dependencies; upgrade will be handled separately from this hooks PR" }, + { id = "RUSTSEC-2026-0045", reason = "aws-lc-rs/aws-lc-sys are pulled in transitively via rustls stack dependencies; upgrade will be handled separately from this hooks PR" }, + { id = "RUSTSEC-2026-0046", reason = "aws-lc-rs/aws-lc-sys are pulled in transitively via rustls stack dependencies; upgrade will be handled separately from this hooks PR" }, + { id = "RUSTSEC-2026-0047", reason = "aws-lc-rs/aws-lc-sys are pulled in transitively via rustls stack dependencies; upgrade will be handled separately from this hooks PR" }, + { id = "RUSTSEC-2026-0048", reason = "aws-lc-rs/aws-lc-sys are pulled in transitively via rustls stack dependencies; upgrade will be handled separately from this hooks PR" }, + { id = "RUSTSEC-2026-0049", reason = "aws-lc-rs/aws-lc-sys are pulled in transitively via rustls stack dependencies; upgrade will be handled separately from this hooks PR" }, # TODO(fcoury): remove this exception when syntect drops yaml-rust and bincode, or updates to versions that have fixed the vulnerabilities. { id = "RUSTSEC-2024-0320", reason = "yaml-rust is unmaintained; pulled in via syntect v5.3.0 used by codex-tui for syntax highlighting; no fixed release yet" }, { id = "RUSTSEC-2025-0141", reason = "bincode is unmaintained; pulled in via syntect v5.3.0 used by codex-tui for syntax highlighting; no fixed release yet" }, diff --git a/codex-rs/hooks/schema/generated/post-tool-use.command.input.schema.json b/codex-rs/hooks/schema/generated/post-tool-use.command.input.schema.json new file mode 100644 index 0000000000..e8a87c1f5e --- /dev/null +++ b/codex-rs/hooks/schema/generated/post-tool-use.command.input.schema.json @@ -0,0 +1,82 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "additionalProperties": false, + "definitions": { + "NullableString": { + "type": [ + "string", + "null" + ] + }, + "PostToolUseToolInput": { + "additionalProperties": false, + "properties": { + "command": { + "type": "string" + } + }, + "required": [ + "command" + ], + "type": "object" + } + }, + "properties": { + "cwd": { + "type": "string" + }, + "hook_event_name": { + "const": "PostToolUse", + "type": "string" + }, + "model": { + "type": "string" + }, + "permission_mode": { + "enum": [ + "default", + "acceptEdits", + "plan", + "dontAsk", + "bypassPermissions" + ], + "type": "string" + }, + "session_id": { + "type": "string" + }, + "tool_input": { + "$ref": "#/definitions/PostToolUseToolInput" + }, + "tool_name": { + "const": "Bash", + "type": "string" + }, + "tool_response": true, + "tool_use_id": { + "type": "string" + }, + "transcript_path": { + "$ref": "#/definitions/NullableString" + }, + "turn_id": { + "description": "Codex extension: expose the active turn id to internal turn-scoped hooks.", + "type": "string" + } + }, + "required": [ + "cwd", + "hook_event_name", + "model", + "permission_mode", + "session_id", + "tool_input", + "tool_name", + "tool_response", + "tool_use_id", + "transcript_path", + "turn_id" + ], + "title": "post-tool-use.command.input", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/hooks/schema/generated/post-tool-use.command.output.schema.json b/codex-rs/hooks/schema/generated/post-tool-use.command.output.schema.json new file mode 100644 index 0000000000..dc0425a755 --- /dev/null +++ b/codex-rs/hooks/schema/generated/post-tool-use.command.output.schema.json @@ -0,0 +1,81 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "additionalProperties": false, + "definitions": { + "BlockDecisionWire": { + "enum": [ + "block" + ], + "type": "string" + }, + "HookEventNameWire": { + "enum": [ + "PreToolUse", + "PostToolUse", + "SessionStart", + "UserPromptSubmit", + "Stop" + ], + "type": "string" + }, + "PostToolUseHookSpecificOutputWire": { + "additionalProperties": false, + "properties": { + "additionalContext": { + "default": null, + "type": "string" + }, + "hookEventName": { + "$ref": "#/definitions/HookEventNameWire" + }, + "updatedMCPToolOutput": { + "default": null + } + }, + "required": [ + "hookEventName" + ], + "type": "object" + } + }, + "properties": { + "continue": { + "default": true, + "type": "boolean" + }, + "decision": { + "allOf": [ + { + "$ref": "#/definitions/BlockDecisionWire" + } + ], + "default": null + }, + "hookSpecificOutput": { + "allOf": [ + { + "$ref": "#/definitions/PostToolUseHookSpecificOutputWire" + } + ], + "default": null + }, + "reason": { + "default": null, + "type": "string" + }, + "stopReason": { + "default": null, + "type": "string" + }, + "suppressOutput": { + "default": false, + "type": "boolean" + }, + "systemMessage": { + "default": null, + "type": "string" + } + }, + "title": "post-tool-use.command.output", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/hooks/schema/generated/pre-tool-use.command.output.schema.json b/codex-rs/hooks/schema/generated/pre-tool-use.command.output.schema.json index 0992983fe4..a7ff1d5f7a 100644 --- a/codex-rs/hooks/schema/generated/pre-tool-use.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/pre-tool-use.command.output.schema.json @@ -5,6 +5,7 @@ "HookEventNameWire": { "enum": [ "PreToolUse", + "PostToolUse", "SessionStart", "UserPromptSubmit", "Stop" diff --git a/codex-rs/hooks/schema/generated/session-start.command.output.schema.json b/codex-rs/hooks/schema/generated/session-start.command.output.schema.json index f44928983d..d79ab2a9a0 100644 --- a/codex-rs/hooks/schema/generated/session-start.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/session-start.command.output.schema.json @@ -5,6 +5,7 @@ "HookEventNameWire": { "enum": [ "PreToolUse", + "PostToolUse", "SessionStart", "UserPromptSubmit", "Stop" diff --git a/codex-rs/hooks/schema/generated/user-prompt-submit.command.output.schema.json b/codex-rs/hooks/schema/generated/user-prompt-submit.command.output.schema.json index 27878752c1..4f63bec89e 100644 --- a/codex-rs/hooks/schema/generated/user-prompt-submit.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/user-prompt-submit.command.output.schema.json @@ -11,6 +11,7 @@ "HookEventNameWire": { "enum": [ "PreToolUse", + "PostToolUse", "SessionStart", "UserPromptSubmit", "Stop" diff --git a/codex-rs/hooks/src/engine/config.rs b/codex-rs/hooks/src/engine/config.rs index 1a2d962bc8..839fee825c 100644 --- a/codex-rs/hooks/src/engine/config.rs +++ b/codex-rs/hooks/src/engine/config.rs @@ -10,6 +10,8 @@ pub(crate) struct HooksFile { pub(crate) struct HookEvents { #[serde(rename = "PreToolUse", default)] pub pre_tool_use: Vec, + #[serde(rename = "PostToolUse", default)] + pub post_tool_use: Vec, #[serde(rename = "SessionStart", default)] pub session_start: Vec, #[serde(rename = "UserPromptSubmit", default)] diff --git a/codex-rs/hooks/src/engine/discovery.rs b/codex-rs/hooks/src/engine/discovery.rs index 55dfca63cd..f39eb77438 100644 --- a/codex-rs/hooks/src/engine/discovery.rs +++ b/codex-rs/hooks/src/engine/discovery.rs @@ -7,6 +7,7 @@ use codex_config::ConfigLayerStackOrdering; use super::ConfiguredHandler; use super::config::HookHandlerConfig; use super::config::HooksFile; +use super::config::MatcherGroup; use crate::events::common::matcher_pattern_for_event; use crate::events::common::validate_matcher_pattern; @@ -70,63 +71,40 @@ pub(crate) fn discover_handlers(config_layer_stack: Option<&ConfigLayerStack>) - } }; - for group in parsed.hooks.pre_tool_use { - append_group_handlers( - &mut handlers, - &mut warnings, - &mut display_order, - source_path.as_path(), + let super::config::HookEvents { + pre_tool_use, + post_tool_use, + session_start, + user_prompt_submit, + stop, + } = parsed.hooks; + + for (event_name, groups) in [ + ( codex_protocol::protocol::HookEventName::PreToolUse, - matcher_pattern_for_event( - codex_protocol::protocol::HookEventName::PreToolUse, - group.matcher.as_deref(), - ), - group.hooks, - ); - } - - for group in parsed.hooks.session_start { - append_group_handlers( - &mut handlers, - &mut warnings, - &mut display_order, - source_path.as_path(), + pre_tool_use, + ), + ( + codex_protocol::protocol::HookEventName::PostToolUse, + post_tool_use, + ), + ( codex_protocol::protocol::HookEventName::SessionStart, - matcher_pattern_for_event( - codex_protocol::protocol::HookEventName::SessionStart, - group.matcher.as_deref(), - ), - group.hooks, - ); - } - - for group in parsed.hooks.user_prompt_submit { - append_group_handlers( - &mut handlers, - &mut warnings, - &mut display_order, - source_path.as_path(), + session_start, + ), + ( codex_protocol::protocol::HookEventName::UserPromptSubmit, - matcher_pattern_for_event( - codex_protocol::protocol::HookEventName::UserPromptSubmit, - group.matcher.as_deref(), - ), - group.hooks, - ); - } - - for group in parsed.hooks.stop { - append_group_handlers( + user_prompt_submit, + ), + (codex_protocol::protocol::HookEventName::Stop, stop), + ] { + append_matcher_groups( &mut handlers, &mut warnings, &mut display_order, source_path.as_path(), - codex_protocol::protocol::HookEventName::Stop, - matcher_pattern_for_event( - codex_protocol::protocol::HookEventName::Stop, - group.matcher.as_deref(), - ), - group.hooks, + event_name, + groups, ); } } @@ -199,6 +177,27 @@ fn append_group_handlers( } } +fn append_matcher_groups( + handlers: &mut Vec, + warnings: &mut Vec, + display_order: &mut i64, + source_path: &Path, + event_name: codex_protocol::protocol::HookEventName, + groups: Vec, +) { + for group in groups { + append_group_handlers( + handlers, + warnings, + display_order, + source_path, + event_name, + matcher_pattern_for_event(event_name, group.matcher.as_deref()), + group.hooks, + ); + } +} + #[cfg(test)] mod tests { use std::path::Path; @@ -309,4 +308,31 @@ mod tests { assert_eq!(handlers.len(), 1); assert_eq!(handlers[0].matcher.as_deref(), Some("*")); } + + #[test] + fn post_tool_use_keeps_valid_matcher_during_discovery() { + let mut handlers = Vec::new(); + let mut warnings = Vec::new(); + let mut display_order = 0; + + append_group_handlers( + &mut handlers, + &mut warnings, + &mut display_order, + Path::new("/tmp/hooks.json"), + HookEventName::PostToolUse, + matcher_pattern_for_event(HookEventName::PostToolUse, Some("Edit|Write")), + vec![HookHandlerConfig::Command { + command: "echo hello".to_string(), + timeout_sec: None, + r#async: false, + status_message: None, + }], + ); + + assert_eq!(warnings, Vec::::new()); + assert_eq!(handlers.len(), 1); + assert_eq!(handlers[0].event_name, HookEventName::PostToolUse); + assert_eq!(handlers[0].matcher.as_deref(), Some("Edit|Write")); + } } diff --git a/codex-rs/hooks/src/engine/dispatcher.rs b/codex-rs/hooks/src/engine/dispatcher.rs index 0b29e12fa0..133fc48982 100644 --- a/codex-rs/hooks/src/engine/dispatcher.rs +++ b/codex-rs/hooks/src/engine/dispatcher.rs @@ -31,7 +31,9 @@ pub(crate) fn select_handlers( .iter() .filter(|handler| handler.event_name == event_name) .filter(|handler| match event_name { - HookEventName::PreToolUse | HookEventName::SessionStart => { + HookEventName::PreToolUse + | HookEventName::PostToolUse + | HookEventName::SessionStart => { matches_matcher(handler.matcher.as_deref(), matcher_input) } HookEventName::UserPromptSubmit | HookEventName::Stop => true, @@ -106,9 +108,10 @@ pub(crate) fn completed_summary( fn scope_for_event(event_name: HookEventName) -> HookScope { match event_name { HookEventName::SessionStart => HookScope::Thread, - HookEventName::PreToolUse | HookEventName::UserPromptSubmit | HookEventName::Stop => { - HookScope::Turn - } + HookEventName::PreToolUse + | HookEventName::PostToolUse + | HookEventName::UserPromptSubmit + | HookEventName::Stop => HookScope::Turn, } } @@ -184,6 +187,19 @@ mod tests { assert_eq!(selected[0].display_order, 0); } + #[test] + fn post_tool_use_matches_tool_name() { + let handlers = vec![ + make_handler(HookEventName::PostToolUse, Some("^Bash$"), "echo same", 0), + make_handler(HookEventName::PostToolUse, Some("^Edit$"), "echo same", 1), + ]; + + let selected = select_handlers(&handlers, HookEventName::PostToolUse, Some("Bash")); + + assert_eq!(selected.len(), 1); + assert_eq!(selected[0].display_order, 0); + } + #[test] fn pre_tool_use_star_matcher_matches_all_tools() { let handlers = vec![ diff --git a/codex-rs/hooks/src/engine/mod.rs b/codex-rs/hooks/src/engine/mod.rs index f54403b74b..f91fee24c9 100644 --- a/codex-rs/hooks/src/engine/mod.rs +++ b/codex-rs/hooks/src/engine/mod.rs @@ -10,6 +10,8 @@ use std::path::PathBuf; use codex_config::ConfigLayerStack; use codex_protocol::protocol::HookRunSummary; +use crate::events::post_tool_use::PostToolUseOutcome; +use crate::events::post_tool_use::PostToolUseRequest; use crate::events::pre_tool_use::PreToolUseOutcome; use crate::events::pre_tool_use::PreToolUseRequest; use crate::events::session_start::SessionStartOutcome; @@ -49,6 +51,7 @@ impl ConfiguredHandler { fn event_name_label(&self) -> &'static str { match self.event_name { codex_protocol::protocol::HookEventName::PreToolUse => "pre-tool-use", + codex_protocol::protocol::HookEventName::PostToolUse => "post-tool-use", codex_protocol::protocol::HookEventName::SessionStart => "session-start", codex_protocol::protocol::HookEventName::UserPromptSubmit => "user-prompt-submit", codex_protocol::protocol::HookEventName::Stop => "stop", @@ -112,6 +115,13 @@ impl ClaudeHooksEngine { crate::events::pre_tool_use::preview(&self.handlers, request) } + pub(crate) fn preview_post_tool_use( + &self, + request: &PostToolUseRequest, + ) -> Vec { + crate::events::post_tool_use::preview(&self.handlers, request) + } + pub(crate) async fn run_session_start( &self, request: SessionStartRequest, @@ -124,6 +134,13 @@ impl ClaudeHooksEngine { crate::events::pre_tool_use::run(&self.handlers, &self.shell, request).await } + pub(crate) async fn run_post_tool_use( + &self, + request: PostToolUseRequest, + ) -> PostToolUseOutcome { + crate::events::post_tool_use::run(&self.handlers, &self.shell, request).await + } + pub(crate) fn preview_user_prompt_submit( &self, request: &UserPromptSubmitRequest, diff --git a/codex-rs/hooks/src/engine/output_parser.rs b/codex-rs/hooks/src/engine/output_parser.rs index 3fc0e7a0ba..dd9ab64160 100644 --- a/codex-rs/hooks/src/engine/output_parser.rs +++ b/codex-rs/hooks/src/engine/output_parser.rs @@ -19,6 +19,16 @@ pub(crate) struct PreToolUseOutput { pub invalid_reason: Option, } +#[derive(Debug, Clone)] +pub(crate) struct PostToolUseOutput { + pub universal: UniversalOutput, + pub should_block: bool, + pub reason: Option, + pub invalid_block_reason: Option, + pub additional_context: Option, + pub invalid_reason: Option, +} + #[derive(Debug, Clone)] pub(crate) struct UserPromptSubmitOutput { pub universal: UniversalOutput, @@ -38,6 +48,7 @@ pub(crate) struct StopOutput { use crate::schema::BlockDecisionWire; use crate::schema::HookUniversalOutputWire; +use crate::schema::PostToolUseCommandOutputWire; use crate::schema::PreToolUseCommandOutputWire; use crate::schema::PreToolUseDecisionWire; use crate::schema::PreToolUsePermissionDecisionWire; @@ -104,6 +115,40 @@ pub(crate) fn parse_pre_tool_use(stdout: &str) -> Option { }) } +pub(crate) fn parse_post_tool_use(stdout: &str) -> Option { + let wire: PostToolUseCommandOutputWire = parse_json(stdout)?; + let universal = UniversalOutput::from(wire.universal); + let invalid_reason = unsupported_post_tool_use_universal(&universal).or_else(|| { + wire.hook_specific_output + .as_ref() + .and_then(unsupported_post_tool_use_hook_specific_output) + }); + let should_block = matches!(wire.decision, Some(BlockDecisionWire::Block)); + let invalid_block_reason = if should_block + && match wire.reason.as_deref() { + Some(reason) => reason.trim().is_empty(), + None => true, + } { + Some(invalid_block_message("PostToolUse")) + } else if !should_block && universal.continue_processing && wire.reason.is_some() { + Some("PostToolUse hook returned reason without decision".to_string()) + } else { + None + }; + let additional_context = wire + .hook_specific_output + .and_then(|output| output.additional_context); + + Some(PostToolUseOutput { + universal, + should_block: should_block && invalid_reason.is_none() && invalid_block_reason.is_none(), + reason: wire.reason, + invalid_block_reason, + additional_context, + invalid_reason, + }) +} + pub(crate) fn parse_user_prompt_submit(stdout: &str) -> Option { let wire: UserPromptSubmitCommandOutputWire = parse_json(stdout)?; let should_block = matches!(wire.decision, Some(BlockDecisionWire::Block)); @@ -190,6 +235,24 @@ fn unsupported_pre_tool_use_universal(universal: &UniversalOutput) -> Option Option { + if universal.suppress_output { + Some("PostToolUse hook returned unsupported suppressOutput".to_string()) + } else { + None + } +} + +fn unsupported_post_tool_use_hook_specific_output( + output: &crate::schema::PostToolUseHookSpecificOutputWire, +) -> Option { + if output.updated_mcp_tool_output.is_some() { + Some("PostToolUse hook returned unsupported updatedMCPToolOutput".to_string()) + } else { + None + } +} + fn unsupported_pre_tool_use_hook_specific_output( output: &crate::schema::PreToolUseHookSpecificOutputWire, ) -> Option { diff --git a/codex-rs/hooks/src/engine/schema_loader.rs b/codex-rs/hooks/src/engine/schema_loader.rs index 1a51e59527..644d1dd46d 100644 --- a/codex-rs/hooks/src/engine/schema_loader.rs +++ b/codex-rs/hooks/src/engine/schema_loader.rs @@ -4,6 +4,8 @@ use serde_json::Value; #[allow(dead_code)] pub(crate) struct GeneratedHookSchemas { + pub post_tool_use_command_input: Value, + pub post_tool_use_command_output: Value, pub pre_tool_use_command_input: Value, pub pre_tool_use_command_output: Value, pub session_start_command_input: Value, @@ -17,6 +19,14 @@ pub(crate) struct GeneratedHookSchemas { pub(crate) fn generated_hook_schemas() -> &'static GeneratedHookSchemas { static SCHEMAS: OnceLock = OnceLock::new(); SCHEMAS.get_or_init(|| GeneratedHookSchemas { + post_tool_use_command_input: parse_json_schema( + "post-tool-use.command.input", + include_str!("../../schema/generated/post-tool-use.command.input.schema.json"), + ), + post_tool_use_command_output: parse_json_schema( + "post-tool-use.command.output", + include_str!("../../schema/generated/post-tool-use.command.output.schema.json"), + ), pre_tool_use_command_input: parse_json_schema( "pre-tool-use.command.input", include_str!("../../schema/generated/pre-tool-use.command.input.schema.json"), @@ -66,6 +76,8 @@ mod tests { fn loads_generated_hook_schemas() { let schemas = generated_hook_schemas(); + assert_eq!(schemas.post_tool_use_command_input["type"], "object"); + assert_eq!(schemas.post_tool_use_command_output["type"], "object"); assert_eq!(schemas.pre_tool_use_command_input["type"], "object"); assert_eq!(schemas.pre_tool_use_command_output["type"], "object"); assert_eq!(schemas.session_start_command_input["type"], "object"); diff --git a/codex-rs/hooks/src/events/common.rs b/codex-rs/hooks/src/events/common.rs index b4c274bbd3..48fbed2422 100644 --- a/codex-rs/hooks/src/events/common.rs +++ b/codex-rs/hooks/src/events/common.rs @@ -74,7 +74,9 @@ pub(crate) fn matcher_pattern_for_event( matcher: Option<&str>, ) -> Option<&str> { match event_name { - HookEventName::PreToolUse | HookEventName::SessionStart => matcher, + HookEventName::PreToolUse | HookEventName::PostToolUse | HookEventName::SessionStart => { + matcher + } HookEventName::UserPromptSubmit | HookEventName::Stop => None, } } @@ -172,6 +174,10 @@ mod tests { matcher_pattern_for_event(HookEventName::PreToolUse, Some("Bash")), Some("Bash") ); + assert_eq!( + matcher_pattern_for_event(HookEventName::PostToolUse, Some("Edit|Write")), + Some("Edit|Write") + ); assert_eq!( matcher_pattern_for_event(HookEventName::SessionStart, Some("startup|resume")), Some("startup|resume") diff --git a/codex-rs/hooks/src/events/mod.rs b/codex-rs/hooks/src/events/mod.rs index 603395eb5a..0d2e6d31c4 100644 --- a/codex-rs/hooks/src/events/mod.rs +++ b/codex-rs/hooks/src/events/mod.rs @@ -1,4 +1,5 @@ pub(crate) mod common; +pub mod post_tool_use; pub mod pre_tool_use; pub mod session_start; pub mod stop; diff --git a/codex-rs/hooks/src/events/post_tool_use.rs b/codex-rs/hooks/src/events/post_tool_use.rs new file mode 100644 index 0000000000..3af9bef5e5 --- /dev/null +++ b/codex-rs/hooks/src/events/post_tool_use.rs @@ -0,0 +1,489 @@ +use std::path::PathBuf; + +use codex_protocol::ThreadId; +use codex_protocol::protocol::HookCompletedEvent; +use codex_protocol::protocol::HookEventName; +use codex_protocol::protocol::HookOutputEntry; +use codex_protocol::protocol::HookOutputEntryKind; +use codex_protocol::protocol::HookRunStatus; +use codex_protocol::protocol::HookRunSummary; +use serde_json::Value; + +use super::common; +use crate::engine::CommandShell; +use crate::engine::ConfiguredHandler; +use crate::engine::command_runner::CommandRunResult; +use crate::engine::dispatcher; +use crate::engine::output_parser; +use crate::schema::PostToolUseCommandInput; +use crate::schema::PostToolUseToolInput; + +#[derive(Debug, Clone)] +pub struct PostToolUseRequest { + pub session_id: ThreadId, + pub turn_id: String, + pub cwd: PathBuf, + pub transcript_path: Option, + pub model: String, + pub permission_mode: String, + pub tool_name: String, + pub tool_use_id: String, + pub command: String, + pub tool_response: Value, +} + +#[derive(Debug)] +pub struct PostToolUseOutcome { + pub hook_events: Vec, + pub should_stop: bool, + pub stop_reason: Option, + pub additional_contexts: Vec, + pub feedback_message: Option, +} + +#[derive(Debug, Default, PartialEq, Eq)] +struct PostToolUseHandlerData { + should_stop: bool, + stop_reason: Option, + additional_contexts_for_model: Vec, + feedback_messages_for_model: Vec, +} + +pub(crate) fn preview( + handlers: &[ConfiguredHandler], + request: &PostToolUseRequest, +) -> Vec { + dispatcher::select_handlers( + handlers, + HookEventName::PostToolUse, + Some(&request.tool_name), + ) + .into_iter() + .map(|handler| dispatcher::running_summary(&handler)) + .collect() +} + +pub(crate) async fn run( + handlers: &[ConfiguredHandler], + shell: &CommandShell, + request: PostToolUseRequest, +) -> PostToolUseOutcome { + let matched = dispatcher::select_handlers( + handlers, + HookEventName::PostToolUse, + Some(&request.tool_name), + ); + if matched.is_empty() { + return PostToolUseOutcome { + hook_events: Vec::new(), + should_stop: false, + stop_reason: None, + additional_contexts: Vec::new(), + feedback_message: None, + }; + } + + let input_json = match serde_json::to_string(&PostToolUseCommandInput { + session_id: request.session_id.to_string(), + turn_id: request.turn_id.clone(), + transcript_path: crate::schema::NullableString::from_path(request.transcript_path.clone()), + cwd: request.cwd.display().to_string(), + hook_event_name: "PostToolUse".to_string(), + model: request.model.clone(), + permission_mode: request.permission_mode.clone(), + tool_name: "Bash".to_string(), + tool_input: PostToolUseToolInput { + command: request.command.clone(), + }, + tool_response: request.tool_response.clone(), + tool_use_id: request.tool_use_id.clone(), + }) { + Ok(input_json) => input_json, + Err(error) => { + return serialization_failure_outcome(common::serialization_failure_hook_events( + matched, + Some(request.turn_id), + format!("failed to serialize post tool use hook input: {error}"), + )); + } + }; + + let results = dispatcher::execute_handlers( + shell, + matched, + input_json, + request.cwd.as_path(), + Some(request.turn_id), + parse_completed, + ) + .await; + + let additional_contexts = common::flatten_additional_contexts( + results + .iter() + .map(|result| result.data.additional_contexts_for_model.as_slice()), + ); + let should_stop = results.iter().any(|result| result.data.should_stop); + let stop_reason = results + .iter() + .find_map(|result| result.data.stop_reason.clone()); + let feedback_message = common::join_text_chunks( + results + .iter() + .flat_map(|result| result.data.feedback_messages_for_model.clone()) + .collect(), + ); + + PostToolUseOutcome { + hook_events: results.into_iter().map(|result| result.completed).collect(), + should_stop, + stop_reason, + additional_contexts, + feedback_message, + } +} + +fn parse_completed( + handler: &ConfiguredHandler, + run_result: CommandRunResult, + turn_id: Option, +) -> dispatcher::ParsedHandler { + let mut entries = Vec::new(); + let mut status = HookRunStatus::Completed; + let mut should_stop = false; + let mut stop_reason = None; + let mut additional_contexts_for_model = Vec::new(); + let mut feedback_messages_for_model = Vec::new(); + + match run_result.error.as_deref() { + Some(error) => { + status = HookRunStatus::Failed; + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: error.to_string(), + }); + } + None => match run_result.exit_code { + Some(0) => { + let trimmed_stdout = run_result.stdout.trim(); + if trimmed_stdout.is_empty() { + } else if let Some(parsed) = output_parser::parse_post_tool_use(&run_result.stdout) + { + if let Some(system_message) = parsed.universal.system_message { + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Warning, + text: system_message, + }); + } + if parsed.invalid_reason.is_none() + && parsed.invalid_block_reason.is_none() + && let Some(additional_context) = parsed.additional_context + { + common::append_additional_context( + &mut entries, + &mut additional_contexts_for_model, + additional_context, + ); + } + if !parsed.universal.continue_processing { + status = HookRunStatus::Stopped; + should_stop = true; + stop_reason = parsed.universal.stop_reason.clone(); + let stop_text = parsed + .universal + .stop_reason + .unwrap_or_else(|| "PostToolUse hook stopped execution".to_string()); + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Stop, + text: stop_text.clone(), + }); + let model_feedback = parsed + .reason + .as_deref() + .and_then(common::trimmed_non_empty) + .unwrap_or(stop_text); + feedback_messages_for_model.push(model_feedback); + } else if let Some(invalid_reason) = parsed.invalid_reason { + status = HookRunStatus::Failed; + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: invalid_reason, + }); + } else if let Some(invalid_block_reason) = parsed.invalid_block_reason { + status = HookRunStatus::Failed; + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: invalid_block_reason, + }); + } else if parsed.should_block { + status = HookRunStatus::Blocked; + if let Some(reason) = parsed.reason { + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Feedback, + text: reason.clone(), + }); + feedback_messages_for_model.push(reason); + } + } + } else if trimmed_stdout.starts_with('{') || trimmed_stdout.starts_with('[') { + status = HookRunStatus::Failed; + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: "hook returned invalid post-tool-use JSON output".to_string(), + }); + } + } + Some(2) => { + if let Some(reason) = common::trimmed_non_empty(&run_result.stderr) { + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Feedback, + text: reason.clone(), + }); + feedback_messages_for_model.push(reason); + } else { + status = HookRunStatus::Failed; + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: "PostToolUse hook exited with code 2 but did not write feedback to stderr".to_string(), + }); + } + } + Some(exit_code) => { + status = HookRunStatus::Failed; + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: format!("hook exited with code {exit_code}"), + }); + } + None => { + status = HookRunStatus::Failed; + entries.push(HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: "hook exited without a status code".to_string(), + }); + } + }, + } + + let completed = HookCompletedEvent { + turn_id, + run: dispatcher::completed_summary(handler, &run_result, status, entries), + }; + + dispatcher::ParsedHandler { + completed, + data: PostToolUseHandlerData { + should_stop, + stop_reason, + additional_contexts_for_model, + feedback_messages_for_model, + }, + } +} + +fn serialization_failure_outcome(hook_events: Vec) -> PostToolUseOutcome { + PostToolUseOutcome { + hook_events, + should_stop: false, + stop_reason: None, + additional_contexts: Vec::new(), + feedback_message: None, + } +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use codex_protocol::protocol::HookEventName; + use codex_protocol::protocol::HookOutputEntry; + use codex_protocol::protocol::HookOutputEntryKind; + use codex_protocol::protocol::HookRunStatus; + use pretty_assertions::assert_eq; + + use super::PostToolUseHandlerData; + use super::parse_completed; + use crate::engine::ConfiguredHandler; + use crate::engine::command_runner::CommandRunResult; + + #[test] + fn block_decision_stops_normal_processing() { + let parsed = parse_completed( + &handler(), + run_result( + Some(0), + r#"{"decision":"block","reason":"bash output looked sketchy"}"#, + "", + ), + Some("turn-1".to_string()), + ); + + assert_eq!( + parsed.data, + PostToolUseHandlerData { + should_stop: false, + stop_reason: None, + additional_contexts_for_model: Vec::new(), + feedback_messages_for_model: vec!["bash output looked sketchy".to_string()], + } + ); + assert_eq!(parsed.completed.run.status, HookRunStatus::Blocked); + } + + #[test] + fn additional_context_is_recorded() { + let parsed = parse_completed( + &handler(), + run_result( + Some(0), + r#"{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"Remember the bash cleanup note."}}"#, + "", + ), + Some("turn-1".to_string()), + ); + + assert_eq!( + parsed.data, + PostToolUseHandlerData { + should_stop: false, + stop_reason: None, + additional_contexts_for_model: vec!["Remember the bash cleanup note.".to_string()], + feedback_messages_for_model: Vec::new(), + } + ); + assert_eq!( + parsed.completed.run.entries, + vec![HookOutputEntry { + kind: HookOutputEntryKind::Context, + text: "Remember the bash cleanup note.".to_string(), + }] + ); + } + + #[test] + fn unsupported_updated_mcp_tool_output_fails_open() { + let parsed = parse_completed( + &handler(), + run_result( + Some(0), + r#"{"hookSpecificOutput":{"hookEventName":"PostToolUse","updatedMCPToolOutput":{"ok":true}}}"#, + "", + ), + Some("turn-1".to_string()), + ); + + assert_eq!( + parsed.data, + PostToolUseHandlerData { + should_stop: false, + stop_reason: None, + additional_contexts_for_model: Vec::new(), + feedback_messages_for_model: Vec::new(), + } + ); + assert_eq!(parsed.completed.run.status, HookRunStatus::Failed); + assert_eq!( + parsed.completed.run.entries, + vec![HookOutputEntry { + kind: HookOutputEntryKind::Error, + text: "PostToolUse hook returned unsupported updatedMCPToolOutput".to_string(), + }] + ); + } + + #[test] + fn exit_two_surfaces_feedback_to_model_without_blocking() { + let parsed = parse_completed( + &handler(), + run_result(Some(2), "", "post hook says pause"), + Some("turn-1".to_string()), + ); + + assert_eq!( + parsed.data, + PostToolUseHandlerData { + should_stop: false, + stop_reason: None, + additional_contexts_for_model: Vec::new(), + feedback_messages_for_model: vec!["post hook says pause".to_string()], + } + ); + assert_eq!(parsed.completed.run.status, HookRunStatus::Completed); + } + + #[test] + fn continue_false_stops_with_reason() { + let parsed = parse_completed( + &handler(), + run_result( + Some(0), + r#"{"continue":false,"stopReason":"halt after bash output","reason":"post-tool hook says stop"}"#, + "", + ), + Some("turn-1".to_string()), + ); + + assert_eq!( + parsed.data, + PostToolUseHandlerData { + should_stop: true, + stop_reason: Some("halt after bash output".to_string()), + additional_contexts_for_model: Vec::new(), + feedback_messages_for_model: vec!["post-tool hook says stop".to_string()], + } + ); + assert_eq!(parsed.completed.run.status, HookRunStatus::Stopped); + assert_eq!( + parsed.completed.run.entries, + vec![HookOutputEntry { + kind: HookOutputEntryKind::Stop, + text: "halt after bash output".to_string(), + }] + ); + } + + #[test] + fn plain_stdout_is_ignored_for_post_tool_use() { + let parsed = parse_completed( + &handler(), + run_result(Some(0), "plain text only", ""), + Some("turn-1".to_string()), + ); + + assert_eq!( + parsed.data, + PostToolUseHandlerData { + should_stop: false, + stop_reason: None, + additional_contexts_for_model: Vec::new(), + feedback_messages_for_model: Vec::new(), + } + ); + assert_eq!(parsed.completed.run.status, HookRunStatus::Completed); + assert_eq!(parsed.completed.run.entries, Vec::::new()); + } + + fn handler() -> ConfiguredHandler { + ConfiguredHandler { + event_name: HookEventName::PostToolUse, + matcher: Some("^Bash$".to_string()), + command: "python3 post_tool_use_hook.py".to_string(), + timeout_sec: 5, + status_message: Some("running post tool use hook".to_string()), + source_path: PathBuf::from("/tmp/hooks.json"), + display_order: 0, + } + } + + fn run_result(exit_code: Option, stdout: &str, stderr: &str) -> CommandRunResult { + CommandRunResult { + started_at: 1_700_000_000, + completed_at: 1_700_000_001, + duration_ms: 12, + exit_code, + stdout: stdout.to_string(), + stderr: stderr.to_string(), + error: None, + } + } +} diff --git a/codex-rs/hooks/src/lib.rs b/codex-rs/hooks/src/lib.rs index 86b39b0b7d..16334a6476 100644 --- a/codex-rs/hooks/src/lib.rs +++ b/codex-rs/hooks/src/lib.rs @@ -5,6 +5,8 @@ mod registry; mod schema; mod types; +pub use events::post_tool_use::PostToolUseOutcome; +pub use events::post_tool_use::PostToolUseRequest; pub use events::pre_tool_use::PreToolUseOutcome; pub use events::pre_tool_use::PreToolUseRequest; pub use events::session_start::SessionStartOutcome; diff --git a/codex-rs/hooks/src/registry.rs b/codex-rs/hooks/src/registry.rs index 440af648dd..9a9667f8a9 100644 --- a/codex-rs/hooks/src/registry.rs +++ b/codex-rs/hooks/src/registry.rs @@ -3,6 +3,8 @@ use tokio::process::Command; use crate::engine::ClaudeHooksEngine; use crate::engine::CommandShell; +use crate::events::post_tool_use::PostToolUseOutcome; +use crate::events::post_tool_use::PostToolUseRequest; use crate::events::pre_tool_use::PreToolUseOutcome; use crate::events::pre_tool_use::PreToolUseRequest; use crate::events::session_start::SessionStartOutcome; @@ -101,6 +103,13 @@ impl Hooks { self.engine.preview_pre_tool_use(request) } + pub fn preview_post_tool_use( + &self, + request: &PostToolUseRequest, + ) -> Vec { + self.engine.preview_post_tool_use(request) + } + pub async fn run_session_start( &self, request: SessionStartRequest, @@ -113,6 +122,10 @@ impl Hooks { self.engine.run_pre_tool_use(request).await } + pub async fn run_post_tool_use(&self, request: PostToolUseRequest) -> PostToolUseOutcome { + self.engine.run_post_tool_use(request).await + } + pub fn preview_user_prompt_submit( &self, request: &UserPromptSubmitRequest, diff --git a/codex-rs/hooks/src/schema.rs b/codex-rs/hooks/src/schema.rs index 277500984c..b1a5017cd1 100644 --- a/codex-rs/hooks/src/schema.rs +++ b/codex-rs/hooks/src/schema.rs @@ -13,6 +13,8 @@ use std::path::Path; use std::path::PathBuf; const GENERATED_DIR: &str = "generated"; +const POST_TOOL_USE_INPUT_FIXTURE: &str = "post-tool-use.command.input.schema.json"; +const POST_TOOL_USE_OUTPUT_FIXTURE: &str = "post-tool-use.command.output.schema.json"; const PRE_TOOL_USE_INPUT_FIXTURE: &str = "pre-tool-use.command.input.schema.json"; const PRE_TOOL_USE_OUTPUT_FIXTURE: &str = "pre-tool-use.command.output.schema.json"; const SESSION_START_INPUT_FIXTURE: &str = "session-start.command.input.schema.json"; @@ -67,6 +69,8 @@ pub(crate) struct HookUniversalOutputWire { pub(crate) enum HookEventNameWire { #[serde(rename = "PreToolUse")] PreToolUse, + #[serde(rename = "PostToolUse")] + PostToolUse, #[serde(rename = "SessionStart")] SessionStart, #[serde(rename = "UserPromptSubmit")] @@ -90,6 +94,33 @@ pub(crate) struct PreToolUseCommandOutputWire { pub hook_specific_output: Option, } +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +#[serde(deny_unknown_fields)] +#[schemars(rename = "post-tool-use.command.output")] +pub(crate) struct PostToolUseCommandOutputWire { + #[serde(flatten)] + pub universal: HookUniversalOutputWire, + #[serde(default)] + pub decision: Option, + #[serde(default)] + pub reason: Option, + #[serde(default)] + pub hook_specific_output: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +#[serde(deny_unknown_fields)] +pub(crate) struct PostToolUseHookSpecificOutputWire { + pub hook_event_name: HookEventNameWire, + #[serde(default)] + pub additional_context: Option, + #[serde(default)] + #[serde(rename = "updatedMCPToolOutput")] + pub updated_mcp_tool_output: Option, +} + #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "camelCase")] #[serde(deny_unknown_fields)] @@ -150,6 +181,34 @@ pub(crate) struct PreToolUseCommandInput { pub tool_use_id: String, } +#[derive(Debug, Clone, Serialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +#[serde(deny_unknown_fields)] +pub(crate) struct PostToolUseToolInput { + pub command: String, +} + +#[derive(Debug, Clone, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +#[schemars(rename = "post-tool-use.command.input")] +pub(crate) struct PostToolUseCommandInput { + pub session_id: String, + /// Codex extension: expose the active turn id to internal turn-scoped hooks. + pub turn_id: String, + pub transcript_path: NullableString, + pub cwd: String, + #[schemars(schema_with = "post_tool_use_hook_event_name_schema")] + pub hook_event_name: String, + pub model: String, + #[schemars(schema_with = "permission_mode_schema")] + pub permission_mode: String, + #[schemars(schema_with = "post_tool_use_tool_name_schema")] + pub tool_name: String, + pub tool_input: PostToolUseToolInput, + pub tool_response: Value, + pub tool_use_id: String, +} + #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "camelCase")] #[serde(deny_unknown_fields)] @@ -291,6 +350,14 @@ pub fn write_schema_fixtures(schema_root: &Path) -> anyhow::Result<()> { let generated_dir = schema_root.join(GENERATED_DIR); ensure_empty_dir(&generated_dir)?; + write_schema( + &generated_dir.join(POST_TOOL_USE_INPUT_FIXTURE), + schema_json::()?, + )?; + write_schema( + &generated_dir.join(POST_TOOL_USE_OUTPUT_FIXTURE), + schema_json::()?, + )?; write_schema( &generated_dir.join(PRE_TOOL_USE_INPUT_FIXTURE), schema_json::()?, @@ -382,6 +449,14 @@ fn session_start_hook_event_name_schema(_gen: &mut SchemaGenerator) -> Schema { string_const_schema("SessionStart") } +fn post_tool_use_hook_event_name_schema(_gen: &mut SchemaGenerator) -> Schema { + string_const_schema("PostToolUse") +} + +fn post_tool_use_tool_name_schema(_gen: &mut SchemaGenerator) -> Schema { + string_const_schema("Bash") +} + fn pre_tool_use_hook_event_name_schema(_gen: &mut SchemaGenerator) -> Schema { string_const_schema("PreToolUse") } @@ -441,8 +516,11 @@ fn default_continue() -> bool { #[cfg(test)] mod tests { + use super::POST_TOOL_USE_INPUT_FIXTURE; + use super::POST_TOOL_USE_OUTPUT_FIXTURE; use super::PRE_TOOL_USE_INPUT_FIXTURE; use super::PRE_TOOL_USE_OUTPUT_FIXTURE; + use super::PostToolUseCommandInput; use super::PreToolUseCommandInput; use super::SESSION_START_INPUT_FIXTURE; use super::SESSION_START_OUTPUT_FIXTURE; @@ -460,6 +538,12 @@ mod tests { fn expected_fixture(name: &str) -> &'static str { match name { + POST_TOOL_USE_INPUT_FIXTURE => { + include_str!("../schema/generated/post-tool-use.command.input.schema.json") + } + POST_TOOL_USE_OUTPUT_FIXTURE => { + include_str!("../schema/generated/post-tool-use.command.output.schema.json") + } PRE_TOOL_USE_INPUT_FIXTURE => { include_str!("../schema/generated/pre-tool-use.command.input.schema.json") } @@ -499,6 +583,8 @@ mod tests { write_schema_fixtures(&schema_root).expect("write generated hook schemas"); for fixture in [ + POST_TOOL_USE_INPUT_FIXTURE, + POST_TOOL_USE_OUTPUT_FIXTURE, PRE_TOOL_USE_INPUT_FIXTURE, PRE_TOOL_USE_OUTPUT_FIXTURE, SESSION_START_INPUT_FIXTURE, @@ -524,6 +610,11 @@ mod tests { &schema_json::().expect("serialize pre tool use input schema"), ) .expect("parse pre tool use input schema"); + let post_tool_use: Value = serde_json::from_slice( + &schema_json::() + .expect("serialize post tool use input schema"), + ) + .expect("parse post tool use input schema"); let user_prompt_submit: Value = serde_json::from_slice( &schema_json::() .expect("serialize user prompt submit input schema"), @@ -534,7 +625,7 @@ mod tests { ) .expect("parse stop input schema"); - for schema in [&pre_tool_use, &user_prompt_submit, &stop] { + for schema in [&pre_tool_use, &post_tool_use, &user_prompt_submit, &stop] { assert_eq!(schema["properties"]["turn_id"]["type"], "string"); assert!( schema["required"] diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 6856f19417..2e67fa5d73 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -1408,6 +1408,7 @@ pub enum EventMsg { #[serde(rename_all = "snake_case")] pub enum HookEventName { PreToolUse, + PostToolUse, SessionStart, UserPromptSubmit, Stop, diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index a4a7155ed0..68497f4e07 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -9640,6 +9640,7 @@ fn extract_first_bold(s: &str) -> Option { fn hook_event_label(event_name: codex_protocol::protocol::HookEventName) -> &'static str { match event_name { codex_protocol::protocol::HookEventName::PreToolUse => "PreToolUse", + codex_protocol::protocol::HookEventName::PostToolUse => "PostToolUse", codex_protocol::protocol::HookEventName::SessionStart => "SessionStart", codex_protocol::protocol::HookEventName::UserPromptSubmit => "UserPromptSubmit", codex_protocol::protocol::HookEventName::Stop => "Stop", diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__post_tool_use_hook_events_render_snapshot.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__post_tool_use_hook_events_render_snapshot.snap new file mode 100644 index 0000000000..722aa89e47 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__post_tool_use_hook_events_render_snapshot.snap @@ -0,0 +1,9 @@ +--- +source: tui/src/chatwidget/tests.rs +expression: combined +--- +• Running PostToolUse hook: warming the shell + +PostToolUse hook (completed) + warning: Heads up from the hook + hook context: Remember the startup checklist. diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 41e9b49897..cba1b285e0 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -12151,6 +12151,17 @@ async fn pre_tool_use_hook_events_render_snapshot() { .await; } +#[tokio::test] +async fn post_tool_use_hook_events_render_snapshot() { + assert_hook_events_snapshot( + codex_protocol::protocol::HookEventName::PostToolUse, + "post-tool-use:0:/tmp/hooks.json", + "warming the shell", + "post_tool_use_hook_events_render_snapshot", + ) + .await; +} + #[tokio::test] async fn session_start_hook_events_render_snapshot() { assert_hook_events_snapshot( diff --git a/codex-rs/tui/tests/suite/model_availability_nux.rs b/codex-rs/tui/tests/suite/model_availability_nux.rs index 7ba0ec4b21..bcbb3f0e2c 100644 --- a/codex-rs/tui/tests/suite/model_availability_nux.rs +++ b/codex-rs/tui/tests/suite/model_availability_nux.rs @@ -179,9 +179,15 @@ trust_level = "trusted" } }; let output_text = String::from_utf8_lossy(&output); - let interrupted_startup = exit_code == 1 && output_text.trim() == "^C"; + let interrupt_only_output = { + let trimmed_output = output_text.trim(); + !trimmed_output.is_empty() + && trimmed_output + .chars() + .all(|character| character == '^' || character == 'C' || character.is_whitespace()) + }; anyhow::ensure!( - exit_code == 0 || exit_code == 130 || interrupted_startup, + exit_code == 0 || exit_code == 130 || (exit_code == 1 && interrupt_only_output), "unexpected exit code from codex resume: {exit_code}; output: {output_text}", ); diff --git a/codex-rs/tui_app_server/src/chatwidget.rs b/codex-rs/tui_app_server/src/chatwidget.rs index 0aea665b67..d0a8ab076e 100644 --- a/codex-rs/tui_app_server/src/chatwidget.rs +++ b/codex-rs/tui_app_server/src/chatwidget.rs @@ -10911,6 +10911,7 @@ fn extract_first_bold(s: &str) -> Option { fn hook_event_label(event_name: codex_protocol::protocol::HookEventName) -> &'static str { match event_name { codex_protocol::protocol::HookEventName::PreToolUse => "PreToolUse", + codex_protocol::protocol::HookEventName::PostToolUse => "PostToolUse", codex_protocol::protocol::HookEventName::SessionStart => "SessionStart", codex_protocol::protocol::HookEventName::UserPromptSubmit => "UserPromptSubmit", codex_protocol::protocol::HookEventName::Stop => "Stop", diff --git a/codex-rs/tui_app_server/src/chatwidget/snapshots/codex_tui_app_server__chatwidget__tests__post_tool_use_hook_events_render_snapshot.snap b/codex-rs/tui_app_server/src/chatwidget/snapshots/codex_tui_app_server__chatwidget__tests__post_tool_use_hook_events_render_snapshot.snap new file mode 100644 index 0000000000..67376a9fbb --- /dev/null +++ b/codex-rs/tui_app_server/src/chatwidget/snapshots/codex_tui_app_server__chatwidget__tests__post_tool_use_hook_events_render_snapshot.snap @@ -0,0 +1,9 @@ +--- +source: tui_app_server/src/chatwidget/tests.rs +expression: combined +--- +• Running PostToolUse hook: warming the shell + +PostToolUse hook (completed) + warning: Heads up from the hook + hook context: Remember the startup checklist. diff --git a/codex-rs/tui_app_server/src/chatwidget/tests.rs b/codex-rs/tui_app_server/src/chatwidget/tests.rs index 9b54d70351..e09965df9b 100644 --- a/codex-rs/tui_app_server/src/chatwidget/tests.rs +++ b/codex-rs/tui_app_server/src/chatwidget/tests.rs @@ -12626,6 +12626,17 @@ async fn pre_tool_use_hook_events_render_snapshot() { .await; } +#[tokio::test] +async fn post_tool_use_hook_events_render_snapshot() { + assert_hook_events_snapshot( + codex_protocol::protocol::HookEventName::PostToolUse, + "post-tool-use:0:/tmp/hooks.json", + "warming the shell", + "post_tool_use_hook_events_render_snapshot", + ) + .await; +} + #[tokio::test] async fn session_start_hook_events_render_snapshot() { assert_hook_events_snapshot( diff --git a/codex-rs/tui_app_server/tests/suite/model_availability_nux.rs b/codex-rs/tui_app_server/tests/suite/model_availability_nux.rs index 7ba0ec4b21..bcbb3f0e2c 100644 --- a/codex-rs/tui_app_server/tests/suite/model_availability_nux.rs +++ b/codex-rs/tui_app_server/tests/suite/model_availability_nux.rs @@ -179,9 +179,15 @@ trust_level = "trusted" } }; let output_text = String::from_utf8_lossy(&output); - let interrupted_startup = exit_code == 1 && output_text.trim() == "^C"; + let interrupt_only_output = { + let trimmed_output = output_text.trim(); + !trimmed_output.is_empty() + && trimmed_output + .chars() + .all(|character| character == '^' || character == 'C' || character.is_whitespace()) + }; anyhow::ensure!( - exit_code == 0 || exit_code == 130 || interrupted_startup, + exit_code == 0 || exit_code == 130 || (exit_code == 1 && interrupt_only_output), "unexpected exit code from codex resume: {exit_code}; output: {output_text}", ); From 4b50446ffa3385f8b72a5ced71a1306d28646d02 Mon Sep 17 00:00:00 2001 From: Matthew Zeng Date: Wed, 25 Mar 2026 20:24:06 -0700 Subject: [PATCH 005/212] [plugins] Flip flags on. (#15820) - [x] Flip flags on. --- codex-rs/features/src/lib.rs | 8 ++++---- codex-rs/features/src/tests.rs | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/codex-rs/features/src/lib.rs b/codex-rs/features/src/lib.rs index 0aa019cb06..ccde6a5e54 100644 --- a/codex-rs/features/src/lib.rs +++ b/codex-rs/features/src/lib.rs @@ -717,7 +717,7 @@ pub const FEATURES: &[FeatureSpec] = &[ id: Feature::Apps, key: "apps", stage: Stage::Stable, - default_enabled: false, + default_enabled: true, }, FeatureSpec { id: Feature::ToolSearch, @@ -729,13 +729,13 @@ pub const FEATURES: &[FeatureSpec] = &[ id: Feature::ToolSuggest, key: "tool_suggest", stage: Stage::Stable, - default_enabled: false, + default_enabled: true, }, FeatureSpec { id: Feature::Plugins, key: "plugins", stage: Stage::Stable, - default_enabled: false, + default_enabled: true, }, FeatureSpec { id: Feature::ImageGeneration, @@ -787,7 +787,7 @@ pub const FEATURES: &[FeatureSpec] = &[ id: Feature::ToolCallMcpElicitation, key: "tool_call_mcp_elicitation", stage: Stage::Stable, - default_enabled: false, + default_enabled: true, }, FeatureSpec { id: Feature::Personality, diff --git a/codex-rs/features/src/tests.rs b/codex-rs/features/src/tests.rs index 4943a1ccf8..ecfa87b41b 100644 --- a/codex-rs/features/src/tests.rs +++ b/codex-rs/features/src/tests.rs @@ -115,9 +115,9 @@ fn request_permissions_tool_is_under_development() { } #[test] -fn tool_suggest_is_stable_and_disabled_by_default() { +fn tool_suggest_is_stable_and_enabled_by_default() { assert_eq!(Feature::ToolSuggest.stage(), Stage::Stable); - assert_eq!(Feature::ToolSuggest.default_enabled(), false); + assert_eq!(Feature::ToolSuggest.default_enabled(), true); } #[test] @@ -145,9 +145,9 @@ fn image_generation_is_under_development() { } #[test] -fn tool_call_mcp_elicitation_is_stable_and_disabled_by_default() { +fn tool_call_mcp_elicitation_is_stable_and_enabled_by_default() { assert_eq!(Feature::ToolCallMcpElicitation.stage(), Stage::Stable); - assert_eq!(Feature::ToolCallMcpElicitation.default_enabled(), false); + assert_eq!(Feature::ToolCallMcpElicitation.default_enabled(), true); } #[test] From b565f05d79c9e6ee8bc891353ae4c037c5982a01 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Wed, 25 Mar 2026 22:03:29 -0600 Subject: [PATCH 006/212] Fix quoted command rendering in tui_app_server (#15825) When `tui_app_server` is enabled, shell commands in the transcript render as fully quoted invocations like `/bin/zsh -lc "..."`. The non-app-server TUI correctly shows the parsed command body. Root cause: The app-server stores `ThreadItem::CommandExecution.command` as a shell-quoted string. When `tui_app_server` bridges that item back into the exec renderer, it was passing `vec![command]` unchanged instead of splitting the string back into argv. That prevented `strip_bash_lc_and_escape()` from recognizing the shell wrapper, so the renderer displayed the wrapper literally. Solution: Add a shared command-string splitter that round-trips shell-quoted commands back into argv when it is safe to do so, while preserving non-roundtrippable inputs as a single string. Use that helper everywhere `tui_app_server` reconstructs exec commands from app-server payloads, including live command-execution items, replayed thread items, and exec approval requests. This restores the same command display behavior as the direct TUI path without breaking Windows-style commands that cannot be safely round-tripped. --- codex-rs/tui_app_server/src/app.rs | 37 ++++++- .../src/app/app_server_adapter.rs | 19 +--- codex-rs/tui_app_server/src/chatwidget.rs | 13 ++- ...ommand_execution_strips_shell_wrapper.snap | 6 ++ .../tui_app_server/src/chatwidget/tests.rs | 101 ++++++++++++++++++ codex-rs/tui_app_server/src/exec_command.rs | 37 +++++++ 6 files changed, 191 insertions(+), 22 deletions(-) create mode 100644 codex-rs/tui_app_server/src/chatwidget/snapshots/codex_tui_app_server__chatwidget__tests__live_app_server_command_execution_strips_shell_wrapper.snap diff --git a/codex-rs/tui_app_server/src/app.rs b/codex-rs/tui_app_server/src/app.rs index 452a1cfbd3..20264647d7 100644 --- a/codex-rs/tui_app_server/src/app.rs +++ b/codex-rs/tui_app_server/src/app.rs @@ -22,6 +22,7 @@ use crate::chatwidget::ReplayKind; use crate::chatwidget::ThreadInputState; use crate::cwd_prompt::CwdPromptAction; use crate::diff_render::DiffSummary; +use crate::exec_command::split_command_string; use crate::exec_command::strip_bash_lc_and_escape; use crate::external_editor; use crate::file_search::FileSearchManager; @@ -1701,7 +1702,11 @@ impl App { .approval_id .clone() .unwrap_or_else(|| params.item_id.clone()), - command: params.command.clone().into_iter().collect(), + command: params + .command + .as_deref() + .map(split_command_string) + .unwrap_or_default(), reason: params.reason.clone(), available_decisions: params .available_decisions @@ -7554,6 +7559,36 @@ guardian_approval = true ); } + #[tokio::test] + async fn inactive_thread_exec_approval_splits_shell_wrapped_command() { + let app = make_test_app().await; + let thread_id = ThreadId::new(); + let script = r#"python3 -c 'print("Hello, world!")'"#; + let mut request = exec_approval_request(thread_id, "turn-approval", "call-approval", None); + let ServerRequest::CommandExecutionRequestApproval { params, .. } = &mut request else { + panic!("expected exec approval request"); + }; + params.command = Some( + shlex::try_join(["/bin/zsh", "-lc", script]).expect("round-trippable shell wrapper"), + ); + + let Some(ThreadInteractiveRequest::Approval(ApprovalRequest::Exec { command, .. })) = app + .interactive_request_for_thread_request(thread_id, &request) + .await + else { + panic!("expected exec approval request"); + }; + + assert_eq!( + command, + vec![ + "/bin/zsh".to_string(), + "-lc".to_string(), + script.to_string(), + ] + ); + } + #[tokio::test] async fn inactive_thread_approval_badge_clears_after_turn_completion_notification() -> Result<()> { diff --git a/codex-rs/tui_app_server/src/app/app_server_adapter.rs b/codex-rs/tui_app_server/src/app/app_server_adapter.rs index c358b9cef1..719efc1778 100644 --- a/codex-rs/tui_app_server/src/app/app_server_adapter.rs +++ b/codex-rs/tui_app_server/src/app/app_server_adapter.rs @@ -16,6 +16,8 @@ use crate::app_event::AppEvent; use crate::app_server_session::AppServerSession; use crate::app_server_session::app_server_rate_limit_snapshot_to_core; use crate::app_server_session::status_account_display_from_auth_mode; +#[cfg(test)] +use crate::exec_command::split_command_string; use codex_app_server_client::AppServerEvent; use codex_app_server_protocol::AuthMode; use codex_app_server_protocol::JSONRPCErrorError; @@ -956,23 +958,6 @@ fn command_execution_snapshot_events(turn_id: &str, item: &ThreadItem) -> Option Some(events) } -#[cfg(test)] -fn split_command_string(command: &str) -> Vec { - let Some(parts) = shlex::split(command) else { - return vec![command.to_string()]; - }; - match shlex::try_join(parts.iter().map(String::as_str)) { - Ok(round_trip) - if round_trip == command - || (!command.contains(":\\") - && shlex::split(&round_trip).as_ref() == Some(&parts)) => - { - parts - } - _ => vec![command.to_string()], - } -} - #[cfg(test)] fn app_server_web_search_action_to_core( action: codex_app_server_protocol::WebSearchAction, diff --git a/codex-rs/tui_app_server/src/chatwidget.rs b/codex-rs/tui_app_server/src/chatwidget.rs index d0a8ab076e..deb378ea22 100644 --- a/codex-rs/tui_app_server/src/chatwidget.rs +++ b/codex-rs/tui_app_server/src/chatwidget.rs @@ -311,6 +311,7 @@ use crate::diff_render::display_path_for; use crate::exec_cell::CommandOutput; use crate::exec_cell::ExecCell; use crate::exec_cell::new_active_exec_command; +use crate::exec_command::split_command_string; use crate::exec_command::strip_bash_lc_and_escape; use crate::get_git_diff::get_git_diff; use crate::history_cell; @@ -1261,7 +1262,11 @@ fn exec_approval_request_from_params( ) -> ExecApprovalRequestEvent { ExecApprovalRequestEvent { call_id: params.item_id, - command: params.command.into_iter().collect(), + command: params + .command + .as_deref() + .map(split_command_string) + .unwrap_or_default(), cwd: params.cwd.unwrap_or_default(), reason: params.reason, network_approval_context: params @@ -5809,7 +5814,7 @@ impl ChatWidget { call_id: id, process_id, turn_id: turn_id.clone(), - command: vec![command], + command: split_command_string(&command), cwd, parsed_cmd: command_actions .into_iter() @@ -5824,7 +5829,7 @@ impl ChatWidget { call_id: id, process_id, turn_id: turn_id.clone(), - command: vec![command], + command: split_command_string(&command), cwd, parsed_cmd: command_actions .into_iter() @@ -6391,7 +6396,7 @@ impl ChatWidget { call_id: id, process_id, turn_id: notification.turn_id, - command: vec![command], + command: split_command_string(&command), cwd, parsed_cmd: command_actions .into_iter() diff --git a/codex-rs/tui_app_server/src/chatwidget/snapshots/codex_tui_app_server__chatwidget__tests__live_app_server_command_execution_strips_shell_wrapper.snap b/codex-rs/tui_app_server/src/chatwidget/snapshots/codex_tui_app_server__chatwidget__tests__live_app_server_command_execution_strips_shell_wrapper.snap new file mode 100644 index 0000000000..f8d81249fd --- /dev/null +++ b/codex-rs/tui_app_server/src/chatwidget/snapshots/codex_tui_app_server__chatwidget__tests__live_app_server_command_execution_strips_shell_wrapper.snap @@ -0,0 +1,6 @@ +--- +source: tui_app_server/src/chatwidget/tests.rs +expression: blob +--- +• You ran python3 -c 'print("Hello, world!")' + └ Hello, world! diff --git a/codex-rs/tui_app_server/src/chatwidget/tests.rs b/codex-rs/tui_app_server/src/chatwidget/tests.rs index e09965df9b..a74b43fa81 100644 --- a/codex-rs/tui_app_server/src/chatwidget/tests.rs +++ b/codex-rs/tui_app_server/src/chatwidget/tests.rs @@ -26,6 +26,10 @@ use codex_app_server_protocol::CollabAgentState as AppServerCollabAgentState; use codex_app_server_protocol::CollabAgentStatus as AppServerCollabAgentStatus; use codex_app_server_protocol::CollabAgentTool as AppServerCollabAgentTool; use codex_app_server_protocol::CollabAgentToolCallStatus as AppServerCollabAgentToolCallStatus; +use codex_app_server_protocol::CommandAction as AppServerCommandAction; +use codex_app_server_protocol::CommandExecutionRequestApprovalParams as AppServerCommandExecutionRequestApprovalParams; +use codex_app_server_protocol::CommandExecutionSource as AppServerCommandExecutionSource; +use codex_app_server_protocol::CommandExecutionStatus as AppServerCommandExecutionStatus; use codex_app_server_protocol::ErrorNotification; use codex_app_server_protocol::FileUpdateChange; use codex_app_server_protocol::GuardianApprovalReview; @@ -3503,6 +3507,40 @@ async fn exec_approval_emits_proposed_command_and_decision_history() { ); } +#[test] +fn app_server_exec_approval_request_splits_shell_wrapped_command() { + let script = r#"python3 -c 'print("Hello, world!")'"#; + let request = + exec_approval_request_from_params(AppServerCommandExecutionRequestApprovalParams { + thread_id: "thread-1".to_string(), + turn_id: "turn-1".to_string(), + item_id: "item-1".to_string(), + approval_id: Some("approval-1".to_string()), + reason: None, + network_approval_context: None, + command: Some( + shlex::try_join(["/bin/zsh", "-lc", script]) + .expect("round-trippable shell wrapper"), + ), + cwd: Some(PathBuf::from("/tmp")), + command_actions: None, + additional_permissions: None, + skill_metadata: None, + proposed_execpolicy_amendment: None, + proposed_network_policy_amendments: None, + available_decisions: None, + }); + + assert_eq!( + request.command, + vec![ + "/bin/zsh".to_string(), + "-lc".to_string(), + script.to_string(), + ] + ); +} + #[tokio::test] async fn exec_approval_uses_approval_id_when_present() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await; @@ -4650,6 +4688,69 @@ async fn live_app_server_file_change_item_started_preserves_changes() { ); } +#[tokio::test] +async fn live_app_server_command_execution_strips_shell_wrapper() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await; + let script = r#"python3 -c 'print("Hello, world!")'"#; + let command = + shlex::try_join(["/bin/zsh", "-lc", script]).expect("round-trippable shell wrapper"); + + chat.handle_server_notification( + ServerNotification::ItemStarted(ItemStartedNotification { + thread_id: "thread-1".to_string(), + turn_id: "turn-1".to_string(), + item: AppServerThreadItem::CommandExecution { + id: "cmd-1".to_string(), + command: command.clone(), + cwd: PathBuf::from("/tmp"), + process_id: None, + source: AppServerCommandExecutionSource::UserShell, + status: AppServerCommandExecutionStatus::InProgress, + command_actions: vec![AppServerCommandAction::Unknown { + command: script.to_string(), + }], + aggregated_output: None, + exit_code: None, + duration_ms: None, + }, + }), + None, + ); + chat.handle_server_notification( + ServerNotification::ItemCompleted(ItemCompletedNotification { + thread_id: "thread-1".to_string(), + turn_id: "turn-1".to_string(), + item: AppServerThreadItem::CommandExecution { + id: "cmd-1".to_string(), + command, + cwd: PathBuf::from("/tmp"), + process_id: None, + source: AppServerCommandExecutionSource::UserShell, + status: AppServerCommandExecutionStatus::Completed, + command_actions: vec![AppServerCommandAction::Unknown { + command: script.to_string(), + }], + aggregated_output: Some("Hello, world!\n".to_string()), + exit_code: Some(0), + duration_ms: Some(5), + }, + }), + None, + ); + + let cells = drain_insert_history(&mut rx); + assert_eq!( + cells.len(), + 1, + "expected one completed command history cell" + ); + let blob = lines_to_single_string(cells.first().expect("command cell")); + assert_snapshot!( + "live_app_server_command_execution_strips_shell_wrapper", + blob + ); +} + #[test] fn app_server_patch_changes_to_core_preserves_diffs() { let changes = app_server_patch_changes_to_core(vec![FileUpdateChange { diff --git a/codex-rs/tui_app_server/src/exec_command.rs b/codex-rs/tui_app_server/src/exec_command.rs index bcfbc1776d..0083e1df2b 100644 --- a/codex-rs/tui_app_server/src/exec_command.rs +++ b/codex-rs/tui_app_server/src/exec_command.rs @@ -16,6 +16,22 @@ pub(crate) fn strip_bash_lc_and_escape(command: &[String]) -> String { escape_command(command) } +pub(crate) fn split_command_string(command: &str) -> Vec { + let Some(parts) = shlex::split(command) else { + return vec![command.to_string()]; + }; + match shlex::try_join(parts.iter().map(String::as_str)) { + Ok(round_trip) + if round_trip == command + || (!command.contains(":\\") + && shlex::split(&round_trip).as_ref() == Some(&parts)) => + { + parts + } + _ => vec![command.to_string()], + } +} + /// If `path` is absolute and inside $HOME, return the part *after* the home /// directory; otherwise, return the path as-is. Note if `path` is the homedir, /// this will return and empty path. @@ -67,4 +83,25 @@ mod tests { let cmdline = strip_bash_lc_and_escape(&args); assert_eq!(cmdline, "echo hello"); } + + #[test] + fn split_command_string_round_trips_shell_wrappers() { + let command = + shlex::try_join(["/bin/zsh", "-lc", r#"python3 -c 'print("Hello, world!")'"#]) + .expect("round-trippable command"); + assert_eq!( + split_command_string(&command), + vec![ + "/bin/zsh".to_string(), + "-lc".to_string(), + r#"python3 -c 'print("Hello, world!")'"#.to_string(), + ] + ); + } + + #[test] + fn split_command_string_preserves_non_roundtrippable_windows_commands() { + let command = r#"C:\Program Files\Git\bin\bash.exe -lc "echo hi""#; + assert_eq!(split_command_string(command), vec![command.to_string()]); + } } From 1ff39b6fa812e987c143c976c488794fd4966f2d Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Wed, 25 Mar 2026 22:17:03 -0600 Subject: [PATCH 007/212] Wire remote app-server auth through the client (#14853) For app-server websocket auth, support the two server-side mechanisms from PR #14847: - `--ws-auth capability-token --ws-token-file /abs/path` - `--ws-auth signed-bearer-token --ws-shared-secret-file /abs/path` with optional `--ws-issuer`, `--ws-audience`, and `--ws-max-clock-skew-seconds` On the client side, add interactive remote support via: - `--remote ws://host:port` or `--remote wss://host:port` - `--remote-auth-token-env ` Codex reads the bearer token from the named environment variable and sends it as `Authorization: Bearer ` during the websocket handshake. Remote auth tokens are only allowed for `wss://` URLs or loopback `ws://` URLs. Testing: - tested both auth methods manually to confirm connection success and rejection for both auth types --- codex-rs/app-server-client/src/lib.rs | 94 +++++++- codex-rs/app-server-client/src/remote.rs | 40 +++- codex-rs/cli/src/main.rs | 291 ++++++++++++++++++++--- codex-rs/tui/src/main.rs | 1 + codex-rs/tui_app_server/src/app.rs | 10 +- codex-rs/tui_app_server/src/lib.rs | 79 +++++- codex-rs/tui_app_server/src/main.rs | 1 + 7 files changed, 469 insertions(+), 47 deletions(-) diff --git a/codex-rs/app-server-client/src/lib.rs b/codex-rs/app-server-client/src/lib.rs index 1ea9f6fd87..ad9eca65e7 100644 --- a/codex-rs/app-server-client/src/lib.rs +++ b/codex-rs/app-server-client/src/lib.rs @@ -868,8 +868,11 @@ mod tests { use tokio::net::TcpListener; use tokio::time::Duration; use tokio::time::timeout; - use tokio_tungstenite::accept_async; + use tokio_tungstenite::accept_hdr_async; use tokio_tungstenite::tungstenite::Message; + use tokio_tungstenite::tungstenite::handshake::server::Request as WebSocketRequest; + use tokio_tungstenite::tungstenite::handshake::server::Response as WebSocketResponse; + use tokio_tungstenite::tungstenite::http::header::AUTHORIZATION; async fn build_test_config() -> Config { match ConfigBuilder::default().build().await { @@ -908,6 +911,19 @@ mod tests { } async fn start_test_remote_server(handler: F) -> String + where + F: FnOnce(tokio_tungstenite::WebSocketStream) -> Fut + + Send + + 'static, + Fut: std::future::Future + Send + 'static, + { + start_test_remote_server_with_auth(None, handler).await + } + + async fn start_test_remote_server_with_auth( + expected_auth_token: Option, + handler: F, + ) -> String where F: FnOnce(tokio_tungstenite::WebSocketStream) -> Fut + Send @@ -920,9 +936,23 @@ mod tests { let addr = listener.local_addr().expect("listener address"); tokio::spawn(async move { let (stream, _) = listener.accept().await.expect("accept should succeed"); - let websocket = accept_async(stream) - .await - .expect("websocket upgrade should succeed"); + let websocket = accept_hdr_async( + stream, + move |request: &WebSocketRequest, response: WebSocketResponse| { + let provided_auth_token = request + .headers() + .get(AUTHORIZATION) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let expected_auth_token = expected_auth_token + .as_ref() + .map(|token| format!("Bearer {token}")); + assert_eq!(provided_auth_token, expected_auth_token); + Ok(response) + }, + ) + .await + .expect("websocket upgrade should succeed"); handler(websocket).await; }); format!("ws://{addr}") @@ -1037,6 +1067,7 @@ mod tests { fn test_remote_connect_args(websocket_url: String) -> RemoteAppServerConnectArgs { RemoteAppServerConnectArgs { websocket_url, + auth_token: None, client_name: "codex-app-server-client-test".to_string(), client_version: "0.0.0-test".to_string(), experimental_api: true, @@ -1253,6 +1284,7 @@ mod tests { }), ) .await; + websocket.close(None).await.expect("close should succeed"); }) .await; let client = RemoteAppServerClient::connect(test_remote_connect_args(websocket_url)) @@ -1273,6 +1305,59 @@ mod tests { client.shutdown().await.expect("shutdown should complete"); } + #[tokio::test] + async fn remote_connect_includes_auth_header_when_configured() { + let auth_token = "remote-bearer-token".to_string(); + let websocket_url = start_test_remote_server_with_auth( + Some(auth_token.clone()), + |mut websocket| async move { + expect_remote_initialize(&mut websocket).await; + websocket.close(None).await.expect("close should succeed"); + }, + ) + .await; + let client = RemoteAppServerClient::connect(RemoteAppServerConnectArgs { + auth_token: Some(auth_token), + ..test_remote_connect_args(websocket_url) + }) + .await + .expect("remote client should connect"); + + client.shutdown().await.expect("shutdown should complete"); + } + + #[tokio::test] + async fn remote_connect_rejects_non_loopback_ws_when_auth_configured() { + let result = RemoteAppServerClient::connect(RemoteAppServerConnectArgs { + websocket_url: "ws://example.com:4500".to_string(), + auth_token: Some("remote-bearer-token".to_string()), + ..test_remote_connect_args("ws://127.0.0.1:1".to_string()) + }) + .await; + let err = match result { + Ok(_) => panic!("non-loopback ws should be rejected before connect"), + Err(err) => err, + }; + assert_eq!(err.kind(), ErrorKind::InvalidInput); + assert!( + err.to_string() + .contains("remote auth tokens require `wss://` or loopback `ws://` URLs") + ); + } + + #[test] + fn remote_auth_token_transport_policy_allows_wss_and_loopback_ws() { + assert!(crate::remote::websocket_url_supports_auth_token( + &url::Url::parse("wss://example.com:443").expect("wss URL should parse") + )); + assert!(crate::remote::websocket_url_supports_auth_token( + &url::Url::parse("ws://127.0.0.1:4500").expect("loopback ws URL should parse") + )); + assert!(!crate::remote::websocket_url_supports_auth_token( + &url::Url::parse("ws://example.com:4500").expect("non-loopback ws URL should parse") + )); + } + #[tokio::test] async fn remote_duplicate_request_id_keeps_original_waiter() { let (first_request_seen_tx, first_request_seen_rx) = tokio::sync::oneshot::channel(); @@ -1425,6 +1510,7 @@ mod tests { .await; let mut client = RemoteAppServerClient::connect(RemoteAppServerConnectArgs { websocket_url, + auth_token: None, client_name: "codex-app-server-client-test".to_string(), client_version: "0.0.0-test".to_string(), experimental_api: true, diff --git a/codex-rs/app-server-client/src/remote.rs b/codex-rs/app-server-client/src/remote.rs index 9cf37e262f..a82b924e45 100644 --- a/codex-rs/app-server-client/src/remote.rs +++ b/codex-rs/app-server-client/src/remote.rs @@ -48,6 +48,9 @@ use tokio_tungstenite::MaybeTlsStream; use tokio_tungstenite::WebSocketStream; use tokio_tungstenite::connect_async; use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tokio_tungstenite::tungstenite::http::HeaderValue; +use tokio_tungstenite::tungstenite::http::header::AUTHORIZATION; use tracing::warn; use url::Url; @@ -57,6 +60,7 @@ const INITIALIZE_TIMEOUT: Duration = Duration::from_secs(10); #[derive(Debug, Clone)] pub struct RemoteAppServerConnectArgs { pub websocket_url: String, + pub auth_token: Option, pub client_name: String, pub client_version: String, pub experimental_api: bool, @@ -86,6 +90,16 @@ impl RemoteAppServerConnectArgs { } } +pub(crate) fn websocket_url_supports_auth_token(url: &Url) -> bool { + match (url.scheme(), url.host()) { + ("wss", Some(_)) => true, + ("ws", Some(url::Host::Domain(domain))) => domain.eq_ignore_ascii_case("localhost"), + ("ws", Some(url::Host::Ipv4(addr))) => addr.is_loopback(), + ("ws", Some(url::Host::Ipv6(addr))) => addr.is_loopback(), + _ => false, + } +} + enum RemoteClientCommand { Request { request: Box, @@ -132,7 +146,31 @@ impl RemoteAppServerClient { format!("invalid websocket URL `{websocket_url}`: {err}"), ) })?; - let stream = timeout(CONNECT_TIMEOUT, connect_async(url.as_str())) + if args.auth_token.is_some() && !websocket_url_supports_auth_token(&url) { + return Err(IoError::new( + ErrorKind::InvalidInput, + format!( + "remote auth tokens require `wss://` or loopback `ws://` URLs; got `{websocket_url}`" + ), + )); + } + let mut request = url.as_str().into_client_request().map_err(|err| { + IoError::new( + ErrorKind::InvalidInput, + format!("invalid websocket URL `{websocket_url}`: {err}"), + ) + })?; + if let Some(auth_token) = args.auth_token.as_deref() { + let header_value = + HeaderValue::from_str(&format!("Bearer {auth_token}")).map_err(|err| { + IoError::new( + ErrorKind::InvalidInput, + format!("invalid remote authorization header value: {err}"), + ) + })?; + request.headers_mut().insert(AUTHORIZATION, header_value); + } + let stream = timeout(CONNECT_TIMEOUT, connect_async(request)) .await .map_err(|_| { IoError::new( diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index 5e0d405eb3..12a531d35d 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -530,6 +530,11 @@ struct InteractiveRemoteOptions { /// Accepted forms: `ws://host:port` or `wss://host:port`. #[arg(long = "remote", value_name = "ADDR")] remote: Option, + + /// Name of the environment variable containing the bearer token to send to + /// a remote app server websocket. + #[arg(long = "remote-auth-token-env", value_name = "ENV_VAR")] + remote_auth_token_env: Option, } impl FeatureToggles { @@ -607,6 +612,7 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { let toggle_overrides = feature_toggles.to_overrides()?; root_config_overrides.raw_overrides.extend(toggle_overrides); let root_remote = remote.remote; + let root_remote_auth_token_env = remote.remote_auth_token_env; match subcommand { None => { @@ -614,12 +620,21 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { &mut interactive.config_overrides, root_config_overrides.clone(), ); - let exit_info = - run_interactive_tui(interactive, root_remote.clone(), arg0_paths.clone()).await?; + let exit_info = run_interactive_tui( + interactive, + root_remote.clone(), + root_remote_auth_token_env.clone(), + arg0_paths.clone(), + ) + .await?; handle_app_exit(exit_info)?; } Some(Subcommand::Exec(mut exec_cli)) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "exec")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "exec", + )?; prepend_config_flags( &mut exec_cli.config_overrides, root_config_overrides.clone(), @@ -627,7 +642,11 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { codex_exec::run_main(exec_cli, arg0_paths.clone()).await?; } Some(Subcommand::Review(review_args)) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "review")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "review", + )?; let mut exec_cli = ExecCli::try_parse_from(["codex", "exec"])?; exec_cli.command = Some(ExecCommand::Review(review_args)); prepend_config_flags( @@ -637,11 +656,19 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { codex_exec::run_main(exec_cli, arg0_paths.clone()).await?; } Some(Subcommand::McpServer) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "mcp-server")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "mcp-server", + )?; codex_mcp_server::run_main(arg0_paths.clone(), root_config_overrides).await?; } Some(Subcommand::Mcp(mut mcp_cli)) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "mcp")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "mcp", + )?; // Propagate any root-level config overrides (e.g. `-c key=value`). prepend_config_flags(&mut mcp_cli.config_overrides, root_config_overrides.clone()); mcp_cli.run().await?; @@ -653,9 +680,13 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { analytics_default_enabled, auth, } = app_server_cli; + reject_remote_mode_for_app_server_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + subcommand.as_ref(), + )?; match subcommand { None => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "app-server")?; let transport = listen; let auth = auth.try_into_settings()?; codex_app_server::run_main_with_transport( @@ -670,10 +701,6 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { .await?; } Some(AppServerSubcommand::GenerateTs(gen_cli)) => { - reject_remote_mode_for_subcommand( - root_remote.as_deref(), - "app-server generate-ts", - )?; let options = codex_app_server_protocol::GenerateTsOptions { experimental_api: gen_cli.experimental, ..Default::default() @@ -685,10 +712,6 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { )?; } Some(AppServerSubcommand::GenerateJsonSchema(gen_cli)) => { - reject_remote_mode_for_subcommand( - root_remote.as_deref(), - "app-server generate-json-schema", - )?; codex_app_server_protocol::generate_json_with_experimental( &gen_cli.out_dir, gen_cli.experimental, @@ -701,7 +724,11 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { } #[cfg(target_os = "macos")] Some(Subcommand::App(app_cli)) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "app")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "app", + )?; app_cmd::run_app(app_cli).await?; } Some(Subcommand::Resume(ResumeCommand { @@ -724,6 +751,9 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { let exit_info = run_interactive_tui( interactive, remote.remote.or(root_remote.clone()), + remote + .remote_auth_token_env + .or(root_remote_auth_token_env.clone()), arg0_paths.clone(), ) .await?; @@ -747,13 +777,20 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { let exit_info = run_interactive_tui( interactive, remote.remote.or(root_remote.clone()), + remote + .remote_auth_token_env + .or(root_remote_auth_token_env.clone()), arg0_paths.clone(), ) .await?; handle_app_exit(exit_info)?; } Some(Subcommand::Login(mut login_cli)) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "login")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "login", + )?; prepend_config_flags( &mut login_cli.config_overrides, root_config_overrides.clone(), @@ -785,7 +822,11 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { } } Some(Subcommand::Logout(mut logout_cli)) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "logout")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "logout", + )?; prepend_config_flags( &mut logout_cli.config_overrides, root_config_overrides.clone(), @@ -793,11 +834,19 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { run_logout(logout_cli.config_overrides).await; } Some(Subcommand::Completion(completion_cli)) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "completion")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "completion", + )?; print_completion(completion_cli); } Some(Subcommand::Cloud(mut cloud_cli)) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "cloud")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "cloud", + )?; prepend_config_flags( &mut cloud_cli.config_overrides, root_config_overrides.clone(), @@ -807,7 +856,11 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { } Some(Subcommand::Sandbox(sandbox_args)) => match sandbox_args.cmd { SandboxCommand::Macos(mut seatbelt_cli) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "sandbox macos")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "sandbox macos", + )?; prepend_config_flags( &mut seatbelt_cli.config_overrides, root_config_overrides.clone(), @@ -819,7 +872,11 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { .await?; } SandboxCommand::Linux(mut landlock_cli) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "sandbox linux")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "sandbox linux", + )?; prepend_config_flags( &mut landlock_cli.config_overrides, root_config_overrides.clone(), @@ -831,7 +888,11 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { .await?; } SandboxCommand::Windows(mut windows_cli) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "sandbox windows")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "sandbox windows", + )?; prepend_config_flags( &mut windows_cli.config_overrides, root_config_overrides.clone(), @@ -845,22 +906,38 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { }, Some(Subcommand::Debug(DebugCommand { subcommand })) => match subcommand { DebugSubcommand::AppServer(cmd) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "debug app-server")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "debug app-server", + )?; run_debug_app_server_command(cmd).await?; } DebugSubcommand::ClearMemories => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "debug clear-memories")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "debug clear-memories", + )?; run_debug_clear_memories_command(&root_config_overrides, &interactive).await?; } }, Some(Subcommand::Execpolicy(ExecpolicyCommand { sub })) => match sub { ExecpolicySubcommand::Check(cmd) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "execpolicy check")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "execpolicy check", + )?; run_execpolicycheck(cmd)? } }, Some(Subcommand::Apply(mut apply_cli)) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "apply")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "apply", + )?; prepend_config_flags( &mut apply_cli.config_overrides, root_config_overrides.clone(), @@ -868,19 +945,31 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { run_apply_command(apply_cli, /*cwd*/ None).await?; } Some(Subcommand::ResponsesApiProxy(args)) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "responses-api-proxy")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "responses-api-proxy", + )?; tokio::task::spawn_blocking(move || codex_responses_api_proxy::run_main(args)) .await??; } Some(Subcommand::StdioToUds(cmd)) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "stdio-to-uds")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "stdio-to-uds", + )?; let socket_path = cmd.socket_path; tokio::task::spawn_blocking(move || codex_stdio_to_uds::run(socket_path.as_path())) .await??; } Some(Subcommand::Features(FeaturesCli { sub })) => match sub { FeaturesSubcommand::List => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "features list")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "features list", + )?; // Respect root-level `-c` overrides plus top-level flags like `--profile`. let mut cli_kv_overrides = root_config_overrides .parse_overrides() @@ -923,11 +1012,19 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { } } FeaturesSubcommand::Enable(FeatureSetArgs { feature }) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "features enable")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "features enable", + )?; enable_feature_in_config(&interactive, &feature).await?; } FeaturesSubcommand::Disable(FeatureSetArgs { feature }) => { - reject_remote_mode_for_subcommand(root_remote.as_deref(), "features disable")?; + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "features disable", + )?; disable_feature_in_config(&interactive, &feature).await?; } }, @@ -1046,18 +1143,64 @@ fn prepend_config_flags( .splice(0..0, cli_config_overrides.raw_overrides); } -fn reject_remote_mode_for_subcommand(remote: Option<&str>, subcommand: &str) -> anyhow::Result<()> { +fn reject_remote_mode_for_subcommand( + remote: Option<&str>, + remote_auth_token_env: Option<&str>, + subcommand: &str, +) -> anyhow::Result<()> { if let Some(remote) = remote { anyhow::bail!( "`--remote {remote}` is only supported for interactive TUI commands, not `codex {subcommand}`" ); } + if remote_auth_token_env.is_some() { + anyhow::bail!( + "`--remote-auth-token-env` is only supported for interactive TUI commands, not `codex {subcommand}`" + ); + } Ok(()) } +fn reject_remote_mode_for_app_server_subcommand( + remote: Option<&str>, + remote_auth_token_env: Option<&str>, + subcommand: Option<&AppServerSubcommand>, +) -> anyhow::Result<()> { + let subcommand_name = match subcommand { + None => "app-server", + Some(AppServerSubcommand::GenerateTs(_)) => "app-server generate-ts", + Some(AppServerSubcommand::GenerateJsonSchema(_)) => "app-server generate-json-schema", + Some(AppServerSubcommand::GenerateInternalJsonSchema(_)) => { + "app-server generate-internal-json-schema" + } + }; + reject_remote_mode_for_subcommand(remote, remote_auth_token_env, subcommand_name) +} + +fn read_remote_auth_token_from_env_var_with( + env_var_name: &str, + get_var: F, +) -> anyhow::Result +where + F: FnOnce(&str) -> Result, +{ + let auth_token = get_var(env_var_name) + .map_err(|_| anyhow::anyhow!("environment variable `{env_var_name}` is not set"))?; + let auth_token = auth_token.trim().to_string(); + if auth_token.is_empty() { + anyhow::bail!("environment variable `{env_var_name}` is empty"); + } + Ok(auth_token) +} + +fn read_remote_auth_token_from_env_var(env_var_name: &str) -> anyhow::Result { + read_remote_auth_token_from_env_var_with(env_var_name, |name| std::env::var(name)) +} + async fn run_interactive_tui( mut interactive: TuiCli, remote: Option, + remote_auth_token_env: Option, arg0_paths: Arg0DispatchPaths, ) -> std::io::Result { if let Some(prompt) = interactive.prompt.take() { @@ -1089,17 +1232,28 @@ async fn run_interactive_tui( .map(codex_tui_app_server::normalize_remote_addr) .transpose() .map_err(std::io::Error::other)?; + if remote_auth_token_env.is_some() && normalized_remote.is_none() { + return Ok(AppExitInfo::fatal( + "`--remote-auth-token-env` requires `--remote`.", + )); + } if normalized_remote.is_some() && !use_app_server_tui { return Ok(AppExitInfo::fatal( "`--remote` requires the `tui_app_server` feature flag to be enabled.", )); } if use_app_server_tui { + let remote_auth_token = remote_auth_token_env + .as_deref() + .map(read_remote_auth_token_from_env_var) + .transpose() + .map_err(std::io::Error::other)?; codex_tui_app_server::run_main( into_app_server_tui_cli(interactive), arg0_paths, codex_core::config_loader::LoaderOverrides::default(), normalized_remote, + remote_auth_token, ) .await .map(into_legacy_app_exit_info) @@ -1661,6 +1815,22 @@ mod tests { assert_eq!(cli.remote.remote.as_deref(), Some("ws://127.0.0.1:4500")); } + #[test] + fn remote_auth_token_env_flag_parses_for_interactive_root() { + let cli = MultitoolCli::try_parse_from([ + "codex", + "--remote-auth-token-env", + "CODEX_REMOTE_AUTH_TOKEN", + "--remote", + "ws://127.0.0.1:4500", + ]) + .expect("parse"); + assert_eq!( + cli.remote.remote_auth_token_env.as_deref(), + Some("CODEX_REMOTE_AUTH_TOKEN") + ); + } + #[test] fn remote_flag_parses_for_resume_subcommand() { let cli = @@ -1676,7 +1846,7 @@ mod tests { #[test] fn reject_remote_mode_for_non_interactive_subcommands() { - let err = reject_remote_mode_for_subcommand(Some("127.0.0.1:4500"), "exec") + let err = reject_remote_mode_for_subcommand(Some("127.0.0.1:4500"), None, "exec") .expect_err("non-interactive subcommands should reject --remote"); assert!( err.to_string() @@ -1684,6 +1854,59 @@ mod tests { ); } + #[test] + fn reject_remote_auth_token_env_for_non_interactive_subcommands() { + let err = reject_remote_mode_for_subcommand(None, Some("CODEX_REMOTE_AUTH_TOKEN"), "exec") + .expect_err("non-interactive subcommands should reject --remote-auth-token-env"); + assert!( + err.to_string() + .contains("only supported for interactive TUI commands") + ); + } + + #[test] + fn reject_remote_auth_token_env_for_app_server_generate_internal_json_schema() { + let subcommand = + AppServerSubcommand::GenerateInternalJsonSchema(GenerateInternalJsonSchemaCommand { + out_dir: PathBuf::from("/tmp/out"), + }); + let err = reject_remote_mode_for_app_server_subcommand( + None, + Some("CODEX_REMOTE_AUTH_TOKEN"), + Some(&subcommand), + ) + .expect_err("non-interactive app-server subcommands should reject --remote-auth-token-env"); + assert!(err.to_string().contains("generate-internal-json-schema")); + } + + #[test] + fn read_remote_auth_token_from_env_var_reports_missing_values() { + let err = read_remote_auth_token_from_env_var_with("CODEX_REMOTE_AUTH_TOKEN", |_| { + Err(std::env::VarError::NotPresent) + }) + .expect_err("missing env vars should be rejected"); + assert!(err.to_string().contains("is not set")); + } + + #[test] + fn read_remote_auth_token_from_env_var_trims_values() { + let auth_token = + read_remote_auth_token_from_env_var_with("CODEX_REMOTE_AUTH_TOKEN", |_| { + Ok(" bearer-token ".to_string()) + }) + .expect("env var should parse"); + assert_eq!(auth_token, "bearer-token"); + } + + #[test] + fn read_remote_auth_token_from_env_var_rejects_empty_values() { + let err = read_remote_auth_token_from_env_var_with("CODEX_REMOTE_AUTH_TOKEN", |_| { + Ok(" \n\t ".to_string()) + }) + .expect_err("empty env vars should be rejected"); + assert!(err.to_string().contains("is empty")); + } + #[test] fn app_server_listen_websocket_url_parses() { let app_server = app_server_from_args( diff --git a/codex-rs/tui/src/main.rs b/codex-rs/tui/src/main.rs index a784d3bc23..c563366214 100644 --- a/codex-rs/tui/src/main.rs +++ b/codex-rs/tui/src/main.rs @@ -92,6 +92,7 @@ fn main() -> anyhow::Result<()> { arg0_paths, codex_core::config_loader::LoaderOverrides::default(), /*remote*/ None, + /*remote_auth_token*/ None, ) .await?, ) diff --git a/codex-rs/tui_app_server/src/app.rs b/codex-rs/tui_app_server/src/app.rs index 20264647d7..dbef11ebc6 100644 --- a/codex-rs/tui_app_server/src/app.rs +++ b/codex-rs/tui_app_server/src/app.rs @@ -959,6 +959,7 @@ pub(crate) struct App { pub(crate) feedback: codex_feedback::CodexFeedback, feedback_audience: FeedbackAudience, remote_app_server_url: Option, + remote_app_server_auth_token: Option, /// Set when the user confirms an update; propagated on exit. pub(crate) pending_update_action: Option, @@ -3124,6 +3125,7 @@ impl App { is_first_run: bool, should_prompt_windows_sandbox_nux_at_startup: bool, remote_app_server_url: Option, + remote_app_server_auth_token: Option, ) -> Result { use tokio_stream::StreamExt; let (app_event_tx, mut app_event_rx) = unbounded_channel(); @@ -3335,6 +3337,7 @@ impl App { feedback: feedback.clone(), feedback_audience, remote_app_server_url, + remote_app_server_auth_token, pending_update_action: None, pending_shutdown_exit_thread_id: None, windows_sandbox: WindowsSandboxState::default(), @@ -3583,7 +3586,10 @@ impl App { let picker_app_server = match crate::start_app_server_for_picker( &self.config, &match self.remote_app_server_url.clone() { - Some(websocket_url) => crate::AppServerTarget::Remote(websocket_url), + Some(websocket_url) => crate::AppServerTarget::Remote { + websocket_url, + auth_token: self.remote_app_server_auth_token.clone(), + }, None => crate::AppServerTarget::Embedded, }, ) @@ -8121,6 +8127,7 @@ guardian_approval = true feedback: codex_feedback::CodexFeedback::new(), feedback_audience: FeedbackAudience::External, remote_app_server_url: None, + remote_app_server_auth_token: None, pending_update_action: None, pending_shutdown_exit_thread_id: None, windows_sandbox: WindowsSandboxState::default(), @@ -8173,6 +8180,7 @@ guardian_approval = true feedback: codex_feedback::CodexFeedback::new(), feedback_audience: FeedbackAudience::External, remote_app_server_url: None, + remote_app_server_auth_token: None, pending_update_action: None, pending_shutdown_exit_thread_id: None, windows_sandbox: WindowsSandboxState::default(), diff --git a/codex-rs/tui_app_server/src/lib.rs b/codex-rs/tui_app_server/src/lib.rs index 4a36eb58c6..c5e2479bf4 100644 --- a/codex-rs/tui_app_server/src/lib.rs +++ b/codex-rs/tui_app_server/src/lib.rs @@ -284,7 +284,10 @@ async fn start_embedded_app_server( #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum AppServerTarget { Embedded, - Remote(String), + Remote { + websocket_url: String, + auth_token: Option, + }, } fn remote_addr_has_explicit_port(addr: &str, parsed: &Url) -> bool { @@ -316,6 +319,16 @@ fn remote_addr_has_explicit_port(addr: &str, parsed: &Url) -> bool { host_and_port == format!("{expected_host}:{explicit_default_port}") } +fn websocket_url_supports_auth_token(parsed: &Url) -> bool { + match (parsed.scheme(), parsed.host()) { + ("wss", Some(_)) => true, + ("ws", Some(url::Host::Domain(domain))) => domain.eq_ignore_ascii_case("localhost"), + ("ws", Some(url::Host::Ipv4(addr))) => addr.is_loopback(), + ("ws", Some(url::Host::Ipv6(addr))) => addr.is_loopback(), + _ => false, + } +} + pub fn normalize_remote_addr(addr: &str) -> color_eyre::Result { let parsed = match Url::parse(addr) { Ok(parsed) => parsed, @@ -340,9 +353,24 @@ pub fn normalize_remote_addr(addr: &str) -> color_eyre::Result { ); } -async fn connect_remote_app_server(websocket_url: String) -> color_eyre::Result { +fn validate_remote_auth_token_transport(websocket_url: &str) -> color_eyre::Result<()> { + let parsed = Url::parse(websocket_url).map_err(color_eyre::Report::new)?; + if websocket_url_supports_auth_token(&parsed) { + return Ok(()); + } + + color_eyre::eyre::bail!( + "remote auth tokens require `wss://` or loopback `ws://` URLs; got `{websocket_url}`" + ) +} + +async fn connect_remote_app_server( + websocket_url: String, + auth_token: Option, +) -> color_eyre::Result { let app_server = RemoteAppServerClient::connect(RemoteAppServerConnectArgs { websocket_url, + auth_token, client_name: "codex-tui".to_string(), client_version: env!("CARGO_PKG_VERSION").to_string(), experimental_api: true, @@ -374,9 +402,10 @@ async fn start_app_server( ) .await .map(AppServerClient::InProcess), - AppServerTarget::Remote(websocket_url) => { - connect_remote_app_server(websocket_url.clone()).await - } + AppServerTarget::Remote { + websocket_url, + auth_token, + } => connect_remote_app_server(websocket_url.clone(), auth_token.clone()).await, } } @@ -590,11 +619,18 @@ pub async fn run_main( arg0_paths: Arg0DispatchPaths, loader_overrides: LoaderOverrides, remote: Option, + remote_auth_token: Option, ) -> std::io::Result { let remote_url = remote; + if let (Some(websocket_url), Some(_)) = (remote_url.as_deref(), remote_auth_token.as_ref()) { + validate_remote_auth_token_transport(websocket_url).map_err(std::io::Error::other)?; + } let app_server_target = remote_url .clone() - .map(AppServerTarget::Remote) + .map(|websocket_url| AppServerTarget::Remote { + websocket_url, + auth_token: remote_auth_token.clone(), + }) .unwrap_or(AppServerTarget::Embedded); let (sandbox_mode, approval_policy) = if cli.full_auto { ( @@ -904,6 +940,7 @@ pub async fn run_main( cloud_requirements, feedback, remote_url, + remote_auth_token, ) .await .map_err(|err| std::io::Error::other(err.to_string())) @@ -921,8 +958,9 @@ async fn run_ratatui_app( mut cloud_requirements: CloudRequirementsLoader, feedback: codex_feedback::CodexFeedback, remote_url: Option, + remote_auth_token: Option, ) -> color_eyre::Result { - let remote_mode = matches!(&app_server_target, AppServerTarget::Remote(_)); + let remote_mode = matches!(&app_server_target, AppServerTarget::Remote { .. }); color_eyre::install()?; tooltips::announcement::prewarm(); @@ -1326,6 +1364,7 @@ async fn run_ratatui_app( should_show_trust_screen, // Proxy to: is it a first run in this directory? should_prompt_windows_sandbox_nux_at_startup, remote_url, + remote_auth_token, ) .await; @@ -1724,6 +1763,32 @@ mod tests { ); } + #[test] + fn remote_auth_token_transport_accepts_loopback_ws() { + validate_remote_auth_token_transport("ws://127.0.0.1:4500/") + .expect("loopback ws should be allowed for auth tokens"); + validate_remote_auth_token_transport("ws://localhost:4500/") + .expect("localhost ws should be allowed for auth tokens"); + validate_remote_auth_token_transport("ws://[::1]:4500/") + .expect("ipv6 loopback ws should be allowed for auth tokens"); + } + + #[test] + fn remote_auth_token_transport_accepts_secure_wss() { + validate_remote_auth_token_transport("wss://example.com:443/") + .expect("wss should be allowed for auth tokens"); + } + + #[test] + fn remote_auth_token_transport_rejects_non_loopback_ws() { + let err = validate_remote_auth_token_transport("ws://example.com:4500/") + .expect_err("non-loopback ws should be rejected for auth tokens"); + assert!( + err.to_string() + .contains("remote auth tokens require `wss://` or loopback `ws://` URLs") + ); + } + #[tokio::test] async fn latest_session_lookup_params_keep_local_filters_for_embedded_sessions() -> std::io::Result<()> { diff --git a/codex-rs/tui_app_server/src/main.rs b/codex-rs/tui_app_server/src/main.rs index feda31b0b7..ae61111437 100644 --- a/codex-rs/tui_app_server/src/main.rs +++ b/codex-rs/tui_app_server/src/main.rs @@ -27,6 +27,7 @@ fn main() -> anyhow::Result<()> { arg0_paths, codex_core::config_loader::LoaderOverrides::default(), /*remote*/ None, + /*remote_auth_token*/ None, ) .await?; let token_usage = exit_info.token_usage; From 6d0525ae7015cb9239cc907fe78e88cf2fea5ce5 Mon Sep 17 00:00:00 2001 From: Tiffany Citra Date: Wed, 25 Mar 2026 21:19:57 -0700 Subject: [PATCH 008/212] Expand home-relative paths on Windows (#15817) Follow up to: https://github.com/openai/codex/pull/9193, also support this for Windows. --------- Co-authored-by: Michael Bolin --- codex-rs/utils/absolute-path/src/lib.rs | 51 +++++++++++-------------- 1 file changed, 23 insertions(+), 28 deletions(-) diff --git a/codex-rs/utils/absolute-path/src/lib.rs b/codex-rs/utils/absolute-path/src/lib.rs index 69691ac752..0de0f4e023 100644 --- a/codex-rs/utils/absolute-path/src/lib.rs +++ b/codex-rs/utils/absolute-path/src/lib.rs @@ -23,21 +23,18 @@ pub struct AbsolutePathBuf(PathBuf); impl AbsolutePathBuf { fn maybe_expand_home_directory(path: &Path) -> PathBuf { - let Some(path_str) = path.to_str() else { - return path.to_path_buf(); - }; - if cfg!(not(target_os = "windows")) + if let Some(path_str) = path.to_str() && let Some(home) = home_dir() + && let Some(rest) = path_str.strip_prefix('~') { - if path_str == "~" { + if rest.is_empty() { return home; - } - if let Some(rest) = path_str.strip_prefix("~/") { - let rest = rest.trim_start_matches('/'); - if rest.is_empty() { - return home; - } - return home.join(rest); + } else if let Some(rest) = rest.strip_prefix('/') { + return home.join(rest.trim_start_matches('/')); + } else if cfg!(windows) + && let Some(rest) = rest.strip_prefix('\\') + { + return home.join(rest.trim_start_matches('\\')); } } path.to_path_buf() @@ -257,9 +254,8 @@ mod tests { ); } - #[cfg(not(target_os = "windows"))] #[test] - fn home_directory_root_on_non_windows_is_expanded_in_deserialization() { + fn home_directory_root_is_expanded_in_deserialization() { let Some(home) = home_dir() else { return; }; @@ -271,9 +267,8 @@ mod tests { assert_eq!(abs_path_buf.as_path(), home.as_path()); } - #[cfg(not(target_os = "windows"))] #[test] - fn home_directory_subpath_on_non_windows_is_expanded_in_deserialization() { + fn home_directory_subpath_is_expanded_in_deserialization() { let Some(home) = home_dir() else { return; }; @@ -285,9 +280,8 @@ mod tests { assert_eq!(abs_path_buf.as_path(), home.join("code").as_path()); } - #[cfg(not(target_os = "windows"))] #[test] - fn home_directory_double_slash_on_non_windows_is_expanded_in_deserialization() { + fn home_directory_double_slash_is_expanded_in_deserialization() { let Some(home) = home_dir() else { return; }; @@ -301,16 +295,17 @@ mod tests { #[cfg(target_os = "windows")] #[test] - fn home_directory_on_windows_is_not_expanded_in_deserialization() { - let temp_dir = tempdir().expect("base dir"); - let base_dir = temp_dir.path(); - let abs_path_buf = { - let _guard = AbsolutePathBufGuard::new(base_dir); - serde_json::from_str::("\"~/code\"").expect("failed to deserialize") + fn home_directory_backslash_subpath_is_expanded_in_deserialization() { + let Some(home) = home_dir() else { + return; }; - assert_eq!( - abs_path_buf.as_path(), - base_dir.join("~").join("code").as_path() - ); + let temp_dir = tempdir().expect("base dir"); + let abs_path_buf = { + let _guard = AbsolutePathBufGuard::new(temp_dir.path()); + let input = + serde_json::to_string(r#"~\code"#).expect("string should serialize as JSON"); + serde_json::from_str::(&input).expect("is valid abs path") + }; + assert_eq!(abs_path_buf.as_path(), home.join("code").as_path()); } } From 937cb5081df1ac9c458a7bcd784e9878ac924a47 Mon Sep 17 00:00:00 2001 From: viyatb-oai Date: Wed, 25 Mar 2026 23:51:39 -0700 Subject: [PATCH 009/212] fix: fix old system bubblewrap compatibility without falling back to vendored bwrap (#15693) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #15283. ## Summary Older system bubblewrap builds reject `--argv0`, which makes our Linux sandbox fail before the helper can re-exec. This PR keeps using system `/usr/bin/bwrap` whenever it exists and only falls back to vendored bwrap when the system binary is missing. That matters on stricter AppArmor hosts, where the distro bwrap package also provides the policy setup needed for user namespaces. For old system bwrap, we avoid `--argv0` instead of switching binaries: - pass the sandbox helper a full-path `argv0`, - keep the existing `current_exe() + --argv0` path when the selected launcher supports it, - otherwise omit `--argv0` and re-exec through the helper's own `argv[0]` path, whose basename still dispatches as `codex-linux-sandbox`. Also updates the launcher/warning tests and docs so they match the new behavior: present-but-old system bwrap uses the compatibility path, and only absent system bwrap falls back to vendored. ### Validation 1. Install Ubuntu 20.04 in a VM 2. Compile codex and run without bubblewrap installed - see a warning about falling back to the vendored bwrap 3. Install bwrap and verify version is 0.4.0 without `argv0` support 4. run codex and use apply_patch tool without errors Screenshot 2026-03-25 at 11 48 36 PM Screenshot 2026-03-25 at 11 47 32 PM Screenshot 2026-03-25 at 11 45 45 PM Screenshot 2026-03-25 at 11 43 56 PM --------- Co-authored-by: Michael Bolin --- codex-rs/Cargo.lock | 2 + .../app-server/src/codex_message_processor.rs | 1 + codex-rs/arg0/Cargo.toml | 1 + codex-rs/arg0/src/lib.rs | 71 ++++++++++++--- codex-rs/core/README.md | 9 +- codex-rs/core/src/codex.rs | 4 + codex-rs/core/src/config/config_tests.rs | 29 ++---- codex-rs/core/src/config/mod.rs | 32 ++----- codex-rs/core/src/landlock.rs | 20 ++++- .../core/src/tools/handlers/apply_patch.rs | 2 - .../core/src/tools/runtimes/apply_patch.rs | 57 +++++++----- .../src/tools/runtimes/apply_patch_tests.rs | 75 +++++++++++++++- codex-rs/core/tests/common/lib.rs | 8 +- codex-rs/core/tests/common/test_codex.rs | 20 +++-- codex-rs/core/tests/suite/apply_patch_cli.rs | 49 ++++++++++ codex-rs/core/tests/suite/mod.rs | 22 ++++- codex-rs/exec/src/lib.rs | 1 + codex-rs/exec/tests/suite/sandbox.rs | 2 +- codex-rs/linux-sandbox/Cargo.toml | 1 + codex-rs/linux-sandbox/README.md | 27 +++--- codex-rs/linux-sandbox/src/launcher.rs | 89 ++++++++++--------- codex-rs/linux-sandbox/src/linux_run_main.rs | 57 +++++++++--- .../linux-sandbox/src/linux_run_main_tests.rs | 75 +++++++++++++++- codex-rs/mcp-server/src/codex_tool_config.rs | 1 + codex-rs/sandboxing/src/landlock.rs | 5 ++ codex-rs/sandboxing/src/manager.rs | 14 ++- codex-rs/sandboxing/src/manager_tests.rs | 51 +++++++++++ codex-rs/tui/src/lib.rs | 1 + codex-rs/tui_app_server/src/lib.rs | 1 + 29 files changed, 556 insertions(+), 171 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 02625d90c2..9fc695795d 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1595,6 +1595,7 @@ dependencies = [ "anyhow", "codex-apply-patch", "codex-linux-sandbox", + "codex-sandboxing", "codex-shell-escalation", "codex-utils-home-dir", "dotenvy", @@ -2252,6 +2253,7 @@ dependencies = [ "clap", "codex-core", "codex-protocol", + "codex-sandboxing", "codex-utils-absolute-path", "landlock", "libc", diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 4687ec5ba3..620a85a095 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -537,6 +537,7 @@ impl CodexMessageProcessor { data: None, })?; apply_runtime_feature_enablement(&mut config, &self.current_runtime_feature_enablement()); + config.codex_self_exe = self.arg0_paths.codex_self_exe.clone(); config.codex_linux_sandbox_exe = self.arg0_paths.codex_linux_sandbox_exe.clone(); config.main_execve_wrapper_exe = self.arg0_paths.main_execve_wrapper_exe.clone(); Ok(config) diff --git a/codex-rs/arg0/Cargo.toml b/codex-rs/arg0/Cargo.toml index abe7277d94..cd409fedd8 100644 --- a/codex-rs/arg0/Cargo.toml +++ b/codex-rs/arg0/Cargo.toml @@ -15,6 +15,7 @@ workspace = true anyhow = { workspace = true } codex-apply-patch = { workspace = true } codex-linux-sandbox = { workspace = true } +codex-sandboxing = { workspace = true } codex-shell-escalation = { workspace = true } codex-utils-home-dir = { workspace = true } dotenvy = { workspace = true } diff --git a/codex-rs/arg0/src/lib.rs b/codex-rs/arg0/src/lib.rs index e210783a35..efad6c2481 100644 --- a/codex-rs/arg0/src/lib.rs +++ b/codex-rs/arg0/src/lib.rs @@ -4,12 +4,12 @@ use std::path::Path; use std::path::PathBuf; use codex_apply_patch::CODEX_CORE_APPLY_PATCH_ARG1; +use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0; use codex_utils_home_dir::find_codex_home; #[cfg(unix)] use std::os::unix::fs::symlink; use tempfile::TempDir; -const LINUX_SANDBOX_ARG0: &str = "codex-linux-sandbox"; const APPLY_PATCH_ARG0: &str = "apply_patch"; const MISSPELLED_APPLY_PATCH_ARG0: &str = "applypatch"; #[cfg(unix)] @@ -19,6 +19,12 @@ const TOKIO_WORKER_STACK_SIZE_BYTES: usize = 16 * 1024 * 1024; #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct Arg0DispatchPaths { + /// Stable path to the current Codex executable for child re-execs. + /// + /// Prefer this over [`std::env::current_exe()`] in code that may run under + /// a test harness, where `current_exe()` can point at the harness binary + /// instead of the real Codex CLI. + pub codex_self_exe: Option, pub codex_linux_sandbox_exe: Option, pub main_execve_wrapper_exe: Option, } @@ -79,7 +85,7 @@ pub fn arg0_dispatch() -> Option { } } - if exe_name == LINUX_SANDBOX_ARG0 { + if exe_name == CODEX_LINUX_SANDBOX_ARG0 { // Safety: [`run_main`] never returns. codex_linux_sandbox::run_main(); } else if exe_name == APPLY_PATCH_ARG0 || exe_name == MISSPELLED_APPLY_PATCH_ARG0 { @@ -133,8 +139,10 @@ pub fn arg0_dispatch() -> Option { /// /// 1. Load `.env` values from `~/.codex/.env` before creating any threads. /// 2. Construct a Tokio multi-thread runtime. -/// 3. Derive the path to the current executable (so children can re-invoke the -/// sandbox) when running on Linux. +/// 3. Capture the current executable path and derive the +/// `codex-linux-sandbox` helper path (falling back to the current +/// executable if needed) so children can re-invoke the sandbox when running +/// on Linux. /// 4. Execute the provided async `main_fn` inside that runtime, forwarding any /// error. Note that `main_fn` receives [`Arg0DispatchPaths`], which /// contains the helper executable paths needed to construct @@ -150,7 +158,7 @@ where // Retain the TempDir so it exists for the lifetime of the invocation of // this executable. Admittedly, we could invoke `keep()` on it, but it // would be nice to avoid leaving temporary directories behind, if possible. - let path_entry = arg0_dispatch(); + let path_entry_guard = arg0_dispatch(); // Regular invocation – create a Tokio runtime and execute the provided // async entry-point. @@ -158,16 +166,13 @@ where runtime.block_on(async move { let current_exe = std::env::current_exe().ok(); let paths = Arg0DispatchPaths { + codex_self_exe: current_exe.clone(), codex_linux_sandbox_exe: if cfg!(target_os = "linux") { - current_exe.or_else(|| { - path_entry - .as_ref() - .and_then(|path_entry| path_entry.paths().codex_linux_sandbox_exe.clone()) - }) + linux_sandbox_exe_path(path_entry_guard.as_ref(), current_exe) } else { None }, - main_execve_wrapper_exe: path_entry + main_execve_wrapper_exe: path_entry_guard .as_ref() .and_then(|path_entry| path_entry.paths().main_execve_wrapper_exe.clone()), }; @@ -176,6 +181,18 @@ where }) } +fn linux_sandbox_exe_path( + path_entry_guard: Option<&Arg0PathEntryGuard>, + current_exe: Option, +) -> Option { + // Prefer the `codex-linux-sandbox` alias when available so callers can + // re-exec through a path whose basename still triggers arg0 dispatch on + // bubblewrap builds that do not support `--argv0`. + path_entry_guard + .and_then(|path_entry| path_entry.paths().codex_linux_sandbox_exe.clone()) + .or(current_exe) +} + fn build_runtime() -> anyhow::Result { let mut builder = tokio::runtime::Builder::new_multi_thread(); builder.enable_all(); @@ -276,7 +293,7 @@ pub fn prepend_path_entry_for_codex_aliases() -> std::io::Result std::io::Result std::io::Result> { #[cfg(test)] mod tests { + use super::Arg0DispatchPaths; + use super::Arg0PathEntryGuard; use super::LOCK_FILENAME; use super::janitor_cleanup; + use super::linux_sandbox_exe_path; use std::fs; use std::fs::File; use std::path::Path; + use std::path::PathBuf; + use tempfile::TempDir; fn create_lock(dir: &Path) -> std::io::Result { let lock_path = dir.join(LOCK_FILENAME); @@ -413,6 +436,28 @@ mod tests { .open(lock_path) } + #[test] + fn linux_sandbox_exe_path_prefers_codex_linux_sandbox_alias() -> std::io::Result<()> { + let temp_dir = TempDir::new()?; + let lock_file = create_lock(temp_dir.path())?; + let alias_path = temp_dir.path().join("codex-linux-sandbox"); + let path_entry = Arg0PathEntryGuard::new( + temp_dir, + lock_file, + Arg0DispatchPaths { + codex_self_exe: Some(PathBuf::from("/usr/bin/codex")), + codex_linux_sandbox_exe: Some(alias_path.clone()), + main_execve_wrapper_exe: None, + }, + ); + + assert_eq!( + linux_sandbox_exe_path(Some(&path_entry), Some(PathBuf::from("/usr/bin/codex"))), + Some(alias_path), + ); + Ok(()) + } + #[test] fn janitor_skips_dirs_without_lock_file() -> std::io::Result<()> { let root = tempfile::tempdir()?; diff --git a/codex-rs/core/README.md b/codex-rs/core/README.md index c154ef463d..4b8cb793b7 100644 --- a/codex-rs/core/README.md +++ b/codex-rs/core/README.md @@ -59,10 +59,11 @@ only when the split filesystem policy round-trips through the legacy cases like `/repo = write`, `/repo/a = none`, `/repo/a/b = write`, where the more specific writable child must reopen under a denied parent. -The Linux sandbox helper prefers `/usr/bin/bwrap` whenever it is available and -supports the required argv-rewrite flags, and falls back to the vendored -bubblewrap path compiled into the binary otherwise. When `/usr/bin/bwrap` is -missing or too old to support the required flags, Codex also surfaces a startup +The Linux sandbox helper prefers `/usr/bin/bwrap` whenever it is available. If +`/usr/bin/bwrap` is present but too old to support `--argv0`, the helper keeps +using system bubblewrap and switches to a no-`--argv0` compatibility path for +the inner re-exec. If `/usr/bin/bwrap` is missing, it falls back to the +vendored bubblewrap path compiled into the binary and Codex surfaces a startup warning through its normal notification path instead of printing directly from the sandbox helper. diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index a4bdb2c944..f29d37fe25 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -867,6 +867,7 @@ pub(crate) struct TurnContext { pub(crate) features: ManagedFeatures, pub(crate) ghost_snapshot: GhostSnapshotConfig, pub(crate) final_output_json_schema: Option, + pub(crate) codex_self_exe: Option, pub(crate) codex_linux_sandbox_exe: Option, pub(crate) tool_call_gate: Arc, pub(crate) truncation_policy: TruncationPolicy, @@ -974,6 +975,7 @@ impl TurnContext { features, ghost_snapshot: self.ghost_snapshot.clone(), final_output_json_schema: self.final_output_json_schema.clone(), + codex_self_exe: self.codex_self_exe.clone(), codex_linux_sandbox_exe: self.codex_linux_sandbox_exe.clone(), tool_call_gate: Arc::new(ReadinessFlag::new()), truncation_policy, @@ -1431,6 +1433,7 @@ impl Session { features: per_turn_config.features.clone(), ghost_snapshot: per_turn_config.ghost_snapshot.clone(), final_output_json_schema: None, + codex_self_exe: per_turn_config.codex_self_exe.clone(), codex_linux_sandbox_exe: per_turn_config.codex_linux_sandbox_exe.clone(), tool_call_gate: Arc::new(ReadinessFlag::new()), truncation_policy: model_info.truncation_policy.into(), @@ -5477,6 +5480,7 @@ async fn spawn_review_thread( shell_environment_policy: parent_turn_context.shell_environment_policy.clone(), cwd: parent_turn_context.cwd.clone(), final_output_json_schema: None, + codex_self_exe: parent_turn_context.codex_self_exe.clone(), codex_linux_sandbox_exe: parent_turn_context.codex_linux_sandbox_exe.clone(), tool_call_gate: Arc::new(ReadinessFlag::new()), js_repl: Arc::clone(&sess.js_repl), diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index 84ac6d71bc..7d2f6c573a 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -4417,6 +4417,7 @@ fn test_precedence_fixture_with_o3_profile() -> std::io::Result<()> { history: History::default(), ephemeral: false, file_opener: UriBasedFileOpener::VsCode, + codex_self_exe: None, codex_linux_sandbox_exe: None, main_execve_wrapper_exe: None, js_repl_node_path: None, @@ -4559,6 +4560,7 @@ fn test_precedence_fixture_with_gpt3_profile() -> std::io::Result<()> { history: History::default(), ephemeral: false, file_opener: UriBasedFileOpener::VsCode, + codex_self_exe: None, codex_linux_sandbox_exe: None, main_execve_wrapper_exe: None, js_repl_node_path: None, @@ -4699,6 +4701,7 @@ fn test_precedence_fixture_with_zdr_profile() -> std::io::Result<()> { history: History::default(), ephemeral: false, file_opener: UriBasedFileOpener::VsCode, + codex_self_exe: None, codex_linux_sandbox_exe: None, main_execve_wrapper_exe: None, js_repl_node_path: None, @@ -4825,6 +4828,7 @@ fn test_precedence_fixture_with_gpt5_profile() -> std::io::Result<()> { history: History::default(), ephemeral: false, file_opener: UriBasedFileOpener::VsCode, + codex_self_exe: None, codex_linux_sandbox_exe: None, main_execve_wrapper_exe: None, js_repl_node_path: None, @@ -5708,7 +5712,7 @@ fn system_bwrap_warning_reports_missing_system_bwrap() { #[cfg(target_os = "linux")] #[test] -fn system_bwrap_warning_reports_too_old_system_bwrap() { +fn system_bwrap_warning_skips_too_old_system_bwrap() { let fake_bwrap = write_fake_bwrap( r#"#!/bin/sh if [ "$1" = "--help" ]; then @@ -5719,27 +5723,12 @@ exit 1 "#, ); let fake_bwrap_path: &Path = fake_bwrap.as_ref(); - let warning = system_bwrap_warning_for_path(fake_bwrap_path) - .expect("old system bwrap should emit a warning"); - assert!(warning.contains("too old to support `--argv0`")); -} - -#[cfg(target_os = "linux")] -#[test] -fn system_bwrap_warning_skips_supported_system_bwrap() { - let fake_bwrap = write_fake_bwrap( - r#"#!/bin/sh -if [ "$1" = "--help" ]; then - echo ' --argv0 PROGRAM' - exit 0 -fi -exit 1 -"#, + assert_eq!( + system_bwrap_warning_for_path(fake_bwrap_path), + None, + "Do not warn even if bwrap does not support `--argv0`", ); - let fake_bwrap_path: &Path = fake_bwrap.as_ref(); - - assert_eq!(system_bwrap_warning_for_path(fake_bwrap_path), None); } #[cfg(not(target_os = "linux"))] diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 761e43b936..b2b55feeca 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -96,8 +96,6 @@ use std::collections::HashMap; use std::io::ErrorKind; use std::path::Path; use std::path::PathBuf; -#[cfg(target_os = "linux")] -use std::process::Command; use crate::config::permissions::compile_permission_profile; use crate::config::permissions::get_readable_roots_required_for_codex_runtime; @@ -172,27 +170,8 @@ fn system_bwrap_warning_for_path(system_bwrap_path: &Path) -> Option { system_bwrap_path.display() )); } - if system_bwrap_supports_argv0(system_bwrap_path) { - return None; - } - Some(format!( - "Codex found system bubblewrap at {}, but it is too old to support `--argv0`. Please upgrade bubblewrap with your package manager. Codex will use the vendored bubblewrap in the meantime.", - system_bwrap_path.display() - )) -} - -#[cfg(target_os = "linux")] -fn system_bwrap_supports_argv0(system_bwrap_path: &Path) -> bool { - // bubblewrap added `--argv0` in v0.9.0: - // https://github.com/containers/bubblewrap/releases/tag/v0.9.0 - let output = match Command::new(system_bwrap_path).arg("--help").output() { - Ok(output) => output, - Err(_) => return false, - }; - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - stdout.contains("--argv0") || stderr.contains("--argv0") + None } fn resolve_sqlite_home_env(resolved_cwd: &Path) -> Option { @@ -476,6 +455,10 @@ pub struct Config { /// output will be hyperlinked using the specified URI scheme. pub file_opener: UriBasedFileOpener, + /// Path to the current Codex executable. This cannot be set in the config + /// file: it must be set in code via [`ConfigOverrides`]. + pub codex_self_exe: Option, + /// Path to the `codex-linux-sandbox` executable. This must be set if /// [`codex_sandboxing::SandboxType::LinuxSeccomp`] is used. Note that this /// cannot be set in the config file: it must be set in code via @@ -760,7 +743,7 @@ impl Config { /// designed to use [AskForApproval::Never] exclusively. /// /// Further, [ConfigOverrides] contains some options that are not supported - /// in [ConfigToml], such as `cwd`, `codex_linux_sandbox_exe`, and + /// in [ConfigToml], such as `cwd`, `codex_self_exe`, `codex_linux_sandbox_exe`, and /// `main_execve_wrapper_exe`. pub async fn load_with_cli_overrides_and_harness_overrides( cli_overrides: Vec<(String, TomlValue)>, @@ -1838,6 +1821,7 @@ pub struct ConfigOverrides { pub model_provider: Option, pub service_tier: Option>, pub config_profile: Option, + pub codex_self_exe: Option, pub codex_linux_sandbox_exe: Option, pub main_execve_wrapper_exe: Option, pub js_repl_node_path: Option, @@ -2036,6 +2020,7 @@ impl Config { model_provider, service_tier: service_tier_override, config_profile: config_profile_key, + codex_self_exe, codex_linux_sandbox_exe, main_execve_wrapper_exe, js_repl_node_path: js_repl_node_path_override, @@ -2642,6 +2627,7 @@ impl Config { history, ephemeral: ephemeral.unwrap_or_default(), file_opener: cfg.file_opener.unwrap_or(UriBasedFileOpener::VsCode), + codex_self_exe, codex_linux_sandbox_exe, main_execve_wrapper_exe, js_repl_node_path, diff --git a/codex-rs/core/src/landlock.rs b/codex-rs/core/src/landlock.rs index c1dc4ba542..ef55a207e2 100644 --- a/codex-rs/core/src/landlock.rs +++ b/codex-rs/core/src/landlock.rs @@ -5,6 +5,7 @@ use crate::spawn::spawn_child_async; use codex_network_proxy::NetworkProxy; use codex_protocol::permissions::FileSystemSandboxPolicy; use codex_protocol::permissions::NetworkSandboxPolicy; +use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0; use codex_sandboxing::landlock::allow_network_for_proxy; use codex_sandboxing::landlock::create_linux_sandbox_command_args_for_policies; use std::collections::HashMap; @@ -48,11 +49,24 @@ where use_legacy_landlock, allow_network_for_proxy(/*enforce_managed_network*/ false), ); - let arg0 = Some("codex-linux-sandbox"); + let codex_linux_sandbox_exe = codex_linux_sandbox_exe.as_ref(); + // Preserve the helper alias when we already have it; otherwise force argv0 + // so arg0 dispatch still reaches the Linux sandbox path. + let arg0 = if codex_linux_sandbox_exe + .file_name() + .and_then(|name| name.to_str()) + == Some(CODEX_LINUX_SANDBOX_ARG0) + { + // Old bubblewrap builds without `--argv0` need a real helper path whose + // basename still dispatches to the Linux sandbox entrypoint. + codex_linux_sandbox_exe.to_string_lossy().into_owned() + } else { + CODEX_LINUX_SANDBOX_ARG0.to_string() + }; spawn_child_async(SpawnChildRequest { - program: codex_linux_sandbox_exe.as_ref().to_path_buf(), + program: codex_linux_sandbox_exe.to_path_buf(), args, - arg0, + arg0: Some(&arg0), cwd: command_cwd, network_sandbox_policy, network, diff --git a/codex-rs/core/src/tools/handlers/apply_patch.rs b/codex-rs/core/src/tools/handlers/apply_patch.rs index 62ebde48b8..edb94fb4f0 100644 --- a/codex-rs/core/src/tools/handlers/apply_patch.rs +++ b/codex-rs/core/src/tools/handlers/apply_patch.rs @@ -205,7 +205,6 @@ impl ToolHandler for ApplyPatchHandler { permissions_preapproved: effective_additional_permissions .permissions_preapproved, timeout_ms: None, - codex_exe: turn.codex_linux_sandbox_exe.clone(), }; let mut orchestrator = ToolOrchestrator::new(); @@ -308,7 +307,6 @@ pub(crate) async fn intercept_apply_patch( permissions_preapproved: effective_additional_permissions .permissions_preapproved, timeout_ms, - codex_exe: turn.codex_linux_sandbox_exe.clone(), }; let mut orchestrator = ToolOrchestrator::new(); diff --git a/codex-rs/core/src/tools/runtimes/apply_patch.rs b/codex-rs/core/src/tools/runtimes/apply_patch.rs index 7f5686e47d..c476d47738 100644 --- a/codex-rs/core/src/tools/runtimes/apply_patch.rs +++ b/codex-rs/core/src/tools/runtimes/apply_patch.rs @@ -42,7 +42,6 @@ pub struct ApplyPatchRequest { pub additional_permissions: Option, pub permissions_preapproved: bool, pub timeout_ms: Option, - pub codex_exe: Option, } #[derive(Default)] @@ -66,25 +65,38 @@ impl ApplyPatchRuntime { } } + #[cfg(target_os = "windows")] fn build_sandbox_command( req: &ApplyPatchRequest, - _codex_home: &std::path::Path, + codex_home: &std::path::Path, ) -> Result { - let exe = if let Some(path) = &req.codex_exe { - path.clone() - } else { - #[cfg(target_os = "windows")] - { - codex_windows_sandbox::resolve_current_exe_for_launch(_codex_home, "codex.exe") - } - #[cfg(not(target_os = "windows"))] - { - std::env::current_exe().map_err(|e| { - ToolError::Rejected(format!("failed to determine codex exe: {e}")) - })? - } - }; - Ok(SandboxCommand { + Ok(Self::build_sandbox_command_with_program( + req, + codex_windows_sandbox::resolve_current_exe_for_launch(codex_home, "codex.exe"), + )) + } + + #[cfg(not(target_os = "windows"))] + fn build_sandbox_command( + req: &ApplyPatchRequest, + codex_self_exe: Option<&PathBuf>, + ) -> Result { + let exe = Self::resolve_apply_patch_program(codex_self_exe)?; + Ok(Self::build_sandbox_command_with_program(req, exe)) + } + + #[cfg(not(target_os = "windows"))] + fn resolve_apply_patch_program(codex_self_exe: Option<&PathBuf>) -> Result { + if let Some(path) = codex_self_exe { + return Ok(path.clone()); + } + + std::env::current_exe() + .map_err(|e| ToolError::Rejected(format!("failed to determine codex exe: {e}"))) + } + + fn build_sandbox_command_with_program(req: &ApplyPatchRequest, exe: PathBuf) -> SandboxCommand { + SandboxCommand { program: exe.to_string_lossy().to_string(), args: vec![ CODEX_CORE_APPLY_PATCH_ARG1.to_string(), @@ -94,7 +106,7 @@ impl ApplyPatchRuntime { // Run apply_patch with a minimal environment for determinism and to avoid leaks. env: HashMap::new(), additional_permissions: req.additional_permissions.clone(), - }) + } } fn stdout_stream(ctx: &ToolCtx) -> Option { @@ -134,13 +146,13 @@ impl Approvable for ApplyPatchRuntime { let approval_keys = self.approval_keys(req); let changes = req.changes.clone(); Box::pin(async move { + if req.permissions_preapproved && retry_reason.is_none() { + return ReviewDecision::Approved; + } if routes_approval_to_guardian(turn) { let action = ApplyPatchRuntime::build_guardian_review_request(req, ctx.call_id); return review_approval_request(session, turn, action, retry_reason).await; } - if req.permissions_preapproved && retry_reason.is_none() { - return ReviewDecision::Approved; - } if let Some(reason) = retry_reason { let rx_approve = session .request_patch_approval( @@ -200,7 +212,10 @@ impl ToolRuntime for ApplyPatchRuntime { attempt: &SandboxAttempt<'_>, ctx: &ToolCtx, ) -> Result { + #[cfg(target_os = "windows")] let command = Self::build_sandbox_command(req, &ctx.turn.config.codex_home)?; + #[cfg(not(target_os = "windows"))] + let command = Self::build_sandbox_command(req, ctx.turn.codex_self_exe.as_ref())?; let options = ExecOptions { expiration: req.timeout_ms.into(), capture_policy: ExecCapturePolicy::ShellTool, diff --git a/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs b/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs index 79e35a9c2d..e38bf5bb05 100644 --- a/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs +++ b/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs @@ -2,6 +2,8 @@ use super::*; use codex_protocol::protocol::GranularApprovalConfig; use pretty_assertions::assert_eq; use std::collections::HashMap; +#[cfg(not(target_os = "windows"))] +use std::path::PathBuf; #[test] fn wants_no_sandbox_approval_granular_respects_sandbox_flag() { @@ -51,7 +53,6 @@ fn guardian_review_request_includes_patch_context() { additional_permissions: None, permissions_preapproved: false, timeout_ms: None, - codex_exe: None, }; let guardian_request = ApplyPatchRuntime::build_guardian_review_request(&request, "call-1"); @@ -67,3 +68,75 @@ fn guardian_review_request_includes_patch_context() { } ); } + +#[cfg(not(target_os = "windows"))] +#[test] +fn build_sandbox_command_prefers_configured_codex_self_exe_for_apply_patch() { + let path = std::env::temp_dir().join("apply-patch-current-exe-test.txt"); + let action = ApplyPatchAction::new_add_for_test(&path, "hello".to_string()); + let request = ApplyPatchRequest { + action, + file_paths: vec![ + AbsolutePathBuf::from_absolute_path(&path).expect("temp path should be absolute"), + ], + changes: HashMap::from([( + path, + FileChange::Add { + content: "hello".to_string(), + }, + )]), + exec_approval_requirement: ExecApprovalRequirement::NeedsApproval { + reason: None, + proposed_execpolicy_amendment: None, + }, + additional_permissions: None, + permissions_preapproved: false, + timeout_ms: None, + }; + let codex_self_exe = PathBuf::from("/tmp/codex"); + + let command = ApplyPatchRuntime::build_sandbox_command(&request, Some(&codex_self_exe)) + .expect("build sandbox command"); + + assert_eq!( + command.program, + codex_self_exe.to_string_lossy().to_string() + ); +} + +#[cfg(not(target_os = "windows"))] +#[test] +fn build_sandbox_command_falls_back_to_current_exe_for_apply_patch() { + let path = std::env::temp_dir().join("apply-patch-current-exe-test.txt"); + let action = ApplyPatchAction::new_add_for_test(&path, "hello".to_string()); + let request = ApplyPatchRequest { + action, + file_paths: vec![ + AbsolutePathBuf::from_absolute_path(&path).expect("temp path should be absolute"), + ], + changes: HashMap::from([( + path, + FileChange::Add { + content: "hello".to_string(), + }, + )]), + exec_approval_requirement: ExecApprovalRequirement::NeedsApproval { + reason: None, + proposed_execpolicy_amendment: None, + }, + additional_permissions: None, + permissions_preapproved: false, + timeout_ms: None, + }; + + let command = + ApplyPatchRuntime::build_sandbox_command(&request, None).expect("build sandbox command"); + + assert_eq!( + command.program, + std::env::current_exe() + .expect("current exe") + .to_string_lossy() + .to_string() + ); +} diff --git a/codex-rs/core/tests/common/lib.rs b/codex-rs/core/tests/common/lib.rs index 484bd189ef..8c03971ad7 100644 --- a/codex-rs/core/tests/common/lib.rs +++ b/codex-rs/core/tests/common/lib.rs @@ -208,10 +208,6 @@ fn default_test_overrides() -> ConfigOverrides { #[cfg(target_os = "linux")] pub fn find_codex_linux_sandbox_exe() -> Result { - if let Ok(path) = std::env::current_exe() { - return Ok(path); - } - if let Some(path) = TEST_ARG0_PATH_ENTRY .get() .and_then(Option::as_ref) @@ -220,6 +216,10 @@ pub fn find_codex_linux_sandbox_exe() -> Result { return Ok(path); } + if let Ok(path) = std::env::current_exe() { + return Ok(path); + } + codex_utils_cargo_bin::cargo_bin("codex-linux-sandbox") } diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index 5ed5e8a731..efbcf8d8ce 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -568,15 +568,21 @@ impl TestCodexBuilder { hook(home.path()); } if let Ok(path) = codex_utils_cargo_bin::cargo_bin("codex") { - config.codex_linux_sandbox_exe = Some(path); + config.codex_self_exe = Some(path); + } else if let Ok(path) = codex_utils_cargo_bin::cargo_bin("codex-exec") { + // `codex-exec` also supports `--codex-run-as-apply-patch`, so use it + // when the multitool binary is not available in test builds. + config.codex_self_exe = Some(path); } else if let Ok(exe) = std::env::current_exe() - && let Some(path) = exe - .parent() - .and_then(|parent| parent.parent()) - .map(|parent| parent.join("codex")) - && path.is_file() + && let Some(bin_dir) = exe.parent().and_then(|parent| parent.parent()) { - config.codex_linux_sandbox_exe = Some(path); + let codex = bin_dir.join("codex"); + let codex_exec = bin_dir.join("codex-exec"); + if codex.is_file() { + config.codex_self_exe = Some(codex); + } else if codex_exec.is_file() { + config.codex_self_exe = Some(codex_exec); + } } let mut mutators = vec![]; diff --git a/codex-rs/core/tests/suite/apply_patch_cli.rs b/codex-rs/core/tests/suite/apply_patch_cli.rs index d0cefcb616..15fd3b7d36 100644 --- a/codex-rs/core/tests/suite/apply_patch_cli.rs +++ b/codex-rs/core/tests/suite/apply_patch_cli.rs @@ -19,6 +19,8 @@ use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; use codex_protocol::protocol::SandboxPolicy; use codex_protocol::user_input::UserInput; +#[cfg(target_os = "linux")] +use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0; use core_test_support::assert_regex_match; use core_test_support::responses::ev_apply_patch_function_call; use core_test_support::responses::ev_assistant_message; @@ -87,6 +89,53 @@ fn apply_patch_responses( ] } +#[cfg(target_os = "linux")] +#[large_stack_test] +async fn apply_patch_cli_uses_codex_self_exe_with_linux_sandbox_helper_alias() -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness().await?; + let codex_linux_sandbox_exe = harness + .test() + .config + .codex_linux_sandbox_exe + .as_ref() + .expect("linux test config should include codex-linux-sandbox helper"); + assert_eq!( + codex_linux_sandbox_exe + .file_name() + .and_then(|name| name.to_str()), + Some(CODEX_LINUX_SANDBOX_ARG0), + ); + + let patch = "*** Begin Patch\n*** Add File: helper-alias.txt\n+hello\n*** End Patch"; + let call_id = "apply-helper-alias"; + mount_apply_patch( + &harness, + call_id, + patch, + "done", + ApplyPatchModelOutput::Function, + ) + .await; + + harness.submit("please apply helper alias patch").await?; + + let out = harness + .apply_patch_output(call_id, ApplyPatchModelOutput::Function) + .await; + assert_regex_match( + r"(?s)^Exit code: 0.*Success\. Updated the following files:\nA helper-alias\.txt\n?$", + &out, + ); + assert_eq!( + fs::read_to_string(harness.path("helper-alias.txt"))?, + "hello\n" + ); + + Ok(()) +} + #[large_stack_test] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs index d540b01bbf..5bbf233f1e 100644 --- a/codex-rs/core/tests/suite/mod.rs +++ b/codex-rs/core/tests/suite/mod.rs @@ -1,8 +1,11 @@ // Aggregates all former standalone integration tests as modules. use std::ffi::OsString; +use std::path::Path; +use codex_apply_patch::CODEX_CORE_APPLY_PATCH_ARG1; use codex_arg0::Arg0PathEntryGuard; use codex_arg0::arg0_dispatch; +use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0; use ctor::ctor; use tempfile::TempDir; @@ -19,7 +22,20 @@ const CODEX_HOME_ENV_VAR: &str = "CODEX_HOME"; // based on the arg0. // NOTE: this doesn't work on ARM #[ctor] -pub static CODEX_ALIASES_TEMP_DIR: TestCodexAliasesGuard = unsafe { +pub static CODEX_ALIASES_TEMP_DIR: Option = { + let mut args = std::env::args_os(); + let argv0 = args.next().unwrap_or_default(); + let exe_name = Path::new(&argv0) + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or(""); + let argv1 = args.next().unwrap_or_default(); + // Helper re-execs inherit this ctor too, but they may run inside a sandbox + // where creating another CODEX_HOME tempdir under /tmp is not allowed. + if exe_name == CODEX_LINUX_SANDBOX_ARG0 || argv1 == CODEX_CORE_APPLY_PATCH_ARG1 { + return None; + } + #[allow(clippy::unwrap_used)] let codex_home = tempfile::Builder::new() .prefix("codex-core-tests") @@ -47,11 +63,11 @@ pub static CODEX_ALIASES_TEMP_DIR: TestCodexAliasesGuard = unsafe { }, } - TestCodexAliasesGuard { + Some(TestCodexAliasesGuard { _codex_home: codex_home, _arg0: arg0, _previous_codex_home: previous_codex_home, - } + }) }; #[cfg(not(target_os = "windows"))] diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index c4f106b464..0cc5ad28ca 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -327,6 +327,7 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result cwd: resolved_cwd, model_provider: model_provider.clone(), service_tier: None, + codex_self_exe: arg0_paths.codex_self_exe.clone(), codex_linux_sandbox_exe: arg0_paths.codex_linux_sandbox_exe.clone(), main_execve_wrapper_exe: arg0_paths.main_execve_wrapper_exe.clone(), js_repl_node_path: None, diff --git a/codex-rs/exec/tests/suite/sandbox.rs b/codex-rs/exec/tests/suite/sandbox.rs index e6dd37927b..744a9998ff 100644 --- a/codex-rs/exec/tests/suite/sandbox.rs +++ b/codex-rs/exec/tests/suite/sandbox.rs @@ -43,7 +43,7 @@ async fn spawn_command_under_sandbox( env: HashMap, ) -> std::io::Result { use codex_core::landlock::spawn_command_under_linux_sandbox; - let codex_linux_sandbox_exe = codex_utils_cargo_bin::cargo_bin("codex-exec") + let codex_linux_sandbox_exe = core_test_support::find_codex_linux_sandbox_exe() .map_err(|err| io::Error::new(io::ErrorKind::NotFound, err))?; spawn_command_under_linux_sandbox( codex_linux_sandbox_exe, diff --git a/codex-rs/linux-sandbox/Cargo.toml b/codex-rs/linux-sandbox/Cargo.toml index 88da2d7479..c0bfc7aca2 100644 --- a/codex-rs/linux-sandbox/Cargo.toml +++ b/codex-rs/linux-sandbox/Cargo.toml @@ -19,6 +19,7 @@ workspace = true clap = { workspace = true, features = ["derive"] } codex-core = { workspace = true } codex-protocol = { workspace = true } +codex-sandboxing = { workspace = true } codex-utils-absolute-path = { workspace = true } landlock = { workspace = true } libc = { workspace = true } diff --git a/codex-rs/linux-sandbox/README.md b/codex-rs/linux-sandbox/README.md index ac34fb4edc..5898a9c688 100644 --- a/codex-rs/linux-sandbox/README.md +++ b/codex-rs/linux-sandbox/README.md @@ -8,23 +8,24 @@ This crate is responsible for producing: - this should also be true of the `codex` multitool CLI On Linux, the bubblewrap pipeline prefers the system `/usr/bin/bwrap` whenever -it is available and supports the required argv-rewrite flags. If `/usr/bin/bwrap` -is missing or too old to support the required flags, the helper falls back to -the vendored bubblewrap path compiled into this binary. -Codex also surfaces a startup warning when `/usr/bin/bwrap` is missing or too -old to support the required flags so users know it is falling back to the -vendored helper. +it is available. If `/usr/bin/bwrap` is present but too old to support +`--argv0`, the helper keeps using system bubblewrap and switches to a +no-`--argv0` compatibility path for the inner re-exec. If `/usr/bin/bwrap` is +missing, the helper falls back to the vendored bubblewrap path compiled into +this binary. +Codex also surfaces a startup warning when `/usr/bin/bwrap` is missing so users +know it is falling back to the vendored helper. **Current Behavior** - Legacy `SandboxPolicy` / `sandbox_mode` configs remain supported. - Bubblewrap is the default filesystem sandbox pipeline. -- If `/usr/bin/bwrap` is present and supports the required argv-rewrite flags, - the helper uses it. -- If `/usr/bin/bwrap` is missing or too old to support the required flags, the - helper falls back to the vendored bubblewrap path. -- If `/usr/bin/bwrap` is missing or too old to support the required flags, - Codex also surfaces a startup warning instead of printing directly from the - sandbox helper. +- If `/usr/bin/bwrap` is present, the helper uses it. +- If `/usr/bin/bwrap` is present but too old to support `--argv0`, the helper + uses a no-`--argv0` compatibility path for the inner re-exec. +- If `/usr/bin/bwrap` is missing, the helper falls back to the vendored + bubblewrap path. +- If `/usr/bin/bwrap` is missing, Codex also surfaces a startup warning instead + of printing directly from the sandbox helper. - Legacy Landlock + mount protections remain available as an explicit legacy fallback path. - Set `features.use_legacy_landlock = true` (or CLI `-c use_legacy_landlock=true`) diff --git a/codex-rs/linux-sandbox/src/launcher.rs b/codex-rs/linux-sandbox/src/launcher.rs index 7d7e040844..e68eea2725 100644 --- a/codex-rs/linux-sandbox/src/launcher.rs +++ b/codex-rs/linux-sandbox/src/launcher.rs @@ -14,13 +14,21 @@ const SYSTEM_BWRAP_PATH: &str = "/usr/bin/bwrap"; #[derive(Debug, Clone, PartialEq, Eq)] enum BubblewrapLauncher { - System(AbsolutePathBuf), + System(SystemBwrapLauncher), Vendored, } +#[derive(Debug, Clone, PartialEq, Eq)] +struct SystemBwrapLauncher { + program: AbsolutePathBuf, + supports_argv0: bool, +} + pub(crate) fn exec_bwrap(argv: Vec, preserved_files: Vec) -> ! { match preferred_bwrap_launcher() { - BubblewrapLauncher::System(program) => exec_system_bwrap(&program, argv, preserved_files), + BubblewrapLauncher::System(launcher) => { + exec_system_bwrap(&launcher.program, argv, preserved_files) + } BubblewrapLauncher::Vendored => exec_vendored_bwrap(argv, preserved_files), } } @@ -33,10 +41,18 @@ fn preferred_bwrap_launcher() -> BubblewrapLauncher { } fn preferred_bwrap_launcher_for_path(system_bwrap_path: &Path) -> BubblewrapLauncher { - if !system_bwrap_supports_argv0(system_bwrap_path) { + preferred_bwrap_launcher_for_path_with_probe(system_bwrap_path, system_bwrap_supports_argv0) +} + +fn preferred_bwrap_launcher_for_path_with_probe( + system_bwrap_path: &Path, + system_bwrap_supports_argv0: impl FnOnce(&Path) -> bool, +) -> BubblewrapLauncher { + if !system_bwrap_path.is_file() { return BubblewrapLauncher::Vendored; } + let supports_argv0 = system_bwrap_supports_argv0(system_bwrap_path); let system_bwrap_path = match AbsolutePathBuf::from_absolute_path(system_bwrap_path) { Ok(path) => path, Err(err) => panic!( @@ -44,14 +60,25 @@ fn preferred_bwrap_launcher_for_path(system_bwrap_path: &Path) -> BubblewrapLaun system_bwrap_path.display() ), }; - BubblewrapLauncher::System(system_bwrap_path) + BubblewrapLauncher::System(SystemBwrapLauncher { + program: system_bwrap_path, + supports_argv0, + }) +} + +pub(crate) fn preferred_bwrap_supports_argv0() -> bool { + match preferred_bwrap_launcher() { + BubblewrapLauncher::System(launcher) => launcher.supports_argv0, + BubblewrapLauncher::Vendored => true, + } } fn system_bwrap_supports_argv0(system_bwrap_path: &Path) -> bool { // bubblewrap added `--argv0` in v0.9.0: // https://github.com/containers/bubblewrap/releases/tag/v0.9.0 // Older distro packages (for example Ubuntu 20.04/22.04) ship builds that - // reject `--argv0`, so prefer the vendored build in that case. + // reject `--argv0`, so use the system binary's no-argv0 compatibility path + // in that case. let output = match Command::new(system_bwrap_path).arg("--help").output() { Ok(output) => output, Err(_) => return false, @@ -126,47 +153,34 @@ fn clear_cloexec(fd: libc::c_int) { mod tests { use super::*; use pretty_assertions::assert_eq; - use std::fs; - use std::os::unix::fs::PermissionsExt; use tempfile::NamedTempFile; - use tempfile::TempPath; #[test] fn prefers_system_bwrap_when_help_lists_argv0() { - let fake_bwrap = write_fake_bwrap( - r#"#!/bin/sh -if [ "$1" = "--help" ]; then - echo ' --argv0 PROGRAM' - exit 0 -fi -exit 1 -"#, - ); - let fake_bwrap_path: &Path = fake_bwrap.as_ref(); + let fake_bwrap = NamedTempFile::new().expect("temp file"); + let fake_bwrap_path = fake_bwrap.path(); let expected = AbsolutePathBuf::from_absolute_path(fake_bwrap_path).expect("absolute"); assert_eq!( - preferred_bwrap_launcher_for_path(fake_bwrap_path), - BubblewrapLauncher::System(expected) + preferred_bwrap_launcher_for_path_with_probe(fake_bwrap_path, |_| true), + BubblewrapLauncher::System(SystemBwrapLauncher { + program: expected, + supports_argv0: true, + }) ); } #[test] - fn falls_back_to_vendored_when_system_bwrap_lacks_argv0() { - let fake_bwrap = write_fake_bwrap( - r#"#!/bin/sh -if [ "$1" = "--help" ]; then - echo 'usage: bwrap [OPTION...] COMMAND' - exit 0 -fi -exit 1 -"#, - ); - let fake_bwrap_path: &Path = fake_bwrap.as_ref(); + fn prefers_system_bwrap_when_system_bwrap_lacks_argv0() { + let fake_bwrap = NamedTempFile::new().expect("temp file"); + let fake_bwrap_path = fake_bwrap.path(); assert_eq!( - preferred_bwrap_launcher_for_path(fake_bwrap_path), - BubblewrapLauncher::Vendored + preferred_bwrap_launcher_for_path_with_probe(fake_bwrap_path, |_| false), + BubblewrapLauncher::System(SystemBwrapLauncher { + program: AbsolutePathBuf::from_absolute_path(fake_bwrap_path).expect("absolute"), + supports_argv0: false, + }) ); } @@ -207,13 +221,4 @@ exit 1 } flags } - - fn write_fake_bwrap(contents: &str) -> TempPath { - // Linux rejects exec-ing a file that is still open for writing. - let path = NamedTempFile::new().expect("temp file").into_temp_path(); - fs::write(&path, contents).expect("write fake bwrap"); - let permissions = fs::Permissions::from_mode(0o755); - fs::set_permissions(&path, permissions).expect("chmod fake bwrap"); - path - } } diff --git a/codex-rs/linux-sandbox/src/linux_run_main.rs b/codex-rs/linux-sandbox/src/linux_run_main.rs index b753460dcb..8f39837de1 100644 --- a/codex-rs/linux-sandbox/src/linux_run_main.rs +++ b/codex-rs/linux-sandbox/src/linux_run_main.rs @@ -12,11 +12,13 @@ use crate::bwrap::BwrapOptions; use crate::bwrap::create_bwrap_command_args; use crate::landlock::apply_sandbox_policy_to_current_thread; use crate::launcher::exec_bwrap; +use crate::launcher::preferred_bwrap_supports_argv0; use crate::proxy_routing::activate_proxy_routes_in_netns; use crate::proxy_routing::prepare_host_proxy_route_spec; use codex_protocol::protocol::FileSystemSandboxPolicy; use codex_protocol::protocol::NetworkSandboxPolicy; use codex_protocol::protocol::SandboxPolicy; +use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0; #[derive(Debug, Parser)] /// CLI surface for the Linux sandbox helper. @@ -426,13 +428,14 @@ fn run_bwrap_with_proc_fallback( mount_proc, network_mode, }; - let bwrap_args = build_bwrap_argv( + let mut bwrap_args = build_bwrap_argv( inner, file_system_sandbox_policy, sandbox_policy_cwd, command_cwd, options, ); + apply_inner_command_argv0(&mut bwrap_args.args); exec_bwrap(bwrap_args.args, bwrap_args.preserved_files); } @@ -456,7 +459,7 @@ fn build_bwrap_argv( command_cwd: &Path, options: BwrapOptions, ) -> crate::bwrap::BwrapArgs { - let mut bwrap_args = create_bwrap_command_args( + let bwrap_args = create_bwrap_command_args( inner, file_system_sandbox_policy, sandbox_policy_cwd, @@ -465,16 +468,6 @@ fn build_bwrap_argv( ) .unwrap_or_else(|err| panic!("error building bubblewrap command: {err:?}")); - let command_separator_index = bwrap_args - .args - .iter() - .position(|arg| arg == "--") - .unwrap_or_else(|| panic!("bubblewrap argv is missing command separator '--'")); - bwrap_args.args.splice( - command_separator_index..command_separator_index, - ["--argv0".to_string(), "codex-linux-sandbox".to_string()], - ); - let mut argv = vec!["bwrap".to_string()]; argv.extend(bwrap_args.args); crate::bwrap::BwrapArgs { @@ -483,6 +476,46 @@ fn build_bwrap_argv( } } +fn apply_inner_command_argv0(argv: &mut Vec) { + apply_inner_command_argv0_for_launcher( + argv, + preferred_bwrap_supports_argv0(), + current_process_argv0(), + ); +} + +fn apply_inner_command_argv0_for_launcher( + argv: &mut Vec, + supports_argv0: bool, + argv0_fallback_command: String, +) { + let command_separator_index = argv + .iter() + .position(|arg| arg == "--") + .unwrap_or_else(|| panic!("bubblewrap argv is missing command separator '--'")); + + if supports_argv0 { + argv.splice( + command_separator_index..command_separator_index, + ["--argv0".to_string(), CODEX_LINUX_SANDBOX_ARG0.to_string()], + ); + return; + } + + let command_index = command_separator_index + 1; + let Some(command) = argv.get_mut(command_index) else { + panic!("bubblewrap argv is missing inner command after '--'"); + }; + *command = argv0_fallback_command; +} + +fn current_process_argv0() -> String { + match std::env::args_os().next() { + Some(argv0) => argv0.to_string_lossy().into_owned(), + None => panic!("failed to resolve current process argv[0]"), + } +} + fn preflight_proc_mount_support( sandbox_policy_cwd: &Path, command_cwd: &Path, diff --git a/codex-rs/linux-sandbox/src/linux_run_main_tests.rs b/codex-rs/linux-sandbox/src/linux_run_main_tests.rs index b42d7e552a..d8b84ffbaf 100644 --- a/codex-rs/linux-sandbox/src/linux_run_main_tests.rs +++ b/codex-rs/linux-sandbox/src/linux_run_main_tests.rs @@ -40,7 +40,7 @@ fn ignores_non_proc_mount_errors() { #[test] fn inserts_bwrap_argv0_before_command_separator() { let sandbox_policy = SandboxPolicy::new_read_only_policy(); - let argv = build_bwrap_argv( + let mut argv = build_bwrap_argv( vec!["/bin/true".to_string()], &FileSystemSandboxPolicy::from(&sandbox_policy), Path::new("/"), @@ -51,6 +51,11 @@ fn inserts_bwrap_argv0_before_command_separator() { }, ) .args; + apply_inner_command_argv0_for_launcher( + &mut argv, + true, + "/tmp/codex-arg0-session/codex-linux-sandbox".to_string(), + ); assert_eq!( argv, vec![ @@ -74,6 +79,73 @@ fn inserts_bwrap_argv0_before_command_separator() { ); } +#[test] +fn rewrites_inner_command_path_when_bwrap_lacks_argv0() { + let sandbox_policy = SandboxPolicy::new_read_only_policy(); + let mut argv = build_bwrap_argv( + vec!["/bin/true".to_string()], + &FileSystemSandboxPolicy::from(&sandbox_policy), + Path::new("/"), + Path::new("/"), + BwrapOptions { + mount_proc: true, + network_mode: BwrapNetworkMode::FullAccess, + }, + ) + .args; + apply_inner_command_argv0_for_launcher( + &mut argv, + false, + "/tmp/codex-arg0-session/codex-linux-sandbox".to_string(), + ); + + assert!(!argv.iter().any(|arg| arg == "--argv0")); + assert!( + argv.windows(2) + .any(|window| { window == ["--", "/tmp/codex-arg0-session/codex-linux-sandbox"] }) + ); +} + +#[test] +fn rewrites_bwrap_helper_command_not_nested_user_command_when_current_exe_appears_later() { + let nested_current_exe = std::env::current_exe() + .expect("current exe") + .to_string_lossy() + .into_owned(); + let mut argv = vec![ + "bwrap".to_string(), + "--".to_string(), + "/tmp/helper-symlink".to_string(), + "--sandbox-policy-cwd".to_string(), + "/tmp/cwd".to_string(), + "--".to_string(), + nested_current_exe.clone(), + "--codex-run-as-apply-patch".to_string(), + "patch".to_string(), + ]; + + apply_inner_command_argv0_for_launcher( + &mut argv, + false, + "/tmp/argv0-fallback-helper".to_string(), + ); + + assert_eq!( + argv, + vec![ + "bwrap".to_string(), + "--".to_string(), + "/tmp/argv0-fallback-helper".to_string(), + "--sandbox-policy-cwd".to_string(), + "/tmp/cwd".to_string(), + "--".to_string(), + nested_current_exe, + "--codex-run-as-apply-patch".to_string(), + "patch".to_string(), + ] + ); +} + #[test] fn inserts_unshare_net_when_network_isolation_requested() { let sandbox_policy = SandboxPolicy::new_read_only_policy(); @@ -313,6 +385,7 @@ fn resolve_sandbox_policies_rejects_mismatched_legacy_and_split_inputs() { Some(NetworkSandboxPolicy::Enabled), ) .expect_err("mismatched legacy and split policies should fail"); + assert!( matches!( err, diff --git a/codex-rs/mcp-server/src/codex_tool_config.rs b/codex-rs/mcp-server/src/codex_tool_config.rs index f3f66b5559..f83fd4fd5a 100644 --- a/codex-rs/mcp-server/src/codex_tool_config.rs +++ b/codex-rs/mcp-server/src/codex_tool_config.rs @@ -176,6 +176,7 @@ impl CodexToolCallParam { cwd: cwd.map(PathBuf::from), approval_policy: approval_policy.map(Into::into), sandbox_mode: sandbox.map(Into::into), + codex_self_exe: arg0_paths.codex_self_exe.clone(), codex_linux_sandbox_exe: arg0_paths.codex_linux_sandbox_exe.clone(), main_execve_wrapper_exe: arg0_paths.main_execve_wrapper_exe.clone(), base_instructions, diff --git a/codex-rs/sandboxing/src/landlock.rs b/codex-rs/sandboxing/src/landlock.rs index 8636f9ed04..d948d23d1f 100644 --- a/codex-rs/sandboxing/src/landlock.rs +++ b/codex-rs/sandboxing/src/landlock.rs @@ -2,6 +2,11 @@ use codex_protocol::permissions::FileSystemSandboxPolicy; use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::protocol::SandboxPolicy; use std::path::Path; + +/// Basename used when the Codex executable self-invokes as the Linux sandbox +/// helper. +pub const CODEX_LINUX_SANDBOX_ARG0: &str = "codex-linux-sandbox"; + pub fn allow_network_for_proxy(enforce_managed_network: bool) -> bool { // When managed network requirements are active, request proxy-only // networking from the Linux sandbox helper. Without managed requirements, diff --git a/codex-rs/sandboxing/src/manager.rs b/codex-rs/sandboxing/src/manager.rs index f55f53cb13..3d286eb64c 100644 --- a/codex-rs/sandboxing/src/manager.rs +++ b/codex-rs/sandboxing/src/manager.rs @@ -1,3 +1,4 @@ +use crate::landlock::CODEX_LINUX_SANDBOX_ARG0; use crate::landlock::allow_network_for_proxy; use crate::landlock::create_linux_sandbox_command_args_for_policies; use crate::policy_transforms::EffectiveSandboxPermissions; @@ -247,7 +248,10 @@ impl SandboxManager { let mut full_command = Vec::with_capacity(1 + args.len()); full_command.push(exe.to_string_lossy().to_string()); full_command.append(&mut args); - (full_command, Some("codex-linux-sandbox".to_string())) + ( + full_command, + Some(linux_sandbox_arg0_override(exe.as_path())), + ) } #[cfg(target_os = "windows")] SandboxType::WindowsRestrictedToken => (argv, None), @@ -271,6 +275,14 @@ impl SandboxManager { } } +fn linux_sandbox_arg0_override(exe: &Path) -> String { + if exe.file_name().and_then(|name| name.to_str()) == Some(CODEX_LINUX_SANDBOX_ARG0) { + exe.to_string_lossy().into_owned() + } else { + CODEX_LINUX_SANDBOX_ARG0.to_string() + } +} + #[cfg(test)] #[path = "manager_tests.rs"] mod tests; diff --git a/codex-rs/sandboxing/src/manager_tests.rs b/codex-rs/sandboxing/src/manager_tests.rs index 17921b1914..690aec89d5 100644 --- a/codex-rs/sandboxing/src/manager_tests.rs +++ b/codex-rs/sandboxing/src/manager_tests.rs @@ -249,3 +249,54 @@ fn transform_additional_permissions_preserves_denied_entries() { NetworkSandboxPolicy::Restricted ); } + +#[cfg(target_os = "linux")] +fn transform_linux_seccomp_request( + codex_linux_sandbox_exe: &std::path::PathBuf, +) -> super::SandboxExecRequest { + let manager = SandboxManager::new(); + let cwd = std::env::current_dir().expect("current dir"); + manager + .transform(SandboxTransformRequest { + command: SandboxCommand { + program: "true".to_string(), + args: Vec::new(), + cwd: cwd.clone(), + env: HashMap::new(), + additional_permissions: None, + }, + policy: &SandboxPolicy::DangerFullAccess, + file_system_policy: &FileSystemSandboxPolicy::unrestricted(), + network_policy: NetworkSandboxPolicy::Enabled, + sandbox: SandboxType::LinuxSeccomp, + enforce_managed_network: false, + network: None, + sandbox_policy_cwd: cwd.as_path(), + codex_linux_sandbox_exe: Some(codex_linux_sandbox_exe), + use_legacy_landlock: false, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + windows_sandbox_private_desktop: false, + }) + .expect("transform") +} + +#[cfg(target_os = "linux")] +#[test] +fn transform_linux_seccomp_preserves_helper_path_in_arg0_when_available() { + let codex_linux_sandbox_exe = std::path::PathBuf::from("/tmp/codex-linux-sandbox"); + let exec_request = transform_linux_seccomp_request(&codex_linux_sandbox_exe); + + assert_eq!( + exec_request.arg0, + Some(codex_linux_sandbox_exe.to_string_lossy().into_owned()) + ); +} + +#[cfg(target_os = "linux")] +#[test] +fn transform_linux_seccomp_uses_helper_alias_when_launcher_is_not_helper_path() { + let codex_linux_sandbox_exe = std::path::PathBuf::from("/tmp/codex"); + let exec_request = transform_linux_seccomp_request(&codex_linux_sandbox_exe); + + assert_eq!(exec_request.arg0, Some("codex-linux-sandbox".to_string())); +} diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 43182b5240..e291480d0b 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -418,6 +418,7 @@ pub async fn run_main( cwd, model_provider: model_provider_override.clone(), config_profile: cli.config_profile.clone(), + codex_self_exe: arg0_paths.codex_self_exe.clone(), codex_linux_sandbox_exe: arg0_paths.codex_linux_sandbox_exe.clone(), main_execve_wrapper_exe: arg0_paths.main_execve_wrapper_exe.clone(), show_raw_agent_reasoning: cli.oss.then_some(true), diff --git a/codex-rs/tui_app_server/src/lib.rs b/codex-rs/tui_app_server/src/lib.rs index c5e2479bf4..1e40866855 100644 --- a/codex-rs/tui_app_server/src/lib.rs +++ b/codex-rs/tui_app_server/src/lib.rs @@ -776,6 +776,7 @@ pub async fn run_main( cwd, model_provider: model_provider_override.clone(), config_profile: cli.config_profile.clone(), + codex_self_exe: arg0_paths.codex_self_exe.clone(), codex_linux_sandbox_exe: arg0_paths.codex_linux_sandbox_exe.clone(), main_execve_wrapper_exe: arg0_paths.main_execve_wrapper_exe.clone(), show_raw_agent_reasoning: cli.oss.then_some(true), From 7ef3cfe63e435ee03812cfb818c4ba8a063a6833 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 26 Mar 2026 09:33:25 +0000 Subject: [PATCH 010/212] feat: replace askama by custom lib (#15784) Finalise the drop of `askama` to use our internal lib instead --- MODULE.bazel.lock | 4 -- codex-rs/Cargo.lock | 54 +------------- codex-rs/Cargo.toml | 1 - codex-rs/core/BUILD.bazel | 5 +- codex-rs/core/Cargo.toml | 2 +- codex-rs/core/src/memories/prompts.rs | 78 +++++++++++---------- codex-rs/core/src/memories/prompts_tests.rs | 43 ++++++++++++ codex-rs/deny.toml | 4 +- 8 files changed, 91 insertions(+), 100 deletions(-) diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index ee89f6243f..3ca1e5e967 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -618,10 +618,6 @@ "arrayvec_0.7.6": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"bencher\",\"req\":\"^0.1.4\"},{\"default_features\":false,\"name\":\"borsh\",\"optional\":true,\"req\":\"^1.2.0\"},{\"kind\":\"dev\",\"name\":\"matches\",\"req\":\"^0.1\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"serde_test\",\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"zeroize\",\"optional\":true,\"req\":\"^1.4\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "ascii-canvas_3.0.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"diff\",\"req\":\"^0.1\"},{\"name\":\"term\",\"req\":\"^0.7\"}],\"features\":{}}", "ascii_1.1.0": "{\"dependencies\":[{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0.25\"},{\"name\":\"serde_test\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"alloc\":[],\"default\":[\"std\"],\"std\":[\"alloc\"]}}", - "askama_0.15.4": "{\"dependencies\":[{\"default_features\":false,\"name\":\"askama_macros\",\"optional\":true,\"req\":\"=0.15.4\"},{\"kind\":\"dev\",\"name\":\"assert_matches\",\"req\":\"^1.5.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.8\"},{\"name\":\"itoa\",\"req\":\"^1.0.11\"},{\"default_features\":false,\"name\":\"percent-encoding\",\"optional\":true,\"req\":\"^2.1.0\"},{\"default_features\":false,\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"default_features\":false,\"name\":\"serde_json\",\"optional\":true,\"req\":\"^1.0\"}],\"features\":{\"alloc\":[\"askama_macros?/alloc\",\"serde?/alloc\",\"serde_json?/alloc\",\"percent-encoding?/alloc\"],\"code-in-doc\":[\"askama_macros?/code-in-doc\"],\"config\":[\"askama_macros?/config\"],\"default\":[\"config\",\"derive\",\"std\",\"urlencode\"],\"derive\":[\"dep:askama_macros\",\"dep:askama_macros\"],\"full\":[\"default\",\"code-in-doc\",\"serde_json\"],\"nightly-spans\":[\"askama_macros/nightly-spans\"],\"serde_json\":[\"std\",\"askama_macros?/serde_json\",\"dep:serde\",\"dep:serde_json\"],\"std\":[\"alloc\",\"askama_macros?/std\",\"serde?/std\",\"serde_json?/std\",\"percent-encoding?/std\"],\"urlencode\":[\"askama_macros?/urlencode\",\"dep:percent-encoding\"]}}", - "askama_derive_0.15.4": "{\"dependencies\":[{\"name\":\"basic-toml\",\"optional\":true,\"req\":\"^0.1.1\"},{\"kind\":\"dev\",\"name\":\"console\",\"req\":\"^0.16.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.8\"},{\"name\":\"memchr\",\"req\":\"^2\"},{\"name\":\"parser\",\"package\":\"askama_parser\",\"req\":\"=0.15.4\"},{\"kind\":\"dev\",\"name\":\"prettyplease\",\"req\":\"^0.2.20\"},{\"default_features\":false,\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"default_features\":false,\"name\":\"pulldown-cmark\",\"optional\":true,\"req\":\"^0.13.0\"},{\"default_features\":false,\"name\":\"quote\",\"req\":\"^1\"},{\"name\":\"rustc-hash\",\"req\":\"^2.0.0\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_derive\",\"optional\":true,\"req\":\"^1.0\"},{\"kind\":\"dev\",\"name\":\"similar\",\"req\":\"^2.6.0\"},{\"default_features\":false,\"features\":[\"clone-impls\",\"derive\",\"full\",\"parsing\",\"printing\"],\"name\":\"syn\",\"req\":\"^2.0.3\"}],\"features\":{\"alloc\":[],\"code-in-doc\":[\"dep:pulldown-cmark\"],\"config\":[\"external-sources\",\"dep:basic-toml\",\"dep:serde\",\"dep:serde_derive\",\"parser/config\"],\"default\":[\"alloc\",\"code-in-doc\",\"config\",\"external-sources\",\"proc-macro\",\"serde_json\",\"std\",\"urlencode\"],\"external-sources\":[],\"nightly-spans\":[],\"proc-macro\":[\"proc-macro2/proc-macro\"],\"serde_json\":[],\"std\":[\"alloc\"],\"urlencode\":[]}}", - "askama_macros_0.15.4": "{\"dependencies\":[{\"default_features\":false,\"features\":[\"external-sources\",\"proc-macro\"],\"name\":\"askama_derive\",\"package\":\"askama_derive\",\"req\":\"=0.15.4\"}],\"features\":{\"alloc\":[\"askama_derive/alloc\"],\"code-in-doc\":[\"askama_derive/code-in-doc\"],\"config\":[\"askama_derive/config\"],\"default\":[\"config\",\"derive\",\"std\",\"urlencode\"],\"derive\":[],\"full\":[\"default\",\"code-in-doc\",\"serde_json\"],\"nightly-spans\":[\"askama_derive/nightly-spans\"],\"serde_json\":[\"askama_derive/serde_json\"],\"std\":[\"askama_derive/std\"],\"urlencode\":[\"askama_derive/urlencode\"]}}", - "askama_parser_0.15.4": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.8\"},{\"name\":\"rustc-hash\",\"req\":\"^2.0.0\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"serde_derive\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"unicode-ident\",\"req\":\"^1.0.12\"},{\"features\":[\"simd\"],\"name\":\"winnow\",\"req\":\"^0.7.0\"}],\"features\":{\"config\":[\"dep:serde\",\"dep:serde_derive\"]}}", "asn1-rs-derive_0.6.0": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1.0\"},{\"name\":\"quote\",\"req\":\"^1.0\"},{\"features\":[\"full\"],\"name\":\"syn\",\"req\":\"^2.0\"},{\"name\":\"synstructure\",\"req\":\"^0.13\"}],\"features\":{}}", "asn1-rs-impl_0.2.0": "{\"dependencies\":[{\"name\":\"proc-macro2\",\"req\":\"^1\"},{\"name\":\"quote\",\"req\":\"^1\"},{\"name\":\"syn\",\"req\":\"^2.0\"}],\"features\":{}}", "asn1-rs_0.7.1": "{\"dependencies\":[{\"name\":\"asn1-rs-derive\",\"req\":\"^0.6\"},{\"name\":\"asn1-rs-impl\",\"req\":\"^0.2\"},{\"name\":\"bitvec\",\"optional\":true,\"req\":\"^1.0\"},{\"name\":\"colored\",\"optional\":true,\"req\":\"^3.0\"},{\"kind\":\"dev\",\"name\":\"colored\",\"req\":\"^3.0\"},{\"name\":\"cookie-factory\",\"optional\":true,\"req\":\"^0.3.0\"},{\"name\":\"displaydoc\",\"req\":\"^0.2.2\"},{\"kind\":\"dev\",\"name\":\"hex-literal\",\"req\":\"^0.4\"},{\"default_features\":false,\"features\":[\"std\"],\"name\":\"nom\",\"req\":\"^7.0\"},{\"name\":\"num-bigint\",\"optional\":true,\"req\":\"^0.4\"},{\"name\":\"num-traits\",\"req\":\"^0.2.14\"},{\"kind\":\"dev\",\"name\":\"pem\",\"req\":\"^3.0\"},{\"name\":\"rusticata-macros\",\"req\":\"^4.0\"},{\"name\":\"thiserror\",\"req\":\"^2.0.0\"},{\"features\":[\"macros\",\"parsing\",\"formatting\"],\"name\":\"time\",\"optional\":true,\"req\":\"^0.3\"},{\"kind\":\"dev\",\"name\":\"trybuild\",\"req\":\"^1.0\"}],\"features\":{\"bigint\":[\"num-bigint\"],\"bits\":[\"bitvec\"],\"datetime\":[\"time\"],\"debug\":[\"std\",\"colored\"],\"default\":[\"std\"],\"serialize\":[\"cookie-factory\"],\"std\":[],\"trace\":[\"debug\"]}}", diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 9fc695795d..3c6303b14f 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -481,58 +481,6 @@ dependencies = [ "term", ] -[[package]] -name = "askama" -version = "0.15.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08e1676b346cadfec169374f949d7490fd80a24193d37d2afce0c047cf695e57" -dependencies = [ - "askama_macros", - "itoa", - "percent-encoding", - "serde", - "serde_json", -] - -[[package]] -name = "askama_derive" -version = "0.15.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7661ff56517787343f376f75db037426facd7c8d3049cef8911f1e75016f3a37" -dependencies = [ - "askama_parser", - "basic-toml", - "memchr", - "proc-macro2", - "quote", - "rustc-hash 2.1.1", - "serde", - "serde_derive", - "syn 2.0.114", -] - -[[package]] -name = "askama_macros" -version = "0.15.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "713ee4dbfd1eb719c2dab859465b01fa1d21cb566684614a713a6b7a99a4e47b" -dependencies = [ - "askama_derive", -] - -[[package]] -name = "askama_parser" -version = "0.15.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d62d674238a526418b30c0def480d5beadb9d8964e7f38d635b03bf639c704c" -dependencies = [ - "rustc-hash 2.1.1", - "serde", - "serde_derive", - "unicode-ident", - "winnow", -] - [[package]] name = "asn1-rs" version = "0.7.1" @@ -1881,7 +1829,6 @@ version = "0.0.0" dependencies = [ "anyhow", "arc-swap", - "askama", "assert_cmd", "assert_matches", "async-channel", @@ -1934,6 +1881,7 @@ dependencies = [ "codex-utils-readiness", "codex-utils-stream-parser", "codex-utils-string", + "codex-utils-template", "codex-windows-sandbox", "core-foundation 0.9.4", "core_test_support", diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index f19fb650f7..dd7e708c82 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -189,7 +189,6 @@ allocative = "0.3.3" ansi-to-tui = "7.0.0" anyhow = "1" arboard = { version = "3", features = ["wayland-data-control"] } -askama = "0.15.4" assert_cmd = "2" assert_matches = "1.5.0" async-channel = "2.3.1" diff --git a/codex-rs/core/BUILD.bazel b/codex-rs/core/BUILD.bazel index e8773b42fd..591eb1f28a 100644 --- a/codex-rs/core/BUILD.bazel +++ b/codex-rs/core/BUILD.bazel @@ -32,9 +32,8 @@ codex_rust_crate( "//codex-rs:node-version.txt", ], rustc_env = { - # Askama resolves template paths relative to CARGO_MANIFEST_DIR. In - # Bazel, the Cargo-provided absolute source path points outside the - # sandbox, so keep the manifest root anchored inside the execroot. + # Keep manifest-root path lookups inside the Bazel execroot for code + # that relies on env!("CARGO_MANIFEST_DIR"). "CARGO_MANIFEST_DIR": "codex-rs/core", }, integration_compile_data_extra = [ diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 25e44d7631..09a16db5c1 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -21,7 +21,6 @@ anyhow = { workspace = true } arc-swap = "1.8.2" async-channel = { workspace = true } async-trait = { workspace = true } -askama = { workspace = true } base64 = { workspace = true } bm25 = { workspace = true } chardetng = { workspace = true } @@ -66,6 +65,7 @@ codex-utils-readiness = { workspace = true } codex-secrets = { workspace = true } codex-utils-string = { workspace = true } codex-utils-stream-parser = { workspace = true } +codex-utils-template = { workspace = true } codex-windows-sandbox = { package = "codex-windows-sandbox", path = "../windows-sandbox-rs" } csv = { workspace = true } dirs = { workspace = true } diff --git a/codex-rs/core/src/memories/prompts.rs b/codex-rs/core/src/memories/prompts.rs index 851179426f..56cb2b7b60 100644 --- a/codex-rs/core/src/memories/prompts.rs +++ b/codex-rs/core/src/memories/prompts.rs @@ -1,37 +1,42 @@ use crate::memories::memory_root; use crate::memories::phase_one; use crate::memories::storage::rollout_summary_file_stem_from_parts; -use askama::Template; use codex_protocol::openai_models::ModelInfo; use codex_state::Phase2InputSelection; use codex_state::Stage1Output; use codex_state::Stage1OutputRef; use codex_utils_output_truncation::TruncationPolicy; use codex_utils_output_truncation::truncate_text; +use codex_utils_template::Template; use std::path::Path; +use std::sync::LazyLock; use tokio::fs; use tracing::warn; -#[derive(Template)] -#[template(path = "memories/consolidation.md", escape = "none")] -struct ConsolidationPromptTemplate<'a> { - memory_root: &'a str, - phase2_input_selection: &'a str, -} +static CONSOLIDATION_PROMPT_TEMPLATE: LazyLock