Add first-class agent communication events

This commit is contained in:
Nikil Pancha
2026-06-26 17:25:22 -07:00
parent a1c89d3a60
commit b3951adaf9
45 changed files with 1149 additions and 29 deletions
@@ -138,6 +138,65 @@
},
"type": "object"
},
"AgentCommunication": {
"properties": {
"content": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/AgentCommunicationKind"
},
"occurredAtMs": {
"format": "int64",
"type": "integer"
},
"receiverThreadId": {
"type": "string"
},
"senderThreadId": {
"type": "string"
},
"sourceCallId": {
"type": [
"string",
"null"
]
},
"state": {
"$ref": "#/definitions/AgentCommunicationState"
}
},
"required": [
"content",
"id",
"kind",
"occurredAtMs",
"receiverThreadId",
"senderThreadId",
"sourceCallId",
"state"
],
"type": "object"
},
"AgentCommunicationKind": {
"enum": [
"initialTask",
"message",
"followup",
"result"
],
"type": "string"
},
"AgentCommunicationState": {
"enum": [
"created",
"enqueued"
],
"type": "string"
},
"AgentMessageDeltaNotification": {
"properties": {
"delta": {
@@ -5977,6 +6036,26 @@
"title": "Thread/tokenUsage/updatedNotification",
"type": "object"
},
{
"properties": {
"method": {
"enum": [
"agentCommunication/updated"
],
"title": "AgentCommunication/updatedNotificationMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/AgentCommunication"
}
},
"required": [
"method",
"params"
],
"title": "AgentCommunication/updatedNotification",
"type": "object"
},
{
"properties": {
"method": {
@@ -4368,6 +4368,26 @@
"title": "Thread/tokenUsage/updatedNotification",
"type": "object"
},
{
"properties": {
"method": {
"enum": [
"agentCommunication/updated"
],
"title": "AgentCommunication/updatedNotificationMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/v2/AgentCommunication"
}
},
"required": [
"method",
"params"
],
"title": "AgentCommunication/updatedNotification",
"type": "object"
},
{
"properties": {
"method": {
@@ -6181,6 +6201,67 @@
},
"type": "object"
},
"AgentCommunication": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"content": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/v2/AgentCommunicationKind"
},
"occurredAtMs": {
"format": "int64",
"type": "integer"
},
"receiverThreadId": {
"type": "string"
},
"senderThreadId": {
"type": "string"
},
"sourceCallId": {
"type": [
"string",
"null"
]
},
"state": {
"$ref": "#/definitions/v2/AgentCommunicationState"
}
},
"required": [
"content",
"id",
"kind",
"occurredAtMs",
"receiverThreadId",
"senderThreadId",
"sourceCallId",
"state"
],
"title": "AgentCommunication",
"type": "object"
},
"AgentCommunicationKind": {
"enum": [
"initialTask",
"message",
"followup",
"result"
],
"type": "string"
},
"AgentCommunicationState": {
"enum": [
"created",
"enqueued"
],
"type": "string"
},
"AgentMessageDeltaNotification": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
@@ -307,6 +307,67 @@
},
"type": "object"
},
"AgentCommunication": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"content": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/AgentCommunicationKind"
},
"occurredAtMs": {
"format": "int64",
"type": "integer"
},
"receiverThreadId": {
"type": "string"
},
"senderThreadId": {
"type": "string"
},
"sourceCallId": {
"type": [
"string",
"null"
]
},
"state": {
"$ref": "#/definitions/AgentCommunicationState"
}
},
"required": [
"content",
"id",
"kind",
"occurredAtMs",
"receiverThreadId",
"senderThreadId",
"sourceCallId",
"state"
],
"title": "AgentCommunication",
"type": "object"
},
"AgentCommunicationKind": {
"enum": [
"initialTask",
"message",
"followup",
"result"
],
"type": "string"
},
"AgentCommunicationState": {
"enum": [
"created",
"enqueued"
],
"type": "string"
},
"AgentMessageDeltaNotification": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
@@ -12840,6 +12901,26 @@
"title": "Thread/tokenUsage/updatedNotification",
"type": "object"
},
{
"properties": {
"method": {
"enum": [
"agentCommunication/updated"
],
"title": "AgentCommunication/updatedNotificationMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/AgentCommunication"
}
},
"required": [
"method",
"params"
],
"title": "AgentCommunication/updatedNotification",
"type": "object"
},
{
"properties": {
"method": {
@@ -0,0 +1,63 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"AgentCommunicationKind": {
"enum": [
"initialTask",
"message",
"followup",
"result"
],
"type": "string"
},
"AgentCommunicationState": {
"enum": [
"created",
"enqueued"
],
"type": "string"
}
},
"properties": {
"content": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/AgentCommunicationKind"
},
"occurredAtMs": {
"format": "int64",
"type": "integer"
},
"receiverThreadId": {
"type": "string"
},
"senderThreadId": {
"type": "string"
},
"sourceCallId": {
"type": [
"string",
"null"
]
},
"state": {
"$ref": "#/definitions/AgentCommunicationState"
}
},
"required": [
"content",
"id",
"kind",
"occurredAtMs",
"receiverThreadId",
"senderThreadId",
"sourceCallId",
"state"
],
"title": "AgentCommunication",
"type": "object"
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,7 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { AgentCommunicationKind } from "./AgentCommunicationKind";
import type { AgentCommunicationState } from "./AgentCommunicationState";
export type AgentCommunication = { id: string, kind: AgentCommunicationKind, state: AgentCommunicationState, senderThreadId: string, receiverThreadId: string, content: string, sourceCallId: string | null, occurredAtMs: bigint, };
@@ -0,0 +1,5 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type AgentCommunicationKind = "initialTask" | "message" | "followup" | "result";
@@ -0,0 +1,5 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type AgentCommunicationState = "created" | "enqueued";
@@ -14,6 +14,9 @@ export type { AdditionalContextKind } from "./AdditionalContextKind";
export type { AdditionalFileSystemPermissions } from "./AdditionalFileSystemPermissions";
export type { AdditionalNetworkPermissions } from "./AdditionalNetworkPermissions";
export type { AdditionalPermissionProfile } from "./AdditionalPermissionProfile";
export type { AgentCommunication } from "./AgentCommunication";
export type { AgentCommunicationKind } from "./AgentCommunicationKind";
export type { AgentCommunicationState } from "./AgentCommunicationState";
export type { AgentMessageDeltaNotification } from "./AgentMessageDeltaNotification";
export type { AnalyticsConfig } from "./AnalyticsConfig";
export type { AppBranding } from "./AppBranding";
@@ -1613,6 +1613,7 @@ server_notification_definitions! {
#[experimental("thread/settings/updated")]
ThreadSettingsUpdated => "thread/settings/updated" (v2::ThreadSettingsUpdatedNotification),
ThreadTokenUsageUpdated => "thread/tokenUsage/updated" (v2::ThreadTokenUsageUpdatedNotification),
AgentCommunicationUpdated => "agentCommunication/updated" (v2::AgentCommunication),
TurnStarted => "turn/started" (v2::TurnStartedNotification),
HookStarted => "hook/started" (v2::HookStartedNotification),
TurnCompleted => "turn/completed" (v2::TurnCompletedNotification),
@@ -0,0 +1,84 @@
use codex_protocol::protocol::AgentCommunicationKind as CoreAgentCommunicationKind;
use codex_protocol::protocol::AgentCommunicationRecord as CoreAgentCommunicationRecord;
use codex_protocol::protocol::AgentCommunicationState as CoreAgentCommunicationState;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum AgentCommunicationKind {
InitialTask,
Message,
Followup,
Result,
}
impl From<CoreAgentCommunicationKind> for AgentCommunicationKind {
fn from(value: CoreAgentCommunicationKind) -> Self {
match value {
CoreAgentCommunicationKind::InitialTask => Self::InitialTask,
CoreAgentCommunicationKind::Message => Self::Message,
CoreAgentCommunicationKind::Followup => Self::Followup,
CoreAgentCommunicationKind::Result => Self::Result,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum AgentCommunicationState {
Created,
Enqueued,
}
impl From<CoreAgentCommunicationState> for AgentCommunicationState {
fn from(value: CoreAgentCommunicationState) -> Self {
match value {
CoreAgentCommunicationState::Created => Self::Created,
CoreAgentCommunicationState::Enqueued => Self::Enqueued,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct AgentCommunication {
pub id: String,
pub kind: AgentCommunicationKind,
pub state: AgentCommunicationState,
pub sender_thread_id: String,
pub receiver_thread_id: String,
pub content: String,
#[schemars(required, schema_with = "nullable_string_schema")]
pub source_call_id: Option<String>,
pub occurred_at_ms: i64,
}
fn nullable_string_schema(
generator: &mut schemars::r#gen::SchemaGenerator,
) -> schemars::schema::Schema {
generator.subschema_for::<Option<String>>()
}
impl From<CoreAgentCommunicationRecord> for AgentCommunication {
fn from(value: CoreAgentCommunicationRecord) -> Self {
Self {
id: value.id,
kind: value.kind.into(),
state: value.state.into(),
sender_thread_id: value.sender_thread_id.to_string(),
receiver_thread_id: value.receiver_thread_id.to_string(),
content: value.content,
source_call_id: value.source_call_id,
occurred_at_ms: value.occurred_at_ms,
}
}
}
@@ -1,6 +1,7 @@
mod shared;
mod account;
mod agent;
mod apps;
mod attestation;
mod collaboration_mode;
@@ -28,6 +29,7 @@ mod turn;
mod windows_sandbox;
pub use account::*;
pub use agent::*;
pub use apps::*;
pub use attestation::*;
pub use collaboration_mode::*;
+3
View File
@@ -157,6 +157,7 @@ Example with notification opt-out:
- `thread/goal/cleared` — notification emitted whenever a thread goal is removed.
- `thread/settings/updated` — experimental notification emitted to subscribed clients when a loaded thread’s effective next-turn settings change; includes `threadId` and the full `threadSettings`.
- `thread/status/changed` — notification emitted when a loaded thread’s status changes (`threadId` + new `status`).
- `agentCommunication/updated` — notification emitted when content is created for transfer between agent threads and again after the recipient mailbox accepts it.
- `thread/archive` — move a thread’s rollout file into the archived directory and attempt to move any spawned descendant thread rollout files; returns `{}` on success and emits `thread/archived` for each archived thread.
- `thread/delete` — hard-delete an active or archived thread and any spawned descendant threads; returns `{}` on success and emits `thread/deleted` for each deleted thread.
- `thread/unsubscribe` — unsubscribe this connection from thread turn/item events. If this was the last subscriber, the server keeps the thread loaded and unloads it only after it has had no subscribers and no thread activity for 30 minutes, then emits `thread/closed`.
@@ -1298,6 +1299,8 @@ All filesystem paths in this section must be absolute.
Event notifications are the server-initiated event stream for thread lifecycles, turn lifecycles, and the items within them. After you start or resume a thread, keep reading stdout for `thread/started`, `thread/archived`, `thread/unarchived`, `thread/closed`, `turn/*`, and `item/*` notifications.
Multi-agent communication is exposed live through `agentCommunication/updated`; it is not written to the rollout. Its payload contains a stable `id`, `kind` (`initialTask`, `message`, `followup`, or `result`), `state` (`created` or `enqueued`), exact `senderThreadId` and `receiverThreadId`, `content` (plaintext when available, otherwise the opaque encrypted content), optional causal `sourceCallId`, and `occurredAtMs`. A successful mailbox enqueue produces matching `created` and `enqueued` notifications with the same `id`; if enqueueing fails, only `created` is emitted. `enqueued` means the recipient mailbox accepted the communication, not that the recipient model consumed it.
Thread realtime uses a separate thread-scoped notification surface. `thread/realtime/*` notifications are ephemeral transport events, not `ThreadItem`s, and are not returned by `thread/read`, `thread/resume`, or `thread/fork`.
Recoverable configuration and initialization warnings use the existing `configWarning` notification: `{ summary, details?, path?, range? }`. App-server may emit it during initialization for config parsing and related setup diagnostics.
@@ -0,0 +1,35 @@
use std::sync::Arc;
use codex_app_server_protocol::AgentCommunication;
use codex_app_server_protocol::ServerNotification;
use codex_core::AgentCommunicationSink;
use codex_protocol::protocol::AgentCommunicationRecord;
use tokio::sync::mpsc;
use crate::outgoing_message::OutgoingMessageSender;
pub(crate) fn app_server_agent_communication_sink(
outgoing: Arc<OutgoingMessageSender>,
) -> Arc<dyn AgentCommunicationSink> {
let (sender, mut receiver) = mpsc::unbounded_channel();
tokio::spawn(async move {
while let Some(record) = receiver.recv().await {
outgoing
.send_server_notification(ServerNotification::AgentCommunicationUpdated(
AgentCommunication::from(record),
))
.await;
}
});
Arc::new(AppServerAgentCommunicationSink { sender })
}
struct AppServerAgentCommunicationSink {
sender: mpsc::UnboundedSender<AgentCommunicationRecord>,
}
impl AgentCommunicationSink for AppServerAgentCommunicationSink {
fn emit(&self, record: AgentCommunicationRecord) {
let _ = self.sender.send(record);
}
}
+2
View File
@@ -68,6 +68,7 @@ use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tracing::error;
use tracing::info;
use tracing::warn;
@@ -79,6 +80,7 @@ use tracing_subscriber::util::SubscriberInitExt;
const SQLITE_RECOVERY_CONFIG_WARNING_SUMMARY: &str = "Codex rebuilt its local database.";
mod agent_communication;
mod analytics_utils;
mod app_info;
mod app_server_tracing;
+1
View File
@@ -250,6 +250,7 @@ mod tests {
codex_core::local_agent_graph_store_from_state_db(Some(&state_db)),
"11111111-1111-4111-8111-111111111111".to_string(),
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
)
});
@@ -4,6 +4,7 @@ use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::atomic::AtomicBool;
use crate::agent_communication::app_server_agent_communication_sink;
use crate::attestation::app_server_attestation_provider;
use crate::config_manager::ConfigManager;
use crate::connection_rpc_gate::ConnectionRpcGate;
@@ -379,6 +380,7 @@ impl MessageProcessor {
outgoing.clone(),
thread_state_manager.clone(),
)),
Some(app_server_agent_communication_sink(outgoing.clone())),
Some(app_server_time_provider(
outgoing.clone(),
thread_state_manager.clone(),
@@ -18,6 +18,9 @@ use codex_app_server::INPUT_TOO_LARGE_ERROR_CODE;
use codex_app_server::INVALID_PARAMS_ERROR_CODE;
use codex_app_server_protocol::AdditionalContextEntry;
use codex_app_server_protocol::AdditionalContextKind;
use codex_app_server_protocol::AgentCommunication;
use codex_app_server_protocol::AgentCommunicationKind;
use codex_app_server_protocol::AgentCommunicationState;
use codex_app_server_protocol::ByteRange;
use codex_app_server_protocol::ClientInfo;
use codex_app_server_protocol::CollabAgentStatus;
@@ -3638,7 +3641,7 @@ async fn direct_input_to_multi_agent_v2_subagent_is_rejected() -> Result<()> {
let turn_req = mcp
.send_turn_start_request(TurnStartParams {
thread_id: thread.id,
thread_id: thread.id.clone(),
input: vec![V2UserInput::Text {
text: PARENT_PROMPT.to_string(),
text_elements: Vec::new(),
@@ -3653,6 +3656,42 @@ async fn direct_input_to_multi_agent_v2_subagent_is_rejected() -> Result<()> {
.await??;
let _: TurnStartResponse = to_response(turn_resp)?;
let created_notification = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("agentCommunication/updated"),
)
.await??;
let created: AgentCommunication = serde_json::from_value(
created_notification
.params
.expect("agentCommunication/updated params"),
)?;
assert_eq!(created.kind, AgentCommunicationKind::InitialTask);
assert_eq!(created.state, AgentCommunicationState::Created);
assert_eq!(created.sender_thread_id, thread.id);
assert_eq!(created.content, CHILD_PROMPT);
assert_eq!(created.source_call_id.as_deref(), Some(SPAWN_CALL_ID));
let enqueued_notification = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("agentCommunication/updated"),
)
.await??;
let enqueued: AgentCommunication = serde_json::from_value(
enqueued_notification
.params
.expect("agentCommunication/updated params"),
)?;
assert_eq!(
enqueued,
AgentCommunication {
state: AgentCommunicationState::Enqueued,
occurred_at_ms: enqueued.occurred_at_ms,
..created.clone()
}
);
assert!(created.occurred_at_ms <= enqueued.occurred_at_ms);
let child_thread_id = timeout(DEFAULT_READ_TIMEOUT, async {
loop {
let completed_notif = mcp
@@ -3673,6 +3712,7 @@ async fn direct_input_to_multi_agent_v2_subagent_is_rejected() -> Result<()> {
}
})
.await??;
assert_eq!(child_thread_id, created.receiver_thread_id);
let direct_turn_req = mcp
.send_turn_start_request(TurnStartParams {
+41 -1
View File
@@ -24,6 +24,8 @@ 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::AgentCommunicationRecord;
use codex_protocol::protocol::InitialHistory;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::MultiAgentVersion;
@@ -64,6 +66,7 @@ pub(crate) enum SpawnAgentForkMode {
#[derive(Clone, Debug, Default)]
pub(crate) struct SpawnAgentOptions {
pub(crate) fork_parent_spawn_call_id: Option<String>,
pub(crate) initial_communication_source_call_id: Option<String>,
pub(crate) fork_mode: Option<SpawnAgentForkMode>,
pub(crate) parent_thread_id: Option<ThreadId>,
pub(crate) environments: Option<Vec<TurnEnvironmentSelection>>,
@@ -201,6 +204,33 @@ impl AgentControl {
result
}
async fn create_and_emit_agent_communication(
&self,
state: &ThreadManagerState,
kind: AgentCommunicationKind,
sender_thread_id: ThreadId,
receiver_thread_id: ThreadId,
communication: &InterAgentCommunication,
source_call_id: Option<String>,
) -> Option<AgentCommunicationRecord> {
let sink_thread = match state.get_thread(sender_thread_id).await {
Ok(thread) => thread,
Err(_) => state.get_thread(receiver_thread_id).await.ok()?,
};
let record = sink_thread.codex.session.new_agent_communication(
kind,
sender_thread_id,
receiver_thread_id,
communication,
source_call_id,
);
sink_thread
.codex
.session
.emit_agent_communication(record.clone());
Some(record)
}
/// Interrupt the current task for an existing agent thread.
pub(crate) async fn interrupt_agent(&self, agent_id: ThreadId) -> CodexResult<String> {
let state = self.upgrade()?;
@@ -473,13 +503,23 @@ 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_record = control
.create_and_emit_agent_communication(
state.as_ref(),
AgentCommunicationKind::Result,
child_thread_id,
parent_thread_id,
&communication,
/*source_call_id*/ None,
)
.await;
let _ = control
.send_inter_agent_communication(parent_thread_id, communication)
.await;
+18 -1
View File
@@ -197,7 +197,7 @@ impl AgentControl {
async fn spawn_agent_internal(
&self,
config: Config,
initial_operation: Op,
mut initial_operation: Op,
session_source: Option<SessionSource>,
options: SpawnAgentOptions,
) -> CodexResult<LiveAgent> {
@@ -356,6 +356,23 @@ impl AgentControl {
)
.await;
if multi_agent_version == MultiAgentVersion::V2
&& let Some(sender_thread_id) = options.parent_thread_id
&& let Op::InterAgentCommunication { communication } = &mut initial_operation
{
let record = self
.create_and_emit_agent_communication(
state.as_ref(),
codex_protocol::protocol::AgentCommunicationKind::InitialTask,
sender_thread_id,
new_thread.thread_id,
communication,
options.initial_communication_source_call_id.clone(),
)
.await;
communication.agent_communication_record = record;
}
self.send_input_after_capacity_check(new_thread.thread_id, &state, initial_operation)
.await?;
if multi_agent_version != MultiAgentVersion::V2 {
+23 -15
View File
@@ -2112,27 +2112,34 @@ 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,
),
},
);
timeout(Duration::from_secs(5), async {
loop {
let captured = harness
.manager
.captured_ops()
.into_iter()
.find(|entry| *entry == expected);
if captured == Some(expected.clone()) {
.any(|(thread_id, op)| {
thread_id == worker_thread_id
&& matches!(
op,
Op::InterAgentCommunication { communication }
if communication.author == tester_path
&& communication.recipient == worker_path
&& communication.other_recipients.is_empty()
&& communication.content == expected_message
&& !communication.trigger_turn
&& communication.agent_communication_record.as_ref().is_some_and(|record| {
record.kind
== codex_protocol::protocol::AgentCommunicationKind::Result
&& record.state
== codex_protocol::protocol::AgentCommunicationState::Created
&& record.sender_thread_id == tester_thread_id
&& record.receiver_thread_id == worker_thread_id
&& record.source_call_id.is_none()
})
)
});
if captured {
break;
}
sleep(Duration::from_millis(10)).await;
@@ -2383,6 +2390,7 @@ async fn resume_thread_subagent_restores_stored_metadata() {
/*agent_graph_store*/ None,
uuid::Uuid::new_v4().to_string(),
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
);
let control = manager.agent_control();
+62
View File
@@ -0,0 +1,62 @@
use codex_protocol::ThreadId;
use codex_protocol::protocol::AgentCommunicationKind;
use codex_protocol::protocol::AgentCommunicationRecord;
use codex_protocol::protocol::AgentCommunicationState;
use codex_protocol::protocol::InterAgentCommunication;
use uuid::Uuid;
use crate::session::Session;
/// Receives live agent-to-agent communication lifecycle records.
///
/// Implementations must return quickly and must not block the agent runtime. Records sent to this
/// sink are intentionally not persisted in rollouts.
pub trait AgentCommunicationSink: Send + Sync {
/// Publishes one live communication lifecycle record without blocking.
fn emit(&self, record: AgentCommunicationRecord);
}
/// Drops agent communication lifecycle records when the host does not expose them.
#[derive(Debug, Default, Clone, Copy)]
pub struct NoopAgentCommunicationSink;
impl AgentCommunicationSink for NoopAgentCommunicationSink {
fn emit(&self, _record: AgentCommunicationRecord) {}
}
impl Session {
pub(crate) fn new_agent_communication(
&self,
kind: AgentCommunicationKind,
sender_thread_id: ThreadId,
receiver_thread_id: ThreadId,
communication: &InterAgentCommunication,
source_call_id: Option<String>,
) -> AgentCommunicationRecord {
let content = if communication.content.is_empty() {
communication.encrypted_content.clone().unwrap_or_default()
} else {
communication.content.clone()
};
AgentCommunicationRecord {
id: Uuid::new_v4().to_string(),
kind,
state: AgentCommunicationState::Created,
sender_thread_id,
receiver_thread_id,
content,
source_call_id,
occurred_at_ms: crate::turn_timing::now_unix_timestamp_ms(),
}
}
pub(crate) fn emit_agent_communication(&self, record: AgentCommunicationRecord) {
self.services.agent_communication_sink.emit(record);
}
pub(crate) fn emit_agent_communication_enqueued(&self, mut record: AgentCommunicationRecord) {
record.state = AgentCommunicationState::Enqueued;
record.occurred_at_ms = crate::turn_timing::now_unix_timestamp_ms();
self.emit_agent_communication(record);
}
}
+1
View File
@@ -131,6 +131,7 @@ pub(crate) async fn run_codex_thread_interactive(
analytics_events_client: Some(parent_session.services.analytics_events_client.clone()),
thread_store: Arc::clone(&parent_session.services.thread_store),
attestation_provider: parent_session.services.attestation_provider.clone(),
agent_communication_sink: Arc::clone(&parent_session.services.agent_communication_sink),
external_time_provider: Some(Arc::clone(&parent_session.services.time_provider)),
inherited_multi_agent_version: Some(MultiAgentVersion::Disabled),
}))
+3
View File
@@ -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;
@@ -179,6 +180,8 @@ mod tasks;
mod user_shell_command;
pub mod util;
pub use agent_communication::AgentCommunicationSink;
pub use agent_communication::NoopAgentCommunicationSink;
pub use attestation::AttestationContext;
pub use attestation::AttestationProvider;
pub use attestation::GenerateAttestationFuture;
+1
View File
@@ -60,6 +60,7 @@ pub async fn build_prompt_input(
crate::local_agent_graph_store_from_state_db(state_db.as_ref()),
installation_id,
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
);
let thread = thread_manager.start_thread(config).await?;
+4
View File
@@ -282,9 +282,13 @@ pub async fn inter_agent_communication(
communication: InterAgentCommunication,
) {
let trigger_turn = communication.trigger_turn;
let communication_record = communication.agent_communication_record.clone();
sess.input_queue
.enqueue_mailbox_communication(communication)
.await;
if let Some(communication_record) = communication_record {
sess.emit_agent_communication_enqueued(communication_record);
}
if trigger_turn {
sess.maybe_start_turn_for_pending_work_with_sub_id(sub_id)
.await;
+15 -2
View File
@@ -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;
@@ -231,7 +232,7 @@ pub(crate) use self::input_queue::TurnInputQueue;
pub use self::mcp_runtime::McpRuntimeSnapshot;
use self::review::spawn_review_thread;
use self::session::AppServerClientMetadata;
use self::session::Session;
pub(crate) use self::session::Session;
use self::session::SessionConfiguration;
pub(crate) use self::session::SessionSettingsUpdate;
#[cfg(test)]
@@ -444,6 +445,7 @@ pub(crate) struct CodexSpawnArgs {
pub(crate) analytics_events_client: Option<AnalyticsEventsClient>,
pub(crate) thread_store: Arc<dyn ThreadStore>,
pub(crate) attestation_provider: Option<Arc<dyn AttestationProvider>>,
pub(crate) agent_communication_sink: Arc<dyn crate::AgentCommunicationSink>,
pub(crate) external_time_provider: Option<Arc<dyn TimeProvider>>,
pub(crate) inherited_multi_agent_version: Option<MultiAgentVersion>,
}
@@ -532,6 +534,7 @@ impl Codex {
analytics_events_client,
thread_store,
attestation_provider,
agent_communication_sink,
external_time_provider,
inherited_multi_agent_version,
} = args;
@@ -700,6 +703,7 @@ impl Codex {
thread_store,
parent_rollout_thread_trace,
attestation_provider,
agent_communication_sink,
external_time_provider,
multi_agent_version,
))
@@ -1860,13 +1864,22 @@ 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,
);
let communication_record = self.new_agent_communication(
AgentCommunicationKind::Result,
self.thread_id,
parent_thread_id,
&communication,
/*source_call_id*/ None,
);
self.emit_agent_communication(communication_record.clone());
communication.agent_communication_record = Some(communication_record);
if let Err(err) = self
.services
.agent_control
+2
View File
@@ -504,6 +504,7 @@ impl Session {
thread_store: Arc<dyn ThreadStore>,
parent_rollout_thread_trace: ThreadTraceContext,
attestation_provider: Option<Arc<dyn AttestationProvider>>,
agent_communication_sink: Arc<dyn crate::AgentCommunicationSink>,
external_time_provider: Option<Arc<dyn TimeProvider>>,
multi_agent_version: Option<MultiAgentVersion>,
) -> anyhow::Result<Arc<Self>> {
@@ -1042,6 +1043,7 @@ impl Session {
}
let services = SessionServices {
agent_communication_sink,
// Initialize the MCP connection manager with an uninitialized
// instance. It will be replaced with one created via
// McpConnectionManager::new() once all its constructor args are
+5
View File
@@ -5244,6 +5244,7 @@ async fn session_new_fails_when_zsh_fork_enabled_without_packaged_zsh() {
)),
codex_rollout_trace::ThreadTraceContext::disabled(),
/*attestation_provider*/ None,
Arc::new(crate::NoopAgentCommunicationSink),
/*external_time_provider*/ None,
Some(config.multi_agent_version_from_features()),
)
@@ -5377,6 +5378,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
let mcp_runtime =
crate::session::McpRuntimeSnapshot::new_uninitialized_for_test(config.as_ref());
let services = SessionServices {
agent_communication_sink: Arc::new(crate::NoopAgentCommunicationSink),
mcp_connection_manager: Arc::new(arc_swap::ArcSwap::from(mcp_runtime.manager_arc())),
mcp_runtime: arc_swap::ArcSwapOption::from(Some(mcp_runtime)),
mcp_projection_lock: Mutex::new(()),
@@ -5626,6 +5628,7 @@ async fn make_session_with_config_and_rx(
)),
codex_rollout_trace::ThreadTraceContext::disabled(),
/*attestation_provider*/ None,
Arc::new(crate::NoopAgentCommunicationSink),
/*external_time_provider*/ None,
Some(config.multi_agent_version_from_features()),
)
@@ -5741,6 +5744,7 @@ async fn make_session_with_history_source_and_agent_control_and_rx(
)),
codex_rollout_trace::ThreadTraceContext::disabled(),
/*attestation_provider*/ None,
Arc::new(crate::NoopAgentCommunicationSink),
/*external_time_provider*/ None,
Some(config.multi_agent_version_from_features()),
)
@@ -7460,6 +7464,7 @@ where
let mcp_runtime =
crate::session::McpRuntimeSnapshot::new_uninitialized_for_test(config.as_ref());
let services = SessionServices {
agent_communication_sink: Arc::new(crate::NoopAgentCommunicationSink),
mcp_connection_manager: Arc::new(arc_swap::ArcSwap::from(mcp_runtime.manager_arc())),
mcp_runtime: arc_swap::ArcSwapOption::from(Some(mcp_runtime)),
mcp_projection_lock: Mutex::new(()),
@@ -752,6 +752,7 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() {
analytics_events_client: None,
thread_store,
attestation_provider: None,
agent_communication_sink: Arc::new(crate::NoopAgentCommunicationSink),
external_time_provider: None,
inherited_multi_agent_version: None,
})
+1
View File
@@ -47,6 +47,7 @@ use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;
pub(crate) struct SessionServices {
pub(crate) agent_communication_sink: Arc<dyn crate::AgentCommunicationSink>,
/// Mirror of the latest manager for extension resource clients that predate runtime snapshots.
pub(crate) mcp_connection_manager: Arc<ArcSwap<McpConnectionManager>>,
/// The latest atomically published MCP config and manager pair.
+6
View File
@@ -251,6 +251,7 @@ pub(crate) struct ThreadManagerState {
thread_store: Arc<dyn ThreadStore>,
agent_graph_store: Option<Arc<dyn AgentGraphStore>>,
attestation_provider: Option<Arc<dyn AttestationProvider>>,
agent_communication_sink: Arc<dyn crate::AgentCommunicationSink>,
external_time_provider: Option<Arc<dyn TimeProvider>>,
session_source: SessionSource,
installation_id: String,
@@ -314,6 +315,7 @@ impl ThreadManager {
agent_graph_store: Option<Arc<dyn AgentGraphStore>>,
installation_id: String,
attestation_provider: Option<Arc<dyn AttestationProvider>>,
agent_communication_sink: Option<Arc<dyn crate::AgentCommunicationSink>>,
external_time_provider: Option<Arc<dyn TimeProvider>>,
) -> Self {
let codex_home = config.codex_home.clone();
@@ -352,6 +354,8 @@ impl ThreadManager {
thread_store,
agent_graph_store,
attestation_provider,
agent_communication_sink: agent_communication_sink
.unwrap_or_else(|| Arc::new(crate::NoopAgentCommunicationSink)),
external_time_provider,
auth_manager,
session_source,
@@ -460,6 +464,7 @@ impl ThreadManager {
thread_store,
agent_graph_store,
attestation_provider: None,
agent_communication_sink: Arc::new(crate::NoopAgentCommunicationSink),
external_time_provider: None,
auth_manager,
session_source: SessionSource::Exec,
@@ -1606,6 +1611,7 @@ impl ThreadManagerState {
analytics_events_client: self.analytics_events_client.clone(),
thread_store: Arc::clone(&self.thread_store),
attestation_provider: self.attestation_provider.clone(),
agent_communication_sink: Arc::clone(&self.agent_communication_sink),
external_time_provider: self.external_time_provider.clone(),
inherited_multi_agent_version: multi_agent_version,
}))
+12
View File
@@ -597,6 +597,7 @@ async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors()
/*agent_graph_store*/ None,
TEST_INSTALLATION_ID.to_string(),
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
);
let selected_root_init = |id: &str, environment_id: &str| {
@@ -797,6 +798,7 @@ async fn resume_and_fork_do_not_restore_thread_environments_from_rollout() {
/*agent_graph_store*/ None,
TEST_INSTALLATION_ID.to_string(),
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
);
let selected_cwd =
@@ -923,6 +925,7 @@ async fn explicit_installation_id_skips_codex_home_file() {
local_agent_graph_store_from_state_db(state_db.as_ref()),
installation_id.clone(),
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
);
@@ -964,6 +967,7 @@ async fn resume_active_thread_from_rollout_returns_running_thread() {
/*agent_graph_store*/ None,
TEST_INSTALLATION_ID.to_string(),
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
);
@@ -1024,6 +1028,7 @@ async fn resume_stopped_thread_from_rollout_spawns_new_thread() {
/*agent_graph_store*/ None,
TEST_INSTALLATION_ID.to_string(),
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
);
@@ -1091,6 +1096,7 @@ async fn resume_stopped_thread_from_rollout_preserves_thread_source() {
local_agent_graph_store_from_state_db(state_db.as_ref()),
TEST_INSTALLATION_ID.to_string(),
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
);
@@ -1183,6 +1189,7 @@ async fn subtree_listing_uses_injected_graph_store_without_state_db() {
Some(agent_graph_store),
TEST_INSTALLATION_ID.to_string(),
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
);
@@ -1228,6 +1235,7 @@ async fn rollout_path_resume_and_fork_read_history_through_thread_store() {
local_agent_graph_store_from_state_db(state_db.as_ref()),
TEST_INSTALLATION_ID.to_string(),
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
);
@@ -1333,6 +1341,7 @@ async fn new_uses_active_provider_for_model_refresh() {
/*agent_graph_store*/ None,
TEST_INSTALLATION_ID.to_string(),
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
);
@@ -1555,6 +1564,7 @@ async fn interrupted_fork_snapshot_does_not_synthesize_turn_id_for_legacy_histor
local_agent_graph_store_from_state_db(state_db.as_ref()),
TEST_INSTALLATION_ID.to_string(),
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
);
@@ -1664,6 +1674,7 @@ async fn interrupted_fork_snapshot_preserves_explicit_turn_id() {
local_agent_graph_store_from_state_db(state_db.as_ref()),
TEST_INSTALLATION_ID.to_string(),
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
);
@@ -1763,6 +1774,7 @@ async fn interrupted_fork_snapshot_uses_persisted_mid_turn_history_without_live_
local_agent_graph_store_from_state_db(state_db.as_ref()),
TEST_INSTALLATION_ID.to_string(),
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
);
@@ -129,6 +129,7 @@ async fn handle_spawn_agent(
)?),
SpawnAgentOptions {
fork_parent_spawn_call_id: args.fork_context.then(|| call_id.clone()),
initial_communication_source_call_id: None,
fork_mode: args.fork_context.then_some(SpawnAgentForkMode::FullHistory),
parent_thread_id: Some(session.thread_id),
environments: Some(turn.environments.to_selections()),
@@ -4268,6 +4268,7 @@ async fn tool_handlers_cascade_close_and_resume_and_keep_explicitly_closed_subtr
local_agent_graph_store_from_state_db(state_db.as_ref()),
"11111111-1111-4111-8111-111111111111".to_string(),
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
);
@@ -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,26 @@ 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,
};
let communication_record = session.new_agent_communication(
communication_kind,
session.thread_id,
receiver_thread_id,
&communication,
Some(call_id.clone()),
);
session.emit_agent_communication(communication_record.clone());
communication.agent_communication_record = Some(communication_record);
let resume_config = build_agent_resume_config(turn.as_ref())?;
session
.services
@@ -95,12 +116,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
@@ -126,6 +126,7 @@ async fn handle_spawn_agent(
Some(spawn_source),
SpawnAgentOptions {
fork_parent_spawn_call_id: fork_mode.as_ref().map(|_| call_id.clone()),
initial_communication_source_call_id: Some(call_id.clone()),
fork_mode,
parent_thread_id: Some(session.thread_id),
environments: Some(turn.environments.to_selections()),
+11
View File
@@ -289,6 +289,7 @@ pub struct TestCodexBuilder {
extensions: Arc<ExtensionRegistry<Config>>,
user_instructions_provider: Option<Arc<dyn UserInstructionsProvider>>,
supports_openai_form_elicitation: bool,
agent_communication_sink: Option<Arc<dyn codex_core::AgentCommunicationSink>>,
external_time_provider: Option<Arc<dyn TimeProvider>>,
}
@@ -396,6 +397,14 @@ impl TestCodexBuilder {
self
}
pub fn with_agent_communication_sink(
mut self,
sink: Arc<dyn codex_core::AgentCommunicationSink>,
) -> Self {
self.agent_communication_sink = Some(sink);
self
}
pub fn with_windows_cmd_shell(self) -> Self {
if cfg!(windows) {
self.with_user_shell(get_shell_by_model_provided_path(&PathBuf::from("cmd.exe")))
@@ -611,6 +620,7 @@ impl TestCodexBuilder {
codex_core::local_agent_graph_store_from_state_db(state_db.as_ref()),
installation_id,
/*attestation_provider*/ None,
/*agent_communication_sink*/ self.agent_communication_sink.clone(),
/*external_time_provider*/ self.external_time_provider.clone(),
);
let thread_manager = Arc::new(thread_manager);
@@ -1218,6 +1228,7 @@ pub fn test_codex() -> TestCodexBuilder {
extensions: empty_extension_registry(),
user_instructions_provider: None,
supports_openai_form_elicitation: false,
agent_communication_sink: None,
external_time_provider: None,
}
}
+1
View File
@@ -1469,6 +1469,7 @@ async fn prefers_apikey_when_config_prefers_apikey_even_with_chatgpt_tokens() {
/*agent_graph_store*/ None,
installation_id,
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
);
let NewThread { thread: codex, .. } = thread_manager
@@ -1,4 +1,5 @@
use anyhow::Result;
use codex_core::AgentCommunicationSink;
use codex_core::StartThreadOptions;
use codex_core::ThreadConfigSnapshot;
use codex_core::config::AgentRoleConfig;
@@ -6,6 +7,9 @@ use codex_features::Feature;
use codex_protocol::ThreadId;
use codex_protocol::models::PermissionProfile;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::AgentCommunicationKind;
use codex_protocol::protocol::AgentCommunicationRecord;
use codex_protocol::protocol::AgentCommunicationState;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::InitialHistory;
@@ -39,8 +43,10 @@ use serde_json::Value;
use serde_json::json;
use std::fs;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use test_case::test_case;
use tokio::sync::mpsc;
use tokio::time::Instant;
use tokio::time::sleep;
use wiremock::MockServer;
@@ -62,6 +68,56 @@ const SUBAGENT_START_CONTEXT: &str = "subagent start context reaches child";
const SUBAGENT_STOP_CONTINUATION: &str = "continue only the child";
const INTERNAL_SUBAGENT_PROMPT: &str = "internal subagent: review";
struct RecordingAgentCommunicationSink {
tx: mpsc::UnboundedSender<AgentCommunicationRecord>,
}
impl AgentCommunicationSink for RecordingAgentCommunicationSink {
fn emit(&self, record: AgentCommunicationRecord) {
self.tx
.send(record)
.expect("agent communication receiver should remain open");
}
}
async fn wait_for_agent_communication(
rx: &mut mpsc::UnboundedReceiver<AgentCommunicationRecord>,
kind: AgentCommunicationKind,
state: AgentCommunicationState,
) -> AgentCommunicationRecord {
let record = tokio::time::timeout(Duration::from_secs(15), rx.recv())
.await
.expect("agent communication record timeout")
.expect("agent communication sink closed");
assert_eq!((record.kind, record.state), (kind, state));
record
}
async fn submit_turn_without_wait(test: &TestCodex, prompt: &str) -> Result<()> {
let (sandbox_policy, permission_profile) =
turn_permission_fields(PermissionProfile::Disabled, test.config.cwd.as_path());
test.codex
.submit(Op::UserInput {
items: vec![UserInput::Text {
text: prompt.to_string(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
additional_context: Default::default(),
thread_settings: codex_protocol::protocol::ThreadSettingsOverrides {
environments: Some(local_selections(test.config.cwd.clone())),
approval_policy: Some(AskForApproval::Never),
sandbox_policy: Some(sandbox_policy),
permission_profile,
model: Some(test.session_configured.model.clone()),
..Default::default()
},
})
.await?;
Ok(())
}
fn body_contains(req: &wiremock::Request, text: &str) -> bool {
decoded_body(req)
.and_then(|body| String::from_utf8(body).ok())
@@ -1127,6 +1183,331 @@ async fn encrypted_multi_agent_v2_spawn_sends_agent_message_to_child() -> Result
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn multi_agent_v2_communications_emit_created_and_enqueued_events() -> Result<()> {
const QUEUE_PROMPT: &str = "queue a message for the worker";
const FOLLOWUP_PROMPT: &str = "give the worker a follow-up";
const FAILED_PROMPT: &str = "message the unavailable worker";
const SEND_CALL_ID: &str = "send-call-1";
const FOLLOWUP_CALL_ID: &str = "followup-call-1";
const FAILED_CALL_ID: &str = "failed-send-call-1";
const INITIAL_RESULT: &str = "Message Type: FINAL_ANSWER\nTask name: /root\nSender: /root/worker\nPayload:\ninitial result";
const FOLLOWUP_RESULT: &str = "Message Type: FINAL_ANSWER\nTask name: /root\nSender: /root/worker\nPayload:\nfollow-up result";
let server = start_mock_server().await;
let spawn_args = serde_json::to_string(&json!({
"message": "encrypted initial task",
"task_name": "worker",
}))?;
mount_sse_once_match(
&server,
|req: &wiremock::Request| body_contains(req, TURN_1_PROMPT),
sse(vec![
ev_response_created("resp-parent-spawn-1"),
ev_function_call_with_namespace(
SPAWN_CALL_ID,
MULTI_AGENT_V2_NAMESPACE,
"spawn_agent",
&spawn_args,
),
ev_completed("resp-parent-spawn-1"),
]),
)
.await;
mount_sse_once_match(
&server,
|req: &wiremock::Request| request_has_input_type(req, "agent_message"),
sse(vec![
ev_response_created("resp-child-initial"),
ev_assistant_message("msg-child-initial", "initial result"),
ev_completed("resp-child-initial"),
]),
)
.await;
mount_sse_once_match(
&server,
|req: &wiremock::Request| body_contains(req, SPAWN_CALL_ID),
sse(vec![
ev_response_created("resp-parent-spawn-2"),
ev_assistant_message("msg-parent-spawn", "spawned"),
ev_completed("resp-parent-spawn-2"),
]),
)
.await;
let (communication_tx, mut communication_rx) = mpsc::unbounded_channel();
let communication_sink = Arc::new(RecordingAgentCommunicationSink {
tx: communication_tx,
});
let mut builder = test_codex()
.with_agent_communication_sink(communication_sink.clone())
.with_model("koffing")
.with_config(|config| {
config
.features
.enable(Feature::Collab)
.expect("test config should allow feature update");
config
.features
.enable(Feature::MultiAgentV2)
.expect("test config should allow feature update");
});
let test = builder.build(&server).await?;
let root_id = test.session_configured.thread_id;
submit_turn_without_wait(&test, TURN_1_PROMPT).await?;
let initial_created = wait_for_agent_communication(
&mut communication_rx,
AgentCommunicationKind::InitialTask,
AgentCommunicationState::Created,
)
.await;
let child_id = initial_created.receiver_thread_id;
let child = test.thread_manager.get_thread(child_id).await?;
let initial_enqueued = wait_for_agent_communication(
&mut communication_rx,
AgentCommunicationKind::InitialTask,
AgentCommunicationState::Enqueued,
)
.await;
let result_created = wait_for_agent_communication(
&mut communication_rx,
AgentCommunicationKind::Result,
AgentCommunicationState::Created,
)
.await;
let result_enqueued = wait_for_agent_communication(
&mut communication_rx,
AgentCommunicationKind::Result,
AgentCommunicationState::Enqueued,
)
.await;
let send_args = serde_json::to_string(&json!({
"target": child_id.to_string(),
"message": "encrypted queued message",
}))?;
mount_sse_once_match(
&server,
|req: &wiremock::Request| body_contains(req, QUEUE_PROMPT),
sse(vec![
ev_response_created("resp-parent-send-1"),
ev_function_call_with_namespace(
SEND_CALL_ID,
MULTI_AGENT_V2_NAMESPACE,
"send_message",
&send_args,
),
ev_completed("resp-parent-send-1"),
]),
)
.await;
mount_sse_once_match(
&server,
|req: &wiremock::Request| body_contains(req, SEND_CALL_ID),
sse(vec![
ev_response_created("resp-parent-send-2"),
ev_assistant_message("msg-parent-send", "sent"),
ev_completed("resp-parent-send-2"),
]),
)
.await;
submit_turn_without_wait(&test, QUEUE_PROMPT).await?;
let message_created = wait_for_agent_communication(
&mut communication_rx,
AgentCommunicationKind::Message,
AgentCommunicationState::Created,
)
.await;
let message_enqueued = wait_for_agent_communication(
&mut communication_rx,
AgentCommunicationKind::Message,
AgentCommunicationState::Enqueued,
)
.await;
wait_for_event_match(test.codex.as_ref(), |event| {
matches!(event, EventMsg::TurnComplete(_)).then_some(())
})
.await;
let followup_args = serde_json::to_string(&json!({
"target": child_id.to_string(),
"message": "encrypted follow-up",
}))?;
mount_sse_once_match(
&server,
|req: &wiremock::Request| body_contains(req, FOLLOWUP_PROMPT),
sse(vec![
ev_response_created("resp-parent-followup-1"),
ev_function_call_with_namespace(
FOLLOWUP_CALL_ID,
MULTI_AGENT_V2_NAMESPACE,
"followup_task",
&followup_args,
),
ev_completed("resp-parent-followup-1"),
]),
)
.await;
mount_sse_once_match(
&server,
|req: &wiremock::Request| {
!body_contains(req, FOLLOWUP_PROMPT) && !body_contains(req, FOLLOWUP_CALL_ID)
},
sse(vec![
ev_response_created("resp-child-followup"),
ev_assistant_message("msg-child-followup", "follow-up result"),
ev_completed("resp-child-followup"),
]),
)
.await;
mount_sse_once_match(
&server,
|req: &wiremock::Request| body_contains(req, FOLLOWUP_CALL_ID),
sse(vec![
ev_response_created("resp-parent-followup-2"),
ev_assistant_message("msg-parent-followup", "followed up"),
ev_completed("resp-parent-followup-2"),
]),
)
.await;
submit_turn_without_wait(&test, FOLLOWUP_PROMPT).await?;
let followup_created = wait_for_agent_communication(
&mut communication_rx,
AgentCommunicationKind::Followup,
AgentCommunicationState::Created,
)
.await;
let followup_enqueued = wait_for_agent_communication(
&mut communication_rx,
AgentCommunicationKind::Followup,
AgentCommunicationState::Enqueued,
)
.await;
let followup_result_created = wait_for_agent_communication(
&mut communication_rx,
AgentCommunicationKind::Result,
AgentCommunicationState::Created,
)
.await;
let followup_result_enqueued = wait_for_agent_communication(
&mut communication_rx,
AgentCommunicationKind::Result,
AgentCommunicationState::Enqueued,
)
.await;
for (created, enqueued, sender, receiver, content, source_call_id) in [
(
&initial_created,
&initial_enqueued,
root_id,
child_id,
"encrypted initial task",
Some(SPAWN_CALL_ID),
),
(
&message_created,
&message_enqueued,
root_id,
child_id,
"encrypted queued message",
Some(SEND_CALL_ID),
),
(
&followup_created,
&followup_enqueued,
root_id,
child_id,
"encrypted follow-up",
Some(FOLLOWUP_CALL_ID),
),
(
&result_created,
&result_enqueued,
child_id,
root_id,
INITIAL_RESULT,
None,
),
(
&followup_result_created,
&followup_result_enqueued,
child_id,
root_id,
FOLLOWUP_RESULT,
None,
),
] {
assert_eq!(created.id, enqueued.id);
assert_eq!(created.kind, enqueued.kind);
assert_eq!(created.sender_thread_id, sender);
assert_eq!(enqueued.sender_thread_id, sender);
assert_eq!(created.receiver_thread_id, receiver);
assert_eq!(enqueued.receiver_thread_id, receiver);
assert_eq!(created.content, content);
assert_eq!(enqueued.content, content);
assert_eq!(created.source_call_id.as_deref(), source_call_id);
assert_eq!(enqueued.source_call_id.as_deref(), source_call_id);
assert!(created.occurred_at_ms <= enqueued.occurred_at_ms);
}
let timestamps = [
initial_created.occurred_at_ms,
initial_enqueued.occurred_at_ms,
result_created.occurred_at_ms,
result_enqueued.occurred_at_ms,
message_created.occurred_at_ms,
message_enqueued.occurred_at_ms,
followup_created.occurred_at_ms,
followup_enqueued.occurred_at_ms,
followup_result_created.occurred_at_ms,
followup_result_enqueued.occurred_at_ms,
];
assert!(timestamps.windows(2).all(|pair| pair[0] <= pair[1]));
let child_rollout_path = child.rollout_path();
test.thread_manager.remove_thread(&child_id).await;
child.shutdown_and_wait().await?;
if let Some(child_rollout_path) = child_rollout_path {
tokio::fs::remove_file(child_rollout_path).await?;
}
mount_sse_once_match(
&server,
|req: &wiremock::Request| body_contains(req, FAILED_PROMPT),
sse(vec![
ev_response_created("resp-parent-failed-send"),
ev_function_call_with_namespace(
FAILED_CALL_ID,
MULTI_AGENT_V2_NAMESPACE,
"send_message",
&send_args,
),
ev_completed("resp-parent-failed-send"),
]),
)
.await;
submit_turn_without_wait(&test, FAILED_PROMPT).await?;
let failed_created = wait_for_agent_communication(
&mut communication_rx,
AgentCommunicationKind::Message,
AgentCommunicationState::Created,
)
.await;
assert_eq!(
failed_created.source_call_id.as_deref(),
Some(FAILED_CALL_ID)
);
assert_eq!(failed_created.receiver_thread_id, child_id);
assert_eq!(failed_created.content, "encrypted queued message");
assert!(
tokio::time::timeout(Duration::from_millis(100), communication_rx.recv())
.await
.is_err()
);
Ok(())
}
#[derive(Clone, Copy)]
enum CompletionScenario {
Completed,
@@ -78,6 +78,7 @@ impl MessageProcessor {
codex_core::local_agent_graph_store_from_state_db(state_db.as_ref()),
installation_id,
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
));
Self {
+34
View File
@@ -737,6 +737,11 @@ pub struct InterAgentCommunication {
#[ts(optional)]
pub internal_chat_message_metadata_passthrough: Option<InternalChatMessageMetadataPassthrough>,
pub trigger_turn: bool,
/// Runtime-only metadata used to emit communication lifecycle records.
#[serde(skip)]
#[schemars(skip)]
#[ts(skip)]
pub agent_communication_record: Option<AgentCommunicationRecord>,
}
impl InterAgentCommunication {
@@ -756,6 +761,7 @@ impl InterAgentCommunication {
encrypted_content: None,
internal_chat_message_metadata_passthrough: None,
trigger_turn,
agent_communication_record: None,
}
}
@@ -775,6 +781,7 @@ impl InterAgentCommunication {
encrypted_content: Some(encrypted_content),
internal_chat_message_metadata_passthrough: None,
trigger_turn,
agent_communication_record: None,
}
}
@@ -4272,6 +4279,32 @@ pub struct SubAgentActivityEvent {
pub kind: SubAgentActivityKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentCommunicationKind {
InitialTask,
Message,
Followup,
Result,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentCommunicationState {
Created,
Enqueued,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentCommunicationRecord {
pub id: String,
pub kind: AgentCommunicationKind,
pub state: AgentCommunicationState,
pub sender_thread_id: ThreadId,
pub receiver_thread_id: ThreadId,
pub content: String,
pub source_call_id: Option<String>,
pub occurred_at_ms: i64,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)]
pub struct CollabWaitingBeginEvent {
#[serde(default)]
@@ -4520,6 +4553,7 @@ mod tests {
encrypted_content: None,
internal_chat_message_metadata_passthrough: None,
trigger_turn: true,
agent_communication_record: None,
};
communication.set_turn_id_if_missing("turn-1");
let mut serialized_communication = communication.clone();
@@ -137,6 +137,7 @@ async fn run_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> {
local_agent_graph_store_from_state_db(state_db.as_ref()),
installation_id,
/*attestation_provider*/ None,
/*agent_communication_sink*/ None,
/*external_time_provider*/ None,
);
@@ -161,7 +161,8 @@ pub(super) fn server_notification_thread_target(
None => return ServerNotificationThreadTarget::AppScoped,
}
}
ServerNotification::SkillsChanged(_)
ServerNotification::AgentCommunicationUpdated(_)
| ServerNotification::SkillsChanged(_)
| ServerNotification::McpServerOauthLoginCompleted(_)
| ServerNotification::AccountUpdated(_)
| ServerNotification::AccountRateLimitsUpdated(_)
+2 -1
View File
@@ -191,7 +191,8 @@ impl ChatWidget {
self.on_shutdown_complete();
}
}
ServerNotification::ServerRequestResolved(_)
ServerNotification::AgentCommunicationUpdated(_)
| ServerNotification::ServerRequestResolved(_)
| ServerNotification::AccountUpdated(_)
| ServerNotification::AccountRateLimitsUpdated(_)
| ServerNotification::ThreadStarted(_)