mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Let V3 workers stop after their tool calls finish (#65025)
## Why A worker can send a message and ask to stop in the same response. It needs to see any send failure before going idle so it can respond to the error. ## What changed When a V3 worker targets itself with `interrupt_agent`, finish the current tool batch and skip the automatic model follow-up if no `send_message` call in that batch failed. Pending input can still trigger another model request. Scope the stop to the sampling attempt so it cannot carry over to a retry. ## Testing Extend the mailbox integration test to cover a truncated response, a send failure alongside a self-stop, and a subsequent self-stop that runs the `SubagentStop` hook and frees the worker slot. GitOrigin-RevId: 62e377026d32ffc59d1ea5b88030ce9148d414b4
This commit is contained in:
@@ -4949,6 +4949,7 @@ impl Session {
|
||||
Ok(Arc::new(StepContext {
|
||||
active_collaboration_mode,
|
||||
sampled_through_sequence: None,
|
||||
worker_self_stop: None,
|
||||
serving_assessment: None,
|
||||
guardian_probe: None,
|
||||
hook_rewrote_input: false,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Request-scoped settings and capabilities, with live grants bound to the originating turn.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use crate::agents_md::LoadedAgentsMd;
|
||||
use crate::config::TokenBudgetConfig;
|
||||
@@ -24,11 +25,21 @@ use codex_protocol::items::ModelInvocationContext;
|
||||
use codex_protocol::protocol::TurnContextItem;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// Scoped to one sampling attempt so a yielded cell cannot stop a later batch.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct WorkerSelfStop {
|
||||
pub(crate) requested: OnceLock<()>,
|
||||
/// The worker must see a failed send regardless of which tool finishes first.
|
||||
pub(crate) send_failed: OnceLock<()>,
|
||||
}
|
||||
|
||||
/// Request-scoped state that may change between model sampling requests.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct StepContext {
|
||||
/// Input prefix captured for this normal inference attempt, acknowledged with its output.
|
||||
pub(crate) sampled_through_sequence: Option<u64>,
|
||||
/// Only tools from this V3 sampling attempt can stop its automatic follow-up.
|
||||
pub(crate) worker_self_stop: Option<Arc<WorkerSelfStop>>,
|
||||
/// Final serving value for this invocation; retained by its code cell across waits.
|
||||
pub(crate) serving_assessment: Option<Arc<crate::guardian::ServingAssessment>>,
|
||||
/// Existing serving review flag, retained only for shadow logging.
|
||||
|
||||
@@ -301,6 +301,7 @@ impl StepContext {
|
||||
Arc::new(Self {
|
||||
active_collaboration_mode: settings.active_collaboration_mode(/*previous*/ None),
|
||||
sampled_through_sequence: None,
|
||||
worker_self_stop: None,
|
||||
turn_cancellation: tokio_util::sync::CancellationToken::new(),
|
||||
preempt: turn
|
||||
.config
|
||||
|
||||
@@ -119,6 +119,7 @@ use codex_protocol::protocol::CodexErrorInfo;
|
||||
use codex_protocol::protocol::ErrorEvent;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::InternalSessionSource;
|
||||
use codex_protocol::protocol::MultiAgentVersion;
|
||||
use codex_protocol::protocol::PlanDeltaEvent;
|
||||
use codex_protocol::protocol::ReasoningContentDeltaEvent;
|
||||
use codex_protocol::protocol::ReasoningRawContentDeltaEvent;
|
||||
@@ -690,6 +691,7 @@ pub(crate) async fn run_turn(
|
||||
|
||||
let SamplingRequestResult {
|
||||
needs_follow_up: model_needs_follow_up,
|
||||
worker_self_stop,
|
||||
mailbox_preempted,
|
||||
last_agent_message: sampling_request_last_agent_message,
|
||||
} = sampling_request_output;
|
||||
@@ -697,6 +699,8 @@ pub(crate) async fn run_turn(
|
||||
final_answer,
|
||||
trailing_commentary,
|
||||
} = sampling_request_last_agent_message;
|
||||
// Self-stop skips the follow-up that would normally replace progress with an answer.
|
||||
let trailing_commentary = trailing_commentary.filter(|_| !worker_self_stop);
|
||||
let sampling_request_last_agent_message =
|
||||
work.assistant_message(final_answer, trailing_commentary);
|
||||
completion_hooks = TurnCompletionHooks {
|
||||
@@ -738,6 +742,8 @@ pub(crate) async fn run_turn(
|
||||
}
|
||||
.instrument(trace_span!("run_turn.collect_post_sampling_state"))
|
||||
.await;
|
||||
// Self-stop suppresses the tool follow-up. Fresh input still runs after compaction.
|
||||
let model_needs_follow_up = model_needs_follow_up && !worker_self_stop;
|
||||
let needs_follow_up = model_needs_follow_up || has_pending_input;
|
||||
let token_limit_reached = token_status.token_limit_reached;
|
||||
|
||||
@@ -793,11 +799,14 @@ pub(crate) async fn run_turn(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let should_roll_over = auto_compaction_enabled
|
||||
&& needs_follow_up
|
||||
&& (sess.take_new_context_window_request().await
|
||||
|| token_limit_reached
|
||||
|| candidate.is_some());
|
||||
// A sibling new_context must reset the window even if the worker goes idle.
|
||||
let reset_requested = auto_compaction_enabled
|
||||
&& (needs_follow_up || worker_self_stop)
|
||||
&& sess.take_new_context_window_request().await;
|
||||
let should_roll_over = reset_requested
|
||||
|| (auto_compaction_enabled
|
||||
&& needs_follow_up
|
||||
&& (token_limit_reached || candidate.is_some()));
|
||||
if auto_compaction_enabled {
|
||||
let allow_auto_compact_fallback = !should_roll_over && !token_limit_reached;
|
||||
super::token_budget::maybe_record(
|
||||
@@ -822,7 +831,7 @@ pub(crate) async fn run_turn(
|
||||
)
|
||||
.await;
|
||||
match compacted {
|
||||
Ok(true) => {
|
||||
Ok(true) if needs_follow_up => {
|
||||
if run_pending_session_start_hooks(
|
||||
&sess,
|
||||
&turn_context,
|
||||
@@ -842,7 +851,7 @@ pub(crate) async fn run_turn(
|
||||
.is_some_and(CancellationToken::is_cancelled);
|
||||
continue;
|
||||
}
|
||||
Ok(false) => {}
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
if crate::tasks::ends_turn_as_interrupted(&err) {
|
||||
return Err(err);
|
||||
@@ -2141,7 +2150,7 @@ async fn run_sampling_request(
|
||||
};
|
||||
let base_instructions = sess.get_prompt_base_instructions().await;
|
||||
|
||||
let tool_runtime = ToolCallRuntime::new(
|
||||
let mut tool_runtime = ToolCallRuntime::new(
|
||||
Arc::clone(&sess),
|
||||
Arc::clone(&step_context),
|
||||
Arc::clone(&turn_diff_tracker),
|
||||
@@ -2175,10 +2184,17 @@ async fn run_sampling_request(
|
||||
sess.clone_history().await
|
||||
};
|
||||
let input_item_count = history.raw_items().len();
|
||||
// A yielded cell retains its issuing attempt, even when the stream retries
|
||||
// with the same step extension data.
|
||||
let sampling_step_context = Arc::new(StepContext {
|
||||
sampled_through_sequence: Some(history.input_sequence()),
|
||||
worker_self_stop: (turn_context.multi_agent_version == MultiAgentVersion::V3)
|
||||
.then(Arc::default),
|
||||
..step_context.as_ref().clone()
|
||||
});
|
||||
if sampling_step_context.worker_self_stop.is_some() {
|
||||
tool_runtime.step_context = Arc::clone(&sampling_step_context);
|
||||
}
|
||||
let mut prompt_input = history
|
||||
.for_prompt(
|
||||
&step_context.settings.model_info.input_modalities,
|
||||
@@ -2311,6 +2327,7 @@ async fn run_sampling_request(
|
||||
return Ok((
|
||||
SamplingRequestResult {
|
||||
needs_follow_up: true,
|
||||
worker_self_stop: false,
|
||||
mailbox_preempted: draining_for_mailbox,
|
||||
last_agent_message: AssistantMessages::default(),
|
||||
},
|
||||
@@ -2452,6 +2469,7 @@ impl AssistantMessages {
|
||||
#[derive(Debug)]
|
||||
struct SamplingRequestResult {
|
||||
needs_follow_up: bool,
|
||||
worker_self_stop: bool,
|
||||
/// Queued mail interrupted sampling and must be drained before the next request.
|
||||
mailbox_preempted: bool,
|
||||
last_agent_message: AssistantMessages,
|
||||
@@ -3308,6 +3326,7 @@ async fn try_run_sampling_request(
|
||||
.await;
|
||||
break Ok(SamplingRequestResult {
|
||||
needs_follow_up: needs_follow_up || mailbox_preempted,
|
||||
worker_self_stop: false,
|
||||
mailbox_preempted,
|
||||
last_agent_message,
|
||||
});
|
||||
@@ -3387,6 +3406,7 @@ async fn try_run_sampling_request(
|
||||
if stream.consumer_dropped.is_cancelled() {
|
||||
break Ok(SamplingRequestResult {
|
||||
needs_follow_up: true,
|
||||
worker_self_stop: false,
|
||||
mailbox_preempted: *draining_for_mailbox,
|
||||
last_agent_message,
|
||||
});
|
||||
@@ -3416,6 +3436,7 @@ async fn try_run_sampling_request(
|
||||
// receiving the interrupt. Do not retry without that pending input.
|
||||
break Ok(SamplingRequestResult {
|
||||
needs_follow_up: true,
|
||||
worker_self_stop: false,
|
||||
mailbox_preempted: true,
|
||||
last_agent_message,
|
||||
});
|
||||
@@ -3844,6 +3865,7 @@ async fn try_run_sampling_request(
|
||||
if wait_for_bill_only {
|
||||
break Ok(SamplingRequestResult {
|
||||
needs_follow_up: true,
|
||||
worker_self_stop: false,
|
||||
mailbox_preempted: *draining_for_mailbox,
|
||||
last_agent_message,
|
||||
});
|
||||
@@ -4051,7 +4073,12 @@ async fn try_run_sampling_request(
|
||||
}
|
||||
|
||||
response_work.finish(&sess.services.budget_policy)?;
|
||||
outcome
|
||||
let mut output = outcome?;
|
||||
if let Some(stop) = &step_context.worker_self_stop {
|
||||
output.worker_self_stop =
|
||||
stop.requested.get().is_some() && stop.send_failed.get().is_none();
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
pub(crate) fn get_last_assistant_message_from_turn<'a>(
|
||||
|
||||
@@ -34,6 +34,7 @@ async fn handle_interrupt_agent(
|
||||
let ToolInvocation {
|
||||
session,
|
||||
turn,
|
||||
step_context,
|
||||
payload,
|
||||
call_id,
|
||||
..
|
||||
@@ -42,6 +43,17 @@ async fn handle_interrupt_agent(
|
||||
let args: InterruptAgentArgs = parse_arguments(&arguments)?;
|
||||
let agent_id = resolve_agent_target(&session, &turn, &args.target).await?;
|
||||
analytics.set_receiver(agent_id);
|
||||
if session.thread_id == agent_id
|
||||
&& let Some(stop) = &step_context.worker_self_stop
|
||||
{
|
||||
session
|
||||
.ensure_stoppable_worker(&turn.session_source)
|
||||
.map_err(|err| collab_v2_agent_error(agent_id, err))?;
|
||||
stop.requested.get_or_init(|| ());
|
||||
return Ok(InterruptAgentResult {
|
||||
previous_status: AgentStatus::Running,
|
||||
});
|
||||
}
|
||||
let snapshot = session
|
||||
.services
|
||||
.agent_control
|
||||
|
||||
@@ -446,6 +446,17 @@ impl ToolRouter {
|
||||
)));
|
||||
}
|
||||
|
||||
// Observe native sends here so a denial before the handler runs also reaches the worker.
|
||||
let worker_stop = step_context
|
||||
.worker_self_stop
|
||||
.as_ref()
|
||||
.filter(|_| {
|
||||
tool_name.name == "send_message"
|
||||
&& self
|
||||
.registered_tool(&tool_name)
|
||||
.is_some_and(|tool| tool.is_trusted)
|
||||
})
|
||||
.cloned();
|
||||
// Keep the legacy ToolInvocation.turn field tied to the same request state until handlers migrate.
|
||||
let turn = Arc::clone(&step_context.turn);
|
||||
let invocation = ToolInvocation {
|
||||
@@ -462,9 +473,16 @@ impl ToolRouter {
|
||||
environments: Default::default(),
|
||||
};
|
||||
|
||||
self.registry
|
||||
let result = self
|
||||
.registry
|
||||
.dispatch_any_with_state(invocation, call_state)
|
||||
.await
|
||||
.await;
|
||||
if result.is_err()
|
||||
&& let Some(stop) = worker_stop
|
||||
{
|
||||
stop.send_failed.get_or_init(|| ());
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ use codex_extension_api::MessageLifecycleContributor;
|
||||
use codex_extension_api::MessageLifecycleInput;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::AgentStatus;
|
||||
use codex_protocol::protocol::HookEventName;
|
||||
use codex_protocol::protocol::MultiAgentVersion;
|
||||
use codex_protocol::protocol::Op;
|
||||
use codex_protocol::protocol::TurnAbortReason;
|
||||
@@ -315,6 +316,13 @@ async fn v3_message_wakes_require_a_slot_only_for_idle_workers() -> Result<()> {
|
||||
let mut extensions = ExtensionRegistryBuilder::new();
|
||||
extensions.thread_lifecycle_contributor(Arc::new(ThreadIdle));
|
||||
let test = one_worker_slot(extensions)
|
||||
.with_pre_build_hook(|home| {
|
||||
let hooks = json!({"hooks": {"SubagentStop": [{"hooks": [
|
||||
{"type": "command", "command": "echo {}"}
|
||||
]}]}});
|
||||
std::fs::write(home.join("hooks.json"), hooks.to_string()).unwrap();
|
||||
})
|
||||
.with_config(core_test_support::hooks::trust_discovered_hooks)
|
||||
.build_with_auto_env(&server)
|
||||
.await?;
|
||||
let mut created = test.thread_manager.subscribe_thread_created();
|
||||
@@ -379,11 +387,75 @@ async fn v3_message_wakes_require_a_slot_only_for_idle_workers() -> Result<()> {
|
||||
send("blocked-wake", "first", BLOCKED).await?,
|
||||
"collab tool failed: agent thread limit reached"
|
||||
);
|
||||
let active = mount_completed_worker(&server, ACTIVE, "send-active").await;
|
||||
let stop = |id| {
|
||||
ev_function_call_with_namespace(
|
||||
id,
|
||||
MULTI_AGENT_V2_NAMESPACE,
|
||||
"interrupt_agent",
|
||||
r#"{"target":"/root/second"}"#,
|
||||
)
|
||||
};
|
||||
// The stream closes after the stop call but before response.completed.
|
||||
mount_sse_once_match(
|
||||
&server,
|
||||
|r: &wiremock::Request| has_function_call_output(r, "waiting") && body_contains(r, ACTIVE),
|
||||
sse(vec![stop("cut-short")]),
|
||||
)
|
||||
.await;
|
||||
// On retry, the failed send must reach the worker despite the same-batch stop.
|
||||
mount_sse_once_match(
|
||||
&server,
|
||||
|r: &wiremock::Request| has_function_call_output(r, "cut-short"),
|
||||
sse(vec![
|
||||
ev_function_call_with_namespace(
|
||||
"send-full",
|
||||
MULTI_AGENT_V2_NAMESPACE,
|
||||
"send_message",
|
||||
&json!({"target": "/root/first", "message": BLOCKED}).to_string(),
|
||||
),
|
||||
stop("stop-self"),
|
||||
ev_completed("report-and-stop"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let mut progress = ev_assistant_message("progress", "Checking the first worker.");
|
||||
progress["item"]["phase"] = json!("commentary");
|
||||
let correction = mount_sse_once_match(
|
||||
&server,
|
||||
|r: &wiremock::Request| has_function_call_output(r, "send-full"),
|
||||
sse(vec![progress, stop("finish"), ev_completed("done")]),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(send("send-active", "second", ACTIVE).await?, "");
|
||||
let mut stops = 0;
|
||||
let end = wait_for_event(&second, |event| {
|
||||
if let EventMsg::HookCompleted(hook) = event
|
||||
&& hook.run.event_name == HookEventName::SubagentStop
|
||||
{
|
||||
stops += 1;
|
||||
}
|
||||
matches!(event, EventMsg::TurnComplete(_))
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
matches!(&end, EventMsg::TurnComplete(done) if done.error.is_none()),
|
||||
"{end:?}"
|
||||
);
|
||||
assert_eq!(stops, 1);
|
||||
ThreadIdle::wait(&second).await;
|
||||
assert!(active.function_call_output_text("waiting").is_some());
|
||||
assert_eq!(second.agent_status().await, AgentStatus::Completed(None));
|
||||
assert_eq!(
|
||||
correction.function_call_output_text("send-full").as_deref(),
|
||||
Some("collab tool failed: agent thread limit reached")
|
||||
);
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert!(
|
||||
!requests
|
||||
.iter()
|
||||
.any(|r| has_function_call_output(r, "finish"))
|
||||
);
|
||||
|
||||
// The second worker stopped itself, freeing the only slot for the first.
|
||||
let retry = mount_completed_worker(&server, RETRY, "retry-wake").await;
|
||||
assert_eq!(send("retry-wake", "first", RETRY).await?, "");
|
||||
ThreadIdle::wait(test.thread_manager.get_thread(first).await?.as_ref()).await;
|
||||
|
||||
Reference in New Issue
Block a user