From 71df25b78741454ba53c6c245e4b5c6e81630175 Mon Sep 17 00:00:00 2001 From: Abhinav Vedmala Date: Mon, 13 Apr 2026 18:14:17 -0700 Subject: [PATCH] Support interrupting permission request hook denials Allow PermissionRequest hooks to return interrupt=true on deny and route that through the existing interrupted turn lifecycle. Co-authored-by: Codex --- codex-rs/core/src/codex.rs | 5 +- codex-rs/core/src/function_tool.rs | 2 + codex-rs/core/src/stream_events_utils.rs | 3 + codex-rs/core/src/tasks/mod.rs | 44 +++++-- codex-rs/core/src/tools/events.rs | 1 + codex-rs/core/src/tools/network_approval.rs | 7 +- codex-rs/core/src/tools/orchestrator.rs | 6 +- codex-rs/core/src/tools/parallel.rs | 1 + .../tools/runtimes/shell/unix_escalation.rs | 10 +- codex-rs/core/src/tools/sandboxing.rs | 1 + codex-rs/core/tests/suite/hooks.rs | 117 ++++++++++++++++++ ...mission-request.command.output.schema.json | 2 +- codex-rs/hooks/src/engine/output_parser.rs | 36 +++++- .../hooks/src/events/permission_request.rs | 20 ++- codex-rs/hooks/src/schema.rs | 5 +- 15 files changed, 234 insertions(+), 26 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index f44a79528f..f14eb45b1f 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -4430,7 +4430,7 @@ impl Session { info!("interrupt received: abort current task, if any"); let has_active_turn = { self.active_turn.lock().await.is_some() }; if has_active_turn { - self.abort_all_tasks(TurnAbortReason::Interrupted).await; + self.request_task_abort(TurnAbortReason::Interrupted).await; } else { self.cancel_mcp_startup().await; } @@ -7533,6 +7533,9 @@ async fn drain_in_flight( sess.record_conversation_items(&turn_context, &[response_input.into()]) .await; } + Err(CodexErr::TurnAborted) => { + return Err(CodexErr::TurnAborted); + } Err(err) => { error_or_panic(format!("in-flight tool future failed during drain: {err}")); } diff --git a/codex-rs/core/src/function_tool.rs b/codex-rs/core/src/function_tool.rs index 240e04361c..a66ce5b732 100644 --- a/codex-rs/core/src/function_tool.rs +++ b/codex-rs/core/src/function_tool.rs @@ -4,6 +4,8 @@ use thiserror::Error; pub enum FunctionCallError { #[error("{0}")] RespondToModel(String), + #[error("tool interrupted")] + Interrupted, #[error("LocalShellCall without call_id or id")] MissingLocalShellCallId, #[error("Fatal error: {0}")] diff --git a/codex-rs/core/src/stream_events_utils.rs b/codex-rs/core/src/stream_events_utils.rs index 8c63616e7e..19debaaf67 100644 --- a/codex-rs/core/src/stream_events_utils.rs +++ b/codex-rs/core/src/stream_events_utils.rs @@ -325,6 +325,9 @@ pub(crate) async fn handle_output_item_done( Err(FunctionCallError::Fatal(message)) => { return Err(CodexErr::Fatal(message)); } + Err(FunctionCallError::Interrupted) => { + return Err(CodexErr::TurnAborted); + } } Ok(output) diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index b46db8e98f..15adcbd675 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -384,18 +384,32 @@ impl Session { pub async fn abort_all_tasks(self: &Arc, reason: TurnAbortReason) { if let Some(mut active_turn) = self.take_active_turn().await { - for task in active_turn.drain_tasks() { + let tasks = self.prepare_tasks_for_abort(&mut active_turn).await; + for task in tasks { self.handle_task_abort(task, reason.clone()).await; } - // Let interrupted tasks observe cancellation before dropping pending approvals, or an - // in-flight approval wait can surface as a model-visible rejection before TurnAborted. - active_turn.clear_pending().await; } if reason == TurnAbortReason::Interrupted { self.maybe_start_turn_for_pending_work().await; } } + pub(crate) async fn request_task_abort(self: &Arc, reason: TurnAbortReason) { + let Some(mut active_turn) = self.take_active_turn().await else { + return; + }; + let tasks = self.prepare_tasks_for_abort(&mut active_turn).await; + let session = Arc::clone(self); + tokio::spawn(async move { + for task in tasks { + session.handle_task_abort(task, reason.clone()).await; + } + if reason == TurnAbortReason::Interrupted { + session.maybe_start_turn_for_pending_work().await; + } + }); + } + pub async fn on_task_finished( self: &Arc, turn_context: Arc, @@ -550,6 +564,20 @@ impl Session { active.take() } + async fn prepare_tasks_for_abort(&self, active_turn: &mut ActiveTurn) -> Vec { + let tasks = active_turn.drain_tasks(); + for task in &tasks { + task.cancellation_token.cancel(); + task.turn_context + .turn_metadata_state + .cancel_git_enrichment_task(); + } + // Let interrupted tasks observe cancellation before dropping pending approvals, or an + // in-flight approval wait can surface as a model-visible rejection before TurnAborted. + active_turn.clear_pending().await; + tasks + } + pub(crate) async fn close_unified_exec_processes(&self) { self.services .unified_exec_manager @@ -567,12 +595,10 @@ impl Session { async fn handle_task_abort(self: &Arc, task: RunningTask, reason: TurnAbortReason) { let sub_id = task.turn_context.sub_id.clone(); - if task.cancellation_token.is_cancelled() { - return; + if !task.cancellation_token.is_cancelled() { + trace!(task_kind = ?task.kind, sub_id, "aborting running task"); + task.cancellation_token.cancel(); } - - trace!(task_kind = ?task.kind, sub_id, "aborting running task"); - task.cancellation_token.cancel(); task.turn_context .turn_metadata_state .cancel_git_enrichment_task(); diff --git a/codex-rs/core/src/tools/events.rs b/codex-rs/core/src/tools/events.rs index 58438cf563..931c268bb4 100644 --- a/codex-rs/core/src/tools/events.rs +++ b/codex-rs/core/src/tools/events.rs @@ -357,6 +357,7 @@ impl ToolEmitter { let result = Err(FunctionCallError::RespondToModel(normalized)); (event, result) } + Err(ToolError::Interrupted) => return Err(FunctionCallError::Interrupted), }; self.emit(ctx, event).await; result diff --git a/codex-rs/core/src/tools/network_approval.rs b/codex-rs/core/src/tools/network_approval.rs index bb585cbc95..e1e3b708a9 100644 --- a/codex-rs/core/src/tools/network_approval.rs +++ b/codex-rs/core/src/tools/network_approval.rs @@ -402,14 +402,17 @@ impl NetworkApprovalService { pending_approvals.remove(&key); return NetworkDecision::Allow; } - PermissionRequestDecision::Deny { message } => { + PermissionRequestDecision::Deny { message, interrupt } => { if let Some(owner_call) = owner_call.as_ref() { self.record_call_outcome( &owner_call.registration_id, - NetworkApprovalOutcome::DeniedByPolicy(message), + NetworkApprovalOutcome::DeniedByPolicy(message.clone()), ) .await; } + if interrupt { + session.interrupt_task().await; + } pending.set_decision(PendingApprovalDecision::Deny).await; let mut pending_approvals = self.pending_host_approvals.lock().await; pending_approvals.remove(&key); diff --git a/codex-rs/core/src/tools/orchestrator.rs b/codex-rs/core/src/tools/orchestrator.rs index 7d3be77719..84dfd87815 100644 --- a/codex-rs/core/src/tools/orchestrator.rs +++ b/codex-rs/core/src/tools/orchestrator.rs @@ -386,13 +386,17 @@ impl ToolOrchestrator { ); return Ok(ReviewDecision::Approved); } - Some(PermissionRequestDecision::Deny { message }) => { + Some(PermissionRequestDecision::Deny { message, interrupt }) => { telemetry.otel.tool_decision( telemetry.tool_name, telemetry.call_id, &ReviewDecision::Denied, ToolDecisionSource::Config, ); + if interrupt { + approval_ctx.session.interrupt_task().await; + return Err(ToolError::Interrupted); + } return Err(ToolError::Rejected(message)); } None => {} diff --git a/codex-rs/core/src/tools/parallel.rs b/codex-rs/core/src/tools/parallel.rs index a0818dfc83..658ce21225 100644 --- a/codex-rs/core/src/tools/parallel.rs +++ b/codex-rs/core/src/tools/parallel.rs @@ -64,6 +64,7 @@ impl ToolCallRuntime { async move { match future.await { Ok(response) => Ok(response.into_response()), + Err(FunctionCallError::Interrupted) => Err(CodexErr::TurnAborted), Err(FunctionCallError::Fatal(message)) => Err(CodexErr::Fatal(message)), Err(other) => Ok(Self::failure_response(error_call, other)), } diff --git a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs index 836cd2a114..1b129019bb 100644 --- a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs +++ b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs @@ -420,9 +420,15 @@ impl CoreShellActionProvider { rejection_message: None, }; } - Some(PermissionRequestDecision::Deny { message }) => { + Some(PermissionRequestDecision::Deny { message, interrupt }) => { + let decision = if interrupt { + session.interrupt_task().await; + ReviewDecision::Abort + } else { + ReviewDecision::Denied + }; return PromptDecision { - decision: ReviewDecision::Denied, + decision, guardian_review_id: None, rejection_message: Some(message), }; diff --git a/codex-rs/core/src/tools/sandboxing.rs b/codex-rs/core/src/tools/sandboxing.rs index 60303064f3..91a70262eb 100644 --- a/codex-rs/core/src/tools/sandboxing.rs +++ b/codex-rs/core/src/tools/sandboxing.rs @@ -321,6 +321,7 @@ pub(crate) struct ToolCtx { #[derive(Debug)] pub(crate) enum ToolError { Rejected(String), + Interrupted, Codex(CodexErr), } diff --git a/codex-rs/core/tests/suite/hooks.rs b/codex-rs/core/tests/suite/hooks.rs index ee63ca77b8..59eea92c8d 100644 --- a/codex-rs/core/tests/suite/hooks.rs +++ b/codex-rs/core/tests/suite/hooks.rs @@ -294,6 +294,17 @@ elif mode == "deny": }} }} }})) +elif mode == "deny_interrupt": + print(json.dumps({{ + "hookSpecificOutput": {{ + "hookEventName": "PermissionRequest", + "decision": {{ + "behavior": "deny", + "message": reason, + "interrupt": True + }} + }} + }})) elif mode == "exit_2": sys.stderr.write(reason + "\n") raise SystemExit(2) @@ -1221,6 +1232,112 @@ async fn permission_request_hook_allows_shell_command_without_user_approval() -> Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn permission_request_hook_interrupts_shell_command_turn() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let call_id = "permissionrequest-shell-command-interrupt"; + let marker = std::env::temp_dir().join("permissionrequest-shell-command-interrupt-marker"); + let command = format!("rm -f {}", marker.display()); + let args = serde_json::json!({ "command": command }); + let responses = mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-1"), + core_test_support::responses::ev_function_call( + call_id, + "shell_command", + &serde_json::to_string(&args)?, + ), + ev_completed("resp-1"), + ]), + ) + .await; + + let test = test_codex() + .with_pre_build_hook(|home| { + if let Err(error) = write_permission_request_hook( + home, + Some(PERMISSION_REQUEST_HOOK_MATCHER), + "deny_interrupt", + "blocked and interrupted by hook", + ) { + panic!("failed to write permission request hook test fixture: {error}"); + } + }) + .with_config(|config| { + config + .features + .enable(Feature::CodexHooks) + .expect("test config should allow feature update"); + }) + .build(&server) + .await?; + + fs::write(&marker, "seed").context("create interrupt permission request marker")?; + + test.codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "run the shell command after hook approval".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + cwd: test.config.cwd.to_path_buf(), + approval_policy: AskForApproval::OnRequest, + approvals_reviewer: None, + sandbox_policy: SandboxPolicy::DangerFullAccess, + model: test.session_configured.model.clone(), + effort: None, + summary: None, + service_tier: None, + collaboration_mode: None, + personality: None, + }) + .await?; + + let mut started_turn_id = None; + let mut aborted = None; + let mut seen_events = Vec::new(); + while aborted.is_none() { + let event = timeout(Duration::from_secs(10), test.codex.next_event()) + .await + .expect("timeout waiting for hook interrupt events")?; + seen_events.push(format!("{:?}", event.msg)); + match event.msg { + EventMsg::TurnStarted(started) => { + started_turn_id = Some(started.turn_id); + } + EventMsg::TurnAborted(event) => { + aborted = Some(event); + } + EventMsg::TurnComplete(event) => { + panic!("expected interrupted turn, saw completion instead: {event:?}"); + } + _ => {} + } + } + let aborted = aborted.expect("turn aborted event should be present"); + assert_eq!( + aborted.reason, + codex_protocol::protocol::TurnAbortReason::Interrupted + ); + assert_eq!(aborted.turn_id, started_turn_id); + assert_eq!(responses.requests().len(), 1); + assert!( + marker.exists(), + "interrupted command should not remove marker file" + ); + assert_single_permission_request_hook_input( + test.codex_home_path(), + &command, + /*description*/ None, + )?; + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn permission_request_hook_sees_raw_exec_command_input() -> Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/hooks/schema/generated/permission-request.command.output.schema.json b/codex-rs/hooks/schema/generated/permission-request.command.output.schema.json index 21d45382b0..4403ce77fe 100644 --- a/codex-rs/hooks/schema/generated/permission-request.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/permission-request.command.output.schema.json @@ -28,7 +28,7 @@ }, "interrupt": { "default": false, - "description": "Reserved for future short-circuiting semantics.\n\nPermissionRequest hooks currently fail closed if this field is `true`.", + "description": "When `true`, a deny decision interrupts the current turn after the hook feedback is recorded.", "type": "boolean" }, "message": { diff --git a/codex-rs/hooks/src/engine/output_parser.rs b/codex-rs/hooks/src/engine/output_parser.rs index 0a3a994e19..940c9cf80c 100644 --- a/codex-rs/hooks/src/engine/output_parser.rs +++ b/codex-rs/hooks/src/engine/output_parser.rs @@ -22,7 +22,7 @@ pub(crate) struct PreToolUseOutput { #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum PermissionRequestDecision { Allow, - Deny { message: String }, + Deny { message: String, interrupt: bool }, } #[derive(Debug, Clone)] @@ -302,7 +302,9 @@ fn unsupported_permission_request_hook_specific_output( Some("PermissionRequest hook returned unsupported updatedInput".to_string()) } else if decision.updated_permissions.is_some() { Some("PermissionRequest hook returned unsupported updatedPermissions".to_string()) - } else if decision.interrupt { + } else if decision.interrupt + && matches!(decision.behavior, PermissionRequestBehaviorWire::Allow) + { Some("PermissionRequest hook returned unsupported interrupt:true".to_string()) } else { None @@ -320,6 +322,7 @@ fn permission_request_decision( .as_deref() .and_then(trimmed_reason) .unwrap_or_else(|| "PermissionRequest hook denied approval".to_string()), + interrupt: decision.interrupt, }, } } @@ -421,6 +424,7 @@ mod tests { use pretty_assertions::assert_eq; use serde_json::json; + use super::PermissionRequestDecision; use super::parse_permission_request; #[test] @@ -491,4 +495,32 @@ mod tests { Some("PermissionRequest hook returned unsupported interrupt:true".to_string()) ); } + + #[test] + fn permission_request_accepts_interrupting_deny() { + let parsed = parse_permission_request( + &json!({ + "continue": true, + "hookSpecificOutput": { + "hookEventName": "PermissionRequest", + "decision": { + "behavior": "deny", + "message": "blocked", + "interrupt": true + } + } + }) + .to_string(), + ) + .expect("permission request hook output should parse"); + + assert_eq!(parsed.invalid_reason, None); + assert_eq!( + parsed.decision, + Some(PermissionRequestDecision::Deny { + message: "blocked".to_string(), + interrupt: true, + }) + ); + } } diff --git a/codex-rs/hooks/src/events/permission_request.rs b/codex-rs/hooks/src/events/permission_request.rs index c6b58b86f1..c9cd861fed 100644 --- a/codex-rs/hooks/src/events/permission_request.rs +++ b/codex-rs/hooks/src/events/permission_request.rs @@ -48,7 +48,7 @@ pub struct PermissionRequestRequest { #[derive(Debug, Clone, PartialEq, Eq)] pub enum PermissionRequestDecision { Allow, - Deny { message: String }, + Deny { message: String, interrupt: bool }, } #[derive(Debug)] @@ -155,9 +155,10 @@ fn resolve_permission_request_decision<'a>( PermissionRequestDecision::Allow => { resolved_allow = Some(PermissionRequestDecision::Allow); } - PermissionRequestDecision::Deny { message } => { + PermissionRequestDecision::Deny { message, interrupt } => { return Some(PermissionRequestDecision::Deny { message: message.clone(), + interrupt: *interrupt, }); } } @@ -223,13 +224,17 @@ fn parse_completed( output_parser::PermissionRequestDecision::Allow => { decision = Some(PermissionRequestDecision::Allow); } - output_parser::PermissionRequestDecision::Deny { message } => { + output_parser::PermissionRequestDecision::Deny { + message, + interrupt, + } => { status = HookRunStatus::Blocked; entries.push(HookOutputEntry { kind: HookOutputEntryKind::Feedback, text: message.clone(), }); - decision = Some(PermissionRequestDecision::Deny { message }); + decision = + Some(PermissionRequestDecision::Deny { message, interrupt }); } } } @@ -248,7 +253,10 @@ fn parse_completed( kind: HookOutputEntryKind::Feedback, text: message.clone(), }); - decision = Some(PermissionRequestDecision::Deny { message }); + decision = Some(PermissionRequestDecision::Deny { + message, + interrupt: false, + }); } else { status = HookRunStatus::Failed; entries.push(HookOutputEntry { @@ -298,6 +306,7 @@ mod tests { PermissionRequestDecision::Allow, PermissionRequestDecision::Deny { message: "repo deny".to_string(), + interrupt: false, }, ]; @@ -305,6 +314,7 @@ mod tests { resolve_permission_request_decision(decisions.iter()), Some(PermissionRequestDecision::Deny { message: "repo deny".to_string(), + interrupt: false, }) ); } diff --git a/codex-rs/hooks/src/schema.rs b/codex-rs/hooks/src/schema.rs index d7693ac704..a09a301bc1 100644 --- a/codex-rs/hooks/src/schema.rs +++ b/codex-rs/hooks/src/schema.rs @@ -150,9 +150,8 @@ pub(crate) struct PermissionRequestDecisionWire { pub updated_permissions: Option, #[serde(default)] pub message: Option, - /// Reserved for future short-circuiting semantics. - /// - /// PermissionRequest hooks currently fail closed if this field is `true`. + /// When `true`, a deny decision interrupts the current turn after the hook + /// feedback is recorded. #[serde(default)] pub interrupt: bool, }