Accept an explicit tool call in Guardian review requests (#63654)

## Why

Selecting the final item in an idle thread's history ties Guardian review
to what was recorded. For example, a client may record an `exec` script
and need an assessment of an individual `exec_command` from that script.

## What changed

Require `toolCall` in the experimental `thread/guardianReview` request.
Guardian assesses the supplied `function_call` or `custom_tool_call`
against the idle thread's full history without appending or executing it.

## Testing

Cover rejection of requests missing `toolCall` and verify that Guardian
sees the recorded script alongside each command submitted for review.
Check that only the original script call is persisted in the thread.

GitOrigin-RevId: a1ce61e10e98107b38db60071dd63f189ef33ad1
This commit is contained in:
swastik-oai
2026-11-24 14:35:46 +00:00
committed by copyberry
parent 5f2bd3342f
commit 53fe98bdc2
14 changed files with 168 additions and 132 deletions
@@ -216,14 +216,13 @@ impl TurnRequestProcessor {
EnsureConversationListenerResult::Attached => {}
EnsureConversationListenerResult::ConnectionClosed => return Ok(None),
}
let result =
thread
.guardian_review(cancellation)
.await
.map_err(|err| match err.details() {
CodexErrorDetails::InvalidRequest(message) => invalid_request(message.clone()),
_ => internal_error(format!("Guardian review failed: {err}")),
})?;
let result = thread
.guardian_review(&params.tool_call, cancellation)
.await
.map_err(|err| match err.details() {
CodexErrorDetails::InvalidRequest(message) => invalid_request(message.clone()),
_ => internal_error(format!("Guardian review failed: {err}")),
})?;
Ok(Some(
ThreadGuardianReviewResponse {
call_id: result.call_id,
@@ -489,20 +489,12 @@ async fn websocket_disconnect_cancels_guardian_review_and_releases_thread() -> R
read_response_for_id(client, /*id*/ 1).await?;
}
let thread_id = start_thread(&mut owner, /*id*/ 2).await?;
send_request(&mut owner, "thread/inject_items", /*id*/ 3, Some(json!({
"threadId":thread_id, "items":[{
send_request(&mut owner, "thread/guardianReview", /*id*/ 4, Some(json!({
"threadId":thread_id, "toolCall":{
"type":"function_call","name":"exec_command","call_id":"review",
"arguments":r#"{"cmd":"touch marker","sandbox_permissions":"require_escalated","justification":"create the marker"}"#
}]
}
}))).await?;
read_response_for_id(&mut owner, /*id*/ 3).await?;
send_request(
&mut owner,
"thread/guardianReview",
/*id*/ 4,
Some(json!({"threadId":thread_id})),
)
.await?;
timeout(
DEFAULT_READ_TIMEOUT,
guardian.wait_for_request_count(/*count*/ 1),
@@ -812,43 +812,56 @@ async fn guardian_review_assesses_allowlisted_calls_and_reuses_private_history_p
let parent = app.start_thread(ThreadStartParams::default()).await?.thread;
let other = app.start_thread(ThreadStartParams::default()).await?.thread;
for (thread, call_id) in [(&parent, "a"), (&parent, "b"), (&other, "c")] {
let evidence = if call_id == "b" {
json!({
"type": "function_call_output",
"call_id": "a",
"output": "Recorded success.",
})
} else {
json!({
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "List tracked files."}],
})
};
let items = vec![
evidence,
json!({
"type": "function_call",
"name": "exec_command",
"call_id": call_id,
"arguments": r#"{"cmd":"git ls-files"}"#,
}),
];
let script = r#"for (const path of ["a", "b"]) await tools.exec_command({cmd: "git ls-files " + path});"#;
let command = |id: &str| {
json!({
"type": "function_call",
"name": "exec_command",
"call_id": id,
"arguments": json!({"cmd": format!("git ls-files {id}")}).to_string(),
})
};
for (thread, last) in [
(
&parent,
json!({"type":"custom_tool_call", "name":"exec", "call_id":"outer", "input":script}),
),
(&other, command("c")),
] {
let _: ThreadInjectItemsResponse = app
.request(|request_id| ClientRequest::ThreadInjectItems {
request_id,
params: ThreadInjectItemsParams {
thread_id: thread.id.clone(),
items,
items: vec![
json!({
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "List tracked files."}],
}),
last,
],
},
})
.await?;
}
let id = app
.send_raw_request("thread/guardianReview", Some(json!({"threadId":other.id})))
.await?;
let error = app
.read_stream_until_error_message(RequestId::Integer(id))
.await?;
assert!(error.error.message.contains("toolCall"));
for (thread, call_id) in [(&parent, "a"), (&parent, "b"), (&other, "c")] {
let tool_call = serde_json::from_value(command(call_id))?;
let result: Value = app
.request(|request_id| ClientRequest::ThreadGuardianReview {
request_id,
params: ThreadGuardianReviewParams {
thread_id: thread.id.clone(),
tool_call,
},
})
.await?;
@@ -870,6 +883,23 @@ async fn guardian_review_assesses_allowlisted_calls_and_reuses_private_history_p
let [a, b, c] = requests.as_slice() else {
anyhow::bail!("expected three Guardian requests, got {}", requests.len());
};
for (request, id) in [(a, "a"), (b, "b")] {
let input = request.input();
let texts = input
.iter()
.filter_map(|item| item["content"].as_array())
.flatten()
.filter_map(|part| part["text"].as_str());
assert!(texts.clone().any(|text| text.contains(script)));
let action = texts
.filter_map(|text| serde_json::from_str::<Value>(text).ok())
.rfind(|action| action["tool"] == "exec_command")
.expect("planned command");
assert_eq!(
action["command"].as_array().unwrap().last().unwrap(),
&json!(format!("git ls-files {id}"))
);
}
for request in [a, b, c] {
assert_eq!(
request.body_json()["client_metadata"]["x-openai-subagent"],
@@ -892,6 +922,15 @@ async fn guardian_review_assesses_allowlisted_calls_and_reuses_private_history_p
);
app.shutdown_gracefully().await?;
let rollout = std::fs::read_to_string(parent.path.expect("parent rollout"))?;
let mut calls = Vec::new();
for line in rollout.lines() {
let entry: Value = serde_json::from_str(line)?;
if entry["type"] == "response_item" && entry["payload"]["call_id"].is_string() {
calls.push(entry["payload"]["call_id"].clone());
}
}
assert_eq!(calls, vec![json!("outer")]);
Ok(())
}
@@ -143,7 +143,10 @@ base_url = "{}/v1"
("thread/resume", json!({"threadId": started.thread.id})),
(
"thread/guardianReview",
json!({ "threadId": started.thread.id }),
json!({"threadId": started.thread.id, "toolCall": {
"type": "function_call", "name": "exec_command", "call_id": "blocked",
"arguments": r#"{"cmd":"pwd"}"#,
}}),
),
(
"thread/goal/set",