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

claudeWorkflowProgress.ts

190 lines7.4 KB

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;
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;
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;
36​
37function preview(value: unknown): string | undefined {
38 return typeof value === "string" && value.length > 0 ? value : undefined;
40​
41function optional<T>(key: string, value: T | undefined): Record<string, T> {
42 return value === undefined ? {} : ({ [key]: value } as Record<string, T>);
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 };
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 };
84​
85/**
86 * A background launch answers the model with an acknowledgement rather than the run's output, and
87 * that acknowledgement is the only place the run's filesystem handles appear — nothing later on
88 * the event stream repeats them.
89 */
90export function parseClaudeWorkflowRunHandles(
91 toolUseResult: unknown,
92): OrchestrationV2WorkflowRunHandles | undefined {
93 if (text(field(toolUseResult, "taskType")) !== CLAUDE_WORKFLOW_TASK_TYPE) return undefined;
94 const handles = {
95 ...optional("runId", text(field(toolUseResult, "runId"))),
96 ...optional("transcriptDir", text(field(toolUseResult, "transcriptDir"))),
97 ...optional("scriptPath", text(field(toolUseResult, "scriptPath"))),
98 };
99 return Object.keys(handles).length === 0 ? undefined : handles;
101​
102function parseClaudeWorkflowProgress(message: unknown): {
103 readonly phases: ReadonlyArray<OrchestrationV2WorkflowPhase>;
104 readonly agents: ReadonlyArray<OrchestrationV2WorkflowAgent>;
105} | null {
106 if (!hasClaudeWorkflowSnapshot(message)) return null;
107 const phases: OrchestrationV2WorkflowPhase[] = [];
108 const agents: OrchestrationV2WorkflowAgent[] = [];
109 for (const entry of message.workflow_progress) {
110 const type = text(field(entry, "type"));
111 if (type === "workflow_phase") {
112 const phase = parsePhase(entry);
113 if (phase !== null) phases.push(phase);
114 } else if (type === "workflow_agent") {
115 const agent = parseAgent(entry);
116 if (agent !== null) agents.push(agent);
117 }
118 }
119 return phases.length === 0 && agents.length === 0 ? null : { phases, agents };
121​
122/**
123 * Returns undefined when nothing identifies the task as a workflow. Progress frames do not repeat
124 * `task_type`, so this is the single place that decides whether a task is a coordinator; without
125 * it every ordinary subagent's usage frame would mint an empty workflow and render as a
126 * coordinator.
127 */
128export function mergeClaudeWorkflowProgress(input: {
129 readonly previous: OrchestrationV2SubagentWorkflow | undefined;
130 readonly name?: string | undefined;
131 readonly runHandles?: OrchestrationV2WorkflowRunHandles | undefined;
132 readonly message: unknown;
133}): OrchestrationV2SubagentWorkflow | undefined {
134 const { previous } = input;
135 const snapshot = parseClaudeWorkflowProgress(input.message);
136 if (
137 previous === undefined &&
138 input.name === undefined &&
139 input.runHandles === undefined &&
140 snapshot === null
141 ) {
142 return undefined;
143 }
144 const reported = field(input.message, "usage");
145 const phasesByIndex = new Map(
146 (previous?.phases ?? []).map((phase) => [phase.index, phase] as const),
147 );
148 for (const phase of snapshot?.phases ?? []) phasesByIndex.set(phase.index, phase);
149 const agentsByIndex = new Map(
150 (previous?.agents ?? []).map((agent) => [agent.index, agent] as const),
151 );
152 for (const agent of snapshot?.agents ?? []) {
153 const prior = agentsByIndex.get(agent.index);
154 const attempt = agent.attempt ?? prior?.attempt ?? 1;
155 if (prior !== undefined && attempt < (prior.attempt ?? 1)) continue;
156 const restarted = prior !== undefined && attempt > (prior.attempt ?? 1);
157 const regressed =
158 !restarted &&
159 (((prior?.state === "completed" || prior?.state === "failed") &&
160 agent.state !== prior.state) ||
161 (prior?.state === "running" && agent.state === "queued"));
162 agentsByIndex.set(
163 agent.index,
164 regressed
165 ? { ...agent, ...prior }
166 : {
167 ...(restarted
168 ? {
169 ...optional("phaseIndex", prior.phaseIndex),
170 ...optional("phaseTitle", prior.phaseTitle),
171 }
172 : prior),
173 ...agent,
174 },
175 );
176 }
177 const runHandles =
178 input.runHandles === undefined
179 ? previous?.runHandles
180 : { ...previous?.runHandles, ...input.runHandles };
181 return {
182 ...optional("name", input.name ?? previous?.name),
183 ...optional("runHandles", runHandles),
184 phases: Array.from(phasesByIndex.values()).sort((left, right) => left.index - right.index),
185 agents: Array.from(agentsByIndex.values()).sort((left, right) => left.index - right.index),
186 ...optional("totalTokens", count(field(reported, "total_tokens")) ?? previous?.totalTokens),
187 ...optional("toolCalls", count(field(reported, "tool_uses")) ?? previous?.toolCalls),
188 ...optional("durationMs", count(field(reported, "duration_ms")) ?? previous?.durationMs),
189 };