Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

subagentRuntime.ts

1,004 lines37.2 KB

1/**
2 * Native-provider subagent observability: a tolerant fold over persisted
3 * task.* / tool.* thread activities into orchestration-v2-shaped subagent
4 * state, plus the source-neutral panel model every client renders.
5 *
6 * This module is deliberately legacy-bridge code. When orchestration-v2's
7 * subagent projection is available for a thread, deriveAgentPanelModel
8 * prefers it (see the v2Projection parameter) and the fold is skipped; when
9 * the v1 orchestrator is retired this file is deleted. Field names and
10 * transition semantics copy the v2 stack (#4779) exactly so that swap is
11 * mechanical.
12 *
13 * Invariants encoded here trace to shipped bugs in the prior PRs (#4220,
14 * #3650, #4662): reusable identity vs one-shot activations, idle as a real
15 * nonterminal state, provider-specific usage merges, first-write terminal
16 * timestamps, reactivation clearing terminal detail, and order-robust
17 * folding (completion can create an agent; a late start only fills
18 * metadata).
19 */
20import * as DateTime from "effect/DateTime";
21import type { OrchestrationThreadActivity, OrchestrationV2Subagent } from "@t3tools/contracts";
22​
23export type RuntimeSubagentStatus =
24 | "pending"
25 | "running"
26 | "waiting"
27 | "idle"
28 | "completed"
29 | "failed"
30 | "cancelled"
31 | "interrupted";
32​
33export interface SubagentUsage {
34 readonly totalTokens: number;
35 readonly inputTokens?: number;
36 readonly cachedInputTokens?: number;
37 readonly outputTokens?: number;
38 readonly reasoningOutputTokens?: number;
39 readonly toolUses?: number;
40 readonly durationMs?: number;
42​
43export interface SubagentActivityEntry {
44 readonly at: string;
45 readonly summary: string;
47​
48export interface SubagentWorkflowPhase {
49 readonly index: number;
50 readonly title: string;
52​
53export interface SubagentRunHandles {
54 readonly runId?: string;
55 readonly scriptPath?: string;
56 readonly transcriptDir?: string;
57 readonly sessionUrl?: string;
59​
60export interface RuntimeSubagent {
61 readonly id: string;
62 readonly kind: "subagent" | "subagent_batch" | "workflow" | "workflow_agent";
63 readonly title: string;
64 readonly role: string | null;
65 readonly model: string | null;
66 readonly effort: string | null;
67 readonly status: RuntimeSubagentStatus;
68 readonly activationCount: number;
69 readonly usage: SubagentUsage | null;
70 readonly progress: string | null;
71 readonly lastToolName: string | null;
72 readonly result: string | null;
73 readonly error: string | null;
74 readonly outputFile: string | null;
75 readonly parentAgentId: string | null;
76 readonly agentIndex: number | null;
77 readonly phaseIndex: number | null;
78 readonly phaseTitle: string | null;
79 readonly attempt: number | null;
80 readonly workflowName: string | null;
81 readonly phases: ReadonlyArray<SubagentWorkflowPhase>;
82 readonly runHandles: SubagentRunHandles | null;
83 readonly recentActivity: ReadonlyArray<SubagentActivityEntry>;
84 /** First retained observation, used as the roster's stable display order. */
85 readonly firstSeenAt: string;
86 readonly startedAt: string | null;
87 readonly completedAt: string | null;
88 readonly updatedAt: string;
90​
91const TERMINAL_STATUSES: ReadonlySet<RuntimeSubagentStatus> = new Set([
92 "completed",
93 "failed",
94 "cancelled",
95 "interrupted",
96]);
97​
98export function isTerminalSubagentStatus(status: RuntimeSubagentStatus): boolean {
99 return TERMINAL_STATUSES.has(status);
101​
102/** Active = the user may still need to care while it runs. Idle is settled-ish
103 * but resumable; waiting counts as active because it needs the user. */
104export function isActiveSubagentStatus(status: RuntimeSubagentStatus): boolean {
105 return status === "pending" || status === "running" || status === "waiting";
107​
108const RECENT_ACTIVITY_LIMIT = 6;
109const SUMMARY_CHAR_LIMIT = 180;
110const ROSTER_LIMIT = 100;
111​
112/**
113 * True when this activity's payload does NOT belong on the Agents surface.
114 * Classification happens exactly once, server-side at ingestion
115 * (classifyTaskAgentKind → the persisted agentKind stamp); the client only
116 * reads it. Rows without a stamp — legacy threads, pre-stamp servers — are
117 * background by definition: they render in the ordinary work log, exactly
118 * as they did before this feature existed.
119 */
120export function isBackgroundTaskActivity(payload: Record<string, unknown>): boolean {
121 return payload.agentKind !== "agent";
123​
124function bounded(value: string): string {
125 return value.length <= SUMMARY_CHAR_LIMIT ? value : `${value.slice(0, SUMMARY_CHAR_LIMIT - 1)}…`;
127​
128/** Appends to the ring buffer, deduping consecutive identical summaries. */
129function appendActivity(
130 entries: ReadonlyArray<SubagentActivityEntry>,
131 at: string,
132 summary: string,
133): ReadonlyArray<SubagentActivityEntry> {
134 const boundedSummary = bounded(summary);
135 if (entries.length > 0 && entries[entries.length - 1]?.summary === boundedSummary) {
136 return entries;
137 }
138 const next = [...entries, { at, summary: boundedSummary }];
139 return next.length > RECENT_ACTIVITY_LIMIT ? next.slice(-RECENT_ACTIVITY_LIMIT) : next;
141​
142function asString(value: unknown): string | undefined {
143 return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
145​
146function asCount(value: unknown): number | undefined {
147 return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
149​
150function asUsage(value: unknown): SubagentUsage | undefined {
151 if (typeof value !== "object" || value === null) {
152 return undefined;
153 }
154 const record = value as Record<string, unknown>;
155 const totalTokens = asCount(record.totalTokens);
156 if (totalTokens === undefined) {
157 return undefined;
158 }
159 const usage: {
160 totalTokens: number;
161 inputTokens?: number;
162 cachedInputTokens?: number;
163 outputTokens?: number;
164 reasoningOutputTokens?: number;
165 toolUses?: number;
166 durationMs?: number;
167 } = { totalTokens };
168 const inputTokens = asCount(record.inputTokens);
169 if (inputTokens !== undefined) usage.inputTokens = inputTokens;
170 const cachedInputTokens = asCount(record.cachedInputTokens);
171 if (cachedInputTokens !== undefined) usage.cachedInputTokens = cachedInputTokens;
172 const outputTokens = asCount(record.outputTokens);
173 if (outputTokens !== undefined) usage.outputTokens = outputTokens;
174 const reasoningOutputTokens = asCount(record.reasoningOutputTokens);
175 if (reasoningOutputTokens !== undefined) usage.reasoningOutputTokens = reasoningOutputTokens;
176 const toolUses = asCount(record.toolUses);
177 if (toolUses !== undefined) usage.toolUses = toolUses;
178 const durationMs = asCount(record.durationMs);
179 if (durationMs !== undefined) usage.durationMs = durationMs;
180 return usage;
182​
183/**
184 * Provider-specific usage merge (#4779 semantics, verbatim):
185 * - max-merge (Codex-style cumulative frames): field-wise maximum, idempotent
186 * under duplicate or late frames. Cumulative totals never shrink.
187 * - accumulate (Claude-style activation deltas): not needed at this layer —
188 * Claude's task_progress usage is itself cumulative per task, so the fold
189 * also max-merges. The distinction matters when v2 sums activations.
190 * Field-wise: a terminal payload carrying only totalTokens must not wipe a
191 * known breakdown.
192 */
193function mergeUsageMax(
194 current: SubagentUsage | null,
195 incoming: SubagentUsage | undefined,
196): SubagentUsage | null {
197 if (!incoming) {
198 return current;
199 }
200 if (!current) {
201 return incoming;
202 }
203 const pick = (a: number | undefined, b: number | undefined): number | undefined =>
204 a === undefined ? b : b === undefined ? a : Math.max(a, b);
205 const merged: {
206 totalTokens: number;
207 inputTokens?: number;
208 cachedInputTokens?: number;
209 outputTokens?: number;
210 reasoningOutputTokens?: number;
211 toolUses?: number;
212 durationMs?: number;
213 } = { totalTokens: Math.max(current.totalTokens, incoming.totalTokens) };
214 const inputTokens = pick(current.inputTokens, incoming.inputTokens);
215 if (inputTokens !== undefined) merged.inputTokens = inputTokens;
216 const cachedInputTokens = pick(current.cachedInputTokens, incoming.cachedInputTokens);
217 if (cachedInputTokens !== undefined) merged.cachedInputTokens = cachedInputTokens;
218 const outputTokens = pick(current.outputTokens, incoming.outputTokens);
219 if (outputTokens !== undefined) merged.outputTokens = outputTokens;
220 const reasoningOutputTokens = pick(current.reasoningOutputTokens, incoming.reasoningOutputTokens);
221 if (reasoningOutputTokens !== undefined) merged.reasoningOutputTokens = reasoningOutputTokens;
222 const toolUses = pick(current.toolUses, incoming.toolUses);
223 if (toolUses !== undefined) merged.toolUses = toolUses;
224 const durationMs = pick(current.durationMs, incoming.durationMs);
225 if (durationMs !== undefined) merged.durationMs = durationMs;
226 return merged;
228​
229interface MutableAgent {
230 id: string;
231 kind: RuntimeSubagent["kind"];
232 title: string;
233 role: string | null;
234 model: string | null;
235 effort: string | null;
236 status: RuntimeSubagentStatus;
237 activationCount: number;
238 usage: SubagentUsage | null;
239 progress: string | null;
240 lastToolName: string | null;
241 result: string | null;
242 error: string | null;
243 outputFile: string | null;
244 parentAgentId: string | null;
245 agentIndex: number | null;
246 phaseIndex: number | null;
247 phaseTitle: string | null;
248 attempt: number | null;
249 workflowName: string | null;
250 phases: ReadonlyArray<SubagentWorkflowPhase>;
251 runHandles: SubagentRunHandles | null;
252 recentActivity: ReadonlyArray<SubagentActivityEntry>;
253 firstSeenAt: string;
254 startedAt: string | null;
255 completedAt: string | null;
256 updatedAt: string;
258​
259function kindFromPayload(
260 payload: Record<string, unknown>,
261 agentId: string,
262): RuntimeSubagent["kind"] {
263 if (payload.taskType === "subagent_batch") {
264 return "subagent_batch";
265 }
266 if (asString(payload.taskType) === "local_workflow") {
267 return "workflow";
268 }
269 if (payload.parentAgentId !== undefined || agentId.includes(":wf:")) {
270 return "workflow_agent";
271 }
272 return "subagent";
274​
275/** Completion can create an agent (its start may have aged out of retention). */
276function getOrCreate(
277 agents: Map<string, MutableAgent>,
278 id: string,
279 payload: Record<string, unknown>,
280 at: string,
281): MutableAgent {
282 const existing = agents.get(id);
283 if (existing) {
284 return existing;
285 }
286 const created: MutableAgent = {
287 id,
288 kind: kindFromPayload(payload, id),
289 title: asString(payload.title) ?? asString(payload.detail) ?? id,
290 role: asString(payload.role) ?? null,
291 model: asString(payload.model) ?? null,
292 effort: asString(payload.effort) ?? null,
293 status: "pending",
294 activationCount: 0,
295 usage: null,
296 progress: null,
297 lastToolName: null,
298 result: null,
299 error: null,
300 outputFile: null,
301 parentAgentId: asString(payload.parentAgentId) ?? null,
302 agentIndex: asCount(payload.agentIndex) ?? null,
303 phaseIndex: asCount(payload.phaseIndex) ?? null,
304 phaseTitle: asString(payload.phaseTitle) ?? null,
305 attempt: asCount(payload.attempt) ?? null,
306 workflowName: asString(payload.workflowName) ?? null,
307 phases: [],
308 runHandles: null,
309 recentActivity: [],
310 firstSeenAt: at,
311 startedAt: null,
312 completedAt: null,
313 updatedAt: at,
314 };
315 agents.set(id, created);
316 return created;
318​
319/** Metadata fill from any payload: never downgrades known values to null. */
320function fillMetadata(agent: MutableAgent, payload: Record<string, unknown>): void {
321 if (payload.taskType === "subagent_batch") agent.kind = "subagent_batch";
322 const title = asString(payload.title);
323 if (title) agent.title = title;
324 const role = asString(payload.role);
325 if (role) agent.role = role;
326 const model = asString(payload.model);
327 if (model) agent.model = model;
328 const effort = asString(payload.effort);
329 if (effort) agent.effort = effort;
330 const parentAgentId = asString(payload.parentAgentId);
331 if (parentAgentId) {
332 agent.parentAgentId = parentAgentId;
333 if (agent.kind === "subagent") agent.kind = "workflow_agent";
334 }
335 const workflowName = asString(payload.workflowName);
336 if (workflowName) agent.workflowName = workflowName;
337 if (asString(payload.taskType) === "local_workflow") agent.kind = "workflow";
338 const agentIndex = asCount(payload.agentIndex);
339 if (agentIndex !== undefined) agent.agentIndex = agentIndex;
340 const phaseIndex = asCount(payload.phaseIndex);
341 if (phaseIndex !== undefined) agent.phaseIndex = phaseIndex;
342 const phaseTitle = asString(payload.phaseTitle);
343 if (phaseTitle) agent.phaseTitle = phaseTitle;
344 const attempt = asCount(payload.attempt);
345 if (attempt !== undefined) {
346 // A new attempt on a workflow slot is a reactivation of the same
347 // identity: clear the previous attempt's terminal detail so the status
348 // transition (terminal → running, in applyStatus) reads as a fresh run.
349 // The activation bump lives ONLY in applyStatus — bumping here too
350 // counted every retry twice (review finding: two attempts read "run 3").
351 if (agent.attempt !== null && attempt > agent.attempt) {
352 agent.result = null;
353 agent.error = null;
354 agent.completedAt = null;
355 }
356 agent.attempt = attempt;
357 }
358 const outputFile = asString(payload.outputFile);
359 if (outputFile) agent.outputFile = outputFile;
360 if (Array.isArray(payload.phases)) {
361 const phases: SubagentWorkflowPhase[] = [];
362 for (const entry of payload.phases) {
363 if (typeof entry !== "object" || entry === null) continue;
364 const record = entry as Record<string, unknown>;
365 const index = asCount(record.index);
366 const phaseName = asString(record.title);
367 if (index !== undefined && phaseName) {
368 phases.push({ index, title: phaseName });
369 }
370 }
371 if (phases.length > 0) {
372 agent.phases = phases.slice().sort((a, b) => a.index - b.index);
373 }
374 }
375 if (typeof payload.runHandles === "object" && payload.runHandles !== null) {
376 const record = payload.runHandles as Record<string, unknown>;
377 const runHandles: {
378 runId?: string;
379 scriptPath?: string;
380 transcriptDir?: string;
381 sessionUrl?: string;
382 } = {};
383 const runId = asString(record.runId);
384 if (runId) runHandles.runId = runId;
385 const scriptPath = asString(record.scriptPath);
386 if (scriptPath) runHandles.scriptPath = scriptPath;
387 const transcriptDir = asString(record.transcriptDir);
388 if (transcriptDir) runHandles.transcriptDir = transcriptDir;
389 // Defense-in-depth: the adapter already sanitizes, but payloads are not
390 // schema-validated on the read path (shipped XSS lesson).
391 const sessionUrl = asString(record.sessionUrl);
392 if (sessionUrl && /^https?:\/\//i.test(sessionUrl)) runHandles.sessionUrl = sessionUrl;
393 if (Object.keys(runHandles).length > 0) {
394 agent.runHandles = { ...agent.runHandles, ...runHandles };
395 }
396 }
398​
399function applyStatus(agent: MutableAgent, status: RuntimeSubagentStatus, at: string): void {
400 const wasTerminal = isTerminalSubagentStatus(agent.status);
401 const isTerminal = isTerminalSubagentStatus(status);
402 if (wasTerminal && isTerminal) {
403 // Duplicate terminal events are idempotent: first write wins, timestamps
404 // don't slide.
405 return;
406 }
407 if ((wasTerminal || agent.status === "idle") && (status === "running" || status === "pending")) {
408 // Reactivation: same identity, new run. Clear the previous run's terminal
409 // detail so a live card never shows the prior run's output.
410 agent.activationCount += 1;
411 agent.result = null;
412 agent.error = null;
413 agent.completedAt = null;
414 if (status === "running") {
415 agent.startedAt = at;
416 }
417 }
418 if (status === "running" && agent.startedAt === null) {
419 agent.startedAt = at;
420 }
421 if (isTerminal && agent.completedAt === null) {
422 agent.completedAt = at;
423 }
424 agent.status = status;
426​
427// Map, not object literal: payloads aren't schema-validated on the read
428// path, so a status like "toString" must miss instead of resolving an
429// inherited Function through the prototype chain.
430const TASK_COMPLETED_STATUS: ReadonlyMap<string, RuntimeSubagentStatus> = new Map([
431 ["completed", "completed"],
432 ["failed", "failed"],
433 ["stopped", "interrupted"],
434]);
435​
436const KNOWN_STATUSES: ReadonlySet<string> = new Set([
437 "pending",
438 "running",
439 "waiting",
440 "idle",
441 "completed",
442 "failed",
443 "cancelled",
444 "interrupted",
445]);
446​
447function asRuntimeStatus(value: unknown): RuntimeSubagentStatus | undefined {
448 return typeof value === "string" && KNOWN_STATUSES.has(value)
449 ? (value as RuntimeSubagentStatus)
450 : undefined;
452​
453/**
454 * Folds a thread's persisted activities into subagent state. Tolerant by
455 * construction: malformed rows are skipped individually; unknown kinds are
456 * ignored. Pure — memoize by activity-list identity at the atom layer.
457 *
458 * sessionLive=false derives interruption: background tasks die with their
459 * provider session, so agents whose terminal rows were lost (server
460 * restart, crash) must not read as running forever (review finding: a dead
461 * session left a panel full of "Working" agents while the sidebar showed
462 * nothing). Idle is preserved — a resumable Codex child stays resumable.
463 */
464export function foldSubagentActivities(
465 activities: ReadonlyArray<OrchestrationThreadActivity>,
466 options?: { readonly sessionLive?: boolean },
467): ReadonlyArray<RuntimeSubagent> {
468 const agents = new Map<string, MutableAgent>();
469​
470 for (const activity of activities) {
471 if (typeof activity.payload !== "object" || activity.payload === null) {
472 continue;
473 }
474 const payload = activity.payload as Record<string, unknown>;
475 const at = activity.createdAt;
476​
477 switch (activity.kind) {
478 case "task.started": {
479 const taskId = asString(payload.taskId);
480 if (!taskId) break;
481 // Only real agents join the roster. Shells, monitors, and plan-mode
482 // tasks are background work — they render in the ordinary work log,
483 // not the Agents surface (a "Run 12s stall" shell is not a subagent).
484 if (isBackgroundTaskActivity(payload)) break;
485 const agent = getOrCreate(agents, taskId, payload, at);
486 fillMetadata(agent, payload);
487 // Order-robustness: a start row arriving after a terminal state is a
488 // late/out-of-order delivery and only fills metadata — it must not
489 // reopen the run. Reactivation comes exclusively from explicit
490 // status transitions (task.updated / progress status). Guard on the
491 // status itself, not activationCount: a task first seen via a
492 // terminal task.updated has zero activations but is still settled
493 // (review finding: a late start reopened a failed child).
494 if (agent.activationCount === 0 && !isTerminalSubagentStatus(agent.status)) {
495 agent.activationCount = 1;
496 agent.startedAt = agent.startedAt ?? at;
497 agent.status = "running";
498 } else if (agent.status === "idle") {
499 applyStatus(agent, "running", at);
500 }
501 const detail = asString(payload.detail);
502 if (detail && agent.title === agent.id) agent.title = detail;
503 agent.updatedAt = at;
504 break;
505 }
506 case "task.progress": {
507 const taskId = asString(payload.taskId);
508 if (!taskId) break;
509 // Membership is sticky per taskId: rows after the first (terminal
510 // rows often carry only taskId+status, no marker fields) inherit the
511 // first row's classification instead of being re-judged.
512 const existed = agents.has(taskId);
513 if (!existed && isBackgroundTaskActivity(payload)) break;
514 const agent = getOrCreate(agents, taskId, payload, at);
515 fillMetadata(agent, payload);
516 if (agent.activationCount === 0) agent.activationCount = 1;
517 const explicitStatus = asRuntimeStatus(payload.status);
518 if (explicitStatus) {
519 applyStatus(agent, explicitStatus, at);
520 } else if (
521 (payload.usageSnapshot !== true || !existed) &&
522 !isTerminalSubagentStatus(agent.status) &&
523 agent.status !== "idle"
524 ) {
525 applyStatus(agent, "running", at);
526 }
527 const summary = asString(payload.summary);
528 if (summary) {
529 agent.progress = bounded(summary);
530 agent.recentActivity = appendActivity(agent.recentActivity, at, summary);
531 }
532 const lastToolName = asString(payload.lastToolName);
533 if (lastToolName) {
534 agent.lastToolName = lastToolName;
535 if (!summary) {
536 agent.recentActivity = appendActivity(agent.recentActivity, at, `▸ ${lastToolName}`);
537 }
538 }
539 const error = asString(payload.error);
540 if (error) agent.error = bounded(error);
541 agent.usage = mergeUsageMax(agent.usage, asUsage(payload.typedUsage));
542 agent.updatedAt = at;
543 break;
544 }
545 case "task.updated": {
546 const taskId = asString(payload.taskId);
547 if (!taskId) break;
548 // Membership is sticky per taskId: rows after the first (terminal
549 // rows often carry only taskId+status, no marker fields) inherit the
550 // first row's classification instead of being re-judged.
551 if (!agents.has(taskId) && isBackgroundTaskActivity(payload)) break;
552 const agent = getOrCreate(agents, taskId, payload, at);
553 fillMetadata(agent, payload);
554 const detail = asString(payload.detail);
555 if (detail) agent.progress = bounded(detail);
556 // A task first seen via task.updated (start row aged out) has run at
557 // least once — zero activations would misreport "run 0" and let a
558 // later start row treat it as never-started (review finding).
559 if (agent.activationCount === 0) agent.activationCount = 1;
560 const wasTerminal = isTerminalSubagentStatus(agent.status);
561 const status = asRuntimeStatus(payload.status);
562 if (status) applyStatus(agent, status, at);
563 const error = asString(payload.error);
564 if (error) agent.error = bounded(error);
565 // Provider end time beats ingestion time for the transition that
566 // actually settled the run (applyStatus fills completedAt with the
567 // activity timestamp first, so check the transition, not null).
568 const endedAt = asString(payload.endedAt);
569 if (endedAt && !wasTerminal && isTerminalSubagentStatus(agent.status)) {
570 agent.completedAt = endedAt;
571 }
572 agent.updatedAt = at;
573 break;
574 }
575 case "task.completed": {
576 const taskId = asString(payload.taskId);
577 if (!taskId) break;
578 // Membership is sticky per taskId: rows after the first (terminal
579 // rows often carry only taskId+status, no marker fields) inherit the
580 // first row's classification instead of being re-judged.
581 if (!agents.has(taskId) && isBackgroundTaskActivity(payload)) break;
582 const agent = getOrCreate(agents, taskId, payload, at);
583 fillMetadata(agent, payload);
584 if (agent.activationCount === 0) agent.activationCount = 1;
585 // Already-terminal: status and timestamps are frozen (first write
586 // wins, duplicates must not slide them) but the completion still
587 // ENRICHES — Claude commonly emits terminal task.updated before
588 // task.completed, and the completion carries the result summary and
589 // final usage the update lacked (review finding: the early return
590 // dropped both). Fill-if-missing keeps duplicate completions from
591 // replacing the first result.
592 const summary = asString(payload.summary) ?? asString(payload.detail);
593 if (isTerminalSubagentStatus(agent.status)) {
594 if (summary) {
595 if (agent.status === "failed") {
596 agent.error = agent.error ?? bounded(summary);
597 } else {
598 agent.result = agent.result ?? bounded(summary);
599 }
600 }
601 agent.usage = mergeUsageMax(agent.usage, asUsage(payload.typedUsage));
602 break;
603 }
604 const status = TASK_COMPLETED_STATUS.get(asString(payload.status) ?? "") ?? "completed";
605 applyStatus(agent, status, at);
606 if (summary) {
607 if (status === "failed") {
608 agent.error = agent.error ?? bounded(summary);
609 } else {
610 agent.result = bounded(summary);
611 }
612 }
613 agent.usage = mergeUsageMax(agent.usage, asUsage(payload.typedUsage));
614 agent.updatedAt = at;
615 break;
616 }
617 case "tool.progress": {
618 // Agent-owned heartbeat: "what it's doing right now".
619 const taskId = asString(payload.taskId);
620 if (!taskId) break;
621 const agent = agents.get(taskId);
622 if (!agent) break;
623 const toolName = asString(payload.toolName);
624 if (toolName) {
625 agent.lastToolName = toolName;
626 agent.recentActivity = appendActivity(agent.recentActivity, at, `▸ ${toolName}`);
627 }
628 agent.updatedAt = at;
629 break;
630 }
631 default:
632 break;
633 }
634 }
635​
636 // Consistency pass: when a workflow coordinator has settled, members that
637 // never received their own terminal row cannot still be in-flight — the
638 // run is over. Cascade the coordinator's outcome so stalled member rows
639 // don't read as working forever (live-test finding: statuses drifted
640 // whenever member terminal rows were lost or never emitted).
641 for (const agent of agents.values()) {
642 if (agent.kind !== "workflow" || !isTerminalSubagentStatus(agent.status)) {
643 continue;
644 }
645 for (const member of agents.values()) {
646 if (member.parentAgentId !== agent.id) {
647 continue;
648 }
649 if (isTerminalSubagentStatus(member.status) || member.status === "idle") {
650 continue;
651 }
652 member.status = agent.status === "completed" ? "completed" : "interrupted";
653 member.completedAt = member.completedAt ?? agent.completedAt ?? agent.updatedAt;
654 member.updatedAt = agent.updatedAt;
655 }
656 }
657​
658 // Session death orphans every live agent: no process remains to finish
659 // them. Mirrors the server-side liveness registry clearing on
660 // session.exited, so panel and sidebar can never disagree.
661 if (options?.sessionLive === false) {
662 for (const agent of agents.values()) {
663 if (isActiveSubagentStatus(agent.status)) {
664 agent.status = "interrupted";
665 agent.completedAt = agent.completedAt ?? agent.updatedAt;
666 }
667 }
668 }
669​
670 let roster = Array.from(agents.values());
671 if (roster.length > ROSTER_LIMIT) {
672 // Prefer live, then waiting/idle, then newest settled.
673 const rank = (agent: MutableAgent): number =>
674 isActiveSubagentStatus(agent.status) ? 0 : agent.status === "idle" ? 1 : 2;
675 roster = roster
676 .slice()
677 .sort((a, b) => rank(a) - rank(b) || b.updatedAt.localeCompare(a.updatedAt))
678 .slice(0, ROSTER_LIMIT);
679 }
680​
681 return roster.map((agent) => ({ ...agent }));
683​
684export interface AgentPanelWorkflowGroup {
685 readonly workflow: RuntimeSubagent;
686 readonly phases: ReadonlyArray<{
687 readonly index: number;
688 readonly title: string;
689 readonly members: ReadonlyArray<RuntimeSubagent>;
690 /** done = every member settled (success or error); running = any active. */
691 readonly state: "pending" | "running" | "done";
692 readonly activeCount: number;
693 readonly settledCount: number;
694 }>;
695 /** Members with no resolvable phase (orphans render under the workflow). */
696 readonly unphasedMembers: ReadonlyArray<RuntimeSubagent>;
698​
699export interface AgentPanelModel {
700 readonly workflows: ReadonlyArray<AgentPanelWorkflowGroup>;
701 readonly directAgents: ReadonlyArray<RuntimeSubagent>;
702 readonly runningCount: number;
703 readonly waitingCount: number;
704 readonly idleCount: number;
705 readonly settledCount: number;
706 readonly totalTokens: number;
707 readonly hasAgents: boolean;
708 readonly liveCount: number;
710​
711const EMPTY_PANEL_MODEL: AgentPanelModel = {
712 workflows: [],
713 directAgents: [],
714 runningCount: 0,
715 waitingCount: 0,
716 idleCount: 0,
717 settledCount: 0,
718 totalTokens: 0,
719 hasAgents: false,
720 liveCount: 0,
721};
722​
723export function emptyAgentPanelModel(): AgentPanelModel {
724 return EMPTY_PANEL_MODEL;
726​
727/**
728 * The v2 leg of the mapper swap (#5219 spec): project orchestration-v2
729 * subagent entities into the same runtime shape the native fold produced.
730 * The panel/CTA components never see which source fed them.
731 */
732export function projectedSubagentsToRuntime(
733 subagents: ReadonlyArray<{
734 readonly id: string;
735 readonly title: string | null;
736 readonly prompt: string;
737 readonly model: string | null;
738 readonly status: OrchestrationV2Subagent["status"];
739 readonly progress?: string | undefined;
740 readonly result: string | null;
741 readonly startedAt: DateTime.Utc | null;
742 readonly completedAt: DateTime.Utc | null;
743 readonly updatedAt: DateTime.Utc;
744 }>,
745): ReadonlyArray<RuntimeSubagent> {
746 return subagents.map((subagent) => {
747 const updatedAt = DateTime.formatIso(subagent.updatedAt);
748 const startedAt = subagent.startedAt === null ? null : DateTime.formatIso(subagent.startedAt);
749 return {
750 id: subagent.id,
751 kind: "subagent" as const,
752 title:
753 subagent.title ??
754 (subagent.prompt.length > 80 ? `${subagent.prompt.slice(0, 77)}...` : subagent.prompt),
755 role: null,
756 model: subagent.model,
757 effort: null,
758 status: subagent.status,
759 activationCount: 1,
760 usage: null,
761 progress: subagent.progress ?? null,
762 lastToolName: null,
763 result: subagent.result,
764 error: subagent.status === "failed" ? (subagent.result ?? null) : null,
765 outputFile: null,
766 parentAgentId: null,
767 agentIndex: null,
768 phaseIndex: null,
769 phaseTitle: null,
770 attempt: null,
771 workflowName: null,
772 phases: [],
773 runHandles: null,
774 recentActivity: [],
775 firstSeenAt: startedAt ?? updatedAt,
776 startedAt,
777 completedAt: subagent.completedAt === null ? null : DateTime.formatIso(subagent.completedAt),
778 updatedAt,
779 } satisfies RuntimeSubagent;
780 });
782​
783/**
784 * Source-neutral view model. When the orchestration-v2 subagent projection
785 * exists for the thread, pass it as v2Projection and it wins outright — the
786 * two sources are never merged (duplicate-agents failure mode). Until v2
787 * lands, callers pass null and the native fold output is used.
788 */
789export function deriveAgentPanelModel({
790 agents,
791 v2Projection,
792}: {
793 readonly agents: ReadonlyArray<RuntimeSubagent>;
794 readonly v2Projection?: ReadonlyArray<RuntimeSubagent> | null;
795}): AgentPanelModel {
796 const source = v2Projection ?? agents;
797 if (source.length === 0) {
798 return EMPTY_PANEL_MODEL;
799 }
800​
801 const workflows = source
802 .filter((agent) => agent.kind === "workflow")
803 .slice()
804 .sort((a, b) => a.firstSeenAt.localeCompare(b.firstSeenAt) || a.id.localeCompare(b.id));
805 const workflowIds = new Set(workflows.map((workflow) => workflow.id));
806 const members = new Map<string, RuntimeSubagent[]>();
807 const direct: RuntimeSubagent[] = [];
808​
809 for (const agent of source) {
810 if (agent.kind === "workflow") {
811 continue;
812 }
813 if (agent.parentAgentId !== null && workflowIds.has(agent.parentAgentId)) {
814 const list = members.get(agent.parentAgentId) ?? [];
815 list.push(agent);
816 members.set(agent.parentAgentId, list);
817 } else {
818 // Orphaned members (coordinator aged out) fall back to the direct list.
819 direct.push(agent);
820 }
821 }
822​
823 const workflowGroups: AgentPanelWorkflowGroup[] = workflows.map((workflow) => {
824 const workflowMembers = members.get(workflow.id) ?? [];
825 const knownPhases =
826 workflow.phases.length > 0
827 ? workflow.phases
828 : (() => {
829 const derived = new Map<number, string>();
830 for (const member of workflowMembers) {
831 if (member.phaseIndex !== null && !derived.has(member.phaseIndex)) {
832 derived.set(
833 member.phaseIndex,
834 member.phaseTitle ?? `Phase ${member.phaseIndex + 1}`,
835 );
836 }
837 }
838 return Array.from(derived.entries())
839 .map(([index, title]) => ({ index, title }))
840 .slice()
841 .sort((a, b) => a.index - b.index);
842 })();
843​
844 const knownPhaseIndices = new Set(knownPhases.map((phase) => phase.index));
845 const phases = knownPhases.map((phase) => {
846 const phaseMembers = workflowMembers
847 .filter((member) => member.phaseIndex === phase.index)
848 .slice()
849 .sort((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0));
850 const activeCount = phaseMembers.filter(
851 // Idle members count as active for phase-liveness: a resumable Codex
852 // member has not finished the phase.
853 (member) => isActiveSubagentStatus(member.status) || member.status === "idle",
854 ).length;
855 const settledCount = phaseMembers.filter((member) =>
856 isTerminalSubagentStatus(member.status),
857 ).length;
858 const state: "pending" | "running" | "done" =
859 phaseMembers.length === 0
860 ? "pending"
861 : activeCount > 0
862 ? "running"
863 : settledCount === phaseMembers.length
864 ? "done"
865 : "pending";
866 return {
867 index: phase.index,
868 title: phase.title,
869 members: phaseMembers,
870 state,
871 activeCount,
872 settledCount,
873 };
874 });
875​
876 // Unknown phase indices land here too — a member must never vanish just
877 // because its phase row was lost (review finding).
878 const unphasedMembers = workflowMembers
879 .filter((member) => member.phaseIndex === null || !knownPhaseIndices.has(member.phaseIndex))
880 .slice()
881 .sort((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0));
882​
883 return { workflow, phases, unphasedMembers };
884 });
885​
886 let runningCount = 0;
887 let waitingCount = 0;
888 let idleCount = 0;
889 let settledCount = 0;
890 let totalTokens = 0;
891 for (const agent of source) {
892 // A workflow coordinator with members is a container for those members, not
893 // work of its own: it reports running for the whole run and aggregates their
894 // usage upstream in some providers. Counting it would report one more agent
895 // working than there are, and double count tokens.
896 if (agent.kind === "workflow" && (members.get(agent.id) ?? []).length > 0) continue;
897 if (agent.status === "running" || agent.status === "pending") runningCount += 1;
898 else if (agent.status === "waiting") waitingCount += 1;
899 else if (agent.status === "idle") idleCount += 1;
900 else settledCount += 1;
901 totalTokens += agent.usage?.totalTokens ?? 0;
902 }
903​
904 return {
905 workflows: workflowGroups,
906 // Updates and the >100-agent retention ranking must never reshuffle rows
907 // that remain visible.
908 directAgents: direct
909 .slice()
910 .sort((a, b) => a.firstSeenAt.localeCompare(b.firstSeenAt) || a.id.localeCompare(b.id)),
911 runningCount,
912 waitingCount,
913 idleCount,
914 settledCount,
915 totalTokens,
916 hasAgents: true,
917 liveCount: runningCount + waitingCount,
918 };
920​
921/**
922 * Members ordered by urgency for the capped inline workflow card: running and
923 * failed first, then waiting, then most recently updated.
924 */
925export function workflowCardMembers(
926 group: AgentPanelWorkflowGroup,
927 limit: number,
928): { readonly visible: ReadonlyArray<RuntimeSubagent>; readonly overflow: number } {
929 const all = [...group.phases.flatMap((phase) => phase.members), ...group.unphasedMembers];
930 const urgency = (agent: RuntimeSubagent): number => {
931 if (agent.status === "failed") return 0;
932 if (agent.status === "running") return 1;
933 if (agent.status === "waiting") return 2;
934 return 3;
935 };
936 const ordered = all
937 .slice()
938 .sort((a, b) => urgency(a) - urgency(b) || b.updatedAt.localeCompare(a.updatedAt));
939 return {
940 visible: ordered.slice(0, limit),
941 overflow: Math.max(0, ordered.length - limit),
942 };
944​
945/** Kinds the timeline should not render as generic rows (fold input only). */
946export function isSubagentActivityKind(kind: string): boolean {
947 return (
948 kind === "task.started" ||
949 kind === "task.progress" ||
950 kind === "task.updated" ||
951 kind === "task.completed" ||
952 kind === "tool.progress"
953 );
955​
956/**
957 * Quiet-timeline guarantee: tool rows attributed to an owning agent belong in
958 * the Agents surface, not the parent chat. Unattributed rows must stay.
959 */
960export function isAgentAttributedToolActivity(activity: OrchestrationThreadActivity): boolean {
961 if (typeof activity.payload !== "object" || activity.payload === null) {
962 return false;
963 }
964 const payload = activity.payload as Record<string, unknown>;
965 return typeof payload.agentId === "string" && payload.agentId.trim().length > 0;
967​
968/** Timeline-bypassing synthesized rows (Codex children, workflow members). */
969export function isTimelineBypassActivity(activity: OrchestrationThreadActivity): boolean {
970 if (typeof activity.payload !== "object" || activity.payload === null) {
971 return false;
972 }
973 return (activity.payload as Record<string, unknown>).timelineBypass === true;
975​
976/**
977 * Compact model chip text: strips vendor prefixes/date-or-context suffixes
978 * ("claude-sonnet-5[1m]" → "sonnet-5[1m]", "claude-opus-4-20250514" →
979 * "opus-4"). Unknown ids pass through untouched; effort appends as "· high".
980 */
981export function formatSubagentModelLabel(
982 model: string | null,
983 effort: string | null,
984): string | null {
985 if (!model) {
986 return null;
987 }
988 const compact = model
989 .replace(/^claude-/, "")
990 .replace(/-\d{8}$/, "")
991 .replace(/-latest$/, "");
992 return effort ? `${compact} · ${effort}` : compact;
994​
995export function formatSubagentTokenCount(totalTokens: number): string {
996 if (totalTokens < 1000) {
997 return `${totalTokens}`;
998 }
999 if (totalTokens < 1_000_000) {
1000 const value = totalTokens / 1000;
1001 return `${value >= 100 ? Math.round(value) : value.toFixed(1)}k`;
1003 return `${(totalTokens / 1_000_000).toFixed(1)}M`;