pi-subagents 0.82.1 → 0.83.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 (77) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/bundle/agents.js +4 -4
  3. package/bundle/background-work.js +1 -1
  4. package/bundle/child-tool-plan.js +3 -3
  5. package/bundle/{chunk-FXUXCX2K.js → chunk-4BW55BTL.js} +6 -6
  6. package/bundle/{chunk-PBK2I7WY.js → chunk-527E3D2J.js} +6 -6
  7. package/bundle/{chunk-46XKCPJR.js → chunk-5ESXK62X.js} +7 -1073
  8. package/bundle/{chunk-UTT254JE.js → chunk-6B4ITO2W.js} +8 -4
  9. package/bundle/{chunk-CIZQXJ5Q.js → chunk-7F5SK2U3.js} +39 -6
  10. package/bundle/{chunk-OYF6AFDY.js → chunk-BKFWQ642.js} +2 -2
  11. package/bundle/{chunk-ZIV4J4HG.js → chunk-CDI3GMNV.js} +47 -30
  12. package/bundle/{chunk-3JCDWF4V.js → chunk-CGXWSNPA.js} +12 -18
  13. package/bundle/{chunk-JYUKW2SY.js → chunk-CNLDYEH4.js} +12 -12
  14. package/bundle/{chunk-4SDU2BZX.js → chunk-CSSZRTKY.js} +2 -2
  15. package/bundle/{chunk-VSUSLDNW.js → chunk-CZTMUBUI.js} +10 -8
  16. package/bundle/{chunk-IVAE5Z6Q.js → chunk-HJJAVHFB.js} +28 -24
  17. package/bundle/{chunk-GJECHSAR.js → chunk-HLE22FSH.js} +2 -2
  18. package/bundle/{chunk-4Y2ROR7L.js → chunk-HXVKGS33.js} +5 -5
  19. package/bundle/{chunk-5LFLVSTM.js → chunk-JEZOSEWG.js} +2 -0
  20. package/bundle/{chunk-YKEWIB4M.js → chunk-JHZ6DZ5M.js} +1 -1
  21. package/bundle/{chunk-QE4AGIMG.js → chunk-LDMXJIA6.js} +457 -657
  22. package/bundle/{chunk-43SCHIMD.js → chunk-MBDOYZ2V.js} +1 -1
  23. package/bundle/{chunk-XSWOTIA3.js → chunk-MHX22USZ.js} +1 -1
  24. package/bundle/{chunk-6XJB7PIX.js → chunk-OOFW75PV.js} +4 -4
  25. package/bundle/{chunk-RMQFMMAT.js → chunk-P2NCCTZP.js} +231 -10
  26. package/bundle/{chunk-UCPP4GNU.js → chunk-RZJN63GU.js} +12 -5
  27. package/bundle/{chunk-G4GZD3OJ.js → chunk-TJQJ3MEA.js} +10 -10
  28. package/bundle/{chunk-5TYMSZX3.js → chunk-VTMNBPCQ.js} +2 -2
  29. package/bundle/{chunk-52UBALJL.js → chunk-WG2OTTAK.js} +2 -2
  30. package/bundle/{chunk-N2BN7BF5.js → chunk-XA3DY6UG.js} +7 -5
  31. package/bundle/{chunk-PDZWJCHD.js → chunk-XXKG3P2W.js} +9 -6
  32. package/bundle/{chunk-PLCCBLPY.js → chunk-Y3I6H6DV.js} +2 -2
  33. package/bundle/control-channel.js +3 -3
  34. package/bundle/index.js +1 -1
  35. package/bundle/intercom-bridge.js +3 -3
  36. package/bundle/preflight.js +9 -9
  37. package/bundle/project-panes.js +4 -4
  38. package/bundle/shared-types.js +1 -1
  39. package/docs/configuration.md +1 -1
  40. package/docs/extension-api.md +19 -4
  41. package/docs/observability.md +1 -0
  42. package/docs/tool-reference.md +1 -1
  43. package/package.json +1 -1
  44. package/skills/pi-subagents/SKILL.md +6 -6
  45. package/src/agents/agent-management.js +8 -14
  46. package/src/agents/agent-serializer.js +1 -2
  47. package/src/agents/agents.js +19 -3
  48. package/src/api/background-work.d.ts +9 -6
  49. package/src/api/background-work.js +14 -7
  50. package/src/extension/index.js +4 -1
  51. package/src/extension/public-execution.d.ts +2 -2
  52. package/src/extension/public-execution.js +3 -3
  53. package/src/extension/reply-workflow-script.js +4 -5
  54. package/src/extension/rpc.js +3 -1
  55. package/src/extension/subagent-options.js +17 -4
  56. package/src/runs/background/async-execution.js +4 -1
  57. package/src/runs/background/async-job-tracker.js +2 -1
  58. package/src/runs/background/auto-drain.js +2 -3
  59. package/src/runs/background/fleet-view.js +1 -1
  60. package/src/runs/background/run-child-session.js +22 -6
  61. package/src/runs/background/subagent-wait.d.ts +2 -1
  62. package/src/runs/background/subagent-wait.js +5 -2
  63. package/src/runs/foreground/execution.js +22 -6
  64. package/src/runs/foreground/subagent-executor.js +2 -5
  65. package/src/runs/shared/child-launch.js +5 -2
  66. package/src/runs/shared/child-session.d.ts +6 -0
  67. package/src/runs/shared/child-session.js +20 -4
  68. package/src/runs/shared/herdr-machine.d.ts +2 -0
  69. package/src/runs/shared/herdr-machine.js +2 -0
  70. package/src/runs/shared/herdr-placed-run.js +11 -4
  71. package/src/runs/shared/subagent-prompt-runtime.js +11 -17
  72. package/src/shared/disabled-features.d.ts +3 -1
  73. package/src/shared/disabled-features.js +11 -3
  74. package/src/shared/types.d.ts +3 -1
  75. package/src/shared/types.js +2 -0
  76. package/src/workflows/scripted-workflow.js +9 -1070
  77. package/workflow-script-worker.cjs +1067 -0
@@ -19,1075 +19,8 @@ function validGitRef(ref) {
19
19
  }
20
20
  const requireFromPackage = createRequire(import.meta.url);
21
21
  const WORKFLOW_ASSEMBLY_FLUSH_TIMEOUT_MS = 5_000;
22
- const WORKER_SOURCE = String.raw `
23
- const { parentPort, workerData } = require("node:worker_threads");
24
- const vm = require("node:vm");
25
- const { inspect } = require("node:util");
26
- const { parse } = require(workerData.acornPath);
27
-
28
- let promiseHooks;
29
- try {
30
- ({ promiseHooks } = require("node:v8"));
31
- } catch {}
32
-
33
- function createWorkflowPromiseHook(callbacks) {
34
- if (!promiseHooks || typeof promiseHooks.createHook !== "function") return () => {};
35
- try {
36
- return promiseHooks.createHook(callbacks);
37
- } catch (error) {
38
- if (error?.name !== "NotImplementedError") throw error;
39
- return () => {};
40
- }
41
- }
42
-
43
- let nextCallId = 0;
44
- let topLevelWorkflowPromise;
45
- let suppressNativePromiseConsumption = 0;
46
- const activeNativePromises = [];
47
- const pending = new Map();
48
- const workflowErrorKinds = new WeakMap();
49
- const runKeyPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
50
- function validGitRef(ref) {
51
- if (typeof ref !== "string" || !ref || ref === "@" || new TextEncoder().encode(ref).length > 1024 || ref.startsWith("/") || ref.endsWith("/") || ref.includes("//") || ref.includes("..") || ref.includes("@{")) return false;
52
- if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/iu.test(ref)) return false;
53
- if (/[[\]\\~^:?*\u0000-\u0020\u007f]/u.test(ref) || ref.endsWith(".") || ref.endsWith(".lock")) return false;
54
- return ref.split("/").every((component) => component.length > 0 && component !== "." && component !== ".." && !component.startsWith(".") && !component.endsWith(".") && !component.endsWith(".lock"));
55
- }
56
- const trackedPromiseTrackers = new WeakMap();
57
- const trackedPromiseTargets = new WeakMap();
58
- let nativePromiseTrackers = new WeakMap();
59
- let nativePromiseParents = new WeakMap();
60
- const observedCallIds = new Set();
61
-
62
- function stableRunJson(value) {
63
- if (Array.isArray(value)) return "[" + value.map(stableRunJson).join(",") + "]";
64
- if (value && typeof value === "object") return "{" + Object.keys(value).sort().map((key) => JSON.stringify(key) + ":" + stableRunJson(value[key])).join(",") + "}";
65
- return JSON.stringify(value) ?? "undefined";
66
- }
67
-
68
- function canonicalRunParams(params) {
69
- if (params.gate === undefined || params.acceptance !== false) return params;
70
- const { acceptance: _acceptance, ...withoutAcceptance } = params;
71
- return withoutAcceptance;
72
- }
73
-
74
- function isDirectWorkflowScriptPromiseHandlerCall() {
75
- const stack = new Error().stack;
76
- if (typeof stack !== "string") return false;
77
- return stack.split("\n").some((line) => line.includes("workflow-script.js") && !line.includes("at async "));
78
- }
79
-
80
- function nativePromiseTracker(promise) {
81
- if (!promise || (typeof promise !== "object" && typeof promise !== "function")) return undefined;
82
- let tracker = nativePromiseTrackers.get(promise);
83
- if (!tracker) {
84
- tracker = { observations: [], consumed: false, dependencies: [] };
85
- nativePromiseTrackers.set(promise, tracker);
86
- }
87
- return tracker;
88
- }
89
-
90
- function promiseObservationTracker(value) {
91
- if (!value || (typeof value !== "object" && typeof value !== "function")) return undefined;
92
- return trackedPromiseTrackers.get(value) ?? nativePromiseTrackers.get(value);
93
- }
94
-
95
- function addTrackerDependency(tracker, dependency) {
96
- if (!dependency) return;
97
- tracker.dependencies ??= [];
98
- if (!tracker.dependencies.includes(dependency)) tracker.dependencies.push(dependency);
99
- if (tracker.consumed) markTrackedObservationsConsumed(dependency);
100
- }
101
-
102
- function descendsFromTopLevelWorkflow(promise) {
103
- const seen = new Set();
104
- for (let current = promise; current && !seen.has(current); current = nativePromiseParents.get(current)) {
105
- if (current === topLevelWorkflowPromise) return true;
106
- seen.add(current);
107
- }
108
- return false;
109
- }
110
-
111
- function withSuppressedNativePromiseConsumption(callback) {
112
- suppressNativePromiseConsumption++;
113
- try {
114
- return callback();
115
- } finally {
116
- suppressNativePromiseConsumption--;
117
- }
118
- }
119
-
120
- function mergeObservations(...groups) {
121
- const seen = new Set();
122
- const merged = [];
123
- for (const group of groups) {
124
- for (const observation of group) {
125
- if (!observation || typeof observation.callId !== "number" || typeof observation.key !== "string" || typeof observation.operation !== "string" || seen.has(observation.callId)) continue;
126
- seen.add(observation.callId);
127
- merged.push(observation);
128
- }
129
- }
130
- return merged;
131
- }
132
-
133
- function trackedObservationTracker(value) {
134
- return value && (typeof value === "object" || typeof value === "function") ? trackedPromiseTrackers.get(value) : undefined;
135
- }
136
-
137
- function trackedPromiseTarget(value) {
138
- return value && (typeof value === "object" || typeof value === "function") ? trackedPromiseTargets.get(value) ?? value : value;
139
- }
140
-
141
- function addTrackedObservations(tracker, observations) {
142
- tracker.observations = mergeObservations(tracker.observations, observations);
143
- if (!tracker.consumed) return;
144
- for (const observation of tracker.observations) {
145
- if (observedCallIds.has(observation.callId)) continue;
146
- observedCallIds.add(observation.callId);
147
- parentPort.postMessage({ type: "callObserved", callId: observation.callId, key: observation.key, operation: observation.operation });
148
- }
149
- }
150
-
151
- function markTrackedObservationsConsumed(tracker, seen = new Set()) {
152
- if (seen.has(tracker)) return;
153
- seen.add(tracker);
154
- tracker.consumed = true;
155
- addTrackedObservations(tracker, []);
156
- for (const dependency of tracker.dependencies ?? []) markTrackedObservationsConsumed(dependency, seen);
157
- }
158
-
159
- function consumeTrackedObservations(tracker) {
160
- if (isDirectWorkflowScriptPromiseHandlerCall()) return;
161
- const activePromise = activeNativePromises.at(-1);
162
- if (activePromise === topLevelWorkflowPromise || descendsFromTopLevelWorkflow(activePromise)) {
163
- markTrackedObservationsConsumed(tracker);
164
- } else if (activePromise) {
165
- addTrackerDependency(nativePromiseTracker(activePromise), tracker);
166
- } else {
167
- markTrackedObservationsConsumed(tracker);
168
- }
169
- }
170
-
171
- function trackObservationTracker(tracker, promise, allowFutureObservations = false) {
172
- const target = trackedPromiseTarget(promise);
173
- if ((!allowFutureObservations && tracker.observations.length === 0) || !target || typeof target.then !== "function") return promise;
174
-
175
- const tracked = new Proxy(target, {
176
- get(promiseTarget, prop) {
177
- if (prop === "then") return function promiseThen(onFulfilled, onRejected) {
178
- consumeTrackedObservations(tracker);
179
- const chainTracker = { observations: tracker.observations, consumed: false, dependencies: [tracker] };
180
- const wrapHandler = (handler) => typeof handler === "function"
181
- ? function trackedThenHandler(...args) {
182
- const value = handler.apply(this, args);
183
- addTrackerDependency(chainTracker, promiseObservationTracker(value));
184
- return trackedPromiseTarget(value);
185
- }
186
- : handler;
187
- return trackObservationTracker(chainTracker, promiseTarget.then(wrapHandler(onFulfilled), wrapHandler(onRejected)), true);
188
- };
189
- if (prop === "catch") return function promiseCatch(onRejected) {
190
- consumeTrackedObservations(tracker);
191
- return trackObservationTracker({ observations: tracker.observations, consumed: false, dependencies: [tracker] }, promiseTarget.catch(onRejected), true);
192
- };
193
- if (prop === "finally") return function promiseFinally(onFinally) {
194
- consumeTrackedObservations(tracker);
195
- return trackObservationTracker({ observations: tracker.observations, consumed: false, dependencies: [tracker] }, promiseTarget.finally(onFinally), true);
196
- };
197
- return Reflect.get(promiseTarget, prop, promiseTarget);
198
- },
199
- });
200
- trackedPromiseTrackers.set(tracked, tracker);
201
- trackedPromiseTargets.set(tracked, target);
202
- return tracked;
203
- }
204
-
205
- function trackRunObservation(observations, promise) {
206
- const tracker = trackedObservationTracker(promise) ?? { observations: [], consumed: false };
207
- addTrackedObservations(tracker, observations);
208
- return trackObservationTracker(tracker, promise);
209
- }
210
-
211
- function trackPromiseCombinator(items, createPromise) {
212
- const values = Array.from(items);
213
- const dependencies = [...new Set(values.map(promiseObservationTracker).filter(Boolean))];
214
- const promise = withSuppressedNativePromiseConsumption(() => createPromise(values.map(trackedPromiseTarget)));
215
- if (dependencies.length === 0) return promise;
216
- return trackObservationTracker({ observations: [], consumed: false, dependencies }, promise, true);
217
- }
218
-
219
- // Hosts that freeze built-ins make Promise.all and friends non-writable and non-configurable, and a
220
- // Proxy over Promise itself may not return wrappers for those. Proxy a plain constructor instead.
221
- const workflowPromiseTarget = function Promise() {};
222
- workflowPromiseTarget.prototype = Promise.prototype;
223
- const workflowPromise = new Proxy(workflowPromiseTarget, {
224
- apply() {
225
- throw new TypeError("Promise constructor cannot be invoked without 'new'");
226
- },
227
- construct(_proxyTarget, [executor]) {
228
- const target = Promise;
229
- if (typeof executor !== "function") return new target(executor);
230
- const tracker = { observations: [], consumed: false };
231
- const promise = new target((resolve, reject) => {
232
- let settled = false;
233
- try {
234
- executor((value) => {
235
- if (settled) return;
236
- settled = true;
237
- addTrackerDependency(tracker, promiseObservationTracker(value));
238
- resolve(trackedPromiseTarget(value));
239
- }, (reason) => {
240
- if (settled) return;
241
- settled = true;
242
- reject(reason);
243
- });
244
- } catch (error) {
245
- settled = true;
246
- throw error;
247
- }
248
- });
249
- return trackObservationTracker(tracker, promise, true);
250
- },
251
- get(_proxyTarget, prop) {
252
- const target = Promise;
253
- if (prop === "all") return (items) => trackPromiseCombinator(items, (values) => target.all(values));
254
- if (prop === "allSettled") return (items) => trackPromiseCombinator(items, (values) => target.allSettled(values));
255
- if (prop === "race") return (items) => trackPromiseCombinator(items, (values) => target.race(values));
256
- if (prop === "any") return (items) => trackPromiseCombinator(items, (values) => target.any(values));
257
- if (prop === "resolve") return (value) => {
258
- const dependency = promiseObservationTracker(value);
259
- const promise = withSuppressedNativePromiseConsumption(() => target.resolve(trackedPromiseTarget(value)));
260
- if (!dependency) return promise;
261
- return trackObservationTracker({ observations: [], consumed: false, dependencies: [dependency] }, promise, true);
262
- };
263
- const value = target[prop];
264
- return typeof value === "function" ? value.bind(target) : value;
265
- },
266
- });
267
-
268
- function hostCall(method, args, observation) {
269
- const callId = ++nextCallId;
270
- const promise = new Promise((resolve, reject) => {
271
- pending.set(callId, { resolve, reject });
272
- parentPort.postMessage({ type: "call", callId, method, args });
273
- });
274
- return observation && typeof observation.key === "string" && typeof observation.operation === "string"
275
- ? trackRunObservation([{ key: observation.key, operation: observation.operation, callId }], promise)
276
- : promise;
277
- }
278
-
279
- function runHostCall(key, params, collectFailure, batch, generatedLaneKey) {
280
- const callId = ++nextCallId;
281
- const promise = new Promise((resolve, reject) => {
282
- pending.set(callId, { resolve, reject });
283
- parentPort.postMessage({ type: "call", callId, method: "run", args: { key, params, ...(collectFailure ? { collectFailure: true } : {}), ...(batch ? { batch } : {}), ...(generatedLaneKey ? { generatedLaneKey } : {}) } });
284
- });
285
- return { key, callId, promise };
286
- }
287
-
288
- function isArrayIndexProperty(prop) {
289
- if (!/^(0|[1-9]\d*)$/.test(prop)) return false;
290
- const index = Number(prop);
291
- return Number.isSafeInteger(index) && index >= 0 && index < 4294967295;
292
- }
293
-
294
- const runsAllResultTargets = new WeakMap();
295
-
296
- const MAX_LANES = 32;
297
- const MAX_LANE_STAGES = 16;
298
- const MAX_LANE_STAGE_COUNT = 64;
299
- const MAX_LANE_SPEC_BYTES = 64 * 1024;
300
- const MAX_LANE_TASK_BYTES = 1024 * 1024;
301
- const MAX_LANE_PATH_BYTES = 32 * 1024;
302
- const MAX_LANE_BOARD_TEXT_BYTES = 256;
303
- const LANE_PATH_FIELDS = new Set(["cwd", "output", "sessionDir"]);
304
-
305
- function runsAllKeyAccessError(prop) {
306
- return new Error("Cannot read runs.all result property '" + prop + "'. runs.all resolves to an ordered array, not a key map. Use results[0], array destructuring, or results.map((result) => result.output), not results." + prop + ".");
307
- }
308
-
309
- function wrapRunsAllResults(results, keys) {
310
- const keySet = new Set(keys);
311
- const proxy = new Proxy(results, {
312
- get(target, prop, receiver) {
313
- if (typeof prop !== "string") return Reflect.get(target, prop, receiver);
314
- if (prop === "then" || prop === "toJSON") return undefined;
315
- if (prop in target || isArrayIndexProperty(prop)) return Reflect.get(target, prop, receiver);
316
- if (keySet.has(prop)) throw runsAllKeyAccessError(prop);
317
- throw runsAllKeyAccessError(prop);
318
- },
319
- });
320
- runsAllResultTargets.set(proxy, results);
321
- return proxy;
322
- }
323
-
324
- function laneByteLength(value) {
325
- return new TextEncoder().encode(value).byteLength;
326
- }
327
-
328
- function laneBoardText(value) {
329
- if (typeof value !== "string" || !value) return undefined;
330
- if (laneByteLength(value) <= MAX_LANE_BOARD_TEXT_BYTES) return value;
331
- const bytes = new TextEncoder().encode(value).subarray(0, MAX_LANE_BOARD_TEXT_BYTES - 3);
332
- return new TextDecoder().decode(bytes) + "...";
333
- }
334
-
335
- function laneBoardPath(value) {
336
- if (typeof value !== "string" || !value || laneByteLength(value) > MAX_LANE_BOARD_TEXT_BYTES) return undefined;
337
- return value;
338
- }
339
-
340
- function validateLaneStageBounds(params, label) {
341
- if (typeof params.task === "string" && laneByteLength(params.task) > MAX_LANE_TASK_BYTES) throw new Error(label + " task exceeds 1 MiB when UTF-8 encoded.");
342
- for (const field of LANE_PATH_FIELDS) if (typeof params[field] === "string" && laneByteLength(params[field]) > MAX_LANE_PATH_BYTES) throw new Error(label + " " + field + " exceeds 32 KiB when UTF-8 encoded.");
343
- }
344
-
345
- function validateLaneKey(value, owner) {
346
- if (typeof value !== "string" || !runKeyPattern.test(value)) throw new Error(owner + " key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.");
347
- return value;
348
- }
349
-
350
- function laneStageParams(stage, previous) {
351
- const resume = stage.resume;
352
- const params = { ...stage.params };
353
- if (resume !== "previous") return params;
354
- if (!previous || typeof previous.runId !== "string" || !previous.runId.trim()) return undefined;
355
- return { ...params, resume: previous.runId.trim() };
356
- }
357
-
358
- function laneStageVerdict(result) {
359
- const structured = result && typeof result === "object" && !Array.isArray(result) ? result.structuredOutput : undefined;
360
- const verdict = structured && typeof structured === "object" && !Array.isArray(structured) ? structured.verdict : undefined;
361
- return typeof verdict === "string" && verdict.trim() ? laneBoardText(verdict.trim()) : undefined;
362
- }
363
-
364
- function laneStageIsBlocked(result) {
365
- const structured = result && typeof result === "object" && !Array.isArray(result) ? result.structuredOutput : undefined;
366
- return structured && typeof structured === "object" && !Array.isArray(structured) && structured.verdict === "blocked";
367
- }
368
-
369
- function laneStageRecord(stageKey, child, forcedState) {
370
- const result = child && typeof child === "object" && !Array.isArray(child) ? child : undefined;
371
- const ok = result?.ok === true;
372
- const verdict = laneStageVerdict(result);
373
- const blocked = laneStageIsBlocked(result);
374
- const state = forcedState ?? (result?.state === "running" ? "running" : result?.stopped ? "stopped" : result?.detached ? "detached" : ok ? blocked ? "blocked" : "completed" : "failed");
375
- const error = state !== "completed" && state !== "running"
376
- ? state === "blocked" && blocked
377
- ? "Stage returned a blocked verdict."
378
- : typeof result?.error === "string"
379
- ? result.error
380
- : typeof result?.output === "string"
381
- ? result.output
382
- : "Stage did not complete successfully."
383
- : undefined;
384
- return {
385
- key: stageKey,
386
- ...(typeof result?.runId === "string" && result.runId.trim() ? { runId: laneBoardText(result.runId.trim()) } : {}),
387
- ...(result ? { ok } : {}),
388
- state,
389
- ...(typeof result?.outputReference === "string" ? (laneBoardPath(result.outputReference) ? { outputReference: laneBoardPath(result.outputReference) } : {}) : {}),
390
- ...(verdict ? { verdict } : {}),
391
- ...(error ? { error: laneBoardText(error) } : {}),
392
- };
393
- }
394
-
395
- function laneFailure(stageKey, error) {
396
- const text = error instanceof Error ? error.message : String(error);
397
- return { key: stageKey, ok: false, output: text, error: text, artifactPaths: [] };
398
- }
399
-
400
- function runCollected(key, params, observe, generatedLaneKey) {
401
- validateRunCall(key, params, "runs.lanes stage", runFingerprints);
402
- const launched = runHostCall(key, params, true, undefined, generatedLaneKey);
403
- observe([{ key, operation: "run", callId: launched.callId }]);
404
- return launched.promise.then(decorateWorkflowChildResult);
405
- }
406
-
407
- function validateLaneSpecs(laneSpecs) {
408
- if (!Array.isArray(laneSpecs)) throw new Error("runs.lanes(lanes) requires an array.");
409
- if (laneSpecs.length === 0) throw new Error("runs.lanes(lanes) requires at least one lane.");
410
- if (laneSpecs.length > MAX_LANES) throw new Error("runs.lanes supports at most " + MAX_LANES + " lanes.");
411
- assertJsonValue(laneSpecs, "runs.lanes lanes");
412
- if (laneByteLength(stableRunJson(laneSpecs)) > MAX_LANE_SPEC_BYTES) throw new Error("runs.lanes canonical JSON exceeds 64 KiB.");
413
- const generatedKeys = new Set();
414
- const validationFingerprints = new Map();
415
- let stageCount = 0;
416
- const normalized = [];
417
- for (let laneIndex = 0; laneIndex < laneSpecs.length; laneIndex++) {
418
- const lane = laneSpecs[laneIndex];
419
- const laneLabel = "runs.lanes lane " + laneIndex;
420
- if (!lane || typeof lane !== "object" || Array.isArray(lane)) throw new Error(laneLabel + " must be an object.");
421
- const laneFields = Object.keys(lane);
422
- if (laneFields.some((field) => field !== "key" && field !== "stages")) throw new Error(laneLabel + " contains unsupported fields.");
423
- const laneKey = validateLaneKey(lane.key, laneLabel);
424
- if (!Array.isArray(lane.stages) || lane.stages.length === 0) throw new Error(laneLabel + " stages must contain at least one stage.");
425
- if (lane.stages.length > MAX_LANE_STAGES) throw new Error(laneLabel + " supports at most " + MAX_LANE_STAGES + " stages.");
426
- const stageKeys = new Set();
427
- const stages = [];
428
- for (let stageIndex = 0; stageIndex < lane.stages.length; stageIndex++) {
429
- stageCount++;
430
- if (stageCount > MAX_LANE_STAGE_COUNT) throw new Error("runs.lanes supports at most " + MAX_LANE_STAGE_COUNT + " total stages.");
431
- const stage = lane.stages[stageIndex];
432
- const stageLabel = laneLabel + " stage " + stageIndex;
433
- if (!stage || typeof stage !== "object" || Array.isArray(stage)) throw new Error(stageLabel + " must be an object.");
434
- const stageKey = validateLaneKey(stage.key, stageLabel);
435
- if (stageKeys.has(stageKey)) throw new Error(laneLabel + " contains duplicate stage key '" + stageKey + "'.");
436
- stageKeys.add(stageKey);
437
- const generatedKey = laneKey + "." + stageKey;
438
- validateLaneKey(generatedKey, stageLabel + " generated");
439
- if (generatedKeys.has(generatedKey)) throw new Error("runs.lanes generated child key '" + generatedKey + "' is duplicated.");
440
- generatedKeys.add(generatedKey);
441
- const resume = stage.resume;
442
- if (resume !== undefined && resume !== "previous") {
443
- if (stageIndex === 0 && typeof resume === "string") {
444
- throw new Error(stageLabel + " cannot resume a retained run id in runs.lanes; use runs.run(key, { resume: id }) outside lanes, or start the lane with an agent stage and use resume: \"previous\" later.");
445
- }
446
- throw new Error(stageLabel + " resume must be 'previous'.");
447
- }
448
- if (stageIndex === 0 && resume === "previous") throw new Error(stageLabel + " cannot resume previous without a predecessor stage.");
449
- const { key: _stageKey, resume: _resume, ...params } = stage;
450
- const validationParams = resume === "previous" ? { ...params, resume: "retained-run-placeholder" } : params;
451
- validateLaneStageBounds(validationParams, stageLabel);
452
- validateRunCall(generatedKey, validationParams, stageLabel, validationFingerprints);
453
- const existingFingerprint = runFingerprints.get(generatedKey);
454
- if (existingFingerprint !== undefined && (resume === "previous" || existingFingerprint !== stableRunJson(canonicalRunParams(params)))) {
455
- throw new Error("runs.lanes generated child key '" + generatedKey + "' is already used with incompatible launch params.");
456
- }
457
- stages.push({ key: stageKey, generatedKey, resume, params });
458
- }
459
- normalized.push({ key: laneKey, stages });
460
- }
461
- return normalized;
462
- }
463
-
464
- function runLane(lane, firstResult, observe) {
465
- const records = [];
466
- const appendSkipped = (start) => {
467
- for (let index = start; index < lane.stages.length; index++) records.push({ key: lane.stages[index].key, state: "skipped" });
468
- };
469
- const finish = (state, failedStage) => ({ key: lane.key, state, ...(failedStage ? { failedStage } : {}), stages: records });
470
- const visit = (index, previous) => {
471
- if (index >= lane.stages.length) return Promise.resolve(finish("complete"));
472
- const stage = lane.stages[index];
473
- if (index === 0) {
474
- const record = laneStageRecord(stage.key, previous);
475
- records.push(record);
476
- if (record.state !== "completed") {
477
- appendSkipped(index + 1);
478
- return Promise.resolve(finish("blocked", stage.key));
479
- }
480
- return visit(index + 1, previous);
481
- }
482
- if (stage.resume === "previous" && (!previous || typeof previous.runId !== "string" || !previous.runId.trim())) {
483
- records.push({ key: stage.key, state: "blocked", error: "Previous stage did not return a retained run id." });
484
- appendSkipped(index + 1);
485
- return Promise.resolve(finish("blocked", stage.key));
486
- }
487
- if (!previous || previous.ok !== true || laneStageIsBlocked(previous)) {
488
- records.push({ key: stage.key, state: "blocked", error: "Previous stage did not complete successfully." });
489
- appendSkipped(index + 1);
490
- return Promise.resolve(finish("blocked", stage.key));
491
- }
492
- const params = laneStageParams(stage, previous);
493
- if (!params) {
494
- records.push({ key: stage.key, state: "blocked", error: "Previous stage did not return a retained run id." });
495
- appendSkipped(index + 1);
496
- return Promise.resolve(finish("blocked", stage.key));
497
- }
498
- let launched;
499
- try {
500
- launched = runCollected(stage.generatedKey, params, observe, lane.key);
501
- } catch (error) {
502
- const failed = laneFailure(stage.generatedKey, error);
503
- records.push(laneStageRecord(stage.key, failed));
504
- appendSkipped(index + 1);
505
- return Promise.resolve(finish("blocked", stage.key));
506
- }
507
- return launched.then((result) => {
508
- const record = laneStageRecord(stage.key, result);
509
- records.push(record);
510
- if (record.state === "completed") return visit(index + 1, result);
511
- appendSkipped(index + 1);
512
- return finish("blocked", stage.key);
513
- }, (error) => {
514
- const failed = laneFailure(stage.generatedKey, error);
515
- records.push(laneStageRecord(stage.key, failed));
516
- appendSkipped(index + 1);
517
- return finish("blocked", stage.key);
518
- });
519
- };
520
- return visit(0, firstResult);
521
- }
522
-
523
- function workflowPlanStringMetadata(params) {
524
- return {
525
- ...(typeof params.phase === "string" && params.phase.trim() ? { phase: params.phase.trim() } : {}),
526
- ...(typeof params.label === "string" && params.label.trim() ? { label: params.label.trim() } : {}),
527
- ...(typeof params.agent === "string" && params.agent.trim() ? { agent: params.agent.trim() } : {}),
528
- };
529
- }
530
-
531
- function runLanes(laneSpecs) {
532
- const lanes = validateLaneSpecs(laneSpecs);
533
- parentPort.postMessage({ type: "lanePlan", lanes: lanes.map((lane) => ({
534
- key: lane.key,
535
- stages: lane.stages.map((stage) => ({
536
- key: stage.key,
537
- generatedKey: stage.generatedKey,
538
- ...workflowPlanStringMetadata(stage.params),
539
- ...(typeof stage.params.as === "string" && stage.params.as.trim() ? { outputName: stage.params.as.trim() } : {}),
540
- ...(stage.params.outputSchema ? { structured: true } : {}),
541
- })),
542
- })) });
543
- const firstItems = lanes.map((lane) => {
544
- const first = lane.stages[0];
545
- return { key: first.generatedKey, ...first.params };
546
- });
547
- // Share the runs.all batch launcher while allowing each lane to advance independently.
548
- const firstBatch = launchRunsAll(firstItems, lanes.map((lane) => lane.key));
549
- const firstResults = firstBatch.launched.map(({ promise }) => promise.then(decorateWorkflowChildResult));
550
- let trackedAggregate;
551
- const observe = (observations) => trackRunObservation(observations, trackedAggregate);
552
- const laneAggregate = Promise.all(lanes.map((lane, index) => firstResults[index].then(
553
- (result) => runLane(lane, result, observe),
554
- (error) => runLane(lane, laneFailure(lane.stages[0].generatedKey, error), observe),
555
- )));
556
- trackedAggregate = trackRunObservation(firstBatch.launched.map(({ key, callId }) => ({ key, operation: "run", callId })), laneAggregate);
557
- return trackedAggregate;
558
- }
559
-
560
- function formatRef(result) {
561
- if (!result || typeof result !== "object") throw new Error("runs.ref(result) requires a run result object.");
562
- const parts = ["run " + (result.key || "unknown")];
563
- if (result.runId) parts.push("id=" + String(result.runId).slice(0, 8));
564
- return "[" + parts.join("; ") + "]";
565
- }
566
-
567
- function formatChildResultString(result) {
568
- const output = typeof result?.output === "string" ? result.output.trim() : "";
569
- return output || formatRef(result);
570
- }
571
-
572
- function decorateWorkflowChildResult(result) {
573
- if (!result || typeof result !== "object" || Array.isArray(result)) return result;
574
- Object.defineProperties(result, {
575
- toString: { value() { return formatChildResultString(this); }, enumerable: false, configurable: true },
576
- });
577
- return result;
578
- }
579
-
580
- let runFingerprints = new Map();
581
-
582
- function validateExtensionBindings(value, label) {
583
- if (value === undefined) return;
584
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(label + " extensionBindings must be a plain JSON object.");
585
- const keys = Object.keys(value);
586
- if (keys.length > 16) throw new Error(label + " extensionBindings supports at most 16 namespaces.");
587
- for (const key of keys) if (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,62})\/[1-9][0-9]{0,8}$/.test(key)) throw new Error(label + " extensionBindings namespace '" + key + "' must use a package-like name followed by '/<positive-version>'.");
588
- assertJsonValue(value, label + " extensionBindings");
589
- let propertyCount = 0;
590
- function visit(entry, depth) {
591
- if (!entry || typeof entry !== "object") return;
592
- if (depth > 16) throw new Error(label + " extensionBindings exceeds the maximum nesting depth of 16.");
593
- if (Array.isArray(entry)) { for (const item of entry) visit(item, depth + 1); return; }
594
- for (const child of Object.values(entry)) {
595
- propertyCount++;
596
- if (propertyCount > 256) throw new Error(label + " extensionBindings exceeds 256 total properties.");
597
- visit(child, depth + 1);
598
- }
599
- }
600
- visit(value, 0);
601
- if (new TextEncoder().encode(stableRunJson(value)).byteLength > 16384) throw new Error(label + " extensionBindings canonical JSON exceeds 16384 bytes.");
602
- }
603
-
604
- function validateLaneMetadata(value, label, workflowKey) {
605
- if (value === undefined) return;
606
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(label + " must be a plain JSON object.");
607
- const fields = Object.keys(value);
608
- const allowed = ["version", "key", "mode", "sourceRef", "claims", "outputPaths"];
609
- const unknown = fields.filter((field) => !allowed.includes(field));
610
- if (unknown.length > 0) throw new Error(label + " has unsupported fields: " + unknown.join(", ") + ".");
611
- if (value.version !== 1) throw new Error(label + ".version must be 1.");
612
- if (typeof value.key !== "string" || !value.key.trim() || !runKeyPattern.test(value.key.trim())) throw new Error(label + ".key is invalid.");
613
- if (workflowKey !== undefined && value.key.trim() !== workflowKey) throw new Error(label + ".key must match workflow key '" + workflowKey + "'.");
614
- if (value.mode !== undefined && !["mutation", "review", "scout", "gate"].includes(value.mode)) throw new Error(label + ".mode is invalid.");
615
- const bounded = (entry, maxBytes) => typeof entry === "string" && entry.trim() && new TextEncoder().encode(entry.trim()).byteLength <= maxBytes && !/[\r\n\u0000]/.test(entry);
616
- if (value.sourceRef !== undefined && !bounded(value.sourceRef, 128)) throw new Error(label + ".sourceRef is invalid.");
617
- for (const [name, maxItems, maxLength] of [["claims", 20, 160], ["outputPaths", 10, 256]]) {
618
- if (value[name] === undefined) continue;
619
- if (!Array.isArray(value[name]) || value[name].length > maxItems || value[name].some((entry) => !bounded(entry, maxLength))) throw new Error(label + "." + name + " is invalid.");
620
- }
621
- }
622
-
623
- // Mirrors parseGateInput in src/runs/shared/acceptance.ts; the sandbox cannot import it.
624
- function describeGateShapeError(gate) {
625
- const shape = "gate must be a non-empty command string or { command, output?: \"json\", schema?, timeoutMs? }.";
626
- if (typeof gate === "string") return gate.trim() ? undefined : shape;
627
- if (!gate || typeof gate !== "object" || Array.isArray(gate)) return shape;
628
- for (const key of Object.keys(gate)) {
629
- if (!["command", "output", "schema", "timeoutMs"].includes(key)) return "gate." + key + " is not supported.";
630
- }
631
- if (typeof gate.command !== "string" || !gate.command.trim()) return shape;
632
- if (gate.output !== undefined && gate.output !== "json") return "gate.output must be \"json\" when present.";
633
- if (gate.schema !== undefined) {
634
- if (gate.output !== "json") return "gate.schema requires gate.output: \"json\".";
635
- if (!gate.schema || typeof gate.schema !== "object" || Array.isArray(gate.schema)) return "gate.schema must be a JSON Schema object.";
636
- }
637
- if (gate.timeoutMs !== undefined && (!Number.isInteger(gate.timeoutMs) || gate.timeoutMs < 1)) return "gate.timeoutMs must be an integer >= 1.";
638
- return undefined;
639
- }
640
-
641
- function describeGateAcceptanceConflict(gate, acceptance) {
642
- const render = (value) => {
643
- let encoded;
644
- try {
645
- encoded = JSON.stringify(value) ?? String(value);
646
- } catch {
647
- encoded = String(value);
648
- }
649
- return encoded.length > 120 ? encoded.slice(0, 120) + "..." : encoded;
650
- };
651
- return " Both fields were present: gate=" + render(gate) + " acceptance=" + render(acceptance) + ".";
652
- }
653
-
654
- function validateRunCall(key, params, label, fingerprints) {
655
- if (typeof key !== "string" || !runKeyPattern.test(key)) throw new Error(label + " has an invalid key.");
656
- if (hostKeys.has(key)) throw new Error("Workflow key '" + key + "' is already used by runs.host.");
657
- if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error(label + " requires a params object.");
658
- 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")) {
659
- const hint = label === "runs.run" ? "; use runs.all(...) and JavaScript control flow for orchestration." : ".";
660
- throw new Error(label + " accepts one child via { agent, task } and execution controls only" + hint);
661
- }
662
- if (Object.prototype.hasOwnProperty.call(params, "clarify")) throw new Error(label + " does not support clarify UI.");
663
- if (params.worktree !== undefined && typeof params.worktree !== "boolean") throw new Error(label + " worktree must be true or false.");
664
- if (params.baseRef !== undefined && (typeof params.baseRef !== "string" || !validGitRef(params.baseRef))) throw new Error(label + " baseRef must be a valid Git ref: use HEAD or a supported named ref (for example, refs/heads/main). Full 40/64-character commit IDs and revision expressions are unsupported.");
665
- validateLaneMetadata(params.lane, label + " lane", key);
666
- if (params.gate !== undefined) {
667
- const gateError = describeGateShapeError(params.gate);
668
- if (gateError) throw new Error(label + " " + gateError);
669
- }
670
- if (params.gate !== undefined && params.acceptance !== undefined && params.acceptance !== false) throw new Error(label + " gate cannot be combined with acceptance; use one gate command or acceptance.verify." + describeGateAcceptanceConflict(params.gate, params.acceptance));
671
- if (params.gate !== undefined && params.resume !== undefined) throw new Error(label + " gate is not supported with retained resume.");
672
- if (params.extensionBindings !== undefined && params.resume !== undefined) throw new Error(label + " extensionBindings is not supported with retained resume; resume uses the original retained child binding.");
673
- if (params.resume !== undefined && typeof params.resume !== "string") {
674
- const reference = params.resume;
675
- if (!reference || typeof reference !== "object" || Array.isArray(reference)) throw new Error(label + " resume must be a retained run id or keyed workflow receipt reference.");
676
- const fields = Object.keys(reference);
677
- if (fields.some((field) => field !== "workflowRunId" && field !== "key" && field !== "latest")) throw new Error(label + " keyed resume contains unsupported fields.");
678
- if (typeof reference.workflowRunId !== "string" || !reference.workflowRunId.trim()) throw new Error(label + " keyed resume workflowRunId must be non-empty.");
679
- if (typeof reference.key !== "string" || !runKeyPattern.test(reference.key)) throw new Error(label + " keyed resume key is invalid.");
680
- if (reference.latest !== true) throw new Error(label + " keyed resume requires latest: true.");
681
- }
682
- if (typeof params.resume === "string" && !params.resume.trim()) throw new Error(label + " resume must be a non-empty retained run id.");
683
- if (params.resume !== undefined && params.agent !== undefined) throw new Error(label + " resume and agent are mutually exclusive.");
684
- if (params.resume !== undefined && (typeof params.task !== "string" || !params.task.trim())) throw new Error(label + " resume requires a non-empty task follow-up.");
685
- validateExtensionBindings(params.extensionBindings, label);
686
- assertJsonValue(params, label + " params");
687
- const fingerprint = stableRunJson(canonicalRunParams(params));
688
- const existing = fingerprints.get(key);
689
- if (existing !== undefined && existing !== fingerprint) throw new Error("Duplicate workflow key '" + key + "' used with incompatible launch params.");
690
- fingerprints.set(key, fingerprint);
691
- }
692
-
693
- const hostKeys = new Set();
694
-
695
- function validateHostCommand(key, params) {
696
- validateLaneKey(key, "runs.host");
697
- if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error("runs.host('" + key + "') params must be an object.");
698
- const allowed = new Set(["kind", "command", "timeoutMs", "output", "role", "provider"]);
699
- const unknown = Object.keys(params).filter((field) => !allowed.has(field));
700
- if (unknown.length) {
701
- const cwdHint = unknown.includes("cwd")
702
- ? " The host step does not accept per-step cwd; commands and relative output paths use the workflow cwd. Set cwd on the outer subagent request, or put a trusted directory change in command (for example, 'cd /path/to/worktree && npm test')."
703
- : "";
704
- throw new Error("runs.host('" + key + "') params have unsupported fields: " + unknown.join(", ") + "." + cwdHint);
705
- }
706
- if (params.kind !== "command") throw new Error("runs.host('" + key + "') kind must be 'command'.");
707
- 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.");
708
- 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.");
709
- 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.");
710
- if (params.role !== undefined && params.role !== "ci" && params.role !== "gate") throw new Error("runs.host('" + key + "') role must be 'ci' or 'gate'.");
711
- 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.");
712
- assertJsonValue(params, "runs.host('" + key + "') params");
713
- if (hostKeys.has(key) || runFingerprints.has(key)) throw new Error("Workflow key '" + key + "' is already in use.");
714
- if (hostKeys.size >= 32) throw new Error("workflowScript supports at most 32 runs.host calls.");
715
- hostKeys.add(key);
716
- }
717
-
718
- const RUNS_ALL_PERMISSIVE_WARNING = "runs.all received runs.run(...) launch promise(s) or thenable(s). Those children were already launched individually, so runs.all cannot apply batch fingerprint validation, batch grouping in the fleet view, or collectFailure semantics; a failed child will throw at the runs.all boundary instead of returning as { ok: false }. To get full runs.all semantics, pass config objects: runs.all(items.map((item) => ({ key: item.key, agent: item.agent, task: item.task }))).";
719
-
720
- function runsAllItemThenableInfo(item, index) {
721
- if (!item || typeof item !== "object" || Array.isArray(item)) return null;
722
- if (typeof item.then !== "function") return null;
723
- const tracker = promiseObservationTracker(item);
724
- const observation = tracker && Array.isArray(tracker.observations) ? tracker.observations.find((entry) => entry && entry.operation === "run") : undefined;
725
- return {
726
- key: observation && typeof observation.key === "string" ? observation.key : ("runs.all[" + index + "]"),
727
- callId: observation && typeof observation.callId === "number" ? observation.callId : null,
728
- promise: item,
729
- };
730
- }
731
-
732
- let warnedPermissiveRunsAll = false;
733
-
734
- function launchRunsAll(items, generatedLaneKeys) {
735
- if (!Array.isArray(items)) throw new Error("runs.all(items) requires an array.");
736
- const anyThenable = items.some((item, index) => runsAllItemThenableInfo(item, index) !== null);
737
- if (anyThenable) return launchRunsAllPermissive(items);
738
- const fingerprints = new Map(runFingerprints);
739
- const calls = [];
740
- for (let index = 0; index < items.length; index++) {
741
- if (!Object.prototype.hasOwnProperty.call(items, index)) throw new Error("runs.all items must not contain sparse entries.");
742
- const item = items[index];
743
- if (!item || typeof item !== "object" || Array.isArray(item)) throw new Error("runs.all item " + index + " must be an object.");
744
- const { key, ...params } = item;
745
- validateRunCall(key, params, "runs.all item " + index, fingerprints);
746
- calls.push({ key, params });
747
- }
748
- runFingerprints = fingerprints;
749
- const batch = { id: "batch-" + (++nextCallId), calls };
750
- const launched = calls.map(({ key, params }, index) => runHostCall(key, params, true, batch, generatedLaneKeys?.[index]));
751
- return { calls, launched };
752
- }
753
-
754
- function launchRunsAllPermissive(items) {
755
- if (!warnedPermissiveRunsAll) {
756
- warnedPermissiveRunsAll = true;
757
- try { capturedConsole.warn(RUNS_ALL_PERMISSIVE_WARNING); } catch { /* console emission is best-effort */ }
758
- }
759
- const fingerprints = new Map(runFingerprints);
760
- const calls = [];
761
- const launched = [];
762
- for (let index = 0; index < items.length; index++) {
763
- if (!Object.prototype.hasOwnProperty.call(items, index)) throw new Error("runs.all items must not contain sparse entries.");
764
- const item = items[index];
765
- if (!item || typeof item !== "object" || Array.isArray(item)) throw new Error("runs.all item " + index + " must be an object or a runs.run(...) launch promise.");
766
- const thenable = runsAllItemThenableInfo(item, index);
767
- if (thenable) {
768
- calls.push({ key: thenable.key, params: {} });
769
- launched.push(thenable);
770
- continue;
771
- }
772
- const { key, ...params } = item;
773
- validateRunCall(key, params, "runs.all item " + index, fingerprints);
774
- calls.push({ key, params });
775
- launched.push(null);
776
- }
777
- runFingerprints = fingerprints;
778
- return { calls, launched: launched.map((entry, index) => entry ?? runHostCall(calls[index].key, calls[index].params, false, undefined)) };
779
- }
780
-
781
- const runs = Object.freeze({
782
- run(key, params) {
783
- validateRunCall(key, params, "runs.run", runFingerprints);
784
- const launched = runHostCall(key, params, false);
785
- return trackRunObservation([{ key, operation: "run", callId: launched.callId }], launched.promise.then(decorateWorkflowChildResult));
786
- },
787
- all(items) {
788
- const { calls, launched } = launchRunsAll(items);
789
- return trackRunObservation(launched.map(({ key, callId }) => ({ key, operation: "run", callId })), trackPromiseCombinator(launched.map(({ promise }) => promise), (values) => Promise.all(values).then((results) => wrapRunsAllResults(results.map(decorateWorkflowChildResult), calls.map(({ key }) => key)))));
790
- },
791
- lanes(laneSpecs) {
792
- return runLanes(laneSpecs);
793
- },
794
- host(key, params) {
795
- validateHostCommand(key, params);
796
- return hostCall("host", { key, params }, { key, operation: "host" });
797
- },
798
- steer(key, message, options = {}) {
799
- if (typeof key !== "string" || !runKeyPattern.test(key)) throw new Error("runs.steer has an invalid key.");
800
- if (typeof message !== "string" || !message.trim()) throw new Error("runs.steer message must be a non-empty string.");
801
- if (!options || typeof options !== "object" || Array.isArray(options)) throw new Error("runs.steer options must be an object.");
802
- const allowed = new Set(["mode", "index", "ackTimeoutMs"]);
803
- for (const option of Object.keys(options)) if (!allowed.has(option)) throw new Error("runs.steer options contain unsupported field '" + option + "'.");
804
- if (options.mode !== undefined && options.mode !== "steer" && options.mode !== "follow_up" && options.mode !== "auto") throw new Error("runs.steer mode must be 'steer', 'follow_up', or 'auto'.");
805
- if (options.index !== undefined && (!Number.isInteger(options.index) || options.index < 0 || options.index > 1000000)) throw new Error("runs.steer index must be an integer between 0 and 1000000.");
806
- if (options.ackTimeoutMs !== undefined && (!Number.isInteger(options.ackTimeoutMs) || options.ackTimeoutMs < 1)) throw new Error("runs.steer ackTimeoutMs must be a positive integer.");
807
- return hostCall("steer", { key, message: message.trim(), options }, { key, operation: "steer" });
808
- },
809
- status(keyOrRunId) { return hostCall("status", { keyOrRunId }); },
810
- ref: formatRef,
811
- refs(results) {
812
- if (!Array.isArray(results)) throw new Error("runs.refs(results) requires an array.");
813
- return results.map(formatRef).join("\n");
814
- },
815
- });
816
-
817
- function validateStateKey(key) {
818
- if (typeof key !== "string" || !runKeyPattern.test(key)) throw new Error("state key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.");
819
- return key;
820
- }
821
-
822
- const state = Object.freeze({
823
- get(key) { return hostCall("state.get", { key: validateStateKey(key) }); },
824
- set(key, value) {
825
- const validKey = validateStateKey(key);
826
- assertJsonValue(value, "state.set('" + validKey + "') value");
827
- return hostCall("state.set", { key: validKey, value });
828
- },
829
- });
830
-
831
- let contextObjectPrototype;
832
-
833
- const capturedConsole = Object.freeze(Object.fromEntries(
834
- ["log", "info", "warn", "error"].map((level) => [level, (...args) => {
835
- parentPort.postMessage({ type: "console", level, text: args.map((value) => typeof value === "string" ? value : inspect(value, { depth: 4, breakLength: 120 })).join(" ") });
836
- }]),
837
- ));
838
-
839
- function formatWorkflowScriptSyntaxError(error) {
840
- const details = formatWorkflowScriptError(error);
841
- return [
842
- "workflowScript must be valid JavaScript.",
843
- "If task text contains Markdown fences or backticks, use an array joined with \"\\n\" or escaped strings instead of a raw backtick template literal.",
844
- "",
845
- "Original SyntaxError:",
846
- details,
847
- ].join("\n");
848
- }
849
-
850
- function formatWorkflowScriptError(error) {
851
- const message = error && typeof error.message === "string" ? error.message : String(error);
852
- const stack = error && typeof error.stack === "string" ? error.stack : "";
853
- if (!stack) return message;
854
- return stack.includes(message) ? stack : message + "\n" + stack;
855
- }
856
-
857
- function isSyntaxError(error) {
858
- return error instanceof SyntaxError || error?.name === "SyntaxError";
859
- }
860
-
861
- function postWorkflowError(error) {
862
- // Pre-run syntax and portability errors are tagged "validation" where the script is compiled;
863
- // anything reaching here was thrown while the script ran, including a runtime SyntaxError.
864
- const taggedKind = error && (typeof error === "object" || typeof error === "function") ? workflowErrorKinds.get(error) : undefined;
865
- parentPort.postMessage({ type: "error", error: isSyntaxError(error) ? formatWorkflowScriptSyntaxError(error) : formatWorkflowScriptError(error), errorKind: taggedKind ?? "script" });
866
- }
867
-
868
- process.on("unhandledRejection", postWorkflowError);
869
-
870
- 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 } };";
871
- const AST_SCALAR_KEYS = new Set(["type", "start", "end"]);
872
-
873
- function assertPortableWorkflowScript(source) {
874
- const wrapped = "(async () => {\n" + source + "\n})()";
875
- let ast;
876
- try {
877
- ast = parse(wrapped, { ecmaVersion: "latest", sourceType: "script" });
878
- } catch (error) {
879
- // The wrapper adds one line before the script; report the script's own line.
880
- if (isSyntaxError(error) && typeof error.message === "string") {
881
- const message = error.message.replace(/\((\d+):(\d+)\)$/, (_match, line, column) => "(" + Math.max(1, Number(line) - 1) + ":" + column + ")");
882
- if (typeof error.stack === "string") error.stack = error.stack.replace(error.message, message);
883
- error.message = message;
884
- }
885
- throw error;
886
- }
887
- const wrapper = workflowWrapperFunction(ast);
888
- walkWorkflowAst(wrapper.body, wrapper);
889
- }
890
-
891
- function workflowWrapperFunction(ast) {
892
- const wrapper = ast.body?.[0]?.expression?.callee;
893
- if (!wrapper || wrapper.type !== "ArrowFunctionExpression") throw new Error("workflowScript wrapper parse invariant failed.");
894
- return wrapper;
895
- }
896
-
897
- function isAsyncFunctionNode(node) {
898
- return node.async === true && (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression");
899
- }
900
-
901
- function walkWorkflowAst(node, allowedAsyncFunction) {
902
- if (!node || typeof node !== "object") return;
903
- if (Array.isArray(node)) {
904
- for (const item of node) walkWorkflowAst(item, allowedAsyncFunction);
905
- return;
906
- }
907
- if (node !== allowedAsyncFunction && isAsyncFunctionNode(node)) {
908
- throw new Error(NESTED_ASYNC_WORKFLOW_ERROR);
909
- }
910
- for (const [key, child] of Object.entries(node)) {
911
- if (AST_SCALAR_KEYS.has(key)) continue;
912
- walkWorkflowAst(child, allowedAsyncFunction);
913
- }
914
- }
915
-
916
- function assertJsonValue(value, path = "emit", seen = new Set()) {
917
- if (value === null || typeof value === "string" || typeof value === "boolean") return;
918
- if (typeof value === "number") {
919
- if (!Number.isFinite(value)) throw new Error(path + " must contain only finite JSON numbers.");
920
- return;
921
- }
922
- if (typeof value !== "object") throw new Error(path + " must be a JSON value; received " + typeof value + ".");
923
- if (seen.has(value)) throw new Error(path + " must not contain cycles.");
924
- seen.add(value);
925
- if (Array.isArray(value)) {
926
- for (let index = 0; index < value.length; index++) {
927
- if (!Object.prototype.hasOwnProperty.call(value, index)) throw new Error(path + " must not contain sparse array entries.");
928
- assertJsonValue(value[index], path + "[" + index + "]", seen);
929
- }
930
- } else {
931
- const prototype = Object.getPrototypeOf(value);
932
- if (prototype !== null && prototype !== Object.prototype && prototype !== contextObjectPrototype) throw new Error(path + " must contain only plain JSON objects.");
933
- if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(path + " must not contain symbol keys.");
934
- for (const [key, entry] of Object.entries(value)) assertJsonValue(entry, path + "." + key, seen);
935
- }
936
- seen.delete(value);
937
- }
938
-
939
- function isPlainWorkflowObject(value) {
940
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
941
- const prototype = Object.getPrototypeOf(value);
942
- return prototype === null || prototype === Object.prototype || prototype === contextObjectPrototype;
943
- }
944
-
945
- function unwrapRunsAllResults(value, seen = new Map()) {
946
- if (value === null || typeof value !== "object") return value;
947
- const runsAllTarget = runsAllResultTargets.get(value);
948
- const target = runsAllTarget || value;
949
- if (seen.has(target)) return seen.get(target);
950
- if (Array.isArray(target)) {
951
- const copy = [];
952
- seen.set(target, copy);
953
- let changed = !!runsAllTarget;
954
- for (let index = 0; index < target.length; index++) {
955
- copy[index] = unwrapRunsAllResults(target[index], seen);
956
- changed ||= copy[index] !== target[index];
957
- }
958
- return changed ? copy : target;
959
- }
960
- if (!isPlainWorkflowObject(target) || Object.getOwnPropertySymbols(target).length > 0) return target;
961
- let changed = false;
962
- const entries = Object.entries(target).map(([key, entry]) => {
963
- const unwrapped = unwrapRunsAllResults(entry, seen);
964
- changed ||= unwrapped !== entry;
965
- return [key, unwrapped];
966
- });
967
- return changed ? Object.fromEntries(entries) : target;
968
- }
969
-
970
- function omitUndefinedWorkflowValues(value, seen = new Set()) {
971
- if (value === null || typeof value !== "object") return value;
972
- if (seen.has(value)) return value;
973
- seen.add(value);
974
- const normalized = Array.isArray(value)
975
- ? value.map((entry) => entry === undefined ? null : omitUndefinedWorkflowValues(entry, seen))
976
- : isPlainWorkflowObject(value) && Object.getOwnPropertySymbols(value).length === 0
977
- ? Object.fromEntries(Object.entries(value).flatMap(([key, entry]) => entry === undefined ? [] : [[key, omitUndefinedWorkflowValues(entry, seen)]]))
978
- : value;
979
- seen.delete(value);
980
- return normalized;
981
- }
982
-
983
- function deepFreezeWorkflowArgs(value) {
984
- if (value === null || typeof value !== "object" || Object.isFrozen(value)) return value;
985
- for (const entry of Object.values(value)) deepFreezeWorkflowArgs(entry);
986
- return Object.freeze(value);
987
- }
988
-
989
- parentPort.on("message", async (message) => {
990
- if (message.type === "response") {
991
- const entry = pending.get(message.callId);
992
- if (!entry) return;
993
- pending.delete(message.callId);
994
- if (message.ok) entry.resolve(message.value);
995
- else {
996
- const error = new Error(message.error);
997
- if (message.errorKind === "child" || message.errorKind === "detached-child") workflowErrorKinds.set(error, message.errorKind);
998
- entry.reject(error);
999
- }
1000
- return;
1001
- }
1002
- if (message.type !== "start") return;
1003
- try {
1004
- 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 };
1005
- if (message.stateEnabled) sandbox.state = state;
1006
- const context = vm.createContext(sandbox, { codeGeneration: { strings: false, wasm: false } });
1007
- contextObjectPrototype = vm.runInContext("Object.prototype", context);
1008
- // Rebuild args inside the VM realm: a worker-realm object would expose the worker's unrestricted
1009
- // Function through args.constructor.constructor, bypassing codeGeneration.strings: false.
1010
- sandbox.args = deepFreezeWorkflowArgs(vm.runInContext("JSON.parse", context)(JSON.stringify(message.args ?? {})));
1011
- let compiled;
1012
- try {
1013
- assertPortableWorkflowScript(message.script);
1014
- compiled = new vm.Script("(async () => {\n" + message.script + "\n})()", { filename: "workflow-script.js", lineOffset: -1 });
1015
- } catch (error) {
1016
- parentPort.postMessage({ type: "error", errorKind: "validation", error: isSyntaxError(error) ? formatWorkflowScriptSyntaxError(error) : formatWorkflowScriptError(error) });
1017
- return;
1018
- }
1019
- const nativePromisePrototype = vm.runInContext("(async () => {})().constructor.prototype", context);
1020
- const nativeThenDescriptor = Object.getOwnPropertyDescriptor(nativePromisePrototype, "then");
1021
- if (!nativeThenDescriptor || typeof nativeThenDescriptor.value !== "function") throw new Error("workflowScript could not inspect the VM Promise.prototype.then method.");
1022
- const nativeThen = nativeThenDescriptor.value;
1023
- let stopWorkflowPromiseHook;
1024
- let value;
1025
- try {
1026
- // Some hosts freeze built-ins in every realm, which makes then read-only. The promise hooks
1027
- // below still track observation, so skip the wrapper rather than fail every workflow.
1028
- if (nativeThenDescriptor.configurable) Object.defineProperty(nativePromisePrototype, "then", {
1029
- ...nativeThenDescriptor,
1030
- value: function workflowPromiseThen(...args) {
1031
- if (isDirectWorkflowScriptPromiseHandlerCall() || suppressNativePromiseConsumption > 0) {
1032
- return withSuppressedNativePromiseConsumption(() => Reflect.apply(nativeThen, this, args));
1033
- }
1034
- return Reflect.apply(nativeThen, this, args);
1035
- },
1036
- });
1037
- stopWorkflowPromiseHook = createWorkflowPromiseHook({
1038
- before(promise) {
1039
- activeNativePromises.push(promise);
1040
- },
1041
- after(promise) {
1042
- const index = activeNativePromises.lastIndexOf(promise);
1043
- if (index !== -1) activeNativePromises.splice(index, 1);
1044
- },
1045
- init(promise, parent) {
1046
- const childTracker = nativePromiseTracker(promise);
1047
- if (!parent) return;
1048
- nativePromiseParents.set(promise, parent);
1049
- const parentTracker = nativePromiseTracker(parent);
1050
- addTrackerDependency(childTracker, parentTracker);
1051
- const activePromise = activeNativePromises.at(-1);
1052
- if (activePromise && activePromise !== parent) {
1053
- addTrackerDependency(nativePromiseTracker(activePromise), parentTracker);
1054
- } else if (!activePromise && suppressNativePromiseConsumption === 0) {
1055
- markTrackedObservationsConsumed(parentTracker);
1056
- }
1057
- },
1058
- });
1059
- const workflowResultPromise = compiled.runInContext(context);
1060
- topLevelWorkflowPromise = workflowResultPromise;
1061
- markTrackedObservationsConsumed(nativePromiseTracker(workflowResultPromise));
1062
- value = await workflowResultPromise;
1063
- } finally {
1064
- try {
1065
- stopWorkflowPromiseHook?.();
1066
- } finally {
1067
- try {
1068
- if (nativeThenDescriptor.configurable) Object.defineProperty(nativePromisePrototype, "then", nativeThenDescriptor);
1069
- } finally {
1070
- topLevelWorkflowPromise = undefined;
1071
- activeNativePromises.length = 0;
1072
- suppressNativePromiseConsumption = 0;
1073
- nativePromiseTrackers = new WeakMap();
1074
- nativePromiseParents = new WeakMap();
1075
- }
1076
- }
1077
- }
1078
- const persistedValue = value === undefined ? null : omitUndefinedWorkflowValues(value);
1079
- try {
1080
- assertJsonValue(persistedValue, "return");
1081
- } catch (error) {
1082
- parentPort.postMessage({ type: "error", errorKind: "return-serialization", errorPhase: "return-serialization", error: formatWorkflowScriptError(error) });
1083
- return;
1084
- }
1085
- parentPort.postMessage({ type: "complete", value: persistedValue });
1086
- } catch (error) {
1087
- postWorkflowError(error);
1088
- }
1089
- });
1090
- `;
22
+ const WORKFLOW_WORKER_URL = new URL("../../workflow-script-worker.cjs", import.meta.url);
23
+ let nodeWorkerSource;
1091
24
  function isWorkflowScriptFailureKind(value) {
1092
25
  return value === "validation" || value === "script" || value === "child" || value === "return-serialization" || value === "timeout" || value === "detached-child" || value === "runtime";
1093
26
  }
@@ -2063,7 +996,13 @@ export async function runWorkflowScript(options) {
2063
996
  }
2064
997
  let worker;
2065
998
  try {
2066
- worker = new Worker(WORKER_SOURCE, { eval: true, workerData: { acornPath } });
999
+ const bun = typeof process.versions.bun === "string";
1000
+ // Bun needs a real file as its resolver base on warm transpiler-cache hits, and no eval key at all: with one,
1001
+ // its Worker finalizer passes the URL to URL.revokeObjectURL and throws. Node keeps eval source because its
1002
+ // eval worker does not re-resolve inherited --import preloads after a cwd change.
1003
+ worker = bun
1004
+ ? new Worker(WORKFLOW_WORKER_URL, { workerData: { acornPath } })
1005
+ : new Worker(nodeWorkerSource ??= readFileSync(WORKFLOW_WORKER_URL, "utf8"), { eval: true, workerData: { acornPath } });
2067
1006
  }
2068
1007
  catch (error) {
2069
1008
  throw new WorkflowScriptError(`Workflow worker could not start: ${error instanceof Error ? error.message : String(error)}`, emptyPartial(), "runtime", { cause: error });