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 <noreply@openai.com>
This commit is contained in:
Abhinav Vedmala
2026-04-13 18:14:17 -07:00
co-authored by Codex
parent 7e4869308c
commit 71df25b787
15 changed files with 234 additions and 26 deletions
+4 -1
View File
@@ -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}"));
}
+2
View File
@@ -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}")]
+3
View File
@@ -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)
+35 -9
View File
@@ -384,18 +384,32 @@ impl Session {
pub async fn abort_all_tasks(self: &Arc<Self>, 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<Self>, 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<Self>,
turn_context: Arc<TurnContext>,
@@ -550,6 +564,20 @@ impl Session {
active.take()
}
async fn prepare_tasks_for_abort(&self, active_turn: &mut ActiveTurn) -> Vec<RunningTask> {
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<Self>, 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();
+1
View File
@@ -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
+5 -2
View File
@@ -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);
+5 -1
View File
@@ -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 => {}
+1
View File
@@ -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)),
}
@@ -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),
};
+1
View File
@@ -321,6 +321,7 @@ pub(crate) struct ToolCtx {
#[derive(Debug)]
pub(crate) enum ToolError {
Rejected(String),
Interrupted,
Codex(CodexErr),
}
+117
View File
@@ -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(()));
@@ -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": {
+34 -2
View File
@@ -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,
})
);
}
}
@@ -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,
})
);
}
+2 -3
View File
@@ -150,9 +150,8 @@ pub(crate) struct PermissionRequestDecisionWire {
pub updated_permissions: Option<Value>,
#[serde(default)]
pub message: Option<String>,
/// 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,
}