diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index fc3683c65b..55826ef220 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -3597,7 +3597,7 @@ "type": "integer" }, "disable_direct_message": { - "description": "Disable the model's direct-message tools; spawning and automatic child results remain available.", + "description": "Disable V2 direct-message tools while retaining automatic child results. V3 workers use `send_message` to report results, so V3 always includes it in the native tool set.", "type": "boolean" }, "disable_native_tools": { diff --git a/codex-rs/core/src/agent/api.rs b/codex-rs/core/src/agent/api.rs index a2e07c164f..e86c83b1e2 100644 --- a/codex-rs/core/src/agent/api.rs +++ b/codex-rs/core/src/agent/api.rs @@ -137,12 +137,12 @@ pub trait AgentControl: Send + Sync { fn record_usage(&self, usage: Option, hook_units: f64) -> BoxFuture<'_, Result<()>>; - /// Report the terminal result to the parent and completion activity to the task - /// initiator. Local delivery remains best effort and uses the reporting runtime's - /// diagnostic trace; it is not deduplicated. + /// Report completion activity and deliver results according to the worker's version. + /// V3 workers send successful results explicitly. Local delivery is best effort. fn turn_finished<'a>( &'a self, outcome: AgentTurnOutcome, + version: MultiAgentVersion, trace: &'a ThreadTraceContext, ) -> BoxFuture<'a, ()>; diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 997ebf6dde..403022708e 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -276,7 +276,8 @@ impl LocalAgentControl { Some(MessageDelivery::publish( &context, state.extensions.message_lifecycle_contributors(), - terminal_result.then_some(&self.runtime.unconfirmed_results), + (terminal_result || context.kind == AgentCommunicationKind::ParentMessage) + .then_some(&self.runtime.unconfirmed_results), )) }; let log_content = crate::agent_communication::send_log_content(&communication); diff --git a/codex-rs/core/src/agent/control/api.rs b/codex-rs/core/src/agent/control/api.rs index 9efeaa50a7..63ec62dcc4 100644 --- a/codex-rs/core/src/agent/control/api.rs +++ b/codex-rs/core/src/agent/control/api.rs @@ -173,6 +173,13 @@ impl AgentControl for LocalAgentControl { start_options.parent_turn_id = None; } let kind = match mode { + MessageDeliveryMode::WakeWorker + if communication.author.as_str().rsplit_once('/').is_some_and( + |(parent, _)| parent == communication.recipient.as_str(), + ) => + { + AgentCommunicationKind::ParentMessage + } MessageDeliveryMode::QueueOnly | MessageDeliveryMode::WakeWorker => { AgentCommunicationKind::Message } @@ -318,9 +325,10 @@ impl AgentControl for LocalAgentControl { fn turn_finished<'a>( &'a self, outcome: AgentTurnOutcome, + version: MultiAgentVersion, trace: &'a ThreadTraceContext, ) -> BoxFuture<'a, ()> { - Box::pin(self.notify_parent_of_terminal_turn(outcome, trace)) + Box::pin(self.notify_parent_of_terminal_turn(outcome, version, trace)) } fn service_tier(&self) -> Option { diff --git a/codex-rs/core/src/agent/control/completion.rs b/codex-rs/core/src/agent/control/completion.rs index ef64a6096d..6b561a2b55 100644 --- a/codex-rs/core/src/agent/control/completion.rs +++ b/codex-rs/core/src/agent/control/completion.rs @@ -1,4 +1,4 @@ -//! Delivers terminal child results and completion activity to the agent tree. +//! Delivers completion activity and errors. V2 also forwards successful results. //! //! Sessions capture terminal state; the controller owns routing and queue-only delivery. //! Unconsumed results remain available to the source writer through graceful suspension. @@ -16,6 +16,7 @@ use codex_protocol::items::SubAgentActivityItem; use codex_protocol::protocol::AgentStatus; use codex_protocol::protocol::CodexErrorInfo; use codex_protocol::protocol::InterAgentCommunication; +use codex_protocol::protocol::MultiAgentVersion; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentActivityKind; use codex_protocol::protocol::SubAgentSource; @@ -28,6 +29,7 @@ impl LocalAgentControl { pub(crate) async fn notify_parent_of_terminal_turn( &self, outcome: AgentTurnOutcome, + version: MultiAgentVersion, trace: &ThreadTraceContext, ) { let SessionSource::SubAgent(SubAgentSource::ThreadSpawn { @@ -91,6 +93,8 @@ impl LocalAgentControl { } let message = match (&status, outcome.error_info) { + // V3 workers report successful results with send_message. + (AgentStatus::Completed(_), _) if version == MultiAgentVersion::V3 => return, (AgentStatus::Errored(error), Some(CodexErrorInfo::TooManyDenials)) => { Some(format_guardian_interruption_message( parent_agent_path.clone(), diff --git a/codex-rs/core/src/agent/control/runtime.rs b/codex-rs/core/src/agent/control/runtime.rs index ccc88e9512..39dafff89a 100644 --- a/codex-rs/core/src/agent/control/runtime.rs +++ b/codex-rs/core/src/agent/control/runtime.rs @@ -444,7 +444,7 @@ impl LocalAgentRuntime { { let results = self .mailboxes - .take(parent, crate::PendingAgentMessage::is_terminal_result); + .take(parent, crate::PendingAgentMessage::awaits_result_write); if results.is_empty() { continue; } diff --git a/codex-rs/core/src/agent_communication.rs b/codex-rs/core/src/agent_communication.rs index 2bcbdb88ad..17ac5f6fe1 100644 --- a/codex-rs/core/src/agent_communication.rs +++ b/codex-rs/core/src/agent_communication.rs @@ -28,6 +28,8 @@ const AGENT_COMMUNICATION_TARGET: &str = "codex_otel.agent_communication"; pub(crate) enum AgentCommunicationKind { Spawn, Message, + /// A V3 worker's ordinary message to its parent can be its only report. + ParentMessage, Followup, Result, CompletionWatcher, @@ -37,7 +39,7 @@ impl AgentCommunicationKind { fn as_str(self) -> &'static str { match self { Self::Spawn => "spawn", - Self::Message => "message", + Self::Message | Self::ParentMessage => "message", Self::Followup => "followup", Self::Result | Self::CompletionWatcher => "result", } @@ -142,18 +144,34 @@ impl PendingAgentMessage { communication: InterAgentCommunication, delivery: Option, ) -> Self { + // A parent report becomes outstanding only when the recipient accepts it. + // A rejected or cancelled submission must not block a later suspension. + if let Some(delivery) = &delivery + && delivery.kind == AgentCommunicationKind::ParentMessage + && let Some(publication) = &delivery.publication + && let Some(publication) = publication + .lock() + .unwrap_or_else(PoisonError::into_inner) + .as_mut() + && let Some(count) = publication.report_counter.take() + { + publication.result_write = Some(ResultWrite::new(&count)); + } Self { communication, delivery, } } + pub(crate) fn kind(&self) -> Option { + self.delivery.as_ref().map(|delivery| delivery.kind) + } + pub(crate) fn to_model_input_item(&self) -> ResponseItem { - if self - .delivery - .as_ref() - .is_some_and(|delivery| delivery.kind == AgentCommunicationKind::Message) - { + if matches!( + self.kind(), + Some(AgentCommunicationKind::Message | AgentCommunicationKind::ParentMessage) + ) { self.communication.to_model_input_item_as_message() } else { self.communication.to_model_input_item() @@ -161,21 +179,39 @@ impl PendingAgentMessage { } pub(crate) fn is_terminal_result(&self) -> bool { + self.kind() == Some(AgentCommunicationKind::Result) + } + + pub(crate) fn awaits_result_write(&self) -> bool { self.delivery .as_ref() .is_some_and(MessageDelivery::awaits_result_write) } + /// The interrupted turn already used the wake. Keep the report for the next turn. + pub(crate) fn into_unread_result(mut self) -> Option { + if !self.awaits_result_write() { + return None; + } + self.communication.trigger_turn = false; + Some(self) + } + pub(crate) fn consumed(&self, recipient: ThreadId) -> Option { self.delivery.as_ref()?.consumed(recipient) } } -/// Only a confirmed append releases a terminal result. Dropping this receipt +/// Only a confirmed append releases a tracked report. Dropping this receipt /// leaves the write outstanding, so an ambiguous handoff fails. pub(crate) struct ResultWrite(Arc); impl ResultWrite { + fn new(count: &Arc) -> Self { + count.fetch_add(1, Ordering::Relaxed); + Self(Arc::clone(count)) + } + pub(crate) fn confirm(self) { self.0.fetch_sub(1, Ordering::Release); } @@ -186,6 +222,7 @@ struct MessagePublication { input: MessageLifecycleInput, observers: Box<[Arc]>, result_write: Option, + report_counter: Option>, } /// Clones follow one logical delivery through queues and share its consumption state. @@ -217,14 +254,17 @@ impl MessageDelivery { for observer in observers { observer.on_publish(&input); } - let result_write = unconfirmed_results.map(|count| { - count.fetch_add(1, Ordering::Relaxed); - ResultWrite(Arc::clone(count)) - }); + let (result_write, report_counter) = + if context.kind == AgentCommunicationKind::ParentMessage { + (None, unconfirmed_results.cloned()) + } else { + (unconfirmed_results.map(ResultWrite::new), None) + }; let publication = MessagePublication { input, observers: observers.into(), result_write, + report_counter, }; delivery.publication = Some(Arc::new(Mutex::new(Some(publication)))); delivery @@ -236,7 +276,9 @@ impl MessageDelivery { .lock() .unwrap_or_else(PoisonError::into_inner) .as_ref() - .is_some_and(|publication| publication.result_write.is_some()) + .is_some_and(|publication| { + publication.result_write.is_some() || publication.report_counter.is_some() + }) }) } diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index 7ddcba6dce..fb5d5d8eae 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -3,6 +3,7 @@ use super::sampling_interrupt::SamplingInterrupt; use super::submission::SubmissionOp; use crate::McpRefreshReason; use crate::WithTurnExtensionData; +use crate::agent_communication::AgentCommunicationKind; use crate::realtime_conversation::handle_audio as handle_realtime_conversation_audio; use crate::realtime_conversation::handle_close as handle_realtime_conversation_close; use crate::realtime_conversation::handle_speech as handle_realtime_conversation_speech; @@ -512,14 +513,24 @@ pub(super) async fn shutdown_session_runtime(sess: &Arc) { sess.record_annotated_conversation_items(&context, context.model_info(), injected) .await; } - if runtime.suspension_root().is_some() { + // A draining host can reject an idle root's wake and then shut down normally. + // Evicted workers must keep their mailbox for reload. + if runtime.suspension_root().is_some() + || sess + .input_queue + .has_mailbox_items_matching(|mail| { + mail.recipient.is_root() + && mail.kind() == Some(AgentCommunicationKind::ParentMessage) + }) + .await + { let pending: Vec<_> = sess .input_queue .drain_mailbox() .await .into_iter() .map(|mail| mail.communication) - .filter(crate::PendingAgentMessage::is_terminal_result) + .filter(crate::PendingAgentMessage::awaits_result_write) .collect(); if !pending.is_empty() && sess.live_thread().is_some() { let turn_id = { diff --git a/codex-rs/core/src/session/input_queue.rs b/codex-rs/core/src/session/input_queue.rs index bf7d16ff9d..ade88306db 100644 --- a/codex-rs/core/src/session/input_queue.rs +++ b/codex-rs/core/src/session/input_queue.rs @@ -455,9 +455,7 @@ impl InputQueue { .items .into_iter() .filter_map(|entry| match entry.input { - TurnInput::InterAgentCommunication(message) if message.is_terminal_result() => { - Some(message) - } + TurnInput::InterAgentCommunication(message) => message.into_unread_result(), _ => None, }) .collect(); diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 03b5159317..8b145e6f71 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -3006,7 +3006,11 @@ impl Session { let host_outcome = reporter.is_some().then(|| outcome.clone()); self.services .agent_control - .turn_finished(outcome, &self.services.rollout_thread_trace) + .turn_finished( + outcome, + turn_context.multi_agent_version, + &self.services.rollout_thread_trace, + ) .await; host_outcome } else { diff --git a/codex-rs/core/src/session/turn_input.rs b/codex-rs/core/src/session/turn_input.rs index e342ce344a..ced26fe05e 100644 --- a/codex-rs/core/src/session/turn_input.rs +++ b/codex-rs/core/src/session/turn_input.rs @@ -951,8 +951,8 @@ impl Session { tracing::debug!(%error, "rollout budget stopped a pending-work wake"); return None; } - // Explicit follow-ups and native child results finish already-admitted work. - // Injected mail has no terminal-result receipt and still respects drain. + // Explicit follow-ups and terminal child results finish already-admitted work. + // Ordinary messages still need admission, even when their writes are tracked. let admission = if has_trigger_turn || self .input_queue diff --git a/codex-rs/core/src/tools/spec_plan.rs b/codex-rs/core/src/tools/spec_plan.rs index 0705e45002..630d968379 100644 --- a/codex-rs/core/src/tools/spec_plan.rs +++ b/codex-rs/core/src/tools/spec_plan.rs @@ -542,7 +542,7 @@ pub(crate) fn finalize_tool_router( .filter(|info| !info.is_empty()); let child_management_tools = required_child_management_tool_names(turn_context, model_info); - Ok(ToolRouter::from_parts( + let router = ToolRouter::from_parts( registry, model_visible_specs, tool_mode, @@ -550,7 +550,29 @@ pub(crate) fn finalize_tool_router( exec_definitions, tool_namespaces_info, &child_management_tools, - )) + ); + // A worker cannot fall back to a final answer. Check its tools after policy + // and Code Mode filtering, including on resume. It need not manage children. + let agents = &turn_context.config.multi_agent_v2; + if turn_context.multi_agent_version == MultiAgentVersion::V3 + && turn_context.session_source.get_agent_path().is_some() + && !agents.disable_native_tools + { + for name in ["send_message", "stop_agent"] { + let tool = ToolName::new(agents.tool_namespace.clone(), name); + if !router.exposes_tool(&tool) + || !router + .registered_tool(&tool) + .is_some_and(|tool| tool.is_trusted) + { + return Err(CodexErrorDetails::InvalidRequest(format!( + "V3 worker needs {tool}. Check the model and tool policy." + )) + .into()); + } + } + } + Ok(router) } fn apply_direct_model_only_namespace_overrides( @@ -730,6 +752,13 @@ fn multi_agent_v2_enabled(turn_context: &TurnContext) -> bool { turn_context.multi_agent_version.uses_v2_runtime() } +fn model_allows_delegation(turn_context: &TurnContext, model_info: &ModelInfo) -> bool { + turn_context.session_source.get_agent_path().is_none() + || model_info + .multi_agent_version + .is_some_and(MultiAgentVersion::uses_v2_runtime) +} + fn collab_tools_enabled(turn_context: &TurnContext, model_info: &ModelInfo) -> bool { match turn_context.multi_agent_version { MultiAgentVersion::Disabled => false, @@ -737,12 +766,15 @@ fn collab_tools_enabled(turn_context: &TurnContext, model_info: &ModelInfo) -> b next_thread_spawn_depth(&turn_context.session_source), turn_context.config.agent_max_depth, ), - MultiAgentVersion::V2 | MultiAgentVersion::V3 => { + MultiAgentVersion::V2 => { + !turn_context.config.multi_agent_v2.disable_native_tools + && model_allows_delegation(turn_context, model_info) + } + MultiAgentVersion::V3 => { + // Even workers without delegation support need to report results and stop themselves. !turn_context.config.multi_agent_v2.disable_native_tools && (turn_context.session_source.get_agent_path().is_none() - || model_info - .multi_agent_version - .is_some_and(MultiAgentVersion::uses_v2_runtime)) + || model_info.multi_agent_version != Some(MultiAgentVersion::Disabled)) } } } @@ -763,11 +795,7 @@ fn required_child_management_tool_names( ), MultiAgentVersion::V3 => ( turn_context.config.multi_agent_v2.tool_namespace.as_deref(), - if turn_context.config.multi_agent_v2.disable_direct_message { - &["stop_agent", "list_agents"] - } else { - &["send_message", "stop_agent", "list_agents"] - }, + &["send_message", "stop_agent", "list_agents"], ), MultiAgentVersion::V2 => ( turn_context.config.multi_agent_v2.tool_namespace.as_deref(), @@ -1443,8 +1471,30 @@ fn add_collaboration_tools(context: &CoreToolPlanContext<'_>, registry: &mut Too .expose_spawn_agent_service_tier; if multi_agent_v2_enabled(turn_context) { let model_messages = ResolvedModelMessages::from_model(context.model_info); - let spawn_agent_description = - model_messages.multi_agent_tool_description_override("spawn_agent"); + let v3 = turn_context.multi_agent_version == MultiAgentVersion::V3; + // The catalog's V2 descriptions promise automatic results and queue-only messages. + // V3 shares argument schemas, but selects descriptions for its own delivery rules. + let description = |tool_name| { + let catalog = model_messages.multi_agent_tool_description_override(tool_name); + if !v3 + || (context.model_info.multi_agent_version == Some(MultiAgentVersion::V3) + && catalog.is_some()) + { + return catalog; + } + match tool_name { + "spawn_agent" => Some( + "Spawn a worker to handle the specified task. Its canonical path is your path followed by its task name. Workers report results using send_message. Use fork_turns to choose how much history they inherit.", + ), + "send_message" => Some( + "Send a message to an agent. An idle worker starts a new turn in its existing conversation. Messages to /root follow its wake policy.", + ), + "wait_agent" => Some( + "Wait for a message or a failure notification. The wait also ends on new user input or timeout. Reports which event ended the wait. Workers send their results with send_message.", + ), + _ => catalog, + } + }; let tools_in_code_mode = context .model_info .multi_agent_tools_in_code_mode @@ -1463,12 +1513,12 @@ fn add_collaboration_tools(context: &CoreToolPlanContext<'_>, registry: &mut Too } else { NativeReview::Disabled }; - let agent_type_description = - agent_type_description(turn_context, context.default_agent_type_description); - let hide_spawn_agent_metadata = - turn_context.config.multi_agent_v2.hide_spawn_agent_metadata; - registry.register_trusted_with_native_review( - multi_agent_v2_handler( + if model_allows_delegation(turn_context, context.model_info) { + let agent_type_description = + agent_type_description(turn_context, context.default_agent_type_description); + let hide_spawn_agent_metadata = + turn_context.config.multi_agent_v2.hide_spawn_agent_metadata; + let spawn = multi_agent_v2_handler( SpawnAgentHandlerV2::new( SpawnAgentToolOptions { available_models: turn_context.available_models.clone(), @@ -1491,31 +1541,22 @@ fn add_collaboration_tools(context: &CoreToolPlanContext<'_>, registry: &mut Too .usage_hint_text .clone(), }, - spawn_agent_description.map(str::to_owned), + description("spawn_agent").map(str::to_owned), ), tool_namespace, // Spawn composes the selected description with inheritance and usage guidance. /*description_override*/ None, model_messages.multi_agent_tool_parameters_override("spawn_agent"), - ), - exposure, - native_review, - ); - if !turn_context.config.multi_agent_v2.disable_direct_message { - let v3 = turn_context.multi_agent_version == MultiAgentVersion::V3; - let send_message_description = if v3 { - Some( - "Send a message to an agent. An idle worker starts a new turn in its existing conversation. Messages to /root follow its wake policy.", - ) - } else { - model_messages.multi_agent_tool_description_override("send_message") - }; + ); + registry.register_trusted_with_native_review(spawn, exposure, native_review); + } + if v3 || !turn_context.config.multi_agent_v2.disable_direct_message { registry.register_trusted_with_native_review( multi_agent_v2_handler( SendMessageHandlerV2, tool_namespace, - send_message_description, + description("send_message"), model_messages.multi_agent_tool_parameters_override("send_message"), ), exposure, @@ -1539,13 +1580,13 @@ fn add_collaboration_tools(context: &CoreToolPlanContext<'_>, registry: &mut Too multi_agent_v2_handler( WaitAgentHandlerV2::new(context.wait_agent_timeouts), tool_namespace, - model_messages.multi_agent_tool_description_override("wait_agent"), + description("wait_agent"), model_messages.multi_agent_tool_parameters_override("wait_agent"), ), exposure, ); } - let stop = if turn_context.multi_agent_version == MultiAgentVersion::V3 { + let stop = if v3 { StopAgentHandler } else { InterruptAgentHandler diff --git a/codex-rs/core/tests/suite/agent_control_tests.rs b/codex-rs/core/tests/suite/agent_control_tests.rs index 876f8f6591..5b30464217 100644 --- a/codex-rs/core/tests/suite/agent_control_tests.rs +++ b/codex-rs/core/tests/suite/agent_control_tests.rs @@ -284,6 +284,7 @@ impl AgentControl for TestAgentControl { fn turn_finished<'a>( &'a self, _outcome: AgentTurnOutcome, + _version: MultiAgentVersion, _trace: &'a ThreadTraceContext, ) -> BoxFuture<'a, ()> { Box::pin(async {}) diff --git a/codex-rs/core/tests/suite/scenarios_agent_eviction_tests.rs b/codex-rs/core/tests/suite/scenarios_agent_eviction_tests.rs index 685f5e8ea7..b6f6c50260 100644 --- a/codex-rs/core/tests/suite/scenarios_agent_eviction_tests.rs +++ b/codex-rs/core/tests/suite/scenarios_agent_eviction_tests.rs @@ -1,8 +1,11 @@ //! Snapshots a worker's retained history and unread mail across idle eviction and follow-up. use super::*; +use crate::suite::turn_input_submission::RecoveryLifecycleBarrier; +use crate::suite::turn_input_submission::TestAdmission; use codex_core::ThreadEvictionOutcome; use codex_exec_server::CreateDirectoryOptions; +use codex_protocol::models::AgentMessageInputContent; use codex_protocol::protocol::ThreadSettingsOverrides; use codex_protocol::protocol::TurnSettingsUpdate; use codex_protocol::protocol::TurnSettingsUpdateOutcome; @@ -10,6 +13,7 @@ use core_test_support::ThreadIdle; use core_test_support::responses; use core_test_support::submit_thread_settings; use pretty_assertions::assert_eq; +use std::sync::atomic::Ordering; #[test_case::test_case(MultiAgentVersion::V2; "v2_followup_task")] #[test_case::test_case(MultiAgentVersion::V3; "v3_encrypted_send_message")] @@ -20,12 +24,23 @@ async fn idle_eviction_preserves_worker_context_for_followup( skip_if_no_network!(Ok(())); let server = start_mock_server().await; + let wake = Arc::new(RecoveryLifecycleBarrier::default()); + let admission = Arc::new(TestAdmission::default()); let mut extensions = ExtensionRegistryBuilder::::new(); + extensions.turn_start_admission(admission.clone()); extensions.thread_lifecycle_contributor(Arc::new(ThreadIdle)); + extensions.turn_lifecycle_contributor(wake.clone()); let mut test = test_codex() .with_extensions(Arc::new(extensions.build())) - .with_config(|config| { + .with_config(move |config| { configure_scenario_catalog(config); + config + .features + .set_enabled( + Feature::WakeOnAgentMessages, + version == MultiAgentVersion::V3, + ) + .expect("configure message wake"); // This scenario uses client_echo; omit platform-specific shell schemas. config .features @@ -47,6 +62,8 @@ async fn idle_eviction_preserves_worker_context_for_followup( .features .enable(Feature::MultiAgentV2DynamicTools) .expect("enable worker access to client_echo"); + // Even when V2 direct messages are disabled, V3 needs an explicit report path. + config.multi_agent_v2.disable_direct_message = version == MultiAgentVersion::V3; config.multi_agent_v2.max_concurrent_threads_per_session = 2; }) .with_model_info_override("gpt-5.6-sol", move |model| { @@ -232,13 +249,35 @@ async fn idle_eviction_preserves_worker_context_for_followup( }) .await?; assert_eq!(outcome.await?, TurnSettingsUpdateOutcome::Applied); + let events = if version == MultiAgentVersion::V3 && tool == wake_tool { + // Drain while the worker is still running and the root is idle. + admission.0.store(true, Ordering::SeqCst); + wake.block_next.store(true, Ordering::SeqCst); + vec![ + ev_function_call_with_namespace( + "report", + "collaboration", + "send_message", + &json!({"target": "/root", "message": answer}).to_string(), + ), + ev_function_call_with_namespace( + "stop", + "collaboration", + "stop_agent", + r#"{"target":"/root/worker"}"#, + ), + ev_completed("worker-stopped"), + ] + } else { + vec![ + ev_assistant_message("worker-result", answer), + ev_completed("worker-done"), + ] + }; responses::mount_sse_once_match( &server, wiremock::matchers::header("thread-id", id.to_string()), - sse(vec![ - ev_assistant_message("worker-result", answer), - ev_completed("worker-done"), - ]), + sse(events), ) .await; child @@ -258,6 +297,50 @@ async fn idle_eviction_preserves_worker_context_for_followup( } } + if version == MultiAgentVersion::V3 { + // The settings update fences delivery. Only reopening admission may wake the root. + assert!(!test.codex.has_active_turn().await); + admission.0.store(false, Ordering::SeqCst); + admission.1.send_replace(()); + wake.entered.notified().await; + // Stop the wake before the parent reads the report, then hand off the idle tree. + test.codex.submit(Op::Interrupt).await?; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnAborted(_)) + }) + .await; + submit_thread_settings(&test.codex, ThreadSettingsOverrides::default()).await?; + let suspended = test + .thread_manager + .suspend_agent_tree(&test.codex) + .await? + .expect("suspended root"); + assert_eq!(suspended.root_turn_id, None); + assert_eq!(suspended.wake_root_after, None); + // Only the resumed worker's explicit report should survive the interrupted wake. + let (history, _, _) = codex_rollout::RolloutRecorder::load_rollout_items( + &test.codex.rollout_path().expect("root rollout"), + ) + .await?; + let reports: Vec<_> = history + .iter() + .filter_map(|item| match item { + RolloutItem::ResponseItem(item) => match &item.item { + ResponseItem::AgentMessage { content, .. } => Some(content.as_slice()), + _ => None, + }, + _ => None, + }) + .collect(); + assert!( + matches!( + reports.as_slice(), + [[_, AgentMessageInputContent::EncryptedContent { encrypted_content }]] + if encrypted_content == "I will continue with Mira using the new API." + ), + "{reports:?}" + ); + } let mut requests = responses::received_responses_requests(&server).await; // Preserve each stream's complete history while removing parent/child scheduling order. requests @@ -284,7 +367,7 @@ async fn idle_eviction_preserves_worker_context_for_followup( let (snapshot, description) = if version == MultiAgentVersion::V3 { ( "idle_eviction_v3_send_message", - "A V3 parent spawns a worker, checks its status, and sends it an encrypted message after eviction. The same worker resumes with the original assignment and the new message. Complete model streams are grouped as parent, then worker.", + "A V3 worker finishes without sending an automatic result. After eviction an encrypted message wakes the same worker, which reports to the idle parent and stops.", ) } else { ( diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__agent_eviction__idle_eviction_v3_send_message.snap b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__agent_eviction__idle_eviction_v3_send_message.snap index 44144ca7b8..f9f0ca904c 100644 --- a/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__agent_eviction__idle_eviction_v3_send_message.snap +++ b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__agent_eviction__idle_eviction_v3_send_message.snap @@ -2,16 +2,16 @@ source: core/tests/suite/scenarios_agent_eviction_tests.rs expression: "format!(\"{history}\\n\\nResumed worker mailbox:\\n{mailbox}\")" --- -Scenario: A V3 parent spawns a worker, checks its status, and sends it an encrypted message after eviction. The same worker resumes with the original assignment and the new message. Complete model streams are grouped as parent, then worker. +Scenario: A V3 worker finishes without sending an automatic result. After eviction an encrypted message wakes the same worker, which reports to the idle parent and stops. ## Window 1 -- request 1 (turn) -- -00:additional_tools/developer (2; hash=e4ca971ebcca4486): +00:additional_tools/developer (2; hash=9d31d4d6c0422f40): - namespace/functions; hash=f33f647fee88e25e - custom/exec - function/wait - function/request_user_input - - namespace/collaboration: Tools for spawning and managing sub-agents.; hash=170d28937de769cb + - namespace/collaboration: Tools for spawning and managing sub-agents.; hash=5a8e688fb27f3fd9 - function/list_agents - function/send_message - function/spawn_agent @@ -38,22 +38,21 @@ Scenario: A V3 parent spawns a worker, checks its status, and sends it an encryp -- request 4 (turn) -- 10:function_call/collaboration.list_agents:{"path_prefix":"/root/worker"} 11:function_call_output:{"agents":[{"agent_name":"/root/worker","agent_status":{"completed":"Mira owns the API migration."}}]} -12:agent_message -- request 5 (turn) -- -13:message/user: +12:message/user: Run send_message for the API migration. -- request 6 (turn) -- -14:function_call/collaboration.send_message:{"message":"Continue the migration using the new API.","target":"worker"} -15:function_call_output: +13:function_call/collaboration.send_message:{"message":"Continue the migration using the new API.","target":"worker"} +14:function_call_output: ## Window 2 (after request 6: input diverged at item 03) -- request 7 (turn) -- -00:additional_tools/developer (2; hash=e4ca971ebcca4486): +00:additional_tools/developer (2; hash=9d31d4d6c0422f40): - namespace/functions; hash=f33f647fee88e25e - custom/exec - function/wait - function/request_user_input - - namespace/collaboration: Tools for spawning and managing sub-agents.; hash=170d28937de769cb + - namespace/collaboration: Tools for spawning and managing sub-agents.; hash=5a8e688fb27f3fd9 - function/list_agents - function/send_message - function/spawn_agent diff --git a/codex-rs/core/tests/suite/turn_input_submission.rs b/codex-rs/core/tests/suite/turn_input_submission.rs index 151ad99906..f258938bdd 100644 --- a/codex-rs/core/tests/suite/turn_input_submission.rs +++ b/codex-rs/core/tests/suite/turn_input_submission.rs @@ -247,8 +247,11 @@ async fn turn_extension_data_is_captured_for_automatic_turns() -> anyhow::Result Ok(()) } -#[derive(Debug)] -struct TestAdmission(AtomicBool, tokio::sync::watch::Sender<()>); +#[derive(Debug, Default)] +pub(super) struct TestAdmission( + pub(super) AtomicBool, + pub(super) tokio::sync::watch::Sender<()>, +); impl TurnStartAdmission for TestAdmission { fn admit_turn_start(&self) -> Option> { @@ -848,9 +851,9 @@ async fn recover_turn_if_idle_preserves_id_and_resumes_plan_mode() { } #[derive(Default)] -struct RecoveryLifecycleBarrier { - block_next: AtomicBool, - entered: tokio::sync::Notify, +pub(super) struct RecoveryLifecycleBarrier { + pub(super) block_next: AtomicBool, + pub(super) entered: tokio::sync::Notify, block_stop: AtomicBool, stop_entered: tokio::sync::Notify, release_stop: tokio::sync::Notify, diff --git a/codex-rs/features/src/feature_configs.rs b/codex-rs/features/src/feature_configs.rs index dc3851dcd6..4bdcb66b74 100644 --- a/codex-rs/features/src/feature_configs.rs +++ b/codex-rs/features/src/feature_configs.rs @@ -456,7 +456,8 @@ pub struct MultiAgentV2ConfigToml { /// Hide native multi-agent tools while retaining the V2 runtime for host-provided tools. #[serde(skip_serializing_if = "Option::is_none")] pub disable_native_tools: Option, - /// Disable the model's direct-message tools; spawning and automatic child results remain available. + /// Disable V2 direct-message tools while retaining automatic child results. + /// V3 workers use `send_message` to report results, so V3 always includes it in the native tool set. #[serde(skip_serializing_if = "Option::is_none")] pub disable_direct_message: Option, /// Keep the message board in memory for a training session, including ephemeral sessions. diff --git a/codex-rs/prompts/src/model_messages/multi_agent.rs b/codex-rs/prompts/src/model_messages/multi_agent.rs index 513649e6fa..51b552f033 100644 --- a/codex-rs/prompts/src/model_messages/multi_agent.rs +++ b/codex-rs/prompts/src/model_messages/multi_agent.rs @@ -80,8 +80,8 @@ impl<'a> ResolvedMultiAgentMessages<'a> { let mode = messages.and_then(|messages| messages.mode.as_ref()); let (root, subagent) = if role_version == MultiAgentVersion::V3 { ( - "You are `/root`. Use `spawn_agent` to delegate work. Use `send_message` to give a worker more input, including after it stops. Use `stop_agent` to stop a worker when its work is no longer needed.", - "You are a worker. Use `send_message` to communicate with your parent or other workers. Call `stop_agent` with your own canonical path to release your slot. A later message resumes your conversation.", + "You are `/root`. Use `spawn_agent` to delegate work. Use `send_message` to give a worker more input, including after it stops. Workers report results through messages. Use `stop_agent` to stop a worker when its work is no longer needed.", + "You are a worker. Use `send_message` to communicate with your parent or other workers. Your parent does not automatically receive your final answer. Send your result to your parent with `send_message`. Call `stop_agent` with your own canonical path when done to release your slot. A later message resumes your conversation.", ) } else { (