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