From 75a4146411d22e4c487ba86f026201594cdbaa85 Mon Sep 17 00:00:00 2001 From: andrewgu-oai Date: Fri, 23 Oct 2026 00:03:40 +0000 Subject: [PATCH] Add support for environment-scoped managed hooks (#56304) ## What changed - Add discovery and listing APIs for environment-owned required hooks, with command and MCP execution routed to the owning environment. - Use each environment's working directory in hook input, withhold controller transcript paths, and prevent environment hooks from granting permission requests. - Resolve `command_windows` against the environment's platform and, when hooks are enabled, reject unloadable required hooks before accepting environment configurations at startup or readiness. ## Testing Add regression coverage for invalid managed hook matchers at startup and readiness, successful readiness after correction, and per-hook working directory and transcript path scoping for `SubagentStop`. GitOrigin-RevId: 1ac0ab3778ba608c72e5917fcbaebcc1d454887f --- codex-rs/core/src/session/environment.rs | 17 ++- codex-rs/core/src/session/session.rs | 10 +- codex-rs/core/src/session/step_activation.rs | 5 +- codex-rs/core/tests/suite/hooks_executor.rs | 69 +++++++++++ codex-rs/hooks/src/engine/command_runner.rs | 54 +++++++-- .../hooks/src/engine/command_runner_tests.rs | 2 + codex-rs/hooks/src/engine/discovery.rs | 107 ++++++++++++++++++ codex-rs/hooks/src/engine/dispatcher.rs | 54 ++++++--- codex-rs/hooks/src/engine/mcp_runner.rs | 9 +- codex-rs/hooks/src/engine/mcp_runner_tests.rs | 2 +- codex-rs/hooks/src/engine/mod.rs | 37 +++++- codex-rs/hooks/src/engine/mod_tests.rs | 72 ++++++++++++ codex-rs/hooks/src/environment.rs | 35 ++++++ codex-rs/hooks/src/events/common.rs | 7 +- codex-rs/hooks/src/events/compact.rs | 33 +++--- codex-rs/hooks/src/events/interrupt.rs | 13 ++- codex-rs/hooks/src/events/model_request.rs | 4 +- .../hooks/src/events/permission_request.rs | 14 ++- codex-rs/hooks/src/events/post_tool_use.rs | 16 ++- codex-rs/hooks/src/events/pre_tool_use.rs | 16 ++- codex-rs/hooks/src/events/session_end.rs | 6 +- codex-rs/hooks/src/events/session_start.rs | 16 +-- codex-rs/hooks/src/events/stop.rs | 21 ++-- .../hooks/src/events/user_prompt_submit.rs | 6 +- codex-rs/hooks/src/lib.rs | 5 + codex-rs/hooks/src/registry.rs | 58 ++++++++-- 26 files changed, 574 insertions(+), 114 deletions(-) create mode 100644 codex-rs/hooks/src/environment.rs diff --git a/codex-rs/core/src/session/environment.rs b/codex-rs/core/src/session/environment.rs index 8c9e75111d..09dd1c68d1 100644 --- a/codex-rs/core/src/session/environment.rs +++ b/codex-rs/core/src/session/environment.rs @@ -5,6 +5,7 @@ use codex_exec_server::LOCAL_ENVIRONMENT_ID; use codex_exec_server::MAX_SELECTED_CAPABILITY_ROOTS; use codex_exec_server::SelectedCapabilityRootsStatus; use codex_execpolicy::Policy; +use codex_features::Feature; use codex_protocol::capabilities::CapabilityRootLocation; use codex_protocol::error::CodexErr; use codex_protocol::error::Result as CodexResult; @@ -16,6 +17,7 @@ use codex_protocol::sandbox::SandboxType; use crate::config::ConstraintError; use crate::config::ConstraintResult; +use crate::config::ManagedFeatures; use crate::config::NetworkProxySpec; use crate::environment_selection::TurnEnvironmentSnapshot; use crate::session::session::Session; @@ -50,6 +52,7 @@ impl ThreadEnvironmentDefaults { pub(super) fn validate_environment_configs( selections: &[TurnEnvironmentSelection], + features: &ManagedFeatures, ) -> ConstraintResult<()> { for selection in selections { match &selection.config { @@ -57,7 +60,7 @@ pub(super) fn validate_environment_configs( | EnvironmentConfigState::Pending | EnvironmentConfigState::Failed(_) => {} EnvironmentConfigState::Ready(config) => { - validate_environment_config(selection, config).map_err(|error| { + validate_environment_config(selection, config, features).map_err(|error| { ConstraintError::InvalidValue { field_name: "environments", candidate: "environment configuration".to_string(), @@ -95,7 +98,16 @@ pub(super) fn ensure_configs_stay_owner_provided( fn validate_environment_config( selection: &TurnEnvironmentSelection, config: &EnvironmentConfig, + features: &ManagedFeatures, ) -> CodexResult<()> { + if features.enabled(Feature::CodexHooks) { + codex_hooks::validate_environment_hooks( + &selection.environment_id, + &selection.cwd, + &config.environment_hooks, + ) + .map_err(|error| CodexErr::InvalidRequest(error.to_string()))?; + } if let Some(policy) = config.network_policy.as_ref() { if selection.environment_id == LOCAL_ENVIRONMENT_ID { return Err(CodexErr::InvalidRequest( @@ -300,7 +312,8 @@ impl Session { return Ok(()); } if let Ok(config) = &result { - validate_environment_config(selection, config)?; + // Return the specific readiness error before applying session-level constraints. + validate_environment_config(selection, config, &self.features)?; } let (current_environment, future_environment) = match environments { (None, None) => { diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index 1477843968..9d213c763d 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -381,7 +381,10 @@ impl SessionConfiguration { ) -> ConstraintResult<()> { self.step_settings .validate(&self.step_settings_constraints(environments))?; - super::environment::validate_environment_configs(environments) + super::environment::validate_environment_configs( + environments, + &self.original_config_do_not_use.features, + ) } pub(super) fn step_settings_constraints( @@ -555,7 +558,10 @@ impl SessionConfiguration { .map_or(current_environments, |environments| { environments.environments.as_slice() }); - super::environment::validate_environment_configs(next_environments)?; + super::environment::validate_environment_configs( + next_environments, + &next_configuration.original_config_do_not_use.features, + )?; // Apply step settings last: the proposed permissions and environment // selections must be complete before deriving their validation constraints. next_configuration.step_settings = Arc::new(self.step_settings.apply( diff --git a/codex-rs/core/src/session/step_activation.rs b/codex-rs/core/src/session/step_activation.rs index c7a5de0272..48fe180dcb 100644 --- a/codex-rs/core/src/session/step_activation.rs +++ b/codex-rs/core/src/session/step_activation.rs @@ -303,8 +303,9 @@ impl Session { }; // Validate the environment configuration supplied in the update. - let environment_config_validation = - environments.as_deref().map(validate_environment_configs); + let environment_config_validation = environments + .as_deref() + .map(|environments| validate_environment_configs(environments, &self.features)); // Confirm the task we originally targeted is still running. let active = self.active_turn.lock().await; diff --git a/codex-rs/core/tests/suite/hooks_executor.rs b/codex-rs/core/tests/suite/hooks_executor.rs index eec51c7399..9d44e567af 100644 --- a/codex-rs/core/tests/suite/hooks_executor.rs +++ b/codex-rs/core/tests/suite/hooks_executor.rs @@ -44,6 +44,7 @@ use core_test_support::skip_if_remote; use core_test_support::submit_thread_settings; use core_test_support::test_codex::TestCodex; use core_test_support::test_codex::TestCodexBuilder; +use core_test_support::test_codex::environment_config_for_selection; use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; use core_test_support::wait_for_event_match; @@ -67,6 +68,74 @@ use wiremock::matchers::path; use super::rmcp_client::remote_aware_environment_id; +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn environment_requires_loadable_managed_hooks_at_startup_and_readiness() -> Result<()> { + let server = start_mock_server().await; + let test = test_codex() + .with_config(|config| { + config + .features + .enable(Feature::CodexHooks) + .expect("enable hooks"); + config + .features + .enable(Feature::DeferredExecutor) + .expect("allow the environment to start with pending configuration"); + }) + .build_with_auto_env(&server) + .await?; + let mut selection = test.executor_environment().selection().clone(); + let mut config = environment_config_for_selection(&test.config, &selection); + config.environment_hooks = toml::from_str( + r#" + [[PreToolUse]] + matcher = "[" + [[PreToolUse.hooks]] + type = "command" + command = "echo managed-hook" + "#, + )?; + selection.config = EnvironmentConfigState::Ready(config.clone()); + let start = |selection: TurnEnvironmentSelection| { + test.thread_manager.start_thread(StartThreadOptions { + environments: Some(vec![selection.into_request()]), + ..StartThreadOptions::new(test.config.clone()) + }) + }; + let assert_invalid_matcher = |error: String| { + assert!(error.contains("invalid matcher"), "{error}"); + assert!(error.contains(&selection.environment_id), "{error}"); + }; + let error = start(selection.clone()) + .await + .err() + .context("startup accepted an invalid managed hook")?; + assert_invalid_matcher(error.to_string()); + + selection.config = EnvironmentConfigState::Pending; + let thread = start(selection.clone()).await?.thread; + let error = thread + .environment_ready(&selection, config.clone()) + .await + .expect_err("an invalid managed hook must prevent readiness"); + assert_invalid_matcher(error.to_string()); + assert_eq!( + thread.environment_selections().await, + vec![selection.clone()] + ); + + config.environment_hooks.pre_tool_use[0].matcher = Some("^Bash$".to_string()); + thread.environment_ready(&selection, config).await?; + assert!( + thread + .config_snapshot() + .await + .is_primary_environment_configured() + ); + thread.shutdown_and_wait().await?; + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn thread_plugin_selection_disables_executor_hooks_without_disabling_their_server() -> Result<()> { diff --git a/codex-rs/hooks/src/engine/command_runner.rs b/codex-rs/hooks/src/engine/command_runner.rs index cd43860ad9..00cd404713 100644 --- a/codex-rs/hooks/src/engine/command_runner.rs +++ b/codex-rs/hooks/src/engine/command_runner.rs @@ -21,6 +21,7 @@ use codex_utils_pty::Command; #[cfg(windows)] use codex_utils_pty::JobObject; use futures::future::try_join; +use serde_json::Value; use tokio::io::AsyncWriteExt; #[cfg(not(unix))] use tokio::process::Command; @@ -32,9 +33,9 @@ use tracing::Span; #[cfg(windows)] const CREATE_NO_WINDOW: u32 = 0x08000000; +use super::ClaudeHooksEngine; use super::CommandShell; use super::ConfiguredHandler; -use super::ConfiguredHandlerKind; use super::HandlerRunResult; use super::dispatcher::ParsedHandler; use super::dispatcher::hook_event_name_label; @@ -55,6 +56,7 @@ const MAX_CONCURRENT_ASYNC_HOOKS: usize = 8; /// Owns command execution and bounded asynchronous work for one session. #[derive(Clone)] pub(crate) struct CommandHookRuntime { + pub(crate) environment_executor: Option>, shell: CommandShell, environment: Arc>, result_sender: Sender, @@ -84,6 +86,7 @@ impl CommandHookRuntime { result_sender: Sender, ) -> Self { Self { + environment_executor: None, shell, environment, result_sender, @@ -100,6 +103,7 @@ impl CommandHookRuntime { pub(crate) fn reconfigured(&self, shell: CommandShell) -> Self { Self { + environment_executor: self.environment_executor.clone(), shell, environment: Arc::clone(&self.environment), result_sender: self.result_sender.clone(), @@ -114,8 +118,9 @@ impl CommandHookRuntime { pub(crate) fn schedule_async_hook( &self, + engine: ClaudeHooksEngine, handler: ConfiguredHandler, - input_json: String, + event_input: Value, cwd: std::path::PathBuf, turn_id: Option, parse: fn(&ConfiguredHandler, HandlerRunResult, Option) -> ParsedHandler, @@ -127,12 +132,14 @@ impl CommandHookRuntime { let result_sender = self.result_sender.clone(); let runtime = self.clone(); self.schedule_async_task(async move { - let result = match &handler.kind { - ConfiguredHandlerKind::Command { command, env, .. } => { - run_command(&runtime, &handler, command, env, &input_json, &cwd).await - } - ConfiguredHandlerKind::McpTool { .. } => return, - }; + let result = super::dispatcher::execute_handler( + &engine, + &handler, + &event_input, + &cwd, + /*metadata*/ None, + ) + .await; let mut hook_result = parse(&handler, result, turn_id).completed; let mut entries = Vec::new(); let mut warnings = Vec::new(); @@ -239,6 +246,37 @@ pub(crate) async fn run_command( } } + if let super::HandlerSourcePath::Environment { environment_id, .. } = &handler.source_path { + let result = match &runtime.environment_executor { + Some(executor) => { + executor + .execute( + environment_id, + command_line, + env, + input_json, + Duration::from_secs(handler.timeout_sec), + ) + .await + } + None => Err(anyhow::anyhow!("environment hook executor is unavailable")), + }; + let (exit_code, stdout, stderr, error) = match result { + Ok(output) => (Some(output.exit_code), output.stdout, output.stderr, None), + Err(error) => (None, String::new(), String::new(), Some(error.to_string())), + }; + return HandlerRunResult { + context_metadata: codex_protocol::models::ContentItemMetadata::command_hook(), + started_at, + completed_at: chrono::Utc::now().timestamp(), + duration_ms: started.elapsed().as_millis().try_into().unwrap_or(i64::MAX), + exit_code, + stdout, + stderr, + error, + }; + } + let mut command = build_command(&runtime.shell, command_line, &runtime.environment, env); command.current_dir(cwd); diff --git a/codex-rs/hooks/src/engine/command_runner_tests.rs b/codex-rs/hooks/src/engine/command_runner_tests.rs index ac5a3fa5b2..5f67b64db5 100644 --- a/codex-rs/hooks/src/engine/command_runner_tests.rs +++ b/codex-rs/hooks/src/engine/command_runner_tests.rs @@ -517,7 +517,9 @@ fn write_handler(temp: &TempDir, source: &str) -> ConfiguredHandler { async fn schedule(runtime: &CommandHookRuntime, handler: ConfiguredHandler, cwd: &Path) { let engine = ClaudeHooksEngine { + enabled: true, handlers: Arc::new(vec![handler]), + hook_entries: Default::default(), warnings: Arc::default(), required_load_errors: Arc::default(), command_runtime: runtime.clone(), diff --git a/codex-rs/hooks/src/engine/discovery.rs b/codex-rs/hooks/src/engine/discovery.rs index b5b07e658d..0fbe32fc7b 100644 --- a/codex-rs/hooks/src/engine/discovery.rs +++ b/codex-rs/hooks/src/engine/discovery.rs @@ -20,6 +20,8 @@ use codex_plugin::PluginHookSource; use codex_plugin::is_allowlisted_bundled_cleanup_hook; use codex_protocol::protocol::HookEventName; use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_path_uri::PathConvention; +use codex_utils_path_uri::PathUri; use serde::Deserialize; use serde::Serialize; @@ -39,6 +41,7 @@ use crate::output_spill::DEFAULT_HOOK_OUTPUT_TOKEN_LIMIT; use codex_protocol::protocol::HookSource; use codex_protocol::protocol::HookTrustStatus; +#[derive(Default)] pub(crate) struct DiscoveryResult { pub handlers: Vec, pub hook_entries: Vec, @@ -46,6 +49,15 @@ pub(crate) struct DiscoveryResult { pub required_load_errors: Vec, } +pub(crate) fn ensure_required_hooks_loaded(errors: &[String]) -> anyhow::Result<()> { + anyhow::ensure!( + errors.is_empty(), + "failed to load required managed hooks: {}", + errors.join("; ") + ); + Ok(()) +} + struct HookHandlerSource<'a> { path: &'a AbsolutePathBuf, key_source: String, @@ -488,6 +500,100 @@ fn escape_xml_text(value: &str) -> String { escaped } +pub(crate) fn discover_environment_hooks( + sources: Vec, + mut display_order: i64, +) -> DiscoveryResult { + let mut discovered = DiscoveryResult::default(); + for source in sources { + append_environment_hooks(&mut discovered, source, &mut display_order); + } + discovered +} + +/// Reject unloadable requirements before accepting an environment's configuration. +pub fn validate_environment_hooks( + environment_id: &str, + cwd: &PathUri, + hooks: &HookEventsToml, +) -> anyhow::Result<()> { + if hooks.is_empty() { + return Ok(()); + } + let source = crate::EnvironmentHookSource { + environment_id: environment_id.to_owned(), + cwd: cwd.clone(), + hooks: hooks.clone(), + }; + let discovered = discover_environment_hooks(vec![source], /*display_order*/ 0); + ensure_required_hooks_loaded(&discovered.required_load_errors) +} + +fn append_environment_hooks( + discovered: &mut DiscoveryResult, + mut source: crate::EnvironmentHookSource, + display_order: &mut i64, +) { + let path = synthetic_layer_path(&format!( + "/requirements.toml", + source.environment_id + )); + // Resolve overrides against the executor platform before normal local discovery. + for (_, groups) in source.hooks.matcher_groups_mut() { + for handler in groups.iter_mut().flat_map(|group| &mut group.hooks) { + if let HookHandlerConfig::Command { + command, + command_windows, + .. + } = handler + && let Some(windows) = command_windows.take() + && source.cwd.infer_path_convention() == Some(PathConvention::Windows) + { + *command = windows; + } + } + } + let handler_start = discovered.handlers.len(); + let entry_start = discovered.hook_entries.len(); + append_hook_events( + &mut discovered.handlers, + &mut discovered.hook_entries, + &mut discovered.warnings, + display_order, + HookHandlerSource { + path: &path, + key_source: path.display().to_string(), + source: HookSource::System, + is_managed: true, + requirement: HookRequirement::Required(&mut discovered.required_load_errors), + bypass_hook_trust: false, + hook_states: &HashMap::new(), + env: HashMap::new(), + plugin_id: None, + plugin_content_hash: None, + config_layer_stack: None, + plugin_root: None, + }, + source.hooks, + HookDiscoveryPolicy { + config_layer_stack: None, + mode: DiscoveryMode::Runtime, + allow_managed_hooks_only: true, + bypass_hook_trust: false, + }, + ); + for entry in &mut discovered.hook_entries[entry_start..] { + entry.environment_id = Some(source.environment_id.clone()); + } + for handler in &mut discovered.handlers[handler_start..] { + handler.source_path = super::HandlerSourcePath::Environment { + environment_id: source.environment_id.clone(), + cwd: source.cwd.clone(), + source_path: path.clone(), + }; + } +} + fn append_hook_events( handlers: &mut Vec, hook_entries: &mut Vec, @@ -801,6 +907,7 @@ fn append_matcher_groups( source_path: source.path.clone(), source: source.source, plugin_id: source.plugin_id.clone(), + environment_id: None, display_order: *display_order, enabled, is_managed: source.is_managed, diff --git a/codex-rs/hooks/src/engine/dispatcher.rs b/codex-rs/hooks/src/engine/dispatcher.rs index e84d998093..85c110ab70 100644 --- a/codex-rs/hooks/src/engine/dispatcher.rs +++ b/codex-rs/hooks/src/engine/dispatcher.rs @@ -78,8 +78,14 @@ pub(crate) fn select_handlers_for_matcher_inputs( } pub(crate) fn running_summary(handler: &ConfiguredHandler) -> HookRunSummary { - let HandlerSourcePath::Local(source_path) = &handler.source_path else { - unreachable!("executor-scoped hooks do not produce public hook summaries"); + let source_path = match &handler.source_path { + HandlerSourcePath::Local(path) + | HandlerSourcePath::Environment { + source_path: path, .. + } => path, + HandlerSourcePath::ExecutorScoped { .. } => { + unreachable!("executor-scoped hooks do not produce public hook summaries") + } }; HookRunSummary { builtin: handler.builtin, @@ -103,13 +109,13 @@ pub(crate) fn running_summary(handler: &ConfiguredHandler) -> HookRunSummary { pub(crate) async fn execute_handlers( engine: &ClaudeHooksEngine, handlers: Vec, - input_json: String, + input: &Value, cwd: &Path, turn_id: Option, parse: fn(&ConfiguredHandler, HandlerRunResult, Option) -> ParsedHandler, ) -> Vec> { execute_handlers_with_metadata( - engine, handlers, input_json, cwd, turn_id, /*metadata*/ None, parse, + engine, handlers, input, cwd, turn_id, /*metadata*/ None, parse, ) .await } @@ -117,7 +123,7 @@ pub(crate) async fn execute_handlers( pub(crate) async fn execute_handlers_with_metadata( engine: &ClaudeHooksEngine, handlers: Vec, - input_json: String, + input: &Value, cwd: &Path, turn_id: Option, metadata: Option<&Map>, @@ -133,21 +139,22 @@ pub(crate) async fn execute_handlers_with_metadata( executor_handlers.push(handler); continue; } + let event_input = handler.source_path.event_input(input); if handler.execution_mode() == HookExecutionMode::Async { engine.command_runtime.schedule_async_hook( + engine.clone(), handler, - input_json.clone(), + event_input.into_owned(), cwd.to_path_buf(), turn_id.clone(), parse, ); continue; } - let input_json = input_json.clone(); let turn_id = turn_id.clone(); pending.push(async move { let result = - execute_handler(engine, &handler, &input_json, cwd, /*metadata*/ None).await; + execute_handler(engine, &handler, &event_input, cwd, /*metadata*/ None).await; let parsed = parse(&handler, result, turn_id); (configured_order, parsed) }); @@ -169,13 +176,18 @@ pub(crate) async fn execute_handlers_with_metadata( if should_stop || !should_block { for handler in executor_handlers { let task_engine = engine.clone(); - let input_json = input_json.clone(); + let event_input = input.clone(); let cwd = cwd.to_path_buf(); let metadata = metadata.cloned(); engine.command_runtime.schedule_async_task(async move { - let result = - execute_handler(&task_engine, &handler, &input_json, &cwd, metadata.as_ref()) - .await; + let result = execute_handler( + &task_engine, + &handler, + &event_input, + &cwd, + metadata.as_ref(), + ) + .await; if let Some(error) = result.error { tracing::warn!( source_path = %handler.source_path, @@ -190,10 +202,10 @@ pub(crate) async fn execute_handlers_with_metadata( completed.into_iter().map(|(_, parsed)| parsed).collect() } -async fn execute_handler( +pub(super) async fn execute_handler( engine: &ClaudeHooksEngine, handler: &ConfiguredHandler, - input_json: &str, + event_input: &Value, cwd: &Path, metadata: Option<&Map>, ) -> HandlerRunResult { @@ -204,7 +216,7 @@ async fn execute_handler( handler, command, env, - input_json, + &event_input.to_string(), cwd, ) .await @@ -220,7 +232,7 @@ async fn execute_handler( server, tool, input, - input_json, + event_input, metadata, ) .await @@ -234,8 +246,14 @@ pub(crate) fn completed_summary( status: HookRunStatus, entries: Vec, ) -> HookRunSummary { - let HandlerSourcePath::Local(source_path) = &handler.source_path else { - unreachable!("executor-scoped hooks do not produce public hook summaries"); + let source_path = match &handler.source_path { + HandlerSourcePath::Local(path) + | HandlerSourcePath::Environment { + source_path: path, .. + } => path, + HandlerSourcePath::ExecutorScoped { .. } => { + unreachable!("executor-scoped hooks do not produce public hook summaries") + } }; HookRunSummary { builtin: handler.builtin, diff --git a/codex-rs/hooks/src/engine/mcp_runner.rs b/codex-rs/hooks/src/engine/mcp_runner.rs index 2c3f26f854..2d3cdc6d92 100644 --- a/codex-rs/hooks/src/engine/mcp_runner.rs +++ b/codex-rs/hooks/src/engine/mcp_runner.rs @@ -32,7 +32,7 @@ pub(crate) async fn run_mcp_tool( server: &str, tool: &str, argument_template: &Map, - hook_event_json: &str, + hook_event: &Value, metadata: Option<&Map>, ) -> HandlerRunResult { let started_at = chrono::Utc::now().timestamp(); @@ -45,11 +45,12 @@ pub(crate) async fn run_mcp_tool( .await .context("hook trust verification timed out")??; } - let hook_event: Value = - serde_json::from_str(hook_event_json).context("failed to parse hook event input")?; - let input = expand_mcp_argument_template(argument_template, &hook_event)?; + let input = expand_mcp_argument_template(argument_template, hook_event)?; let (environment_id, mut call_metadata) = match &handler.source_path { HandlerSourcePath::Local(_) => (None, None), + HandlerSourcePath::Environment { environment_id, .. } => { + (Some(environment_id.clone()), None) + } HandlerSourcePath::ExecutorScoped { environment_id, mcp_environment_id, diff --git a/codex-rs/hooks/src/engine/mcp_runner_tests.rs b/codex-rs/hooks/src/engine/mcp_runner_tests.rs index 8a37d8d238..ea3fdb7359 100644 --- a/codex-rs/hooks/src/engine/mcp_runner_tests.rs +++ b/codex-rs/hooks/src/engine/mcp_runner_tests.rs @@ -123,7 +123,7 @@ async fn mcp_tool_results_use_command_hook_output_contract() { "security", "scan", &configured_input, - r#"{"tool_input":{"file_path":"/tmp/example.rs"}}"#, + &json!({ "tool_input": { "file_path": "/tmp/example.rs" } }), /*metadata*/ None, ) .await; diff --git a/codex-rs/hooks/src/engine/mod.rs b/codex-rs/hooks/src/engine/mod.rs index f7bdc97d0d..9063559e2f 100644 --- a/codex-rs/hooks/src/engine/mod.rs +++ b/codex-rs/hooks/src/engine/mod.rs @@ -47,6 +47,7 @@ use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_path_uri::PathUri; use serde_json::Map; use serde_json::Value; +use std::borrow::Cow; use std::collections::HashMap; use std::collections::HashSet; use std::sync::Arc; @@ -79,6 +80,11 @@ pub(crate) struct ConfiguredHandler { #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum HandlerSourcePath { Local(AbsolutePathBuf), + Environment { + environment_id: String, + cwd: PathUri, + source_path: AbsolutePathBuf, + }, /// Executor-scoped handlers are currently excluded from user-visible hook reporting /// (events, summary, telemetry). Their handlers are always executed async. /// @@ -95,6 +101,24 @@ pub(crate) enum HandlerSourcePath { }, } +impl HandlerSourcePath { + /// Use the environment's working directory and withhold controller-owned transcript paths. + fn event_input<'a>(&self, input: &'a Value) -> Cow<'a, Value> { + match self { + Self::Environment { cwd, .. } => { + let mut input = input.clone(); + input["cwd"] = Value::String(cwd.inferred_native_path_string()); + input["transcript_path"] = Value::Null; + if let Some(path) = input.get_mut("agent_transcript_path") { + *path = Value::Null; + } + Cow::Owned(input) + } + Self::Local(_) | Self::ExecutorScoped { .. } => Cow::Borrowed(input), + } + } +} + impl From for HandlerSourcePath { fn from(path: AbsolutePathBuf) -> Self { Self::Local(path) @@ -105,6 +129,7 @@ impl std::fmt::Display for HandlerSourcePath { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Local(path) => write!(formatter, "{}", path.display()), + Self::Environment { source_path, .. } => write!(formatter, "{}", source_path.display()), Self::ExecutorScoped { environment_id, manifest_path, @@ -237,6 +262,8 @@ pub struct HookListEntry { pub source_path: AbsolutePathBuf, pub source: HookSource, pub plugin_id: Option, + /// The owning execution environment, if this hook came from its requirements. + pub environment_id: Option, pub display_order: i64, pub enabled: bool, pub is_managed: bool, @@ -246,9 +273,12 @@ pub struct HookListEntry { #[derive(Clone)] pub(crate) struct ClaudeHooksEngine { + pub(crate) enabled: bool, // Per-turn views share configuration; executor overlays copy handlers on mutation. pub(crate) handlers: Arc>, - warnings: Arc<[String]>, + /// Retain the session inventory without copying it for every hook dispatch. + pub(crate) hook_entries: Arc>, + pub(crate) warnings: Arc<[String]>, required_load_errors: Arc<[String]>, pub(crate) command_runtime: CommandHookRuntime, pub(crate) mcp_executor: Arc, @@ -266,7 +296,9 @@ impl ClaudeHooksEngine { ) -> Self { if !enabled && plugin_hook_sources.is_empty() { return Self { + enabled, handlers: Arc::default(), + hook_entries: Arc::default(), warnings: Arc::default(), required_load_errors: Arc::default(), command_runtime, @@ -284,12 +316,15 @@ impl ClaudeHooksEngine { ); if !enabled { discovered.handlers.retain(|handler| handler.builtin); + discovered.hook_entries.clear(); // Disabled ordinary hooks must not emit warnings or reject session startup. discovered.warnings.clear(); discovered.required_load_errors.clear(); } Self { + enabled, handlers: Arc::new(discovered.handlers), + hook_entries: Arc::new(discovered.hook_entries), warnings: discovered.warnings.into(), required_load_errors: discovered.required_load_errors.into(), command_runtime, diff --git a/codex-rs/hooks/src/engine/mod_tests.rs b/codex-rs/hooks/src/engine/mod_tests.rs index e5eadbe31a..7108cad545 100644 --- a/codex-rs/hooks/src/engine/mod_tests.rs +++ b/codex-rs/hooks/src/engine/mod_tests.rs @@ -32,6 +32,7 @@ use codex_protocol::protocol::HookOutputEntryKind; use codex_protocol::protocol::HookRunStatus; use codex_protocol::protocol::HookSource; use codex_protocol::protocol::HookTrustStatus; +use codex_utils_path_uri::PathUri; use futures::FutureExt; use futures::future::BoxFuture; use pretty_assertions::assert_eq; @@ -2422,6 +2423,77 @@ async fn wait_for_mcp_calls(calls: &Arc>>, count: usize) .expect("executor hook should complete in the background"); } +#[tokio::test] +async fn subagent_stop_paths_are_scoped_to_each_hook() { + let (mut engine, calls, mut request, _, _) = executor_stop_hook_fixture(); + let local_cwd = request.cwd.clone(); + let transcript = local_cwd.join("parent.jsonl"); + let agent_transcript = local_cwd.join("child.jsonl"); + request.transcript_path = Some(transcript.to_path_buf()); + request.target = StopHookTarget::SubagentStop { + agent_id: "child".to_string(), + agent_type: "explorer".to_string(), + agent_transcript_path: Some(agent_transcript.to_path_buf()), + }; + + let source_path = local_cwd.join("hooks.json"); + let local = ConfiguredHandler { + event_name: HookEventName::SubagentStop, + source_path: source_path.clone().into(), + source: HookSource::User, + kind: ConfiguredHandlerKind::McpTool { + server: "recorder".to_string(), + tool: "capture".to_string(), + input: serde_json::from_value(serde_json::json!({ + "cwd": "${cwd}", + "transcript_path": "${transcript_path}", + "agent_transcript_path": "${agent_transcript_path}", + })) + .expect("object input"), + }, + ..engine.handlers[0].clone() + }; + let remote = ConfiguredHandler { + source_path: HandlerSourcePath::Environment { + environment_id: "remote".to_string(), + cwd: PathUri::parse("file:///C:/team%20workspace").expect("Windows working directory"), + source_path, + }, + source: HookSource::System, + ..local.clone() + }; + engine.handlers = Arc::new(vec![remote, local]); + engine.run_stop(request).await; + + let inputs: HashMap<_, _> = calls + .lock() + .expect("lock MCP calls") + .drain(..) + .map(|call| (call.environment_id, serde_json::Value::Object(call.input))) + .collect(); + assert_eq!( + inputs, + HashMap::from([ + ( + Some("remote".to_string()), + serde_json::json!({ + "cwd": r"C:\team workspace", + "transcript_path": null, + "agent_transcript_path": null, + }) + ), + ( + None, + serde_json::json!({ + "cwd": local_cwd, + "transcript_path": transcript, + "agent_transcript_path": agent_transcript, + }) + ), + ]) + ); +} + #[tokio::test] async fn executor_stop_hooks_run_unless_regular_hooks_block_without_stopping() { let (mut engine, calls, request, expected_executor_call, _source) = diff --git a/codex-rs/hooks/src/environment.rs b/codex-rs/hooks/src/environment.rs new file mode 100644 index 0000000000..61968db51c --- /dev/null +++ b/codex-rs/hooks/src/environment.rs @@ -0,0 +1,35 @@ +//! Owner-admitted hooks bound to the exact environment that supplied them. + +use std::collections::HashMap; +use std::time::Duration; + +use codex_protocol::hooks::HookEventsToml; +use codex_utils_path_uri::PathUri; +use futures::future::BoxFuture; + +/// An admitted requirements source. The owner must not populate this from user configuration. +pub struct EnvironmentHookSource { + pub environment_id: String, + /// Working directory from the same captured environment used for execution. + pub cwd: PathUri, + pub hooks: HookEventsToml, +} + +/// Executes commands in ready environments without coupling the hooks engine to core or transports. +/// Implementations must honor the timeout, terminate timed-out processes, and bound captured output. +pub trait HookEnvironmentExecutor: Send + Sync { + fn execute( + &self, + environment_id: &str, + command: &str, + env: &HashMap, + input_json: &str, + timeout: Duration, + ) -> BoxFuture<'_, anyhow::Result>; +} + +pub struct EnvironmentHookOutput { + pub exit_code: i32, + pub stdout: String, + pub stderr: String, +} diff --git a/codex-rs/hooks/src/events/common.rs b/codex-rs/hooks/src/events/common.rs index d1f0f59ba5..735e0b4be9 100644 --- a/codex-rs/hooks/src/events/common.rs +++ b/codex-rs/hooks/src/events/common.rs @@ -68,7 +68,12 @@ pub(crate) fn serialization_failure_hook_events( ) -> Vec { handlers .into_iter() - .filter(|handler| matches!(handler.source_path, HandlerSourcePath::Local(_))) + .filter(|handler| { + !matches!( + handler.source_path, + HandlerSourcePath::ExecutorScoped { .. } + ) + }) .map(|handler| { let mut run = dispatcher::running_summary(&handler); run.status = HookRunStatus::Failed; diff --git a/codex-rs/hooks/src/events/compact.rs b/codex-rs/hooks/src/events/compact.rs index cdc9846e7d..720e097cd6 100644 --- a/codex-rs/hooks/src/events/compact.rs +++ b/codex-rs/hooks/src/events/compact.rs @@ -8,6 +8,7 @@ use codex_protocol::protocol::HookOutputEntryKind; use codex_protocol::protocol::HookRunStatus; use codex_protocol::protocol::HookRunSummary; use codex_utils_absolute_path::AbsolutePathBuf; +use serde_json::Value; use super::common; use crate::engine::ClaudeHooksEngine; @@ -86,8 +87,8 @@ pub(crate) async fn run_pre( }; } - let input_json = match pre_command_input_json(&request) { - Ok(input_json) => input_json, + let input = match pre_command_input(&request) { + Ok(input) => input, Err(error) => { return PreCompactOutcome { hook_events: common::serialization_failure_hook_events( @@ -104,7 +105,7 @@ pub(crate) async fn run_pre( let results = dispatcher::execute_handlers( engine, matched, - input_json, + &input, request.cwd.as_path(), Some(request.turn_id), parse_pre_completed, @@ -121,9 +122,9 @@ pub(crate) async fn run_pre( } } -fn pre_command_input_json(request: &PreCompactRequest) -> Result { +fn pre_command_input(request: &PreCompactRequest) -> Result { let subagent = SubagentCommandInputFields::from(request.subagent.as_ref()); - serde_json::to_string(&PreCompactCommandInput { + serde_json::to_value(PreCompactCommandInput { session_id: request.session_id.to_string(), turn_id: request.turn_id.clone(), agent_id: subagent.agent_id, @@ -167,8 +168,8 @@ pub(crate) async fn run_post( }; } - let input_json = match post_command_input_json(&request) { - Ok(input_json) => input_json, + let input = match post_command_input(&request) { + Ok(input) => input, Err(error) => { return StatelessHookOutcome { hook_events: common::serialization_failure_hook_events( @@ -185,7 +186,7 @@ pub(crate) async fn run_post( let results = dispatcher::execute_handlers( engine, matched, - input_json, + &input, request.cwd.as_path(), Some(request.turn_id), parse_post_completed, @@ -202,9 +203,9 @@ pub(crate) async fn run_post( } } -fn post_command_input_json(request: &PostCompactRequest) -> Result { +fn post_command_input(request: &PostCompactRequest) -> Result { let subagent = SubagentCommandInputFields::from(request.subagent.as_ref()); - serde_json::to_string(&PostCompactCommandInput { + serde_json::to_value(PostCompactCommandInput { session_id: request.session_id.to_string(), turn_id: request.turn_id.clone(), agent_id: subagent.agent_id, @@ -355,17 +356,15 @@ mod tests { use super::parse_post_completed; use super::parse_pre_completed; - use super::post_command_input_json; - use super::pre_command_input_json; + use super::post_command_input; + use super::pre_command_input; use crate::engine::ConfiguredHandler; use crate::engine::HandlerRunResult; #[test] fn pre_compact_input_includes_lifecycle_metadata() { let request = pre_request(); - let input_json = pre_command_input_json(&request).expect("serialize command input"); - let input: serde_json::Value = - serde_json::from_str(&input_json).expect("parse command input"); + let input = pre_command_input(&request).expect("serialize command input"); assert_eq!( input, @@ -384,9 +383,7 @@ mod tests { #[test] fn post_compact_input_includes_lifecycle_metadata() { let request = post_request(); - let input_json = post_command_input_json(&request).expect("serialize command input"); - let input: serde_json::Value = - serde_json::from_str(&input_json).expect("parse command input"); + let input = post_command_input(&request).expect("serialize command input"); assert_eq!( input, diff --git a/codex-rs/hooks/src/events/interrupt.rs b/codex-rs/hooks/src/events/interrupt.rs index 743002eb9c..9d5817884d 100644 --- a/codex-rs/hooks/src/events/interrupt.rs +++ b/codex-rs/hooks/src/events/interrupt.rs @@ -48,7 +48,12 @@ pub(crate) fn preview(handlers: &[ConfiguredHandler]) -> Vec { ) .into_iter() // Executor-scoped hooks run asynchronously and do not emit public hook lifecycle events. - .filter(|handler| matches!(handler.source_path, HandlerSourcePath::Local(_))) + .filter(|handler| { + !matches!( + handler.source_path, + HandlerSourcePath::ExecutorScoped { .. } + ) + }) .map(|handler| dispatcher::running_summary(&handler)) .collect() } @@ -72,7 +77,7 @@ pub(crate) async fn run(engine: &ClaudeHooksEngine, request: InterruptRequest) - permission_mode, request_metadata, } = request; - let input_json = match serde_json::to_string(&InterruptCommandInput { + let input = match serde_json::to_value(InterruptCommandInput { session_id: session_id.to_string(), turn_id: turn_id.clone(), transcript_path: NullableString::from_path(transcript_path), @@ -81,7 +86,7 @@ pub(crate) async fn run(engine: &ClaudeHooksEngine, request: InterruptRequest) - model, permission_mode, }) { - Ok(input_json) => input_json, + Ok(input) => input, Err(error) => { return InterruptOutcome { hook_events: common::serialization_failure_hook_events( @@ -96,7 +101,7 @@ pub(crate) async fn run(engine: &ClaudeHooksEngine, request: InterruptRequest) - let results = dispatcher::execute_handlers_with_metadata( engine, matched, - input_json, + &input, cwd.as_path(), Some(turn_id), request_metadata.as_ref(), diff --git a/codex-rs/hooks/src/events/model_request.rs b/codex-rs/hooks/src/events/model_request.rs index 221f2b70cf..058d0b7016 100644 --- a/codex-rs/hooks/src/events/model_request.rs +++ b/codex-rs/hooks/src/events/model_request.rs @@ -106,7 +106,7 @@ pub(crate) async fn run( if matched.is_empty() { return Vec::new(); } - let input = match serde_json::to_string(&request) { + let input = match serde_json::to_value(&request) { Ok(input) => input, Err(error) => { return common::serialization_failure_hook_events( @@ -119,7 +119,7 @@ pub(crate) async fn run( dispatcher::execute_handlers( engine, matched, - input, + &input, request.cwd.as_path(), Some(request.turn_id), parse_completed, diff --git a/codex-rs/hooks/src/events/permission_request.rs b/codex-rs/hooks/src/events/permission_request.rs index 58da6c8e4d..cc00e31f49 100644 --- a/codex-rs/hooks/src/events/permission_request.rs +++ b/codex-rs/hooks/src/events/permission_request.rs @@ -101,8 +101,8 @@ pub(crate) async fn run( }; } - let input_json = match serde_json::to_string(&build_command_input(&request)) { - Ok(input_json) => input_json, + let input = match serde_json::to_value(build_command_input(&request)) { + Ok(input) => input, Err(error) => { let hook_events = common::serialization_failure_hook_events_for_tool_use( matched, @@ -120,7 +120,7 @@ pub(crate) async fn run( let results = dispatcher::execute_handlers( engine, matched, - input_json, + &input, request.cwd.as_path(), Some(request.turn_id.clone()), parse_completed, @@ -225,7 +225,13 @@ fn parse_completed( } else if let Some(parsed_decision) = parsed.decision { match parsed_decision { output_parser::PermissionRequestDecision::Allow => { - decision = Some(PermissionRequestDecision::Allow); + // Environment authority may restrict the controller's policy, never grant it. + if !matches!( + handler.source_path, + crate::engine::HandlerSourcePath::Environment { .. } + ) { + decision = Some(PermissionRequestDecision::Allow); + } } output_parser::PermissionRequestDecision::Deny { message } => { status = HookRunStatus::Blocked; diff --git a/codex-rs/hooks/src/events/post_tool_use.rs b/codex-rs/hooks/src/events/post_tool_use.rs index 820659211c..8af7ba5a2b 100644 --- a/codex-rs/hooks/src/events/post_tool_use.rs +++ b/codex-rs/hooks/src/events/post_tool_use.rs @@ -87,8 +87,8 @@ pub(crate) async fn run( }; } - let input_json = match command_input_json(&request) { - Ok(input_json) => input_json, + let input = match command_input(&request) { + Ok(input) => input, Err(error) => { let hook_events = common::serialization_failure_hook_events_for_tool_use( matched, @@ -103,7 +103,7 @@ pub(crate) async fn run( let results = dispatcher::execute_handlers( engine, matched, - input_json, + &input, request.cwd.as_path(), Some(request.turn_id.clone()), parse_completed, @@ -147,9 +147,9 @@ pub(crate) async fn run( /// the canonical `tool_name` for logs and for consumers that pair pre/post /// events across processes. Shell-like tools pass `{ "command": ... }` as /// `tool_input`; MCP tools pass their resolved JSON arguments. -fn command_input_json(request: &PostToolUseRequest) -> Result { +fn command_input(request: &PostToolUseRequest) -> Result { let subagent = SubagentCommandInputFields::from(request.subagent.as_ref()); - serde_json::to_string(&PostToolUseCommandInput { + serde_json::to_value(PostToolUseCommandInput { session_id: request.session_id.to_string(), turn_id: request.turn_id.clone(), agent_id: subagent.agent_id, @@ -329,7 +329,7 @@ mod tests { use serde_json::json; use super::PostToolUseHandlerData; - use super::command_input_json; + use super::command_input; use super::parse_completed; use super::preview; use crate::engine::ConfiguredHandler; @@ -343,9 +343,7 @@ mod tests { let mut request = request_for_tool_use("call-apply-patch"); request.tool_name = "apply_patch".to_string(); - let input_json = command_input_json(&request).expect("serialize command input"); - let input: serde_json::Value = - serde_json::from_str(&input_json).expect("parse command input"); + let input = command_input(&request).expect("serialize command input"); assert_eq!(input["tool_name"], "apply_patch"); } diff --git a/codex-rs/hooks/src/events/pre_tool_use.rs b/codex-rs/hooks/src/events/pre_tool_use.rs index 7613c15b87..505eeae1da 100644 --- a/codex-rs/hooks/src/events/pre_tool_use.rs +++ b/codex-rs/hooks/src/events/pre_tool_use.rs @@ -89,8 +89,8 @@ pub(crate) async fn run( }; } - let input_json = match command_input_json(&request) { - Ok(input_json) => input_json, + let input = match command_input(&request) { + Ok(input) => input, Err(error) => { let hook_events = common::serialization_failure_hook_events_for_tool_use( matched, @@ -105,7 +105,7 @@ pub(crate) async fn run( let results = dispatcher::execute_handlers( engine, matched, - input_json, + &input, request.cwd.as_path(), Some(request.turn_id.clone()), parse_completed, @@ -172,9 +172,9 @@ fn latest_updated_input( /// the canonical `tool_name` so audit logs and downstream policy decisions stay /// stable. Shell-like tools pass `{ "command": ... }` as `tool_input`; MCP /// tools pass their resolved JSON arguments. -fn command_input_json(request: &PreToolUseRequest) -> Result { +fn command_input(request: &PreToolUseRequest) -> Result { let subagent = SubagentCommandInputFields::from(request.subagent.as_ref()); - serde_json::to_string(&PreToolUseCommandInput { + serde_json::to_value(PreToolUseCommandInput { session_id: request.session_id.to_string(), turn_id: request.turn_id.clone(), agent_id: subagent.agent_id, @@ -332,7 +332,7 @@ mod tests { use pretty_assertions::assert_eq; use super::PreToolUseHandlerData; - use super::command_input_json; + use super::command_input; use super::latest_updated_input; use super::parse_completed; use super::preview; @@ -347,9 +347,7 @@ mod tests { let mut request = request_for_tool_use("call-apply-patch"); request.tool_name = "apply_patch".to_string(); - let input_json = command_input_json(&request).expect("serialize command input"); - let input: serde_json::Value = - serde_json::from_str(&input_json).expect("parse command input"); + let input = command_input(&request).expect("serialize command input"); assert_eq!(input["tool_name"], "apply_patch"); } diff --git a/codex-rs/hooks/src/events/session_end.rs b/codex-rs/hooks/src/events/session_end.rs index 708d0e53d9..294eea20b2 100644 --- a/codex-rs/hooks/src/events/session_end.rs +++ b/codex-rs/hooks/src/events/session_end.rs @@ -60,14 +60,14 @@ pub(crate) async fn run( return SessionEndOutcome::default(); } - let input_json = match serde_json::to_string(&SessionEndCommandInput { + let input = match serde_json::to_value(SessionEndCommandInput { session_id: request.session_id.to_string(), transcript_path: NullableString::from_path(request.transcript_path.clone()), cwd: request.cwd.display().to_string(), hook_event_name: "SessionEnd".to_string(), reason: SESSION_END_REASON.to_string(), }) { - Ok(input_json) => input_json, + Ok(input) => input, Err(error) => { return SessionEndOutcome { hook_events: common::serialization_failure_hook_events( @@ -82,7 +82,7 @@ pub(crate) async fn run( let results = dispatcher::execute_handlers( engine, matched, - input_json, + &input, request.cwd.as_path(), Some(request.turn_id), parse_completed, diff --git a/codex-rs/hooks/src/events/session_start.rs b/codex-rs/hooks/src/events/session_start.rs index df5ab4f923..0da8b21706 100644 --- a/codex-rs/hooks/src/events/session_start.rs +++ b/codex-rs/hooks/src/events/session_start.rs @@ -127,9 +127,9 @@ pub(crate) async fn run( }; } - let (input_json, turn_id) = match request.target { + let (input, turn_id) = match request.target { StartHookTarget::SessionStart { source } => { - let input_json = match serde_json::to_string(&SessionStartCommandInput::new( + let input = match serde_json::to_value(SessionStartCommandInput::new( request.session_id.to_string(), request.transcript_path.clone(), request.cwd.display().to_string(), @@ -137,7 +137,7 @@ pub(crate) async fn run( request.permission_mode.clone(), source.as_str().to_string(), )) { - Ok(input_json) => input_json, + Ok(input) => input, Err(error) => { return serialization_failure_outcome( common::serialization_failure_hook_events( @@ -148,7 +148,7 @@ pub(crate) async fn run( ); } }; - (input_json, turn_id) + (input, turn_id) } StartHookTarget::SubagentStart { turn_id: subagent_turn_id, @@ -166,8 +166,8 @@ pub(crate) async fn run( agent_id, agent_type, }; - let input_json = match serde_json::to_string(&input) { - Ok(input_json) => input_json, + let input = match serde_json::to_value(input) { + Ok(input) => input, Err(error) => { return serialization_failure_outcome( common::serialization_failure_hook_events( @@ -178,14 +178,14 @@ pub(crate) async fn run( ); } }; - (input_json, Some(subagent_turn_id)) + (input, Some(subagent_turn_id)) } }; let results = dispatcher::execute_handlers( engine, matched, - input_json, + &input, request.cwd.as_path(), turn_id, parse_completed, diff --git a/codex-rs/hooks/src/events/stop.rs b/codex-rs/hooks/src/events/stop.rs index e795c795bd..83cc6f6585 100644 --- a/codex-rs/hooks/src/events/stop.rs +++ b/codex-rs/hooks/src/events/stop.rs @@ -102,7 +102,12 @@ pub(crate) fn preview( .target .select_handlers(handlers) .into_iter() - .filter(|handler| matches!(handler.source_path, HandlerSourcePath::Local(_))) + .filter(|handler| { + !matches!( + handler.source_path, + HandlerSourcePath::ExecutorScoped { .. } + ) + }) .map(|handler| dispatcher::running_summary(&handler)) .collect() } @@ -129,7 +134,7 @@ pub(crate) async fn run(engine: &ClaudeHooksEngine, request: StopRequest) -> Sto HandlerSourcePath::ExecutorScoped { .. } ) }); - let input_json = match request.target { + let input = match request.target { StopHookTarget::Stop | StopHookTarget::MemoryConsolidation => { let input = StopCommandInput { session_id: request.session_id.to_string(), @@ -144,8 +149,8 @@ pub(crate) async fn run(engine: &ClaudeHooksEngine, request: StopRequest) -> Sto request.last_assistant_message.clone(), ), }; - match serde_json::to_string(&input) { - Ok(input_json) => input_json, + match serde_json::to_value(input) { + Ok(input) => input, Err(error) => { return serialization_failure_outcome( common::serialization_failure_hook_events( @@ -178,8 +183,8 @@ pub(crate) async fn run(engine: &ClaudeHooksEngine, request: StopRequest) -> Sto request.last_assistant_message.clone(), ), }; - match serde_json::to_string(&input) { - Ok(input_json) => input_json, + match serde_json::to_value(input) { + Ok(input) => input, Err(error) => { return serialization_failure_outcome( common::serialization_failure_hook_events( @@ -196,7 +201,7 @@ pub(crate) async fn run(engine: &ClaudeHooksEngine, request: StopRequest) -> Sto let results = dispatcher::execute_handlers_with_metadata( engine, matched, - input_json.clone(), + &input, request.cwd.as_path(), Some(request.turn_id.clone()), request.request_metadata.as_ref(), @@ -208,7 +213,7 @@ pub(crate) async fn run(engine: &ClaudeHooksEngine, request: StopRequest) -> Sto dispatcher::execute_handlers_with_metadata( engine, executor_cleanup, - input_json, + &input, request.cwd.as_path(), Some(request.turn_id), request.request_metadata.as_ref(), diff --git a/codex-rs/hooks/src/events/user_prompt_submit.rs b/codex-rs/hooks/src/events/user_prompt_submit.rs index 3a44a03457..17342cad9d 100644 --- a/codex-rs/hooks/src/events/user_prompt_submit.rs +++ b/codex-rs/hooks/src/events/user_prompt_submit.rs @@ -80,7 +80,7 @@ pub(crate) async fn run( } let subagent = SubagentCommandInputFields::from(request.subagent.as_ref()); - let input_json = match serde_json::to_string(&UserPromptSubmitCommandInput { + let input = match serde_json::to_value(UserPromptSubmitCommandInput { session_id: request.session_id.to_string(), turn_id: request.turn_id.clone(), agent_id: subagent.agent_id, @@ -92,7 +92,7 @@ pub(crate) async fn run( permission_mode: request.permission_mode.clone(), prompt: request.prompt.clone(), }) { - Ok(input_json) => input_json, + Ok(input) => input, Err(error) => { return serialization_failure_outcome(common::serialization_failure_hook_events( matched, @@ -105,7 +105,7 @@ pub(crate) async fn run( let results = dispatcher::execute_handlers( engine, matched, - input_json, + &input, request.cwd.as_path(), Some(request.turn_id), parse_completed, diff --git a/codex-rs/hooks/src/lib.rs b/codex-rs/hooks/src/lib.rs index 9e02b987ff..4e7c073d77 100644 --- a/codex-rs/hooks/src/lib.rs +++ b/codex-rs/hooks/src/lib.rs @@ -2,9 +2,13 @@ mod config_rules; mod context; mod declarations; mod engine; +mod environment; pub(crate) mod events; mod legacy_notify; mod mcp; +pub use environment::EnvironmentHookOutput; +pub use environment::EnvironmentHookSource; +pub use environment::HookEnvironmentExecutor; mod output_spill; mod registry; mod schema; @@ -17,6 +21,7 @@ pub use declarations::PluginHookDeclaration; pub use declarations::plugin_hook_declarations; pub use engine::HookListEntry; pub use engine::HookListEntryHandler; +pub use engine::discovery::validate_environment_hooks; pub use engine::dispatcher::hook_execution_mode_label; pub use engine::dispatcher::hook_handler_type_label; pub use events::common::SubagentHookContext; diff --git a/codex-rs/hooks/src/registry.rs b/codex-rs/hooks/src/registry.rs index 6ae2b142a8..244ef75431 100644 --- a/codex-rs/hooks/src/registry.rs +++ b/codex-rs/hooks/src/registry.rs @@ -84,13 +84,9 @@ impl Hooks { let hooks = Self::from_config(config, mcp_executor, Arc::clone(&environment), |shell| { CommandHookRuntime::new(shell, environment, thread_id, result_sender) }); - let required_load_errors = hooks.engine.required_load_errors(); - if !required_load_errors.is_empty() { - anyhow::bail!( - "failed to load required managed hooks: {}", - required_load_errors.join("; ") - ); - } + crate::engine::discovery::ensure_required_hooks_loaded( + hooks.engine.required_load_errors(), + )?; Ok((hooks, result_receiver)) } @@ -113,6 +109,54 @@ impl Hooks { && self.plugin_hook_load_warnings.iter().eq(warnings) } + /// Adds only owner-admitted requirements hooks; execution remains scoped to their environment. + pub fn with_environment_hooks( + &self, + sources: Vec, + executor: Arc, + ) -> Self { + let discovered = self.discover_environment_hooks(sources); + let mut hooks = self.clone(); + hooks.engine.command_runtime.environment_executor = Some(executor); + if !discovered.handlers.is_empty() { + Arc::make_mut(&mut hooks.engine.handlers).extend(discovered.handlers); + } + if !discovered.warnings.is_empty() { + let mut warnings = hooks.engine.warnings.to_vec(); + warnings.extend(discovered.warnings); + hooks.engine.warnings = warnings.into(); + } + hooks + } + + /// List this session's declarations, including hooks that are disabled or not yet trusted. + pub fn list_with_environment_hooks( + &self, + sources: Vec, + ) -> HookListOutcome { + let discovered = self.discover_environment_hooks(sources); + let mut hooks = self.engine.hook_entries.as_ref().clone(); + hooks.extend(discovered.hook_entries); + let mut warnings = self.engine.warnings.to_vec(); + warnings.extend(discovered.warnings); + HookListOutcome { hooks, warnings } + } + + fn discover_environment_hooks( + &self, + sources: Vec, + ) -> crate::engine::discovery::DiscoveryResult { + if !self.engine.enabled { + return crate::engine::discovery::DiscoveryResult::default(); + } + let display_order = self + .engine + .hook_entries + .last() + .map_or(0, |entry| entry.display_order.saturating_add(1)); + crate::engine::discovery::discover_environment_hooks(sources, display_order) + } + pub fn with_executor_hooks(&self, executor_hooks: Vec) -> Self { let mut hooks = self.clone(); hooks.engine.set_executor_hooks(executor_hooks);