pi-subagents 0.83.1 → 0.85.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 (206) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-5YIITCPD.js → chunk-3UZ5FVVJ.js} +322 -110
  5. package/bundle/{chunk-F4ASL6OV.js → chunk-7MAE3DJV.js} +1 -1
  6. package/bundle/{chunk-YXFJVCOL.js → chunk-CS4O36CZ.js} +11 -156
  7. package/bundle/{chunk-AHIFYGR3.js → chunk-DV2NCNPR.js} +22 -11
  8. package/bundle/{chunk-G2Z6ZH26.js → chunk-GCSLVFCX.js} +1 -1
  9. package/bundle/{chunk-2S4K53MV.js → chunk-H2NLFTC5.js} +1 -1
  10. package/bundle/{chunk-MABL3FUM.js → chunk-HFTBF7SG.js} +2 -1
  11. package/bundle/chunk-HXRB42AF.js +108 -0
  12. package/bundle/{chunk-UFL7IYCW.js → chunk-IQIWF2VX.js} +190 -1177
  13. package/bundle/{chunk-NPIYWVOD.js → chunk-JNXT3MPI.js} +15 -6
  14. package/bundle/{chunk-C7JMPU5F.js → chunk-JO67XSKD.js} +59 -27
  15. package/bundle/{chunk-UUP372DR.js → chunk-JWYG26RE.js} +223 -93
  16. package/bundle/{chunk-C5P5CHYK.js → chunk-KDMFBYFM.js} +1 -1
  17. package/bundle/{chunk-V2BZYLEP.js → chunk-KEY3UQMQ.js} +7 -2
  18. package/bundle/{chunk-VLFZIN6D.js → chunk-KZ34KQQH.js} +9 -6
  19. package/bundle/{chunk-ZVOAMTUQ.js → chunk-L2ENOFVZ.js} +76 -58
  20. package/bundle/{chunk-RNIZLSEA.js → chunk-LGMILZNE.js} +323 -18
  21. package/bundle/{chunk-UYK5MZWE.js → chunk-LTPH2DXH.js} +247 -153
  22. package/bundle/{chunk-2D52JFLF.js → chunk-N7B2KD74.js} +41 -117
  23. package/bundle/{chunk-IPGZMQXV.js → chunk-O7CPL6H4.js} +183 -28
  24. package/bundle/{chunk-D3JAFGMO.js → chunk-PHZP3KHB.js} +1 -1
  25. package/bundle/{chunk-2DHZTCOL.js → chunk-PVIVCDG2.js} +2 -2
  26. package/bundle/{chunk-LFDBD4PW.js → chunk-QO75KJBT.js} +2 -2
  27. package/bundle/{chunk-SSG7IEP5.js → chunk-RQAUNAWG.js} +2 -2
  28. package/bundle/{chunk-QP5ZWNIS.js → chunk-RV5OGHLO.js} +6 -3
  29. package/bundle/chunk-T5V5BRCL.js +1067 -0
  30. package/bundle/{chunk-LNRJCP2Y.js → chunk-UX4SCV5N.js} +337 -207
  31. package/bundle/{chunk-F5DBXJ2G.js → chunk-WOVMHDES.js} +234 -182
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +8 -8
  36. package/bundle/project-panes.js +3 -3
  37. package/docs/agents.md +17 -2
  38. package/docs/configuration.md +2 -2
  39. package/docs/extension-api.md +16 -1
  40. package/docs/workflows.md +30 -2
  41. package/package.json +1 -1
  42. package/src/agents/agent-management.js +27 -11
  43. package/src/agents/agent-memory.d.ts +1 -4
  44. package/src/agents/agent-memory.js +1 -4
  45. package/src/agents/agents.d.ts +1 -3
  46. package/src/agents/agents.js +7 -6
  47. package/src/agents/frontmatter.js +1 -8
  48. package/src/agents/global-npm-root.d.ts +1 -0
  49. package/src/agents/global-npm-root.js +11 -3
  50. package/src/agents/skills.d.ts +0 -3
  51. package/src/agents/skills.js +0 -3
  52. package/src/extension/config.js +7 -1
  53. package/src/extension/herdr-pi-bridge.js +10 -2
  54. package/src/extension/index.d.ts +0 -13
  55. package/src/extension/index.js +43 -32
  56. package/src/extension/public-execution.d.ts +1 -0
  57. package/src/extension/public-execution.js +4 -0
  58. package/src/extension/reply-workflow-script.js +24 -4
  59. package/src/extension/schemas.d.ts +8 -3
  60. package/src/extension/schemas.js +5 -3
  61. package/src/extension/session-switch.d.ts +25 -0
  62. package/src/extension/session-switch.js +138 -0
  63. package/src/extension/subagent-guide.d.ts +1 -1
  64. package/src/extension/subagent-guide.js +1 -1
  65. package/src/extension/subagent-launch-tool.d.ts +25 -0
  66. package/src/extension/subagent-launch-tool.js +48 -0
  67. package/src/extension/tool-activation.js +25 -11
  68. package/src/extension/tool-description.js +6 -0
  69. package/src/inspectors/herdr/actions.d.ts +0 -1
  70. package/src/inspectors/herdr/actions.js +0 -1
  71. package/src/inspectors/session-roots-codec.d.ts +0 -1
  72. package/src/inspectors/session-roots-codec.js +0 -1
  73. package/src/inspectors/tmux/actions.d.ts +0 -1
  74. package/src/inspectors/tmux/actions.js +0 -1
  75. package/src/integrations/herdr-status.js +3 -8
  76. package/src/intercom/native-supervisor-channel.js +65 -9
  77. package/src/runs/background/async-execution.d.ts +8 -9
  78. package/src/runs/background/async-execution.js +77 -27
  79. package/src/runs/background/async-job-tracker.js +12 -0
  80. package/src/runs/background/async-resume.d.ts +2 -1
  81. package/src/runs/background/async-resume.js +112 -39
  82. package/src/runs/background/async-retention.d.ts +1 -0
  83. package/src/runs/background/async-retention.js +22 -11
  84. package/src/runs/background/auto-drain.js +2 -1
  85. package/src/runs/background/boot-id.d.ts +1 -3
  86. package/src/runs/background/boot-id.js +1 -3
  87. package/src/runs/background/completion-batcher.d.ts +3 -4
  88. package/src/runs/background/completion-batcher.js +2 -3
  89. package/src/runs/background/control-channel.d.ts +0 -6
  90. package/src/runs/background/control-channel.js +0 -6
  91. package/src/runs/background/fleet-view.js +2 -3
  92. package/src/runs/background/notify.d.ts +0 -2
  93. package/src/runs/background/notify.js +0 -2
  94. package/src/runs/background/result-watcher.d.ts +1 -0
  95. package/src/runs/background/result-watcher.js +59 -29
  96. package/src/runs/background/resume-guidance.js +4 -2
  97. package/src/runs/background/retained-children.js +2 -1
  98. package/src/runs/background/run-child-session.d.ts +2 -1
  99. package/src/runs/background/run-child-session.js +10 -2
  100. package/src/runs/background/run-status.js +4 -3
  101. package/src/runs/background/scheduled-runs.d.ts +3 -1
  102. package/src/runs/background/scheduled-runs.js +13 -16
  103. package/src/runs/background/subagent-runner.d.ts +2 -4
  104. package/src/runs/background/subagent-runner.js +10 -6
  105. package/src/runs/background/subagent-wait.js +12 -15
  106. package/src/runs/background/wait-config.d.ts +2 -0
  107. package/src/runs/background/wait-config.js +17 -3
  108. package/src/runs/background/wait-tool.js +4 -2
  109. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  110. package/src/runs/background/workflow-terminal-proof.js +0 -1
  111. package/src/runs/foreground/execution.d.ts +0 -3
  112. package/src/runs/foreground/execution.js +17 -9
  113. package/src/runs/foreground/subagent-executor.d.ts +3 -2
  114. package/src/runs/foreground/subagent-executor.js +112 -26
  115. package/src/runs/shared/child-commands.js +15 -2
  116. package/src/runs/shared/child-hooks.d.ts +1 -7
  117. package/src/runs/shared/child-hooks.js +13 -5
  118. package/src/runs/shared/child-launch.js +6 -2
  119. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  120. package/src/runs/shared/child-session.d.ts +3 -1
  121. package/src/runs/shared/child-session.js +22 -2
  122. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  123. package/src/runs/shared/child-tool-plan.js +0 -1
  124. package/src/runs/shared/claude-code-adapter.js +11 -0
  125. package/src/runs/shared/external-cli-runner.js +26 -6
  126. package/src/runs/shared/herdr-connection.js +2 -1
  127. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  128. package/src/runs/shared/herdr-pane-host.js +17 -1
  129. package/src/runs/shared/herdr-placed-run.js +48 -22
  130. package/src/runs/shared/lane-metadata.d.ts +0 -1
  131. package/src/runs/shared/lane-metadata.js +0 -1
  132. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  133. package/src/runs/shared/model-resolution-diagnostic.d.ts +11 -1
  134. package/src/runs/shared/model-resolution-diagnostic.js +25 -0
  135. package/src/runs/shared/model-resolution.d.ts +2 -2
  136. package/src/runs/shared/model-resolution.js +7 -1
  137. package/src/runs/shared/model-scope.d.ts +1 -5
  138. package/src/runs/shared/model-scope.js +1 -5
  139. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  140. package/src/runs/shared/mutation-evidence.js +52 -7
  141. package/src/runs/shared/nested-events.d.ts +1 -0
  142. package/src/runs/shared/nested-events.js +1 -1
  143. package/src/runs/shared/parallel-utils.d.ts +2 -1
  144. package/src/runs/shared/permissions.js +5 -3
  145. package/src/runs/shared/placement-host.d.ts +5 -1
  146. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  147. package/src/runs/shared/rex-pane-host.js +0 -2
  148. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  149. package/src/runs/shared/run-launch-folder.js +21 -0
  150. package/src/runs/shared/runner-launcher.d.ts +12 -1
  151. package/src/runs/shared/runner-launcher.js +16 -0
  152. package/src/runs/shared/single-output.d.ts +3 -3
  153. package/src/runs/shared/single-output.js +5 -3
  154. package/src/runs/shared/structured-output.d.ts +8 -0
  155. package/src/runs/shared/structured-output.js +30 -2
  156. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  157. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  158. package/src/runs/shared/tool-timeout.js +2 -1
  159. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  160. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  161. package/src/runs/shared/worktree.d.ts +3 -0
  162. package/src/runs/shared/worktree.js +20 -0
  163. package/src/shared/capacity-resilient-json.d.ts +1 -1
  164. package/src/shared/child-cache-retention.d.ts +1 -2
  165. package/src/shared/child-cache-retention.js +1 -2
  166. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  167. package/src/shared/fleet-transcript-reader.js +333 -0
  168. package/src/shared/formatters.d.ts +0 -18
  169. package/src/shared/formatters.js +0 -18
  170. package/src/shared/session-succession.d.ts +16 -1
  171. package/src/shared/session-succession.js +41 -2
  172. package/src/shared/session-warnings.d.ts +7 -0
  173. package/src/shared/session-warnings.js +26 -0
  174. package/src/shared/settings.d.ts +0 -23
  175. package/src/shared/settings.js +3 -35
  176. package/src/shared/types.d.ts +28 -11
  177. package/src/shared/types.js +0 -12
  178. package/src/shared/utils.d.ts +0 -14
  179. package/src/shared/utils.js +0 -22
  180. package/src/shared/wait-tool-name.d.ts +8 -0
  181. package/src/shared/wait-tool-name.js +13 -0
  182. package/src/slash/slash-commands.js +2 -1
  183. package/src/slash/subagent-cost.d.ts +3 -2
  184. package/src/slash/subagent-cost.js +22 -3
  185. package/src/slash/subagents-admin.js +0 -1
  186. package/src/tui/fleet-status.d.ts +0 -5
  187. package/src/tui/fleet-status.js +4 -24
  188. package/src/tui/fleet-transcript.d.ts +1 -44
  189. package/src/tui/fleet-transcript.js +1 -327
  190. package/src/tui/fleet.js +6 -4
  191. package/src/tui/render.d.ts +0 -9
  192. package/src/tui/render.js +81 -47
  193. package/src/tui/subagent-messages.js +3 -2
  194. package/src/watchdog/register-child.d.ts +2 -3
  195. package/src/watchdog/register-child.js +2 -3
  196. package/src/watchdog/turn-delta.js +2 -1
  197. package/src/workflows/scripted-workflow.js +243 -20
  198. package/src/workflows/workflow-launch-record.d.ts +15 -6
  199. package/src/workflows/workflow-launch-record.js +30 -12
  200. package/src/workflows/workflow-resume-claim.js +2 -2
  201. package/src/workflows/workflow-resume.d.ts +1 -1
  202. package/src/workflows/workflow-resume.js +11 -8
  203. package/src/workflows/workflow-script-worker.d.ts +13 -0
  204. package/src/workflows/workflow-script-worker.js +79 -0
  205. package/workflow-script-process.cjs +36 -0
  206. package/workflow-script-worker.cjs +453 -176
@@ -1,3 +1,5 @@
1
+ "use strict";
2
+
1
3
  const { parentPort, workerData } = require("node:worker_threads");
2
4
  const vm = require("node:vm");
3
5
  const { inspect } = require("node:util");
@@ -18,6 +20,72 @@ function createWorkflowPromiseHook(callbacks) {
18
20
  }
19
21
  }
20
22
 
23
+ // Workflow scripts run in their own vm context (the script realm). The API a script can reach (runs,
24
+ // state, emit, console, Promise, results, errors) is built by workflowRuntime inside a second vm
25
+ // context (the runtime realm), compiled from this function's source. Neither realm can compile code
26
+ // from strings, and no worker-realm object may ever become reachable from either: one would hand the
27
+ // script the worker's Function, and with it process. The runtime talks to the worker only through
28
+ // `bridge`, which it keeps in this closure, passes only strings and numbers, and calls in try/catch.
29
+ // Engine paths can still throw a worker-realm error into script code (a stack overflow inside Node's
30
+ // stack formatter, for one), so lockWorkerRealm also makes every worker value useless before a script runs.
31
+ function workflowRuntime(bridge, scriptRealm, stateEnabled) {
32
+ "use strict";
33
+
34
+ // Promise hooks report every promise in the isolate, the worker's own included. Captured before any
35
+ // script runs, so a script that replaces Object.getPrototypeOf cannot receive a worker promise.
36
+ const getPrototypeOf = Object.getPrototypeOf;
37
+ const runtimePromisePrototype = Promise.prototype;
38
+ const nativePromisePrototype = scriptRealm.promisePrototype;
39
+
40
+ function isWorkflowRealmPromise(value) {
41
+ if (!value || typeof value !== "object") return false;
42
+ let prototype = getPrototypeOf(value);
43
+ for (let depth = 0; prototype && depth < 16; depth++) {
44
+ if (prototype === nativePromisePrototype || prototype === runtimePromisePrototype) return true;
45
+ prototype = getPrototypeOf(prototype);
46
+ }
47
+ return false;
48
+ }
49
+
50
+ function post(message) {
51
+ const json = JSON.stringify(message);
52
+ let posted = false;
53
+ try {
54
+ posted = bridge.post(json);
55
+ } catch {}
56
+ if (posted !== true) throw new Error("Workflow runtime could not send a message to the host.");
57
+ }
58
+
59
+ function inspectValue(value) {
60
+ let encoded;
61
+ try {
62
+ encoded = bridge.inspect(value);
63
+ } catch {}
64
+ if (typeof encoded !== "string") throw new Error("console could not format a value.");
65
+ const decoded = JSON.parse(encoded);
66
+ if (decoded[0] !== true) throw new Error(String(decoded[1]));
67
+ return decoded[1];
68
+ }
69
+
70
+ function utf8ByteLength(value) {
71
+ if (typeof value !== "string") throw new TypeError("Expected a string to measure.");
72
+ let length;
73
+ try {
74
+ length = bridge.utf8Length(value);
75
+ } catch {}
76
+ if (typeof length !== "number" || length < 0) throw new Error("Workflow runtime could not measure a string.");
77
+ return length;
78
+ }
79
+
80
+ function utf8Prefix(value, maxBytes) {
81
+ let prefix;
82
+ try {
83
+ prefix = bridge.utf8Prefix(value, maxBytes);
84
+ } catch {}
85
+ if (typeof prefix !== "string") throw new Error("Workflow runtime could not truncate a string.");
86
+ return prefix;
87
+ }
88
+
21
89
  let nextCallId = 0;
22
90
  let topLevelWorkflowPromise;
23
91
  let suppressNativePromiseConsumption = 0;
@@ -26,7 +94,7 @@ const pending = new Map();
26
94
  const workflowErrorKinds = new WeakMap();
27
95
  const runKeyPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
28
96
  function validGitRef(ref) {
29
- if (typeof ref !== "string" || !ref || ref === "@" || new TextEncoder().encode(ref).length > 1024 || ref.startsWith("/") || ref.endsWith("/") || ref.includes("//") || ref.includes("..") || ref.includes("@{")) return false;
97
+ if (typeof ref !== "string" || !ref || ref === "@" || utf8ByteLength(ref) > 1024 || ref.startsWith("/") || ref.endsWith("/") || ref.includes("//") || ref.includes("..") || ref.includes("@{")) return false;
30
98
  if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/iu.test(ref)) return false;
31
99
  if (/[[\]\\~^:?*\u0000-\u0020\u007f]/u.test(ref) || ref.endsWith(".") || ref.endsWith(".lock")) return false;
32
100
  return ref.split("/").every((component) => component.length > 0 && component !== "." && component !== ".." && !component.startsWith(".") && !component.endsWith(".") && !component.endsWith(".lock"));
@@ -50,7 +118,13 @@ function canonicalRunParams(params) {
50
118
  }
51
119
 
52
120
  function isDirectWorkflowScriptPromiseHandlerCall() {
53
- const stack = new Error().stack;
121
+ let stack;
122
+ try {
123
+ stack = new Error().stack;
124
+ } catch {
125
+ // Near the stack limit the host's formatter overflows and throws its own realm's RangeError.
126
+ return false;
127
+ }
54
128
  if (typeof stack !== "string") return false;
55
129
  return stack.split("\n").some((line) => line.includes("workflow-script.js") && !line.includes("at async "));
56
130
  }
@@ -122,7 +196,7 @@ function addTrackedObservations(tracker, observations) {
122
196
  for (const observation of tracker.observations) {
123
197
  if (observedCallIds.has(observation.callId)) continue;
124
198
  observedCallIds.add(observation.callId);
125
- parentPort.postMessage({ type: "callObserved", callId: observation.callId, key: observation.key, operation: observation.operation });
199
+ post({ type: "callObserved", callId: observation.callId, key: observation.key, operation: observation.operation });
126
200
  }
127
201
  }
128
202
 
@@ -247,7 +321,7 @@ function hostCall(method, args, observation) {
247
321
  const callId = ++nextCallId;
248
322
  const promise = new Promise((resolve, reject) => {
249
323
  pending.set(callId, { resolve, reject });
250
- parentPort.postMessage({ type: "call", callId, method, args });
324
+ post({ type: "call", callId, method, args });
251
325
  });
252
326
  return observation && typeof observation.key === "string" && typeof observation.operation === "string"
253
327
  ? trackRunObservation([{ key: observation.key, operation: observation.operation, callId }], promise)
@@ -258,7 +332,7 @@ function runHostCall(key, params, collectFailure, batch, generatedLaneKey) {
258
332
  const callId = ++nextCallId;
259
333
  const promise = new Promise((resolve, reject) => {
260
334
  pending.set(callId, { resolve, reject });
261
- parentPort.postMessage({ type: "call", callId, method: "run", args: { key, params, ...(collectFailure ? { collectFailure: true } : {}), ...(batch ? { batch } : {}), ...(generatedLaneKey ? { generatedLaneKey } : {}) } });
335
+ post({ type: "call", callId, method: "run", args: { key, params, ...(collectFailure ? { collectFailure: true } : {}), ...(batch ? { batch } : {}), ...(generatedLaneKey ? { generatedLaneKey } : {}) } });
262
336
  });
263
337
  return { key, callId, promise };
264
338
  }
@@ -300,14 +374,13 @@ function wrapRunsAllResults(results, keys) {
300
374
  }
301
375
 
302
376
  function laneByteLength(value) {
303
- return new TextEncoder().encode(value).byteLength;
377
+ return utf8ByteLength(value);
304
378
  }
305
379
 
306
380
  function laneBoardText(value) {
307
381
  if (typeof value !== "string" || !value) return undefined;
308
382
  if (laneByteLength(value) <= MAX_LANE_BOARD_TEXT_BYTES) return value;
309
- const bytes = new TextEncoder().encode(value).subarray(0, MAX_LANE_BOARD_TEXT_BYTES - 3);
310
- return new TextDecoder().decode(bytes, { stream: true }) + "...";
383
+ return utf8Prefix(value, MAX_LANE_BOARD_TEXT_BYTES - 3) + "...";
311
384
  }
312
385
 
313
386
  function laneBoardPath(value) {
@@ -508,7 +581,7 @@ function workflowPlanStringMetadata(params) {
508
581
 
509
582
  function runLanes(laneSpecs) {
510
583
  const lanes = validateLaneSpecs(laneSpecs);
511
- parentPort.postMessage({ type: "lanePlan", lanes: lanes.map((lane) => ({
584
+ post({ type: "lanePlan", lanes: lanes.map((lane) => ({
512
585
  key: lane.key,
513
586
  stages: lane.stages.map((stage) => ({
514
587
  key: stage.key,
@@ -576,7 +649,7 @@ function validateExtensionBindings(value, label) {
576
649
  }
577
650
  }
578
651
  visit(value, 0);
579
- if (new TextEncoder().encode(stableRunJson(value)).byteLength > 16384) throw new Error(label + " extensionBindings canonical JSON exceeds 16384 bytes.");
652
+ if (utf8ByteLength(stableRunJson(value)) > 16384) throw new Error(label + " extensionBindings canonical JSON exceeds 16384 bytes.");
580
653
  }
581
654
 
582
655
  function validateLaneMetadata(value, label, workflowKey) {
@@ -590,7 +663,7 @@ function validateLaneMetadata(value, label, workflowKey) {
590
663
  if (typeof value.key !== "string" || !value.key.trim() || !runKeyPattern.test(value.key.trim())) throw new Error(label + ".key is invalid.");
591
664
  if (workflowKey !== undefined && value.key.trim() !== workflowKey) throw new Error(label + ".key must match workflow key '" + workflowKey + "'.");
592
665
  if (value.mode !== undefined && !["mutation", "review", "scout", "gate"].includes(value.mode)) throw new Error(label + ".mode is invalid.");
593
- const bounded = (entry, maxBytes) => typeof entry === "string" && entry.trim() && new TextEncoder().encode(entry.trim()).byteLength <= maxBytes && !/[\r\n\u0000]/.test(entry);
666
+ const bounded = (entry, maxBytes) => typeof entry === "string" && entry.trim() && utf8ByteLength(entry.trim()) <= maxBytes && !/[\r\n\u0000]/.test(entry);
594
667
  if (value.sourceRef !== undefined && !bounded(value.sourceRef, 128)) throw new Error(label + ".sourceRef is invalid.");
595
668
  for (const [name, maxItems, maxLength] of [["claims", 20, 160], ["outputPaths", 10, 256]]) {
596
669
  if (value[name] === undefined) continue;
@@ -630,7 +703,10 @@ function describeGateAcceptanceConflict(gate, acceptance) {
630
703
  }
631
704
 
632
705
  function validateRunCall(key, params, label, fingerprints) {
633
- if (typeof key !== "string" || !runKeyPattern.test(key)) throw new Error(label + " has an invalid key.");
706
+ if (typeof key !== "string" || !runKeyPattern.test(key)) {
707
+ const problem = key === undefined ? " has no key" : typeof key === "string" ? " has an invalid key '" + (key.length > 80 ? key.slice(0, 80) + "..." : key) + "'" : " has a key of type " + (key === null ? "null" : typeof key);
708
+ throw new Error(label + problem + "; keys must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.");
709
+ }
634
710
  if (hostKeys.has(key)) throw new Error("Workflow key '" + key + "' is already used by runs.host.");
635
711
  if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error(label + " requires a params object.");
636
712
  if (Object.prototype.hasOwnProperty.call(params, "action") || Object.prototype.hasOwnProperty.call(params, "workflowScript") || Object.prototype.hasOwnProperty.call(params, "globalConcurrencyLimit") || Object.prototype.hasOwnProperty.call(params, "maxSubagentSpawnsPerRun") || Object.prototype.hasOwnProperty.call(params, "tasks") || Object.prototype.hasOwnProperty.call(params, "chain") || Object.prototype.hasOwnProperty.call(params, "parallel") || Object.prototype.hasOwnProperty.call(params, "concurrency") || Object.prototype.hasOwnProperty.call(params, "chainDir")) {
@@ -682,11 +758,11 @@ function validateHostCommand(key, params) {
682
758
  throw new Error("runs.host('" + key + "') params have unsupported fields: " + unknown.join(", ") + "." + cwdHint);
683
759
  }
684
760
  if (params.kind !== "command") throw new Error("runs.host('" + key + "') kind must be 'command'.");
685
- if (typeof params.command !== "string" || !params.command.trim() || params.command.includes("\u0000") || new TextEncoder().encode(params.command.trim()).byteLength > 16384) throw new Error("runs.host('" + key + "') command must be a non-empty string of at most 16384 bytes without NUL.");
761
+ if (typeof params.command !== "string" || !params.command.trim() || params.command.includes("\u0000") || utf8ByteLength(params.command.trim()) > 16384) throw new Error("runs.host('" + key + "') command must be a non-empty string of at most 16384 bytes without NUL.");
686
762
  if (!Number.isInteger(params.timeoutMs) || params.timeoutMs < 1 || params.timeoutMs > 86400000) throw new Error("runs.host('" + key + "') timeoutMs must be an integer from 1 to 86400000.");
687
- if (params.output !== undefined && (typeof params.output !== "string" || !params.output.trim() || /^[/\\]|(?:^|[/\\])\.\.(?:[/\\]|$)/.test(params.output) || /[\u0000-\u001f\u007f]/.test(params.output) || new TextEncoder().encode(params.output.trim()).byteLength > 240)) throw new Error("runs.host('" + key + "') output must be a bounded relative path without traversal or control characters.");
763
+ if (params.output !== undefined && (typeof params.output !== "string" || !params.output.trim() || /^[/\\]|(?:^|[/\\])\.\.(?:[/\\]|$)/.test(params.output) || /[\u0000-\u001f\u007f]/.test(params.output) || utf8ByteLength(params.output.trim()) > 240)) throw new Error("runs.host('" + key + "') output must be a bounded relative path without traversal or control characters.");
688
764
  if (params.role !== undefined && params.role !== "ci" && params.role !== "gate") throw new Error("runs.host('" + key + "') role must be 'ci' or 'gate'.");
689
- if (params.provider !== undefined && (typeof params.provider !== "string" || !params.provider.trim() || /[\r\n\u0000]/.test(params.provider) || new TextEncoder().encode(params.provider.trim()).byteLength > 64)) throw new Error("runs.host('" + key + "') provider must be a non-empty single-line string of at most 64 bytes.");
765
+ if (params.provider !== undefined && (typeof params.provider !== "string" || !params.provider.trim() || /[\r\n\u0000]/.test(params.provider) || utf8ByteLength(params.provider.trim()) > 64)) throw new Error("runs.host('" + key + "') provider must be a non-empty single-line string of at most 64 bytes.");
690
766
  assertJsonValue(params, "runs.host('" + key + "') params");
691
767
  if (hostKeys.has(key) || runFingerprints.has(key)) throw new Error("Workflow key '" + key + "' is already in use.");
692
768
  if (hostKeys.size >= 32) throw new Error("workflowScript supports at most 32 runs.host calls.");
@@ -807,14 +883,221 @@ const state = Object.freeze({
807
883
  },
808
884
  });
809
885
 
810
- let contextObjectPrototype;
886
+ const contextObjectPrototype = scriptRealm.objectPrototype;
811
887
 
812
888
  const capturedConsole = Object.freeze(Object.fromEntries(
813
889
  ["log", "info", "warn", "error"].map((level) => [level, (...args) => {
814
- parentPort.postMessage({ type: "console", level, text: args.map((value) => typeof value === "string" ? value : inspect(value, { depth: 4, breakLength: 120 })).join(" ") });
890
+ post({ type: "console", level, text: args.map((value) => typeof value === "string" ? value : inspectValue(value)).join(" ") });
815
891
  }]),
816
892
  ));
817
893
 
894
+ function postWorkflowError(error) {
895
+ // Pre-run syntax and portability errors are tagged "validation" where the script is compiled;
896
+ // anything reaching here was thrown while the script ran, including a runtime SyntaxError.
897
+ const taggedKind = error && (typeof error === "object" || typeof error === "function") ? workflowErrorKinds.get(error) : undefined;
898
+ post({ type: "error", error: isSyntaxError(error) ? formatWorkflowScriptSyntaxError(error) : formatWorkflowScriptError(error), errorKind: taggedKind ?? "script" });
899
+ }
900
+ function assertJsonValue(value, path = "emit", seen = new Set()) {
901
+
902
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
903
+ if (typeof value === "number") {
904
+ if (!Number.isFinite(value)) throw new Error(path + " must contain only finite JSON numbers.");
905
+ return;
906
+ }
907
+ if (typeof value !== "object") throw new Error(path + " must be a JSON value; received " + typeof value + ".");
908
+ if (seen.has(value)) throw new Error(path + " must not contain cycles.");
909
+ seen.add(value);
910
+ if (Array.isArray(value)) {
911
+ for (let index = 0; index < value.length; index++) {
912
+ if (!Object.prototype.hasOwnProperty.call(value, index)) throw new Error(path + " must not contain sparse array entries.");
913
+ assertJsonValue(value[index], path + "[" + index + "]", seen);
914
+ }
915
+ } else {
916
+ const prototype = Object.getPrototypeOf(value);
917
+ if (prototype !== null && prototype !== Object.prototype && prototype !== contextObjectPrototype) throw new Error(path + " must contain only plain JSON objects.");
918
+ if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(path + " must not contain symbol keys.");
919
+ for (const [key, entry] of Object.entries(value)) assertJsonValue(entry, path + "." + key, seen);
920
+ }
921
+ seen.delete(value);
922
+ }
923
+
924
+ function isPlainWorkflowObject(value) {
925
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
926
+ const prototype = Object.getPrototypeOf(value);
927
+ return prototype === null || prototype === Object.prototype || prototype === contextObjectPrototype;
928
+ }
929
+
930
+ function unwrapRunsAllResults(value, seen = new Map()) {
931
+ if (value === null || typeof value !== "object") return value;
932
+ const runsAllTarget = runsAllResultTargets.get(value);
933
+ const target = runsAllTarget || value;
934
+ if (seen.has(target)) return seen.get(target);
935
+ if (Array.isArray(target)) {
936
+ const copy = [];
937
+ seen.set(target, copy);
938
+ let changed = !!runsAllTarget;
939
+ for (let index = 0; index < target.length; index++) {
940
+ copy[index] = unwrapRunsAllResults(target[index], seen);
941
+ changed ||= copy[index] !== target[index];
942
+ }
943
+ return changed ? copy : target;
944
+ }
945
+ if (!isPlainWorkflowObject(target) || Object.getOwnPropertySymbols(target).length > 0) return target;
946
+ let changed = false;
947
+ const entries = Object.entries(target).map(([key, entry]) => {
948
+ const unwrapped = unwrapRunsAllResults(entry, seen);
949
+ changed ||= unwrapped !== entry;
950
+ return [key, unwrapped];
951
+ });
952
+ return changed ? Object.fromEntries(entries) : target;
953
+ }
954
+
955
+ function omitUndefinedWorkflowValues(value, seen = new Set()) {
956
+ if (value === null || typeof value !== "object") return value;
957
+ if (seen.has(value)) return value;
958
+ seen.add(value);
959
+ const normalized = Array.isArray(value)
960
+ ? value.map((entry) => entry === undefined ? null : omitUndefinedWorkflowValues(entry, seen))
961
+ : isPlainWorkflowObject(value) && Object.getOwnPropertySymbols(value).length === 0
962
+ ? Object.fromEntries(Object.entries(value).flatMap(([key, entry]) => entry === undefined ? [] : [[key, omitUndefinedWorkflowValues(entry, seen)]]))
963
+ : value;
964
+ seen.delete(value);
965
+ return normalized;
966
+ }
967
+
968
+ const scriptGlobals = { runs, Promise: workflowPromise, emit(value) { const unwrapped = unwrapRunsAllResults(value); const emittedValue = unwrapped === undefined ? null : omitUndefinedWorkflowValues(unwrapped); assertJsonValue(emittedValue); post({ type: "emit", value: emittedValue }); }, console: capturedConsole };
969
+ if (stateEnabled) scriptGlobals.state = state;
970
+
971
+ function deliver(callId, ok, encodedValue, errorText, errorKind) {
972
+ const entry = pending.get(callId);
973
+ if (!entry) return;
974
+ pending.delete(callId);
975
+ if (ok) entry.resolve(JSON.parse(encodedValue).value);
976
+ else {
977
+ const error = new Error(errorText);
978
+ if (errorKind === "child" || errorKind === "detached-child") workflowErrorKinds.set(error, errorKind);
979
+ entry.reject(error);
980
+ }
981
+ }
982
+
983
+ let nativeThenDescriptor;
984
+
985
+ function beginWorkflowScript() {
986
+ try {
987
+ nativeThenDescriptor = Object.getOwnPropertyDescriptor(nativePromisePrototype, "then");
988
+ if (!nativeThenDescriptor || typeof nativeThenDescriptor.value !== "function") throw new Error("workflowScript could not inspect the VM Promise.prototype.then method.");
989
+ const nativeThen = nativeThenDescriptor.value;
990
+ // Some hosts freeze built-ins in every realm, which makes then read-only. The promise hooks
991
+ // still track observation, so skip the wrapper rather than fail every workflow.
992
+ if (nativeThenDescriptor.configurable) Object.defineProperty(nativePromisePrototype, "then", {
993
+ ...nativeThenDescriptor,
994
+ value: function workflowPromiseThen(...args) {
995
+ if (isDirectWorkflowScriptPromiseHandlerCall() || suppressNativePromiseConsumption > 0) {
996
+ return withSuppressedNativePromiseConsumption(() => Reflect.apply(nativeThen, this, args));
997
+ }
998
+ return Reflect.apply(nativeThen, this, args);
999
+ },
1000
+ });
1001
+ return true;
1002
+ } catch (error) {
1003
+ postWorkflowError(error);
1004
+ return false;
1005
+ }
1006
+ }
1007
+
1008
+ function hookBefore(promise) {
1009
+ if (!isWorkflowRealmPromise(promise)) return;
1010
+ activeNativePromises.push(promise);
1011
+ }
1012
+
1013
+ function hookAfter(promise) {
1014
+ // Compare by identity rather than lastIndexOf: this may be a worker promise, and a script can replace Array methods.
1015
+ for (let index = activeNativePromises.length - 1; index >= 0; index--) {
1016
+ if (activeNativePromises[index] !== promise) continue;
1017
+ activeNativePromises.splice(index, 1);
1018
+ return;
1019
+ }
1020
+ }
1021
+
1022
+ function hookInit(promise, parent) {
1023
+ if (!isWorkflowRealmPromise(promise)) return;
1024
+ const childTracker = nativePromiseTracker(promise);
1025
+ if (!parent || !isWorkflowRealmPromise(parent)) return;
1026
+ nativePromiseParents.set(promise, parent);
1027
+ const parentTracker = nativePromiseTracker(parent);
1028
+ addTrackerDependency(childTracker, parentTracker);
1029
+ const activePromise = activeNativePromises.at(-1);
1030
+ if (activePromise && activePromise !== parent) {
1031
+ addTrackerDependency(nativePromiseTracker(activePromise), parentTracker);
1032
+ } else if (!activePromise && suppressNativePromiseConsumption === 0) {
1033
+ markTrackedObservationsConsumed(parentTracker);
1034
+ }
1035
+ }
1036
+
1037
+ function endWorkflowScript() {
1038
+ try {
1039
+ let stopped = false;
1040
+ try {
1041
+ stopped = bridge.stopPromiseHooks();
1042
+ } catch {}
1043
+ if (stopped !== true) throw new Error("Workflow runtime could not stop its promise hooks.");
1044
+ } finally {
1045
+ try {
1046
+ if (nativeThenDescriptor.configurable) Object.defineProperty(nativePromisePrototype, "then", nativeThenDescriptor);
1047
+ } finally {
1048
+ topLevelWorkflowPromise = undefined;
1049
+ activeNativePromises.length = 0;
1050
+ suppressNativePromiseConsumption = 0;
1051
+ nativePromiseTrackers = new WeakMap();
1052
+ nativePromiseParents = new WeakMap();
1053
+ }
1054
+ }
1055
+ }
1056
+
1057
+ function completeWorkflowScript(value) {
1058
+ const persistedValue = value === undefined ? null : omitUndefinedWorkflowValues(value);
1059
+ try {
1060
+ assertJsonValue(persistedValue, "return");
1061
+ } catch (error) {
1062
+ post({ type: "error", errorKind: "return-serialization", errorPhase: "return-serialization", error: formatWorkflowScriptError(error) });
1063
+ return;
1064
+ }
1065
+ post({ type: "complete", value: persistedValue });
1066
+ }
1067
+
1068
+ // The worker ran the compiled script: `result` is its completion value, or what it threw synchronously.
1069
+ function awaitWorkflowScript(threw, result) {
1070
+ let settled;
1071
+ try {
1072
+ if (threw) throw result;
1073
+ topLevelWorkflowPromise = result;
1074
+ markTrackedObservationsConsumed(nativePromiseTracker(result));
1075
+ settled = Promise.resolve(result);
1076
+ } catch (error) {
1077
+ settled = Promise.reject(error);
1078
+ }
1079
+ settled.then((value) => {
1080
+ endWorkflowScript();
1081
+ completeWorkflowScript(value);
1082
+ }, (error) => {
1083
+ endWorkflowScript();
1084
+ postWorkflowError(error);
1085
+ }).catch(postWorkflowError);
1086
+ }
1087
+
1088
+ return Object.freeze({
1089
+ __proto__: null,
1090
+ scriptGlobals: Object.freeze(scriptGlobals),
1091
+ deliver,
1092
+ beginWorkflowScript,
1093
+ hookBefore,
1094
+ hookAfter,
1095
+ hookInit,
1096
+ awaitWorkflowScript,
1097
+ reportError: postWorkflowError,
1098
+ });
1099
+ }
1100
+
818
1101
  function formatWorkflowScriptSyntaxError(error) {
819
1102
  const details = formatWorkflowScriptError(error);
820
1103
  return [
@@ -837,17 +1120,11 @@ function isSyntaxError(error) {
837
1120
  return error instanceof SyntaxError || error?.name === "SyntaxError";
838
1121
  }
839
1122
 
840
- function postWorkflowError(error) {
841
- // Pre-run syntax and portability errors are tagged "validation" where the script is compiled;
842
- // anything reaching here was thrown while the script ran, including a runtime SyntaxError.
843
- const taggedKind = error && (typeof error === "object" || typeof error === "function") ? workflowErrorKinds.get(error) : undefined;
844
- parentPort.postMessage({ type: "error", error: isSyntaxError(error) ? formatWorkflowScriptSyntaxError(error) : formatWorkflowScriptError(error), errorKind: taggedKind ?? "script" });
845
- }
846
-
847
- process.on("unhandledRejection", postWorkflowError);
848
-
849
1123
  const NESTED_ASYNC_WORKFLOW_ERROR = "workflowScript validation failed before child launch; no children launched. workflowScript does not support nested async functions. Use top-level await, plain helper functions that return runs.run(...), or explicit Promise chains so workflows stay portable across Node and Bun. Parallel plus sequential rewrite: const a = runs.run(\"a\", { agent: \"worker\", task: \"A\" }); const writer = await runs.run(\"writer\", { agent: \"worker\", task: \"Write\" }); const review = await runs.run(\"review\", { agent: \"reviewer\", task: writer.output }); const [aResult] = await Promise.all([a]); return { a: aResult.output, issue: { writerRunId: writer.runId, reviewRunId: review.runId } };";
850
1124
  const AST_SCALAR_KEYS = new Set(["type", "start", "end"]);
1125
+ // A script context has no module loader, and Node and Bun reject import() there with an error built in
1126
+ // the worker realm, so the call is refused before the script runs.
1127
+ const DYNAMIC_IMPORT_WORKFLOW_ERROR = "workflowScript validation failed before child launch; no children launched. workflowScript cannot load modules with import().";
851
1128
 
852
1129
  function assertPortableWorkflowScript(source) {
853
1130
  const wrapped = "(async () => {\n" + source + "\n})()";
@@ -864,7 +1141,8 @@ function assertPortableWorkflowScript(source) {
864
1141
  throw error;
865
1142
  }
866
1143
  const wrapper = workflowWrapperFunction(ast);
867
- walkWorkflowAst(wrapper.body, wrapper);
1144
+ // Walk the whole program, not just the wrapper body: a script can close the wrapper early.
1145
+ walkWorkflowAst(ast, wrapper);
868
1146
  }
869
1147
 
870
1148
  function workflowWrapperFunction(ast) {
@@ -886,183 +1164,182 @@ function walkWorkflowAst(node, allowedAsyncFunction) {
886
1164
  if (node !== allowedAsyncFunction && isAsyncFunctionNode(node)) {
887
1165
  throw new Error(NESTED_ASYNC_WORKFLOW_ERROR);
888
1166
  }
1167
+ if (node.type === "ImportExpression") throw new Error(DYNAMIC_IMPORT_WORKFLOW_ERROR);
889
1168
  for (const [key, child] of Object.entries(node)) {
890
1169
  if (AST_SCALAR_KEYS.has(key)) continue;
891
1170
  walkWorkflowAst(child, allowedAsyncFunction);
892
1171
  }
893
1172
  }
894
1173
 
895
- function assertJsonValue(value, path = "emit", seen = new Set()) {
896
- if (value === null || typeof value === "string" || typeof value === "boolean") return;
897
- if (typeof value === "number") {
898
- if (!Number.isFinite(value)) throw new Error(path + " must contain only finite JSON numbers.");
899
- return;
900
- }
901
- if (typeof value !== "object") throw new Error(path + " must be a JSON value; received " + typeof value + ".");
902
- if (seen.has(value)) throw new Error(path + " must not contain cycles.");
903
- seen.add(value);
904
- if (Array.isArray(value)) {
905
- for (let index = 0; index < value.length; index++) {
906
- if (!Object.prototype.hasOwnProperty.call(value, index)) throw new Error(path + " must not contain sparse array entries.");
907
- assertJsonValue(value[index], path + "[" + index + "]", seen);
908
- }
909
- } else {
910
- const prototype = Object.getPrototypeOf(value);
911
- if (prototype !== null && prototype !== Object.prototype && prototype !== contextObjectPrototype) throw new Error(path + " must contain only plain JSON objects.");
912
- if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(path + " must not contain symbol keys.");
913
- for (const [key, entry] of Object.entries(value)) assertJsonValue(entry, path + "." + key, seen);
914
- }
915
- seen.delete(value);
1174
+ // The error-format helpers run in both realms; the runtime realm compiles its own copies from their source.
1175
+ const WORKFLOW_RUNTIME_SOURCE = [
1176
+ "(function (bridge, scriptRealm, stateEnabled) {",
1177
+ "\"use strict\";",
1178
+ formatWorkflowScriptSyntaxError,
1179
+ formatWorkflowScriptError,
1180
+ isSyntaxError,
1181
+ "return (" + workflowRuntime + ")(bridge, scriptRealm, stateEnabled);",
1182
+ "})",
1183
+ ].join("\n");
1184
+
1185
+ const VM_CONTEXT_OPTIONS = { codeGeneration: { strings: false, wasm: false } };
1186
+ const LOCK_PREPARE_STACK_TRACE_SOURCE = "Object.defineProperty(Error, \"prepareStackTrace\", { value: undefined, writable: false, enumerable: false, configurable: false });";
1187
+
1188
+ // A null-prototype sandbox keeps globalThis.constructor out of the worker realm. The sandbox itself is
1189
+ // still a worker-realm object, and Bun forwards a failed global redefinition to it as the worker's
1190
+ // TypeError; lockWorkerRealm makes that error useless. vm.constants.DONT_CONTEXTIFY would avoid the
1191
+ // sandbox, but Bun 1.3 ignores properties defined on such a global, so the script API could not be installed.
1192
+ function createVmRealm() {
1193
+ return vm.createContext(Object.create(null), VM_CONTEXT_OPTIONS);
1194
+ }
1195
+
1196
+ // Runs once the worker has compiled everything it needs, right before the script starts. A worker-realm
1197
+ // value can still reach a script through engine paths (see workflowRuntime), so take away what such a
1198
+ // value would be used for: no worker function's constructor compiles code, and no script can install a
1199
+ // stack formatter that hands it worker frames.
1200
+ function lockWorkerRealm() {
1201
+ const refuse = function Function() {
1202
+ throw new TypeError("Code generation is disabled in the workflow worker.");
1203
+ };
1204
+ const functionPrototypes = [
1205
+ Function.prototype,
1206
+ Object.getPrototypeOf(async function () {}),
1207
+ Object.getPrototypeOf(function* () {}),
1208
+ Object.getPrototypeOf(async function* () {}),
1209
+ ];
1210
+ // A host that froze these already chose their values; redefining them would throw and fail every workflow.
1211
+ const lock = (target, key, value) => {
1212
+ if (Object.getOwnPropertyDescriptor(target, key)?.configurable === false) return;
1213
+ Object.defineProperty(target, key, { value, writable: false, enumerable: false, configurable: false });
1214
+ };
1215
+ for (const prototype of functionPrototypes) lock(prototype, "constructor", refuse);
1216
+ lock(Error, "prepareStackTrace", Error.prepareStackTrace);
916
1217
  }
1218
+ const INSPECT_OPTIONS = { depth: 4, breakLength: 120, customInspect: false };
917
1219
 
918
- function isPlainWorkflowObject(value) {
919
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
920
- const prototype = Object.getPrototypeOf(value);
921
- return prototype === null || prototype === Object.prototype || prototype === contextObjectPrototype;
922
- }
1220
+ let runtime;
1221
+ let stopWorkflowPromiseHook;
923
1222
 
924
- function unwrapRunsAllResults(value, seen = new Map()) {
925
- if (value === null || typeof value !== "object") return value;
926
- const runsAllTarget = runsAllResultTargets.get(value);
927
- const target = runsAllTarget || value;
928
- if (seen.has(target)) return seen.get(target);
929
- if (Array.isArray(target)) {
930
- const copy = [];
931
- seen.set(target, copy);
932
- let changed = !!runsAllTarget;
933
- for (let index = 0; index < target.length; index++) {
934
- copy[index] = unwrapRunsAllResults(target[index], seen);
935
- changed ||= copy[index] !== target[index];
1223
+ // Each method takes and returns only strings, numbers and booleans, and catches its own failures.
1224
+ // inspect is the one exception on input: it formats a script value without calling script-defined
1225
+ // custom inspectors, which would receive worker-realm arguments.
1226
+ const bridge = Object.freeze({
1227
+ __proto__: null,
1228
+ post(json) {
1229
+ try {
1230
+ parentPort.postMessage(JSON.parse(json));
1231
+ return true;
1232
+ } catch {
1233
+ return false;
936
1234
  }
937
- return changed ? copy : target;
938
- }
939
- if (!isPlainWorkflowObject(target) || Object.getOwnPropertySymbols(target).length > 0) return target;
940
- let changed = false;
941
- const entries = Object.entries(target).map(([key, entry]) => {
942
- const unwrapped = unwrapRunsAllResults(entry, seen);
943
- changed ||= unwrapped !== entry;
944
- return [key, unwrapped];
945
- });
946
- return changed ? Object.fromEntries(entries) : target;
947
- }
1235
+ },
1236
+ inspect(value) {
1237
+ try {
1238
+ return JSON.stringify([true, inspect(value, INSPECT_OPTIONS)]);
1239
+ } catch (error) {
1240
+ const message = error && typeof error.message === "string" ? error.message : "console could not format a value.";
1241
+ return JSON.stringify([false, message]);
1242
+ }
1243
+ },
1244
+ utf8Length(value) {
1245
+ try {
1246
+ return typeof value === "string" ? new TextEncoder().encode(value).byteLength : -1;
1247
+ } catch {
1248
+ return -1;
1249
+ }
1250
+ },
1251
+ utf8Prefix(value, maxBytes) {
1252
+ try {
1253
+ if (typeof value !== "string" || typeof maxBytes !== "number") return undefined;
1254
+ return new TextDecoder().decode(new TextEncoder().encode(value).subarray(0, maxBytes), { stream: true });
1255
+ } catch {
1256
+ return undefined;
1257
+ }
1258
+ },
1259
+ stopPromiseHooks() {
1260
+ const stop = stopWorkflowPromiseHook;
1261
+ stopWorkflowPromiseHook = undefined;
1262
+ try {
1263
+ stop?.();
1264
+ return true;
1265
+ } catch {
1266
+ return false;
1267
+ }
1268
+ },
1269
+ });
948
1270
 
949
- function omitUndefinedWorkflowValues(value, seen = new Set()) {
950
- if (value === null || typeof value !== "object") return value;
951
- if (seen.has(value)) return value;
952
- seen.add(value);
953
- const normalized = Array.isArray(value)
954
- ? value.map((entry) => entry === undefined ? null : omitUndefinedWorkflowValues(entry, seen))
955
- : isPlainWorkflowObject(value) && Object.getOwnPropertySymbols(value).length === 0
956
- ? Object.fromEntries(Object.entries(value).flatMap(([key, entry]) => entry === undefined ? [] : [[key, omitUndefinedWorkflowValues(entry, seen)]]))
957
- : value;
958
- seen.delete(value);
959
- return normalized;
1271
+ function postWorkerError(error) {
1272
+ parentPort.postMessage({ type: "error", error: isSyntaxError(error) ? formatWorkflowScriptSyntaxError(error) : formatWorkflowScriptError(error), errorKind: "script" });
960
1273
  }
961
1274
 
1275
+ process.on("unhandledRejection", (reason) => {
1276
+ // A worker-realm reason is the worker's own failure; it must not enter the runtime realm.
1277
+ if (runtime && !(reason instanceof Object)) runtime.reportError(reason);
1278
+ else postWorkerError(reason);
1279
+ });
1280
+
962
1281
  function deepFreezeWorkflowArgs(value) {
963
1282
  if (value === null || typeof value !== "object" || Object.isFrozen(value)) return value;
964
1283
  for (const entry of Object.values(value)) deepFreezeWorkflowArgs(entry);
965
1284
  return Object.freeze(value);
966
1285
  }
967
1286
 
968
- parentPort.on("message", async (message) => {
969
- if (message.type === "response") {
970
- const entry = pending.get(message.callId);
971
- if (!entry) return;
972
- pending.delete(message.callId);
973
- if (message.ok) entry.resolve(message.value);
974
- else {
975
- const error = new Error(message.error);
976
- if (message.errorKind === "child" || message.errorKind === "detached-child") workflowErrorKinds.set(error, message.errorKind);
977
- entry.reject(error);
978
- }
1287
+ function startWorkflow(message) {
1288
+ const context = createVmRealm();
1289
+ const runtimeContext = createVmRealm();
1290
+ // Bun hands Error.prepareStackTrace call sites (and the array holding them) from the worker's realm,
1291
+ // whatever context the error came from. Lock it in both realms before any code runs there.
1292
+ for (const realm of [context, runtimeContext]) vm.runInContext(LOCK_PREPARE_STACK_TRACE_SOURCE, realm);
1293
+ const scriptRealm = vm.runInContext("({ __proto__: null, objectPrototype: Object.prototype, promisePrototype: (async () => {})().constructor.prototype })", context);
1294
+ const createRuntime = new vm.Script(WORKFLOW_RUNTIME_SOURCE, { filename: "pi-workflow-runtime.js" }).runInContext(runtimeContext);
1295
+ runtime = createRuntime(bridge, scriptRealm, Boolean(message.stateEnabled));
1296
+ Object.assign(context, runtime.scriptGlobals);
1297
+ // Rebuild args inside the VM realm: a worker-realm object would expose the worker's unrestricted
1298
+ // Function through args.constructor.constructor, bypassing codeGeneration.strings: false.
1299
+ context.args = deepFreezeWorkflowArgs(vm.runInContext("JSON.parse", context)(JSON.stringify(message.args ?? {})));
1300
+ let compiled;
1301
+ try {
1302
+ assertPortableWorkflowScript(message.script);
1303
+ compiled = new vm.Script("(async () => {\n" + message.script + "\n})()", { filename: "workflow-script.js", lineOffset: -1 });
1304
+ } catch (error) {
1305
+ parentPort.postMessage({ type: "error", errorKind: "validation", error: isSyntaxError(error) ? formatWorkflowScriptSyntaxError(error) : formatWorkflowScriptError(error) });
979
1306
  return;
980
1307
  }
981
- if (message.type !== "start") return;
1308
+ if (!runtime.beginWorkflowScript()) return;
1309
+ stopWorkflowPromiseHook = createWorkflowPromiseHook({ init: runtime.hookInit, before: runtime.hookBefore, after: runtime.hookAfter });
1310
+ lockWorkerRealm();
1311
+ let result;
1312
+ let threw = false;
982
1313
  try {
983
- const sandbox = { runs, Promise: workflowPromise, emit(value) { const unwrapped = unwrapRunsAllResults(value); const emittedValue = unwrapped === undefined ? null : omitUndefinedWorkflowValues(unwrapped); assertJsonValue(emittedValue); parentPort.postMessage({ type: "emit", value: emittedValue }); }, console: capturedConsole };
984
- if (message.stateEnabled) sandbox.state = state;
985
- const context = vm.createContext(sandbox, { codeGeneration: { strings: false, wasm: false } });
986
- contextObjectPrototype = vm.runInContext("Object.prototype", context);
987
- // Rebuild args inside the VM realm: a worker-realm object would expose the worker's unrestricted
988
- // Function through args.constructor.constructor, bypassing codeGeneration.strings: false.
989
- sandbox.args = deepFreezeWorkflowArgs(vm.runInContext("JSON.parse", context)(JSON.stringify(message.args ?? {})));
990
- let compiled;
991
- try {
992
- assertPortableWorkflowScript(message.script);
993
- compiled = new vm.Script("(async () => {\n" + message.script + "\n})()", { filename: "workflow-script.js", lineOffset: -1 });
994
- } catch (error) {
995
- parentPort.postMessage({ type: "error", errorKind: "validation", error: isSyntaxError(error) ? formatWorkflowScriptSyntaxError(error) : formatWorkflowScriptError(error) });
1314
+ result = compiled.runInContext(context);
1315
+ } catch (error) {
1316
+ threw = true;
1317
+ result = error;
1318
+ }
1319
+ runtime.awaitWorkflowScript(threw, result);
1320
+ }
1321
+
1322
+ parentPort.on("message", (message) => {
1323
+ if (message.type === "response") {
1324
+ if (!runtime || typeof message.callId !== "number") return;
1325
+ if (!message.ok) {
1326
+ runtime.deliver(message.callId, false, undefined, message.error === undefined ? undefined : String(message.error), typeof message.errorKind === "string" ? message.errorKind : undefined);
996
1327
  return;
997
1328
  }
998
- const nativePromisePrototype = vm.runInContext("(async () => {})().constructor.prototype", context);
999
- const nativeThenDescriptor = Object.getOwnPropertyDescriptor(nativePromisePrototype, "then");
1000
- if (!nativeThenDescriptor || typeof nativeThenDescriptor.value !== "function") throw new Error("workflowScript could not inspect the VM Promise.prototype.then method.");
1001
- const nativeThen = nativeThenDescriptor.value;
1002
- let stopWorkflowPromiseHook;
1003
- let value;
1004
- try {
1005
- // Some hosts freeze built-ins in every realm, which makes then read-only. The promise hooks
1006
- // below still track observation, so skip the wrapper rather than fail every workflow.
1007
- if (nativeThenDescriptor.configurable) Object.defineProperty(nativePromisePrototype, "then", {
1008
- ...nativeThenDescriptor,
1009
- value: function workflowPromiseThen(...args) {
1010
- if (isDirectWorkflowScriptPromiseHandlerCall() || suppressNativePromiseConsumption > 0) {
1011
- return withSuppressedNativePromiseConsumption(() => Reflect.apply(nativeThen, this, args));
1012
- }
1013
- return Reflect.apply(nativeThen, this, args);
1014
- },
1015
- });
1016
- stopWorkflowPromiseHook = createWorkflowPromiseHook({
1017
- before(promise) {
1018
- activeNativePromises.push(promise);
1019
- },
1020
- after(promise) {
1021
- const index = activeNativePromises.lastIndexOf(promise);
1022
- if (index !== -1) activeNativePromises.splice(index, 1);
1023
- },
1024
- init(promise, parent) {
1025
- const childTracker = nativePromiseTracker(promise);
1026
- if (!parent) return;
1027
- nativePromiseParents.set(promise, parent);
1028
- const parentTracker = nativePromiseTracker(parent);
1029
- addTrackerDependency(childTracker, parentTracker);
1030
- const activePromise = activeNativePromises.at(-1);
1031
- if (activePromise && activePromise !== parent) {
1032
- addTrackerDependency(nativePromiseTracker(activePromise), parentTracker);
1033
- } else if (!activePromise && suppressNativePromiseConsumption === 0) {
1034
- markTrackedObservationsConsumed(parentTracker);
1035
- }
1036
- },
1037
- });
1038
- const workflowResultPromise = compiled.runInContext(context);
1039
- topLevelWorkflowPromise = workflowResultPromise;
1040
- markTrackedObservationsConsumed(nativePromiseTracker(workflowResultPromise));
1041
- value = await workflowResultPromise;
1042
- } finally {
1043
- try {
1044
- stopWorkflowPromiseHook?.();
1045
- } finally {
1046
- try {
1047
- if (nativeThenDescriptor.configurable) Object.defineProperty(nativePromisePrototype, "then", nativeThenDescriptor);
1048
- } finally {
1049
- topLevelWorkflowPromise = undefined;
1050
- activeNativePromises.length = 0;
1051
- suppressNativePromiseConsumption = 0;
1052
- nativePromiseTrackers = new WeakMap();
1053
- nativePromiseParents = new WeakMap();
1054
- }
1055
- }
1056
- }
1057
- const persistedValue = value === undefined ? null : omitUndefinedWorkflowValues(value);
1329
+ let encodedValue;
1058
1330
  try {
1059
- assertJsonValue(persistedValue, "return");
1331
+ encodedValue = JSON.stringify({ value: message.value });
1060
1332
  } catch (error) {
1061
- parentPort.postMessage({ type: "error", errorKind: "return-serialization", errorPhase: "return-serialization", error: formatWorkflowScriptError(error) });
1333
+ runtime.deliver(message.callId, false, undefined, "Workflow host response is not JSON: " + error.message, undefined);
1062
1334
  return;
1063
1335
  }
1064
- parentPort.postMessage({ type: "complete", value: persistedValue });
1336
+ runtime.deliver(message.callId, true, encodedValue, undefined, undefined);
1337
+ return;
1338
+ }
1339
+ if (message.type !== "start") return;
1340
+ try {
1341
+ startWorkflow(message);
1065
1342
  } catch (error) {
1066
- postWorkflowError(error);
1343
+ postWorkerError(error);
1067
1344
  }
1068
1345
  });