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

subagentRuntime.ts

421 lines14.9 KB

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