Open History to see the last commit
1import { groupBy } from "effect/Array";
2import * as DateTime from "effect/DateTime";
3import type {
4 OrchestrationV2AppThread,
5 OrchestrationV2Subagent,
6 OrchestrationV2SubagentWorkflow,
7 OrchestrationV2TurnItem,
8} from "@t3tools/contracts";
9import { isOrchestrationV2WorkActive, isProviderNativeSubagentThread } from "@t3tools/contracts";
10
11export type RuntimeSubagentStatus =
12 | "pending"
13 | "running"
14 | "waiting"
15 | "idle"
16 | "completed"
17 | "failed"
18 | "cancelled"
19 | "interrupted";
20
21export interface SubagentUsage {
22 readonly totalTokens: number;
23 readonly inputTokens?: number;
24 readonly cachedInputTokens?: number;
25 readonly outputTokens?: number;
26 readonly reasoningOutputTokens?: number;
27 readonly toolUses?: number;
28 readonly durationMs?: number;
29}
30
31export interface SubagentActivityEntry {
32 readonly at: string;
33 readonly summary: string;
34}
35
36export interface SubagentWorkflowPhase {
37 readonly index: number;
38 readonly title: string;
39}
40
41export interface SubagentRunHandles {
42 readonly runId?: string | undefined;
43 readonly scriptPath?: string | undefined;
44 readonly transcriptDir?: string | undefined;
45 readonly sessionUrl?: string | undefined;
46}
47
48export interface RuntimeSubagent {
49 readonly id: string;
50 readonly kind: "subagent" | "subagent_batch" | "workflow" | "workflow_agent";
51 readonly title: string;
52 readonly role: string | null;
53 readonly model: string | null;
54 readonly effort: string | null;
55 readonly speed?: string | undefined;
56 readonly status: RuntimeSubagentStatus;
57 readonly activationCount: number;
58 readonly usage: SubagentUsage | null;
59 readonly progress: string | null;
60 readonly lastToolName: string | null;
61 readonly result: string | null;
62 readonly error: string | null;
63 readonly outputFile: string | null;
64 readonly parentAgentId: string | null;
65 readonly agentIndex: number | null;
66 readonly phaseIndex: number | null;
67 readonly phaseTitle: string | null;
68 readonly attempt: number | null;
69 readonly workflowName: string | null;
70 readonly phases: ReadonlyArray<SubagentWorkflowPhase>;
71 readonly runHandles: SubagentRunHandles | null;
72 readonly childThreadId: string | null;
73 readonly recentActivity: ReadonlyArray<SubagentActivityEntry>;
74 readonly firstSeenAt: string;
75 readonly startedAt: string | null;
76 readonly completedAt: string | null;
77 readonly updatedAt: string;
78}
79
80const TERMINAL_STATUSES: ReadonlySet<RuntimeSubagentStatus> = new Set([
81 "completed",
82 "failed",
83 "cancelled",
84 "interrupted",
85]);
86
87export function isTerminalSubagentStatus(status: RuntimeSubagentStatus): boolean {
88 return TERMINAL_STATUSES.has(status);
89}
90
91export function isActiveSubagentStatus(status: RuntimeSubagentStatus): boolean {
92 return isOrchestrationV2WorkActive(status);
93}
94
95export function isLiveSubagentTurnItem(item: OrchestrationV2TurnItem): boolean {
96 return item.type === "subagent" && isOrchestrationV2WorkActive(item.status);
97}
98
99export interface SubagentWorkflowGroup {
100 readonly workflow: RuntimeSubagent;
101 readonly phases: ReadonlyArray<{
102 readonly index: number;
103 readonly title: string;
104 readonly members: ReadonlyArray<RuntimeSubagent>;
105 readonly state: "pending" | "running" | "done";
106 readonly settledCount: number;
107 }>;
108 readonly unphasedMembers: ReadonlyArray<RuntimeSubagent>;
109}
110
111function workflowUsage(source: {
112 readonly totalTokens?: number | undefined;
113 readonly toolCalls?: number | undefined;
114 readonly durationMs?: number | undefined;
115}): SubagentUsage | null {
116 if (source.totalTokens === undefined) return null;
117 return {
118 totalTokens: source.totalTokens,
119 ...(source.toolCalls === undefined ? {} : { toolUses: source.toolCalls }),
120 ...(source.durationMs === undefined ? {} : { durationMs: source.durationMs }),
121 };
122}
123
124function isoFromEpochMillis(value: number | undefined): string | null {
125 return value === undefined ? null : DateTime.formatIso(DateTime.makeUnsafe(value));
126}
127
128function workflowMembersToRuntime(
129 coordinator: RuntimeSubagent,
130 workflow: OrchestrationV2SubagentWorkflow,
131): ReadonlyArray<RuntimeSubagent> {
132 return workflow.agents.map((agent) => {
133 const status =
134 (agent.state === "queued" || agent.state === "running") &&
135 isTerminalSubagentStatus(coordinator.status)
136 ? coordinator.status
137 : agent.state === "queued"
138 ? "pending"
139 : agent.state;
140 const failed = status === "failed";
141 const startedAt = isoFromEpochMillis(agent.startedAt);
142 const completedAt = isTerminalSubagentStatus(status)
143 ? (isoFromEpochMillis(agent.completedAt) ??
144 (agent.startedAt !== undefined && agent.durationMs !== undefined
145 ? isoFromEpochMillis(agent.startedAt + agent.durationMs)
146 : coordinator.completedAt))
147 : null;
148 return {
149 ...coordinator,
150 id: `${coordinator.id}:agent:${agent.index}`,
151 kind: "workflow_agent" as const,
152 title: agent.label,
153 model: agent.model ?? null,
154 effort: agent.effort ?? null,
155 ...(agent.speed === undefined ? {} : { speed: agent.speed }),
156 status,
157 activationCount: agent.attempt ?? 1,
158 usage: workflowUsage(agent),
159 progress: agent.prompt ?? null,
160 result: failed ? null : (agent.result ?? null),
161 error: failed ? (agent.result ?? null) : null,
162 parentAgentId: coordinator.id,
163 agentIndex: agent.index,
164 phaseIndex: agent.phaseIndex ?? null,
165 phaseTitle: agent.phaseTitle ?? null,
166 attempt: agent.attempt ?? null,
167 phases: [],
168 childThreadId: agent.childThreadId ?? null,
169 recentActivity: [],
170 firstSeenAt: isoFromEpochMillis(agent.queuedAt) ?? startedAt ?? coordinator.firstSeenAt,
171 startedAt,
172 completedAt,
173 updatedAt: completedAt ?? startedAt ?? coordinator.firstSeenAt,
174 } satisfies RuntimeSubagent;
175 });
176}
177
178export function projectedSubagentsToRuntime(
179 subagents: ReadonlyArray<{
180 readonly id: string;
181 readonly title: string | null;
182 readonly prompt: string;
183 readonly model: string | null;
184 readonly status: OrchestrationV2Subagent["status"];
185 readonly progress?: string | undefined;
186 readonly childThreadId?: string | null | undefined;
187 readonly workflow?: OrchestrationV2SubagentWorkflow | undefined;
188 readonly result: string | null;
189 readonly startedAt: DateTime.Utc | null;
190 readonly completedAt: DateTime.Utc | null;
191 readonly updatedAt: DateTime.Utc;
192 }>,
193): ReadonlyArray<RuntimeSubagent> {
194 return subagents.flatMap((subagent) => {
195 const updatedAt = DateTime.formatIso(subagent.updatedAt);
196 const startedAt = subagent.startedAt === null ? null : DateTime.formatIso(subagent.startedAt);
197 const firstSeenAt = startedAt ?? updatedAt;
198 const { workflow } = subagent;
199 const runHandles = workflow?.runHandles ?? null;
200 const coordinator = {
201 id: subagent.id,
202 kind: workflow === undefined ? "subagent" : "workflow",
203 title:
204 subagent.title ??
205 (subagent.prompt.length > 80 ? `${subagent.prompt.slice(0, 77)}...` : subagent.prompt),
206 role: null,
207 model: subagent.model,
208 effort: null,
209 status: subagent.status,
210 activationCount: 1,
211 usage: workflow === undefined ? null : workflowUsage(workflow),
212 progress: subagent.progress ?? null,
213 lastToolName: null,
214 result: subagent.result,
215 error: subagent.status === "failed" ? (subagent.result ?? null) : null,
216 outputFile: null,
217 parentAgentId: null,
218 agentIndex: null,
219 phaseIndex: null,
220 phaseTitle: null,
221 attempt: null,
222 workflowName: workflow?.name ?? null,
223 phases: workflow?.phases ?? [],
224 runHandles,
225 childThreadId: subagent.childThreadId ?? null,
226 recentActivity: [],
227 firstSeenAt,
228 startedAt,
229 completedAt: subagent.completedAt === null ? null : DateTime.formatIso(subagent.completedAt),
230 updatedAt,
231 } satisfies RuntimeSubagent;
232 return workflow === undefined
233 ? [coordinator]
234 : [coordinator, ...workflowMembersToRuntime(coordinator, workflow)];
235 });
236}
237
238export function deriveWorkflowGroups(
239 agents: ReadonlyArray<RuntimeSubagent>,
240): ReadonlyArray<SubagentWorkflowGroup> {
241 const workflows = agents
242 .filter((agent) => agent.kind === "workflow")
243 .sort((a, b) => a.firstSeenAt.localeCompare(b.firstSeenAt) || a.id.localeCompare(b.id));
244 const members = groupBy(
245 agents.filter((agent) => agent.kind !== "workflow" && agent.parentAgentId !== null),
246 (agent) => agent.parentAgentId!,
247 );
248
249 return workflows.map((workflow) => {
250 const workflowMembers = Object.hasOwn(members, workflow.id) ? members[workflow.id]! : [];
251 // Union, not either/or: the declared plan lags the members, because the
252 // provider only admits a phase once something in it starts. Members seed
253 // the map; the declared titles then overwrite whatever they guessed.
254 const phaseTitles = new Map<number, string>();
255 for (const member of workflowMembers) {
256 if (member.phaseIndex === null) continue;
257 phaseTitles.set(
258 member.phaseIndex,
259 member.phaseTitle ?? phaseTitles.get(member.phaseIndex) ?? `Phase ${member.phaseIndex + 1}`,
260 );
261 }
262 for (const phase of workflow.phases) phaseTitles.set(phase.index, phase.title);
263 const knownPhases = Array.from(phaseTitles.entries())
264 .map(([index, title]) => ({ index, title }))
265 .sort((a, b) => a.index - b.index);
266
267 const phases = knownPhases.map((phase) => {
268 const phaseMembers = workflowMembers
269 .filter((member) => member.phaseIndex === phase.index)
270 .sort((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0));
271 const hasActiveMember = phaseMembers.some(
272 // Idle members count as active for phase-liveness: a resumable Codex
273 // member has not finished the phase.
274 (member) => isActiveSubagentStatus(member.status) || member.status === "idle",
275 );
276 const settledCount = phaseMembers.filter((member) =>
277 isTerminalSubagentStatus(member.status),
278 ).length;
279 const state: "pending" | "running" | "done" =
280 phaseMembers.length === 0 ? "pending" : hasActiveMember ? "running" : "done";
281 return {
282 index: phase.index,
283 title: phase.title,
284 members: phaseMembers,
285 state,
286 settledCount,
287 };
288 });
289
290 const unphasedMembers = workflowMembers
291 .filter((member) => member.phaseIndex === null)
292 .sort((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0));
293
294 return { workflow, phases, unphasedMembers };
295 });
296}
297
298// Workflow scripts open with their `meta` export, after any leading comments.
299const WORKFLOW_SCRIPT_START = /^\s*(?:(?:\/\/[^\n]*|\/\*[\s\S]*?\*\/)\s*)*export\s+const\s+meta\b/;
300
301/**
302 * Whether a user message is the script a provider-native workflow runs. Servers mark every
303 * subagent prompt either way; only threads recorded before the mark fall back to the text.
304 */
305export function isWorkflowScriptMessage(message: {
306 readonly role: string;
307 readonly text: string;
308 readonly workflowScript?: boolean | undefined;
309}): boolean {
310 return (
311 message.role === "user" && (message.workflowScript ?? WORKFLOW_SCRIPT_START.test(message.text))
312 );
313}
314
315type ProjectedSubagent = Parameters<typeof projectedSubagentsToRuntime>[0][number] &
316 Pick<OrchestrationV2Subagent, "driver" | "providerInstanceId">;
317
318export interface WorkflowOpening {
319 readonly messageId: string;
320 readonly script: string;
321 readonly name: string | null;
322 readonly description: string | null;
323 readonly driver: OrchestrationV2Subagent["driver"] | null;
324 readonly providerInstanceId: OrchestrationV2Subagent["providerInstanceId"] | null;
325 /** Null until the parent thread's coordinator row is loaded. */
326 readonly group: SubagentWorkflowGroup | null;
327}
328
329/**
330 * The opening of a workflow coordinator's thread: its first user message is the workflow script,
331 * shown as the workflow's plan. The coordinator row lives on the parent thread, so
332 * `parentSubagents` is the parent projection's subagents, or null when it is not loaded.
333 */
334export function resolveWorkflowOpening(input: {
335 readonly thread: Pick<OrchestrationV2AppThread, "id" | "lineage" | "creationSource">;
336 readonly messages: ReadonlyArray<{
337 readonly id: string;
338 readonly role: string;
339 readonly text: string;
340 readonly workflowScript?: boolean | undefined;
341 }>;
342 readonly parentSubagents: ReadonlyArray<ProjectedSubagent> | null;
343}): WorkflowOpening | null {
344 if (!isProviderNativeSubagentThread(input.thread)) return null;
345 const first = input.messages.find((message) => message.role === "user");
346 if (first === undefined) return null;
347 const coordinator = input.parentSubagents?.find(
348 (subagent) => subagent.childThreadId === input.thread.id,
349 );
350 if (first.workflowScript === false) return null;
351 if (coordinator?.workflow === undefined && !isWorkflowScriptMessage(first)) return null;
352 return {
353 messageId: first.id,
354 script: first.text,
355 name: coordinator?.workflow?.name ?? null,
356 description: coordinator?.title ?? null,
357 driver: coordinator?.driver ?? null,
358 providerInstanceId: coordinator?.providerInstanceId ?? null,
359 group:
360 coordinator?.workflow === undefined
361 ? null
362 : (deriveWorkflowGroups(projectedSubagentsToRuntime([coordinator]))[0] ?? null),
363 };
364}
365
366/**
367 * The parent thread whose subagent rows describe this thread's workflow, or null when the thread
368 * does not open with a workflow script. Gates loading the parent so ordinary subagent threads
369 * never subscribe to their parent's detail.
370 */
371export function workflowOpeningParentThreadId(input: {
372 readonly thread: Pick<OrchestrationV2AppThread, "lineage" | "creationSource">;
373 readonly messages: ReadonlyArray<Parameters<typeof isWorkflowScriptMessage>[0]>;
374}): OrchestrationV2AppThread["id"] | null {
375 if (!isProviderNativeSubagentThread(input.thread)) return null;
376 const first = input.messages.find((message) => message.role === "user");
377 return first !== undefined && isWorkflowScriptMessage(first)
378 ? input.thread.lineage.parentThreadId
379 : null;
380}
381
382/** The opening block's heading: the workflow, what it does, and how its agents stand. */
383export function workflowOpeningHeadline(opening: WorkflowOpening): {
384 readonly title: string;
385 readonly description: string | null;
386 readonly agents: string | null;
387} {
388 const title = opening.name ?? opening.description ?? "Workflow";
389 const members =
390 opening.group === null
391 ? []
392 : [
393 ...opening.group.phases.flatMap((phase) => phase.members),
394 ...opening.group.unphasedMembers,
395 ];
396 const counts = new Map<string, number>();
397 for (const member of members) {
398 const key = isTerminalSubagentStatus(member.status)
399 ? member.status === "completed"
400 ? "done"
401 : member.status === "failed"
402 ? "failed"
403 : "stopped"
404 : "working";
405 counts.set(key, (counts.get(key) ?? 0) + 1);
406 }
407 const agents =
408 members.length === 0
409 ? null
410 : `${members.length} ${members.length === 1 ? "agent" : "agents"} · ${[
411 "working",
412 "done",
413 "failed",
414 "stopped",
415 ]
416 .filter((key) => counts.has(key))
417 .map((key) => `${counts.get(key)} ${key}`)
418 .join(" · ")}`;
419 return {
420 title,
421 description:
422 opening.description !== null && opening.description !== title ? opening.description : null,
423 agents,
424 };
425}