Open History to see the last commit
1import { groupBy } from "effect/Array";
2import * as DateTime from "effect/DateTime";
3import type {
4 OrchestrationV2Subagent,
5 OrchestrationV2SubagentWorkflow,
6 OrchestrationV2TurnItem,
7} from "@t3tools/contracts";
8import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
9
10export type RuntimeSubagentStatus =
11 | "pending"
12 | "running"
13 | "waiting"
14 | "idle"
15 | "completed"
16 | "failed"
17 | "cancelled"
18 | "interrupted";
19
20export interface SubagentUsage {
21 readonly totalTokens: number;
22 readonly inputTokens?: number;
23 readonly cachedInputTokens?: number;
24 readonly outputTokens?: number;
25 readonly reasoningOutputTokens?: number;
26 readonly toolUses?: number;
27 readonly durationMs?: number;
28}
29
30export interface SubagentActivityEntry {
31 readonly at: string;
32 readonly summary: string;
33}
34
35export interface SubagentWorkflowPhase {
36 readonly index: number;
37 readonly title: string;
38}
39
40export interface SubagentRunHandles {
41 readonly runId?: string | undefined;
42 readonly scriptPath?: string | undefined;
43 readonly transcriptDir?: string | undefined;
44 readonly sessionUrl?: string | undefined;
45}
46
47export interface RuntimeSubagent {
48 readonly id: string;
49 readonly kind: "subagent" | "subagent_batch" | "workflow" | "workflow_agent";
50 readonly title: string;
51 readonly role: string | null;
52 readonly model: string | null;
53 readonly effort: string | null;
54 readonly status: RuntimeSubagentStatus;
55 readonly activationCount: number;
56 readonly usage: SubagentUsage | null;
57 readonly progress: string | null;
58 readonly lastToolName: string | null;
59 readonly result: string | null;
60 readonly error: string | null;
61 readonly outputFile: string | null;
62 readonly parentAgentId: string | null;
63 readonly agentIndex: number | null;
64 readonly phaseIndex: number | null;
65 readonly phaseTitle: string | null;
66 readonly attempt: number | null;
67 readonly workflowName: string | null;
68 readonly phases: ReadonlyArray<SubagentWorkflowPhase>;
69 readonly runHandles: SubagentRunHandles | null;
70 readonly childThreadId: string | null;
71 readonly recentActivity: ReadonlyArray<SubagentActivityEntry>;
72 readonly firstSeenAt: string;
73 readonly startedAt: string | null;
74 readonly completedAt: string | null;
75 readonly updatedAt: string;
76}
77
78const TERMINAL_STATUSES: ReadonlySet<RuntimeSubagentStatus> = new Set([
79 "completed",
80 "failed",
81 "cancelled",
82 "interrupted",
83]);
84
85export function isTerminalSubagentStatus(status: RuntimeSubagentStatus): boolean {
86 return TERMINAL_STATUSES.has(status);
87}
88
89export function isActiveSubagentStatus(status: RuntimeSubagentStatus): boolean {
90 return isOrchestrationV2WorkActive(status);
91}
92
93export function isLiveSubagentTurnItem(item: OrchestrationV2TurnItem): boolean {
94 return item.type === "subagent" && isOrchestrationV2WorkActive(item.status);
95}
96
97export interface SubagentWorkflowGroup {
98 readonly workflow: RuntimeSubagent;
99 readonly phases: ReadonlyArray<{
100 readonly index: number;
101 readonly title: string;
102 readonly members: ReadonlyArray<RuntimeSubagent>;
103 readonly state: "pending" | "running" | "done";
104 readonly settledCount: number;
105 }>;
106 readonly unphasedMembers: ReadonlyArray<RuntimeSubagent>;
107}
108
109function workflowUsage(source: {
110 readonly totalTokens?: number | undefined;
111 readonly toolCalls?: number | undefined;
112 readonly durationMs?: number | undefined;
113}): SubagentUsage | null {
114 if (source.totalTokens === undefined) return null;
115 return {
116 totalTokens: source.totalTokens,
117 ...(source.toolCalls === undefined ? {} : { toolUses: source.toolCalls }),
118 ...(source.durationMs === undefined ? {} : { durationMs: source.durationMs }),
119 };
120}
121
122function isoFromEpochMillis(value: number | undefined): string | null {
123 return value === undefined ? null : DateTime.formatIso(DateTime.makeUnsafe(value));
124}
125
126function workflowMembersToRuntime(
127 coordinator: RuntimeSubagent,
128 workflow: OrchestrationV2SubagentWorkflow,
129): ReadonlyArray<RuntimeSubagent> {
130 return workflow.agents.map((agent) => {
131 const status =
132 (agent.state === "queued" || agent.state === "running") &&
133 isTerminalSubagentStatus(coordinator.status)
134 ? coordinator.status
135 : agent.state === "queued"
136 ? "pending"
137 : agent.state;
138 const failed = status === "failed";
139 const startedAt = isoFromEpochMillis(agent.startedAt);
140 const completedAt = isTerminalSubagentStatus(status)
141 ? agent.startedAt !== undefined && agent.durationMs !== undefined
142 ? isoFromEpochMillis(agent.startedAt + agent.durationMs)
143 : coordinator.completedAt
144 : null;
145 return {
146 ...coordinator,
147 id: `${coordinator.id}:agent:${agent.index}`,
148 kind: "workflow_agent" as const,
149 title: agent.label,
150 model: agent.model ?? null,
151 status,
152 activationCount: agent.attempt ?? 1,
153 usage: workflowUsage(agent),
154 progress: agent.prompt ?? null,
155 result: failed ? null : (agent.result ?? null),
156 error: failed ? (agent.result ?? null) : null,
157 parentAgentId: coordinator.id,
158 agentIndex: agent.index,
159 phaseIndex: agent.phaseIndex ?? null,
160 phaseTitle: agent.phaseTitle ?? null,
161 attempt: agent.attempt ?? null,
162 phases: [],
163 childThreadId: agent.childThreadId ?? null,
164 recentActivity: [],
165 firstSeenAt: isoFromEpochMillis(agent.queuedAt) ?? startedAt ?? coordinator.firstSeenAt,
166 startedAt,
167 completedAt,
168 updatedAt: completedAt ?? startedAt ?? coordinator.firstSeenAt,
169 } satisfies RuntimeSubagent;
170 });
171}
172
173export function projectedSubagentsToRuntime(
174 subagents: ReadonlyArray<{
175 readonly id: string;
176 readonly title: string | null;
177 readonly prompt: string;
178 readonly model: string | null;
179 readonly status: OrchestrationV2Subagent["status"];
180 readonly progress?: string | undefined;
181 readonly childThreadId?: string | null | undefined;
182 readonly workflow?: OrchestrationV2SubagentWorkflow | undefined;
183 readonly result: string | null;
184 readonly startedAt: DateTime.Utc | null;
185 readonly completedAt: DateTime.Utc | null;
186 readonly updatedAt: DateTime.Utc;
187 }>,
188): ReadonlyArray<RuntimeSubagent> {
189 return subagents.flatMap((subagent) => {
190 const updatedAt = DateTime.formatIso(subagent.updatedAt);
191 const startedAt = subagent.startedAt === null ? null : DateTime.formatIso(subagent.startedAt);
192 const firstSeenAt = startedAt ?? updatedAt;
193 const { workflow } = subagent;
194 const runHandles = workflow?.runHandles ?? null;
195 const coordinator = {
196 id: subagent.id,
197 kind: workflow === undefined ? "subagent" : "workflow",
198 title:
199 subagent.title ??
200 (subagent.prompt.length > 80 ? `${subagent.prompt.slice(0, 77)}...` : subagent.prompt),
201 role: null,
202 model: subagent.model,
203 effort: null,
204 status: subagent.status,
205 activationCount: 1,
206 usage: workflow === undefined ? null : workflowUsage(workflow),
207 progress: subagent.progress ?? null,
208 lastToolName: null,
209 result: subagent.result,
210 error: subagent.status === "failed" ? (subagent.result ?? null) : null,
211 outputFile: null,
212 parentAgentId: null,
213 agentIndex: null,
214 phaseIndex: null,
215 phaseTitle: null,
216 attempt: null,
217 workflowName: workflow?.name ?? null,
218 phases: workflow?.phases ?? [],
219 runHandles,
220 childThreadId: subagent.childThreadId ?? null,
221 recentActivity: [],
222 firstSeenAt,
223 startedAt,
224 completedAt: subagent.completedAt === null ? null : DateTime.formatIso(subagent.completedAt),
225 updatedAt,
226 } satisfies RuntimeSubagent;
227 return workflow === undefined
228 ? [coordinator]
229 : [coordinator, ...workflowMembersToRuntime(coordinator, workflow)];
230 });
231}
232
233export function deriveWorkflowGroups(
234 agents: ReadonlyArray<RuntimeSubagent>,
235): ReadonlyArray<SubagentWorkflowGroup> {
236 const workflows = agents
237 .filter((agent) => agent.kind === "workflow")
238 .sort((a, b) => a.firstSeenAt.localeCompare(b.firstSeenAt) || a.id.localeCompare(b.id));
239 const members = groupBy(
240 agents.filter((agent) => agent.kind !== "workflow" && agent.parentAgentId !== null),
241 (agent) => agent.parentAgentId!,
242 );
243
244 return workflows.map((workflow) => {
245 const workflowMembers = Object.hasOwn(members, workflow.id) ? members[workflow.id]! : [];
246 // Union, not either/or: the declared plan lags the members, because the
247 // provider only admits a phase once something in it starts. Members seed
248 // the map; the declared titles then overwrite whatever they guessed.
249 const phaseTitles = new Map<number, string>();
250 for (const member of workflowMembers) {
251 if (member.phaseIndex === null) continue;
252 phaseTitles.set(
253 member.phaseIndex,
254 member.phaseTitle ?? phaseTitles.get(member.phaseIndex) ?? `Phase ${member.phaseIndex + 1}`,
255 );
256 }
257 for (const phase of workflow.phases) phaseTitles.set(phase.index, phase.title);
258 const knownPhases = Array.from(phaseTitles.entries())
259 .map(([index, title]) => ({ index, title }))
260 .sort((a, b) => a.index - b.index);
261
262 const phases = knownPhases.map((phase) => {
263 const phaseMembers = workflowMembers
264 .filter((member) => member.phaseIndex === phase.index)
265 .sort((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0));
266 const hasActiveMember = phaseMembers.some(
267 // Idle members count as active for phase-liveness: a resumable Codex
268 // member has not finished the phase.
269 (member) => isActiveSubagentStatus(member.status) || member.status === "idle",
270 );
271 const settledCount = phaseMembers.filter((member) =>
272 isTerminalSubagentStatus(member.status),
273 ).length;
274 const state: "pending" | "running" | "done" =
275 phaseMembers.length === 0 ? "pending" : hasActiveMember ? "running" : "done";
276 return {
277 index: phase.index,
278 title: phase.title,
279 members: phaseMembers,
280 state,
281 settledCount,
282 };
283 });
284
285 const unphasedMembers = workflowMembers
286 .filter((member) => member.phaseIndex === null)
287 .sort((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0));
288
289 return { workflow, phases, unphasedMembers };
290 });
291}