@xzzpig/pi-subagents 0.8.0 → 0.10.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 (221) hide show
  1. package/CHANGELOG.md +477 -0
  2. package/README.md +2 -2
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +195 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +7 -6
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +384 -115
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +14 -2
  35. package/src/agents/agents.ts +935 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +42 -21
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +77 -21
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +65 -29
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +7 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +417 -133
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +60 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +204 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +718 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +489 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1223 -402
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +364 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +366 -0
  115. package/src/runs/shared/child-tool-plan.ts +632 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +146 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +99 -77
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +20 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/sandbox-profile-guard.ts +85 -0
  149. package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
  150. package/src/runs/shared/single-output.ts +89 -22
  151. package/src/runs/shared/structured-output.ts +49 -9
  152. package/src/runs/shared/subagent-control.ts +6 -2
  153. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  154. package/src/runs/shared/task-intent.ts +21 -7
  155. package/src/runs/shared/tool-availability.ts +18 -62
  156. package/src/runs/shared/tool-budget.ts +0 -14
  157. package/src/runs/shared/tool-timeout.ts +1 -1
  158. package/src/runs/shared/workflow-graph.ts +16 -0
  159. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  160. package/src/runs/shared/worktree.ts +571 -62
  161. package/src/shared/atomic-json.ts +3 -1
  162. package/src/shared/child-session-name.ts +46 -0
  163. package/src/shared/extension-context.ts +24 -0
  164. package/src/shared/fork-context.ts +21 -12
  165. package/src/shared/fork-session-cwd.ts +27 -0
  166. package/src/shared/formatters.ts +18 -3
  167. package/src/shared/jsonl-writer.ts +11 -0
  168. package/src/shared/launch-contract.ts +11 -1
  169. package/src/shared/pruned-fork.ts +450 -0
  170. package/src/shared/sandbox-profile.ts +23 -0
  171. package/src/shared/session-file-trust.ts +19 -0
  172. package/src/shared/session-tokens.ts +14 -3
  173. package/src/shared/settings.ts +19 -105
  174. package/src/shared/shortcuts.ts +17 -0
  175. package/src/shared/thinking-ceiling.ts +0 -6
  176. package/src/shared/types.ts +545 -70
  177. package/src/shared/utils.ts +60 -93
  178. package/src/shared/workflow-child-permit.ts +207 -0
  179. package/src/slash/delegation-adapters.ts +1 -9
  180. package/src/slash/delegation-request.ts +0 -4
  181. package/src/slash/prompt-template-bridge.ts +37 -1
  182. package/src/slash/slash-bridge.ts +1 -2
  183. package/src/slash/slash-commands.ts +383 -116
  184. package/src/slash/slash-live-state.ts +22 -11
  185. package/src/slash/subagents-admin.ts +29 -12
  186. package/src/tui/fleet-native-transcript.ts +4 -0
  187. package/src/tui/fleet-status.ts +217 -82
  188. package/src/tui/fleet-transcript.ts +11 -5
  189. package/src/tui/fleet.ts +54 -28
  190. package/src/tui/render-helpers.ts +31 -0
  191. package/src/tui/render.ts +1429 -163
  192. package/src/watchdog/change-signature.ts +40 -1
  193. package/src/watchdog/child-status.ts +54 -34
  194. package/src/watchdog/diff-tool.ts +77 -0
  195. package/src/watchdog/emission-guard.ts +5 -3
  196. package/src/watchdog/guidance.ts +20 -0
  197. package/src/watchdog/register-child.ts +28 -25
  198. package/src/watchdog/register-main.ts +10 -9
  199. package/src/watchdog/render.ts +4 -5
  200. package/src/watchdog/review.ts +15 -4
  201. package/src/watchdog/rules.ts +70 -0
  202. package/src/watchdog/runtime.ts +75 -92
  203. package/src/watchdog/scope.ts +0 -11
  204. package/src/watchdog/settings.ts +48 -104
  205. package/src/watchdog/turn-delta.ts +1 -1
  206. package/src/watchdog/types.ts +18 -32
  207. package/src/watchdog/warning-format.ts +0 -1
  208. package/src/workflows/chat-progress.ts +7 -3
  209. package/src/workflows/host-command.ts +235 -0
  210. package/src/workflows/scripted-workflow.ts +988 -59
  211. package/src/workflows/workflow-checklist.ts +439 -0
  212. package/src/workflows/workflow-child-summary.ts +121 -0
  213. package/src/workflows/workflow-preflight.ts +297 -0
  214. package/src/workflows/workflow-receipt.ts +232 -6
  215. package/src/workflows/workflow-resources.ts +150 -0
  216. package/src/workflows/workflow-settlement.ts +246 -0
  217. package/src/runs/shared/child-protocol.ts +0 -401
  218. package/src/runs/shared/pi-args.ts +0 -935
  219. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  220. package/src/runs/shared/turn-budget.ts +0 -98
  221. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -2,9 +2,32 @@ import { readFileSync } from "node:fs";
2
2
  import { createRequire } from "node:module";
3
3
  import { dirname, resolve as resolvePath } from "node:path";
4
4
  import { Worker } from "node:worker_threads";
5
+ import { DEFAULT_GLOBAL_CONCURRENCY_LIMIT, Semaphore } from "../runs/shared/parallel-utils.ts";
6
+ import { HOST_STEP_MAX_COUNT } from "../runs/shared/host-step-status.ts";
7
+ import { classifyTaskMutationIntent } from "../runs/shared/task-intent.ts";
8
+ import type { AcceptanceRecoveryMetadata, HostStepNodeV1, SingleResult } from "../shared/types.ts";
9
+ import { normalizeWorkflowHostCommandParams, type WorkflowHostCommandParams, type WorkflowHostCommandResult } from "./host-command.ts";
5
10
 
6
11
  const KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
12
+ function validGitRef(ref: unknown): ref is string {
13
+ if (typeof ref !== "string" || !ref || ref === "@" || Buffer.byteLength(ref, "utf-8") > 1024 || ref.startsWith("/") || ref.endsWith("/") || ref.includes("//") || ref.includes("..") || ref.includes("@{")) return false;
14
+ if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/iu.test(ref)) return false;
15
+ if (/[[\]\\~^:?*\u0000-\u0020\u007f]/u.test(ref) || ref.endsWith(".") || ref.endsWith(".lock")) return false;
16
+ return ref.split("/").every((component) => component.length > 0 && component !== "." && component !== ".." && !component.startsWith(".") && !component.endsWith(".") && !component.endsWith(".lock"));
17
+ }
7
18
  const requireFromPackage = createRequire(import.meta.url);
19
+ const WORKFLOW_ASSEMBLY_FLUSH_TIMEOUT_MS = 5_000;
20
+
21
+ export interface WorkflowScriptValidationError {
22
+ message: string;
23
+ line?: number;
24
+ column?: number;
25
+ }
26
+
27
+ export interface WorkflowScriptValidationResult {
28
+ ok: boolean;
29
+ errors: WorkflowScriptValidationError[];
30
+ }
8
31
 
9
32
  const WORKER_SOURCE = String.raw`
10
33
  const { parentPort, workerData } = require("node:worker_threads");
@@ -33,6 +56,12 @@ let suppressNativePromiseConsumption = 0;
33
56
  const activeNativePromises = [];
34
57
  const pending = new Map();
35
58
  const runKeyPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
59
+ function validGitRef(ref) {
60
+ if (typeof ref !== "string" || !ref || ref === "@" || new TextEncoder().encode(ref).length > 1024 || ref.startsWith("/") || ref.endsWith("/") || ref.includes("//") || ref.includes("..") || ref.includes("@{")) return false;
61
+ if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/iu.test(ref)) return false;
62
+ if (/[[\]\\~^:?*\u0000-\u0020\u007f]/u.test(ref) || ref.endsWith(".") || ref.endsWith(".lock")) return false;
63
+ return ref.split("/").every((component) => component.length > 0 && component !== "." && component !== ".." && !component.startsWith(".") && !component.endsWith(".") && !component.endsWith(".lock"));
64
+ }
36
65
  const trackedPromiseTrackers = new WeakMap();
37
66
  const trackedPromiseTargets = new WeakMap();
38
67
  let nativePromiseTrackers = new WeakMap();
@@ -241,11 +270,11 @@ function hostCall(method, args, observation) {
241
270
  : promise;
242
271
  }
243
272
 
244
- function runHostCall(key, params, collectFailure, batch) {
273
+ function runHostCall(key, params, collectFailure, batch, generatedLaneKey) {
245
274
  const callId = ++nextCallId;
246
275
  const promise = new Promise((resolve, reject) => {
247
276
  pending.set(callId, { resolve, reject });
248
- parentPort.postMessage({ type: "call", callId, method: "run", args: { key, params, ...(collectFailure ? { collectFailure: true } : {}), ...(batch ? { batch } : {}) } });
277
+ parentPort.postMessage({ type: "call", callId, method: "run", args: { key, params, ...(collectFailure ? { collectFailure: true } : {}), ...(batch ? { batch } : {}), ...(generatedLaneKey ? { generatedLaneKey } : {}) } });
249
278
  });
250
279
  return { key, callId, promise };
251
280
  }
@@ -258,6 +287,15 @@ function isArrayIndexProperty(prop) {
258
287
 
259
288
  const runsAllResultTargets = new WeakMap();
260
289
 
290
+ const MAX_LANES = 32;
291
+ const MAX_LANE_STAGES = 16;
292
+ const MAX_LANE_STAGE_COUNT = 64;
293
+ const MAX_LANE_SPEC_BYTES = 64 * 1024;
294
+ const MAX_LANE_TASK_BYTES = 1024 * 1024;
295
+ const MAX_LANE_PATH_BYTES = 32 * 1024;
296
+ const MAX_LANE_BOARD_TEXT_BYTES = 256;
297
+ const LANE_PATH_FIELDS = new Set(["cwd", "output", "sessionDir"]);
298
+
261
299
  function runsAllKeyAccessError(prop) {
262
300
  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 + ".");
263
301
  }
@@ -277,6 +315,242 @@ function wrapRunsAllResults(results, keys) {
277
315
  return proxy;
278
316
  }
279
317
 
318
+ function laneByteLength(value) {
319
+ return new TextEncoder().encode(value).byteLength;
320
+ }
321
+
322
+ function laneBoardText(value) {
323
+ if (typeof value !== "string" || !value) return undefined;
324
+ if (laneByteLength(value) <= MAX_LANE_BOARD_TEXT_BYTES) return value;
325
+ const bytes = new TextEncoder().encode(value).subarray(0, MAX_LANE_BOARD_TEXT_BYTES - 3);
326
+ return new TextDecoder().decode(bytes) + "...";
327
+ }
328
+
329
+ function laneBoardPath(value) {
330
+ if (typeof value !== "string" || !value || laneByteLength(value) > MAX_LANE_BOARD_TEXT_BYTES) return undefined;
331
+ return value;
332
+ }
333
+
334
+ function validateLaneStageBounds(params, label) {
335
+ if (typeof params.task === "string" && laneByteLength(params.task) > MAX_LANE_TASK_BYTES) throw new Error(label + " task exceeds 1 MiB when UTF-8 encoded.");
336
+ 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.");
337
+ }
338
+
339
+ function validateLaneKey(value, owner) {
340
+ 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.");
341
+ return value;
342
+ }
343
+
344
+ function laneStageParams(stage, previous) {
345
+ const resume = stage.resume;
346
+ const params = { ...stage.params };
347
+ if (resume !== "previous") return params;
348
+ if (!previous || typeof previous.runId !== "string" || !previous.runId.trim()) return undefined;
349
+ return { ...params, resume: previous.runId.trim() };
350
+ }
351
+
352
+ function laneStageVerdict(result) {
353
+ const structured = result && typeof result === "object" && !Array.isArray(result) ? result.structuredOutput : undefined;
354
+ const verdict = structured && typeof structured === "object" && !Array.isArray(structured) ? structured.verdict : undefined;
355
+ return typeof verdict === "string" && verdict.trim() ? laneBoardText(verdict.trim()) : undefined;
356
+ }
357
+
358
+ function laneStageIsBlocked(result) {
359
+ const structured = result && typeof result === "object" && !Array.isArray(result) ? result.structuredOutput : undefined;
360
+ return structured && typeof structured === "object" && !Array.isArray(structured) && structured.verdict === "blocked";
361
+ }
362
+
363
+ function laneStageRecord(stageKey, child, forcedState) {
364
+ const result = child && typeof child === "object" && !Array.isArray(child) ? child : undefined;
365
+ const ok = result?.ok === true;
366
+ const verdict = laneStageVerdict(result);
367
+ const blocked = laneStageIsBlocked(result);
368
+ const state = forcedState ?? (result?.stopped ? "stopped" : result?.detached ? "detached" : ok ? blocked ? "blocked" : "completed" : "failed");
369
+ const error = state !== "completed"
370
+ ? state === "blocked" && blocked
371
+ ? "Stage returned a blocked verdict."
372
+ : typeof result?.error === "string"
373
+ ? result.error
374
+ : typeof result?.output === "string"
375
+ ? result.output
376
+ : "Stage did not complete successfully."
377
+ : undefined;
378
+ return {
379
+ key: stageKey,
380
+ ...(typeof result?.runId === "string" && result.runId.trim() ? { runId: laneBoardText(result.runId.trim()) } : {}),
381
+ ...(result ? { ok } : {}),
382
+ state,
383
+ ...(typeof result?.outputReference === "string" ? (laneBoardPath(result.outputReference) ? { outputReference: laneBoardPath(result.outputReference) } : {}) : {}),
384
+ ...(verdict ? { verdict } : {}),
385
+ ...(error ? { error: laneBoardText(error) } : {}),
386
+ };
387
+ }
388
+
389
+ function laneFailure(stageKey, error) {
390
+ const text = error instanceof Error ? error.message : String(error);
391
+ return { key: stageKey, ok: false, output: text, error: text, artifactPaths: [] };
392
+ }
393
+
394
+ function runCollected(key, params, observe, generatedLaneKey) {
395
+ validateRunCall(key, params, "runs.lanes stage", runFingerprints);
396
+ const launched = runHostCall(key, params, true, undefined, generatedLaneKey);
397
+ observe([{ key, operation: "run", callId: launched.callId }]);
398
+ return launched.promise.then(decorateWorkflowChildResult);
399
+ }
400
+
401
+ function validateLaneSpecs(laneSpecs) {
402
+ if (!Array.isArray(laneSpecs)) throw new Error("runs.lanes(lanes) requires an array.");
403
+ if (laneSpecs.length === 0) throw new Error("runs.lanes(lanes) requires at least one lane.");
404
+ if (laneSpecs.length > MAX_LANES) throw new Error("runs.lanes supports at most " + MAX_LANES + " lanes.");
405
+ assertJsonValue(laneSpecs, "runs.lanes lanes");
406
+ if (laneByteLength(stableRunJson(laneSpecs)) > MAX_LANE_SPEC_BYTES) throw new Error("runs.lanes canonical JSON exceeds 64 KiB.");
407
+ const generatedKeys = new Set();
408
+ const validationFingerprints = new Map();
409
+ let stageCount = 0;
410
+ const normalized = [];
411
+ for (let laneIndex = 0; laneIndex < laneSpecs.length; laneIndex++) {
412
+ const lane = laneSpecs[laneIndex];
413
+ const laneLabel = "runs.lanes lane " + laneIndex;
414
+ if (!lane || typeof lane !== "object" || Array.isArray(lane)) throw new Error(laneLabel + " must be an object.");
415
+ const laneFields = Object.keys(lane);
416
+ if (laneFields.some((field) => field !== "key" && field !== "stages")) throw new Error(laneLabel + " contains unsupported fields.");
417
+ const laneKey = validateLaneKey(lane.key, laneLabel);
418
+ if (!Array.isArray(lane.stages) || lane.stages.length === 0) throw new Error(laneLabel + " stages must contain at least one stage.");
419
+ if (lane.stages.length > MAX_LANE_STAGES) throw new Error(laneLabel + " supports at most " + MAX_LANE_STAGES + " stages.");
420
+ const stageKeys = new Set();
421
+ const stages = [];
422
+ for (let stageIndex = 0; stageIndex < lane.stages.length; stageIndex++) {
423
+ stageCount++;
424
+ if (stageCount > MAX_LANE_STAGE_COUNT) throw new Error("runs.lanes supports at most " + MAX_LANE_STAGE_COUNT + " total stages.");
425
+ const stage = lane.stages[stageIndex];
426
+ const stageLabel = laneLabel + " stage " + stageIndex;
427
+ if (!stage || typeof stage !== "object" || Array.isArray(stage)) throw new Error(stageLabel + " must be an object.");
428
+ const stageKey = validateLaneKey(stage.key, stageLabel);
429
+ if (stageKeys.has(stageKey)) throw new Error(laneLabel + " contains duplicate stage key '" + stageKey + "'.");
430
+ stageKeys.add(stageKey);
431
+ const generatedKey = laneKey + "." + stageKey;
432
+ validateLaneKey(generatedKey, stageLabel + " generated");
433
+ if (generatedKeys.has(generatedKey)) throw new Error("runs.lanes generated child key '" + generatedKey + "' is duplicated.");
434
+ generatedKeys.add(generatedKey);
435
+ const resume = stage.resume;
436
+ if (resume !== undefined && resume !== "previous") {
437
+ if (stageIndex === 0 && typeof resume === "string") {
438
+ 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.");
439
+ }
440
+ throw new Error(stageLabel + " resume must be 'previous'.");
441
+ }
442
+ if (stageIndex === 0 && resume === "previous") throw new Error(stageLabel + " cannot resume previous without a predecessor stage.");
443
+ const { key: _stageKey, resume: _resume, ...params } = stage;
444
+ const validationParams = resume === "previous" ? { ...params, resume: "retained-run-placeholder" } : params;
445
+ validateLaneStageBounds(validationParams, stageLabel);
446
+ validateRunCall(generatedKey, validationParams, stageLabel, validationFingerprints);
447
+ const existingFingerprint = runFingerprints.get(generatedKey);
448
+ if (existingFingerprint !== undefined && (resume === "previous" || existingFingerprint !== stableRunJson(params))) {
449
+ throw new Error("runs.lanes generated child key '" + generatedKey + "' is already used with incompatible launch params.");
450
+ }
451
+ stages.push({ key: stageKey, generatedKey, resume, params });
452
+ }
453
+ normalized.push({ key: laneKey, stages });
454
+ }
455
+ return normalized;
456
+ }
457
+
458
+ function runLane(lane, firstResult, observe) {
459
+ const records = [];
460
+ const appendSkipped = (start) => {
461
+ for (let index = start; index < lane.stages.length; index++) records.push({ key: lane.stages[index].key, state: "skipped" });
462
+ };
463
+ const finish = (state, failedStage) => ({ key: lane.key, state, ...(failedStage ? { failedStage } : {}), stages: records });
464
+ const visit = (index, previous) => {
465
+ if (index >= lane.stages.length) return Promise.resolve(finish("complete"));
466
+ const stage = lane.stages[index];
467
+ if (index === 0) {
468
+ const record = laneStageRecord(stage.key, previous);
469
+ records.push(record);
470
+ if (record.state !== "completed") {
471
+ appendSkipped(index + 1);
472
+ return Promise.resolve(finish("blocked", stage.key));
473
+ }
474
+ return visit(index + 1, previous);
475
+ }
476
+ if (stage.resume === "previous" && (!previous || typeof previous.runId !== "string" || !previous.runId.trim())) {
477
+ records.push({ key: stage.key, state: "blocked", error: "Previous stage did not return a retained run id." });
478
+ appendSkipped(index + 1);
479
+ return Promise.resolve(finish("blocked", stage.key));
480
+ }
481
+ if (!previous || previous.ok !== true || laneStageIsBlocked(previous)) {
482
+ records.push({ key: stage.key, state: "blocked", error: "Previous stage did not complete successfully." });
483
+ appendSkipped(index + 1);
484
+ return Promise.resolve(finish("blocked", stage.key));
485
+ }
486
+ const params = laneStageParams(stage, previous);
487
+ if (!params) {
488
+ records.push({ key: stage.key, state: "blocked", error: "Previous stage did not return a retained run id." });
489
+ appendSkipped(index + 1);
490
+ return Promise.resolve(finish("blocked", stage.key));
491
+ }
492
+ let launched;
493
+ try {
494
+ launched = runCollected(stage.generatedKey, params, observe, lane.key);
495
+ } catch (error) {
496
+ const failed = laneFailure(stage.generatedKey, error);
497
+ records.push(laneStageRecord(stage.key, failed));
498
+ appendSkipped(index + 1);
499
+ return Promise.resolve(finish("blocked", stage.key));
500
+ }
501
+ return launched.then((result) => {
502
+ const record = laneStageRecord(stage.key, result);
503
+ records.push(record);
504
+ if (record.state === "completed") return visit(index + 1, result);
505
+ appendSkipped(index + 1);
506
+ return finish("blocked", stage.key);
507
+ }, (error) => {
508
+ const failed = laneFailure(stage.generatedKey, error);
509
+ records.push(laneStageRecord(stage.key, failed));
510
+ appendSkipped(index + 1);
511
+ return finish("blocked", stage.key);
512
+ });
513
+ };
514
+ return visit(0, firstResult);
515
+ }
516
+
517
+ function workflowPlanStringMetadata(params) {
518
+ return {
519
+ ...(typeof params.phase === "string" && params.phase.trim() ? { phase: params.phase.trim() } : {}),
520
+ ...(typeof params.label === "string" && params.label.trim() ? { label: params.label.trim() } : {}),
521
+ ...(typeof params.agent === "string" && params.agent.trim() ? { agent: params.agent.trim() } : {}),
522
+ };
523
+ }
524
+
525
+ function runLanes(laneSpecs) {
526
+ const lanes = validateLaneSpecs(laneSpecs);
527
+ parentPort.postMessage({ type: "lanePlan", lanes: lanes.map((lane) => ({
528
+ key: lane.key,
529
+ stages: lane.stages.map((stage) => ({
530
+ key: stage.key,
531
+ generatedKey: stage.generatedKey,
532
+ ...workflowPlanStringMetadata(stage.params),
533
+ ...(typeof stage.params.as === "string" && stage.params.as.trim() ? { outputName: stage.params.as.trim() } : {}),
534
+ ...(stage.params.outputSchema !== undefined ? { structured: true } : {}),
535
+ })),
536
+ })) });
537
+ const firstItems = lanes.map((lane) => {
538
+ const first = lane.stages[0];
539
+ return { key: first.generatedKey, ...first.params };
540
+ });
541
+ // Share the runs.all batch launcher while allowing each lane to advance independently.
542
+ const firstBatch = launchRunsAll(firstItems, lanes.map((lane) => lane.key));
543
+ const firstResults = firstBatch.launched.map(({ promise }) => promise.then(decorateWorkflowChildResult));
544
+ let trackedAggregate;
545
+ const observe = (observations) => trackRunObservation(observations, trackedAggregate);
546
+ const laneAggregate = Promise.all(lanes.map((lane, index) => firstResults[index].then(
547
+ (result) => runLane(lane, result, observe),
548
+ (error) => runLane(lane, laneFailure(lane.stages[0].generatedKey, error), observe),
549
+ )));
550
+ trackedAggregate = trackRunObservation(firstBatch.launched.map(({ key, callId }) => ({ key, operation: "run", callId })), laneAggregate);
551
+ return trackedAggregate;
552
+ }
553
+
280
554
  function formatRef(result) {
281
555
  if (!result || typeof result !== "object") throw new Error("runs.ref(result) requires a run result object.");
282
556
  const parts = ["run " + (result.key || "unknown")];
@@ -321,15 +595,37 @@ function validateExtensionBindings(value, label) {
321
595
  if (new TextEncoder().encode(stableRunJson(value)).byteLength > 16384) throw new Error(label + " extensionBindings canonical JSON exceeds 16384 bytes.");
322
596
  }
323
597
 
598
+ function validateLaneMetadata(value, label, workflowKey) {
599
+ if (value === undefined) return;
600
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(label + " must be a plain JSON object.");
601
+ const fields = Object.keys(value);
602
+ const allowed = ["version", "key", "mode", "sourceRef", "claims", "outputPaths"];
603
+ const unknown = fields.filter((field) => !allowed.includes(field));
604
+ if (unknown.length > 0) throw new Error(label + " has unsupported fields: " + unknown.join(", ") + ".");
605
+ if (value.version !== 1) throw new Error(label + ".version must be 1.");
606
+ if (typeof value.key !== "string" || !value.key.trim() || !runKeyPattern.test(value.key.trim())) throw new Error(label + ".key is invalid.");
607
+ if (workflowKey !== undefined && value.key.trim() !== workflowKey) throw new Error(label + ".key must match workflow key '" + workflowKey + "'.");
608
+ if (value.mode !== undefined && !["mutation", "review", "scout", "gate"].includes(value.mode)) throw new Error(label + ".mode is invalid.");
609
+ const bounded = (entry, maxBytes) => typeof entry === "string" && entry.trim() && new TextEncoder().encode(entry.trim()).byteLength <= maxBytes && !/[\r\n\u0000]/.test(entry);
610
+ if (value.sourceRef !== undefined && !bounded(value.sourceRef, 128)) throw new Error(label + ".sourceRef is invalid.");
611
+ for (const [name, maxItems, maxLength] of [["claims", 20, 160], ["outputPaths", 10, 256]]) {
612
+ if (value[name] === undefined) continue;
613
+ if (!Array.isArray(value[name]) || value[name].length > maxItems || value[name].some((entry) => !bounded(entry, maxLength))) throw new Error(label + "." + name + " is invalid.");
614
+ }
615
+ }
616
+
324
617
  function validateRunCall(key, params, label, fingerprints) {
325
618
  if (typeof key !== "string" || !runKeyPattern.test(key)) throw new Error(label + " has an invalid key.");
619
+ if (hostKeys.has(key)) throw new Error("Workflow key '" + key + "' is already used by runs.host.");
326
620
  if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error(label + " requires a params object.");
327
- if (Object.prototype.hasOwnProperty.call(params, "action") || Object.prototype.hasOwnProperty.call(params, "workflowScript") || 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")) {
621
+ 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")) {
328
622
  const hint = label === "runs.run" ? "; use runs.all(...) and JavaScript control flow for orchestration." : ".";
329
623
  throw new Error(label + " accepts one child via { agent, task } and execution controls only" + hint);
330
624
  }
331
625
  if (Object.prototype.hasOwnProperty.call(params, "clarify")) throw new Error(label + " does not support clarify UI.");
332
626
  if (params.worktree !== undefined && typeof params.worktree !== "boolean") throw new Error(label + " worktree must be true or false.");
627
+ if (params.baseRef !== undefined && (typeof params.baseRef !== "string" || !validGitRef(params.baseRef))) throw new Error(label + " baseRef must be a valid Git ref.");
628
+ validateLaneMetadata(params.lane, label + " lane", key);
333
629
  if (params.gate !== undefined && (typeof params.gate !== "string" || !params.gate.trim())) throw new Error(label + " gate must be a non-empty command string.");
334
630
  if (params.gate !== undefined && params.acceptance !== undefined) throw new Error(label + " gate cannot be combined with acceptance; use one gate command or acceptance.verify.");
335
631
  if (params.gate !== undefined && params.resume !== undefined) throw new Error(label + " gate is not supported with retained resume.");
@@ -354,6 +650,49 @@ function validateRunCall(key, params, label, fingerprints) {
354
650
  fingerprints.set(key, fingerprint);
355
651
  }
356
652
 
653
+ const hostKeys = new Set();
654
+
655
+ function validateHostCommand(key, params) {
656
+ validateLaneKey(key, "runs.host");
657
+ if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error("runs.host('" + key + "') params must be an object.");
658
+ const allowed = new Set(["kind", "command", "timeoutMs", "output", "role", "provider"]);
659
+ const unknown = Object.keys(params).filter((field) => !allowed.has(field));
660
+ if (unknown.length) {
661
+ const cwdHint = unknown.includes("cwd")
662
+ ? " 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')."
663
+ : "";
664
+ throw new Error("runs.host('" + key + "') params have unsupported fields: " + unknown.join(", ") + "." + cwdHint);
665
+ }
666
+ if (params.kind !== "command") throw new Error("runs.host('" + key + "') kind must be 'command'.");
667
+ 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.");
668
+ 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.");
669
+ 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.");
670
+ if (params.role !== undefined && params.role !== "ci" && params.role !== "gate") throw new Error("runs.host('" + key + "') role must be 'ci' or 'gate'.");
671
+ 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.");
672
+ assertJsonValue(params, "runs.host('" + key + "') params");
673
+ if (hostKeys.has(key) || runFingerprints.has(key)) throw new Error("Workflow key '" + key + "' is already in use.");
674
+ if (hostKeys.size >= 32) throw new Error("workflowScript supports at most 32 runs.host calls.");
675
+ hostKeys.add(key);
676
+ }
677
+
678
+ function launchRunsAll(items, generatedLaneKeys) {
679
+ if (!Array.isArray(items)) throw new Error("runs.all(items) requires an array.");
680
+ const fingerprints = new Map(runFingerprints);
681
+ const calls = [];
682
+ for (let index = 0; index < items.length; index++) {
683
+ if (!Object.prototype.hasOwnProperty.call(items, index)) throw new Error("runs.all items must not contain sparse entries.");
684
+ const item = items[index];
685
+ if (!item || typeof item !== "object" || Array.isArray(item)) throw new Error("runs.all item " + index + " must be an object.");
686
+ const { key, ...params } = item;
687
+ validateRunCall(key, params, "runs.all item " + index, fingerprints);
688
+ calls.push({ key, params });
689
+ }
690
+ runFingerprints = fingerprints;
691
+ const batch = { id: "batch-" + (++nextCallId), calls };
692
+ const launched = calls.map(({ key, params }, index) => runHostCall(key, params, true, batch, generatedLaneKeys?.[index]));
693
+ return { calls, launched };
694
+ }
695
+
357
696
  const runs = Object.freeze({
358
697
  run(key, params) {
359
698
  validateRunCall(key, params, "runs.run", runFingerprints);
@@ -361,22 +700,16 @@ const runs = Object.freeze({
361
700
  return trackRunObservation([{ key, operation: "run", callId: launched.callId }], launched.promise.then(decorateWorkflowChildResult));
362
701
  },
363
702
  all(items) {
364
- if (!Array.isArray(items)) throw new Error("runs.all(items) requires an array.");
365
- const fingerprints = new Map(runFingerprints);
366
- const calls = [];
367
- for (let index = 0; index < items.length; index++) {
368
- if (!Object.prototype.hasOwnProperty.call(items, index)) throw new Error("runs.all items must not contain sparse entries.");
369
- const item = items[index];
370
- if (!item || typeof item !== "object" || Array.isArray(item)) throw new Error("runs.all item " + index + " must be an object.");
371
- const { key, ...params } = item;
372
- validateRunCall(key, params, "runs.all item " + index, fingerprints);
373
- calls.push({ key, params });
374
- }
375
- runFingerprints = fingerprints;
376
- const batch = { id: "batch-" + (++nextCallId), calls };
377
- const launched = calls.map(({ key, params }) => runHostCall(key, params, true, batch));
703
+ const { calls, launched } = launchRunsAll(items);
378
704
  return trackRunObservation(launched.map(({ key, callId }) => ({ key, operation: "run", callId })), Promise.all(launched.map(({ promise }) => promise)).then((results) => wrapRunsAllResults(results.map(decorateWorkflowChildResult), calls.map(({ key }) => key))));
379
705
  },
706
+ lanes(laneSpecs) {
707
+ return runLanes(laneSpecs);
708
+ },
709
+ host(key, params) {
710
+ validateHostCommand(key, params);
711
+ return hostCall("host", { key, params }, { key, operation: "host" });
712
+ },
380
713
  steer(key, message, options = {}) {
381
714
  if (typeof key !== "string" || !runKeyPattern.test(key)) throw new Error("runs.steer has an invalid key.");
382
715
  if (typeof message !== "string" || !message.trim()) throw new Error("runs.steer message must be a non-empty string.");
@@ -440,7 +773,7 @@ function isSyntaxError(error) {
440
773
  return error instanceof SyntaxError || error?.name === "SyntaxError";
441
774
  }
442
775
 
443
- const NESTED_ASYNC_WORKFLOW_ERROR = "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.";
776
+ 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 } };";
444
777
  const AST_SCALAR_KEYS = new Set(["type", "start", "end"]);
445
778
 
446
779
  function assertPortableWorkflowScript(source) {
@@ -627,7 +960,12 @@ parentPort.on("message", async (message) => {
627
960
  }
628
961
  }
629
962
  const persistedValue = value === undefined ? null : omitUndefinedWorkflowValues(value);
630
- assertJsonValue(persistedValue, "return");
963
+ try {
964
+ assertJsonValue(persistedValue, "return");
965
+ } catch (error) {
966
+ parentPort.postMessage({ type: "error", errorPhase: "return-serialization", error: formatWorkflowScriptError(error) });
967
+ return;
968
+ }
631
969
  parentPort.postMessage({ type: "complete", value: persistedValue });
632
970
  } catch (error) {
633
971
  parentPort.postMessage({ type: "error", error: isSyntaxError(error) ? formatWorkflowScriptSyntaxError(error) : formatWorkflowScriptError(error), ...(error && error.workflowErrorKind === "detached-child" ? { errorKind: "detached-child" } : {}) });
@@ -638,6 +976,8 @@ parentPort.on("message", async (message) => {
638
976
  export interface WorkflowScriptChildResult {
639
977
  key: string;
640
978
  ok: boolean;
979
+ lane?: import("../shared/types.ts").WorkflowLaneMetadata;
980
+ terminalOutcome?: import("../shared/types.ts").WorkflowTerminalOutcome;
641
981
  stopped?: boolean;
642
982
  /** Canonical child agent name when launch resolution produced one. */
643
983
  agent?: string;
@@ -650,14 +990,17 @@ export interface WorkflowScriptChildResult {
650
990
  requestedContext?: "fresh" | "fork";
651
991
  resolvedContext?: "fresh" | "fork" | "mixed";
652
992
  outputReference?: string;
993
+ recovery?: AcceptanceRecoveryMetadata;
994
+ outputPathMapping?: { requestedPath: string; savedPath: string };
995
+ externalAdapter?: import("../shared/types.ts").ExternalCliReceiptMetadata;
653
996
  resumability?: { state: "resumable" } | { state: "not-resumable"; reason: string };
654
997
  continuation?: { runIds: string[] };
655
998
  artifactPaths: string[];
656
- results?: unknown[];
999
+ results?: SingleResult[];
657
1000
  }
658
1001
 
659
1002
  export interface WorkflowScriptTraceEntry {
660
- operation: "run" | "status" | "steer";
1003
+ operation: "run" | "status" | "steer" | "host";
661
1004
  key: string;
662
1005
  state: "started" | "completed" | "failed" | "detached" | "stopped" | "reused" | "queued" | "delivered" | "missed";
663
1006
  /** Canonical child agent name when resolved launch or result data is available. */
@@ -667,6 +1010,26 @@ export interface WorkflowScriptTraceEntry {
667
1010
  phase?: string;
668
1011
  label?: string;
669
1012
  error?: string;
1013
+ /** Internal provenance for a generated runs.lanes child key. */
1014
+ generatedLaneKey?: string;
1015
+ lane?: import("../shared/types.ts").WorkflowLaneMetadata;
1016
+ warning?: string;
1017
+ }
1018
+
1019
+ /** Bounded plan metadata emitted when a workflow materializes a runs.lanes graph. */
1020
+ export interface WorkflowLanePlanStage {
1021
+ key: string;
1022
+ generatedKey: string;
1023
+ agent?: string;
1024
+ phase?: string;
1025
+ label?: string;
1026
+ outputName?: string;
1027
+ structured?: boolean;
1028
+ }
1029
+
1030
+ export interface WorkflowLanePlan {
1031
+ key: string;
1032
+ stages: WorkflowLanePlanStage[];
670
1033
  }
671
1034
 
672
1035
  export interface WorkflowSteerOptions {
@@ -705,9 +1068,9 @@ export interface WorkflowScriptResult {
705
1068
 
706
1069
  export class WorkflowScriptError extends Error {
707
1070
  readonly partial: Omit<WorkflowScriptResult, "value">;
708
- readonly errorKind?: "detached-child";
1071
+ readonly errorKind?: "detached-child" | "timeout";
709
1072
 
710
- constructor(message: string, partial: Omit<WorkflowScriptResult, "value">, errorKind?: "detached-child") {
1073
+ constructor(message: string, partial: Omit<WorkflowScriptResult, "value">, errorKind?: "detached-child" | "timeout") {
711
1074
  super(message);
712
1075
  this.name = "WorkflowScriptError";
713
1076
  this.partial = partial;
@@ -717,19 +1080,28 @@ export class WorkflowScriptError extends Error {
717
1080
 
718
1081
  export interface RunWorkflowScriptOptions {
719
1082
  script: string;
1083
+ /** Host-only first-slice admission context. It is never sent to the workflow worker. */
1084
+ oneUsePermit?: { claim: (key: string) => string | undefined };
720
1085
  timeoutMs?: number;
721
1086
  signal?: AbortSignal;
1087
+ /** Let an async workflow flush pure result assembly after reload once every child is terminal. */
1088
+ continueAfterAbortWhenChildrenSettled?: (abortError: Error) => boolean;
1089
+ /** Maximum children executing concurrently within this workflow. Defaults to 20. */
1090
+ globalConcurrencyLimit?: number;
722
1091
  admit?: (calls: Array<{ key: string; params: Record<string, unknown> }>) => void | Promise<void>;
723
- launch: (key: string, params: Record<string, unknown>, signal: AbortSignal, admission: { admitted: boolean }) => Promise<WorkflowScriptChildResult>;
1092
+ launch: (key: string, params: Record<string, unknown>, signal: AbortSignal, admission: { admitted: boolean; batch: boolean }) => Promise<WorkflowScriptChildResult>;
724
1093
  resolveResume?: (reference: WorkflowReceiptResumeReference, signal: AbortSignal) => string | WorkflowResolvedResumeReference | Promise<string | WorkflowResolvedResumeReference>;
725
1094
  status: (keyOrRunId: string, signal: AbortSignal) => Promise<WorkflowScriptChildResult>;
726
1095
  steer?: (key: string, message: string, options: WorkflowSteerOptions, signal: AbortSignal) => Promise<WorkflowSteerResult>;
1096
+ host?: (key: string, params: WorkflowHostCommandParams, signal: AbortSignal) => Promise<WorkflowHostCommandResult>;
1097
+ onHostStep?: (hostStep: HostStepNodeV1) => void;
727
1098
  state?: {
728
1099
  get: (key: string) => unknown | Promise<unknown>;
729
1100
  set: (key: string, value: unknown) => void | Promise<void>;
730
1101
  };
731
1102
  registerStopChild?: (stop: ((key: string, message?: string) => boolean) | undefined) => void;
732
1103
  onTrace?: (trace: WorkflowScriptTraceEntry[]) => void;
1104
+ onLanePlan?: (lanes: WorkflowLanePlan[]) => void;
733
1105
  onEmit?: (emits: unknown[]) => void;
734
1106
  }
735
1107
 
@@ -753,6 +1125,138 @@ function isRecord(value: unknown): value is Record<string, unknown> {
753
1125
  return !!value && typeof value === "object" && !Array.isArray(value);
754
1126
  }
755
1127
 
1128
+ function isAcceptanceMetadataRecovery(result: WorkflowScriptChildResult): boolean {
1129
+ return !result.ok
1130
+ && result.recovery?.status === "available-for-review"
1131
+ && result.recovery.reason === "acceptance-metadata-rejected";
1132
+ }
1133
+
1134
+ const RECOVERY_REVIEW_MUTATION_VERB_PATTERN = /\b(?:add(?:ing)?|append(?:ing)?|apply(?:ing)?|cherry[ -]pick(?:ing)?|change|changing|clean(?:ing)?|commit(?:ting)?|cop(?:y|ying)|create|creating|delete|deleting|edit(?:ing)?|fix(?:ing)?|implement(?:ing)?|insert(?:ing)?|make|making|merge|merging|mov(?:e|ing)|modify(?:ing)?|mutate|mutating|open(?:ing)?|patch(?:ing)?|prepend(?:ing)?|push(?:ing)?|rebase|rebasing|refactor(?:ing)?|remove|removing|rename|renaming|replace|replacing|revert(?:ing)?|revise|revising|rewrite|rewriting|sav(?:e|ing)|stag(?:e|ing)|stash(?:ing)?|tag(?:ging)?|touch(?:ing)?|update|updating|write|writing)\b/i;
1135
+ const RECOVERY_REVIEW_READ_ONLY_PATTERN = /\b(?:read[- ]only|review only|only return findings|return findings only|suggest fixes only|without\s+(?:editing|modifying|changing|writing|touching)|do not\s+(?:edit|modify|change|write|touch)|don't\s+(?:edit|modify|change|write|touch)|must not\s+(?:edit|modify|change|write|touch))\b/i;
1136
+ const RECOVERY_REVIEW_NO_MUTATION_CLAUSE_PATTERN = /\b(?:do not|don't|must not)\s+(?:edit|modify|change|write|touch)(?:\s+files?)?(?:\s*,\s*(?:commit|push|comment|merge|launch(?:\s+subagents?)?)(?=\s*(?:,|\bor\b|[.;!?\n)]|$)))*(?:\s*,?\s*or\s+(?:commit|push|comment|merge|launch(?:\s+subagents?)?)(?=\s*(?:[.;!?\n)]|$)))?/gi;
1137
+ const RECOVERY_REVIEW_DELIVERABLE_PATTERN = /\b(?:compose|create|draft|prepare|produce|write)\s+(?:(?:a|an|the|your)\s+)?(?:findings?|review|report|summary|analysis|recommendations?)(?:\s+(?:to|at|in)\s+\S+)?/gi;
1138
+ const RECOVERY_REVIEW_CONTEXT_OBJECT_PATTERN = /\breview\s+(?:(?:the|this|that|saved)\s+)?(?:patch|diff|changes?|implementation|report)\b/gi;
1139
+ const RECOVERY_REVIEW_MUTATION_NOUN_CONTEXT_PATTERN = /\b(?:later\s+real\s+)?update\s+imperatives?\b/gi;
1140
+ const RECOVERY_REVIEW_PRIOR_FIX_CONTEXT_PATTERN = /\bthe\s+prior\s+fix\s+keeps\b/gi;
1141
+ const RECOVERY_REVIEW_DETECTION_CONTEXT_PATTERN = /\b(?:mutation\s+detection\s+now\s+includes\s+move\/rename\/copy\s+file\s+mutation\s+imperatives|delegation\s+detection\s+now\s+blocks\s+get\/let\/have\/tell\/ask\s+follow-up\s+forms)(?=[,.;!?\n]|\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b|$)/gi;
1142
+ const RECOVERY_REVIEW_PATTERN_CHANGE_CONTEXT_PATTERN = /\bRECOVERY_REVIEW_MUTATION_VERB_PATTERN\s+now\s+includes\s+append,\s+prepend,\s+and\s+sav(?:e|ing)\b(?=\s*(?:[,.;!?\n)]|$))/gi;
1143
+ const RECOVERY_REVIEW_GIT_PATTERN_CHANGE_CONTEXT_PATTERN = /\bfixed\s+mutating\s+git\s+follow-up\s+bypasses\b|\b(?:added|adding)\s+[a-z][a-z-]*(?:\/[a-z][a-z-]*)*(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)[a-z][a-z-]*(?:\/[a-z][a-z-]*)*)*\s+to\s+the\s+(?:mutation\s+imperative|mutating\s+git\s+command)\s+pattern\b|\band\s+[a-z][a-z-]*(?:\/[a-z][a-z-]*)*(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)[a-z][a-z-]*(?:\/[a-z][a-z-]*)*)*\s+to\s+the\s+mutating\s+git\s+command\s+pattern\b/gi;
1144
+ const RECOVERY_REVIEW_VALIDATION_EVIDENCE_PATTERN = /\bvalidation(?:\s+after\s+fix)?\s*:/gi;
1145
+ const RECOVERY_REVIEW_CONTRACT_PROHIBITION_PATTERN = /\b(?:do not|don't|must not)\s+(?:mutate\s+durable\s+state|launch\s+(?:mutating|destructive|mutating\/destructive)\s+work)(?:\s+or\s+(?:mutate\s+durable\s+state|launch\s+(?:mutating|destructive|mutating\/destructive)\s+work))*/gi;
1146
+ const RECOVERY_REVIEW_ONLY_REVIEW_CONTRACT_PATTERN = /\bmay\s+only\s+launch\s+explicit\s+read-only\s+review\s+children\s+with\s+acceptance:false\b/gi;
1147
+ const RECOVERY_REVIEW_BLOCKED_CONTEXT_FRAGMENT_PATTERN = /\bstate\.set, runs\.host, runs\.steer, ordinary\/mutating children, and destructive command wording are blocked(?=[,.;!?\n)\]}]|$)/gi;
1148
+ const RECOVERY_REVIEW_REGRESSION_EVIDENCE_PATTERN = /\b(?:existing regressions cover plain rm and git clean\/reset\/restore|prior regressions covering rm\/git clean as evidence only)(?=[,.;!?\n)\]}]|$)/gi;
1149
+ const RECOVERY_REVIEW_BLOCKED_QUOTED_EXAMPLE_PATTERN = /(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+")(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+"))*\s+(?:is|are|remains?)\s+(?:blocked|(?:an?\s+)?blocked\s+examples?)(?=[,.;!?\n)\]}]|$)/gi;
1150
+ const RECOVERY_REVIEW_CONTEXT_QUOTED_EXAMPLE_PATTERN = /\b(?:examples?|phrasing|forms|variants):\s*(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+")(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+"))*/gi;
1151
+ const RECOVERY_REVIEW_LISTED_BLOCKED_EXAMPLE_PATTERN = /(?:^|[.;!?\n]\s*)blocked\s+examples:\s*(?:\r?\n[ \t]*(?:[-*]|\d+[.)])\s+[^\r\n]+)+/gim;
1152
+ const RECOVERY_REVIEW_BLOCKS_QUOTED_EXAMPLE_PATTERN = /\b(?:this\s+)?blocks?\s+examples?\s+like\s+(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+")(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+"))*/gi;
1153
+ const RECOVERY_REVIEW_EXAMPLES_LIKE_BLOCKED_PATTERN = /\bexamples?\s+like\s+(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+")(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+"))*\s+(?:is|are|remains?)\s+blocked\b/gi;
1154
+ const RECOVERY_REVIEW_QUOTED_VISIBLE_BLOCKED_PATTERN = /(?:\b(?:(?:the\s+)?examples?|commands?\s+hidden\s+in)\s+|(?:^|[\s([{]))(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+")(?:(?:\s*,\s*(?:and\s+|or\s+)?|\s+(?:and|or)\s+)(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+"))*\s+(?:(?:is|are|remains?)\s+)?visible\s+and\s+blocked\b/gi;
1155
+ const RECOVERY_REVIEW_PROMPTS_LIKE_BLOCKED_PATTERN = /\bdescribed\s+prompts?\s+like\s+Run\s+git\s+rebase\s+main,\s+git\s+rebase\s+main,\s+Run\s+git\s+cherry-pick\s+abc123,\s+cherry-pick\s+abc123,\s+and\s+Stage\s+the\s+changed\s+files\s+as\s+blocked\b/gi;
1156
+ const RECOVERY_REVIEW_GIT_MUTATIONS_BROADER_CONTEXT_PATTERN = /\bpositive\s+git\s+mutations\s+are\s+broader:\s*git\s+branch\s+-D\s+old,\s+git\s+tag\s+-d\s+v1\.0,\s+git\s+stash,\s+git\s+revert\s+abc123,\s+and\s+natural\s+cherry\s+pick\s+abc123\s+now\s+trips?\s+the\s+recovery\s+barrier\b/gi;
1157
+ const RECOVERY_REVIEW_GIT_COVERAGE_CONTEXT_PATTERN = /\bbroadened\s+positive\s+git\s+mutation\s+coverage\s+for\s+natural\s+`cherry\s+pick`,\s+`revert`,\s+`stash`,\s+`tag`,\s+plus\s+git\s+`branch\|revert\|stash\|tag`/gi;
1158
+ const RECOVERY_REVIEW_REGRESSION_QUOTED_EXAMPLE_PATTERN = /\b(?:added\s+)?exact\s+regressions?\s+for\s+(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+")(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)(?:`[^`\n]+`|'[^'\n]+'|"[^"\n]+"))*/gi;
1159
+ const RECOVERY_REVIEW_REGRESSION_ANAPHORIC_EXAMPLE_PATTERN = /\b(?:added\s+)?exact\s+regressions?\s+for\s+(?:do|run|execute|perform|apply)\s+(?:it|that|this|(?:the\s+)?(?:(?:previous(?:ly)?|prior|above|quoted|blocked)\s+){0,4}(?:command|example|operation|action|phrase|instruction|request))(?:[\s,]+(?:now|still|again|really|actually|immediately)){0,3}[\s,]+anyway(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)(?:do|run|execute|perform|apply)\s+(?:it|that|this|(?:the\s+)?(?:(?:previous(?:ly)?|prior|above|quoted|blocked)\s+){0,4}(?:command|example|operation|action|phrase|instruction|request))(?:[\s,]+(?:now|still|again|really|actually|immediately)){0,3}[\s,]+anyway)*/gi;
1160
+ const RECOVERY_REVIEW_REGRESSION_FOLLOWED_BY_ANAPHORIC_PATTERN = /\badded\s+(?:exact\s+)?regressions?\s+for\s+quoted\s+rm\s+remaining\s+blocked\s+followed\s+by\s+execute\s+the\s+previous\s+command\b(?=\s*(?:[,.;!?\n)]|\bwhile\b|$))/gi;
1161
+ const RECOVERY_REVIEW_REGRESSION_FOLLOWED_BY_NAMED_RM_PATTERN = /\b(?:added\s+)?(?:exact\s+)?regressions?\s+for\s+quoted\s+rm\s+remaining\s+blocked\s+followed\s+by\s+(?:do|run|execute|perform|apply)\s+(?:it|that|this|(?:the\s+)?(?:(?:previous(?:ly)?|prior|above|quoted|blocked)\s+){0,4}(?:command|example|operation|action|phrase|instruction|request))(?:[\s,]+(?:now|still|again|really|actually|immediately)){0,3}(?:[\s,]+anyway)?(?=\s*(?:[,.;!?\n)]|\bwhile\b|$))/gi;
1162
+ const RECOVERY_REVIEW_BLOCKED_LIVE_VARIANT_CONTEXT_PATTERN = /\b(?:while\s+)?keeping\s+live-command\s+variants\s+such\s+as\s+followed\s+by\s+execute\s+the\s+previous\s+command\s+then\s+update\s+tests\s+blocked\b(?=\s*(?:[,.;!?\n)]|$))/gi;
1163
+ const RECOVERY_REVIEW_ANAPHORIC_REFERENCES_CONTEXT_PATTERN = /\bdirect\s+anaphoric\s+references\s+now\s+include\s+numeric\s+and\s+word\s+ordinals\s+through\s+tenth\s+plus\s+one,\s+so\s+(?:do|run|execute|perform|apply)\s+(?:it|that|this|(?:the\s+)?(?:(?:\d+(?:st|nd|rd|th)|first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|last|next|previous(?:ly)?|prior|above|quoted|blocked)\s+){0,4}(?:command|example|operation|action|phrase|instruction|request|one))(?:[\s,]+(?:right|now|still|again|really|actually|immediately)){0,4}[\s,]+anyway(?:(?:\s*,\s*(?:and\s+)?|\s+and\s+)(?:do|run|execute|perform|apply)\s+(?:it|that|this|(?:the\s+)?(?:(?:\d+(?:st|nd|rd|th)|first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|last|next|previous(?:ly)?|prior|above|quoted|blocked)\s+){0,4}(?:command|example|operation|action|phrase|instruction|request|one))(?:[\s,]+(?:right|now|still|again|really|actually|immediately)){0,4}[\s,]+anyway)*\s+(?:is|are|remains?)\s+blocked\b(?:\s+after\s+quoted\s+destructive\s+examples\s+are\s+scrubbed)?/gi;
1164
+ const RECOVERY_REVIEW_NO_ANAPHORIC_MUTATION_CLAUSE_PATTERN = /\b(?:do not|don't|must not)\s+(?:do|run|execute|perform|apply)\s+(?:it|that|this|(?:the\s+)?(?:(?:\d+(?:st|nd|rd|th)|first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|last|next|previous(?:ly)?|prior|above|quoted|blocked)\s+){0,4}(?:command|example|operation|action|phrase|instruction|request|one))(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n—–-]){0,80}/gi;
1165
+ const RECOVERY_REVIEW_NO_DELEGATION_CLAUSE_PATTERN = /\b(?:do not|don't|must not)\s+(?:(?:launch|start|spawn|run)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:workers?|reviewers?|agents?|subagents?|children|child|runs?)|(?:get|let|request|hand\s+off|assign|use|have|tell)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:workers?|reviewers?|agents?|subagents?|children|child)|(?:get|let|have|tell|request)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:review|implementation|fix(?:es)?|changes?|follow-up)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*\b(?:from|with|via|by)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:workers?|reviewers?|agents?|subagents?|children|child)|ask\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:(?:workers?|reviewers?|agents?|subagents?|children|child)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*\b(?:continue|implement|review|fix|edit|write|modify|change|patch|update|delete|remove|create|follow-up)|(?:review|implementation|fix(?:es)?|changes?|follow-up)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*\b(?:from|via)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:workers?|reviewers?|agents?|subagents?|children|child)))\b/gi;
1166
+ const RECOVERY_REVIEW_DELEGATION_PATTERN = /\b(?:launch|start|spawn|run)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child|runs?)\b|\b(?:delegate|hand\s+off|assign)\s+(?:remediation|implementation(?:\s+follow-up)?|changes?|fix(?:es)?|follow-up)\s+to\s+(?:(?:a|an|the)\s+)?(?:workers?|reviewers?|agents?|subagents?|children|child)\b|\b(?:get|let|have|tell|request)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child)\b[^,.;!?\n]*\b(?:continue|implement|review|fix|edit|write|modify|change|patch|update|delete|remove|create|follow-up)\b|\b(?:get|let|have|tell|request)\b[^,.;!?\n]*(?:review|implementation|fix(?:es)?|changes?|follow-up)\b[^,.;!?\n]*\b(?:from|with|via|by)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child)\b|\bask\b[^,.;!?\n]*(?:(?:workers?|reviewers?|agents?|subagents?|children|child)\b[^,.;!?\n]*\b(?:continue|implement|review|fix|edit|write|modify|change|patch|update|delete|remove|create|follow-up)|(?:review|implementation|fix(?:es)?|changes?|follow-up)\b[^,.;!?\n]*\b(?:from|via)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child))\b|\buse\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child|runs?)\s+(?:for|to)\s+(?:implementation|follow-up|remediation|fix|edit|write|modify|change|patch|update|delete|remove|create)\b/i;
1167
+ const RECOVERY_REVIEW_ANAPHORIC_MUTATION_PATTERN = /\b(?:do|run|execute|perform|apply)\s+(?:it|that|this|(?:the\s+)?(?:(?:\d+(?:st|nd|rd|th)|first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|last|next|previous(?:ly)?|prior|above|quoted|blocked)\s+){0,4}(?:command|example|operation|action|phrase|instruction|request|one))(?!(?:\s+(?:(?:now|still|also|already)\s+)*(?:is|are|remains?)\s+blocked\b))(?:(?:[\s,]+\w+){0,4}[\s,]+anyway|(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n]){0,80})(?=\s*(?:[,.;!?\n)]|\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b|$))/i;
1168
+ const RECOVERY_REVIEW_DESTRUCTIVE_COMMAND_PATTERN = /(?:^|[\s;,.`'"([{])(?:\S*\/)?(?:rm|rmdir|unlink|truncate|mv|cp|chmod|chown)\b|\bgit\b(?:\s+(?:-[A-Za-z](?:\s+(?:"[^"\n]*"|'[^'\n]*'|\S+))?|--(?:git-dir|work-tree|namespace|exec-path|config-env)(?:=(?:"[^"\n]*"|'[^'\n]*'|\S+)|\s+(?:"[^"\n]*"|'[^'\n]*'|\S+))|--[A-Za-z0-9-]+(?:=(?:"[^"\n]*"|'[^'\n]*'|\S+))?))*\s+(?:add|branch|cherry-pick|clean|commit|merge|rebase|reset|restore|revert|stash|tag|checkout|switch)\b/i;
1169
+ const RECOVERY_REVIEW_DASH_LIVE_ACTION_PATTERN = /(?:[—–]|--|\s-\s|:|\s\/\s)\s*(?:then\s+)?(?:(?:add|append|apply|change|cherry[ -]pick|clean|commit|copy|create|delete|edit|fix|implement|insert|make|merge|move|modify|mutate|open|patch|prepend|push|rebase|refactor|remove|rename|replace|revert|revise|rewrite|save|stage|stash|tag|touch|update|write)\b|(?:launch|start|spawn|run)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child|runs?)\b|(?:\S*\/)?(?:rm|rmdir|unlink|truncate|mv|cp|chmod|chown)\b|git\b[^,.;!?\n]*\b(?:add|branch|cherry-pick|clean|commit|merge|rebase|reset|restore|revert|stash|tag|checkout|switch)\b)/i;
1170
+
1171
+ function isExplicitReadOnlyRecoveryReview(params: Record<string, unknown>): boolean {
1172
+ const agent = typeof params.agent === "string" ? params.agent.trim() : "";
1173
+ const task = typeof params.task === "string" ? params.task.trim() : "";
1174
+ const taskDestructiveCommandText = task
1175
+ .replace(RECOVERY_REVIEW_BLOCKED_CONTEXT_FRAGMENT_PATTERN, " ")
1176
+ .replace(RECOVERY_REVIEW_REGRESSION_EVIDENCE_PATTERN, " ")
1177
+ .replace(RECOVERY_REVIEW_BLOCKED_QUOTED_EXAMPLE_PATTERN, " ")
1178
+ .replace(RECOVERY_REVIEW_CONTEXT_QUOTED_EXAMPLE_PATTERN, " ")
1179
+ .replace(RECOVERY_REVIEW_LISTED_BLOCKED_EXAMPLE_PATTERN, " ")
1180
+ .replace(RECOVERY_REVIEW_BLOCKS_QUOTED_EXAMPLE_PATTERN, " ")
1181
+ .replace(RECOVERY_REVIEW_EXAMPLES_LIKE_BLOCKED_PATTERN, " ")
1182
+ .replace(RECOVERY_REVIEW_QUOTED_VISIBLE_BLOCKED_PATTERN, " ")
1183
+ .replace(RECOVERY_REVIEW_PROMPTS_LIKE_BLOCKED_PATTERN, " ")
1184
+ .replace(RECOVERY_REVIEW_GIT_MUTATIONS_BROADER_CONTEXT_PATTERN, " ")
1185
+ .replace(RECOVERY_REVIEW_GIT_COVERAGE_CONTEXT_PATTERN, " ")
1186
+ .replace(RECOVERY_REVIEW_REGRESSION_FOLLOWED_BY_NAMED_RM_PATTERN, " ");
1187
+ const taskDashLiveActionText = task
1188
+ .replace(RECOVERY_REVIEW_DELIVERABLE_PATTERN, " ")
1189
+ .replace(RECOVERY_REVIEW_CONTEXT_OBJECT_PATTERN, " ")
1190
+ .replace(RECOVERY_REVIEW_MUTATION_NOUN_CONTEXT_PATTERN, " ")
1191
+ .replace(RECOVERY_REVIEW_PRIOR_FIX_CONTEXT_PATTERN, " ")
1192
+ .replace(RECOVERY_REVIEW_DETECTION_CONTEXT_PATTERN, " ")
1193
+ .replace(RECOVERY_REVIEW_PATTERN_CHANGE_CONTEXT_PATTERN, " ")
1194
+ .replace(RECOVERY_REVIEW_GIT_PATTERN_CHANGE_CONTEXT_PATTERN, " ")
1195
+ .replace(RECOVERY_REVIEW_VALIDATION_EVIDENCE_PATTERN, " ")
1196
+ .replace(RECOVERY_REVIEW_CONTRACT_PROHIBITION_PATTERN, " ")
1197
+ .replace(RECOVERY_REVIEW_ONLY_REVIEW_CONTRACT_PATTERN, " ")
1198
+ .replace(RECOVERY_REVIEW_BLOCKED_QUOTED_EXAMPLE_PATTERN, " ")
1199
+ .replace(RECOVERY_REVIEW_CONTEXT_QUOTED_EXAMPLE_PATTERN, " ")
1200
+ .replace(RECOVERY_REVIEW_LISTED_BLOCKED_EXAMPLE_PATTERN, " ")
1201
+ .replace(RECOVERY_REVIEW_BLOCKS_QUOTED_EXAMPLE_PATTERN, " ")
1202
+ .replace(RECOVERY_REVIEW_EXAMPLES_LIKE_BLOCKED_PATTERN, " ")
1203
+ .replace(RECOVERY_REVIEW_QUOTED_VISIBLE_BLOCKED_PATTERN, " ")
1204
+ .replace(RECOVERY_REVIEW_PROMPTS_LIKE_BLOCKED_PATTERN, " ")
1205
+ .replace(RECOVERY_REVIEW_GIT_MUTATIONS_BROADER_CONTEXT_PATTERN, " ")
1206
+ .replace(RECOVERY_REVIEW_GIT_COVERAGE_CONTEXT_PATTERN, " ")
1207
+ .replace(RECOVERY_REVIEW_REGRESSION_QUOTED_EXAMPLE_PATTERN, " ")
1208
+ .replace(RECOVERY_REVIEW_REGRESSION_ANAPHORIC_EXAMPLE_PATTERN, " ")
1209
+ .replace(RECOVERY_REVIEW_REGRESSION_FOLLOWED_BY_ANAPHORIC_PATTERN, " ")
1210
+ .replace(RECOVERY_REVIEW_BLOCKED_LIVE_VARIANT_CONTEXT_PATTERN, " ")
1211
+ .replace(RECOVERY_REVIEW_ANAPHORIC_REFERENCES_CONTEXT_PATTERN, " ");
1212
+ const taskMutationText = task
1213
+ .replace(RECOVERY_REVIEW_DELIVERABLE_PATTERN, " ")
1214
+ .replace(RECOVERY_REVIEW_CONTEXT_OBJECT_PATTERN, " ")
1215
+ .replace(RECOVERY_REVIEW_MUTATION_NOUN_CONTEXT_PATTERN, " ")
1216
+ .replace(RECOVERY_REVIEW_PRIOR_FIX_CONTEXT_PATTERN, " ")
1217
+ .replace(RECOVERY_REVIEW_DETECTION_CONTEXT_PATTERN, " ")
1218
+ .replace(RECOVERY_REVIEW_PATTERN_CHANGE_CONTEXT_PATTERN, " ")
1219
+ .replace(RECOVERY_REVIEW_GIT_PATTERN_CHANGE_CONTEXT_PATTERN, " ")
1220
+ .replace(RECOVERY_REVIEW_VALIDATION_EVIDENCE_PATTERN, " ")
1221
+ .replace(RECOVERY_REVIEW_CONTRACT_PROHIBITION_PATTERN, " ")
1222
+ .replace(RECOVERY_REVIEW_ONLY_REVIEW_CONTRACT_PATTERN, " ")
1223
+ .replace(RECOVERY_REVIEW_BLOCKED_CONTEXT_FRAGMENT_PATTERN, " ")
1224
+ .replace(RECOVERY_REVIEW_REGRESSION_EVIDENCE_PATTERN, " ")
1225
+ .replace(RECOVERY_REVIEW_BLOCKED_QUOTED_EXAMPLE_PATTERN, " ")
1226
+ .replace(RECOVERY_REVIEW_CONTEXT_QUOTED_EXAMPLE_PATTERN, " ")
1227
+ .replace(RECOVERY_REVIEW_LISTED_BLOCKED_EXAMPLE_PATTERN, " ")
1228
+ .replace(RECOVERY_REVIEW_BLOCKS_QUOTED_EXAMPLE_PATTERN, " ")
1229
+ .replace(RECOVERY_REVIEW_EXAMPLES_LIKE_BLOCKED_PATTERN, " ")
1230
+ .replace(RECOVERY_REVIEW_QUOTED_VISIBLE_BLOCKED_PATTERN, " ")
1231
+ .replace(RECOVERY_REVIEW_PROMPTS_LIKE_BLOCKED_PATTERN, " ")
1232
+ .replace(RECOVERY_REVIEW_GIT_MUTATIONS_BROADER_CONTEXT_PATTERN, " ")
1233
+ .replace(RECOVERY_REVIEW_GIT_COVERAGE_CONTEXT_PATTERN, " ")
1234
+ .replace(RECOVERY_REVIEW_REGRESSION_QUOTED_EXAMPLE_PATTERN, " ")
1235
+ .replace(RECOVERY_REVIEW_REGRESSION_ANAPHORIC_EXAMPLE_PATTERN, " ")
1236
+ .replace(RECOVERY_REVIEW_REGRESSION_FOLLOWED_BY_ANAPHORIC_PATTERN, " ")
1237
+ .replace(RECOVERY_REVIEW_BLOCKED_LIVE_VARIANT_CONTEXT_PATTERN, " ")
1238
+ .replace(RECOVERY_REVIEW_ANAPHORIC_REFERENCES_CONTEXT_PATTERN, " ")
1239
+ .replace(RECOVERY_REVIEW_NO_ANAPHORIC_MUTATION_CLAUSE_PATTERN, " ")
1240
+ .replace(RECOVERY_REVIEW_NO_DELEGATION_CLAUSE_PATTERN, " ")
1241
+ .replace(RECOVERY_REVIEW_NO_MUTATION_CLAUSE_PATTERN, " ")
1242
+ .replace(new RegExp(RECOVERY_REVIEW_READ_ONLY_PATTERN.source, "gi"), " ");
1243
+ return params.acceptance === false
1244
+ && agent !== ""
1245
+ && /\b(?:advisor|oracle|review|reviewer)\b/i.test(agent)
1246
+ && RECOVERY_REVIEW_READ_ONLY_PATTERN.test(task)
1247
+ && !RECOVERY_REVIEW_DESTRUCTIVE_COMMAND_PATTERN.test(taskDestructiveCommandText)
1248
+ && !RECOVERY_REVIEW_MUTATION_VERB_PATTERN.test(taskMutationText)
1249
+ && !RECOVERY_REVIEW_DELEGATION_PATTERN.test(taskMutationText)
1250
+ && !RECOVERY_REVIEW_ANAPHORIC_MUTATION_PATTERN.test(taskMutationText)
1251
+ && !RECOVERY_REVIEW_DESTRUCTIVE_COMMAND_PATTERN.test(taskMutationText)
1252
+ && !RECOVERY_REVIEW_DASH_LIVE_ACTION_PATTERN.test(taskDashLiveActionText)
1253
+ && classifyTaskMutationIntent(agent, task).kind === "read-only";
1254
+ }
1255
+
1256
+ function recoveryBarrierMessage(sourceKey: string, target: string): string {
1257
+ return `Run '${target}' cannot launch after run '${sourceKey}' returned rejected acceptance recovery; only explicit read-only review children with acceptance:false may follow.`;
1258
+ }
1259
+
756
1260
  function isPlainJsonObject(value: unknown): value is Record<string, unknown> {
757
1261
  if (!isRecord(value)) return false;
758
1262
  const prototype = Object.getPrototypeOf(value);
@@ -827,6 +1331,15 @@ export function formatWorkflowJsonPreview(value: unknown, maxLength: number): st
827
1331
  }
828
1332
  }
829
1333
 
1334
+ function workflowReturnRecoveryHint(children: WorkflowScriptChildResult[]): string {
1335
+ if (children.length === 0) return " Return only plain JSON data. For a child result, select fields such as { runId: child.runId, ok: child.ok, outputReference: child.outputReference }.";
1336
+ const references = children.slice(0, 10).map((child) => {
1337
+ const fields = [child.runId ? `runId=${child.runId.slice(0, 500)}` : undefined, child.outputReference ? `outputReference=${child.outputReference.slice(0, 500)}` : undefined, child.artifactPaths[0] ? `artifact=${child.artifactPaths[0].slice(0, 500)}` : undefined].filter((field): field is string => field !== undefined);
1338
+ return `'${child.key}'${fields.length > 0 ? ` (${fields.join(", ")})` : ""}`;
1339
+ });
1340
+ return ` Child work completed before return serialization failed. Recover outputs from: ${references.join(", ")}${children.length > references.length ? `, and ${children.length - references.length} more` : ""}. Return a plain projection such as { runId: child.runId, ok: child.ok, outputReference: child.outputReference }.`;
1341
+ }
1342
+
830
1343
  export interface SimpleWorkflowRunPreview {
831
1344
  agent?: string;
832
1345
  task?: string;
@@ -864,6 +1377,230 @@ function validateKey(value: unknown, owner = "runs.run"): string {
864
1377
  return value;
865
1378
  }
866
1379
 
1380
+ type AstNode = {
1381
+ type: string;
1382
+ loc?: { start: { line: number; column: number } };
1383
+ [key: string]: unknown;
1384
+ };
1385
+
1386
+ const AST_LOCATION_KEYS = new Set(["type", "start", "end", "loc", "range"]);
1387
+
1388
+ function astNode(value: unknown): value is AstNode {
1389
+ return Boolean(value) && typeof value === "object" && typeof (value as { type?: unknown }).type === "string";
1390
+ }
1391
+
1392
+ function literalString(node: unknown): string | undefined {
1393
+ if (!astNode(node)) return undefined;
1394
+ if (node.type === "Literal" && typeof node.value === "string") return node.value;
1395
+ if (node.type === "TemplateLiteral" && Array.isArray(node.expressions) && node.expressions.length === 0 && Array.isArray(node.quasis)) {
1396
+ const first = node.quasis[0] as { value?: { cooked?: unknown } } | undefined;
1397
+ if (typeof first?.value?.cooked === "string") return first.value.cooked;
1398
+ }
1399
+ return undefined;
1400
+ }
1401
+
1402
+ function directRunsCall(node: unknown, method: "run" | "all" | "host"): node is AstNode {
1403
+ if (!astNode(node) || node.type !== "CallExpression" || !astNode(node.callee) || node.callee.type !== "MemberExpression") return false;
1404
+ const property = node.callee.computed === true ? literalString(node.callee.property) : astNode(node.callee.property) && node.callee.property.type === "Identifier" ? node.callee.property.name : undefined;
1405
+ return property === method && astNode(node.callee.object) && node.callee.object.type === "Identifier" && node.callee.object.name === "runs";
1406
+ }
1407
+
1408
+ function validateStaticHostCall(call: AstNode): WorkflowScriptValidationError[] {
1409
+ const args = Array.isArray(call.arguments) ? call.arguments : [];
1410
+ const keyNode = astNode(args[0]) ? args[0] : undefined;
1411
+ const params = astNode(args[1]) ? args[1] : undefined;
1412
+ const errors: WorkflowScriptValidationError[] = [];
1413
+ const key = literalString(keyNode);
1414
+ if (keyNode && key !== undefined && !KEY_PATTERN.test(key)) errors.push({ message: "runs.host key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.", ...nodeLocation(keyNode) });
1415
+ if (!params || params.type !== "ObjectExpression" || !Array.isArray(params.properties) || params.properties.some((property) => !astNode(property) || property.type !== "Property")) return errors;
1416
+ const allowed = new Set(["kind", "command", "timeoutMs", "output", "role", "provider"]);
1417
+ for (const property of params.properties) {
1418
+ if (!astNode(property)) continue;
1419
+ const name = staticPropertyKey(property);
1420
+ if (name !== undefined && !allowed.has(name)) errors.push({ message: name === "cwd" ? "runs.host params contain unsupported field 'cwd'. 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')." : `runs.host params contain unsupported field '${name}'.`, ...nodeLocation(property) });
1421
+ }
1422
+ const kindNode = directObjectPropertyValue(params, "kind");
1423
+ const commandNode = directObjectPropertyValue(params, "command");
1424
+ const timeoutNode = directObjectPropertyValue(params, "timeoutMs");
1425
+ const kind = literalString(kindNode);
1426
+ const command = literalString(commandNode);
1427
+ const timeout = astNode(timeoutNode) && timeoutNode.type === "Literal" ? timeoutNode.value : undefined;
1428
+ if (!kindNode) errors.push({ message: "runs.host params require kind: 'command'.", ...nodeLocation(params) });
1429
+ else if (kind !== undefined && kind !== "command") errors.push({ message: "runs.host params kind must be 'command'.", ...nodeLocation(kindNode) });
1430
+ if (!commandNode) errors.push({ message: "runs.host params require command.", ...nodeLocation(params) });
1431
+ else if (command !== undefined && !command.trim()) errors.push({ message: "runs.host params command must be non-empty.", ...nodeLocation(commandNode) });
1432
+ if (!timeoutNode) errors.push({ message: "runs.host params require timeoutMs.", ...nodeLocation(params) });
1433
+ else if (typeof timeout === "number" && (!Number.isInteger(timeout) || timeout < 1)) errors.push({ message: "runs.host params timeoutMs must be a positive integer.", ...nodeLocation(timeoutNode) });
1434
+ const outputNode = directObjectPropertyValue(params, "output");
1435
+ const output = literalString(outputNode);
1436
+ if (outputNode && output !== undefined && (!output.trim() || /^[/\\]|(?:^|[/\\])\.\.(?:[/\\]|$)/.test(output))) errors.push({ message: "runs.host params output must be a non-empty relative path without traversal.", ...nodeLocation(outputNode) });
1437
+ const roleNode = directObjectPropertyValue(params, "role");
1438
+ const role = literalString(roleNode);
1439
+ if (roleNode && role !== undefined && role !== "ci" && role !== "gate") errors.push({ message: "runs.host params role must be 'ci' or 'gate'.", ...nodeLocation(roleNode) });
1440
+ return errors;
1441
+ }
1442
+
1443
+ function nodeLocation(node: AstNode): Pick<WorkflowScriptValidationError, "line" | "column"> {
1444
+ return node.loc ? { line: Math.max(1, node.loc.start.line - 1), column: node.loc.start.column + 1 } : {};
1445
+ }
1446
+
1447
+ function walkAst(node: unknown, visit: (node: AstNode) => void, includeNestedFunctions = true): void {
1448
+ if (Array.isArray(node)) {
1449
+ for (const item of node) walkAst(item, visit, includeNestedFunctions);
1450
+ return;
1451
+ }
1452
+ if (!astNode(node)) return;
1453
+ visit(node);
1454
+ if (!includeNestedFunctions && (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression")) return;
1455
+ for (const [key, child] of Object.entries(node)) {
1456
+ if (!AST_LOCATION_KEYS.has(key)) walkAst(child, visit, includeNestedFunctions);
1457
+ }
1458
+ }
1459
+
1460
+ function definitelyNonJson(node: AstNode, normalizeUndefined = false): string | undefined {
1461
+ if (node.type === "Literal") {
1462
+ if (typeof node.bigint === "string") return "BigInt values are not JSON-representable";
1463
+ if (node.regex !== undefined) return "regular expressions are not JSON-representable";
1464
+ return undefined;
1465
+ }
1466
+ if (node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") return "functions are not JSON-representable";
1467
+ if (node.type === "Identifier" && node.name === "undefined") return normalizeUndefined ? undefined : "undefined is not JSON-representable";
1468
+ if (node.type === "UnaryExpression" && node.operator === "void") return normalizeUndefined ? undefined : "undefined is not JSON-representable";
1469
+ if (node.type === "ArrayExpression" && Array.isArray(node.elements)) {
1470
+ if (node.elements.some((entry) => entry === null)) return "sparse arrays are not JSON-representable";
1471
+ for (const entry of node.elements) if (astNode(entry)) {
1472
+ const error = definitelyNonJson(entry, normalizeUndefined);
1473
+ if (error) return error;
1474
+ }
1475
+ }
1476
+ if (node.type === "ObjectExpression" && Array.isArray(node.properties)) {
1477
+ const values = new Map<string, AstNode>();
1478
+ for (const property of node.properties) {
1479
+ if (!astNode(property) || property.type !== "Property" || !astNode(property.value)) return undefined;
1480
+ const key = staticPropertyKey(property);
1481
+ if (key === undefined) return undefined;
1482
+ values.set(key, property.value);
1483
+ }
1484
+ for (const value of values.values()) {
1485
+ const error = definitelyNonJson(value, normalizeUndefined);
1486
+ if (error) return error;
1487
+ }
1488
+ }
1489
+ return undefined;
1490
+ }
1491
+
1492
+ function staticPropertyKey(property: AstNode): string | undefined {
1493
+ return property.computed === true
1494
+ ? literalString(property.key)
1495
+ : literalString(property.key) ?? (astNode(property.key) && property.key.type === "Identifier" ? property.key.name as string : undefined);
1496
+ }
1497
+
1498
+ function directObjectPropertyValue(node: AstNode, name: string): AstNode | undefined {
1499
+ if (node.type !== "ObjectExpression" || !Array.isArray(node.properties)) return undefined;
1500
+ let value: AstNode | undefined;
1501
+ for (const property of node.properties) {
1502
+ if (!astNode(property) || property.type !== "Property" || !astNode(property.value)) continue;
1503
+ if (staticPropertyKey(property) === name) value = property.value;
1504
+ }
1505
+ return value;
1506
+ }
1507
+
1508
+ function directRunsAllKeys(call: AstNode): Array<{ key: string; node: AstNode }> {
1509
+ const args = Array.isArray(call.arguments) ? call.arguments : [];
1510
+ const items = astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements) ? args[0].elements : [];
1511
+ return items.flatMap((item) => {
1512
+ if (!astNode(item)) return [];
1513
+ const keyNode = directObjectPropertyValue(item, "key");
1514
+ const key = literalString(keyNode);
1515
+ return keyNode && key !== undefined ? [{ key, node: keyNode }] : [];
1516
+ });
1517
+ }
1518
+
1519
+ /** Parse a workflowScript and apply only rules that are decidable from its local syntax. */
1520
+ export function validateWorkflowScript(script: string): WorkflowScriptValidationResult {
1521
+ const errors: WorkflowScriptValidationError[] = [];
1522
+ if (!script.trim()) return { ok: false, errors: [{ message: "workflowScript must not be empty." }] };
1523
+ let root: AstNode;
1524
+ try {
1525
+ const parser = requireFromPackage(resolveWorkflowParserEntry()) as { parse(source: string, options: Record<string, unknown>): unknown };
1526
+ root = parser.parse(`(async () => {\n${script}\n})()`, { ecmaVersion: "latest", sourceType: "script", locations: true }) as AstNode;
1527
+ } catch (error) {
1528
+ const location = error && typeof error === "object" && "loc" in error && error.loc && typeof error.loc === "object"
1529
+ ? error.loc as { line?: unknown; column?: unknown }
1530
+ : undefined;
1531
+ const message = (error instanceof Error ? error.message : String(error)).replace(/\s+\(\d+:\d+\)$/, "");
1532
+ return { ok: false, errors: [{ message, ...(typeof location?.line === "number" ? { line: Math.max(1, location.line - 1) } : {}), ...(typeof location?.column === "number" ? { column: location.column + 1 } : {}) }] };
1533
+ }
1534
+
1535
+ const wrapper = astNode(root.body) ? undefined : Array.isArray(root.body) && astNode(root.body[0]) && astNode(root.body[0].expression) && astNode(root.body[0].expression.callee)
1536
+ ? root.body[0].expression.callee
1537
+ : undefined;
1538
+ const workflowBody = wrapper && astNode(wrapper.body) ? wrapper.body : root;
1539
+ walkAst(workflowBody, (node) => {
1540
+ if (node !== wrapper && node.async === true && (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression")) {
1541
+ errors.push({ message: "workflowScript does not support nested async functions. Use top-level await, plain helper functions that return runs.run(...), or explicit Promise chains.", ...nodeLocation(node) });
1542
+ }
1543
+ if (directRunsCall(node, "run")) {
1544
+ const args = Array.isArray(node.arguments) ? node.arguments : [];
1545
+ const keyNode = astNode(args[0]) ? args[0] : undefined;
1546
+ const key = literalString(keyNode);
1547
+ if (keyNode && key !== undefined && !KEY_PATTERN.test(key)) errors.push({ message: "runs.run key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.", ...nodeLocation(keyNode) });
1548
+ if (astNode(args[1])) {
1549
+ const message = definitelyNonJson(args[1]);
1550
+ if (message) errors.push({ message: `runs.run params are invalid: ${message}.`, ...nodeLocation(args[1]) });
1551
+ }
1552
+ }
1553
+ if (directRunsCall(node, "all")) {
1554
+ for (const entry of directRunsAllKeys(node)) if (!KEY_PATTERN.test(entry.key)) errors.push({ message: "runs.all item key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.", ...nodeLocation(entry.node) });
1555
+ const args = Array.isArray(node.arguments) ? node.arguments : [];
1556
+ if (astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements)) {
1557
+ for (const item of args[0].elements) if (astNode(item)) {
1558
+ const message = definitelyNonJson(item);
1559
+ if (message) errors.push({ message: `runs.all item params are invalid: ${message}.`, ...nodeLocation(item) });
1560
+ }
1561
+ }
1562
+ }
1563
+ if (directRunsCall(node, "host")) errors.push(...validateStaticHostCall(node));
1564
+ const boundaryValue = node.type === "CallExpression" && astNode(node.callee) && node.callee.type === "Identifier" && node.callee.name === "emit" && Array.isArray(node.arguments) && astNode(node.arguments[0])
1565
+ ? node.arguments[0]
1566
+ : node.type === "CallExpression" && astNode(node.callee) && node.callee.type === "MemberExpression" && astNode(node.callee.object) && node.callee.object.type === "Identifier" && node.callee.object.name === "state" && astNode(node.callee.property) && node.callee.property.type === "Identifier" && node.callee.property.name === "set" && Array.isArray(node.arguments) && astNode(node.arguments[1])
1567
+ ? node.arguments[1]
1568
+ : undefined;
1569
+ if (boundaryValue) {
1570
+ const message = definitelyNonJson(boundaryValue);
1571
+ if (message) errors.push({ message: `workflowScript boundary value is invalid: ${message}.`, ...nodeLocation(boundaryValue) });
1572
+ }
1573
+ });
1574
+ walkAst(workflowBody, (node) => {
1575
+ if (node.type !== "ReturnStatement" || !astNode(node.argument)) return;
1576
+ const message = definitelyNonJson(node.argument, true);
1577
+ if (message) errors.push({ message: `workflowScript boundary value is invalid: ${message}.`, ...nodeLocation(node.argument) });
1578
+ }, false);
1579
+
1580
+ if (workflowBody.type === "BlockStatement" && Array.isArray(workflowBody.body)) {
1581
+ for (let statementIndex = 0; statementIndex < workflowBody.body.length; statementIndex++) {
1582
+ const statement = workflowBody.body[statementIndex];
1583
+ if (!astNode(statement) || statement.type !== "VariableDeclaration" || !Array.isArray(statement.declarations)) continue;
1584
+ for (const declaration of statement.declarations) {
1585
+ if (!astNode(declaration) || !astNode(declaration.id) || declaration.id.type !== "Identifier" || !astNode(declaration.init) || declaration.init.type !== "AwaitExpression" || !directRunsCall(declaration.init.argument, "all")) continue;
1586
+ const name = declaration.id.name as string;
1587
+ const keys = new Set(directRunsAllKeys(declaration.init.argument).map((entry) => entry.key));
1588
+ if (keys.size === 0) continue;
1589
+ const args = Array.isArray(declaration.init.argument.arguments) ? declaration.init.argument.arguments : [];
1590
+ const itemCount = astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements) ? args[0].elements.length : 0;
1591
+ const arrayResultShape = Array.from({ length: itemCount });
1592
+ for (const later of workflowBody.body.slice(statementIndex + 1)) walkAst(later, (node) => {
1593
+ if (node.type !== "MemberExpression" || !astNode(node.object) || node.object.type !== "Identifier" || node.object.name !== name) return;
1594
+ const property = node.computed === true ? literalString(node.property) : astNode(node.property) && node.property.type === "Identifier" ? node.property.name as string : undefined;
1595
+ if (property && keys.has(property) && !(property in arrayResultShape)) errors.push({ message: `runs.all returns an ordered array; '${name}.${property}' is keyed access. Use an index, destructuring, or map(...).`, ...nodeLocation(node) });
1596
+ }, false);
1597
+ }
1598
+ }
1599
+ }
1600
+
1601
+ const unique = errors.filter((error, index) => errors.findIndex((candidate) => candidate.message === error.message && candidate.line === error.line && candidate.column === error.column) === index);
1602
+ return { ok: unique.length === 0, errors: unique };
1603
+ }
867
1604
  function workflowStringMetadata(params: Record<string, unknown>): Pick<WorkflowScriptTraceEntry, "phase" | "label" | "agent"> {
868
1605
  return {
869
1606
  ...(typeof params.phase === "string" && params.phase.trim() ? { phase: params.phase.trim() } : {}),
@@ -893,9 +1630,48 @@ function resolveWorkflowParserEntry(): string {
893
1630
  }
894
1631
  }
895
1632
 
1633
+ const AUTO_RESUME_PARAM_KEYS = ["acceptance", "agentContract", "baseRef", "index", "intercomBridge", "label", "lane", "maxRuntimeMs", "output", "outputMode", "outputSchema", "phase", "skill", "skills", "task", "timeoutMs", "toolBudget", "worktree"] as const;
1634
+
1635
+ function isZeroUsage(usage: unknown): boolean {
1636
+ if (!isRecord(usage)) return false;
1637
+ const cost = usage.cost;
1638
+ return (usage.input ?? 0) === 0
1639
+ && (usage.output ?? 0) === 0
1640
+ && (usage.cacheRead ?? 0) === 0
1641
+ && (usage.cacheWrite ?? 0) === 0
1642
+ && (!isRecord(cost) || (cost.total ?? 0) === 0);
1643
+ }
1644
+
1645
+ function setupAbortResumeParams(params: Record<string, unknown>, result: WorkflowScriptChildResult, signal: AbortSignal): Record<string, unknown> | undefined {
1646
+ if (signal.aborted || result.ok || result.stopped || result.interrupted || !result.runId) return undefined;
1647
+ const childResult = Array.isArray(result.results) && result.results.length === 1 && isRecord(result.results[0]) ? result.results[0] : undefined;
1648
+ const error = typeof childResult?.error === "string" ? childResult.error : result.error;
1649
+ if (error !== "This operation was aborted" || !isZeroUsage(childResult?.usage)) return undefined;
1650
+ const messages = Array.isArray(childResult?.messages) ? childResult.messages : [];
1651
+ const message = messages.findLast((entry) => isRecord(entry) && entry.role === "assistant");
1652
+ if (message !== undefined) {
1653
+ if (!isRecord(message)) return undefined;
1654
+ if (message.stopReason !== "error" || message.errorMessage !== error) return undefined;
1655
+ if (!Array.isArray(message.content) || message.content.length > 0 || !isZeroUsage(message.usage)) return undefined;
1656
+ if (Object.hasOwn(message, "diagnostics") || Object.hasOwn(message, "responseId")) return undefined;
1657
+ }
1658
+ const task = typeof params.task === "string" && params.task.trim() ? params.task.trim() : "Continue after the setup abort.";
1659
+ const resumeParams: Record<string, unknown> = { resume: result.runId, task };
1660
+ for (const key of AUTO_RESUME_PARAM_KEYS) {
1661
+ if (Object.hasOwn(params, key)) resumeParams[key] = params[key];
1662
+ }
1663
+ resumeParams.resume = result.runId;
1664
+ resumeParams.task = task;
1665
+ return resumeParams;
1666
+ }
1667
+
896
1668
  export async function runWorkflowScript(options: RunWorkflowScriptOptions): Promise<WorkflowScriptResult> {
897
1669
  if (!options.script.trim()) throw new Error("workflowScript must not be empty.");
898
1670
  if (options.timeoutMs !== undefined && (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1)) throw new Error("workflow script timeout must be a positive integer.");
1671
+ if (options.globalConcurrencyLimit !== undefined && (!Number.isSafeInteger(options.globalConcurrencyLimit) || options.globalConcurrencyLimit < 1)) {
1672
+ throw new Error("workflow script global concurrency limit must be a positive integer.");
1673
+ }
1674
+ const launchSemaphore = new Semaphore(options.globalConcurrencyLimit ?? DEFAULT_GLOBAL_CONCURRENCY_LIMIT);
899
1675
 
900
1676
  let acornPath: string;
901
1677
  try {
@@ -909,16 +1685,22 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
909
1685
  const trace: WorkflowScriptTraceEntry[] = [];
910
1686
  const children = new Map<string, WorkflowScriptChildResult>();
911
1687
  const childOrder: string[] = [];
912
- const launches = new Map<string, { fingerprint: string; promise: Promise<WorkflowScriptChildResult>; observed: boolean }>();
1688
+ const launches = new Map<string, { fingerprint: string; promise: Promise<WorkflowScriptChildResult>; observed: boolean; generatedLaneKey?: string }>();
913
1689
  const steers = new Map<number, { key: string; promise: Promise<WorkflowSteerResult>; observed: boolean }>();
1690
+ const hostCalls = new Map<number, { key: string; promise: Promise<WorkflowHostCommandResult>; observed: boolean }>();
914
1691
  const stoppedLaunches = new Set<string>();
915
1692
  const childStopControllers = new Map<string, AbortController>();
916
1693
  const batchAdmissions = new Map<string, Promise<void>>();
917
1694
  const observedRunCalls = new Set<number>();
918
1695
  const observedSteerCalls = new Set<number>();
1696
+ const observedHostCalls = new Set<number>();
919
1697
  const childController = new AbortController();
1698
+ let acceptanceRecoveryBarrier: { key: string } | undefined;
920
1699
  let settled = false;
921
1700
  let finishing = false;
1701
+ let assemblyAbortRequested = false;
1702
+ let assemblyFlushTimer: ReturnType<typeof setTimeout> | undefined;
1703
+ let abortError: Error | undefined;
922
1704
 
923
1705
  const partial = (): Omit<WorkflowScriptResult, "value"> => ({ emits, console: consoleEntries, trace, children: childOrder.flatMap((key) => {
924
1706
  const child = children.get(key);
@@ -936,7 +1718,32 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
936
1718
  console.error("Workflow onTrace callback failed:", error);
937
1719
  }
938
1720
  };
1721
+ const lanePlanChanged = (lanes: WorkflowLanePlan[]) => {
1722
+ try {
1723
+ options.onLanePlan?.(lanes);
1724
+ } catch (error) {
1725
+ console.error("Workflow onLanePlan callback failed:", error);
1726
+ }
1727
+ };
1728
+ const hostStepChanged = (hostStep: HostStepNodeV1) => {
1729
+ try {
1730
+ options.onHostStep?.(hostStep);
1731
+ } catch (error) {
1732
+ console.error("Workflow onHostStep callback failed:", error);
1733
+ }
1734
+ };
939
1735
  const stoppedChildResult = (key: string, message: string): WorkflowScriptChildResult => ({ key, ok: false, stopped: true, output: message, error: message, artifactPaths: [] });
1736
+ const responseBoundaryFailure = (key: string, error: unknown): WorkflowScriptChildResult => {
1737
+ const text = error instanceof Error ? error.message : String(error);
1738
+ return { key, ok: false, output: text, error: text, artifactPaths: [] };
1739
+ };
1740
+ const assertRecoveryBarrierAllowsRun = (key: string, params: Record<string, unknown>): void => {
1741
+ if (!acceptanceRecoveryBarrier || isExplicitReadOnlyRecoveryReview(params)) return;
1742
+ throw new Error(recoveryBarrierMessage(acceptanceRecoveryBarrier.key, key));
1743
+ };
1744
+ const recordAcceptanceRecoveryBarrier = (key: string, result: WorkflowScriptChildResult): void => {
1745
+ if (isAcceptanceMetadataRecovery(result)) acceptanceRecoveryBarrier = { key };
1746
+ };
940
1747
  const stopChild = (key: string, message = `Workflow child '${key}' stopped by user.`): boolean => {
941
1748
  if (!launches.has(key) || children.has(key)) return false;
942
1749
  stoppedLaunches.add(key);
@@ -950,6 +1757,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
950
1757
  ...(started?.agent ? { agent: started.agent } : {}),
951
1758
  ...(started?.phase ? { phase: started.phase } : {}),
952
1759
  ...(started?.label ? { label: started.label } : {}),
1760
+ ...(started?.generatedLaneKey ? { generatedLaneKey: started.generatedLaneKey } : {}),
953
1761
  error: message,
954
1762
  });
955
1763
  traceChanged();
@@ -961,8 +1769,12 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
961
1769
  const finish = (outcome: { value: unknown } | { error: Error & { workflowErrorKind?: unknown } }) => {
962
1770
  if (settled || finishing) return;
963
1771
  finishing = true;
1772
+ if (assemblyFlushTimer !== undefined) {
1773
+ clearTimeout(assemblyFlushTimer);
1774
+ assemblyFlushTimer = undefined;
1775
+ }
964
1776
  childController.abort("error" in outcome ? outcome.error : new Error("Workflow script completed."));
965
- void Promise.allSettled([...steers.values()].map(({ promise }) => promise)).then(() => {
1777
+ void Promise.allSettled([...steers.values(), ...hostCalls.values()].map(({ promise }) => promise)).then(() => {
966
1778
  if (settled) return;
967
1779
  settled = true;
968
1780
  options.registerStopChild?.(undefined);
@@ -975,10 +1787,12 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
975
1787
  : "value" in outcome
976
1788
  ? (() => {
977
1789
  const unobservedSteers = [...steers.values()].filter((steer) => !steer.observed).map((steer) => steer.key);
978
- return unobservedSteers.length > 0 ? new Error(`workflowScript completed with unawaited runs.steer call(s): ${unobservedSteers.map((key) => `'${key}'`).join(", ")}. Await or return each call.`) : undefined;
1790
+ if (unobservedSteers.length > 0) return new Error(`workflowScript completed with unawaited runs.steer call(s): ${unobservedSteers.map((key) => `'${key}'`).join(", ")}. Await or return each call.`);
1791
+ const unobservedHosts = [...hostCalls.values()].filter((host) => !host.observed).map((host) => host.key);
1792
+ return unobservedHosts.length > 0 ? new Error(`workflowScript completed with unawaited runs.host call(s): ${unobservedHosts.map((key) => `'${key}'`).join(", ")}. Await or return each call.`) : undefined;
979
1793
  })()
980
1794
  : undefined;
981
- if ("error" in outcome) reject(new WorkflowScriptError(outcome.error.message, partial(), outcome.error.workflowErrorKind === "detached-child" ? "detached-child" : undefined));
1795
+ if ("error" in outcome) reject(new WorkflowScriptError(outcome.error.message, partial(), outcome.error.workflowErrorKind === "detached-child" || outcome.error.workflowErrorKind === "timeout" ? outcome.error.workflowErrorKind : undefined));
982
1796
  else if (completionError) reject(new WorkflowScriptError(completionError.message, partial()));
983
1797
  else resolve({ value: outcome.value, ...partial() });
984
1798
  });
@@ -990,6 +1804,26 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
990
1804
  : typeof signalReason === "string"
991
1805
  ? new Error(signalReason)
992
1806
  : new Error("Workflow script aborted.");
1807
+ if (finishing) return;
1808
+ abortError = error;
1809
+ const allChildrenSettled = launches.size > 0
1810
+ && [...launches.keys()].every((key) => children.has(key));
1811
+ let mayFlushAssembly = false;
1812
+ try {
1813
+ mayFlushAssembly = options.continueAfterAbortWhenChildrenSettled?.(error) === true;
1814
+ } catch (callbackError) {
1815
+ const callbackMessage = callbackError instanceof Error ? callbackError.message : String(callbackError);
1816
+ return finish({ error: new Error(`Workflow assembly flush eligibility failed: ${callbackMessage}`) });
1817
+ }
1818
+ if (mayFlushAssembly && allChildrenSettled) {
1819
+ // A reloaded async workflow may already be past its last child launch.
1820
+ // Keep the worker alive for pure result assembly, but abort the child
1821
+ // signal so any later launch or side effect cannot use stale context.
1822
+ assemblyAbortRequested = true;
1823
+ childController.abort(error);
1824
+ assemblyFlushTimer = setTimeout(() => finish({ error }), WORKFLOW_ASSEMBLY_FLUSH_TIMEOUT_MS);
1825
+ return;
1826
+ }
993
1827
  for (const key of launches.keys()) {
994
1828
  if (children.has(key)) continue;
995
1829
  stoppedLaunches.add(key);
@@ -1001,6 +1835,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1001
1835
  ...(started?.agent ? { agent: started.agent } : {}),
1002
1836
  ...(started?.phase ? { phase: started.phase } : {}),
1003
1837
  ...(started?.label ? { label: started.label } : {}),
1838
+ ...(started?.generatedLaneKey ? { generatedLaneKey: started.generatedLaneKey } : {}),
1004
1839
  error: error.message,
1005
1840
  });
1006
1841
  }
@@ -1009,7 +1844,11 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1009
1844
  };
1010
1845
  const timer = options.timeoutMs === undefined
1011
1846
  ? undefined
1012
- : setTimeout(() => finish({ error: new Error(`Workflow script timed out after ${options.timeoutMs}ms.`) }), options.timeoutMs);
1847
+ : setTimeout(() => {
1848
+ const error = new Error(`Workflow script timed out after ${options.timeoutMs}ms.`) as Error & { workflowErrorKind: "timeout" };
1849
+ error.workflowErrorKind = "timeout";
1850
+ finish({ error });
1851
+ }, options.timeoutMs);
1013
1852
  options.signal?.addEventListener("abort", onAbort, { once: true });
1014
1853
  if (options.signal?.aborted) return onAbort();
1015
1854
 
@@ -1019,6 +1858,10 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1019
1858
  });
1020
1859
  worker.on("message", (message: Record<string, unknown>) => {
1021
1860
  if (settled) return;
1861
+ if (message.type === "lanePlan" && Array.isArray(message.lanes)) {
1862
+ lanePlanChanged(message.lanes as WorkflowLanePlan[]);
1863
+ return;
1864
+ }
1022
1865
  if (message.type === "emit") {
1023
1866
  try {
1024
1867
  assertWorkflowJsonValue(message.value, "emit");
@@ -1049,7 +1892,9 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1049
1892
  return finish({ value: message.value });
1050
1893
  }
1051
1894
  if (message.type === "error") {
1052
- const workflowError = new Error(typeof message.error === "string" ? message.error : "Workflow script failed.") as Error & { workflowErrorKind?: "detached-child" };
1895
+ const rawError = typeof message.error === "string" ? message.error : "Workflow script failed.";
1896
+ const text = message.errorPhase === "return-serialization" ? `${rawError}${workflowReturnRecoveryHint(partial().children)}` : rawError;
1897
+ const workflowError = new Error(text) as Error & { workflowErrorKind?: "detached-child" };
1053
1898
  if (message.errorKind === "detached-child") workflowError.workflowErrorKind = "detached-child";
1054
1899
  return finish({ error: workflowError });
1055
1900
  }
@@ -1063,12 +1908,17 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1063
1908
  const steer = steers.get(message.callId);
1064
1909
  if (steer) steer.observed = true;
1065
1910
  else observedSteerCalls.add(message.callId);
1911
+ } else if (message.operation === "host") {
1912
+ const host = hostCalls.get(message.callId);
1913
+ if (host) host.observed = true;
1914
+ else observedHostCalls.add(message.callId);
1066
1915
  }
1067
1916
  return;
1068
1917
  }
1069
1918
  if (message.type !== "call" || typeof message.callId !== "number" || typeof message.method !== "string" || !isRecord(message.args)) return;
1919
+ if (assemblyAbortRequested) return finish({ error: abortError ?? new Error("Workflow context was replaced or reloaded.") });
1070
1920
 
1071
- const respond = (promise: Promise<unknown>, responsePath?: string) => {
1921
+ const respond = (promise: Promise<unknown>, responsePath?: string, onBoundaryError?: (error: unknown) => void) => {
1072
1922
  void promise.then(
1073
1923
  (value) => {
1074
1924
  if (settled) return;
@@ -1081,6 +1931,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1081
1931
  assertWorkflowJsonValue(normalized, responsePath);
1082
1932
  worker.postMessage({ type: "response", callId: message.callId, ok: true, value: normalized });
1083
1933
  } catch (error) {
1934
+ onBoundaryError?.(error);
1084
1935
  worker.postMessage({ type: "response", callId: message.callId, ok: false, error: `${responsePath} must contain only JSON data before it can be returned from workflowScript. Return a plain projection such as { runId, ok, output }. ${error instanceof Error ? error.message : String(error)}` });
1085
1936
  }
1086
1937
  },
@@ -1098,6 +1949,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1098
1949
  return respond(Promise.reject(error));
1099
1950
  }
1100
1951
  if (message.method === "state.get") return respond(Promise.resolve().then(() => options.state!.get(key)));
1952
+ if (acceptanceRecoveryBarrier) return respond(Promise.reject(new Error(recoveryBarrierMessage(acceptanceRecoveryBarrier.key, `state.set('${key}')`))));
1101
1953
  const value = message.args.value;
1102
1954
  try {
1103
1955
  assertWorkflowJsonValue(value, `state.set('${key}') value`);
@@ -1134,6 +1986,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1134
1986
  const steerMessage = message.args.message;
1135
1987
  if (typeof steerMessage !== "string" || !steerMessage.trim()) return respond(Promise.reject(new Error(`runs.steer('${key}') requires a non-empty message.`)));
1136
1988
  const steerOptions = isRecord(message.args.options) ? message.args.options as WorkflowSteerOptions : {};
1989
+ if (acceptanceRecoveryBarrier) return respond(Promise.reject(new Error(recoveryBarrierMessage(acceptanceRecoveryBarrier.key, `runs.steer('${key}')`))));
1137
1990
  const startedAt = Date.now();
1138
1991
  trace.push({ operation: "steer", key, state: "started" });
1139
1992
  traceChanged();
@@ -1155,6 +2008,53 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1155
2008
  respond(promise);
1156
2009
  return;
1157
2010
  }
2011
+ if (message.method === "host") {
2012
+ let key: string;
2013
+ let params: WorkflowHostCommandParams;
2014
+ try {
2015
+ key = validateKey(message.args.key, "runs.host");
2016
+ params = normalizeWorkflowHostCommandParams(message.args.params, `runs.host('${key}') params`);
2017
+ } catch (error) {
2018
+ return respond(Promise.reject(error));
2019
+ }
2020
+ if (acceptanceRecoveryBarrier) return respond(Promise.reject(new Error(recoveryBarrierMessage(acceptanceRecoveryBarrier.key, `runs.host('${key}')`))));
2021
+ if (!options.host) return respond(Promise.reject(new Error("runs.host is unavailable in this host context.")));
2022
+ if (hostCalls.size >= HOST_STEP_MAX_COUNT) return respond(Promise.reject(new Error(`workflowScript supports at most ${HOST_STEP_MAX_COUNT} runs.host calls.`)));
2023
+ const startedAt = Date.now();
2024
+ const startedStep: HostStepNodeV1 = {
2025
+ version: 1,
2026
+ kind: "host-step",
2027
+ monitorKind: "command",
2028
+ id: key,
2029
+ label: key,
2030
+ ...(params.role ? { role: params.role } : {}),
2031
+ ...(params.provider ? { provider: params.provider } : {}),
2032
+ state: "running",
2033
+ updatedAt: startedAt,
2034
+ deadlineAt: startedAt + params.timeoutMs,
2035
+ };
2036
+ hostStepChanged(startedStep);
2037
+ trace.push({ operation: "host", key, state: "started" });
2038
+ traceChanged();
2039
+ const promise = Promise.resolve().then(() => options.host!(key, params, childController.signal)).then((result) => {
2040
+ const state = result.state === "stopped" ? "cancelled" : result.ok ? "done" : "error";
2041
+ const detail = [result.error, result.stderr.trim() || result.stdout.trim()].filter(Boolean).join(" ").replace(/\s+/g, " ").trim().slice(0, 200);
2042
+ hostStepChanged({ ...startedStep, state, ...(state === "done" ? { verdict: "pass" as const } : {}), ...(!result.ok ? { reasonCode: result.state === "timed-out" ? "timed_out" : result.state === "stopped" ? "aborted" : "command_failed" } : {}), ...(detail ? { detail } : {}), reportPath: params.output ?? result.outputPath.split(/[\\/]/).at(-1), exitCode: result.exitCode, updatedAt: Date.now() });
2043
+ trace.push({ operation: "host", key, state: result.ok ? "completed" : result.state === "stopped" ? "stopped" : "failed", durationMs: result.durationMs, ...(!result.ok ? { error: result.error ?? "Host command failed." } : {}) });
2044
+ traceChanged();
2045
+ if (!result.ok) throw new Error(`Host command '${key}' failed: ${detail || result.error || `exit code ${result.exitCode ?? "unknown"}`}`);
2046
+ return result;
2047
+ }, (error: unknown) => {
2048
+ const text = error instanceof Error ? error.message : String(error);
2049
+ hostStepChanged({ ...startedStep, state: "error", reasonCode: "execution_failed", detail: text.replace(/\s+/g, " ").slice(0, 200), updatedAt: Date.now() });
2050
+ trace.push({ operation: "host", key, state: "failed", durationMs: Date.now() - startedAt, error: text });
2051
+ traceChanged();
2052
+ throw error;
2053
+ });
2054
+ hostCalls.set(message.callId, { key, promise, observed: observedHostCalls.delete(message.callId) });
2055
+ respond(promise, `runs.host('${key}') result`);
2056
+ return;
2057
+ }
1158
2058
  if (message.method !== "run") return respond(Promise.reject(new Error(`Unknown runs API method '${message.method}'.`)));
1159
2059
 
1160
2060
  let key: string;
@@ -1165,6 +2065,36 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1165
2065
  }
1166
2066
  const params = message.args.params;
1167
2067
  if (!isRecord(params)) return respond(Promise.reject(new Error(`runs.run('${key}', params) requires a params object.`)));
2068
+ const generatedLaneKey = typeof message.args.generatedLaneKey === "string" && KEY_PATTERN.test(message.args.generatedLaneKey) && key.startsWith(`${message.args.generatedLaneKey}.`)
2069
+ ? message.args.generatedLaneKey
2070
+ : undefined;
2071
+ const collectFailure = message.args.collectFailure === true;
2072
+ const callObserved = observedRunCalls.delete(message.callId);
2073
+ const deliver = (promise: Promise<WorkflowScriptChildResult>) => collectFailure
2074
+ ? promise
2075
+ : promise.then((result) => {
2076
+ const recoverableAcceptanceMetadata = result.recovery?.status === "available-for-review"
2077
+ && result.recovery.reason === "acceptance-metadata-rejected";
2078
+ if (!result.ok && !result.stopped && !recoverableAcceptanceMetadata) {
2079
+ const childError = new Error(result.detached ? `Run '${key}' detached: ${result.error ?? result.output}` : `Run '${key}' failed: ${result.error ?? result.output}`) as Error & { workflowErrorKind?: "detached-child" };
2080
+ if (result.detached) childError.workflowErrorKind = "detached-child";
2081
+ throw childError;
2082
+ }
2083
+ return result;
2084
+ });
2085
+ const fingerprint = stableJson(params);
2086
+ const existing = launches.get(key);
2087
+ if (existing) {
2088
+ if (existing.fingerprint !== fingerprint) return respond(Promise.reject(new Error(`Duplicate workflow key '${key}' used with incompatible launch params.`)));
2089
+ if (callObserved) existing.observed = true;
2090
+ trace.push({ operation: "run", key, state: "reused", ...workflowStringMetadata(params), ...(existing.generatedLaneKey ? { generatedLaneKey: existing.generatedLaneKey } : {}) });
2091
+ traceChanged();
2092
+ return respond(deliver(existing.promise), `runs.run('${key}') result`, (error) => children.set(key, responseBoundaryFailure(key, error)));
2093
+ }
2094
+ const permitError = options.oneUsePermit?.claim(key);
2095
+ if (permitError) return respond(Promise.reject(new Error(permitError)));
2096
+ if (options.oneUsePermit && message.args.batch !== undefined) return respond(Promise.reject(new Error("Workflow child permit does not support runs.all.")));
2097
+ if (options.oneUsePermit && params.resume !== undefined) return respond(Promise.reject(new Error("Workflow child permit does not support retained resume.")));
1168
2098
  if (params.action !== undefined) return respond(Promise.reject(new Error(`runs.run('${key}') accepts execution params only; management action is not allowed.`)));
1169
2099
  if (params.workflowScript !== undefined) return respond(Promise.reject(new Error(`runs.run('${key}') cannot start a nested workflow script.`)));
1170
2100
  if (params.tasks !== undefined || params.chain !== undefined || params.parallel !== undefined || params.concurrency !== undefined || params.chainDir !== undefined) {
@@ -1173,6 +2103,9 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1173
2103
  if (params.worktree !== undefined && typeof params.worktree !== "boolean") {
1174
2104
  return respond(Promise.reject(new Error(`runs.run('${key}') worktree must be true or false.`)));
1175
2105
  }
2106
+ if (params.baseRef !== undefined && (typeof params.baseRef !== "string" || !validGitRef(params.baseRef))) {
2107
+ return respond(Promise.reject(new Error(`runs.run('${key}') baseRef must be a valid Git ref.`)));
2108
+ }
1176
2109
  if (params.gate !== undefined && (typeof params.gate !== "string" || !params.gate.trim())) {
1177
2110
  return respond(Promise.reject(new Error(`runs.run('${key}') gate must be a non-empty command string.`)));
1178
2111
  }
@@ -1195,28 +2128,6 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1195
2128
  if (params.resume !== undefined && (typeof params.task !== "string" || !params.task.trim())) {
1196
2129
  return respond(Promise.reject(new Error(`runs.run('${key}') resume requires a non-empty task follow-up.`)));
1197
2130
  }
1198
- const collectFailure = message.args.collectFailure === true;
1199
- const callObserved = observedRunCalls.delete(message.callId);
1200
- const deliver = (promise: Promise<WorkflowScriptChildResult>) => collectFailure
1201
- ? promise
1202
- : promise.then((result) => {
1203
- if (!result.ok && !result.stopped) {
1204
- const childError = new Error(result.detached ? `Run '${key}' detached: ${result.error ?? result.output}` : `Run '${key}' failed: ${result.error ?? result.output}`) as Error & { workflowErrorKind?: "detached-child" };
1205
- if (result.detached) childError.workflowErrorKind = "detached-child";
1206
- throw childError;
1207
- }
1208
- return result;
1209
- });
1210
- const fingerprint = stableJson(params);
1211
- const existing = launches.get(key);
1212
- if (existing) {
1213
- if (existing.fingerprint !== fingerprint) return respond(Promise.reject(new Error(`Duplicate workflow key '${key}' used with incompatible launch params.`)));
1214
- if (callObserved) existing.observed = true;
1215
- trace.push({ operation: "run", key, state: "reused", ...workflowStringMetadata(params) });
1216
- traceChanged();
1217
- return respond(deliver(existing.promise), `runs.run('${key}') result`);
1218
- }
1219
-
1220
2131
  const startedAt = Date.now();
1221
2132
  const batch = isRecord(message.args.batch) && typeof message.args.batch.id === "string" && Array.isArray(message.args.batch.calls)
1222
2133
  ? { id: message.args.batch.id, calls: message.args.batch.calls.filter((call): call is { key: string; params: Record<string, unknown> } => isRecord(call) && typeof call.key === "string" && isRecord(call.params)) }
@@ -1231,6 +2142,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1231
2142
  });
1232
2143
  admission = Promise.resolve().then(() => {
1233
2144
  if (settled || finishing) return;
2145
+ for (const call of calls) assertRecoveryBarrierAllowsRun(call.key, call.params);
1234
2146
  return options.admit?.(calls);
1235
2147
  });
1236
2148
  if (batch) batchAdmissions.set(batch.id, admission);
@@ -1266,7 +2178,23 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1266
2178
  if (resolvedResumeLineage.at(-1) !== resolvedResumeId) resolvedResumeLineage.push(resolvedResumeId!);
1267
2179
  }
1268
2180
  const launchParams = resolvedResumeId ? { ...params, resume: resolvedResumeId } : params;
1269
- return options.launch(key, launchParams, childSignal, { admitted: true });
2181
+ await launchSemaphore.acquire();
2182
+ try {
2183
+ if (settled || finishing || stoppedLaunches.has(key) || childSignal.aborted) {
2184
+ const reason = childSignal.reason;
2185
+ const text = children.get(key)?.error ?? (reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.");
2186
+ return stoppedChildResult(key, text);
2187
+ }
2188
+ const result = await options.launch(key, launchParams, childSignal, { admitted: true, batch: batch !== undefined });
2189
+ const autoResumeParams = setupAbortResumeParams(params, result, childSignal);
2190
+ if (!autoResumeParams) return result;
2191
+ resolvedResumeLineage = [...new Set([...(resolvedResumeLineage ?? []), result.runId!])];
2192
+ trace.push({ operation: "run", key, state: "started", ...workflowStringMetadata(autoResumeParams), ...(generatedLaneKey ? { generatedLaneKey } : {}), phase: "auto-resume", runId: result.runId });
2193
+ traceChanged();
2194
+ return options.launch(key, autoResumeParams, childSignal, { admitted: true, batch: batch !== undefined });
2195
+ } finally {
2196
+ launchSemaphore.release();
2197
+ }
1270
2198
  }).then((result) => {
1271
2199
  let normalized = !result.ok && !result.error ? { ...result, error: result.output } : result;
1272
2200
  if (resolvedResumeLineage?.length && normalized.runId) {
@@ -1275,8 +2203,9 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1275
2203
  childStopControllers.delete(key);
1276
2204
  if (stoppedLaunches.has(key)) return children.get(key) ?? normalized;
1277
2205
  children.set(key, normalized);
2206
+ recordAcceptanceRecoveryBarrier(key, normalized);
1278
2207
  const state = normalized.ok ? "completed" : normalized.stopped ? "stopped" : normalized.detached ? "detached" : "failed";
1279
- trace.push({ operation: "run", key, state, durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), ...(normalized.agent ? { agent: normalized.agent } : {}), ...(normalized.runId ? { runId: normalized.runId } : {}), ...(!normalized.ok ? { error: normalized.error ?? normalized.output } : {}) });
2208
+ trace.push({ operation: "run", key, state, durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), ...(generatedLaneKey ? { generatedLaneKey } : {}), ...(normalized.agent ? { agent: normalized.agent } : {}), ...(normalized.runId ? { runId: normalized.runId } : {}), ...(!normalized.ok ? { error: normalized.error ?? normalized.output } : {}) });
1280
2209
  traceChanged();
1281
2210
  return normalized;
1282
2211
  }, (error: unknown) => {
@@ -1285,15 +2214,15 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1285
2214
  childStopControllers.delete(key);
1286
2215
  if (stoppedLaunches.has(key)) return children.get(key) ?? { ...failure, stopped: true };
1287
2216
  children.set(key, failure);
1288
- trace.push({ operation: "run", key, state: "failed", durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), error: text });
2217
+ trace.push({ operation: "run", key, state: "failed", durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), ...(generatedLaneKey ? { generatedLaneKey } : {}), error: text });
1289
2218
  traceChanged();
1290
2219
  return failure;
1291
2220
  });
1292
- launches.set(key, { fingerprint, promise, observed: callObserved });
2221
+ launches.set(key, { fingerprint, promise, observed: callObserved, ...(generatedLaneKey ? { generatedLaneKey } : {}) });
1293
2222
  childOrder.push(key);
1294
- trace.push({ operation: "run", key, state: "started", ...workflowStringMetadata(params) });
2223
+ trace.push({ operation: "run", key, state: "started", ...workflowStringMetadata(params), ...(generatedLaneKey ? { generatedLaneKey } : {}) });
1295
2224
  traceChanged();
1296
- respond(deliver(promise), `runs.run('${key}') result`);
2225
+ respond(deliver(promise), `runs.run('${key}') result`, (error) => children.set(key, responseBoundaryFailure(key, error)));
1297
2226
  });
1298
2227
 
1299
2228
  worker.postMessage({ type: "start", script: options.script, stateEnabled: options.state !== undefined });