The best way to control Claude Code, Codex and more from any computer or phone

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