diff --git a/apps/server/src/provider/Layers/CodexAdapter.test.ts b/apps/server/src/provider/Layers/CodexAdapter.test.ts index 4ae654a518..9a5c820b05 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.test.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.test.ts @@ -555,6 +555,129 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { }), ); + it.effect("maps collab/agentActivity turn lifecycle to timeline-bypassing task events", () => + Effect.gen(function* () { + const { adapter, runtime } = yield* startLifecycleRuntime(); + const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); + + yield* runtime.emit({ + id: asEventId("evt-collab-turn-start"), + kind: "notification", + provider: ProviderDriverKind.make("codex"), + createdAt: "2026-01-01T00:00:00.000Z", + method: "collab/agentActivity", + threadId: asThreadId("thread-1"), + payload: { + agentThreadId: "child-thread-1", + agentPath: "/root/marlow", + method: "turn/started", + params: { threadId: "child-thread-1", turn: { id: "child-turn-1" } }, + }, + }); + const firstEvent = yield* Fiber.join(firstEventFiber); + + NodeAssert.equal(firstEvent._tag, "Some"); + if (firstEvent._tag !== "Some") { + return; + } + NodeAssert.equal(firstEvent.value.type, "task.started"); + if (firstEvent.value.type !== "task.started") { + return; + } + NodeAssert.equal(firstEvent.value.payload.taskId, "child-thread-1"); + NodeAssert.equal(firstEvent.value.payload.name, "marlow"); + NodeAssert.equal(firstEvent.value.payload.timelineBypass, true); + }), + ); + + it.effect("maps collab child turn/completed to an idle task.updated", () => + Effect.gen(function* () { + const { adapter, runtime } = yield* startLifecycleRuntime(); + const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); + + yield* runtime.emit({ + id: asEventId("evt-collab-turn-complete"), + kind: "notification", + provider: ProviderDriverKind.make("codex"), + createdAt: "2026-01-01T00:00:01.000Z", + method: "collab/agentActivity", + threadId: asThreadId("thread-1"), + payload: { + agentThreadId: "child-thread-1", + agentPath: "/root/marlow", + method: "turn/completed", + params: { threadId: "child-thread-1", turn: { id: "child-turn-1" } }, + }, + }); + const firstEvent = yield* Fiber.join(firstEventFiber); + + NodeAssert.equal(firstEvent._tag, "Some"); + if (firstEvent._tag !== "Some") { + return; + } + NodeAssert.equal(firstEvent.value.type, "task.updated"); + if (firstEvent.value.type !== "task.updated") { + return; + } + NodeAssert.equal(firstEvent.value.payload.status, "idle"); + NodeAssert.equal(firstEvent.value.payload.timelineBypass, true); + }), + ); + + it.effect("maps collab child token usage to task.progress with normalized usage", () => + Effect.gen(function* () { + const { adapter, runtime } = yield* startLifecycleRuntime(); + const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); + + yield* runtime.emit({ + id: asEventId("evt-collab-usage"), + kind: "notification", + provider: ProviderDriverKind.make("codex"), + createdAt: "2026-01-01T00:00:02.000Z", + method: "collab/agentActivity", + threadId: asThreadId("thread-1"), + payload: { + agentThreadId: "child-thread-1", + agentPath: "/root/marlow", + method: "thread/tokenUsage/updated", + params: { + threadId: "child-thread-1", + turnId: "child-turn-1", + tokenUsage: { + total: { + totalTokens: 4200, + inputTokens: 4000, + cachedInputTokens: 1000, + outputTokens: 200, + reasoningOutputTokens: 50, + }, + last: { + totalTokens: 4200, + inputTokens: 4000, + cachedInputTokens: 1000, + outputTokens: 200, + reasoningOutputTokens: 50, + }, + modelContextWindow: 272_000, + }, + }, + }, + }); + const firstEvent = yield* Fiber.join(firstEventFiber); + + NodeAssert.equal(firstEvent._tag, "Some"); + if (firstEvent._tag !== "Some") { + return; + } + NodeAssert.equal(firstEvent.value.type, "task.progress"); + if (firstEvent.value.type !== "task.progress") { + return; + } + const usage = firstEvent.value.payload.usage as { totalTokens?: number } | undefined; + NodeAssert.equal(usage?.totalTokens, 4200); + }), + ); + it.effect("labels MCP lifecycle entries with server and tool names", () => Effect.gen(function* () { const { adapter, runtime } = yield* startLifecycleRuntime(); diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts index 38a5887cdc..8d088648d7 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -20,6 +20,7 @@ import { type ProviderUserInputAnswers, RuntimeItemId, RuntimeRequestId, + RuntimeTaskId, ProviderApprovalDecision, ThreadId, ProviderSendTurnInput, @@ -494,10 +495,156 @@ function mapItemLifecycle( }; } +/** + * Codex v2 collab child threads have no task lifecycle of their own — the + * session runtime intercepts their notifications and forwards them wrapped as + * `collab/agentActivity`. Translate into the shared `task.*` family so the + * ingestion agent reducer treats Codex children like Claude subagents. All + * synthesized events set `timelineBypass` so they never become timeline rows. + * + * Probe-verified mapping (codex-cli 0.144.1): children emit no + * `thread/started`; their first event is `thread/status/changed`. Nicknames + * arrive via the parent's `subAgentActivity.agentPath` (`/root/`). + * `turn/completed` means idle-and-resumable, not terminal. + */ +function mapCollabAgentActivity( + event: ProviderEvent, + canonicalThreadId: ThreadId, +): ReadonlyArray { + const wrapper = + event.payload !== null && typeof event.payload === "object" + ? (event.payload as { + agentThreadId?: unknown; + agentPath?: unknown; + method?: unknown; + params?: unknown; + }) + : undefined; + if (!wrapper || typeof wrapper.agentThreadId !== "string" || typeof wrapper.method !== "string") { + return []; + } + const agentThreadId = wrapper.agentThreadId; + const agentPath = typeof wrapper.agentPath === "string" ? wrapper.agentPath : undefined; + // "/root/marlow" → "marlow" + const nickname = agentPath?.split("/").filter(Boolean).at(-1); + const inner: ProviderEvent = { + ...event, + method: wrapper.method, + ...(wrapper.params !== undefined ? { payload: wrapper.params } : {}), + }; + const base = { + ...runtimeEventBase(event, canonicalThreadId), + payload: { + taskId: RuntimeTaskId.make(agentThreadId), + description: nickname ?? agentThreadId, + name: nickname ?? agentThreadId, + taskType: "local_agent", + timelineBypass: true, + }, + } as const; + + switch (wrapper.method) { + case "turn/started": + return [{ ...base, type: "task.started", payload: { ...base.payload } }]; + case "turn/completed": + return [ + { + ...base, + type: "task.updated", + payload: { taskId: base.payload.taskId, status: "idle", timelineBypass: true }, + }, + ]; + case "thread/status/changed": { + const payload = readPayload( + EffectCodexSchema.V2ThreadStatusChangedNotification, + inner.payload, + ); + const status = payload?.status; + if (!status) return []; + if (status.type === "active" && status.activeFlags.length > 0) { + return [ + { + ...base, + type: "task.updated", + payload: { taskId: base.payload.taskId, status: "waiting", timelineBypass: true }, + }, + ]; + } + return []; + } + case "thread/closed": + return [ + { + ...base, + type: "task.completed", + payload: { taskId: base.payload.taskId, status: "stopped", timelineBypass: true }, + }, + ]; + case "thread/tokenUsage/updated": { + const payload = readPayload( + EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification, + inner.payload, + ); + const usage = payload ? normalizeCodexTokenUsage(payload.tokenUsage) : undefined; + if (!usage) return []; + return [ + { + ...base, + type: "task.progress", + payload: { + ...base.payload, + usage: { + totalTokens: usage.usedTokens, + ...(usage.inputTokens !== undefined ? { inputTokens: usage.inputTokens } : {}), + ...(usage.cachedInputTokens !== undefined + ? { cachedInputTokens: usage.cachedInputTokens } + : {}), + ...(usage.outputTokens !== undefined ? { outputTokens: usage.outputTokens } : {}), + ...(usage.reasoningOutputTokens !== undefined + ? { reasoningOutputTokens: usage.reasoningOutputTokens } + : {}), + }, + }, + }, + ]; + } + case "item/started": + case "item/completed": { + const payload = + readPayload(EffectCodexSchema.V2ItemStartedNotification, inner.payload) ?? + readPayload(EffectCodexSchema.V2ItemCompletedNotification, inner.payload); + const item = payload?.item; + if (!item) return []; + const itemType = toCanonicalItemType(item.type); + const title = itemTitle(itemType, item); + const detail = itemDetail(itemType, item); + const summary = detail ?? title; + if (!summary) return []; + return [ + { + ...base, + type: "task.progress", + payload: { + ...base.payload, + description: summary, + summary, + ...(title ? { lastToolName: title } : {}), + }, + }, + ]; + } + default: + return []; + } +} + function mapToRuntimeEvents( event: ProviderEvent, canonicalThreadId: ThreadId, ): ReadonlyArray { + if (event.kind === "notification" && event.method === "collab/agentActivity") { + return mapCollabAgentActivity(event, canonicalThreadId); + } if (event.kind === "error") { if (!event.message) { return []; diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.ts index 5a81e915e3..18a3fba8ec 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.ts @@ -585,6 +585,38 @@ function readRouteFields(notification: CodexServerNotification): { } } +interface CollabChildAgent { + readonly agentPath: string; + readonly interrupted: boolean; +} + +/** + * v2 collab children announce themselves only via `subAgentActivity` items on + * the parent stream (the probe shows no child `thread/started`, and v2 + * `collabAgentToolCall` items carry empty receiver lists). Track them so their + * notifications can be folded into agent telemetry instead of leaking into the + * parent timeline as unattributed items. + */ +function rememberSubAgentActivity( + childAgents: Map, + notification: CodexServerNotification, +): void { + if (notification.method !== "item/started" && notification.method !== "item/completed") { + return; + } + const item = notification.params.item; + if (item.type !== "subAgentActivity") { + return; + } + childAgents.set(item.agentThreadId, { + agentPath: item.agentPath, + interrupted: item.kind === "interrupted", + }); +} + +/** Synthetic method carrying an intercepted child-thread notification. */ +export const COLLAB_AGENT_ACTIVITY_METHOD = "collab/agentActivity"; + function rememberCollabReceiverTurns( collabReceiverTurns: Map, notification: CodexServerNotification, @@ -708,6 +740,7 @@ export const makeCodexSessionRuntime = ( const approvalCorrelationsRef = yield* Ref.make(new Map()); const pendingUserInputsRef = yield* Ref.make(new Map()); const collabReceiverTurnsRef = yield* Ref.make(new Map()); + const collabChildAgentsRef = yield* Ref.make(new Map()); const closedRef = yield* Ref.make(false); // `~` is not shell-expanded when env vars are set via @@ -829,14 +862,39 @@ export const makeCodexSessionRuntime = ( const payload = notification.params; const route = readRouteFields(notification); const collabReceiverTurns = yield* Ref.get(collabReceiverTurnsRef); - const childParentTurnId = (() => { - const providerConversationId = readNotificationThreadId(notification); - return providerConversationId - ? collabReceiverTurns.get(providerConversationId) - : undefined; - })(); + const collabChildAgents = yield* Ref.get(collabChildAgentsRef); + const notificationThreadId = readNotificationThreadId(notification); + const childParentTurnId = notificationThreadId + ? collabReceiverTurns.get(notificationThreadId) + : undefined; rememberCollabReceiverTurns(collabReceiverTurns, notification, route.turnId); + rememberSubAgentActivity(collabChildAgents, notification); + yield* Ref.set(collabChildAgentsRef, collabChildAgents); + + // v2 collab child threads: their notifications arrive on this + // connection keyed by the child threadId. Divert the whole stream into + // a synthetic collab/agentActivity event for the agent tracker and keep + // it out of the parent timeline. + const childAgent = notificationThreadId + ? collabChildAgents.get(notificationThreadId) + : undefined; + if (childAgent && notificationThreadId) { + yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns); + yield* emitEvent({ + kind: "notification", + threadId: options.threadId, + method: COLLAB_AGENT_ACTIVITY_METHOD, + payload: { + agentThreadId: notificationThreadId, + agentPath: childAgent.agentPath, + method: notification.method, + params: payload, + }, + }); + return; + } + if (childParentTurnId && shouldSuppressChildConversationNotification(notification.method)) { yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns); return; diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.ts index e76850b981..2b86b18a93 100644 --- a/packages/contracts/src/providerRuntime.ts +++ b/packages/contracts/src/providerRuntime.ts @@ -530,8 +530,19 @@ export type TaskProgressPayload = typeof TaskProgressPayload.Type; */ const TaskUpdatedPayload = Schema.Struct({ taskId: RuntimeTaskId, + // "idle" = finished a run but resumable (Codex agents between activations); + // "waiting" = blocked on approval/user input. status: Schema.optional( - Schema.Literals(["pending", "running", "completed", "failed", "killed", "paused"]), + Schema.Literals([ + "pending", + "running", + "completed", + "failed", + "killed", + "paused", + "idle", + "waiting", + ]), ), endTime: Schema.optional(IsoDateTime), isBackgrounded: Schema.optional(Schema.Boolean),