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