diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 4efc2af72c..ef71341db4 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -4,6 +4,8 @@ use crate::agent::registry::AgentRegistry; use crate::agent::role::DEFAULT_ROLE_NAME; use crate::agent::role::resolve_role_config; use crate::agent::status::is_final; +use crate::agent_communication::AgentCommunicationContext; +use crate::agent_communication::AgentCommunicationKind; use crate::codex_thread::ThreadConfigSnapshot; use crate::config::Config; use crate::config::RolloutBudgetConfig; @@ -24,7 +26,6 @@ use codex_protocol::error::Result as CodexResult; use codex_protocol::models::ContentItem; use codex_protocol::models::MessagePhase; use codex_protocol::models::ResponseItem; -use codex_protocol::protocol::AgentCommunicationKind; use codex_protocol::protocol::InitialHistory; use codex_protocol::protocol::InterAgentCommunication; use codex_protocol::protocol::MultiAgentVersion; @@ -68,6 +69,7 @@ pub(crate) struct SpawnAgentOptions { pub(crate) fork_mode: Option, pub(crate) parent_thread_id: Option, pub(crate) environments: Option>, + pub(crate) agent_communication_context: Option, } #[derive(Clone, Debug)] @@ -77,6 +79,11 @@ pub(crate) struct LiveAgent { pub(crate) status: AgentStatus, } +enum SubmissionId<'a> { + Generated, + Provided(&'a str), +} + #[derive(Clone, Debug, Serialize, PartialEq, Eq)] pub(crate) struct ListedAgent { pub(crate) agent_name: String, @@ -145,8 +152,13 @@ impl AgentControl { let state = self.upgrade()?; self.ensure_execution_capacity_for_op(agent_id, &initial_operation) .await?; - self.send_input_after_capacity_check(agent_id, &state, initial_operation) - .await + self.send_input_after_capacity_check( + agent_id, + &state, + initial_operation, + SubmissionId::Generated, + ) + .await } async fn send_input_after_capacity_check( @@ -154,6 +166,7 @@ impl AgentControl { agent_id: ThreadId, state: &Arc, initial_operation: Op, + submission_id: SubmissionId<'_>, ) -> CodexResult { let last_task_message = match &initial_operation { Op::InterAgentCommunication { communication } => { @@ -161,12 +174,16 @@ impl AgentControl { } _ => non_empty_task_message(render_input_preview(&initial_operation)), }; + let send_result = match submission_id { + SubmissionId::Generated => state.send_op(agent_id, initial_operation).await, + SubmissionId::Provided(id) => { + state + .send_op_with_id(agent_id, id.to_string(), initial_operation) + .await + } + }; let result = self - .handle_thread_request_result( - agent_id, - state, - state.send_op(agent_id, initial_operation).await, - ) + .handle_thread_request_result(agent_id, state, send_result) .await; if result.is_ok() { match last_task_message { @@ -183,23 +200,23 @@ impl AgentControl { &self, agent_id: ThreadId, communication: InterAgentCommunication, + context: AgentCommunicationContext, ) -> CodexResult { - let last_task_message = last_task_message_from_communication(&communication); + crate::agent_communication::emit_agent_communication_created( + &context, + &communication, + agent_id, + ); let state = self.upgrade()?; let op = Op::InterAgentCommunication { communication }; self.ensure_execution_capacity_for_op(agent_id, &op).await?; - let result = self - .handle_thread_request_result(agent_id, &state, state.send_op(agent_id, op).await) - .await; - if result.is_ok() { - match last_task_message { - Some(last_task_message) => self - .state - .update_last_task_message(agent_id, last_task_message), - None => self.state.clear_last_task_message(agent_id), - } - } - result + self.send_input_after_capacity_check( + agent_id, + &state, + op, + SubmissionId::Provided(context.id()), + ) + .await } /// Interrupt the current task for an existing agent thread. @@ -474,26 +491,23 @@ impl AgentControl { ) else { return; }; - let mut communication = InterAgentCommunication::new( + let communication = InterAgentCommunication::new( child_agent_path, parent_agent_path, Vec::new(), message, /*trigger_turn*/ false, ); - communication.agent_communication_metadata = Some( - crate::agent_communication::new_agent_communication_metadata( - AgentCommunicationKind::Result, - child_thread_id, - /*source_call_id*/ None, - ), - ); - crate::agent_communication::emit_agent_communication_created( - &communication, - parent_thread_id, + let communication_context = AgentCommunicationContext::without_source_call( + AgentCommunicationKind::Result, + child_thread_id, ); let _ = control - .send_inter_agent_communication(parent_thread_id, communication) + .send_inter_agent_communication( + parent_thread_id, + communication, + communication_context, + ) .await; return; } diff --git a/codex-rs/core/src/agent/control/spawn.rs b/codex-rs/core/src/agent/control/spawn.rs index 114ab09e88..96658be44e 100644 --- a/codex-rs/core/src/agent/control/spawn.rs +++ b/codex-rs/core/src/agent/control/spawn.rs @@ -356,17 +356,26 @@ impl AgentControl { ) .await; - if multi_agent_version == MultiAgentVersion::V2 - && let Op::InterAgentCommunication { communication } = &initial_operation - { + if let (Some(context), Op::InterAgentCommunication { communication }) = ( + options.agent_communication_context.as_ref(), + &initial_operation, + ) { crate::agent_communication::emit_agent_communication_created( + context, communication, new_thread.thread_id, ); } - - self.send_input_after_capacity_check(new_thread.thread_id, &state, initial_operation) - .await?; + self.send_input_after_capacity_check( + new_thread.thread_id, + &state, + initial_operation, + match options.agent_communication_context.as_ref() { + Some(context) => SubmissionId::Provided(context.id()), + None => SubmissionId::Generated, + }, + ) + .await?; if multi_agent_version != MultiAgentVersion::V2 { let child_reference = agent_metadata .agent_path diff --git a/codex-rs/core/src/agent/control_tests.rs b/codex-rs/core/src/agent/control_tests.rs index 8016ba8d66..a84f21c204 100644 --- a/codex-rs/core/src/agent/control_tests.rs +++ b/codex-rs/core/src/agent/control_tests.rs @@ -3,6 +3,7 @@ use crate::CodexThread; use crate::StateDbHandle; use crate::ThreadManager; use crate::agent::agent_status_from_event; +use crate::agent_communication::AgentCommunicationKind; use crate::config::AgentRoleConfig; use crate::config::Config; use crate::config::ConfigBuilder; @@ -23,7 +24,6 @@ use codex_protocol::config_types::ModeKind; use codex_protocol::models::ContentItem; use codex_protocol::models::MessagePhase; use codex_protocol::models::ResponseItem; -use codex_protocol::protocol::AgentCommunicationKind; use codex_protocol::protocol::CompactedItem; use codex_protocol::protocol::ErrorEvent; use codex_protocol::protocol::EventMsg; @@ -459,29 +459,22 @@ async fn failed_communication_send_emits_created_without_enqueued() { let harness = AgentControlHarness::new().await; let sender_thread_id = ThreadId::new(); let receiver_thread_id = ThreadId::new(); - let metadata = codex_protocol::protocol::AgentCommunicationMetadata { - id: uuid::Uuid::new_v4().to_string(), - kind: codex_protocol::protocol::AgentCommunicationKind::Message, + let context = crate::agent_communication::AgentCommunicationContext::from_tool_call( + AgentCommunicationKind::Message, sender_thread_id, - source_call_id: Some("call-1".to_string()), - }; - let id = metadata.id.clone(); - let mut communication = InterAgentCommunication::new( + "call-1", + ); + let id = context.id().to_string(); + let communication = InterAgentCommunication::new( AgentPath::root(), AgentPath::try_from("/root/missing").expect("agent path"), Vec::new(), "mail".to_string(), /*trigger_turn*/ false, ); - communication.agent_communication_metadata = Some(metadata); - crate::agent_communication::emit_agent_communication_created( - &communication, - receiver_thread_id, - ); - let err = harness .control - .send_inter_agent_communication(receiver_thread_id, communication) + .send_inter_agent_communication(receiver_thread_id, communication, context) .await .expect_err("send should fail for missing receiver"); assert_matches!(err, CodexErr::ThreadNotFound(id) if id == receiver_thread_id); @@ -594,12 +587,17 @@ async fn send_inter_agent_communication_without_turn_queues_message_without_trig /*trigger_turn*/ false, ); + let context = crate::agent_communication::AgentCommunicationContext::without_source_call( + AgentCommunicationKind::Message, + ThreadId::new(), + ); + let communication_id = context.id().to_string(); let submission_id = harness .control - .send_inter_agent_communication(thread_id, communication.clone()) + .send_inter_agent_communication(thread_id, communication.clone(), context) .await .expect("send_inter_agent_communication should succeed"); - assert!(!submission_id.is_empty()); + assert_eq!(submission_id, communication_id); let expected = ( thread_id, @@ -721,7 +719,14 @@ async fn ensure_v2_agent_loaded_reloads_registered_unloaded_agent() { ); harness .control - .send_inter_agent_communication(spawned_agent.thread_id, communication.clone()) + .send_inter_agent_communication( + spawned_agent.thread_id, + communication.clone(), + crate::agent_communication::AgentCommunicationContext::without_source_call( + AgentCommunicationKind::Message, + ThreadId::new(), + ), + ) .await .expect("send_inter_agent_communication should succeed after reload"); let expected = ( @@ -868,7 +873,14 @@ async fn encrypted_inter_agent_communication_clears_existing_last_task_message() ); harness .control - .send_inter_agent_communication(spawned_agent.thread_id, communication) + .send_inter_agent_communication( + spawned_agent.thread_id, + communication, + crate::agent_communication::AgentCommunicationContext::without_source_call( + AgentCommunicationKind::Followup, + ThreadId::new(), + ), + ) .await .expect("send_inter_agent_communication should succeed"); @@ -2191,24 +2203,10 @@ async fn multi_agent_v2_completion_queues_message_for_direct_parent() { if thread_id != worker_thread_id { continue; } - let Op::InterAgentCommunication { mut communication } = op else { + let Op::InterAgentCommunication { communication } = op else { continue; }; - let metadata = communication.agent_communication_metadata.take(); if communication == expected { - let metadata = metadata.expect("completion communication metadata"); - assert_eq!( - ( - metadata.kind, - metadata.sender_thread_id, - metadata.source_call_id, - ), - ( - AgentCommunicationKind::Result, - tester_thread_id, - /*source_call_id*/ None, - ) - ); return; } } diff --git a/codex-rs/core/src/agent_communication.rs b/codex-rs/core/src/agent_communication.rs index e82004e700..571af936e2 100644 --- a/codex-rs/core/src/agent_communication.rs +++ b/codex-rs/core/src/agent_communication.rs @@ -1,65 +1,94 @@ use codex_protocol::ThreadId; -use codex_protocol::protocol::AgentCommunicationKind; -use codex_protocol::protocol::AgentCommunicationMetadata; -use codex_protocol::protocol::AgentCommunicationState; use codex_protocol::protocol::InterAgentCommunication; use uuid::Uuid; -pub(crate) fn new_agent_communication_metadata( +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum AgentCommunicationKind { + InitialTask, + Message, + Followup, + Result, +} + +impl AgentCommunicationKind { + fn as_str(self) -> &'static str { + match self { + Self::InitialTask => "initialTask", + Self::Message => "message", + Self::Followup => "followup", + Self::Result => "result", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct AgentCommunicationContext { + id: String, kind: AgentCommunicationKind, sender_thread_id: ThreadId, - source_call_id: Option<&str>, -) -> AgentCommunicationMetadata { - AgentCommunicationMetadata { - id: Uuid::new_v4().to_string(), - kind, - sender_thread_id, - source_call_id: source_call_id.map(str::to_owned), + source_call_id: Option, +} + +impl AgentCommunicationContext { + pub(crate) fn from_tool_call( + kind: AgentCommunicationKind, + sender_thread_id: ThreadId, + source_call_id: &str, + ) -> Self { + Self::new(kind, sender_thread_id, Some(source_call_id.to_string())) + } + + pub(crate) fn without_source_call( + kind: AgentCommunicationKind, + sender_thread_id: ThreadId, + ) -> Self { + Self::new(kind, sender_thread_id, None) + } + + fn new( + kind: AgentCommunicationKind, + sender_thread_id: ThreadId, + source_call_id: Option, + ) -> Self { + Self { + id: Uuid::now_v7().to_string(), + kind, + sender_thread_id, + source_call_id, + } + } + + pub(crate) fn id(&self) -> &str { + &self.id } } pub(crate) fn emit_agent_communication_created( + context: &AgentCommunicationContext, communication: &InterAgentCommunication, receiver_thread_id: ThreadId, -) { - let Some(metadata) = communication.agent_communication_metadata.as_ref() else { - return; - }; - emit_agent_communication_event( - metadata, - AgentCommunicationState::Created, - receiver_thread_id, - communication_content(communication), - ); -} - -fn emit_agent_communication_event( - metadata: &AgentCommunicationMetadata, - state: AgentCommunicationState, - receiver_thread_id: ThreadId, - content: &str, ) { tracing::trace!( { event.name = "codex.agent_communication", - communication_id = %metadata.id, - kind = metadata.kind.as_str(), - state = state.as_str(), - sender_thread_id = %metadata.sender_thread_id, + communication_id = %context.id, + kind = context.kind.as_str(), + state = "created", + sender_thread_id = %context.sender_thread_id, receiver_thread_id = %receiver_thread_id, - content, - source_call_id = metadata.source_call_id.as_deref(), + content = communication_content(communication), + source_call_id = context.source_call_id.as_deref(), }, "agent communication updated" ); } -pub(crate) fn emit_agent_communication_enqueued(metadata: AgentCommunicationMetadata) { +pub(crate) fn emit_agent_communication_enqueued(id: &str) { tracing::trace!( { event.name = "codex.agent_communication", - communication_id = %metadata.id, - state = AgentCommunicationState::Enqueued.as_str(), + communication_id = id, + state = "enqueued", }, "agent communication updated" ); diff --git a/codex-rs/core/src/agent_communication_tests.rs b/codex-rs/core/src/agent_communication_tests.rs index 504d734e56..ddd6e0ab35 100644 --- a/codex-rs/core/src/agent_communication_tests.rs +++ b/codex-rs/core/src/agent_communication_tests.rs @@ -26,29 +26,26 @@ fn emits_structured_lifecycle_events_at_trace() { let sender_thread_id = ThreadId::new(); let receiver_thread_id = ThreadId::new(); - let mut communication = InterAgentCommunication::new( + let communication = InterAgentCommunication::new( AgentPath::root(), AgentPath::root(), Vec::new(), "hello".to_string(), /*trigger_turn*/ false, ); - let metadata = new_agent_communication_metadata( + let context = AgentCommunicationContext::from_tool_call( AgentCommunicationKind::Message, sender_thread_id, - Some("call-1"), + "call-1", ); - communication.agent_communication_metadata = Some(metadata.clone()); - emit_agent_communication_created(&communication, receiver_thread_id); - emit_agent_communication_enqueued(metadata.clone()); + emit_agent_communication_created(&context, &communication, receiver_thread_id); + emit_agent_communication_enqueued(context.id()); - let result_metadata = new_agent_communication_metadata( + let result_context = AgentCommunicationContext::without_source_call( AgentCommunicationKind::Result, receiver_thread_id, - /*source_call_id*/ None, ); - communication.agent_communication_metadata = Some(result_metadata.clone()); - emit_agent_communication_created(&communication, sender_thread_id); + emit_agent_communication_created(&result_context, &communication, sender_thread_id); let events = String::from_utf8(output.lock().expect("buffer lock").clone()) .expect("JSON logs should be UTF-8") @@ -63,7 +60,7 @@ fn emits_structured_lifecycle_events_at_trace() { json!({ "message": "agent communication updated", "event.name": "codex.agent_communication", - "communication_id": metadata.id, + "communication_id": context.id(), "kind": "message", "state": "created", "sender_thread_id": sender_thread_id.to_string(), @@ -79,7 +76,7 @@ fn emits_structured_lifecycle_events_at_trace() { json!({ "message": "agent communication updated", "event.name": "codex.agent_communication", - "communication_id": metadata.id, + "communication_id": context.id(), "state": "enqueued", }) ); @@ -88,7 +85,7 @@ fn emits_structured_lifecycle_events_at_trace() { json!({ "message": "agent communication updated", "event.name": "codex.agent_communication", - "communication_id": result_metadata.id, + "communication_id": result_context.id(), "kind": "result", "state": "created", "sender_thread_id": receiver_thread_id.to_string(), @@ -100,14 +97,16 @@ fn emits_structured_lifecycle_events_at_trace() { #[test] fn content_prefers_plaintext_and_falls_back_to_encrypted_content() { - let mut plaintext = InterAgentCommunication::new( - AgentPath::root(), - AgentPath::root(), - Vec::new(), - "plain".to_string(), - /*trigger_turn*/ false, - ); - plaintext.encrypted_content = Some("encrypted".to_string()); + let plaintext = InterAgentCommunication { + encrypted_content: Some("encrypted".to_string()), + ..InterAgentCommunication::new( + AgentPath::root(), + AgentPath::root(), + Vec::new(), + "plain".to_string(), + /*trigger_turn*/ false, + ) + }; let encrypted = InterAgentCommunication::new_encrypted( AgentPath::root(), AgentPath::root(), diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index 43b4d848e1..f4b2c72f76 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -279,16 +279,13 @@ pub(super) async fn user_input_or_turn_inner( pub async fn inter_agent_communication( sess: &Arc, sub_id: String, - mut communication: InterAgentCommunication, + communication: InterAgentCommunication, ) { let trigger_turn = communication.trigger_turn; - let communication_metadata = communication.agent_communication_metadata.take(); sess.input_queue .enqueue_mailbox_communication(communication) .await; - if let Some(metadata) = communication_metadata { - crate::agent_communication::emit_agent_communication_enqueued(metadata); - } + crate::agent_communication::emit_agent_communication_enqueued(&sub_id); if trigger_turn { sess.maybe_start_turn_for_pending_work_with_sub_id(sub_id) .await; diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index ee05accaa5..9386987231 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -14,6 +14,7 @@ use crate::agent::AgentControl; use crate::agent::AgentStatus; use crate::agent::agent_status_from_event; use crate::agent::status::is_final; +use crate::agent_communication::AgentCommunicationKind; use crate::attestation::AttestationProvider; use crate::build_available_skills; use crate::compact; @@ -111,7 +112,6 @@ use codex_protocol::openai_models::ModelPreset; use codex_protocol::permissions::FileSystemSandboxPolicy; use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::protocol::AdditionalContextEntry; -use codex_protocol::protocol::AgentCommunicationKind; use codex_protocol::protocol::FileChange; use codex_protocol::protocol::HasLegacyEvent; use codex_protocol::protocol::InterAgentCommunication; @@ -893,7 +893,7 @@ impl Codex { /// /// Some use cases take advantage of the fact that these are UUID7 which /// encodes a timestamp, so think carefully before changing this. -fn new_submission_id() -> String { +pub(crate) fn new_submission_id() -> String { Uuid::now_v7().to_string() } @@ -1861,28 +1861,22 @@ impl Session { .rollout_thread_trace .is_enabled() .then(|| message.clone()); - let mut communication = InterAgentCommunication::new( + let communication = InterAgentCommunication::new( child_agent_path.clone(), parent_agent_path, Vec::new(), message, /*trigger_turn*/ false, ); - communication.agent_communication_metadata = Some( - crate::agent_communication::new_agent_communication_metadata( + let communication_context = + crate::agent_communication::AgentCommunicationContext::without_source_call( AgentCommunicationKind::Result, self.thread_id, - /*source_call_id*/ None, - ), - ); - crate::agent_communication::emit_agent_communication_created( - &communication, - parent_thread_id, - ); + ); if let Err(err) = self .services .agent_control - .send_inter_agent_communication(parent_thread_id, communication) + .send_inter_agent_communication(parent_thread_id, communication, communication_context) .await { debug!("failed to notify parent thread {parent_thread_id}: {err}"); diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index db69b00e8f..aa36863ec5 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -9806,29 +9806,15 @@ async fn mailbox_enqueue_emits_enqueued_communication_with_same_id() { let _guard = tracing::subscriber::set_default(subscriber); let (session, _) = make_session_and_context().await; - let sender_thread_id = ThreadId::new(); let id = Uuid::new_v4().to_string(); - let mut communication = InterAgentCommunication::new( + let communication = InterAgentCommunication::new( AgentPath::root(), AgentPath::root(), Vec::new(), "mail".to_string(), /*trigger_turn*/ false, ); - communication.agent_communication_metadata = - Some(codex_protocol::protocol::AgentCommunicationMetadata { - id: id.clone(), - kind: codex_protocol::protocol::AgentCommunicationKind::Message, - sender_thread_id, - source_call_id: Some("call-1".to_string()), - }); - - super::handlers::inter_agent_communication( - &Arc::new(session), - "turn-1".to_string(), - communication, - ) - .await; + super::handlers::inter_agent_communication(&Arc::new(session), id.clone(), communication).await; let events = String::from_utf8(output.lock().expect("buffer lock").clone()) .expect("JSON logs should be UTF-8") diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index 4ea86cb33d..4f2e4c261b 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -13,6 +13,7 @@ use crate::session::Codex; use crate::session::CodexSpawnArgs; use crate::session::CodexSpawnOk; use crate::session::INITIAL_SUBMIT_ID; +use crate::session::new_submission_id; use crate::session::resolve_multi_agent_version; use crate::tasks::InterruptedTurnHistoryMarker; use crate::tasks::interrupted_turn_history_marker; @@ -56,6 +57,7 @@ use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::SessionConfiguredEvent; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; +use codex_protocol::protocol::Submission; use codex_protocol::protocol::ThreadHistoryMode; use codex_protocol::protocol::ThreadSource; use codex_protocol::protocol::TurnAbortReason; @@ -1146,13 +1148,31 @@ impl ThreadManagerState { /// Send an operation to a thread by ID. pub(crate) async fn send_op(&self, thread_id: ThreadId, op: Op) -> CodexResult { + self.send_op_with_id(thread_id, new_submission_id(), op) + .await + } + + pub(crate) async fn send_op_with_id( + &self, + thread_id: ThreadId, + id: String, + op: Op, + ) -> CodexResult { let thread = self.get_thread(thread_id).await?; if let Some(ops_log) = &self.ops_log && let Ok(mut log) = ops_log.lock() { log.push((thread_id, op.clone())); } - thread.submit(op).await + thread + .submit_with_id(Submission { + id: id.clone(), + op, + client_user_message_id: None, + trace: None, + }) + .await?; + Ok(id) } /// Remove a thread from the manager by ID, returning it when present. diff --git a/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs b/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs index 204385934e..9dc8bc208e 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs @@ -132,6 +132,7 @@ async fn handle_spawn_agent( fork_mode: args.fork_context.then_some(SpawnAgentForkMode::FullHistory), parent_thread_id: Some(session.thread_id), environments: Some(turn.environments.to_selections()), + agent_communication_context: None, }, )) .await diff --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.rs index 383c2c8467..092a0abfae 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 @@ -4,9 +4,9 @@ //! resulting `InterAgentCommunication` should wake the target immediately. use super::*; +use crate::agent_communication::AgentCommunicationKind; use crate::tools::context::FunctionToolOutput; use crate::turn_timing::now_unix_timestamp_ms; -use codex_protocol::protocol::AgentCommunicationKind; use codex_protocol::protocol::InterAgentCommunication; #[derive(Clone, Copy, PartialEq, Eq)] @@ -93,23 +93,18 @@ pub(crate) async fn handle_message_string_tool( .session_source .get_agent_path() .unwrap_or_else(AgentPath::root); - let mut communication = + let communication = communication_from_tool_message(author, receiver_agent_path.clone(), message); let communication_kind = match mode { MessageDeliveryMode::QueueOnly => AgentCommunicationKind::Message, MessageDeliveryMode::TriggerTurn => AgentCommunicationKind::Followup, }; - communication.agent_communication_metadata = Some( - crate::agent_communication::new_agent_communication_metadata( + let communication_context = + crate::agent_communication::AgentCommunicationContext::from_tool_call( communication_kind, session.thread_id, - Some(call_id.as_str()), - ), - ); - crate::agent_communication::emit_agent_communication_created( - &communication, - receiver_thread_id, - ); + call_id.as_str(), + ); let resume_config = build_agent_resume_config(turn.as_ref())?; session @@ -121,7 +116,11 @@ pub(crate) async fn handle_message_string_tool( let result = session .services .agent_control - .send_inter_agent_communication(receiver_thread_id, mode.apply(communication)) + .send_inter_agent_communication( + receiver_thread_id, + mode.apply(communication), + communication_context, + ) .await .map_err(|err| collab_agent_error(receiver_thread_id, err)); result?; diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs index db785e3823..a34be00769 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs @@ -4,11 +4,11 @@ use crate::agent::control::SpawnAgentOptions; use crate::agent::next_thread_spawn_depth; use crate::agent::role::DEFAULT_ROLE_NAME; use crate::agent::role::apply_role_to_config; +use crate::agent_communication::AgentCommunicationKind; use crate::tools::handlers::multi_agents_spec::SpawnAgentToolOptions; use crate::tools::handlers::multi_agents_spec::create_spawn_agent_tool_v2; use crate::turn_timing::now_unix_timestamp_ms; use codex_protocol::AgentPath; -use codex_protocol::protocol::AgentCommunicationKind; use codex_protocol::protocol::Op; use codex_tools::ToolSpec; @@ -105,41 +105,39 @@ async fn handle_spawn_agent( "spawned agent is missing a canonical task name".to_string(), ) })?; - let spawned_agent = Box::pin( - session.services.agent_control.spawn_agent_with_metadata( - config, - match initial_operation { - Op::UserInput { items, .. } - if items - .iter() - .all(|item| matches!(item, UserInput::Text { .. })) => - { - let author = turn - .session_source - .get_agent_path() - .unwrap_or_else(AgentPath::root); - let mut communication = - communication_from_tool_message(author, new_agent_path.clone(), message); - communication.agent_communication_metadata = Some( - crate::agent_communication::new_agent_communication_metadata( - AgentCommunicationKind::InitialTask, - session.thread_id, - Some(call_id.as_str()), - ), - ); - Op::InterAgentCommunication { communication } - } - initial_operation => initial_operation, - }, - Some(spawn_source), - SpawnAgentOptions { - fork_parent_spawn_call_id: fork_mode.as_ref().map(|_| call_id.clone()), - fork_mode, - parent_thread_id: Some(session.thread_id), - environments: Some(turn.environments.to_selections()), - }, - ), - ) + let (initial_operation, agent_communication_context) = match initial_operation { + Op::UserInput { items, .. } + if items + .iter() + .all(|item| matches!(item, UserInput::Text { .. })) => + { + let author = turn + .session_source + .get_agent_path() + .unwrap_or_else(AgentPath::root); + let communication = + communication_from_tool_message(author, new_agent_path.clone(), message); + let context = crate::agent_communication::AgentCommunicationContext::from_tool_call( + AgentCommunicationKind::InitialTask, + session.thread_id, + call_id.as_str(), + ); + (Op::InterAgentCommunication { communication }, Some(context)) + } + initial_operation => (initial_operation, None), + }; + let spawned_agent = Box::pin(session.services.agent_control.spawn_agent_with_metadata( + config, + initial_operation, + Some(spawn_source), + SpawnAgentOptions { + fork_parent_spawn_call_id: fork_mode.as_ref().map(|_| call_id.clone()), + fork_mode, + parent_thread_id: Some(session.thread_id), + environments: Some(turn.environments.to_selections()), + agent_communication_context, + }, + )) .await .map_err(collab_spawn_error)?; let new_thread_id = spawned_agent.thread_id; diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index c3179cde1e..96a793bcd3 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -737,11 +737,6 @@ pub struct InterAgentCommunication { #[ts(optional)] pub internal_chat_message_metadata_passthrough: Option, pub trigger_turn: bool, - /// Runtime-only metadata used to emit communication lifecycle records. - #[serde(skip)] - #[schemars(skip)] - #[ts(skip)] - pub agent_communication_metadata: Option, } impl InterAgentCommunication { @@ -761,7 +756,6 @@ impl InterAgentCommunication { encrypted_content: None, internal_chat_message_metadata_passthrough: None, trigger_turn, - agent_communication_metadata: None, } } @@ -781,7 +775,6 @@ impl InterAgentCommunication { encrypted_content: Some(encrypted_content), internal_chat_message_metadata_passthrough: None, trigger_turn, - agent_communication_metadata: None, } } @@ -4279,48 +4272,6 @@ pub struct SubAgentActivityEvent { pub kind: SubAgentActivityKind, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum AgentCommunicationKind { - InitialTask, - Message, - Followup, - Result, -} - -impl AgentCommunicationKind { - pub fn as_str(self) -> &'static str { - match self { - Self::InitialTask => "initialTask", - Self::Message => "message", - Self::Followup => "followup", - Self::Result => "result", - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum AgentCommunicationState { - Created, - Enqueued, -} - -impl AgentCommunicationState { - pub fn as_str(self) -> &'static str { - match self { - Self::Created => "created", - Self::Enqueued => "enqueued", - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct AgentCommunicationMetadata { - pub id: String, - pub kind: AgentCommunicationKind, - pub sender_thread_id: ThreadId, - pub source_call_id: Option, -} - #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)] pub struct CollabWaitingBeginEvent { #[serde(default)] @@ -4569,7 +4520,6 @@ mod tests { encrypted_content: None, internal_chat_message_metadata_passthrough: None, trigger_turn: true, - agent_communication_metadata: None, }; communication.set_turn_id_if_missing("turn-1"); let mut serialized_communication = communication.clone();