@selesai/code 0.9.11 → 0.9.13

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 (580) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/config.d.ts +4 -6
  3. package/dist/config.js +10 -14
  4. package/dist/core/agent-session.d.ts +0 -1
  5. package/dist/core/agent-session.js +3 -49
  6. package/dist/core/extensions/types.d.ts +0 -2
  7. package/dist/core/settings-manager.d.ts +0 -2
  8. package/dist/core/settings-manager.js +0 -3
  9. package/dist/core/tools/index.d.ts +0 -1
  10. package/dist/core/tools/index.js +0 -1
  11. package/dist/defaults/settings.json +2 -3
  12. package/dist/extensions/model-prompt-injector/index.test.ts +0 -10
  13. package/dist/extensions/model-prompt-injector/index.ts +0 -3
  14. package/dist/extensions/pi-intercom/CHANGELOG.md +53 -16
  15. package/dist/extensions/pi-intercom/README.md +41 -8
  16. package/dist/extensions/pi-intercom/banner.png +0 -0
  17. package/dist/extensions/pi-intercom/broker/broker.ts +498 -215
  18. package/dist/extensions/pi-intercom/broker/client.ts +39 -12
  19. package/dist/extensions/pi-intercom/broker/extension.test.ts +102 -3
  20. package/dist/extensions/pi-intercom/broker/paths.test.ts +2 -2
  21. package/dist/extensions/pi-intercom/broker/protocol.ts +26 -0
  22. package/dist/extensions/pi-intercom/broker/spawn.test.ts +5 -20
  23. package/dist/extensions/pi-intercom/config.test.ts +41 -0
  24. package/dist/extensions/pi-intercom/config.ts +21 -0
  25. package/dist/extensions/pi-intercom/extension-api.ts +40 -0
  26. package/dist/extensions/pi-intercom/index.ts +362 -26
  27. package/dist/extensions/pi-intercom/intercom.integration.test.ts +819 -13
  28. package/dist/extensions/pi-intercom/package.json +1 -1
  29. package/dist/extensions/pi-intercom/project-agent.ts +2 -2
  30. package/dist/extensions/pi-intercom/skills/pi-intercom/SKILL.md +8 -110
  31. package/dist/extensions/pi-intercom/types.ts +32 -5
  32. package/dist/extensions/pi-intercom/ui/inline-message.ts +6 -0
  33. package/dist/extensions/pi-subagents/.github/assets/subagent-fleet-inspector.png +0 -0
  34. package/dist/extensions/pi-subagents/.github/workflows/release.yml +28 -0
  35. package/dist/extensions/pi-subagents/.github/workflows/test.yml +51 -0
  36. package/dist/extensions/pi-subagents/.greptile/config.json +33 -0
  37. package/dist/extensions/pi-subagents/.greptile/files.json +8 -0
  38. package/dist/extensions/pi-subagents/.greptile/rules.md +16 -0
  39. package/dist/extensions/pi-subagents/CHANGELOG.md +309 -87
  40. package/dist/extensions/pi-subagents/README.md +15 -17
  41. package/dist/extensions/pi-subagents/agents/oracle.md +3 -1
  42. package/dist/extensions/pi-subagents/agents/researcher.md +32 -13
  43. package/dist/extensions/pi-subagents/agents/reviewer.md +13 -2
  44. package/dist/extensions/pi-subagents/agents/scout.md +2 -2
  45. package/dist/extensions/pi-subagents/agents/worker.md +2 -1
  46. package/dist/extensions/pi-subagents/async-retention-discovery-worker.mjs +180 -0
  47. package/dist/extensions/pi-subagents/docs/configuration.md +106 -27
  48. package/dist/extensions/pi-subagents/docs/extension-api.md +85 -21
  49. package/dist/extensions/pi-subagents/docs/missions.md +41 -4
  50. package/dist/extensions/pi-subagents/docs/models.md +52 -9
  51. package/dist/extensions/pi-subagents/docs/observability.md +103 -16
  52. package/dist/extensions/pi-subagents/docs/tool-reference.md +60 -45
  53. package/dist/extensions/pi-subagents/docs/watchdog.md +60 -3
  54. package/dist/extensions/pi-subagents/docs/workflows.md +181 -7
  55. package/dist/extensions/pi-subagents/index.ts +10 -1
  56. package/dist/extensions/pi-subagents/install.mjs +4 -4
  57. package/dist/extensions/pi-subagents/package-lock.json +1483 -1470
  58. package/dist/extensions/pi-subagents/package.json +6 -3
  59. package/dist/extensions/pi-subagents/prompts/council.md +60 -0
  60. package/dist/extensions/pi-subagents/prompts/parallel-review.md +5 -1
  61. package/dist/extensions/pi-subagents/prompts/review-loop.md +9 -5
  62. package/dist/extensions/pi-subagents/skills/council-mode/SKILL.md +254 -0
  63. package/dist/extensions/pi-subagents/skills/pi-subagents/SKILL.md +18 -17
  64. package/dist/extensions/pi-subagents/skills/pi-subagents/references/constraints-and-recipes.md +31 -9
  65. package/dist/extensions/pi-subagents/skills/pi-subagents/references/execution-controls.md +107 -140
  66. package/dist/extensions/pi-subagents/skills/pi-subagents/references/management-authoring-rpc.md +9 -12
  67. package/dist/extensions/pi-subagents/skills/pi-subagents/references/multi-lane-orchestration.md +39 -0
  68. package/dist/extensions/pi-subagents/skills/pi-subagents/references/prompting-and-roles.md +44 -92
  69. package/dist/extensions/pi-subagents/src/agents/agent-management.ts +261 -368
  70. package/dist/extensions/pi-subagents/src/agents/agent-serializer.ts +6 -2
  71. package/dist/extensions/pi-subagents/src/agents/agents.ts +388 -85
  72. package/dist/extensions/pi-subagents/src/agents/builtin-names.ts +14 -0
  73. package/dist/extensions/pi-subagents/src/agents/runtime-agent-registry.ts +418 -0
  74. package/dist/extensions/pi-subagents/src/agents/skills.ts +1 -1
  75. package/dist/extensions/pi-subagents/src/api/agents.ts +7 -0
  76. package/dist/extensions/pi-subagents/src/api/external-job-provider.ts +195 -0
  77. package/dist/extensions/pi-subagents/src/api/preflight.ts +88 -27
  78. package/dist/extensions/pi-subagents/src/api/project-panes.ts +2 -0
  79. package/dist/extensions/pi-subagents/src/api/shared-types.ts +2 -0
  80. package/dist/extensions/pi-subagents/src/extension/config.ts +20 -11
  81. package/dist/extensions/pi-subagents/src/extension/doctor.ts +14 -6
  82. package/dist/extensions/pi-subagents/src/extension/fanout-child.ts +5 -4
  83. package/dist/extensions/pi-subagents/src/extension/index.ts +270 -187
  84. package/dist/extensions/pi-subagents/src/extension/public-execution.ts +65 -28
  85. package/dist/extensions/pi-subagents/src/extension/rpc.ts +120 -11
  86. package/dist/extensions/pi-subagents/src/extension/schemas.ts +46 -64
  87. package/dist/extensions/pi-subagents/src/extension/tool-description.ts +51 -37
  88. package/dist/extensions/pi-subagents/src/extension/tool-result.ts +19 -0
  89. package/dist/extensions/pi-subagents/src/inspectors/herdr/actions.ts +2 -2
  90. package/dist/extensions/pi-subagents/src/inspectors/herdr/client.ts +3 -3
  91. package/dist/extensions/pi-subagents/src/inspectors/herdr/focus.ts +55 -0
  92. package/dist/extensions/pi-subagents/src/inspectors/herdr/inspector-runner.ts +2 -1
  93. package/dist/extensions/pi-subagents/src/inspectors/herdr/project-panes.ts +230 -46
  94. package/dist/extensions/pi-subagents/src/integrations/herdr-status.ts +26 -4
  95. package/dist/extensions/pi-subagents/src/intercom/native-supervisor-channel.ts +32 -10
  96. package/dist/extensions/pi-subagents/src/missions/lifecycle.ts +6 -1
  97. package/dist/extensions/pi-subagents/src/missions/store.ts +4 -9
  98. package/dist/extensions/pi-subagents/src/missions/workflow-state.ts +2 -2
  99. package/dist/extensions/pi-subagents/src/policy/authority.ts +2 -0
  100. package/dist/extensions/pi-subagents/src/profiles/profiles.ts +3 -1
  101. package/dist/extensions/pi-subagents/src/runs/background/active-run-index.ts +31 -8
  102. package/dist/extensions/pi-subagents/src/runs/background/async-execution.ts +210 -52
  103. package/dist/extensions/pi-subagents/src/runs/background/async-job-tracker.ts +63 -33
  104. package/dist/extensions/pi-subagents/src/runs/background/async-resume.ts +71 -17
  105. package/dist/extensions/pi-subagents/src/runs/background/async-retention.ts +886 -0
  106. package/dist/extensions/pi-subagents/src/runs/background/async-status-snapshot.ts +14 -5
  107. package/dist/extensions/pi-subagents/src/runs/background/async-status.ts +49 -56
  108. package/dist/extensions/pi-subagents/src/runs/background/auto-drain.ts +1 -0
  109. package/dist/extensions/pi-subagents/src/runs/background/chain-append.ts +3 -33
  110. package/dist/extensions/pi-subagents/src/runs/background/chain-root-attachment.ts +5 -0
  111. package/dist/extensions/pi-subagents/src/runs/background/completion-dedupe.ts +5 -1
  112. package/dist/extensions/pi-subagents/src/runs/background/completion-replay.ts +22 -12
  113. package/dist/extensions/pi-subagents/src/runs/background/control-channel.ts +105 -71
  114. package/dist/extensions/pi-subagents/src/runs/background/fleet-view.ts +68 -19
  115. package/dist/extensions/pi-subagents/src/runs/background/index-segment.ts +59 -0
  116. package/dist/extensions/pi-subagents/src/runs/background/inspect-rpc.ts +443 -0
  117. package/dist/extensions/pi-subagents/src/runs/background/notify.ts +94 -10
  118. package/dist/extensions/pi-subagents/src/runs/background/result-files.ts +158 -90
  119. package/dist/extensions/pi-subagents/src/runs/background/result-watcher.ts +141 -53
  120. package/dist/extensions/pi-subagents/src/runs/background/resume-guidance.ts +8 -5
  121. package/dist/extensions/pi-subagents/src/runs/background/retained-children.ts +14 -4
  122. package/dist/extensions/pi-subagents/src/runs/background/run-id-query.ts +7 -0
  123. package/dist/extensions/pi-subagents/src/runs/background/run-id-resolver.ts +13 -14
  124. package/dist/extensions/pi-subagents/src/runs/background/run-status.ts +46 -25
  125. package/dist/extensions/pi-subagents/src/runs/background/scheduled-runs.ts +823 -0
  126. package/dist/extensions/pi-subagents/src/runs/background/stale-run-reconciler.ts +9 -3
  127. package/dist/extensions/pi-subagents/src/runs/background/steering.ts +11 -1
  128. package/dist/extensions/pi-subagents/src/runs/background/subagent-runner.ts +594 -216
  129. package/dist/extensions/pi-subagents/src/runs/background/subagent-wait.ts +17 -13
  130. package/dist/extensions/pi-subagents/src/runs/background/terminal-run-index.ts +138 -0
  131. package/dist/extensions/pi-subagents/src/runs/background/wait-completions.ts +23 -4
  132. package/dist/extensions/pi-subagents/src/runs/background/wait-subscriptions.ts +82 -4
  133. package/dist/extensions/pi-subagents/src/runs/background/wait-tool.ts +5 -3
  134. package/dist/extensions/pi-subagents/src/runs/foreground/async-steering-action.ts +21 -14
  135. package/dist/extensions/pi-subagents/src/runs/foreground/async-stop-action.ts +23 -2
  136. package/dist/extensions/pi-subagents/src/runs/foreground/execution.ts +153 -58
  137. package/dist/extensions/pi-subagents/src/runs/foreground/foreground-history.ts +7 -9
  138. package/dist/extensions/pi-subagents/src/runs/foreground/subagent-executor.ts +1283 -1657
  139. package/dist/extensions/pi-subagents/src/runs/foreground/workflow-detach-reconcile.ts +274 -0
  140. package/dist/extensions/pi-subagents/src/runs/foreground/workflow-foreground-steering.ts +6 -5
  141. package/dist/extensions/pi-subagents/src/runs/shared/acceptance.ts +59 -10
  142. package/dist/extensions/pi-subagents/src/runs/shared/agent-contract.ts +1 -1
  143. package/dist/extensions/pi-subagents/src/runs/shared/chain-outputs.ts +1 -3
  144. package/dist/extensions/pi-subagents/src/runs/shared/child-identity.ts +36 -0
  145. package/dist/extensions/pi-subagents/src/runs/shared/completion-guard.ts +52 -2
  146. package/dist/extensions/pi-subagents/src/runs/shared/dynamic-fanout.ts +1 -1
  147. package/dist/extensions/pi-subagents/src/runs/shared/extension-bindings.ts +78 -0
  148. package/dist/extensions/pi-subagents/src/runs/shared/external-cli-runner.ts +2 -0
  149. package/dist/extensions/pi-subagents/src/runs/shared/external-job-bridge.ts +460 -0
  150. package/dist/extensions/pi-subagents/src/runs/shared/external-job-runner.ts +389 -0
  151. package/dist/extensions/pi-subagents/src/runs/shared/fast-mode-extension.ts +10 -0
  152. package/dist/extensions/pi-subagents/src/runs/shared/mcp-direct-tool-allowlist.ts +14 -0
  153. package/dist/extensions/pi-subagents/src/runs/shared/model-exclusions.ts +243 -0
  154. package/dist/extensions/pi-subagents/src/runs/shared/model-fallback.ts +201 -85
  155. package/dist/extensions/pi-subagents/src/runs/shared/model-scope.ts +106 -39
  156. package/dist/extensions/pi-subagents/src/runs/shared/mutation-evidence.ts +145 -0
  157. package/dist/extensions/pi-subagents/src/runs/shared/orca-progress-tabs.ts +150 -27
  158. package/dist/extensions/pi-subagents/src/runs/shared/parallel-handoff.ts +46 -4
  159. package/dist/extensions/pi-subagents/src/runs/shared/parallel-utils.ts +19 -15
  160. package/dist/extensions/pi-subagents/src/runs/shared/permissions.ts +5 -1
  161. package/dist/extensions/pi-subagents/src/runs/shared/pi-args.ts +86 -2
  162. package/dist/extensions/pi-subagents/src/runs/shared/pi-spawn.ts +9 -9
  163. package/dist/extensions/pi-subagents/src/runs/shared/session-lease.ts +0 -6
  164. package/dist/extensions/pi-subagents/src/runs/shared/structured-output.ts +18 -4
  165. package/dist/extensions/pi-subagents/src/runs/shared/subagent-control.ts +51 -7
  166. package/dist/extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.ts +62 -21
  167. package/dist/extensions/pi-subagents/src/runs/shared/tool-availability.ts +1 -3
  168. package/dist/extensions/pi-subagents/src/runs/shared/tool-timeout.ts +1 -3
  169. package/dist/extensions/pi-subagents/src/runs/shared/workflow-graph.ts +1 -23
  170. package/dist/extensions/pi-subagents/src/runs/shared/worktree.ts +14 -2
  171. package/dist/extensions/pi-subagents/src/shared/artifacts.ts +2 -2
  172. package/dist/extensions/pi-subagents/src/shared/atomic-json.ts +22 -2
  173. package/dist/extensions/pi-subagents/src/shared/capacity-resilient-json.ts +102 -0
  174. package/dist/extensions/pi-subagents/src/shared/completion-owner.ts +14 -0
  175. package/dist/extensions/pi-subagents/src/shared/file-system-retry.ts +49 -1
  176. package/dist/extensions/pi-subagents/src/shared/fork-context.ts +59 -1
  177. package/dist/extensions/pi-subagents/src/shared/launch-contract.ts +12 -5
  178. package/dist/extensions/pi-subagents/src/shared/model-info.ts +20 -0
  179. package/dist/extensions/pi-subagents/src/shared/prompt-resources.ts +0 -40
  180. package/dist/extensions/pi-subagents/src/shared/settings.ts +11 -30
  181. package/dist/extensions/pi-subagents/src/shared/thinking-ceiling.ts +52 -0
  182. package/dist/extensions/pi-subagents/src/shared/types.ts +228 -49
  183. package/dist/extensions/pi-subagents/src/shared/utils.ts +11 -3
  184. package/dist/extensions/pi-subagents/src/shared/watch-strategy.ts +10 -0
  185. package/dist/extensions/pi-subagents/src/slash/prompt-workflows.ts +0 -162
  186. package/dist/extensions/pi-subagents/src/slash/slash-bridge.ts +2 -5
  187. package/dist/extensions/pi-subagents/src/slash/slash-commands.ts +105 -13
  188. package/dist/extensions/pi-subagents/src/slash/slash-live-state.ts +6 -36
  189. package/dist/extensions/pi-subagents/src/tui/fleet-status.ts +829 -0
  190. package/dist/extensions/pi-subagents/src/tui/fleet.ts +1415 -0
  191. package/dist/extensions/pi-subagents/src/tui/render.ts +78 -7
  192. package/dist/extensions/pi-subagents/src/watchdog/change-signature.ts +1 -1
  193. package/dist/extensions/pi-subagents/src/watchdog/lsp-diagnostics.ts +1 -0
  194. package/dist/extensions/pi-subagents/src/watchdog/permission-arbiter.ts +59 -51
  195. package/dist/extensions/pi-subagents/src/watchdog/register-main.ts +8 -2
  196. package/dist/extensions/pi-subagents/src/watchdog/tool-actions.ts +2 -1
  197. package/dist/extensions/pi-subagents/src/workflows/chat-progress.ts +4 -4
  198. package/dist/extensions/pi-subagents/src/workflows/scripted-workflow.ts +471 -86
  199. package/dist/extensions/pi-subagents/src/workflows/workflow-receipt.ts +140 -0
  200. package/dist/extensions/pi-subagents/test/e2e/real-session-subagent.test.ts +2 -2
  201. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/bun/cli.d.ts +3 -0
  202. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/bun/register-bedrock.d.ts +2 -0
  203. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/bun/restore-sandbox-env.d.ts +17 -0
  204. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/cli/args.d.ts +57 -0
  205. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/cli/config-selector.d.ts +16 -0
  206. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/cli/file-processor.d.ts +15 -0
  207. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/cli/initial-message.d.ts +18 -0
  208. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/cli/list-models.d.ts +9 -0
  209. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/cli/project-trust.d.ts +10 -0
  210. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/cli/session-picker.d.ts +10 -0
  211. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/cli/startup-ui.d.ts +20 -0
  212. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/cli.d.ts +3 -0
  213. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/config.d.ts +96 -0
  214. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/agent-session-runtime.d.ts +119 -0
  215. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/agent-session-services.d.ts +85 -0
  216. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/agent-session.d.ts +620 -0
  217. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/auth-guidance.d.ts +5 -0
  218. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/auth-storage.d.ts +56 -0
  219. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/bash-executor.d.ts +32 -0
  220. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/cache-stats.d.ts +49 -0
  221. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/compaction/branch-summarization.d.ts +93 -0
  222. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/compaction/compaction.d.ts +128 -0
  223. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/compaction/index.d.ts +7 -0
  224. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/compaction/utils.d.ts +38 -0
  225. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/defaults.d.ts +3 -0
  226. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/diagnostics.d.ts +15 -0
  227. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/event-bus.d.ts +9 -0
  228. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/exec.d.ts +29 -0
  229. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/experimental.d.ts +2 -0
  230. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/export-html/ansi-to-html.d.ts +22 -0
  231. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/export-html/index.d.ts +37 -0
  232. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/export-html/tool-renderer.d.ts +34 -0
  233. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/extensions/index.d.ts +12 -0
  234. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/extensions/loader.d.ts +23 -0
  235. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/extensions/runner.d.ts +171 -0
  236. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/extensions/types.d.ts +1261 -0
  237. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/extensions/wrapper.d.ts +20 -0
  238. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/footer-data-provider.d.ts +54 -0
  239. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/http-dispatcher.d.ts +22 -0
  240. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/index.d.ts +13 -0
  241. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/keybindings.d.ts +358 -0
  242. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/messages.d.ts +77 -0
  243. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/model-config.d.ts +512 -0
  244. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/model-registry.d.ts +43 -0
  245. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/model-resolver.d.ts +121 -0
  246. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/model-runtime.d.ts +82 -0
  247. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/models-store.d.ts +17 -0
  248. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/output-guard.d.ts +7 -0
  249. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/package-manager.d.ts +210 -0
  250. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/project-trust.d.ts +15 -0
  251. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/prompt-templates.d.ts +54 -0
  252. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/provider-attribution.d.ts +4 -0
  253. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/provider-composer.d.ts +55 -0
  254. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/radius.d.ts +2 -0
  255. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/remote-catalog-provider.d.ts +5 -0
  256. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/resolve-config-value.d.ts +30 -0
  257. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/resource-loader.d.ts +206 -0
  258. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/runtime-credentials.d.ts +15 -0
  259. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/sdk.d.ts +106 -0
  260. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/session-cwd.d.ts +19 -0
  261. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/session-manager.d.ts +356 -0
  262. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/settings-manager.d.ts +297 -0
  263. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/skills.d.ts +60 -0
  264. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/slash-commands.d.ts +15 -0
  265. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/source-info.d.ts +18 -0
  266. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/system-prompt.d.ts +28 -0
  267. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/telemetry.d.ts +3 -0
  268. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/timings.d.ts +10 -0
  269. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/tools/bash.d.ts +68 -0
  270. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/tools/edit-diff.d.ts +106 -0
  271. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/tools/edit.d.ts +51 -0
  272. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/tools/file-mutation-queue.d.ts +6 -0
  273. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/tools/find.d.ts +35 -0
  274. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/tools/grep.d.ts +37 -0
  275. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/tools/index.d.ts +40 -0
  276. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/tools/ls.d.ts +37 -0
  277. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/tools/output-accumulator.d.ts +52 -0
  278. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/tools/path-utils.d.ts +10 -0
  279. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/tools/read.d.ts +35 -0
  280. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/tools/render-utils.d.ts +24 -0
  281. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/tools/tool-definition-wrapper.d.ts +14 -0
  282. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/tools/truncate.d.ts +70 -0
  283. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/tools/write.d.ts +26 -0
  284. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/trust-manager.d.ts +36 -0
  285. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/core/usage-totals.d.ts +19 -0
  286. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/extensions/index.d.ts +3 -0
  287. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/extensions/llama/client.d.ts +61 -0
  288. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/extensions/llama/huggingface.d.ts +23 -0
  289. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/extensions/llama/index.d.ts +3 -0
  290. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/extensions/llama/provider.d.ts +10 -0
  291. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/extensions/llama/ui.d.ts +42 -0
  292. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/index.d.ts +35 -0
  293. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/main.d.ts +12 -0
  294. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/migrations.d.ts +33 -0
  295. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/index.d.ts +9 -0
  296. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/armin.d.ts +34 -0
  297. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/assistant-message.d.ts +22 -0
  298. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/bash-execution.d.ts +34 -0
  299. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/bordered-loader.d.ts +16 -0
  300. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/branch-summary-message.d.ts +16 -0
  301. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/compaction-summary-message.d.ts +16 -0
  302. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/config-selector.d.ts +102 -0
  303. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/countdown-timer.d.ts +14 -0
  304. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/custom-editor.d.ts +21 -0
  305. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/custom-entry.d.ts +19 -0
  306. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/custom-message.d.ts +20 -0
  307. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/daxnuts.d.ts +23 -0
  308. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/diff.d.ts +12 -0
  309. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/dynamic-border.d.ts +15 -0
  310. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/earendil-announcement.d.ts +5 -0
  311. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/extension-editor.d.ts +22 -0
  312. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/extension-input.d.ts +23 -0
  313. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/extension-selector.d.ts +26 -0
  314. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/first-time-setup.d.ts +25 -0
  315. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/footer.d.ts +32 -0
  316. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/index.d.ts +34 -0
  317. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/keybinding-hints.d.ts +13 -0
  318. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/login-dialog.d.ts +52 -0
  319. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/model-selector.d.ts +54 -0
  320. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/oauth-selector.d.ts +33 -0
  321. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/scoped-models-selector.d.ts +42 -0
  322. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/session-selector-search.d.ts +23 -0
  323. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/session-selector.d.ts +95 -0
  324. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/settings-selector.d.ts +77 -0
  325. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/show-images-selector.d.ts +10 -0
  326. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/skill-invocation-message.d.ts +17 -0
  327. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/status-indicator.d.ts +28 -0
  328. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/theme-selector.d.ts +11 -0
  329. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/thinking-selector.d.ts +11 -0
  330. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/tool-execution.d.ts +63 -0
  331. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/tree-selector.d.ts +94 -0
  332. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/trust-selector.d.ts +23 -0
  333. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/user-message-selector.d.ts +30 -0
  334. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/user-message.d.ts +14 -0
  335. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/components/visual-truncate.d.ts +24 -0
  336. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/interactive-mode.d.ts +394 -0
  337. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/model-search.d.ts +12 -0
  338. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/theme/theme-controller.d.ts +29 -0
  339. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/interactive/theme/theme.d.ts +120 -0
  340. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/print-mode.d.ts +28 -0
  341. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/rpc/jsonl.d.ts +17 -0
  342. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/rpc/rpc-client.d.ts +246 -0
  343. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/rpc/rpc-mode.d.ts +20 -0
  344. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/modes/rpc/rpc-types.d.ts +457 -0
  345. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/package-manager-cli.d.ts +8 -0
  346. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/rpc-entry.d.ts +3 -0
  347. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/ansi.d.ts +2 -0
  348. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/changelog.d.ts +22 -0
  349. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/child-process.d.ts +18 -0
  350. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/clipboard-image.d.ts +11 -0
  351. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/clipboard-native.d.ts +11 -0
  352. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/clipboard.d.ts +4 -0
  353. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/deprecation.d.ts +4 -0
  354. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/exif-orientation.d.ts +5 -0
  355. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/frontmatter.d.ts +8 -0
  356. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/fs-watch.d.ts +5 -0
  357. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/git.d.ts +26 -0
  358. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/html.d.ts +7 -0
  359. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/image-convert.d.ts +10 -0
  360. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/image-process.d.ts +18 -0
  361. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/image-resize-core.d.ts +30 -0
  362. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/image-resize-worker.d.ts +2 -0
  363. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/image-resize.d.ts +16 -0
  364. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/json.d.ts +3 -0
  365. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/mime.d.ts +3 -0
  366. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/open-browser.d.ts +9 -0
  367. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/paths.d.ts +31 -0
  368. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/photon.d.ts +21 -0
  369. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/pi-user-agent.d.ts +2 -0
  370. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/shell.d.ts +31 -0
  371. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/sleep.d.ts +5 -0
  372. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/syntax-highlight.d.ts +12 -0
  373. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/tools-manager.d.ts +3 -0
  374. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/version-check.d.ts +15 -0
  375. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/dist/utils/windows-self-update.d.ts +3 -0
  376. package/dist/extensions/pi-subagents/test/fixtures/pi-coding-agent-shim/index.mjs +1 -1
  377. package/dist/extensions/pi-subagents/test/integration/acceptance-file-report.test.ts +0 -54
  378. package/dist/extensions/pi-subagents/test/integration/async-execution.test.ts +1053 -414
  379. package/dist/extensions/pi-subagents/test/integration/async-job-tracker.test.ts +194 -4
  380. package/dist/extensions/pi-subagents/test/integration/async-status.test.ts +59 -4
  381. package/dist/extensions/pi-subagents/test/integration/error-handling.test.ts +0 -77
  382. package/dist/extensions/pi-subagents/test/integration/external-cli-runner.test.ts +107 -6
  383. package/dist/extensions/pi-subagents/test/integration/fork-context-execution.test.ts +211 -897
  384. package/dist/extensions/pi-subagents/test/integration/intercom-result-delivery.test.ts +265 -375
  385. package/dist/extensions/pi-subagents/test/integration/orca-progress-tabs.test.ts +77 -7
  386. package/dist/extensions/pi-subagents/test/integration/render-fork-badge.test.ts +1 -1
  387. package/dist/extensions/pi-subagents/test/integration/render-widget.test.ts +10 -10
  388. package/dist/extensions/pi-subagents/test/integration/result-watcher.test.ts +547 -30
  389. package/dist/extensions/pi-subagents/test/integration/single-execution.test.ts +2112 -310
  390. package/dist/extensions/pi-subagents/test/integration/slash-commands.test.ts +274 -34
  391. package/dist/extensions/pi-subagents/test/integration/slash-live-state.test.ts +1 -1
  392. package/dist/extensions/pi-subagents/test/integration/template-resolution.test.ts +20 -3
  393. package/dist/extensions/pi-subagents/test/support/isolated-temp-root.mjs +9 -0
  394. package/dist/extensions/pi-subagents/test/support/mock-pi-script.mjs +30 -5
  395. package/dist/extensions/pi-subagents/test/support/mock-pi.ts +2 -0
  396. package/dist/extensions/pi-subagents/test/support/real-session-runner.ts +4 -2
  397. package/dist/extensions/pi-subagents/test/support/register-loader.mjs +1 -0
  398. package/dist/extensions/pi-subagents/test/unit/acceptance.test.ts +197 -0
  399. package/dist/extensions/pi-subagents/test/unit/agent-contract.test.ts +14 -0
  400. package/dist/extensions/pi-subagents/test/unit/agent-disabled.test.ts +1 -1
  401. package/dist/extensions/pi-subagents/test/unit/agent-frontmatter.test.ts +204 -27
  402. package/dist/extensions/pi-subagents/test/unit/agent-management.test.ts +444 -145
  403. package/dist/extensions/pi-subagents/test/unit/agent-overrides.test.ts +256 -4
  404. package/dist/extensions/pi-subagents/test/unit/artifacts.test.ts +9 -7
  405. package/dist/extensions/pi-subagents/test/unit/async-interrupt-action.test.ts +152 -22
  406. package/dist/extensions/pi-subagents/test/unit/async-recovery-descriptor.test.ts +29 -0
  407. package/dist/extensions/pi-subagents/test/unit/async-resume.test.ts +205 -23
  408. package/dist/extensions/pi-subagents/test/unit/async-retention.test.ts +579 -0
  409. package/dist/extensions/pi-subagents/test/unit/atomic-json.test.ts +24 -0
  410. package/dist/extensions/pi-subagents/test/unit/authority-policy.test.ts +1 -0
  411. package/dist/extensions/pi-subagents/test/unit/auto-drain.test.ts +3 -3
  412. package/dist/extensions/pi-subagents/test/unit/capacity-resilient-json.test.ts +155 -0
  413. package/dist/extensions/pi-subagents/test/unit/compaction-resume.test.ts +2 -2
  414. package/dist/extensions/pi-subagents/test/unit/completion-dedupe.test.ts +7 -0
  415. package/dist/extensions/pi-subagents/test/unit/completion-guard.test.ts +123 -0
  416. package/dist/extensions/pi-subagents/test/unit/completion-replay.test.ts +81 -3
  417. package/dist/extensions/pi-subagents/test/unit/control-channel.test.ts +109 -7
  418. package/dist/extensions/pi-subagents/test/unit/default-extensions.test.ts +2 -2
  419. package/dist/extensions/pi-subagents/test/unit/doctor.test.ts +5 -2
  420. package/dist/extensions/pi-subagents/test/unit/dynamic-fanout.test.ts +3 -2
  421. package/dist/extensions/pi-subagents/test/unit/extension-bindings.test.ts +79 -0
  422. package/dist/extensions/pi-subagents/test/unit/external-cli-runner.test.ts +22 -0
  423. package/dist/extensions/pi-subagents/test/unit/external-job-runner.test.ts +961 -0
  424. package/dist/extensions/pi-subagents/test/unit/file-system-retry.test.ts +64 -0
  425. package/dist/extensions/pi-subagents/test/unit/fleet-status.test.ts +1110 -0
  426. package/dist/extensions/pi-subagents/test/unit/fleet.test.ts +1664 -0
  427. package/dist/extensions/pi-subagents/test/unit/fork-context.test.ts +81 -1
  428. package/dist/extensions/pi-subagents/test/unit/herdr-inspector.test.ts +138 -11
  429. package/dist/extensions/pi-subagents/test/unit/herdr-status-bridge.test.ts +41 -2
  430. package/dist/extensions/pi-subagents/test/unit/index-child-registration.test.ts +210 -79
  431. package/dist/extensions/pi-subagents/test/unit/index-segment.test.ts +95 -0
  432. package/dist/extensions/pi-subagents/test/unit/inspect-rpc.test.ts +596 -0
  433. package/dist/extensions/pi-subagents/test/unit/mission-lifecycle.test.ts +10 -1
  434. package/dist/extensions/pi-subagents/test/unit/mission-store.test.ts +3 -5
  435. package/dist/extensions/pi-subagents/test/unit/model-exclusions.test.ts +167 -0
  436. package/dist/extensions/pi-subagents/test/unit/model-fallback.test.ts +319 -18
  437. package/dist/extensions/pi-subagents/test/unit/model-info.test.ts +78 -0
  438. package/dist/extensions/pi-subagents/test/unit/model-scope-settings.test.ts +19 -5
  439. package/dist/extensions/pi-subagents/test/unit/model-scope.test.ts +44 -0
  440. package/dist/extensions/pi-subagents/test/unit/mutation-evidence.test.ts +129 -0
  441. package/dist/extensions/pi-subagents/test/unit/native-supervisor-channel.test.ts +231 -2
  442. package/dist/extensions/pi-subagents/test/unit/nested-control.test.ts +28 -1
  443. package/dist/extensions/pi-subagents/test/unit/notify.test.ts +106 -2
  444. package/dist/extensions/pi-subagents/test/unit/orca-progress-tabs.test.ts +204 -7
  445. package/dist/extensions/pi-subagents/test/unit/package-manifest.test.ts +59 -4
  446. package/dist/extensions/pi-subagents/test/unit/path-handling.test.ts +2 -6
  447. package/dist/extensions/pi-subagents/test/unit/pi-args-permission-system.test.ts +34 -2
  448. package/dist/extensions/pi-subagents/test/unit/pi-args.test.ts +116 -6
  449. package/dist/extensions/pi-subagents/test/unit/pi-coding-agent-dir.test.ts +12 -3
  450. package/dist/extensions/pi-subagents/test/unit/pi-spawn.test.ts +56 -61
  451. package/dist/extensions/pi-subagents/test/unit/preflight.test.ts +416 -1
  452. package/dist/extensions/pi-subagents/test/unit/profiles.test.ts +9 -2
  453. package/dist/extensions/pi-subagents/test/unit/project-panes-public-api.test.ts +42 -0
  454. package/dist/extensions/pi-subagents/test/unit/prompt-workflows.test.ts +21 -30
  455. package/dist/extensions/pi-subagents/test/unit/public-execution.test.ts +86 -11
  456. package/dist/extensions/pi-subagents/test/unit/render-helpers.test.ts +49 -1
  457. package/dist/extensions/pi-subagents/test/unit/result-files.test.ts +233 -5
  458. package/dist/extensions/pi-subagents/test/unit/retained-children.test.ts +28 -5
  459. package/dist/extensions/pi-subagents/test/unit/rpc.test.ts +323 -20
  460. package/dist/extensions/pi-subagents/test/unit/run-id-resolver.test.ts +66 -10
  461. package/dist/extensions/pi-subagents/test/unit/run-status.test.ts +68 -5
  462. package/dist/extensions/pi-subagents/test/unit/runtime-agent-registration.test.ts +174 -0
  463. package/dist/extensions/pi-subagents/test/unit/scheduled-runs.test.ts +679 -0
  464. package/dist/extensions/pi-subagents/test/unit/scheduled-store-root.test.ts +67 -0
  465. package/dist/extensions/pi-subagents/test/unit/schemas.test.ts +55 -44
  466. package/dist/extensions/pi-subagents/test/unit/scripted-workflow.test.ts +399 -84
  467. package/dist/extensions/pi-subagents/test/unit/session-lease.test.ts +13 -0
  468. package/dist/extensions/pi-subagents/test/unit/skills-fallback.test.ts +1 -1
  469. package/dist/extensions/pi-subagents/test/unit/slash-bridge.test.ts +15 -10
  470. package/dist/extensions/pi-subagents/test/unit/stale-run-reconciler.test.ts +11 -7
  471. package/dist/extensions/pi-subagents/test/unit/steering-action.test.ts +2 -0
  472. package/dist/extensions/pi-subagents/test/unit/steering.test.ts +40 -1
  473. package/dist/extensions/pi-subagents/test/unit/subagent-action-recovery.test.ts +10 -2
  474. package/dist/extensions/pi-subagents/test/unit/subagent-control.test.ts +38 -3
  475. package/dist/extensions/pi-subagents/test/unit/subagent-prompt-runtime.test.ts +110 -12
  476. package/dist/extensions/pi-subagents/test/unit/subagent-wait.test.ts +204 -19
  477. package/dist/extensions/pi-subagents/test/unit/temp-paths.test.ts +25 -0
  478. package/dist/extensions/pi-subagents/test/unit/thinking-ceiling.test.ts +73 -0
  479. package/dist/extensions/pi-subagents/test/unit/tool-description.test.ts +90 -50
  480. package/dist/extensions/pi-subagents/test/unit/tool-timeout.test.ts +1 -2
  481. package/dist/extensions/pi-subagents/test/unit/wait-subscriptions.test.ts +234 -7
  482. package/dist/extensions/pi-subagents/test/unit/watch-strategy.test.ts +24 -0
  483. package/dist/extensions/pi-subagents/test/unit/watchdog-permission-arbiter.test.ts +36 -0
  484. package/dist/extensions/pi-subagents/test/unit/workflow-chat-progress.test.ts +37 -9
  485. package/dist/extensions/pi-subagents/test/unit/workflow-detach-reconcile.test.ts +302 -0
  486. package/dist/extensions/pi-subagents/test/unit/workflow-launch-params.test.ts +167 -7
  487. package/dist/extensions/pi-subagents/test/unit/workflow-receipt.test.ts +113 -0
  488. package/dist/extensions/pi-subagents/test/unit/worktree.test.ts +6 -6
  489. package/dist/extensions/ponytail/index.js +31 -25
  490. package/dist/extensions/ponytail/ponytail-config.cjs +34 -7
  491. package/dist/extensions/ponytail/ponytail-instructions.cjs +7 -9
  492. package/dist/extensions/ponytail/test/extension.test.js +7 -8
  493. package/dist/extensions/ponytail/test/helpers.test.js +1 -1
  494. package/dist/skills/brandkit/SKILL.md +799 -0
  495. package/dist/skills/design-taste-frontend/SKILL.md +1207 -0
  496. package/dist/skills/design-taste-frontend-v1/SKILL.md +227 -0
  497. package/dist/skills/full-output-enforcement/SKILL.md +50 -0
  498. package/dist/skills/gpt-taste/SKILL.md +75 -0
  499. package/dist/skills/high-end-visual-design/SKILL.md +99 -0
  500. package/dist/skills/image-to-code/SKILL.md +1229 -0
  501. package/dist/skills/imagegen-frontend-mobile/SKILL.md +1466 -0
  502. package/dist/skills/imagegen-frontend-web/SKILL.md +988 -0
  503. package/dist/skills/industrial-brutalist-ui/SKILL.md +93 -0
  504. package/dist/skills/minimalist-ui/SKILL.md +86 -0
  505. package/dist/skills/pi-subagents/SKILL.md +18 -17
  506. package/dist/skills/pi-subagents/references/constraints-and-recipes.md +31 -9
  507. package/dist/skills/pi-subagents/references/execution-controls.md +95 -143
  508. package/dist/skills/pi-subagents/references/management-authoring-rpc.md +9 -12
  509. package/dist/skills/pi-subagents/references/multi-lane-orchestration.md +39 -0
  510. package/dist/skills/pi-subagents/references/prompting-and-roles.md +45 -94
  511. package/dist/skills/ponytail/SKILL.md +12 -8
  512. package/dist/skills/ponytail-audit/SKILL.md +0 -1
  513. package/dist/skills/ponytail-debt/SKILL.md +0 -1
  514. package/dist/skills/ponytail-gain/SKILL.md +0 -1
  515. package/dist/skills/ponytail-help/SKILL.md +4 -3
  516. package/dist/skills/ponytail-review/SKILL.md +0 -1
  517. package/dist/skills/redesign-existing-projects/SKILL.md +179 -0
  518. package/dist/skills/stitch-design-taste/SKILL.md +185 -0
  519. package/dist/skills/unlazy/CHANGELOG.md +100 -0
  520. package/dist/skills/unlazy/CONTRIBUTING.md +66 -0
  521. package/dist/skills/unlazy/LICENSE +21 -0
  522. package/dist/skills/unlazy/README.md +242 -0
  523. package/dist/skills/unlazy/SECURITY.md +70 -0
  524. package/dist/skills/unlazy/SKILL.md +100 -0
  525. package/dist/skills/unlazy/package.json +13 -0
  526. package/dist/skills/unlazy/references/dispatch.md +82 -0
  527. package/dist/skills/unlazy/references/gates.md +132 -0
  528. package/dist/skills/unlazy/references/method.md +49 -0
  529. package/dist/skills/unlazy/references/orchestration.md +99 -0
  530. package/dist/skills/unlazy/references/parallel.md +123 -0
  531. package/dist/skills/unlazy/references/token-economy.md +39 -0
  532. package/dist/skills/unlazy/research/validation-protocol.md +81 -0
  533. package/dist/skills/unlazy/scripts/dispatch-check.mjs +108 -0
  534. package/dist/skills/unlazy/scripts/gate-check.mjs +894 -0
  535. package/dist/skills/unlazy/scripts/gate-lint.mjs +178 -0
  536. package/dist/skills/unlazy/scripts/install-hooks.mjs +206 -0
  537. package/dist/skills/unlazy/scripts/lib/check-supervisor.mjs +46 -0
  538. package/dist/skills/unlazy/scripts/lib/dispatch.mjs +283 -0
  539. package/dist/skills/unlazy/scripts/lib/gates.mjs +629 -0
  540. package/dist/skills/unlazy/scripts/lib/process-tree.mjs +161 -0
  541. package/dist/skills/unlazy/scripts/lib/regex-worker.mjs +9 -0
  542. package/dist/skills/unlazy/scripts/stop-hook.mjs +174 -0
  543. package/dist/skills/unlazy/templates/PLAN.md +65 -0
  544. package/dist/skills/unlazy/templates/gates-leaf.md +51 -0
  545. package/dist/skills/unlazy/templates/gates-node.md +50 -0
  546. package/dist/skills/unlazy/tests/contract-tests.mjs +127 -0
  547. package/dist/skills/unlazy/tests/dispatch-tests.mjs +481 -0
  548. package/dist/skills/unlazy/tests/hardening-tests.mjs +903 -0
  549. package/dist/skills/unlazy/tests/lint-tests.mjs +242 -0
  550. package/dist/skills/unlazy/tests/run-tests.mjs +554 -0
  551. package/dist/skills/unlazy/tests/self-check.mjs +165 -0
  552. package/dist/skills/unlazy/tests/stress-tests.mjs +356 -0
  553. package/dist/skills/web-design-guidelines/SKILL.md +40 -0
  554. package/docs/settings.md +0 -5
  555. package/package.json +1 -1
  556. package/dist/core/tools/schema-prune.d.ts +0 -16
  557. package/dist/core/tools/schema-prune.js +0 -39
  558. package/dist/core/tools/schema-prune.test.d.ts +0 -1
  559. package/dist/core/tools/schema-prune.test.js +0 -111
  560. package/dist/extensions/pi-subagents/UPSTREAM-V0.50-MAPPING.md +0 -172
  561. package/dist/extensions/pi-subagents/prompts/parallel-context-build.md +0 -55
  562. package/dist/extensions/pi-subagents/prompts/parallel-handoff-plan.md +0 -61
  563. package/dist/extensions/pi-subagents/src/agents/task-aware-routing.ts +0 -132
  564. package/dist/extensions/pi-subagents/src/extension/chain-validation.ts +0 -181
  565. package/dist/extensions/pi-subagents/src/runs/foreground/chain-clarify.ts +0 -1354
  566. package/dist/extensions/pi-subagents/src/runs/foreground/chain-execution.ts +0 -1581
  567. package/dist/extensions/pi-subagents/src/shared/env.ts +0 -16
  568. package/dist/extensions/pi-subagents/src/shared/session-lineage.ts +0 -71
  569. package/dist/extensions/pi-subagents/src/slash/inline-subagents.ts +0 -136
  570. package/dist/extensions/pi-subagents/src/workflows/workflow-auto-relaunch.ts +0 -41
  571. package/dist/extensions/pi-subagents/test/integration/chain-clarify.test.ts +0 -466
  572. package/dist/extensions/pi-subagents/test/integration/chain-execution.test.ts +0 -1859
  573. package/dist/extensions/pi-subagents/test/integration/parallel-execution.test.ts +0 -733
  574. package/dist/extensions/pi-subagents/test/unit/builtin-agent-documentation.test.ts +0 -63
  575. package/dist/extensions/pi-subagents/test/unit/chain-validation.test.ts +0 -326
  576. package/dist/extensions/pi-subagents/test/unit/handoff-adoption.test.ts +0 -103
  577. package/dist/extensions/pi-subagents/test/unit/inline-subagents.test.ts +0 -127
  578. package/dist/extensions/pi-subagents/test/unit/session-lineage.test.ts +0 -73
  579. package/dist/extensions/pi-subagents/test/unit/task-aware-routing.test.ts +0 -213
  580. package/dist/extensions/pi-subagents/test/unit/workflow-auto-relaunch.test.ts +0 -65
@@ -1,1581 +0,0 @@
1
- /**
2
- * Chain execution logic for subagent tool
3
- */
4
-
5
- import * as fs from "node:fs";
6
- import * as path from "node:path";
7
- import type { AgentToolResult } from "@earendil-works/pi-agent-core";
8
- import type { ExtensionContext } from "@selesai/code";
9
- import type { AgentConfig } from "../../agents/agents.ts";
10
- import { ChainClarifyComponent, type ChainClarifyResult, type BehaviorOverride } from "./chain-clarify.ts";
11
- import { resolveEffectiveThinking, toModelInfo, type ModelInfo } from "../../shared/model-info.ts";
12
- import {
13
- resolveChainTemplates,
14
- createChainDir,
15
- removeChainDir,
16
- resolveStepBehavior,
17
- resolveParallelBehaviors,
18
- buildChainInstructions,
19
- writeInitialProgressFile,
20
- createParallelDirs,
21
- suppressProgressForReadOnlyTask,
22
- aggregateParallelOutputs,
23
- isCheckpointStep,
24
- isDynamicParallelStep,
25
- isParallelStep,
26
- type StepOverrides,
27
- type ChainStep,
28
- type ParallelStep,
29
- type SequentialStep,
30
- type ParallelTaskResult,
31
- type ResolvedStepBehavior,
32
- type ResolvedTemplates,
33
- } from "../../shared/settings.ts";
34
- import { discoverAvailableSkills, normalizeSkillInput } from "../../agents/skills.ts";
35
- import { INTERCOM_BRIDGE_MARKER } from "../../intercom/intercom-bridge.ts";
36
- import { runSync } from "./execution.ts";
37
- import { createTaskMutationArbiter } from "../shared/llm-intent-arbiter.ts";
38
- import { workflowForegroundSteeringLaunchOptions } from "./workflow-foreground-steering.ts";
39
- import {
40
- beginForegroundChild,
41
- finishForegroundChild,
42
- retainForegroundSchedulingOwner,
43
- settleForegroundSchedulingOwner,
44
- updateForegroundChild,
45
- } from "./foreground-control.ts";
46
- import { updateLiveEffectivePrompt } from "./prompt-audit.ts";
47
- import { buildChainSummary } from "../../shared/formatters.ts";
48
- import { compactForegroundDetails, getSingleResultOutput, mapConcurrent, resolveChildCwd, sumResultsCost, sumResultsUsage } from "../../shared/utils.ts";
49
- import { DEFAULT_GLOBAL_CONCURRENCY_LIMIT, Semaphore } from "../shared/parallel-utils.ts";
50
- import type { PermissionConfig } from "../shared/permissions.ts";
51
- import { formatParallelHandoffError, formatParallelHandoffReference, parallelHandoffPath, writeParallelHandoffGroup, writePendingParallelHandoff } from "../shared/parallel-handoff.ts";
52
- import { recordRun } from "../shared/run-history.ts";
53
- import {
54
- cleanupWorktrees,
55
- createWorktrees,
56
- diffWorktrees,
57
- findWorktreeTaskCwdConflict,
58
- formatWorktreeDiffSummary,
59
- formatWorktreeTaskCwdConflict,
60
- type WorktreeSetup,
61
- } from "../shared/worktree.ts";
62
- import {
63
- type ActivityState,
64
- type AgentContract,
65
- type AgentProgress,
66
- type ArtifactConfig,
67
- type ArtifactPaths,
68
- type ControlEvent,
69
- type Details,
70
- type ForegroundRunControl,
71
- type IntercomEventBus,
72
- type NestedRouteInfo,
73
- type ResolvedControlConfig,
74
- type ResolvedTurnBudget,
75
- type ResolvedToolBudget,
76
- type RunFanoutBudgetDescriptor,
77
- type SingleResult,
78
- type ToolBudgetConfig,
79
- type ChainCheckpointState,
80
- type UsageBudgetConfig,
81
- MAX_CONCURRENCY,
82
- resolveChildMaxSubagentDepth,
83
- } from "../../shared/types.ts";
84
- import { resolveEffectiveSubagentModel } from "../shared/model-fallback.ts";
85
- import type { ModelScopeConfig } from "../shared/model-scope.ts";
86
- import { injectSingleOutputInstruction, validateFileOnlyOutputMode } from "../shared/single-output.ts";
87
- import { buildWorkflowGraphSnapshot } from "../shared/workflow-graph.ts";
88
- import { ChainOutputValidationError, outputEntryFromResult, resolveOutputReferences, validateChainOutputBindings } from "../shared/chain-outputs.ts";
89
- import { createStructuredOutputRuntime } from "../shared/structured-output.ts";
90
- import { collectDynamicResults, DynamicFanoutError, materializeDynamicParallelStep, validateDynamicCollection, type DynamicCollectedResult } from "../shared/dynamic-fanout.ts";
91
- import { acceptanceFailureMessage, aggregateAcceptanceReport, evaluateAcceptance, resolveEffectiveAcceptance } from "../shared/acceptance.ts";
92
- import { claimRunFanoutBatch, RunFanoutLimitError } from "../shared/run-fanout-budget.ts";
93
- import { isAgentContractV1 } from "../shared/agent-contract.ts";
94
- import type { ChainOutputMap } from "../../shared/types.ts";
95
- import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
96
- import { usageBudgetExceededMessage, usageBudgetState } from "../shared/usage-budget.ts";
97
- import type { ContextMode } from "../shared/context-mode.ts";
98
- import type { ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
99
-
100
- interface ChainExecutionDetailsInput {
101
- results: SingleResult[];
102
- includeProgress?: boolean;
103
- allProgress: AgentProgress[];
104
- allArtifactPaths: ArtifactPaths[];
105
- artifactsDir: string;
106
- chainAgents: string[];
107
- chainSteps: ChainStep[];
108
- totalSteps: number;
109
- currentStepIndex?: number;
110
- runId: string;
111
- outputs?: ChainOutputMap;
112
- currentFlatIndex?: number;
113
- dynamicChildren?: Record<number, Array<{ agent: string; label?: string; flatIndex: number; itemKey: string; outputName?: string; structured?: boolean; error?: string }>>;
114
- dynamicGroupStatuses?: Record<number, { status: "pending" | "running" | "completed" | "failed" | "paused" | "stopped" | "detached"; error?: string; acceptance?: SingleResult["acceptance"] }>;
115
- parallelHandoff?: Details["parallelHandoff"];
116
- checkpoint?: ChainCheckpointState;
117
- usageBudget?: UsageBudgetConfig;
118
- }
119
-
120
- interface ParallelChainRunInput {
121
- step: ParallelStep;
122
- parallelTemplates: string[];
123
- parallelBehaviors: ResolvedStepBehavior[];
124
- agents: AgentConfig[];
125
- stepIndex: number;
126
- availableModels: ModelInfo[];
127
- modelScope?: ModelScopeConfig;
128
- chainDir: string;
129
- prev: string;
130
- originalTask: string;
131
- ctx: ExtensionContext;
132
- intercomEvents?: IntercomEventBus;
133
- cwd?: string;
134
- runId: string;
135
- globalTaskIndex: number;
136
- sessionDirForIndex: (idx?: number) => string | undefined;
137
- sessionFileForIndex?: (idx?: number) => string | undefined;
138
- sessionFileForTask?: (agentName: string, idx?: number, modelOverride?: string) => string | undefined;
139
- thinkingOverrideForTask?: (agentName: string, idx?: number, modelOverride?: string) => AgentConfig["thinking"] | undefined;
140
- contextForAgent?: (agentName: string) => ContextMode;
141
- shareEnabled: boolean;
142
- artifactConfig: ArtifactConfig;
143
- artifactsDir: string;
144
- signal?: AbortSignal;
145
- onUpdate?: (r: AgentToolResult<Details>) => void;
146
- onControlEvent?: (event: ControlEvent) => void;
147
- controlConfig: ResolvedControlConfig;
148
- agentContract?: AgentContract;
149
- childIntercomTarget?: (agent: string, index: number) => string | undefined;
150
- orchestratorIntercomTarget?: string;
151
- foregroundControl?: ForegroundRunControl;
152
- results: SingleResult[];
153
- allProgress: AgentProgress[];
154
- outputs: ChainOutputMap;
155
- chainAgents: string[];
156
- chainSteps: ChainStep[];
157
- totalSteps: number;
158
- dynamicChildren?: ChainExecutionDetailsInput["dynamicChildren"];
159
- dynamicGroupStatuses?: ChainExecutionDetailsInput["dynamicGroupStatuses"];
160
- worktreeSetup?: WorktreeSetup;
161
- maxSubagentDepth: number;
162
- nestedRoute?: NestedRouteInfo;
163
- timeoutMs?: number;
164
- deadlineAt?: number;
165
- callToolTimeoutMs?: number;
166
- configToolTimeoutMs?: number;
167
- turnBudget?: ResolvedTurnBudget;
168
- usageBudget?: UsageBudgetConfig;
169
- onDetachedExit?: (index: number, result: SingleResult) => void;
170
- /** Called after an attached child releases its foreground ownership. */
171
- onForegroundChildSettled?: () => void;
172
- toolBudget?: ResolvedToolBudget;
173
- configToolBudget?: ToolBudgetConfig;
174
- globalSemaphore?: Semaphore;
175
- capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
176
- runFanoutBudget?: RunFanoutBudgetDescriptor;
177
- permissions?: PermissionConfig;
178
- dynamic?: boolean;
179
- }
180
-
181
- function buildChainExecutionDetails(input: ChainExecutionDetailsInput): Details {
182
- return compactForegroundDetails({
183
- mode: "chain",
184
- results: input.results,
185
- progress: input.includeProgress ? input.allProgress : undefined,
186
- artifacts: input.allArtifactPaths.length ? { dir: input.artifactsDir, files: input.allArtifactPaths } : undefined,
187
- chainAgents: input.chainAgents,
188
- totalSteps: input.totalSteps,
189
- currentStepIndex: input.currentStepIndex,
190
- outputs: input.outputs,
191
- totalChildUsage: sumResultsUsage(input.results),
192
- totalCost: sumResultsCost(input.results),
193
- usageBudget: usageBudgetState(input.usageBudget, sumResultsCost(input.results)),
194
- ...(input.checkpoint ? { checkpoint: input.checkpoint } : {}),
195
- ...(input.parallelHandoff ? { parallelHandoff: input.parallelHandoff } : {}),
196
- workflowGraph: buildWorkflowGraphSnapshot({
197
- runId: input.runId,
198
- mode: "chain",
199
- steps: input.chainSteps,
200
- results: input.results,
201
- currentStepIndex: input.currentStepIndex,
202
- currentFlatIndex: input.currentFlatIndex,
203
- dynamicChildren: input.dynamicChildren,
204
- dynamicGroupStatuses: input.dynamicGroupStatuses,
205
- }),
206
- });
207
- }
208
-
209
- function buildChainExecutionErrorResult(message: string, input: ChainExecutionDetailsInput): ChainExecutionResult {
210
- return {
211
- content: [{ type: "text", text: message }],
212
- isError: true,
213
- details: buildChainExecutionDetails(input),
214
- };
215
- }
216
-
217
- function ensureParallelProgressFile(
218
- chainDir: string,
219
- progressCreated: boolean,
220
- parallelBehaviors: ResolvedStepBehavior[],
221
- ): boolean {
222
- if (progressCreated || !parallelBehaviors.some((behavior) => behavior.progress)) {
223
- return progressCreated;
224
- }
225
- writeInitialProgressFile(chainDir);
226
- return true;
227
- }
228
-
229
- function finalizeParallelWorktreeHandoff(input: {
230
- output: string;
231
- worktreeSetup: WorktreeSetup;
232
- artifactsDir: string;
233
- runId: string;
234
- cwd: string;
235
- stepIndex: number;
236
- flatStartIndex: number;
237
- agents: string[];
238
- results: SingleResult[];
239
- }): { output: string; reference?: NonNullable<Details["parallelHandoff"]> } {
240
- const diffs = diffWorktrees(input.worktreeSetup, input.agents, path.join(input.artifactsDir, "worktree-diffs", input.runId, `step-${input.stepIndex}`));
241
- const diffSummary = formatWorktreeDiffSummary(diffs);
242
- const manifestPath = parallelHandoffPath(input.artifactsDir, input.runId);
243
- const handoff = {
244
- manifestPath,
245
- runId: input.runId,
246
- mode: "chain" as const,
247
- source: "foreground" as const,
248
- cwd: input.cwd,
249
- stepIndex: input.stepIndex,
250
- flatStartIndex: input.flatStartIndex,
251
- setup: input.worktreeSetup,
252
- diffs,
253
- results: input.results.map((result) => ({
254
- agent: result.agent,
255
- status: result.stopped ? "stopped" as const : result.detached ? "detached" as const : result.interrupted ? "paused" as const : result.exitCode === 0 ? "completed" as const : "failed" as const,
256
- summary: getSingleResultOutput(result) || result.error || "(no output)",
257
- ...(result.artifactPaths?.outputPath ? { outputPath: result.artifactPaths.outputPath } : {}),
258
- ...(result.structuredOutput !== undefined ? { structuredOutput: result.structuredOutput } : {}),
259
- ...(result.structuredOutputPath ? { structuredOutputPath: result.structuredOutputPath } : {}),
260
- ...(result.sessionFile ? { sessionPath: result.sessionFile } : {}),
261
- })),
262
- };
263
- try {
264
- writeParallelHandoffGroup(handoff);
265
- const cleanup = cleanupWorktrees(input.worktreeSetup, { kind: "preserve", capturedDiffs: diffs, handoffManifestPath: manifestPath });
266
- const reference = writeParallelHandoffGroup({ ...handoff, cleanup });
267
- const suffix = [diffSummary, formatParallelHandoffReference(reference)].filter(Boolean).join("\n\n");
268
- return { output: suffix ? `${input.output}\n\n${suffix}` : input.output, reference };
269
- } catch (error) {
270
- const suffix = [diffSummary, formatParallelHandoffError(error)].filter(Boolean).join("\n\n");
271
- return { output: suffix ? `${input.output}\n\n${suffix}` : input.output };
272
- }
273
- }
274
-
275
- function resolveChainToolBudget(input: { stepBudget?: ToolBudgetConfig; runBudget?: ResolvedToolBudget; agentBudget?: ToolBudgetConfig; configBudget?: ToolBudgetConfig }): { toolBudget?: ResolvedToolBudget; error?: string } {
276
- if (input.stepBudget !== undefined) {
277
- const resolved = validateToolBudgetConfig(input.stepBudget, "toolBudget");
278
- return { toolBudget: resolved.budget, error: resolved.error };
279
- }
280
- if (input.runBudget !== undefined) return { toolBudget: input.runBudget };
281
- if (input.agentBudget !== undefined) {
282
- const resolved = validateToolBudgetConfig(input.agentBudget, "agent.toolBudget");
283
- return { toolBudget: resolved.budget, error: resolved.error };
284
- }
285
- const resolved = validateToolBudgetConfig(input.configBudget, "config.toolBudget");
286
- return { toolBudget: resolved.budget, error: resolved.error };
287
- }
288
-
289
- async function runParallelChainTasks(input: ParallelChainRunInput): Promise<SingleResult[]> {
290
- const concurrency = input.step.concurrency ?? MAX_CONCURRENCY;
291
- const failFast = input.step.failFast ?? false;
292
- let aborted = false;
293
- const effectiveModels = input.step.parallel.map((task) => {
294
- const taskAgentConfig = input.agents.find((agent) => agent.name === task.agent);
295
- return resolveEffectiveSubagentModel(
296
- task.model,
297
- taskAgentConfig?.model,
298
- input.ctx.model,
299
- input.availableModels,
300
- input.ctx.model?.provider,
301
- { scope: input.modelScope },
302
- );
303
- });
304
- for (let taskIndex = 0; taskIndex < input.step.parallel.length; taskIndex++) {
305
- const task = input.step.parallel[taskIndex]!;
306
- input.sessionFileForTask?.(task.agent, input.globalTaskIndex + taskIndex, effectiveModels[taskIndex]);
307
- }
308
-
309
- const completedResults: SingleResult[] = [];
310
- if (input.foregroundControl) retainForegroundSchedulingOwner(input.foregroundControl);
311
- const parallelResults = await mapConcurrent(
312
- input.step.parallel,
313
- concurrency,
314
- async (task, taskIndex) => {
315
- const childIndex = input.globalTaskIndex + taskIndex;
316
- const budgetState = usageBudgetState(input.usageBudget, sumResultsCost(input.results.concat(completedResults)));
317
- if (budgetState?.exhausted) {
318
- return {
319
- index: childIndex,
320
- agent: task.agent,
321
- task: input.parallelTemplates[taskIndex] ?? "(skipped)",
322
- exitCode: 1,
323
- messages: [],
324
- usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 },
325
- error: usageBudgetExceededMessage(budgetState),
326
- skipped: true,
327
- } as SingleResult;
328
- }
329
- if (aborted && failFast) {
330
- return {
331
- index: childIndex,
332
- agent: task.agent,
333
- task: "(skipped)",
334
- exitCode: -1,
335
- messages: [],
336
- usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 },
337
- error: "Skipped due to fail-fast",
338
- } as SingleResult;
339
- }
340
-
341
- const taskTemplate = input.parallelTemplates[taskIndex] ?? "{previous}";
342
- const behavior = suppressProgressForReadOnlyTask(input.parallelBehaviors[taskIndex]!, taskTemplate, input.originalTask);
343
- const taskAgentConfig = input.agents.find((agent) => agent.name === task.agent);
344
- const templateHasPrevious = taskTemplate.includes("{previous}");
345
- const { prefix, suffix } = buildChainInstructions(
346
- { ...behavior, output: false },
347
- input.chainDir,
348
- false,
349
- templateHasPrevious ? undefined : input.prev,
350
- );
351
-
352
- let taskStr = resolveOutputReferences(taskTemplate, input.outputs);
353
- taskStr = taskStr.replace(/\{task\}/g, input.originalTask);
354
- taskStr = taskStr.replace(/\{previous\}/g, input.prev);
355
- taskStr = taskStr.replace(/\{chain_dir\}/g, input.chainDir);
356
- const cleanTask = taskStr;
357
- taskStr = prefix + taskStr + suffix;
358
-
359
- const effectiveModel = effectiveModels[taskIndex];
360
- const maxSubagentDepth = resolveChildMaxSubagentDepth(input.maxSubagentDepth, taskAgentConfig?.maxSubagentDepth);
361
- const toolBudget = resolveChainToolBudget({ stepBudget: task.toolBudget, runBudget: input.toolBudget, agentBudget: taskAgentConfig?.toolBudget, configBudget: input.configToolBudget });
362
- if (toolBudget.error) throw new Error(toolBudget.error);
363
-
364
- const taskCwd = input.worktreeSetup
365
- ? input.worktreeSetup.worktrees[taskIndex]!.agentCwd
366
- : resolveChildCwd(input.cwd ?? input.ctx.cwd, task.cwd);
367
-
368
- const outputPath = typeof behavior.output === "string"
369
- ? (path.isAbsolute(behavior.output) ? behavior.output : path.join(input.chainDir, behavior.output))
370
- : undefined;
371
- taskStr = injectSingleOutputInstruction(taskStr, outputPath, taskAgentConfig);
372
- const interruptController = new AbortController();
373
- if (input.foregroundControl) {
374
- const thinking = resolveEffectiveThinking(effectiveModel, input.thinkingOverrideForTask?.(task.agent, childIndex, effectiveModel));
375
- beginForegroundChild(input.foregroundControl, {
376
- index: childIndex,
377
- agent: task.agent,
378
- authoredTask: cleanTask,
379
- effectivePrompt: taskStr,
380
- cwd: taskCwd,
381
- ...(outputPath ? { outputPath } : {}),
382
- description: `${task.agent} child`,
383
- ...(effectiveModel ? { model: effectiveModel } : {}),
384
- ...(thinking ? { thinking } : {}),
385
- interrupt: () => {
386
- if (interruptController.signal.aborted) return false;
387
- interruptController.abort();
388
- return true;
389
- },
390
- });
391
- }
392
-
393
- const structuredRuntime = task.outputSchema
394
- ? createStructuredOutputRuntime(task.outputSchema, path.join(input.chainDir, "structured-output"))
395
- : undefined;
396
- const agentContract = task.agentContract ?? input.step.agentContract ?? input.agentContract;
397
- let result!: SingleResult;
398
- try {
399
- result = await runSync(input.ctx.cwd, input.agents, task.agent, taskStr, {
400
- permissions: input.permissions,
401
- parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
402
- llmIntentArbiter: createTaskMutationArbiter(input.ctx),
403
- ...workflowForegroundSteeringLaunchOptions(input.foregroundControl, childIndex),
404
- capabilityCeiling: input.capabilityCeiling,
405
- runFanoutBudget: input.runFanoutBudget ? { ...input.runFanoutBudget, parentPath: `${input.runFanoutBudget.parentPath ? `${input.runFanoutBudget.parentPath}/` : ""}chain[${input.stepIndex}]${input.dynamic ? `.expand[${taskIndex}]` : `.parallel[${taskIndex}]`}` } : undefined,
406
- context: input.contextForAgent?.(task.agent),
407
- cwd: taskCwd,
408
- signal: input.signal,
409
- interruptSignal: interruptController.signal,
410
- allowIntercomDetach: taskAgentConfig?.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === true,
411
- intercomEvents: input.intercomEvents,
412
- runId: input.runId,
413
- index: childIndex,
414
- sessionDir: input.sessionDirForIndex(childIndex),
415
- sessionFile: input.sessionFileForTask?.(task.agent, childIndex, effectiveModel)
416
- ?? input.sessionFileForIndex?.(childIndex),
417
- thinkingOverride: input.thinkingOverrideForTask?.(task.agent, childIndex, effectiveModel),
418
- share: input.shareEnabled,
419
- artifactsDir: input.artifactConfig.enabled ? input.artifactsDir : undefined,
420
- artifactConfig: input.artifactConfig,
421
- outputPath,
422
- outputMode: behavior.outputMode,
423
- maxSubagentDepth,
424
- controlConfig: input.controlConfig,
425
- onControlEvent: input.onControlEvent,
426
- intercomSessionName: input.childIntercomTarget?.(task.agent, childIndex),
427
- orchestratorIntercomTarget: input.orchestratorIntercomTarget,
428
- nestedRoute: input.nestedRoute,
429
- modelOverride: effectiveModel,
430
- availableModels: input.availableModels,
431
- preferredModelProvider: input.ctx.model?.provider,
432
- modelScope: input.modelScope,
433
- skills: behavior.skills === false ? [] : behavior.skills,
434
- structuredOutput: structuredRuntime,
435
- agentContract,
436
- acceptance: task.acceptance,
437
- acceptanceContext: { mode: "chain", dynamic: input.dynamic && task.acceptance === undefined },
438
- onEffectivePrompt: input.foregroundControl ? (prompt) => updateLiveEffectivePrompt(input.foregroundControl!, childIndex, prompt) : undefined,
439
- timeoutMs: input.timeoutMs,
440
- deadlineAt: input.deadlineAt,
441
- toolTimeoutMs: input.callToolTimeoutMs,
442
- configToolTimeoutMs: input.configToolTimeoutMs,
443
- turnBudget: input.turnBudget,
444
- onDetachedExit: (result) => {
445
- try {
446
- if (input.foregroundControl) finishForegroundChild(input.foregroundControl, childIndex);
447
- } finally {
448
- input.onDetachedExit?.(childIndex, result);
449
- }
450
- },
451
- toolBudget: toolBudget.toolBudget,
452
- onUpdate: input.onUpdate
453
- ? (progressUpdate) => {
454
- const stepResults = progressUpdate.details?.results || [];
455
- const stepProgress = progressUpdate.details?.progress || [];
456
- if (input.foregroundControl && stepProgress.length > 0) {
457
- updateForegroundChild(input.foregroundControl, childIndex, stepProgress[0]);
458
- }
459
- input.onUpdate?.({
460
- ...progressUpdate,
461
- details: {
462
- mode: "chain",
463
- results: input.results.concat(stepResults),
464
- progress: input.allProgress.concat(stepProgress),
465
- controlEvents: progressUpdate.details?.controlEvents,
466
- chainAgents: input.chainAgents,
467
- totalSteps: input.totalSteps,
468
- currentStepIndex: input.stepIndex,
469
- outputs: input.outputs,
470
- workflowGraph: buildWorkflowGraphSnapshot({
471
- runId: input.runId,
472
- mode: "chain",
473
- steps: input.chainSteps,
474
- results: input.results.concat(stepResults),
475
- currentStepIndex: input.stepIndex,
476
- currentFlatIndex: childIndex,
477
- dynamicChildren: input.dynamicChildren,
478
- dynamicGroupStatuses: input.dynamicGroupStatuses,
479
- }),
480
- },
481
- });
482
- }
483
- : undefined,
484
- });
485
- } finally {
486
- // Rejected attached attempts still release their parallel child control;
487
- // detached receipts transfer ownership to onDetachedExit.
488
- if (!result?.detached) {
489
- if (input.foregroundControl) finishForegroundChild(input.foregroundControl, childIndex);
490
- input.onForegroundChildSettled?.();
491
- }
492
- }
493
-
494
- if (result.exitCode !== 0 && failFast) {
495
- aborted = true;
496
- }
497
- recordRun(task.agent, cleanTask, result.exitCode, result.progressSummary?.durationMs ?? 0);
498
- completedResults.push(result);
499
- return result;
500
- },
501
- input.globalSemaphore,
502
- () => {
503
- if (input.foregroundControl) settleForegroundSchedulingOwner(input.foregroundControl);
504
- input.onForegroundChildSettled?.();
505
- },
506
- );
507
-
508
- return parallelResults;
509
- }
510
-
511
- interface ChainExecutionParams {
512
- chain: ChainStep[];
513
- task?: string;
514
- agents: AgentConfig[];
515
- ctx: ExtensionContext;
516
- intercomEvents?: IntercomEventBus;
517
- signal?: AbortSignal;
518
- runId: string;
519
- cwd?: string;
520
- shareEnabled: boolean;
521
- sessionDirForIndex: (idx?: number) => string | undefined;
522
- sessionFileForIndex?: (idx?: number) => string | undefined;
523
- sessionFileForTask?: (agentName: string, idx?: number, modelOverride?: string) => string | undefined;
524
- thinkingOverrideForTask?: (agentName: string, idx?: number, modelOverride?: string) => AgentConfig["thinking"] | undefined;
525
- contextForAgent?: (agentName: string) => ContextMode;
526
- modelScope?: ModelScopeConfig;
527
- artifactsDir: string;
528
- artifactConfig: ArtifactConfig;
529
- includeProgress?: boolean;
530
- clarify?: boolean;
531
- onUpdate?: (r: AgentToolResult<Details>) => void;
532
- onControlEvent?: (event: ControlEvent) => void;
533
- controlConfig: ResolvedControlConfig;
534
- agentContract?: AgentContract;
535
- childIntercomTarget?: (agent: string, index: number) => string | undefined;
536
- orchestratorIntercomTarget?: string;
537
- foregroundControl?: ForegroundRunControl;
538
- chainSkills?: string[];
539
- chainDir?: string;
540
- dynamicFanoutMaxItems?: number;
541
- maxSubagentDepth: number;
542
- nestedRoute?: NestedRouteInfo;
543
- worktreeSetupHook?: string;
544
- worktreeSetupHookTimeoutMs?: number;
545
- worktreeBaseDir?: string;
546
- timeoutMs?: number;
547
- deadlineAt?: number;
548
- turnBudget?: ResolvedTurnBudget;
549
- onDetachedExit?: (index: number, result: SingleResult) => void;
550
- /** Ownership callback used when parallel siblings outlive executeChain rejection. */
551
- onForegroundChildSettled?: () => void;
552
- toolBudget?: ResolvedToolBudget;
553
- usageBudget?: UsageBudgetConfig;
554
- configToolBudget?: ToolBudgetConfig;
555
- /** Optional per-call hard toolTimeoutMs override (highest precedence). */
556
- callToolTimeoutMs?: number;
557
- /** Global config.toolTimeoutMs (third precedence, after agent frontmatter). */
558
- configToolTimeoutMs?: number;
559
- /** SELESAI_SUBAGENT_TOOL_TIMEOUT_MS override (lowest precedence). */
560
- toolTimeoutMsEnv?: string | undefined;
561
- permissions?: PermissionConfig;
562
- /** Global cap on simultaneously-running tasks within this chain. Defaults to DEFAULT_GLOBAL_CONCURRENCY_LIMIT. */
563
- globalConcurrencyLimit?: number;
564
- capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
565
- runFanoutBudget?: RunFanoutBudgetDescriptor;
566
- }
567
-
568
- interface ChainExecutionResult {
569
- content: Array<{ type: "text"; text: string }>;
570
- details: Details;
571
- isError?: boolean;
572
- /** User requested async execution via TUI - caller should dispatch to executeAsyncChain */
573
- requestedAsync?: {
574
- chain: ChainStep[];
575
- chainSkills: string[];
576
- };
577
- }
578
-
579
- /**
580
- * Execute a chain of subagent steps
581
- */
582
- export async function executeChain(params: ChainExecutionParams): Promise<ChainExecutionResult> {
583
- const {
584
- chain: chainSteps,
585
- agents,
586
- ctx,
587
- signal,
588
- runId,
589
- cwd,
590
- shareEnabled,
591
- sessionDirForIndex,
592
- sessionFileForIndex,
593
- sessionFileForTask,
594
- thinkingOverrideForTask,
595
- artifactsDir,
596
- artifactConfig,
597
- includeProgress,
598
- clarify,
599
- onUpdate,
600
- onControlEvent,
601
- controlConfig,
602
- onDetachedExit,
603
- childIntercomTarget,
604
- orchestratorIntercomTarget,
605
- foregroundControl,
606
- intercomEvents,
607
- chainSkills: chainSkillsParam,
608
- chainDir: chainDirBase,
609
- modelScope,
610
- } = params;
611
- const chainSkills = chainSkillsParam ?? [];
612
-
613
- const results: SingleResult[] = [];
614
- const outputs: ChainOutputMap = {};
615
- const dynamicChildren: ChainExecutionDetailsInput["dynamicChildren"] = {};
616
- const dynamicGroupStatuses: ChainExecutionDetailsInput["dynamicGroupStatuses"] = {};
617
- const allProgress: AgentProgress[] = [];
618
- const allArtifactPaths: ArtifactPaths[] = [];
619
- let parallelHandoff: Details["parallelHandoff"];
620
-
621
- const chainAgents: string[] = chainSteps.map((step) =>
622
- isCheckpointStep(step)
623
- ? `checkpoint:${step.checkpoint}`
624
- : isParallelStep(step)
625
- ? `[${step.parallel.map((t) => t.agent).join("+")}]`
626
- : isDynamicParallelStep(step)
627
- ? `expand:${step.parallel.agent}`
628
- : (step as SequentialStep).agent,
629
- );
630
- const totalSteps = chainSteps.length;
631
-
632
- const makeDetailsInput = (overrides: Pick<Partial<ChainExecutionDetailsInput>, "currentStepIndex" | "currentFlatIndex" | "checkpoint"> = {}): ChainExecutionDetailsInput => ({
633
- results,
634
- ...(includeProgress !== undefined ? { includeProgress } : {}),
635
- allProgress,
636
- allArtifactPaths,
637
- artifactsDir,
638
- chainAgents,
639
- chainSteps,
640
- totalSteps,
641
- runId,
642
- outputs,
643
- dynamicChildren,
644
- dynamicGroupStatuses,
645
- ...(parallelHandoff ? { parallelHandoff } : {}),
646
- usageBudget: params.usageBudget,
647
- ...overrides,
648
- });
649
-
650
- const usageBudgetError = (stepIndex: number, flatIndex: number): ChainExecutionResult | undefined => {
651
- const state = usageBudgetState(params.usageBudget, sumResultsCost(results));
652
- if (!state?.exhausted) return undefined;
653
- return buildChainExecutionErrorResult(usageBudgetExceededMessage(state), makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: flatIndex }));
654
- };
655
-
656
- const firstStep = chainSteps[0]!;
657
- const originalTask = params.task
658
- ?? (isCheckpointStep(firstStep)
659
- ? undefined
660
- : isParallelStep(firstStep)
661
- ? firstStep.parallel[0]!.task
662
- : isDynamicParallelStep(firstStep)
663
- ? firstStep.parallel.task
664
- : (firstStep as SequentialStep).task)
665
- ?? "";
666
- try {
667
- validateChainOutputBindings(chainSteps, { maxItems: params.dynamicFanoutMaxItems });
668
- } catch (error) {
669
- if (error instanceof ChainOutputValidationError) {
670
- return {
671
- content: [{ type: "text", text: error.message }],
672
- isError: true,
673
- details: buildChainExecutionDetails(makeDetailsInput()),
674
- };
675
- }
676
- throw error;
677
- }
678
-
679
- const chainDir = createChainDir(runId, chainDirBase);
680
- const hasParallelSteps = chainSteps.some((step) => isParallelStep(step) || isDynamicParallelStep(step) || isCheckpointStep(step));
681
- let templates: ResolvedTemplates = resolveChainTemplates(chainSteps);
682
- const shouldClarify = clarify === true && ctx.hasUI && !hasParallelSteps;
683
- let tuiBehaviorOverrides: (BehaviorOverride | undefined)[] | undefined;
684
- const availableModels: ModelInfo[] = ctx.modelRegistry.getAvailable().map(toModelInfo);
685
- const availableSkills = discoverAvailableSkills(cwd ?? ctx.cwd);
686
-
687
- if (shouldClarify) {
688
- const seqSteps = chainSteps as SequentialStep[];
689
- const agentConfigs: AgentConfig[] = [];
690
- for (const step of seqSteps) {
691
- const config = agents.find((a) => a.name === step.agent);
692
- if (!config) {
693
- removeChainDir(chainDir);
694
- return {
695
- content: [{ type: "text", text: `Unknown agent: ${step.agent}` }],
696
- isError: true,
697
- details: buildChainExecutionDetails(makeDetailsInput({ currentStepIndex: seqSteps.indexOf(step) })),
698
- };
699
- }
700
- agentConfigs.push(config);
701
- }
702
-
703
- const stepOverrides: StepOverrides[] = seqSteps.map((step) => ({
704
- output: step.output,
705
- outputMode: step.outputMode,
706
- reads: step.reads,
707
- progress: step.progress,
708
- skills: normalizeSkillInput(step.skill),
709
- model: step.model,
710
- }));
711
-
712
- const resolvedBehaviors = agentConfigs.map((config, i) =>
713
- resolveStepBehavior(config, stepOverrides[i]!, chainSkills),
714
- );
715
- const flatTemplates = templates as string[];
716
-
717
- const result = await ctx.ui.custom<ChainClarifyResult>(
718
- (tui, theme, _kb, done) =>
719
- new ChainClarifyComponent(
720
- tui,
721
- theme,
722
- agentConfigs,
723
- flatTemplates,
724
- originalTask,
725
- chainDir,
726
- resolvedBehaviors,
727
- availableModels,
728
- ctx.model?.provider,
729
- availableSkills,
730
- done,
731
- ),
732
- {
733
- overlay: true,
734
- overlayOptions: { anchor: "center", width: 84, maxHeight: "80%" },
735
- },
736
- );
737
-
738
- if (!result || !result.confirmed) {
739
- removeChainDir(chainDir);
740
- return {
741
- content: [{ type: "text", text: "Chain cancelled" }],
742
- details: buildChainExecutionDetails(makeDetailsInput()),
743
- };
744
- }
745
-
746
- if (result.runInBackground) {
747
- removeChainDir(chainDir);
748
- const updatedChain: ChainStep[] = chainSteps.map((step, i) => {
749
- if (isParallelStep(step)) return step;
750
- const override = result.behaviorOverrides[i];
751
- return {
752
- ...step,
753
- task: result.templates[i]!,
754
- ...(override?.model !== undefined ? { model: override.model } : {}),
755
- ...(override?.output !== undefined ? { output: override.output } : {}),
756
- ...("outputMode" in step && step.outputMode !== undefined ? { outputMode: step.outputMode } : {}),
757
- ...(override?.reads !== undefined ? { reads: override.reads } : {}),
758
- ...(override?.progress !== undefined ? { progress: override.progress } : {}),
759
- ...(override?.skills !== undefined ? { skill: override.skills } : {}),
760
- };
761
- });
762
- return {
763
- content: [{ type: "text", text: "Launching in background..." }],
764
- details: buildChainExecutionDetails(makeDetailsInput()),
765
- requestedAsync: { chain: updatedChain, chainSkills },
766
- };
767
- }
768
-
769
- templates = result.templates;
770
- tuiBehaviorOverrides = result.behaviorOverrides;
771
- }
772
-
773
- const deadlineAt = params.deadlineAt ?? (params.timeoutMs !== undefined ? Date.now() + params.timeoutMs : undefined);
774
- const globalSemaphore = new Semaphore(params.globalConcurrencyLimit ?? DEFAULT_GLOBAL_CONCURRENCY_LIMIT);
775
- let prev = "";
776
- let globalTaskIndex = 0;
777
- let progressCreated = false;
778
-
779
- for (let stepIndex = 0; stepIndex < chainSteps.length; stepIndex++) {
780
- const budgetError = usageBudgetError(stepIndex, globalTaskIndex);
781
- if (budgetError) return budgetError;
782
- const step = chainSteps[stepIndex]!;
783
- const stepTemplates = templates[stepIndex]!;
784
-
785
- if (isCheckpointStep(step)) {
786
- const checkpoint = { name: step.checkpoint, ...(step.message ? { message: step.message } : {}), status: "pending" as const, stepIndex };
787
- return {
788
- content: [{ type: "text", text: `Chain paused at checkpoint '${step.checkpoint}'. Approve with subagent({ action: "approve-checkpoint", id: "${runId}" }) or reject with subagent({ action: "reject-checkpoint", id: "${runId}" }).${step.message ? `
789
-
790
- ${step.message}` : ""}` }],
791
- details: buildChainExecutionDetails(makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex, checkpoint })),
792
- };
793
- }
794
-
795
- if (isParallelStep(step)) {
796
- const parallelTemplates = stepTemplates as string[];
797
- const parallelCwd = resolveChildCwd(cwd ?? ctx.cwd, step.cwd);
798
- let worktreeSetup: WorktreeSetup | undefined;
799
- let worktreeFinalized = false;
800
- if (step.worktree) {
801
- const worktreeTaskCwdConflict = findWorktreeTaskCwdConflict(step.parallel, parallelCwd);
802
- if (worktreeTaskCwdConflict) {
803
- return buildChainExecutionErrorResult(
804
- `parallel chain step ${stepIndex + 1}: ${formatWorktreeTaskCwdConflict(worktreeTaskCwdConflict, parallelCwd)}`,
805
- makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex }),
806
- );
807
- }
808
- try {
809
- worktreeSetup = createWorktrees(parallelCwd, `${runId}-s${stepIndex}`, step.parallel.length, {
810
- agents: step.parallel.map((task) => task.agent),
811
- setupHook: params.worktreeSetupHook
812
- ? { hookPath: params.worktreeSetupHook, timeoutMs: params.worktreeSetupHookTimeoutMs }
813
- : undefined,
814
- baseDir: params.worktreeBaseDir,
815
- });
816
- } catch (error) {
817
- const message = error instanceof Error ? error.message : String(error);
818
- return buildChainExecutionErrorResult(message, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex }));
819
- }
820
- }
821
-
822
- try {
823
- if (worktreeSetup) {
824
- writePendingParallelHandoff({
825
- manifestPath: parallelHandoffPath(artifactsDir, runId),
826
- runId,
827
- mode: "chain",
828
- source: "foreground",
829
- cwd: parallelCwd,
830
- stepIndex,
831
- flatStartIndex: globalTaskIndex,
832
- setup: worktreeSetup,
833
- });
834
- }
835
- const agentNames = step.parallel.map((task) => task.agent);
836
- const parallelBehaviors = resolveParallelBehaviors(step.parallel, agents, stepIndex, chainSkills)
837
- .map((behavior, taskIndex) => suppressProgressForReadOnlyTask(behavior, parallelTemplates[taskIndex] ?? step.parallel[taskIndex]?.task, originalTask));
838
- for (let taskIndex = 0; taskIndex < step.parallel.length; taskIndex++) {
839
- const behavior = parallelBehaviors[taskIndex]!;
840
- const outputPath = typeof behavior.output === "string"
841
- ? (path.isAbsolute(behavior.output) ? behavior.output : path.join(chainDir, behavior.output))
842
- : undefined;
843
- const validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Parallel chain step ${stepIndex + 1} task ${taskIndex + 1} (${step.parallel[taskIndex]!.agent})`);
844
- if (validationError) return buildChainExecutionErrorResult(validationError, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex + taskIndex }));
845
- }
846
- progressCreated = ensureParallelProgressFile(chainDir, progressCreated, parallelBehaviors);
847
- createParallelDirs(chainDir, stepIndex, step.parallel.length, agentNames);
848
-
849
- const parallelResults = await runParallelChainTasks({
850
- step,
851
- parallelTemplates,
852
- parallelBehaviors,
853
- agents,
854
- stepIndex,
855
- availableModels,
856
- modelScope,
857
- chainDir,
858
- prev,
859
- originalTask,
860
- ctx,
861
- intercomEvents,
862
- cwd,
863
- runId,
864
- globalTaskIndex,
865
- sessionDirForIndex,
866
- sessionFileForIndex,
867
- sessionFileForTask,
868
- thinkingOverrideForTask,
869
- contextForAgent: params.contextForAgent,
870
- shareEnabled,
871
- artifactConfig,
872
- artifactsDir,
873
- signal,
874
- onUpdate,
875
- results,
876
- allProgress,
877
- outputs,
878
- chainAgents,
879
- chainSteps,
880
- totalSteps,
881
- dynamicChildren,
882
- dynamicGroupStatuses,
883
- controlConfig,
884
- agentContract: params.agentContract,
885
- onControlEvent,
886
- childIntercomTarget,
887
- orchestratorIntercomTarget,
888
- foregroundControl,
889
- nestedRoute: params.nestedRoute,
890
- worktreeSetup,
891
- maxSubagentDepth: params.maxSubagentDepth,
892
- timeoutMs: params.timeoutMs,
893
- deadlineAt,
894
- callToolTimeoutMs: params.callToolTimeoutMs,
895
- configToolTimeoutMs: params.configToolTimeoutMs,
896
- turnBudget: params.turnBudget,
897
- usageBudget: params.usageBudget,
898
- onDetachedExit,
899
- onForegroundChildSettled: params.onForegroundChildSettled,
900
- toolBudget: params.toolBudget,
901
- configToolBudget: params.configToolBudget,
902
- globalSemaphore,
903
- permissions: params.permissions,
904
- runFanoutBudget: params.runFanoutBudget,
905
- });
906
- globalTaskIndex += step.parallel.length;
907
-
908
- for (const result of parallelResults) {
909
- results.push(result);
910
- if (result.progress) allProgress.push(result.progress);
911
- if (result.artifactPaths) allArtifactPaths.push(result.artifactPaths);
912
- }
913
- let worktreeSuffix = "";
914
- if (worktreeSetup) {
915
- worktreeFinalized = true;
916
- const finalized = finalizeParallelWorktreeHandoff({
917
- output: "",
918
- worktreeSetup,
919
- artifactsDir,
920
- runId,
921
- cwd: parallelCwd,
922
- stepIndex,
923
- flatStartIndex: globalTaskIndex - step.parallel.length,
924
- agents: agentNames,
925
- results: parallelResults,
926
- });
927
- if (finalized.reference) parallelHandoff = finalized.reference;
928
- worktreeSuffix = finalized.output.trim();
929
- }
930
- const interruptedIndexInStep = parallelResults.findIndex((result) => result.interrupted);
931
- const interrupted = interruptedIndexInStep >= 0 ? parallelResults[interruptedIndexInStep] : undefined;
932
- if (interrupted) {
933
- return {
934
- content: [{ type: "text", text: `Chain paused after interrupt at step ${stepIndex + 1} (${interrupted.agent}). Waiting for explicit next action.` }],
935
- details: buildChainExecutionDetails(makeDetailsInput({
936
- currentStepIndex: stepIndex,
937
- currentFlatIndex: globalTaskIndex - step.parallel.length + interruptedIndexInStep,
938
- })),
939
- };
940
- }
941
- const detachedIndexInStep = parallelResults.findIndex((result) => result.detached);
942
- const detached = detachedIndexInStep >= 0 ? parallelResults[detachedIndexInStep] : undefined;
943
- if (detached) {
944
- return {
945
- content: [{ type: "text", text: `Chain detached for intercom coordination at step ${stepIndex + 1} (${detached.agent}). Reply to the supervisor request first, then wait with subagent_wait({ id: "${runId}" }). Use subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.` }],
946
- details: buildChainExecutionDetails(makeDetailsInput({
947
- currentStepIndex: stepIndex,
948
- currentFlatIndex: globalTaskIndex - step.parallel.length + detachedIndexInStep,
949
- })),
950
- };
951
- }
952
-
953
- const failures = parallelResults
954
- .map((result, originalIndex) => ({ ...result, originalIndex }))
955
- .filter((result) => result.exitCode !== 0 && result.exitCode !== -1);
956
- if (failures.length > 0) {
957
- const failureSummary = failures
958
- .map((failure) => `- Task ${failure.originalIndex + 1} (${failure.agent}): ${failure.error || "failed"}`)
959
- .join("\n");
960
- const errorMsg = `Parallel step ${stepIndex + 1} failed:\n${failureSummary}`;
961
- const summary = buildChainSummary(chainSteps, results, chainDir, "failed", {
962
- index: stepIndex,
963
- error: errorMsg,
964
- });
965
- return {
966
- content: [{ type: "text", text: summary }],
967
- isError: true,
968
- details: buildChainExecutionDetails(makeDetailsInput({
969
- currentStepIndex: stepIndex,
970
- currentFlatIndex: globalTaskIndex - step.parallel.length + failures[0]!.originalIndex,
971
- })),
972
- };
973
- }
974
- const acceptanceFailures = parallelResults
975
- .map((result, originalIndex) => ({ result, originalIndex, task: step.parallel[originalIndex] }))
976
- .filter(({ result, task }) => isAgentContractV1(task?.agentContract ?? step.agentContract ?? params.agentContract) && (task?.gateOn ?? step.gateOn) === "acceptance" && result.acceptance?.status === "rejected");
977
- if (acceptanceFailures.length > 0) {
978
- const acceptanceSummary = acceptanceFailures
979
- .map(({ result, originalIndex }) => `- Task ${originalIndex + 1} (${result.agent}): ${(result.acceptance ? acceptanceFailureMessage(result.acceptance) : undefined) ?? "acceptance rejected"}`)
980
- .join("\n");
981
- const errorMsg = `Parallel step ${stepIndex + 1} acceptance gate failed:\n${acceptanceSummary}`;
982
- const summary = buildChainSummary(chainSteps, results, chainDir, "failed", { index: stepIndex, error: errorMsg });
983
- return {
984
- content: [{ type: "text", text: summary }],
985
- isError: true,
986
- details: buildChainExecutionDetails(makeDetailsInput({
987
- currentStepIndex: stepIndex,
988
- currentFlatIndex: globalTaskIndex - step.parallel.length + acceptanceFailures[0]!.originalIndex,
989
- })),
990
- };
991
- }
992
-
993
- for (let taskIndex = 0; taskIndex < parallelResults.length; taskIndex++) {
994
- const outputName = step.parallel[taskIndex]?.as;
995
- if (outputName) outputs[outputName] = outputEntryFromResult(parallelResults[taskIndex]!, stepIndex);
996
- }
997
-
998
- const taskResults: ParallelTaskResult[] = parallelResults.map((result, i) => {
999
- const outputTarget = parallelBehaviors[i]?.output;
1000
- const outputTargetPath = typeof outputTarget === "string"
1001
- ? (path.isAbsolute(outputTarget) ? outputTarget : path.join(chainDir, outputTarget))
1002
- : undefined;
1003
- return {
1004
- agent: result.agent,
1005
- taskIndex: i,
1006
- output: getSingleResultOutput(result),
1007
- exitCode: result.exitCode,
1008
- error: result.error,
1009
- timedOut: result.timedOut,
1010
- outputTargetPath,
1011
- outputTargetExists: outputTargetPath ? fs.existsSync(outputTargetPath) : undefined,
1012
- };
1013
- });
1014
- prev = aggregateParallelOutputs(taskResults);
1015
- if (worktreeSuffix) prev = `${prev}\n\n${worktreeSuffix}`;
1016
- } finally {
1017
- if (worktreeSetup && !worktreeFinalized) cleanupWorktrees(worktreeSetup);
1018
- }
1019
- } else if (isDynamicParallelStep(step)) {
1020
- const dynamicStartIndex = globalTaskIndex;
1021
- const reservedDynamicItems = step.expand.maxItems ?? params.dynamicFanoutMaxItems ?? 0;
1022
- let materialized: ReturnType<typeof materializeDynamicParallelStep>;
1023
- try {
1024
- materialized = materializeDynamicParallelStep(step, outputs, stepIndex, { maxItems: params.dynamicFanoutMaxItems });
1025
- } catch (error) {
1026
- const message = error instanceof DynamicFanoutError ? error.message : error instanceof Error ? error.message : String(error);
1027
- dynamicGroupStatuses[stepIndex] = { status: "failed", error: message };
1028
- return buildChainExecutionErrorResult(message, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex }));
1029
- }
1030
-
1031
- try {
1032
- if (params.runFanoutBudget) claimRunFanoutBatch(params.runFanoutBudget, materialized.parallel.map((_, itemIndex) => `chain[${stepIndex}].expand[${itemIndex}]`));
1033
- } catch (error) {
1034
- const message = error instanceof Error ? error.message : String(error);
1035
- dynamicGroupStatuses[stepIndex] = { status: "failed", error: message };
1036
- const result = buildChainExecutionErrorResult(message, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex }));
1037
- if (error instanceof RunFanoutLimitError) {
1038
- result.details.runFanoutBudget = error.snapshot;
1039
- result.details.runFanoutRejection = error.rejection;
1040
- }
1041
- return result;
1042
- }
1043
-
1044
- dynamicChildren[stepIndex] = materialized.items.map((item, itemIndex) => ({
1045
- agent: step.parallel.agent,
1046
- label: materialized.parallel[itemIndex]?.label,
1047
- flatIndex: globalTaskIndex + itemIndex,
1048
- itemKey: item.key,
1049
- structured: Boolean(step.parallel.outputSchema),
1050
- }));
1051
-
1052
- if (materialized.parallel.length === 0) {
1053
- const collection: DynamicCollectedResult[] = [];
1054
- try {
1055
- await validateDynamicCollection(step.collect.outputSchema, collection);
1056
- } catch (error) {
1057
- const message = error instanceof DynamicFanoutError ? error.message : error instanceof Error ? error.message : String(error);
1058
- dynamicGroupStatuses[stepIndex] = { status: "failed", error: message };
1059
- return buildChainExecutionErrorResult(message, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex }));
1060
- }
1061
- outputs[step.collect.as] = {
1062
- text: JSON.stringify(collection),
1063
- structured: collection,
1064
- agent: step.parallel.agent,
1065
- stepIndex,
1066
- };
1067
- dynamicGroupStatuses[stepIndex] = { status: "completed" };
1068
- if (step.acceptance !== undefined) {
1069
- const effectiveGroupAcceptance = resolveEffectiveAcceptance({
1070
- explicit: step.acceptance,
1071
- agentName: step.parallel.agent,
1072
- acceptanceRole: agents.find((agent) => agent.name === step.parallel.agent)?.acceptanceRole,
1073
- task: (step.parallel.task ?? originalTask ?? "").replace(/\{task\}/g, originalTask ?? ""),
1074
- mode: "chain",
1075
- dynamicGroup: true,
1076
- agentContract: step.agentContract ?? params.agentContract,
1077
- });
1078
- const groupAcceptance = await evaluateAcceptance({
1079
- acceptance: effectiveGroupAcceptance,
1080
- output: "",
1081
- report: aggregateAcceptanceReport({
1082
- results: [],
1083
- notes: "Dynamic fanout produced 0 results.",
1084
- }),
1085
- cwd: cwd ?? ctx.cwd,
1086
- reportOptional: isAgentContractV1(step.agentContract ?? params.agentContract),
1087
- });
1088
- const dynamicGroupStatus = dynamicGroupStatuses[stepIndex];
1089
- if (!dynamicGroupStatus) throw new Error(`Missing dynamic group status at step ${stepIndex}`);
1090
- dynamicGroupStatus.acceptance = groupAcceptance;
1091
- const groupAcceptanceFailure = !isAgentContractV1(step.agentContract ?? params.agentContract) || step.gateOn === "acceptance" ? acceptanceFailureMessage(groupAcceptance) : undefined;
1092
- if (groupAcceptanceFailure) {
1093
- dynamicGroupStatuses[stepIndex] = { status: "failed", error: groupAcceptanceFailure, acceptance: groupAcceptance };
1094
- return buildChainExecutionErrorResult(groupAcceptanceFailure, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex }));
1095
- }
1096
- }
1097
- prev = "Dynamic fanout produced 0 results.";
1098
- globalTaskIndex = dynamicStartIndex + reservedDynamicItems;
1099
- continue;
1100
- }
1101
-
1102
- const dynamicParallelStep: ParallelStep = {
1103
- parallel: materialized.parallel,
1104
- concurrency: step.concurrency,
1105
- failFast: step.failFast,
1106
- agentContract: step.agentContract,
1107
- gateOn: step.gateOn,
1108
- };
1109
- const parallelTemplates = materialized.parallel.map((task) => task.task ?? "{previous}");
1110
- const parallelBehaviors = resolveParallelBehaviors(dynamicParallelStep.parallel, agents, stepIndex, chainSkills)
1111
- .map((behavior, taskIndex) => suppressProgressForReadOnlyTask(behavior, parallelTemplates[taskIndex] ?? dynamicParallelStep.parallel[taskIndex]?.task, originalTask));
1112
-
1113
- for (let taskIndex = 0; taskIndex < dynamicParallelStep.parallel.length; taskIndex++) {
1114
- const behavior = parallelBehaviors[taskIndex]!;
1115
- const outputPath = typeof behavior.output === "string"
1116
- ? (path.isAbsolute(behavior.output) ? behavior.output : path.join(chainDir, behavior.output))
1117
- : undefined;
1118
- const validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Dynamic chain step ${stepIndex + 1} item ${taskIndex + 1} (${dynamicParallelStep.parallel[taskIndex]!.agent})`);
1119
- if (validationError) {
1120
- dynamicGroupStatuses[stepIndex] = { status: "failed", error: validationError };
1121
- return buildChainExecutionErrorResult(validationError, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex + taskIndex }));
1122
- }
1123
- }
1124
-
1125
- progressCreated = ensureParallelProgressFile(chainDir, progressCreated, parallelBehaviors);
1126
- createParallelDirs(chainDir, stepIndex, dynamicParallelStep.parallel.length, dynamicParallelStep.parallel.map((task) => task.agent));
1127
- const parallelResults = await runParallelChainTasks({
1128
- step: dynamicParallelStep,
1129
- parallelTemplates,
1130
- parallelBehaviors,
1131
- agents,
1132
- stepIndex,
1133
- availableModels,
1134
- modelScope,
1135
- chainDir,
1136
- prev,
1137
- originalTask,
1138
- ctx,
1139
- intercomEvents,
1140
- cwd,
1141
- runId,
1142
- globalTaskIndex,
1143
- sessionDirForIndex,
1144
- sessionFileForIndex,
1145
- sessionFileForTask,
1146
- thinkingOverrideForTask,
1147
- contextForAgent: params.contextForAgent,
1148
- shareEnabled,
1149
- artifactConfig,
1150
- artifactsDir,
1151
- signal,
1152
- onUpdate,
1153
- results,
1154
- allProgress,
1155
- outputs,
1156
- chainAgents,
1157
- chainSteps,
1158
- totalSteps,
1159
- dynamicChildren,
1160
- dynamicGroupStatuses,
1161
- controlConfig,
1162
- agentContract: params.agentContract,
1163
- onControlEvent,
1164
- childIntercomTarget,
1165
- orchestratorIntercomTarget,
1166
- foregroundControl,
1167
- nestedRoute: params.nestedRoute,
1168
- maxSubagentDepth: params.maxSubagentDepth,
1169
- timeoutMs: params.timeoutMs,
1170
- deadlineAt,
1171
- callToolTimeoutMs: params.callToolTimeoutMs,
1172
- configToolTimeoutMs: params.configToolTimeoutMs,
1173
- turnBudget: params.turnBudget,
1174
- usageBudget: params.usageBudget,
1175
- onDetachedExit,
1176
- onForegroundChildSettled: params.onForegroundChildSettled,
1177
- toolBudget: params.toolBudget,
1178
- configToolBudget: params.configToolBudget,
1179
- globalSemaphore,
1180
- permissions: params.permissions,
1181
- runFanoutBudget: params.runFanoutBudget,
1182
- dynamic: true,
1183
- });
1184
- globalTaskIndex = dynamicStartIndex + reservedDynamicItems;
1185
-
1186
- for (const result of parallelResults) {
1187
- results.push(result);
1188
- if (result.progress) allProgress.push(result.progress);
1189
- if (result.artifactPaths) allArtifactPaths.push(result.artifactPaths);
1190
- }
1191
- const collected = collectDynamicResults(step, materialized.items, parallelResults);
1192
- const interruptedIndexInStep = parallelResults.findIndex((result) => result.interrupted);
1193
- const interrupted = interruptedIndexInStep >= 0 ? parallelResults[interruptedIndexInStep] : undefined;
1194
- if (interrupted) {
1195
- return {
1196
- content: [{ type: "text", text: `Chain paused after interrupt at step ${stepIndex + 1} (${interrupted.agent}). Waiting for explicit next action.` }],
1197
- details: buildChainExecutionDetails(makeDetailsInput({
1198
- currentStepIndex: stepIndex,
1199
- currentFlatIndex: dynamicStartIndex + interruptedIndexInStep,
1200
- })),
1201
- };
1202
- }
1203
- const detachedIndexInStep = parallelResults.findIndex((result) => result.detached);
1204
- const detached = detachedIndexInStep >= 0 ? parallelResults[detachedIndexInStep] : undefined;
1205
- if (detached) {
1206
- return {
1207
- content: [{ type: "text", text: `Chain detached for intercom coordination at step ${stepIndex + 1} (${detached.agent}). Reply to the supervisor request first, then wait with subagent_wait({ id: "${runId}" }). Use subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.` }],
1208
- details: buildChainExecutionDetails(makeDetailsInput({
1209
- currentStepIndex: stepIndex,
1210
- currentFlatIndex: dynamicStartIndex + detachedIndexInStep,
1211
- })),
1212
- };
1213
- }
1214
- const failures = parallelResults
1215
- .map((result, originalIndex) => ({ ...result, originalIndex }))
1216
- .filter((result) => result.exitCode !== 0 && result.exitCode !== -1);
1217
- if (failures.length > 0) {
1218
- const failureSummary = failures
1219
- .map((failure) => `- Item ${failure.originalIndex + 1} (${failure.agent}, key ${materialized.items[failure.originalIndex]?.key ?? failure.originalIndex}): ${failure.error || "failed"}`)
1220
- .join("\n");
1221
- const errorMsg = `Dynamic step ${stepIndex + 1} failed:\n${failureSummary}`;
1222
- dynamicGroupStatuses[stepIndex] = { status: "failed", error: errorMsg };
1223
- const summary = buildChainSummary(chainSteps, results, chainDir, "failed", {
1224
- index: stepIndex,
1225
- error: errorMsg,
1226
- });
1227
- return {
1228
- content: [{ type: "text", text: summary }],
1229
- isError: true,
1230
- details: buildChainExecutionDetails(makeDetailsInput({
1231
- currentStepIndex: stepIndex,
1232
- currentFlatIndex: dynamicStartIndex + failures[0]!.originalIndex,
1233
- })),
1234
- };
1235
- }
1236
- const acceptanceFailures = parallelResults
1237
- .map((result, originalIndex) => ({ result, originalIndex, task: dynamicParallelStep.parallel[originalIndex] }))
1238
- .filter(({ result, task }) => isAgentContractV1(task?.agentContract ?? dynamicParallelStep.agentContract ?? params.agentContract) && (task?.gateOn ?? dynamicParallelStep.gateOn) === "acceptance" && result.acceptance?.status === "rejected");
1239
- if (acceptanceFailures.length > 0) {
1240
- const acceptanceSummary = acceptanceFailures
1241
- .map(({ result, originalIndex }) => `- Item ${originalIndex + 1} (${result.agent}, key ${materialized.items[originalIndex]?.key ?? originalIndex}): ${(result.acceptance ? acceptanceFailureMessage(result.acceptance) : undefined) ?? "acceptance rejected"}`)
1242
- .join("\n");
1243
- const errorMsg = `Dynamic step ${stepIndex + 1} acceptance gate failed:\n${acceptanceSummary}`;
1244
- dynamicGroupStatuses[stepIndex] = { status: "failed", error: errorMsg };
1245
- const summary = buildChainSummary(chainSteps, results, chainDir, "failed", { index: stepIndex, error: errorMsg });
1246
- return {
1247
- content: [{ type: "text", text: summary }],
1248
- isError: true,
1249
- details: buildChainExecutionDetails(makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: dynamicStartIndex + acceptanceFailures[0]!.originalIndex })),
1250
- };
1251
- }
1252
- try {
1253
- await validateDynamicCollection(step.collect.outputSchema, collected);
1254
- } catch (error) {
1255
- const message = error instanceof DynamicFanoutError ? error.message : error instanceof Error ? error.message : String(error);
1256
- dynamicGroupStatuses[stepIndex] = { status: "failed", error: message };
1257
- return buildChainExecutionErrorResult(message, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: dynamicStartIndex }));
1258
- }
1259
- outputs[step.collect.as] = {
1260
- text: JSON.stringify(collected),
1261
- structured: collected,
1262
- agent: step.parallel.agent,
1263
- stepIndex,
1264
- };
1265
- dynamicGroupStatuses[stepIndex] = { status: "completed" };
1266
- const effectiveGroupAcceptance = resolveEffectiveAcceptance({
1267
- explicit: step.acceptance,
1268
- agentName: step.parallel.agent,
1269
- acceptanceRole: agents.find((agent) => agent.name === step.parallel.agent)?.acceptanceRole,
1270
- task: materialized.parallel
1271
- .map((task) => (task.task ?? originalTask ?? "").replace(/\{task\}/g, originalTask ?? ""))
1272
- .join("\n"),
1273
- mode: "chain",
1274
- dynamicGroup: true,
1275
- agentContract: step.agentContract ?? params.agentContract,
1276
- });
1277
- const groupAcceptance = await evaluateAcceptance({
1278
- acceptance: effectiveGroupAcceptance,
1279
- output: "",
1280
- report: aggregateAcceptanceReport({
1281
- results: parallelResults,
1282
- notes: `Dynamic fanout collected ${collected.length} result(s) into ${step.collect.as}.`,
1283
- }),
1284
- cwd: cwd ?? ctx.cwd,
1285
- reportOptional: isAgentContractV1(step.agentContract ?? params.agentContract),
1286
- });
1287
- const dynamicGroupStatus = dynamicGroupStatuses[stepIndex];
1288
- if (!dynamicGroupStatus) throw new Error(`Missing dynamic group status at step ${stepIndex}`);
1289
- dynamicGroupStatus.acceptance = groupAcceptance;
1290
- const groupAcceptanceFailure = effectiveGroupAcceptance.explicit && (!isAgentContractV1(step.agentContract ?? params.agentContract) || step.gateOn === "acceptance") ? acceptanceFailureMessage(groupAcceptance) : undefined;
1291
- if (groupAcceptanceFailure) {
1292
- dynamicGroupStatuses[stepIndex] = { status: "failed", error: groupAcceptanceFailure, acceptance: groupAcceptance };
1293
- return buildChainExecutionErrorResult(groupAcceptanceFailure, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex - dynamicParallelStep.parallel.length }));
1294
- }
1295
- const taskResults: ParallelTaskResult[] = parallelResults.map((result, i) => ({
1296
- agent: result.agent,
1297
- taskIndex: i,
1298
- output: getSingleResultOutput(result),
1299
- exitCode: result.exitCode,
1300
- error: result.error,
1301
- timedOut: result.timedOut,
1302
- }));
1303
- prev = aggregateParallelOutputs(taskResults, (i, agent) => `=== Dynamic Item ${i + 1} (${agent}, key ${materialized.items[i]?.key ?? i}) ===`);
1304
- } else {
1305
- const seqStep = step as SequentialStep;
1306
- const stepTemplate = stepTemplates as string;
1307
-
1308
- const agentConfig = agents.find((a) => a.name === seqStep.agent);
1309
- if (!agentConfig) {
1310
- removeChainDir(chainDir);
1311
- return {
1312
- content: [{ type: "text", text: `Unknown agent: ${seqStep.agent}` }],
1313
- isError: true,
1314
- details: buildChainExecutionDetails(makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex })),
1315
- };
1316
- }
1317
-
1318
- const tuiOverride = tuiBehaviorOverrides?.[stepIndex];
1319
- const stepOverride: StepOverrides = {
1320
- output: tuiOverride?.output !== undefined ? tuiOverride.output : seqStep.output,
1321
- outputMode: seqStep.outputMode,
1322
- reads: tuiOverride?.reads !== undefined ? tuiOverride.reads : seqStep.reads,
1323
- progress: tuiOverride?.progress !== undefined ? tuiOverride.progress : seqStep.progress,
1324
- skills:
1325
- tuiOverride?.skills !== undefined
1326
- ? tuiOverride.skills
1327
- : normalizeSkillInput(seqStep.skill),
1328
- };
1329
- const behavior = suppressProgressForReadOnlyTask(resolveStepBehavior(agentConfig, stepOverride, chainSkills), stepTemplate, originalTask);
1330
-
1331
- const isFirstProgress = behavior.progress && !progressCreated;
1332
- if (isFirstProgress) {
1333
- progressCreated = true;
1334
- }
1335
-
1336
- const templateHasPrevious = stepTemplate.includes("{previous}");
1337
- const { prefix, suffix } = buildChainInstructions(
1338
- { ...behavior, output: false },
1339
- chainDir,
1340
- isFirstProgress,
1341
- templateHasPrevious ? undefined : prev,
1342
- );
1343
-
1344
- let stepTask = resolveOutputReferences(stepTemplate, outputs);
1345
- stepTask = stepTask.replace(/\{task\}/g, originalTask);
1346
- stepTask = stepTask.replace(/\{previous\}/g, prev);
1347
- stepTask = stepTask.replace(/\{chain_dir\}/g, chainDir);
1348
- const cleanTask = stepTask;
1349
- stepTask = prefix + stepTask + suffix;
1350
-
1351
- const explicitStepModel = tuiOverride?.model ?? seqStep.model;
1352
- const effectiveModel = resolveEffectiveSubagentModel(
1353
- explicitStepModel,
1354
- agentConfig.model,
1355
- ctx.model,
1356
- availableModels,
1357
- ctx.model?.provider,
1358
- { scope: modelScope },
1359
- );
1360
-
1361
- const outputPath = typeof behavior.output === "string"
1362
- ? (path.isAbsolute(behavior.output) ? behavior.output : path.join(chainDir, behavior.output))
1363
- : undefined;
1364
- stepTask = injectSingleOutputInstruction(stepTask, outputPath, agentConfig);
1365
- const validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Chain step ${stepIndex + 1} (${seqStep.agent})`);
1366
- if (validationError) {
1367
- return buildChainExecutionErrorResult(validationError, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex }));
1368
- }
1369
- const maxSubagentDepth = resolveChildMaxSubagentDepth(params.maxSubagentDepth, agentConfig.maxSubagentDepth);
1370
- const childIndex = globalTaskIndex;
1371
- const interruptController = new AbortController();
1372
- if (foregroundControl) {
1373
- const thinking = resolveEffectiveThinking(effectiveModel, params.thinkingOverrideForTask?.(seqStep.agent, childIndex, effectiveModel));
1374
- beginForegroundChild(foregroundControl, {
1375
- index: childIndex,
1376
- agent: seqStep.agent,
1377
- authoredTask: cleanTask,
1378
- effectivePrompt: stepTask,
1379
- cwd,
1380
- ...(outputPath ? { outputPath } : {}),
1381
- description: `${seqStep.agent} child`,
1382
- ...(effectiveModel ? { model: effectiveModel } : {}),
1383
- ...(thinking ? { thinking } : {}),
1384
- interrupt: () => {
1385
- if (interruptController.signal.aborted) return false;
1386
- interruptController.abort();
1387
- return true;
1388
- },
1389
- });
1390
- }
1391
-
1392
- const agentContract = seqStep.agentContract ?? params.agentContract;
1393
- let r!: SingleResult;
1394
- try {
1395
- const structuredRuntime = seqStep.outputSchema
1396
- ? createStructuredOutputRuntime(seqStep.outputSchema, path.join(chainDir, "structured-output"))
1397
- : undefined;
1398
- const toolBudget = resolveChainToolBudget({ stepBudget: seqStep.toolBudget, runBudget: params.toolBudget, agentBudget: agentConfig?.toolBudget, configBudget: params.configToolBudget });
1399
- if (toolBudget.error) return buildChainExecutionErrorResult(toolBudget.error, {
1400
- results,
1401
- includeProgress,
1402
- allProgress,
1403
- allArtifactPaths,
1404
- artifactsDir: params.artifactsDir,
1405
- chainAgents,
1406
- chainSteps,
1407
- totalSteps,
1408
- currentStepIndex: stepIndex,
1409
- runId: params.runId,
1410
- outputs,
1411
- currentFlatIndex: globalTaskIndex,
1412
- dynamicChildren,
1413
- dynamicGroupStatuses,
1414
- });
1415
- r = await runSync(ctx.cwd, agents, seqStep.agent, stepTask, {
1416
- permissions: params.permissions,
1417
- parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
1418
- llmIntentArbiter: createTaskMutationArbiter(ctx),
1419
- ...workflowForegroundSteeringLaunchOptions(params.foregroundControl, childIndex),
1420
- capabilityCeiling: params.capabilityCeiling,
1421
- runFanoutBudget: params.runFanoutBudget ? { ...params.runFanoutBudget, parentPath: `${params.runFanoutBudget.parentPath ? `${params.runFanoutBudget.parentPath}/` : ""}chain[${stepIndex}]` } : undefined,
1422
- context: params.contextForAgent?.(seqStep.agent),
1423
- cwd: resolveChildCwd(cwd ?? ctx.cwd, seqStep.cwd),
1424
- signal,
1425
- interruptSignal: interruptController.signal,
1426
- allowIntercomDetach: agentConfig.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === true,
1427
- intercomEvents,
1428
- runId,
1429
- index: childIndex,
1430
- sessionDir: sessionDirForIndex(childIndex),
1431
- sessionFile: sessionFileForTask?.(seqStep.agent, childIndex, effectiveModel)
1432
- ?? sessionFileForIndex?.(childIndex),
1433
- thinkingOverride: thinkingOverrideForTask?.(seqStep.agent, childIndex, effectiveModel),
1434
- share: shareEnabled,
1435
- artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
1436
- artifactConfig,
1437
- outputPath,
1438
- outputMode: behavior.outputMode,
1439
- maxSubagentDepth,
1440
- controlConfig,
1441
- onControlEvent,
1442
- intercomSessionName: childIntercomTarget?.(seqStep.agent, childIndex),
1443
- orchestratorIntercomTarget,
1444
- nestedRoute: params.nestedRoute,
1445
- modelOverride: effectiveModel,
1446
- availableModels,
1447
- preferredModelProvider: ctx.model?.provider,
1448
- modelScope,
1449
- skills: behavior.skills === false ? [] : behavior.skills,
1450
- structuredOutput: structuredRuntime,
1451
- agentContract,
1452
- acceptance: seqStep.acceptance,
1453
- acceptanceContext: { mode: "chain" },
1454
- onEffectivePrompt: foregroundControl ? (prompt) => updateLiveEffectivePrompt(foregroundControl, childIndex, prompt) : undefined,
1455
- timeoutMs: params.timeoutMs,
1456
- deadlineAt,
1457
- toolTimeoutMs: params.callToolTimeoutMs,
1458
- configToolTimeoutMs: params.configToolTimeoutMs,
1459
- turnBudget: params.turnBudget,
1460
- onDetachedExit: (result) => {
1461
- try {
1462
- if (foregroundControl) finishForegroundChild(foregroundControl, childIndex);
1463
- } finally {
1464
- onDetachedExit?.(childIndex, result);
1465
- }
1466
- },
1467
- toolBudget: toolBudget.toolBudget,
1468
- onUpdate: onUpdate
1469
- ? (p) => {
1470
- const stepResults = p.details?.results || [];
1471
- const stepProgress = p.details?.progress || [];
1472
- if (foregroundControl && stepProgress.length > 0) {
1473
- updateForegroundChild(foregroundControl, childIndex, stepProgress[0]);
1474
- }
1475
- onUpdate({
1476
- ...p,
1477
- details: {
1478
- mode: "chain",
1479
- results: results.concat(stepResults),
1480
- progress: allProgress.concat(stepProgress),
1481
- controlEvents: p.details?.controlEvents,
1482
- chainAgents,
1483
- totalSteps,
1484
- currentStepIndex: stepIndex,
1485
- outputs,
1486
- workflowGraph: buildWorkflowGraphSnapshot({
1487
- runId,
1488
- mode: "chain",
1489
- steps: chainSteps,
1490
- results: results.concat(stepResults),
1491
- currentStepIndex: stepIndex,
1492
- currentFlatIndex: childIndex,
1493
- dynamicChildren,
1494
- dynamicGroupStatuses,
1495
- }),
1496
- },
1497
- });
1498
- }
1499
- : undefined,
1500
- });
1501
- } finally {
1502
- // Rejected attempts and early validation returns release the child here.
1503
- // A detached receipt transfers cleanup ownership to onDetachedExit.
1504
- if (!r?.detached) {
1505
- if (foregroundControl) finishForegroundChild(foregroundControl, childIndex);
1506
- params.onForegroundChildSettled?.();
1507
- }
1508
- }
1509
- recordRun(seqStep.agent, cleanTask, r.exitCode, r.progressSummary?.durationMs ?? 0);
1510
-
1511
- globalTaskIndex++;
1512
- results.push(r);
1513
- if (r.progress) allProgress.push(r.progress);
1514
- if (r.artifactPaths) allArtifactPaths.push(r.artifactPaths);
1515
-
1516
- if (r.interrupted) {
1517
- return {
1518
- content: [{ type: "text", text: `Chain paused after interrupt at step ${stepIndex + 1} (${r.agent}). Waiting for explicit next action.` }],
1519
- details: buildChainExecutionDetails(makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: childIndex })),
1520
- };
1521
- }
1522
- if (r.detached) {
1523
- return {
1524
- content: [{ type: "text", text: `Chain detached for intercom coordination at step ${stepIndex + 1} (${r.agent}). Reply to the supervisor request first, then wait with subagent_wait({ id: "${runId}" }). Use subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.` }],
1525
- details: buildChainExecutionDetails(makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: childIndex })),
1526
- };
1527
- }
1528
-
1529
- if (r.exitCode !== 0) {
1530
- const summary = buildChainSummary(chainSteps, results, chainDir, "failed", {
1531
- index: stepIndex,
1532
- error: r.error || "Chain failed",
1533
- });
1534
- return {
1535
- content: [{ type: "text", text: summary }],
1536
- details: buildChainExecutionDetails(makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: childIndex })),
1537
- isError: true,
1538
- };
1539
- }
1540
- if (isAgentContractV1(agentContract) && seqStep.gateOn === "acceptance" && r.acceptance?.status === "rejected") {
1541
- const summary = buildChainSummary(chainSteps, results, chainDir, "failed", {
1542
- index: stepIndex,
1543
- error: acceptanceFailureMessage(r.acceptance) ?? "Chain acceptance gate rejected the step.",
1544
- });
1545
- return {
1546
- content: [{ type: "text", text: summary }],
1547
- details: buildChainExecutionDetails(makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: childIndex })),
1548
- isError: true,
1549
- };
1550
- }
1551
-
1552
- if (behavior.output) {
1553
- try {
1554
- const expectedPath = path.isAbsolute(behavior.output)
1555
- ? behavior.output
1556
- : path.join(chainDir, behavior.output);
1557
- if (!fs.existsSync(expectedPath)) {
1558
- const dirFiles = fs.readdirSync(chainDir);
1559
- const mdFiles = dirFiles.filter((file) => file.endsWith(".md") && file !== "progress.md");
1560
- const warning = mdFiles.length > 0
1561
- ? `Agent wrote to different file(s): ${mdFiles.join(", ")} instead of ${behavior.output}`
1562
- : `Agent did not create expected output file: ${behavior.output}`;
1563
- r.error = r.error ? `${r.error}\n${warning}` : warning;
1564
- }
1565
- } catch {
1566
- // Ignore validation errors; this diagnostic should not mask successful chain output.
1567
- }
1568
- }
1569
-
1570
- if (seqStep.as) outputs[seqStep.as] = outputEntryFromResult(r, stepIndex);
1571
- prev = getSingleResultOutput(r);
1572
- }
1573
- }
1574
-
1575
- const summary = buildChainSummary(chainSteps, results, chainDir, "completed");
1576
-
1577
- return {
1578
- content: [{ type: "text", text: summary }],
1579
- details: buildChainExecutionDetails(makeDetailsInput()),
1580
- };
1581
- }