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

subagentRuntime.ts

487 lines17.0 KB

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