@xzzpig/pi-subagents 0.24.1 → 0.25.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 (263) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/bundle/agent-management.js +4 -4
  3. package/bundle/agents.js +3 -3
  4. package/bundle/child-tool-plan.js +2 -2
  5. package/bundle/chunk-34TUUBRN.js +1107 -0
  6. package/bundle/{chunk-SW2VMNIU.js → chunk-5OD3OWTE.js} +2 -2
  7. package/bundle/{chunk-ZWXU5SPQ.js → chunk-5YEOWNSD.js} +371 -135
  8. package/bundle/{chunk-EUPJB4S7.js → chunk-5Z7JAORM.js} +196 -1219
  9. package/bundle/{chunk-LCDJWBVM.js → chunk-66JNFRFS.js} +1 -1
  10. package/bundle/{chunk-6BJUEES3.js → chunk-6MNRKUHY.js} +23 -12
  11. package/bundle/{chunk-ED55MIC2.js → chunk-CGFF4WA3.js} +42 -19
  12. package/bundle/{chunk-TMHVDPYW.js → chunk-DLVPMML3.js} +263 -154
  13. package/bundle/chunk-HXRB42AF.js +108 -0
  14. package/bundle/{chunk-355ECEP2.js → chunk-IH7LQVEE.js} +29 -14
  15. package/bundle/{chunk-SLNMBXLL.js → chunk-IJWITCC6.js} +411 -249
  16. package/bundle/{chunk-RU522D5W.js → chunk-IKFKH5EL.js} +369 -50
  17. package/bundle/{chunk-Z6TFJ6BR.js → chunk-INWSUNI6.js} +1 -1
  18. package/bundle/{chunk-JEA2ZKUA.js → chunk-IUDEI6FJ.js} +35 -200
  19. package/bundle/{chunk-WW76JRIX.js → chunk-JAXVBXGF.js} +1 -1
  20. package/bundle/{chunk-ICNYIALB.js → chunk-JH5H4CYJ.js} +784 -474
  21. package/bundle/{chunk-35GII5EF.js → chunk-JWFLPSTP.js} +41 -117
  22. package/bundle/{chunk-LMGQAJ3O.js → chunk-KCJFGKVK.js} +350 -123
  23. package/bundle/{chunk-RB4GELQA.js → chunk-LPJEKHOY.js} +1 -1
  24. package/bundle/chunk-LYKG4FKH.js +523 -0
  25. package/bundle/{chunk-X6LOM3Z4.js → chunk-LZ3HBDTR.js} +161 -78
  26. package/bundle/{chunk-FG6SQJAR.js → chunk-OGPOCGWX.js} +24 -6
  27. package/bundle/{chunk-Y6H2G6KX.js → chunk-OSVXFWPG.js} +67 -30
  28. package/bundle/{chunk-FJWI64H7.js → chunk-RMSABUN3.js} +27 -13
  29. package/bundle/{chunk-H36HBZB2.js → chunk-SJPABBZG.js} +2 -2
  30. package/bundle/{chunk-3U633XDZ.js → chunk-U3ZDUUTM.js} +11 -3
  31. package/bundle/{chunk-LVWU2HOO.js → chunk-ULGMXABL.js} +16 -7
  32. package/bundle/{chunk-WPW4V6HM.js → chunk-W7ZA6TYD.js} +2 -2
  33. package/bundle/{chunk-V2KFIGFH.js → chunk-XAC2XNAP.js} +503 -304
  34. package/bundle/{chunk-TGLFTQWJ.js → chunk-YWXILP5N.js} +5 -4
  35. package/bundle/control-channel.js +2 -2
  36. package/bundle/index.js +1 -1
  37. package/bundle/intercom-bridge.js +2 -2
  38. package/bundle/preflight.js +12 -10
  39. package/bundle/project-panes.js +3 -3
  40. package/bundle/workflow-resources.js +1 -1
  41. package/docs/agents.md +27 -6
  42. package/docs/configuration.md +20 -8
  43. package/docs/extension-api.md +18 -1
  44. package/docs/models.md +6 -2
  45. package/docs/observability.md +2 -0
  46. package/docs/tool-reference.md +7 -1
  47. package/docs/workflows.md +30 -2
  48. package/node_modules/@xzzpig/pi-components/CHANGELOG.md +12 -0
  49. package/node_modules/@xzzpig/pi-components/README.md +94 -0
  50. package/node_modules/@xzzpig/pi-components/dist/src/transcript-presenter.d.ts +186 -0
  51. package/node_modules/@xzzpig/pi-components/dist/src/transcript-presenter.js +693 -0
  52. package/node_modules/@xzzpig/pi-components/package.json +5 -1
  53. package/package.json +4 -4
  54. package/skills/pi-subagents/SKILL.md +15 -6
  55. package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
  56. package/src/agents/agent-management.d.ts +1 -0
  57. package/src/agents/agent-management.js +46 -18
  58. package/src/agents/agent-memory.d.ts +1 -4
  59. package/src/agents/agent-memory.js +1 -4
  60. package/src/agents/agent-serializer.d.ts +2 -0
  61. package/src/agents/agent-serializer.js +1 -1
  62. package/src/agents/agents.d.ts +2 -3
  63. package/src/agents/agents.js +46 -20
  64. package/src/agents/frontmatter.js +1 -8
  65. package/src/agents/global-npm-root.d.ts +1 -0
  66. package/src/agents/global-npm-root.js +11 -3
  67. package/src/agents/skills.d.ts +0 -3
  68. package/src/agents/skills.js +0 -3
  69. package/src/api/preflight.d.ts +3 -1
  70. package/src/api/preflight.js +2 -0
  71. package/src/extension/config.d.ts +1 -0
  72. package/src/extension/config.js +13 -1
  73. package/src/extension/herdr-pi-bridge.js +10 -2
  74. package/src/extension/index.d.ts +0 -13
  75. package/src/extension/index.js +51 -37
  76. package/src/extension/public-execution.d.ts +1 -0
  77. package/src/extension/public-execution.js +4 -0
  78. package/src/extension/reply-workflow-script.js +24 -4
  79. package/src/extension/schemas.d.ts +12 -3
  80. package/src/extension/schemas.js +7 -3
  81. package/src/extension/session-switch.d.ts +25 -0
  82. package/src/extension/session-switch.js +138 -0
  83. package/src/extension/subagent-guide.d.ts +1 -1
  84. package/src/extension/subagent-guide.js +1 -1
  85. package/src/extension/subagent-launch-tool.d.ts +25 -0
  86. package/src/extension/subagent-launch-tool.js +48 -0
  87. package/src/extension/tool-activation.js +55 -15
  88. package/src/extension/tool-description.d.ts +1 -1
  89. package/src/extension/tool-description.js +14 -8
  90. package/src/inspectors/herdr/actions.d.ts +0 -1
  91. package/src/inspectors/herdr/actions.js +0 -1
  92. package/src/inspectors/session-roots-codec.d.ts +0 -1
  93. package/src/inspectors/session-roots-codec.js +0 -1
  94. package/src/inspectors/tmux/actions.d.ts +0 -1
  95. package/src/inspectors/tmux/actions.js +0 -1
  96. package/src/integrations/herdr-status.js +3 -8
  97. package/src/intercom/native-supervisor-channel.js +65 -9
  98. package/src/runs/background/async-execution.d.ts +7 -10
  99. package/src/runs/background/async-execution.js +66 -29
  100. package/src/runs/background/async-job-tracker.js +12 -0
  101. package/src/runs/background/async-resume.d.ts +2 -1
  102. package/src/runs/background/async-resume.js +114 -40
  103. package/src/runs/background/async-retention.d.ts +0 -2
  104. package/src/runs/background/async-retention.js +17 -6
  105. package/src/runs/background/async-status.d.ts +2 -0
  106. package/src/runs/background/async-status.js +4 -0
  107. package/src/runs/background/auto-drain.js +2 -1
  108. package/src/runs/background/boot-id.d.ts +1 -3
  109. package/src/runs/background/boot-id.js +1 -3
  110. package/src/runs/background/completion-batcher.d.ts +3 -4
  111. package/src/runs/background/completion-batcher.js +2 -3
  112. package/src/runs/background/control-channel.d.ts +0 -6
  113. package/src/runs/background/control-channel.js +0 -6
  114. package/src/runs/background/fleet-view.js +2 -3
  115. package/src/runs/background/notify.d.ts +0 -2
  116. package/src/runs/background/notify.js +0 -2
  117. package/src/runs/background/result-watcher.d.ts +1 -0
  118. package/src/runs/background/result-watcher.js +59 -29
  119. package/src/runs/background/resume-guidance.js +4 -2
  120. package/src/runs/background/retained-children.js +2 -1
  121. package/src/runs/background/run-child-session.d.ts +2 -3
  122. package/src/runs/background/run-child-session.js +5 -8
  123. package/src/runs/background/run-status.js +9 -7
  124. package/src/runs/background/runner-aliases.js +15 -0
  125. package/src/runs/background/scheduled-runs.d.ts +3 -1
  126. package/src/runs/background/scheduled-runs.js +13 -16
  127. package/src/runs/background/steering.d.ts +2 -11
  128. package/src/runs/background/steering.js +11 -6
  129. package/src/runs/background/subagent-runner.d.ts +2 -6
  130. package/src/runs/background/subagent-runner.js +88 -70
  131. package/src/runs/background/subagent-wait.js +12 -15
  132. package/src/runs/background/wait-config.d.ts +2 -0
  133. package/src/runs/background/wait-config.js +17 -3
  134. package/src/runs/background/wait-subscriptions.js +124 -12
  135. package/src/runs/background/wait-tool.js +4 -2
  136. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  137. package/src/runs/background/workflow-terminal-proof.js +0 -1
  138. package/src/runs/foreground/async-steering-action.js +24 -9
  139. package/src/runs/foreground/async-stop-action.d.ts +1 -1
  140. package/src/runs/foreground/async-stop-action.js +9 -1
  141. package/src/runs/foreground/execution.d.ts +0 -3
  142. package/src/runs/foreground/execution.js +56 -24
  143. package/src/runs/foreground/prompt-audit.js +1 -0
  144. package/src/runs/foreground/subagent-executor.d.ts +5 -10
  145. package/src/runs/foreground/subagent-executor.js +164 -49
  146. package/src/runs/shared/acceptance.js +69 -26
  147. package/src/runs/shared/async-status-projection.d.ts +2 -0
  148. package/src/runs/shared/async-status-projection.js +10 -0
  149. package/src/runs/shared/child-commands.js +15 -2
  150. package/src/runs/shared/child-hooks.d.ts +1 -7
  151. package/src/runs/shared/child-hooks.js +13 -5
  152. package/src/runs/shared/child-launch.js +6 -2
  153. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  154. package/src/runs/shared/child-session.d.ts +6 -5
  155. package/src/runs/shared/child-session.js +85 -38
  156. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  157. package/src/runs/shared/child-tool-plan.js +0 -1
  158. package/src/runs/shared/claude-code-adapter.js +11 -0
  159. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  160. package/src/runs/shared/external-cli-contract.js +18 -13
  161. package/src/runs/shared/external-cli-runner.js +26 -6
  162. package/src/runs/shared/herdr-connection.js +2 -1
  163. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  164. package/src/runs/shared/herdr-pane-host.js +17 -1
  165. package/src/runs/shared/herdr-placed-run.js +51 -24
  166. package/src/runs/shared/lane-metadata.d.ts +0 -1
  167. package/src/runs/shared/lane-metadata.js +0 -1
  168. package/src/runs/shared/mcp-config-sources.d.ts +4 -1
  169. package/src/runs/shared/mcp-config-sources.js +1 -1
  170. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -3
  171. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -17
  172. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  173. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  174. package/src/runs/shared/model-resolution.d.ts +20 -5
  175. package/src/runs/shared/model-resolution.js +55 -50
  176. package/src/runs/shared/model-scope.d.ts +1 -5
  177. package/src/runs/shared/model-scope.js +1 -5
  178. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  179. package/src/runs/shared/mutation-evidence.js +52 -7
  180. package/src/runs/shared/nested-events.d.ts +1 -0
  181. package/src/runs/shared/nested-events.js +1 -1
  182. package/src/runs/shared/parallel-utils.d.ts +0 -1
  183. package/src/runs/shared/permissions.js +5 -3
  184. package/src/runs/shared/placement-host.d.ts +5 -1
  185. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  186. package/src/runs/shared/rex-pane-host.js +0 -2
  187. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  188. package/src/runs/shared/run-launch-folder.js +21 -0
  189. package/src/runs/shared/runner-launcher.d.ts +12 -1
  190. package/src/runs/shared/runner-launcher.js +16 -0
  191. package/src/runs/shared/single-output.d.ts +3 -3
  192. package/src/runs/shared/single-output.js +5 -3
  193. package/src/runs/shared/structured-output.d.ts +8 -0
  194. package/src/runs/shared/structured-output.js +40 -5
  195. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  196. package/src/runs/shared/subagent-prompt-runtime.js +18 -4
  197. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  198. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  199. package/src/runs/shared/tool-timeout.js +2 -1
  200. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  201. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  202. package/src/runs/shared/worktree.d.ts +3 -0
  203. package/src/runs/shared/worktree.js +20 -0
  204. package/src/shared/artifacts.d.ts +1 -0
  205. package/src/shared/artifacts.js +132 -22
  206. package/src/shared/capacity-resilient-json.d.ts +1 -1
  207. package/src/shared/child-cache-retention.d.ts +1 -2
  208. package/src/shared/child-cache-retention.js +1 -2
  209. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  210. package/src/shared/fleet-transcript-reader.js +333 -0
  211. package/src/shared/formatters.d.ts +0 -18
  212. package/src/shared/formatters.js +0 -18
  213. package/src/shared/pruned-fork.js +2 -2
  214. package/src/shared/reported-progress.d.ts +1 -0
  215. package/src/shared/reported-progress.js +12 -0
  216. package/src/shared/session-succession.d.ts +16 -1
  217. package/src/shared/session-succession.js +41 -2
  218. package/src/shared/session-warnings.d.ts +7 -0
  219. package/src/shared/session-warnings.js +26 -0
  220. package/src/shared/settings.d.ts +0 -23
  221. package/src/shared/settings.js +3 -35
  222. package/src/shared/status-format.d.ts +1 -0
  223. package/src/shared/status-format.js +1 -1
  224. package/src/shared/types.d.ts +108 -59
  225. package/src/shared/types.js +0 -12
  226. package/src/shared/utils.d.ts +3 -15
  227. package/src/shared/utils.js +4 -22
  228. package/src/shared/wait-tool-name.d.ts +8 -0
  229. package/src/shared/wait-tool-name.js +13 -0
  230. package/src/slash/slash-commands.js +2 -1
  231. package/src/slash/subagent-cost.d.ts +3 -2
  232. package/src/slash/subagent-cost.js +22 -3
  233. package/src/slash/subagents-admin.js +0 -1
  234. package/src/tui/fleet-status.d.ts +0 -5
  235. package/src/tui/fleet-status.js +4 -24
  236. package/src/tui/fleet.js +6 -4
  237. package/src/tui/render.d.ts +0 -9
  238. package/src/tui/render.js +194 -68
  239. package/src/tui/subagent-messages.js +3 -2
  240. package/src/watchdog/model-selection.js +2 -2
  241. package/src/watchdog/permission-arbiter.js +1 -0
  242. package/src/watchdog/register-child.d.ts +2 -3
  243. package/src/watchdog/register-child.js +2 -3
  244. package/src/watchdog/review.d.ts +0 -5
  245. package/src/watchdog/review.js +4 -3
  246. package/src/watchdog/turn-delta.js +2 -1
  247. package/src/workflows/scripted-workflow.d.ts +2 -0
  248. package/src/workflows/scripted-workflow.js +344 -59
  249. package/src/workflows/structured-workflow-scripts.d.ts +4 -3
  250. package/src/workflows/structured-workflow-scripts.js +32 -11
  251. package/src/workflows/workflow-launch-record.d.ts +15 -6
  252. package/src/workflows/workflow-launch-record.js +30 -12
  253. package/src/workflows/workflow-receipt.js +36 -53
  254. package/src/workflows/workflow-resources.js +4 -4
  255. package/src/workflows/workflow-resume-claim.d.ts +2 -0
  256. package/src/workflows/workflow-resume-claim.js +3 -3
  257. package/src/workflows/workflow-resume.d.ts +1 -1
  258. package/src/workflows/workflow-resume.js +13 -8
  259. package/src/workflows/workflow-script-worker.d.ts +13 -0
  260. package/src/workflows/workflow-script-worker.js +81 -0
  261. package/workflow-script-process.cjs +36 -0
  262. package/workflow-script-worker.cjs +4 -1
  263. package/bundle/chunk-U4ODUYAG.js +0 -235
@@ -7,7 +7,28 @@ const OUTPUT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
7
7
  const PLACEHOLDER_PATTERN = /\{(?:task|previous|outputs\.([A-Za-z_][A-Za-z0-9_]*))\}/g;
8
8
  /** Optional per-child launch fields copied verbatim onto the generated runs.all item. */
9
9
  const CHILD_FIELDS = ["cwd", "model"];
10
- export const TOP_LEVEL_CONTROLS_HINT = " Put worktree and other child controls on the subagent call itself; they apply to every child.";
10
+ // Outer subagent-call controls that default onto every workflow child (docs/workflows.md); output gets its own advice.
11
+ const SHARED_CHILD_CONTROLS = new Set(["worktree", "baseRef", "context", "skill", "fast", "agentScope", "outputMode", "outputSchema", "agentContract", "acceptance", "gate", "toolBudget", "toolTimeoutMs", "control"]);
12
+ // runs.run/runs.all child fields whose outer-call form is missing or means something else (async and timeoutMs apply to the workflow).
13
+ const SCRIPT_CHILD_FIELDS = new Set(["key", "label", "phase", "resume", "async", "timeoutMs"]);
14
+ /** Recovery advice per rejected field, so a retry keeps the caller's intent instead of dropping the field. */
15
+ export function unsupportedChildFieldAdvice(fields, scripts) {
16
+ const perChild = scripts ? "use workflow: true with runs.all items" : "you need workflow scripts, which disabledFeatures has turned off";
17
+ const advice = [];
18
+ const itemFields = fields.filter((field) => CHILD_FIELDS.includes(field));
19
+ if (itemFields.length > 0)
20
+ advice.push(`Set ${itemFields.join(", ")} on each item, or on the subagent call itself to give every child the same value.`);
21
+ if (fields.includes("output"))
22
+ advice.push(`For one shared output, set output on the subagent call itself: the workflow result is written there and each child gets its own file beside it. For exact or different per-child paths, ${perChild}. Do not drop output if you need durable child files.`);
23
+ const shared = fields.filter((field) => SHARED_CHILD_CONTROLS.has(field));
24
+ if (shared.length > 0)
25
+ advice.push(`Set ${shared.join(", ")} on the subagent call itself to give every child the same value; for different values per child, ${perChild}.`);
26
+ const scriptOnly = fields.filter((field) => SCRIPT_CHILD_FIELDS.has(field));
27
+ if (scriptOnly.length > 0)
28
+ advice.push(`For per-child ${scriptOnly.join(", ")}, ${perChild}.`);
29
+ advice.push("No child was launched.");
30
+ return advice.join(" ");
31
+ }
11
32
  export function isPlainRecord(value) {
12
33
  if (!value || typeof value !== "object" || Array.isArray(value))
13
34
  return false;
@@ -19,12 +40,12 @@ function nonEmptyString(value, path) {
19
40
  throw new Error(`${path} must be a non-empty string.`);
20
41
  return value;
21
42
  }
22
- function exactFields(value, path, allowed, hint) {
43
+ function exactFields(value, path, allowed, hint, scripts) {
23
44
  if (!isPlainRecord(value))
24
45
  throw new Error(`${path} must be an object.`);
25
46
  const unsupported = Object.keys(value).filter((key) => !allowed.includes(key));
26
47
  if (unsupported.length > 0)
27
- throw new Error(`${path} contains unsupported fields: ${unsupported.join(", ")}. ${hint}`);
48
+ throw new Error(`${path} contains unsupported fields: ${unsupported.join(", ")}. ${hint} ${unsupportedChildFieldAdvice(unsupported, scripts)}`);
28
49
  return value;
29
50
  }
30
51
  /** Single pass: text inserted for a placeholder is never scanned again. Unrecognized brace text stays literal. */
@@ -93,12 +114,12 @@ const SETTLE_HELPER = [
93
114
  " return new Error(label + \": \" + children.filter(function (child) { return !child.ok; }).map(function (child) { return child.key + \" (\" + child.agent + \") failed\" + (child.error ? \": \" + child.error : \"\"); }).join(\"; \"));",
94
115
  "}",
95
116
  ].join("\n");
96
- function buildTasksScript(steps, originalTask) {
117
+ function buildTasksScript(steps, originalTask, scripts) {
97
118
  if (!Array.isArray(steps) || steps.length === 0)
98
119
  throw new Error("tasks must be a non-empty array of { agent, task } items.");
99
120
  const children = steps.map((item, index) => {
100
121
  const path = `tasks[${index}]`;
101
- const record = exactFields(item, path, ["agent", "task", ...CHILD_FIELDS], `Each tasks item accepts agent and task, plus optional cwd and model.${TOP_LEVEL_CONTROLS_HINT}`);
122
+ const record = exactFields(item, path, ["agent", "task", ...CHILD_FIELDS], "Each tasks item accepts agent and task, plus optional cwd and model.", scripts);
102
123
  const agent = nonEmptyString(record.agent, `${path}.agent`);
103
124
  const task = nonEmptyString(record.task, `${path}.task`);
104
125
  const taskExpression = compileTemplate(task, {
@@ -132,20 +153,20 @@ function buildChainScript(steps, originalTask) {
132
153
  let stepChildren;
133
154
  let outputName;
134
155
  if (isPlainRecord(step) && Object.hasOwn(step, "parallel")) {
135
- const record = exactFields(step, path, ["parallel"], `A parallel step accepts only parallel; as is supported on sequential steps only.${TOP_LEVEL_CONTROLS_HINT}`);
156
+ const record = exactFields(step, path, ["parallel"], "A parallel step accepts only parallel; as is supported on sequential steps only.", false);
136
157
  const items = record.parallel;
137
158
  if (!Array.isArray(items) || items.length === 0)
138
159
  throw new Error(`${path}.parallel must be a non-empty array of { agent, task } items.`);
139
160
  stepChildren = items.map((item, itemIndex) => {
140
161
  const itemPath = `${path}.parallel[${itemIndex}]`;
141
- const itemRecord = exactFields(item, itemPath, ["agent", "task", ...CHILD_FIELDS], `Each parallel item accepts agent and task, plus optional cwd and model.${TOP_LEVEL_CONTROLS_HINT}`);
162
+ const itemRecord = exactFields(item, itemPath, ["agent", "task", ...CHILD_FIELDS], "Each parallel item accepts agent and task, plus optional cwd and model.", false);
142
163
  const agent = nonEmptyString(itemRecord.agent, `${itemPath}.agent`);
143
164
  const task = nonEmptyString(itemRecord.task, `${itemPath}.task`);
144
165
  return { key: `step-${number}-${itemIndex + 1}`, agent, fields: childFields(itemRecord, itemPath), taskExpression: compileTemplate(task, { path: `${itemPath}.task`, hasOriginalTask, previous, outputs }) };
145
166
  });
146
167
  }
147
168
  else {
148
- const record = exactFields(step, path, ["agent", "task", "as", ...CHILD_FIELDS], `A sequential step accepts agent, task, as, cwd and model; a parallel step accepts only parallel.${TOP_LEVEL_CONTROLS_HINT}`);
169
+ const record = exactFields(step, path, ["agent", "task", "as", ...CHILD_FIELDS], "A sequential step accepts agent, task, as, cwd and model; a parallel step accepts only parallel.", false);
149
170
  const agent = nonEmptyString(record.agent, `${path}.agent`);
150
171
  let task;
151
172
  if (record.task === undefined) {
@@ -173,7 +194,7 @@ function buildChainScript(steps, originalTask) {
173
194
  lines.push("return { ok: true, children };");
174
195
  return lines.join("\n");
175
196
  }
176
- /** Validate exact data shapes and expand them into a package-owned workflow script. */
177
- export function buildStructuredWorkflowScript(kind, steps, originalTask) {
178
- return kind === "tasks" ? buildTasksScript(steps, originalTask) : buildChainScript(steps, originalTask);
197
+ /** Validate exact data shapes and expand them into a package-owned workflow script. `scripts` is true only for the named `parallel` workflow; top-level tasks and chain exist only when workflow scripts are disabled. */
198
+ export function buildStructuredWorkflowScript(kind, steps, originalTask, scripts) {
199
+ return kind === "tasks" ? buildTasksScript(steps, originalTask, scripts) : buildChainScript(steps, originalTask);
179
200
  }
@@ -1,17 +1,26 @@
1
+ import { type ResolvedSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.ts";
1
2
  /**
2
- * The public launch of an async top-level workflow, saved in its run directory so the run can be
3
- * relaunched later. A named resource is saved by name (its `runs.host` permit cannot be saved);
4
- * structured tasks/chain launches save no params, so they cannot be relaunched from this record.
3
+ * The public launch of an async top-level workflow, saved so the run can be relaunched later. A
4
+ * named resource is saved by name (its `runs.host` permit cannot be saved); structured tasks/chain
5
+ * launches and internal ones (schedule ticks, prompt-template delegation) save no params, so they
6
+ * cannot be relaunched from this record; their record still gives a child revive its ceiling.
7
+ * The record is the only source of a relaunch's owner and capability ceiling. It lives outside the
8
+ * run directory because a run behind a runner launcher can write its own directory.
5
9
  */
6
10
  export type WorkflowLaunch = {
7
11
  source: "script" | "resource";
8
12
  params: Record<string, unknown>;
9
13
  } | {
10
14
  source: "structured";
15
+ } | {
16
+ source: "internal";
11
17
  };
12
18
  export type WorkflowLaunchRecord = WorkflowLaunch & {
13
- version: 1;
19
+ version: 2;
14
20
  scriptDigest: string;
21
+ /** The session that launched the run; only it, or a session that replaced it, may relaunch it. */
22
+ sessionId: string;
23
+ admissionCapabilityCeiling?: ResolvedSubagentCapabilityCeiling;
15
24
  };
16
25
  type WorkflowLaunchRecordRead = {
17
26
  ok: true;
@@ -22,6 +31,6 @@ type WorkflowLaunchRecordRead = {
22
31
  error: string;
23
32
  };
24
33
  /** Throws on a write failure; the launch must fail rather than start a run it cannot relaunch. */
25
- export declare function writeWorkflowLaunchRecord(asyncDir: string, record: WorkflowLaunchRecord): void;
26
- export declare function readWorkflowLaunchRecord(asyncDir: string): WorkflowLaunchRecordRead;
34
+ export declare function writeWorkflowLaunchRecord(asyncDirRoot: string, runId: string, record: WorkflowLaunchRecord): void;
35
+ export declare function readWorkflowLaunchRecord(asyncDirRoot: string, runId: string): WorkflowLaunchRecordRead;
27
36
  export {};
@@ -1,13 +1,15 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
+ import { parseSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.js";
4
+ import { runLaunchDir } from "../runs/shared/run-launch-folder.js";
3
5
  import { writeAtomicJson } from "../shared/atomic-json.js";
4
6
  const WORKFLOW_LAUNCH_RECORD_FILE = "launch.json";
5
- function launchRecordPath(asyncDir) {
6
- return path.join(asyncDir, WORKFLOW_LAUNCH_RECORD_FILE);
7
+ function launchRecordPath(asyncDirRoot, runId) {
8
+ return path.join(runLaunchDir(asyncDirRoot, runId), WORKFLOW_LAUNCH_RECORD_FILE);
7
9
  }
8
10
  /** Throws on a write failure; the launch must fail rather than start a run it cannot relaunch. */
9
- export function writeWorkflowLaunchRecord(asyncDir, record) {
10
- writeAtomicJson(launchRecordPath(asyncDir), record);
11
+ export function writeWorkflowLaunchRecord(asyncDirRoot, runId, record) {
12
+ writeAtomicJson(launchRecordPath(asyncDirRoot, runId), record);
11
13
  }
12
14
  function isPlainObject(value) {
13
15
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
@@ -15,10 +17,10 @@ function isPlainObject(value) {
15
17
  function invalid(error) {
16
18
  return { ok: false, missing: false, error };
17
19
  }
18
- export function readWorkflowLaunchRecord(asyncDir) {
20
+ export function readWorkflowLaunchRecord(asyncDirRoot, runId) {
19
21
  let text;
20
22
  try {
21
- text = fs.readFileSync(launchRecordPath(asyncDir), "utf-8");
23
+ text = fs.readFileSync(launchRecordPath(asyncDirRoot, runId), "utf-8");
22
24
  }
23
25
  catch (error) {
24
26
  if (error.code === "ENOENT")
@@ -34,15 +36,31 @@ export function readWorkflowLaunchRecord(asyncDir) {
34
36
  }
35
37
  if (!isPlainObject(value))
36
38
  return invalid("not a JSON object");
37
- if (value.version !== 1)
38
- return invalid("version must be 1");
39
+ if (value.version !== 2)
40
+ return invalid("version must be 2");
39
41
  if (typeof value.scriptDigest !== "string" || !value.scriptDigest)
40
42
  return invalid("scriptDigest must be a non-empty string");
41
- if (value.source === "structured")
42
- return { ok: true, record: { version: 1, source: "structured", scriptDigest: value.scriptDigest } };
43
+ if (typeof value.sessionId !== "string" || !value.sessionId)
44
+ return invalid("sessionId must be a non-empty string");
45
+ let admissionCapabilityCeiling;
46
+ try {
47
+ if (value.admissionCapabilityCeiling !== undefined)
48
+ admissionCapabilityCeiling = parseSubagentCapabilityCeiling(value.admissionCapabilityCeiling, "admissionCapabilityCeiling");
49
+ }
50
+ catch (error) {
51
+ return invalid(error instanceof Error ? error.message : String(error));
52
+ }
53
+ const owner = {
54
+ version: 2,
55
+ scriptDigest: value.scriptDigest,
56
+ sessionId: value.sessionId,
57
+ ...(admissionCapabilityCeiling ? { admissionCapabilityCeiling } : {}),
58
+ };
59
+ if (value.source === "structured" || value.source === "internal")
60
+ return { ok: true, record: { ...owner, source: value.source } };
43
61
  if (value.source !== "script" && value.source !== "resource")
44
- return invalid("source must be \"script\", \"resource\", or \"structured\"");
62
+ return invalid("source must be \"script\", \"resource\", \"structured\", or \"internal\"");
45
63
  if (!isPlainObject(value.params))
46
64
  return invalid("params must be an object");
47
- return { ok: true, record: { version: 1, source: value.source, params: value.params, scriptDigest: value.scriptDigest } };
65
+ return { ok: true, record: { ...owner, source: value.source, params: value.params } };
48
66
  }
@@ -5,6 +5,7 @@ import { parseWorkflowChildSummary } from "./workflow-child-summary.js";
5
5
  import { HOST_STEP_MAX_COUNT, assertUniqueHostStepIds, parseHostStepNode } from "../runs/shared/host-step-status.js";
6
6
  import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../runs/shared/lane-metadata.js";
7
7
  import { projectWorkflowKeyRevival } from "./workflow-revival.js";
8
+ import { EXTERNAL_CLI_ADAPTER_SAFETY, isCodeOwnedExternalCliAdapterId } from "../runs/shared/external-cli-contract.js";
8
9
  export const WORKFLOW_RECEIPT_VERSION = 1;
9
10
  export const WORKFLOW_RECEIPT_FILE = "workflow-receipt.json";
10
11
  const MAX_WORKFLOW_RECEIPT_BYTES = 2 * 1024 * 1024;
@@ -127,6 +128,30 @@ function parseExternalCliMachine(value, label) {
127
128
  if (unknownRemoteGit.length > 0 || (remoteGit.head !== undefined && (typeof remoteGit.head !== "string" || !remoteGit.head.trim())) || (remoteGit.branch !== undefined && (typeof remoteGit.branch !== "string" || !remoteGit.branch.trim())) || (remoteGit.dirty !== undefined && typeof remoteGit.dirty !== "boolean"))
128
129
  throw new Error(`${label}.machine.remoteGit is invalid.`);
129
130
  }
131
+ function parseCodeOwnedSafety(value, adapter, label) {
132
+ if (!value || typeof value !== "object" || Array.isArray(value))
133
+ throw new Error(`${label}.safety is missing.`);
134
+ const safety = value;
135
+ const profile = EXTERNAL_CLI_ADAPTER_SAFETY[adapter];
136
+ const unknownSafety = Object.keys(safety).filter((field) => !Object.hasOwn(profile, field));
137
+ if (unknownSafety.length > 0)
138
+ throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
139
+ if (Object.entries(profile).some(([field, expected]) => safety[field] !== expected))
140
+ throw new Error(`${label}.safety is invalid.`);
141
+ }
142
+ function parseExternalCliSafetySource(value, label) {
143
+ if (value === undefined)
144
+ return false;
145
+ if (!value || typeof value !== "object" || Array.isArray(value))
146
+ throw new Error(`${label}.safetySource must be an object.`);
147
+ const source = value;
148
+ const unknownSource = Object.keys(source).filter((field) => !["measured", "command"].includes(field));
149
+ if (unknownSource.length > 0)
150
+ throw new Error(`${label}.safetySource has unsupported fields: ${unknownSource.join(", ")}.`);
151
+ if (source.measured !== false || (source.command !== undefined && (typeof source.command !== "string" || !source.command.trim())))
152
+ throw new Error(`${label}.safetySource is invalid.`);
153
+ return true;
154
+ }
130
155
  function parseExternalCliReceiptMetadata(value, key, source) {
131
156
  if (value === undefined)
132
157
  return undefined;
@@ -134,7 +159,7 @@ function parseExternalCliReceiptMetadata(value, key, source) {
134
159
  if (!value || typeof value !== "object" || Array.isArray(value))
135
160
  throw new Error(`${label} must be an object.`);
136
161
  const metadata = value;
137
- const unknownMetadata = Object.keys(metadata).filter((field) => !["adapter", "capabilities", "machine", "safety", "outputArtifacts", "handoff", "supervisor", "nonResumableReason"].includes(field));
162
+ const unknownMetadata = Object.keys(metadata).filter((field) => !["adapter", "capabilities", "machine", "safety", "safetySource", "outputArtifacts", "handoff", "supervisor", "nonResumableReason"].includes(field));
138
163
  if (unknownMetadata.length > 0)
139
164
  throw new Error(`${label} has unsupported fields: ${unknownMetadata.join(", ")}.`);
140
165
  const adapter = metadata.adapter;
@@ -160,65 +185,21 @@ function parseExternalCliReceiptMetadata(value, key, source) {
160
185
  if (metadata.machine !== undefined)
161
186
  parseExternalCliMachine(metadata.machine, label);
162
187
  const safety = metadata.safety;
163
- if (adapterRecord.id === "codex-exec") {
164
- if (!safety || typeof safety !== "object" || Array.isArray(safety))
165
- throw new Error(`${label}.safety is missing.`);
166
- const safetyRecord = safety;
167
- const unknownSafety = Object.keys(safetyRecord).filter((field) => !["sandbox", "approvalPolicy", "ephemeral"].includes(field));
168
- if (unknownSafety.length > 0)
169
- throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
170
- if (safetyRecord.sandbox !== "read-only" || safetyRecord.approvalPolicy !== "never" || safetyRecord.ephemeral !== true)
171
- throw new Error(`${label}.safety is invalid.`);
172
- }
173
- else if (adapterRecord.id === "codex-exec-writer") {
174
- if (!safety || typeof safety !== "object" || Array.isArray(safety))
175
- throw new Error(`${label}.safety is missing.`);
188
+ const hasSafetySource = parseExternalCliSafetySource(metadata.safetySource, label);
189
+ if (adapterRecord.id === "claude-code" && !hasSafetySource && safety && typeof safety === "object" && !Array.isArray(safety) && safety.authentication === undefined) {
176
190
  const safetyRecord = safety;
177
- const unknownSafety = Object.keys(safetyRecord).filter((field) => !["access", "sandbox", "approvalPolicy", "ephemeral"].includes(field));
191
+ const unknownSafety = Object.keys(safetyRecord).filter((field) => !["permissionMode", "tools", "mcp", "settingSources", "sessionPersistence"].includes(field));
178
192
  if (unknownSafety.length > 0)
179
193
  throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
180
- if (safetyRecord.access !== "workspace-write" || safetyRecord.sandbox !== "workspace-write" || safetyRecord.approvalPolicy !== "never" || safetyRecord.ephemeral !== true)
194
+ if (safetyRecord.permissionMode !== "plan" || safetyRecord.tools !== "none" || safetyRecord.mcp !== "empty-strict" || safetyRecord.settingSources !== "none" || safetyRecord.sessionPersistence !== false)
181
195
  throw new Error(`${label}.safety is invalid.`);
182
196
  }
183
- else if (adapterRecord.id === "claude-code") {
184
- if (!safety || typeof safety !== "object" || Array.isArray(safety))
185
- throw new Error(`${label}.safety is missing.`);
186
- const safetyRecord = safety;
187
- const legacy = safetyRecord.authentication === undefined;
188
- const unknownSafety = Object.keys(safetyRecord).filter((field) => !(legacy
189
- ? ["permissionMode", "tools", "mcp", "settingSources", "sessionPersistence"]
190
- : ["access", "authentication", "permissionMode", "tools", "mcp", "settingSources", "userSettingsTrust", "sessionPersistence"]).includes(field));
191
- if (unknownSafety.length > 0)
192
- throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
193
- if (legacy) {
194
- if (safetyRecord.permissionMode !== "plan" || safetyRecord.tools !== "none" || safetyRecord.mcp !== "empty-strict" || safetyRecord.settingSources !== "none" || safetyRecord.sessionPersistence !== false)
195
- throw new Error(`${label}.safety is invalid.`);
196
- }
197
- else if (safetyRecord.access !== "read-only" || safetyRecord.authentication !== "existing-cli-required" || safetyRecord.permissionMode !== "plan" || safetyRecord.tools !== "none" || safetyRecord.mcp !== "empty-strict" || safetyRecord.settingSources !== "user" || safetyRecord.userSettingsTrust !== "required" || safetyRecord.sessionPersistence !== false)
198
- throw new Error(`${label}.safety is invalid.`);
199
- }
200
- else if (adapterRecord.id === "claude-code-writer") {
201
- if (!safety || typeof safety !== "object" || Array.isArray(safety))
202
- throw new Error(`${label}.safety is missing.`);
203
- const safetyRecord = safety;
204
- const unknownSafety = Object.keys(safetyRecord).filter((field) => !["access", "authentication", "permissionMode", "tools", "mcp", "settingSources", "userSettingsTrust", "sessionPersistence"].includes(field));
205
- if (unknownSafety.length > 0)
206
- throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
207
- if (safetyRecord.access !== "workspace-write" || safetyRecord.authentication !== "existing-cli-required" || safetyRecord.permissionMode !== "acceptEdits" || safetyRecord.tools !== "Read,Write,Edit,Glob,Grep" || safetyRecord.mcp !== "empty-strict" || safetyRecord.settingSources !== "user" || safetyRecord.userSettingsTrust !== "required" || safetyRecord.sessionPersistence !== false)
208
- throw new Error(`${label}.safety is invalid.`);
209
- }
210
- else if (adapterRecord.id === "cursor-agent" || adapterRecord.id === "cursor-agent-writer") {
211
- if (!safety || typeof safety !== "object" || Array.isArray(safety))
212
- throw new Error(`${label}.safety is missing.`);
213
- const safetyRecord = safety;
214
- const unknownSafety = Object.keys(safetyRecord).filter((field) => !["access", "authentication", "mode", "sandbox", "workspaceTrust", "sessionReuse"].includes(field));
215
- if (unknownSafety.length > 0)
216
- throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
217
- const writer = adapterRecord.id === "cursor-agent-writer";
218
- if (safetyRecord.access !== (writer ? "workspace-write" : "read-only") || safetyRecord.authentication !== "cursor-api-key-or-existing-login" || safetyRecord.mode !== (writer ? "print" : "ask") || safetyRecord.sandbox !== "enabled" || safetyRecord.workspaceTrust !== "existing-required" || safetyRecord.sessionReuse !== false)
219
- throw new Error(`${label}.safety is invalid.`);
197
+ else if (isCodeOwnedExternalCliAdapterId(adapterRecord.id)) {
198
+ parseCodeOwnedSafety(safety, adapterRecord.id, label);
220
199
  }
221
200
  else if (adapterRecord.id === "grok-build") {
201
+ if (hasSafetySource)
202
+ throw new Error(`${label}.safetySource is invalid for the legacy grok-build adapter.`);
222
203
  if (!safety || typeof safety !== "object" || Array.isArray(safety))
223
204
  throw new Error(`${label}.safety is missing.`);
224
205
  const safetyRecord = safety;
@@ -228,6 +209,8 @@ function parseExternalCliReceiptMetadata(value, key, source) {
228
209
  if (safetyRecord.access !== "read-only" || safetyRecord.authentication !== "xai-api-key-required" || safetyRecord.permissionMode !== "plan" || safetyRecord.tools !== "read_file,grep,list_dir" || safetyRecord.deniedTools !== "run_terminal_cmd,search_replace,Agent,Bash,Edit,Write,MCPTool" || safetyRecord.sandbox !== "read-only" || safetyRecord.webSearch !== false || safetyRecord.subagents !== false || safetyRecord.config !== "temporary-home" || safetyRecord.updates !== "disabled" || safetyRecord.sessionPersistence !== false)
229
210
  throw new Error(`${label}.safety is invalid.`);
230
211
  }
212
+ else if (hasSafetySource)
213
+ throw new Error(`${label}.safetySource is invalid for the generic adapter.`);
231
214
  else if (safety !== undefined)
232
215
  throw new Error(`${label}.safety is invalid for the generic adapter.`);
233
216
  const handoff = metadata.handoff;
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { stableJsonDigest } from "../shared/launch-contract.js";
3
3
  import { createWorkflowResourcePermit, } from "../shared/workflow-child-permit.js";
4
- import { buildStructuredWorkflowScript, isPlainRecord, TOP_LEVEL_CONTROLS_HINT } from "./structured-workflow-scripts.js";
4
+ import { buildStructuredWorkflowScript, isPlainRecord, unsupportedChildFieldAdvice } from "./structured-workflow-scripts.js";
5
5
  const RESOURCE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
6
6
  export const MAX_ARGS_BYTES = 16 * 1024;
7
7
  export const MAX_ARGS_FIELDS = 16;
@@ -152,9 +152,9 @@ function resolveRunCi(args) {
152
152
  function resolveParallel(args) {
153
153
  const unsupported = Object.keys(args).filter((key) => key !== "tasks");
154
154
  if (unsupported.length > 0)
155
- return { error: `workflow 'parallel' args contain unsupported fields: ${unsupported.join(", ")}. Pass args.tasks: [{ agent, task, cwd?, model? }, ...].${TOP_LEVEL_CONTROLS_HINT}` };
155
+ return { error: `workflow 'parallel' args contain unsupported fields: ${unsupported.join(", ")}. Pass args.tasks: [{ agent, task, cwd?, model? }, ...]. ${unsupportedChildFieldAdvice(unsupported, true)}` };
156
156
  try {
157
- return { script: buildStructuredWorkflowScript("tasks", args.tasks, undefined) };
157
+ return { script: buildStructuredWorkflowScript("tasks", args.tasks, undefined, true) };
158
158
  }
159
159
  catch (error) {
160
160
  return { error: `workflow 'parallel' args.${error instanceof Error ? error.message : String(error)}` };
@@ -204,7 +204,7 @@ export function resolveStructuredWorkflowResource(input) {
204
204
  }
205
205
  if (jsonByteLength({ [kind]: steps, task }) > MAX_ARGS_BYTES)
206
206
  return { ok: false, error: `${kind} input exceeds ${MAX_ARGS_BYTES} bytes.` };
207
- const script = buildStructuredWorkflowScript(kind, JSON.parse(JSON.stringify(steps)), task);
207
+ const script = buildStructuredWorkflowScript(kind, JSON.parse(JSON.stringify(steps)), task, false);
208
208
  return { ok: true, resource: issueWorkflowResource(kind, STRUCTURED_WORKFLOW_RESOURCE_VERSION, script) };
209
209
  }
210
210
  catch (error) {
@@ -54,6 +54,8 @@ export declare function resumedRunStarted(sourceAsyncDir: string, newRunId: stri
54
54
  export declare function workflowResumeClaimState(asyncDir: string, options?: {
55
55
  liveness?: ClaimLiveness;
56
56
  }): WorkflowResumeClaimState;
57
+ /** Creates the claim file only if none exists, with its whole body in place at once. */
58
+ export declare function createClaimFile(filePath: string, claim: object): boolean;
57
59
  /**
58
60
  * Claims the right to continue the stopped run in `asyncDir` as `newRunId`. A dead claimant is
59
61
  * superseded by the next generation file; of several takers, the one whose exclusive create
@@ -93,7 +93,7 @@ export function workflowResumeClaimState(asyncDir, options = {}) {
93
93
  return claimantLiveness(top.filePath, top.claim, options.liveness) === "dead" ? { kind: "none" } : { kind: "busy", pid: top.claim.pid, newRunId: top.claim.newRunId };
94
94
  }
95
95
  /** Creates the claim file only if none exists, with its whole body in place at once. */
96
- function createClaimFile(filePath, claim) {
96
+ export function createClaimFile(filePath, claim) {
97
97
  const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
98
98
  try {
99
99
  fs.writeFileSync(tempPath, JSON.stringify(claim, null, 2), "utf-8");
@@ -205,6 +205,6 @@ export function describeWorkflowResume(asyncDir, runId) {
205
205
  }
206
206
  if (claim)
207
207
  return `${RESUMED_AS[claim.trigger]} ${claim.newRunId}.`;
208
- const launch = readWorkflowLaunchRecord(asyncDir);
209
- return launch.ok && launch.record.source !== "structured" ? resumeByHandText(runId) : relaunchByHandText(runId);
208
+ const launch = readWorkflowLaunchRecord(path.dirname(asyncDir), runId);
209
+ return launch.ok && (launch.record.source === "script" || launch.record.source === "resource") ? resumeByHandText(runId) : relaunchByHandText(runId);
210
210
  }
@@ -1,5 +1,5 @@
1
1
  type WorkflowResumeTrigger = "auto" | "manual";
2
- export type WorkflowResumeRefusalCode = "not-owned" | "not-interrupted" | "claim-busy" | "claim-resumed" | "launch-missing" | "launch-invalid" | "structured" | "digest" | "authority" | "capacity" | "attempts" | "launch-failed";
2
+ export type WorkflowResumeRefusalCode = "not-owned" | "not-interrupted" | "claim-busy" | "claim-resumed" | "launch-missing" | "launch-invalid" | "structured" | "internal" | "digest" | "authority" | "capacity" | "attempts" | "launch-failed" | "drained";
3
3
  export interface WorkflowResumeRefusalReason {
4
4
  code: WorkflowResumeRefusalCode;
5
5
  reason: string;
@@ -12,7 +12,7 @@ import { isReusableWorkflowStopCause, WORKFLOW_STOP_CAUSE_OWNER_EXITED } from ".
12
12
  /** A run may be resumed again after at most this many resumes that followed Pi exits (auto-resume only). */
13
13
  const MAX_WORKFLOW_RESUME_ATTEMPTS = 3;
14
14
  export function workflowResumeRefusal(code, reason, runId) {
15
- const byHand = code === "launch-missing" || code === "launch-invalid" || code === "structured" || code === "digest" || code === "authority"
15
+ const byHand = code === "launch-missing" || code === "launch-invalid" || code === "structured" || code === "internal" || code === "digest" || code === "authority" || code === "drained"
16
16
  ? relaunchByHandText(runId)
17
17
  : code === "capacity" || code === "attempts" || code === "launch-failed" ? resumeByHandText(runId) : "";
18
18
  return { code, reason, byHand };
@@ -51,10 +51,15 @@ export function prepareWorkflowResume(input) {
51
51
  const { asyncDirRoot, sourceRunId, trigger } = input;
52
52
  const refuse = (code, reason) => ({ ok: false, ...workflowResumeRefusal(code, reason, sourceRunId) });
53
53
  const sourceAsyncDir = path.join(asyncDirRoot, sourceRunId);
54
+ // What is relaunched, by whom and under which ceiling comes only from the parent-owned launch
55
+ // record: a run behind a runner launcher can rewrite every file in its own run directory.
56
+ const read = readWorkflowLaunchRecord(asyncDirRoot, sourceRunId);
57
+ if (!read.ok)
58
+ return read.missing ? refuse("launch-missing", "launch.json is missing (the run started before launches were saved outside its run directory)") : refuse("launch-invalid", `launch.json is invalid: ${read.error}`);
59
+ const record = read.record;
54
60
  // Only the session that owns the run (itself or one it replaced) may resume it, and nothing is
55
61
  // written into another session's run, so this comes before the reconcile.
56
- const stored = readStatus(sourceAsyncDir);
57
- if (stored && !ownsRun(input.currentSessionId, stored.sessionId))
62
+ if (!ownsRun(input.currentSessionId, record.sessionId))
58
63
  return refuse("not-owned", "it was started in another session; reopen that session to resume it");
59
64
  // Session start has already reconciled this session's runs; a resume by id may come later.
60
65
  if (trigger === "manual")
@@ -62,16 +67,16 @@ export function prepareWorkflowResume(input) {
62
67
  const status = readStatus(sourceAsyncDir);
63
68
  if (!status || status.mode !== "workflow" || !isReusableWorkflowStopCause(status.workflow?.stopCause))
64
69
  return refuse("not-interrupted", "not interrupted; pass message to revive one of its children");
70
+ if (status.workflow?.drainRequestedAt !== undefined)
71
+ return refuse("drained", "it was being drained when it was interrupted");
65
72
  // The attempt the resumed run records: only resumes that follow a Pi exit count.
66
73
  const attempt = (status.workflow?.resumeOrigin?.attempt ?? 0) + (status.workflow?.stopCause === WORKFLOW_STOP_CAUSE_OWNER_EXITED ? 1 : 0);
67
74
  if (trigger === "auto" && attempt > MAX_WORKFLOW_RESUME_ATTEMPTS)
68
75
  return refuse("attempts", `${MAX_WORKFLOW_RESUME_ATTEMPTS} resumes already followed Pi exits`);
69
- const read = readWorkflowLaunchRecord(sourceAsyncDir);
70
- if (!read.ok)
71
- return read.missing ? refuse("launch-missing", "launch.json is missing (the run started before launches were saved)") : refuse("launch-invalid", `launch.json is invalid: ${read.error}`);
72
- const record = read.record;
73
76
  if (record.source === "structured")
74
77
  return refuse("structured", "launched from tasks/chain");
78
+ if (record.source === "internal")
79
+ return refuse("internal", "launched by a schedule or prompt-template delegation");
75
80
  if (record.source === "script" && (typeof record.params.workflowScript !== "string" || workflowScriptDigest(record.params.workflowScript) !== record.scriptDigest)) {
76
81
  return refuse("launch-invalid", "launch.json is invalid: its script does not match its scriptDigest");
77
82
  }
@@ -97,7 +102,7 @@ export function prepareWorkflowResume(input) {
97
102
  ...record.params,
98
103
  async: true,
99
104
  reuseFrom: sourceRunId,
100
- ...(status.admissionCapabilityCeiling ? { capabilityCeiling: status.admissionCapabilityCeiling } : {}),
105
+ ...(record.admissionCapabilityCeiling ? { capabilityCeiling: record.admissionCapabilityCeiling } : {}),
101
106
  },
102
107
  expectedScriptDigest: record.scriptDigest,
103
108
  resumeOrigin: { sourceRunId, attempt },
@@ -0,0 +1,13 @@
1
+ import { type ChildProcess } from "node:child_process";
2
+ import { EventEmitter } from "node:events";
3
+ import { Worker } from "node:worker_threads";
4
+ export declare class WorkflowScriptProcess extends EventEmitter {
5
+ readonly child: ChildProcess;
6
+ private exitCode;
7
+ private stopping;
8
+ private stderr;
9
+ constructor(acornPath: string);
10
+ postMessage(message: unknown): void;
11
+ terminate(): Promise<number>;
12
+ }
13
+ export declare function createWorkflowScriptWorker(acornPath: string): Worker | WorkflowScriptProcess;
@@ -0,0 +1,81 @@
1
+ import { fork } from "node:child_process";
2
+ import { EventEmitter } from "node:events";
3
+ import { realpathSync } from "node:fs";
4
+ import { dirname } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { Worker } from "node:worker_threads";
7
+ const WORKFLOW_WORKER_URL = new URL("../../workflow-script-worker.cjs", import.meta.url);
8
+ const WORKFLOW_PROCESS_URL = new URL("../../workflow-script-process.cjs", import.meta.url);
9
+ export class WorkflowScriptProcess extends EventEmitter {
10
+ child;
11
+ exitCode;
12
+ stopping = false;
13
+ stderr = "";
14
+ constructor(acornPath) {
15
+ super();
16
+ const acorn = realpathSync(acornPath);
17
+ // Fork a path, not the URL. A host that runs Pi on Electron does not strip execArgv from a child started
18
+ // from a file URL, so the flags below would arrive in the child's argv ahead of the script.
19
+ this.child = fork(fileURLToPath(WORKFLOW_PROCESS_URL), [acorn], {
20
+ // Under --permission, Node lets worker threads read everything under the process cwd, so the cwd must
21
+ // hold only public files: acorn's own directory. It also never holds a caller's cwd open on Windows.
22
+ cwd: dirname(acorn),
23
+ // No inherited execArgv or NODE_OPTIONS. Only the supervisor may create a worker.
24
+ execArgv: [
25
+ "--permission", "--allow-worker",
26
+ `--allow-fs-read=${realpathSync(fileURLToPath(WORKFLOW_PROCESS_URL))}`,
27
+ `--allow-fs-read=${realpathSync(fileURLToPath(WORKFLOW_WORKER_URL))}`,
28
+ `--allow-fs-read=${acorn}`,
29
+ ],
30
+ env: process.platform === "win32" && process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {},
31
+ stdio: ["ignore", "ignore", "pipe", "ipc"],
32
+ });
33
+ this.child.stderr.on("data", (chunk) => { this.stderr = (this.stderr + chunk.toString("utf8")).slice(-4096); });
34
+ this.child.on("error", (error) => this.emit("error", error));
35
+ this.child.on("message", (json) => {
36
+ if (this.stopping)
37
+ return;
38
+ try {
39
+ if (typeof json !== "string")
40
+ throw new Error("Workflow process sent a non-string IPC message.");
41
+ const message = JSON.parse(json);
42
+ if (!message || typeof message !== "object" || Array.isArray(message))
43
+ throw new Error("Workflow process sent an invalid IPC message.");
44
+ this.emit("message", message);
45
+ }
46
+ catch (error) {
47
+ this.emit("error", error);
48
+ }
49
+ });
50
+ this.child.on("exit", (code) => {
51
+ this.exitCode = code ?? 1;
52
+ this.child.stderr.destroy();
53
+ if (!this.stopping && code !== 0 && this.stderr.trim())
54
+ this.emit("error", new Error(this.stderr.trim()));
55
+ this.emit("exit", this.exitCode);
56
+ });
57
+ }
58
+ postMessage(message) {
59
+ if (this.stopping || !this.child.connected)
60
+ return;
61
+ this.child.send(JSON.stringify(message), (error) => {
62
+ if (error && !this.stopping)
63
+ this.emit("error", error);
64
+ });
65
+ }
66
+ async terminate() {
67
+ if (this.exitCode !== undefined)
68
+ return this.exitCode;
69
+ this.stopping = true;
70
+ return await new Promise((resolve) => {
71
+ this.once("exit", resolve);
72
+ this.child.kill("SIGKILL");
73
+ });
74
+ }
75
+ }
76
+ export function createWorkflowScriptWorker(acornPath) {
77
+ // Bun has no permission model. Keep its existing file worker; do not claim process isolation there.
78
+ return typeof process.versions.bun === "string"
79
+ ? new Worker(WORKFLOW_WORKER_URL, { workerData: { acornPath } })
80
+ : new WorkflowScriptProcess(acornPath);
81
+ }
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+
3
+ const { Worker } = require("node:worker_threads");
4
+ const { join } = require("node:path");
5
+
6
+ // Windows process creation adds a standard environment even when fork receives an empty one.
7
+ for (const key of Object.keys(process.env)) {
8
+ if (process.platform !== "win32" || key.toLowerCase() !== "systemroot") delete process.env[key];
9
+ }
10
+
11
+ // Keep IPC on this thread: a busy workflow must not prevent parent-disconnect cleanup.
12
+ // The script thread has no worker permission; filesystem grants are inherited from the process.
13
+ const worker = new Worker(join(__dirname, "workflow-script-worker.cjs"), {
14
+ workerData: { acornPath: process.argv[2] },
15
+ execArgv: process.execArgv.filter((arg) => arg !== "--allow-worker"),
16
+ });
17
+
18
+ function fail(error) {
19
+ if (!process.connected) return process.exit(1);
20
+ process.send(JSON.stringify({ type: "error", errorKind: "runtime", error: String(error?.message ?? error) }), () => process.exit(1));
21
+ }
22
+
23
+ process.on("disconnect", () => process.exit(0));
24
+ process.on("message", (json) => {
25
+ try {
26
+ if (typeof json !== "string") throw new Error("Workflow process received a non-string IPC message.");
27
+ worker.postMessage(JSON.parse(json));
28
+ } catch (error) { fail(error); }
29
+ });
30
+ worker.on("message", (message) => {
31
+ try {
32
+ process.send(JSON.stringify(message), (error) => { if (error) process.exit(1); });
33
+ } catch (error) { fail(error); }
34
+ });
35
+ worker.on("error", fail);
36
+ worker.on("exit", (code) => fail(new Error(`Workflow script thread exited before returning a result (code ${code}).`)));
@@ -703,7 +703,10 @@ function describeGateAcceptanceConflict(gate, acceptance) {
703
703
  }
704
704
 
705
705
  function validateRunCall(key, params, label, fingerprints) {
706
- if (typeof key !== "string" || !runKeyPattern.test(key)) throw new Error(label + " has an invalid key.");
706
+ if (typeof key !== "string" || !runKeyPattern.test(key)) {
707
+ const problem = key === undefined ? " has no key" : typeof key === "string" ? " has an invalid key '" + (key.length > 80 ? key.slice(0, 80) + "..." : key) + "'" : " has a key of type " + (key === null ? "null" : typeof key);
708
+ throw new Error(label + problem + "; keys must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.");
709
+ }
707
710
  if (hostKeys.has(key)) throw new Error("Workflow key '" + key + "' is already used by runs.host.");
708
711
  if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error(label + " requires a params object.");
709
712
  if (Object.prototype.hasOwnProperty.call(params, "action") || Object.prototype.hasOwnProperty.call(params, "workflowScript") || Object.prototype.hasOwnProperty.call(params, "globalConcurrencyLimit") || Object.prototype.hasOwnProperty.call(params, "maxSubagentSpawnsPerRun") || Object.prototype.hasOwnProperty.call(params, "tasks") || Object.prototype.hasOwnProperty.call(params, "chain") || Object.prototype.hasOwnProperty.call(params, "parallel") || Object.prototype.hasOwnProperty.call(params, "concurrency") || Object.prototype.hasOwnProperty.call(params, "chainDir")) {