feat(codex): track v2 collab child threads as agent telemetry

CodexSessionRuntime learns children from subAgentActivity items (probe:
no child thread/started arrives) and diverts their notifications into
synthetic collab/agentActivity events; CodexAdapter maps those to
timeline-bypassing task.* events (turn lifecycle, waiting flags, token
usage, item summaries). turn/completed maps to idle, not terminal.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-07-21 19:59:36 -07:00
1 parent 45783d5fab
commit 7e898d22df
4 files changed
+346 -7

No files matched your search

@@ -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();
@@ -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/<nickname>`).
* `turn/completed` means idle-and-resumable, not terminal.
*/
function mapCollabAgentActivity(
event: ProviderEvent,
canonicalThreadId: ThreadId,
): ReadonlyArray<ProviderRuntimeEvent> {
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<ProviderRuntimeEvent> {
if (event.kind === "notification" && event.method === "collab/agentActivity") {
return mapCollabAgentActivity(event, canonicalThreadId);
}
if (event.kind === "error") {
if (!event.message) {
return [];
@@ -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<string, CollabChildAgent>,
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<string, TurnId>,
notification: CodexServerNotification,
@@ -708,6 +740,7 @@ export const makeCodexSessionRuntime = (
const approvalCorrelationsRef = yield* Ref.make(new Map<string, ApprovalCorrelation>());
const pendingUserInputsRef = yield* Ref.make(new Map<ApprovalRequestId, PendingUserInput>());
const collabReceiverTurnsRef = yield* Ref.make(new Map<string, TurnId>());
const collabChildAgentsRef = yield* Ref.make(new Map<string, CollabChildAgent>());
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;
+12 -1
View File
@@ -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),