@timmyjl12/pi-subagents 0.0.0-stage → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/CHANGELOG.md +862 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1125 -3
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +40 -0
  9. package/dist/active-agents-prompt.js +98 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +131 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +872 -0
  17. package/dist/agent-manager.js +2910 -0
  18. package/dist/agent-runner.d.ts +358 -0
  19. package/dist/agent-runner.js +1219 -0
  20. package/dist/agent-types.d.ts +142 -0
  21. package/dist/agent-types.js +315 -0
  22. package/dist/awaited-result.d.ts +37 -0
  23. package/dist/awaited-result.js +150 -0
  24. package/dist/child-context.d.ts +15 -0
  25. package/dist/child-context.js +181 -0
  26. package/dist/child-session-shutdown.d.ts +21 -0
  27. package/dist/child-session-shutdown.js +97 -0
  28. package/dist/cleanup-plans.d.ts +10 -0
  29. package/dist/cleanup-plans.js +112 -0
  30. package/dist/context.d.ts +12 -0
  31. package/dist/context.js +56 -0
  32. package/dist/cross-extension-rpc.d.ts +73 -0
  33. package/dist/cross-extension-rpc.js +192 -0
  34. package/dist/custom-agents.d.ts +79 -0
  35. package/dist/custom-agents.js +583 -0
  36. package/dist/default-agents.d.ts +7 -0
  37. package/dist/default-agents.js +125 -0
  38. package/dist/enabled-models.d.ts +49 -0
  39. package/dist/enabled-models.js +145 -0
  40. package/dist/env.d.ts +6 -0
  41. package/dist/env.js +28 -0
  42. package/dist/error-log.d.ts +64 -0
  43. package/dist/error-log.js +176 -0
  44. package/dist/force-main-model.d.ts +21 -0
  45. package/dist/force-main-model.js +28 -0
  46. package/dist/goal-bridge.d.ts +155 -0
  47. package/dist/goal-bridge.js +305 -0
  48. package/dist/group-join.d.ts +36 -0
  49. package/dist/group-join.js +161 -0
  50. package/dist/index.d.ts +52 -0
  51. package/dist/index.js +6390 -0
  52. package/dist/invocation-config.d.ts +164 -0
  53. package/dist/invocation-config.js +158 -0
  54. package/dist/memory.d.ts +53 -0
  55. package/dist/memory.js +165 -0
  56. package/dist/mention-clone.d.ts +87 -0
  57. package/dist/mention-clone.js +178 -0
  58. package/dist/mention.d.ts +81 -0
  59. package/dist/mention.js +131 -0
  60. package/dist/model-resolver.d.ts +36 -0
  61. package/dist/model-resolver.js +95 -0
  62. package/dist/model-scope.d.ts +49 -0
  63. package/dist/model-scope.js +48 -0
  64. package/dist/nested-tools.d.ts +76 -0
  65. package/dist/nested-tools.js +393 -0
  66. package/dist/output-diagnostics.d.ts +11 -0
  67. package/dist/output-diagnostics.js +64 -0
  68. package/dist/output-file.d.ts +64 -0
  69. package/dist/output-file.js +351 -0
  70. package/dist/prompts.d.ts +61 -0
  71. package/dist/prompts.js +94 -0
  72. package/dist/recovery.d.ts +56 -0
  73. package/dist/recovery.js +341 -0
  74. package/dist/report-cleanup.d.ts +204 -0
  75. package/dist/report-cleanup.js +1632 -0
  76. package/dist/report-store.d.ts +738 -0
  77. package/dist/report-store.js +3612 -0
  78. package/dist/schedule-store.d.ts +52 -0
  79. package/dist/schedule-store.js +240 -0
  80. package/dist/schedule.d.ts +121 -0
  81. package/dist/schedule.js +420 -0
  82. package/dist/settings.d.ts +388 -0
  83. package/dist/settings.js +268 -0
  84. package/dist/skill-loader.d.ts +24 -0
  85. package/dist/skill-loader.js +93 -0
  86. package/dist/standalone-fallback.d.ts +30 -0
  87. package/dist/standalone-fallback.js +239 -0
  88. package/dist/status-note.d.ts +61 -0
  89. package/dist/status-note.js +85 -0
  90. package/dist/structured-output.d.ts +61 -0
  91. package/dist/structured-output.js +112 -0
  92. package/dist/terminal-progress.d.ts +115 -0
  93. package/dist/terminal-progress.js +206 -0
  94. package/dist/types.d.ts +411 -0
  95. package/dist/types.js +5 -0
  96. package/dist/ui/agent-mention.d.ts +82 -0
  97. package/dist/ui/agent-mention.js +187 -0
  98. package/dist/ui/agent-widget.d.ts +304 -0
  99. package/dist/ui/agent-widget.js +770 -0
  100. package/dist/ui/cleanup-preview.d.ts +59 -0
  101. package/dist/ui/cleanup-preview.js +466 -0
  102. package/dist/ui/conversation-viewer.d.ts +105 -0
  103. package/dist/ui/conversation-viewer.js +544 -0
  104. package/dist/ui/fleet-list.d.ts +183 -0
  105. package/dist/ui/fleet-list.js +494 -0
  106. package/dist/ui/fleet-overlay.d.ts +203 -0
  107. package/dist/ui/fleet-overlay.js +887 -0
  108. package/dist/ui/hub-feed.d.ts +52 -0
  109. package/dist/ui/hub-feed.js +148 -0
  110. package/dist/ui/native-transcript.d.ts +33 -0
  111. package/dist/ui/native-transcript.js +234 -0
  112. package/dist/ui/schedule-menu.d.ts +16 -0
  113. package/dist/ui/schedule-menu.js +94 -0
  114. package/dist/ui/select-item.d.ts +27 -0
  115. package/dist/ui/select-item.js +34 -0
  116. package/dist/ui/tool-progress.d.ts +22 -0
  117. package/dist/ui/tool-progress.js +56 -0
  118. package/dist/ui/viewer-keys.d.ts +20 -0
  119. package/dist/ui/viewer-keys.js +17 -0
  120. package/dist/ui/workflow-card.d.ts +175 -0
  121. package/dist/ui/workflow-card.js +332 -0
  122. package/dist/ui/workflow-dialog.d.ts +305 -0
  123. package/dist/ui/workflow-dialog.js +848 -0
  124. package/dist/ui/workflow-menu.d.ts +60 -0
  125. package/dist/ui/workflow-menu.js +147 -0
  126. package/dist/usage.d.ts +147 -0
  127. package/dist/usage.js +147 -0
  128. package/dist/workflow/collisions.d.ts +95 -0
  129. package/dist/workflow/collisions.js +88 -0
  130. package/dist/workflow/entry.d.ts +32 -0
  131. package/dist/workflow/entry.js +29 -0
  132. package/dist/workflow/host.d.ts +65 -0
  133. package/dist/workflow/host.js +477 -0
  134. package/dist/workflow/journal.d.ts +113 -0
  135. package/dist/workflow/journal.js +177 -0
  136. package/dist/workflow/json-schema.d.ts +51 -0
  137. package/dist/workflow/json-schema.js +111 -0
  138. package/dist/workflow/meta.d.ts +67 -0
  139. package/dist/workflow/meta.js +317 -0
  140. package/dist/workflow/progress.d.ts +224 -0
  141. package/dist/workflow/progress.js +361 -0
  142. package/dist/workflow/runtime.d.ts +373 -0
  143. package/dist/workflow/runtime.js +919 -0
  144. package/dist/workflow/saved.d.ts +90 -0
  145. package/dist/workflow/saved.js +203 -0
  146. package/dist/workflow/task.d.ts +145 -0
  147. package/dist/workflow/task.js +213 -0
  148. package/dist/workflow/tool-description.d.ts +43 -0
  149. package/dist/workflow/tool-description.js +204 -0
  150. package/dist/workflow/worker-source.d.ts +47 -0
  151. package/dist/workflow/worker-source.js +778 -0
  152. package/dist/worktree.d.ts +52 -0
  153. package/dist/worktree.js +164 -0
  154. package/dist/xml.d.ts +10 -0
  155. package/dist/xml.js +12 -0
  156. package/docs/DEVELOPMENT.md +40 -0
  157. package/docs/artifacts.md +93 -0
  158. package/docs/recovery.md +62 -0
  159. package/docs/rpc.md +252 -0
  160. package/docs/runtime-performance.md +53 -0
  161. package/docs/workflows.md +467 -0
  162. package/examples/agent-tool-description.md +43 -0
  163. package/examples/workflows/compose.js +51 -0
  164. package/examples/workflows/fan-out-audit.js +47 -0
  165. package/examples/workflows/gated-fix.js +60 -0
  166. package/examples/workflows/lib/count-child.js +27 -0
  167. package/examples/workflows/review-panel.js +66 -0
  168. package/examples/workflows/structured-findings.js +78 -0
  169. package/package.json +75 -6
  170. package/src/abortable.ts +43 -0
  171. package/src/active-agents-prompt.ts +115 -0
  172. package/src/advisor-status.ts +74 -0
  173. package/src/agent-color.ts +169 -0
  174. package/src/agent-file-toggle.ts +273 -0
  175. package/src/agent-manager.ts +3312 -0
  176. package/src/agent-runner.ts +1500 -0
  177. package/src/agent-types.ts +390 -0
  178. package/src/awaited-result.ts +187 -0
  179. package/src/child-context.ts +173 -0
  180. package/src/child-session-shutdown.ts +114 -0
  181. package/src/cleanup-plans.ts +112 -0
  182. package/src/context.ts +58 -0
  183. package/src/cross-extension-rpc.ts +257 -0
  184. package/src/custom-agents.ts +689 -0
  185. package/src/default-agents.ts +129 -0
  186. package/src/enabled-models.ts +180 -0
  187. package/src/env.ts +33 -0
  188. package/src/error-log.ts +202 -0
  189. package/src/force-main-model.ts +29 -0
  190. package/src/goal-bridge.ts +468 -0
  191. package/src/group-join.ts +188 -0
  192. package/src/index.ts +6856 -0
  193. package/src/invocation-config.ts +276 -0
  194. package/src/memory.ts +179 -0
  195. package/src/mention-clone.ts +221 -0
  196. package/src/mention.ts +141 -0
  197. package/src/model-resolver.ts +118 -0
  198. package/src/model-scope.ts +70 -0
  199. package/src/nested-tools.ts +553 -0
  200. package/src/output-diagnostics.ts +68 -0
  201. package/src/output-file.ts +380 -0
  202. package/src/prompts.ts +151 -0
  203. package/src/recovery.ts +320 -0
  204. package/src/report-cleanup.ts +2044 -0
  205. package/src/report-store.ts +4130 -0
  206. package/src/schedule-store.ts +244 -0
  207. package/src/schedule.ts +450 -0
  208. package/src/settings.ts +632 -0
  209. package/src/skill-loader.ts +102 -0
  210. package/src/standalone-fallback.ts +195 -0
  211. package/src/status-note.ts +90 -0
  212. package/src/structured-output.ts +130 -0
  213. package/src/terminal-progress.ts +215 -0
  214. package/src/types.ts +424 -0
  215. package/src/ui/agent-mention.ts +216 -0
  216. package/src/ui/agent-widget.ts +866 -0
  217. package/src/ui/cleanup-preview.ts +518 -0
  218. package/src/ui/conversation-viewer.ts +527 -0
  219. package/src/ui/fleet-list.ts +563 -0
  220. package/src/ui/fleet-overlay.ts +1048 -0
  221. package/src/ui/hub-feed.ts +179 -0
  222. package/src/ui/native-transcript.ts +224 -0
  223. package/src/ui/schedule-menu.ts +105 -0
  224. package/src/ui/select-item.ts +45 -0
  225. package/src/ui/tool-progress.ts +67 -0
  226. package/src/ui/viewer-keys.ts +39 -0
  227. package/src/ui/workflow-card.ts +470 -0
  228. package/src/ui/workflow-dialog.ts +1119 -0
  229. package/src/ui/workflow-menu.ts +193 -0
  230. package/src/usage.ts +217 -0
  231. package/src/workflow/collisions.ts +123 -0
  232. package/src/workflow/entry.ts +47 -0
  233. package/src/workflow/host.ts +524 -0
  234. package/src/workflow/journal.ts +221 -0
  235. package/src/workflow/json-schema.ts +128 -0
  236. package/src/workflow/meta.ts +325 -0
  237. package/src/workflow/progress.ts +550 -0
  238. package/src/workflow/runtime.ts +1342 -0
  239. package/src/workflow/saved.ts +217 -0
  240. package/src/workflow/task.ts +313 -0
  241. package/src/workflow/tool-description.ts +205 -0
  242. package/src/workflow/worker-source.ts +781 -0
  243. package/src/worktree.ts +205 -0
  244. package/src/xml.ts +13 -0
@@ -0,0 +1,1342 @@
1
+ /**
2
+ * runtime.ts — the host half of a workflow run.
3
+ *
4
+ * Owns the worker lifecycle, the RPC bridge, the concurrency semaphore, the
5
+ * per-run caps, and the progress log. The script's only route to an agent is a
6
+ * `call` message landing here, which is what makes the caps and the abort story
7
+ * enforceable at all: a script cannot go around them because it has nothing to
8
+ * go around them *with*.
9
+ *
10
+ * Spawning is injected rather than imported. `AgentManager` is a large, stateful
11
+ * dependency and wiring it in directly would make every test here an integration
12
+ * test; a {@link WorkflowHost} stub is a dozen lines. The adapter that binds this
13
+ * to the real manager lives at the call site.
14
+ */
15
+
16
+ import { cpus } from "node:os";
17
+ import { Worker } from "node:worker_threads";
18
+ import { type JournalKeyInput, journalKey, type WorkflowJournalEntry } from "./journal.ts";
19
+ import { type CompiledSchema, compileJsonSchema } from "./json-schema.ts";
20
+ import { extractMeta, type WorkflowMeta } from "./meta.ts";
21
+ import type { WorkflowAgentEntry, WorkflowEntry } from "./progress.ts";
22
+ import { WORKER_SOURCE } from "./worker-source.ts";
23
+
24
+ /** Matches the `script` field's `maxLength` in the tool schema. */
25
+ export const MAX_SCRIPT_LENGTH = 524_288;
26
+
27
+ /** Economical workflow role; explicit run and per-call roles take precedence. */
28
+ export const DEFAULT_WORKFLOW_AGENT_TYPE = "task";
29
+
30
+ /** Agents one run may schedule, in total. */
31
+ export const WORKFLOW_AGENT_CAP = 1000;
32
+
33
+ /** Items one `parallel()` or `pipeline()` call may take. */
34
+ export const WORKFLOW_ITEM_CAP = 4096;
35
+
36
+ /** Nested `workflow()` invocations allowed per run. */
37
+ export const WORKFLOW_NESTED_CAP = 256;
38
+
39
+ /** How much of a prompt or result is kept for the UI. */
40
+ const PREVIEW_LENGTH = 200;
41
+
42
+ export class WorkflowRuntimeError extends Error {}
43
+
44
+ /**
45
+ * Concurrent agents allowed, leaving two cores for the host and the TUI.
46
+ *
47
+ * `Math.max(1, …)` is not decoration: the raw `min(16, cpus - 2)` is 0 on a one-
48
+ * or two-core machine, and a semaphore with zero permits never hands out a slot,
49
+ * so the run would hang before its first agent rather than fail.
50
+ */
51
+ export function workflowConcurrency(cpuCount: number = cpus().length): number {
52
+ return Math.max(1, Math.min(16, cpuCount - 2));
53
+ }
54
+
55
+ /** One agent the script asked for. `agentId` is the handle for {@link WorkflowHost.abortAgent}. */
56
+ export interface WorkflowSpawnRequest {
57
+ agentId: string;
58
+ /** Position in the run, and the progress entry's stable identity. */
59
+ index: number;
60
+ prompt: string;
61
+ label: string;
62
+ agentType: string;
63
+ /**
64
+ * True when the call's opts.agentType or the run's agentType selected a role.
65
+ * A setting-derived default is not explicit, and a configured generic
66
+ * fallback must not turn that default into an authorized premium request.
67
+ */
68
+ agentTypeExplicit?: boolean;
69
+ model?: string;
70
+ /**
71
+ * Reasoning effort for this child, as one of pi's thinking levels.
72
+ *
73
+ * Typed as a plain string because this interface is the host boundary and
74
+ * deliberately knows nothing about pi — `host.ts` is where it becomes a
75
+ * `ThinkingLevel`. The worker has already rejected anything off the list.
76
+ */
77
+ effort?: string;
78
+ isolation?: "worktree";
79
+ /**
80
+ * Called by the host once the child's EFFECTIVE configuration is known —
81
+ * which is when its session exists, not when the spawn resolves.
82
+ *
83
+ * Without it a row could only ever show what the script asked for: a fuzzy
84
+ * `model: "haiku"` stays `haiku` instead of the id it resolved to, an
85
+ * `agent()` that named no model shows nothing at all, and a level pi clamped
86
+ * is presented as the level that was requested (#168, #182).
87
+ *
88
+ * Plain strings, like `effort` above: this interface is the host boundary and
89
+ * deliberately knows nothing about pi's `AgentInvocation`. Optional, so a host
90
+ * that cannot report any of this simply does not, and the row keeps the
91
+ * requested values it started with.
92
+ */
93
+ onResolved?(info: {
94
+ /**
95
+ * The host's own id for the child — the manager's `AgentRecord` id here.
96
+ *
97
+ * Reported as soon as the host has one, which is earlier than the rest of
98
+ * this: the model is knowable only once a session exists, but the id is
99
+ * what lets a reader open that child's conversation, and a child that
100
+ * never got a model is exactly the one worth opening.
101
+ */
102
+ recordId?: string;
103
+ modelName?: string;
104
+ modelId?: string;
105
+ thinking?: string;
106
+ requestedThinking?: string;
107
+ requestedModel?: string;
108
+ }): void;
109
+ /**
110
+ * Compiled from the script's `agent({ schema })`.
111
+ *
112
+ * The host must give the child a `StructuredOutput` tool built from it and
113
+ * return the validated payload as JSON text. Compiled rather than raw so the
114
+ * runtime can re-check the answer without re-parsing the schema per call.
115
+ */
116
+ schema?: CompiledSchema;
117
+ phaseIndex?: number;
118
+ phaseTitle?: string;
119
+ /**
120
+ * The `gate` command this agent is being spawned under, when it has one.
121
+ *
122
+ * Passed down rather than run purely from here because an isolated child's
123
+ * worktree is destroyed as part of its own settle: a host that can reach
124
+ * inside that settle runs the gate there, against the tree the child wrote,
125
+ * and reports the outcome back as {@link WorkflowSpawnResult.gate}. A host
126
+ * that ignores this leaves the gate to {@link applyGate}, which then runs it
127
+ * itself — so exactly one execution either way.
128
+ */
129
+ gate?: string;
130
+ }
131
+
132
+ export interface WorkflowSpawnResult {
133
+ ok: boolean;
134
+ /** The agent's answer. Present when `ok`. */
135
+ text?: string;
136
+ /** Why it failed. Present when not `ok`. */
137
+ error?: string;
138
+ /** Configuration failures must not be swallowed as a null pipeline item. */
139
+ fatal?: boolean;
140
+ /** The user dismissed it rather than it failing; renders as skipped. */
141
+ skipped?: boolean;
142
+ tokens?: number;
143
+ /**
144
+ * Output tokens only, for the script's `budget.spent()`.
145
+ *
146
+ * Separate from {@link tokens}, which is the lifetime total. Claude Code's
147
+ * budget counts output, and a fan-out's re-sent input would swamp it.
148
+ */
149
+ outputTokens?: number;
150
+ /** Whether the child needed an extra prompt to produce its structured answer. */
151
+ structuredRetried?: boolean;
152
+ toolCalls?: number;
153
+ /**
154
+ * Where the child actually ran.
155
+ *
156
+ * Only meaningful for `isolation: "worktree"`, and the whole reason it exists:
157
+ * a gate has to run against the tree the child edited, not the main one, or it
158
+ * verifies the wrong working copy. Left unset, a gate runs wherever the host
159
+ * runs commands by default.
160
+ *
161
+ * Usually unset for a worktree child even so: the copy is removed during the
162
+ * child's own settle, so it no longer exists by the time this is read. That
163
+ * is what {@link gate} is for.
164
+ */
165
+ cwd?: string;
166
+ /**
167
+ * The outcome of this agent's `gate`, when the host already ran it.
168
+ *
169
+ * Set only by a host that ran the command itself — inside the child's
170
+ * worktree, while that directory still existed. Its presence is what tells
171
+ * {@link applyGate} the command has already been executed; the pass/fail
172
+ * decision and the error shaping still happen there, in one place.
173
+ */
174
+ gate?: WorkflowGateResult;
175
+ }
176
+
177
+ /** Outcome of a `gate` command. `output` is what the user is shown when it fails. */
178
+ export interface WorkflowGateResult {
179
+ ok: boolean;
180
+ /** Combined stdout/stderr, or whatever the host wants surfaced as the failure. */
181
+ output: string;
182
+ }
183
+
184
+ /** The one seam between a workflow and the rest of the extension. */
185
+ /** How a script names another workflow: a saved name, or a path to a file. */
186
+ export interface WorkflowScriptRef {
187
+ name?: string;
188
+ scriptPath?: string;
189
+ }
190
+
191
+ export type WorkflowScriptSource =
192
+ | { ok: true; script: string; path?: string }
193
+ | { ok: false; message: string };
194
+
195
+ export interface WorkflowHost {
196
+ spawnAgent(request: WorkflowSpawnRequest): Promise<WorkflowSpawnResult>;
197
+ /** Called for every in-flight agent when the run aborts. */
198
+ abortAgent(agentId: string): void;
199
+ /**
200
+ * Continue a child that already ran in this run, keeping its context.
201
+ *
202
+ * `agentId` is one previously handed out in a {@link WorkflowSpawnRequest};
203
+ * the child keeps the agent type, model and tool contract it started with, so
204
+ * only the follow-up prompt crosses.
205
+ *
206
+ * Optional: a host without it rejects `resume` rather than quietly starting a
207
+ * fresh child that has none of the context the script is counting on.
208
+ */
209
+ resumeAgent?(
210
+ agentId: string,
211
+ prompt: string,
212
+ /**
213
+ * Same reporter {@link WorkflowSpawnRequest.onResolved} carries, for the
214
+ * same reason: a resumed row is rebuilt from scratch, so without it the
215
+ * continuation of a child would show the model the script *asked* for while
216
+ * the row above it shows the one that ran.
217
+ */
218
+ onResolved?: WorkflowSpawnRequest["onResolved"],
219
+ ): Promise<WorkflowSpawnResult>;
220
+ /**
221
+ * Run a `gate` command and report whether it passed.
222
+ *
223
+ * `cwd` is the child's worktree when it had one. Optional for the same reason
224
+ * as {@link resumeAgent}, and more sharply: a gate that silently does not run
225
+ * would mark unverified work as verified, so the runtime fails the call
226
+ * instead of skipping it.
227
+ */
228
+ runGate?(command: string, options: { agentId: string; cwd?: string }): Promise<WorkflowGateResult>;
229
+ /**
230
+ * Resolve a nested `workflow()` reference to source.
231
+ *
232
+ * The runtime knows nothing about the filesystem or about pi, so it asks. It
233
+ * still decides whether what comes back *is* a workflow — see
234
+ * {@link validateScript} — because those rules belong with the runtime that
235
+ * enforces them everywhere else.
236
+ *
237
+ * Optional for the same reason as {@link resumeAgent}: a host without it
238
+ * rejects `workflow()` outright rather than silently running nothing.
239
+ */
240
+ loadWorkflow?(ref: WorkflowScriptRef): Promise<WorkflowScriptSource> | WorkflowScriptSource;
241
+ }
242
+
243
+ /**
244
+ * What a run can be told to do while it is going, from the workflows dialog.
245
+ *
246
+ * Every method is best-effort and idempotent: the dialog renders off a progress
247
+ * log that lags the runtime slightly, so it will sometimes ask for something
248
+ * that has just stopped being possible. `false` means "there was nothing to do
249
+ * that to" — a caller can say so, but it is never an error.
250
+ */
251
+ export interface WorkflowControl {
252
+ /**
253
+ * Stop *starting* agents. Ones already running are left to finish, because
254
+ * killing model work mid-turn throws away everything it has spent and there
255
+ * is no way to hand it back its context.
256
+ */
257
+ pause(): void;
258
+ resume(): void;
259
+ isPaused(): boolean;
260
+ /**
261
+ * Give up on the agent at `index`: its `agent()` call returns `null`, exactly
262
+ * as a terminal failure does, and the row renders skipped.
263
+ *
264
+ * Immediate for a running agent and for one held at a pause. An agent parked
265
+ * behind the concurrency limit takes its skip when it reaches the front —
266
+ * the alternative is a cancellable semaphore for a case that resolves itself
267
+ * as soon as any sibling finishes.
268
+ */
269
+ skip(index: number): boolean;
270
+ /**
271
+ * Start the agent at `index` over: the child is stopped and the same call is
272
+ * re-run, so the script's `agent()` promise is still the one waiting and it
273
+ * gets the new answer.
274
+ *
275
+ * Only while it is running — that is the whole window. Once the call has
276
+ * settled its value is already the script's, and re-running would produce a
277
+ * result with nowhere to go.
278
+ */
279
+ retry(index: number): boolean;
280
+ }
281
+
282
+ export interface RunWorkflowOptions {
283
+ /** Full script source, starting with `export const meta = { … }`. */
284
+ script: string;
285
+ args?: unknown;
286
+ /** Used only when an agent() call does not name its own role. */
287
+ defaultAgentType?: string;
288
+ /** True when the run's `agentType` named that default — see {@link WorkflowSpawnRequest.agentTypeExplicit}. */
289
+ defaultAgentTypeExplicit?: boolean;
290
+ host: WorkflowHost;
291
+ signal?: AbortSignal;
292
+ /** Fired per batch, not per entry — see the worker's progress batching. */
293
+ onProgress?(entries: readonly WorkflowEntry[]): void;
294
+ concurrency?: number;
295
+ agentCap?: number;
296
+ itemCap?: number;
297
+ /**
298
+ * Hands the caller the run's control surface, once per run.
299
+ *
300
+ * A callback rather than a return value because `runWorkflow` resolves when
301
+ * the run is *over*, which is the one moment there is nothing left to
302
+ * control. Fired before the first agent starts.
303
+ */
304
+ onControl?(control: WorkflowControl): void;
305
+ /**
306
+ * How many nested `workflow()` invocations one run may make in total.
307
+ *
308
+ * Each costs a compile and a scope rather than a thread, so the ceiling is
309
+ * generous — but unbounded is worse than capped, on the same reasoning as
310
+ * {@link agentCap}.
311
+ */
312
+ nestedCap?: number;
313
+ /**
314
+ * Replay and record, for `resumeFromRunId`.
315
+ *
316
+ * The runtime does no file IO — `entries` come in already read and `append`
317
+ * goes back out — so its tests stay free of a filesystem, the same reason
318
+ * spawning is behind {@link WorkflowHost}.
319
+ */
320
+ journal?: {
321
+ /** A previous run's settled calls, in position order. Empty replays nothing. */
322
+ entries?: readonly WorkflowJournalEntry[];
323
+ /**
324
+ * Called as each call of *this* run settles, so it can be resumed in turn.
325
+ *
326
+ * May return a promise. The runtime accepts records synchronously and
327
+ * writes them through one ordered chain, so a slow disk never blocks an
328
+ * agent's response and a failed write never drops the records after it.
329
+ * {@link onJournalDrain} is how a caller waits for that chain: this callback
330
+ * only runs once the record reaches the front of it.
331
+ */
332
+ append?(entry: WorkflowJournalEntry): void | Promise<void>;
333
+ };
334
+ /**
335
+ * The run's accepted-write drain, handed over before any work starts.
336
+ *
337
+ * Whatever {@link journal.append} is given is queued inside this run first, so
338
+ * a record can be accepted long before the journal module has been handed it
339
+ * — and `readJournal` can only wait for appends it was given. A caller that
340
+ * reads the journal back (a paused run being resumed, a shutdown that must
341
+ * not lose the tail) needs to wait for the *queue*. The handle delivered here
342
+ * resolves once every record accepted so far has settled, and keeps following
343
+ * the queue if a call settles while it is waiting. Nothing accepted is ever
344
+ * dropped, and a failed write is still swallowed rather than failing the wait:
345
+ * this is the same best-effort treatment `append` gets.
346
+ *
347
+ * Called once, before the worker exists. A handle delivered later could miss
348
+ * a call that had already settled for a run nobody had been told about yet.
349
+ */
350
+ onJournalDrain?(drain: () => Promise<void>): void;
351
+ }
352
+
353
+ export interface WorkflowRunResult {
354
+ status: "completed" | "failed" | "killed";
355
+ meta: WorkflowMeta;
356
+ /** The script's return value, JSON-checked at the boundary. */
357
+ value?: unknown;
358
+ error?: string;
359
+ /** The append-only log, in emission order. */
360
+ progress: WorkflowEntry[];
361
+ /** Agents scheduled, including those that failed. */
362
+ agentCount: number;
363
+ /** How many of those came back from the journal instead of being spawned. */
364
+ replayedCount: number;
365
+ }
366
+
367
+ /* ------------------------------------------------------------------------- *
368
+ * JSON boundary — host side
369
+ * ------------------------------------------------------------------------- */
370
+
371
+ function boundaryError(what: string, path: string): WorkflowRuntimeError {
372
+ return new WorkflowRuntimeError(
373
+ `Cannot pass ${what} across the workflow VM boundary (at ${path}).`,
374
+ );
375
+ }
376
+
377
+ function walk(value: unknown, path: string, seen: Set<object>): void {
378
+ if (value === null) return;
379
+ const kind = typeof value;
380
+ if (kind === "string" || kind === "boolean") return;
381
+ if (kind === "number") {
382
+ if (!Number.isFinite(value)) throw boundaryError("a non-finite number", path);
383
+ return;
384
+ }
385
+ if (kind === "undefined") {
386
+ if (path === "args") return;
387
+ throw boundaryError("undefined", path);
388
+ }
389
+ if (kind === "bigint") throw boundaryError("a BigInt", path);
390
+ if (kind === "symbol") throw boundaryError("a symbol", path);
391
+ if (kind === "function") throw boundaryError("a function", path);
392
+ if (kind !== "object") throw boundaryError(`a ${kind}`, path);
393
+
394
+ const object = value as object;
395
+ if (seen.has(object)) throw boundaryError("a circular structure", path);
396
+ seen.add(object);
397
+
398
+ if (Object.getOwnPropertySymbols(object).length > 0) {
399
+ throw boundaryError("an object with symbol keys", path);
400
+ }
401
+
402
+ if (Array.isArray(object)) {
403
+ for (let i = 0; i < object.length; i++) {
404
+ if (!Object.hasOwn(object, i)) throw boundaryError("a sparse array", `${path}[${i}]`);
405
+ walk(object[i], `${path}[${i}]`, seen);
406
+ }
407
+ seen.delete(object);
408
+ return;
409
+ }
410
+
411
+ const prototype = Object.getPrototypeOf(object);
412
+ if (prototype !== null && prototype !== Object.prototype) {
413
+ throw boundaryError("a non-plain object", path);
414
+ }
415
+ for (const [key, entry] of Object.entries(object)) {
416
+ walk(entry, `${path}.${key}`, seen);
417
+ }
418
+ seen.delete(object);
419
+ }
420
+
421
+ /**
422
+ * Reject anything that cannot survive the round trip to the worker and into a
423
+ * resume journal. Structured clone would happily carry a `Map` or a cycle that
424
+ * the journal then cannot represent, so the check is stricter than the transport.
425
+ */
426
+ export function assertBoundarySafe(value: unknown, path: string): void {
427
+ walk(value, path, new Set());
428
+ }
429
+
430
+ /* ------------------------------------------------------------------------- *
431
+ * Semaphore
432
+ * ------------------------------------------------------------------------- */
433
+
434
+ class Semaphore {
435
+ private active = 0;
436
+ private readonly waiters: (() => void)[] = [];
437
+
438
+ constructor(private readonly limit: number) {}
439
+
440
+ acquire(): Promise<void> {
441
+ if (this.active < this.limit) {
442
+ this.active++;
443
+ return Promise.resolve();
444
+ }
445
+ return new Promise<void>(resolve => {
446
+ this.waiters.push(resolve);
447
+ });
448
+ }
449
+
450
+ release(): void {
451
+ const next = this.waiters.shift();
452
+ // Hand the permit straight over rather than decrementing and re-acquiring;
453
+ // otherwise a burst of releases can let more than `limit` through.
454
+ if (next) next();
455
+ else this.active--;
456
+ }
457
+
458
+ /** Wake everyone so aborted callers can observe the abort and bail. */
459
+ drain(): void {
460
+ while (this.waiters.length > 0) {
461
+ const next = this.waiters.shift();
462
+ next?.();
463
+ }
464
+ }
465
+ }
466
+
467
+ /* ------------------------------------------------------------------------- *
468
+ * Messages
469
+ * ------------------------------------------------------------------------- */
470
+
471
+ interface AgentCallPayload {
472
+ prompt: string;
473
+ label?: string;
474
+ model?: string;
475
+ agentType?: string;
476
+ isolation?: "worktree";
477
+ phaseIndex?: number;
478
+ phaseTitle?: string;
479
+ /** Shell command that has to pass before the agent counts as done. */
480
+ gate?: string;
481
+ /** Label of an earlier child in this run to continue instead of starting one. */
482
+ resume?: string;
483
+ /** Reasoning effort, already validated against pi's thinking levels worker-side. */
484
+ effort?: string;
485
+ /** Raw JSON Schema from `agent({ schema })`, compiled before anything spawns. */
486
+ schema?: unknown;
487
+ }
488
+
489
+ type WorkerMessage =
490
+ | { type: "call"; callId: number; method: string; payload: AgentCallPayload }
491
+ | { type: "progress"; entries: WorkflowEntry[] }
492
+ | { type: "complete"; resultJson?: string }
493
+ | { type: "error"; message: string; stack?: string };
494
+
495
+ /** Everything below 0x20 except tab, newline and carriage return, plus DEL. */
496
+ const CONTROL_CHARACTERS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/;
497
+
498
+ const preview = (text: string) =>
499
+ text.length <= PREVIEW_LENGTH ? text : `${text.slice(0, PREVIEW_LENGTH - 1)}…`;
500
+
501
+ /** First line of the prompt, trimmed — the fallback display name for an agent. */
502
+ function derivedLabel(prompt: string): string {
503
+ const line = prompt.split("\n", 1)[0].trim();
504
+ return line.length <= 60 ? line || "agent" : `${line.slice(0, 59)}…`;
505
+ }
506
+
507
+ /**
508
+ * A child `resume` can revive, remembered under its label.
509
+ *
510
+ * The spawn options travel with it because `resume` deliberately takes none: the
511
+ * revived child keeps the agent type, model and isolation it was started with,
512
+ * and the progress entry has to show the same thing the first entry showed.
513
+ */
514
+ interface CompletedChild {
515
+ agentId: string;
516
+ label: string;
517
+ agentType: string;
518
+ model?: string;
519
+ isolation?: "worktree";
520
+ }
521
+
522
+ /**
523
+ * Turn a failing gate into a failing agent.
524
+ *
525
+ * Deliberately no new state, no new entry type: a gated agent whose command
526
+ * fails is *a failed agent*, so the card, the dialog and `agent()`'s `null`
527
+ * return all handle it with the code they already have. The command output
528
+ * becomes the error, because that is the thing worth reading.
529
+ *
530
+ * The single place that decides whether a gate passed. The command may have
531
+ * been run by the host instead (inside a worktree that no longer exists by
532
+ * now), but only ever by one of the two: a host that ran it says so with
533
+ * `result.gate`, and this then shapes that outcome rather than running it
534
+ * again.
535
+ */
536
+ /**
537
+ * Hold a schema'd result to its schema, host-side.
538
+ *
539
+ * The child's own tool already validated whatever it passed, so this normally
540
+ * agrees. It exists for the cases where nothing did: a host that ignores
541
+ * `schema` entirely, a replayed journal entry from before the schema changed,
542
+ * or a payload that reached us some other way. The script asked for a shape;
543
+ * exactly one place should be able to promise it.
544
+ */
545
+ function applySchema(result: WorkflowSpawnResult, compiled: CompiledSchema): WorkflowSpawnResult {
546
+ let parsed: unknown;
547
+ try {
548
+ parsed = JSON.parse(result.text ?? "");
549
+ } catch {
550
+ return {
551
+ ...result,
552
+ ok: false,
553
+ error: "The agent did not return structured output: its answer was not JSON.",
554
+ };
555
+ }
556
+ const verdict = compiled.check(parsed);
557
+ if (verdict === true) return result;
558
+ return {
559
+ ...result,
560
+ ok: false,
561
+ error: `The agent's answer did not match the requested schema: ${verdict}`,
562
+ };
563
+ }
564
+
565
+ async function applyGate(
566
+ result: WorkflowSpawnResult,
567
+ command: string,
568
+ agentId: string,
569
+ runGate: NonNullable<WorkflowHost["runGate"]>,
570
+ ): Promise<WorkflowSpawnResult> {
571
+ const outcome =
572
+ result.gate ??
573
+ (await runGate(command, {
574
+ agentId,
575
+ // Where the child worked, when it had a worktree of its own. Gating the
576
+ // main tree instead would verify code the child never touched.
577
+ ...(result.cwd !== undefined ? { cwd: result.cwd } : {}),
578
+ }));
579
+ const { gate: _ran, ...kept } = result;
580
+ if (outcome.ok) return kept;
581
+ const { text: _discarded, ...rest } = kept;
582
+ const output = outcome.output.trim();
583
+ return { ...rest, ok: false, error: output === "" ? `Gate command failed: ${command}` : output };
584
+ }
585
+
586
+ /**
587
+ * Nico's wording, kept verbatim — this is the one borrowed check whose message a
588
+ * user is likely to search for.
589
+ */
590
+ function unawaitedLaunchMessage(labels: readonly string[]): string {
591
+ const list = labels.map(label => `'${label}'`).join(", ");
592
+ return `workflow script completed with unawaited agent launch(es): ${list}. Await or return each launch.`;
593
+ }
594
+
595
+ /**
596
+ * Run one workflow script to completion.
597
+ *
598
+ * Rejects before starting for a script that cannot run at all (bad `meta`, over
599
+ * the size limit, control characters, non-JSON `args`). Everything after the
600
+ * worker is live resolves instead, carrying the failure in `status` — by then
601
+ * there is a progress log worth handing back.
602
+ */
603
+ /**
604
+ * Everything a script must satisfy before it is compiled.
605
+ *
606
+ * Extracted so a nested `workflow()` is held to exactly the same standard as a
607
+ * top-level run: same size limit, same character rules, same `meta` contract.
608
+ * The host resolves a reference to source; deciding whether that source is a
609
+ * workflow stays here, where the rules live.
610
+ */
611
+ export function validateScript(script: string): { meta: WorkflowMeta; body: string } {
612
+ if (script.length > MAX_SCRIPT_LENGTH) {
613
+ throw new WorkflowRuntimeError(
614
+ `Workflow script is ${script.length} characters, over the limit of ${MAX_SCRIPT_LENGTH}.`,
615
+ );
616
+ }
617
+ if (CONTROL_CHARACTERS.test(script)) {
618
+ throw new WorkflowRuntimeError(
619
+ "Workflow script contains control characters. Only tab, carriage return and newline are allowed.",
620
+ );
621
+ }
622
+ return extractMeta(script);
623
+ }
624
+
625
+ export async function runWorkflow(options: RunWorkflowOptions): Promise<WorkflowRunResult> {
626
+ const { script, host } = options;
627
+
628
+ assertBoundarySafe(options.args, "args");
629
+
630
+ const { meta, body } = validateScript(script);
631
+ const defaultAgentType = (options.defaultAgentType ?? DEFAULT_WORKFLOW_AGENT_TYPE).trim();
632
+ if (defaultAgentType === "") throw new WorkflowRuntimeError("Workflow defaultAgentType must be a non-empty agent name.");
633
+ const agentCap = options.agentCap ?? WORKFLOW_AGENT_CAP;
634
+ const itemCap = options.itemCap ?? WORKFLOW_ITEM_CAP;
635
+ const semaphore = new Semaphore(options.concurrency ?? workflowConcurrency());
636
+
637
+ const progress: WorkflowEntry[] = [];
638
+ const inflight = new Set<string>();
639
+ /** Label → the child that ran under it, last one wins. The `resume` handle. */
640
+ const completedByLabel = new Map<string, CompletedChild>();
641
+ /**
642
+ * Launches the host has accepted and not yet answered, in call order.
643
+ *
644
+ * This is the whole unawaited-launch mechanism: a script that drops an
645
+ * `agent()` promise still gets its call answered eventually, but it returns
646
+ * first — so anything left here when `complete` arrives is a result nobody is
647
+ * waiting for. Tracking it host-side avoids proxying `Promise` inside the
648
+ * realm, which §2.4 rules out, and reading stack traces, which is brittle.
649
+ */
650
+ const openLaunches = new Map<number, string>();
651
+ let agentCount = 0;
652
+ let aborted = false;
653
+ let settled = false;
654
+
655
+ /* --- resume state ---------------------------------------------------- */
656
+
657
+ const journalEntries = options.journal?.entries ?? [];
658
+ const appendJournalEntry = options.journal?.append;
659
+ /**
660
+ * Whether this run still accepts journal records.
661
+ *
662
+ * Closed synchronously by `finish` before any abort or termination work, so a
663
+ * call that settles during teardown cannot append to a journal the run is
664
+ * already reporting as finished.
665
+ */
666
+ let journalAccepting = true;
667
+ /** The accepted records, in settlement order. Never rejects. */
668
+ let journalWrites: Promise<void> = Promise.resolve();
669
+
670
+ /**
671
+ * Accept one record into the run's single ordered write chain.
672
+ *
673
+ * Deliberately synchronous: the agent path answers the script immediately and
674
+ * `finish` only has to await writes that were accepted before it closed the
675
+ * gate. `appendJournalEntry` may be sync or promise-returning; either way its
676
+ * failure is swallowed here so later records still get written and a
677
+ * best-effort journal can never fail the run.
678
+ */
679
+ const recordJournal = (entry: WorkflowJournalEntry): void => {
680
+ if (!journalAccepting || appendJournalEntry === undefined) return;
681
+ journalWrites = journalWrites.then(async () => {
682
+ try {
683
+ await appendJournalEntry(entry);
684
+ } catch {
685
+ // A journal that cannot be written costs a future resume, nothing more.
686
+ // Staying on this chain is what keeps the later records alive.
687
+ }
688
+ });
689
+ };
690
+ /**
691
+ * Wait for every record this run has accepted so far.
692
+ *
693
+ * The tail is re-read after each wait: a call that settles while this is
694
+ * suspended appends a new link, and resolving on the tail observed first
695
+ * would hand back exactly the half-written journal this exists to prevent.
696
+ * The chain swallows its own write failures as it goes — see `recordJournal`
697
+ * — so waiting on it never rejects and a failed record never strands the
698
+ * ones behind it. Called after the run settles it resolves immediately: the
699
+ * chain is closed, settled and stable, so a shutdown that arrives late has
700
+ * nothing special to do.
701
+ */
702
+ const drainJournal = async (): Promise<void> => {
703
+ let tail = journalWrites;
704
+ await tail;
705
+ while (tail !== journalWrites) {
706
+ tail = journalWrites;
707
+ await tail;
708
+ }
709
+ };
710
+ // Registered before the worker exists, because the worker is what settles
711
+ // calls: a handle delivered any later could miss a record already accepted.
712
+ options.onJournalDrain?.(drainJournal);
713
+ /**
714
+ * Whether the replayable prefix is still intact.
715
+ *
716
+ * Once a position misses — different key, a journaled failure, or nothing
717
+ * recorded there — every later call runs live, however well it matches.
718
+ * See the header of journal.ts for why this is a prefix and not a lookup.
719
+ */
720
+ // A journal from a run that used `agent({ resume })` is declined whole: see
721
+ // journal.ts on why a replayed agent leaves nothing for a later resume to
722
+ // continue. Declining up front beats stranding the first `resume` call
723
+ // partway through a run that has already spent its cheap half.
724
+ const journalResumes = journalEntries.some(entry => entry.resumed);
725
+ let prefixIntact = journalEntries.length > 0 && !journalResumes;
726
+ let replayedCount = 0;
727
+
728
+ /* --- live control ---------------------------------------------------- */
729
+
730
+ /**
731
+ * Agents that still have an unanswered `agent()` call, by index.
732
+ *
733
+ * The window in which skip and retry mean anything: before the entry appears
734
+ * there is nothing to act on, and after it is gone the script already has its
735
+ * value. `started` is what separates the two — a retry needs a child to stop.
736
+ */
737
+ interface LiveAgent {
738
+ agentId: string;
739
+ started: boolean;
740
+ intent?: "skip" | "retry";
741
+ /** Wakes it out of a pause hold, so a skip does not wait for a resume. */
742
+ wake?: () => void;
743
+ }
744
+ const liveAgents = new Map<number, LiveAgent>();
745
+
746
+ /**
747
+ * Output tokens this run has spent, mirrored to the script as
748
+ * `budget.spent()`.
749
+ *
750
+ * The host owns the number and every response carries it, rather than the
751
+ * worker accumulating its own: two counters would drift, and there is nothing
752
+ * to gain from the second one. Nor is there observable staleness — tokens
753
+ * only accrue through agents, and the script only learns anything through
754
+ * agent responses.
755
+ */
756
+ let spentOutputTokens = 0;
757
+
758
+ let paused = false;
759
+ /** Read through a call for the same reason `intent()` is — see below. */
760
+ const isPaused = () => paused;
761
+ const pauseWaiters = new Set<() => void>();
762
+ /** Release everyone held at a pause — on resume, and on the way out. */
763
+ function releasePause(): void {
764
+ for (const wake of [...pauseWaiters]) wake();
765
+ pauseWaiters.clear();
766
+ }
767
+ /** Park here while the run is paused, so no new agent is started. */
768
+ function pauseGate(live: LiveAgent): Promise<void> {
769
+ if (!paused || aborted || settled) return Promise.resolve();
770
+ return new Promise<void>(resolve => {
771
+ const wake = () => {
772
+ pauseWaiters.delete(wake);
773
+ live.wake = undefined;
774
+ resolve();
775
+ };
776
+ live.wake = wake;
777
+ pauseWaiters.add(wake);
778
+ });
779
+ }
780
+
781
+ options.onControl?.({
782
+ pause: () => { paused = true; },
783
+ resume: () => { paused = false; releasePause(); },
784
+ isPaused: () => paused,
785
+ skip: index => {
786
+ const live = liveAgents.get(index);
787
+ if (live === undefined || live.intent !== undefined) return false;
788
+ live.intent = "skip";
789
+ // A running child is stopped, which comes back as a skipped result; a
790
+ // held one is woken so it can bail at the gate it is parked on.
791
+ if (live.started) host.abortAgent(live.agentId);
792
+ else live.wake?.();
793
+ return true;
794
+ },
795
+ retry: index => {
796
+ const live = liveAgents.get(index);
797
+ if (live === undefined || !live.started || live.intent !== undefined) return false;
798
+ live.intent = "retry";
799
+ host.abortAgent(live.agentId);
800
+ return true;
801
+ },
802
+ });
803
+
804
+ /** The journal entry to reuse at `index`, or undefined to run it live. */
805
+ function replayAt(index: number, key: string, input: JournalKeyInput): WorkflowJournalEntry | undefined {
806
+ if (!prefixIntact) return undefined;
807
+ const entry = journalEntries[index];
808
+ if (entry === undefined || entry.index !== index || !entry.ok ||
809
+ (entry.key !== key && entry.key !== journalKey(input, "legacy"))) {
810
+ prefixIntact = false;
811
+ return undefined;
812
+ }
813
+ return entry;
814
+ }
815
+
816
+ const worker = new Worker(WORKER_SOURCE, {
817
+ eval: true,
818
+ workerData: {
819
+ body,
820
+ metaJson: JSON.stringify(meta),
821
+ argsJson: options.args === undefined ? undefined : JSON.stringify(options.args),
822
+ itemCap,
823
+ nestedCap: options.nestedCap ?? WORKFLOW_NESTED_CAP,
824
+ },
825
+ });
826
+
827
+ return await new Promise<WorkflowRunResult>(resolve => {
828
+ const emit = (entries: WorkflowEntry[]) => {
829
+ if (entries.length === 0) return;
830
+ progress.push(...entries);
831
+ options.onProgress?.(entries);
832
+ };
833
+
834
+ const respond = (callId: number, ok: boolean, value?: unknown, error?: string, fatal?: boolean) => {
835
+ // Cleared before the settled check: a launch answered by a run that is
836
+ // already finishing is not an unawaited launch either.
837
+ openLaunches.delete(callId);
838
+ if (settled) return;
839
+ // `spent` rides on every response, so the worker's `budget.spent()` is a
840
+ // mirror of this number rather than a second tally of its own.
841
+ worker.postMessage({ type: "response", callId, ok, value, error, fatal, spent: spentOutputTokens });
842
+ };
843
+
844
+ const finish = (result: Omit<WorkflowRunResult, "meta" | "progress" | "agentCount" | "replayedCount">) => {
845
+ if (settled) return;
846
+ settled = true;
847
+ // Closed before anything else can run: every record accepted so far is
848
+ // captured, and none accepted afterwards can reach the journal.
849
+ journalAccepting = false;
850
+ const acceptedJournalWrites = journalWrites;
851
+ options.signal?.removeEventListener("abort", onAbort);
852
+ // Symmetric with `semaphore.drain()` below: everything parked is woken so
853
+ // it observes the settle and unwinds. Nothing depends on it — the run's
854
+ // promise resolves either way — it just does not leave live-agent
855
+ // bookkeeping behind for a run that is over.
856
+ releasePause();
857
+ for (const agentId of inflight) host.abortAgent(agentId);
858
+ inflight.clear();
859
+ semaphore.drain();
860
+ // Resolve only once the thread is actually down AND the records this run
861
+ // accepted are flushed. The chain contains only append callbacks, never a
862
+ // child/provider promise, so a hung agent cannot delay the result while
863
+ // an immediate resume still cannot miss a write.
864
+ const settle = () => resolve({ ...result, meta, progress, agentCount, replayedCount });
865
+ void Promise.allSettled([acceptedJournalWrites, worker.terminate()]).then(settle);
866
+ };
867
+
868
+ function onAbort() {
869
+ aborted = true;
870
+ // terminate() is why this runs in a worker at all: it stops a script that
871
+ // is spinning or wedged mid-await, which an in-process vm cannot do.
872
+ finish({ status: "killed", error: "Workflow aborted." });
873
+ }
874
+
875
+ if (options.signal) {
876
+ if (options.signal.aborted) {
877
+ onAbort();
878
+ return;
879
+ }
880
+ options.signal.addEventListener("abort", onAbort, { once: true });
881
+ }
882
+
883
+ async function handleAgent(callId: number, payload: AgentCallPayload): Promise<void> {
884
+ // Bound now: the optional methods are checked once, up front, so a
885
+ // capability the host lacks fails before an agent is spawned rather than
886
+ // after — a gate that never ran must not be mistaken for a gate that
887
+ // passed.
888
+ const runGate = host.runGate?.bind(host);
889
+ const resumeAgent = host.resumeAgent?.bind(host);
890
+ if (payload.gate !== undefined && runGate === undefined) {
891
+ respond(callId, false, undefined, "This workflow host cannot run gate commands.", true);
892
+ return;
893
+ }
894
+ if (payload.resume !== undefined && resumeAgent === undefined) {
895
+ respond(callId, false, undefined, "This workflow host cannot resume agents.", true);
896
+ return;
897
+ }
898
+
899
+ let resumed: CompletedChild | undefined;
900
+ if (payload.resume !== undefined) {
901
+ resumed = completedByLabel.get(payload.resume);
902
+ if (resumed === undefined) {
903
+ const known = [...completedByLabel.keys()];
904
+ // Fatal: a typo'd label is a script bug, and folding it into a null
905
+ // would show up as an agent that mysteriously returned nothing.
906
+ //
907
+ // Unless agents were replayed, in which case it is not a script bug
908
+ // at all — the label's child came back from the journal and has no
909
+ // conversation here to continue. Saying "no agent has completed"
910
+ // would send the reader hunting for a typo that is not there.
911
+ respond(
912
+ callId,
913
+ false,
914
+ undefined,
915
+ replayedCount > 0 ?
916
+ `agent() opts.resume: "${payload.resume}" was replayed from the resume journal, not run, so there is ` +
917
+ "no conversation in this run to continue. Re-run without resumeFromRunId."
918
+ : `agent() opts.resume: no agent has completed under the label "${payload.resume}" in this run. ${
919
+ known.length === 0
920
+ ? "No agent has completed yet."
921
+ : `Known labels: ${known.map(label => `"${label}"`).join(", ")}.`
922
+ }`,
923
+ true,
924
+ );
925
+ return;
926
+ }
927
+ }
928
+
929
+ // Compiled before anything is scheduled. A schema the runtime cannot use
930
+ // is a script bug, so it is fatal like a typo'd resume label — folding it
931
+ // into a null would surface as an agent that mysteriously returned
932
+ // nothing, and it costs no model call to say so here.
933
+ let compiledSchema: CompiledSchema | undefined;
934
+ if (payload.schema !== undefined) {
935
+ const compilation = compileJsonSchema(payload.schema);
936
+ if (!compilation.ok) {
937
+ respond(callId, false, undefined, compilation.message, true);
938
+ return;
939
+ }
940
+ compiledSchema = compilation.compiled;
941
+ }
942
+
943
+ if (agentCount >= agentCap) {
944
+ // Fatal, so parallel()/pipeline() rethrow instead of folding it into a
945
+ // null. A cap that silently drops work is worse than no cap.
946
+ respond(callId, false, undefined, `Workflow exceeded its cap of ${agentCap} agents.`, true);
947
+ return;
948
+ }
949
+ const index = agentCount++;
950
+ // A resumed call is the same child again: it keeps the agent id, so an
951
+ // abort still reaches it, and it keeps its spawn contract, so the row
952
+ // reads the same as the row it continues.
953
+ const agentId = resumed?.agentId ?? `wf-agent-${index}`;
954
+ const label = payload.label ?? resumed?.label ?? derivedLabel(payload.prompt);
955
+ const agentType = resumed?.agentType ?? payload.agentType ?? defaultAgentType;
956
+ const agentTypeExplicit = payload.agentType !== undefined || options.defaultAgentTypeExplicit === true;
957
+ const model = resumed !== undefined ? resumed.model : payload.model;
958
+ const isolation = resumed !== undefined ? resumed.isolation : payload.isolation;
959
+ openLaunches.set(callId, label);
960
+
961
+ const base: WorkflowAgentEntry = {
962
+ type: "workflow_agent",
963
+ index,
964
+ label,
965
+ state: "start",
966
+ agentId,
967
+ agentType,
968
+ promptPreview: preview(payload.prompt),
969
+ ...(model !== undefined ? { model } : {}),
970
+ ...(isolation !== undefined ? { isolation } : {}),
971
+ ...(payload.phaseIndex !== undefined ? { phaseIndex: payload.phaseIndex } : {}),
972
+ ...(payload.phaseTitle !== undefined ? { phaseTitle: payload.phaseTitle } : {}),
973
+ };
974
+
975
+ const queuedAt = Date.now();
976
+ emit([{ ...base, queuedAt }]);
977
+
978
+ // Replay before the semaphore, not after: a cached answer is not model
979
+ // running, so it must not hold a concurrency slot that a live agent
980
+ // could use. The row still appears in the tree — the run reads as the
981
+ // same shape it had the first time, just faster.
982
+ // The payload's `schema` is the raw object; the key wants it serialized,
983
+ // so the spread is narrowed rather than passed through.
984
+ const keyInput: JournalKeyInput = {
985
+ ...payload,
986
+ agentType,
987
+ agentTypeExplicit,
988
+ schema: payload.schema !== undefined ? JSON.stringify(payload.schema) : undefined,
989
+ };
990
+ const key = journalKey(keyInput);
991
+ let replayed = replayAt(index, key, keyInput);
992
+ // A replayed answer still has to satisfy the schema. The key covers a
993
+ // schema that *changed*, but not a journal that was hand-edited, and not
994
+ // the empty text a torn entry leaves behind — either would hand the
995
+ // script a null from an entry the journal claims succeeded.
996
+ if (replayed !== undefined && compiledSchema !== undefined) {
997
+ const recheck = applySchema({ ok: true, text: replayed.text ?? "" }, compiledSchema);
998
+ if (!recheck.ok) {
999
+ prefixIntact = false;
1000
+ replayed = undefined;
1001
+ }
1002
+ }
1003
+ if (replayed !== undefined) {
1004
+ replayedCount++;
1005
+ const replayedText = replayed.text ?? "";
1006
+ const at = Date.now();
1007
+ emit([
1008
+ {
1009
+ ...base,
1010
+ queuedAt,
1011
+ startedAt: at,
1012
+ lastProgressAt: at,
1013
+ durationMs: 0,
1014
+ state: "done",
1015
+ // The row reads as done, because it is — `cached` is what tells the
1016
+ // dialog to annotate it "from resume journal" rather than letting a
1017
+ // 0ms agent look like one that did the work impossibly fast.
1018
+ cached: true,
1019
+ resultPreview: preview(replayedText),
1020
+ },
1021
+ ]);
1022
+ openLaunches.delete(callId);
1023
+ // Re-recorded so this run's journal is complete on its own terms: a
1024
+ // resume of a resume must not have to walk back through a chain of
1025
+ // earlier files to find the prefix.
1026
+ recordJournal({ index, key: replayed.key, ok: true, text: replayedText });
1027
+ respond(callId, true, replayedText);
1028
+ return;
1029
+ }
1030
+
1031
+ const resumeMark = payload.resume !== undefined ? ({ resumed: true } as const) : {};
1032
+
1033
+ /** A skip the user asked for, before the child ever started. */
1034
+ const settleSkipped = (extra: Partial<WorkflowAgentEntry>) => {
1035
+ recordJournal({ index, key, ok: false, ...resumeMark });
1036
+ emit([{ ...base, queuedAt, ...extra, state: "error", skipped: true, error: "Skipped by user." }]);
1037
+ // `null`, exactly as a terminal failure gives — a skipped agent is one
1038
+ // the script's `.filter(Boolean)` was already written to survive.
1039
+ respond(callId, true, null);
1040
+ };
1041
+
1042
+ // Registered for exactly as long as the call is unanswered, which is the
1043
+ // window in which skip and retry mean anything.
1044
+ const live: LiveAgent = { agentId, started: false };
1045
+ liveAgents.set(index, live);
1046
+ // Read through a call, not off the field: `intent` is set from outside
1047
+ // this function while it is suspended at an await, so control-flow
1048
+ // narrowing across the awaits would be reasoning about a value that has
1049
+ // since changed.
1050
+ const intent = (): LiveAgent["intent"] => live.intent;
1051
+ let attempt = 1;
1052
+ try {
1053
+ for (;;) {
1054
+ // Held before the slot, not after: a paused run must not sit on
1055
+ // concurrency it is not using while its running agents drain.
1056
+ await pauseGate(live);
1057
+ if (intent() === "skip") return settleSkipped({});
1058
+
1059
+ // A resumed agent waits its turn like any other: it is the same amount of
1060
+ // model running at once.
1061
+ await semaphore.acquire();
1062
+ if (aborted || settled) {
1063
+ semaphore.release();
1064
+ respond(callId, false, undefined, "Workflow aborted.", true);
1065
+ return;
1066
+ }
1067
+ // Paused while parked behind the limit: this agent was waiting for a
1068
+ // permit when the pause landed, so it never passed the gate above.
1069
+ // Hand the permit back and go wait at the gate like everything else,
1070
+ // or a pause would leak exactly as many agents as were queued.
1071
+ if (isPaused() && !aborted && !settled) {
1072
+ semaphore.release();
1073
+ continue;
1074
+ }
1075
+ // Skipped while parked behind the limit: the permit arrived, and the
1076
+ // only thing left to do with it is give it back.
1077
+ if (intent() === "skip") {
1078
+ semaphore.release();
1079
+ return settleSkipped({});
1080
+ }
1081
+
1082
+ // Carried on every emit from here on, so a retried row keeps saying
1083
+ // why it is on its second attempt instead of losing it to the next
1084
+ // progress update.
1085
+ const attemptMark =
1086
+ attempt > 1 ? { attempt, lastAttemptReason: "user-retry" as const } : {};
1087
+
1088
+ const startedAt = Date.now();
1089
+ emit([{ ...base, queuedAt, startedAt, ...attemptMark }]);
1090
+
1091
+ // Mutates `base` rather than emitting a standalone patch: every later
1092
+ // emit spreads it, so the settle path carries the effective values
1093
+ // without knowing they were ever corrected. Re-emitting under the
1094
+ // same `index` is what the append-only, last-write-wins progress log
1095
+ // is for — the row updates in place while the agent is still running.
1096
+ const onResolved = (info: {
1097
+ recordId?: string;
1098
+ modelName?: string;
1099
+ modelId?: string;
1100
+ thinking?: string;
1101
+ requestedThinking?: string;
1102
+ requestedModel?: string;
1103
+ }) => {
1104
+ if (info.recordId !== undefined) base.recordId = info.recordId;
1105
+ if (info.modelName !== undefined) base.model = info.modelName;
1106
+ if (info.modelId !== undefined) base.modelId = info.modelId;
1107
+ if (info.thinking !== undefined) base.thinking = info.thinking;
1108
+ if (info.requestedThinking !== undefined) base.requestedThinking = info.requestedThinking;
1109
+ if (info.requestedModel !== undefined) base.requestedModel = info.requestedModel;
1110
+ // `base.state` is still "start", so emitting after the row reached a
1111
+ // terminal state would revert it to running under last-write-wins.
1112
+ // Not reachable from this repo's host, which reports during startup
1113
+ // — but this is the host boundary, and every other promise it makes
1114
+ // is checked rather than trusted.
1115
+ if (!inflight.has(agentId)) return;
1116
+ emit([{ ...base, queuedAt, startedAt, ...attemptMark, lastProgressAt: Date.now() }]);
1117
+ };
1118
+ live.started = true;
1119
+ inflight.add(agentId);
1120
+
1121
+ let result: WorkflowSpawnResult;
1122
+ try {
1123
+ result =
1124
+ resumed !== undefined && resumeAgent !== undefined
1125
+ ? await resumeAgent(resumed.agentId, payload.prompt, onResolved)
1126
+ : await host.spawnAgent({
1127
+ agentId,
1128
+ index,
1129
+ prompt: payload.prompt,
1130
+ label,
1131
+ agentType,
1132
+ ...(agentTypeExplicit ? { agentTypeExplicit: true } : {}),
1133
+ ...(model !== undefined ? { model } : {}),
1134
+ ...(payload.effort !== undefined ? { effort: payload.effort } : {}),
1135
+ ...(compiledSchema !== undefined ? { schema: compiledSchema } : {}),
1136
+ ...(isolation !== undefined ? { isolation } : {}),
1137
+ ...(payload.phaseIndex !== undefined ? { phaseIndex: payload.phaseIndex } : {}),
1138
+ ...(payload.phaseTitle !== undefined ? { phaseTitle: payload.phaseTitle } : {}),
1139
+ // Offered, not delegated: a host that can run it inside the
1140
+ // child's worktree does, and hands back `result.gate`.
1141
+ ...(payload.gate !== undefined ? { gate: payload.gate } : {}),
1142
+ onResolved,
1143
+ });
1144
+ if (result.ok) {
1145
+ // Recorded before the gate runs: the child itself finished, so it is
1146
+ // resumable even when its gate rejects the work — "here is what the
1147
+ // gate said, fix it" is the loop this exists for.
1148
+ completedByLabel.set(label, {
1149
+ agentId,
1150
+ label,
1151
+ agentType,
1152
+ ...(model !== undefined ? { model } : {}),
1153
+ ...(isolation !== undefined ? { isolation } : {}),
1154
+ });
1155
+ // Re-checked here, not just in the child's tool: this is the one
1156
+ // place that decides the script's value matches the schema it
1157
+ // asked for, so a host that ignored `schema` fails loudly instead
1158
+ // of handing the script prose. Before the gate, because a gate
1159
+ // verifies work and there is no work to verify if the shape is
1160
+ // wrong — and the reader should see the schema error, not a gate
1161
+ // error standing in front of it.
1162
+ if (compiledSchema !== undefined && result.ok) {
1163
+ result = applySchema(result, compiledSchema);
1164
+ }
1165
+ if (result.ok && payload.gate !== undefined && runGate !== undefined) {
1166
+ result = await applyGate(result, payload.gate, agentId, runGate);
1167
+ }
1168
+ }
1169
+ } catch (error) {
1170
+ result = { ok: false, error: error instanceof Error ? error.message : String(error) };
1171
+ } finally {
1172
+ inflight.delete(agentId);
1173
+ live.started = false;
1174
+ semaphore.release();
1175
+ }
1176
+
1177
+ if (settled) return;
1178
+
1179
+ // The stop that produced this result was ours, so run the same call
1180
+ // again rather than reporting it. The script is still awaiting this
1181
+ // `agent()`, which is the only reason a retry can mean anything.
1182
+ if (intent() === "retry" && !aborted) {
1183
+ live.intent = undefined;
1184
+ attempt++;
1185
+ emit([{ ...base, queuedAt, attempt, lastAttemptReason: "user-retry" }]);
1186
+ continue;
1187
+ }
1188
+
1189
+ // Counted before the response is sent, so the very call that spent
1190
+ // them already sees them in `budget.spent()`. Failed and skipped
1191
+ // agents count too — they burned the tokens either way.
1192
+ spentOutputTokens += result.outputTokens ?? 0;
1193
+
1194
+ const finishedAt = Date.now();
1195
+ const common = {
1196
+ ...base,
1197
+ queuedAt,
1198
+ startedAt,
1199
+ ...attemptMark,
1200
+ lastProgressAt: finishedAt,
1201
+ durationMs: finishedAt - startedAt,
1202
+ ...(result.tokens !== undefined ? { tokens: result.tokens } : {}),
1203
+ ...(result.toolCalls !== undefined ? { toolCalls: result.toolCalls } : {}),
1204
+ };
1205
+
1206
+ if (result.ok) {
1207
+ const text = result.text ?? "";
1208
+ emit([{ ...common, state: "done", resultPreview: preview(text) }]);
1209
+ recordJournal({ index, key, ok: true, text, ...resumeMark });
1210
+ respond(callId, true, text);
1211
+ return;
1212
+ }
1213
+ // Recorded as a failure rather than left out: a gap would be read as an
1214
+ // unchanged prefix on the next resume, silently skipping the retry this
1215
+ // whole mechanism exists to make cheap.
1216
+ recordJournal({ index, key, ok: false, ...resumeMark });
1217
+ // A dead agent is a null in the script, not a thrown error: Claude Code
1218
+ // scripts .filter(Boolean) rather than try/catch around every call.
1219
+ emit([
1220
+ {
1221
+ ...common,
1222
+ state: "error",
1223
+ // A user skip reaches here as a stopped child, which the host
1224
+ // already reports as skipped — the flag is taken from the result
1225
+ // rather than from the intent so an abort mid-skip still reads
1226
+ // as whatever actually happened to the child.
1227
+ error: result.error ?? "Agent failed.",
1228
+ ...(result.skipped ? { skipped: true } : {}),
1229
+ },
1230
+ ]);
1231
+ if (result.fatal) {
1232
+ respond(callId, false, undefined, result.error ?? "Agent configuration failed.", true);
1233
+ } else {
1234
+ respond(callId, true, null);
1235
+ }
1236
+ return;
1237
+ }
1238
+ } finally {
1239
+ liveAgents.delete(index);
1240
+ }
1241
+ }
1242
+
1243
+ /**
1244
+ * Resolve one `workflow(ref)` and hand the child's source back compiled.
1245
+ *
1246
+ * Resolution failures are non-fatal — Claude Code documents `workflow()` as
1247
+ * throwing on an unknown name so a script can catch it and carry on. A host
1248
+ * with no `loadWorkflow` at all is fatal, matching how a missing `runGate`
1249
+ * or `resumeAgent` is treated: a capability the script asked for and this
1250
+ * host cannot provide is a wiring error, not a runtime condition.
1251
+ */
1252
+ async function handleLoadWorkflow(callId: number, ref: WorkflowScriptRef): Promise<void> {
1253
+ const loadWorkflow = host.loadWorkflow?.bind(host);
1254
+ if (loadWorkflow === undefined) {
1255
+ respond(callId, false, undefined, "This workflow host cannot run nested workflows.", true);
1256
+ return;
1257
+ }
1258
+ let source: WorkflowScriptSource;
1259
+ try {
1260
+ source = await loadWorkflow(ref);
1261
+ } catch (error) {
1262
+ respond(callId, false, undefined, error instanceof Error ? error.message : String(error));
1263
+ return;
1264
+ }
1265
+ if (!source.ok) {
1266
+ respond(callId, false, undefined, source.message);
1267
+ return;
1268
+ }
1269
+ try {
1270
+ const child = validateScript(source.script);
1271
+ respond(callId, true, {
1272
+ name: child.meta.name,
1273
+ metaJson: JSON.stringify(child.meta),
1274
+ body: child.body,
1275
+ });
1276
+ } catch (error) {
1277
+ respond(callId, false, undefined, error instanceof Error ? error.message : String(error));
1278
+ }
1279
+ }
1280
+
1281
+ worker.on("message", (message: WorkerMessage) => {
1282
+ if (settled) return;
1283
+ switch (message.type) {
1284
+ case "progress":
1285
+ emit(message.entries);
1286
+ break;
1287
+ case "call":
1288
+ if (message.method === "workflow") {
1289
+ void handleLoadWorkflow(message.callId, message.payload as WorkflowScriptRef);
1290
+ break;
1291
+ }
1292
+ if (message.method !== "agent") {
1293
+ respond(message.callId, false, undefined, `Unknown workflow host method "${message.method}".`, true);
1294
+ break;
1295
+ }
1296
+ void handleAgent(message.callId, message.payload as AgentCallPayload);
1297
+ break;
1298
+ case "complete": {
1299
+ // The script is done, so every launch it made should have been
1300
+ // answered by now — a response is sent before the worker can post
1301
+ // this, so anything still open was never awaited. finish() aborts
1302
+ // those children on the way out.
1303
+ const unawaited = [...openLaunches.values()];
1304
+ if (unawaited.length > 0) {
1305
+ finish({ status: "failed", error: unawaitedLaunchMessage(unawaited) });
1306
+ break;
1307
+ }
1308
+ finish({
1309
+ status: "completed",
1310
+ ...(message.resultJson === undefined ? {} : { value: JSON.parse(message.resultJson) }),
1311
+ });
1312
+ break;
1313
+ }
1314
+ case "error": {
1315
+ const frames = message.stack?.split("\n")
1316
+ .filter(line => /(?:workflow\.js|workflow:[^\r\n]+?\.js):\d+/.test(line))
1317
+ .slice(0, 3) ?? [];
1318
+ let error = [message.message, ...frames].join("\n");
1319
+ if (!frames[0]?.includes("workflow:") && /Cannot read properties|is not (?:a function|iterable)|expects an array/.test(message.message)) {
1320
+ if (options.args === undefined) {
1321
+ error += "\nNo workflow args were supplied. If this script expects inputs, pass an actual JSON value, e.g. args: { probes: [...] }. Re-pass args when re-running a scriptPath.";
1322
+ } else if (typeof options.args === "string") {
1323
+ error += "\nWorkflow args is a string. If this script expects an object or array, pass the actual JSON value, not a JSON-encoded string, e.g. args: { probes: [...] }. Strings are not automatically parsed.";
1324
+ }
1325
+ }
1326
+ finish({ status: "failed", error });
1327
+ break;
1328
+ }
1329
+ }
1330
+ });
1331
+
1332
+ worker.on("error", error => {
1333
+ finish({ status: "failed", error: error instanceof Error ? error.message : String(error) });
1334
+ });
1335
+
1336
+ worker.on("exit", () => {
1337
+ // Only reachable when the worker dies without reporting — a terminate()
1338
+ // we did not initiate, or a hard crash.
1339
+ finish({ status: "failed", error: "Workflow worker exited before completing." });
1340
+ });
1341
+ });
1342
+ }