@xzzpig/pi-subagents 0.13.0 → 0.15.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 (202) hide show
  1. package/CHANGELOG.md +243 -0
  2. package/README.md +6 -5
  3. package/agents/evidence-auditor.md +34 -0
  4. package/agents/researcher.md +23 -13
  5. package/agents/reviewer.md +3 -2
  6. package/docs/agents.md +56 -15
  7. package/docs/configuration.md +93 -15
  8. package/docs/extension-api.md +132 -19
  9. package/docs/missions.md +10 -2
  10. package/docs/models.md +11 -22
  11. package/docs/observability.md +67 -11
  12. package/docs/standalone-background.md +59 -0
  13. package/docs/tool-reference.md +42 -23
  14. package/docs/watchdog.md +39 -10
  15. package/docs/workflows.md +58 -19
  16. package/index.ts +5 -2
  17. package/inspector-runner.mjs +2 -2
  18. package/node_modules/@xzzpig/pi-components/CHANGELOG.md +19 -0
  19. package/node_modules/@xzzpig/pi-components/README.md +28 -0
  20. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +46 -4
  21. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +65 -17
  22. package/node_modules/@xzzpig/pi-components/package.json +1 -1
  23. package/node_modules/@xzzpig/pi-components/src/transcript.ts +107 -14
  24. package/package.json +10 -5
  25. package/prompts/parallel-review.md +1 -1
  26. package/runner-peer-loader.mjs +24 -0
  27. package/runner-peer-preload.mjs +36 -0
  28. package/skills/pi-subagents/SKILL.md +34 -22
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  30. package/skills/pi-subagents/references/execution-controls.md +27 -8
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  33. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  34. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  35. package/src/agents/advertised-agent-prompt.ts +94 -0
  36. package/src/agents/agent-management.ts +71 -59
  37. package/src/agents/agent-serializer.ts +6 -3
  38. package/src/agents/agents.ts +198 -72
  39. package/src/agents/builtin-names.ts +1 -0
  40. package/src/agents/chain-serializer.ts +5 -0
  41. package/src/agents/runtime-agent-registry.ts +7 -6
  42. package/src/api/delegation.ts +4 -0
  43. package/src/api/preflight.ts +110 -71
  44. package/src/api/required-child-extensions.ts +6 -0
  45. package/src/api/shared-types.ts +3 -1
  46. package/src/api/workflow-resources.ts +6 -0
  47. package/src/extension/config.ts +14 -37
  48. package/src/extension/fanout-child.ts +68 -5
  49. package/src/extension/herdr-pi-bridge.ts +164 -0
  50. package/src/extension/index.ts +141 -51
  51. package/src/extension/public-execution.ts +7 -6
  52. package/src/extension/rpc.ts +8 -21
  53. package/src/extension/schemas.ts +86 -84
  54. package/src/extension/tool-description.ts +32 -79
  55. package/src/inspectors/actions.ts +148 -0
  56. package/src/inspectors/ghostty/actions.ts +74 -0
  57. package/src/inspectors/ghostty/plugin.ts +17 -0
  58. package/src/inspectors/herdr/actions.ts +99 -179
  59. package/src/inspectors/herdr/plugin.ts +20 -0
  60. package/src/inspectors/herdr/project-panes.ts +4 -1
  61. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  62. package/src/inspectors/plugins.ts +8 -0
  63. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  64. package/src/inspectors/types.ts +51 -0
  65. package/src/integrations/pi-web-session-liveness.ts +73 -0
  66. package/src/intercom/intercom-bridge.ts +50 -8
  67. package/src/intercom/native-supervisor-channel.ts +142 -115
  68. package/src/intercom/supervisor-ui.ts +3 -2
  69. package/src/missions/workflow-state.ts +37 -16
  70. package/src/policy/authority.ts +4 -0
  71. package/src/profiles/profiles.ts +12 -6
  72. package/src/runs/background/active-async-capacity.ts +22 -18
  73. package/src/runs/background/active-run-index.ts +17 -1
  74. package/src/runs/background/async-execution.ts +359 -176
  75. package/src/runs/background/async-job-tracker.ts +41 -7
  76. package/src/runs/background/async-resume.ts +19 -12
  77. package/src/runs/background/async-retention.ts +20 -0
  78. package/src/runs/background/async-status-snapshot.ts +10 -12
  79. package/src/runs/background/async-status.ts +32 -13
  80. package/src/runs/background/auto-drain.ts +59 -35
  81. package/src/runs/background/binary-bootstrap.ts +38 -0
  82. package/src/runs/background/chain-append.ts +1 -1
  83. package/src/runs/background/chain-root-attachment.ts +22 -33
  84. package/src/runs/background/control-channel.ts +78 -44
  85. package/src/runs/background/fleet-view.ts +30 -2
  86. package/src/runs/background/notify.ts +193 -19
  87. package/src/runs/background/owned-process-tree.ts +35 -8
  88. package/src/runs/background/process-terminal.ts +23 -23
  89. package/src/runs/background/result-files.ts +8 -4
  90. package/src/runs/background/result-watcher.ts +19 -2
  91. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  92. package/src/runs/background/run-child-session.ts +118 -41
  93. package/src/runs/background/run-status.ts +78 -5
  94. package/src/runs/background/runner-aliases.ts +22 -5
  95. package/src/runs/background/runner-child-launch.ts +93 -0
  96. package/src/runs/background/runner-child-sessions.ts +5 -4
  97. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  98. package/src/runs/background/scheduled-runs.ts +51 -18
  99. package/src/runs/background/stale-run-reconciler.ts +38 -12
  100. package/src/runs/background/steering.ts +20 -2
  101. package/src/runs/background/subagent-runner.ts +766 -432
  102. package/src/runs/background/subagent-wait.ts +179 -28
  103. package/src/runs/background/wait-completions.ts +79 -27
  104. package/src/runs/background/wait-subscriptions.ts +9 -3
  105. package/src/runs/background/wait-tool.ts +5 -3
  106. package/src/runs/foreground/async-steering-action.ts +37 -7
  107. package/src/runs/foreground/async-stop-action.ts +93 -3
  108. package/src/runs/foreground/execution.ts +174 -194
  109. package/src/runs/foreground/foreground-history.ts +5 -2
  110. package/src/runs/foreground/prompt-audit.ts +12 -6
  111. package/src/runs/foreground/subagent-executor.ts +896 -397
  112. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  113. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  114. package/src/runs/shared/acceptance.ts +54 -14
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +172 -78
  117. package/src/runs/shared/capability-ceiling.ts +2 -0
  118. package/src/runs/shared/child-hooks.ts +167 -3
  119. package/src/runs/shared/child-launch-plan.ts +15 -3
  120. package/src/runs/shared/child-launch.ts +44 -16
  121. package/src/runs/shared/child-lifecycle.ts +6 -3
  122. package/src/runs/shared/child-runtime-config.ts +8 -1
  123. package/src/runs/shared/child-session.ts +130 -24
  124. package/src/runs/shared/child-tool-plan.ts +145 -14
  125. package/src/runs/shared/completion-evidence.ts +2 -2
  126. package/src/runs/shared/completion-guard.ts +6 -3
  127. package/src/runs/shared/dynamic-fanout.ts +2 -2
  128. package/src/runs/shared/effective-system-prompt.ts +33 -0
  129. package/src/runs/shared/external-cli-contract.ts +11 -1
  130. package/src/runs/shared/external-cli-preflight.ts +6 -2
  131. package/src/runs/shared/external-cli-runner.ts +9 -7
  132. package/src/runs/shared/herdr-connection.ts +134 -0
  133. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  134. package/src/runs/shared/herdr-machine.ts +279 -0
  135. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  136. package/src/runs/shared/herdr-placed-run.ts +263 -0
  137. package/src/runs/shared/host-step-status.ts +11 -11
  138. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  139. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  140. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  141. package/src/runs/shared/model-scope.ts +1 -1
  142. package/src/runs/shared/nested-events.ts +19 -10
  143. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  144. package/src/runs/shared/parallel-handoff.ts +57 -12
  145. package/src/runs/shared/parallel-utils.ts +10 -4
  146. package/src/runs/shared/pi-spawn.ts +10 -0
  147. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  148. package/src/runs/shared/run-fanout-budget.ts +8 -8
  149. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  150. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  151. package/src/runs/shared/task-intent.ts +46 -13
  152. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  153. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  154. package/src/runs/shared/worktree-setup-command.ts +213 -0
  155. package/src/runs/shared/worktree.ts +437 -214
  156. package/src/shared/child-cache-retention.ts +43 -0
  157. package/src/shared/fork-context.ts +15 -72
  158. package/src/shared/launch-contract.ts +70 -8
  159. package/src/shared/model-response-aliases.ts +13 -0
  160. package/src/shared/opencode-session-headers.ts +30 -0
  161. package/src/shared/pruned-fork.ts +1 -1
  162. package/src/shared/required-child-extensions.ts +81 -0
  163. package/src/shared/settings.ts +5 -2
  164. package/src/shared/shortcuts.ts +0 -4
  165. package/src/shared/types.ts +164 -90
  166. package/src/shared/utils.ts +10 -2
  167. package/src/shared/watch-strategy.ts +2 -0
  168. package/src/shared/workflow-child-permit.ts +18 -13
  169. package/src/slash/delegation-adapters.ts +3 -1
  170. package/src/slash/delegation-request.ts +14 -0
  171. package/src/slash/slash-commands.ts +2 -7
  172. package/src/slash/subagents-admin.ts +31 -14
  173. package/src/tui/fleet-native-transcript.ts +50 -6
  174. package/src/tui/fleet-status.ts +165 -20
  175. package/src/tui/fleet.ts +52 -21
  176. package/src/tui/render.ts +210 -50
  177. package/src/watchdog/child-status.ts +28 -28
  178. package/src/watchdog/lsp-diagnostics.ts +1 -1
  179. package/src/watchdog/model-selection.ts +21 -1
  180. package/src/watchdog/permission-arbiter.ts +5 -2
  181. package/src/watchdog/register-child.ts +10 -2
  182. package/src/watchdog/register-main.ts +39 -35
  183. package/src/watchdog/render.ts +1 -1
  184. package/src/watchdog/review.ts +122 -74
  185. package/src/watchdog/rules.ts +1 -1
  186. package/src/watchdog/runtime.ts +100 -27
  187. package/src/watchdog/scope.ts +1 -1
  188. package/src/watchdog/settings.ts +3 -0
  189. package/src/watchdog/tool-actions.ts +13 -12
  190. package/src/watchdog/turn-delta.ts +23 -0
  191. package/src/watchdog/types.ts +5 -3
  192. package/src/watchdog/warning-format.ts +1 -1
  193. package/src/workflows/chat-progress.ts +3 -3
  194. package/src/workflows/scripted-workflow.ts +349 -26
  195. package/src/workflows/workflow-checklist.ts +17 -20
  196. package/src/workflows/workflow-child-summary.ts +57 -8
  197. package/src/workflows/workflow-preflight.ts +19 -19
  198. package/src/workflows/workflow-receipt.ts +24 -6
  199. package/src/workflows/workflow-resources.ts +108 -22
  200. package/src/workflows/workflow-settlement.ts +3 -0
  201. package/src/runs/shared/model-exclusions.ts +0 -373
  202. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -1,14 +1,16 @@
1
- import { readFileSync } from "node:fs";
1
+ import { accessSync, constants, readFileSync, realpathSync, statSync } 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
5
  import { DEFAULT_GLOBAL_CONCURRENCY_LIMIT, Semaphore } from "../runs/shared/parallel-utils.ts";
6
6
  import { HOST_STEP_MAX_COUNT } from "../runs/shared/host-step-status.ts";
7
7
  import { classifyTaskMutationIntent } from "../runs/shared/task-intent.ts";
8
- import type { AcceptanceRecoveryMetadata, HostStepNodeV1, SingleResult } from "../shared/types.ts";
8
+ import { describeGateAcceptanceConflict } from "../runs/shared/acceptance.ts";
9
+ import type { AcceptanceRecoveryMetadata, HostStepNode, SingleResult } from "../shared/types.ts";
9
10
  import { normalizeWorkflowHostCommandParams, type WorkflowHostCommandParams, type WorkflowHostCommandResult } from "./host-command.ts";
10
11
 
11
12
  const KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
13
+ const BASE_REF_VALIDATION_ERROR = "baseRef must be a valid Git ref: use HEAD or a supported named ref (for example, refs/heads/main). Full 40/64-character commit IDs and revision expressions are unsupported.";
12
14
  function validGitRef(ref: unknown): ref is string {
13
15
  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
16
  if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/iu.test(ref)) return false;
@@ -22,11 +24,22 @@ export interface WorkflowScriptValidationError {
22
24
  message: string;
23
25
  line?: number;
24
26
  column?: number;
27
+ kind?: "spawn-budget";
28
+ }
29
+
30
+ export interface WorkflowScriptValidationWarning {
31
+ message: string;
32
+ kind: "dynamic-spawn-count";
25
33
  }
26
34
 
27
35
  export interface WorkflowScriptValidationResult {
28
36
  ok: boolean;
29
37
  errors: WorkflowScriptValidationError[];
38
+ warnings?: WorkflowScriptValidationWarning[];
39
+ }
40
+
41
+ export interface WorkflowScriptValidationOptions {
42
+ maxSubagentSpawnsPerRun?: number;
30
43
  }
31
44
 
32
45
  const WORKER_SOURCE = String.raw`
@@ -74,6 +87,12 @@ function stableRunJson(value) {
74
87
  return JSON.stringify(value) ?? "undefined";
75
88
  }
76
89
 
90
+ function canonicalRunParams(params) {
91
+ if (params.gate === undefined || params.acceptance !== false) return params;
92
+ const { acceptance: _acceptance, ...withoutAcceptance } = params;
93
+ return withoutAcceptance;
94
+ }
95
+
77
96
  function isDirectWorkflowScriptPromiseHandlerCall() {
78
97
  const stack = new Error().stack;
79
98
  if (typeof stack !== "string") return false;
@@ -445,7 +464,7 @@ function validateLaneSpecs(laneSpecs) {
445
464
  validateLaneStageBounds(validationParams, stageLabel);
446
465
  validateRunCall(generatedKey, validationParams, stageLabel, validationFingerprints);
447
466
  const existingFingerprint = runFingerprints.get(generatedKey);
448
- if (existingFingerprint !== undefined && (resume === "previous" || existingFingerprint !== stableRunJson(params))) {
467
+ if (existingFingerprint !== undefined && (resume === "previous" || existingFingerprint !== stableRunJson(canonicalRunParams(params)))) {
449
468
  throw new Error("runs.lanes generated child key '" + generatedKey + "' is already used with incompatible launch params.");
450
469
  }
451
470
  stages.push({ key: stageKey, generatedKey, resume, params });
@@ -531,7 +550,7 @@ function runLanes(laneSpecs) {
531
550
  generatedKey: stage.generatedKey,
532
551
  ...workflowPlanStringMetadata(stage.params),
533
552
  ...(typeof stage.params.as === "string" && stage.params.as.trim() ? { outputName: stage.params.as.trim() } : {}),
534
- ...(stage.params.outputSchema !== undefined ? { structured: true } : {}),
553
+ ...(stage.params.outputSchema ? { structured: true } : {}),
535
554
  })),
536
555
  })) });
537
556
  const firstItems = lanes.map((lane) => {
@@ -614,6 +633,19 @@ function validateLaneMetadata(value, label, workflowKey) {
614
633
  }
615
634
  }
616
635
 
636
+ function describeGateAcceptanceConflict(gate, acceptance) {
637
+ const render = (value) => {
638
+ let encoded;
639
+ try {
640
+ encoded = JSON.stringify(value) ?? String(value);
641
+ } catch {
642
+ encoded = String(value);
643
+ }
644
+ return encoded.length > 120 ? encoded.slice(0, 120) + "..." : encoded;
645
+ };
646
+ return " Both fields were present: gate=" + render(gate) + " acceptance=" + render(acceptance) + ".";
647
+ }
648
+
617
649
  function validateRunCall(key, params, label, fingerprints) {
618
650
  if (typeof key !== "string" || !runKeyPattern.test(key)) throw new Error(label + " has an invalid key.");
619
651
  if (hostKeys.has(key)) throw new Error("Workflow key '" + key + "' is already used by runs.host.");
@@ -624,10 +656,10 @@ function validateRunCall(key, params, label, fingerprints) {
624
656
  }
625
657
  if (Object.prototype.hasOwnProperty.call(params, "clarify")) throw new Error(label + " does not support clarify UI.");
626
658
  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.");
659
+ if (params.baseRef !== undefined && (typeof params.baseRef !== "string" || !validGitRef(params.baseRef))) throw new Error(label + " baseRef must be a valid Git ref: use HEAD or a supported named ref (for example, refs/heads/main). Full 40/64-character commit IDs and revision expressions are unsupported.");
628
660
  validateLaneMetadata(params.lane, label + " lane", key);
629
661
  if (params.gate !== undefined && (typeof params.gate !== "string" || !params.gate.trim())) throw new Error(label + " gate must be a non-empty command string.");
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.");
662
+ if (params.gate !== undefined && params.acceptance !== undefined && params.acceptance !== false) throw new Error(label + " gate cannot be combined with acceptance; use one gate command or acceptance.verify." + describeGateAcceptanceConflict(params.gate, params.acceptance));
631
663
  if (params.gate !== undefined && params.resume !== undefined) throw new Error(label + " gate is not supported with retained resume.");
632
664
  if (params.extensionBindings !== undefined && params.resume !== undefined) throw new Error(label + " extensionBindings is not supported with retained resume; resume uses the original retained child binding.");
633
665
  if (params.resume !== undefined && typeof params.resume !== "string") {
@@ -644,7 +676,7 @@ function validateRunCall(key, params, label, fingerprints) {
644
676
  if (params.resume !== undefined && (typeof params.task !== "string" || !params.task.trim())) throw new Error(label + " resume requires a non-empty task follow-up.");
645
677
  validateExtensionBindings(params.extensionBindings, label);
646
678
  assertJsonValue(params, label + " params");
647
- const fingerprint = stableRunJson(params);
679
+ const fingerprint = stableRunJson(canonicalRunParams(params));
648
680
  const existing = fingerprints.get(key);
649
681
  if (existing !== undefined && existing !== fingerprint) throw new Error("Duplicate workflow key '" + key + "' used with incompatible launch params.");
650
682
  fingerprints.set(key, fingerprint);
@@ -675,8 +707,26 @@ function validateHostCommand(key, params) {
675
707
  hostKeys.add(key);
676
708
  }
677
709
 
710
+ const RUNS_ALL_PERMISSIVE_WARNING = "runs.all received runs.run(...) launch promise(s) or thenable(s). Those children were already launched individually, so runs.all cannot apply batch fingerprint validation, batch grouping in the fleet view, or collectFailure semantics; a failed child will throw at the runs.all boundary instead of returning as { ok: false }. To get full runs.all semantics, pass config objects: runs.all(items.map((item) => ({ key: item.key, agent: item.agent, task: item.task }))).";
711
+
712
+ function runsAllItemThenableInfo(item, index) {
713
+ if (!item || typeof item !== "object" || Array.isArray(item)) return null;
714
+ if (typeof item.then !== "function") return null;
715
+ const tracker = promiseObservationTracker(item);
716
+ const observation = tracker && Array.isArray(tracker.observations) ? tracker.observations.find((entry) => entry && entry.operation === "run") : undefined;
717
+ return {
718
+ key: observation && typeof observation.key === "string" ? observation.key : ("runs.all[" + index + "]"),
719
+ callId: observation && typeof observation.callId === "number" ? observation.callId : null,
720
+ promise: item,
721
+ };
722
+ }
723
+
724
+ let warnedPermissiveRunsAll = false;
725
+
678
726
  function launchRunsAll(items, generatedLaneKeys) {
679
727
  if (!Array.isArray(items)) throw new Error("runs.all(items) requires an array.");
728
+ const anyThenable = items.some((item, index) => runsAllItemThenableInfo(item, index) !== null);
729
+ if (anyThenable) return launchRunsAllPermissive(items);
680
730
  const fingerprints = new Map(runFingerprints);
681
731
  const calls = [];
682
732
  for (let index = 0; index < items.length; index++) {
@@ -693,6 +743,33 @@ function launchRunsAll(items, generatedLaneKeys) {
693
743
  return { calls, launched };
694
744
  }
695
745
 
746
+ function launchRunsAllPermissive(items) {
747
+ if (!warnedPermissiveRunsAll) {
748
+ warnedPermissiveRunsAll = true;
749
+ try { capturedConsole.warn(RUNS_ALL_PERMISSIVE_WARNING); } catch { /* console emission is best-effort */ }
750
+ }
751
+ const fingerprints = new Map(runFingerprints);
752
+ const calls = [];
753
+ const launched = [];
754
+ for (let index = 0; index < items.length; index++) {
755
+ if (!Object.prototype.hasOwnProperty.call(items, index)) throw new Error("runs.all items must not contain sparse entries.");
756
+ const item = items[index];
757
+ if (!item || typeof item !== "object" || Array.isArray(item)) throw new Error("runs.all item " + index + " must be an object or a runs.run(...) launch promise.");
758
+ const thenable = runsAllItemThenableInfo(item, index);
759
+ if (thenable) {
760
+ calls.push({ key: thenable.key, params: {} });
761
+ launched.push(thenable);
762
+ continue;
763
+ }
764
+ const { key, ...params } = item;
765
+ validateRunCall(key, params, "runs.all item " + index, fingerprints);
766
+ calls.push({ key, params });
767
+ launched.push(null);
768
+ }
769
+ runFingerprints = fingerprints;
770
+ return { calls, launched: launched.map((entry, index) => entry ?? runHostCall(calls[index].key, calls[index].params, false, undefined)) };
771
+ }
772
+
696
773
  const runs = Object.freeze({
697
774
  run(key, params) {
698
775
  validateRunCall(key, params, "runs.run", runFingerprints);
@@ -701,7 +778,7 @@ const runs = Object.freeze({
701
778
  },
702
779
  all(items) {
703
780
  const { calls, launched } = launchRunsAll(items);
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))));
781
+ return trackRunObservation(launched.map(({ key, callId }) => ({ key, operation: "run", callId })), trackPromiseCombinator(launched.map(({ promise }) => promise), (values) => Promise.all(values).then((results) => wrapRunsAllResults(results.map(decorateWorkflowChildResult), calls.map(({ key }) => key)))));
705
782
  },
706
783
  lanes(laneSpecs) {
707
784
  return runLanes(laneSpecs);
@@ -875,6 +952,12 @@ function omitUndefinedWorkflowValues(value, seen = new Set()) {
875
952
  return normalized;
876
953
  }
877
954
 
955
+ function deepFreezeWorkflowArgs(value) {
956
+ if (value === null || typeof value !== "object" || Object.isFrozen(value)) return value;
957
+ for (const entry of Object.values(value)) deepFreezeWorkflowArgs(entry);
958
+ return Object.freeze(value);
959
+ }
960
+
878
961
  parentPort.on("message", async (message) => {
879
962
  if (message.type === "response") {
880
963
  const entry = pending.get(message.callId);
@@ -894,6 +977,9 @@ parentPort.on("message", async (message) => {
894
977
  if (message.stateEnabled) sandbox.state = state;
895
978
  const context = vm.createContext(sandbox, { codeGeneration: { strings: false, wasm: false } });
896
979
  contextObjectPrototype = vm.runInContext("Object.prototype", context);
980
+ // Rebuild args inside the VM realm: a worker-realm object would expose the worker's unrestricted
981
+ // Function through args.constructor.constructor, bypassing codeGeneration.strings: false.
982
+ sandbox.args = deepFreezeWorkflowArgs(vm.runInContext("JSON.parse", context)(JSON.stringify(message.args ?? {})));
897
983
  let compiled;
898
984
  try {
899
985
  assertPortableWorkflowScript(message.script);
@@ -1078,8 +1164,26 @@ export class WorkflowScriptError extends Error {
1078
1164
  }
1079
1165
  }
1080
1166
 
1167
+ export type WorkflowChildSettledOutcome = "completed" | "failed" | "paused" | "stopped";
1168
+
1169
+ export interface WorkflowChildSettledNotification {
1170
+ workflowRunId: string;
1171
+ childKey: string;
1172
+ childRunId?: string;
1173
+ outcome: WorkflowChildSettledOutcome;
1174
+ outputReference?: string;
1175
+ error?: string;
1176
+ workflowRunning: boolean;
1177
+ }
1178
+
1081
1179
  export interface RunWorkflowScriptOptions {
1082
1180
  script: string;
1181
+ /** Normalized raw-script input exposed as the deeply frozen sandbox global `args`. */
1182
+ args?: Readonly<Record<string, unknown>>;
1183
+ /** Parent-session cwd used to recover a stale process cwd. */
1184
+ processCwd?: string;
1185
+ /** Workflow run ID for notifications. Required when onChildSettled is provided. */
1186
+ workflowRunId?: string;
1083
1187
  /** Host-only first-slice admission context. It is never sent to the workflow worker. */
1084
1188
  oneUsePermit?: { claim: (key: string) => string | undefined };
1085
1189
  timeoutMs?: number;
@@ -1088,13 +1192,13 @@ export interface RunWorkflowScriptOptions {
1088
1192
  continueAfterAbortWhenChildrenSettled?: (abortError: Error) => boolean;
1089
1193
  /** Maximum children executing concurrently within this workflow. Defaults to 20. */
1090
1194
  globalConcurrencyLimit?: number;
1091
- admit?: (calls: Array<{ key: string; params: Record<string, unknown> }>) => void | Promise<void>;
1195
+ admit?: (calls: Array<{ key: string; params: Record<string, unknown> }>, signal: AbortSignal) => void | Promise<void>;
1092
1196
  launch: (key: string, params: Record<string, unknown>, signal: AbortSignal, admission: { admitted: boolean; batch: boolean }) => Promise<WorkflowScriptChildResult>;
1093
- resolveResume?: (reference: WorkflowReceiptResumeReference, signal: AbortSignal) => string | WorkflowResolvedResumeReference | Promise<string | WorkflowResolvedResumeReference>;
1197
+ resolveResume?: (reference: WorkflowReceiptResumeReference | string, signal: AbortSignal, index?: number) => string | WorkflowResolvedResumeReference | Promise<string | WorkflowResolvedResumeReference>;
1094
1198
  status: (keyOrRunId: string, signal: AbortSignal) => Promise<WorkflowScriptChildResult>;
1095
1199
  steer?: (key: string, message: string, options: WorkflowSteerOptions, signal: AbortSignal) => Promise<WorkflowSteerResult>;
1096
1200
  host?: (key: string, params: WorkflowHostCommandParams, signal: AbortSignal) => Promise<WorkflowHostCommandResult>;
1097
- onHostStep?: (hostStep: HostStepNodeV1) => void;
1201
+ onHostStep?: (hostStep: HostStepNode) => void;
1098
1202
  state?: {
1099
1203
  get: (key: string) => unknown | Promise<unknown>;
1100
1204
  set: (key: string, value: unknown) => void | Promise<void>;
@@ -1103,6 +1207,7 @@ export interface RunWorkflowScriptOptions {
1103
1207
  onTrace?: (trace: WorkflowScriptTraceEntry[]) => void;
1104
1208
  onLanePlan?: (lanes: WorkflowLanePlan[]) => void;
1105
1209
  onEmit?: (emits: unknown[]) => void;
1210
+ onChildSettled?: (notification: WorkflowChildSettledNotification) => void;
1106
1211
  }
1107
1212
 
1108
1213
  function combinedAbortSignal(signals: AbortSignal[]): AbortSignal {
@@ -1370,6 +1475,12 @@ function stableJson(value: unknown): string {
1370
1475
  return JSON.stringify(value) ?? "undefined";
1371
1476
  }
1372
1477
 
1478
+ function canonicalRunParams(params: Record<string, unknown>): Record<string, unknown> {
1479
+ if (params.gate === undefined || params.acceptance !== false) return params;
1480
+ const { acceptance: _acceptance, ...withoutAcceptance } = params;
1481
+ return withoutAcceptance;
1482
+ }
1483
+
1373
1484
  function validateKey(value: unknown, owner = "runs.run"): string {
1374
1485
  if (typeof value !== "string" || !KEY_PATTERN.test(value)) {
1375
1486
  throw new Error(`${owner} key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.`);
@@ -1399,7 +1510,7 @@ function literalString(node: unknown): string | undefined {
1399
1510
  return undefined;
1400
1511
  }
1401
1512
 
1402
- function directRunsCall(node: unknown, method: "run" | "all" | "host"): node is AstNode {
1513
+ function directRunsCall(node: unknown, method: "run" | "all" | "host" | "lanes"): boolean {
1403
1514
  if (!astNode(node) || node.type !== "CallExpression" || !astNode(node.callee) || node.callee.type !== "MemberExpression") return false;
1404
1515
  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
1516
  return property === method && astNode(node.callee.object) && node.callee.object.type === "Identifier" && node.callee.object.name === "runs";
@@ -1476,7 +1587,7 @@ function definitelyNonJson(node: AstNode, normalizeUndefined = false): string |
1476
1587
  if (node.type === "ObjectExpression" && Array.isArray(node.properties)) {
1477
1588
  const values = new Map<string, AstNode>();
1478
1589
  for (const property of node.properties) {
1479
- if (!astNode(property) || property.type !== "Property" || !astNode(property.value)) return undefined;
1590
+ if (!astNode(property) || property.type !== "Property" || !astNode(property.value) || property.kind !== "init") return undefined;
1480
1591
  const key = staticPropertyKey(property);
1481
1592
  if (key === undefined) return undefined;
1482
1593
  values.set(key, property.value);
@@ -1505,6 +1616,26 @@ function directObjectPropertyValue(node: AstNode, name: string): AstNode | undef
1505
1616
  return value;
1506
1617
  }
1507
1618
 
1619
+ function validateStaticBaseRef(params: AstNode, owner: string): WorkflowScriptValidationError[] {
1620
+ if (params.type !== "ObjectExpression" || !Array.isArray(params.properties)) return [];
1621
+ // Inspect the final definition only. A later spread or unknown key may overwrite it.
1622
+ for (let index = params.properties.length - 1; index >= 0; index--) {
1623
+ const property = params.properties[index];
1624
+ if (!astNode(property) || property.type !== "Property") return [];
1625
+ const key = staticPropertyKey(property);
1626
+ if (key === undefined) return [];
1627
+ if (key !== "baseRef") continue;
1628
+ if (property.kind !== "init" || !astNode(property.value)) return [];
1629
+ const valueNode = property.value;
1630
+ const value = literalString(valueNode);
1631
+ if ((value !== undefined || valueNode.type === "Literal") && !validGitRef(value)) {
1632
+ return [{ message: `${owner} ${BASE_REF_VALIDATION_ERROR}`, ...nodeLocation(valueNode) }];
1633
+ }
1634
+ return [];
1635
+ }
1636
+ return [];
1637
+ }
1638
+
1508
1639
  function directRunsAllKeys(call: AstNode): Array<{ key: string; node: AstNode }> {
1509
1640
  const args = Array.isArray(call.arguments) ? call.arguments : [];
1510
1641
  const items = astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements) ? args[0].elements : [];
@@ -1516,8 +1647,121 @@ function directRunsAllKeys(call: AstNode): Array<{ key: string; node: AstNode }>
1516
1647
  });
1517
1648
  }
1518
1649
 
1650
+ function containsWorkflowLaunch(node: unknown): boolean {
1651
+ let found = false;
1652
+ walkAst(node, (candidate) => {
1653
+ if (directRunsCall(candidate, "run") || directRunsCall(candidate, "all") || directRunsCall(candidate, "lanes")) found = true;
1654
+ });
1655
+ return found;
1656
+ }
1657
+
1658
+ function containsRunsIdentifier(node: unknown): boolean {
1659
+ let found = false;
1660
+ walkAst(node, (candidate) => {
1661
+ if (candidate.type === "Identifier" && candidate.name === "runs") found = true;
1662
+ });
1663
+ return found;
1664
+ }
1665
+
1666
+ function invalidatesRunsBinding(workflowBody: AstNode): boolean {
1667
+ let invalidated = false;
1668
+ walkAst(workflowBody, (node) => {
1669
+ if ((node.type === "VariableDeclarator" || node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ClassDeclaration" || node.type === "ClassExpression")
1670
+ && containsRunsIdentifier(node.id)) invalidated = true;
1671
+ if ((node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") && Array.isArray(node.params)
1672
+ && node.params.some(containsRunsIdentifier)) invalidated = true;
1673
+ if (node.type === "CatchClause" && containsRunsIdentifier(node.param)) invalidated = true;
1674
+ if ((node.type === "AssignmentExpression" || node.type === "UpdateExpression") && containsRunsIdentifier(node.left ?? node.argument)) invalidated = true;
1675
+ });
1676
+ return invalidated;
1677
+ }
1678
+
1679
+ function containsAbruptControl(node: AstNode): boolean {
1680
+ let found = false;
1681
+ walkAst(node, (candidate) => {
1682
+ if (candidate !== node && (candidate.type === "ReturnStatement" || candidate.type === "ThrowStatement" || candidate.type === "BreakStatement" || candidate.type === "ContinueStatement")) found = true;
1683
+ }, false);
1684
+ return found;
1685
+ }
1686
+
1687
+ function directLaunchCall(expression: unknown): AstNode | undefined {
1688
+ if (!astNode(expression)) return undefined;
1689
+ const candidate = expression.type === "AwaitExpression" && astNode(expression.argument) ? expression.argument : expression;
1690
+ return directRunsCall(candidate, "run") || directRunsCall(candidate, "all") ? candidate : undefined;
1691
+ }
1692
+
1693
+ function staticWorkflowLaunchPlan(workflowBody: AstNode): { keys: string[]; dynamic: boolean } {
1694
+ if (workflowBody.type !== "BlockStatement" || !Array.isArray(workflowBody.body) || invalidatesRunsBinding(workflowBody)) {
1695
+ return { keys: [], dynamic: containsWorkflowLaunch(workflowBody) };
1696
+ }
1697
+ const keys = new Set<string>();
1698
+ let dynamic = false;
1699
+ let remainderUncertain = false;
1700
+ const addCall = (call: AstNode): void => {
1701
+ const args = Array.isArray(call.arguments) ? call.arguments : [];
1702
+ let nestedLaunch = false;
1703
+ for (const argument of args) walkAst(argument, (node) => {
1704
+ if (node !== call && (directRunsCall(node, "run") || directRunsCall(node, "all") || directRunsCall(node, "lanes"))) nestedLaunch = true;
1705
+ });
1706
+ if (nestedLaunch) {
1707
+ dynamic = true;
1708
+ return;
1709
+ }
1710
+ if (directRunsCall(call, "run")) {
1711
+ const key = literalString(args[0]);
1712
+ if (key === undefined) dynamic = true;
1713
+ else keys.add(key);
1714
+ return;
1715
+ }
1716
+ const array = astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements) ? args[0] : undefined;
1717
+ if (!array) {
1718
+ dynamic = true;
1719
+ return;
1720
+ }
1721
+ const batchKeys: string[] = [];
1722
+ for (const item of array.elements as unknown[]) {
1723
+ if (!astNode(item) || item.type !== "ObjectExpression" || !Array.isArray(item.properties)
1724
+ || item.properties.some((property) => !astNode(property) || property.type !== "Property" || staticPropertyKey(property) === undefined)) {
1725
+ dynamic = true;
1726
+ return;
1727
+ }
1728
+ const key = literalString(directObjectPropertyValue(item, "key"));
1729
+ if (key === undefined) {
1730
+ dynamic = true;
1731
+ return;
1732
+ }
1733
+ batchKeys.push(key);
1734
+ }
1735
+ for (const key of batchKeys) keys.add(key);
1736
+ };
1737
+ for (const statement of workflowBody.body) {
1738
+ if (!astNode(statement)) continue;
1739
+ if (remainderUncertain) {
1740
+ if (containsWorkflowLaunch(statement)) dynamic = true;
1741
+ continue;
1742
+ }
1743
+ const expressions: unknown[] = [];
1744
+ if (statement.type === "VariableDeclaration" && Array.isArray(statement.declarations)) {
1745
+ for (const declaration of statement.declarations) if (astNode(declaration)) expressions.push(declaration.init);
1746
+ } else if (statement.type === "ExpressionStatement") expressions.push(statement.expression);
1747
+ else if (statement.type === "ReturnStatement" || statement.type === "ThrowStatement") expressions.push(statement.argument);
1748
+ let handledLaunch = false;
1749
+ for (const expression of expressions) {
1750
+ const call = directLaunchCall(expression);
1751
+ if (call) {
1752
+ addCall(call);
1753
+ handledLaunch = true;
1754
+ } else if (containsWorkflowLaunch(expression)) dynamic = true;
1755
+ }
1756
+ if (!handledLaunch && expressions.length === 0 && containsWorkflowLaunch(statement)) dynamic = true;
1757
+ if (statement.type === "ReturnStatement" || statement.type === "ThrowStatement") remainderUncertain = true;
1758
+ else if (containsAbruptControl(statement)) remainderUncertain = true;
1759
+ }
1760
+ return { keys: [...keys], dynamic };
1761
+ }
1762
+
1519
1763
  /** Parse a workflowScript and apply only rules that are decidable from its local syntax. */
1520
- export function validateWorkflowScript(script: string): WorkflowScriptValidationResult {
1764
+ export function validateWorkflowScript(script: string, options: WorkflowScriptValidationOptions = {}): WorkflowScriptValidationResult {
1521
1765
  const errors: WorkflowScriptValidationError[] = [];
1522
1766
  if (!script.trim()) return { ok: false, errors: [{ message: "workflowScript must not be empty." }] };
1523
1767
  let root: AstNode;
@@ -1546,6 +1790,7 @@ export function validateWorkflowScript(script: string): WorkflowScriptValidation
1546
1790
  const key = literalString(keyNode);
1547
1791
  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
1792
  if (astNode(args[1])) {
1793
+ errors.push(...validateStaticBaseRef(args[1], "runs.run"));
1549
1794
  const message = definitelyNonJson(args[1]);
1550
1795
  if (message) errors.push({ message: `runs.run params are invalid: ${message}.`, ...nodeLocation(args[1]) });
1551
1796
  }
@@ -1555,6 +1800,7 @@ export function validateWorkflowScript(script: string): WorkflowScriptValidation
1555
1800
  const args = Array.isArray(node.arguments) ? node.arguments : [];
1556
1801
  if (astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements)) {
1557
1802
  for (const item of args[0].elements) if (astNode(item)) {
1803
+ errors.push(...validateStaticBaseRef(item, "runs.all item"));
1558
1804
  const message = definitelyNonJson(item);
1559
1805
  if (message) errors.push({ message: `runs.all item params are invalid: ${message}.`, ...nodeLocation(item) });
1560
1806
  }
@@ -1582,7 +1828,7 @@ export function validateWorkflowScript(script: string): WorkflowScriptValidation
1582
1828
  const statement = workflowBody.body[statementIndex];
1583
1829
  if (!astNode(statement) || statement.type !== "VariableDeclaration" || !Array.isArray(statement.declarations)) continue;
1584
1830
  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;
1831
+ if (!astNode(declaration) || !astNode(declaration.id) || declaration.id.type !== "Identifier" || !astNode(declaration.init) || declaration.init.type !== "AwaitExpression" || !astNode(declaration.init.argument) || !directRunsCall(declaration.init.argument, "all")) continue;
1586
1832
  const name = declaration.id.name as string;
1587
1833
  const keys = new Set(directRunsAllKeys(declaration.init.argument).map((entry) => entry.key));
1588
1834
  if (keys.size === 0) continue;
@@ -1598,8 +1844,24 @@ export function validateWorkflowScript(script: string): WorkflowScriptValidation
1598
1844
  }
1599
1845
  }
1600
1846
 
1847
+ const warnings: WorkflowScriptValidationWarning[] = [];
1848
+ if (options.maxSubagentSpawnsPerRun !== undefined) {
1849
+ const plan = staticWorkflowLaunchPlan(workflowBody);
1850
+ if (plan.keys.length > options.maxSubagentSpawnsPerRun) {
1851
+ errors.push({
1852
+ kind: "spawn-budget",
1853
+ message: `workflowScript statically requires child launches ${plan.keys.map((key) => `'${key}'`).join(", ")}; minimum required: ${plan.keys.length}; configured: ${options.maxSubagentSpawnsPerRun}.`,
1854
+ });
1855
+ }
1856
+ if (plan.dynamic) {
1857
+ warnings.push({
1858
+ kind: "dynamic-spawn-count",
1859
+ message: `workflowScript contains dynamic child launches; static validation proved ${plan.keys.length} launch(es), so runtime fan-out enforcement remains authoritative for the configured budget of ${options.maxSubagentSpawnsPerRun}.`,
1860
+ });
1861
+ }
1862
+ }
1601
1863
  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 };
1864
+ return { ok: unique.length === 0, errors: unique, ...(warnings.length > 0 ? { warnings } : {}) };
1603
1865
  }
1604
1866
  function workflowStringMetadata(params: Record<string, unknown>): Pick<WorkflowScriptTraceEntry, "phase" | "label" | "agent"> {
1605
1867
  return {
@@ -1673,6 +1935,32 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1673
1935
  }
1674
1936
  const launchSemaphore = new Semaphore(options.globalConcurrencyLimit ?? DEFAULT_GLOBAL_CONCURRENCY_LIMIT);
1675
1937
 
1938
+ if (options.processCwd !== undefined) {
1939
+ let staleCwd = false;
1940
+ try {
1941
+ realpathSync(process.cwd());
1942
+ } catch (error) {
1943
+ const code = typeof error === "object" && error !== null && "code" in error ? (error as NodeJS.ErrnoException).code : undefined;
1944
+ if (code !== "ENOENT") throw new Error("Workflow current cwd could not be validated.", { cause: error });
1945
+ staleCwd = true;
1946
+ }
1947
+ try {
1948
+ if (staleCwd) process.chdir(options.processCwd);
1949
+ else {
1950
+ const target = realpathSync(options.processCwd);
1951
+ if (!statSync(target).isDirectory()) {
1952
+ const error = new Error(`ENOTDIR: not a directory, access '${target}'`) as NodeJS.ErrnoException;
1953
+ error.code = "ENOTDIR";
1954
+ throw error;
1955
+ }
1956
+ accessSync(target, constants.X_OK);
1957
+ }
1958
+ } catch (error) {
1959
+ const detail = error instanceof Error ? error.message : String(error);
1960
+ throw new Error(`Workflow process cwd is unavailable: ${options.processCwd}: ${detail}`, { cause: error });
1961
+ }
1962
+ }
1963
+
1676
1964
  let acornPath: string;
1677
1965
  try {
1678
1966
  acornPath = resolveWorkflowParserEntry();
@@ -1725,7 +2013,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1725
2013
  console.error("Workflow onLanePlan callback failed:", error);
1726
2014
  }
1727
2015
  };
1728
- const hostStepChanged = (hostStep: HostStepNodeV1) => {
2016
+ const hostStepChanged = (hostStep: HostStepNode) => {
1729
2017
  try {
1730
2018
  options.onHostStep?.(hostStep);
1731
2019
  } catch (error) {
@@ -1763,6 +2051,30 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
1763
2051
  traceChanged();
1764
2052
  return true;
1765
2053
  };
2054
+ const notifyChildSettled = (key: string, result: WorkflowScriptChildResult): void => {
2055
+ if (!options.onChildSettled || !options.workflowRunId) return;
2056
+ const outcome: WorkflowChildSettledOutcome = result.ok
2057
+ ? "completed"
2058
+ : result.stopped
2059
+ ? "stopped"
2060
+ : result.detached
2061
+ ? "paused"
2062
+ : "failed";
2063
+ const outputReference = result.outputReference ?? result.artifactPaths[0];
2064
+ try {
2065
+ options.onChildSettled({
2066
+ workflowRunId: options.workflowRunId,
2067
+ childKey: key,
2068
+ ...(result.runId ? { childRunId: result.runId } : {}),
2069
+ outcome,
2070
+ ...(outputReference ? { outputReference } : {}),
2071
+ ...(!result.ok && result.error ? { error: result.error } : {}),
2072
+ workflowRunning: !settled && !finishing,
2073
+ });
2074
+ } catch (error) {
2075
+ console.error("Workflow onChildSettled callback failed:", error);
2076
+ }
2077
+ };
1766
2078
  options.registerStopChild?.(stopChild);
1767
2079
 
1768
2080
  return await new Promise<WorkflowScriptResult>((resolve, reject) => {
@@ -2021,7 +2333,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2021
2333
  if (!options.host) return respond(Promise.reject(new Error("runs.host is unavailable in this host context.")));
2022
2334
  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
2335
  const startedAt = Date.now();
2024
- const startedStep: HostStepNodeV1 = {
2336
+ const startedStep: HostStepNode = {
2025
2337
  version: 1,
2026
2338
  kind: "host-step",
2027
2339
  monitorKind: "command",
@@ -2082,7 +2394,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2082
2394
  }
2083
2395
  return result;
2084
2396
  });
2085
- const fingerprint = stableJson(params);
2397
+ const fingerprint = stableJson(canonicalRunParams(params));
2086
2398
  const existing = launches.get(key);
2087
2399
  if (existing) {
2088
2400
  if (existing.fingerprint !== fingerprint) return respond(Promise.reject(new Error(`Duplicate workflow key '${key}' used with incompatible launch params.`)));
@@ -2104,13 +2416,13 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2104
2416
  return respond(Promise.reject(new Error(`runs.run('${key}') worktree must be true or false.`)));
2105
2417
  }
2106
2418
  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.`)));
2419
+ return respond(Promise.reject(new Error(`runs.run('${key}') ${BASE_REF_VALIDATION_ERROR}`)));
2108
2420
  }
2109
2421
  if (params.gate !== undefined && (typeof params.gate !== "string" || !params.gate.trim())) {
2110
2422
  return respond(Promise.reject(new Error(`runs.run('${key}') gate must be a non-empty command string.`)));
2111
2423
  }
2112
- if (params.gate !== undefined && params.acceptance !== undefined) {
2113
- return respond(Promise.reject(new Error(`runs.run('${key}') gate cannot be combined with acceptance; use one gate command or acceptance.verify.`)));
2424
+ if (params.gate !== undefined && params.acceptance !== undefined && params.acceptance !== false) {
2425
+ return respond(Promise.reject(new Error(`runs.run('${key}') gate cannot be combined with acceptance; use one gate command or acceptance.verify.` + describeGateAcceptanceConflict(params.gate, params.acceptance))));
2114
2426
  }
2115
2427
  if (params.gate !== undefined && params.resume !== undefined) {
2116
2428
  return respond(Promise.reject(new Error(`runs.run('${key}') gate is not supported with retained resume.`)));
@@ -2143,7 +2455,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2143
2455
  admission = Promise.resolve().then(() => {
2144
2456
  if (settled || finishing) return;
2145
2457
  for (const call of calls) assertRecoveryBarrierAllowsRun(call.key, call.params);
2146
- return options.admit?.(calls);
2458
+ return options.admit?.(calls, childController.signal);
2147
2459
  });
2148
2460
  if (batch) batchAdmissions.set(batch.id, admission);
2149
2461
  }
@@ -2157,10 +2469,11 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2157
2469
  const childStopController = new AbortController();
2158
2470
  childStopControllers.set(key, childStopController);
2159
2471
  const childSignal = combinedAbortSignal([childController.signal, childStopController.signal]);
2160
- const resolvedResumeValue = resumeReference
2472
+ const resumeInput = resumeReference ?? (typeof params.resume === "string" && options.resolveResume ? params.resume : undefined);
2473
+ const resolvedResumeValue = resumeInput
2161
2474
  ? await Promise.resolve().then(() => {
2162
2475
  if (!options.resolveResume) throw new Error("Keyed workflow receipt resume is unavailable in this host.");
2163
- return options.resolveResume(resumeReference, childSignal);
2476
+ return options.resolveResume(resumeInput, childSignal, typeof params.index === "number" ? params.index : undefined);
2164
2477
  })
2165
2478
  : undefined;
2166
2479
  const resolvedResume = typeof resolvedResumeValue === "string"
@@ -2176,6 +2489,10 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2176
2489
  : [];
2177
2490
  resolvedResumeLineage = [...new Set(lineage.length ? lineage : [resolvedResumeId!])];
2178
2491
  if (resolvedResumeLineage.at(-1) !== resolvedResumeId) resolvedResumeLineage.push(resolvedResumeId!);
2492
+ if (typeof resumeInput === "string") {
2493
+ const predecessor = [...children.values()].find((child) => child.runId === resolvedResumeId);
2494
+ if (predecessor?.continuation && predecessor.continuation.runIds.at(-1) === resolvedResumeId) resolvedResumeLineage = predecessor.continuation.runIds;
2495
+ }
2179
2496
  }
2180
2497
  const launchParams = resolvedResumeId ? { ...params, resume: resolvedResumeId } : params;
2181
2498
  await launchSemaphore.acquire();
@@ -2195,6 +2512,10 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2195
2512
  } finally {
2196
2513
  launchSemaphore.release();
2197
2514
  }
2515
+ }, (error: unknown) => {
2516
+ if (!childController.signal.aborted) throw error;
2517
+ const reason = childController.signal.reason;
2518
+ return stoppedChildResult(key, reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.");
2198
2519
  }).then((result) => {
2199
2520
  let normalized = !result.ok && !result.error ? { ...result, error: result.output } : result;
2200
2521
  if (resolvedResumeLineage?.length && normalized.runId) {
@@ -2207,6 +2528,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2207
2528
  const state = normalized.ok ? "completed" : normalized.stopped ? "stopped" : normalized.detached ? "detached" : "failed";
2208
2529
  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 } : {}) });
2209
2530
  traceChanged();
2531
+ notifyChildSettled(key, normalized);
2210
2532
  return normalized;
2211
2533
  }, (error: unknown) => {
2212
2534
  const text = error instanceof Error ? error.message : String(error);
@@ -2216,6 +2538,7 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2216
2538
  children.set(key, failure);
2217
2539
  trace.push({ operation: "run", key, state: "failed", durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), ...(generatedLaneKey ? { generatedLaneKey } : {}), error: text });
2218
2540
  traceChanged();
2541
+ notifyChildSettled(key, failure);
2219
2542
  return failure;
2220
2543
  });
2221
2544
  launches.set(key, { fingerprint, promise, observed: callObserved, ...(generatedLaneKey ? { generatedLaneKey } : {}) });
@@ -2225,6 +2548,6 @@ export async function runWorkflowScript(options: RunWorkflowScriptOptions): Prom
2225
2548
  respond(deliver(promise), `runs.run('${key}') result`, (error) => children.set(key, responseBoundaryFailure(key, error)));
2226
2549
  });
2227
2550
 
2228
- worker.postMessage({ type: "start", script: options.script, stateEnabled: options.state !== undefined });
2551
+ worker.postMessage({ type: "start", script: options.script, ...(options.args ? { args: options.args } : {}), stateEnabled: options.state !== undefined });
2229
2552
  });
2230
2553
  }