From 0e35d88be194e41e035ffb65b5f61ae12cf156d2 Mon Sep 17 00:00:00 2001 From: Nikil Pancha Date: Fri, 26 Jun 2026 14:49:14 -0700 Subject: [PATCH] Add first-class agent communication events --- codex-rs/core/Cargo.toml | 2 +- codex-rs/core/src/agent/control.rs | 14 +- codex-rs/core/src/agent/control/spawn.rs | 9 ++ codex-rs/core/src/agent/control_tests.rs | 113 +++++++++++++--- codex-rs/core/src/agent_communication.rs | 81 ++++++++++++ .../core/src/agent_communication_tests.rs | 121 ++++++++++++++++++ codex-rs/core/src/lib.rs | 1 + codex-rs/core/src/session/handlers.rs | 6 +- codex-rs/core/src/session/mod.rs | 14 +- codex-rs/core/src/session/tests.rs | 66 ++++++++++ .../handlers/multi_agents_v2/message_tool.rs | 29 ++++- .../tools/handlers/multi_agents_v2/spawn.rs | 10 +- codex-rs/feedback/src/lib.rs | 25 +++- codex-rs/protocol/src/protocol.rs | 50 ++++++++ codex-rs/state/src/log_db.rs | 1 + codex-rs/state/src/log_db_filter_tests.rs | 8 +- 16 files changed, 514 insertions(+), 36 deletions(-) create mode 100644 codex-rs/core/src/agent_communication.rs create mode 100644 codex-rs/core/src/agent_communication_tests.rs diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 4435a2eb63..ecbabb2641 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -157,7 +157,7 @@ serial_test = { workspace = true } tempfile = { workspace = true } test-log = { workspace = true } tracing-opentelemetry = { workspace = true } -tracing-subscriber = { workspace = true } +tracing-subscriber = { workspace = true, features = ["json"] } tracing-test = { workspace = true, features = ["no-env-filter"] } walkdir = { workspace = true } wiremock = { workspace = true } diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 49bbab0f87..4efc2af72c 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -24,6 +24,7 @@ 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; @@ -473,13 +474,24 @@ impl AgentControl { ) else { return; }; - let communication = InterAgentCommunication::new( + let mut 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 _ = control .send_inter_agent_communication(parent_thread_id, communication) .await; diff --git a/codex-rs/core/src/agent/control/spawn.rs b/codex-rs/core/src/agent/control/spawn.rs index c4c40577ca..114ab09e88 100644 --- a/codex-rs/core/src/agent/control/spawn.rs +++ b/codex-rs/core/src/agent/control/spawn.rs @@ -356,6 +356,15 @@ impl AgentControl { ) .await; + if multi_agent_version == MultiAgentVersion::V2 + && let Op::InterAgentCommunication { communication } = &initial_operation + { + crate::agent_communication::emit_agent_communication_created( + communication, + new_thread.thread_id, + ); + } + self.send_input_after_capacity_check(new_thread.thread_id, &state, initial_operation) .await?; if multi_agent_version != MultiAgentVersion::V2 { diff --git a/codex-rs/core/src/agent/control_tests.rs b/codex-rs/core/src/agent/control_tests.rs index 9863bfb7e2..8016ba8d66 100644 --- a/codex-rs/core/src/agent/control_tests.rs +++ b/codex-rs/core/src/agent/control_tests.rs @@ -23,6 +23,7 @@ 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; @@ -431,6 +432,70 @@ async fn send_input_errors_when_thread_missing() { assert_matches!(err, CodexErr::ThreadNotFound(id) if id == thread_id); } +#[tokio::test] +async fn failed_communication_send_emits_created_without_enqueued() { + use tracing_subscriber::filter::LevelFilter; + use tracing_subscriber::filter::Targets; + use tracing_subscriber::layer::SubscriberExt; + use tracing_test::internal::MockWriter; + + let output: &'static std::sync::Mutex> = + Box::leak(Box::new(std::sync::Mutex::new(Vec::new()))); + let subscriber = tracing_subscriber::registry() + .with( + Targets::new() + .with_default(LevelFilter::OFF) + .with_target("codex_core::agent_communication", LevelFilter::TRACE), + ) + .with( + tracing_subscriber::fmt::layer() + .json() + .with_current_span(false) + .with_span_list(false) + .with_writer(MockWriter::new(output)), + ); + let _guard = tracing::subscriber::set_default(subscriber); + + 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, + sender_thread_id, + source_call_id: Some("call-1".to_string()), + }; + let id = metadata.id.clone(); + let mut 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) + .await + .expect_err("send should fail for missing receiver"); + assert_matches!(err, CodexErr::ThreadNotFound(id) if id == receiver_thread_id); + + let events = String::from_utf8(output.lock().expect("buffer lock").clone()) + .expect("JSON logs should be UTF-8") + .lines() + .map(|line| serde_json::from_str::(line).expect("valid JSON log event")) + .collect::>(); + assert_eq!(events.len(), 1); + assert_eq!(events[0]["fields"]["communication_id"], id); + assert_eq!(events[0]["fields"]["state"], "created"); +} + #[tokio::test] async fn get_status_returns_not_found_for_missing_thread() { let harness = AgentControlHarness::new().await; @@ -2112,28 +2177,40 @@ async fn multi_agent_v2_completion_queues_message_for_direct_parent() { &AgentStatus::Completed(Some("done".to_string())), ) .expect("completed status should render"); - let expected = ( - worker_thread_id, - Op::InterAgentCommunication { - communication: InterAgentCommunication::new( - tester_path.clone(), - worker_path.clone(), - Vec::new(), - expected_message.clone(), - /*trigger_turn*/ false, - ), - }, + let expected = InterAgentCommunication::new( + tester_path.clone(), + worker_path.clone(), + Vec::new(), + expected_message.clone(), + /*trigger_turn*/ false, ); timeout(Duration::from_secs(5), async { loop { - let captured = harness - .manager - .captured_ops() - .into_iter() - .find(|entry| *entry == expected); - if captured == Some(expected.clone()) { - break; + for (thread_id, op) in harness.manager.captured_ops() { + if thread_id != worker_thread_id { + continue; + } + let Op::InterAgentCommunication { mut 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; + } } sleep(Duration::from_millis(10)).await; } diff --git a/codex-rs/core/src/agent_communication.rs b/codex-rs/core/src/agent_communication.rs new file mode 100644 index 0000000000..e82004e700 --- /dev/null +++ b/codex-rs/core/src/agent_communication.rs @@ -0,0 +1,81 @@ +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( + 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), + } +} + +pub(crate) fn emit_agent_communication_created( + 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, + receiver_thread_id = %receiver_thread_id, + content, + source_call_id = metadata.source_call_id.as_deref(), + }, + "agent communication updated" + ); +} + +pub(crate) fn emit_agent_communication_enqueued(metadata: AgentCommunicationMetadata) { + tracing::trace!( + { + event.name = "codex.agent_communication", + communication_id = %metadata.id, + state = AgentCommunicationState::Enqueued.as_str(), + }, + "agent communication updated" + ); +} + +pub(crate) fn communication_content(communication: &InterAgentCommunication) -> &str { + if communication.content.is_empty() { + communication + .encrypted_content + .as_deref() + .unwrap_or_default() + } else { + &communication.content + } +} + +#[cfg(test)] +#[path = "agent_communication_tests.rs"] +mod tests; diff --git a/codex-rs/core/src/agent_communication_tests.rs b/codex-rs/core/src/agent_communication_tests.rs new file mode 100644 index 0000000000..504d734e56 --- /dev/null +++ b/codex-rs/core/src/agent_communication_tests.rs @@ -0,0 +1,121 @@ +use super::*; +use codex_protocol::AgentPath; +use pretty_assertions::assert_eq; +use serde_json::Value; +use serde_json::json; +use tracing_subscriber::filter::LevelFilter; +use tracing_subscriber::filter::Targets; +use tracing_subscriber::layer::SubscriberExt; +use tracing_test::internal::MockWriter; + +#[test] +fn emits_structured_lifecycle_events_at_trace() { + let output: &'static std::sync::Mutex> = + Box::leak(Box::new(std::sync::Mutex::new(Vec::new()))); + let filter = Targets::new() + .with_default(LevelFilter::WARN) + .with_target("codex_core::agent_communication", LevelFilter::TRACE); + let subscriber = tracing_subscriber::registry().with(filter).with( + tracing_subscriber::fmt::layer() + .json() + .with_current_span(false) + .with_span_list(false) + .with_writer(MockWriter::new(output)), + ); + let _guard = tracing::subscriber::set_default(subscriber); + + let sender_thread_id = ThreadId::new(); + let receiver_thread_id = ThreadId::new(); + let mut communication = InterAgentCommunication::new( + AgentPath::root(), + AgentPath::root(), + Vec::new(), + "hello".to_string(), + /*trigger_turn*/ false, + ); + let metadata = new_agent_communication_metadata( + AgentCommunicationKind::Message, + sender_thread_id, + Some("call-1"), + ); + communication.agent_communication_metadata = Some(metadata.clone()); + emit_agent_communication_created(&communication, receiver_thread_id); + emit_agent_communication_enqueued(metadata.clone()); + + let result_metadata = new_agent_communication_metadata( + 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); + + let events = String::from_utf8(output.lock().expect("buffer lock").clone()) + .expect("JSON logs should be UTF-8") + .lines() + .map(|line| serde_json::from_str::(line).expect("valid JSON log event")) + .collect::>(); + assert_eq!(events.len(), 3); + assert_eq!(events[0]["level"], "TRACE"); + assert_eq!(events[0]["target"], "codex_core::agent_communication"); + assert_eq!( + events[0]["fields"], + json!({ + "message": "agent communication updated", + "event.name": "codex.agent_communication", + "communication_id": metadata.id, + "kind": "message", + "state": "created", + "sender_thread_id": sender_thread_id.to_string(), + "receiver_thread_id": receiver_thread_id.to_string(), + "content": "hello", + "source_call_id": "call-1", + }) + ); + assert_eq!(events[1]["level"], "TRACE"); + assert_eq!(events[1]["target"], "codex_core::agent_communication"); + assert_eq!( + events[1]["fields"], + json!({ + "message": "agent communication updated", + "event.name": "codex.agent_communication", + "communication_id": metadata.id, + "state": "enqueued", + }) + ); + assert_eq!( + events[2]["fields"], + json!({ + "message": "agent communication updated", + "event.name": "codex.agent_communication", + "communication_id": result_metadata.id, + "kind": "result", + "state": "created", + "sender_thread_id": receiver_thread_id.to_string(), + "receiver_thread_id": sender_thread_id.to_string(), + "content": "hello", + }) + ); +} + +#[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 encrypted = InterAgentCommunication::new_encrypted( + AgentPath::root(), + AgentPath::root(), + Vec::new(), + "encrypted".to_string(), + /*trigger_turn*/ false, + ); + + let contents = [&plaintext, &encrypted].map(communication_content); + assert_eq!(contents, ["plain", "encrypted"]); +} diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index e9b749fea9..df8753a386 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -31,6 +31,7 @@ pub use codex_thread::TryStartTurnIfIdleError; pub use codex_thread::TryStartTurnIfIdleRejectionReason; pub use session::turn_context::TurnContext; mod agent; +mod agent_communication; mod attestation; mod codex_delegate; mod command_canonicalization; diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index a483ce5e0f..43b4d848e1 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -279,12 +279,16 @@ pub(super) async fn user_input_or_turn_inner( pub async fn inter_agent_communication( sess: &Arc, sub_id: String, - communication: InterAgentCommunication, + mut 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); + } 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 f45616eed8..ee05accaa5 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -111,6 +111,7 @@ 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; @@ -1860,13 +1861,24 @@ impl Session { .rollout_thread_trace .is_enabled() .then(|| message.clone()); - let communication = InterAgentCommunication::new( + let mut 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( + 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 diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index ece9d446b5..db69b00e8f 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -9781,6 +9781,72 @@ async fn task_finish_emits_thread_idle_lifecycle_after_active_turn_clears() { assert!(session.active_turn.lock().await.is_none()); } +#[tokio::test] +async fn mailbox_enqueue_emits_enqueued_communication_with_same_id() { + use tracing_subscriber::filter::LevelFilter; + use tracing_subscriber::filter::Targets; + use tracing_subscriber::layer::SubscriberExt; + use tracing_test::internal::MockWriter; + + let output: &'static std::sync::Mutex> = + Box::leak(Box::new(std::sync::Mutex::new(Vec::new()))); + let subscriber = tracing_subscriber::registry() + .with( + Targets::new() + .with_default(LevelFilter::OFF) + .with_target("codex_core::agent_communication", LevelFilter::TRACE), + ) + .with( + tracing_subscriber::fmt::layer() + .json() + .with_current_span(false) + .with_span_list(false) + .with_writer(MockWriter::new(output)), + ); + 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( + 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; + + let events = String::from_utf8(output.lock().expect("buffer lock").clone()) + .expect("JSON logs should be UTF-8") + .lines() + .map(|line| serde_json::from_str::(line).expect("valid JSON log event")) + .collect::>(); + assert_eq!(events.len(), 1); + assert_eq!( + events[0]["fields"], + serde_json::json!({ + "message": "agent communication updated", + "event.name": "codex.agent_communication", + "communication_id": id, + "state": "enqueued", + }) + ); +} + #[tokio::test] async fn thread_idle_lifecycle_waits_for_trigger_turn_mailbox_work() { struct ThreadIdleRecorder { 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 7fdb80e8bc..383c2c8467 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 @@ -6,6 +6,7 @@ use super::*; 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)] @@ -88,6 +89,28 @@ pub(crate) async fn handle_message_string_tool( let receiver_agent_path = receiver_agent.agent_path.clone().ok_or_else(|| { FunctionCallError::RespondToModel("target agent is missing an agent_path".to_string()) })?; + let author = turn + .session_source + .get_agent_path() + .unwrap_or_else(AgentPath::root); + let mut 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( + communication_kind, + session.thread_id, + Some(call_id.as_str()), + ), + ); + crate::agent_communication::emit_agent_communication_created( + &communication, + receiver_thread_id, + ); + let resume_config = build_agent_resume_config(turn.as_ref())?; session .services @@ -95,12 +118,6 @@ pub(crate) async fn handle_message_string_tool( .ensure_v2_agent_loaded(resume_config, receiver_thread_id) .await .map_err(|err| collab_agent_error(receiver_thread_id, err))?; - let author = turn - .session_source - .get_agent_path() - .unwrap_or_else(AgentPath::root); - let communication = - communication_from_tool_message(author, receiver_agent_path.clone(), message); let result = session .services .agent_control 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 2186a4a6d6..db785e3823 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 @@ -8,6 +8,7 @@ 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; @@ -117,8 +118,15 @@ async fn handle_spawn_agent( .session_source .get_agent_path() .unwrap_or_else(AgentPath::root); - let communication = + 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, diff --git a/codex-rs/feedback/src/lib.rs b/codex-rs/feedback/src/lib.rs index 7c27d2b3b0..c12a06a8f2 100644 --- a/codex-rs/feedback/src/lib.rs +++ b/codex-rs/feedback/src/lib.rs @@ -18,6 +18,7 @@ use tracing::Event; use tracing::Level; use tracing::field::Visit; use tracing_subscriber::Layer; +use tracing_subscriber::filter::LevelFilter; use tracing_subscriber::filter::Targets; use tracing_subscriber::fmt::writer::MakeWriter; use tracing_subscriber::registry::LookupSpan; @@ -204,7 +205,11 @@ impl CodexFeedback { .with_target(false) // Capture everything, regardless of the caller's `RUST_LOG`, so feedback includes the // full trace when the user uploads a report. - .with_filter(Targets::new().with_default(Level::TRACE)) + .with_filter( + Targets::new() + .with_default(Level::TRACE) + .with_target("codex_core::agent_communication", LevelFilter::OFF), + ) } /// Returns a [`tracing_subscriber`] layer that collects structured metadata for feedback. @@ -723,6 +728,24 @@ mod tests { pretty_assertions::assert_eq!(snap.tags.get("cached").map(String::as_str), Some("true")); } + #[test] + fn logger_layer_excludes_agent_communication_content() { + let fb = CodexFeedback::new(); + let _guard = tracing_subscriber::registry() + .with(fb.logger_layer()) + .set_default(); + + tracing::info!(target: "codex_core", "retained-log"); + tracing::trace!(target: "codex_core::agent_communication", content = "secret", "dropped-log"); + + let logs = std::str::from_utf8(fb.snapshot(/*session_id*/ None).as_bytes()) + .expect("feedback logs should be UTF-8") + .to_string(); + assert!(logs.contains("retained-log")); + assert!(!logs.contains("secret")); + assert!(!logs.contains("dropped-log")); + } + #[test] fn feedback_attachments_gate_connectivity_diagnostics() { let extra_filename = format!("codex-feedback-extra-{}.jsonl", ThreadId::new()); diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 96a793bcd3..c3179cde1e 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -737,6 +737,11 @@ 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 { @@ -756,6 +761,7 @@ impl InterAgentCommunication { encrypted_content: None, internal_chat_message_metadata_passthrough: None, trigger_turn, + agent_communication_metadata: None, } } @@ -775,6 +781,7 @@ impl InterAgentCommunication { encrypted_content: Some(encrypted_content), internal_chat_message_metadata_passthrough: None, trigger_turn, + agent_communication_metadata: None, } } @@ -4272,6 +4279,48 @@ 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)] @@ -4520,6 +4569,7 @@ 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(); diff --git a/codex-rs/state/src/log_db.rs b/codex-rs/state/src/log_db.rs index 2cf0f5d9af..55ef26eb76 100644 --- a/codex-rs/state/src/log_db.rs +++ b/codex-rs/state/src/log_db.rs @@ -54,6 +54,7 @@ pub fn default_filter() -> Targets { Targets::new() .with_default(LevelFilter::TRACE) .with_target("log", LevelFilter::OFF) + .with_target("codex_core::agent_communication", LevelFilter::OFF) .with_target("codex_otel.log_only", LevelFilter::OFF) .with_target("codex_otel.trace_safe", LevelFilter::OFF) } diff --git a/codex-rs/state/src/log_db_filter_tests.rs b/codex-rs/state/src/log_db_filter_tests.rs index 36ee27aba8..aef1ee97c2 100644 --- a/codex-rs/state/src/log_db_filter_tests.rs +++ b/codex-rs/state/src/log_db_filter_tests.rs @@ -1,5 +1,4 @@ use pretty_assertions::assert_eq; -use tracing_subscriber::filter::Targets; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; use uuid::Uuid; @@ -16,17 +15,14 @@ async fn sqlite_sink_drops_low_level_opentelemetry_sdk_logs() { let layer = start(runtime.clone()); let guard = tracing_subscriber::registry() - .with( - layer - .clone() - .with_filter(Targets::new().with_default(tracing::Level::TRACE)), - ) + .with(layer.clone().with_filter(default_filter())) .set_default(); tracing::trace!(target: "opentelemetry_sdk", "dropped-trace"); tracing::debug!(target: "opentelemetry_sdk", "dropped-debug"); tracing::info!(target: "opentelemetry_sdk", "retained-info"); tracing::trace!(target: "codex_state", "retained-trace"); + tracing::trace!(target: "codex_core::agent_communication", content = "secret", "dropped-agent-communication"); layer.flush().await; drop(guard);