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

subagentRuntime.ts

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