From 624fdeeceef695398d120bbcac02eb5e67d6ce7b Mon Sep 17 00:00:00 2001 From: Aismit Date: Tue, 1 Dec 2026 19:09:06 +0000 Subject: [PATCH] Run patch hooks for intercepted `apply_patch` commands (#65077) ## Why Codex can intercept an `apply_patch` heredoc passed to `exec_command` and apply the patch directly. That path ran shell hooks but bypassed `apply_patch` hooks, so patch-specific rules could miss the same edit when it was submitted through the shell tool. ## What changed - Run `apply_patch` `PreToolUse` after shell hooks and before file verification. Hooks can block or rewrite the patch, and the final patch is checked against the selected environment's permissions. - Report the executed patch through `apply_patch` `PostToolUse`. Link the patch hook events to the outer shell call with `parent_tool_use_id` and provide working-directory and filesystem metadata for hooks that inspect patch targets. - Apply the same block and rewrite rules in recorded Guardian reviews. Mark those hook requests with `review_only` and review the resulting patch without executing it or publishing hook-provided context. ## Testing Add coverage for hook blocks and rewrites, effective working directories, environment permissions, and cancellation before and after a patch write. Cover recorded reviews of rewritten patches and reviews stopped by a hook. GitOrigin-RevId: 2115f26261a20d4a512669bc9e277a764b8f42f4 --- codex-rs/apply-patch/src/invocation.rs | 26 +- .../core/src/guardian/recorded_tool_call.rs | 67 +- .../core/src/hook_environment_executor.rs | 14 +- codex-rs/core/src/hook_runtime.rs | 111 ++- codex-rs/core/src/stream_events_utils.rs | 6 +- codex-rs/core/src/tools/context.rs | 15 +- .../core/src/tools/handlers/apply_patch.rs | 200 ++++- .../src/tools/handlers/apply_patch_tests.rs | 1 + codex-rs/core/src/tools/handlers/dynamic.rs | 1 + .../src/tools/handlers/extension_tools.rs | 1 + codex-rs/core/src/tools/handlers/mcp.rs | 2 + .../src/tools/handlers/mcp_resource_tests.rs | 4 +- .../core/src/tools/handlers/unified_exec.rs | 8 +- .../handlers/unified_exec/exec_command.rs | 97 ++- .../src/tools/handlers/unified_exec_tests.rs | 7 +- codex-rs/core/src/tools/parallel.rs | 8 +- codex-rs/core/src/tools/registry.rs | 126 ++- codex-rs/core/src/tools/registry_tests.rs | 322 ++++++- .../core/src/tools/runtimes/apply_patch.rs | 2 +- .../src/tools/runtimes/apply_patch_tests.rs | 5 +- .../core/src/tools/user_messaging_tests.rs | 1 + codex-rs/core/tests/suite/hooks.rs | 6 + codex-rs/core/tests/suite/hooks_cwd_tests.rs | 94 ++- .../suite/hooks_intercepted_patch_tests.rs | 785 ++++++++++++++++++ .../suite/scenarios_guardian_direct_review.rs | 739 +++++++++++++++-- ...ct_review__guardian_direct_exec_patch.snap | 20 +- ..._direct_review__guardian_direct_patch.snap | 14 +- codex-rs/ext/skills/src/tools/read.rs | 2 + .../post-tool-use.command.input.schema.json | 12 + .../pre-tool-use.command.input.schema.json | 16 + codex-rs/hooks/src/engine/discovery.rs | 2 + codex-rs/hooks/src/engine/dispatcher.rs | 20 +- .../hooks/src/engine/failure_policy_tests.rs | 5 + codex-rs/hooks/src/engine/mod.rs | 33 +- codex-rs/hooks/src/engine/mod_tests.rs | 131 +++ codex-rs/hooks/src/environment.rs | 2 + codex-rs/hooks/src/events/post_tool_use.rs | 10 + codex-rs/hooks/src/events/pre_tool_use.rs | 67 +- codex-rs/hooks/src/schema.rs | 34 + codex-rs/message-board-mcp/src/lib.rs | 8 +- codex-rs/tools/src/function_call_error.rs | 6 + codex-rs/tools/src/tool_output.rs | 16 +- 42 files changed, 2730 insertions(+), 316 deletions(-) create mode 100644 codex-rs/core/tests/suite/hooks_intercepted_patch_tests.rs diff --git a/codex-rs/apply-patch/src/invocation.rs b/codex-rs/apply-patch/src/invocation.rs index 64e6a5be60..dfd5f0890f 100644 --- a/codex-rs/apply-patch/src/invocation.rs +++ b/codex-rs/apply-patch/src/invocation.rs @@ -36,6 +36,7 @@ enum ApplyPatchShell { #[derive(Debug, PartialEq)] pub enum MaybeApplyPatch { Body(ApplyPatchArgs), + ImplicitInvocation, ShellParseError(ExtractHeredocError), PatchParseError(ParseError), NotApplyPatch, @@ -118,6 +119,10 @@ fn is_implicit_patch(argv: &[String], cwd: &PathUri) -> bool { // TODO: make private once we remove tests in lib.rs /// `cwd` supplies the path convention used to interpret the shell executable in `argv`. pub fn maybe_parse_apply_patch(argv: &[String], cwd: &PathUri) -> MaybeApplyPatch { + if is_implicit_patch(argv, cwd) { + return MaybeApplyPatch::ImplicitInvocation; + } + match argv { // Direct invocation: apply_patch [cmd, body] if APPLY_PATCH_COMMANDS.contains(&cmd.as_str()) => match parse_patch(body) { @@ -152,12 +157,11 @@ pub async fn maybe_parse_apply_patch_verified( fs: &dyn ExecutorFileSystem, sandbox: Option<&codex_exec_server::FileSystemSandboxContext>, ) -> MaybeApplyPatchVerified { - if is_implicit_patch(argv, cwd) { - return MaybeApplyPatchVerified::CorrectnessError(ApplyPatchError::ImplicitInvocation); - } - match maybe_parse_apply_patch(argv, cwd) { MaybeApplyPatch::Body(args) => verify_apply_patch_args(args, cwd, fs, sandbox).await, + MaybeApplyPatch::ImplicitInvocation => { + MaybeApplyPatchVerified::CorrectnessError(ApplyPatchError::ImplicitInvocation) + } MaybeApplyPatch::ShellParseError(e) => MaybeApplyPatchVerified::ShellParseError(e), MaybeApplyPatch::PatchParseError(e) => MaybeApplyPatchVerified::CorrectnessError(e.into()), MaybeApplyPatch::NotApplyPatch => MaybeApplyPatchVerified::NotApplyPatch, @@ -508,6 +512,13 @@ mod tests { let patch = "*** Begin Patch\n*** Add File: foo\n+hi\n*** End Patch".to_string(); let args = vec![patch]; let dir = tempdir().unwrap(); + assert_matches!( + maybe_parse_apply_patch( + &args, + &PathUri::from_host_native_path(dir.path()).expect("absolute test path"), + ), + MaybeApplyPatch::ImplicitInvocation + ); assert_matches!( maybe_parse_apply_patch_verified( &args, @@ -525,6 +536,13 @@ mod tests { let script = "*** Begin Patch\n*** Add File: foo\n+hi\n*** End Patch"; let args = args_bash(script); let dir = tempdir().unwrap(); + assert_matches!( + maybe_parse_apply_patch( + &args, + &PathUri::from_host_native_path(dir.path()).expect("absolute test path"), + ), + MaybeApplyPatch::ImplicitInvocation + ); assert_matches!( maybe_parse_apply_patch_verified( &args, diff --git a/codex-rs/core/src/guardian/recorded_tool_call.rs b/codex-rs/core/src/guardian/recorded_tool_call.rs index ce9340d5c1..d19799daad 100644 --- a/codex-rs/core/src/guardian/recorded_tool_call.rs +++ b/codex-rs/core/src/guardian/recorded_tool_call.rs @@ -34,6 +34,7 @@ use crate::context_manager::ContextManager; use crate::guardian_review::AttachedReviewer; use crate::guardian_review::GuardianReviewResult; use crate::guardian_review::RecordedReviewMode; +use crate::hook_runtime::PreToolUseContextPolicy; use crate::mcp_tool_call; use crate::session::session::Session; use crate::tools::context::ToolInvocation; @@ -50,6 +51,7 @@ use crate::tools::handlers::unified_exec::preparation::ParsedExecCommand; use crate::tools::registry::PreToolUseError; use crate::tools::registry::apply_pre_tool_use; use crate::tools::sandboxing::ExecApprovalRequirement; +use crate::tools::sandboxing::ToolCtx; pub(crate) async fn review_tool_call( session: &Arc, @@ -158,24 +160,35 @@ pub(crate) async fn review_tool_call( .runtime .environments_for_input(&invocation) .map_err(tool_error)?; - apply_pre_tool_use(tool.runtime.as_ref(), &mut invocation) - .await - .map_err(|err| match err { - PreToolUseError::Blocked(reason) => CodexErr::InvalidRequest(reason), - PreToolUseError::Failed(err) => tool_error(err), - PreToolUseError::Cancelled(_) => CodexErr::TurnAborted, - })?; + apply_pre_tool_use( + tool.runtime.as_ref(), + &mut invocation, + PreToolUseContextPolicy::RecordedReview, + ) + .await + .map_err(|err| match err { + PreToolUseError::Blocked(reason) => CodexErr::InvalidRequest(reason), + PreToolUseError::Failed(err) => tool_error(err), + PreToolUseError::Cancelled(_) => CodexErr::TurnAborted, + })?; let step = &invocation.step_context; - let context = GuardianReviewContext { - root_evidence: root_evidence.map(Arc::new), - ..GuardianReviewContext::from(step) - }; - let (approval, request) = if let Some(tool_info) = advertised_mcp_tool { + let (context, approval, request) = if let Some(tool_info) = advertised_mcp_tool { let request = mcp_tool_call::recorded::prepare_review_request(&invocation, tool_info) .await .map_err(tool_error)?; - (None, request) + let context = GuardianReviewContext { + root_evidence: root_evidence.map(Arc::new), + ..GuardianReviewContext::from(step) + }; + (context, None, request) } else { + let mut tool_ctx = ToolCtx { + session: Arc::clone(session), + step_context: Arc::clone(step), + cancellation_token: cancellation.clone(), + call_id: invocation.call_id.to_string(), + tool_name: invocation.tool_name.clone(), + }; let name = invocation.tool_name.name.as_str(); let (requirement, action) = match (name, &invocation.payload) { ("exec_command", ToolPayload::Function { arguments }) => { @@ -194,19 +207,23 @@ pub(crate) async fn review_tool_call( ExecCommandLifetime::OneShot }; let prepared = parsed.prepare(lifetime).map_err(tool_error)?; - let fs = prepared.turn_environment.environment().get_filesystem(); if let Some(patch) = prepare_intercepted_patch( &prepared.resolved.command, &prepared.cwd, - fs.as_ref(), &prepared.turn_environment, - step, + &mut tool_ctx, + PreToolUseContextPolicy::RecordedReview, ) .await - .map_err(tool_error)? - { - let action = patch.approval_action(&invocation.call_id); - (Some(patch.exec_approval_requirement), action) + .map_err(|error| { + if cancellation.is_cancelled() { + CodexErr::TurnAborted + } else { + tool_error(error) + } + })? { + let action = patch.request.approval_action(&invocation.call_id); + (Some(patch.request.exec_approval_requirement), action) } else { let requirement = prepared.approval_requirement(session, step).await; let action = prepared.approval_action(&invocation.call_id, &requirement); @@ -250,10 +267,14 @@ pub(crate) async fn review_tool_call( return Err(CodexErr::InvalidRequest(reason.clone())); } }; + let context = GuardianReviewContext { + root_evidence: root_evidence.map(Arc::new), + ..GuardianReviewContext::from(&tool_ctx.step_context) + }; let request = from_approval_action(action, &context) .request .map_err(CodexErr::InvalidRequest)?; - (approval, request) + (context, approval, request) }; let input = ReviewInput { session: Arc::clone(session), @@ -421,7 +442,9 @@ pub(super) fn root_messages(evidence: &GuardianRootEvidence) -> Vec CodexErr { match error { - FunctionCallError::RespondToModel(message) => CodexErr::InvalidRequest(message), + FunctionCallError::RespondToModel(message) + | FunctionCallError::FailedBeforeExecution(message) + | FunctionCallError::Blocked(message) => CodexErr::InvalidRequest(message), FunctionCallError::Fatal(message) => CodexErr::Fatal(message), } } diff --git a/codex-rs/core/src/hook_environment_executor.rs b/codex-rs/core/src/hook_environment_executor.rs index f8b42cd987..a92c301c55 100644 --- a/codex-rs/core/src/hook_environment_executor.rs +++ b/codex-rs/core/src/hook_environment_executor.rs @@ -19,6 +19,7 @@ use codex_hooks::HookEnvironmentExecutor; use codex_hooks::Hooks; use codex_network_proxy::NetworkProxy; use codex_protocol::models::PermissionProfile; +use codex_utils_path_uri::PathUri; use futures::FutureExt; use futures::future::BoxFuture; @@ -44,6 +45,7 @@ pub(crate) fn with_environment_hooks( turn, environments, /*target_environments*/ &[], + /*tool_cwd*/ None, ) } @@ -52,9 +54,18 @@ pub(crate) fn with_tool_environment_hooks( turn: &Arc, environments: &TurnEnvironmentSnapshot, target_environments: &[&str], + tool_cwd: Option<&PathUri>, ) -> Hooks { + let mut sources = environment_hook_sources(environments, target_environments); + if let ([environment_id], Some(cwd)) = (target_environments, tool_cwd) + && let Some(source) = sources + .iter_mut() + .find(|source| source.environment_id == *environment_id) + { + source.tool_cwd = Some(cwd.clone()); + } session.hooks().with_environment_hooks( - environment_hook_sources(environments, target_environments), + sources, Arc::new(EnvironmentCommandExecutor { environments: environments.clone(), session: Arc::clone(session), @@ -77,6 +88,7 @@ pub(crate) fn environment_hook_sources( .map(|environment| EnvironmentHookSource { environment_id: environment.selection.environment_id.clone(), cwd: environment.cwd().clone(), + tool_cwd: None, hooks: environment.config().environment_hooks.clone(), }) .collect() diff --git a/codex-rs/core/src/hook_runtime.rs b/codex-rs/core/src/hook_runtime.rs index aa257291df..a3e14ff7ad 100644 --- a/codex-rs/core/src/hook_runtime.rs +++ b/codex-rs/core/src/hook_runtime.rs @@ -77,6 +77,7 @@ use crate::session::turn_context::TurnContext; use crate::state::TurnState; use crate::tools::hook_names::HookToolName; use crate::tools::registry::PostToolUsePayload; +use crate::tools::registry::PreToolUsePayload; use crate::tools::sandboxing::PermissionRequestPayload; use crate::turn_metadata::ExecutionMetadata; @@ -90,6 +91,12 @@ pub(crate) enum PreToolUseHookResult { Blocked(String), } +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum PreToolUseContextPolicy { + Publish, + RecordedReview, +} + struct ContextInjectingHookOutcome { hook_events: Vec, outcome: HookRuntimeOutcome, @@ -210,36 +217,49 @@ pub(crate) async fn run_pending_session_start_hooks( /// `tool_name` is the canonical name serialized to hook stdin. Matcher aliases /// are internal compatibility names used only for selecting configured hook /// handlers. +#[allow(clippy::too_many_arguments)] pub(crate) async fn run_pre_tool_use_hooks( sess: &Arc, step_context: &StepContext, - tool_use_id: String, - tool_name: &HookToolName, - tool_input: &Value, + tool_use_id: &str, + parent_tool_use_id: Option<&str>, + payload: &PreToolUsePayload, tool_cwd: Option, target_environments: &[&str], + context_policy: PreToolUseContextPolicy, ) -> PreToolUseHookResult { + let PreToolUsePayload { + tool_name, + tool_input, + } = payload; let turn_context = &step_context.turn; - let request = PreToolUseRequest { - session_id: sess.session_id().into(), - turn_id: turn_context.sub_id.clone(), - subagent: thread_spawn_subagent_hook_context(sess, turn_context), - cwd: tool_hook_cwd(&step_context.environments, turn_context), - tool_cwd, - transcript_path: sess.hook_transcript_path().await, - model: step_context.settings.model_info.slug.clone(), - permission_mode: hook_permission_mode(step_context.settings.approval_policy()), - tool_name: tool_name.name().to_string(), - matcher_aliases: tool_name.matcher_aliases().to_vec(), - tool_use_id, - tool_input: tool_input.clone(), - }; + let is_patch = tool_name == &HookToolName::apply_patch(); let hooks = with_tool_environment_hooks( sess, turn_context, &step_context.environments, target_environments, + tool_cwd.as_ref().filter(|_| is_patch), ); + let tool_target_is_remote = + tool_target_is_remote(&step_context.environments, target_environments, is_patch); + let request = PreToolUseRequest { + session_id: sess.session_id().into(), + turn_id: turn_context.sub_id.clone(), + subagent: thread_spawn_subagent_hook_context(sess, turn_context), + cwd: tool_hook_cwd(&step_context.environments, turn_context), + tool_cwd: tool_cwd.filter(|_| tool_target_is_remote != Some(true)), + tool_target_is_remote, + transcript_path: sess.hook_transcript_path().await, + model: step_context.settings.model_info.slug.clone(), + permission_mode: hook_permission_mode(step_context.settings.approval_policy()), + tool_name: tool_name.name().to_string(), + matcher_aliases: tool_name.matcher_aliases().to_vec(), + tool_use_id: tool_use_id.to_owned(), + parent_tool_use_id: parent_tool_use_id.map(str::to_owned), + tool_input: tool_input.clone(), + review_only: context_policy == PreToolUseContextPolicy::RecordedReview, + }; let preview_runs = hooks.preview_pre_tool_use(&request); emit_hook_started_events(sess, turn_context, preview_runs).await; @@ -250,8 +270,15 @@ pub(crate) async fn run_pre_tool_use_hooks( additional_contexts, updated_input, } = hooks.run_pre_tool_use(request).await; - emit_hook_completed_events(sess, turn_context, hook_events).await; - record_additional_contexts(sess, turn_context, additional_contexts).await; + match context_policy { + PreToolUseContextPolicy::Publish => { + emit_hook_completed_events(sess, turn_context, hook_events).await; + record_additional_contexts(sess, turn_context, additional_contexts).await; + } + PreToolUseContextPolicy::RecordedReview => { + report_hook_completions(sess, turn_context, hook_events).await; + } + } if !should_block { return PreToolUseHookResult::Continue { updated_input }; @@ -287,6 +314,21 @@ fn tool_hook_cwd(environments: &TurnEnvironmentSnapshot, turn: &TurnContext) -> .unwrap_or_else(|| turn.cwd.clone()) } +fn tool_target_is_remote( + environments: &TurnEnvironmentSnapshot, + target_environments: &[&str], + is_patch: bool, +) -> Option { + let [environment_id] = target_environments else { + return None; + }; + let environment = environments + .turn_environments() + .find(|environment| environment.selection.environment_id == *environment_id)?; + let remote = environment.environment().is_remote(); + (remote || is_patch).then_some(remote) +} + // PermissionRequest hooks share the same preview/start/completed event flow as // other hook types, but they return an optional decision instead of mutating // tool input or post-run state. @@ -317,6 +359,7 @@ pub(crate) async fn run_permission_request_hooks( turn_context, review_context.environments(), &[target_environment], + /*tool_cwd*/ None, ); let preview_runs = hooks.preview_permission_request(&request); emit_hook_started_events(sess, turn_context, preview_runs).await; @@ -342,27 +385,35 @@ pub(crate) async fn run_post_tool_use_hooks( target_environments: &[&str], ) -> PostToolUseOutcome { let turn_context = &step_context.turn; + let is_patch = payload.tool_name == HookToolName::apply_patch(); + let hooks = with_tool_environment_hooks( + sess, + turn_context, + &step_context.environments, + target_environments, + payload.tool_cwd.as_ref().filter(|_| is_patch), + ); + let tool_target_is_remote = + tool_target_is_remote(&step_context.environments, target_environments, is_patch); let request = PostToolUseRequest { session_id: sess.session_id().into(), turn_id: turn_context.sub_id.clone(), subagent: thread_spawn_subagent_hook_context(sess, turn_context), cwd: tool_hook_cwd(&step_context.environments, turn_context), - tool_cwd: payload.tool_cwd, + tool_cwd: payload + .tool_cwd + .filter(|_| tool_target_is_remote != Some(true)), + tool_target_is_remote, transcript_path: sess.hook_transcript_path().await, model: step_context.settings.model_info.slug.clone(), permission_mode: hook_permission_mode(step_context.settings.approval_policy()), tool_name: payload.tool_name.name().to_string(), matcher_aliases: payload.tool_name.matcher_aliases().to_vec(), tool_use_id: payload.tool_use_id, + parent_tool_use_id: payload.parent_tool_use_id, tool_input: payload.tool_input, tool_response: payload.tool_response, }; - let hooks = with_tool_environment_hooks( - sess, - turn_context, - &step_context.environments, - target_environments, - ); let preview_runs = hooks.preview_post_tool_use(&request); emit_hook_started_events(sess, turn_context, preview_runs).await; @@ -1012,6 +1063,14 @@ pub(crate) async fn emit_hook_completed_events( .await; } + report_hook_completions(sess, turn_context, completed_events).await; +} + +async fn report_hook_completions( + sess: &Arc, + turn_context: &Arc, + completed_events: Vec, +) { for completed in completed_events { emit_hook_completed_metrics(turn_context, &completed); track_hook_completed_analytics(sess, turn_context, &completed); diff --git a/codex-rs/core/src/stream_events_utils.rs b/codex-rs/core/src/stream_events_utils.rs index d93cec0ec9..6c7f4a1d9d 100644 --- a/codex-rs/core/src/stream_events_utils.rs +++ b/codex-rs/core/src/stream_events_utils.rs @@ -468,7 +468,11 @@ pub(crate) async fn handle_output_item_done( output.last_agent_message = finalized_facts.and_then(|facts| facts.last_agent_message); } // The tool request should be answered directly (or was denied); push that response into the transcript. - Err(FunctionCallError::RespondToModel(message)) => { + Err( + FunctionCallError::RespondToModel(message) + | FunctionCallError::FailedBeforeExecution(message) + | FunctionCallError::Blocked(message), + ) => { ctx.sess .services .executed_tool_calls diff --git a/codex-rs/core/src/tools/context.rs b/codex-rs/core/src/tools/context.rs index 1963b2ec27..2288b13ace 100644 --- a/codex-rs/core/src/tools/context.rs +++ b/codex-rs/core/src/tools/context.rs @@ -353,10 +353,6 @@ impl FunctionToolOutput { post_tool_use_response: None, } } - - pub fn into_text(self) -> String { - function_call_output_content_items_to_text(&self.body).unwrap_or_default() - } } impl ToolOutput for FunctionToolOutput { @@ -421,6 +417,13 @@ pub struct AbortedToolOutput { } impl AbortedToolOutput { + pub(crate) fn by_user(tool_name: &ToolName, secs: f32) -> Self { + if tool_name.is_default_namespace() && tool_name.name == "exec_command" { + return Self::exec_command(secs); + } + Self::user(secs) + } + pub(crate) fn user(secs: f32) -> Self { Self { message: format!("aborted by user after {secs:.1}s"), @@ -480,8 +483,8 @@ pub struct ExecCommandToolOutput { pub exit_code: Option, pub original_token_count: Option, pub hook_command: Option, - /// Local execution cwd retained for PostToolUse, independent of the collecting - /// turn. Remote commands leave this unset to retain the host hook cwd. + /// Effective execution cwd retained for PostToolUse, independent of the collecting + /// turn. Hook dispatch retains the host fallback for remote tools' local hooks. pub tool_cwd: Option, } diff --git a/codex-rs/core/src/tools/handlers/apply_patch.rs b/codex-rs/core/src/tools/handlers/apply_patch.rs index 66586ab5e1..47592d4027 100644 --- a/codex-rs/core/src/tools/handlers/apply_patch.rs +++ b/codex-rs/core/src/tools/handlers/apply_patch.rs @@ -10,6 +10,9 @@ use tokio_util::sync::CancellationToken; use crate::apply_patch; use crate::apply_patch::convert_apply_patch_to_protocol; use crate::function_tool::FunctionCallError; +use crate::hook_runtime::PreToolUseContextPolicy; +use crate::hook_runtime::PreToolUseHookResult; +use crate::hook_runtime::run_pre_tool_use_hooks; use crate::safety::PatchPolicyMatcher; use crate::safety::PatchSandboxRoute; use crate::session::session::Session; @@ -17,7 +20,6 @@ use crate::session::step_context::StepContext; use crate::session::turn_context::TurnContext; use crate::session::turn_context::TurnEnvironment; use crate::tools::context::ApplyPatchToolOutput; -use crate::tools::context::FunctionToolOutput; use crate::tools::context::SharedTurnDiffTracker; use crate::tools::context::ToolEnvironments; use crate::tools::context::ToolInvocation; @@ -27,7 +29,6 @@ use crate::tools::events::ToolEmitter; use crate::tools::events::ToolEventCtx; use crate::tools::handlers::apply_granted_turn_permissions; use crate::tools::handlers::apply_patch_spec::create_apply_patch_freeform_tool; -use crate::tools::handlers::file_system_sandbox_policy_context_for_cwd; use crate::tools::handlers::resolve_tool_environment; use crate::tools::handlers::selected_executor; use crate::tools::handlers::updated_hook_command; @@ -44,10 +45,11 @@ use crate::tools::sandboxing::ExecApprovalRequirement; use crate::tools::sandboxing::ToolCtx; use crate::windows_sandbox::windows_sandbox_level_for_legacy_checks; use codex_apply_patch::ApplyPatchAction; +use codex_apply_patch::ApplyPatchArgs; use codex_apply_patch::ApplyPatchFileChange; use codex_apply_patch::Hunk; use codex_apply_patch::StreamingPatchParser; -use codex_exec_server::ExecutorFileSystem; +use codex_async_utils::OrCancelExt; use codex_features::Feature; use codex_protocol::models::AdditionalPermissionProfile; use codex_protocol::models::FileSystemPermissions; @@ -329,7 +331,7 @@ impl ApplyPatchHandler { call_id: call_id.into(), tool_name, }; - let content = execute_prepared_patch(request, Some(&tracker), tool_ctx).await?; + let content = execute_prepared_patch(&request, Some(&tracker), tool_ctx).await?; Ok(boxed_tool_output(ApplyPatchToolOutput::from_text(content))) } } @@ -407,6 +409,7 @@ impl CoreToolRuntime for ApplyPatchHandler { tool_cwd: result.post_tool_use_cwd(), tool_name: HookToolName::apply_patch(), tool_use_id: invocation.call_id.to_string(), + parent_tool_use_id: None, tool_input: serde_json::json!({ "command": apply_patch_payload_command(&invocation.payload)?, }), @@ -415,11 +418,22 @@ impl CoreToolRuntime for ApplyPatchHandler { } } +pub(crate) struct InterceptedApplyPatch { + pub(crate) content: String, + pub(crate) patch: String, + pub(crate) cwd: PathUri, + pub(crate) hook_use_id: String, +} + +pub(crate) struct PreparedInterceptedPatch { + pub(crate) request: ApplyPatchRequest, + hook_use_id: String, +} + #[allow(clippy::too_many_arguments)] pub(crate) async fn intercept_apply_patch( command: &[String], cwd: &PathUri, - fs: &dyn ExecutorFileSystem, turn_environment: &TurnEnvironment, session: Arc, step_context: Arc, @@ -427,48 +441,147 @@ pub(crate) async fn intercept_apply_patch( tracker: Option<&SharedTurnDiffTracker>, call_id: &str, tool_name: &str, -) -> Result, FunctionCallError> { - let Some(request) = - prepare_intercepted_patch(command, cwd, fs, turn_environment, &step_context).await? - else { - return Ok(None); - }; - let tool_ctx = ToolCtx { +) -> Result, FunctionCallError> { + let mut tool_ctx = ToolCtx { session, step_context, cancellation_token, call_id: call_id.to_string(), tool_name: ToolName::plain(tool_name), }; - let content = execute_prepared_patch(request, tracker, tool_ctx).await?; - Ok(Some(FunctionToolOutput::from_text(content, Some(true)))) + let Some(prepared) = prepare_intercepted_patch( + command, + cwd, + turn_environment, + &mut tool_ctx, + PreToolUseContextPolicy::Publish, + ) + .await + .map_err(|error| match error { + FunctionCallError::RespondToModel(message) => { + FunctionCallError::FailedBeforeExecution(message) + } + error => error, + })? + else { + return Ok(None); + }; + if tool_ctx.cancellation_token.is_cancelled() { + return Err(FunctionCallError::Blocked( + "tool call cancelled".to_string(), + )); + } + let request = prepared.request; + let content = execute_prepared_patch(&request, tracker, tool_ctx).await?; + Ok(Some(InterceptedApplyPatch { + content, + patch: request.action.patch, + cwd: request.action.cwd, + hook_use_id: prepared.hook_use_id, + })) } pub(crate) async fn prepare_intercepted_patch( command: &[String], cwd: &PathUri, - fs: &dyn ExecutorFileSystem, turn_environment: &TurnEnvironment, - step_context: &StepContext, -) -> Result, FunctionCallError> { - let sandbox = turn_environment.sandbox_context(/*additional_permissions*/ None); - match codex_apply_patch::maybe_parse_apply_patch_verified(command, cwd, fs, Some(&sandbox)) - .await - { - codex_apply_patch::MaybeApplyPatchVerified::Body(changes) => { - prepare_verified_patch(changes, turn_environment.clone(), step_context).map(Some) + tool_ctx: &mut ToolCtx, + context_policy: PreToolUseContextPolicy, +) -> Result, FunctionCallError> { + let mut args = match codex_apply_patch::maybe_parse_apply_patch(command, cwd) { + codex_apply_patch::MaybeApplyPatch::Body(args) => args, + codex_apply_patch::MaybeApplyPatch::ImplicitInvocation => { + return Err(FunctionCallError::RespondToModel(format!( + "apply_patch verification failed: {}", + codex_apply_patch::ApplyPatchError::ImplicitInvocation + ))); } - codex_apply_patch::MaybeApplyPatchVerified::CorrectnessError(parse_error) => { - Err(FunctionCallError::RespondToModel(format!( - "apply_patch verification failed: {parse_error}" - ))) + codex_apply_patch::MaybeApplyPatch::PatchParseError(error) => { + return Err(FunctionCallError::RespondToModel(format!( + "apply_patch verification failed: {error}" + ))); } - codex_apply_patch::MaybeApplyPatchVerified::ShellParseError(error) => { + codex_apply_patch::MaybeApplyPatch::ShellParseError(error) => { tracing::trace!("Failed to parse apply_patch input, {error:?}"); - Ok(None) + return Ok(None); } - codex_apply_patch::MaybeApplyPatchVerified::NotApplyPatch => Ok(None), + codex_apply_patch::MaybeApplyPatch::NotApplyPatch => return Ok(None), + }; + if args + .environment_id + .as_ref() + .is_some_and(|environment_id| environment_id != &turn_environment.selection.environment_id) + { + return Err(FunctionCallError::RespondToModel( + "apply_patch environment does not match the tool environment".to_string(), + )); } + let patch_cwd = args + .workdir + .take() + .map(|dir| cwd.join(&dir)) + .transpose() + .map_err(|error| { + FunctionCallError::RespondToModel(format!("apply_patch verification failed: {error}")) + })? + .unwrap_or_else(|| cwd.clone()); + let hook_use_id = uuid::Uuid::now_v7().to_string(); + let tool_cwd = Some(patch_cwd.clone()); + let target_environments = [turn_environment.selection.environment_id.as_str()]; + // The outer command already passed Bash hooks. Interception performs only this patch. + let pre_outcome = run_pre_tool_use_hooks( + &tool_ctx.session, + &tool_ctx.step_context, + &hook_use_id, + Some(&tool_ctx.call_id), + &PreToolUsePayload { + tool_name: HookToolName::apply_patch(), + tool_input: serde_json::json!({ "command": args.patch }), + }, + tool_cwd, + &target_environments, + context_policy, + ) + .or_cancel(&tool_ctx.cancellation_token) + .await + .map_err(|_| FunctionCallError::Blocked("tool call cancelled".to_string()))?; + match pre_outcome { + PreToolUseHookResult::Blocked(reason) => { + return Err(FunctionCallError::Blocked(reason)); + } + PreToolUseHookResult::Continue { + updated_input: None, + } => {} + PreToolUseHookResult::Continue { + updated_input: Some(input), + } => { + let updated_patch = updated_hook_command(&input)?; + let updated_args = codex_apply_patch::parse_patch(updated_patch).map_err(|err| { + FunctionCallError::RespondToModel(format!("apply_patch verification failed: {err}")) + })?; + if updated_args + .environment_id + .as_ref() + .is_some_and(|environment_id| { + environment_id != &turn_environment.selection.environment_id + }) + { + return Err(FunctionCallError::RespondToModel( + "PreToolUse hook cannot change the tool environment".to_string(), + )); + } + if updated_patch != args.patch { + Arc::make_mut(&mut tool_ctx.step_context).mark_hook_input_rewritten(); + } + args = updated_args; + } + } + let request = + prepare_parsed_patch(args, &patch_cwd, turn_environment, &tool_ctx.step_context).await?; + Ok(Some(PreparedInterceptedPatch { + request, + hook_use_id, + })) } pub(crate) async fn prepare_patch_request( @@ -484,16 +597,18 @@ pub(crate) async fn prepare_patch_request( ))); } }; + prepare_parsed_patch(args, turn_environment.cwd(), turn_environment, step_context).await +} + +async fn prepare_parsed_patch( + args: ApplyPatchArgs, + cwd: &PathUri, + turn_environment: &TurnEnvironment, + step_context: &StepContext, +) -> Result { let fs = turn_environment.environment().get_filesystem(); let sandbox = turn_environment.sandbox_context(/*additional_permissions*/ None); - match codex_apply_patch::verify_apply_patch_args( - args, - turn_environment.cwd(), - fs.as_ref(), - Some(&sandbox), - ) - .await - { + match codex_apply_patch::verify_apply_patch_args(args, cwd, fs.as_ref(), Some(&sandbox)).await { codex_apply_patch::MaybeApplyPatchVerified::Body(changes) => { prepare_verified_patch(changes, turn_environment.clone(), step_context) } @@ -521,9 +636,8 @@ fn prepare_verified_patch( turn_environment: TurnEnvironment, step_context: &StepContext, ) -> Result { - let cwd = action.cwd.clone(); let sandbox_context = turn_environment.sandbox_context(/*additional_permissions*/ None); - let policy_context = file_system_sandbox_policy_context_for_cwd(&sandbox_context, &cwd); + let policy_context = sandbox_context.policy_context(); let sandbox_route = if turn_environment.environment().is_remote() { PatchSandboxRoute::ExecutorManaged } else { @@ -556,7 +670,7 @@ fn prepare_verified_patch( let effective_additional_permissions = apply_granted_turn_permissions( step_context, &turn_environment, - &cwd, + turn_environment.cwd(), crate::sandboxing::SandboxPermissions::UseDefault, additional_permissions, ); @@ -578,7 +692,7 @@ fn prepare_verified_patch( }) } async fn execute_prepared_patch( - request: ApplyPatchRequest, + request: &ApplyPatchRequest, tracker: Option<&SharedTurnDiffTracker>, tool_ctx: ToolCtx, ) -> Result { @@ -602,7 +716,7 @@ async fn execute_prepared_patch( let mut orchestrator = ToolOrchestrator::new(); let mut runtime = ApplyPatchRuntime::new(); let result = orchestrator - .run(&mut runtime, &request, &tool_ctx) + .run(&mut runtime, request, &tool_ctx) .await .map(|result| result.output); let (result, delta) = match result { diff --git a/codex-rs/core/src/tools/handlers/apply_patch_tests.rs b/codex-rs/core/src/tools/handlers/apply_patch_tests.rs index d3efcb48c8..54adc56dbb 100644 --- a/codex-rs/core/src/tools/handlers/apply_patch_tests.rs +++ b/codex-rs/core/src/tools/handlers/apply_patch_tests.rs @@ -94,6 +94,7 @@ async fn post_tool_use_payload_uses_patch_input_and_tool_output() { tool_cwd: None, tool_name: HookToolName::apply_patch(), tool_use_id: "call-apply-patch".to_string(), + parent_tool_use_id: None, tool_input: json!({ "command": patch }), tool_response: json!("Success. Updated files."), }) diff --git a/codex-rs/core/src/tools/handlers/dynamic.rs b/codex-rs/core/src/tools/handlers/dynamic.rs index fc8b82162b..c106a5c879 100644 --- a/codex-rs/core/src/tools/handlers/dynamic.rs +++ b/codex-rs/core/src/tools/handlers/dynamic.rs @@ -300,6 +300,7 @@ impl CoreToolRuntime for DynamicToolHandler { &invocation.turn, &invocation.step_context.environments, &invocation.environments.hook_ids(), + /*tool_cwd*/ None, ); if !hooks.has_post_tool_use_match(tool_name.name(), tool_name.matcher_aliases()) { return None; diff --git a/codex-rs/core/src/tools/handlers/extension_tools.rs b/codex-rs/core/src/tools/handlers/extension_tools.rs index b46fcc7c83..98caa0085b 100644 --- a/codex-rs/core/src/tools/handlers/extension_tools.rs +++ b/codex-rs/core/src/tools/handlers/extension_tools.rs @@ -436,6 +436,7 @@ mod tests { tool_cwd: None, tool_name: HookToolName::new("extension_echo"), tool_use_id: "call-extension".to_string(), + parent_tool_use_id: None, tool_input: json!({ "message": "hello" }), tool_response: json!({ "ok": true }), }) diff --git a/codex-rs/core/src/tools/handlers/mcp.rs b/codex-rs/core/src/tools/handlers/mcp.rs index a0fe01f20e..87758cb4a5 100644 --- a/codex-rs/core/src/tools/handlers/mcp.rs +++ b/codex-rs/core/src/tools/handlers/mcp.rs @@ -658,6 +658,7 @@ impl CoreToolRuntime for McpHandler { tool_cwd: result.post_tool_use_cwd(), tool_name: self.hook_tool_name(), tool_use_id: invocation.call_id.to_string(), + parent_tool_use_id: None, tool_input: result.post_tool_use_input(&invocation.payload)?, tool_response, }) @@ -953,6 +954,7 @@ mod tests { tool_cwd: None, tool_name: HookToolName::new("mcp__filesystem__read_file"), tool_use_id: "call-mcp-post".to_string(), + parent_tool_use_id: None, tool_input: json!({ "path": { "file_id": "file_123" diff --git a/codex-rs/core/src/tools/handlers/mcp_resource_tests.rs b/codex-rs/core/src/tools/handlers/mcp_resource_tests.rs index 868405ce99..4a383b1440 100644 --- a/codex-rs/core/src/tools/handlers/mcp_resource_tests.rs +++ b/codex-rs/core/src/tools/handlers/mcp_resource_tests.rs @@ -190,7 +190,7 @@ fn serialize_function_output_preserves_small_payload() { let output = serialize_function_output(payload, TruncationPolicy::Bytes(1_024)) .expect("serialize function output") - .into_text(); + .log_output(); assert_eq!(output, expected); } @@ -214,7 +214,7 @@ fn serialize_function_output_caps_read_resource_payload() { let output = serialize_function_output(payload, truncation_policy) .expect("serialize bounded function output") - .into_text(); + .log_output(); assert_ne!(output, serialized); assert_eq!(output, expected); diff --git a/codex-rs/core/src/tools/handlers/unified_exec.rs b/codex-rs/core/src/tools/handlers/unified_exec.rs index ec7a7d24aa..7ce563f883 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec.rs @@ -139,10 +139,16 @@ fn post_unified_exec_tool_use_payload( let tool_input = result.post_tool_use_input(&invocation.payload)?; let tool_use_id = result.post_tool_use_id(&invocation.call_id); let tool_response = result.post_tool_use_response(&tool_use_id, &invocation.payload)?; + let committed_tool = result.committed_tool_name(); Some(PostToolUsePayload { tool_cwd: result.post_tool_use_cwd(), - tool_name: HookToolName::bash(), + tool_name: match committed_tool { + Some("apply_patch") => HookToolName::apply_patch(), + Some(name) => HookToolName::new(name), + None => HookToolName::bash(), + }, tool_use_id, + parent_tool_use_id: committed_tool.map(|_| invocation.call_id.to_string()), tool_input, tool_response, }) diff --git a/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs b/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs index 1d946805cd..4b4efdb825 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs @@ -7,6 +7,7 @@ use crate::tools::context::AbortedToolOutput; use crate::tools::context::ExecCommandToolOutput; use crate::tools::context::ToolEnvironments; use crate::tools::context::ToolInvocation; +use crate::tools::context::ToolOutput; use crate::tools::context::ToolPayload; use crate::tools::context::boxed_tool_output; use crate::tools::handlers::ToolEnvironmentArgs; @@ -28,17 +29,20 @@ use crate::unified_exec::UnifiedExecError; use crate::unified_exec::UnifiedExecProcessManager; use crate::unified_exec::generate_chunk_id; use crate::unified_exec::output::CapturedStream; +use codex_code_mode::CodeModeToolResult; use codex_features::Feature; use codex_otel::EXEC_COMMAND_INITIAL_OUTPUT_COLLECTION_COUNT_METRIC; use codex_otel::EXEC_COMMAND_INITIAL_OUTPUT_COLLECTION_TOTAL_METRIC; use codex_otel::SessionTelemetry; use codex_otel::TOOL_CALL_UNIFIED_EXEC_METRIC; +use codex_protocol::models::ResponseInputItem; use codex_tools::JsonSchema; use codex_tools::ToolName; use codex_tools::ToolSpec; use codex_utils_output_truncation::approx_token_count; use codex_utils_path_uri::PathUri; use codex_utils_string::truncate_middle_chars; +use serde_json::Value; use super::super::shell_spec::create_exec_command_tool; use super::ExecCommandArgs; @@ -64,6 +68,49 @@ pub struct ExecCommandHandler { lifetime: ExecCommandLifetime, } +struct InterceptedApplyPatchOutput { + output: ExecCommandToolOutput, + hook_use_id: String, +} + +impl ToolOutput for InterceptedApplyPatchOutput { + fn log_output(&self) -> String { + self.output.log_output() + } + + fn success_for_logging(&self) -> bool { + self.output.success_for_logging() + } + + fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem { + self.output.to_response_item(call_id, payload) + } + + fn code_mode_result(&self, payload: &ToolPayload) -> CodeModeToolResult { + self.output.code_mode_result(payload) + } + + fn committed_tool_name(&self) -> Option<&str> { + Some("apply_patch") + } + + fn post_tool_use_id(&self, _call_id: &str) -> String { + self.hook_use_id.clone() + } + + fn post_tool_use_cwd(&self) -> Option { + self.output.post_tool_use_cwd() + } + + fn post_tool_use_input(&self, payload: &ToolPayload) -> Option { + self.output.post_tool_use_input(payload) + } + + fn post_tool_use_response(&self, _call_id: &str, _payload: &ToolPayload) -> Option { + Some(Value::String(self.output.raw_output.text.clone())) + } +} + impl Default for ExecCommandHandler { fn default() -> Self { Self { @@ -174,10 +221,14 @@ impl ExecCommandHandler { let prepared = parsed.prepare(self.lifetime)?; let max_output_tokens = prepared.max_output_tokens; let fs = prepared.turn_environment.environment().get_filesystem(); + let aborted = || { + boxed_tool_output(AbortedToolOutput::exec_command( + started.elapsed().as_secs_f32().max(0.1), + )) + }; let intercepted_patch = intercept_apply_patch( &prepared.resolved.command, &prepared.cwd, - fs.as_ref(), &prepared.turn_environment, context.session.clone(), Arc::clone(&context.step_context), @@ -187,22 +238,31 @@ impl ExecCommandHandler { "exec_command", ) .await; - if let Some(output) = intercepted_patch? { - return Ok(boxed_tool_output(ExecCommandToolOutput { - event_call_id: String::new(), - chunk_id: String::new(), - wall_time: std::time::Duration::ZERO, - raw_output: CapturedStream { - text: output.into_text(), - omitted_bytes: 0, + let intercepted_patch = match intercepted_patch { + Err(FunctionCallError::Blocked(_)) if context.cancellation_token.is_cancelled() => { + return Ok(aborted()); + } + result => result?, + }; + if let Some(output) = intercepted_patch { + return Ok(boxed_tool_output(InterceptedApplyPatchOutput { + hook_use_id: output.hook_use_id, + output: ExecCommandToolOutput { + event_call_id: String::new(), + chunk_id: String::new(), + wall_time: std::time::Duration::ZERO, + raw_output: CapturedStream { + text: output.content, + omitted_bytes: 0, + }, + truncation_policy: step_context.settings.model_info.truncation_policy.into(), + max_output_tokens, + process_id: None, + exit_code: None, + original_token_count: None, + hook_command: Some(output.patch), + tool_cwd: Some(output.cwd), }, - truncation_policy: step_context.settings.model_info.truncation_policy.into(), - max_output_tokens, - process_id: None, - exit_code: None, - original_token_count: None, - hook_command: None, - tool_cwd: None, })); } @@ -217,11 +277,6 @@ impl ExecCommandHandler { ) .await; // Preparation can be cancelled. Reserve a process only once it is done. - let aborted = || { - boxed_tool_output(AbortedToolOutput::exec_command( - started.elapsed().as_secs_f32().max(0.1), - )) - }; if prepared.completion_timeout.is_none() && context.cancellation_token.is_cancelled() { return Ok(aborted()); } 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 83f5adbb00..0da4b0b084 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec_tests.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec_tests.rs @@ -459,7 +459,7 @@ async fn exec_command_reuses_foreign_windows_grant() { }) .await; - let Err(FunctionCallError::RespondToModel(message)) = response else { + let Err(FunctionCallError::FailedBeforeExecution(message)) = response else { panic!("raw patch should stop before remote execution"); }; assert!( @@ -625,6 +625,7 @@ async fn exec_command_post_tool_use_payload_uses_output_for_noninteractive_one_s tool_cwd: Some(PathUri::parse("file:///C:/workspace").expect("valid Windows cwd")), tool_name: HookToolName::bash(), tool_use_id: "call-43".to_string(), + parent_tool_use_id: None, tool_input: serde_json::json!({ "command": "echo three" }), tool_response: serde_json::json!("three"), }) @@ -658,6 +659,7 @@ async fn exec_command_post_tool_use_payload_uses_output_for_interactive_completi tool_cwd: None, tool_name: HookToolName::bash(), tool_use_id: "call-44".to_string(), + parent_tool_use_id: None, tool_input: serde_json::json!({ "command": "echo three" }), tool_response: serde_json::json!("three"), }) @@ -718,6 +720,7 @@ async fn write_stdin_post_tool_use_payload_uses_original_exec_call_id_and_comman tool_cwd: None, tool_name: HookToolName::bash(), tool_use_id: "exec-call-45".to_string(), + parent_tool_use_id: None, tool_input: serde_json::json!({ "command": "sleep 1; echo finished" }), tool_response: serde_json::json!("finished\n"), }) @@ -773,6 +776,7 @@ async fn write_stdin_post_tool_use_payload_keeps_parallel_session_metadata_separ ), tool_name: HookToolName::bash(), tool_use_id: "exec-call-b".to_string(), + parent_tool_use_id: None, tool_input: serde_json::json!({ "command": "sleep 1; echo beta" }), tool_response: serde_json::json!("beta\n"), }), @@ -782,6 +786,7 @@ async fn write_stdin_post_tool_use_payload_keeps_parallel_session_metadata_separ ), tool_name: HookToolName::bash(), tool_use_id: "exec-call-a".to_string(), + parent_tool_use_id: None, tool_input: serde_json::json!({ "command": "sleep 2; echo alpha" }), tool_response: serde_json::json!("alpha\n"), }), diff --git a/codex-rs/core/src/tools/parallel.rs b/codex-rs/core/src/tools/parallel.rs index bdf7e1fe1a..fe6d2efff3 100644 --- a/codex-rs/core/src/tools/parallel.rs +++ b/codex-rs/core/src/tools/parallel.rs @@ -532,13 +532,7 @@ impl ToolCallRuntime { ToolAbort::BeforeDispatch => AbortedToolOutput { message: "aborted before dispatch".to_string(), }, - ToolAbort::User(secs) - if call.tool_name.is_default_namespace() - && call.tool_name.name == "exec_command" => - { - AbortedToolOutput::exec_command(secs) - } - ToolAbort::User(secs) => AbortedToolOutput::user(secs), + ToolAbort::User(secs) => AbortedToolOutput::by_user(&call.tool_name, secs), }; AnyToolResult { call_id: call.call_id.clone(), diff --git a/codex-rs/core/src/tools/registry.rs b/codex-rs/core/src/tools/registry.rs index 7779afeae6..330769b91f 100644 --- a/codex-rs/core/src/tools/registry.rs +++ b/codex-rs/core/src/tools/registry.rs @@ -393,7 +393,7 @@ pub(crate) struct PreToolUsePayload { #[derive(Debug, Clone, PartialEq)] pub(crate) struct PostToolUsePayload { - /// Local execution cwd used by hook input; remote tools retain the host fallback. + /// Effective execution cwd; dispatch retains the host fallback for remote tools' local hooks. pub(crate) tool_cwd: Option, /// Hook-facing tool name model. /// @@ -402,6 +402,7 @@ pub(crate) struct PostToolUsePayload { pub(crate) tool_name: HookToolName, /// The originating tool-use id exposed at `tool_use_id`. pub(crate) tool_use_id: String, + pub(crate) parent_tool_use_id: Option, /// Tool-specific input exposed at `tool_input`. pub(crate) tool_input: Value, /// Tool result exposed at `tool_response`. @@ -902,7 +903,13 @@ impl ToolRegistry { Ok(environments) => environments, Err(err) => return Err(fail_before_execution(dispatch_trace, &invocation, err).await), }; - match apply_pre_tool_use(tool.as_ref(), &mut invocation).await { + match apply_pre_tool_use( + tool.as_ref(), + &mut invocation, + crate::hook_runtime::PreToolUseContextPolicy::Publish, + ) + .await + { Ok(()) => {} Err(PreToolUseError::Blocked(message)) => { if tool.is_builtin_control_tool() { @@ -1028,6 +1035,7 @@ impl ToolRegistry { let log_payload = tool_log_payload(&invocation.payload, &invocation.source); + let handler_started_at = Instant::now(); let mut result = otel .log_tool_result_with_tags( &tool_name, @@ -1056,54 +1064,53 @@ impl ToolRegistry { }); } emit_metric_for_tool_read(&invocation, success); - let post_tool_use_payload = if success { - result - .as_mut() - .ok() - .and_then(|result| result.post_tool_use_payload.take()) - } 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.step_context.as_ref(), - post_tool_use_payload, - &invocation.environments.hook_ids(), - ) - .or_cancel_tool(&cancellation_token) - .await?, - ) - } else { - None - }; - if let Some(outcome) = &post_tool_use_outcome { - record_additional_contexts( - &invocation.session, - &invocation.turn, - outcome.additional_contexts.clone(), - ) - .or_cancel_tool(&cancellation_token) - .await?; - } - // A PostToolUse block rejects the result, not the already-completed tool execution. let lifecycle_outcome = match &result { - _ if tool.finishes_on_cancellation() - && invocation.cancellation_token.is_cancelled() => - { - ToolCallOutcome::Aborted - } Ok(result) if result.result.was_aborted() => ToolCallOutcome::Aborted, Ok(_) => ToolCallOutcome::Completed { success }, + Err(FunctionCallError::Blocked(_)) => ToolCallOutcome::Blocked, + Err(FunctionCallError::FailedBeforeExecution(_)) => ToolCallOutcome::Failed { + handler_executed: false, + }, Err(_) => ToolCallOutcome::Failed { handler_executed: true, }, }; - drop(invocation_guard); - notify_tool_finish_if_unclaimed(&invocation, call_state.as_deref(), lifecycle_outcome) - .await; + let finish = async { + let outcome = if tool.finishes_on_cancellation() && cancellation_token.is_cancelled() { + ToolCallOutcome::Aborted + } else { + lifecycle_outcome + }; + drop(invocation_guard); + notify_tool_finish_if_unclaimed(&invocation, call_state.as_deref(), outcome).await; + }; + let payload = if success && let Ok(output) = &mut result { + output.post_tool_use_payload.take() + } else { + None + }; + let post = apply_post_tool_use(&invocation, payload); + let post_tool_use_outcome = if let Ok(output) = &mut result + && output.result.committed_tool_name().is_some() + { + // The caller can drop its completion future while a post-hook waits. + finish.await; + match post.await { + Ok(outcome) => outcome, + Err(_) => { + output.result = Box::new(AbortedToolOutput::by_user( + &tool_name, + handler_started_at.elapsed().as_secs_f32().max(0.1), + )); + None + } + } + } else { + let outcome = post.await?; + finish.await; + outcome + }; match result { Ok(result) if result.result.was_aborted() => { @@ -1207,6 +1214,7 @@ pub(crate) enum PreToolUseError { pub(crate) async fn apply_pre_tool_use( tool: &dyn CoreToolRuntime, invocation: &mut ToolInvocation, + context_policy: crate::hook_runtime::PreToolUseContextPolicy, ) -> Result<(), PreToolUseError> { let Some(payload) = tool.pre_tool_use_payload(invocation) else { return Ok(()); @@ -1217,11 +1225,12 @@ pub(crate) async fn apply_pre_tool_use( let outcome = run_pre_tool_use_hooks( &invocation.session, &invocation.step_context, - invocation.call_id.to_string(), - &payload.tool_name, - &payload.tool_input, + &invocation.call_id, + /*parent_tool_use_id*/ None, + &payload, cwd, &invocation.environments.hook_ids(), + context_policy, ) .or_cancel_tool(&invocation.cancellation_token) .await @@ -1248,6 +1257,32 @@ pub(crate) async fn apply_pre_tool_use( } } +/// Only cancellation returns an error. Hook feedback and vetoes are outcomes. +async fn apply_post_tool_use( + invocation: &ToolInvocation, + payload: Option, +) -> Result, FunctionCallError> { + let Some(payload) = payload else { + return Ok(None); + }; + let outcome = run_post_tool_use_hooks( + &invocation.session, + invocation.step_context.as_ref(), + payload, + &invocation.environments.hook_ids(), + ) + .or_cancel_tool(&invocation.cancellation_token) + .await?; + record_additional_contexts( + &invocation.session, + &invocation.turn, + outcome.additional_contexts.clone(), + ) + .or_cancel_tool(&invocation.cancellation_token) + .await?; + Ok(Some(outcome)) +} + pub(super) fn function_post_tool_use_payload( invocation: &ToolInvocation, result: &dyn ToolOutput, @@ -1261,6 +1296,7 @@ pub(super) fn function_post_tool_use_payload( tool_cwd: result.post_tool_use_cwd(), tool_name, tool_use_id: result.post_tool_use_id(&invocation.call_id), + parent_tool_use_id: None, tool_input: result .post_tool_use_input(&invocation.payload) .unwrap_or_else(|| function_hook_tool_input(arguments)), diff --git a/codex-rs/core/src/tools/registry_tests.rs b/codex-rs/core/src/tools/registry_tests.rs index ec2947d66f..d652bd2e3c 100644 --- a/codex-rs/core/src/tools/registry_tests.rs +++ b/codex-rs/core/src/tools/registry_tests.rs @@ -98,6 +98,7 @@ impl CoreToolRuntime for ReadinessTestHandler { enum LifecycleTestResult { Ok { success: bool }, Err, + ErrAfterSideEffect { path: std::path::PathBuf }, } struct LifecycleTestHandler { @@ -119,13 +120,14 @@ impl ToolExecutor for LifecycleTestHandler { invocation.tool_name, self.tool_name.clone().with_default_namespace() ); - Box::pin(self.handle_call()) + Box::pin(self.handle_call(invocation.cancellation_token)) } } impl LifecycleTestHandler { async fn handle_call( &self, + cancellation_token: tokio_util::sync::CancellationToken, ) -> Result, FunctionCallError> { match self.result.clone() { LifecycleTestResult::Ok { success } => Ok(Box::new( @@ -138,6 +140,14 @@ impl LifecycleTestHandler { LifecycleTestResult::Err => Err(FunctionCallError::RespondToModel( "handler failed".to_string(), )), + LifecycleTestResult::ErrAfterSideEffect { path } => { + std::fs::write(path, "partially executed\n") + .expect("write partial execution marker"); + cancellation_token.cancel(); + Err(FunctionCallError::RespondToModel( + "handler failed after writing".to_string(), + )) + } } } } @@ -509,6 +519,7 @@ async fn function_tools_expose_default_hook_payloads_and_rewrites() -> anyhow::R tool_cwd: None, tool_name: HookToolName::new("functions.echo"), tool_use_id: "call-1".to_string(), + parent_tool_use_id: None, tool_input: serde_json::json!({ "message": "hello" }), tool_response: serde_json::json!("echoed"), }) @@ -744,7 +755,12 @@ async fn hook_updates_use_validated_payload_bytes_for_freshness() -> anyhow::Res let step = Arc::make_mut(&mut invocation.step_context); step.hook_rewrote_input = hook_rewrote_input; step.guardian_probe = Some(true); - let result = apply_pre_tool_use(handler.as_ref(), &mut invocation).await; + let result = apply_pre_tool_use( + handler.as_ref(), + &mut invocation, + crate::hook_runtime::PreToolUseContextPolicy::Publish, + ) + .await; assert_eq!(executor.calls.load(Ordering::Relaxed), 1, "{case}"); if let Some(expected) = expected { assert!( @@ -1088,6 +1104,15 @@ async fn dispatch_uses_canonical_tool_names_for_lifecycle_contributors() -> anyh tool_name: failing_tool.clone(), result: LifecycleTestResult::Err, }) as Arc; + let partial_directory = tempfile::tempdir()?; + let partial_path = partial_directory.path().join("partial.txt"); + let partial_tool = codex_tools::ToolName::plain("partially_executed_tool"); + let partial_handler = Arc::new(LifecycleTestHandler { + tool_name: partial_tool.clone(), + result: LifecycleTestResult::ErrAfterSideEffect { + path: partial_path.clone(), + }, + }) as Arc; let reviewed_tool = codex_tools::ToolName::namespaced("extensions", "reviewed_tool"); let reviewed_handler = Arc::new(LifecycleTestHandler { tool_name: reviewed_tool.clone(), @@ -1095,7 +1120,7 @@ async fn dispatch_uses_canonical_tool_names_for_lifecycle_contributors() -> anyh }); builder.approval_review_contributor(reviewed_handler.clone()); session.services.extensions = Arc::new(builder.build()); - let mut registry = ToolRegistry::from_tools([ok_handler, failing_handler]); + let mut registry = ToolRegistry::from_tools([ok_handler, failing_handler, partial_handler]); registry.register_trusted_with_native_review( reviewed_handler, super::ToolExposure::Direct, @@ -1131,6 +1156,27 @@ async fn dispatch_uses_canonical_tool_names_for_lifecycle_contributors() -> anyh Err(err) => err, }; assert_eq!(err.to_string(), "handler failed"); + let partial = registry + .dispatch_any_with_state( + test_invocation( + Arc::clone(&session), + Arc::clone(&turn), + "partial-call", + partial_tool.clone().with_default_namespace(), + ), + /*call_state*/ None, + ) + .await; + assert_eq!( + partial.err(), + Some(FunctionCallError::RespondToModel( + "handler failed after writing".to_string(), + )), + ); + assert_eq!( + std::fs::read_to_string(partial_path)?, + "partially executed\n" + ); let denied = registry .dispatch_any_with_state( test_invocation(session, turn, "reviewed-call", reviewed_tool.clone()), @@ -1165,6 +1211,18 @@ async fn dispatch_uses_canonical_tool_names_for_lifecycle_contributors() -> anyh handler_executed: true, }, }, + RecordedToolLifecycle::Start { + call_id: "partial-call".to_string(), + tool_name: partial_tool.clone().with_default_namespace(), + root_turn_id: Some("root-turn".to_string()), + }, + RecordedToolLifecycle::Finish { + call_id: "partial-call".to_string(), + tool_name: partial_tool.with_default_namespace(), + outcome: codex_extension_api::ToolCallOutcome::Failed { + handler_executed: true, + }, + }, RecordedToolLifecycle::Finish { call_id: "reviewed-call".to_string(), tool_name: reviewed_tool, @@ -1208,3 +1266,261 @@ fn test_invocation( }, } } + +struct CancelledPatchHook { + started: tokio::sync::Notify, + stopped: tokio_util::sync::CancellationToken, + calls: std::sync::Mutex>, + finishes: tokio::sync::mpsc::UnboundedSender<(String, ToolCallOutcome)>, + cancel_on_allow: Option, +} + +impl codex_hooks::HookMcpExecutor for CancelledPatchHook { + fn execute( + &self, + call: codex_hooks::HookMcpCall, + ) -> BoxFuture<'_, anyhow::Result> { + Box::pin(async move { + self.calls.lock().expect("hook calls").push(call); + let _stopped = self.stopped.clone().drop_guard(); + self.started.notify_one(); + if let Some(token) = &self.cancel_on_allow { + // Make the allow reply ready in the same poll that cancels the write. + token.cancel(); + return Ok(codex_hooks::HookMcpOutput { + result: codex_protocol::mcp::CallToolResult { + content: Vec::new(), + structured_content: None, + meta: None, + is_error: None, + }, + source_tool_namespace: None, + }); + } + std::future::pending().await + }) + } +} + +impl codex_extension_api::ToolLifecycleContributor for CancelledPatchHook { + fn on_tool_finish<'a>( + &'a self, + input: codex_extension_api::ToolFinishInput<'a>, + ) -> codex_extension_api::ToolLifecycleFuture<'a> { + Box::pin(async move { + self.finishes + .send((input.call_id.to_string(), input.outcome)) + .expect("record tool finish"); + }) + } +} + +enum PatchCancellationOrder { + HandlerFirst, + WatcherFirst, +} + +enum PatchCancellationPoint { + DuringPreHook, + OnAllow, + DuringPostHook, +} + +#[test_case::test_case(PatchCancellationPoint::DuringPreHook, PatchCancellationOrder::HandlerFirst; "pre_hook_handler_first")] +#[test_case::test_case(PatchCancellationPoint::DuringPreHook, PatchCancellationOrder::WatcherFirst; "pre_hook_watcher_first")] +#[test_case::test_case(PatchCancellationPoint::OnAllow, PatchCancellationOrder::HandlerFirst; "on_allow_before_write")] +#[test_case::test_case(PatchCancellationPoint::DuringPostHook, PatchCancellationOrder::HandlerFirst; "post_hook_handler_first")] +#[test_case::test_case(PatchCancellationPoint::DuringPostHook, PatchCancellationOrder::WatcherFirst; "post_hook_watcher_first")] +#[tokio::test(flavor = "current_thread")] +async fn intercepted_patch_hook_cancellation_reports_execution_outcome( + point: PatchCancellationPoint, + order: PatchCancellationOrder, +) -> anyhow::Result<()> { + let workspace = tempfile::tempdir()?; + let target = workspace.path().join("cancelled-patch.txt"); + std::fs::write(&target, "before\n")?; + let patch = "*** Begin Patch\n*** Update File: cancelled-patch.txt\n@@\n-before\n+after\n*** Add File: unexpected.txt\n+unexpected\n*** End Patch"; + let hook = serde_json::json!({ + "matcher": "^apply_patch$", + "hooks": [{ + "type": "mcp_tool", + "server": "test-hook", + "tool": "wait", + "input": { + "command": "${tool_input.command}", + }, + }], + }); + let post_hook = matches!(point, PatchCancellationPoint::DuringPostHook); + let pre_hooks = if post_hook { + vec![] + } else { + vec![hook.clone()] + }; + std::fs::write( + workspace.path().join("hooks.json"), + serde_json::json!({"hooks": { + "PreToolUse": pre_hooks, + "PostToolUse": [hook], + }}) + .to_string(), + )?; + let config_stack = codex_config::ConfigLayerStack::new( + vec![codex_config::ConfigLayerEntry::new( + codex_config::ConfigLayerSource::User { + file: codex_utils_absolute_path::AbsolutePathBuf::try_from( + workspace.path().join("config.toml"), + )?, + profile: None, + }, + codex_config::TomlValue::Table(Default::default()), + )], + Default::default(), + Default::default(), + )?; + let token = tokio_util::sync::CancellationToken::new(); + let (finish_tx, mut finish_rx) = tokio::sync::mpsc::unbounded_channel(); + let recorder = Arc::new(CancelledPatchHook { + started: tokio::sync::Notify::new(), + stopped: tokio_util::sync::CancellationToken::new(), + calls: std::sync::Mutex::new(Vec::new()), + finishes: finish_tx, + cancel_on_allow: matches!(point, PatchCancellationPoint::OnAllow).then(|| token.clone()), + }); + let (mut session, mut turn) = crate::session::tests::make_session_and_context().await; + let crate::environment_selection::TurnEnvironmentState::Ready(environment) = + &mut turn.initial_environments.environments[0] + else { + panic!("primary environment should be ready"); + }; + environment.config_mut().permission_profile = crate::config::PermissionProfileSnapshot::legacy( + codex_protocol::models::PermissionProfile::Disabled, + ); + let (hooks, _hook_results) = codex_hooks::Hooks::new( + codex_hooks::HooksConfig { + feature_enabled: true, + bypass_hook_trust: true, + config_layer_stack: Some(config_stack), + ..Default::default() + }, + session.thread_id, + recorder.clone(), + )?; + session.services.hooks.store(Arc::new(hooks)); + let mut extensions = codex_extension_api::ExtensionRegistryBuilder::new(); + extensions.tool_lifecycle_contributor(recorder.clone()); + session.services.extensions = Arc::new(extensions.build()); + let session = Arc::new(session); + let turn = Arc::new(turn); + let handler = Arc::new(crate::tools::handlers::ExecCommandHandler::default()); + let router = Arc::new(crate::tools::router::ToolRouter::from_parts( + ToolRegistry::with_handler_for_test(handler), + Vec::new(), + codex_protocol::openai_models::ToolMode::Direct, + BTreeMap::new(), + /*exec_definitions*/ None, + /*tool_namespaces_info*/ None, + &[], + )); + let step = StepContext::for_test(turn).with_tool_router_for_test(router); + let tracker = Arc::new(tokio::sync::Mutex::new( + crate::turn_diff_tracker::TurnDiffTracker::new(), + )); + let runtime = crate::tools::parallel::ToolCallRuntime::new( + Arc::clone(&session), + Arc::clone(&step), + tracker, + ); + let state = Arc::new(ToolCallState::default()); + let call_id = "cancelled-patch"; + // The current-thread runtime lets completion polling select the cancellation ordering. + let completion = runtime.handle_tool_call_with_source( + step, + crate::tools::router::ToolCall { + tool_name: codex_tools::ToolName::plain("exec_command"), + call_id: call_id.into(), + payload: ToolPayload::Function { + arguments: serde_json::json!({ + "cmd": format!("apply_patch <<'PATCH'\n{patch}\nPATCH"), + "workdir": workspace.path(), + "login": false, + }) + .to_string(), + }, + encrypted_function_args: None, + native_call: None, + }, + ToolCallSource::Direct, + token.clone(), + Arc::clone(&state), + ); + let deadline = Duration::from_secs(30); + tokio::time::timeout(deadline, recorder.started.notified()).await?; + assert_eq!( + recorder.calls.lock().expect("hook calls")[0].input, + serde_json::json!({"command": patch}) + .as_object() + .expect("hook input") + .clone(), + ); + let expected = if post_hook { + ToolCallOutcome::Completed { success: true } + } else { + ToolCallOutcome::Aborted + }; + if post_hook { + assert_eq!(std::fs::read_to_string(&target)?, "after\n"); + assert_eq!(state.terminal_outcome.get(), Some(&expected)); + assert_eq!(finish_rx.len(), 1, "write reported before post-hook"); + } + if !matches!(point, PatchCancellationPoint::OnAllow) { + token.cancel(); + } + let mut outcome = None; + if matches!(order, PatchCancellationOrder::HandlerFirst) { + if post_hook { + tokio::time::timeout(deadline, recorder.stopped.cancelled()).await?; + } else { + let finish = tokio::time::timeout(deadline, finish_rx.recv()).await; + assert_eq!(std::fs::read_to_string(&target)?, "before\n"); + outcome = finish?; + } + } + let result = tokio::time::timeout(deadline, completion).await??; + assert!(recorder.stopped.is_cancelled()); + assert_eq!( + outcome.or_else(|| finish_rx.try_recv().ok()), + Some((call_id.to_string(), expected)), + ); + assert!(result.result.was_aborted()); + assert!(result.post_tool_use_payload.is_none()); + let message = result.result.log_output(); + assert!(message.starts_with("Wall time: ")); + assert!(message.ends_with(" seconds\naborted by user")); + assert_eq!( + result.result.to_response_item(call_id, &result.payload), + codex_protocol::models::ResponseInputItem::FunctionCallOutput { + call_id: call_id.to_string(), + output: codex_protocol::models::FunctionCallOutputPayload { + body: codex_protocol::models::FunctionCallOutputBody::Text(message), + success: None, + }, + }, + ); + assert_eq!(state.terminal_outcome.get(), Some(&expected)); + assert!( + finish_rx.try_recv().is_err(), + "only one terminal lifecycle event" + ); + assert_eq!(recorder.calls.lock().expect("hook calls").len(), 1); + assert_eq!( + std::fs::read_to_string(&target)?, + if post_hook { "after\n" } else { "before\n" } + ); + assert_eq!( + workspace.path().join("unexpected.txt").try_exists()?, + post_hook + ); + tokio::time::timeout(deadline, session.hooks().shutdown()).await?; + Ok(()) +} diff --git a/codex-rs/core/src/tools/runtimes/apply_patch.rs b/codex-rs/core/src/tools/runtimes/apply_patch.rs index abf6161267..75b7010b3b 100644 --- a/codex-rs/core/src/tools/runtimes/apply_patch.rs +++ b/codex-rs/core/src/tools/runtimes/apply_patch.rs @@ -167,7 +167,7 @@ impl ToolRuntime for ApplyPatchRunti } fn sandbox_cwd<'a>(&self, req: &'a ApplyPatchRequest) -> Option<&'a PathUri> { - Some(&req.action.cwd) + Some(req.turn_environment.cwd()) } async fn run( diff --git a/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs b/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs index 814e1e62e0..2a973d4a3b 100644 --- a/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs +++ b/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs @@ -183,9 +183,10 @@ async fn approval_keys_include_environment_id() { } #[tokio::test] -async fn sandbox_cwd_uses_patch_action_cwd() { +async fn sandbox_cwd_uses_environment_cwd() { let runtime = ApplyPatchRuntime::new(); let path = std::env::temp_dir() + .join("nested") .join("apply-patch-runtime-sandbox-cwd.txt") .abs(); let req = ApplyPatchRequest { @@ -204,7 +205,7 @@ async fn sandbox_cwd_uses_patch_action_cwd() { permissions_preapproved: false, }; - assert_eq!(runtime.sandbox_cwd(&req), Some(&req.action.cwd)); + assert_eq!(runtime.sandbox_cwd(&req), Some(req.turn_environment.cwd())); } #[tokio::test] diff --git a/codex-rs/core/src/tools/user_messaging_tests.rs b/codex-rs/core/src/tools/user_messaging_tests.rs index cf49b98e3c..97bf6dabbf 100644 --- a/codex-rs/core/src/tools/user_messaging_tests.rs +++ b/codex-rs/core/src/tools/user_messaging_tests.rs @@ -67,6 +67,7 @@ fn messaging_result(name: &str, input: Value, success: bool) -> AnyToolResult { tool_cwd: None, tool_name: HookToolName::new(name), tool_use_id: "message-call".to_owned(), + parent_tool_use_id: None, tool_input: input, tool_response: json!({}), }), diff --git a/codex-rs/core/tests/suite/hooks.rs b/codex-rs/core/tests/suite/hooks.rs index 5b515a7220..cdec6ac816 100644 --- a/codex-rs/core/tests/suite/hooks.rs +++ b/codex-rs/core/tests/suite/hooks.rs @@ -106,6 +106,10 @@ const PERMISSION_REQUEST_ALLOW_REASON: &str = "should not be used for allow"; #[path = "hooks_cwd_tests.rs"] mod cwd_tests; +#[cfg(test)] +#[path = "hooks_intercepted_patch_tests.rs"] +mod intercepted_patch_tests; + #[tokio::test] async fn managed_hook_discovery_failure_rejects_session_startup_when_hooks_enabled() -> Result<()> { let server = start_mock_server().await; @@ -6006,6 +6010,8 @@ async fn post_tool_use_blocks_when_exec_session_completes_via_write_stdin() -> R assert_eq!(post_hook_inputs[0]["hook_event_name"], "PostToolUse"); assert_eq!(post_hook_inputs[0]["tool_name"], "Bash"); assert_eq!(post_hook_inputs[0]["tool_use_id"], start_call_id); + assert_eq!(post_hook_inputs[0].get("parent_tool_use_id"), None); + assert_eq!(post_hook_inputs[0].get("workspace_cwd"), None); assert_eq!(post_hook_inputs[0]["tool_input"]["command"], command); assert!( post_hook_inputs[0]["tool_response"] diff --git a/codex-rs/core/tests/suite/hooks_cwd_tests.rs b/codex-rs/core/tests/suite/hooks_cwd_tests.rs index 3fa45226dc..35cb9729d7 100644 --- a/codex-rs/core/tests/suite/hooks_cwd_tests.rs +++ b/codex-rs/core/tests/suite/hooks_cwd_tests.rs @@ -1,10 +1,13 @@ #![cfg(test)] -//! Tool hooks report local command cwd and retain host cwd for remote commands. +//! Local hooks report command cwd; environment-owned command hooks retain their environment cwd. +//! Remote command paths never replace host-local hook cwd. use super::*; use codex_exec_server::CreateDirectoryOptions; +use codex_protocol::protocol::EnvironmentConfigState; use codex_utils_absolute_path::AbsolutePathBuf; +use core_test_support::test_codex::environment_config_for_selection; use core_test_support::test_codex::local; use pretty_assertions::assert_eq; use test_case::test_case; @@ -222,6 +225,8 @@ async fn invalid_execution_cwd_records_failure_without_running_hooks() -> Result #[test_case(Some("nested"), "rewrite"; "rewritten")] #[test_case(Some("nested"), "delayed"; "completion_in_another_turn")] #[test_case(Some("nested"), "stdin"; "stdin_approval_in_another_turn")] +#[test_case(Some("nested"), "environment_owned"; "environment_owned_completion")] +#[test_case(Some("nested"), "environment_owned_delayed"; "environment_owned_write_stdin_completion")] #[tokio::test] async fn command_hooks_keep_execution_cwd(workdir: Option<&str>, mode: &'static str) -> Result<()> { use codex_protocol::protocol::TurnEnvironmentRequests; @@ -230,9 +235,11 @@ async fn command_hooks_keep_execution_cwd(workdir: Option<&str>, mode: &'static if mode == "stdin" { core_test_support::skip_if_target_windows!(Ok(()), "uses a POSIX read/tty fixture"); } - let later_turn = matches!(mode, "delayed" | "stdin"); + let environment_owned = matches!(mode, "environment_owned" | "environment_owned_delayed"); + let delayed = matches!(mode, "delayed" | "environment_owned_delayed"); + let later_turn = delayed || mode == "stdin"; let server = start_mock_server().await; - let test = test_codex() + let mut builder = test_codex() .with_pre_build_hook(move |home| { let script = format!( r#"import json @@ -261,29 +268,54 @@ elif event == 'PreToolUse' and {mode:?} == 'rewrite': let group = json!([{"matcher": "^(Bash|write_stdin)$", "hooks": [{ "type": "command", "command": format!("python3 {}", script_path.display()), }]}]); - fs::write( - home.join("hooks.json"), - json!({"hooks": { - "PreToolUse": group, "PermissionRequest": group, "PostToolUse": group, - }}) - .to_string(), - ) - .expect("write hook configuration"); + if !environment_owned { + fs::write( + home.join("hooks.json"), + json!({"hooks": { + "PreToolUse": group, "PermissionRequest": group, "PostToolUse": group, + }}) + .to_string(), + ) + .expect("write hook configuration"); + } }) .with_config(move |config| { - trust_discovered_hooks(config); + if environment_owned { + config + .features + .enable(Feature::CodexHooks) + .expect("enable environment-owned hooks"); + } else { + trust_discovered_hooks(config); + } if mode == "stdin" { config .features .enable(Feature::WriteStdinApproval) .expect("enable stdin approval"); } - }) - .build_with_remote_and_local_env(&server) - .await?; + }); + let test = if environment_owned { + builder.build(&server).await? + } else { + builder.build_with_remote_and_local_env(&server).await? + }; // Remote command paths never replace the host cwd in hook input. let local_hook_directory = TempDir::new()?; let mut environments = vec![test.executor_environment().request()]; + if environment_owned { + let mut config = + environment_config_for_selection(&test.config, test.executor_environment().selection()); + config.allow_login_shell = false; + let script_path = test.codex_home_path().join("tool_cwd_hook.py"); + let group = json!([{"matcher": "^Bash$", "hooks": [{ + "type": "command", "command": format!("python3 {}", script_path.display()), + }]}]); + config.environment_hooks = serde_json::from_value(json!({ + "PreToolUse": group, "PostToolUse": group, + }))?; + environments[0].config = EnvironmentConfigState::Ready(config); + } let hook_cwd = if test.executor_environment().environment().is_remote() { let cwd = AbsolutePathBuf::try_from(local_hook_directory.path())?; environments.push(core_test_support::test_codex::local_request(cwd.clone())); @@ -320,14 +352,13 @@ elif event == 'PreToolUse' and {mode:?} == 'rewrite': } let command = if mode == "stdin" { "read -r line; cat cwd-marker.txt" - } else if mode == "delayed" { - match test_target_os() { - TestTargetOs::Windows => { - "while (!(Test-Path release.txt)) { Start-Sleep -Milliseconds 50 }; Get-Content cwd-marker.txt" - } - TestTargetOs::Linux | TestTargetOs::MacOs => { - "while [ ! -f release.txt ]; do sleep 0.05; done; cat cwd-marker.txt" - } + } else if delayed { + if (environment_owned && cfg!(windows)) + || (!environment_owned && test_target_os() == TestTargetOs::Windows) + { + "while (!(Test-Path release.txt)) { Start-Sleep -Milliseconds 50 }; Get-Content cwd-marker.txt" + } else { + "while [ ! -f release.txt ]; do sleep 0.05; done; cat cwd-marker.txt" } } else { "cat cwd-marker.txt" @@ -336,7 +367,7 @@ elif event == 'PreToolUse' and {mode:?} == 'rewrite': // Only the cross-turn cases intentionally return before the command completes. let yield_time_ms = if later_turn { 1000 } else { 30000 }; let mut args = json!({"cmd": command, "login": false, "yield_time_ms": yield_time_ms, - "sandbox_permissions": "require_escalated"}); + "sandbox_permissions": if environment_owned { "use_default" } else { "require_escalated" }}); if mode == "stdin" { args["tty"] = json!(true); } @@ -420,7 +451,9 @@ elif event == 'PreToolUse' and {mode:?} == 'rewrite': let mut post_process_cwd = dunce::canonicalize(&hook_cwd)? .to_string_lossy() .into_owned(); - let expected_hook_cwd = if test.executor_environment().environment().is_remote() { + let expected_hook_cwd = if environment_owned { + root.inferred_native_path_string() + } else if test.executor_environment().environment().is_remote() { post_process_cwd.clone() } else { expected_cwd.inferred_native_path_string() @@ -435,10 +468,10 @@ elif event == 'PreToolUse' and {mode:?} == 'rewrite': ); assert_eq!( fs::read_to_string(&log_path)?.lines().count(), - 2, + if environment_owned { 1 } else { 2 }, "no post hook until completion" ); - if mode == "delayed" { + if delayed { test.fs() .write_file( &expected_cwd.join("release.txt")?, @@ -493,7 +526,9 @@ elif event == 'PreToolUse' and {mode:?} == 'rewrite': ("PermissionRequest", executed_command), ("PostToolUse", executed_command), ] { - if mode == "deny" && event == "PostToolUse" { + if (mode == "deny" && event == "PostToolUse") + || (environment_owned && event == "PermissionRequest") + { continue; } if mode == "stdin" && event == "PostToolUse" { @@ -509,7 +544,8 @@ elif event == 'PreToolUse' and {mode:?} == 'rewrite': })); } expected.push(json!({ - "event": event, "tool_name": "Bash", "cwd": expected_hook_cwd, + "event": event, "tool_name": "Bash", + "cwd": if environment_owned && event == "PostToolUse" && later_turn { other.inferred_native_path_string() } else { expected_hook_cwd.clone() }, "process_cwd": if event == "PostToolUse" { post_process_cwd.clone() } else { dunce::canonicalize(&hook_cwd)?.to_string_lossy().into_owned() }, "tool_input": {"command": event_command}, })); diff --git a/codex-rs/core/tests/suite/hooks_intercepted_patch_tests.rs b/codex-rs/core/tests/suite/hooks_intercepted_patch_tests.rs new file mode 100644 index 0000000000..ca6859d562 --- /dev/null +++ b/codex-rs/core/tests/suite/hooks_intercepted_patch_tests.rs @@ -0,0 +1,785 @@ +#![cfg(test)] + +//! Shell patch interception keeps shell policy checks and the canonical patch hook lifecycle. + +use super::*; +use codex_exec_server::CreateDirectoryOptions; +use codex_extension_api::ExtensionRegistryBuilder; +use codex_extension_api::ToolCallOutcome; +use codex_extension_api::ToolFinishInput; +use codex_extension_api::ToolLifecycleContributor; +use codex_extension_api::ToolLifecycleFuture; +use codex_protocol::models::PermissionProfileSnapshot; +use codex_protocol::permissions::FileSystemAccessMode; +use codex_protocol::permissions::FileSystemPath; +use codex_protocol::permissions::FileSystemSandboxEntry; +use codex_protocol::protocol::EnvironmentConfigState; +use codex_protocol::protocol::TurnEnvironmentSelections; +use codex_utils_absolute_path::AbsolutePathBuf; +use core_test_support::assert_regex_match; +use core_test_support::exec_server::ExecServerProcess; +use core_test_support::test_codex::environment_config_for_selection; +use core_test_support::test_codex::local; +use pretty_assertions::assert_eq; +use std::collections::HashSet; +use std::sync::Mutex; +use test_case::test_case; + +#[derive(Default)] +struct ToolFinishes(Mutex>); + +impl ToolLifecycleContributor for ToolFinishes { + fn on_tool_finish<'a>(&'a self, input: ToolFinishInput<'a>) -> ToolLifecycleFuture<'a> { + Box::pin(async move { + self.0 + .lock() + .expect("tool finish lock") + .push((input.call_id.to_string(), input.outcome)); + }) + } +} + +#[test_case("allow"; "canonical_lifecycle")] +#[test_case("deny_bash"; "shell_policy_blocks")] +#[test_case("deny_patch"; "patch_policy_blocks")] +#[test_case("rewrite"; "rewrite_uses_effective_cwd")] +#[test_case("rewrite_forbidden_original"; "rewrite_precedes_original_permissions")] +#[test_case("rewrite_missing_original"; "rewrite_precedes_original_file_verification")] +#[test_case("rewrite_forbidden_target"; "rewritten_patch_requires_permissions")] +#[test_case("invalid_rewrite"; "invalid_rewrite_does_not_execute")] +#[test_case("environment_rewrite"; "rewrite_cannot_change_environment")] +#[test_case("post_block"; "post_hook_feedback_reaches_model")] +#[test_case("invalid_patch"; "failed_verification_has_no_post")] +#[test_case("deny_relative_glob"; "verification_retains_environment_policy_cwd")] +#[test_case("rewrite_denied_add"; "rewritten_add_retains_environment_policy_cwd")] +#[tokio::test] +async fn intercepted_patch_hooks(mode: &'static str) -> Result<()> { + if mode == "rewrite_forbidden_original" { + skip_if_wine_exec!( + Ok(()), + "Wine does not emulate Windows restricted-token and ACL sandbox semantics" + ); + } + let uses_relative_glob = matches!(mode, "deny_relative_glob" | "rewrite_denied_add"); + if uses_relative_glob { + core_test_support::skip_if_target_windows!( + Ok(()), + "the default Windows restricted-token test backend cannot enforce denied reads" + ); + } + skip_if_no_network!(Ok(())); + let server = start_mock_server().await; + let call_id = "intercepted-patch"; + let patch = match mode { + "invalid_patch" | "rewrite_missing_original" => { + "*** Begin Patch\n*** Update File: missing.txt\n@@\n-before\n+after\n*** End Patch" + } + "rewrite_forbidden_original" => { + "*** Begin Patch\n*** Add File: ../../forbidden.txt\n+forbidden\n*** End Patch" + } + "deny_relative_glob" => { + "*** Begin Patch\n*** Update File: ../../hidden/protected.env\n@@\n-before\n+after\n*** End Patch" + } + _ => "*** Begin Patch\n*** Add File: original.txt\n+original\n*** End Patch", + }; + let rewritten_patch = match mode { + "rewrite_forbidden_target" => { + "*** Begin Patch\n*** Add File: ../../forbidden.txt\n+forbidden\n*** End Patch" + } + "rewrite_denied_add" => { + "*** Begin Patch\n*** Add File: ../../hidden/protected.env\n+after\n*** End Patch" + } + _ => "*** Begin Patch\n*** Add File: rewritten.txt\n+rewritten\n*** End Patch", + }; + let rewritten = matches!( + mode, + "rewrite" | "rewrite_forbidden_original" | "rewrite_missing_original" + ); + let command = format!("cd inner && apply_patch <<'PATCH'\n{patch}\nPATCH"); + let args = json!({ "cmd": command, "workdir": "outer", "login": false }); + let responses = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-1"), + ev_function_call(call_id, "exec_command", &args.to_string()), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_response_created("resp-2"), + ev_assistant_message("msg-1", "done"), + ev_completed("resp-2"), + ]), + ], + ) + .await; + let finishes = Arc::new(ToolFinishes::default()); + let mut extensions = ExtensionRegistryBuilder::new(); + extensions.tool_lifecycle_contributor(finishes.clone()); + let test = test_codex() + .with_extensions(Arc::new(extensions.build())) + .with_pre_build_hook(move |home| { + let script_path = home.join("intercepted_patch_hook.py"); + let log_path = home.join("intercepted_patch_hook.jsonl"); + let script = format!( + r#"import json +from pathlib import Path +import sys + +payload = json.load(sys.stdin) +with Path({log_path}).open("a", encoding="utf-8") as log: + log.write(json.dumps(payload) + "\n") +mode = {mode} +event = payload["hook_event_name"] +name = payload["tool_name"] +if event == "PreToolUse": + if (mode == "deny_bash" and name == "Bash") or (mode == "deny_patch" and name == "apply_patch"): + print(json.dumps({{"hookSpecificOutput": {{"hookEventName": event, "permissionDecision": "deny", "permissionDecisionReason": "denied by " + name}}}})) + elif name == "apply_patch" and (mode.startswith("rewrite") or mode in ("invalid_rewrite", "environment_rewrite")): + patch = {rewritten_patch} + if mode == "invalid_rewrite": + patch = "not a patch" + elif mode == "environment_rewrite": + patch = patch.replace("*** Begin Patch", "*** Begin Patch\n*** Environment ID: another-environment") + print(json.dumps({{"hookSpecificOutput": {{"hookEventName": event, "permissionDecision": "allow", "updatedInput": {{"command": patch}}}}}})) +elif event == "PostToolUse": + if mode == "post_block": + print(json.dumps({{"decision": "block", "reason": "review the intercepted patch"}})) + else: + print(json.dumps({{"hookSpecificOutput": {{"hookEventName": event, "additionalContext": "intercepted patch reviewed"}}}})) +"#, + log_path = serde_json::to_string(&log_path).expect("serialize hook log path"), + mode = serde_json::to_string(mode).expect("serialize hook mode"), + rewritten_patch = serde_json::to_string(rewritten_patch) + .expect("serialize rewritten patch"), + ); + fs::write(&script_path, script).expect("write intercepted patch hook"); + let python = if cfg!(windows) { "python" } else { "python3" }; + let hooks = json!([{ + "type": "command", "command": format!("{python} \"{}\"", script_path.display()), + }]); + let pre = json!({ + "matcher": "Bash|Write", + "hooks": hooks, + }); + let post = json!({ + "matcher": "Edit", + "hooks": hooks, + }); + fs::write( + home.join("hooks.json"), + json!({"hooks": {"PreToolUse": [pre], "PostToolUse": [post]}}).to_string(), + ) + .expect("write intercepted patch hooks config"); + }) + .with_config(trust_discovered_hooks) + .build_with_remote_and_local_env(&server) + .await?; + // Hooks need a host-local executor and cwd even when the patch executor is remote. + let local_hook_directory = TempDir::new()?; + let mut selection = test.executor_environment().selection().clone(); + let root = selection.cwd.clone(); + let outer = root.join("outer")?; + let inner = outer.join("inner")?; + if matches!( + mode, + "rewrite_forbidden_original" | "rewrite_forbidden_target" + ) { + let mut config = environment_config_for_selection(&test.config, &selection); + config.workspace_roots = vec![inner.clone()]; + config.permission_profile = + PermissionProfileSnapshot::legacy(restrictive_workspace_write_profile()); + selection.config = EnvironmentConfigState::Ready(config); + } + if uses_relative_glob { + let mut config = environment_config_for_selection(&test.config, &selection); + let mut file_system = restrictive_workspace_write_profile().file_system_sandbox_policy(); + file_system.entries.push(FileSystemSandboxEntry::new( + FileSystemPath::GlobPattern { + pattern: "hidden/*.env".to_string(), + }, + FileSystemAccessMode::Deny, + )); + config.permission_profile = + PermissionProfileSnapshot::legacy(PermissionProfile::from_runtime_permissions( + &file_system, + NetworkSandboxPolicy::Restricted, + )); + selection.config = EnvironmentConfigState::Ready(config); + let hidden = root.join("hidden")?; + test.fs() + .create_directory( + &hidden, + CreateDirectoryOptions { + recursive: true, + follow_symlinks: true, + }, + /*sandbox*/ None, + ) + .await?; + test.fs() + .write_file( + &hidden.join("protected.env")?, + b"before\n".to_vec(), + Default::default(), + /*sandbox*/ None, + ) + .await?; + } + let mut environments = vec![selection]; + if test.executor_environment().environment().is_remote() { + environments.push(local(AbsolutePathBuf::try_from( + local_hook_directory.path(), + )?)); + } + test.fs() + .create_directory( + &inner, + CreateDirectoryOptions { + recursive: true, + follow_symlinks: true, + }, + /*sandbox*/ None, + ) + .await?; + let (sandbox_policy, permission_profile) = + turn_permission_fields(PermissionProfile::Disabled, test.config.cwd.as_path()); + test.codex + .start_or_steer_turn( + TurnInputRequest::user_input(vec![UserInput::Text { + text: "apply the patch through the command tool".into(), + text_elements: Vec::new(), + }]) + .with_thread_settings(ThreadSettingsOverrides { + environments: Some( + TurnEnvironmentSelections::new(test.config.cwd.clone(), environments) + .into_requests(), + ), + approval_policy: Some(AskForApproval::Never), + sandbox_policy: Some(sandbox_policy), + permission_profile, + ..Default::default() + }), + ) + .await?; + let mut started = Vec::new(); + let mut completed = Vec::new(); + wait_for_event(&test.codex, |event| { + match event { + EventMsg::HookStarted(event) + if matches!( + event.run.event_name, + HookEventName::PreToolUse | HookEventName::PostToolUse + ) => + { + started.push(event.run.id.clone()); + } + EventMsg::HookCompleted(event) + if matches!( + event.run.event_name, + HookEventName::PreToolUse | HookEventName::PostToolUse + ) => + { + completed.push(event.run.id.clone()); + } + _ => {} + } + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; + assert_eq!(started, completed); + assert_eq!(started.len(), started.iter().collect::>().len()); + + let inputs = + read_hook_inputs_from_log(&test.codex_home_path().join("intercepted_patch_hook.jsonl"))?; + let actual = inputs + .iter() + .map(|input| { + json!({ + "event": input["hook_event_name"], + "tool": input["tool_name"], + "id": input["tool_use_id"], + "parent_id": input["parent_tool_use_id"], + "command": input["tool_input"]["command"], + }) + }) + .collect::>(); + let mut expected = vec![json!({ + "event": "PreToolUse", "tool": "Bash", "id": call_id, "parent_id": null, "command": command, + })]; + let patch_hook_id = if mode == "deny_bash" { + None + } else { + let id = inputs[1]["tool_use_id"].as_str().context("patch hook id")?; + assert!(!id.is_empty()); + assert_ne!(id, call_id); + Some(id) + }; + if mode != "deny_bash" { + expected.push(json!({ + "event": "PreToolUse", "tool": "apply_patch", "id": patch_hook_id, + "parent_id": call_id, "command": patch, + })); + } + let applied = matches!(mode, "allow" | "post_block") || rewritten; + if applied { + assert_eq!( + *finishes.0.lock().expect("tool finish lock"), + vec![( + call_id.to_string(), + ToolCallOutcome::Completed { success: true }, + )], + ); + expected.push(json!({ + "event": "PostToolUse", "tool": "apply_patch", "id": patch_hook_id, + "parent_id": call_id, + "command": if rewritten { rewritten_patch } else { patch }, + })); + let tool_response = inputs.last().context("PostToolUse input")?["tool_response"] + .as_str() + .context("patch tool_response")?; + let filename = if rewritten { + "rewritten.txt" + } else { + "original.txt" + }; + assert_regex_match( + &format!( + r"\AExit code: 0\nWall time: [0-9.]+ seconds\nOutput:\nSuccess\. Updated the following files:\nA {}\n\z", + regex_lite::escape(filename), + ), + tool_response, + ); + } else if matches!(mode, "deny_bash" | "deny_patch") { + assert_eq!( + *finishes.0.lock().expect("tool finish lock"), + vec![(call_id.to_string(), ToolCallOutcome::Blocked)], + ); + } else if matches!(mode, "invalid_rewrite" | "environment_rewrite") { + assert_eq!( + *finishes.0.lock().expect("tool finish lock"), + vec![( + call_id.to_string(), + ToolCallOutcome::Failed { + handler_executed: false, + }, + )], + ); + } + assert_eq!(actual, expected); + assert_eq!(started.len(), expected.len()); + assert_eq!(inputs[0].get("workspace_cwd"), None); + let remote = test.executor_environment().environment().is_remote(); + for input in &inputs { + let marker = (remote || input["tool_name"] == "apply_patch").then_some(json!(remote)); + assert_eq!(input.get("tool_target_is_remote"), marker.as_ref()); + } + if !remote { + assert_eq!(inputs[0]["cwd"], outer.inferred_native_path_string()); + for input in &inputs[1..] { + assert_eq!(input["cwd"], inner.inferred_native_path_string()); + assert_eq!(input["workspace_cwd"], root.inferred_native_path_string()); + } + } else { + for input in &inputs { + assert_eq!( + input["cwd"], + local_hook_directory.path().to_string_lossy().as_ref(), + ); + } + for input in &inputs[1..] { + assert_eq!(input["workspace_cwd"], input["cwd"]); + } + } + let mut expected_files = vec![ + ( + "original.txt", + matches!(mode, "allow" | "post_block").then_some("original\n"), + ), + ("rewritten.txt", rewritten.then_some("rewritten\n")), + ("../../forbidden.txt", None), + ]; + if uses_relative_glob { + expected_files.push(("../../hidden/protected.env", Some("before\n"))); + } + for (name, expected) in expected_files { + let content = test + .fs() + .read_file_text( + &inner.join(name)?, + Default::default(), + /*sandbox*/ None, + ) + .await; + match expected { + Some(expected) => assert_eq!(content?, expected), + None => assert_eq!( + content + .expect_err("patch should not create the file") + .kind(), + std::io::ErrorKind::NotFound, + ), + } + } + let requests = responses.requests(); + let output = requests[1] + .function_call_output_text(call_id) + .context("command output")?; + match mode { + "deny_bash" => assert!(output.contains("denied by Bash"), "{output}"), + "deny_patch" => assert!(output.contains("denied by apply_patch"), "{output}"), + "rewrite_denied_add" => assert!(output.contains("Failed to write file"), "{output}"), + "invalid_rewrite" | "invalid_patch" | "deny_relative_glob" => { + assert!( + output.contains("apply_patch verification failed"), + "{output}" + ); + if mode == "deny_relative_glob" { + assert!(output.contains("Failed to read"), "{output}"); + } + } + "environment_rewrite" => assert!( + output.contains("PreToolUse hook cannot change the tool environment"), + "{output}" + ), + "rewrite_forbidden_target" => { + assert!(output.contains("patch rejected:"), "{output}"); + assert!( + output.contains("writing outside of the project"), + "{output}" + ); + } + "post_block" => { + assert!(output.contains("review the intercepted patch"), "{output}"); + assert!(!output.contains("Success."), "{output}"); + } + "allow" | "rewrite" | "rewrite_forbidden_original" | "rewrite_missing_original" => { + assert!(output.contains("Success."), "{output}"); + assert!( + requests[1] + .message_input_texts("developer") + .contains(&"intercepted patch reviewed".to_string()), + ); + } + _ => unreachable!("unknown test case"), + } + Ok(()) +} + +#[test_case("allow", "dev"; "conflicting_header_allow")] +#[test_case("echo", "dev"; "conflicting_header_identical_update")] +#[test_case("allow", "prod"; "matching_header_allow")] +#[test_case("echo", "prod"; "matching_header_identical_update")] +#[test_case("direct", "prod"; "direct_with_matching_header")] +#[tokio::test] +async fn intercepted_patch_header_matches_selected_environment( + mode: &'static str, + header: &'static str, +) -> Result<()> { + skip_if_no_network!(Ok(())); + let server = start_mock_server().await; + let prod_executor = ExecServerProcess::start().await?; + let dev_executor = ExecServerProcess::start().await?; + let prod_root = TempDir::new()?; + let dev_root = TempDir::new()?; + for root in [&prod_root, &dev_root] { + fs::write(root.path().join("original.txt"), "before\n")?; + } + let finishes = Arc::new(ToolFinishes::default()); + let mut extensions = ExtensionRegistryBuilder::new(); + extensions.tool_lifecycle_contributor(finishes.clone()); + let test = test_codex() + .with_extensions(Arc::new(extensions.build())) + .with_pre_build_hook(move |home| { + let script_path = home.join("patch_environment_hook.py"); + let log_path = home.join("patch_environment_hook.jsonl"); + let script = format!( + r#"import json +from pathlib import Path +import sys + +payload = json.load(sys.stdin) +with Path({log_path}).open("a", encoding="utf-8") as log: + log.write(json.dumps(payload) + "\n") +output = {{"hookEventName": "PreToolUse", "permissionDecision": "allow"}} +if {mode} == "echo": + output["updatedInput"] = payload["tool_input"] +print(json.dumps({{"hookSpecificOutput": output}})) +"#, + log_path = serde_json::to_string(&log_path).expect("serialize hook log path"), + mode = serde_json::to_string(mode).expect("serialize hook mode"), + ); + fs::write(&script_path, script).expect("write environment hook"); + fs::write(&log_path, "").expect("initialize environment hook log"); + let python = if cfg!(windows) { "python" } else { "python3" }; + fs::write( + home.join("hooks.json"), + json!({"hooks": {"PreToolUse": [{ + "matcher": "^apply_patch$", + "hooks": [{ + "type": "command", + "command": format!("{python} \"{}\"", script_path.display()), + }], + }]}}) + .to_string(), + ) + .expect("write environment hook configuration"); + }) + .with_config(trust_discovered_hooks) + .build(&server) + .await?; + let manager = test.thread_manager.environment_manager(); + let mut environments = Vec::new(); + for (id, executor, root) in [ + ("prod", &prod_executor, &prod_root), + ("dev", &dev_executor, &dev_root), + ] { + manager.upsert_environment( + id.to_string(), + executor.websocket_url.clone(), + /*connect_timeout*/ None, + )?; + manager + .get_environment(id) + .context("registered environment")? + .wait_until_ready() + .await?; + let mut selection = local(AbsolutePathBuf::try_from(root.path())?); + selection.environment_id = id.to_string(); + let mut config = environment_config_for_selection(&test.config, &selection); + config.permission_profile = PermissionProfileSnapshot::legacy(PermissionProfile::Disabled); + config.allow_login_shell = false; + let log = selection + .cwd + .join("owner.jsonl")? + .inferred_native_path_string(); + config.environment_hooks = serde_json::from_value(owner_patch_hooks(&log))?; + selection.config = EnvironmentConfigState::Ready(config); + environments.push(selection); + } + environments.push(local(test.config.cwd.clone())); + let call_id = "selected-environment-patch"; + let patch = format!( + "*** Begin Patch\n*** Environment ID: {header}\n*** Update File: original.txt\n@@\n-before\n+after\n*** End Patch" + ); + let args = json!({ + "cmd": format!("apply_patch <<'PATCH'\n{patch}\nPATCH"), + "environment_id": "prod", + "login": false, + }); + let call = if mode == "direct" { + core_test_support::responses::ev_custom_tool_call(call_id, "apply_patch", &patch) + } else { + ev_function_call(call_id, "exec_command", &args.to_string()) + }; + let responses = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-1"), + call, + ev_completed("resp-1"), + ]), + sse(vec![ + ev_response_created("resp-2"), + ev_assistant_message("msg-1", "done"), + ev_completed("resp-2"), + ]), + ], + ) + .await; + test.submit_turn_with_environments("apply the patch in prod", Some(environments)) + .await?; + let inputs = + read_hook_inputs_from_log(&test.codex_home_path().join("patch_environment_hook.jsonl"))?; + let requests = responses.requests(); + let output = if mode == "direct" { + requests[1] + .custom_tool_call_output_content_and_success(call_id) + .and_then(|(output, _)| output) + } else { + requests[1].function_call_output_text(call_id) + } + .context("patch output")?; + let owner_log = prod_root.path().join("owner.jsonl"); + assert!(!dev_root.path().join("owner.jsonl").exists()); + let outcome = if header == "prod" { + assert!(output.contains("Success."), "{output}"); + assert_eq!(inputs.len(), 1); + assert_eq!(inputs[0]["tool_input"], json!({"command": patch})); + assert_eq!(inputs[0]["tool_target_is_remote"], true); + let owner_inputs = read_hook_inputs_from_log(&owner_log)?; + assert_eq!(owner_inputs.len(), 2); + for (input, event) in owner_inputs.iter().zip(["PreToolUse", "PostToolUse"]) { + assert_eq!(input["hook_event_name"], event); + assert_eq!(input["tool_target_is_remote"], false); + assert_eq!(input["tool_input"], json!({"command": patch})); + assert_eq!(input["cwd"], json!(prod_root.path())); + } + ToolCallOutcome::Completed { success: true } + } else { + assert!(output.contains("environment"), "{output}"); + assert_eq!(inputs, Vec::::new()); + assert!(!owner_log.exists()); + ToolCallOutcome::Failed { + handler_executed: false, + } + }; + assert_eq!( + *finishes.0.lock().expect("tool finish lock"), + vec![(call_id.to_string(), outcome)], + ); + assert_eq!( + fs::read_to_string(prod_root.path().join("original.txt"))?, + if header == "prod" { + "after\n" + } else { + "before\n" + }, + ); + assert_eq!( + fs::read_to_string(dev_root.path().join("original.txt"))?, + "before\n", + ); + Ok(()) +} + +#[tokio::test] +async fn environment_owned_patch_hooks_keep_effective_cwd() -> Result<()> { + skip_if_no_network!(Ok(())); + let server = start_mock_server().await; + let test = test_codex() + .with_config(|config| { + config + .features + .enable(Feature::CodexHooks) + .expect("enable hooks"); + }) + .build_with_auto_env(&server) + .await?; + let mut selection = test.executor_environment().selection().clone(); + let root = selection.cwd.clone(); + let inner = root.join("outer/inner")?; + test.fs() + .create_directory( + &inner, + CreateDirectoryOptions { + recursive: true, + follow_symlinks: true, + }, + /*sandbox*/ None, + ) + .await?; + let root_file = root.join("original.txt")?; + test.fs() + .write_file( + &root_file, + b"root sentinel\n".to_vec(), + Default::default(), + /*sandbox*/ None, + ) + .await?; + let log_file = root.join("environment_patch_hook.jsonl")?; + let mut config = environment_config_for_selection(&test.config, &selection); + config.allow_login_shell = false; + config.permission_profile = PermissionProfileSnapshot::legacy(PermissionProfile::Disabled); + config.environment_hooks = + serde_json::from_value(owner_patch_hooks(&log_file.inferred_native_path_string()))?; + selection.config = EnvironmentConfigState::Ready(config); + let call_id = "environment-patch-cwd"; + let patch = "*** Begin Patch\n*** Add File: original.txt\n+inner edit\n*** End Patch"; + let command = format!("cd inner && apply_patch <<'PATCH'\n{patch}\nPATCH"); + let args = json!({"cmd": command, "workdir": "outer", "login": false}); + let responses = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-1"), + ev_function_call(call_id, "exec_command", &args.to_string()), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_response_created("resp-2"), + ev_assistant_message("msg-1", "done"), + ev_completed("resp-2"), + ]), + ], + ) + .await; + test.submit_turn_with_environments("apply the nested patch", Some(vec![selection])) + .await?; + + let requests = responses.requests(); + let output = requests[1] + .function_call_output_text(call_id) + .context("command output")?; + assert!(output.contains("Success."), "{output}"); + for (path, expected) in [ + (root_file, "root sentinel\n"), + (inner.join("original.txt")?, "inner edit\n"), + ] { + assert_eq!( + test.fs() + .read_file_text(&path, Default::default(), /*sandbox*/ None) + .await + .with_context(|| format!("read patch target {path}"))?, + expected, + ); + } + let inputs = test + .fs() + .read_file_text(&log_file, Default::default(), /*sandbox*/ None) + .await + .context("read environment-owned hook log")?; + let inputs = inputs + .lines() + .map(serde_json::from_str::) + .collect::, _>>()?; + let patch_hook_id = inputs[0]["tool_use_id"].as_str().context("patch hook id")?; + assert!(!patch_hook_id.is_empty()); + assert_ne!(patch_hook_id, call_id); + assert_eq!( + inputs + .iter() + .map(|input| json!({ + "event": input["hook_event_name"], + "tool": input["tool_name"], + "id": input["tool_use_id"], + "parent_id": input["parent_tool_use_id"], + "tool_target_is_remote": input["tool_target_is_remote"], + "workspace_cwd": input["workspace_cwd"], + "cwd": input["cwd"], + "input": input["tool_input"], + "transcript_path": input["transcript_path"], + })) + .collect::>(), + ["PreToolUse", "PostToolUse"] + .map(|event| json!({ + "event": event, + "tool": "apply_patch", + "id": patch_hook_id, + "parent_id": call_id, + "tool_target_is_remote": false, + "workspace_cwd": root.inferred_native_path_string(), + "cwd": inner.inferred_native_path_string(), + "input": {"command": patch}, + "transcript_path": null, + })) + .to_vec(), + ); + Ok(()) +} + +fn owner_patch_hooks(log_path: &str) -> Value { + let unix_path = log_path.replace('\'', "'\\''"); + let windows_path = log_path.replace('\'', "''"); + let group = json!({ + "matcher": "^apply_patch$", + "hooks": [{ + "type": "command", + "command": format!("{{ cat; printf '\\n'; }} >> '{unix_path}'"), + "command_windows": format!("ForEach-Object {{ Add-Content -LiteralPath '{windows_path}' -Value $_ }}"), + }], + }); + json!({"PreToolUse": [group], "PostToolUse": [group]}) +} diff --git a/codex-rs/core/tests/suite/scenarios_guardian_direct_review.rs b/codex-rs/core/tests/suite/scenarios_guardian_direct_review.rs index 84872a2854..2f3f9e1577 100644 --- a/codex-rs/core/tests/suite/scenarios_guardian_direct_review.rs +++ b/codex-rs/core/tests/suite/scenarios_guardian_direct_review.rs @@ -6,6 +6,7 @@ use codex_core::TurnInputRequest; use codex_core::config::Constrained; use codex_core::guardian_review::GuardianReviewResult; use codex_core::guardian_review::RecordedReviewMode; +use codex_exec_server::CreateDirectoryOptions; use codex_features::Feature; use codex_history::RolloutItem; use codex_protocol::ThreadId; @@ -40,6 +41,7 @@ use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; use pretty_assertions::assert_eq; use serde_json::json; +use std::path::Path; use std::sync::Arc; use std::time::Duration; use tempfile::TempDir; @@ -276,23 +278,81 @@ async fn direct_patch_review_matches_live_action_without_writes( snapshot_name: &str, ) -> Result<()> { skip_if_no_network!(Ok(())); - let builder = test_codex().with_model("gpt-5.5").with_config(|config| { - super::configure_scenario_catalog(config); - config.approvals_reviewer = ApprovalsReviewer::AutoReview; - config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest); - config - .permissions - .set_permission_profile(PermissionProfile::read_only()) - .expect("read-only permissions"); - }); - let harness = TestCodexHarness::with_auto_env_builder(builder).await?; - let test = harness.test(); - harness - .write_file("guardian-direct.txt", "before\n") - .await?; - let patch = "*** Begin Patch\n*** Update File: guardian-direct.txt\n@@\n-before\n+after\n*** End Patch"; + let rewritten_patch = patch.replace("+after", "+hook-rewritten"); + let updated_input = json!({"command": rewritten_patch}); + let mut builder = test_codex() + .with_model("gpt-5.5") + .with_pre_build_hook(move |home| { + write_patch_review_hook( + home, + PatchReviewHook::Reply( + json!({"permissionDecision": "allow", "updatedInput": updated_input}), + ), + ) + .expect("write patch review hook"); + }) + .with_config(|config| { + super::configure_scenario_catalog(config); + core_test_support::hooks::trust_discovered_hooks(config); + config.approvals_reviewer = ApprovalsReviewer::AutoReview; + config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest); + config + .permissions + .set_permission_profile(PermissionProfile::read_only()) + .expect("read-only permissions"); + }); + let server = responses::start_mock_server().await; + let test = builder.build_with_remote_and_local_env(&server).await?; + let local_hook_directory = TempDir::new()?; + if test.executor_environment().environment().is_remote() { + test.codex + .update_thread_settings(ThreadSettingsOverrides { + environments: Some(TurnEnvironmentRequests::new( + test.config.cwd.clone(), + vec![ + test.executor_environment().request(), + local_request(AbsolutePathBuf::try_from(local_hook_directory.path())?), + ], + )), + ..Default::default() + }) + .await?; + } + let mut call = patch_call("patch-review", patch); + let intercepted = call["item"]["type"] == "function_call"; + let patch_cwd = if intercepted { + call["item"]["arguments"] = json!( + json!({ + "cmd": format!("cd inner && apply_patch <<'EOF'\n{patch}\nEOF\n"), + "workdir": "outer", + }) + .to_string() + ); + test.workspace_path_uri("outer/inner")? + } else { + test.executor_environment().selection().cwd.clone() + }; + let file_path = patch_cwd.join("guardian-direct.txt")?; + test.fs() + .create_directory( + &patch_cwd, + CreateDirectoryOptions { + recursive: true, + follow_symlinks: true, + }, + /*sandbox*/ None, + ) + .await?; + test.fs() + .write_file( + &file_path, + b"before\n".to_vec(), + Default::default(), + /*sandbox*/ None, + ) + .await?; let assessment = json!({ "risk_level": "low", "user_authorization": "high", @@ -300,13 +360,10 @@ async fn direct_patch_review_matches_live_action_without_writes( "rationale": "The patch is authorized." }); let mock = responses::mount_sse_sequence( - harness.server(), + &server, vec![ // Normal execution: propose the patch, deny approval, then finish the turn. - sse(vec![ - patch_call("patch-review", patch), - ev_completed("parent-action"), - ]), + sse(vec![call, ev_completed("parent-action")]), sse(vec![ ev_assistant_message("live-denial", r#"{"outcome":"deny"}"#), ev_completed("live-review"), @@ -328,7 +385,9 @@ async fn direct_patch_review_matches_live_action_without_writes( let prompt = "Change guardian-direct.txt from before to after."; test.submit_text_turn(prompt).await?; assert_eq!( - harness.read_file_text("guardian-direct.txt").await?, + test.fs() + .read_file_text(&file_path, Default::default(), /*sandbox*/ None) + .await?, "before\n" ); @@ -373,7 +432,9 @@ async fn direct_patch_review_matches_live_action_without_writes( ); // 3. Verify no writes despite approval, and parity with the normal review input. assert_eq!( - harness.read_file_text("guardian-direct.txt").await?, + test.fs() + .read_file_text(&file_path, Default::default(), /*sandbox*/ None) + .await?, "before\n" ); @@ -381,22 +442,89 @@ async fn direct_patch_review_matches_live_action_without_writes( let [_, live_review_request, _, direct_review_request] = requests.as_slice() else { panic!("expected parent, live review, parent, direct review"); }; + let planned_action = |request: &ResponsesRequest| { + request + .input() + .iter() + .filter_map(|item| item["content"].as_array()) + .flatten() + .filter_map(|part| { + serde_json::from_str::(part["text"].as_str()?).ok() + }) + .find(|value| value["tool"] == "apply_patch") + .expect("patch action") + }; + let expected_action = json!({ + "cwd": patch_cwd.inferred_native_path_string(), + "environment_id": test.executor_environment().selection().environment_id, + "files": [file_path.inferred_native_path_string()], + "patch": rewritten_patch, + "tool": "apply_patch", + }); + assert_eq!(planned_action(live_review_request), expected_action); + assert_eq!(planned_action(direct_review_request), expected_action); + let inputs = std::fs::read_to_string(test.codex_home_path().join("patch_review_hooks.jsonl"))? + .lines() + .map(serde_json::from_str::) + .collect::, _>>()?; + let calls = inputs + .iter() + .map(|input| { + json!({ + "event": input["hook_event_name"], "tool": input["tool_name"], + "id": input["tool_use_id"], + "parent_id": input["parent_tool_use_id"], + "workspace_cwd": input["workspace_cwd"], + }) + }) + .collect::>(); + let mut expected_calls = Vec::new(); + let workspace_cwd = if test.executor_environment().environment().is_remote() { + local_hook_directory.path().display().to_string() + } else { + test.executor_environment() + .selection() + .cwd + .inferred_native_path_string() + }; + let patch_hook_ids = inputs + .iter() + .filter(|input| input["tool_name"] == "apply_patch") + .map(|input| input["tool_use_id"].clone()) + .collect::>(); + assert_eq!(patch_hook_ids.len(), 2); + if intercepted { + assert_ne!(patch_hook_ids[0], patch_hook_ids[1]); + } + for patch_hook_id in patch_hook_ids { + if intercepted { + assert_ne!(patch_hook_id, json!("patch-review")); + expected_calls.push(json!({ + "event": "PreToolUse", "tool": "Bash", "id": "patch-review", "parent_id": null, + "workspace_cwd": null, + })); + } else { + assert_eq!(patch_hook_id, json!("patch-review")); + } + expected_calls.push(json!({ + "event": "PreToolUse", "tool": "apply_patch", "id": patch_hook_id, + "parent_id": intercepted.then_some("patch-review"), + "workspace_cwd": intercepted.then_some(&workspace_cwd), + })); + } + assert_eq!(calls, expected_calls); assert_eq!( model_input(direct_review_request, direct.thread_id)?, model_input(live_review_request, history.thread_id)? ); let snapshot = context_snapshot::format_request_history_snapshot( - "Live and direct Guardian review of a patch; direct approval leaves the file unchanged.", + "Live and direct Guardian review of a hook-rewritten patch; direct approval leaves the file unchanged.", &requests, &ContextSnapshotOptions::default().rewrite_known_segments(), ); let environment = test.executor_environment().selection(); - let cwd = serde_json::to_string(&environment.cwd.inferred_native_path_string())?; - let file = serde_json::to_string( - &test - .workspace_path_uri("guardian-direct.txt")? - .inferred_native_path_string(), - )?; + let cwd = serde_json::to_string(&patch_cwd.inferred_native_path_string())?; + let file = serde_json::to_string(&file_path.inferred_native_path_string())?; let environment_id = serde_json::to_string(&environment.environment_id)?; let snapshot = snapshot .replace(&file.replace('\\', "\\\\"), "\"/guardian-direct.txt\"") @@ -404,6 +532,12 @@ async fn direct_patch_review_matches_live_action_without_writes( .replace(&file, "\"/guardian-direct.txt\"") .replace(&cwd, "\"\"") .replace(&environment_id, "\"\""); + // Execution-tool schemas vary between local and remote fixtures. The assertions above + // compare the complete live and direct model inputs before snapshot normalization. + let snapshot = regex_lite::Regex::new( + r"(?m)(^00:additional_tools/developer \(\d+; hash=|^ +- namespace/functions; hash=)[0-9a-f]{16}", + )? + .replace_all(&snapshot, "${1}"); insta::assert_snapshot!(snapshot_name, snapshot); direct.thread.shutdown_and_wait().await?; test.codex.shutdown_and_wait().await?; @@ -416,15 +550,26 @@ enum OriginalScoreDelivery { DuringReview, } -#[test_case::test_case(OriginalScoreDelivery::BeforeRewrite, "+hook-rewritten"; "rewritten_child")] -#[test_case::test_case(OriginalScoreDelivery::DuringReview, "+hook-rewritten"; "rewritten_child_during_review")] -#[test_case::test_case(OriginalScoreDelivery::BeforeRewrite, "+after"; "unchanged_input")] +#[derive(Clone, Copy, PartialEq, Eq)] +enum PatchRewriteLocation { + CanonicalPatch, + BashInCodeMode, + Bash, +} + +#[test_case::test_case(OriginalScoreDelivery::BeforeRewrite, PatchRewriteLocation::CanonicalPatch, "+hook-rewritten"; "published_score")] +#[test_case::test_case(OriginalScoreDelivery::DuringReview, PatchRewriteLocation::CanonicalPatch, "+hook-rewritten"; "in_flight_score")] +#[test_case::test_case(OriginalScoreDelivery::BeforeRewrite, PatchRewriteLocation::BashInCodeMode, "+hook-rewritten"; "generic_rewrite_after_wrapper_score")] +#[test_case::test_case(OriginalScoreDelivery::DuringReview, PatchRewriteLocation::BashInCodeMode, "+hook-rewritten"; "rewritten_child_during_review")] +#[test_case::test_case(OriginalScoreDelivery::BeforeRewrite, PatchRewriteLocation::Bash, "+after"; "unchanged_input")] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn intercepted_patch_rewrite_requires_fresh_guardian_review( delivery: OriginalScoreDelivery, + location: PatchRewriteLocation, replacement_line: &str, ) -> Result<()> { skip_if_no_network!(Ok(())); + let code_mode = location == PatchRewriteLocation::BashInCodeMode; let server = responses::start_sse_server().await; let hook_gate = TcpListener::bind("127.0.0.1:0").await?; let hook_port = hook_gate.local_addr()?.port(); @@ -489,14 +634,18 @@ async fn intercepted_patch_rewrite_requires_fresh_guardian_review( .await; } let args = json!({"cmd": format!("apply_patch <<'PATCH'\n{patch}\nPATCH"), "login": false}); - let call = if input_is_rewritten { - responses::ev_custom_tool_call( + let call = match location { + PatchRewriteLocation::BashInCodeMode => responses::ev_custom_tool_call( "patch-rewrite", "exec", &format!("// @exec: {{\"yield_time_ms\": 180000}}\nawait tools.exec_command({args});"), - ) - } else { - ev_function_call("patch-rewrite", "exec_command", &args.to_string()) + ), + PatchRewriteLocation::Bash => { + ev_function_call("patch-rewrite", "exec_command", &args.to_string()) + } + PatchRewriteLocation::CanonicalPatch => { + ev_apply_patch_exec_command_call_via_heredoc("patch-rewrite", patch) + } }; let mut events = Vec::new(); if !input_is_rewritten { @@ -541,12 +690,12 @@ if payload["tool_input"]["command"] != "echo score-seed": "# ), ) - .expect("write gated Bash hook"); + .expect("write gated rewrite hook"); let python = if cfg!(windows) { "python" } else { "python3" }; std::fs::write( home.join("hooks.json"), json!({"hooks": {"PreToolUse": [{ - "matcher": "^Bash$", + "matcher": if location == PatchRewriteLocation::CanonicalPatch { "^apply_patch$" } else { "^Bash$" }, "hooks": [{ "type": "command", "command": format!("{python} \"{}\"", script_path.display()), @@ -554,9 +703,9 @@ if payload["tool_input"]["command"] != "echo score-seed": }]}}) .to_string(), ) - .expect("write Bash hook configuration"); + .expect("write rewrite hook configuration"); std::fs::write(home.join("config.toml"), - format!("[features.guardianv2]\nenabled = true\npersist_scores = true\nmax_tool_call_lag = 1\n[features.guardianv2.review_scope]\ncomputer_use_only = false\nsandboxed_exec_commands = {}\n", !input_is_rewritten), + format!("[features.guardianv2]\nenabled = true\npersist_scores = true\nmax_tool_call_lag = 1\n[features.guardianv2.review_scope]\ncomputer_use_only = false\nsandboxed_exec_commands = {}\n", !code_mode), ).expect("write Guardian configuration"); }) .with_model_info_override("guardian-patch-parent", |model| { @@ -569,7 +718,7 @@ if payload["tool_input"]["command"] != "echo score-seed": config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest); config.permissions.set_permission_profile(PermissionProfile::read_only()) .expect("read-only permissions"); - config.features.set_enabled(Feature::CodeMode, input_is_rewritten) + config.features.set_enabled(Feature::CodeMode, code_mode) .expect("configure Code Mode"); }); let test = builder.build_with_remote_and_local_env(&server).await?; @@ -636,7 +785,11 @@ if payload["tool_input"]["command"] != "echo score-seed": if delivery == OriginalScoreDelivery::BeforeRewrite { publish_score.as_mut().await?; } - let rewritten_command = format!("apply_patch <<'PATCH'\n{rewritten_patch}\nPATCH"); + let rewritten_command = if location != PatchRewriteLocation::CanonicalPatch { + format!("apply_patch <<'PATCH'\n{rewritten_patch}\nPATCH") + } else { + rewritten_patch.clone() + }; let reply = json!({"hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "allow", "updatedInput": {"command": rewritten_command}, @@ -744,6 +897,465 @@ if payload["tool_input"]["command"] != "echo score-seed": Ok(()) } +#[test_case::test_case(ev_apply_patch_custom_tool_call; "native")] +#[test_case::test_case(ev_apply_patch_exec_command_call_via_heredoc; "exec_command")] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn recorded_patch_review_preserves_actor_context( + patch_call: fn(&str, &str) -> serde_json::Value, +) -> Result<()> { + skip_if_no_network!(Ok(())); + let patch = "*** Begin Patch\n*** Add File: original.txt\n+original\n*** End Patch"; + let replacement = "*** Begin Patch\n*** Add File: rewritten.txt\n+rewritten\n*** End Patch"; + let hook_context = "context from the executed patch hook"; + let local_hook_directory = TempDir::new()?; + let mcp_servers = serde_json::from_value(json!({ + "patch-hook": { + "command": core_test_support::stdio_server_bin()?, + "cwd": local_hook_directory.path(), + }, + }))?; + let mut builder = test_codex() + .with_model("gpt-5.5") + .with_pre_build_hook(move |home| { + write_patch_review_hook(home, PatchReviewHook::Reply(json!({ + "additionalContext": hook_context, + }))) + .expect("write context-producing patch hook"); + let script = home.join("async_patch_observer.py"); + let log = serde_json::to_string(&home.join("async_patch_observer.jsonl")) + .expect("serialize observer path"); + let finished = serde_json::to_string(&home.join("async_patch_observer.finished")) + .expect("serialize observer completion path"); + std::fs::write( + &script, + format!( + "import json, sys\nfrom pathlib import Path\npayload = json.load(sys.stdin)\nwith Path({log}).open('a', encoding='utf-8') as output:\n output.write(json.dumps(payload) + '\\n')\nprint(json.dumps({{'hookSpecificOutput': {{'hookEventName': 'PreToolUse', 'additionalContext': 'async patch observer context'}}}}), flush=True)\nPath({finished}).touch()\n" + ), + ) + .expect("write async patch observer"); + let config_path = home.join("hooks.json"); + let mut config: serde_json::Value = serde_json::from_slice( + &std::fs::read(&config_path).expect("read patch hook config"), + ) + .expect("parse patch hook config"); + let python = if cfg!(windows) { "python" } else { "python3" }; + let rewrite = json!({ + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": "allow", + "updatedInput": {"command": replacement}, + }, + }); + config["hooks"]["PreToolUse"] + .as_array_mut() + .expect("pre hooks") + .push(json!({ + "matcher": "apply_patch", + "hooks": [{ + "type": "mcp_tool", "server": "patch-hook", "tool": "image_scenario", + "input": {"scenario": "text_only", "caption": rewrite.to_string()}, + }, { + "type": "command", "async": true, + "command": format!("{python} \"{}\"", script.display()), + }], + })); + std::fs::write(config_path, config.to_string()).expect("write observer config"); + }) + .with_config(move |config| { + super::configure_scenario_catalog(config); + core_test_support::hooks::trust_discovered_hooks(config); + config.mcp_servers.set(mcp_servers).expect("set MCP server"); + config.features.enable(Feature::Sqlite).expect("enable SQLite"); + config.memories.disable_on_external_context = true; + config + .permissions + .set_permission_profile(PermissionProfile::Disabled) + .expect("unrestricted permissions"); + }); + let server = responses::start_mock_server().await; + let test = builder.build_with_remote_and_local_env(&server).await?; + core_test_support::wait_for_mcp_server(&test.codex, "patch-hook").await?; + if test.executor_environment().environment().is_remote() { + test.codex + .update_thread_settings(ThreadSettingsOverrides { + environments: Some(TurnEnvironmentRequests::new( + test.config.cwd.clone(), + vec![ + test.executor_environment().request(), + local_request(AbsolutePathBuf::try_from(local_hook_directory.path())?), + ], + )), + ..Default::default() + }) + .await?; + } + test.codex + .inject_response_items(vec![responses::user_message_item("Review this patch.")]) + .await?; + test.codex.flush_rollout().await?; + let before = test + .codex + .load_history(/*include_archived*/ false) + .await? + .items + .into_iter() + .filter_map(|item| match item { + RolloutItem::ResponseItem(item) => Some(item.into_item()), + _ => None, + }) + .collect::>(); + let reviewed_call = patch_call("recorded-patch", patch); + let tool_call = serde_json::from_value(reviewed_call["item"].clone())?; + let assessment = json!({ + "outcome": "allow", "risk_level": "low", "user_authorization": "high", + "rationale": "The effective patch is authorized.", + }); + let mock = responses::mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_assistant_message("review-one", &assessment.to_string()), + ev_completed("review-one"), + ]), + sse(vec![ + ev_assistant_message("review-two", &assessment.to_string()), + ev_completed("review-two"), + ]), + sse(vec![ + patch_call("live-patch", patch), + ev_completed("live-action"), + ]), + sse(vec![ + ev_assistant_message("done", "Applied."), + ev_completed("done"), + ]), + ], + ) + .await; + for _ in 0..2 { + assert_eq!( + assess_with_transcript_reviewer(&test.codex, &tool_call) + .await? + .assessment, + serde_json::from_value(assessment.clone())?, + ); + } + test.codex.flush_rollout().await?; + let after = test + .codex + .load_history(/*include_archived*/ false) + .await? + .items + .into_iter() + .filter_map(|item| match item { + RolloutItem::ResponseItem(item) => Some(item.into_item()), + _ => None, + }) + .collect::>(); + assert_eq!(after, before); + for request in mock.requests() { + assert!(request.body_json().to_string().contains("rewritten.txt")); + } + let db = test.codex.state_db().expect("state db enabled"); + let thread_id = test.session_configured.thread_id; + assert_eq!( + db.get_thread_memory_mode(thread_id).await?.as_deref(), + Some("enabled") + ); + let missing = test + .fs() + .get_metadata( + &test.workspace_path_uri("rewritten.txt")?, + Default::default(), + /*sandbox*/ None, + ) + .await + .expect_err("recorded reviews must not execute the patch"); + assert_eq!(missing.kind(), std::io::ErrorKind::NotFound); + + test.submit_text_turn("Now apply the patch.").await?; + assert_eq!( + db.get_thread_memory_mode(thread_id).await?.as_deref(), + Some("polluted") + ); + let requests = mock.requests(); + assert_eq!(requests.len(), 4); + assert!(!requests[2].body_json().to_string().contains(hook_context)); + assert!( + !requests[2] + .body_json() + .to_string() + .contains("async patch observer context") + ); + assert_eq!( + requests[3] + .message_input_texts("developer") + .iter() + .filter(|text| *text == hook_context) + .count(), + 1, + ); + assert_eq!( + test.fs() + .read_file_text( + &test.workspace_path_uri("rewritten.txt")?, + Default::default(), + /*sandbox*/ None + ) + .await?, + "rewritten\n", + ); + let observer_log = test.codex_home_path().join("async_patch_observer.jsonl"); + core_test_support::fs_wait::wait_for_path_exists( + test.codex_home_path().join("async_patch_observer.finished"), + Duration::from_secs(10), + ) + .await?; + test.codex.shutdown_and_wait().await?; + let observations = std::fs::read_to_string(observer_log)? + .lines() + .map(serde_json::from_str::) + .collect::, _>>()?; + let hook_inputs = + std::fs::read_to_string(test.codex_home_path().join("patch_review_hooks.jsonl"))? + .lines() + .map(serde_json::from_str::) + .collect::, _>>()?; + let remote = test.executor_environment().environment().is_remote(); + for input in &hook_inputs { + let marker = (remote || input["tool_name"] == "apply_patch").then_some(json!(remote)); + assert_eq!(input.get("tool_target_is_remote"), marker.as_ref()); + } + let pre_hook_modes = hook_inputs + .iter() + .filter(|input| input["hook_event_name"] == "PreToolUse") + .map(|input| { + ( + input["tool_name"].clone(), + input.get("review_only").cloned(), + ) + }) + .collect::>(); + let expected_modes = if reviewed_call["item"]["type"] == "function_call" { + vec![ + (json!("Bash"), Some(json!(true))), + (json!("apply_patch"), Some(json!(true))), + (json!("Bash"), Some(json!(true))), + (json!("apply_patch"), Some(json!(true))), + (json!("Bash"), None), + (json!("apply_patch"), None), + ] + } else { + vec![ + (json!("apply_patch"), Some(json!(true))), + (json!("apply_patch"), Some(json!(true))), + (json!("apply_patch"), None), + ] + }; + assert_eq!(pre_hook_modes, expected_modes); + let live_patch_hook = hook_inputs + .into_iter() + .rfind(|input| { + input["hook_event_name"] == "PreToolUse" && input["tool_name"] == "apply_patch" + }) + .expect("live canonical pre-hook"); + assert_eq!( + observations, + vec![live_patch_hook], + "only live execution schedules the async observer" + ); + Ok(()) +} + +enum PatchReviewStop { + Denied, + Cancelled, +} + +#[test_case::test_case(ev_apply_patch_custom_tool_call, PatchReviewStop::Denied; "native_denial")] +#[test_case::test_case(ev_apply_patch_exec_command_call_via_heredoc, PatchReviewStop::Denied; "exec_command_denial")] +#[test_case::test_case(ev_apply_patch_exec_command_call_via_heredoc, PatchReviewStop::Cancelled; "exec_command_cancellation")] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn direct_patch_review_stops_at_canonical_hook( + patch_call: fn(&str, &str) -> serde_json::Value, + stop: PatchReviewStop, +) -> Result<()> { + skip_if_no_network!(Ok(())); + let reason = "blocked by patch-review hook"; + let hook_gate = match stop { + PatchReviewStop::Denied => None, + PatchReviewStop::Cancelled => Some(TcpListener::bind("127.0.0.1:0").await?), + }; + let hook = match &hook_gate { + Some(gate) => PatchReviewHook::Wait { + tool_name: "apply_patch", + port: gate.local_addr()?.port(), + }, + None => PatchReviewHook::Reply(json!({ + "permissionDecision": "deny", "permissionDecisionReason": reason, + })), + }; + let mut builder = test_codex() + .with_model("gpt-5.5") + .with_pre_build_hook(move |home| { + write_patch_review_hook(home, hook).expect("write stopping patch hook"); + }) + .with_config(|config| { + super::configure_scenario_catalog(config); + core_test_support::hooks::trust_discovered_hooks(config); + config + .permissions + .set_permission_profile(PermissionProfile::Disabled) + .expect("unrestricted permissions"); + }); + let server = responses::start_mock_server().await; + let test = builder.build_with_remote_and_local_env(&server).await?; + let local_hook_directory = TempDir::new()?; + if test.executor_environment().environment().is_remote() { + test.codex + .update_thread_settings(ThreadSettingsOverrides { + environments: Some(TurnEnvironmentRequests::new( + test.config.cwd.clone(), + vec![ + test.executor_environment().request(), + local_request(AbsolutePathBuf::try_from(local_hook_directory.path())?), + ], + )), + ..Default::default() + }) + .await?; + } + let mock = responses::mount_sse_once( + &server, + sse(vec![ + ev_assistant_message("unexpected-review", r#"{"outcome":"allow"}"#), + ev_completed("unexpected-review"), + ]), + ) + .await; + let event = patch_call( + "denied-patch", + "*** Begin Patch\n*** Add File: guardian-denied.txt\n+denied\n*** End Patch", + ); + let intercepted = event["item"]["type"] == "function_call"; + let tool_call = serde_json::from_value(event["item"].clone())?; + let cancellation = CancellationToken::new(); + let review = test.codex.review_recorded_call( + &tool_call, + RecordedReviewMode::Transcript { + root_evidence: None, + }, + &cancellation, + ); + tokio::pin!(review); + let connection = if let Some(gate) = &hook_gate { + let connection = tokio::select! { + accepted = tokio::time::timeout(Duration::from_secs(10), gate.accept()) => accepted??.0, + result = &mut review => anyhow::bail!("review completed before canonical hook blocked: {result:?}"), + }; + cancellation.cancel(); + Some(connection) + } else { + None + }; + let error = review + .await + .expect_err("canonical patch hook must stop Guardian review"); + match stop { + PatchReviewStop::Denied => assert!(matches!(error.details(), + codex_protocol::error::CodexErrorDetails::InvalidRequest(message) if message.contains(reason) + )), + PatchReviewStop::Cancelled => assert!(matches!( + error.details(), + codex_protocol::error::CodexErrorDetails::TurnAborted + )), + } + drop(connection); + assert!(mock.requests().is_empty()); + let missing = test + .fs() + .get_metadata( + &test.workspace_path_uri("guardian-denied.txt")?, + Default::default(), + /*sandbox*/ None, + ) + .await + .expect_err("stopped review must not write the patch"); + assert_eq!(missing.kind(), std::io::ErrorKind::NotFound); + let inputs = std::fs::read_to_string(test.codex_home_path().join("patch_review_hooks.jsonl"))? + .lines() + .map(serde_json::from_str::) + .collect::, _>>()?; + let calls = inputs.iter().map(|input| json!({ + "event": input["hook_event_name"], "tool": input["tool_name"], "id": input["tool_use_id"], + })).collect::>(); + let mut expected = Vec::new(); + let patch_hook_id = &inputs.last().expect("canonical patch hook")["tool_use_id"]; + if intercepted { + assert_ne!(patch_hook_id, &json!("denied-patch")); + expected.push(json!({"event": "PreToolUse", "tool": "Bash", "id": "denied-patch"})); + } else { + assert_eq!(patch_hook_id, &json!("denied-patch")); + } + expected.push(json!({"event": "PreToolUse", "tool": "apply_patch", "id": patch_hook_id})); + assert_eq!(calls, expected); + test.codex.shutdown_and_wait().await?; + Ok(()) +} + +enum PatchReviewHook { + Reply(serde_json::Value), + Wait { tool_name: &'static str, port: u16 }, +} + +fn write_patch_review_hook(home: &Path, hook: PatchReviewHook) -> Result<()> { + let script_path = home.join("patch_review_hook.py"); + let log_path = serde_json::to_string(&home.join("patch_review_hooks.jsonl"))?; + let (tool_name, action) = match hook { + PatchReviewHook::Reply(mut output) => { + output["hookEventName"] = json!("PreToolUse"); + let output_json = + serde_json::to_string(&json!({"hookSpecificOutput": output}).to_string())?; + ("apply_patch", format!(" print({output_json})")) + } + PatchReviewHook::Wait { tool_name, port } => ( + tool_name, + format!( + " with socket.create_connection((\"127.0.0.1\", {port})) as gate:\n print(gate.makefile().readline())" + ), + ), + }; + std::fs::write( + &script_path, + format!( + r#"import json +from pathlib import Path +import socket +import sys + +payload = json.load(sys.stdin) +with Path({log_path}).open("a", encoding="utf-8") as log: + log.write(json.dumps(payload) + "\n") +if payload["hook_event_name"] == "PreToolUse" and payload["tool_name"] == {tool_name:?}: +{action} +"# + ), + )?; + let python = if cfg!(windows) { "python" } else { "python3" }; + let group = json!({ + "matcher": "Bash|apply_patch", + "hooks": [{"type": "command", "command": format!("{python} \"{}\"", script_path.display())}], + }); + std::fs::write( + home.join("hooks.json"), + json!({ + "hooks": {"PreToolUse": [group], "PostToolUse": [group]}, + }) + .to_string(), + )?; + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn direct_permissions_review_matches_live_action() -> Result<()> { skip_if_no_network!(Ok(())); @@ -1066,9 +1678,6 @@ prefix_rule(pattern=["git", "init", "guardian-rewritten"], decision="prompt") #[cfg(not(target_os = "windows"))] #[tokio::test] async fn direct_exec_review_honors_hook_denial_before_policy_skip() -> Result<()> { - use codex_protocol::protocol::EventMsg; - use core_test_support::wait_for_event; - skip_if_no_network!(Ok(())); let reason = "blocked by direct-review hook"; @@ -1097,6 +1706,21 @@ async fn direct_exec_review_honors_hook_denial_before_policy_skip() -> Result<() // These hook fixtures use the local Python interpreter and filesystem. let harness = TestCodexHarness::with_builder(builder).await?; let test = harness.test(); + test.codex + .inject_response_items(vec![responses::user_message_item("Review this command.")]) + .await?; + test.codex.flush_rollout().await?; + let original_history = test + .codex + .load_history(/*include_archived*/ false) + .await? + .items + .into_iter() + .filter_map(|entry| match entry { + RolloutItem::ResponseItem(item) => Some(item.into_item()), + _ => None, + }) + .collect::>(); let mock = responses::mount_sse_once(harness.server(), sse(vec![ev_completed("unexpected")])).await; @@ -1110,7 +1734,7 @@ async fn direct_exec_review_honors_hook_denial_before_policy_skip() -> Result<() .expect_err("hook must reject the call before policy can skip review"); assert!(matches!( error.details(), - codex_protocol::error::CodexErrorDetails::InvalidRequest(_) + codex_protocol::error::CodexErrorDetails::InvalidRequest(message) if message.contains(reason) )); assert!(mock.requests().is_empty()); @@ -1118,18 +1742,27 @@ async fn direct_exec_review_honors_hook_denial_before_policy_skip() -> Result<() matches!(event, EventMsg::HookStarted(_)) }) .await; - wait_for_event(&test.codex, |event| { + let completed = wait_for_event(&test.codex, |event| { matches!(event, EventMsg::HookCompleted(_)) }) .await; + assert!(matches!( + completed, + EventMsg::HookCompleted(event) + if event.run.status == codex_protocol::protocol::HookRunStatus::Blocked + )); test.codex.flush_rollout().await?; let history = test.codex.load_history(/*include_archived*/ false).await?; - assert!(history.items.iter().any(|entry| { - matches!(entry, RolloutItem::ResponseItem(item) - if matches!(&item.item, ResponseItem::Message { role, content, .. } - if role == "developer" && content == &[input_text(reason)])) - })); + let response_items = history + .items + .into_iter() + .filter_map(|entry| match entry { + RolloutItem::ResponseItem(item) => Some(item.into_item()), + _ => None, + }) + .collect::>(); + assert_eq!(response_items, original_history); assert!(!harness.path_exists("guardian-original").await?); diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__guardian_direct_review__guardian_direct_exec_patch.snap b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__guardian_direct_review__guardian_direct_exec_patch.snap index c78a6afda3..f03ea2b9a8 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__guardian_direct_review__guardian_direct_exec_patch.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__guardian_direct_review__guardian_direct_exec_patch.snap @@ -2,7 +2,7 @@ source: core/tests/suite/scenarios_guardian_direct_review.rs expression: snapshot --- -Scenario: Live and direct Guardian review of a patch; direct approval leaves the file unchanged. +Scenario: Live and direct Guardian review of a hook-rewritten patch; direct approval leaves the file unchanged. ## Window 1 -- request 1 (turn) -- @@ -21,8 +21,8 @@ Scenario: Live and direct Guardian review of a patch; direct approval leaves the ## Window 2 (after request 1: input diverged at item 00, settings changed (model, parallel_tool_calls, prompt_cache_key, reasoning, text, tools)) -- request 2 (turn) -- -00:additional_tools/developer (1; hash=bbdbc99401a1afb0): - - namespace/functions; hash=42a1e6648ccef1f0 +00:additional_tools/developer (1; hash=): + - namespace/functions; hash= - custom/exec - function/wait 01:message/developer: @@ -48,7 +48,7 @@ Scenario: Live and direct Guardian review of a patch; direct approval leaves the [06] - [2] tool exec_command call: {"cmd":"apply_patch <<'EOF'\\n*** Begin Patch\\n*** Update File: guardian-direct.txt\\n@@\\n-before\\n+after\\n*** End Patch\\nEOF\\n"} + [2] tool exec_command call: {"cmd":"cd inner && apply_patch <<'EOF'\\n*** Begin Patch\\n*** Update File: g...ore\\n+after\\n*** End Patch\\nEOF\\n","workdir":"outer"} [hash=4d28cab1f366c740] [07] >>> TRANSCRIPT END @@ -75,7 +75,7 @@ Scenario: Live and direct Guardian review of a patch; direct approval leaves the "files": [ "/guardian-direct.txt" ], - "patch": "*** Begin Patch\\n*** Update File: guardian-direct.txt\\n@@\\n-before\\n+after\\n*** End Patch", + "patch": "*** Begin Patch\\n*** Update File: guardian-direct.txt\\n@@\\n-before\\n+hook-rewritten\\n*** End Patch", "tool": "apply_patch" } @@ -96,15 +96,15 @@ Scenario: Live and direct Guardian review of a patch; direct approval leaves the 03:message/user: Change guardian-direct.txt from before to after. -04:function_call/exec_command:{"cmd":"apply_patch <<'EOF'\\n*** Begin Patch\\n*** Update File: guardian-direct.txt\\n@@\\n-before\\n+after\\n*** End Patch\\nEOF\\n"} +04:function_call/exec_command:{"cmd":"cd inner && apply_patch <<'EOF'\\n*** Begin Patch\\n*** Update File: guardian-direct.txt\\n@@\\n-before\\n+after\\n*** End Patch\\nEOF\\n","workdir":"outer"} 05:function_call_output:This action was rejected due to unacceptable risk. Reason: Auto-review returned a deny decision without a rationale. The agent must not attempt to achieve the same outcome via workaround, indirect execution, or policy cir... of the risk. Otherwise, stop and request user input. [hash=316a6640caee3870] ## Window 4 (after request 3: input diverged at item 00, settings changed (model, parallel_tool_calls, prompt_cache_key, reasoning, text, tools)) -- request 4 (turn) -- -00:additional_tools/developer (1; hash=bbdbc99401a1afb0): - - namespace/functions; hash=42a1e6648ccef1f0 +00:additional_tools/developer (1; hash=): + - namespace/functions; hash= - custom/exec - function/wait 01:message/developer: @@ -130,7 +130,7 @@ Scenario: Live and direct Guardian review of a patch; direct approval leaves the [06] - [2] tool exec_command call: {"cmd":"apply_patch <<'EOF'\\n*** Begin Patch\\n*** Update File: guardian-direct.txt\\n@@\\n-before\\n+after\\n*** End Patch\\nEOF\\n"} + [2] tool exec_command call: {"cmd":"cd inner && apply_patch <<'EOF'\\n*** Begin Patch\\n*** Update File: g...ore\\n+after\\n*** End Patch\\nEOF\\n","workdir":"outer"} [hash=4d28cab1f366c740] [07] >>> TRANSCRIPT END @@ -157,7 +157,7 @@ Scenario: Live and direct Guardian review of a patch; direct approval leaves the "files": [ "/guardian-direct.txt" ], - "patch": "*** Begin Patch\\n*** Update File: guardian-direct.txt\\n@@\\n-before\\n+after\\n*** End Patch", + "patch": "*** Begin Patch\\n*** Update File: guardian-direct.txt\\n@@\\n-before\\n+hook-rewritten\\n*** End Patch", "tool": "apply_patch" } diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__guardian_direct_review__guardian_direct_patch.snap b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__guardian_direct_review__guardian_direct_patch.snap index b569ccd3f6..842f97c9ec 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__guardian_direct_review__guardian_direct_patch.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__guardian_direct_review__guardian_direct_patch.snap @@ -2,7 +2,7 @@ source: core/tests/suite/scenarios_guardian_direct_review.rs expression: snapshot --- -Scenario: Live and direct Guardian review of a patch; direct approval leaves the file unchanged. +Scenario: Live and direct Guardian review of a hook-rewritten patch; direct approval leaves the file unchanged. ## Window 1 -- request 1 (turn) -- @@ -21,8 +21,8 @@ Scenario: Live and direct Guardian review of a patch; direct approval leaves the ## Window 2 (after request 1: input diverged at item 00, settings changed (model, parallel_tool_calls, prompt_cache_key, reasoning, text, tools)) -- request 2 (turn) -- -00:additional_tools/developer (1; hash=bbdbc99401a1afb0): - - namespace/functions; hash=42a1e6648ccef1f0 +00:additional_tools/developer (1; hash=): + - namespace/functions; hash= - custom/exec - function/wait 01:message/developer: @@ -80,7 +80,7 @@ Scenario: Live and direct Guardian review of a patch; direct approval leaves the "files": [ "/guardian-direct.txt" ], - "patch": "*** Begin Patch\\n*** Update File: guardian-direct.txt\\n@@\\n-before\\n+after\\n*** End Patch", + "patch": "*** Begin Patch\\n*** Update File: guardian-direct.txt\\n@@\\n-before\\n+hook-rewritten\\n*** End Patch", "tool": "apply_patch" } @@ -113,8 +113,8 @@ Scenario: Live and direct Guardian review of a patch; direct approval leaves the ## Window 4 (after request 3: input diverged at item 00, settings changed (model, parallel_tool_calls, prompt_cache_key, reasoning, text, tools)) -- request 4 (turn) -- -00:additional_tools/developer (1; hash=bbdbc99401a1afb0): - - namespace/functions; hash=42a1e6648ccef1f0 +00:additional_tools/developer (1; hash=): + - namespace/functions; hash= - custom/exec - function/wait 01:message/developer: @@ -172,7 +172,7 @@ Scenario: Live and direct Guardian review of a patch; direct approval leaves the "files": [ "/guardian-direct.txt" ], - "patch": "*** Begin Patch\\n*** Update File: guardian-direct.txt\\n@@\\n-before\\n+after\\n*** End Patch", + "patch": "*** Begin Patch\\n*** Update File: guardian-direct.txt\\n@@\\n-before\\n+hook-rewritten\\n*** End Patch", "tool": "apply_patch" } diff --git a/codex-rs/ext/skills/src/tools/read.rs b/codex-rs/ext/skills/src/tools/read.rs index a2ac7a4e8e..63899a687e 100644 --- a/codex-rs/ext/skills/src/tools/read.rs +++ b/codex-rs/ext/skills/src/tools/read.rs @@ -384,6 +384,8 @@ impl ToolExecutor for ReadTool { .inspect_err(|error| { outcome = match error { FunctionCallError::RespondToModel(_) => "response_budget", + FunctionCallError::FailedBeforeExecution(_) => "internal_error", + FunctionCallError::Blocked(_) => "blocked", FunctionCallError::Fatal(_) => "internal_error", }; })?; 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 index f92af1dd32..2f72a6a1c2 100644 --- 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 @@ -26,6 +26,10 @@ "model": { "type": "string" }, + "parent_tool_use_id": { + "description": "The outer shell hook's tool_use_id when Codex intercepts an apply_patch command.", + "type": "string" + }, "permission_mode": { "enum": [ "default", @@ -44,6 +48,10 @@ "type": "string" }, "tool_response": true, + "tool_target_is_remote": { + "description": "True means the hook must skip local reads of the target. For apply_patch, MCP hooks receive true because their server may use a separate filesystem. False confirms a command hook shares the target filesystem. Omission leaves ownership unknown.", + "type": "boolean" + }, "tool_use_id": { "type": "string" }, @@ -53,6 +61,10 @@ "turn_id": { "description": "Codex extension: expose the active turn id to internal turn-scoped hooks.", "type": "string" + }, + "workspace_cwd": { + "description": "The hook owner's workspace directory before workdir or cd for an intercepted patch.", + "type": "string" } }, "required": [ diff --git a/codex-rs/hooks/schema/generated/pre-tool-use.command.input.schema.json b/codex-rs/hooks/schema/generated/pre-tool-use.command.input.schema.json index 48dd4c5710..bf346d19cb 100644 --- a/codex-rs/hooks/schema/generated/pre-tool-use.command.input.schema.json +++ b/codex-rs/hooks/schema/generated/pre-tool-use.command.input.schema.json @@ -26,6 +26,10 @@ "model": { "type": "string" }, + "parent_tool_use_id": { + "description": "The outer shell hook's tool_use_id when Codex intercepts an apply_patch command.", + "type": "string" + }, "permission_mode": { "enum": [ "default", @@ -36,6 +40,10 @@ ], "type": "string" }, + "review_only": { + "description": "True for a recorded review: no action executes and no PostToolUse hook follows. Observation hooks must not start write receipts; decision and rewrite hooks may still evaluate.", + "type": "boolean" + }, "session_id": { "type": "string" }, @@ -43,6 +51,10 @@ "tool_name": { "type": "string" }, + "tool_target_is_remote": { + "description": "True means the hook must skip local reads of the target. For apply_patch, MCP hooks receive true because their server may use a separate filesystem. False confirms a command hook shares the target filesystem. Omission leaves ownership unknown.", + "type": "boolean" + }, "tool_use_id": { "type": "string" }, @@ -52,6 +64,10 @@ "turn_id": { "description": "Codex extension: expose the active turn id to internal turn-scoped hooks.", "type": "string" + }, + "workspace_cwd": { + "description": "The hook owner's workspace directory before workdir or cd for an intercepted patch.", + "type": "string" } }, "required": [ diff --git a/codex-rs/hooks/src/engine/discovery.rs b/codex-rs/hooks/src/engine/discovery.rs index b87814d756..8c7bdfccf6 100644 --- a/codex-rs/hooks/src/engine/discovery.rs +++ b/codex-rs/hooks/src/engine/discovery.rs @@ -526,6 +526,7 @@ pub fn validate_environment_hooks( let source = crate::EnvironmentHookSource { environment_id: environment_id.to_owned(), cwd: cwd.clone(), + tool_cwd: None, hooks: hooks.clone(), }; let discovered = discover_environment_hooks(vec![source], /*display_order*/ 0); @@ -592,6 +593,7 @@ fn append_environment_hooks( handler.source_path = super::HandlerSourcePath::Environment { environment_id: source.environment_id.clone(), cwd: source.cwd.clone(), + tool_cwd: source.tool_cwd.clone(), source_path: path.clone().into(), }; } diff --git a/codex-rs/hooks/src/engine/dispatcher.rs b/codex-rs/hooks/src/engine/dispatcher.rs index 905c6444e3..d6f0c4bfdf 100644 --- a/codex-rs/hooks/src/engine/dispatcher.rs +++ b/codex-rs/hooks/src/engine/dispatcher.rs @@ -43,13 +43,23 @@ pub(crate) fn select_handlers_for_matcher_inputs( event_name: HookEventName, matcher_inputs: &[&str], ) -> Vec { + matching_handlers(handlers, event_name, matcher_inputs) + .cloned() + .collect() +} + +pub(crate) fn matching_handlers<'a>( + handlers: &'a [ConfiguredHandler], + event_name: HookEventName, + matcher_inputs: &[&str], +) -> impl Iterator { // Check each configured handler once, even when several compatibility names // match the same regex. A hook like `apply_patch|Write|Edit` should run a // single time for one tool call, not once per matching alias. handlers .iter() - .filter(|handler| handler.event_name == event_name) - .filter(|handler| match event_name { + .filter(move |handler| handler.event_name == event_name) + .filter(move |handler| match event_name { HookEventName::PreToolUse | HookEventName::PermissionRequest | HookEventName::PostToolUse @@ -73,8 +83,6 @@ pub(crate) fn select_handlers_for_matcher_inputs( | HookEventName::Stop | HookEventName::Interrupt => true, }) - .cloned() - .collect() } pub(crate) fn running_summary(handler: &ConfiguredHandler) -> HookRunSummary { @@ -167,7 +175,7 @@ pub(crate) async fn execute_handlers_with_progress( executor_handlers.push(handler); continue; } - let event_input = handler.source_path.event_input(input); + let event_input = handler.event_input(input); if handler.execution_mode() == HookExecutionMode::Async { engine.command_runtime.schedule_async_hook( engine.clone(), @@ -205,7 +213,7 @@ pub(crate) async fn execute_handlers_with_progress( if should_stop || !should_block { for handler in executor_handlers { let task_engine = engine.clone(); - let event_input = input.clone(); + let event_input = handler.event_input(input).into_owned(); let cwd = cwd.to_path_buf(); let metadata = metadata.cloned(); engine.command_runtime.schedule_async_task(async move { diff --git a/codex-rs/hooks/src/engine/failure_policy_tests.rs b/codex-rs/hooks/src/engine/failure_policy_tests.rs index ed393a5d98..0ed6f3df90 100644 --- a/codex-rs/hooks/src/engine/failure_policy_tests.rs +++ b/codex-rs/hooks/src/engine/failure_policy_tests.rs @@ -95,7 +95,10 @@ async fn run(engine: &ClaudeHooksEngine, event: HookEventName) -> (bool, Vec (bool, Vec, source_path: PathUri, }, /// Executor-scoped handlers are currently excluded from user-visible hook reporting @@ -107,9 +108,13 @@ 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, .. } => { + Self::Environment { cwd, tool_cwd, .. } => { let mut input = input.clone(); - input["cwd"] = Value::String(cwd.inferred_native_path_string()); + if let Some(workspace_cwd) = input.get_mut("workspace_cwd") { + *workspace_cwd = Value::String(cwd.inferred_native_path_string()); + } + let effective_cwd = tool_cwd.as_ref().unwrap_or(cwd); + input["cwd"] = Value::String(effective_cwd.inferred_native_path_string()); input["transcript_path"] = Value::Null; if let Some(path) = input.get_mut("agent_transcript_path") { *path = Value::Null; @@ -177,6 +182,30 @@ pub(crate) struct HandlerRunResult { } impl ConfiguredHandler { + fn event_input<'a>(&self, input: &'a Value) -> Cow<'a, Value> { + let mut scoped = self.source_path.event_input(input); + let marker = "tool_target_is_remote"; + let patch = input["tool_name"] == "apply_patch" + && matches!( + self.event_name, + HookEventName::PreToolUse | HookEventName::PostToolUse + ); + if self.handler_type() == HookHandlerType::McpTool { + // The MCP server may run on a different filesystem from its configuration. + if (patch || input.get(marker).is_some()) && input[marker] != true { + scoped.to_mut()[marker] = Value::Bool(true); + } + } else if matches!(self.source_path, HandlerSourcePath::Environment { .. }) { + // Single-target events reach only the target's environment-owned command hooks. + if patch && let Some(value) = scoped.to_mut().get_mut(marker) { + *value = Value::Bool(false); + } else if let Some(fields) = scoped.to_mut().as_object_mut() { + fields.remove(marker); + } + } + scoped + } + /// Internal memory work runs policy and executor hooks, not user or project hooks. pub(crate) fn runs_for_memory_consolidation(&self) -> bool { matches!(self.source_path, HandlerSourcePath::ExecutorScoped { .. }) diff --git a/codex-rs/hooks/src/engine/mod_tests.rs b/codex-rs/hooks/src/engine/mod_tests.rs index c0396029c8..3e8dda98ca 100644 --- a/codex-rs/hooks/src/engine/mod_tests.rs +++ b/codex-rs/hooks/src/engine/mod_tests.rs @@ -259,6 +259,67 @@ fn required_hooks_stack( .expect("config layer stack") } +#[test] +fn recorded_review_selects_only_synchronous_hooks_without_changing_live_selection() { + let temp = tempdir().expect("create temp dir"); + let mut events = pre_tool_use_hook_events("echo synchronous"); + events.pre_tool_use[0] + .hooks + .push(HookHandlerConfig::Command { + command: "echo asynchronous".to_string(), + command_windows: None, + timeout_sec: Some(10), + r#async: true, + status_message: None, + on_failure: None, + additional_context_limit: None, + }); + let config_layer_stack = required_hooks_stack( + managed_hooks_for_current_platform(temp.path(), events), + RequirementSource::LegacyManagedConfigTomlFromMdm, + ); + let (hooks, _result_receiver) = crate::Hooks::new( + crate::HooksConfig { + feature_enabled: true, + config_layer_stack: Some(config_layer_stack), + ..Default::default() + }, + ThreadId::new(), + mcp_executor(), + ) + .expect("load synchronous and asynchronous hooks"); + let request = PreToolUseRequest { + session_id: ThreadId::new(), + turn_id: "turn-1".to_string(), + subagent: None, + cwd: cwd(), + tool_cwd: None, + transcript_path: None, + model: "gpt-test".to_string(), + permission_mode: "default".to_string(), + tool_name: "Bash".to_string(), + matcher_aliases: Vec::new(), + tool_use_id: "tool-1".to_string(), + parent_tool_use_id: None, + tool_target_is_remote: None, + tool_input: serde_json::json!({"command": "echo hello"}), + review_only: false, + }; + let live = hooks.preview_pre_tool_use(&request); + assert_eq!( + live.iter() + .map(|run| run.execution_mode) + .collect::>(), + vec![HookExecutionMode::Sync, HookExecutionMode::Async], + ); + let recorded = PreToolUseRequest { + review_only: true, + ..request.clone() + }; + assert_eq!(hooks.preview_pre_tool_use(&recorded), vec![live[0].clone()]); + assert_eq!(hooks.preview_pre_tool_use(&request), live); +} + #[test] fn required_managed_hooks_allow_disabled_hooks_feature() { let temp = tempdir().expect("create temp dir"); @@ -663,7 +724,10 @@ with Path(r"{log_path}").open("a", encoding="utf-8") as handle: tool_name: "Bash".to_string(), matcher_aliases: Vec::new(), tool_use_id: "tool-1".to_string(), + parent_tool_use_id: None, + tool_target_is_remote: None, tool_input: serde_json::json!({ "command": "echo hello" }), + review_only: false, }); assert_eq!(preview.len(), 1); assert_eq!( @@ -684,7 +748,10 @@ with Path(r"{log_path}").open("a", encoding="utf-8") as handle: tool_name: "Bash".to_string(), matcher_aliases: Vec::new(), tool_use_id: "tool-1".to_string(), + parent_tool_use_id: None, + tool_target_is_remote: None, tool_input: serde_json::json!({ "command": "echo hello" }), + review_only: false, }) .await; @@ -760,7 +827,10 @@ async fn requirements_managed_hooks_execute_windows_command_override() { tool_name: "Bash".to_string(), matcher_aliases: Vec::new(), tool_use_id: "tool-1".to_string(), + parent_tool_use_id: None, + tool_target_is_remote: None, tool_input: serde_json::json!({ "command": "echo hello" }), + review_only: false, }) .await; @@ -1166,7 +1236,10 @@ fn requirements_managed_hooks_load_when_managed_dir_is_missing() { tool_name: "Bash".to_string(), matcher_aliases: Vec::new(), tool_use_id: "tool-1".to_string(), + parent_tool_use_id: None, + tool_target_is_remote: None, tool_input: serde_json::json!({ "command": "echo hello" }), + review_only: false, }); assert_eq!(preview.len(), 1); assert_eq!( @@ -1600,7 +1673,10 @@ fn discovers_hooks_from_json_and_toml_in_the_same_layer() { tool_name: "Bash".to_string(), matcher_aliases: Vec::new(), tool_use_id: "tool-1".to_string(), + parent_tool_use_id: None, + tool_target_is_remote: None, tool_input: serde_json::json!({ "command": "echo hello" }), + review_only: false, }); assert_eq!(preview.len(), 2); assert_eq!( @@ -1698,7 +1774,10 @@ fn profile_user_layers_load_shared_hooks_json_once() { tool_name: "Bash".to_string(), matcher_aliases: Vec::new(), tool_use_id: "tool-1".to_string(), + parent_tool_use_id: None, + tool_target_is_remote: None, tool_input: serde_json::json!({ "command": "echo hello" }), + review_only: false, }); assert_eq!(preview.len(), 1); assert_eq!( @@ -2201,7 +2280,10 @@ print(json.dumps({ tool_name: "Bash".to_string(), matcher_aliases: Vec::new(), tool_use_id: "tool-1".to_string(), + parent_tool_use_id: None, + tool_target_is_remote: None, tool_input: serde_json::json!({ "command": "echo hello" }), + review_only: false, }); assert_eq!(preview.len(), 1); assert_eq!(preview[0].source, HookSource::Plugin); @@ -2237,7 +2319,10 @@ print(json.dumps({ tool_name: "Bash".to_string(), matcher_aliases: Vec::new(), tool_use_id: "tool-1".to_string(), + parent_tool_use_id: None, + tool_target_is_remote: None, tool_input: serde_json::json!({ "command": "echo hello" }), + review_only: false, }) .await; @@ -2572,6 +2657,48 @@ async fn executor_stop_hooks_normalize_blocking_policy_without_dropping_cleanup( } } +#[test] +fn mcp_patch_hooks_treat_target_filesystem_as_unverified() { + let (engine, ..) = executor_stop_hook_fixture(); + let mut handler = engine.handlers[0].clone(); + let controller = HandlerSourcePath::Local(cwd().join("hooks.json")); + let environment = HandlerSourcePath::Environment { + environment_id: "remote".to_string(), + cwd: PathUri::parse("file:///workspace").expect("workspace URI"), + tool_cwd: None, + source_path: PathUri::parse("file:///workspace/requirements.toml").expect("source URI"), + }; + let sources = [ + (controller.clone(), Some(false)), + (environment, Some(true)), + (handler.source_path.clone(), Some(false)), + (controller, None), + ]; + let template = serde_json::from_value(serde_json::json!({ + "remote": "${tool_target_is_remote}", + "message": "remote=${tool_target_is_remote}", + })) + .expect("MCP template"); + for event in [HookEventName::PreToolUse, HookEventName::PostToolUse] { + handler.event_name = event; + for (source, marker) in &sources { + handler.source_path = source.clone(); + let mut input = serde_json::json!({"tool_name": "apply_patch"}); + if let Some(marker) = marker { + input["tool_target_is_remote"] = (*marker).into(); + } + let input = handler.event_input(&input); + let arguments = super::mcp_runner::expand_mcp_argument_template(&template, &input) + .expect("expand MCP input"); + assert_eq!( + serde_json::Value::Object(arguments), + serde_json::json!({"remote": true, "message": "remote=true"}), + "{source} {event:?}" + ); + } + } +} + #[tokio::test] async fn subagent_stop_paths_are_scoped_to_each_hook() { let (mut engine, calls, mut request, _, _) = executor_stop_hook_fixture(); @@ -2607,6 +2734,7 @@ async fn subagent_stop_paths_are_scoped_to_each_hook() { source_path: HandlerSourcePath::Environment { environment_id: "remote".to_string(), cwd: PathUri::parse("file:///C:/team%20workspace").expect("Windows working directory"), + tool_cwd: None, source_path: PathUri::parse("file:///C:/team%20workspace/requirements.toml") .expect("Windows source path"), }, @@ -3014,7 +3142,10 @@ async fn mcp_tool_hooks_expand_event_input_and_apply_pre_tool_decisions() { tool_name: "Bash".to_string(), matcher_aliases: Vec::new(), tool_use_id: "tool-1".to_string(), + parent_tool_use_id: None, + tool_target_is_remote: None, tool_input: serde_json::json!({ "command": "rm important.txt" }), + review_only: false, }; let calls = Arc::new(Mutex::new(Vec::new())); let executor = StaticMcpExecutor { diff --git a/codex-rs/hooks/src/environment.rs b/codex-rs/hooks/src/environment.rs index 61968db51c..b8a43317b4 100644 --- a/codex-rs/hooks/src/environment.rs +++ b/codex-rs/hooks/src/environment.rs @@ -12,6 +12,8 @@ pub struct EnvironmentHookSource { pub environment_id: String, /// Working directory from the same captured environment used for execution. pub cwd: PathUri, + /// Override for the effective tool directory reported in hook input. + pub tool_cwd: Option, pub hooks: HookEventsToml, } diff --git a/codex-rs/hooks/src/events/post_tool_use.rs b/codex-rs/hooks/src/events/post_tool_use.rs index d7d91795d7..1c8105fad2 100644 --- a/codex-rs/hooks/src/events/post_tool_use.rs +++ b/codex-rs/hooks/src/events/post_tool_use.rs @@ -30,12 +30,14 @@ pub struct PostToolUseRequest { /// Original local execution cwd for hook stdin. Remote commands leave this /// unset to retain the host cwd. The hook process still runs in `cwd`. pub tool_cwd: Option, + pub tool_target_is_remote: Option, pub transcript_path: Option, pub model: String, pub permission_mode: String, pub tool_name: String, pub matcher_aliases: Vec, pub tool_use_id: String, + pub parent_tool_use_id: Option, pub tool_input: Value, pub tool_response: Value, } @@ -160,6 +162,7 @@ fn command_input(request: &PostToolUseRequest) -> Result Result, + pub tool_target_is_remote: Option, pub transcript_path: Option, pub model: String, pub permission_mode: String, pub tool_name: String, pub matcher_aliases: Vec, pub tool_use_id: String, + pub parent_tool_use_id: Option, pub tool_input: Value, + pub review_only: bool, } #[derive(Debug)] @@ -56,33 +59,39 @@ struct PreToolUseHandlerData { updated_input: Option, } +fn select_handlers<'a>( + handlers: &'a [ConfiguredHandler], + request: &PreToolUseRequest, +) -> Vec<&'a ConfiguredHandler> { + let matcher_inputs = common::matcher_inputs(&request.tool_name, &request.matcher_aliases); + dispatcher::matching_handlers(handlers, HookEventName::PreToolUse, &matcher_inputs) + .filter(|handler| !request.review_only || handler.can_apply_control_effects()) + .collect() +} + pub(crate) fn preview( handlers: &[ConfiguredHandler], request: &PreToolUseRequest, ) -> Vec { - let matcher_inputs = common::matcher_inputs(&request.tool_name, &request.matcher_aliases); - dispatcher::select_handlers_for_matcher_inputs( - handlers, - HookEventName::PreToolUse, - &matcher_inputs, - ) - .into_iter() - .map(|handler| { - common::hook_run_for_tool_use(dispatcher::running_summary(&handler), &request.tool_use_id) - }) - .collect() + select_handlers(handlers, request) + .into_iter() + .map(|handler| { + common::hook_run_for_tool_use( + dispatcher::running_summary(handler), + &request.tool_use_id, + ) + }) + .collect() } pub(crate) async fn run( engine: &ClaudeHooksEngine, request: PreToolUseRequest, ) -> PreToolUseOutcome { - let matcher_inputs = common::matcher_inputs(&request.tool_name, &request.matcher_aliases); - let matched = dispatcher::select_handlers_for_matcher_inputs( - &engine.handlers, - HookEventName::PreToolUse, - &matcher_inputs, - ); + let matched: Vec<_> = select_handlers(&engine.handlers, &request) + .into_iter() + .cloned() + .collect(); if matched.is_empty() { return PreToolUseOutcome { hook_events: Vec::new(), @@ -187,12 +196,19 @@ fn command_input(request: &PreToolUseRequest) -> Result, + /// The hook owner's workspace directory before workdir or cd for an intercepted patch. + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace_cwd: Option, + /// True means the hook must skip local reads of the target. For apply_patch, MCP hooks receive + /// true because their server may use a separate filesystem. False confirms a command hook shares + /// the target filesystem. Omission leaves ownership unknown. + #[serde(skip_serializing_if = "Option::is_none")] + pub tool_target_is_remote: Option, + /// True for a recorded review: no action executes and no PostToolUse hook follows. + /// Observation hooks must not start write receipts; decision and rewrite hooks may still evaluate. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub review_only: bool, } #[derive(Debug, Clone, Serialize, JsonSchema)] @@ -340,6 +355,17 @@ pub(crate) struct PostToolUseCommandInput { pub tool_input: Value, pub tool_response: Value, pub tool_use_id: String, + /// The outer shell hook's tool_use_id when Codex intercepts an apply_patch command. + #[serde(skip_serializing_if = "Option::is_none")] + pub parent_tool_use_id: Option, + /// The hook owner's workspace directory before workdir or cd for an intercepted patch. + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace_cwd: Option, + /// True means the hook must skip local reads of the target. For apply_patch, MCP hooks receive + /// true because their server may use a separate filesystem. False confirms a command hook shares + /// the target filesystem. Omission leaves ownership unknown. + #[serde(skip_serializing_if = "Option::is_none")] + pub tool_target_is_remote: Option, } #[derive(Debug, Clone, Serialize, JsonSchema)] @@ -1226,6 +1252,10 @@ mod tests { tool_name: "Bash".to_string(), tool_input: json!({ "command": "echo hello" }), tool_use_id: "tool-1".to_string(), + parent_tool_use_id: None, + workspace_cwd: None, + tool_target_is_remote: None, + review_only: false, }; assert_eq!( @@ -1259,6 +1289,10 @@ mod tests { tool_name: "Bash".to_string(), tool_input: json!({ "command": "echo hello" }), tool_use_id: "tool-1".to_string(), + parent_tool_use_id: None, + workspace_cwd: None, + tool_target_is_remote: None, + review_only: false, }; let root_input = serde_json::to_value(root_input).expect("serialize root hook input"); assert_eq!(root_input.get("agent_id"), None); diff --git a/codex-rs/message-board-mcp/src/lib.rs b/codex-rs/message-board-mcp/src/lib.rs index 8122c456ca..d219e464e4 100644 --- a/codex-rs/message-board-mcp/src/lib.rs +++ b/codex-rs/message-board-mcp/src/lib.rs @@ -139,9 +139,11 @@ impl ServerHandler for MessageBoardMcpServer { result.is_error = Some(!output.success_for_logging()); result } - Err(FunctionCallError::RespondToModel(message)) => { - CallToolResult::error(vec![ContentBlock::text(message)]) - } + Err( + FunctionCallError::RespondToModel(message) + | FunctionCallError::FailedBeforeExecution(message) + | FunctionCallError::Blocked(message), + ) => CallToolResult::error(vec![ContentBlock::text(message)]), Err(FunctionCallError::Fatal(_)) => { return Err(ErrorData::internal_error( "Message-board tool failed", diff --git a/codex-rs/tools/src/function_call_error.rs b/codex-rs/tools/src/function_call_error.rs index 1ab8335b25..9e1723c421 100644 --- a/codex-rs/tools/src/function_call_error.rs +++ b/codex-rs/tools/src/function_call_error.rs @@ -5,6 +5,12 @@ use thiserror::Error; pub enum FunctionCallError { #[error("{0}")] RespondToModel(String), + /// Preparation failed before the underlying action executed. + #[error("{0}")] + FailedBeforeExecution(String), + /// The tool was stopped before its underlying action executed. + #[error("{0}")] + Blocked(String), #[error("Fatal error: {0}")] Fatal(String), } diff --git a/codex-rs/tools/src/tool_output.rs b/codex-rs/tools/src/tool_output.rs index f54c523233..c2af1ecce7 100644 --- a/codex-rs/tools/src/tool_output.rs +++ b/codex-rs/tools/src/tool_output.rs @@ -55,14 +55,20 @@ pub trait ToolOutput: Send { None } + /// Identifies a committed operation performed by another tool during this call. + /// Its post-hook uses this name, and interruption preserves its execution outcome. + fn committed_tool_name(&self) -> Option<&str> { + None + } + /// Returns the tool call id exposed to `PostToolUse` hooks for this output. fn post_tool_use_id(&self, call_id: &str) -> String { call_id.to_string() } - /// Returns the original local execution cwd for hook input, including delayed - /// results. Remote commands return `None` to retain the host hook cwd. - /// This does not change the local directory used to launch the hook process. + /// Returns the original effective execution cwd for hook input, including delayed + /// results. Hook dispatch retains the host fallback for remote tools' local hooks. + /// This does not change the directory used to launch the hook process. fn post_tool_use_cwd(&self) -> Option { None } @@ -141,6 +147,10 @@ where (**self).post_tool_use_id(call_id) } + fn committed_tool_name(&self) -> Option<&str> { + (**self).committed_tool_name() + } + fn post_tool_use_cwd(&self) -> Option { (**self).post_tool_use_cwd() }