Open History to see the last commit
1import type {
2 OrchestrationV2SubagentWorkflow,
3 OrchestrationV2WorkflowAgent,
4 OrchestrationV2WorkflowPhase,
5 OrchestrationV2WorkflowRunHandles,
6} from "@t3tools/contracts";
7
8import { field, text } from "../unknownField.ts";
9
10export const CLAUDE_WORKFLOW_TASK_TYPE = "local_workflow";
11
12export function hasClaudeWorkflowSnapshot(
13 message: unknown,
14): message is { readonly workflow_progress: ReadonlyArray<unknown> } {
15 const entries = field(message, "workflow_progress");
16 return Array.isArray(entries) && entries.length > 0;
17}
18
19const AGENT_STATES: Record<string, OrchestrationV2WorkflowAgent["state"] | undefined> = {
20 queued: "queued",
21 start: "running",
22 done: "completed",
23 error: "failed",
24};
25
26function count(value: unknown): number | undefined {
27 return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
28}
29
30function timestamp(value: unknown): number | undefined {
31 const milliseconds = count(value);
32 return milliseconds !== undefined && milliseconds <= 8_640_000_000_000_000
33 ? milliseconds
34 : undefined;
35}
36
37function preview(value: unknown): string | undefined {
38 return typeof value === "string" && value.length > 0 ? value : undefined;
39}
40
41function optional<T>(key: string, value: T | undefined): Record<string, T> {
42 return value === undefined ? {} : ({ [key]: value } as Record<string, T>);
43}
44
45function parsePhase(entry: unknown): OrchestrationV2WorkflowPhase | null {
46 const index = count(field(entry, "index"));
47 const title = text(field(entry, "title"));
48 return index === undefined || title === undefined ? null : { index, title };
49}
50
51function parseAgent(entry: unknown): OrchestrationV2WorkflowAgent | null {
52 const index = count(field(entry, "index"));
53 const label = text(field(entry, "label"));
54 if (index === undefined || label === undefined) return null;
55 const reportedState = text(field(entry, "state")) ?? "";
56 const state = Object.hasOwn(AGENT_STATES, reportedState)
57 ? (AGENT_STATES[reportedState] ?? "running")
58 : "running";
59 return {
60 index,
61 label,
62 state,
63 ...optional("agentId", text(field(entry, "agentId"))),
64 ...optional("phaseIndex", count(field(entry, "phaseIndex"))),
65 ...optional("phaseTitle", text(field(entry, "phaseTitle"))),
66 ...optional("model", text(field(entry, "model"))),
67 ...optional("attempt", count(field(entry, "attempt"))),
68 ...optional("totalTokens", count(field(entry, "tokens"))),
69 ...optional("toolCalls", count(field(entry, "toolCalls"))),
70 ...optional("durationMs", count(field(entry, "durationMs"))),
71 ...optional("queuedAt", timestamp(field(entry, "queuedAt"))),
72 ...optional("startedAt", timestamp(field(entry, "startedAt"))),
73 // Execution duration excludes startup waits; terminal progress carries the end instant.
74 ...optional(
75 "completedAt",
76 state === "completed" || state === "failed"
77 ? timestamp(field(entry, "lastProgressAt"))
78 : undefined,
79 ),
80 ...optional("prompt", preview(field(entry, "promptPreview"))),
81 ...optional("result", preview(field(entry, "resultPreview"))),
82 };
83}
84
85/** The background-launch ACK is the only frame carrying the run's filesystem handles. */
86export function parseClaudeWorkflowRunHandles(
87 toolUseResult: unknown,
88): OrchestrationV2WorkflowRunHandles | undefined {
89 if (text(field(toolUseResult, "taskType")) !== CLAUDE_WORKFLOW_TASK_TYPE) return undefined;
90 const handles = {
91 ...optional("runId", text(field(toolUseResult, "runId"))),
92 ...optional("transcriptDir", text(field(toolUseResult, "transcriptDir"))),
93 ...optional("scriptPath", text(field(toolUseResult, "scriptPath"))),
94 };
95 return Object.keys(handles).length === 0 ? undefined : handles;
96}
97
98function parseClaudeWorkflowProgress(message: unknown): {
99 readonly phases: ReadonlyArray<OrchestrationV2WorkflowPhase>;
100 readonly agents: ReadonlyArray<OrchestrationV2WorkflowAgent>;
101} | null {
102 if (!hasClaudeWorkflowSnapshot(message)) return null;
103 const phases: OrchestrationV2WorkflowPhase[] = [];
104 const agents: OrchestrationV2WorkflowAgent[] = [];
105 for (const entry of message.workflow_progress) {
106 const type = text(field(entry, "type"));
107 if (type === "workflow_phase") {
108 const phase = parsePhase(entry);
109 if (phase !== null) phases.push(phase);
110 } else if (type === "workflow_agent") {
111 const agent = parseAgent(entry);
112 if (agent !== null) agents.push(agent);
113 }
114 }
115 return phases.length === 0 && agents.length === 0 ? null : { phases, agents };
116}
117
118/** Returns undefined without workflow evidence; progress frames omit task_type and ordinary subagents also emit usage. */
119export function mergeClaudeWorkflowProgress(input: {
120 readonly previous: OrchestrationV2SubagentWorkflow | undefined;
121 readonly name?: string | undefined;
122 readonly runHandles?: OrchestrationV2WorkflowRunHandles | undefined;
123 readonly message: unknown;
124}): OrchestrationV2SubagentWorkflow | undefined {
125 const { previous } = input;
126 const snapshot = parseClaudeWorkflowProgress(input.message);
127 if (
128 previous === undefined &&
129 input.name === undefined &&
130 input.runHandles === undefined &&
131 snapshot === null
132 ) {
133 return undefined;
134 }
135 const reported = field(input.message, "usage");
136 const phasesByIndex = new Map(
137 (previous?.phases ?? []).map((phase) => [phase.index, phase] as const),
138 );
139 for (const phase of snapshot?.phases ?? []) phasesByIndex.set(phase.index, phase);
140 const agentsByIndex = new Map(
141 (previous?.agents ?? []).map((agent) => [agent.index, agent] as const),
142 );
143 for (const agent of snapshot?.agents ?? []) {
144 const prior = agentsByIndex.get(agent.index);
145 const attempt = agent.attempt ?? prior?.attempt ?? 1;
146 if (prior !== undefined && attempt < (prior.attempt ?? 1)) continue;
147 const restarted = prior !== undefined && attempt > (prior.attempt ?? 1);
148 const regressed =
149 !restarted &&
150 (((prior?.state === "completed" || prior?.state === "failed") &&
151 agent.state !== prior.state) ||
152 (prior?.state === "running" && agent.state === "queued"));
153 agentsByIndex.set(
154 agent.index,
155 regressed
156 ? { ...agent, ...prior }
157 : {
158 ...(restarted
159 ? {
160 ...optional("phaseIndex", prior.phaseIndex),
161 ...optional("phaseTitle", prior.phaseTitle),
162 }
163 : prior),
164 ...agent,
165 },
166 );
167 }
168 const runHandles =
169 input.runHandles === undefined
170 ? previous?.runHandles
171 : { ...previous?.runHandles, ...input.runHandles };
172 return {
173 ...optional("name", input.name ?? previous?.name),
174 ...optional("runHandles", runHandles),
175 phases: Array.from(phasesByIndex.values()).sort((left, right) => left.index - right.index),
176 agents: Array.from(agentsByIndex.values()).sort((left, right) => left.index - right.index),
177 ...optional("totalTokens", count(field(reported, "total_tokens")) ?? previous?.totalTokens),
178 ...optional("toolCalls", count(field(reported, "tool_uses")) ?? previous?.toolCalls),
179 ...optional("durationMs", count(field(reported, "duration_ms")) ?? previous?.durationMs),
180 };
181}