From eee692e35167e9c6b7eec459fd8f4b0c347a4458 Mon Sep 17 00:00:00 2001 From: arnavdugar-openai Date: Wed, 25 Mar 2026 15:41:29 -0700 Subject: [PATCH 01/12] Treat ChatGPT `hc` plan as Enterprise (#15789) --- codex-rs/cloud-requirements/src/lib.rs | 28 ++++++++++++++++++++++++++ codex-rs/login/src/token_data.rs | 3 ++- codex-rs/login/src/token_data_tests.rs | 15 ++++++++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/codex-rs/cloud-requirements/src/lib.rs b/codex-rs/cloud-requirements/src/lib.rs index fb0f62a342..12e62d880f 100644 --- a/codex-rs/cloud-requirements/src/lib.rs +++ b/codex-rs/cloud-requirements/src/lib.rs @@ -1153,6 +1153,34 @@ mod tests { ); } + #[tokio::test] + async fn fetch_cloud_requirements_allows_hc_plan_as_enterprise() { + let codex_home = tempdir().expect("tempdir"); + let service = CloudRequirementsService::new( + auth_manager_with_plan("hc"), + Arc::new(StaticFetcher { + contents: Some("allowed_approval_policies = [\"never\"]".to_string()), + }), + codex_home.path().to_path_buf(), + CLOUD_REQUIREMENTS_TIMEOUT, + ); + assert_eq!( + service.fetch().await, + Ok(Some(ConfigRequirementsToml { + allowed_approval_policies: Some(vec![AskForApproval::Never]), + allowed_sandbox_modes: None, + allowed_web_search_modes: None, + guardian_developer_instructions: None, + feature_requirements: None, + mcp_servers: None, + apps: None, + rules: None, + enforce_residency: None, + network: None, + })) + ); + } + #[tokio::test] async fn fetch_cloud_requirements_handles_missing_contents() { let result = parse_for_fetch(None); diff --git a/codex-rs/login/src/token_data.rs b/codex-rs/login/src/token_data.rs index 1056115a37..a05b153a89 100644 --- a/codex-rs/login/src/token_data.rs +++ b/codex-rs/login/src/token_data.rs @@ -72,7 +72,7 @@ impl PlanType { "pro" => Self::Known(KnownPlan::Pro), "team" => Self::Known(KnownPlan::Team), "business" => Self::Known(KnownPlan::Business), - "enterprise" => Self::Known(KnownPlan::Enterprise), + "enterprise" | "hc" => Self::Known(KnownPlan::Enterprise), "education" | "edu" => Self::Known(KnownPlan::Edu), _ => Self::Unknown(raw.to_string()), } @@ -88,6 +88,7 @@ pub enum KnownPlan { Pro, Team, Business, + #[serde(alias = "hc")] Enterprise, Edu, } diff --git a/codex-rs/login/src/token_data_tests.rs b/codex-rs/login/src/token_data_tests.rs index 7f77ee5eaf..336f1032bd 100644 --- a/codex-rs/login/src/token_data_tests.rs +++ b/codex-rs/login/src/token_data_tests.rs @@ -53,6 +53,21 @@ fn id_token_info_parses_go_plan() { assert_eq!(info.get_chatgpt_plan_type().as_deref(), Some("Go")); } +#[test] +fn id_token_info_parses_hc_plan_as_enterprise() { + let fake_jwt = fake_jwt(serde_json::json!({ + "email": "user@example.com", + "https://api.openai.com/auth": { + "chatgpt_plan_type": "hc" + } + })); + + let info = parse_chatgpt_jwt_claims(&fake_jwt).expect("should parse"); + assert_eq!(info.email.as_deref(), Some("user@example.com")); + assert_eq!(info.get_chatgpt_plan_type().as_deref(), Some("Enterprise")); + assert_eq!(info.is_workspace_account(), true); +} + #[test] fn id_token_info_handles_missing_fields() { let fake_jwt = fake_jwt(serde_json::json!({ "sub": "123" })); From f24c55f0d53842ca0061d149380a8cfd4b4bdda4 Mon Sep 17 00:00:00 2001 From: canvrno-oai Date: Wed, 25 Mar 2026 16:09:19 -0700 Subject: [PATCH 02/12] TUI plugin menu polish (#15802) - Add "OpenAI Curated" display name for `openai-curated` marketplace - Hide /apps menu - Change app install phase display text --- codex-rs/core/src/plugins/manager.rs | 15 +++++++++++++-- codex-rs/core/src/plugins/manager_tests.rs | 2 +- codex-rs/tui/src/bottom_pane/command_popup.rs | 1 + codex-rs/tui/src/chatwidget/plugins.rs | 2 +- .../src/bottom_pane/command_popup.rs | 1 + codex-rs/tui_app_server/src/chatwidget/plugins.rs | 2 +- 6 files changed, 18 insertions(+), 5 deletions(-) diff --git a/codex-rs/core/src/plugins/manager.rs b/codex-rs/core/src/plugins/manager.rs index 3f3097d5e3..140882a187 100644 --- a/codex-rs/core/src/plugins/manager.rs +++ b/codex-rs/core/src/plugins/manager.rs @@ -78,6 +78,7 @@ const DEFAULT_SKILLS_DIR_NAME: &str = "skills"; const DEFAULT_MCP_CONFIG_FILE: &str = ".mcp.json"; const DEFAULT_APP_CONFIG_FILE: &str = ".app.json"; pub const OPENAI_CURATED_MARKETPLACE_NAME: &str = "openai-curated"; +pub const OPENAI_CURATED_MARKETPLACE_DISPLAY_NAME: &str = "OpenAI Curated"; static CURATED_REPO_SYNC_STARTED: AtomicBool = AtomicBool::new(false); const FEATURED_PLUGIN_IDS_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(60 * 60 * 3); @@ -889,7 +890,13 @@ impl PluginsManager { (!plugins.is_empty()).then_some(ConfiguredMarketplace { name: marketplace.name, path: marketplace.path, - interface: marketplace.interface, + interface: if marketplace_name == OPENAI_CURATED_MARKETPLACE_NAME { + Some(MarketplaceInterface { + display_name: Some(OPENAI_CURATED_MARKETPLACE_DISPLAY_NAME.to_string()), + }) + } else { + marketplace.interface + }, plugins, }) }) @@ -972,7 +979,11 @@ impl PluginsManager { mcp_server_names.dedup(); Ok(PluginReadOutcome { - marketplace_name: marketplace.name, + marketplace_name: if marketplace.name == OPENAI_CURATED_MARKETPLACE_NAME { + OPENAI_CURATED_MARKETPLACE_DISPLAY_NAME.to_string() + } else { + marketplace.name + }, marketplace_path: marketplace.path, plugin: PluginDetail { id: plugin_key.clone(), diff --git a/codex-rs/core/src/plugins/manager_tests.rs b/codex-rs/core/src/plugins/manager_tests.rs index 884beee66d..af33f90179 100644 --- a/codex-rs/core/src/plugins/manager_tests.rs +++ b/codex-rs/core/src/plugins/manager_tests.rs @@ -1386,7 +1386,7 @@ plugins = true path: AbsolutePathBuf::try_from(curated_root.join(".agents/plugins/marketplace.json")) .unwrap(), interface: Some(MarketplaceInterface { - display_name: Some("ChatGPT Official".to_string()), + display_name: Some(OPENAI_CURATED_MARKETPLACE_DISPLAY_NAME.to_string()), }), plugins: vec![ConfiguredMarketplacePlugin { id: "linear@openai-curated".to_string(), diff --git a/codex-rs/tui/src/bottom_pane/command_popup.rs b/codex-rs/tui/src/bottom_pane/command_popup.rs index e7269c38ef..ef73450f34 100644 --- a/codex-rs/tui/src/bottom_pane/command_popup.rs +++ b/codex-rs/tui/src/bottom_pane/command_popup.rs @@ -68,6 +68,7 @@ impl CommandPopup { slash_commands::builtins_for_input(flags.into()) .into_iter() .filter(|(name, _)| !name.starts_with("debug")) + .filter(|(_, cmd)| *cmd != SlashCommand::Apps) .collect(); // Exclude prompts that collide with builtin command names and sort by name. let exclude: HashSet = builtins.iter().map(|(n, _)| (*n).to_string()).collect(); diff --git a/codex-rs/tui/src/chatwidget/plugins.rs b/codex-rs/tui/src/chatwidget/plugins.rs index 588884639d..9b3f91b202 100644 --- a/codex-rs/tui/src/chatwidget/plugins.rs +++ b/codex-rs/tui/src/chatwidget/plugins.rs @@ -418,7 +418,7 @@ impl ChatWidget { let status_label = if is_installed { "Already installed in this session." } else { - "Not installed yet." + "Install the required Apps in ChatGPT to continue:" }; let mut header = ColumnRenderable::new(); header.push(Line::from("Plugins".bold())); diff --git a/codex-rs/tui_app_server/src/bottom_pane/command_popup.rs b/codex-rs/tui_app_server/src/bottom_pane/command_popup.rs index 36cc87668c..5ad3df5c2e 100644 --- a/codex-rs/tui_app_server/src/bottom_pane/command_popup.rs +++ b/codex-rs/tui_app_server/src/bottom_pane/command_popup.rs @@ -68,6 +68,7 @@ impl CommandPopup { slash_commands::builtins_for_input(flags.into()) .into_iter() .filter(|(name, _)| !name.starts_with("debug")) + .filter(|(_, cmd)| *cmd != SlashCommand::Apps) .collect(); // Exclude prompts that collide with builtin command names and sort by name. let exclude: HashSet = builtins.iter().map(|(n, _)| (*n).to_string()).collect(); diff --git a/codex-rs/tui_app_server/src/chatwidget/plugins.rs b/codex-rs/tui_app_server/src/chatwidget/plugins.rs index 588884639d..9b3f91b202 100644 --- a/codex-rs/tui_app_server/src/chatwidget/plugins.rs +++ b/codex-rs/tui_app_server/src/chatwidget/plugins.rs @@ -418,7 +418,7 @@ impl ChatWidget { let status_label = if is_installed { "Already installed in this session." } else { - "Not installed yet." + "Install the required Apps in ChatGPT to continue:" }; let mut header = ColumnRenderable::new(); header.push(Line::from("Plugins".bold())); From 8fa88fa8cabddb15c6477b84f2d1774ce50b20bd Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Wed, 25 Mar 2026 16:14:36 -0700 Subject: [PATCH 03/12] Add cached environment manager for exec server URL (#15785) Add environment manager that is a singleton and is created early in app-server (before skill manager, before config loading). Use an environment variable to point to a running exec server. --- codex-rs/Cargo.lock | 2 + codex-rs/app-server/src/in_process.rs | 2 + codex-rs/app-server/src/lib.rs | 3 + codex-rs/app-server/src/message_processor.rs | 4 + .../src/message_processor/tracing_tests.rs | 2 + codex-rs/core/config.schema.json | 4 - codex-rs/core/src/agent/control_tests.rs | 21 +++++ codex-rs/core/src/codex.rs | 9 +- codex-rs/core/src/codex_delegate.rs | 4 + codex-rs/core/src/codex_tests.rs | 7 +- codex-rs/core/src/codex_tests_guardian.rs | 2 + codex-rs/core/src/config/config_tests.rs | 32 ------- codex-rs/core/src/config/mod.rs | 9 -- codex-rs/core/src/memories/tests.rs | 3 + codex-rs/core/src/test_support.rs | 9 +- codex-rs/core/src/thread_manager.rs | 15 ++- codex-rs/core/src/thread_manager_tests.rs | 15 +++ codex-rs/core/tests/common/test_codex.rs | 26 +++--- codex-rs/core/tests/suite/client.rs | 3 + codex-rs/exec-server/src/environment.rs | 93 ++++++++++++++++--- codex-rs/exec-server/src/lib.rs | 2 + .../exec-server/src/remote_file_system.rs | 9 ++ codex-rs/exec-server/src/remote_process.rs | 7 ++ codex-rs/exec-server/tests/exec_process.rs | 2 +- codex-rs/exec-server/tests/file_system.rs | 2 +- codex-rs/mcp-server/Cargo.toml | 1 + codex-rs/mcp-server/src/lib.rs | 6 +- codex-rs/mcp-server/src/message_processor.rs | 5 +- codex-rs/tui/Cargo.toml | 1 + codex-rs/tui/src/app.rs | 3 + justfile | 5 + scripts/run_tui_with_exec_server.sh | 61 ++++++++++++ 32 files changed, 286 insertions(+), 83 deletions(-) create mode 100755 scripts/run_tui_with_exec_server.sh diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index fb1710987e..02625d90c2 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2323,6 +2323,7 @@ dependencies = [ "anyhow", "codex-arg0", "codex-core", + "codex-exec-server", "codex-features", "codex-protocol", "codex-shell-command", @@ -2724,6 +2725,7 @@ dependencies = [ "codex-client", "codex-cloud-requirements", "codex-core", + "codex-exec-server", "codex-features", "codex-feedback", "codex-file-search", diff --git a/codex-rs/app-server/src/in_process.rs b/codex-rs/app-server/src/in_process.rs index 79f32c9083..0405c72259 100644 --- a/codex-rs/app-server/src/in_process.rs +++ b/codex-rs/app-server/src/in_process.rs @@ -77,6 +77,7 @@ use codex_arg0::Arg0DispatchPaths; use codex_core::config::Config; use codex_core::config_loader::CloudRequirementsLoader; use codex_core::config_loader::LoaderOverrides; +use codex_exec_server::EnvironmentManager; use codex_feedback::CodexFeedback; use codex_protocol::protocol::SessionSource; use tokio::sync::mpsc; @@ -383,6 +384,7 @@ fn start_uninitialized(args: InProcessStartArgs) -> InProcessClientHandle { outgoing: Arc::clone(&processor_outgoing), arg0_paths: args.arg0_paths, config: args.config, + environment_manager: Arc::new(EnvironmentManager::from_env()), cli_overrides: args.cli_overrides, loader_overrides: args.loader_overrides, cloud_requirements: args.cloud_requirements, diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index 247270a26c..0a2b6f386b 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -40,6 +40,7 @@ use codex_core::ExecPolicyError; use codex_core::check_execpolicy_for_warnings; use codex_core::config_loader::ConfigLoadError; use codex_core::config_loader::TextRange as CoreTextRange; +use codex_exec_server::EnvironmentManager; use codex_feedback::CodexFeedback; use codex_protocol::protocol::SessionSource; use codex_state::log_db; @@ -355,6 +356,7 @@ pub async fn run_main_with_transport( session_source: SessionSource, auth: AppServerWebsocketAuthSettings, ) -> IoResult<()> { + let environment_manager = Arc::new(EnvironmentManager::from_env()); let (transport_event_tx, mut transport_event_rx) = mpsc::channel::(CHANNEL_CAPACITY); let (outgoing_tx, mut outgoing_rx) = mpsc::channel::(CHANNEL_CAPACITY); @@ -620,6 +622,7 @@ pub async fn run_main_with_transport( outgoing: outgoing_message_sender, arg0_paths, config: Arc::new(config), + environment_manager, cli_overrides, loader_overrides, cloud_requirements: cloud_requirements.clone(), diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index feca709513..9a9a145f65 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -66,6 +66,7 @@ use codex_core::default_client::get_codex_user_agent; use codex_core::default_client::set_default_client_residency_requirement; use codex_core::default_client::set_default_originator; use codex_core::models_manager::collaboration_mode_presets::CollaborationModesConfig; +use codex_exec_server::EnvironmentManager; use codex_features::Feature; use codex_feedback::CodexFeedback; use codex_login::auth::ExternalAuthRefreshContext; @@ -176,6 +177,7 @@ pub(crate) struct MessageProcessorArgs { pub(crate) outgoing: Arc, pub(crate) arg0_paths: Arg0DispatchPaths, pub(crate) config: Arc, + pub(crate) environment_manager: Arc, pub(crate) cli_overrides: Vec<(String, TomlValue)>, pub(crate) loader_overrides: LoaderOverrides, pub(crate) cloud_requirements: CloudRequirementsLoader, @@ -194,6 +196,7 @@ impl MessageProcessor { outgoing, arg0_paths, config, + environment_manager, cli_overrides, loader_overrides, cloud_requirements, @@ -217,6 +220,7 @@ impl MessageProcessor { .features .enabled(Feature::DefaultModeRequestUserInput), }, + environment_manager, )); auth_manager.set_forced_chatgpt_workspace_id(config.forced_chatgpt_workspace_id.clone()); auth_manager.set_external_auth_refresher(Arc::new(ExternalAuthRefreshBridge { diff --git a/codex-rs/app-server/src/message_processor/tracing_tests.rs b/codex-rs/app-server/src/message_processor/tracing_tests.rs index aa66f79f29..d2fe9c23d7 100644 --- a/codex-rs/app-server/src/message_processor/tracing_tests.rs +++ b/codex-rs/app-server/src/message_processor/tracing_tests.rs @@ -24,6 +24,7 @@ use codex_core::config::Config; use codex_core::config::ConfigBuilder; use codex_core::config_loader::CloudRequirementsLoader; use codex_core::config_loader::LoaderOverrides; +use codex_exec_server::EnvironmentManager; use codex_feedback::CodexFeedback; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::W3cTraceContext; @@ -236,6 +237,7 @@ fn build_test_processor( outgoing, arg0_paths: Arg0DispatchPaths::default(), config, + environment_manager: Arc::new(EnvironmentManager::new(/*exec_server_url*/ None)), cli_overrides: Vec::new(), loader_overrides: LoaderOverrides::default(), cloud_requirements: CloudRequirementsLoader::default(), diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 3e2d7ff689..853f0235e0 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1914,10 +1914,6 @@ "experimental_compact_prompt_file": { "$ref": "#/definitions/AbsolutePathBuf" }, - "experimental_exec_server_url": { - "description": "Experimental / do not use. Overrides the URL used when connecting to a remote exec server.", - "type": "string" - }, "experimental_realtime_start_instructions": { "description": "Experimental / do not use. Replaces the built-in realtime start instructions inserted into developer messages when realtime becomes active.", "type": "string" diff --git a/codex-rs/core/src/agent/control_tests.rs b/codex-rs/core/src/agent/control_tests.rs index 10e9821aea..878d7d0991 100644 --- a/codex-rs/core/src/agent/control_tests.rs +++ b/codex-rs/core/src/agent/control_tests.rs @@ -75,6 +75,9 @@ impl AgentControlHarness { CodexAuth::from_api_key("dummy"), config.model_provider.clone(), config.codex_home.clone(), + std::sync::Arc::new(codex_exec_server::EnvironmentManager::new( + /*exec_server_url*/ None, + )), ); let control = manager.agent_control(); Self { @@ -811,6 +814,9 @@ async fn spawn_agent_respects_max_threads_limit() { CodexAuth::from_api_key("dummy"), config.model_provider.clone(), config.codex_home.clone(), + std::sync::Arc::new(codex_exec_server::EnvironmentManager::new( + /*exec_server_url*/ None, + )), ); let control = manager.agent_control(); @@ -854,6 +860,9 @@ async fn spawn_agent_releases_slot_after_shutdown() { CodexAuth::from_api_key("dummy"), config.model_provider.clone(), config.codex_home.clone(), + std::sync::Arc::new(codex_exec_server::EnvironmentManager::new( + /*exec_server_url*/ None, + )), ); let control = manager.agent_control(); @@ -888,6 +897,9 @@ async fn spawn_agent_limit_shared_across_clones() { CodexAuth::from_api_key("dummy"), config.model_provider.clone(), config.codex_home.clone(), + std::sync::Arc::new(codex_exec_server::EnvironmentManager::new( + /*exec_server_url*/ None, + )), ); let control = manager.agent_control(); let cloned = control.clone(); @@ -924,6 +936,9 @@ async fn resume_agent_respects_max_threads_limit() { CodexAuth::from_api_key("dummy"), config.model_provider.clone(), config.codex_home.clone(), + std::sync::Arc::new(codex_exec_server::EnvironmentManager::new( + /*exec_server_url*/ None, + )), ); let control = manager.agent_control(); @@ -971,6 +986,9 @@ async fn resume_agent_releases_slot_after_resume_failure() { CodexAuth::from_api_key("dummy"), config.model_provider.clone(), config.codex_home.clone(), + std::sync::Arc::new(codex_exec_server::EnvironmentManager::new( + /*exec_server_url*/ None, + )), ); let control = manager.agent_control(); @@ -1361,6 +1379,9 @@ async fn resume_thread_subagent_restores_stored_nickname_and_role() { CodexAuth::from_api_key("dummy"), config.model_provider.clone(), config.codex_home.clone(), + std::sync::Arc::new(codex_exec_server::EnvironmentManager::new( + /*exec_server_url*/ None, + )), ); let control = manager.agent_control(); let harness = AgentControlHarness { diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index ecc9d3dada..a4bdb2c944 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -57,6 +57,7 @@ use codex_analytics::build_track_events_context; use codex_app_server_protocol::McpServerElicitationRequest; use codex_app_server_protocol::McpServerElicitationRequestParams; use codex_exec_server::Environment; +use codex_exec_server::EnvironmentManager; use codex_features::FEATURES; use codex_features::Feature; use codex_features::unstable_features_warning_event; @@ -402,6 +403,7 @@ pub(crate) struct CodexSpawnArgs { pub(crate) config: Config, pub(crate) auth_manager: Arc, pub(crate) models_manager: Arc, + pub(crate) environment_manager: Arc, pub(crate) skills_manager: Arc, pub(crate) plugins_manager: Arc, pub(crate) mcp_manager: Arc, @@ -455,6 +457,7 @@ impl Codex { mut config, auth_manager, models_manager, + environment_manager, skills_manager, plugins_manager, mcp_manager, @@ -646,6 +649,7 @@ impl Codex { agent_status_tx.clone(), conversation_history, session_source_clone, + environment_manager, skills_manager, plugins_manager, mcp_manager.clone(), @@ -1450,6 +1454,7 @@ impl Session { agent_status: watch::Sender, initial_history: InitialHistory, session_source: SessionSource, + environment_manager: Arc, skills_manager: Arc, plugins_manager: Arc, mcp_manager: Arc, @@ -1884,9 +1889,7 @@ impl Session { code_mode_service: crate::tools::code_mode::CodeModeService::new( config.js_repl_node_path.clone(), ), - environment: Arc::new( - Environment::create(config.experimental_exec_server_url.clone()).await?, - ), + environment: environment_manager.current().await?, }; let js_repl = Arc::new(JsReplHandle::with_node_path( config.js_repl_node_path.clone(), diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index d87dd070d5..9f491bbcb8 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use async_channel::Receiver; use async_channel::Sender; use codex_async_utils::OrCancelExt; +use codex_exec_server::EnvironmentManager; use codex_protocol::protocol::ApplyPatchApprovalRequestEvent; use codex_protocol::protocol::Event; use codex_protocol::protocol::EventMsg; @@ -76,6 +77,9 @@ pub(crate) async fn run_codex_thread_interactive( config, auth_manager, models_manager, + environment_manager: Arc::new(EnvironmentManager::new( + parent_ctx.environment.exec_server_url().map(str::to_owned), + )), skills_manager: Arc::clone(&parent_session.services.skills_manager), plugins_manager: Arc::clone(&parent_session.services.plugins_manager), mcp_manager: Arc::clone(&parent_session.services.mcp_manager), diff --git a/codex-rs/core/src/codex_tests.rs b/codex-rs/core/src/codex_tests.rs index 74aea12965..de64899467 100644 --- a/codex-rs/core/src/codex_tests.rs +++ b/codex-rs/core/src/codex_tests.rs @@ -2551,6 +2551,9 @@ async fn session_new_fails_when_zsh_fork_enabled_without_zsh_path() { agent_status_tx, InitialHistory::New, SessionSource::Exec, + Arc::new(codex_exec_server::EnvironmentManager::new( + /*exec_server_url*/ None, + )), skills_manager, plugins_manager, mcp_manager, @@ -2644,7 +2647,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { let skills_manager = Arc::new(SkillsManager::new(config.codex_home.clone(), true)); let network_approval = Arc::new(NetworkApprovalService::default()); let environment = Arc::new( - codex_exec_server::Environment::create(None) + codex_exec_server::Environment::create(/*exec_server_url*/ None) .await .expect("create environment"), ); @@ -3482,7 +3485,7 @@ pub(crate) async fn make_session_and_context_with_dynamic_tools_and_rx( let skills_manager = Arc::new(SkillsManager::new(config.codex_home.clone(), true)); let network_approval = Arc::new(NetworkApprovalService::default()); let environment = Arc::new( - codex_exec_server::Environment::create(None) + codex_exec_server::Environment::create(/*exec_server_url*/ None) .await .expect("create environment"), ); diff --git a/codex-rs/core/src/codex_tests_guardian.rs b/codex-rs/core/src/codex_tests_guardian.rs index 54f7405be2..33b8d15d19 100644 --- a/codex-rs/core/src/codex_tests_guardian.rs +++ b/codex-rs/core/src/codex_tests_guardian.rs @@ -12,6 +12,7 @@ use crate::sandboxing::SandboxPermissions; use crate::tools::context::FunctionToolOutput; use crate::turn_diff_tracker::TurnDiffTracker; use codex_app_server_protocol::ConfigLayerSource; +use codex_exec_server::EnvironmentManager; use codex_execpolicy::Decision; use codex_execpolicy::Evaluation; use codex_execpolicy::RuleMatch; @@ -437,6 +438,7 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() { config, auth_manager, models_manager, + environment_manager: Arc::new(EnvironmentManager::new(/*exec_server_url*/ None)), skills_manager, plugins_manager, mcp_manager, diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index f67c532341..34c41d44b0 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -4335,7 +4335,6 @@ fn test_precedence_fixture_with_o3_profile() -> std::io::Result<()> { model_verbosity: None, personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), - experimental_exec_server_url: None, realtime_audio: RealtimeAudioConfig::default(), experimental_realtime_start_instructions: None, experimental_realtime_ws_base_url: None, @@ -4478,7 +4477,6 @@ fn test_precedence_fixture_with_gpt3_profile() -> std::io::Result<()> { model_verbosity: None, personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), - experimental_exec_server_url: None, realtime_audio: RealtimeAudioConfig::default(), experimental_realtime_start_instructions: None, experimental_realtime_ws_base_url: None, @@ -4619,7 +4617,6 @@ fn test_precedence_fixture_with_zdr_profile() -> std::io::Result<()> { model_verbosity: None, personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), - experimental_exec_server_url: None, realtime_audio: RealtimeAudioConfig::default(), experimental_realtime_start_instructions: None, experimental_realtime_ws_base_url: None, @@ -4746,7 +4743,6 @@ fn test_precedence_fixture_with_gpt5_profile() -> std::io::Result<()> { model_verbosity: Some(Verbosity::High), personality: Some(Personality::Pragmatic), chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(), - experimental_exec_server_url: None, realtime_audio: RealtimeAudioConfig::default(), experimental_realtime_start_instructions: None, experimental_realtime_ws_base_url: None, @@ -5964,34 +5960,6 @@ experimental_realtime_start_instructions = "start instructions from config" Ok(()) } -#[test] -fn experimental_exec_server_url_loads_from_config_toml() -> std::io::Result<()> { - let cfg: ConfigToml = toml::from_str( - r#" -experimental_exec_server_url = "http://127.0.0.1:8080" -"#, - ) - .expect("TOML deserialization should succeed"); - - assert_eq!( - cfg.experimental_exec_server_url.as_deref(), - Some("http://127.0.0.1:8080") - ); - - let codex_home = TempDir::new()?; - let config = Config::load_from_base_config_with_overrides( - cfg, - ConfigOverrides::default(), - codex_home.path().to_path_buf(), - )?; - - assert_eq!( - config.experimental_exec_server_url.as_deref(), - Some("http://127.0.0.1:8080") - ); - Ok(()) -} - #[test] fn experimental_realtime_ws_base_url_loads_from_config_toml() -> std::io::Result<()> { let cfg: ConfigToml = toml::from_str( diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index e799f1b9ba..761e43b936 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -526,10 +526,6 @@ pub struct Config { /// Base URL for requests to ChatGPT (as opposed to the OpenAI API). pub chatgpt_base_url: String, - /// Experimental / do not use. Overrides the URL used when connecting to - /// a remote exec server. - pub experimental_exec_server_url: Option, - /// Machine-local realtime audio device preferences used by realtime voice. pub realtime_audio: RealtimeAudioConfig, @@ -1319,10 +1315,6 @@ pub struct ConfigToml { /// Base URL override for the built-in `openai` model provider. pub openai_base_url: Option, - /// Experimental / do not use. Overrides the URL used when connecting to - /// a remote exec server. - pub experimental_exec_server_url: Option, - /// Machine-local realtime audio device preferences used by realtime voice. #[serde(default)] pub audio: Option, @@ -2678,7 +2670,6 @@ impl Config { .chatgpt_base_url .or(cfg.chatgpt_base_url) .unwrap_or("https://chatgpt.com/backend-api/".to_string()), - experimental_exec_server_url: cfg.experimental_exec_server_url, realtime_audio: cfg .audio .map_or_else(RealtimeAudioConfig::default, |audio| RealtimeAudioConfig { diff --git a/codex-rs/core/src/memories/tests.rs b/codex-rs/core/src/memories/tests.rs index a929401b96..03dbe71851 100644 --- a/codex-rs/core/src/memories/tests.rs +++ b/codex-rs/core/src/memories/tests.rs @@ -484,6 +484,9 @@ mod phase2 { CodexAuth::from_api_key("dummy"), config.model_provider.clone(), config.codex_home.clone(), + std::sync::Arc::new(codex_exec_server::EnvironmentManager::new( + /*exec_server_url*/ None, + )), ); let (mut session, _turn_context) = make_session_and_context().await; session.services.state_db = Some(Arc::clone(&state_db)); diff --git a/codex-rs/core/src/test_support.rs b/codex-rs/core/src/test_support.rs index c2aad83df4..075395e3a7 100644 --- a/codex-rs/core/src/test_support.rs +++ b/codex-rs/core/src/test_support.rs @@ -7,6 +7,7 @@ use std::path::PathBuf; use std::sync::Arc; +use codex_exec_server::EnvironmentManager; use codex_protocol::config_types::CollaborationModeMask; use codex_protocol::openai_models::ModelInfo; use codex_protocol::openai_models::ModelPreset; @@ -60,8 +61,14 @@ pub fn thread_manager_with_models_provider_and_home( auth: CodexAuth, provider: ModelProviderInfo, codex_home: PathBuf, + environment_manager: Arc, ) -> ThreadManager { - ThreadManager::with_models_provider_and_home_for_tests(auth, provider, codex_home) + ThreadManager::with_models_provider_and_home_for_tests( + auth, + provider, + codex_home, + environment_manager, + ) } pub async fn start_thread_with_user_shell_override( diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index 511a6fc97b..7f272f9595 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -28,6 +28,7 @@ use crate::skills_watcher::SkillsWatcherEvent; use crate::tasks::interrupted_turn_history_marker; use codex_app_server_protocol::ThreadHistoryBuilder; use codex_app_server_protocol::TurnStatus; +use codex_exec_server::EnvironmentManager; use codex_protocol::ThreadId; use codex_protocol::config_types::CollaborationModeMask; #[cfg(test)] @@ -200,6 +201,7 @@ pub(crate) struct ThreadManagerState { thread_created_tx: broadcast::Sender, auth_manager: Arc, models_manager: Arc, + environment_manager: Arc, skills_manager: Arc, plugins_manager: Arc, mcp_manager: Arc, @@ -215,6 +217,7 @@ impl ThreadManager { auth_manager: Arc, session_source: SessionSource, collaboration_modes_config: CollaborationModesConfig, + environment_manager: Arc, ) -> Self { let codex_home = config.codex_home.clone(); let restriction_product = session_source.restriction_product(); @@ -246,6 +249,7 @@ impl ThreadManager { collaboration_modes_config, openai_models_provider, )), + environment_manager, skills_manager, plugins_manager, mcp_manager, @@ -272,8 +276,12 @@ impl ThreadManager { )); std::fs::create_dir_all(&codex_home) .unwrap_or_else(|err| panic!("temp codex home dir create failed: {err}")); - let mut manager = - Self::with_models_provider_and_home_for_tests(auth, provider, codex_home.clone()); + let mut manager = Self::with_models_provider_and_home_for_tests( + auth, + provider, + codex_home.clone(), + Arc::new(EnvironmentManager::new(/*exec_server_url*/ None)), + ); manager._test_codex_home_guard = Some(TempCodexHomeGuard { path: codex_home }); manager } @@ -284,6 +292,7 @@ impl ThreadManager { auth: CodexAuth, provider: ModelProviderInfo, codex_home: PathBuf, + environment_manager: Arc, ) -> Self { set_thread_manager_test_mode_for_tests(/*enabled*/ true); let auth_manager = AuthManager::from_auth_for_testing(auth); @@ -309,6 +318,7 @@ impl ThreadManager { auth_manager.clone(), provider, )), + environment_manager, skills_manager, plugins_manager, mcp_manager, @@ -844,6 +854,7 @@ impl ThreadManagerState { config, auth_manager, models_manager: Arc::clone(&self.models_manager), + environment_manager: Arc::clone(&self.environment_manager), skills_manager: Arc::clone(&self.skills_manager), plugins_manager: Arc::clone(&self.plugins_manager), mcp_manager: Arc::clone(&self.mcp_manager), diff --git a/codex-rs/core/src/thread_manager_tests.rs b/codex-rs/core/src/thread_manager_tests.rs index 64830fa727..c80f5f743b 100644 --- a/codex-rs/core/src/thread_manager_tests.rs +++ b/codex-rs/core/src/thread_manager_tests.rs @@ -244,6 +244,9 @@ async fn shutdown_all_threads_bounded_submits_shutdown_to_every_thread() { CodexAuth::from_api_key("dummy"), config.model_provider.clone(), config.codex_home.clone(), + Arc::new(codex_exec_server::EnvironmentManager::new( + /*exec_server_url*/ None, + )), ); let thread_1 = manager .start_thread(config.clone()) @@ -292,6 +295,9 @@ async fn new_uses_configured_openai_provider_for_model_refresh() { auth_manager, SessionSource::Exec, CollaborationModesConfig::default(), + Arc::new(codex_exec_server::EnvironmentManager::new( + /*exec_server_url*/ None, + )), ); let _ = manager.list_models(RefreshStrategy::Online).await; @@ -419,6 +425,9 @@ async fn interrupted_fork_snapshot_does_not_synthesize_turn_id_for_legacy_histor auth_manager.clone(), SessionSource::Exec, CollaborationModesConfig::default(), + Arc::new(codex_exec_server::EnvironmentManager::new( + /*exec_server_url*/ None, + )), ); let source = manager @@ -516,6 +525,9 @@ async fn interrupted_fork_snapshot_preserves_explicit_turn_id() { auth_manager.clone(), SessionSource::Exec, CollaborationModesConfig::default(), + Arc::new(codex_exec_server::EnvironmentManager::new( + /*exec_server_url*/ None, + )), ); let source = manager @@ -602,6 +614,9 @@ async fn interrupted_fork_snapshot_uses_persisted_mid_turn_history_without_live_ auth_manager.clone(), SessionSource::Exec, CollaborationModesConfig::default(), + Arc::new(codex_exec_server::EnvironmentManager::new( + /*exec_server_url*/ None, + )), ); let source = manager diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index 7b0d412786..5ed5e8a731 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -105,8 +105,7 @@ impl TestEnv { pub async fn local() -> Result { let local_cwd_temp_dir = TempDir::new()?; let cwd = local_cwd_temp_dir.path().to_path_buf(); - let environment = - codex_exec_server::Environment::create(/*experimental_exec_server_url*/ None).await?; + let environment = codex_exec_server::Environment::create(/*exec_server_url*/ None).await?; Ok(Self { environment, cwd, @@ -119,8 +118,8 @@ impl TestEnv { &self.environment } - pub fn experimental_exec_server_url(&self) -> Option<&str> { - self.environment.experimental_exec_server_url() + pub fn exec_server_url(&self) -> Option<&str> { + self.environment.exec_server_url() } } @@ -390,17 +389,17 @@ impl TestCodexBuilder { server: &wiremock::MockServer, ) -> anyhow::Result { let test_env = test_env().await?; - let experimental_exec_server_url = - test_env.experimental_exec_server_url().map(str::to_owned); + let home = match self.home.clone() { + Some(home) => home, + None => Arc::new(TempDir::new()?), + }; + let base_url = format!("{}/v1", server.uri()); let cwd = test_env.cwd.to_path_buf(); self.config_mutators.push(Box::new(move |config| { - config.experimental_exec_server_url = experimental_exec_server_url; config.cwd = cwd.abs(); })); - - let mut test = self.build(server).await?; - test._test_env = test_env; - Ok(test) + let (config, cwd) = self.prepare_config(base_url, &home).await?; + Box::pin(self.build_from_config(config, cwd, home, /*resume_from*/ None, test_env)).await } pub async fn build_with_streaming_server( @@ -479,18 +478,23 @@ impl TestCodexBuilder { test_env: TestEnv, ) -> anyhow::Result { let auth = self.auth.clone(); + let environment_manager = Arc::new(codex_exec_server::EnvironmentManager::new( + test_env.exec_server_url().map(str::to_owned), + )); let thread_manager = if config.model_catalog.is_some() { ThreadManager::new( &config, codex_core::test_support::auth_manager_from_auth(auth.clone()), SessionSource::Exec, CollaborationModesConfig::default(), + Arc::clone(&environment_manager), ) } else { codex_core::test_support::thread_manager_with_models_provider_and_home( auth.clone(), config.model_provider.clone(), config.codex_home.clone(), + Arc::clone(&environment_manager), ) }; let thread_manager = Arc::new(thread_manager); diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index 869acc49f1..e0e265666a 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -829,6 +829,9 @@ async fn prefers_apikey_when_config_prefers_apikey_even_with_chatgpt_tokens() { .features .enabled(Feature::DefaultModeRequestUserInput), }, + Arc::new(codex_exec_server::EnvironmentManager::new( + /*exec_server_url*/ None, + )), ); let NewThread { thread: codex, .. } = thread_manager .start_thread(config) diff --git a/codex-rs/exec-server/src/environment.rs b/codex-rs/exec-server/src/environment.rs index 7cc3f78401..e6f4d540b2 100644 --- a/codex-rs/exec-server/src/environment.rs +++ b/codex-rs/exec-server/src/environment.rs @@ -1,5 +1,7 @@ use std::sync::Arc; +use tokio::sync::OnceCell; + use crate::ExecServerClient; use crate::ExecServerError; use crate::RemoteExecServerConnectArgs; @@ -10,13 +12,49 @@ use crate::process::ExecProcess; use crate::remote_file_system::RemoteFileSystem; use crate::remote_process::RemoteProcess; +pub const CODEX_EXEC_SERVER_URL_ENV_VAR: &str = "CODEX_EXEC_SERVER_URL"; + pub trait ExecutorEnvironment: Send + Sync { fn get_executor(&self) -> Arc; } +#[derive(Debug, Default)] +pub struct EnvironmentManager { + exec_server_url: Option, + current_environment: OnceCell>, +} + +impl EnvironmentManager { + pub fn new(exec_server_url: Option) -> Self { + Self { + exec_server_url: normalize_exec_server_url(exec_server_url), + current_environment: OnceCell::new(), + } + } + + pub fn from_env() -> Self { + Self::new(std::env::var(CODEX_EXEC_SERVER_URL_ENV_VAR).ok()) + } + + pub fn exec_server_url(&self) -> Option<&str> { + self.exec_server_url.as_deref() + } + + pub async fn current(&self) -> Result, ExecServerError> { + self.current_environment + .get_or_try_init(|| async { + Ok(Arc::new( + Environment::create(self.exec_server_url.clone()).await?, + )) + }) + .await + .map(Arc::clone) + } +} + #[derive(Clone)] pub struct Environment { - experimental_exec_server_url: Option, + exec_server_url: Option, remote_exec_server_client: Option, executor: Arc, } @@ -32,7 +70,7 @@ impl Default for Environment { } Self { - experimental_exec_server_url: None, + exec_server_url: None, remote_exec_server_client: None, executor: Arc::new(local_process), } @@ -42,19 +80,15 @@ impl Default for Environment { impl std::fmt::Debug for Environment { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Environment") - .field( - "experimental_exec_server_url", - &self.experimental_exec_server_url, - ) + .field("exec_server_url", &self.exec_server_url) .finish_non_exhaustive() } } impl Environment { - pub async fn create( - experimental_exec_server_url: Option, - ) -> Result { - let remote_exec_server_client = if let Some(url) = &experimental_exec_server_url { + pub async fn create(exec_server_url: Option) -> Result { + let exec_server_url = normalize_exec_server_url(exec_server_url); + let remote_exec_server_client = if let Some(url) = &exec_server_url { Some( ExecServerClient::connect_websocket(RemoteExecServerConnectArgs { websocket_url: url.clone(), @@ -83,14 +117,14 @@ impl Environment { }; Ok(Self { - experimental_exec_server_url, + exec_server_url, remote_exec_server_client, executor, }) } - pub fn experimental_exec_server_url(&self) -> Option<&str> { - self.experimental_exec_server_url.as_deref() + pub fn exec_server_url(&self) -> Option<&str> { + self.exec_server_url.as_deref() } pub fn get_executor(&self) -> Arc { @@ -106,6 +140,13 @@ impl Environment { } } +fn normalize_exec_server_url(exec_server_url: Option) -> Option { + exec_server_url.and_then(|url| { + let url = url.trim(); + (!url.is_empty()).then(|| url.to_string()) + }) +} + impl ExecutorEnvironment for Environment { fn get_executor(&self) -> Arc { Arc::clone(&self.executor) @@ -114,17 +155,39 @@ impl ExecutorEnvironment for Environment { #[cfg(test)] mod tests { + use std::sync::Arc; + use super::Environment; + use super::EnvironmentManager; use pretty_assertions::assert_eq; #[tokio::test] async fn create_without_remote_exec_server_url_does_not_connect() { - let environment = Environment::create(None).await.expect("create environment"); + let environment = Environment::create(/*exec_server_url*/ None) + .await + .expect("create environment"); - assert_eq!(environment.experimental_exec_server_url(), None); + assert_eq!(environment.exec_server_url(), None); assert!(environment.remote_exec_server_client.is_none()); } + #[test] + fn environment_manager_normalizes_empty_url() { + let manager = EnvironmentManager::new(Some(String::new())); + + assert_eq!(manager.exec_server_url(), None); + } + + #[tokio::test] + async fn environment_manager_current_caches_environment() { + let manager = EnvironmentManager::new(/*exec_server_url*/ None); + + let first = manager.current().await.expect("get current environment"); + let second = manager.current().await.expect("get current environment"); + + assert!(Arc::ptr_eq(&first, &second)); + } + #[tokio::test] async fn default_environment_has_ready_local_executor() { let environment = Environment::default(); diff --git a/codex-rs/exec-server/src/lib.rs b/codex-rs/exec-server/src/lib.rs index 68ff9f6549..8a723041ce 100644 --- a/codex-rs/exec-server/src/lib.rs +++ b/codex-rs/exec-server/src/lib.rs @@ -30,7 +30,9 @@ pub use codex_app_server_protocol::FsRemoveParams; pub use codex_app_server_protocol::FsRemoveResponse; pub use codex_app_server_protocol::FsWriteFileParams; pub use codex_app_server_protocol::FsWriteFileResponse; +pub use environment::CODEX_EXEC_SERVER_URL_ENV_VAR; pub use environment::Environment; +pub use environment::EnvironmentManager; pub use environment::ExecutorEnvironment; pub use file_system::CopyOptions; pub use file_system::CreateDirectoryOptions; diff --git a/codex-rs/exec-server/src/remote_file_system.rs b/codex-rs/exec-server/src/remote_file_system.rs index 9711f43e5f..27e4fee911 100644 --- a/codex-rs/exec-server/src/remote_file_system.rs +++ b/codex-rs/exec-server/src/remote_file_system.rs @@ -10,6 +10,7 @@ use codex_app_server_protocol::FsRemoveParams; use codex_app_server_protocol::FsWriteFileParams; use codex_utils_absolute_path::AbsolutePathBuf; use tokio::io; +use tracing::trace; use crate::CopyOptions; use crate::CreateDirectoryOptions; @@ -30,6 +31,7 @@ pub(crate) struct RemoteFileSystem { impl RemoteFileSystem { pub(crate) fn new(client: ExecServerClient) -> Self { + trace!("remote fs new"); Self { client } } } @@ -37,6 +39,7 @@ impl RemoteFileSystem { #[async_trait] impl ExecutorFileSystem for RemoteFileSystem { async fn read_file(&self, path: &AbsolutePathBuf) -> FileSystemResult> { + trace!("remote fs read_file"); let response = self .client .fs_read_file(FsReadFileParams { path: path.clone() }) @@ -51,6 +54,7 @@ impl ExecutorFileSystem for RemoteFileSystem { } async fn write_file(&self, path: &AbsolutePathBuf, contents: Vec) -> FileSystemResult<()> { + trace!("remote fs write_file"); self.client .fs_write_file(FsWriteFileParams { path: path.clone(), @@ -66,6 +70,7 @@ impl ExecutorFileSystem for RemoteFileSystem { path: &AbsolutePathBuf, options: CreateDirectoryOptions, ) -> FileSystemResult<()> { + trace!("remote fs create_directory"); self.client .fs_create_directory(FsCreateDirectoryParams { path: path.clone(), @@ -77,6 +82,7 @@ impl ExecutorFileSystem for RemoteFileSystem { } async fn get_metadata(&self, path: &AbsolutePathBuf) -> FileSystemResult { + trace!("remote fs get_metadata"); let response = self .client .fs_get_metadata(FsGetMetadataParams { path: path.clone() }) @@ -94,6 +100,7 @@ impl ExecutorFileSystem for RemoteFileSystem { &self, path: &AbsolutePathBuf, ) -> FileSystemResult> { + trace!("remote fs read_directory"); let response = self .client .fs_read_directory(FsReadDirectoryParams { path: path.clone() }) @@ -111,6 +118,7 @@ impl ExecutorFileSystem for RemoteFileSystem { } async fn remove(&self, path: &AbsolutePathBuf, options: RemoveOptions) -> FileSystemResult<()> { + trace!("remote fs remove"); self.client .fs_remove(FsRemoveParams { path: path.clone(), @@ -128,6 +136,7 @@ impl ExecutorFileSystem for RemoteFileSystem { destination_path: &AbsolutePathBuf, options: CopyOptions, ) -> FileSystemResult<()> { + trace!("remote fs copy"); self.client .fs_copy(FsCopyParams { source_path: source_path.clone(), diff --git a/codex-rs/exec-server/src/remote_process.rs b/codex-rs/exec-server/src/remote_process.rs index c34c1fe6ac..f6e8109e4a 100644 --- a/codex-rs/exec-server/src/remote_process.rs +++ b/codex-rs/exec-server/src/remote_process.rs @@ -1,5 +1,6 @@ use async_trait::async_trait; use tokio::sync::broadcast; +use tracing::trace; use crate::ExecProcess; use crate::ExecServerClient; @@ -19,6 +20,7 @@ pub(crate) struct RemoteProcess { impl RemoteProcess { pub(crate) fn new(client: ExecServerClient) -> Self { + trace!("remote process new"); Self { client } } } @@ -26,10 +28,12 @@ impl RemoteProcess { #[async_trait] impl ExecProcess for RemoteProcess { async fn start(&self, params: ExecParams) -> Result { + trace!("remote process start"); self.client.exec(params).await } async fn read(&self, params: ReadParams) -> Result { + trace!("remote process read"); self.client.read(params).await } @@ -38,14 +42,17 @@ impl ExecProcess for RemoteProcess { process_id: &str, chunk: Vec, ) -> Result { + trace!("remote process write"); self.client.write(process_id, chunk).await } async fn terminate(&self, process_id: &str) -> Result { + trace!("remote process terminate"); self.client.terminate(process_id).await } fn subscribe_events(&self) -> broadcast::Receiver { + trace!("remote process subscribe_events"); self.client.event_receiver() } } diff --git a/codex-rs/exec-server/tests/exec_process.rs b/codex-rs/exec-server/tests/exec_process.rs index d72f83b951..954c73103e 100644 --- a/codex-rs/exec-server/tests/exec_process.rs +++ b/codex-rs/exec-server/tests/exec_process.rs @@ -30,7 +30,7 @@ async fn create_process_context(use_remote: bool) -> Result { _server: Some(server), }) } else { - let environment = Environment::create(None).await?; + let environment = Environment::create(/*exec_server_url*/ None).await?; Ok(ProcessContext { process: environment.get_executor(), _server: None, diff --git a/codex-rs/exec-server/tests/file_system.rs b/codex-rs/exec-server/tests/file_system.rs index ed90d7aa95..dea47e8fcc 100644 --- a/codex-rs/exec-server/tests/file_system.rs +++ b/codex-rs/exec-server/tests/file_system.rs @@ -36,7 +36,7 @@ async fn create_file_system_context(use_remote: bool) -> Result IoResult<()> { + let environment_manager = Arc::new(EnvironmentManager::from_env()); // 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| { @@ -127,7 +130,8 @@ pub async fn run_main( let mut processor = MessageProcessor::new( outgoing_message_sender, arg0_paths, - std::sync::Arc::new(config), + Arc::new(config), + environment_manager, ); async move { while let Some(msg) = incoming_rx.recv().await { diff --git a/codex-rs/mcp-server/src/message_processor.rs b/codex-rs/mcp-server/src/message_processor.rs index e5397e4cac..1fba41164c 100644 --- a/codex-rs/mcp-server/src/message_processor.rs +++ b/codex-rs/mcp-server/src/message_processor.rs @@ -1,4 +1,5 @@ use std::collections::HashMap; +use std::sync::Arc; use codex_arg0::Arg0DispatchPaths; use codex_core::AuthManager; @@ -7,6 +8,7 @@ use codex_core::config::Config; use codex_core::default_client::USER_AGENT_SUFFIX; use codex_core::default_client::get_codex_user_agent; use codex_core::models_manager::collaboration_mode_presets::CollaborationModesConfig; +use codex_exec_server::EnvironmentManager; use codex_features::Feature; use codex_protocol::ThreadId; use codex_protocol::protocol::SessionSource; @@ -27,7 +29,6 @@ use rmcp::model::RequestId; use rmcp::model::ServerCapabilities; use rmcp::model::ToolsCapability; use serde_json::json; -use std::sync::Arc; use tokio::sync::Mutex; use tokio::task; @@ -52,6 +53,7 @@ impl MessageProcessor { outgoing: OutgoingMessageSender, arg0_paths: Arg0DispatchPaths, config: Arc, + environment_manager: Arc, ) -> Self { let outgoing = Arc::new(outgoing); let auth_manager = AuthManager::shared( @@ -68,6 +70,7 @@ impl MessageProcessor { .features .enabled(Feature::DefaultModeRequestUserInput), }, + environment_manager, )); Self { outgoing, diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 01a9c27a7a..4613ddcf82 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -37,6 +37,7 @@ codex-chatgpt = { workspace = true } codex-client = { workspace = true } codex-cloud-requirements = { workspace = true } codex-core = { workspace = true } +codex-exec-server = { workspace = true } codex-features = { workspace = true } codex-feedback = { workspace = true } codex-file-search = { workspace = true } diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index a606520277..fe1cb6ae0c 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -77,6 +77,7 @@ use codex_core::models_manager::model_presets::HIDE_GPT_5_1_CODEX_MAX_MIGRATION_ use codex_core::models_manager::model_presets::HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG; #[cfg(target_os = "windows")] use codex_core::windows_sandbox::WindowsSandboxLevelExt; +use codex_exec_server::EnvironmentManager; use codex_features::Feature; use codex_otel::SessionTelemetry; use codex_otel::TelemetryAuthMode; @@ -2356,6 +2357,7 @@ impl App { let harness_overrides = normalize_harness_overrides_for_cwd(harness_overrides, &config.cwd)?; + let environment_manager = Arc::new(EnvironmentManager::from_env()); let thread_manager = Arc::new(ThreadManager::new( &config, auth_manager.clone(), @@ -2365,6 +2367,7 @@ impl App { .features .enabled(Feature::DefaultModeRequestUserInput), }, + environment_manager, )); let mut model = thread_manager .get_models_manager() diff --git a/justfile b/justfile index 768b714073..5c9fa5e6ab 100644 --- a/justfile +++ b/justfile @@ -14,6 +14,11 @@ codex *args: exec *args: cargo run --bin codex -- exec "$@" +# Start codex-exec-server, enable the app-server TUI, and run codex-tui. +[no-cd] +tui-with-exec-server *args: + ./scripts/run_tui_with_exec_server.sh "$@" + # Run the CLI version of the file-search crate. file-search *args: cargo run --bin codex-file-search -- "$@" diff --git a/scripts/run_tui_with_exec_server.sh b/scripts/run_tui_with_exec_server.sh new file mode 100755 index 0000000000..8f2fa80131 --- /dev/null +++ b/scripts/run_tui_with_exec_server.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash + +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cargo_root="$repo_root/codex-rs" +listen_url="${CODEX_EXEC_SERVER_LISTEN_URL:-ws://127.0.0.1:0}" +start_timeout_seconds="${CODEX_EXEC_SERVER_START_TIMEOUT_SECONDS:-120}" +tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/codex-tui-with-exec-server.XXXXXX")" +stdout_log="$tmp_dir/exec-server.stdout" +stderr_log="$tmp_dir/exec-server.stderr" +server_pid="" +exec_server_url="" + +cleanup() { + if [[ -n "$server_pid" ]]; then + kill "$server_pid" >/dev/null 2>&1 || true + wait "$server_pid" >/dev/null 2>&1 || true + fi + rm -rf "$tmp_dir" +} + +trap cleanup EXIT INT TERM HUP + +( + cd "$cargo_root" + cargo run -p codex-exec-server -- --listen "$listen_url" +) >"$stdout_log" 2>"$stderr_log" & +server_pid="$!" + +# Wait for the server to print its bound websocket URL before launching the TUI. +for _ in $(seq 1 "$((start_timeout_seconds * 20))"); do + if [[ -s "$stdout_log" ]]; then + exec_server_url="$(head -n 1 "$stdout_log" | tr -d '\r')" + if [[ "$exec_server_url" == ws://* ]]; then + break + fi + fi + + if ! kill -0 "$server_pid" >/dev/null 2>&1; then + cat "$stderr_log" >&2 || true + cat "$stdout_log" >&2 || true + echo "failed to start codex-exec-server" >&2 + exit 1 + fi + + sleep 0.05 +done + +if [[ -z "$exec_server_url" ]]; then + cat "$stderr_log" >&2 || true + cat "$stdout_log" >&2 || true + echo "timed out waiting ${start_timeout_seconds}s for codex-exec-server to report its websocket URL" >&2 + exit 1 +fi + +export CODEX_EXEC_SERVER_URL="$exec_server_url" +echo "Starting codex-tui with CODEX_EXEC_SERVER_URL=$CODEX_EXEC_SERVER_URL" >&2 + +cd "$cargo_root" +cargo run -p codex-tui --bin codex-tui -- -c features.tui_app_server=true -c mcp_oauth_credentials_store=file "$@" From 2794e278497e7e604a512ce877d16ed8e8fe6be9 Mon Sep 17 00:00:00 2001 From: canvrno-oai Date: Wed, 25 Mar 2026 17:03:18 -0700 Subject: [PATCH 04/12] 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 05/12] 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 06/12] [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 07/12] [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 08/12] [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 09/12] 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 10/12] 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 11/12] 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 a0c1ff4d71a118a2f23c2744da2ab072c970db3a Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Wed, 25 Mar 2026 22:35:10 -0700 Subject: [PATCH 12/12] fix: remove apply_patch large-stack test workaround --- codex-rs/Cargo.lock | 10 -- codex-rs/Cargo.toml | 2 - codex-rs/core/Cargo.toml | 1 - codex-rs/core/tests/common/test_codex.rs | 38 ++--- codex-rs/core/tests/suite/apply_patch_cli.rs | 63 ++++---- codex-rs/test-macros/BUILD.bazel | 7 - codex-rs/test-macros/Cargo.toml | 16 -- codex-rs/test-macros/src/lib.rs | 155 ------------------- 8 files changed, 50 insertions(+), 242 deletions(-) delete mode 100644 codex-rs/test-macros/BUILD.bazel delete mode 100644 codex-rs/test-macros/Cargo.toml delete mode 100644 codex-rs/test-macros/src/lib.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 02625d90c2..782cd6fd46 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1920,7 +1920,6 @@ dependencies = [ "codex-shell-escalation", "codex-state", "codex-terminal-detection", - "codex-test-macros", "codex-utils-absolute-path", "codex-utils-cache", "codex-utils-cargo-bin", @@ -2696,15 +2695,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "codex-test-macros" -version = "0.0.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.114", -] - [[package]] name = "codex-tui" version = "0.0.0" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index f19fb650f7..4d325777a7 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -80,7 +80,6 @@ members = [ "state", "terminal-detection", "codex-experimental-api-macros", - "test-macros", "package-manager", "plugin", "artifacts", @@ -152,7 +151,6 @@ codex-shell-escalation = { path = "shell-escalation" } codex-skills = { path = "skills" } codex-state = { path = "state" } codex-stdio-to-uds = { path = "stdio-to-uds" } -codex-test-macros = { path = "test-macros" } codex-terminal-detection = { path = "terminal-detection" } codex-tui = { path = "tui" } codex-tui-app-server = { path = "tui_app_server" } diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 25e44d7631..4274a6bbb2 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -149,7 +149,6 @@ codex-arg0 = { workspace = true } codex-otel = { workspace = true, features = [ "disable-default-metrics-exporter", ] } -codex-test-macros = { workspace = true } codex-utils-cargo-bin = { workspace = true } core_test_support = { workspace = true } ctor = { workspace = true } diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index 5ed5e8a731..e54ca84027 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -661,11 +661,11 @@ impl TestCodex { } pub async fn submit_turn(&self, prompt: &str) -> Result<()> { - self.submit_turn_with_policies( + Box::pin(self.submit_turn_with_policies( prompt, AskForApproval::Never, SandboxPolicy::DangerFullAccess, - ) + )) .await } @@ -674,7 +674,7 @@ impl TestCodex { prompt: &str, sandbox_policy: SandboxPolicy, ) -> Result<()> { - self.submit_turn_with_policies(prompt, AskForApproval::Never, sandbox_policy) + Box::pin(self.submit_turn_with_policies(prompt, AskForApproval::Never, sandbox_policy)) .await } @@ -683,12 +683,12 @@ impl TestCodex { prompt: &str, service_tier: Option, ) -> Result<()> { - self.submit_turn_with_context( + Box::pin(self.submit_turn_with_context( prompt, AskForApproval::Never, SandboxPolicy::DangerFullAccess, Some(service_tier), - ) + )) .await } @@ -698,12 +698,12 @@ impl TestCodex { approval_policy: AskForApproval, sandbox_policy: SandboxPolicy, ) -> Result<()> { - self.submit_turn_with_context( + Box::pin(self.submit_turn_with_context( prompt, approval_policy, sandbox_policy, /*service_tier*/ None, - ) + )) .await } @@ -756,16 +756,16 @@ pub struct TestCodexHarness { impl TestCodexHarness { pub async fn new() -> Result { - Self::with_builder(test_codex()).await + Box::pin(Self::with_builder(test_codex())).await } pub async fn with_config(mutator: impl FnOnce(&mut Config) + Send + 'static) -> Result { - Self::with_builder(test_codex().with_config(mutator)).await + Box::pin(Self::with_builder(test_codex().with_config(mutator))).await } pub async fn with_builder(mut builder: TestCodexBuilder) -> Result { let server = start_mock_server().await; - let test = builder.build(&server).await?; + let test = Box::pin(builder.build(&server)).await?; Ok(Self { server, test }) } @@ -786,7 +786,7 @@ impl TestCodexHarness { } pub async fn submit(&self, prompt: &str) -> Result<()> { - self.test.submit_turn(prompt).await + Box::pin(self.test.submit_turn(prompt)).await } pub async fn submit_with_policy( @@ -794,9 +794,7 @@ impl TestCodexHarness { prompt: &str, sandbox_policy: SandboxPolicy, ) -> Result<()> { - self.test - .submit_turn_with_policy(prompt, sandbox_policy) - .await + Box::pin(self.test.submit_turn_with_policy(prompt, sandbox_policy)).await } pub async fn request_bodies(&self) -> Vec { @@ -815,12 +813,12 @@ impl TestCodexHarness { } pub async fn function_call_output_value(&self, call_id: &str) -> Value { - let bodies = self.request_bodies().await; + let bodies = Box::pin(self.request_bodies()).await; function_call_output(&bodies, call_id).clone() } pub async fn function_call_stdout(&self, call_id: &str) -> String { - self.function_call_output_value(call_id) + Box::pin(self.function_call_output_value(call_id)) .await .get("output") .and_then(Value::as_str) @@ -829,7 +827,7 @@ impl TestCodexHarness { } pub async fn custom_tool_call_output(&self, call_id: &str) -> String { - let bodies = self.request_bodies().await; + let bodies = Box::pin(self.request_bodies()).await; custom_tool_call_output_text(&bodies, call_id) } @@ -839,12 +837,14 @@ impl TestCodexHarness { output_type: ApplyPatchModelOutput, ) -> String { match output_type { - ApplyPatchModelOutput::Freeform => self.custom_tool_call_output(call_id).await, + ApplyPatchModelOutput::Freeform => { + Box::pin(self.custom_tool_call_output(call_id)).await + } ApplyPatchModelOutput::Function | ApplyPatchModelOutput::Shell | ApplyPatchModelOutput::ShellViaHeredoc | ApplyPatchModelOutput::ShellCommandViaHeredoc => { - self.function_call_stdout(call_id).await + Box::pin(self.function_call_stdout(call_id)).await } } } diff --git a/codex-rs/core/tests/suite/apply_patch_cli.rs b/codex-rs/core/tests/suite/apply_patch_cli.rs index d0cefcb616..2bd6837c22 100644 --- a/codex-rs/core/tests/suite/apply_patch_cli.rs +++ b/codex-rs/core/tests/suite/apply_patch_cli.rs @@ -3,7 +3,6 @@ use anyhow::Result; use base64::Engine; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; -use codex_test_macros::large_stack_test; use core_test_support::responses::ev_apply_patch_call; use core_test_support::responses::ev_apply_patch_custom_tool_call; use core_test_support::responses::ev_shell_command_call; @@ -42,7 +41,7 @@ use wiremock::matchers::method; use wiremock::matchers::path_regex; pub async fn apply_patch_harness() -> Result { - apply_patch_harness_with(|builder| builder).await + Box::pin(apply_patch_harness_with(|builder| builder)).await } async fn apply_patch_harness_with( @@ -51,7 +50,7 @@ async fn apply_patch_harness_with( let builder = configure(test_codex()).with_config(|config| { config.include_apply_patch_tool = true; }); - TestCodexHarness::with_builder(builder).await + Box::pin(TestCodexHarness::with_builder(builder)).await } pub async fn mount_apply_patch( @@ -87,7 +86,7 @@ fn apply_patch_responses( ] } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -134,7 +133,7 @@ D delete.txt Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -161,7 +160,7 @@ async fn apply_patch_cli_multiple_chunks(model_output: ApplyPatchModelOutput) -> Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -190,7 +189,7 @@ async fn apply_patch_cli_moves_file_to_new_directory( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -218,7 +217,7 @@ async fn apply_patch_cli_updates_file_appends_trailing_newline( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -244,7 +243,7 @@ async fn apply_patch_cli_insert_only_hunk_modifies_file( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -275,7 +274,7 @@ async fn apply_patch_cli_move_overwrites_existing_destination( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -338,7 +337,7 @@ async fn apply_patch_cli_move_without_content_change_has_no_turn_diff( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -364,7 +363,7 @@ async fn apply_patch_cli_add_overwrites_existing_file( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -396,7 +395,7 @@ async fn apply_patch_cli_rejects_invalid_hunk_header( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -430,7 +429,7 @@ async fn apply_patch_cli_reports_missing_context( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -466,7 +465,7 @@ async fn apply_patch_cli_reports_missing_target_file( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -503,7 +502,7 @@ async fn apply_patch_cli_delete_missing_file_reports_error( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -528,7 +527,7 @@ async fn apply_patch_cli_rejects_empty_patch(model_output: ApplyPatchModelOutput Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -555,7 +554,7 @@ async fn apply_patch_cli_delete_directory_reports_verification_error( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -609,7 +608,7 @@ async fn apply_patch_cli_rejects_path_traversal_outside_workspace( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -664,7 +663,7 @@ async fn apply_patch_cli_rejects_move_path_traversal_outside_workspace( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -701,7 +700,7 @@ async fn apply_patch_cli_verification_failure_has_no_side_effects( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn apply_patch_shell_command_heredoc_with_cd_updates_relative_workdir() -> Result<()> { skip_if_no_network!(Ok(())); @@ -739,7 +738,7 @@ async fn apply_patch_shell_command_heredoc_with_cd_updates_relative_workdir() -> Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn apply_patch_cli_can_use_shell_command_output_as_patch_input() -> Result<()> { skip_if_no_network!(Ok(())); @@ -879,7 +878,7 @@ async fn apply_patch_cli_can_use_shell_command_output_as_patch_input() -> Result Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn apply_patch_shell_command_heredoc_with_cd_emits_turn_diff() -> Result<()> { skip_if_no_network!(Ok(())); @@ -964,7 +963,7 @@ async fn apply_patch_shell_command_heredoc_with_cd_emits_turn_diff() -> Result<( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn apply_patch_shell_command_failure_propagates_error_and_skips_diff() -> Result<()> { skip_if_no_network!(Ok(())); @@ -1042,7 +1041,7 @@ async fn apply_patch_shell_command_failure_propagates_error_and_skips_diff() -> Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] #[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)] async fn apply_patch_function_accepts_lenient_heredoc_wrapped_patch( @@ -1065,7 +1064,7 @@ async fn apply_patch_function_accepts_lenient_heredoc_wrapped_patch( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -1088,7 +1087,7 @@ async fn apply_patch_cli_end_of_file_anchor(model_output: ApplyPatchModelOutput) Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -1123,7 +1122,7 @@ async fn apply_patch_cli_missing_second_chunk_context_rejected( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -1184,7 +1183,7 @@ async fn apply_patch_emits_turn_diff_event_with_unified_diff( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] @@ -1252,7 +1251,7 @@ async fn apply_patch_turn_diff_for_rename_with_content_change( Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn apply_patch_aggregates_diff_across_multiple_tool_calls() -> Result<()> { skip_if_no_network!(Ok(())); @@ -1322,7 +1321,7 @@ async fn apply_patch_aggregates_diff_across_multiple_tool_calls() -> Result<()> Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn apply_patch_aggregates_diff_preserves_success_after_failure() -> Result<()> { skip_if_no_network!(Ok(())); @@ -1414,7 +1413,7 @@ async fn apply_patch_aggregates_diff_preserves_success_after_failure() -> Result Ok(()) } -#[large_stack_test] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_case(ApplyPatchModelOutput::Freeform)] #[test_case(ApplyPatchModelOutput::Function)] #[test_case(ApplyPatchModelOutput::Shell)] diff --git a/codex-rs/test-macros/BUILD.bazel b/codex-rs/test-macros/BUILD.bazel deleted file mode 100644 index 0ff074f5e5..0000000000 --- a/codex-rs/test-macros/BUILD.bazel +++ /dev/null @@ -1,7 +0,0 @@ -load("//:defs.bzl", "codex_rust_crate") - -codex_rust_crate( - name = "test-macros", - crate_name = "codex_test_macros", - proc_macro = True, -) diff --git a/codex-rs/test-macros/Cargo.toml b/codex-rs/test-macros/Cargo.toml deleted file mode 100644 index 275580322d..0000000000 --- a/codex-rs/test-macros/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "codex-test-macros" -version.workspace = true -edition.workspace = true -license.workspace = true - -[lib] -proc-macro = true - -[dependencies] -proc-macro2 = "1" -quote = "1" -syn = { version = "2", features = ["full"] } - -[lints] -workspace = true diff --git a/codex-rs/test-macros/src/lib.rs b/codex-rs/test-macros/src/lib.rs deleted file mode 100644 index 16c87f8582..0000000000 --- a/codex-rs/test-macros/src/lib.rs +++ /dev/null @@ -1,155 +0,0 @@ -use proc_macro::TokenStream; -use proc_macro2::TokenStream as TokenStream2; -use quote::quote; -use syn::Attribute; -use syn::ItemFn; -use syn::parse::Nothing; -use syn::parse_macro_input; -use syn::parse_quote; - -const LARGE_STACK_TEST_STACK_SIZE_BYTES: usize = 16 * 1024 * 1024; - -/// Run a test body on a dedicated thread with a larger stack. -/// -/// For async tests, this macro creates a Tokio multi-thread runtime with two -/// worker threads and blocks on the original async body inside the large-stack -/// thread. -#[proc_macro_attribute] -pub fn large_stack_test(attr: TokenStream, item: TokenStream) -> TokenStream { - parse_macro_input!(attr as Nothing); - - let item = parse_macro_input!(item as ItemFn); - expand_large_stack_test(item).into() -} - -fn expand_large_stack_test(mut item: ItemFn) -> TokenStream2 { - let attrs = filtered_attributes(&item.attrs); - item.attrs = attrs; - - let is_async = item.sig.asyncness.take().is_some(); - let name = &item.sig.ident; - let body = &item.block; - - let thread_body = if is_async { - quote! { - { - let runtime = ::tokio::runtime::Builder::new_multi_thread() - .worker_threads(2) - .enable_all() - .build() - .unwrap_or_else(|error| { - panic!("failed to build tokio runtime for large-stack test: {error}") - }); - runtime.block_on(async move #body) - } - } - } else { - quote! { #body } - }; - - *item.block = parse_quote!({ - let handle = ::std::thread::Builder::new() - .name(::std::string::String::from(::std::stringify!(#name))) - .stack_size(#LARGE_STACK_TEST_STACK_SIZE_BYTES) - .spawn(move || #thread_body) - .unwrap_or_else(|error| { - panic!("failed to spawn large-stack test thread: {error}") - }); - - match handle.join() { - Ok(result) => result, - Err(payload) => ::std::panic::resume_unwind(payload), - } - }); - - quote! { #item } -} - -fn filtered_attributes(attrs: &[Attribute]) -> Vec { - let mut filtered = Vec::with_capacity(attrs.len() + 1); - let mut has_test_attr = false; - - for attr in attrs { - if is_tokio_test_attr(attr) { - continue; - } - if is_test_attr(attr) || is_test_case_attr(attr) { - has_test_attr = true; - } - filtered.push(attr.clone()); - } - - if !has_test_attr { - filtered.push(parse_quote!(#[test])); - } - - filtered -} - -fn is_test_attr(attr: &Attribute) -> bool { - attr.path().is_ident("test") -} - -fn is_test_case_attr(attr: &Attribute) -> bool { - attr.path().is_ident("test_case") -} - -fn is_tokio_test_attr(attr: &Attribute) -> bool { - let mut segments = attr.path().segments.iter(); - matches!( - (segments.next(), segments.next(), segments.next()), - (Some(first), Some(second), None) if first.ident == "tokio" && second.ident == "test" - ) -} - -#[cfg(test)] -mod tests { - use super::expand_large_stack_test; - use syn::ItemFn; - use syn::parse_quote; - - fn has_attr(item: &ItemFn, name: &str) -> bool { - item.attrs.iter().any(|attr| attr.path().is_ident(name)) - } - - #[test] - fn adds_test_attribute_when_missing() { - let item: ItemFn = parse_quote! { - fn sample() {} - }; - - let expanded_tokens = expand_large_stack_test(item); - let expanded: ItemFn = match syn::parse2(expanded_tokens) { - Ok(expanded) => expanded, - Err(error) => panic!("failed to parse expanded function: {error}"), - }; - - assert!(has_attr(&expanded, "test")); - let body = quote::quote!(#expanded).to_string(); - assert!(body.contains("stack_size")); - } - - #[test] - fn removes_tokio_test_and_keeps_test_case() { - let item: ItemFn = parse_quote! { - #[test_case(1)] - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn sample(value: usize) -> anyhow::Result<()> { - let _ = value; - Ok(()) - } - }; - - let expanded_tokens = expand_large_stack_test(item); - let expanded: ItemFn = match syn::parse2(expanded_tokens) { - Ok(expanded) => expanded, - Err(error) => panic!("failed to parse expanded function: {error}"), - }; - - assert!(has_attr(&expanded, "test_case")); - assert!(!has_attr(&expanded, "test")); - let body = quote::quote!(#expanded).to_string(); - assert!(body.contains("tokio :: runtime :: Builder")); - assert!(!body.contains("tokio :: test")); - } -}