@esso0428/pi-subagents 0.17.6 → 0.17.7

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 (260) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/CONTRIBUTING.md +4 -0
  3. package/dist/abortable.d.ts +13 -0
  4. package/dist/abortable.d.ts.map +1 -0
  5. package/dist/abortable.js +43 -0
  6. package/dist/abortable.js.map +1 -0
  7. package/dist/agent-color.d.ts +36 -0
  8. package/dist/agent-color.d.ts.map +1 -0
  9. package/dist/agent-color.js +124 -0
  10. package/dist/agent-color.js.map +1 -0
  11. package/dist/agent-file-toggle.d.ts +126 -0
  12. package/dist/agent-file-toggle.d.ts.map +1 -0
  13. package/dist/agent-file-toggle.js +259 -0
  14. package/dist/agent-file-toggle.js.map +1 -0
  15. package/dist/agent-history.d.ts +4 -0
  16. package/dist/agent-history.d.ts.map +1 -1
  17. package/dist/agent-history.js +47 -1
  18. package/dist/agent-history.js.map +1 -1
  19. package/dist/agent-manager.d.ts +370 -56
  20. package/dist/agent-manager.d.ts.map +1 -1
  21. package/dist/agent-manager.js +1123 -409
  22. package/dist/agent-manager.js.map +1 -1
  23. package/dist/agent-runner.d.ts +100 -10
  24. package/dist/agent-runner.d.ts.map +1 -1
  25. package/dist/agent-runner.js +166 -21
  26. package/dist/agent-runner.js.map +1 -1
  27. package/dist/agent-types.d.ts +57 -5
  28. package/dist/agent-types.d.ts.map +1 -1
  29. package/dist/agent-types.js +164 -32
  30. package/dist/agent-types.js.map +1 -1
  31. package/dist/child-context.d.ts +3 -0
  32. package/dist/child-context.d.ts.map +1 -0
  33. package/dist/child-context.js +13 -0
  34. package/dist/child-context.js.map +1 -0
  35. package/dist/cross-extension-rpc.d.ts +23 -3
  36. package/dist/cross-extension-rpc.d.ts.map +1 -1
  37. package/dist/cross-extension-rpc.js +79 -17
  38. package/dist/cross-extension-rpc.js.map +1 -1
  39. package/dist/custom-agents.d.ts +38 -1
  40. package/dist/custom-agents.d.ts.map +1 -1
  41. package/dist/custom-agents.js +164 -12
  42. package/dist/custom-agents.js.map +1 -1
  43. package/dist/index.d.ts +34 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +1908 -495
  46. package/dist/index.js.map +1 -1
  47. package/dist/invocation-config.d.ts +87 -2
  48. package/dist/invocation-config.d.ts.map +1 -1
  49. package/dist/invocation-config.js +71 -3
  50. package/dist/invocation-config.js.map +1 -1
  51. package/dist/mention-clone.d.ts +88 -0
  52. package/dist/mention-clone.d.ts.map +1 -0
  53. package/dist/mention-clone.js +154 -0
  54. package/dist/mention-clone.js.map +1 -0
  55. package/dist/mention.d.ts +82 -0
  56. package/dist/mention.d.ts.map +1 -0
  57. package/dist/mention.js +132 -0
  58. package/dist/mention.js.map +1 -0
  59. package/dist/model-resolver.d.ts +17 -0
  60. package/dist/model-resolver.d.ts.map +1 -1
  61. package/dist/model-resolver.js +15 -0
  62. package/dist/model-resolver.js.map +1 -1
  63. package/dist/model-scope.d.ts +50 -0
  64. package/dist/model-scope.d.ts.map +1 -0
  65. package/dist/model-scope.js +49 -0
  66. package/dist/model-scope.js.map +1 -0
  67. package/dist/nested-tools.d.ts +57 -0
  68. package/dist/nested-tools.d.ts.map +1 -0
  69. package/dist/nested-tools.js +301 -0
  70. package/dist/nested-tools.js.map +1 -0
  71. package/dist/output-file.d.ts +22 -3
  72. package/dist/output-file.d.ts.map +1 -1
  73. package/dist/output-file.js +58 -7
  74. package/dist/output-file.js.map +1 -1
  75. package/dist/prompts.d.ts +23 -0
  76. package/dist/prompts.d.ts.map +1 -1
  77. package/dist/prompts.js +20 -2
  78. package/dist/prompts.js.map +1 -1
  79. package/dist/schedule.d.ts.map +1 -1
  80. package/dist/schedule.js +36 -15
  81. package/dist/schedule.js.map +1 -1
  82. package/dist/settings.d.ts +228 -2
  83. package/dist/settings.d.ts.map +1 -1
  84. package/dist/settings.js +94 -0
  85. package/dist/settings.js.map +1 -1
  86. package/dist/status-note.d.ts +49 -1
  87. package/dist/status-note.d.ts.map +1 -1
  88. package/dist/status-note.js +62 -1
  89. package/dist/status-note.js.map +1 -1
  90. package/dist/structured-output.d.ts +62 -0
  91. package/dist/structured-output.d.ts.map +1 -0
  92. package/dist/structured-output.js +113 -0
  93. package/dist/structured-output.js.map +1 -0
  94. package/dist/types.d.ts +176 -10
  95. package/dist/types.d.ts.map +1 -1
  96. package/dist/ui/agent-mention.d.ts +83 -0
  97. package/dist/ui/agent-mention.d.ts.map +1 -0
  98. package/dist/ui/agent-mention.js +188 -0
  99. package/dist/ui/agent-mention.js.map +1 -0
  100. package/dist/ui/agent-widget.d.ts +96 -75
  101. package/dist/ui/agent-widget.d.ts.map +1 -1
  102. package/dist/ui/agent-widget.js +397 -420
  103. package/dist/ui/agent-widget.js.map +1 -1
  104. package/dist/ui/conversation-blocks.d.ts.map +1 -1
  105. package/dist/ui/conversation-blocks.js +6 -0
  106. package/dist/ui/conversation-blocks.js.map +1 -1
  107. package/dist/ui/conversation-timeline.d.ts +10 -2
  108. package/dist/ui/conversation-timeline.d.ts.map +1 -1
  109. package/dist/ui/conversation-timeline.js +130 -23
  110. package/dist/ui/conversation-timeline.js.map +1 -1
  111. package/dist/ui/conversation-viewer.d.ts +15 -5
  112. package/dist/ui/conversation-viewer.d.ts.map +1 -1
  113. package/dist/ui/conversation-viewer.js +202 -50
  114. package/dist/ui/conversation-viewer.js.map +1 -1
  115. package/dist/ui/fleet-list.d.ts +198 -0
  116. package/dist/ui/fleet-list.d.ts.map +1 -0
  117. package/dist/ui/fleet-list.js +487 -0
  118. package/dist/ui/fleet-list.js.map +1 -0
  119. package/dist/ui/schedule-menu.d.ts.map +1 -1
  120. package/dist/ui/schedule-menu.js +6 -7
  121. package/dist/ui/schedule-menu.js.map +1 -1
  122. package/dist/ui/select-item.d.ts +28 -0
  123. package/dist/ui/select-item.d.ts.map +1 -0
  124. package/dist/ui/select-item.js +35 -0
  125. package/dist/ui/select-item.js.map +1 -0
  126. package/dist/ui/workflow-card.d.ts +176 -0
  127. package/dist/ui/workflow-card.d.ts.map +1 -0
  128. package/dist/ui/workflow-card.js +333 -0
  129. package/dist/ui/workflow-card.js.map +1 -0
  130. package/dist/ui/workflow-dialog.d.ts +306 -0
  131. package/dist/ui/workflow-dialog.d.ts.map +1 -0
  132. package/dist/ui/workflow-dialog.js +844 -0
  133. package/dist/ui/workflow-dialog.js.map +1 -0
  134. package/dist/ui/workflow-menu.d.ts +61 -0
  135. package/dist/ui/workflow-menu.d.ts.map +1 -0
  136. package/dist/ui/workflow-menu.js +148 -0
  137. package/dist/ui/workflow-menu.js.map +1 -0
  138. package/dist/usage.d.ts +86 -1
  139. package/dist/usage.d.ts.map +1 -1
  140. package/dist/usage.js +72 -1
  141. package/dist/usage.js.map +1 -1
  142. package/dist/workflow/collisions.d.ts +96 -0
  143. package/dist/workflow/collisions.d.ts.map +1 -0
  144. package/dist/workflow/collisions.js +89 -0
  145. package/dist/workflow/collisions.js.map +1 -0
  146. package/dist/workflow/entry.d.ts +33 -0
  147. package/dist/workflow/entry.d.ts.map +1 -0
  148. package/dist/workflow/entry.js +30 -0
  149. package/dist/workflow/entry.js.map +1 -0
  150. package/dist/workflow/host.d.ts +63 -0
  151. package/dist/workflow/host.d.ts.map +1 -0
  152. package/dist/workflow/host.js +363 -0
  153. package/dist/workflow/host.js.map +1 -0
  154. package/dist/workflow/journal.d.ts +98 -0
  155. package/dist/workflow/journal.d.ts.map +1 -0
  156. package/dist/workflow/journal.js +121 -0
  157. package/dist/workflow/journal.js.map +1 -0
  158. package/dist/workflow/json-schema.d.ts +52 -0
  159. package/dist/workflow/json-schema.d.ts.map +1 -0
  160. package/dist/workflow/json-schema.js +112 -0
  161. package/dist/workflow/json-schema.js.map +1 -0
  162. package/dist/workflow/meta.d.ts +68 -0
  163. package/dist/workflow/meta.d.ts.map +1 -0
  164. package/dist/workflow/meta.js +318 -0
  165. package/dist/workflow/meta.js.map +1 -0
  166. package/dist/workflow/progress.d.ts +225 -0
  167. package/dist/workflow/progress.d.ts.map +1 -0
  168. package/dist/workflow/progress.js +362 -0
  169. package/dist/workflow/progress.js.map +1 -0
  170. package/dist/workflow/runtime.d.ts +335 -0
  171. package/dist/workflow/runtime.d.ts.map +1 -0
  172. package/dist/workflow/runtime.js +831 -0
  173. package/dist/workflow/runtime.js.map +1 -0
  174. package/dist/workflow/saved.d.ts +91 -0
  175. package/dist/workflow/saved.d.ts.map +1 -0
  176. package/dist/workflow/saved.js +204 -0
  177. package/dist/workflow/saved.js.map +1 -0
  178. package/dist/workflow/task.d.ts +137 -0
  179. package/dist/workflow/task.d.ts.map +1 -0
  180. package/dist/workflow/task.js +208 -0
  181. package/dist/workflow/task.js.map +1 -0
  182. package/dist/workflow/tool-description.d.ts +39 -0
  183. package/dist/workflow/tool-description.d.ts.map +1 -0
  184. package/dist/workflow/tool-description.js +200 -0
  185. package/dist/workflow/tool-description.js.map +1 -0
  186. package/dist/workflow/worker-source.d.ts +48 -0
  187. package/dist/workflow/worker-source.d.ts.map +1 -0
  188. package/dist/workflow/worker-source.js +779 -0
  189. package/dist/workflow/worker-source.js.map +1 -0
  190. package/dist/worktree.d.ts +10 -3
  191. package/dist/worktree.d.ts.map +1 -1
  192. package/dist/worktree.js +58 -54
  193. package/dist/worktree.js.map +1 -1
  194. package/dist/xml.d.ts +11 -0
  195. package/dist/xml.d.ts.map +1 -0
  196. package/dist/xml.js +13 -0
  197. package/dist/xml.js.map +1 -0
  198. package/docs/rpc.md +183 -0
  199. package/docs/superpowers/plans/2026-09-30-upstream-event-workflow-partial-history.md +195 -0
  200. package/docs/superpowers/specs/2026-09-30-upstream-event-workflow-partial-history-design.md +49 -0
  201. package/docs/workflows.md +437 -0
  202. package/examples/agent-tool-description.md +7 -7
  203. package/examples/workflows/compose.js +51 -0
  204. package/examples/workflows/fan-out-audit.js +47 -0
  205. package/examples/workflows/gated-fix.js +60 -0
  206. package/examples/workflows/lib/count-child.js +27 -0
  207. package/examples/workflows/review-panel.js +63 -0
  208. package/examples/workflows/structured-findings.js +78 -0
  209. package/package.json +1 -1
  210. package/src/abortable.ts +43 -0
  211. package/src/agent-color.ts +161 -0
  212. package/src/agent-file-toggle.ts +269 -0
  213. package/src/agent-history.ts +54 -2
  214. package/src/agent-manager.ts +1263 -402
  215. package/src/agent-runner.ts +251 -27
  216. package/src/agent-types.ts +188 -32
  217. package/src/child-context.ts +15 -0
  218. package/src/cross-extension-rpc.ts +96 -20
  219. package/src/custom-agents.ts +170 -13
  220. package/src/index.ts +2024 -537
  221. package/src/invocation-config.ts +118 -3
  222. package/src/mention-clone.ts +196 -0
  223. package/src/mention.ts +141 -0
  224. package/src/model-resolver.ts +18 -0
  225. package/src/model-scope.ts +70 -0
  226. package/src/nested-tools.ts +424 -0
  227. package/src/output-file.ts +61 -6
  228. package/src/prompts.ts +45 -2
  229. package/src/schedule.ts +35 -14
  230. package/src/settings.ts +312 -2
  231. package/src/status-note.ts +66 -1
  232. package/src/structured-output.ts +130 -0
  233. package/src/types.ts +177 -10
  234. package/src/ui/agent-mention.ts +216 -0
  235. package/src/ui/agent-widget.ts +389 -441
  236. package/src/ui/conversation-blocks.ts +6 -0
  237. package/src/ui/conversation-timeline.ts +139 -25
  238. package/src/ui/conversation-viewer.ts +212 -48
  239. package/src/ui/fleet-list.ts +558 -0
  240. package/src/ui/schedule-menu.ts +9 -8
  241. package/src/ui/select-item.ts +45 -0
  242. package/src/ui/workflow-card.ts +470 -0
  243. package/src/ui/workflow-dialog.ts +1115 -0
  244. package/src/ui/workflow-menu.ts +193 -0
  245. package/src/usage.ts +109 -2
  246. package/src/workflow/collisions.ts +123 -0
  247. package/src/workflow/entry.ts +47 -0
  248. package/src/workflow/host.ts +403 -0
  249. package/src/workflow/journal.ts +164 -0
  250. package/src/workflow/json-schema.ts +128 -0
  251. package/src/workflow/meta.ts +325 -0
  252. package/src/workflow/progress.ts +550 -0
  253. package/src/workflow/runtime.ts +1219 -0
  254. package/src/workflow/saved.ts +217 -0
  255. package/src/workflow/task.ts +302 -0
  256. package/src/workflow/tool-description.ts +200 -0
  257. package/src/workflow/worker-source.ts +781 -0
  258. package/src/worktree.ts +69 -55
  259. package/src/xml.ts +13 -0
  260. package/vitest.config.ts +0 -18
@@ -0,0 +1,831 @@
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
+ import { cpus } from "node:os";
16
+ import { Worker } from "node:worker_threads";
17
+ import { journalKey } from "./journal.js";
18
+ import { compileJsonSchema } from "./json-schema.js";
19
+ import { extractMeta } from "./meta.js";
20
+ import { WORKER_SOURCE } from "./worker-source.js";
21
+ /** Matches the `script` field's `maxLength` in the tool schema. */
22
+ export const MAX_SCRIPT_LENGTH = 524_288;
23
+ /** Agents one run may schedule, in total. */
24
+ export const WORKFLOW_AGENT_CAP = 1000;
25
+ /** Items one `parallel()` or `pipeline()` call may take. */
26
+ export const WORKFLOW_ITEM_CAP = 4096;
27
+ /** Nested `workflow()` invocations allowed per run. */
28
+ export const WORKFLOW_NESTED_CAP = 256;
29
+ /** How much of a prompt or result is kept for the UI. */
30
+ const PREVIEW_LENGTH = 200;
31
+ export class WorkflowRuntimeError extends Error {
32
+ }
33
+ /**
34
+ * Concurrent agents allowed, leaving two cores for the host and the TUI.
35
+ *
36
+ * `Math.max(1, …)` is not decoration: the raw `min(16, cpus - 2)` is 0 on a one-
37
+ * or two-core machine, and a semaphore with zero permits never hands out a slot,
38
+ * so the run would hang before its first agent rather than fail.
39
+ */
40
+ export function workflowConcurrency(cpuCount = cpus().length) {
41
+ return Math.max(1, Math.min(16, cpuCount - 2));
42
+ }
43
+ /* ------------------------------------------------------------------------- *
44
+ * JSON boundary — host side
45
+ * ------------------------------------------------------------------------- */
46
+ function boundaryError(what, path) {
47
+ return new WorkflowRuntimeError(`Cannot pass ${what} across the workflow VM boundary (at ${path}).`);
48
+ }
49
+ function walk(value, path, seen) {
50
+ if (value === null)
51
+ return;
52
+ const kind = typeof value;
53
+ if (kind === "string" || kind === "boolean")
54
+ return;
55
+ if (kind === "number") {
56
+ if (!Number.isFinite(value))
57
+ throw boundaryError("a non-finite number", path);
58
+ return;
59
+ }
60
+ if (kind === "undefined") {
61
+ if (path === "args")
62
+ return;
63
+ throw boundaryError("undefined", path);
64
+ }
65
+ if (kind === "bigint")
66
+ throw boundaryError("a BigInt", path);
67
+ if (kind === "symbol")
68
+ throw boundaryError("a symbol", path);
69
+ if (kind === "function")
70
+ throw boundaryError("a function", path);
71
+ if (kind !== "object")
72
+ throw boundaryError(`a ${kind}`, path);
73
+ const object = value;
74
+ if (seen.has(object))
75
+ throw boundaryError("a circular structure", path);
76
+ seen.add(object);
77
+ if (Object.getOwnPropertySymbols(object).length > 0) {
78
+ throw boundaryError("an object with symbol keys", path);
79
+ }
80
+ if (Array.isArray(object)) {
81
+ for (let i = 0; i < object.length; i++) {
82
+ if (!Object.hasOwn(object, i))
83
+ throw boundaryError("a sparse array", `${path}[${i}]`);
84
+ walk(object[i], `${path}[${i}]`, seen);
85
+ }
86
+ seen.delete(object);
87
+ return;
88
+ }
89
+ const prototype = Object.getPrototypeOf(object);
90
+ if (prototype !== null && prototype !== Object.prototype) {
91
+ throw boundaryError("a non-plain object", path);
92
+ }
93
+ for (const [key, entry] of Object.entries(object)) {
94
+ walk(entry, `${path}.${key}`, seen);
95
+ }
96
+ seen.delete(object);
97
+ }
98
+ /**
99
+ * Reject anything that cannot survive the round trip to the worker and into a
100
+ * resume journal. Structured clone would happily carry a `Map` or a cycle that
101
+ * the journal then cannot represent, so the check is stricter than the transport.
102
+ */
103
+ export function assertBoundarySafe(value, path) {
104
+ walk(value, path, new Set());
105
+ }
106
+ /* ------------------------------------------------------------------------- *
107
+ * Semaphore
108
+ * ------------------------------------------------------------------------- */
109
+ class Semaphore {
110
+ limit;
111
+ active = 0;
112
+ waiters = [];
113
+ constructor(limit) {
114
+ this.limit = limit;
115
+ }
116
+ acquire() {
117
+ if (this.active < this.limit) {
118
+ this.active++;
119
+ return Promise.resolve();
120
+ }
121
+ return new Promise(resolve => {
122
+ this.waiters.push(resolve);
123
+ });
124
+ }
125
+ release() {
126
+ const next = this.waiters.shift();
127
+ // Hand the permit straight over rather than decrementing and re-acquiring;
128
+ // otherwise a burst of releases can let more than `limit` through.
129
+ if (next)
130
+ next();
131
+ else
132
+ this.active--;
133
+ }
134
+ /** Wake everyone so aborted callers can observe the abort and bail. */
135
+ drain() {
136
+ while (this.waiters.length > 0) {
137
+ const next = this.waiters.shift();
138
+ next?.();
139
+ }
140
+ }
141
+ }
142
+ /** Everything below 0x20 except tab, newline and carriage return, plus DEL. */
143
+ const CONTROL_CHARACTERS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/;
144
+ const preview = (text) => text.length <= PREVIEW_LENGTH ? text : `${text.slice(0, PREVIEW_LENGTH - 1)}…`;
145
+ /** First line of the prompt, trimmed — the fallback display name for an agent. */
146
+ function derivedLabel(prompt) {
147
+ const line = prompt.split("\n", 1)[0].trim();
148
+ return line.length <= 60 ? line || "agent" : `${line.slice(0, 59)}…`;
149
+ }
150
+ /**
151
+ * Turn a failing gate into a failing agent.
152
+ *
153
+ * Deliberately no new state, no new entry type: a gated agent whose command
154
+ * fails is *a failed agent*, so the card, the dialog and `agent()`'s `null`
155
+ * return all handle it with the code they already have. The command output
156
+ * becomes the error, because that is the thing worth reading.
157
+ *
158
+ * The single place that decides whether a gate passed. The command may have
159
+ * been run by the host instead (inside a worktree that no longer exists by
160
+ * now), but only ever by one of the two: a host that ran it says so with
161
+ * `result.gate`, and this then shapes that outcome rather than running it
162
+ * again.
163
+ */
164
+ /**
165
+ * Hold a schema'd result to its schema, host-side.
166
+ *
167
+ * The child's own tool already validated whatever it passed, so this normally
168
+ * agrees. It exists for the cases where nothing did: a host that ignores
169
+ * `schema` entirely, a replayed journal entry from before the schema changed,
170
+ * or a payload that reached us some other way. The script asked for a shape;
171
+ * exactly one place should be able to promise it.
172
+ */
173
+ function applySchema(result, compiled) {
174
+ let parsed;
175
+ try {
176
+ parsed = JSON.parse(result.text ?? "");
177
+ }
178
+ catch {
179
+ return {
180
+ ...result,
181
+ ok: false,
182
+ error: "The agent did not return structured output: its answer was not JSON.",
183
+ };
184
+ }
185
+ const verdict = compiled.check(parsed);
186
+ if (verdict === true)
187
+ return result;
188
+ return {
189
+ ...result,
190
+ ok: false,
191
+ error: `The agent's answer did not match the requested schema: ${verdict}`,
192
+ };
193
+ }
194
+ async function applyGate(result, command, agentId, runGate) {
195
+ const outcome = result.gate ??
196
+ (await runGate(command, {
197
+ agentId,
198
+ // Where the child worked, when it had a worktree of its own. Gating the
199
+ // main tree instead would verify code the child never touched.
200
+ ...(result.cwd !== undefined ? { cwd: result.cwd } : {}),
201
+ }));
202
+ const { gate: _ran, ...kept } = result;
203
+ if (outcome.ok)
204
+ return kept;
205
+ const { text: _discarded, ...rest } = kept;
206
+ const output = outcome.output.trim();
207
+ return { ...rest, ok: false, error: output === "" ? `Gate command failed: ${command}` : output };
208
+ }
209
+ /**
210
+ * Nico's wording, kept verbatim — this is the one borrowed check whose message a
211
+ * user is likely to search for.
212
+ */
213
+ function unawaitedLaunchMessage(labels) {
214
+ const list = labels.map(label => `'${label}'`).join(", ");
215
+ return `workflow script completed with unawaited agent launch(es): ${list}. Await or return each launch.`;
216
+ }
217
+ /**
218
+ * Run one workflow script to completion.
219
+ *
220
+ * Rejects before starting for a script that cannot run at all (bad `meta`, over
221
+ * the size limit, control characters, non-JSON `args`). Everything after the
222
+ * worker is live resolves instead, carrying the failure in `status` — by then
223
+ * there is a progress log worth handing back.
224
+ */
225
+ /**
226
+ * Everything a script must satisfy before it is compiled.
227
+ *
228
+ * Extracted so a nested `workflow()` is held to exactly the same standard as a
229
+ * top-level run: same size limit, same character rules, same `meta` contract.
230
+ * The host resolves a reference to source; deciding whether that source is a
231
+ * workflow stays here, where the rules live.
232
+ */
233
+ export function validateScript(script) {
234
+ if (script.length > MAX_SCRIPT_LENGTH) {
235
+ throw new WorkflowRuntimeError(`Workflow script is ${script.length} characters, over the limit of ${MAX_SCRIPT_LENGTH}.`);
236
+ }
237
+ if (CONTROL_CHARACTERS.test(script)) {
238
+ throw new WorkflowRuntimeError("Workflow script contains control characters. Only tab, carriage return and newline are allowed.");
239
+ }
240
+ return extractMeta(script);
241
+ }
242
+ export async function runWorkflow(options) {
243
+ const { script, host } = options;
244
+ assertBoundarySafe(options.args, "args");
245
+ const { meta, body } = validateScript(script);
246
+ const agentCap = options.agentCap ?? WORKFLOW_AGENT_CAP;
247
+ const itemCap = options.itemCap ?? WORKFLOW_ITEM_CAP;
248
+ const semaphore = new Semaphore(options.concurrency ?? workflowConcurrency());
249
+ const progress = [];
250
+ const inflight = new Set();
251
+ /** Label → the child that ran under it, last one wins. The `resume` handle. */
252
+ const completedByLabel = new Map();
253
+ /**
254
+ * Launches the host has accepted and not yet answered, in call order.
255
+ *
256
+ * This is the whole unawaited-launch mechanism: a script that drops an
257
+ * `agent()` promise still gets its call answered eventually, but it returns
258
+ * first — so anything left here when `complete` arrives is a result nobody is
259
+ * waiting for. Tracking it host-side avoids proxying `Promise` inside the
260
+ * realm, which §2.4 rules out, and reading stack traces, which is brittle.
261
+ */
262
+ const openLaunches = new Map();
263
+ let agentCount = 0;
264
+ let aborted = false;
265
+ let settled = false;
266
+ /* --- resume state ---------------------------------------------------- */
267
+ const journalEntries = options.journal?.entries ?? [];
268
+ const recordJournal = options.journal?.append;
269
+ /**
270
+ * Whether the replayable prefix is still intact.
271
+ *
272
+ * Once a position misses — different key, a journaled failure, or nothing
273
+ * recorded there — every later call runs live, however well it matches.
274
+ * See the header of journal.ts for why this is a prefix and not a lookup.
275
+ */
276
+ // A journal from a run that used `agent({ resume })` is declined whole: see
277
+ // journal.ts on why a replayed agent leaves nothing for a later resume to
278
+ // continue. Declining up front beats stranding the first `resume` call
279
+ // partway through a run that has already spent its cheap half.
280
+ const journalResumes = journalEntries.some(entry => entry.resumed);
281
+ let prefixIntact = journalEntries.length > 0 && !journalResumes;
282
+ let replayedCount = 0;
283
+ const liveAgents = new Map();
284
+ /**
285
+ * Output tokens this run has spent, mirrored to the script as
286
+ * `budget.spent()`.
287
+ *
288
+ * The host owns the number and every response carries it, rather than the
289
+ * worker accumulating its own: two counters would drift, and there is nothing
290
+ * to gain from the second one. Nor is there observable staleness — tokens
291
+ * only accrue through agents, and the script only learns anything through
292
+ * agent responses.
293
+ */
294
+ let spentOutputTokens = 0;
295
+ let paused = false;
296
+ /** Read through a call for the same reason `intent()` is — see below. */
297
+ const isPaused = () => paused;
298
+ const pauseWaiters = new Set();
299
+ /** Release everyone held at a pause — on resume, and on the way out. */
300
+ function releasePause() {
301
+ for (const wake of [...pauseWaiters])
302
+ wake();
303
+ pauseWaiters.clear();
304
+ }
305
+ /** Park here while the run is paused, so no new agent is started. */
306
+ function pauseGate(live) {
307
+ if (!paused || aborted || settled)
308
+ return Promise.resolve();
309
+ return new Promise(resolve => {
310
+ const wake = () => {
311
+ pauseWaiters.delete(wake);
312
+ live.wake = undefined;
313
+ resolve();
314
+ };
315
+ live.wake = wake;
316
+ pauseWaiters.add(wake);
317
+ });
318
+ }
319
+ options.onControl?.({
320
+ pause: () => { paused = true; },
321
+ resume: () => { paused = false; releasePause(); },
322
+ isPaused: () => paused,
323
+ skip: index => {
324
+ const live = liveAgents.get(index);
325
+ if (live === undefined || live.intent !== undefined)
326
+ return false;
327
+ live.intent = "skip";
328
+ // A running child is stopped, which comes back as a skipped result; a
329
+ // held one is woken so it can bail at the gate it is parked on.
330
+ if (live.started)
331
+ host.abortAgent(live.agentId);
332
+ else
333
+ live.wake?.();
334
+ return true;
335
+ },
336
+ retry: index => {
337
+ const live = liveAgents.get(index);
338
+ if (live === undefined || !live.started || live.intent !== undefined)
339
+ return false;
340
+ live.intent = "retry";
341
+ host.abortAgent(live.agentId);
342
+ return true;
343
+ },
344
+ });
345
+ /** The journal entry to reuse at `index`, or undefined to run it live. */
346
+ function replayAt(index, key) {
347
+ if (!prefixIntact)
348
+ return undefined;
349
+ const entry = journalEntries[index];
350
+ if (entry === undefined || entry.index !== index || entry.key !== key || !entry.ok) {
351
+ prefixIntact = false;
352
+ return undefined;
353
+ }
354
+ return entry;
355
+ }
356
+ const worker = new Worker(WORKER_SOURCE, {
357
+ eval: true,
358
+ workerData: {
359
+ body,
360
+ metaJson: JSON.stringify(meta),
361
+ argsJson: options.args === undefined ? undefined : JSON.stringify(options.args),
362
+ itemCap,
363
+ nestedCap: options.nestedCap ?? WORKFLOW_NESTED_CAP,
364
+ },
365
+ });
366
+ return await new Promise(resolve => {
367
+ const emit = (entries) => {
368
+ if (entries.length === 0)
369
+ return;
370
+ progress.push(...entries);
371
+ options.onProgress?.(entries);
372
+ };
373
+ const respond = (callId, ok, value, error, fatal) => {
374
+ // Cleared before the settled check: a launch answered by a run that is
375
+ // already finishing is not an unawaited launch either.
376
+ openLaunches.delete(callId);
377
+ if (settled)
378
+ return;
379
+ // `spent` rides on every response, so the worker's `budget.spent()` is a
380
+ // mirror of this number rather than a second tally of its own.
381
+ worker.postMessage({ type: "response", callId, ok, value, error, fatal, spent: spentOutputTokens });
382
+ };
383
+ const finish = (result) => {
384
+ if (settled)
385
+ return;
386
+ settled = true;
387
+ options.signal?.removeEventListener("abort", onAbort);
388
+ // Symmetric with `semaphore.drain()` below: everything parked is woken so
389
+ // it observes the settle and unwinds. Nothing depends on it — the run's
390
+ // promise resolves either way — it just does not leave live-agent
391
+ // bookkeeping behind for a run that is over.
392
+ releasePause();
393
+ for (const agentId of inflight)
394
+ host.abortAgent(agentId);
395
+ inflight.clear();
396
+ semaphore.drain();
397
+ // Resolve only once the thread is actually down, so a caller that awaits
398
+ // runWorkflow() is guaranteed not to be leaking one.
399
+ const settle = () => resolve({ ...result, meta, progress, agentCount, replayedCount });
400
+ void worker.terminate().then(settle, settle);
401
+ };
402
+ function onAbort() {
403
+ aborted = true;
404
+ // terminate() is why this runs in a worker at all: it stops a script that
405
+ // is spinning or wedged mid-await, which an in-process vm cannot do.
406
+ finish({ status: "killed", error: "Workflow aborted." });
407
+ }
408
+ if (options.signal) {
409
+ if (options.signal.aborted) {
410
+ onAbort();
411
+ return;
412
+ }
413
+ options.signal.addEventListener("abort", onAbort, { once: true });
414
+ }
415
+ async function handleAgent(callId, payload) {
416
+ // Bound now: the optional methods are checked once, up front, so a
417
+ // capability the host lacks fails before an agent is spawned rather than
418
+ // after — a gate that never ran must not be mistaken for a gate that
419
+ // passed.
420
+ const runGate = host.runGate?.bind(host);
421
+ const resumeAgent = host.resumeAgent?.bind(host);
422
+ if (payload.gate !== undefined && runGate === undefined) {
423
+ respond(callId, false, undefined, "This workflow host cannot run gate commands.", true);
424
+ return;
425
+ }
426
+ if (payload.resume !== undefined && resumeAgent === undefined) {
427
+ respond(callId, false, undefined, "This workflow host cannot resume agents.", true);
428
+ return;
429
+ }
430
+ let resumed;
431
+ if (payload.resume !== undefined) {
432
+ resumed = completedByLabel.get(payload.resume);
433
+ if (resumed === undefined) {
434
+ const known = [...completedByLabel.keys()];
435
+ // Fatal: a typo'd label is a script bug, and folding it into a null
436
+ // would show up as an agent that mysteriously returned nothing.
437
+ //
438
+ // Unless agents were replayed, in which case it is not a script bug
439
+ // at all — the label's child came back from the journal and has no
440
+ // conversation here to continue. Saying "no agent has completed"
441
+ // would send the reader hunting for a typo that is not there.
442
+ respond(callId, false, undefined, replayedCount > 0 ?
443
+ `agent() opts.resume: "${payload.resume}" was replayed from the resume journal, not run, so there is ` +
444
+ "no conversation in this run to continue. Re-run without resumeFromRunId."
445
+ : `agent() opts.resume: no agent has completed under the label "${payload.resume}" in this run. ${known.length === 0
446
+ ? "No agent has completed yet."
447
+ : `Known labels: ${known.map(label => `"${label}"`).join(", ")}.`}`, true);
448
+ return;
449
+ }
450
+ }
451
+ // Compiled before anything is scheduled. A schema the runtime cannot use
452
+ // is a script bug, so it is fatal like a typo'd resume label — folding it
453
+ // into a null would surface as an agent that mysteriously returned
454
+ // nothing, and it costs no model call to say so here.
455
+ let compiledSchema;
456
+ if (payload.schema !== undefined) {
457
+ const compilation = compileJsonSchema(payload.schema);
458
+ if (!compilation.ok) {
459
+ respond(callId, false, undefined, compilation.message, true);
460
+ return;
461
+ }
462
+ compiledSchema = compilation.compiled;
463
+ }
464
+ if (agentCount >= agentCap) {
465
+ // Fatal, so parallel()/pipeline() rethrow instead of folding it into a
466
+ // null. A cap that silently drops work is worse than no cap.
467
+ respond(callId, false, undefined, `Workflow exceeded its cap of ${agentCap} agents.`, true);
468
+ return;
469
+ }
470
+ const index = agentCount++;
471
+ // A resumed call is the same child again: it keeps the agent id, so an
472
+ // abort still reaches it, and it keeps its spawn contract, so the row
473
+ // reads the same as the row it continues.
474
+ const agentId = resumed?.agentId ?? `wf-agent-${index}`;
475
+ const label = payload.label ?? resumed?.label ?? derivedLabel(payload.prompt);
476
+ const agentType = resumed?.agentType ?? payload.agentType ?? "general-purpose";
477
+ const model = resumed !== undefined ? resumed.model : payload.model;
478
+ const isolation = resumed !== undefined ? resumed.isolation : payload.isolation;
479
+ openLaunches.set(callId, label);
480
+ const base = {
481
+ type: "workflow_agent",
482
+ index,
483
+ label,
484
+ state: "start",
485
+ agentId,
486
+ agentType,
487
+ promptPreview: preview(payload.prompt),
488
+ ...(model !== undefined ? { model } : {}),
489
+ ...(isolation !== undefined ? { isolation } : {}),
490
+ ...(payload.phaseIndex !== undefined ? { phaseIndex: payload.phaseIndex } : {}),
491
+ ...(payload.phaseTitle !== undefined ? { phaseTitle: payload.phaseTitle } : {}),
492
+ };
493
+ const queuedAt = Date.now();
494
+ emit([{ ...base, queuedAt }]);
495
+ // Replay before the semaphore, not after: a cached answer is not model
496
+ // running, so it must not hold a concurrency slot that a live agent
497
+ // could use. The row still appears in the tree — the run reads as the
498
+ // same shape it had the first time, just faster.
499
+ // The payload's `schema` is the raw object; the key wants it serialized,
500
+ // so the spread is narrowed rather than passed through.
501
+ const keyInput = {
502
+ ...payload,
503
+ schema: payload.schema !== undefined ? JSON.stringify(payload.schema) : undefined,
504
+ };
505
+ let replayed = replayAt(index, journalKey(keyInput));
506
+ // A replayed answer still has to satisfy the schema. The key covers a
507
+ // schema that *changed*, but not a journal that was hand-edited, and not
508
+ // the empty text a torn entry leaves behind — either would hand the
509
+ // script a null from an entry the journal claims succeeded.
510
+ if (replayed !== undefined && compiledSchema !== undefined) {
511
+ const recheck = applySchema({ ok: true, text: replayed.text ?? "" }, compiledSchema);
512
+ if (!recheck.ok) {
513
+ prefixIntact = false;
514
+ replayed = undefined;
515
+ }
516
+ }
517
+ if (replayed !== undefined) {
518
+ replayedCount++;
519
+ const replayedText = replayed.text ?? "";
520
+ const at = Date.now();
521
+ emit([
522
+ {
523
+ ...base,
524
+ queuedAt,
525
+ startedAt: at,
526
+ lastProgressAt: at,
527
+ durationMs: 0,
528
+ state: "done",
529
+ // The row reads as done, because it is — `cached` is what tells the
530
+ // dialog to annotate it "from resume journal" rather than letting a
531
+ // 0ms agent look like one that did the work impossibly fast.
532
+ cached: true,
533
+ resultPreview: preview(replayedText),
534
+ },
535
+ ]);
536
+ openLaunches.delete(callId);
537
+ // Re-recorded so this run's journal is complete on its own terms: a
538
+ // resume of a resume must not have to walk back through a chain of
539
+ // earlier files to find the prefix.
540
+ recordJournal?.({ index, key: replayed.key, ok: true, text: replayedText });
541
+ respond(callId, true, replayedText);
542
+ return;
543
+ }
544
+ const key = journalKey(keyInput);
545
+ const resumeMark = payload.resume !== undefined ? { resumed: true } : {};
546
+ /** A skip the user asked for, before the child ever started. */
547
+ const settleSkipped = (extra) => {
548
+ recordJournal?.({ index, key, ok: false, ...resumeMark });
549
+ emit([{ ...base, queuedAt, ...extra, state: "error", skipped: true, error: "Skipped by user." }]);
550
+ // `null`, exactly as a terminal failure gives — a skipped agent is one
551
+ // the script's `.filter(Boolean)` was already written to survive.
552
+ respond(callId, true, null);
553
+ };
554
+ // Registered for exactly as long as the call is unanswered, which is the
555
+ // window in which skip and retry mean anything.
556
+ const live = { agentId, started: false };
557
+ liveAgents.set(index, live);
558
+ // Read through a call, not off the field: `intent` is set from outside
559
+ // this function while it is suspended at an await, so control-flow
560
+ // narrowing across the awaits would be reasoning about a value that has
561
+ // since changed.
562
+ const intent = () => live.intent;
563
+ let attempt = 1;
564
+ try {
565
+ for (;;) {
566
+ // Held before the slot, not after: a paused run must not sit on
567
+ // concurrency it is not using while its running agents drain.
568
+ await pauseGate(live);
569
+ if (intent() === "skip")
570
+ return settleSkipped({});
571
+ // A resumed agent waits its turn like any other: it is the same amount of
572
+ // model running at once.
573
+ await semaphore.acquire();
574
+ if (aborted || settled) {
575
+ semaphore.release();
576
+ respond(callId, false, undefined, "Workflow aborted.", true);
577
+ return;
578
+ }
579
+ // Paused while parked behind the limit: this agent was waiting for a
580
+ // permit when the pause landed, so it never passed the gate above.
581
+ // Hand the permit back and go wait at the gate like everything else,
582
+ // or a pause would leak exactly as many agents as were queued.
583
+ if (isPaused() && !aborted && !settled) {
584
+ semaphore.release();
585
+ continue;
586
+ }
587
+ // Skipped while parked behind the limit: the permit arrived, and the
588
+ // only thing left to do with it is give it back.
589
+ if (intent() === "skip") {
590
+ semaphore.release();
591
+ return settleSkipped({});
592
+ }
593
+ // Carried on every emit from here on, so a retried row keeps saying
594
+ // why it is on its second attempt instead of losing it to the next
595
+ // progress update.
596
+ const attemptMark = attempt > 1 ? { attempt, lastAttemptReason: "user-retry" } : {};
597
+ const startedAt = Date.now();
598
+ emit([{ ...base, queuedAt, startedAt, ...attemptMark }]);
599
+ // Mutates `base` rather than emitting a standalone patch: every later
600
+ // emit spreads it, so the settle path carries the effective values
601
+ // without knowing they were ever corrected. Re-emitting under the
602
+ // same `index` is what the append-only, last-write-wins progress log
603
+ // is for — the row updates in place while the agent is still running.
604
+ const onResolved = (info) => {
605
+ if (info.recordId !== undefined)
606
+ base.recordId = info.recordId;
607
+ if (info.modelName !== undefined)
608
+ base.model = info.modelName;
609
+ if (info.modelId !== undefined)
610
+ base.modelId = info.modelId;
611
+ if (info.thinking !== undefined)
612
+ base.thinking = info.thinking;
613
+ if (info.requestedThinking !== undefined)
614
+ base.requestedThinking = info.requestedThinking;
615
+ if (info.requestedModel !== undefined)
616
+ base.requestedModel = info.requestedModel;
617
+ // `base.state` is still "start", so emitting after the row reached a
618
+ // terminal state would revert it to running under last-write-wins.
619
+ // Not reachable from this repo's host, which reports during startup
620
+ // — but this is the host boundary, and every other promise it makes
621
+ // is checked rather than trusted.
622
+ if (!inflight.has(agentId))
623
+ return;
624
+ emit([{ ...base, queuedAt, startedAt, ...attemptMark, lastProgressAt: Date.now() }]);
625
+ };
626
+ live.started = true;
627
+ inflight.add(agentId);
628
+ let result;
629
+ try {
630
+ result =
631
+ resumed !== undefined && resumeAgent !== undefined
632
+ ? await resumeAgent(resumed.agentId, payload.prompt, onResolved)
633
+ : await host.spawnAgent({
634
+ agentId,
635
+ index,
636
+ prompt: payload.prompt,
637
+ label,
638
+ agentType,
639
+ ...(model !== undefined ? { model } : {}),
640
+ ...(payload.effort !== undefined ? { effort: payload.effort } : {}),
641
+ ...(compiledSchema !== undefined ? { schema: compiledSchema } : {}),
642
+ ...(isolation !== undefined ? { isolation } : {}),
643
+ ...(payload.phaseIndex !== undefined ? { phaseIndex: payload.phaseIndex } : {}),
644
+ ...(payload.phaseTitle !== undefined ? { phaseTitle: payload.phaseTitle } : {}),
645
+ // Offered, not delegated: a host that can run it inside the
646
+ // child's worktree does, and hands back `result.gate`.
647
+ ...(payload.gate !== undefined ? { gate: payload.gate } : {}),
648
+ onResolved,
649
+ });
650
+ if (result.ok) {
651
+ // Recorded before the gate runs: the child itself finished, so it is
652
+ // resumable even when its gate rejects the work — "here is what the
653
+ // gate said, fix it" is the loop this exists for.
654
+ completedByLabel.set(label, {
655
+ agentId,
656
+ label,
657
+ agentType,
658
+ ...(model !== undefined ? { model } : {}),
659
+ ...(isolation !== undefined ? { isolation } : {}),
660
+ });
661
+ // Re-checked here, not just in the child's tool: this is the one
662
+ // place that decides the script's value matches the schema it
663
+ // asked for, so a host that ignored `schema` fails loudly instead
664
+ // of handing the script prose. Before the gate, because a gate
665
+ // verifies work and there is no work to verify if the shape is
666
+ // wrong — and the reader should see the schema error, not a gate
667
+ // error standing in front of it.
668
+ if (compiledSchema !== undefined && result.ok) {
669
+ result = applySchema(result, compiledSchema);
670
+ }
671
+ if (result.ok && payload.gate !== undefined && runGate !== undefined) {
672
+ result = await applyGate(result, payload.gate, agentId, runGate);
673
+ }
674
+ }
675
+ }
676
+ catch (error) {
677
+ result = { ok: false, error: error instanceof Error ? error.message : String(error) };
678
+ }
679
+ finally {
680
+ inflight.delete(agentId);
681
+ live.started = false;
682
+ semaphore.release();
683
+ }
684
+ if (settled)
685
+ return;
686
+ // The stop that produced this result was ours, so run the same call
687
+ // again rather than reporting it. The script is still awaiting this
688
+ // `agent()`, which is the only reason a retry can mean anything.
689
+ if (intent() === "retry" && !aborted) {
690
+ live.intent = undefined;
691
+ attempt++;
692
+ emit([{ ...base, queuedAt, attempt, lastAttemptReason: "user-retry" }]);
693
+ continue;
694
+ }
695
+ // Counted before the response is sent, so the very call that spent
696
+ // them already sees them in `budget.spent()`. Failed and skipped
697
+ // agents count too — they burned the tokens either way.
698
+ spentOutputTokens += result.outputTokens ?? 0;
699
+ const finishedAt = Date.now();
700
+ const common = {
701
+ ...base,
702
+ queuedAt,
703
+ startedAt,
704
+ ...attemptMark,
705
+ lastProgressAt: finishedAt,
706
+ durationMs: finishedAt - startedAt,
707
+ ...(result.tokens !== undefined ? { tokens: result.tokens } : {}),
708
+ ...(result.toolCalls !== undefined ? { toolCalls: result.toolCalls } : {}),
709
+ };
710
+ if (result.ok) {
711
+ const text = result.text ?? "";
712
+ emit([{ ...common, state: "done", resultPreview: preview(text) }]);
713
+ recordJournal?.({ index, key, ok: true, text, ...resumeMark });
714
+ respond(callId, true, text);
715
+ return;
716
+ }
717
+ // Recorded as a failure rather than left out: a gap would be read as an
718
+ // unchanged prefix on the next resume, silently skipping the retry this
719
+ // whole mechanism exists to make cheap.
720
+ recordJournal?.({ index, key, ok: false, ...resumeMark });
721
+ // A dead agent is a null in the script, not a thrown error: Claude Code
722
+ // scripts .filter(Boolean) rather than try/catch around every call.
723
+ emit([
724
+ {
725
+ ...common,
726
+ state: "error",
727
+ // A user skip reaches here as a stopped child, which the host
728
+ // already reports as skipped — the flag is taken from the result
729
+ // rather than from the intent so an abort mid-skip still reads
730
+ // as whatever actually happened to the child.
731
+ error: result.error ?? "Agent failed.",
732
+ ...(result.skipped ? { skipped: true } : {}),
733
+ },
734
+ ]);
735
+ respond(callId, true, null);
736
+ return;
737
+ }
738
+ }
739
+ finally {
740
+ liveAgents.delete(index);
741
+ }
742
+ }
743
+ /**
744
+ * Resolve one `workflow(ref)` and hand the child's source back compiled.
745
+ *
746
+ * Resolution failures are non-fatal — Claude Code documents `workflow()` as
747
+ * throwing on an unknown name so a script can catch it and carry on. A host
748
+ * with no `loadWorkflow` at all is fatal, matching how a missing `runGate`
749
+ * or `resumeAgent` is treated: a capability the script asked for and this
750
+ * host cannot provide is a wiring error, not a runtime condition.
751
+ */
752
+ async function handleLoadWorkflow(callId, ref) {
753
+ const loadWorkflow = host.loadWorkflow?.bind(host);
754
+ if (loadWorkflow === undefined) {
755
+ respond(callId, false, undefined, "This workflow host cannot run nested workflows.", true);
756
+ return;
757
+ }
758
+ let source;
759
+ try {
760
+ source = await loadWorkflow(ref);
761
+ }
762
+ catch (error) {
763
+ respond(callId, false, undefined, error instanceof Error ? error.message : String(error));
764
+ return;
765
+ }
766
+ if (!source.ok) {
767
+ respond(callId, false, undefined, source.message);
768
+ return;
769
+ }
770
+ try {
771
+ const child = validateScript(source.script);
772
+ respond(callId, true, {
773
+ name: child.meta.name,
774
+ metaJson: JSON.stringify(child.meta),
775
+ body: child.body,
776
+ });
777
+ }
778
+ catch (error) {
779
+ respond(callId, false, undefined, error instanceof Error ? error.message : String(error));
780
+ }
781
+ }
782
+ worker.on("message", (message) => {
783
+ if (settled)
784
+ return;
785
+ switch (message.type) {
786
+ case "progress":
787
+ emit(message.entries);
788
+ break;
789
+ case "call":
790
+ if (message.method === "workflow") {
791
+ void handleLoadWorkflow(message.callId, message.payload);
792
+ break;
793
+ }
794
+ if (message.method !== "agent") {
795
+ respond(message.callId, false, undefined, `Unknown workflow host method "${message.method}".`, true);
796
+ break;
797
+ }
798
+ void handleAgent(message.callId, message.payload);
799
+ break;
800
+ case "complete": {
801
+ // The script is done, so every launch it made should have been
802
+ // answered by now — a response is sent before the worker can post
803
+ // this, so anything still open was never awaited. finish() aborts
804
+ // those children on the way out.
805
+ const unawaited = [...openLaunches.values()];
806
+ if (unawaited.length > 0) {
807
+ finish({ status: "failed", error: unawaitedLaunchMessage(unawaited) });
808
+ break;
809
+ }
810
+ finish({
811
+ status: "completed",
812
+ ...(message.resultJson === undefined ? {} : { value: JSON.parse(message.resultJson) }),
813
+ });
814
+ break;
815
+ }
816
+ case "error":
817
+ finish({ status: "failed", error: message.message });
818
+ break;
819
+ }
820
+ });
821
+ worker.on("error", error => {
822
+ finish({ status: "failed", error: error instanceof Error ? error.message : String(error) });
823
+ });
824
+ worker.on("exit", () => {
825
+ // Only reachable when the worker dies without reporting — a terminate()
826
+ // we did not initiate, or a hard crash.
827
+ finish({ status: "failed", error: "Workflow worker exited before completing." });
828
+ });
829
+ });
830
+ }
831
+ //# sourceMappingURL=runtime.js.map