pi-subagents 0.84.0 → 0.86.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 (210) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-JG4QKI5M.js → chunk-2IYBCYFU.js} +214 -97
  5. package/bundle/{chunk-V2BZYLEP.js → chunk-374MZFF4.js} +7 -2
  6. package/bundle/{chunk-4E7BKDTX.js → chunk-3RKFH2UZ.js} +11 -156
  7. package/bundle/{chunk-F4ASL6OV.js → chunk-5H4BICQZ.js} +1 -1
  8. package/bundle/{chunk-PALJGGYC.js → chunk-6VD7BGIC.js} +6 -3
  9. package/bundle/{chunk-C5P5CHYK.js → chunk-77ASNIEM.js} +1 -1
  10. package/bundle/{chunk-XDQORLZ5.js → chunk-7ADDXUGF.js} +15 -6
  11. package/bundle/{chunk-PV63UFUR.js → chunk-7QA7ZA46.js} +183 -28
  12. package/bundle/{chunk-NKQ6JNAS.js → chunk-7ZUFN6ME.js} +2 -1
  13. package/bundle/{chunk-SSG7IEP5.js → chunk-A637IMAO.js} +2 -2
  14. package/bundle/{chunk-L3WFKBEI.js → chunk-BGXEAYUM.js} +247 -153
  15. package/bundle/{chunk-J5YL7LYR.js → chunk-BU6PFPVX.js} +59 -27
  16. package/bundle/{chunk-DZDETGRJ.js → chunk-BWC2LVII.js} +259 -216
  17. package/bundle/{chunk-CGN2TVE7.js → chunk-GJGTMLPE.js} +322 -18
  18. package/bundle/{chunk-D3JAFGMO.js → chunk-GRJHIXYF.js} +1 -1
  19. package/bundle/chunk-HXRB42AF.js +108 -0
  20. package/bundle/{chunk-LFDBD4PW.js → chunk-LGINOOY5.js} +2 -2
  21. package/bundle/{chunk-G2Z6ZH26.js → chunk-NAFLUJ26.js} +1 -1
  22. package/bundle/{chunk-235AWJUQ.js → chunk-O3YH7XIY.js} +324 -111
  23. package/bundle/{chunk-2DHZTCOL.js → chunk-PYOAIN3V.js} +2 -2
  24. package/bundle/{chunk-LNRJCP2Y.js → chunk-QGO6HXHG.js} +417 -242
  25. package/bundle/{chunk-VQVVHSY6.js → chunk-QM3JGE4W.js} +22 -11
  26. package/bundle/{chunk-2S4K53MV.js → chunk-S2Q75LP3.js} +1 -1
  27. package/bundle/{chunk-NENDSQUY.js → chunk-UR7OW5S7.js} +9 -6
  28. package/bundle/{chunk-AKOIVLA5.js → chunk-WN2E5XHN.js} +135 -77
  29. package/bundle/{chunk-2D52JFLF.js → chunk-YK3QYNLE.js} +41 -117
  30. package/bundle/{chunk-7BWGNDNK.js → chunk-ZJJCPV3L.js} +190 -1177
  31. package/bundle/chunk-ZPY5QZCS.js +1067 -0
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +8 -8
  36. package/bundle/project-panes.js +3 -3
  37. package/docs/agents.md +23 -2
  38. package/docs/configuration.md +4 -4
  39. package/docs/extension-api.md +16 -1
  40. package/docs/tool-reference.md +2 -0
  41. package/docs/workflows.md +30 -2
  42. package/package.json +1 -1
  43. package/src/agents/agent-management.js +27 -11
  44. package/src/agents/agent-memory.d.ts +1 -4
  45. package/src/agents/agent-memory.js +1 -4
  46. package/src/agents/agents.d.ts +1 -3
  47. package/src/agents/agents.js +7 -6
  48. package/src/agents/frontmatter.js +1 -8
  49. package/src/agents/global-npm-root.d.ts +1 -0
  50. package/src/agents/global-npm-root.js +11 -3
  51. package/src/agents/skills.d.ts +0 -3
  52. package/src/agents/skills.js +0 -3
  53. package/src/extension/config.js +7 -1
  54. package/src/extension/herdr-pi-bridge.js +10 -2
  55. package/src/extension/index.d.ts +0 -13
  56. package/src/extension/index.js +43 -32
  57. package/src/extension/public-execution.d.ts +1 -0
  58. package/src/extension/public-execution.js +4 -0
  59. package/src/extension/reply-workflow-script.js +24 -4
  60. package/src/extension/schemas.d.ts +8 -3
  61. package/src/extension/schemas.js +5 -3
  62. package/src/extension/session-switch.d.ts +25 -0
  63. package/src/extension/session-switch.js +138 -0
  64. package/src/extension/subagent-guide.d.ts +1 -1
  65. package/src/extension/subagent-guide.js +1 -1
  66. package/src/extension/subagent-launch-tool.d.ts +25 -0
  67. package/src/extension/subagent-launch-tool.js +48 -0
  68. package/src/extension/tool-activation.js +35 -12
  69. package/src/extension/tool-description.d.ts +1 -1
  70. package/src/extension/tool-description.js +14 -8
  71. package/src/inspectors/herdr/actions.d.ts +0 -1
  72. package/src/inspectors/herdr/actions.js +0 -1
  73. package/src/inspectors/session-roots-codec.d.ts +0 -1
  74. package/src/inspectors/session-roots-codec.js +0 -1
  75. package/src/inspectors/tmux/actions.d.ts +0 -1
  76. package/src/inspectors/tmux/actions.js +0 -1
  77. package/src/integrations/herdr-status.js +3 -8
  78. package/src/intercom/native-supervisor-channel.js +65 -9
  79. package/src/runs/background/async-execution.d.ts +5 -9
  80. package/src/runs/background/async-execution.js +62 -27
  81. package/src/runs/background/async-job-tracker.js +12 -0
  82. package/src/runs/background/async-resume.d.ts +2 -1
  83. package/src/runs/background/async-resume.js +112 -39
  84. package/src/runs/background/async-retention.js +6 -1
  85. package/src/runs/background/auto-drain.js +2 -1
  86. package/src/runs/background/boot-id.d.ts +1 -3
  87. package/src/runs/background/boot-id.js +1 -3
  88. package/src/runs/background/completion-batcher.d.ts +3 -4
  89. package/src/runs/background/completion-batcher.js +2 -3
  90. package/src/runs/background/control-channel.d.ts +0 -6
  91. package/src/runs/background/control-channel.js +0 -6
  92. package/src/runs/background/fleet-view.js +2 -3
  93. package/src/runs/background/notify.d.ts +0 -2
  94. package/src/runs/background/notify.js +0 -2
  95. package/src/runs/background/result-watcher.d.ts +1 -0
  96. package/src/runs/background/result-watcher.js +59 -29
  97. package/src/runs/background/resume-guidance.js +4 -2
  98. package/src/runs/background/retained-children.js +2 -1
  99. package/src/runs/background/run-child-session.d.ts +0 -1
  100. package/src/runs/background/run-child-session.js +1 -1
  101. package/src/runs/background/run-status.js +9 -7
  102. package/src/runs/background/scheduled-runs.d.ts +3 -1
  103. package/src/runs/background/scheduled-runs.js +13 -16
  104. package/src/runs/background/subagent-runner.d.ts +2 -4
  105. package/src/runs/background/subagent-runner.js +15 -12
  106. package/src/runs/background/subagent-wait.js +12 -15
  107. package/src/runs/background/wait-config.d.ts +2 -0
  108. package/src/runs/background/wait-config.js +17 -3
  109. package/src/runs/background/wait-tool.js +4 -2
  110. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  111. package/src/runs/background/workflow-terminal-proof.js +0 -1
  112. package/src/runs/foreground/execution.d.ts +0 -3
  113. package/src/runs/foreground/execution.js +17 -9
  114. package/src/runs/foreground/subagent-executor.d.ts +3 -2
  115. package/src/runs/foreground/subagent-executor.js +107 -26
  116. package/src/runs/shared/acceptance.js +69 -26
  117. package/src/runs/shared/child-commands.js +15 -2
  118. package/src/runs/shared/child-hooks.d.ts +1 -7
  119. package/src/runs/shared/child-hooks.js +13 -5
  120. package/src/runs/shared/child-launch.js +6 -2
  121. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  122. package/src/runs/shared/child-session.d.ts +1 -1
  123. package/src/runs/shared/child-session.js +21 -2
  124. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  125. package/src/runs/shared/child-tool-plan.js +0 -1
  126. package/src/runs/shared/claude-code-adapter.js +11 -0
  127. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  128. package/src/runs/shared/external-cli-contract.js +18 -13
  129. package/src/runs/shared/external-cli-runner.js +26 -6
  130. package/src/runs/shared/herdr-connection.js +2 -1
  131. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  132. package/src/runs/shared/herdr-pane-host.js +17 -1
  133. package/src/runs/shared/herdr-placed-run.js +48 -22
  134. package/src/runs/shared/lane-metadata.d.ts +0 -1
  135. package/src/runs/shared/lane-metadata.js +0 -1
  136. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  137. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  138. package/src/runs/shared/model-resolution.d.ts +2 -2
  139. package/src/runs/shared/model-resolution.js +7 -1
  140. package/src/runs/shared/model-scope.d.ts +1 -5
  141. package/src/runs/shared/model-scope.js +1 -5
  142. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  143. package/src/runs/shared/mutation-evidence.js +52 -7
  144. package/src/runs/shared/nested-events.d.ts +1 -0
  145. package/src/runs/shared/nested-events.js +1 -1
  146. package/src/runs/shared/parallel-utils.d.ts +0 -1
  147. package/src/runs/shared/permissions.js +5 -3
  148. package/src/runs/shared/placement-host.d.ts +5 -1
  149. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  150. package/src/runs/shared/rex-pane-host.js +0 -2
  151. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  152. package/src/runs/shared/run-launch-folder.js +21 -0
  153. package/src/runs/shared/runner-launcher.d.ts +12 -1
  154. package/src/runs/shared/runner-launcher.js +16 -0
  155. package/src/runs/shared/single-output.d.ts +3 -3
  156. package/src/runs/shared/single-output.js +5 -3
  157. package/src/runs/shared/structured-output.d.ts +8 -0
  158. package/src/runs/shared/structured-output.js +40 -5
  159. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  160. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  161. package/src/runs/shared/tool-timeout.js +2 -1
  162. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  163. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  164. package/src/runs/shared/worktree.d.ts +3 -0
  165. package/src/runs/shared/worktree.js +20 -0
  166. package/src/shared/capacity-resilient-json.d.ts +1 -1
  167. package/src/shared/child-cache-retention.d.ts +1 -2
  168. package/src/shared/child-cache-retention.js +1 -2
  169. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  170. package/src/shared/fleet-transcript-reader.js +333 -0
  171. package/src/shared/formatters.d.ts +0 -18
  172. package/src/shared/formatters.js +0 -18
  173. package/src/shared/session-succession.d.ts +16 -1
  174. package/src/shared/session-succession.js +41 -2
  175. package/src/shared/session-warnings.d.ts +7 -0
  176. package/src/shared/session-warnings.js +26 -0
  177. package/src/shared/settings.d.ts +0 -23
  178. package/src/shared/settings.js +3 -35
  179. package/src/shared/types.d.ts +85 -59
  180. package/src/shared/types.js +0 -12
  181. package/src/shared/utils.d.ts +0 -14
  182. package/src/shared/utils.js +0 -22
  183. package/src/shared/wait-tool-name.d.ts +8 -0
  184. package/src/shared/wait-tool-name.js +13 -0
  185. package/src/slash/slash-commands.js +2 -1
  186. package/src/slash/subagent-cost.d.ts +3 -2
  187. package/src/slash/subagent-cost.js +22 -3
  188. package/src/slash/subagents-admin.js +0 -1
  189. package/src/tui/fleet-status.d.ts +0 -5
  190. package/src/tui/fleet-status.js +4 -24
  191. package/src/tui/fleet-transcript.d.ts +1 -44
  192. package/src/tui/fleet-transcript.js +1 -327
  193. package/src/tui/fleet.js +6 -4
  194. package/src/tui/render.d.ts +0 -9
  195. package/src/tui/render.js +161 -66
  196. package/src/tui/subagent-messages.js +3 -2
  197. package/src/watchdog/register-child.d.ts +2 -3
  198. package/src/watchdog/register-child.js +2 -3
  199. package/src/watchdog/turn-delta.js +2 -1
  200. package/src/workflows/scripted-workflow.js +241 -20
  201. package/src/workflows/workflow-launch-record.d.ts +15 -6
  202. package/src/workflows/workflow-launch-record.js +30 -12
  203. package/src/workflows/workflow-receipt.js +36 -53
  204. package/src/workflows/workflow-resume-claim.js +2 -2
  205. package/src/workflows/workflow-resume.d.ts +1 -1
  206. package/src/workflows/workflow-resume.js +11 -8
  207. package/src/workflows/workflow-script-worker.d.ts +13 -0
  208. package/src/workflows/workflow-script-worker.js +79 -0
  209. package/workflow-script-process.cjs +36 -0
  210. package/workflow-script-worker.cjs +4 -1
@@ -1,10 +1,11 @@
1
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
- import { Worker } from "node:worker_threads";
4
+ import { createWorkflowScriptWorker } from "./workflow-script-worker.js";
5
5
  import { DEFAULT_GLOBAL_CONCURRENCY_LIMIT, Semaphore } from "../runs/shared/parallel-utils.js";
6
6
  import { HOST_STEP_MAX_COUNT } from "../runs/shared/host-step-status.js";
7
7
  import { describeGateAcceptanceConflict, parseGateInput } from "../runs/shared/acceptance.js";
8
+ import { REQUIRE_LAUNCHER_SHAPE_ERROR } from "../runs/shared/runner-launcher.js";
8
9
  import { normalizeWorkflowHostCommandParams } from "./host-command.js";
9
10
  const KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
10
11
  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.";
@@ -19,8 +20,6 @@ function validGitRef(ref) {
19
20
  }
20
21
  const requireFromPackage = createRequire(import.meta.url);
21
22
  const WORKFLOW_ASSEMBLY_FLUSH_TIMEOUT_MS = 5_000;
22
- const WORKFLOW_WORKER_URL = new URL("../../workflow-script-worker.cjs", import.meta.url);
23
- let nodeWorkerSource;
24
23
  function isWorkflowScriptFailureKind(value) {
25
24
  return value === "validation" || value === "script" || value === "child" || value === "return-serialization" || value === "timeout" || value === "detached-child" || value === "runtime";
26
25
  }
@@ -95,8 +94,182 @@ const RECOVERY_REVIEW_NO_ANAPHORIC_MUTATION_CLAUSE_PATTERN = /\b(?:do not|don't|
95
94
  const RECOVERY_REVIEW_NO_DELEGATION_CLAUSE_PATTERN = /\b(?:do not|don't|must not)\s+(?:(?:launch|start|spawn|run)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:workers?|reviewers?|agents?|subagents?|children|child|runs?)|(?:get|let|request|hand\s+off|assign|use|have|tell)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:workers?|reviewers?|agents?|subagents?|children|child)|(?:get|let|have|tell|request)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:review|implementation|fix(?:es)?|changes?|follow-up)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*\b(?:from|with|via|by)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:workers?|reviewers?|agents?|subagents?|children|child)|ask\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:(?:workers?|reviewers?|agents?|subagents?|children|child)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*\b(?:continue|implement|review|fix|edit|write|modify|change|patch|update|delete|remove|create|follow-up)|(?:review|implementation|fix(?:es)?|changes?|follow-up)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*\b(?:from|via)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:workers?|reviewers?|agents?|subagents?|children|child)))\b/gi;
96
95
  const RECOVERY_REVIEW_DELEGATION_PATTERN = /\b(?:launch|start|spawn|run)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child|runs?)\b|\b(?:delegate|hand\s+off|assign)\s+(?:remediation|implementation(?:\s+follow-up)?|changes?|fix(?:es)?|follow-up)\s+to\s+(?:(?:a|an|the)\s+)?(?:workers?|reviewers?|agents?|subagents?|children|child)\b|\b(?:get|let|have|tell|request)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child)\b[^,.;!?\n]*\b(?:continue|implement|review|fix|edit|write|modify|change|patch|update|delete|remove|create|follow-up)\b|\b(?:get|let|have|tell|request)\b[^,.;!?\n]*(?:review|implementation|fix(?:es)?|changes?|follow-up)\b[^,.;!?\n]*\b(?:from|with|via|by)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child)\b|\bask\b[^,.;!?\n]*(?:(?:workers?|reviewers?|agents?|subagents?|children|child)\b[^,.;!?\n]*\b(?:continue|implement|review|fix|edit|write|modify|change|patch|update|delete|remove|create|follow-up)|(?:review|implementation|fix(?:es)?|changes?|follow-up)\b[^,.;!?\n]*\b(?:from|via)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child))\b|\buse\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child|runs?)\s+(?:for|to)\s+(?:implementation|follow-up|remediation|fix|edit|write|modify|change|patch|update|delete|remove|create)\b/i;
97
96
  const RECOVERY_REVIEW_ANAPHORIC_MUTATION_PATTERN = /\b(?:do|run|execute|perform|apply)\s+(?:it|that|this|(?:the\s+)?(?:(?:\d+(?:st|nd|rd|th)|first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|last|next|previous(?:ly)?|prior|above|quoted|blocked)\s+){0,4}(?:command|example|operation|action|phrase|instruction|request|one))(?!(?:\s+(?:(?:now|still|also|already)\s+)*(?:is|are|remains?)\s+blocked\b))(?:(?:[\s,]+\w+){0,4}[\s,]+anyway|(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n]){0,80})(?=\s*(?:[,.;!?\n)]|\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b|$))/i;
98
- const RECOVERY_REVIEW_DESTRUCTIVE_COMMAND_PATTERN = /(?:^|[\s;,.`'"([{])(?:\S*\/)?(?:rm|rmdir|unlink|truncate|mv|cp|chmod|chown)\b|\bgit\b(?:\s+(?:-[A-Za-z](?:\s+(?:"[^"\n]*"|'[^'\n]*'|\S+))?|--(?:git-dir|work-tree|namespace|exec-path|config-env)(?:=(?:"[^"\n]*"|'[^'\n]*'|\S+)|\s+(?:"[^"\n]*"|'[^'\n]*'|\S+))|--[A-Za-z0-9-]+(?:=(?:"[^"\n]*"|'[^'\n]*'|\S+))?))*\s+(?:add|branch|cherry-pick|clean|commit|merge|rebase|reset|restore|revert|stash|tag|checkout|switch)\b/i;
99
- const RECOVERY_REVIEW_DASH_LIVE_ACTION_PATTERN = /(?:[—–]|--|\s-\s|:|\s\/\s)\s*(?:then\s+)?(?:(?:add|append|apply|change|cherry[ -]pick|clean|commit|copy|create|delete|edit|fix|implement|insert|make|merge|move|modify|mutate|open|patch|prepend|push|rebase|refactor|remove|rename|replace|revert|revise|rewrite|save|stage|stash|tag|touch|update|write)\b|(?:launch|start|spawn|run)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child|runs?)\b|(?:\S*\/)?(?:rm|rmdir|unlink|truncate|mv|cp|chmod|chown)\b|git\b[^,.;!?\n]*\b(?:add|branch|cherry-pick|clean|commit|merge|rebase|reset|restore|revert|stash|tag|checkout|switch)\b)/i;
97
+ // A path need not cross another command-start separator: the same command can match from
98
+ // the last such separator before its slash. Excluding those characters from the path prefix
99
+ // preserves detection while preventing overlapping starts from rescanning the same suffix.
100
+ const RECOVERY_REVIEW_MUTATING_PATH_COMMAND_PATTERN = /(?:^|[\s;,.`'"([{])(?:[^\s;,.`'"([{]*\/)?(?:rm|rmdir|unlink|truncate|mv|cp|chmod|chown)\b/i;
101
+ const RECOVERY_REVIEW_WORD_CHARACTER_PATTERN = /^\w$/;
102
+ // Each branch after a separator is checked at its own anchor, and what it needs from the rest of the
103
+ // line or path comes from tables built in one backward pass, so many separators never rescan a suffix.
104
+ const RECOVERY_REVIEW_DASH_SEPARATOR_AT_PATTERN = /(?:[—–]|--|\s-\s|:|\s\/\s)/iy;
105
+ const RECOVERY_REVIEW_DASH_SEPARATOR_EXISTS_PATTERN = /(?:[—–]|--|\s-\s|:|\s\/\s)/i;
106
+ const RECOVERY_REVIEW_DASH_ACTION_AT_PATTERN = /(?:add|append|apply|change|cherry[ -]pick|clean|commit|copy|create|delete|edit|fix|implement|insert|make|merge|move|modify|mutate|open|patch|prepend|push|rebase|refactor|remove|rename|replace|revert|revise|rewrite|save|stage|stash|tag|touch|update|write)\b/iy;
107
+ const RECOVERY_REVIEW_DASH_LAUNCH_AT_PATTERN = /(?:launch|start|spawn|run)\b/iy;
108
+ const RECOVERY_REVIEW_DASH_WORKER_AT_PATTERN = /(?:workers?|reviewers?|agents?|subagents?|children|child|runs?)\b/iy;
109
+ const RECOVERY_REVIEW_DASH_GIT_AT_PATTERN = /git\b/iy;
110
+ const RECOVERY_REVIEW_DASH_GIT_COMMAND_AT_PATTERN = /\b(?:add|branch|cherry-pick|clean|commit|merge|rebase|reset|restore|revert|stash|tag|checkout|switch)\b/iy;
111
+ const RECOVERY_REVIEW_DASH_FILE_COMMAND_AT_PATTERN = /(?:rm|rmdir|unlink|truncate|mv|cp|chmod|chown)\b/iy;
112
+ const RECOVERY_REVIEW_DASH_THEN_AT_PATTERN = /then/iy;
113
+ const RECOVERY_REVIEW_DASH_LINE_STOP_CHARACTERS = ",.;!?\n";
114
+ const RECOVERY_REVIEW_WHITESPACE_CHARACTER_PATTERN = /^\s$/;
115
+ // Sticky patterns: lastIndex anchors each check. No check yields, so the shared lastIndex cannot interleave.
116
+ function matchesDashBranchAt(pattern, text, index) {
117
+ pattern.lastIndex = index;
118
+ return pattern.test(text);
119
+ }
120
+ function dashBranchLengthAt(pattern, text, index) {
121
+ pattern.lastIndex = index;
122
+ const match = pattern.exec(text);
123
+ return match === null ? 0 : match[0].length;
124
+ }
125
+ function skipDashSeparatorWhitespace(text, index) {
126
+ while (index < text.length && RECOVERY_REVIEW_WHITESPACE_CHARACTER_PATTERN.test(text.charAt(index)))
127
+ index++;
128
+ return index;
129
+ }
130
+ // workerAhead[i] says whether the rest of the line still holds the worker word, gitCommandAhead[i]
131
+ // the same for a git command, and pathCommandAhead[i] whether the rest of the path holds a file
132
+ // command behind a slash.
133
+ function acceptsDashLiveActionAt(text, index, workerAhead, gitCommandAhead, pathCommandAhead) {
134
+ if (matchesDashBranchAt(RECOVERY_REVIEW_DASH_ACTION_AT_PATTERN, text, index))
135
+ return true;
136
+ const launchLength = dashBranchLengthAt(RECOVERY_REVIEW_DASH_LAUNCH_AT_PATTERN, text, index);
137
+ if (launchLength > 0 && workerAhead[index + launchLength] === 1)
138
+ return true;
139
+ if (matchesDashBranchAt(RECOVERY_REVIEW_DASH_FILE_COMMAND_AT_PATTERN, text, index) || pathCommandAhead[index] === 1)
140
+ return true;
141
+ return matchesDashBranchAt(RECOVERY_REVIEW_DASH_GIT_AT_PATTERN, text, index) && gitCommandAhead[index + 3] === 1;
142
+ }
143
+ function mentionsDashLiveAction(text) {
144
+ if (!RECOVERY_REVIEW_DASH_SEPARATOR_EXISTS_PATTERN.test(text))
145
+ return false;
146
+ const workerAhead = new Uint8Array(text.length + 1);
147
+ const gitCommandAhead = new Uint8Array(text.length + 1);
148
+ const pathCommandAhead = new Uint8Array(text.length + 1);
149
+ for (let index = text.length - 1; index >= 0; index--) {
150
+ const character = text.charAt(index);
151
+ const lineCharacter = !RECOVERY_REVIEW_DASH_LINE_STOP_CHARACTERS.includes(character);
152
+ const pathCharacter = !RECOVERY_REVIEW_WHITESPACE_CHARACTER_PATTERN.test(character);
153
+ workerAhead[index] = matchesDashBranchAt(RECOVERY_REVIEW_DASH_WORKER_AT_PATTERN, text, index) || (lineCharacter && workerAhead[index + 1] === 1) ? 1 : 0;
154
+ gitCommandAhead[index] = matchesDashBranchAt(RECOVERY_REVIEW_DASH_GIT_COMMAND_AT_PATTERN, text, index) || (lineCharacter && gitCommandAhead[index + 1] === 1) ? 1 : 0;
155
+ pathCommandAhead[index] = (character === "/" && matchesDashBranchAt(RECOVERY_REVIEW_DASH_FILE_COMMAND_AT_PATTERN, text, index + 1)) || (pathCharacter && pathCommandAhead[index + 1] === 1) ? 1 : 0;
156
+ }
157
+ for (let index = 0; index < text.length; index++) {
158
+ const separatorLength = dashBranchLengthAt(RECOVERY_REVIEW_DASH_SEPARATOR_AT_PATTERN, text, index);
159
+ if (separatorLength === 0)
160
+ continue;
161
+ // \s* and then\s+ only cross whitespace, and no branch starts with whitespace, so the end
162
+ // of that whitespace run is the only anchor a branch can match at.
163
+ const anchor = skipDashSeparatorWhitespace(text, index + separatorLength);
164
+ if (acceptsDashLiveActionAt(text, anchor, workerAhead, gitCommandAhead, pathCommandAhead))
165
+ return true;
166
+ if (!matchesDashBranchAt(RECOVERY_REVIEW_DASH_THEN_AT_PATTERN, text, anchor))
167
+ continue;
168
+ const afterThen = skipDashSeparatorWhitespace(text, anchor + 4);
169
+ if (afterThen > anchor + 4 && acceptsDashLiveActionAt(text, afterThen, workerAhead, gitCommandAhead, pathCommandAhead))
170
+ return true;
171
+ }
172
+ return false;
173
+ }
174
+ // This is the git branch of the dash-live check, not a shell parser. afterOption and
175
+ // afterSpace implement (\s+OPTION)*\s+; short/special options can also take \s+V,
176
+ // generic long options only =V. V keeps "[^"\n]*", '[^'\n]*' and \S+ alive together.
177
+ function createMutatingGitStates() {
178
+ const state = () => ({ edges: [], epsilon: [] });
179
+ const edge = (from, character, next) => {
180
+ from.edges.push({ character, next });
181
+ };
182
+ const literal = (from, word, end) => {
183
+ for (let index = 0; index < word.length; index++) {
184
+ const next = index === word.length - 1 ? end : state();
185
+ edge(from, new RegExp(word.charAt(index), "i"), next);
186
+ from = next;
187
+ }
188
+ };
189
+ const start = state();
190
+ const accept = state();
191
+ const afterOption = state();
192
+ const afterSpace = state();
193
+ literal(start, "git", afterOption);
194
+ edge(afterOption, /\s/, afterSpace);
195
+ edge(afterSpace, /\s/, afterSpace);
196
+ for (const command of ["add", "branch", "cherry-pick", "clean", "commit", "merge", "rebase", "reset", "restore", "revert", "stash", "tag", "checkout", "switch"]) {
197
+ literal(afterSpace, command, accept);
198
+ }
199
+ const value = state();
200
+ const beforeSeparatedValue = state();
201
+ const separatedValue = state();
202
+ edge(beforeSeparatedValue, /\s/, separatedValue);
203
+ edge(separatedValue, /\s/, separatedValue);
204
+ separatedValue.epsilon.push(value);
205
+ const shortDash = state();
206
+ const shortOption = state();
207
+ literal(afterSpace, "-", shortDash);
208
+ edge(shortDash, /[A-Za-z]/, shortOption);
209
+ shortOption.epsilon.push(afterOption, beforeSeparatedValue);
210
+ const longStart = state();
211
+ const longName = state();
212
+ literal(shortDash, "-", longStart);
213
+ edge(longStart, /[A-Za-z0-9-]/, longName);
214
+ edge(longName, /[A-Za-z0-9-]/, longName);
215
+ longName.epsilon.push(afterOption);
216
+ edge(longName, /=/, value);
217
+ for (const option of ["git-dir", "work-tree", "namespace", "exec-path", "config-env"]) {
218
+ const specialOption = state();
219
+ literal(longStart, option, specialOption);
220
+ edge(specialOption, /=/, value);
221
+ specialOption.epsilon.push(beforeSeparatedValue);
222
+ }
223
+ for (const [quote, body] of [[/"/, /[^"\n]/], [/'/, /[^'\n]/]]) {
224
+ const quotedValue = state();
225
+ edge(value, quote, quotedValue);
226
+ edge(quotedValue, body, quotedValue);
227
+ edge(quotedValue, quote, afterOption);
228
+ }
229
+ const plainValue = state();
230
+ edge(value, /\S/, plainValue);
231
+ edge(plainValue, /\S/, plainValue);
232
+ plainValue.epsilon.push(afterOption);
233
+ return { start, accept };
234
+ }
235
+ const MUTATING_GIT_STATES = createMutatingGitStates();
236
+ function mentionsMutatingGitCommand(text) {
237
+ let active = new Set();
238
+ let next = new Set();
239
+ const addState = (states, state) => {
240
+ if (states.has(state))
241
+ return;
242
+ states.add(state);
243
+ for (const reachable of state.epsilon)
244
+ addState(states, reachable);
245
+ };
246
+ // Inject starts even inside another candidate's value. Deduplicating states at each UTF-16
247
+ // position preserves every reading without backtracking or suffix rescans: O(n*m) time and
248
+ // O(m) space for this fixed graph of m states. /i (without /u) uses ASCII word boundaries.
249
+ for (let position = 0; position <= text.length; position++) {
250
+ const character = text.charAt(position);
251
+ const previousIsWord = RECOVERY_REVIEW_WORD_CHARACTER_PATTERN.test(text.charAt(position - 1));
252
+ const currentIsWord = RECOVERY_REVIEW_WORD_CHARACTER_PATTERN.test(character);
253
+ if (active.has(MUTATING_GIT_STATES.accept) && previousIsWord !== currentIsWord)
254
+ return true;
255
+ if (!previousIsWord)
256
+ addState(active, MUTATING_GIT_STATES.start);
257
+ if (position === text.length)
258
+ break;
259
+ next.clear();
260
+ for (const state of active) {
261
+ for (const edge of state.edges) {
262
+ if (edge.character.test(character))
263
+ addState(next, edge.next);
264
+ }
265
+ }
266
+ [active, next] = [next, active];
267
+ }
268
+ return false;
269
+ }
270
+ function mentionsMutatingCommand(text) {
271
+ return RECOVERY_REVIEW_MUTATING_PATH_COMMAND_PATTERN.test(text) || mentionsMutatingGitCommand(text);
272
+ }
100
273
  function isExplicitReadOnlyRecoveryReview(params) {
101
274
  const agent = typeof params.agent === "string" ? params.agent.trim() : "";
102
275
  const task = typeof params.task === "string" ? params.task.trim() : "";
@@ -173,12 +346,12 @@ function isExplicitReadOnlyRecoveryReview(params) {
173
346
  && agent !== ""
174
347
  && /\b(?:advisor|oracle|review|reviewer)\b/i.test(agent)
175
348
  && RECOVERY_REVIEW_READ_ONLY_PATTERN.test(task)
176
- && !RECOVERY_REVIEW_DESTRUCTIVE_COMMAND_PATTERN.test(taskDestructiveCommandText)
349
+ && !mentionsMutatingCommand(taskDestructiveCommandText)
177
350
  && !RECOVERY_REVIEW_MUTATION_VERB_PATTERN.test(taskMutationText)
178
351
  && !RECOVERY_REVIEW_DELEGATION_PATTERN.test(taskMutationText)
179
352
  && !RECOVERY_REVIEW_ANAPHORIC_MUTATION_PATTERN.test(taskMutationText)
180
- && !RECOVERY_REVIEW_DESTRUCTIVE_COMMAND_PATTERN.test(taskMutationText)
181
- && !RECOVERY_REVIEW_DASH_LIVE_ACTION_PATTERN.test(taskDashLiveActionText);
353
+ && !mentionsMutatingCommand(taskMutationText)
354
+ && !mentionsDashLiveAction(taskDashLiveActionText);
182
355
  }
183
356
  function recoveryBarrierMessage(sourceKey, target) {
184
357
  return `Run '${target}' cannot launch after run '${sourceKey}' returned rejected acceptance recovery; only explicit read-only review children with acceptance:false may follow.`;
@@ -620,6 +793,41 @@ function directRunsAllKeys(call) {
620
793
  return keyNode && key !== undefined ? [{ key, node: keyNode }] : [];
621
794
  });
622
795
  }
796
+ /** runs.all items certain to reach the runtime without a key: plain literals in the array, or the one result of a map callback. */
797
+ function keylessRunsAllItems(call) {
798
+ const args = Array.isArray(call.arguments) ? call.arguments : [];
799
+ const items = args[0];
800
+ if (!astNode(items))
801
+ return [];
802
+ if (items.type === "ArrayExpression" && Array.isArray(items.elements)) {
803
+ return items.elements.flatMap((item, index) => keylessItemLiteral(item) ? [{ node: item, index }] : []);
804
+ }
805
+ const callee = items.type === "CallExpression" && astNode(items.callee) && items.callee.type === "MemberExpression" && items.callee.computed !== true ? items.callee : undefined;
806
+ if (!callee || !astNode(callee.property) || callee.property.type !== "Identifier" || callee.property.name !== "map")
807
+ return [];
808
+ const callback = Array.isArray(items.arguments) ? items.arguments[0] : undefined;
809
+ if (!astNode(callback) || (callback.type !== "ArrowFunctionExpression" && callback.type !== "FunctionExpression") || !astNode(callback.body))
810
+ return [];
811
+ let result = callback.body;
812
+ if (callback.body.type === "BlockStatement" && Array.isArray(callback.body.body)) {
813
+ // Only a callback whose single return is its last statement always returns that literal.
814
+ const returns = [];
815
+ walkAst(callback.body, (node) => { if (node.type === "ReturnStatement")
816
+ returns.push(node); }, false);
817
+ result = returns.length === 1 && returns[0] === callback.body.body.at(-1) ? returns[0].argument : undefined;
818
+ }
819
+ return keylessItemLiteral(result) ? [{ node: result }] : [];
820
+ }
821
+ /**
822
+ * An object literal whose own keys are all visible (no spread, getter, setter, or computed key) and has no `key`.
823
+ * A thenable item (`{ then: child.then }`) is awaited as a launched child, so only the runtime can check it.
824
+ */
825
+ function keylessItemLiteral(node) {
826
+ return astNode(node) && node.type === "ObjectExpression" && Array.isArray(node.properties)
827
+ // `__proto__: base` sets the prototype, and the runtime's destructuring reads a `key` found there.
828
+ && node.properties.every((property) => astNode(property) && property.type === "Property" && property.kind === "init" && property.computed !== true && staticPropertyKey(property) !== "__proto__")
829
+ && !directObjectPropertyValue(node, "key") && !directObjectPropertyValue(node, "then");
830
+ }
623
831
  function containsWorkflowLaunch(node) {
624
832
  let found = false;
625
833
  walkAst(node, (candidate) => {
@@ -766,7 +974,13 @@ export function validateWorkflowScript(script, options = {}) {
766
974
  const location = error && typeof error === "object" && "loc" in error && error.loc && typeof error.loc === "object"
767
975
  ? error.loc
768
976
  : undefined;
769
- const message = (error instanceof Error ? error.message : String(error)).replace(/\s+\(\d+:\d+\)$/, "");
977
+ const parserMessage = (error instanceof Error ? error.message : String(error)).replace(/\s+\(\d+:\d+\)$/, "");
978
+ const source = script.trim();
979
+ // A path passed where source is expected parses as a regex or a stray token. Keep the parser's
980
+ // message too: a one-token script can also be a real syntax error.
981
+ const message = /^\S+$/.test(source) && (/^(?:~|\.{1,2})?\//.test(source) || /\.(?:[cm]?[jt]s|json)$/.test(source))
982
+ ? `${parserMessage}. The script looks like a file path ('${source}'): options.script takes the script's source text; pass a script file as workflow: "${source}".`
983
+ : parserMessage;
770
984
  return { ok: false, errors: [{ message, ...(typeof location?.line === "number" ? { line: Math.max(1, location.line - 1) } : {}), ...(typeof location?.column === "number" ? { column: location.column + 1 } : {}) }] };
771
985
  }
772
986
  const wrapper = astNode(root.body) ? undefined : Array.isArray(root.body) && astNode(root.body[0]) && astNode(root.body[0].expression) && astNode(root.body[0].expression.callee)
@@ -801,6 +1015,11 @@ export function validateWorkflowScript(script, options = {}) {
801
1015
  for (const entry of directRunsAllKeys(node))
802
1016
  if (!KEY_PATTERN.test(entry.key))
803
1017
  errors.push({ message: "runs.all item key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.", ...nodeLocation(entry.node) });
1018
+ if (!runsRebound)
1019
+ for (const item of keylessRunsAllItems(node)) {
1020
+ const subject = item.index === undefined ? "runs.all items built by this map(...) callback have no key" : `runs.all item ${item.index} has no key`;
1021
+ errors.push({ message: `${subject}; every runs.all item needs a stable key, for example runs.all([{ key: "review", agent, task }]).`, ...nodeLocation(item.node) });
1022
+ }
804
1023
  const args = Array.isArray(node.arguments) ? node.arguments : [];
805
1024
  if (astNode(args[0]) && args[0].type === "ArrayExpression" && Array.isArray(args[0].elements)) {
806
1025
  for (const item of args[0].elements)
@@ -1001,13 +1220,7 @@ export async function runWorkflowScript(options) {
1001
1220
  }
1002
1221
  let worker;
1003
1222
  try {
1004
- const bun = typeof process.versions.bun === "string";
1005
- // Bun needs a real file as its resolver base on warm transpiler-cache hits, and no eval key at all: with one,
1006
- // its Worker finalizer passes the URL to URL.revokeObjectURL and throws. Node keeps eval source because its
1007
- // eval worker does not re-resolve inherited --import preloads after a cwd change.
1008
- worker = bun
1009
- ? new Worker(WORKFLOW_WORKER_URL, { workerData: { acornPath } })
1010
- : new Worker(nodeWorkerSource ??= readFileSync(WORKFLOW_WORKER_URL, "utf8"), { eval: true, workerData: { acornPath } });
1223
+ worker = createWorkflowScriptWorker(acornPath);
1011
1224
  }
1012
1225
  catch (error) {
1013
1226
  throw new WorkflowScriptError(`Workflow worker could not start: ${error instanceof Error ? error.message : String(error)}`, emptyPartial(), "runtime", { cause: error });
@@ -1226,8 +1439,8 @@ export async function runWorkflowScript(options) {
1226
1439
  return onAbort();
1227
1440
  worker.on("error", (error) => finish({ error: taggedWorkflowError(`Workflow worker failed: ${error instanceof Error ? error.message : String(error)}`, "runtime") }));
1228
1441
  worker.on("exit", (code) => {
1229
- if (!settled && code !== 0)
1230
- finish({ error: taggedWorkflowError(`Workflow worker exited with code ${code}.`, "runtime") });
1442
+ if (!settled && !finishing)
1443
+ finish({ error: taggedWorkflowError(`Workflow worker exited before returning a result (code ${code}).`, "runtime") });
1231
1444
  });
1232
1445
  worker.on("message", (message) => {
1233
1446
  if (settled)
@@ -1494,8 +1707,13 @@ export async function runWorkflowScript(options) {
1494
1707
  return respond(Promise.reject(new Error(`Duplicate workflow key '${key}' used with incompatible launch params.`)));
1495
1708
  if (callObserved)
1496
1709
  existing.observed = true;
1497
- trace.push({ operation: "run", key, state: "reused", ...workflowStringMetadata(params), ...(existing.generatedLaneKey ? { generatedLaneKey: existing.generatedLaneKey } : {}) });
1498
- traceChanged();
1710
+ // Matching params make every later reuse entry identical, and each trace change rewrites the
1711
+ // whole trace to status.json and events.jsonl, so a re-delivery loop would grow without bound.
1712
+ if (!existing.reuseTraced) {
1713
+ existing.reuseTraced = true;
1714
+ trace.push({ operation: "run", key, state: "reused", ...workflowStringMetadata(params), ...(existing.generatedLaneKey ? { generatedLaneKey: existing.generatedLaneKey } : {}) });
1715
+ traceChanged();
1716
+ }
1499
1717
  return respond(deliver(existing.promise), `runs.run('${key}') result`, (error) => children.set(key, responseBoundaryFailure(key, error)));
1500
1718
  }
1501
1719
  const permitError = options.oneUsePermit?.claim(key);
@@ -1507,6 +1725,9 @@ export async function runWorkflowScript(options) {
1507
1725
  return respond(Promise.reject(new Error("Workflow child permit does not support retained resume.")));
1508
1726
  if (params.action !== undefined)
1509
1727
  return respond(Promise.reject(new Error(`runs.run('${key}') accepts execution params only; management action is not allowed.`)));
1728
+ // Before admission, which resolves a resume target; the executor would only see this after that.
1729
+ if (params.requireLauncher !== undefined)
1730
+ return respond(Promise.reject(new Error(`runs.run('${key}'): ${REQUIRE_LAUNCHER_SHAPE_ERROR}`)));
1510
1731
  if (params.workflowScript !== undefined)
1511
1732
  return respond(Promise.reject(new Error(`runs.run('${key}') cannot start a nested workflow script.`)));
1512
1733
  if (params.tasks !== undefined || params.chain !== undefined || params.parallel !== undefined || params.concurrency !== undefined || params.chainDir !== undefined) {
@@ -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;
@@ -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";
3
3
  export interface WorkflowResumeRefusalReason {
4
4
  code: WorkflowResumeRefusalCode;
5
5
  reason: string;