Lightweight coding agent that runs in your terminal
Rust
Route agent delivery through captured send requests (#46994)
jif3938a27c1dd6
diff --git a/codex-rs/core/src/agent/api.rs b/codex-rs/core/src/agent/api.rsindex 4868fee6ab..04e2ab4e2d 100644--- a/codex-rs/core/src/agent/api.rs+++ b/codex-rs/core/src/agent/api.rs@@ -199,6 +199,8 @@ pub struct SendRequest {pub struct DeliveryReceipt {pub thread_id: ThreadId,+ /// Recipient identity captured during delivery, for activity and tool output.+ pub metadata: AgentMetadata,/// Acceptance identifier, not evidence that the recipient processed the input.pub submission_id: String,}diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rsindex cf995a0f8d..a819a1cceb 100644--- a/codex-rs/core/src/agent/control.rs+++ b/codex-rs/core/src/agent/control.rs@@ -66,7 +66,6 @@ use tokio::sync::watch;use tracing::warn;use uuid::Uuid;-pub(crate) use self::delivery::MessageDeliveryError;use self::execution::AgentExecutionLimiter;pub(crate) use self::interrupt::AgentInterruptError;pub(crate) use self::interrupt::AgentInterruptOutcome;@@ -82,6 +81,7 @@ mod residency;mod sender_context;mod service_tier;mod spawn;+mod target;mod user_authorization;const MAX_ENVIRONMENT_SUBAGENTS: usize = 8;@@ -439,27 +439,6 @@ impl LocalAgentControl {Some(thread.config_snapshot().await)}- pub(crate) async fn resolve_agent_reference(- &self,- _current_thread_id: ThreadId,- current_session_source: &SessionSource,- agent_reference: &str,- ) -> CodexResult<ThreadId> {- let current_agent_path = current_session_source- .get_agent_path()- .unwrap_or_else(AgentPath::root);- let agent_path = current_agent_path- .resolve(agent_reference)- .map_err(CodexErr::UnsupportedOperation)?;- if let Some(thread_id) = self.state.agent_id_for_path(&agent_path) {- return Ok(thread_id);- }- Err(CodexErr::UnsupportedOperation(format!(- "live agent path `{}` not found",- agent_path.as_str()- )))- }-/// Subscribe to status updates for `agent_id`, yielding the latest value and changes.pub(crate) async fn subscribe_status(&self,diff --git a/codex-rs/core/src/agent/control/delivery.rs b/codex-rs/core/src/agent/control/delivery.rsindex fa6a8ac2b3..0d84f14cae 100644--- a/codex-rs/core/src/agent/control/delivery.rs+++ b/codex-rs/core/src/agent/control/delivery.rs@@ -1,10 +1,11 @@-//! Delivers V2 messages without exposing local loading and eviction to callers.+//! Delivers captured agent input without exposing local loading and eviction to callers.//!//! Target checks precede reload, and queue-only messages retain their non-waking semantics.use super::LocalAgentControl;-use crate::TurnStartOptions;-use crate::agent::child_config::build_agent_resume_config;+use crate::agent::api::AgentInput;+use crate::agent::api::DeliveryReceipt;+use crate::agent::api::SendRequest;use crate::agent::types::AgentMessage;use crate::agent::types::MessageDeliveryMode;use crate::agent_communication::AgentCommunicationContext;@@ -12,10 +13,9 @@ use crate::agent_communication::AgentCommunicationKind;use crate::context::ContextualUserFragment;use crate::context::InterAgentMessage;use crate::context::InterAgentMessageType;-use crate::session::turn_context::TurnContext;use codex_protocol::AgentPath;-use codex_protocol::ThreadId;use codex_protocol::error::CodexErr;+use codex_protocol::error::Result as CodexResult;use codex_protocol::protocol::InterAgentCommunication;impl AgentMessage {@@ -52,75 +52,70 @@ impl AgentMessage {}}-/// Separates request validation from agent runtime failures so adapters retain their error text.-#[derive(Debug)]-pub(crate) enum MessageDeliveryError {- InvalidRequest(String),- Agent(CodexErr),-}-impl LocalAgentControl {- /// Checks and delivers to a resolved target, restoring an evicted runtime when necessary.- ///- /// The caller resolves tool-facing names separately so it can attribute failures and- /// interruptions to the target before delivery starts.- pub(crate) async fn deliver_message(- &self,- caller: ThreadId,- turn: &TurnContext,- target: ThreadId,- message: AgentMessage,- mode: MessageDeliveryMode,- ) -> Result<AgentPath, MessageDeliveryError> {- let receiver_agent = self- .ensure_agent_known(target)- .map_err(MessageDeliveryError::Agent)?;- if mode == MessageDeliveryMode::TriggerTurn- && receiver_agent- .agent_path- .as_ref()- .is_some_and(AgentPath::is_root)- {- return Err(MessageDeliveryError::InvalidRequest(- "Follow-up tasks can't target the root agent".to_string(),- ));- }- let receiver_agent_path = receiver_agent.agent_path.clone().ok_or_else(|| {- MessageDeliveryError::InvalidRequest(- "target agent is missing an agent_path".to_string(),- )- })?;- let resume_config =- build_agent_resume_config(turn).map_err(MessageDeliveryError::InvalidRequest)?;- self.ensure_v2_agent_loaded(resume_config, target, /*parent*/ None)- .await- .map_err(MessageDeliveryError::Agent)?;- let author = turn- .session_source- .get_agent_path()- .unwrap_or_else(AgentPath::root);- let communication = message.into_communication(author, receiver_agent_path.clone(), mode);- let kind = match mode {- MessageDeliveryMode::QueueOnly => AgentCommunicationKind::Message,- MessageDeliveryMode::TriggerTurn => AgentCommunicationKind::Followup,- };- let context = AgentCommunicationContext::new(kind, caller);- let parent_turn_id =- matches!(mode, MessageDeliveryMode::TriggerTurn).then(|| turn.sub_id.clone());- self.send_inter_agent_communication(+ /// Resolves and delivers captured input, restoring an evicted runtime when necessary.+ pub(crate) async fn send(&self, request: SendRequest) -> CodexResult<DeliveryReceipt> {+ let SendRequest {+ caller,target,- communication,- context,- TurnStartOptions {- parent_turn_id,- root_turn_id: turn.turn_metadata_state.root_turn_id(),- turn_trigger: turn.turn_metadata_state.current_turn_trigger(),- cyber_access_program: turn.cyber_access_program,- ..Default::default()- },- )- .await- .map_err(MessageDeliveryError::Agent)?;- Ok(receiver_agent_path)+ resume_config,+ input,+ mut start_options,+ } = request;+ let target = self.resolve_target(caller, &target)?;+ let (metadata, submission_id) = match input {+ AgentInput::UserInput(input) => {+ let receiver = self.get_agent_metadata(target);+ if receiver.is_some() {+ self.ensure_v2_agent_loaded(resume_config, target, /*parent*/ None)+ .await?;+ }+ let submission_id = self.send_input(target, input, start_options).await?;+ (receiver.unwrap_or_default(), submission_id)+ }+ AgentInput::Message { message, mode } => {+ let receiver = self.ensure_agent_known(target)?;+ let author = self+ .ensure_agent_known(caller)?+ .agent_path+ .unwrap_or_else(AgentPath::root);+ if mode == MessageDeliveryMode::TriggerTurn+ && receiver.agent_path.as_ref().is_some_and(AgentPath::is_root)+ {+ return Err(CodexErr::UnsupportedOperation(+ "Follow-up tasks can't target the root agent".to_string(),+ ));+ }+ let receiver_path = receiver.agent_path.clone().ok_or_else(|| {+ CodexErr::UnsupportedOperation(+ "target agent is missing an agent_path".to_string(),+ )+ })?;+ self.ensure_v2_agent_loaded(resume_config, target, /*parent*/ None)+ .await?;+ let communication = message.into_communication(author, receiver_path, mode);+ let kind = match mode {+ MessageDeliveryMode::QueueOnly => {+ start_options.parent_turn_id = None;+ AgentCommunicationKind::Message+ }+ MessageDeliveryMode::TriggerTurn => AgentCommunicationKind::Followup,+ };+ let submission_id = self+ .send_inter_agent_communication(+ target,+ communication,+ AgentCommunicationContext::new(kind, caller),+ start_options,+ )+ .await?;+ (receiver, submission_id)+ }+ };+ Ok(DeliveryReceipt {+ thread_id: target,+ metadata,+ submission_id,+ })}}diff --git a/codex-rs/core/src/agent/control/target.rs b/codex-rs/core/src/agent/control/target.rsnew file mode 100644index 0000000000..33585b561b--- /dev/null+++ b/codex-rs/core/src/agent/control/target.rs@@ -0,0 +1,58 @@+//! Resolves controller targets using the caller's registered identity.+//! Legacy callers can still supply their captured session source for path resolution.++use super::LocalAgentControl;+use crate::agent::api::AgentTarget;+use codex_protocol::AgentPath;+use codex_protocol::ThreadId;+use codex_protocol::error::CodexErr;+use codex_protocol::error::Result as CodexResult;+use codex_protocol::protocol::SessionSource;++impl LocalAgentControl {+ pub(crate) fn resolve_target(+ &self,+ caller: ThreadId,+ target: &AgentTarget,+ ) -> CodexResult<ThreadId> {+ match target {+ AgentTarget::Id(thread_id) => Ok(*thread_id),+ AgentTarget::Reference(reference) => {+ let caller = self.ensure_agent_known(caller)?;+ self.resolve_path_reference(+ &caller.agent_path.unwrap_or_else(AgentPath::root),+ reference,+ )+ }+ }+ }++ pub(crate) async fn resolve_agent_reference(+ &self,+ _current_thread_id: ThreadId,+ current_session_source: &SessionSource,+ agent_reference: &str,+ ) -> CodexResult<ThreadId> {+ let current_agent_path = current_session_source+ .get_agent_path()+ .unwrap_or_else(AgentPath::root);+ self.resolve_path_reference(¤t_agent_path, agent_reference)+ }++ fn resolve_path_reference(+ &self,+ current_agent_path: &AgentPath,+ agent_reference: &str,+ ) -> CodexResult<ThreadId> {+ let agent_path = current_agent_path+ .resolve(agent_reference)+ .map_err(CodexErr::UnsupportedOperation)?;+ if let Some(thread_id) = self.state.agent_id_for_path(&agent_path) {+ return Ok(thread_id);+ }+ Err(CodexErr::UnsupportedOperation(format!(+ "live agent path `{}` not found",+ agent_path.as_str()+ )))+ }+}diff --git a/codex-rs/core/src/agent/control_tests.rs b/codex-rs/core/src/agent/control_tests.rsindex 3e4da44eb6..b1de6b3e97 100644--- a/codex-rs/core/src/agent/control_tests.rs+++ b/codex-rs/core/src/agent/control_tests.rs@@ -1290,13 +1290,22 @@ async fn cold_resume_with_thread_instructions_preserves_lazy_v2_child_inheritanc.session.services.agent_control- .deliver_message(- parent_thread_id,- &turn,- target_thread_id,- AgentMessage::Plaintext("hello after resume".to_string()),- MessageDeliveryMode::QueueOnly,- )+ .send(crate::SendRequest {+ caller: parent_thread_id,+ target: crate::AgentTarget::Id(target_thread_id),+ resume_config: crate::agent::child_config::build_agent_resume_config(&turn)+ .expect("capture resume config"),+ input: crate::AgentInput::Message {+ message: AgentMessage::Plaintext("hello after resume".to_string()),+ mode: MessageDeliveryMode::QueueOnly,+ },+ start_options: TurnStartOptions {+ root_turn_id: turn.turn_metadata_state.root_turn_id(),+ turn_trigger: turn.turn_metadata_state.current_turn_trigger(),+ cyber_access_program: turn.cyber_access_program,+ ..Default::default()+ },+ }).await.expect("message should reload the grandchild");assert_thread_not_loaded(&resumed_manager, worker_thread_id).await;@@ -1406,13 +1415,22 @@ async fn v2_sibling_reload_preserves_shared_instructions_after_root_unloads(shar.session.services.agent_control- .deliver_message(- sender_id,- &sender_turn,- target_id,- AgentMessage::Plaintext("wake the sibling".to_string()),- MessageDeliveryMode::QueueOnly,- )+ .send(crate::SendRequest {+ caller: sender_id,+ target: crate::AgentTarget::Id(target_id),+ resume_config: crate::agent::child_config::build_agent_resume_config(&sender_turn)+ .expect("capture resume config"),+ input: crate::AgentInput::Message {+ message: AgentMessage::Plaintext("wake the sibling".to_string()),+ mode: MessageDeliveryMode::QueueOnly,+ },+ start_options: TurnStartOptions {+ root_turn_id: sender_turn.turn_metadata_state.root_turn_id(),+ turn_trigger: sender_turn.turn_metadata_state.current_turn_trigger(),+ cyber_access_program: sender_turn.cyber_access_program,+ ..Default::default()+ },+ }).await.expect("reload target from its sibling");let resumed = harnessdiff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/message_tool.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/message_tool.rsindex 826b3f1835..cbf5ff5436 100644--- a/codex-rs/core/src/tools/handlers/multi_agents_v2/message_tool.rs+++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/message_tool.rs@@ -5,9 +5,14 @@use super::analytics::ToolCallAnalytics;use super::*;-use crate::agent::control::MessageDeliveryError;+use crate::TurnStartOptions;+use crate::agent::api::AgentInput;+use crate::agent::api::AgentTarget;+use crate::agent::api::SendRequest;+use crate::agent::child_config::build_agent_resume_config;use crate::agent::types::MessageDeliveryMode;use crate::tools::context::FunctionToolOutput;+use codex_protocol::error::CodexErrorDetails;#[derive(Debug, Deserialize)]#[serde(deny_unknown_fields)]@@ -52,23 +57,40 @@ pub(super) async fn handle_message_string_tool(} = invocation;let receiver_thread_id = resolve_agent_target(&session, &turn, &target).await?;analytics.set_receiver(receiver_thread_id);- let receiver_agent_path = session+ let resume_config =+ build_agent_resume_config(&turn).map_err(FunctionCallError::RespondToModel)?;+ let receipt = session.services.agent_control- .deliver_message(- session.thread_id,- &turn,- receiver_thread_id,- agent_message_from_tool(message, &source),- mode,- )+ .send(SendRequest {+ caller: session.thread_id,+ target: AgentTarget::Id(receiver_thread_id),+ resume_config,+ input: AgentInput::Message {+ message: agent_message_from_tool(message, &source),+ mode,+ },+ start_options: TurnStartOptions {+ parent_turn_id: (mode == MessageDeliveryMode::TriggerTurn)+ .then(|| turn.sub_id.clone()),+ root_turn_id: turn.turn_metadata_state.root_turn_id(),+ turn_trigger: turn.turn_metadata_state.current_turn_trigger(),+ cyber_access_program: turn.cyber_access_program,+ ..Default::default()+ },+ }).await- .map_err(|err| match err {- MessageDeliveryError::InvalidRequest(message) => {- FunctionCallError::RespondToModel(message)+ .map_err(|err| match err.details() {+ CodexErrorDetails::UnsupportedOperation(message)+ if message != "thread manager dropped" =>+ {+ FunctionCallError::RespondToModel(message.clone())}- MessageDeliveryError::Agent(err) => collab_agent_error(receiver_thread_id, err),+ _ => collab_agent_error(receiver_thread_id, err),})?;+ let receiver_agent_path = receipt.metadata.agent_path.ok_or_else(|| {+ FunctionCallError::RespondToModel("target agent is missing an agent_path".to_string())+ })?;emit_sub_agent_activity(&session,&turn,