diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 23dae42a9d..c747f8d632 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -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": { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index f1d6a1af85..e2b1e90bc8 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -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": { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 9983b79257..aedf152e22 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -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": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/AgentCommunication.json b/codex-rs/app-server-protocol/schema/json/v2/AgentCommunication.json new file mode 100644 index 0000000000..49a48c7e9a --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/AgentCommunication.json @@ -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" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts b/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts index f3f828b8ac..cbae3ac45c 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts @@ -6,6 +6,7 @@ import type { FuzzyFileSearchSessionUpdatedNotification } from "./FuzzyFileSearc import type { AccountLoginCompletedNotification } from "./v2/AccountLoginCompletedNotification"; import type { AccountRateLimitsUpdatedNotification } from "./v2/AccountRateLimitsUpdatedNotification"; import type { AccountUpdatedNotification } from "./v2/AccountUpdatedNotification"; +import type { AgentCommunication } from "./v2/AgentCommunication"; import type { AgentMessageDeltaNotification } from "./v2/AgentMessageDeltaNotification"; import type { AppListUpdatedNotification } from "./v2/AppListUpdatedNotification"; import type { CommandExecOutputDeltaNotification } from "./v2/CommandExecOutputDeltaNotification"; @@ -74,4 +75,4 @@ import type { WindowsWorldWritableWarningNotification } from "./v2/WindowsWorldW /** * Notification sent from the server to the client. */ -export type ServerNotification = { "method": "error", "params": ErrorNotification } | { "method": "thread/started", "params": ThreadStartedNotification } | { "method": "thread/status/changed", "params": ThreadStatusChangedNotification } | { "method": "thread/archived", "params": ThreadArchivedNotification } | { "method": "thread/deleted", "params": ThreadDeletedNotification } | { "method": "thread/unarchived", "params": ThreadUnarchivedNotification } | { "method": "thread/closed", "params": ThreadClosedNotification } | { "method": "skills/changed", "params": SkillsChangedNotification } | { "method": "thread/name/updated", "params": ThreadNameUpdatedNotification } | { "method": "thread/goal/updated", "params": ThreadGoalUpdatedNotification } | { "method": "thread/goal/cleared", "params": ThreadGoalClearedNotification } | { "method": "thread/settings/updated", "params": ThreadSettingsUpdatedNotification } | { "method": "thread/tokenUsage/updated", "params": ThreadTokenUsageUpdatedNotification } | { "method": "turn/started", "params": TurnStartedNotification } | { "method": "hook/started", "params": HookStartedNotification } | { "method": "turn/completed", "params": TurnCompletedNotification } | { "method": "hook/completed", "params": HookCompletedNotification } | { "method": "turn/diff/updated", "params": TurnDiffUpdatedNotification } | { "method": "turn/plan/updated", "params": TurnPlanUpdatedNotification } | { "method": "item/started", "params": ItemStartedNotification } | { "method": "item/autoApprovalReview/started", "params": ItemGuardianApprovalReviewStartedNotification } | { "method": "item/autoApprovalReview/completed", "params": ItemGuardianApprovalReviewCompletedNotification } | { "method": "item/completed", "params": ItemCompletedNotification } | { "method": "rawResponseItem/completed", "params": RawResponseItemCompletedNotification } | { "method": "item/agentMessage/delta", "params": AgentMessageDeltaNotification } | { "method": "item/plan/delta", "params": PlanDeltaNotification } | { "method": "command/exec/outputDelta", "params": CommandExecOutputDeltaNotification } | { "method": "process/outputDelta", "params": ProcessOutputDeltaNotification } | { "method": "process/exited", "params": ProcessExitedNotification } | { "method": "item/commandExecution/outputDelta", "params": CommandExecutionOutputDeltaNotification } | { "method": "item/commandExecution/terminalInteraction", "params": TerminalInteractionNotification } | { "method": "item/fileChange/outputDelta", "params": FileChangeOutputDeltaNotification } | { "method": "item/fileChange/patchUpdated", "params": FileChangePatchUpdatedNotification } | { "method": "serverRequest/resolved", "params": ServerRequestResolvedNotification } | { "method": "item/mcpToolCall/progress", "params": McpToolCallProgressNotification } | { "method": "mcpServer/oauthLogin/completed", "params": McpServerOauthLoginCompletedNotification } | { "method": "mcpServer/startupStatus/updated", "params": McpServerStatusUpdatedNotification } | { "method": "account/updated", "params": AccountUpdatedNotification } | { "method": "account/rateLimits/updated", "params": AccountRateLimitsUpdatedNotification } | { "method": "app/list/updated", "params": AppListUpdatedNotification } | { "method": "remoteControl/status/changed", "params": RemoteControlStatusChangedNotification } | { "method": "externalAgentConfig/import/progress", "params": ExternalAgentConfigImportProgressNotification } | { "method": "externalAgentConfig/import/completed", "params": ExternalAgentConfigImportCompletedNotification } | { "method": "fs/changed", "params": FsChangedNotification } | { "method": "item/reasoning/summaryTextDelta", "params": ReasoningSummaryTextDeltaNotification } | { "method": "item/reasoning/summaryPartAdded", "params": ReasoningSummaryPartAddedNotification } | { "method": "item/reasoning/textDelta", "params": ReasoningTextDeltaNotification } | { "method": "thread/compacted", "params": ContextCompactedNotification } | { "method": "model/rerouted", "params": ModelReroutedNotification } | { "method": "model/verification", "params": ModelVerificationNotification } | { "method": "turn/moderationMetadata", "params": TurnModerationMetadataNotification } | { "method": "model/safetyBuffering/updated", "params": ModelSafetyBufferingUpdatedNotification } | { "method": "warning", "params": WarningNotification } | { "method": "guardianWarning", "params": GuardianWarningNotification } | { "method": "deprecationNotice", "params": DeprecationNoticeNotification } | { "method": "configWarning", "params": ConfigWarningNotification } | { "method": "fuzzyFileSearch/sessionUpdated", "params": FuzzyFileSearchSessionUpdatedNotification } | { "method": "fuzzyFileSearch/sessionCompleted", "params": FuzzyFileSearchSessionCompletedNotification } | { "method": "thread/realtime/started", "params": ThreadRealtimeStartedNotification } | { "method": "thread/realtime/itemAdded", "params": ThreadRealtimeItemAddedNotification } | { "method": "thread/realtime/transcript/delta", "params": ThreadRealtimeTranscriptDeltaNotification } | { "method": "thread/realtime/transcript/done", "params": ThreadRealtimeTranscriptDoneNotification } | { "method": "thread/realtime/outputAudio/delta", "params": ThreadRealtimeOutputAudioDeltaNotification } | { "method": "thread/realtime/sdp", "params": ThreadRealtimeSdpNotification } | { "method": "thread/realtime/error", "params": ThreadRealtimeErrorNotification } | { "method": "thread/realtime/closed", "params": ThreadRealtimeClosedNotification } | { "method": "windows/worldWritableWarning", "params": WindowsWorldWritableWarningNotification } | { "method": "windowsSandbox/setupCompleted", "params": WindowsSandboxSetupCompletedNotification } | { "method": "account/login/completed", "params": AccountLoginCompletedNotification }; +export type ServerNotification = { "method": "error", "params": ErrorNotification } | { "method": "thread/started", "params": ThreadStartedNotification } | { "method": "thread/status/changed", "params": ThreadStatusChangedNotification } | { "method": "thread/archived", "params": ThreadArchivedNotification } | { "method": "thread/deleted", "params": ThreadDeletedNotification } | { "method": "thread/unarchived", "params": ThreadUnarchivedNotification } | { "method": "thread/closed", "params": ThreadClosedNotification } | { "method": "skills/changed", "params": SkillsChangedNotification } | { "method": "thread/name/updated", "params": ThreadNameUpdatedNotification } | { "method": "thread/goal/updated", "params": ThreadGoalUpdatedNotification } | { "method": "thread/goal/cleared", "params": ThreadGoalClearedNotification } | { "method": "thread/settings/updated", "params": ThreadSettingsUpdatedNotification } | { "method": "thread/tokenUsage/updated", "params": ThreadTokenUsageUpdatedNotification } | { "method": "agentCommunication/updated", "params": AgentCommunication } | { "method": "turn/started", "params": TurnStartedNotification } | { "method": "hook/started", "params": HookStartedNotification } | { "method": "turn/completed", "params": TurnCompletedNotification } | { "method": "hook/completed", "params": HookCompletedNotification } | { "method": "turn/diff/updated", "params": TurnDiffUpdatedNotification } | { "method": "turn/plan/updated", "params": TurnPlanUpdatedNotification } | { "method": "item/started", "params": ItemStartedNotification } | { "method": "item/autoApprovalReview/started", "params": ItemGuardianApprovalReviewStartedNotification } | { "method": "item/autoApprovalReview/completed", "params": ItemGuardianApprovalReviewCompletedNotification } | { "method": "item/completed", "params": ItemCompletedNotification } | { "method": "rawResponseItem/completed", "params": RawResponseItemCompletedNotification } | { "method": "item/agentMessage/delta", "params": AgentMessageDeltaNotification } | { "method": "item/plan/delta", "params": PlanDeltaNotification } | { "method": "command/exec/outputDelta", "params": CommandExecOutputDeltaNotification } | { "method": "process/outputDelta", "params": ProcessOutputDeltaNotification } | { "method": "process/exited", "params": ProcessExitedNotification } | { "method": "item/commandExecution/outputDelta", "params": CommandExecutionOutputDeltaNotification } | { "method": "item/commandExecution/terminalInteraction", "params": TerminalInteractionNotification } | { "method": "item/fileChange/outputDelta", "params": FileChangeOutputDeltaNotification } | { "method": "item/fileChange/patchUpdated", "params": FileChangePatchUpdatedNotification } | { "method": "serverRequest/resolved", "params": ServerRequestResolvedNotification } | { "method": "item/mcpToolCall/progress", "params": McpToolCallProgressNotification } | { "method": "mcpServer/oauthLogin/completed", "params": McpServerOauthLoginCompletedNotification } | { "method": "mcpServer/startupStatus/updated", "params": McpServerStatusUpdatedNotification } | { "method": "account/updated", "params": AccountUpdatedNotification } | { "method": "account/rateLimits/updated", "params": AccountRateLimitsUpdatedNotification } | { "method": "app/list/updated", "params": AppListUpdatedNotification } | { "method": "remoteControl/status/changed", "params": RemoteControlStatusChangedNotification } | { "method": "externalAgentConfig/import/progress", "params": ExternalAgentConfigImportProgressNotification } | { "method": "externalAgentConfig/import/completed", "params": ExternalAgentConfigImportCompletedNotification } | { "method": "fs/changed", "params": FsChangedNotification } | { "method": "item/reasoning/summaryTextDelta", "params": ReasoningSummaryTextDeltaNotification } | { "method": "item/reasoning/summaryPartAdded", "params": ReasoningSummaryPartAddedNotification } | { "method": "item/reasoning/textDelta", "params": ReasoningTextDeltaNotification } | { "method": "thread/compacted", "params": ContextCompactedNotification } | { "method": "model/rerouted", "params": ModelReroutedNotification } | { "method": "model/verification", "params": ModelVerificationNotification } | { "method": "turn/moderationMetadata", "params": TurnModerationMetadataNotification } | { "method": "model/safetyBuffering/updated", "params": ModelSafetyBufferingUpdatedNotification } | { "method": "warning", "params": WarningNotification } | { "method": "guardianWarning", "params": GuardianWarningNotification } | { "method": "deprecationNotice", "params": DeprecationNoticeNotification } | { "method": "configWarning", "params": ConfigWarningNotification } | { "method": "fuzzyFileSearch/sessionUpdated", "params": FuzzyFileSearchSessionUpdatedNotification } | { "method": "fuzzyFileSearch/sessionCompleted", "params": FuzzyFileSearchSessionCompletedNotification } | { "method": "thread/realtime/started", "params": ThreadRealtimeStartedNotification } | { "method": "thread/realtime/itemAdded", "params": ThreadRealtimeItemAddedNotification } | { "method": "thread/realtime/transcript/delta", "params": ThreadRealtimeTranscriptDeltaNotification } | { "method": "thread/realtime/transcript/done", "params": ThreadRealtimeTranscriptDoneNotification } | { "method": "thread/realtime/outputAudio/delta", "params": ThreadRealtimeOutputAudioDeltaNotification } | { "method": "thread/realtime/sdp", "params": ThreadRealtimeSdpNotification } | { "method": "thread/realtime/error", "params": ThreadRealtimeErrorNotification } | { "method": "thread/realtime/closed", "params": ThreadRealtimeClosedNotification } | { "method": "windows/worldWritableWarning", "params": WindowsWorldWritableWarningNotification } | { "method": "windowsSandbox/setupCompleted", "params": WindowsSandboxSetupCompletedNotification } | { "method": "account/login/completed", "params": AccountLoginCompletedNotification }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/AgentCommunication.ts b/codex-rs/app-server-protocol/schema/typescript/v2/AgentCommunication.ts new file mode 100644 index 0000000000..4637da8714 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/AgentCommunication.ts @@ -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, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/AgentCommunicationKind.ts b/codex-rs/app-server-protocol/schema/typescript/v2/AgentCommunicationKind.ts new file mode 100644 index 0000000000..3f6a0e1755 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/AgentCommunicationKind.ts @@ -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"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/AgentCommunicationState.ts b/codex-rs/app-server-protocol/schema/typescript/v2/AgentCommunicationState.ts new file mode 100644 index 0000000000..ed5f4ef79f --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/AgentCommunicationState.ts @@ -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"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index 2833e6e525..588fca1e18 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -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"; diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 7b15035575..96f2e52829 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -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), diff --git a/codex-rs/app-server-protocol/src/protocol/v2/agent.rs b/codex-rs/app-server-protocol/src/protocol/v2/agent.rs new file mode 100644 index 0000000000..fb5f77f188 --- /dev/null +++ b/codex-rs/app-server-protocol/src/protocol/v2/agent.rs @@ -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 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 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, + pub occurred_at_ms: i64, +} + +fn nullable_string_schema( + generator: &mut schemars::r#gen::SchemaGenerator, +) -> schemars::schema::Schema { + generator.subschema_for::>() +} + +impl From 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, + } + } +} diff --git a/codex-rs/app-server-protocol/src/protocol/v2/mod.rs b/codex-rs/app-server-protocol/src/protocol/v2/mod.rs index 1097b03811..70465bf2a5 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/mod.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/mod.rs @@ -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::*; diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index d291f5c85b..d6b045ed59 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -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. diff --git a/codex-rs/app-server/src/agent_communication.rs b/codex-rs/app-server/src/agent_communication.rs new file mode 100644 index 0000000000..cb45094397 --- /dev/null +++ b/codex-rs/app-server/src/agent_communication.rs @@ -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, +) -> Arc { + 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, +} + +impl AgentCommunicationSink for AppServerAgentCommunicationSink { + fn emit(&self, record: AgentCommunicationRecord) { + let _ = self.sender.send(record); + } +} diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index beed35848b..a71a41b7a4 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -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; diff --git a/codex-rs/app-server/src/mcp_refresh.rs b/codex-rs/app-server/src/mcp_refresh.rs index 848d201f2e..ffa5a9c589 100644 --- a/codex-rs/app-server/src/mcp_refresh.rs +++ b/codex-rs/app-server/src/mcp_refresh.rs @@ -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, ) }); diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 3322f24d8b..8af71c4e46 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -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(), diff --git a/codex-rs/app-server/tests/suite/v2/turn_start.rs b/codex-rs/app-server/tests/suite/v2/turn_start.rs index 528292ae3f..594e46377d 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -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 { diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 49bbab0f87..4e0f214284 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -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, + pub(crate) initial_communication_source_call_id: Option, pub(crate) fork_mode: Option, pub(crate) parent_thread_id: Option, pub(crate) environments: Option>, @@ -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, + ) -> Option { + 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 { 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; diff --git a/codex-rs/core/src/agent/control/spawn.rs b/codex-rs/core/src/agent/control/spawn.rs index c4c40577ca..f4c3581e60 100644 --- a/codex-rs/core/src/agent/control/spawn.rs +++ b/codex-rs/core/src/agent/control/spawn.rs @@ -197,7 +197,7 @@ impl AgentControl { async fn spawn_agent_internal( &self, config: Config, - initial_operation: Op, + mut initial_operation: Op, session_source: Option, options: SpawnAgentOptions, ) -> CodexResult { @@ -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 { diff --git a/codex-rs/core/src/agent/control_tests.rs b/codex-rs/core/src/agent/control_tests.rs index 9863bfb7e2..533266a4f8 100644 --- a/codex-rs/core/src/agent/control_tests.rs +++ b/codex-rs/core/src/agent/control_tests.rs @@ -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(); diff --git a/codex-rs/core/src/agent_communication.rs b/codex-rs/core/src/agent_communication.rs new file mode 100644 index 0000000000..7fe2f82fb0 --- /dev/null +++ b/codex-rs/core/src/agent_communication.rs @@ -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, + ) -> 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); + } +} diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index a671f0dd74..9bb76bee36 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -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), })) diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 5550fe10d0..9090310a2b 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; @@ -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; diff --git a/codex-rs/core/src/prompt_debug.rs b/codex-rs/core/src/prompt_debug.rs index cac9bb41ae..eec035b92d 100644 --- a/codex-rs/core/src/prompt_debug.rs +++ b/codex-rs/core/src/prompt_debug.rs @@ -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?; diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index 75fbca4c86..6438f09afa 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -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; diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index f45616eed8..af3f21058b 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; @@ -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, pub(crate) thread_store: Arc, pub(crate) attestation_provider: Option>, + pub(crate) agent_communication_sink: Arc, pub(crate) external_time_provider: Option>, pub(crate) inherited_multi_agent_version: Option, } @@ -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 diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index 5e7046b148..5107b35a66 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -504,6 +504,7 @@ impl Session { thread_store: Arc, parent_rollout_thread_trace: ThreadTraceContext, attestation_provider: Option>, + agent_communication_sink: Arc, external_time_provider: Option>, multi_agent_version: Option, ) -> anyhow::Result> { @@ -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 diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 20f32ddfcd..b9769cf6c4 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -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(()), diff --git a/codex-rs/core/src/session/tests/guardian_tests.rs b/codex-rs/core/src/session/tests/guardian_tests.rs index d13239d810..c7bceff8ed 100644 --- a/codex-rs/core/src/session/tests/guardian_tests.rs +++ b/codex-rs/core/src/session/tests/guardian_tests.rs @@ -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, }) diff --git a/codex-rs/core/src/state/service.rs b/codex-rs/core/src/state/service.rs index a611b94887..5991be3a87 100644 --- a/codex-rs/core/src/state/service.rs +++ b/codex-rs/core/src/state/service.rs @@ -47,6 +47,7 @@ use tokio::sync::Mutex; use tokio_util::sync::CancellationToken; pub(crate) struct SessionServices { + pub(crate) agent_communication_sink: Arc, /// Mirror of the latest manager for extension resource clients that predate runtime snapshots. pub(crate) mcp_connection_manager: Arc>, /// The latest atomically published MCP config and manager pair. diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index 4ea86cb33d..e306c29811 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -251,6 +251,7 @@ pub(crate) struct ThreadManagerState { thread_store: Arc, agent_graph_store: Option>, attestation_provider: Option>, + agent_communication_sink: Arc, external_time_provider: Option>, session_source: SessionSource, installation_id: String, @@ -314,6 +315,7 @@ impl ThreadManager { agent_graph_store: Option>, installation_id: String, attestation_provider: Option>, + agent_communication_sink: Option>, external_time_provider: Option>, ) -> 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, })) diff --git a/codex-rs/core/src/thread_manager_tests.rs b/codex-rs/core/src/thread_manager_tests.rs index 4f0da0c9c7..88c4e5e402 100644 --- a/codex-rs/core/src/thread_manager_tests.rs +++ b/codex-rs/core/src/thread_manager_tests.rs @@ -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, ); 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..718bbe457c 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs @@ -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()), diff --git a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs index 8acb0a8c8d..574f640f7a 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs @@ -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, ); 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..7c3ab2e3ad 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,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 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..5429607b42 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 @@ -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()), diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index e0e82c37fd..b0835efb3d 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -289,6 +289,7 @@ pub struct TestCodexBuilder { extensions: Arc>, user_instructions_provider: Option>, supports_openai_form_elicitation: bool, + agent_communication_sink: Option>, external_time_provider: Option>, } @@ -396,6 +397,14 @@ impl TestCodexBuilder { self } + pub fn with_agent_communication_sink( + mut self, + sink: Arc, + ) -> 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, } } diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index 4df2bca1c1..0237207023 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -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 diff --git a/codex-rs/core/tests/suite/subagent_notifications.rs b/codex-rs/core/tests/suite/subagent_notifications.rs index 951fb92f17..657a17465b 100644 --- a/codex-rs/core/tests/suite/subagent_notifications.rs +++ b/codex-rs/core/tests/suite/subagent_notifications.rs @@ -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, +} + +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, + 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, diff --git a/codex-rs/mcp-server/src/message_processor.rs b/codex-rs/mcp-server/src/message_processor.rs index d211ff0a32..46fb3c62ff 100644 --- a/codex-rs/mcp-server/src/message_processor.rs +++ b/codex-rs/mcp-server/src/message_processor.rs @@ -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 { diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 96a793bcd3..2efd5a4c10 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_record: Option, } 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, + 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(); diff --git a/codex-rs/thread-manager-sample/src/main.rs b/codex-rs/thread-manager-sample/src/main.rs index 4237a33fef..ae299751ec 100644 --- a/codex-rs/thread-manager-sample/src/main.rs +++ b/codex-rs/thread-manager-sample/src/main.rs @@ -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, ); diff --git a/codex-rs/tui/src/app/app_server_event_targets.rs b/codex-rs/tui/src/app/app_server_event_targets.rs index 6c55850e4d..eac01561ad 100644 --- a/codex-rs/tui/src/app/app_server_event_targets.rs +++ b/codex-rs/tui/src/app/app_server_event_targets.rs @@ -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(_) diff --git a/codex-rs/tui/src/chatwidget/protocol.rs b/codex-rs/tui/src/chatwidget/protocol.rs index 0c5b0ed3ee..621a916d0d 100644 --- a/codex-rs/tui/src/chatwidget/protocol.rs +++ b/codex-rs/tui/src/chatwidget/protocol.rs @@ -191,7 +191,8 @@ impl ChatWidget { self.on_shutdown_complete(); } } - ServerNotification::ServerRequestResolved(_) + ServerNotification::AgentCommunicationUpdated(_) + | ServerNotification::ServerRequestResolved(_) | ServerNotification::AccountUpdated(_) | ServerNotification::AccountRateLimitsUpdated(_) | ServerNotification::ThreadStarted(_)