@xzzpig/pi-subagents 0.22.0 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +346 -0
- package/README.md +2 -2
- package/agents/evidence-auditor.md +1 -0
- package/agents/oracle.md +1 -0
- package/agents/reviewer.md +1 -0
- package/bundle/agent-management.js +16 -0
- package/bundle/agents.js +41 -0
- package/bundle/background-work.js +16 -0
- package/bundle/capability-ceiling.js +22 -0
- package/bundle/child-tool-plan.js +11 -0
- package/bundle/chunk-355ECEP2.js +1321 -0
- package/bundle/chunk-35GII5EF.js +637 -0
- package/bundle/chunk-3G4JXNZ4.js +4130 -0
- package/bundle/chunk-3U633XDZ.js +749 -0
- package/bundle/chunk-4QFZZV3O.js +57 -0
- package/bundle/chunk-62OCY2S4.js +14 -0
- package/bundle/chunk-7J4ZXMY7.js +18 -0
- package/bundle/chunk-7K3Z6DM7.js +276 -0
- package/bundle/chunk-BGIYHF2W.js +138 -0
- package/bundle/chunk-CTPAE36Y.js +94 -0
- package/bundle/chunk-D4EHT5SJ.js +14 -0
- package/bundle/chunk-ED55MIC2.js +1681 -0
- package/bundle/chunk-F3NSN7UH.js +7331 -0
- package/bundle/chunk-FJWI64H7.js +490 -0
- package/bundle/chunk-H36HBZB2.js +753 -0
- package/bundle/chunk-ICNYIALB.js +7347 -0
- package/bundle/chunk-KD2IMFN4.js +1310 -0
- package/bundle/chunk-LCDJWBVM.js +57 -0
- package/bundle/chunk-LPVUHUZ7.js +5503 -0
- package/bundle/chunk-MYCL5QEJ.js +1372 -0
- package/bundle/chunk-NCWCVJLT.js +1768 -0
- package/bundle/chunk-NIXWDZZV.js +9 -0
- package/bundle/chunk-NTRJDXBC.js +4175 -0
- package/bundle/chunk-OFGSZBHP.js +16924 -0
- package/bundle/chunk-OTLRAB22.js +143 -0
- package/bundle/chunk-QXASAHIA.js +173 -0
- package/bundle/chunk-RB4GELQA.js +458 -0
- package/bundle/chunk-RK2HDPLK.js +1234 -0
- package/bundle/chunk-SW2VMNIU.js +526 -0
- package/bundle/chunk-T65XRVVM.js +940 -0
- package/bundle/chunk-U4ODUYAG.js +235 -0
- package/bundle/chunk-UFNSLL5D.js +9796 -0
- package/bundle/chunk-UKG4V45O.js +228 -0
- package/bundle/chunk-UQDHXMUG.js +264 -0
- package/bundle/chunk-V2KFIGFH.js +8774 -0
- package/bundle/chunk-VO3G7HI3.js +85 -0
- package/bundle/chunk-WPW4V6HM.js +227 -0
- package/bundle/chunk-WW76JRIX.js +175 -0
- package/bundle/chunk-XA3DY6UG.js +161 -0
- package/bundle/chunk-YFCK7H2S.js +129 -0
- package/bundle/chunk-YYREO77V.js +137 -0
- package/bundle/chunk-Z6TFJ6BR.js +400 -0
- package/bundle/control-channel.js +11 -0
- package/bundle/delegation.js +14 -0
- package/bundle/external-job-provider.js +20 -0
- package/bundle/external-runs.js +21 -0
- package/bundle/index.js +30 -0
- package/bundle/inspectors.js +8 -0
- package/bundle/intercom-bridge.js +11 -0
- package/bundle/preflight.js +468 -0
- package/bundle/project-panes.js +28 -0
- package/bundle/required-child-extensions.js +6 -0
- package/bundle/shared-types.js +8 -0
- package/bundle/supervisor-routing.js +12 -0
- package/bundle/workflow-resources.js +7 -0
- package/docs/agents.md +42 -10
- package/docs/configuration.md +59 -14
- package/docs/extension-api.md +61 -9
- package/docs/missions.md +2 -0
- package/docs/observability.md +20 -5
- package/docs/standalone-background.md +8 -6
- package/docs/tool-reference.md +18 -5
- package/docs/workflows.md +25 -7
- package/index.d.ts +3 -0
- package/index.js +14 -0
- package/node_modules/@xzzpig/pi-components/package.json +1 -2
- package/package.json +107 -87
- package/skills/council-mode/SKILL.md +1 -4
- package/skills/pi-subagents/SKILL.md +130 -106
- package/skills/pi-subagents/references/orchestration.md +124 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +96 -291
- package/src/agents/advertised-agent-prompt.d.ts +13 -0
- package/src/agents/advertised-agent-prompt.js +68 -0
- package/src/agents/agent-eject.d.ts +39 -0
- package/src/agents/agent-eject.js +263 -0
- package/src/agents/agent-management.d.ts +33 -0
- package/src/agents/agent-management.js +1541 -0
- package/src/agents/agent-memory.d.ts +48 -0
- package/src/agents/agent-memory.js +350 -0
- package/src/agents/agent-refinements.d.ts +99 -0
- package/src/agents/agent-refinements.js +568 -0
- package/src/agents/agent-scope.d.ts +3 -0
- package/src/agents/agent-scope.js +8 -0
- package/src/agents/agent-selection.d.ts +2 -0
- package/src/agents/agent-selection.js +22 -0
- package/src/agents/agent-serializer.d.ts +7 -0
- package/src/agents/agent-serializer.js +213 -0
- package/src/agents/agents.d.ts +352 -0
- package/src/agents/agents.js +2817 -0
- package/src/agents/builtin-names.d.ts +1 -0
- package/src/agents/builtin-names.js +16 -0
- package/src/agents/chain-serializer.d.ts +6 -0
- package/src/agents/chain-serializer.js +318 -0
- package/src/agents/frontmatter.d.ts +19 -0
- package/src/agents/frontmatter.js +166 -0
- package/src/agents/global-npm-root.d.ts +6 -0
- package/src/agents/global-npm-root.js +57 -0
- package/src/agents/identity.d.ts +7 -0
- package/src/agents/identity.js +29 -0
- package/src/agents/proactive-skills.d.ts +35 -0
- package/src/agents/proactive-skills.js +155 -0
- package/src/agents/runtime-agent-events.d.ts +26 -0
- package/src/agents/runtime-agent-events.js +52 -0
- package/src/agents/runtime-agent-registry.d.ts +66 -0
- package/src/agents/runtime-agent-registry.js +415 -0
- package/src/agents/runtime-discovery.d.ts +13 -0
- package/src/agents/runtime-discovery.js +27 -0
- package/src/agents/skills.d.ts +34 -0
- package/src/agents/skills.js +718 -0
- package/src/api/agent-management.d.ts +2 -0
- package/src/api/agent-management.js +2 -0
- package/src/api/agents.d.ts +6 -0
- package/src/api/agents.js +3 -0
- package/src/api/background-work.d.ts +41 -0
- package/src/api/background-work.js +171 -0
- package/src/api/capability-ceiling.d.ts +1 -0
- package/src/api/capability-ceiling.js +1 -0
- package/src/api/child-tool-plan.d.ts +1 -0
- package/src/api/child-tool-plan.js +1 -0
- package/src/api/control-channel.d.ts +1 -0
- package/src/api/control-channel.js +1 -0
- package/src/api/delegation.d.ts +132 -0
- package/src/api/delegation.js +8 -0
- package/src/api/external-job-provider.d.ts +57 -0
- package/src/api/external-job-provider.js +139 -0
- package/src/api/external-runs.d.ts +47 -0
- package/src/api/external-runs.js +245 -0
- package/src/api/inspectors.d.ts +20 -0
- package/src/api/inspectors.js +11 -0
- package/src/api/intercom-bridge.d.ts +1 -0
- package/src/api/intercom-bridge.js +1 -0
- package/src/api/preflight.d.ts +183 -0
- package/src/api/preflight.js +455 -0
- package/src/api/project-panes.d.ts +7 -0
- package/src/api/project-panes.js +7 -0
- package/src/api/required-child-extensions.d.ts +1 -0
- package/src/api/required-child-extensions.js +1 -0
- package/src/api/shared-types.d.ts +1 -0
- package/src/api/shared-types.js +1 -0
- package/src/api/supervisor-routing.d.ts +110 -0
- package/src/api/supervisor-routing.js +95 -0
- package/src/api/workflow-resources.d.ts +2 -0
- package/src/api/workflow-resources.js +1 -0
- package/src/extension/active-runs-prompt.d.ts +7 -0
- package/src/extension/active-runs-prompt.js +29 -0
- package/src/extension/config.d.ts +7 -0
- package/src/extension/config.js +290 -0
- package/src/extension/context-injection.d.ts +52 -0
- package/src/extension/context-injection.js +102 -0
- package/src/extension/control-notices.d.ts +18 -0
- package/src/extension/control-notices.js +29 -0
- package/src/extension/declaration-pinning.d.ts +18 -0
- package/src/extension/declaration-pinning.js +167 -0
- package/src/extension/doctor.d.ts +34 -0
- package/src/extension/doctor.js +236 -0
- package/src/extension/fanout-child.d.ts +6 -0
- package/src/extension/fanout-child.js +278 -0
- package/src/extension/herdr-pi-bridge.d.ts +16 -0
- package/src/extension/herdr-pi-bridge.js +261 -0
- package/src/extension/index.d.ts +18 -0
- package/src/extension/index.js +1288 -0
- package/src/extension/public-execution.d.ts +71 -0
- package/src/extension/public-execution.js +214 -0
- package/src/extension/reply-workflow-script.d.ts +11 -0
- package/src/extension/reply-workflow-script.js +71 -0
- package/src/extension/rpc.d.ts +84 -0
- package/src/extension/rpc.js +729 -0
- package/src/extension/schemas.d.ts +276 -0
- package/src/extension/schemas.js +311 -0
- package/src/extension/steering-notices.d.ts +14 -0
- package/src/extension/steering-notices.js +22 -0
- package/src/extension/subagent-guide.d.ts +4 -0
- package/src/extension/subagent-guide.js +114 -0
- package/src/extension/subagent-options.d.ts +7 -0
- package/src/extension/subagent-options.js +64 -0
- package/src/extension/tool-activation.d.ts +7 -0
- package/src/extension/tool-activation.js +185 -0
- package/src/extension/tool-description.d.ts +19 -0
- package/src/extension/tool-description.js +169 -0
- package/src/extension/tool-result.d.ts +9 -0
- package/src/extension/tool-result.js +16 -0
- package/src/extension/upgrade-notice.d.ts +6 -0
- package/src/extension/upgrade-notice.js +42 -0
- package/src/inspectors/actions.d.ts +24 -0
- package/src/inspectors/actions.js +182 -0
- package/src/inspectors/ghostty/actions.d.ts +11 -0
- package/src/inspectors/ghostty/actions.js +62 -0
- package/src/inspectors/ghostty/plugin.d.ts +7 -0
- package/src/inspectors/ghostty/plugin.js +23 -0
- package/src/inspectors/herdr/actions.d.ts +25 -0
- package/src/inspectors/herdr/actions.js +133 -0
- package/src/inspectors/herdr/client.d.ts +41 -0
- package/src/inspectors/herdr/client.js +129 -0
- package/src/inspectors/herdr/focus.d.ts +24 -0
- package/src/inspectors/herdr/focus.js +49 -0
- package/src/inspectors/herdr/plugin.d.ts +6 -0
- package/src/inspectors/herdr/plugin.js +14 -0
- package/src/inspectors/herdr/project-panes.d.ts +136 -0
- package/src/inspectors/herdr/project-panes.js +610 -0
- package/src/inspectors/inspector-runner.d.ts +23 -0
- package/src/inspectors/inspector-runner.js +161 -0
- package/src/inspectors/plugins.d.ts +8 -0
- package/src/inspectors/plugins.js +82 -0
- package/src/inspectors/session-roots-codec.d.ts +15 -0
- package/src/inspectors/session-roots-codec.js +32 -0
- package/src/inspectors/shell-command.d.ts +1 -0
- package/src/inspectors/shell-command.js +16 -0
- package/src/inspectors/tmux/actions.d.ts +25 -0
- package/src/inspectors/tmux/actions.js +181 -0
- package/src/inspectors/tmux/client.d.ts +27 -0
- package/src/inspectors/tmux/client.js +64 -0
- package/src/inspectors/tmux/plugin.d.ts +7 -0
- package/src/inspectors/tmux/plugin.js +14 -0
- package/src/inspectors/types.d.ts +48 -0
- package/src/inspectors/types.js +1 -0
- package/src/integrations/herdr-status.d.ts +47 -0
- package/src/integrations/herdr-status.js +350 -0
- package/src/integrations/pi-web-session-liveness.d.ts +19 -0
- package/src/integrations/pi-web-session-liveness.js +53 -0
- package/src/integrations/program-status.d.ts +30 -0
- package/src/integrations/program-status.js +188 -0
- package/src/intercom/fork-supervisor-routing.d.ts +90 -0
- package/src/intercom/fork-supervisor-routing.js +392 -0
- package/src/intercom/intercom-bridge.d.ts +58 -0
- package/src/intercom/intercom-bridge.js +193 -0
- package/src/intercom/native-supervisor-channel.d.ts +97 -0
- package/src/intercom/native-supervisor-channel.js +1184 -0
- package/src/intercom/result-intercom.d.ts +35 -0
- package/src/intercom/result-intercom.js +376 -0
- package/src/intercom/supervisor-ui.d.ts +29 -0
- package/src/intercom/supervisor-ui.js +49 -0
- package/src/missions/actions.d.ts +54 -0
- package/src/missions/actions.js +400 -0
- package/src/missions/goal-driver.d.ts +16 -0
- package/src/missions/goal-driver.js +171 -0
- package/src/missions/lifecycle.d.ts +50 -0
- package/src/missions/lifecycle.js +388 -0
- package/src/missions/store.d.ts +21 -0
- package/src/missions/store.js +605 -0
- package/src/missions/types.d.ts +169 -0
- package/src/missions/types.js +9 -0
- package/src/missions/workflow-state.d.ts +14 -0
- package/src/missions/workflow-state.js +273 -0
- package/src/policy/authority.d.ts +9 -0
- package/src/policy/authority.js +41 -0
- package/src/profiles/profiles.d.ts +134 -0
- package/src/profiles/profiles.js +526 -0
- package/src/runs/background/active-async-capacity.d.ts +115 -0
- package/src/runs/background/active-async-capacity.js +517 -0
- package/src/runs/background/active-run-index.d.ts +12 -0
- package/src/runs/background/active-run-index.js +157 -0
- package/src/runs/background/async-execution.d.ts +304 -0
- package/src/runs/background/async-execution.js +2206 -0
- package/src/runs/background/async-job-tracker.d.ts +37 -0
- package/src/runs/background/async-job-tracker.js +921 -0
- package/src/runs/background/async-resume.d.ts +60 -0
- package/src/runs/background/async-resume.js +707 -0
- package/src/runs/background/async-retention.d.ts +45 -0
- package/src/runs/background/async-retention.js +932 -0
- package/src/runs/background/async-status-snapshot.d.ts +9 -0
- package/src/runs/background/async-status-snapshot.js +26 -0
- package/src/runs/background/async-status.d.ts +177 -0
- package/src/runs/background/async-status.js +710 -0
- package/src/runs/background/auto-drain.d.ts +16 -0
- package/src/runs/background/auto-drain.js +71 -0
- package/src/runs/background/await-async-run.d.ts +26 -0
- package/src/runs/background/await-async-run.js +83 -0
- package/src/runs/background/binary-bootstrap.d.ts +8 -0
- package/src/runs/background/binary-bootstrap.js +69 -0
- package/src/runs/background/boot-id.d.ts +12 -0
- package/src/runs/background/boot-id.js +47 -0
- package/src/runs/background/calendar-schedule.d.ts +26 -0
- package/src/runs/background/calendar-schedule.js +93 -0
- package/src/runs/background/chain-append.d.ts +34 -0
- package/src/runs/background/chain-append.js +299 -0
- package/src/runs/background/chain-root-attachment.d.ts +51 -0
- package/src/runs/background/chain-root-attachment.js +186 -0
- package/src/runs/background/completion-batcher.d.ts +51 -0
- package/src/runs/background/completion-batcher.js +119 -0
- package/src/runs/background/completion-dedupe.d.ts +13 -0
- package/src/runs/background/completion-dedupe.js +48 -0
- package/src/runs/background/completion-replay.d.ts +47 -0
- package/src/runs/background/completion-replay.js +266 -0
- package/src/runs/background/control-channel.d.ts +170 -0
- package/src/runs/background/control-channel.js +610 -0
- package/src/runs/background/fleet-view.d.ts +63 -0
- package/src/runs/background/fleet-view.js +666 -0
- package/src/runs/background/index-segment.d.ts +16 -0
- package/src/runs/background/index-segment.js +58 -0
- package/src/runs/background/inspect-rpc.d.ts +64 -0
- package/src/runs/background/inspect-rpc.js +422 -0
- package/src/runs/background/interrupted-elsewhere.d.ts +22 -0
- package/src/runs/background/interrupted-elsewhere.js +68 -0
- package/src/runs/background/notify.d.ts +214 -0
- package/src/runs/background/notify.js +1001 -0
- package/src/runs/background/owned-process-tree.d.ts +10 -0
- package/src/runs/background/owned-process-tree.js +116 -0
- package/src/runs/background/parallel-groups.d.ts +3 -0
- package/src/runs/background/parallel-groups.js +46 -0
- package/src/runs/background/pid-namespace.d.ts +2 -0
- package/src/runs/background/pid-namespace.js +19 -0
- package/src/runs/background/process-terminal-candidate.d.ts +17 -0
- package/src/runs/background/process-terminal-candidate.js +96 -0
- package/src/runs/background/process-terminal.d.ts +21 -0
- package/src/runs/background/process-terminal.js +227 -0
- package/src/runs/background/result-delivery-ownership.d.ts +14 -0
- package/src/runs/background/result-delivery-ownership.js +38 -0
- package/src/runs/background/result-files.d.ts +63 -0
- package/src/runs/background/result-files.js +629 -0
- package/src/runs/background/result-watcher.d.ts +92 -0
- package/src/runs/background/result-watcher.js +819 -0
- package/src/runs/background/resume-guidance.d.ts +4 -0
- package/src/runs/background/resume-guidance.js +57 -0
- package/src/runs/background/retained-children.d.ts +24 -0
- package/src/runs/background/retained-children.js +128 -0
- package/src/runs/background/retained-nested-route-tracker.d.ts +12 -0
- package/src/runs/background/retained-nested-route-tracker.js +90 -0
- package/src/runs/background/run-child-session.d.ts +123 -0
- package/src/runs/background/run-child-session.js +670 -0
- package/src/runs/background/run-id-query.d.ts +3 -0
- package/src/runs/background/run-id-query.js +6 -0
- package/src/runs/background/run-id-resolver.d.ts +22 -0
- package/src/runs/background/run-id-resolver.js +172 -0
- package/src/runs/background/run-status.d.ts +25 -0
- package/src/runs/background/run-status.js +850 -0
- package/src/runs/background/runner-aliases.d.ts +17 -0
- package/src/runs/background/runner-aliases.js +191 -0
- package/src/runs/background/runner-child-launch.d.ts +24 -0
- package/src/runs/background/runner-child-launch.js +72 -0
- package/src/runs/background/runner-child-sessions.d.ts +6 -0
- package/src/runs/background/runner-child-sessions.js +34 -0
- package/src/runs/background/runner-http-dispatcher.d.ts +45 -0
- package/src/runs/background/runner-http-dispatcher.js +115 -0
- package/src/runs/background/runner-startup-failure.d.ts +13 -0
- package/src/runs/background/runner-startup-failure.js +46 -0
- package/src/runs/background/scheduled-runs.d.ts +127 -0
- package/src/runs/background/scheduled-runs.js +1265 -0
- package/src/runs/background/stale-run-reconciler.d.ts +62 -0
- package/src/runs/background/stale-run-reconciler.js +509 -0
- package/src/runs/background/steering.d.ts +51 -0
- package/src/runs/background/steering.js +246 -0
- package/src/runs/background/subagent-runner-bootstrap.d.ts +13 -0
- package/src/runs/background/subagent-runner-bootstrap.js +283 -0
- package/src/runs/background/subagent-runner.d.ts +210 -0
- package/src/runs/background/subagent-runner.js +4963 -0
- package/src/runs/background/subagent-wait.d.ts +124 -0
- package/src/runs/background/subagent-wait.js +756 -0
- package/src/runs/background/terminal-run-index.d.ts +10 -0
- package/src/runs/background/terminal-run-index.js +209 -0
- package/src/runs/background/top-level-async.d.ts +7 -0
- package/src/runs/background/top-level-async.js +5 -0
- package/src/runs/background/wait-completions.d.ts +28 -0
- package/src/runs/background/wait-completions.js +264 -0
- package/src/runs/background/wait-config.d.ts +8 -0
- package/src/runs/background/wait-config.js +46 -0
- package/src/runs/background/wait-subscriptions.d.ts +26 -0
- package/src/runs/background/wait-subscriptions.js +339 -0
- package/src/runs/background/wait-tool.d.ts +6 -0
- package/src/runs/background/wait-tool.js +48 -0
- package/src/runs/background/workflow-terminal-proof.d.ts +47 -0
- package/src/runs/background/workflow-terminal-proof.js +116 -0
- package/src/runs/foreground/async-dismiss-action.d.ts +6 -0
- package/src/runs/foreground/async-dismiss-action.js +82 -0
- package/src/runs/foreground/async-steering-action.d.ts +31 -0
- package/src/runs/foreground/async-steering-action.js +294 -0
- package/src/runs/foreground/async-stop-action.d.ts +13 -0
- package/src/runs/foreground/async-stop-action.js +213 -0
- package/src/runs/foreground/command-action.d.ts +12 -0
- package/src/runs/foreground/command-action.js +38 -0
- package/src/runs/foreground/execution.d.ts +10 -0
- package/src/runs/foreground/execution.js +2322 -0
- package/src/runs/foreground/foreground-control.d.ts +24 -0
- package/src/runs/foreground/foreground-control.js +138 -0
- package/src/runs/foreground/foreground-history.d.ts +25 -0
- package/src/runs/foreground/foreground-history.js +267 -0
- package/src/runs/foreground/prompt-audit.d.ts +32 -0
- package/src/runs/foreground/prompt-audit.js +138 -0
- package/src/runs/foreground/subagent-executor.d.ts +316 -0
- package/src/runs/foreground/subagent-executor.js +7986 -0
- package/src/runs/foreground/workflow-detach-reconcile.d.ts +15 -0
- package/src/runs/foreground/workflow-detach-reconcile.js +283 -0
- package/src/runs/foreground/workflow-foreground-steering.d.ts +43 -0
- package/src/runs/foreground/workflow-foreground-steering.js +148 -0
- package/src/runs/shared/abort-recovery.d.ts +26 -0
- package/src/runs/shared/abort-recovery.js +108 -0
- package/src/runs/shared/acceptance.d.ts +144 -0
- package/src/runs/shared/acceptance.js +1616 -0
- package/src/runs/shared/agent-contract.d.ts +5 -0
- package/src/runs/shared/agent-contract.js +35 -0
- package/src/runs/shared/async-status-projection.d.ts +100 -0
- package/src/runs/shared/async-status-projection.js +566 -0
- package/src/runs/shared/background-process-options.d.ts +4 -0
- package/src/runs/shared/background-process-options.js +6 -0
- package/src/runs/shared/capability-ceiling.d.ts +58 -0
- package/src/runs/shared/capability-ceiling.js +179 -0
- package/src/runs/shared/chain-outputs.d.ts +18 -0
- package/src/runs/shared/chain-outputs.js +104 -0
- package/src/runs/shared/child-commands.d.ts +29 -0
- package/src/runs/shared/child-commands.js +254 -0
- package/src/runs/shared/child-hooks.d.ts +31 -0
- package/src/runs/shared/child-hooks.js +173 -0
- package/src/runs/shared/child-identity.d.ts +23 -0
- package/src/runs/shared/child-identity.js +40 -0
- package/src/runs/shared/child-launch-plan.d.ts +70 -0
- package/src/runs/shared/child-launch-plan.js +88 -0
- package/src/runs/shared/child-launch.d.ts +128 -0
- package/src/runs/shared/child-launch.js +262 -0
- package/src/runs/shared/child-lifecycle.d.ts +13 -0
- package/src/runs/shared/child-lifecycle.js +22 -0
- package/src/runs/shared/child-runtime-config.d.ts +111 -0
- package/src/runs/shared/child-runtime-config.js +44 -0
- package/src/runs/shared/child-session.d.ts +178 -0
- package/src/runs/shared/child-session.js +726 -0
- package/src/runs/shared/child-tool-plan.d.ts +101 -0
- package/src/runs/shared/child-tool-plan.js +430 -0
- package/src/runs/shared/claude-code-adapter.d.ts +80 -0
- package/src/runs/shared/claude-code-adapter.js +255 -0
- package/src/runs/shared/codex-exec-adapter.d.ts +25 -0
- package/src/runs/shared/codex-exec-adapter.js +127 -0
- package/src/runs/shared/context-mode.d.ts +12 -0
- package/src/runs/shared/context-mode.js +38 -0
- package/src/runs/shared/cursor-agent-adapter.d.ts +26 -0
- package/src/runs/shared/cursor-agent-adapter.js +99 -0
- package/src/runs/shared/dynamic-fanout.d.ts +49 -0
- package/src/runs/shared/dynamic-fanout.js +273 -0
- package/src/runs/shared/effective-system-prompt.d.ts +17 -0
- package/src/runs/shared/effective-system-prompt.js +23 -0
- package/src/runs/shared/extension-bindings.d.ts +25 -0
- package/src/runs/shared/extension-bindings.js +96 -0
- package/src/runs/shared/external-cli-contract.d.ts +29 -0
- package/src/runs/shared/external-cli-contract.js +145 -0
- package/src/runs/shared/external-cli-preflight.d.ts +41 -0
- package/src/runs/shared/external-cli-preflight.js +159 -0
- package/src/runs/shared/external-cli-runner.d.ts +65 -0
- package/src/runs/shared/external-cli-runner.js +425 -0
- package/src/runs/shared/external-job-bridge.d.ts +24 -0
- package/src/runs/shared/external-job-bridge.js +486 -0
- package/src/runs/shared/external-job-runner.d.ts +44 -0
- package/src/runs/shared/external-job-runner.js +352 -0
- package/src/runs/shared/fast-mode-extension.d.ts +3 -0
- package/src/runs/shared/fast-mode-extension.js +8 -0
- package/src/runs/shared/fork-placed-env.d.ts +4 -0
- package/src/runs/shared/fork-placed-env.js +13 -0
- package/src/runs/shared/git-environment.d.ts +2 -0
- package/src/runs/shared/git-environment.js +27 -0
- package/src/runs/shared/herdr-connection.d.ts +79 -0
- package/src/runs/shared/herdr-connection.js +269 -0
- package/src/runs/shared/herdr-external-adapters.d.ts +148 -0
- package/src/runs/shared/herdr-external-adapters.js +404 -0
- package/src/runs/shared/herdr-machine.d.ts +59 -0
- package/src/runs/shared/herdr-machine.js +294 -0
- package/src/runs/shared/herdr-pane-host.d.ts +88 -0
- package/src/runs/shared/herdr-pane-host.js +155 -0
- package/src/runs/shared/herdr-pi-protocol.d.ts +21 -0
- package/src/runs/shared/herdr-pi-protocol.js +57 -0
- package/src/runs/shared/herdr-placed-run.d.ts +144 -0
- package/src/runs/shared/herdr-placed-run.js +380 -0
- package/src/runs/shared/host-step-status.d.ts +33 -0
- package/src/runs/shared/host-step-status.js +244 -0
- package/src/runs/shared/lane-metadata.d.ts +23 -0
- package/src/runs/shared/lane-metadata.js +126 -0
- package/src/runs/shared/launch-cwd.d.ts +1 -0
- package/src/runs/shared/launch-cwd.js +16 -0
- package/src/runs/shared/local-machine-access.d.ts +5 -0
- package/src/runs/shared/local-machine-access.js +28 -0
- package/src/runs/shared/long-running-guard.d.ts +34 -0
- package/src/runs/shared/long-running-guard.js +256 -0
- package/src/runs/shared/mcp-config-sources.d.ts +33 -0
- package/src/runs/shared/mcp-config-sources.js +418 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +86 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.js +477 -0
- package/src/runs/shared/mcp-direct-tool-grant.d.ts +42 -0
- package/src/runs/shared/mcp-direct-tool-grant.js +159 -0
- package/src/runs/shared/model-resolution-diagnostic.d.ts +44 -0
- package/src/runs/shared/model-resolution-diagnostic.js +116 -0
- package/src/runs/shared/model-resolution.d.ts +109 -0
- package/src/runs/shared/model-resolution.js +411 -0
- package/src/runs/shared/model-scope.d.ts +68 -0
- package/src/runs/shared/model-scope.js +171 -0
- package/src/runs/shared/mutation-evidence.d.ts +18 -0
- package/src/runs/shared/mutation-evidence.js +198 -0
- package/src/runs/shared/nested-events.d.ts +135 -0
- package/src/runs/shared/nested-events.js +1090 -0
- package/src/runs/shared/nested-path.d.ts +8 -0
- package/src/runs/shared/nested-path.js +34 -0
- package/src/runs/shared/nested-render.d.ts +20 -0
- package/src/runs/shared/nested-render.js +115 -0
- package/src/runs/shared/orca-progress-tabs.d.ts +31 -0
- package/src/runs/shared/orca-progress-tabs.js +503 -0
- package/src/runs/shared/parallel-handoff.d.ts +78 -0
- package/src/runs/shared/parallel-handoff.js +783 -0
- package/src/runs/shared/parallel-utils.d.ts +177 -0
- package/src/runs/shared/parallel-utils.js +125 -0
- package/src/runs/shared/partial-output.d.ts +24 -0
- package/src/runs/shared/partial-output.js +35 -0
- package/src/runs/shared/permissions.d.ts +12 -0
- package/src/runs/shared/permissions.js +92 -0
- package/src/runs/shared/pi-spawn.d.ts +31 -0
- package/src/runs/shared/pi-spawn.js +211 -0
- package/src/runs/shared/placed-run-owner.d.ts +49 -0
- package/src/runs/shared/placed-run-owner.js +93 -0
- package/src/runs/shared/placement-host.d.ts +99 -0
- package/src/runs/shared/placement-host.js +157 -0
- package/src/runs/shared/process-signal.d.ts +15 -0
- package/src/runs/shared/process-signal.js +21 -0
- package/src/runs/shared/profile-extensions.d.ts +21 -0
- package/src/runs/shared/profile-extensions.js +122 -0
- package/src/runs/shared/profile-launch-env.d.ts +26 -0
- package/src/runs/shared/profile-launch-env.js +90 -0
- package/src/runs/shared/readonly-drain-observation.d.ts +25 -0
- package/src/runs/shared/readonly-drain-observation.js +50 -0
- package/src/runs/shared/rex-machine.d.ts +25 -0
- package/src/runs/shared/rex-machine.js +83 -0
- package/src/runs/shared/rex-pane-host.d.ts +62 -0
- package/src/runs/shared/rex-pane-host.js +327 -0
- package/src/runs/shared/run-fanout-budget.d.ts +14 -0
- package/src/runs/shared/run-fanout-budget.js +258 -0
- package/src/runs/shared/run-ownership.d.ts +3 -0
- package/src/runs/shared/run-ownership.js +8 -0
- package/src/runs/shared/runner-launcher.d.ts +11 -0
- package/src/runs/shared/runner-launcher.js +24 -0
- package/src/runs/shared/runtime-acknowledged-extensions.d.ts +7 -0
- package/src/runs/shared/runtime-acknowledged-extensions.js +44 -0
- package/src/runs/shared/sandbox-profile-guard.d.ts +23 -0
- package/src/runs/shared/sandbox-profile-guard.js +106 -0
- package/src/runs/shared/sandbox-startup-diagnostics.d.ts +21 -0
- package/src/runs/shared/sandbox-startup-diagnostics.js +51 -0
- package/src/runs/shared/session-lease.d.ts +69 -0
- package/src/runs/shared/session-lease.js +250 -0
- package/src/runs/shared/single-output.d.ts +90 -0
- package/src/runs/shared/single-output.js +349 -0
- package/src/runs/shared/spawn-budget.d.ts +20 -0
- package/src/runs/shared/spawn-budget.js +93 -0
- package/src/runs/shared/structured-output.d.ts +66 -0
- package/src/runs/shared/structured-output.js +483 -0
- package/src/runs/shared/subagent-control.d.ts +50 -0
- package/src/runs/shared/subagent-control.js +247 -0
- package/src/runs/shared/subagent-prompt-runtime.d.ts +90 -0
- package/src/runs/shared/subagent-prompt-runtime.js +776 -0
- package/src/runs/shared/tool-availability.d.ts +16 -0
- package/src/runs/shared/tool-availability.js +29 -0
- package/src/runs/shared/tool-budget.d.ts +21 -0
- package/src/runs/shared/tool-budget.js +78 -0
- package/src/runs/shared/tool-timeout.d.ts +31 -0
- package/src/runs/shared/tool-timeout.js +73 -0
- package/src/runs/shared/usage-budget.d.ts +7 -0
- package/src/runs/shared/usage-budget.js +74 -0
- package/src/runs/shared/usage-reconciliation.d.ts +8 -0
- package/src/runs/shared/usage-reconciliation.js +71 -0
- package/src/runs/shared/workflow-async-child-guidance.d.ts +3 -0
- package/src/runs/shared/workflow-async-child-guidance.js +17 -0
- package/src/runs/shared/workflow-graph.d.ts +31 -0
- package/src/runs/shared/workflow-graph.js +221 -0
- package/src/runs/shared/worktree-cleanup-apply.d.ts +36 -0
- package/src/runs/shared/worktree-cleanup-apply.js +178 -0
- package/src/runs/shared/worktree-cleanup-plan.d.ts +84 -0
- package/src/runs/shared/worktree-cleanup-plan.js +803 -0
- package/src/runs/shared/worktree-lock.d.ts +5 -0
- package/src/runs/shared/worktree-lock.js +40 -0
- package/src/runs/shared/worktree-setup-command.d.ts +38 -0
- package/src/runs/shared/worktree-setup-command.js +200 -0
- package/src/runs/shared/worktree.d.ts +181 -0
- package/src/runs/shared/worktree.js +1346 -0
- package/src/shared/accessible-dir.d.ts +11 -0
- package/src/shared/accessible-dir.js +39 -0
- package/src/shared/agent-stream-options.d.ts +5 -0
- package/src/shared/agent-stream-options.js +3 -0
- package/src/shared/artifacts.d.ts +22 -0
- package/src/shared/artifacts.js +272 -0
- package/src/shared/atomic-json.d.ts +19 -0
- package/src/shared/atomic-json.js +61 -0
- package/src/shared/capacity-resilient-json.d.ts +26 -0
- package/src/shared/capacity-resilient-json.js +86 -0
- package/src/shared/child-cache-retention.d.ts +29 -0
- package/src/shared/child-cache-retention.js +40 -0
- package/src/shared/child-session-name.d.ts +8 -0
- package/src/shared/child-session-name.js +40 -0
- package/src/shared/child-transcript.d.ts +37 -0
- package/src/shared/child-transcript.js +225 -0
- package/src/shared/completion-owner.d.ts +7 -0
- package/src/shared/completion-owner.js +13 -0
- package/src/shared/disabled-features.d.ts +93 -0
- package/src/shared/disabled-features.js +120 -0
- package/src/shared/display-text.d.ts +5 -0
- package/src/shared/display-text.js +154 -0
- package/src/shared/edit-distance.d.ts +4 -0
- package/src/shared/edit-distance.js +32 -0
- package/src/shared/extension-context.d.ts +21 -0
- package/src/shared/extension-context.js +39 -0
- package/src/shared/file-coalescer.d.ts +11 -0
- package/src/shared/file-coalescer.js +34 -0
- package/src/shared/file-lease.d.ts +10 -0
- package/src/shared/file-lease.js +106 -0
- package/src/shared/file-system-retry.d.ts +31 -0
- package/src/shared/file-system-retry.js +84 -0
- package/src/shared/fork-context.d.ts +64 -0
- package/src/shared/fork-context.js +185 -0
- package/src/shared/fork-session-cwd.d.ts +2 -0
- package/src/shared/fork-session-cwd.js +23 -0
- package/src/shared/formatters.d.ts +35 -0
- package/src/shared/formatters.js +137 -0
- package/src/shared/jsonl-writer.d.ts +20 -0
- package/src/shared/jsonl-writer.js +67 -0
- package/src/shared/launch-contract.d.ts +65 -0
- package/src/shared/launch-contract.js +145 -0
- package/src/shared/model-info.d.ts +55 -0
- package/src/shared/model-info.js +103 -0
- package/src/shared/model-response-aliases.d.ts +1 -0
- package/src/shared/model-response-aliases.js +15 -0
- package/src/shared/node-executable.d.ts +1 -0
- package/src/shared/node-executable.js +20 -0
- package/src/shared/opencode-session-headers.d.ts +12 -0
- package/src/shared/opencode-session-headers.js +26 -0
- package/src/shared/package-version.d.ts +2 -0
- package/src/shared/package-version.js +14 -0
- package/src/shared/parent-wake.d.ts +26 -0
- package/src/shared/parent-wake.js +68 -0
- package/src/shared/permission-profile.d.ts +26 -0
- package/src/shared/permission-profile.js +49 -0
- package/src/shared/prompt-resources.d.ts +5 -0
- package/src/shared/prompt-resources.js +10 -0
- package/src/shared/provider-diagnostics.d.ts +9 -0
- package/src/shared/provider-diagnostics.js +75 -0
- package/src/shared/pruned-fork.d.ts +34 -0
- package/src/shared/pruned-fork.js +434 -0
- package/src/shared/required-child-extensions.d.ts +34 -0
- package/src/shared/required-child-extensions.js +105 -0
- package/src/shared/runtime-module-path.d.ts +10 -0
- package/src/shared/runtime-module-path.js +16 -0
- package/src/shared/sandbox-profile.d.ts +12 -0
- package/src/shared/sandbox-profile.js +35 -0
- package/src/shared/session-file-trust.d.ts +1 -0
- package/src/shared/session-file-trust.js +20 -0
- package/src/shared/session-identity.d.ts +8 -0
- package/src/shared/session-identity.js +32 -0
- package/src/shared/session-succession.d.ts +4 -0
- package/src/shared/session-succession.js +24 -0
- package/src/shared/session-tokens.d.ts +2 -0
- package/src/shared/session-tokens.js +58 -0
- package/src/shared/settings-file-lease.d.ts +4 -0
- package/src/shared/settings-file-lease.js +38 -0
- package/src/shared/settings.d.ts +146 -0
- package/src/shared/settings.js +247 -0
- package/src/shared/shortcuts.d.ts +1 -0
- package/src/shared/shortcuts.js +17 -0
- package/src/shared/status-format.d.ts +9 -0
- package/src/shared/status-format.js +60 -0
- package/src/shared/thinking-ceiling.d.ts +13 -0
- package/src/shared/thinking-ceiling.js +37 -0
- package/src/shared/types.d.ts +2840 -0
- package/src/shared/types.js +276 -0
- package/src/shared/utf8.d.ts +5 -0
- package/src/shared/utf8.js +12 -0
- package/src/shared/utils.d.ts +83 -0
- package/src/shared/utils.js +612 -0
- package/src/shared/watch-strategy.d.ts +2 -0
- package/src/shared/watch-strategy.js +5 -0
- package/src/shared/workflow-child-permit.d.ts +58 -0
- package/src/shared/workflow-child-permit.js +159 -0
- package/src/slash/delegation-adapters.d.ts +154 -0
- package/src/slash/delegation-adapters.js +316 -0
- package/src/slash/delegation-json.d.ts +10 -0
- package/src/slash/delegation-json.js +117 -0
- package/src/slash/delegation-request.d.ts +12 -0
- package/src/slash/delegation-request.js +174 -0
- package/src/slash/prompt-template-bridge.d.ts +29 -0
- package/src/slash/prompt-template-bridge.js +399 -0
- package/src/slash/prompt-workflows.d.ts +21 -0
- package/src/slash/prompt-workflows.js +274 -0
- package/src/slash/selector.d.ts +47 -0
- package/src/slash/selector.js +117 -0
- package/src/slash/slash-bridge.d.ts +30 -0
- package/src/slash/slash-bridge.js +132 -0
- package/src/slash/slash-commands.d.ts +10 -0
- package/src/slash/slash-commands.js +1059 -0
- package/src/slash/slash-live-state.d.ts +21 -0
- package/src/slash/slash-live-state.js +263 -0
- package/src/slash/subagent-cost.d.ts +29 -0
- package/src/slash/subagent-cost.js +310 -0
- package/src/slash/subagents-admin.d.ts +3 -0
- package/src/slash/subagents-admin.js +481 -0
- package/src/tui/fleet-layout.d.ts +20 -0
- package/src/tui/fleet-layout.js +17 -0
- package/src/tui/fleet-native-transcript.d.ts +53 -0
- package/src/tui/fleet-native-transcript.js +339 -0
- package/src/tui/fleet-status.d.ts +92 -0
- package/src/tui/fleet-status.js +1132 -0
- package/src/tui/fleet-transcript.d.ts +64 -0
- package/src/tui/fleet-transcript.js +544 -0
- package/src/tui/fleet-viewport.d.ts +12 -0
- package/src/tui/fleet-viewport.js +35 -0
- package/src/tui/fleet.d.ts +196 -0
- package/src/tui/fleet.js +1588 -0
- package/src/tui/mouse-events.d.ts +21 -0
- package/src/tui/mouse-events.js +26 -0
- package/src/tui/render-helpers.d.ts +23 -0
- package/src/tui/render-helpers.js +100 -0
- package/src/tui/render.d.ts +66 -0
- package/src/tui/render.js +3707 -0
- package/src/tui/running-tone.d.ts +10 -0
- package/src/tui/running-tone.js +22 -0
- package/src/tui/subagent-messages.d.ts +22 -0
- package/src/tui/subagent-messages.js +270 -0
- package/src/ui-silent-marker.d.ts +20 -0
- package/src/ui-silent-marker.js +25 -0
- package/src/watchdog/change-signature.d.ts +7 -0
- package/src/watchdog/change-signature.js +243 -0
- package/src/watchdog/child-status.d.ts +53 -0
- package/src/watchdog/child-status.js +187 -0
- package/src/watchdog/diff-tool.d.ts +25 -0
- package/src/watchdog/diff-tool.js +104 -0
- package/src/watchdog/emission-guard.d.ts +36 -0
- package/src/watchdog/emission-guard.js +97 -0
- package/src/watchdog/guidance.d.ts +3 -0
- package/src/watchdog/guidance.js +19 -0
- package/src/watchdog/lsp-diagnostics.d.ts +17 -0
- package/src/watchdog/lsp-diagnostics.js +489 -0
- package/src/watchdog/model-selection.d.ts +24 -0
- package/src/watchdog/model-selection.js +167 -0
- package/src/watchdog/permission-arbiter.d.ts +20 -0
- package/src/watchdog/permission-arbiter.js +135 -0
- package/src/watchdog/register-child.d.ts +13 -0
- package/src/watchdog/register-child.js +128 -0
- package/src/watchdog/register-main.d.ts +11 -0
- package/src/watchdog/register-main.js +400 -0
- package/src/watchdog/render.d.ts +3 -0
- package/src/watchdog/render.js +33 -0
- package/src/watchdog/review.d.ts +36 -0
- package/src/watchdog/review.js +319 -0
- package/src/watchdog/rules.d.ts +21 -0
- package/src/watchdog/rules.js +58 -0
- package/src/watchdog/runtime.d.ts +195 -0
- package/src/watchdog/runtime.js +864 -0
- package/src/watchdog/scope.d.ts +14 -0
- package/src/watchdog/scope.js +44 -0
- package/src/watchdog/settings.d.ts +29 -0
- package/src/watchdog/settings.js +480 -0
- package/src/watchdog/tool-actions.d.ts +17 -0
- package/src/watchdog/tool-actions.js +150 -0
- package/src/watchdog/turn-delta.d.ts +15 -0
- package/src/watchdog/turn-delta.js +188 -0
- package/src/watchdog/types.d.ts +141 -0
- package/src/watchdog/types.js +27 -0
- package/src/watchdog/warning-format.d.ts +7 -0
- package/src/watchdog/warning-format.js +59 -0
- package/src/workflows/chat-progress.d.ts +37 -0
- package/src/workflows/chat-progress.js +129 -0
- package/src/workflows/host-command.d.ts +30 -0
- package/src/workflows/host-command.js +227 -0
- package/src/workflows/scripted-workflow.d.ts +204 -0
- package/src/workflows/scripted-workflow.js +1673 -0
- package/src/workflows/structured-workflow-scripts.d.ts +10 -0
- package/src/workflows/structured-workflow-scripts.js +179 -0
- package/src/workflows/workflow-auto-resume.d.ts +32 -0
- package/src/workflows/workflow-auto-resume.js +102 -0
- package/src/workflows/workflow-checklist.d.ts +127 -0
- package/src/workflows/workflow-checklist.js +314 -0
- package/src/workflows/workflow-child-summary.d.ts +24 -0
- package/src/workflows/workflow-child-summary.js +195 -0
- package/src/workflows/workflow-launch-record.d.ts +27 -0
- package/src/workflows/workflow-launch-record.js +48 -0
- package/src/workflows/workflow-preflight.d.ts +58 -0
- package/src/workflows/workflow-preflight.js +288 -0
- package/src/workflows/workflow-receipt.d.ts +34 -0
- package/src/workflows/workflow-receipt.js +454 -0
- package/src/workflows/workflow-resources.d.ts +55 -0
- package/src/workflows/workflow-resources.js +271 -0
- package/src/workflows/workflow-resume-claim.d.ts +82 -0
- package/src/workflows/workflow-resume-claim.js +210 -0
- package/src/workflows/workflow-resume.d.ts +56 -0
- package/src/workflows/workflow-resume.js +106 -0
- package/src/workflows/workflow-reuse.d.ts +61 -0
- package/src/workflows/workflow-reuse.js +186 -0
- package/src/workflows/workflow-revival.d.ts +33 -0
- package/src/workflows/workflow-revival.js +111 -0
- package/src/workflows/workflow-settlement.d.ts +84 -0
- package/src/workflows/workflow-settlement.js +203 -0
- package/src/workflows/workflow-stop-cause.d.ts +6 -0
- package/src/workflows/workflow-stop-cause.js +8 -0
- package/workflow-script-worker.cjs +1342 -0
- package/index.ts +0 -18
- package/node_modules/@xzzpig/pi-components/src/transcript.ts +0 -1878
- package/skills/pi-subagents/references/constraints-and-recipes.md +0 -74
- package/skills/pi-subagents/references/execution-controls.md +0 -561
- package/skills/pi-subagents/references/management-authoring-rpc.md +0 -165
- package/skills/pi-subagents/references/multi-lane-orchestration.md +0 -61
- package/skills/pi-subagents/references/review-and-validation.md +0 -73
- package/src/agents/advertised-agent-prompt.ts +0 -82
- package/src/agents/agent-eject.ts +0 -339
- package/src/agents/agent-management.ts +0 -1442
- package/src/agents/agent-memory.ts +0 -341
- package/src/agents/agent-refinements.ts +0 -624
- package/src/agents/agent-scope.ts +0 -10
- package/src/agents/agent-selection.ts +0 -25
- package/src/agents/agent-serializer.ts +0 -195
- package/src/agents/agents.ts +0 -3169
- package/src/agents/builtin-names.ts +0 -16
- package/src/agents/chain-serializer.ts +0 -285
- package/src/agents/frontmatter.ts +0 -153
- package/src/agents/global-npm-root.ts +0 -58
- package/src/agents/identity.ts +0 -30
- package/src/agents/proactive-skills.ts +0 -197
- package/src/agents/runtime-agent-events.ts +0 -70
- package/src/agents/runtime-agent-registry.ts +0 -457
- package/src/agents/runtime-discovery.ts +0 -39
- package/src/agents/skills.ts +0 -787
- package/src/api/agent-management.ts +0 -9
- package/src/api/agents.ts +0 -19
- package/src/api/background-work.ts +0 -206
- package/src/api/capability-ceiling.ts +0 -16
- package/src/api/child-tool-plan.ts +0 -5
- package/src/api/control-channel.ts +0 -4
- package/src/api/delegation.ts +0 -131
- package/src/api/external-job-provider.ts +0 -195
- package/src/api/external-runs.ts +0 -282
- package/src/api/inspectors.ts +0 -27
- package/src/api/intercom-bridge.ts +0 -3
- package/src/api/preflight.ts +0 -641
- package/src/api/project-panes.ts +0 -32
- package/src/api/required-child-extensions.ts +0 -6
- package/src/api/shared-types.ts +0 -29
- package/src/api/supervisor-routing.ts +0 -196
- package/src/api/workflow-resources.ts +0 -6
- package/src/extension/config.ts +0 -262
- package/src/extension/context-injection.ts +0 -123
- package/src/extension/control-notices.ts +0 -53
- package/src/extension/declaration-pinning.ts +0 -164
- package/src/extension/doctor.ts +0 -284
- package/src/extension/fanout-child.ts +0 -282
- package/src/extension/herdr-pi-bridge.ts +0 -166
- package/src/extension/index.ts +0 -1212
- package/src/extension/public-execution.ts +0 -262
- package/src/extension/reply-workflow-script.ts +0 -67
- package/src/extension/rpc.ts +0 -881
- package/src/extension/schemas.ts +0 -337
- package/src/extension/steering-notices.ts +0 -35
- package/src/extension/subagent-guide.ts +0 -127
- package/src/extension/subagent-options.ts +0 -47
- package/src/extension/tool-activation.ts +0 -147
- package/src/extension/tool-description.ts +0 -193
- package/src/extension/tool-result.ts +0 -19
- package/src/extension/upgrade-notice.ts +0 -40
- package/src/inspectors/actions.ts +0 -174
- package/src/inspectors/ghostty/actions.ts +0 -74
- package/src/inspectors/ghostty/plugin.ts +0 -29
- package/src/inspectors/herdr/actions.ts +0 -155
- package/src/inspectors/herdr/client.ts +0 -130
- package/src/inspectors/herdr/focus.ts +0 -55
- package/src/inspectors/herdr/plugin.ts +0 -20
- package/src/inspectors/herdr/project-panes.ts +0 -733
- package/src/inspectors/inspector-runner.ts +0 -153
- package/src/inspectors/plugins.ts +0 -76
- package/src/inspectors/session-roots-codec.ts +0 -31
- package/src/inspectors/shell-command.ts +0 -16
- package/src/inspectors/tmux/actions.ts +0 -204
- package/src/inspectors/tmux/client.ts +0 -85
- package/src/inspectors/tmux/plugin.ts +0 -21
- package/src/inspectors/types.ts +0 -51
- package/src/integrations/herdr-status.ts +0 -385
- package/src/integrations/pi-web-session-liveness.ts +0 -73
- package/src/integrations/program-status.ts +0 -215
- package/src/intercom/fork-supervisor-routing.ts +0 -533
- package/src/intercom/intercom-bridge.ts +0 -235
- package/src/intercom/native-supervisor-channel.ts +0 -1066
- package/src/intercom/result-intercom.ts +0 -433
- package/src/intercom/supervisor-ui.ts +0 -72
- package/src/missions/actions.ts +0 -433
- package/src/missions/goal-driver.ts +0 -177
- package/src/missions/lifecycle.ts +0 -367
- package/src/missions/store.ts +0 -613
- package/src/missions/types.ts +0 -190
- package/src/missions/workflow-state.ts +0 -281
- package/src/policy/authority.ts +0 -50
- package/src/profiles/profiles.ts +0 -674
- package/src/runs/background/active-async-capacity.ts +0 -548
- package/src/runs/background/active-run-index.ts +0 -155
- package/src/runs/background/async-execution.ts +0 -2479
- package/src/runs/background/async-job-tracker.ts +0 -869
- package/src/runs/background/async-resume.ts +0 -686
- package/src/runs/background/async-retention.ts +0 -953
- package/src/runs/background/async-status-snapshot.ts +0 -46
- package/src/runs/background/async-status.ts +0 -787
- package/src/runs/background/auto-drain.ts +0 -92
- package/src/runs/background/await-async-run.ts +0 -83
- package/src/runs/background/binary-bootstrap.ts +0 -67
- package/src/runs/background/calendar-schedule.ts +0 -90
- package/src/runs/background/chain-append.ts +0 -321
- package/src/runs/background/chain-root-attachment.ts +0 -263
- package/src/runs/background/completion-batcher.ts +0 -168
- package/src/runs/background/completion-dedupe.ts +0 -58
- package/src/runs/background/completion-replay.ts +0 -287
- package/src/runs/background/control-channel.ts +0 -659
- package/src/runs/background/fleet-view.ts +0 -692
- package/src/runs/background/index-segment.ts +0 -59
- package/src/runs/background/inspect-rpc.ts +0 -443
- package/src/runs/background/notify.ts +0 -1083
- package/src/runs/background/owned-process-tree.ts +0 -131
- package/src/runs/background/parallel-groups.ts +0 -45
- package/src/runs/background/pid-namespace.ts +0 -18
- package/src/runs/background/process-terminal-candidate.ts +0 -98
- package/src/runs/background/process-terminal.ts +0 -231
- package/src/runs/background/result-delivery-ownership.ts +0 -45
- package/src/runs/background/result-files.ts +0 -634
- package/src/runs/background/result-watcher.ts +0 -842
- package/src/runs/background/resume-guidance.ts +0 -56
- package/src/runs/background/retained-children.ts +0 -136
- package/src/runs/background/retained-nested-route-tracker.ts +0 -96
- package/src/runs/background/run-child-session.ts +0 -725
- package/src/runs/background/run-id-query.ts +0 -7
- package/src/runs/background/run-id-resolver.ts +0 -183
- package/src/runs/background/run-status.ts +0 -803
- package/src/runs/background/runner-aliases.ts +0 -183
- package/src/runs/background/runner-child-launch.ts +0 -96
- package/src/runs/background/runner-child-sessions.ts +0 -32
- package/src/runs/background/runner-http-dispatcher.ts +0 -122
- package/src/runs/background/runner-startup-failure.ts +0 -56
- package/src/runs/background/scheduled-runs.ts +0 -1222
- package/src/runs/background/stale-run-reconciler.ts +0 -463
- package/src/runs/background/steering.ts +0 -260
- package/src/runs/background/subagent-runner-bootstrap.ts +0 -279
- package/src/runs/background/subagent-runner.ts +0 -5251
- package/src/runs/background/subagent-wait.ts +0 -895
- package/src/runs/background/terminal-run-index.ts +0 -183
- package/src/runs/background/top-level-async.ts +0 -14
- package/src/runs/background/wait-completions.ts +0 -262
- package/src/runs/background/wait-config.ts +0 -50
- package/src/runs/background/wait-subscriptions.ts +0 -354
- package/src/runs/background/wait-tool.ts +0 -57
- package/src/runs/background/workflow-terminal-proof.ts +0 -85
- package/src/runs/foreground/async-dismiss-action.ts +0 -86
- package/src/runs/foreground/async-steering-action.ts +0 -276
- package/src/runs/foreground/async-stop-action.ts +0 -216
- package/src/runs/foreground/command-action.ts +0 -41
- package/src/runs/foreground/execution.ts +0 -2315
- package/src/runs/foreground/foreground-control.ts +0 -157
- package/src/runs/foreground/foreground-history.ts +0 -164
- package/src/runs/foreground/prompt-audit.ts +0 -172
- package/src/runs/foreground/subagent-executor.ts +0 -8252
- package/src/runs/foreground/workflow-detach-reconcile.ts +0 -304
- package/src/runs/foreground/workflow-foreground-steering.ts +0 -169
- package/src/runs/shared/abort-recovery.ts +0 -119
- package/src/runs/shared/acceptance.ts +0 -1664
- package/src/runs/shared/agent-contract.ts +0 -38
- package/src/runs/shared/async-status-projection.ts +0 -664
- package/src/runs/shared/background-process-options.ts +0 -9
- package/src/runs/shared/capability-ceiling.ts +0 -214
- package/src/runs/shared/chain-outputs.ts +0 -116
- package/src/runs/shared/child-commands.ts +0 -229
- package/src/runs/shared/child-hooks.ts +0 -175
- package/src/runs/shared/child-identity.ts +0 -62
- package/src/runs/shared/child-launch-plan.ts +0 -163
- package/src/runs/shared/child-launch.ts +0 -389
- package/src/runs/shared/child-lifecycle.ts +0 -28
- package/src/runs/shared/child-runtime-config.ts +0 -136
- package/src/runs/shared/child-session.ts +0 -699
- package/src/runs/shared/child-tool-plan.ts +0 -599
- package/src/runs/shared/claude-code-adapter.ts +0 -288
- package/src/runs/shared/codex-exec-adapter.ts +0 -129
- package/src/runs/shared/context-mode.ts +0 -44
- package/src/runs/shared/cursor-agent-adapter.ts +0 -114
- package/src/runs/shared/dynamic-fanout.ts +0 -297
- package/src/runs/shared/effective-system-prompt.ts +0 -33
- package/src/runs/shared/extension-bindings.ts +0 -103
- package/src/runs/shared/external-cli-contract.ts +0 -177
- package/src/runs/shared/external-cli-preflight.ts +0 -190
- package/src/runs/shared/external-cli-runner.ts +0 -437
- package/src/runs/shared/external-job-bridge.ts +0 -514
- package/src/runs/shared/external-job-runner.ts +0 -389
- package/src/runs/shared/fast-mode-extension.ts +0 -10
- package/src/runs/shared/fork-command-result.ts +0 -10
- package/src/runs/shared/git-environment.ts +0 -29
- package/src/runs/shared/herdr-connection.ts +0 -134
- package/src/runs/shared/herdr-external-adapters.ts +0 -169
- package/src/runs/shared/herdr-machine.ts +0 -279
- package/src/runs/shared/herdr-pi-protocol.ts +0 -59
- package/src/runs/shared/herdr-placed-run.ts +0 -264
- package/src/runs/shared/host-step-status.ts +0 -231
- package/src/runs/shared/lane-metadata.ts +0 -126
- package/src/runs/shared/launch-cwd.ts +0 -16
- package/src/runs/shared/long-running-guard.ts +0 -221
- package/src/runs/shared/mcp-config-sources.ts +0 -426
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +0 -579
- package/src/runs/shared/mcp-direct-tool-grant.ts +0 -210
- package/src/runs/shared/model-resolution-diagnostic.ts +0 -101
- package/src/runs/shared/model-resolution.ts +0 -503
- package/src/runs/shared/model-scope.ts +0 -224
- package/src/runs/shared/mutation-evidence.ts +0 -199
- package/src/runs/shared/nested-events.ts +0 -1125
- package/src/runs/shared/nested-path.ts +0 -38
- package/src/runs/shared/nested-render.ts +0 -127
- package/src/runs/shared/orca-progress-tabs.ts +0 -511
- package/src/runs/shared/parallel-handoff.ts +0 -789
- package/src/runs/shared/parallel-utils.ts +0 -292
- package/src/runs/shared/partial-output.ts +0 -48
- package/src/runs/shared/permissions.ts +0 -86
- package/src/runs/shared/pi-spawn.ts +0 -205
- package/src/runs/shared/process-signal.ts +0 -35
- package/src/runs/shared/profile-extensions.ts +0 -134
- package/src/runs/shared/profile-launch-env.ts +0 -121
- package/src/runs/shared/readonly-drain-observation.ts +0 -42
- package/src/runs/shared/run-fanout-budget.ts +0 -267
- package/src/runs/shared/run-history.ts +0 -288
- package/src/runs/shared/runner-launcher.ts +0 -25
- package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -44
- package/src/runs/shared/sandbox-profile-guard.ts +0 -119
- package/src/runs/shared/sandbox-startup-diagnostics.ts +0 -54
- package/src/runs/shared/session-lease.ts +0 -293
- package/src/runs/shared/single-output.ts +0 -366
- package/src/runs/shared/spawn-budget.ts +0 -128
- package/src/runs/shared/structured-output.ts +0 -463
- package/src/runs/shared/subagent-control.ts +0 -295
- package/src/runs/shared/subagent-prompt-runtime.ts +0 -598
- package/src/runs/shared/tool-availability.ts +0 -37
- package/src/runs/shared/tool-budget.ts +0 -87
- package/src/runs/shared/tool-timeout.ts +0 -93
- package/src/runs/shared/usage-budget.ts +0 -65
- package/src/runs/shared/usage-reconciliation.ts +0 -73
- package/src/runs/shared/workflow-async-child-guidance.ts +0 -18
- package/src/runs/shared/workflow-graph.ts +0 -225
- package/src/runs/shared/worktree-cleanup-apply.ts +0 -160
- package/src/runs/shared/worktree-cleanup-plan.ts +0 -891
- package/src/runs/shared/worktree-lock.ts +0 -29
- package/src/runs/shared/worktree-setup-command.ts +0 -213
- package/src/runs/shared/worktree.ts +0 -1554
- package/src/shared/accessible-dir.ts +0 -47
- package/src/shared/agent-stream-options.ts +0 -5
- package/src/shared/artifacts.ts +0 -281
- package/src/shared/atomic-json.ts +0 -85
- package/src/shared/capacity-resilient-json.ts +0 -102
- package/src/shared/child-cache-retention.ts +0 -43
- package/src/shared/child-session-name.ts +0 -48
- package/src/shared/child-transcript.ts +0 -264
- package/src/shared/completion-owner.ts +0 -14
- package/src/shared/disabled-features.ts +0 -123
- package/src/shared/display-text.ts +0 -150
- package/src/shared/edit-distance.ts +0 -33
- package/src/shared/extension-context.ts +0 -37
- package/src/shared/file-coalescer.ts +0 -49
- package/src/shared/file-lease.ts +0 -74
- package/src/shared/file-system-retry.ts +0 -95
- package/src/shared/fork-context.ts +0 -243
- package/src/shared/fork-session-cwd.ts +0 -27
- package/src/shared/formatters.ts +0 -142
- package/src/shared/jsonl-writer.ts +0 -92
- package/src/shared/launch-contract.ts +0 -206
- package/src/shared/model-info.ts +0 -132
- package/src/shared/model-response-aliases.ts +0 -13
- package/src/shared/node-executable.ts +0 -21
- package/src/shared/opencode-session-headers.ts +0 -30
- package/src/shared/package-version.ts +0 -17
- package/src/shared/parent-wake.ts +0 -79
- package/src/shared/permission-profile.ts +0 -56
- package/src/shared/prompt-resources.ts +0 -11
- package/src/shared/pruned-fork.ts +0 -469
- package/src/shared/required-child-extensions.ts +0 -115
- package/src/shared/runtime-module-path.ts +0 -19
- package/src/shared/sandbox-profile.ts +0 -37
- package/src/shared/session-file-trust.ts +0 -19
- package/src/shared/session-identity.ts +0 -10
- package/src/shared/session-tokens.ts +0 -55
- package/src/shared/settings-file-lease.ts +0 -36
- package/src/shared/settings.ts +0 -412
- package/src/shared/shortcuts.ts +0 -13
- package/src/shared/status-format.ts +0 -55
- package/src/shared/thinking-ceiling.ts +0 -46
- package/src/shared/types.ts +0 -3105
- package/src/shared/utf8.ts +0 -11
- package/src/shared/utils.ts +0 -610
- package/src/shared/watch-strategy.ts +0 -12
- package/src/shared/workflow-child-permit.ts +0 -212
- package/src/slash/delegation-adapters.ts +0 -452
- package/src/slash/delegation-json.ts +0 -108
- package/src/slash/delegation-request.ts +0 -176
- package/src/slash/prompt-template-bridge.ts +0 -435
- package/src/slash/prompt-workflows.ts +0 -298
- package/src/slash/selector.ts +0 -147
- package/src/slash/slash-bridge.ts +0 -192
- package/src/slash/slash-commands.ts +0 -1096
- package/src/slash/slash-live-state.ts +0 -310
- package/src/slash/subagent-cost.ts +0 -317
- package/src/slash/subagents-admin.ts +0 -489
- package/src/tui/fleet-native-transcript.ts +0 -424
- package/src/tui/fleet-status.ts +0 -1139
- package/src/tui/fleet-transcript.ts +0 -591
- package/src/tui/fleet.ts +0 -1618
- package/src/tui/mouse-events.ts +0 -42
- package/src/tui/render-helpers.ts +0 -111
- package/src/tui/render.ts +0 -3824
- package/src/tui/running-tone.ts +0 -28
- package/src/tui/subagent-messages.ts +0 -305
- package/src/ui-silent-marker.ts +0 -32
- package/src/watchdog/change-signature.ts +0 -260
- package/src/watchdog/child-status.ts +0 -225
- package/src/watchdog/diff-tool.ts +0 -112
- package/src/watchdog/emission-guard.ts +0 -125
- package/src/watchdog/guidance.ts +0 -20
- package/src/watchdog/lsp-diagnostics.ts +0 -538
- package/src/watchdog/model-selection.ts +0 -187
- package/src/watchdog/permission-arbiter.ts +0 -154
- package/src/watchdog/register-child.ts +0 -136
- package/src/watchdog/register-main.ts +0 -425
- package/src/watchdog/render.ts +0 -31
- package/src/watchdog/review.ts +0 -362
- package/src/watchdog/rules.ts +0 -70
- package/src/watchdog/runtime.ts +0 -927
- package/src/watchdog/scope.ts +0 -51
- package/src/watchdog/settings.ts +0 -520
- package/src/watchdog/tool-actions.ts +0 -156
- package/src/watchdog/turn-delta.ts +0 -190
- package/src/watchdog/types.ts +0 -186
- package/src/watchdog/warning-format.ts +0 -72
- package/src/workflows/chat-progress.ts +0 -152
- package/src/workflows/host-command.ts +0 -235
- package/src/workflows/scripted-workflow.ts +0 -2733
- package/src/workflows/structured-workflow-scripts.ts +0 -177
- package/src/workflows/workflow-checklist.ts +0 -442
- package/src/workflows/workflow-child-summary.ts +0 -172
- package/src/workflows/workflow-preflight.ts +0 -297
- package/src/workflows/workflow-receipt.ts +0 -390
- package/src/workflows/workflow-resources.ts +0 -275
- package/src/workflows/workflow-reuse.ts +0 -120
- package/src/workflows/workflow-revival.ts +0 -123
- package/src/workflows/workflow-settlement.ts +0 -252
|
@@ -0,0 +1,2206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Async execution logic for subagent tool
|
|
3
|
+
*/
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import * as fs from "node:fs";
|
|
7
|
+
import * as path from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import * as nodeModule from "node:module";
|
|
10
|
+
import { discoverAgents, formatUnknownAgentError, unknownAgentDiagnosticContext } from "../../agents/agents.js";
|
|
11
|
+
import { createAtomicJsonWriter, writePrivateAtomicJson } from "../../shared/atomic-json.js";
|
|
12
|
+
import { childCacheRetentionEnv } from "../../shared/child-cache-retention.js";
|
|
13
|
+
import { buildEffectiveSystemPrompt } from "../shared/effective-system-prompt.js";
|
|
14
|
+
import { currentCompletionOwnerId } from "../../shared/completion-owner.js";
|
|
15
|
+
import { planChildLaunch, projectChainOutputSchemas, resolveStepBehavior, suppressProgressForReadOnlyTask } from "../shared/child-launch-plan.js";
|
|
16
|
+
import { formatHerdrMachineRunnerUnsupported, PLACED_RESTORE_UNSUPPORTED, resolveMachinePlacement } from "../shared/herdr-machine.js";
|
|
17
|
+
import { applyThinkingSuffix, getHostBuiltinToolNames, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan } from "../shared/child-tool-plan.js";
|
|
18
|
+
import { assertClaudeCodeModelScope, isClaudeCodeAdapterId, resolveClaudeCodeOverride } from "../shared/claude-code-adapter.js";
|
|
19
|
+
import { injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.js";
|
|
20
|
+
import { applyWatchdogLaunchRules, sendRuleViolationWarning } from "../../watchdog/rules.js";
|
|
21
|
+
import { buildChainInstructions, getStepAgents, isDynamicParallelStep, isParallelStep, resolveExistingReadInstructionPaths, resolveExistingReadPaths, writeInitialProgressFile } from "../../shared/settings.js";
|
|
22
|
+
import { isDynamicRunnerGroup, isParallelGroup } from "../shared/parallel-utils.js";
|
|
23
|
+
import { PI_CODING_AGENT_PACKAGE, resolveBunPiExecutable, resolveHostPiPackageRoot } from "../shared/pi-spawn.js";
|
|
24
|
+
import { JITI_ALIAS_ENV, resolveHostPeerAliases } from "./runner-aliases.js";
|
|
25
|
+
import { preflightLaunchCwd } from "../shared/launch-cwd.js";
|
|
26
|
+
import { resolveNodeExecutable } from "../../shared/node-executable.js";
|
|
27
|
+
import { resolveRuntimeModulePath } from "../../shared/runtime-module-path.js";
|
|
28
|
+
import { backgroundProcessOptions } from "../shared/background-process-options.js";
|
|
29
|
+
import { normalizeSkillInput, resolveSkillsWithFallback } from "../../agents/skills.js";
|
|
30
|
+
import { PI_CODING_AGENT_PACKAGE_ROOT_ENV, PROMPT_REDACTED, resolveChildCwd } from "../../shared/utils.js";
|
|
31
|
+
import { resolveEffectiveSubagentModel, resolveModelOrigin, resolveModelSelection, resolveSubagentModelOverride } from "../shared/model-resolution.js";
|
|
32
|
+
import { resolveToolTimeoutMs, toolTimeoutFromEnv } from "../shared/tool-timeout.js";
|
|
33
|
+
import { resolveModelScopesForAgent } from "../shared/model-scope.js";
|
|
34
|
+
import { findModelInfo, resolveEffectiveThinking } from "../../shared/model-info.js";
|
|
35
|
+
import { assertThinkingWithinCeiling, intersectThinkingCeilings } from "../../shared/thinking-ceiling.js";
|
|
36
|
+
import { resolveExpectedWorktreeAgentCwd, resolveWorktreeProvider, shouldDeferWorktreeCwd, WORKTREE_AGENT_CWD_PLACEHOLDER } from "../shared/worktree.js";
|
|
37
|
+
import { buildWorkflowGraphSnapshot } from "../shared/workflow-graph.js";
|
|
38
|
+
import { ChainOutputValidationError, validateChainOutputBindings } from "../shared/chain-outputs.js";
|
|
39
|
+
import { createStructuredOutputRuntime } from "../shared/structured-output.js";
|
|
40
|
+
import { resolveAcceptanceReportMode, resolveEffectiveAcceptance, validateAcceptanceInput, validateExecutionAcceptance } from "../shared/acceptance.js";
|
|
41
|
+
import { createRunFanoutBudget, writeRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.js";
|
|
42
|
+
import { DIRS, SUBAGENT_ASYNC_STARTED_EVENT, SUBAGENT_LIFECYCLE_ARTIFACT_VERSION, TEMP_ROOT_DIR, getAsyncConfigPath, resolveChildMaxSubagentDepth, } from "../../shared/types.js";
|
|
43
|
+
import { inheritedNestedParentAddressOf, inheritedNestedRouteOf, nestedResultsPath, nestedSummaryFromAsyncStatus, writeNestedEvent } from "../shared/nested-events.js";
|
|
44
|
+
import { SUBAGENT_PARENT_SESSION_ENV } from "../shared/child-runtime-config.js";
|
|
45
|
+
import { childSessionFactoryModule } from "../shared/child-session.js";
|
|
46
|
+
import { inheritedChildRuntime } from "../shared/child-launch.js";
|
|
47
|
+
import { resultFilePath } from "./result-files.js";
|
|
48
|
+
import { updateActiveRunIndex } from "./active-run-index.js";
|
|
49
|
+
import { validateToolBudgetConfig } from "../shared/tool-budget.js";
|
|
50
|
+
import { usageBudgetState } from "../shared/usage-budget.js";
|
|
51
|
+
import { finalizeProcessTerminal, initializeProcessTerminal, readProcessTerminal } from "./process-terminal.js";
|
|
52
|
+
import { persistRunnerStartupFailure } from "./runner-startup-failure.js";
|
|
53
|
+
import { statusStepDescription } from "./chain-append.js";
|
|
54
|
+
import { currentBootId, currentRecordedPid } from "./boot-id.js";
|
|
55
|
+
import { currentPidNamespaceScope } from "./pid-namespace.js";
|
|
56
|
+
import { checkRecordedPidLiveness } from "./stale-run-reconciler.js";
|
|
57
|
+
import { lookupRunnerLauncher, resolveAgentRunnerLauncher, runnerLauncherPlacementError } from "../shared/runner-launcher.js";
|
|
58
|
+
import { SUBAGENT_PROCESS_TERMINAL_EVENT } from "../../shared/types.js";
|
|
59
|
+
import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling } from "../shared/capability-ceiling.js";
|
|
60
|
+
import { resolveLaunchBinding } from "../../shared/launch-contract.js";
|
|
61
|
+
import { resolvePermissionRules } from "../shared/permissions.js";
|
|
62
|
+
import { normalizeExtensionBindings, omitExtensionBindingsEnv, omitInheritedProfileEnv } from "../shared/extension-bindings.js";
|
|
63
|
+
import { omitGitRoutingEnv } from "../shared/git-environment.js";
|
|
64
|
+
import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.js";
|
|
65
|
+
import { assertRequiredChildExtensionsAdmitted, resolveRequiredChildExtensions, writeRetainedRequiredChildExtensions } from "../../shared/required-child-extensions.js";
|
|
66
|
+
const require = nodeModule.createRequire(import.meta.url);
|
|
67
|
+
// Cache failures as well as roots: management must remain loadable, and launches must not retry another SDK.
|
|
68
|
+
const piPackageSelection = (() => {
|
|
69
|
+
try {
|
|
70
|
+
return { root: resolveHostPiPackageRoot() };
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
return { error };
|
|
74
|
+
}
|
|
75
|
+
})();
|
|
76
|
+
const piPackageRoot = piPackageSelection.root;
|
|
77
|
+
function resolveJitiCliFromPackageJson(packageJsonPath) {
|
|
78
|
+
if (!fs.existsSync(packageJsonPath))
|
|
79
|
+
return undefined;
|
|
80
|
+
const packageRoot = path.dirname(packageJsonPath);
|
|
81
|
+
let parsed;
|
|
82
|
+
try {
|
|
83
|
+
parsed = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
89
|
+
return undefined;
|
|
90
|
+
const pkg = parsed;
|
|
91
|
+
const binField = pkg.bin;
|
|
92
|
+
const binPath = typeof binField === "string"
|
|
93
|
+
? binField
|
|
94
|
+
: binField?.jiti ?? Object.values(binField ?? {})[0];
|
|
95
|
+
const candidates = [binPath, "lib/jiti-cli.mjs"].filter((candidate) => Boolean(candidate));
|
|
96
|
+
for (const candidate of candidates) {
|
|
97
|
+
const cliPath = path.resolve(packageRoot, candidate);
|
|
98
|
+
if (fs.existsSync(cliPath))
|
|
99
|
+
return cliPath;
|
|
100
|
+
}
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
function resolveJitiCliPath() {
|
|
104
|
+
const candidates = [
|
|
105
|
+
() => require.resolve("jiti/package.json"),
|
|
106
|
+
() => piPackageRoot
|
|
107
|
+
? nodeModule.createRequire(path.join(piPackageRoot, "package.json")).resolve("jiti/package.json")
|
|
108
|
+
: undefined,
|
|
109
|
+
() => {
|
|
110
|
+
if (!process.argv[1])
|
|
111
|
+
return undefined;
|
|
112
|
+
const piEntry = fs.realpathSync(process.argv[1]);
|
|
113
|
+
return nodeModule.createRequire(piEntry).resolve("jiti/package.json");
|
|
114
|
+
},
|
|
115
|
+
() => piPackageRoot ? path.join(piPackageRoot, "node_modules", "jiti", "package.json") : undefined,
|
|
116
|
+
];
|
|
117
|
+
for (const candidate of candidates) {
|
|
118
|
+
try {
|
|
119
|
+
const packageJsonPath = candidate();
|
|
120
|
+
if (!packageJsonPath)
|
|
121
|
+
continue;
|
|
122
|
+
const cliPath = resolveJitiCliFromPackageJson(packageJsonPath);
|
|
123
|
+
if (cliPath)
|
|
124
|
+
return cliPath;
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
// Candidate not available in this install, continue probing.
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return undefined;
|
|
131
|
+
}
|
|
132
|
+
const jitiCliPath = resolveJitiCliPath();
|
|
133
|
+
const asyncRunnerModuleDir = path.dirname(fileURLToPath(import.meta.url));
|
|
134
|
+
// Resolved per launch: an in-place package update can swap a sibling's .ts for .js.
|
|
135
|
+
function asyncRunnerSourcePath() {
|
|
136
|
+
return resolveRuntimeModulePath(asyncRunnerModuleDir, "subagent-runner-bootstrap");
|
|
137
|
+
}
|
|
138
|
+
function sourceUnderNodeModules() {
|
|
139
|
+
return asyncRunnerSourcePath().split(path.sep).some((segment) => segment.toLowerCase() === "node_modules");
|
|
140
|
+
}
|
|
141
|
+
function supportsNativeRunner(nodeExecutable) {
|
|
142
|
+
return Boolean(process.features.typescript)
|
|
143
|
+
&& typeof nodeModule.registerHooks === "function"
|
|
144
|
+
&& nodeExecutable === process.execPath
|
|
145
|
+
&& !sourceUnderNodeModules();
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* A runner child without the ambient extensions does not load the parent extension that
|
|
149
|
+
* registered its model's provider, and still resolves the model when a built-in provider
|
|
150
|
+
* has the same id. Name that provider so a failed run can say so.
|
|
151
|
+
*/
|
|
152
|
+
function parentExtensionProviderForChild(ctx, disableAmbientExtensions, model, availableModels, preferredProvider) {
|
|
153
|
+
if (!disableAmbientExtensions || !ctx.parentProviderRegistry)
|
|
154
|
+
return undefined;
|
|
155
|
+
const provider = findModelInfo(model, availableModels, preferredProvider)?.provider;
|
|
156
|
+
return provider && ctx.parentProviderRegistry.getRegisteredProviderIds().includes(provider) ? provider : undefined;
|
|
157
|
+
}
|
|
158
|
+
export const DEFAULT_ASYNC_TIMEOUT_MS = 30 * 60 * 1000;
|
|
159
|
+
export function formatAsyncStartedMessage(headline, interactive) {
|
|
160
|
+
const guidance = interactive
|
|
161
|
+
? [
|
|
162
|
+
"Detached. Return control now: native completion wakes you, so do not sleep, poll, or call bg_wait for it.",
|
|
163
|
+
"One-shot check: subagent({ action: \"status\", id: \"...\" }).",
|
|
164
|
+
]
|
|
165
|
+
: [
|
|
166
|
+
"Detached non-interactive run: Pi auto-drains current-session subagent work at agent_end. Do not run sleep timers or polling loops. Use bg_wait only for results this turn needs from work without native notification, and subagent({ action: \"status\", id: \"...\" }) for a one-shot check.",
|
|
167
|
+
];
|
|
168
|
+
return [headline, "", ...guidance].join("\n");
|
|
169
|
+
}
|
|
170
|
+
/** Check whether detached async execution has a supported runtime. */
|
|
171
|
+
export function isAsyncAvailable() {
|
|
172
|
+
return resolveBunPiExecutable() !== undefined || supportsNativeRunner(resolveNodeExecutable()) || jitiCliPath !== undefined;
|
|
173
|
+
}
|
|
174
|
+
export function resolveAsyncRunnerLogPaths(cfg) {
|
|
175
|
+
const asyncDir = typeof cfg.asyncDir === "string"
|
|
176
|
+
? cfg.asyncDir
|
|
177
|
+
: undefined;
|
|
178
|
+
if (!asyncDir)
|
|
179
|
+
return undefined;
|
|
180
|
+
return {
|
|
181
|
+
stdoutPath: path.join(asyncDir, "runner.stdout.log"),
|
|
182
|
+
stderrPath: path.join(asyncDir, "runner.stderr.log"),
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
function closeFd(fd) {
|
|
186
|
+
if (fd === undefined)
|
|
187
|
+
return;
|
|
188
|
+
try {
|
|
189
|
+
fs.closeSync(fd);
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
// Best-effort cleanup; child process already owns its duplicated stdio fd.
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Spawn the async runner process
|
|
197
|
+
*/
|
|
198
|
+
const RUNNER_STARTUP_TIMEOUT_MS = 10_000;
|
|
199
|
+
function waitForStartupInterval(delayMs = 20) {
|
|
200
|
+
return new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
201
|
+
}
|
|
202
|
+
function readRunnerStartup(startupPath, expectedState, expectedToken) {
|
|
203
|
+
if (!fs.existsSync(startupPath))
|
|
204
|
+
return undefined;
|
|
205
|
+
try {
|
|
206
|
+
const payload = JSON.parse(fs.readFileSync(startupPath, "utf-8"));
|
|
207
|
+
if (payload.state === "error" && typeof payload.error === "string")
|
|
208
|
+
return { ok: false, error: payload.error, startupDidNotProceed: true };
|
|
209
|
+
if (payload.state !== expectedState)
|
|
210
|
+
return undefined;
|
|
211
|
+
if (typeof payload.token !== "string" || (expectedToken !== undefined && payload.token !== expectedToken)) {
|
|
212
|
+
return { ok: false, error: `Async runner wrote an invalid ${expectedState} startup handshake: ${startupPath}`, startupDidNotProceed: true };
|
|
213
|
+
}
|
|
214
|
+
return { ok: true, token: payload.token, pid: payload.pid, pidNamespaceScope: payload.pidNamespaceScope };
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
return { ok: false, error: `Failed to read async runner startup handshake '${startupPath}': ${error instanceof Error ? error.message : String(error)}`, startupDidNotProceed: true };
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
async function waitForRunnerStartup(startupPath, expectedState, timeoutMs, expectedToken, processClosed) {
|
|
221
|
+
const confirmOpen = async (result) => {
|
|
222
|
+
if (!processClosed || result.ok === false)
|
|
223
|
+
return result;
|
|
224
|
+
const outcome = await Promise.race([processClosed.then((exit) => ({ exit })), new Promise((resolve) => setImmediate(() => resolve(undefined)))]);
|
|
225
|
+
if (!outcome)
|
|
226
|
+
return result;
|
|
227
|
+
const finalResult = readRunnerStartup(startupPath, expectedState, expectedToken);
|
|
228
|
+
if (finalResult?.ok === false)
|
|
229
|
+
return finalResult;
|
|
230
|
+
const { exitCode, signal } = outcome.exit;
|
|
231
|
+
return { ok: false, error: `Async runner exited before startup state '${expectedState}' (exit code ${exitCode ?? "unknown"}, signal ${signal ?? "none"}).`, startupDidNotProceed: true };
|
|
232
|
+
};
|
|
233
|
+
const deadline = Date.now() + timeoutMs;
|
|
234
|
+
while (Date.now() <= deadline) {
|
|
235
|
+
const result = readRunnerStartup(startupPath, expectedState, expectedToken);
|
|
236
|
+
if (result)
|
|
237
|
+
return await confirmOpen(result);
|
|
238
|
+
const delay = waitForStartupInterval(Math.min(20, Math.max(1, deadline - Date.now())));
|
|
239
|
+
if (processClosed) {
|
|
240
|
+
const outcome = await Promise.race([delay.then(() => undefined), processClosed.then((exit) => ({ exit }))]);
|
|
241
|
+
if (outcome) {
|
|
242
|
+
const finalResult = readRunnerStartup(startupPath, expectedState, expectedToken);
|
|
243
|
+
if (finalResult?.ok === false)
|
|
244
|
+
return finalResult;
|
|
245
|
+
const { exitCode, signal } = outcome.exit;
|
|
246
|
+
return { ok: false, error: `Async runner exited before startup state '${expectedState}' (exit code ${exitCode ?? "unknown"}, signal ${signal ?? "none"}).`, startupDidNotProceed: true };
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
await delay;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
const finalResult = readRunnerStartup(startupPath, expectedState, expectedToken);
|
|
254
|
+
if (finalResult)
|
|
255
|
+
return finalResult;
|
|
256
|
+
return { ok: false, error: `Timed out after ${timeoutMs}ms waiting for the async runner startup state '${expectedState}'.`, startupDidNotProceed: true };
|
|
257
|
+
}
|
|
258
|
+
const writePrivateStartupControlJson = createAtomicJsonWriter({ mode: 0o600, ignoreCleanupErrorAfterSuccess: true });
|
|
259
|
+
function writeRunnerStartupControl(filePath, payload) {
|
|
260
|
+
// Delegate to the shared atomic JSON writer (temp file + rename, retrying
|
|
261
|
+
// transient Windows EPERM/EBUSY/EACCES locks and cleaning up the temp file
|
|
262
|
+
// on failure), so the startup handshake gets the same locking resilience as
|
|
263
|
+
// every other async control/result file. This is exercised by
|
|
264
|
+
// test/unit/atomic-json.test.ts.
|
|
265
|
+
writePrivateStartupControlJson(filePath, payload);
|
|
266
|
+
}
|
|
267
|
+
function runnerIsAlive(pid) {
|
|
268
|
+
try {
|
|
269
|
+
process.kill(pid, 0);
|
|
270
|
+
return true;
|
|
271
|
+
}
|
|
272
|
+
catch (error) {
|
|
273
|
+
return error.code === "EPERM";
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
function waitForStartupIntervalSync(delayMs = 20) {
|
|
277
|
+
const waitUntil = Date.now() + delayMs;
|
|
278
|
+
while (Date.now() < waitUntil) {
|
|
279
|
+
// Pre-handshake failures happen before the runner can be observed asynchronously.
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
function terminateRunnerBeforeProceed(pid) {
|
|
283
|
+
for (const signal of ["SIGTERM", "SIGKILL"]) {
|
|
284
|
+
if (!runnerIsAlive(pid))
|
|
285
|
+
return true;
|
|
286
|
+
try {
|
|
287
|
+
process.kill(pid, signal);
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
if (!runnerIsAlive(pid))
|
|
291
|
+
return true;
|
|
292
|
+
}
|
|
293
|
+
const deadline = Date.now() + 1000;
|
|
294
|
+
while (runnerIsAlive(pid) && Date.now() < deadline)
|
|
295
|
+
waitForStartupIntervalSync();
|
|
296
|
+
}
|
|
297
|
+
return !runnerIsAlive(pid);
|
|
298
|
+
}
|
|
299
|
+
async function terminateRunnerBeforeProceedAsyncDefault(proc, processClosed) {
|
|
300
|
+
for (const signal of ["SIGTERM", "SIGKILL"]) {
|
|
301
|
+
if (proc.pid === undefined || !runnerIsAlive(proc.pid))
|
|
302
|
+
return true;
|
|
303
|
+
try {
|
|
304
|
+
process.kill(proc.pid, signal);
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
if (proc.pid === undefined || !runnerIsAlive(proc.pid))
|
|
308
|
+
return true;
|
|
309
|
+
}
|
|
310
|
+
const exited = await Promise.race([processClosed.then(() => true), waitForStartupInterval(1000).then(() => false)]);
|
|
311
|
+
if (exited || proc.pid === undefined || !runnerIsAlive(proc.pid))
|
|
312
|
+
return true;
|
|
313
|
+
}
|
|
314
|
+
return proc.pid === undefined || !runnerIsAlive(proc.pid);
|
|
315
|
+
}
|
|
316
|
+
async function completeRunnerStartupHandshake(startupPath, startupAckPath, startupConfirmPath, startupProceedPath, proc, processClosed, getObservedProcessExit, runnerProcessInstanceId, persistStartupFailure,
|
|
317
|
+
// Behind a launcher the spawned pid is only the wrapper's: adopt the runner-reported pid and never signal the wrapper.
|
|
318
|
+
launcherIdentity) {
|
|
319
|
+
const terminateRunnerBeforeProceedAsync = async (proc, processClosed) => launcherIdentity ? launcherIdentity.terminate() : terminateRunnerBeforeProceedAsyncDefault(proc, processClosed);
|
|
320
|
+
try {
|
|
321
|
+
const ready = await waitForRunnerStartup(startupPath, "ready", RUNNER_STARTUP_TIMEOUT_MS, undefined, processClosed);
|
|
322
|
+
const identityError = ready.ok && launcherIdentity ? launcherIdentity.adopt(ready.pid, ready.pidNamespaceScope) : undefined;
|
|
323
|
+
if (identityError) {
|
|
324
|
+
persistStartupFailure(identityError);
|
|
325
|
+
return { runnerProcessInstanceId, error: identityError, terminationObserved: await terminateRunnerBeforeProceedAsync(proc, processClosed), startupDidNotProceed: true };
|
|
326
|
+
}
|
|
327
|
+
if (ready.ok === false) {
|
|
328
|
+
persistStartupFailure(ready.error);
|
|
329
|
+
const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
|
|
330
|
+
return { pid: proc.pid, runnerProcessInstanceId, error: ready.error, terminationObserved, startupDidNotProceed: true };
|
|
331
|
+
}
|
|
332
|
+
try {
|
|
333
|
+
writeRunnerStartupControl(startupAckPath, { action: "ack", token: ready.token });
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
const message = `Failed to acknowledge async runner startup: ${error instanceof Error ? error.message : String(error)}`;
|
|
337
|
+
persistStartupFailure(message);
|
|
338
|
+
const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
|
|
339
|
+
return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
|
|
340
|
+
}
|
|
341
|
+
const acknowledged = await waitForRunnerStartup(startupPath, "acknowledged", RUNNER_STARTUP_TIMEOUT_MS, ready.token, processClosed);
|
|
342
|
+
if (acknowledged.ok === false) {
|
|
343
|
+
persistStartupFailure(acknowledged.error);
|
|
344
|
+
const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
|
|
345
|
+
return { pid: proc.pid, runnerProcessInstanceId, error: acknowledged.error, terminationObserved, startupDidNotProceed: true };
|
|
346
|
+
}
|
|
347
|
+
try {
|
|
348
|
+
writeRunnerStartupControl(startupConfirmPath, { action: "confirm", token: ready.token });
|
|
349
|
+
}
|
|
350
|
+
catch (error) {
|
|
351
|
+
const message = `Failed to confirm async runner startup: ${error instanceof Error ? error.message : String(error)}`;
|
|
352
|
+
persistStartupFailure(message);
|
|
353
|
+
const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
|
|
354
|
+
return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
|
|
355
|
+
}
|
|
356
|
+
const confirmed = await waitForRunnerStartup(startupPath, "confirmed", RUNNER_STARTUP_TIMEOUT_MS, ready.token, processClosed);
|
|
357
|
+
if (confirmed.ok === false) {
|
|
358
|
+
persistStartupFailure(confirmed.error);
|
|
359
|
+
const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
|
|
360
|
+
return { pid: proc.pid, runnerProcessInstanceId, error: confirmed.error, terminationObserved, startupDidNotProceed: true };
|
|
361
|
+
}
|
|
362
|
+
const closedAtCommit = await Promise.race([
|
|
363
|
+
processClosed.then((exit) => exit),
|
|
364
|
+
new Promise((resolve) => setImmediate(() => resolve(undefined))),
|
|
365
|
+
]);
|
|
366
|
+
const observedExit = closedAtCommit ?? getObservedProcessExit();
|
|
367
|
+
if (observedExit) {
|
|
368
|
+
const message = `Async runner exited after startup state 'acknowledged' before proceed (exit code ${observedExit.exitCode ?? "unknown"}, signal ${observedExit.signal ?? "none"}).`;
|
|
369
|
+
persistStartupFailure(message);
|
|
370
|
+
const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
|
|
371
|
+
return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
|
|
372
|
+
}
|
|
373
|
+
try {
|
|
374
|
+
writeRunnerStartupControl(startupProceedPath, { action: "proceed", token: ready.token });
|
|
375
|
+
}
|
|
376
|
+
catch (error) {
|
|
377
|
+
const message = `Failed to authorize async runner startup: ${error instanceof Error ? error.message : String(error)}`;
|
|
378
|
+
persistStartupFailure(message);
|
|
379
|
+
const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
|
|
380
|
+
return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
|
|
381
|
+
}
|
|
382
|
+
try {
|
|
383
|
+
fs.rmSync(startupPath, { force: true });
|
|
384
|
+
}
|
|
385
|
+
catch { }
|
|
386
|
+
return { pid: proc.pid, runnerProcessInstanceId };
|
|
387
|
+
}
|
|
388
|
+
finally {
|
|
389
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
function persistPreProceedStartupFailure(asyncDir, runId, runnerProcessInstanceId, sessionId, completionOwnerId, message) {
|
|
393
|
+
try {
|
|
394
|
+
persistRunnerStartupFailure({ asyncDir, runId, runnerProcessInstanceId, sessionId, completionOwnerId, message });
|
|
395
|
+
}
|
|
396
|
+
catch {
|
|
397
|
+
// Startup failures must still return the original launch error.
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
function isStaleExtensionContextError(error) {
|
|
401
|
+
return error instanceof Error && /extension ctx is stale|stale after session replacement or reload/i.test(error.message);
|
|
402
|
+
}
|
|
403
|
+
export function emitProcessTerminalEvent(ctx, proof) {
|
|
404
|
+
try {
|
|
405
|
+
ctx.pi.events.emit(SUBAGENT_PROCESS_TERMINAL_EVENT, proof);
|
|
406
|
+
}
|
|
407
|
+
catch (error) {
|
|
408
|
+
if (isStaleExtensionContextError(error))
|
|
409
|
+
return;
|
|
410
|
+
console.error("Failed to emit subagent process-terminal event:", error);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
function spawnRunner(cfg, suffix, cwd, initialStatus, initialStatusPath, launchParentSessionId, onProcessTerminal, onBeforeProceed, requestedCwd = cwd) {
|
|
414
|
+
const cwdError = preflightLaunchCwd(requestedCwd, cwd);
|
|
415
|
+
if (cwdError)
|
|
416
|
+
return { error: cwdError };
|
|
417
|
+
if (launchParentSessionId !== undefined && (!launchParentSessionId || launchParentSessionId.trim() !== launchParentSessionId)) {
|
|
418
|
+
return { error: "Background runner parent session identity is invalid." };
|
|
419
|
+
}
|
|
420
|
+
const steps = cfg.steps;
|
|
421
|
+
if (!Array.isArray(steps))
|
|
422
|
+
return { error: "Background runner launch is missing its steps." };
|
|
423
|
+
const inconsistentParent = steps.some((step) => isParallelGroup(step)
|
|
424
|
+
? step.parallel.some((child) => child.parentSessionId !== launchParentSessionId)
|
|
425
|
+
: (isDynamicRunnerGroup(step) ? step.parallel.parentSessionId : step.parentSessionId) !== launchParentSessionId);
|
|
426
|
+
if (inconsistentParent)
|
|
427
|
+
return { error: "Background runner steps have inconsistent parent session identities." };
|
|
428
|
+
// The compiled host exposes its SDK only through Pi's extension loader.
|
|
429
|
+
const binaryHost = resolveBunPiExecutable();
|
|
430
|
+
if (!binaryHost && "error" in piPackageSelection)
|
|
431
|
+
throw piPackageSelection.error;
|
|
432
|
+
const nodeExecutable = resolveNodeExecutable();
|
|
433
|
+
const nativeRunnerSupported = supportsNativeRunner(nodeExecutable);
|
|
434
|
+
const runner = asyncRunnerSourcePath();
|
|
435
|
+
const runnerIsJavaScript = path.extname(runner) === ".js";
|
|
436
|
+
const bootstrap = resolveRuntimeModulePath(path.dirname(runner), "binary-bootstrap");
|
|
437
|
+
if (binaryHost && !fs.existsSync(bootstrap))
|
|
438
|
+
return { error: `Background runner bootstrap not found: ${bootstrap}` };
|
|
439
|
+
if (!binaryHost && !runnerIsJavaScript && !nativeRunnerSupported && !jitiCliPath) {
|
|
440
|
+
return { error: sourceUnderNodeModules()
|
|
441
|
+
? "Background runner source is installed under node_modules, so upstream jiti is required for TypeScript execution."
|
|
442
|
+
: "Background runner requires enabled native TypeScript with synchronous module hooks, or installed upstream jiti for TypeScript execution." };
|
|
443
|
+
}
|
|
444
|
+
if (!binaryHost && !piPackageRoot) {
|
|
445
|
+
return { error: `Background children require a supported standalone Pi host or the installed npm package (${PI_CODING_AGENT_PACKAGE}); neither is available.` };
|
|
446
|
+
}
|
|
447
|
+
const hostPeerAliases = !binaryHost && piPackageRoot ? resolveHostPeerAliases(piPackageRoot) : { aliases: {}, missing: [] };
|
|
448
|
+
if (hostPeerAliases.missing.length > 0) {
|
|
449
|
+
return { error: `Background children require the host npm package (${PI_CODING_AGENT_PACKAGE}) with its dependencies; ${piPackageRoot} does not provide ${hostPeerAliases.missing.join(", ")}.` };
|
|
450
|
+
}
|
|
451
|
+
fs.mkdirSync(TEMP_ROOT_DIR, { recursive: true });
|
|
452
|
+
const cfgPath = getAsyncConfigPath(suffix);
|
|
453
|
+
const runnerProcessInstanceId = randomUUID();
|
|
454
|
+
const hasRevivalLease = typeof cfg.revivalLease === "object";
|
|
455
|
+
const launchBarrierToken = hasRevivalLease ? undefined : runnerProcessInstanceId;
|
|
456
|
+
// A broker launcher may start the runner outside its own process, even under another kernel, so the
|
|
457
|
+
// spawned pid is only the wrapper's and only a direct runner shares Pi's boot id. The runner reports
|
|
458
|
+
// its own identity before it is allowed to proceed.
|
|
459
|
+
const launcher = cfg.launcher;
|
|
460
|
+
const bootId = launcher ? undefined : currentBootId();
|
|
461
|
+
const launchConfig = { ...cfg, runnerProcessInstanceId, ...(launchBarrierToken ? { launchBarrierToken } : {}), ...(bootId ? { bootId } : {}) };
|
|
462
|
+
writePrivateAtomicJson(cfgPath, launchConfig);
|
|
463
|
+
const command = binaryHost ?? nodeExecutable;
|
|
464
|
+
const launchForStartup = launchConfig;
|
|
465
|
+
const launchAsyncDir = typeof launchForStartup.asyncDir === "string" ? launchForStartup.asyncDir : undefined;
|
|
466
|
+
const launchRunId = typeof launchForStartup.id === "string" ? launchForStartup.id : suffix;
|
|
467
|
+
const launchSessionId = typeof launchForStartup.sessionId === "string" ? launchForStartup.sessionId : undefined;
|
|
468
|
+
const launchCompletionOwnerId = typeof launchForStartup.completionOwnerId === "string" ? launchForStartup.completionOwnerId : undefined;
|
|
469
|
+
const startupPath = typeof launchForStartup.revivalLease === "object" && launchAsyncDir
|
|
470
|
+
? path.join(launchAsyncDir, "runner-startup.json")
|
|
471
|
+
: undefined;
|
|
472
|
+
const startupAckPath = startupPath ? path.join(path.dirname(startupPath), "runner-startup-ack.json") : undefined;
|
|
473
|
+
const startupConfirmPath = startupPath ? path.join(path.dirname(startupPath), "runner-startup-confirm.json") : undefined;
|
|
474
|
+
const startupProceedPath = launchAsyncDir && (startupPath || launchBarrierToken)
|
|
475
|
+
? path.join(launchAsyncDir, "runner-startup-proceed.json")
|
|
476
|
+
: undefined;
|
|
477
|
+
if (startupPath)
|
|
478
|
+
fs.rmSync(startupPath, { force: true });
|
|
479
|
+
if (startupAckPath)
|
|
480
|
+
fs.rmSync(startupAckPath, { force: true });
|
|
481
|
+
if (startupConfirmPath)
|
|
482
|
+
fs.rmSync(startupConfirmPath, { force: true });
|
|
483
|
+
if (startupProceedPath)
|
|
484
|
+
fs.rmSync(startupProceedPath, { force: true });
|
|
485
|
+
const identityPath = launcher && launchBarrierToken && launchAsyncDir ? path.join(launchAsyncDir, "runner-startup.json") : undefined;
|
|
486
|
+
if (identityPath)
|
|
487
|
+
fs.rmSync(identityPath, { force: true });
|
|
488
|
+
let runnerIdentity;
|
|
489
|
+
// Wrapper exit is not runner exit, so only a reported runner in this namespace may be signalled.
|
|
490
|
+
const terminateBeforeProceed = (pid) => !launcher
|
|
491
|
+
? terminateRunnerBeforeProceed(pid)
|
|
492
|
+
: runnerIdentity !== undefined && runnerIdentity.pidNamespaceScope === currentPidNamespaceScope() && terminateRunnerBeforeProceed(runnerIdentity.pid);
|
|
493
|
+
const adoptRunnerIdentity = (pid, pidNamespaceScope) => {
|
|
494
|
+
if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid < 1)
|
|
495
|
+
return `Async runner reported an invalid process identity in '${launchAsyncDir}'.`;
|
|
496
|
+
runnerIdentity = { pid, ...(typeof pidNamespaceScope === "string" ? { pidNamespaceScope } : {}) };
|
|
497
|
+
try {
|
|
498
|
+
const status = JSON.parse(fs.readFileSync(initialStatusPath, "utf-8"));
|
|
499
|
+
writePrivateAtomicJson(initialStatusPath, { ...status, pid, ...(runnerIdentity.pidNamespaceScope !== undefined ? { pidNamespaceScope: runnerIdentity.pidNamespaceScope } : {}) });
|
|
500
|
+
return undefined;
|
|
501
|
+
}
|
|
502
|
+
catch (error) {
|
|
503
|
+
return `Failed to record async runner identity: ${error instanceof Error ? error.message : String(error)}`;
|
|
504
|
+
}
|
|
505
|
+
};
|
|
506
|
+
const logPaths = resolveAsyncRunnerLogPaths(launchConfig);
|
|
507
|
+
let stdoutFd;
|
|
508
|
+
let stderrFd;
|
|
509
|
+
try {
|
|
510
|
+
if (logPaths) {
|
|
511
|
+
fs.mkdirSync(path.dirname(logPaths.stdoutPath), { recursive: true });
|
|
512
|
+
stdoutFd = fs.openSync(logPaths.stdoutPath, "a");
|
|
513
|
+
stderrFd = fs.openSync(logPaths.stderrPath, "a");
|
|
514
|
+
}
|
|
515
|
+
// Short-circuit native peer aliases so Pi's loader and generated factories preserve filesystem resolution semantics.
|
|
516
|
+
const preload = Object.keys(hostPeerAliases.aliases).length > 0
|
|
517
|
+
? ["--import", new URL("../../../runner-peer-preload.mjs", import.meta.url).href]
|
|
518
|
+
: [];
|
|
519
|
+
const args = binaryHost
|
|
520
|
+
? ["--no-extensions", "--no-skills", "--no-prompt-templates", "--no-session", "--mode", "rpc", "--extension", bootstrap]
|
|
521
|
+
: runnerIsJavaScript
|
|
522
|
+
? [...preload, runner, cfgPath]
|
|
523
|
+
: nativeRunnerSupported
|
|
524
|
+
? [...preload, "--experimental-strip-types", runner, cfgPath]
|
|
525
|
+
: [...preload, jitiCliPath, runner, cfgPath];
|
|
526
|
+
const runnerEnv = {
|
|
527
|
+
// Fork: profile env inherited from the parent must not leak into children.
|
|
528
|
+
...omitGitRoutingEnv(omitInheritedProfileEnv(omitExtensionBindingsEnv(process.env))),
|
|
529
|
+
...childCacheRetentionEnv(),
|
|
530
|
+
[PI_CODING_AGENT_PACKAGE_ROOT_ENV]: binaryHost ? undefined : piPackageRoot,
|
|
531
|
+
// npm must override inherited bundled layouts (#2071); binaries retain release assets.
|
|
532
|
+
PI_PACKAGE_DIR: binaryHost ? process.env.PI_PACKAGE_DIR : piPackageRoot,
|
|
533
|
+
[JITI_ALIAS_ENV]: binaryHost ? undefined : JSON.stringify(hostPeerAliases.aliases),
|
|
534
|
+
PI_ASYNC_NATIVE_RUNNER: !binaryHost && (runnerIsJavaScript || nativeRunnerSupported) ? "1" : "0",
|
|
535
|
+
PI_SUBAGENT_RUNNER_CONFIG: binaryHost ? cfgPath : undefined,
|
|
536
|
+
};
|
|
537
|
+
if (launchParentSessionId === undefined)
|
|
538
|
+
delete runnerEnv[SUBAGENT_PARENT_SESSION_ENV];
|
|
539
|
+
else
|
|
540
|
+
runnerEnv[SUBAGENT_PARENT_SESSION_ENV] = launchParentSessionId;
|
|
541
|
+
const [spawnCommand, ...spawnArgs] = launcher ? [...launcher.argv, command, ...args] : [command, ...args];
|
|
542
|
+
const proc = spawn(spawnCommand, spawnArgs, {
|
|
543
|
+
cwd,
|
|
544
|
+
...backgroundProcessOptions(),
|
|
545
|
+
stdio: ["ignore", stdoutFd ?? "ignore", stderrFd ?? "ignore"],
|
|
546
|
+
env: runnerEnv,
|
|
547
|
+
});
|
|
548
|
+
let observedProcessExit;
|
|
549
|
+
proc.once("exit", (exitCode, signal) => { observedProcessExit = { exitCode, signal }; });
|
|
550
|
+
const processClosed = new Promise((resolve) => {
|
|
551
|
+
proc.once("close", (exitCode, signal) => {
|
|
552
|
+
observedProcessExit ??= { exitCode, signal };
|
|
553
|
+
resolve({ exitCode, signal });
|
|
554
|
+
});
|
|
555
|
+
});
|
|
556
|
+
closeFd(stdoutFd);
|
|
557
|
+
closeFd(stderrFd);
|
|
558
|
+
proc.on("error", (error) => {
|
|
559
|
+
console.error(`[pi-subagents] async spawn failed: ${error.message}`);
|
|
560
|
+
});
|
|
561
|
+
proc.once("close", (exitCode, signal) => {
|
|
562
|
+
const finalize = () => {
|
|
563
|
+
const launch = launchConfig;
|
|
564
|
+
const asyncDir = launch.asyncDir;
|
|
565
|
+
const runId = launch.id;
|
|
566
|
+
if (typeof asyncDir !== "string" || typeof runId !== "string")
|
|
567
|
+
return;
|
|
568
|
+
if (launcher) {
|
|
569
|
+
try {
|
|
570
|
+
writePrivateAtomicJson(path.join(asyncDir, "launcher-close.json"), { version: 1, runId, runnerProcessInstanceId, closeObservedAt: Date.now(), exitCode, signal, ...(runnerIdentity ? { runnerPid: runnerIdentity.pid } : {}) });
|
|
571
|
+
}
|
|
572
|
+
catch {
|
|
573
|
+
// Diagnostic only; process-terminal proof stays authoritative.
|
|
574
|
+
}
|
|
575
|
+
// The runner may outlive its wrapper; only a confirmed-dead runner in this pid namespace finalizes here,
|
|
576
|
+
// otherwise status-pid reconciliation does it later.
|
|
577
|
+
if (!runnerIdentity || runnerIdentity.pidNamespaceScope !== currentPidNamespaceScope()
|
|
578
|
+
|| checkRecordedPidLiveness(runnerIdentity) !== "dead")
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
finalizeProcessTerminal(asyncDir, runId, {
|
|
582
|
+
processInstanceId: runnerProcessInstanceId,
|
|
583
|
+
closeObservedAt: Date.now(),
|
|
584
|
+
exitCode,
|
|
585
|
+
signal,
|
|
586
|
+
});
|
|
587
|
+
const persisted = readProcessTerminal(asyncDir, { runId, runnerProcessInstanceId });
|
|
588
|
+
if (!persisted)
|
|
589
|
+
return;
|
|
590
|
+
if (launch.nestedRoute && launch.nestedSelf) {
|
|
591
|
+
try {
|
|
592
|
+
let status;
|
|
593
|
+
try {
|
|
594
|
+
status = JSON.parse(fs.readFileSync(path.join(asyncDir, "status.json"), "utf-8"));
|
|
595
|
+
status.processTerminal = persisted;
|
|
596
|
+
}
|
|
597
|
+
catch {
|
|
598
|
+
status = {
|
|
599
|
+
runId,
|
|
600
|
+
mode: "single",
|
|
601
|
+
state: persisted.state === "observed" ? "complete" : "failed",
|
|
602
|
+
startedAt: persisted.observedAt ?? Date.now(),
|
|
603
|
+
lastUpdate: Date.now(),
|
|
604
|
+
processTerminal: persisted,
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
writeNestedEvent(launch.nestedRoute, {
|
|
608
|
+
type: "subagent.nested.completed",
|
|
609
|
+
ts: Date.now(),
|
|
610
|
+
parentRunId: launch.nestedSelf.parentRunId,
|
|
611
|
+
parentStepIndex: launch.nestedSelf.parentStepIndex,
|
|
612
|
+
child: nestedSummaryFromAsyncStatus(status, asyncDir, {
|
|
613
|
+
id: runId,
|
|
614
|
+
parentRunId: launch.nestedSelf.parentRunId,
|
|
615
|
+
parentStepIndex: launch.nestedSelf.parentStepIndex,
|
|
616
|
+
depth: launch.nestedSelf.depth,
|
|
617
|
+
path: launch.nestedSelf.path,
|
|
618
|
+
mode: status.mode,
|
|
619
|
+
ts: Date.now(),
|
|
620
|
+
}),
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
catch (error) {
|
|
624
|
+
console.error("Failed to emit final nested process-terminal status:", error);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
onProcessTerminal?.(persisted);
|
|
628
|
+
};
|
|
629
|
+
if (startupPath)
|
|
630
|
+
setImmediate(finalize);
|
|
631
|
+
else
|
|
632
|
+
finalize();
|
|
633
|
+
});
|
|
634
|
+
if (typeof proc.pid !== "number") {
|
|
635
|
+
return { error: `async runner did not produce a pid for cwd: ${cwd}` };
|
|
636
|
+
}
|
|
637
|
+
try {
|
|
638
|
+
writePrivateAtomicJson(initialStatusPath, {
|
|
639
|
+
...initialStatus,
|
|
640
|
+
...(launcher ? {} : { pid: proc.pid, pidNamespaceScope: currentPidNamespaceScope(), ...(bootId ? { bootId } : {}) }),
|
|
641
|
+
processTerminal: { version: 1, state: "pending", runId: initialStatus.runId, runnerProcessInstanceId },
|
|
642
|
+
});
|
|
643
|
+
// Aggregate waits must see the launch before the runner's first status update.
|
|
644
|
+
updateActiveRunIndex(path.dirname(initialStatusPath), initialStatus.state, initialStatus.toolCallId);
|
|
645
|
+
}
|
|
646
|
+
catch (error) {
|
|
647
|
+
const message = `Failed to persist initial async status: ${error instanceof Error ? error.message : String(error)}`;
|
|
648
|
+
if (launchAsyncDir)
|
|
649
|
+
persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
|
|
650
|
+
const terminationObserved = terminateBeforeProceed(proc.pid);
|
|
651
|
+
return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
|
|
652
|
+
}
|
|
653
|
+
try {
|
|
654
|
+
if (!launchAsyncDir)
|
|
655
|
+
throw new Error("Async runner is missing its lifecycle directory.");
|
|
656
|
+
initializeProcessTerminal(launchAsyncDir, launchRunId, runnerProcessInstanceId);
|
|
657
|
+
}
|
|
658
|
+
catch (error) {
|
|
659
|
+
const message = `Failed to establish async runner lifecycle sidecar: ${error instanceof Error ? error.message : String(error)}`;
|
|
660
|
+
if (launchAsyncDir)
|
|
661
|
+
persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
|
|
662
|
+
const terminationObserved = terminateBeforeProceed(proc.pid);
|
|
663
|
+
return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
|
|
664
|
+
}
|
|
665
|
+
try {
|
|
666
|
+
onBeforeProceed?.(runnerProcessInstanceId);
|
|
667
|
+
}
|
|
668
|
+
catch (error) {
|
|
669
|
+
const message = `Failed to establish async runner capacity ownership: ${error instanceof Error ? error.message : String(error)}`;
|
|
670
|
+
if (launchAsyncDir)
|
|
671
|
+
persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
|
|
672
|
+
const terminationObserved = terminateBeforeProceed(proc.pid);
|
|
673
|
+
return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
|
|
674
|
+
}
|
|
675
|
+
if (identityPath && launchBarrierToken && startupProceedPath) {
|
|
676
|
+
proc.unref();
|
|
677
|
+
const fail = (message) => {
|
|
678
|
+
if (launchAsyncDir)
|
|
679
|
+
persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
|
|
680
|
+
return { ...(runnerIdentity ? { pid: runnerIdentity.pid } : {}), runnerProcessInstanceId, error: message, terminationObserved: terminateBeforeProceed(proc.pid), startupDidNotProceed: true };
|
|
681
|
+
};
|
|
682
|
+
return waitForRunnerStartup(identityPath, "identified", RUNNER_STARTUP_TIMEOUT_MS, launchBarrierToken, processClosed).then((identified) => {
|
|
683
|
+
if (identified.ok === false)
|
|
684
|
+
return fail(identified.error);
|
|
685
|
+
const identityError = adoptRunnerIdentity(identified.pid, identified.pidNamespaceScope);
|
|
686
|
+
if (identityError)
|
|
687
|
+
return fail(identityError);
|
|
688
|
+
try {
|
|
689
|
+
writeRunnerStartupControl(startupProceedPath, { action: "proceed", token: launchBarrierToken });
|
|
690
|
+
}
|
|
691
|
+
catch (error) {
|
|
692
|
+
return fail(`Failed to authorize async runner startup: ${error instanceof Error ? error.message : String(error)}`);
|
|
693
|
+
}
|
|
694
|
+
return { pid: identified.pid, runnerProcessInstanceId };
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
if (launchBarrierToken && startupProceedPath) {
|
|
698
|
+
try {
|
|
699
|
+
writeRunnerStartupControl(startupProceedPath, { action: "proceed", token: launchBarrierToken });
|
|
700
|
+
}
|
|
701
|
+
catch (error) {
|
|
702
|
+
const message = `Failed to authorize async runner startup: ${error instanceof Error ? error.message : String(error)}`;
|
|
703
|
+
if (launchAsyncDir)
|
|
704
|
+
persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
|
|
705
|
+
const terminationObserved = terminateBeforeProceed(proc.pid);
|
|
706
|
+
return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
proc.unref();
|
|
710
|
+
if (startupPath && startupAckPath && startupConfirmPath && startupProceedPath) {
|
|
711
|
+
const persistStartupFailure = (message) => {
|
|
712
|
+
if (launchAsyncDir)
|
|
713
|
+
persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
|
|
714
|
+
};
|
|
715
|
+
const handshake = completeRunnerStartupHandshake(startupPath, startupAckPath, startupConfirmPath, startupProceedPath, proc, processClosed, () => observedProcessExit ?? (proc.exitCode !== null || proc.signalCode !== null ? { exitCode: proc.exitCode, signal: proc.signalCode } : undefined), runnerProcessInstanceId, persistStartupFailure, launcher ? { adopt: adoptRunnerIdentity, terminate: () => terminateBeforeProceed(proc.pid) } : undefined);
|
|
716
|
+
if (!launcher)
|
|
717
|
+
return handshake;
|
|
718
|
+
return handshake.then(({ pid: _wrapperPid, ...result }) => ({ ...result, ...(runnerIdentity ? { pid: runnerIdentity.pid } : {}) }));
|
|
719
|
+
}
|
|
720
|
+
return { pid: proc.pid, runnerProcessInstanceId };
|
|
721
|
+
}
|
|
722
|
+
catch (error) {
|
|
723
|
+
closeFd(stdoutFd);
|
|
724
|
+
closeFd(stderrFd);
|
|
725
|
+
return { error: error instanceof Error ? error.message : String(error) };
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* An explicit `thinking: false` clears the level, so only `undefined` falls
|
|
730
|
+
* through to the agent's own value. Treating `false` as absent would silently
|
|
731
|
+
* apply the agent default the caller just cleared.
|
|
732
|
+
*/
|
|
733
|
+
export function resolveClaudeCodeThinking(source, fallback) {
|
|
734
|
+
const value = source === undefined ? fallback : source;
|
|
735
|
+
return typeof value === "string" ? value : undefined;
|
|
736
|
+
}
|
|
737
|
+
/** A pinned Claude Code model cannot survive pane-native saved-machine placement, which
|
|
738
|
+
* owns the remote model registry, so the combination fails instead of losing both flags. */
|
|
739
|
+
export function assertClaudeCodeOverrideIsLocal(agent, machine, override) {
|
|
740
|
+
if (!machine || !override)
|
|
741
|
+
return;
|
|
742
|
+
throw new Error(`Agent '${agent}' requested machine '${machine}', but a Claude Code model or thinking level cannot be honored on a saved machine. Remove the model or thinking request, or run the agent locally.`);
|
|
743
|
+
}
|
|
744
|
+
function formatAsyncStartError(mode, message) {
|
|
745
|
+
return {
|
|
746
|
+
content: [{ type: "text", text: message }],
|
|
747
|
+
isError: true,
|
|
748
|
+
details: { mode, results: [] },
|
|
749
|
+
};
|
|
750
|
+
}
|
|
751
|
+
const UNAVAILABLE_SUBAGENT_SKILL_ERROR = "Skills not found: pi-subagents";
|
|
752
|
+
class UnavailableSubagentSkillError extends Error {
|
|
753
|
+
}
|
|
754
|
+
class AsyncStartValidationError extends Error {
|
|
755
|
+
}
|
|
756
|
+
function profileProjectTrustedForCwd(ctx, cwd) {
|
|
757
|
+
return ctx.projectTrusted === true
|
|
758
|
+
&& ctx.trustedProjectCwd !== undefined
|
|
759
|
+
&& path.resolve(ctx.trustedProjectCwd) === path.resolve(cwd);
|
|
760
|
+
}
|
|
761
|
+
function profileProjectTrustError(agent, ctx) {
|
|
762
|
+
if (ctx.projectTrusted !== true) {
|
|
763
|
+
return `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but the project is not trusted. Trust the project and retry.`;
|
|
764
|
+
}
|
|
765
|
+
return `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but the child cwd is not an exact trusted project root. Launch from that trusted cwd and retry.`;
|
|
766
|
+
}
|
|
767
|
+
export function buildAsyncRunnerSteps(id, params) {
|
|
768
|
+
const { chain, agents, ctx, cwd, sessionFilesByFlatIndex, thinkingOverridesByFlatIndex, maxSubagentDepth, worktreeBaseDir, worktreeProvider, asyncDir, } = params;
|
|
769
|
+
// One runner hosts every new step, so they share one launcher or none. Covers initial chains and
|
|
770
|
+
// appends to a running runner; the attached root runs in its own runner.
|
|
771
|
+
const stepLaunchers = [...new Set(chain.flatMap(getStepAgents))].map((name) => ({ name, launcher: agents.find((agent) => agent.name === name)?.launcher }));
|
|
772
|
+
const launcherNames = new Set(stepLaunchers.map(({ launcher }) => launcher));
|
|
773
|
+
if (launcherNames.size > 1) {
|
|
774
|
+
return { error: `Every agent in one background runner must use the same launcher or none: ${stepLaunchers.map(({ name, launcher }) => `${name} (${launcher ?? "none"})`).join(", ")}.` };
|
|
775
|
+
}
|
|
776
|
+
const launcher = [...launcherNames][0];
|
|
777
|
+
const launchParentSessionId = ctx.parentSessionId ?? ctx.currentSessionId;
|
|
778
|
+
const outputBaseDir = params.outputBaseDir;
|
|
779
|
+
const resultMode = params.resultMode ?? "chain";
|
|
780
|
+
const chainSkills = params.chainSkills ?? [];
|
|
781
|
+
const availableModels = params.availableModels;
|
|
782
|
+
const runnerCwd = resolveChildCwd(ctx.cwd, cwd);
|
|
783
|
+
const launchMachine = params.machine;
|
|
784
|
+
let managedWorktreeProvider;
|
|
785
|
+
try {
|
|
786
|
+
if (chain.some((step) => "worktree" in step && step.worktree === true)) {
|
|
787
|
+
const resolved = resolveWorktreeProvider(worktreeProvider, worktreeBaseDir);
|
|
788
|
+
managedWorktreeProvider = shouldDeferWorktreeCwd(worktreeProvider, worktreeBaseDir) ? "worktrunk" : resolved;
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
catch (error) {
|
|
792
|
+
return { error: error instanceof Error ? error.message : String(error) };
|
|
793
|
+
}
|
|
794
|
+
const progressDir = params.progressDir ?? runnerCwd;
|
|
795
|
+
const graphChain = params.attachRoot
|
|
796
|
+
? [{
|
|
797
|
+
agent: params.attachRoot.agent,
|
|
798
|
+
task: `Attach async root ${params.attachRoot.runId}`,
|
|
799
|
+
label: params.attachRoot.label ?? `Attached root ${params.attachRoot.runId}`,
|
|
800
|
+
...(params.attachRoot.outputName ? { as: params.attachRoot.outputName } : {}),
|
|
801
|
+
}, ...chain]
|
|
802
|
+
: chain;
|
|
803
|
+
const firstStep = chain[0];
|
|
804
|
+
const originalTask = params.task ?? (firstStep
|
|
805
|
+
? (isParallelStep(firstStep)
|
|
806
|
+
? firstStep.parallel[0]?.task
|
|
807
|
+
: isDynamicParallelStep(firstStep)
|
|
808
|
+
? firstStep.parallel.task
|
|
809
|
+
: firstStep.task)
|
|
810
|
+
: undefined);
|
|
811
|
+
try {
|
|
812
|
+
if (params.validateOutputBindings !== false) {
|
|
813
|
+
validateChainOutputBindings(chain, { maxItems: params.dynamicFanoutMaxItems });
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
catch (error) {
|
|
817
|
+
if (error instanceof ChainOutputValidationError)
|
|
818
|
+
return { error: error.message };
|
|
819
|
+
throw error;
|
|
820
|
+
}
|
|
821
|
+
const diagnosticContext = params.unknownAgentDiagnosticContext
|
|
822
|
+
?? unknownAgentDiagnosticContext(discoverAgents(path.resolve(runnerCwd), "both"));
|
|
823
|
+
for (const s of chain) {
|
|
824
|
+
const stepAgents = isParallelStep(s)
|
|
825
|
+
? s.parallel.map((t) => t.agent)
|
|
826
|
+
: isDynamicParallelStep(s)
|
|
827
|
+
? [s.parallel.agent]
|
|
828
|
+
: [s.agent];
|
|
829
|
+
for (const agentName of stepAgents) {
|
|
830
|
+
if (!agents.find((x) => x.name === agentName))
|
|
831
|
+
return { error: formatUnknownAgentError(agentName, diagnosticContext) };
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
const graphSteps = projectChainOutputSchemas(graphChain, agents);
|
|
835
|
+
const workflowGraph = buildWorkflowGraphSnapshot({ runId: id, mode: resultMode, steps: graphSteps });
|
|
836
|
+
let progressInstructionCreated = false;
|
|
837
|
+
const buildStepOverrides = (s) => {
|
|
838
|
+
const stepSkillInput = normalizeSkillInput(s.skill);
|
|
839
|
+
return {
|
|
840
|
+
...(s.output !== undefined ? { output: s.output } : {}),
|
|
841
|
+
...(s.outputMode !== undefined ? { outputMode: s.outputMode } : {}),
|
|
842
|
+
...(s.reads !== undefined ? { reads: s.reads } : {}),
|
|
843
|
+
...(s.progress !== undefined ? { progress: s.progress } : {}),
|
|
844
|
+
...(stepSkillInput !== undefined ? { skills: stepSkillInput } : {}),
|
|
845
|
+
...(s.model !== undefined ? { model: s.model } : {}),
|
|
846
|
+
...(s.fast !== undefined ? { fast: s.fast } : {}),
|
|
847
|
+
...(s.outputSchema !== undefined ? { outputSchema: s.outputSchema } : {}),
|
|
848
|
+
};
|
|
849
|
+
};
|
|
850
|
+
const buildSeqStep = (s, sessionFile, behaviorCwd, progressPrecreated = false, resolvedBehavior, flatIndex, parallelOutputNamespace, runFanoutPath) => {
|
|
851
|
+
const a = agents.find((x) => x.name === s.agent);
|
|
852
|
+
const effectiveBehavior = resolvedBehavior ?? suppressProgressForReadOnlyTask(resolveStepBehavior(a, buildStepOverrides(s), chainSkills), s.task, originalTask);
|
|
853
|
+
const requestedMachine = s.machine ?? launchMachine ?? a.machine;
|
|
854
|
+
const externalRunner = a.runner?.type === "external-cli" || a.runner?.type === "external-job";
|
|
855
|
+
const externalRunnerType = a.runner?.type;
|
|
856
|
+
const machineUnsupported = formatHerdrMachineRunnerUnsupported({ machine: requestedMachine, agentName: a.name, runnerType: a.runner?.type, adapter: a.runner?.type === "external-cli" ? a.runner.adapter : undefined, worktree: s.worktree });
|
|
857
|
+
if (machineUnsupported)
|
|
858
|
+
throw new AsyncStartValidationError(machineUnsupported);
|
|
859
|
+
const launcherError = runnerLauncherPlacementError(a, requestedMachine);
|
|
860
|
+
if (launcherError)
|
|
861
|
+
throw new AsyncStartValidationError(launcherError);
|
|
862
|
+
const registeredExtensions = resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
|
|
863
|
+
try {
|
|
864
|
+
assertRequiredChildExtensionsAdmitted([params.requiredExtensions, ctx.childRuntime?.requiredExtensions, registeredExtensions], { agent: a.name, runnerType: a.runner?.type, machine: requestedMachine });
|
|
865
|
+
}
|
|
866
|
+
catch (error) {
|
|
867
|
+
throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
|
|
868
|
+
}
|
|
869
|
+
let machine;
|
|
870
|
+
let machineEnv;
|
|
871
|
+
if (requestedMachine) {
|
|
872
|
+
try {
|
|
873
|
+
const placement = resolveMachinePlacement({ machine: requestedMachine, cwd: runnerCwd, stepCwd: s.cwd ?? params.machineCwd });
|
|
874
|
+
machine = placement.machine;
|
|
875
|
+
machineEnv = placement.env;
|
|
876
|
+
}
|
|
877
|
+
catch (error) {
|
|
878
|
+
throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
// A code-owned Claude Code adapter owns its argv, but it does accept an explicit
|
|
882
|
+
// model/thinking request; those become --model/--effort on the launch below.
|
|
883
|
+
const claudeCodeAdapter = a.runner?.type === "external-cli" && isClaudeCodeAdapterId(a.runner.adapter);
|
|
884
|
+
if (externalRunner) {
|
|
885
|
+
const unsupported = [];
|
|
886
|
+
if (s.model !== undefined && !claudeCodeAdapter)
|
|
887
|
+
unsupported.push("model override");
|
|
888
|
+
if (effectiveBehavior.outputSchema !== undefined)
|
|
889
|
+
unsupported.push("structured output");
|
|
890
|
+
if (s.acceptance !== undefined || params.agentContract !== undefined || s.agentContract !== undefined)
|
|
891
|
+
unsupported.push("acceptance/agent contract");
|
|
892
|
+
if (s.toolBudget !== undefined || params.toolBudget !== undefined || a.toolBudget !== undefined || params.configToolBudget !== undefined)
|
|
893
|
+
unsupported.push("tool budget");
|
|
894
|
+
if (a.sandbox !== undefined)
|
|
895
|
+
unsupported.push("sandbox profile");
|
|
896
|
+
if ((s.fast ?? params.fast ?? a.fast) === true)
|
|
897
|
+
unsupported.push("fast mode");
|
|
898
|
+
if (params.contextForAgent?.(s.agent) === "fork")
|
|
899
|
+
unsupported.push("fork context");
|
|
900
|
+
if (unsupported.length > 0)
|
|
901
|
+
throw new AsyncStartValidationError(`Agent '${a.name}' uses runner.type='${externalRunnerType}' and does not support: ${unsupported.join(", ")}.`);
|
|
902
|
+
}
|
|
903
|
+
try {
|
|
904
|
+
assertAgentAllowedByCapabilityCeiling(a.name, intersectSubagentCapabilityCeilings(params.capabilityCeiling, ctx.childRuntime?.capabilityCeiling));
|
|
905
|
+
}
|
|
906
|
+
catch (error) {
|
|
907
|
+
throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
|
|
908
|
+
}
|
|
909
|
+
const toolBudgetInput = s.toolBudget ?? params.toolBudget ?? a.toolBudget ?? params.configToolBudget;
|
|
910
|
+
const resolvedToolBudget = validateToolBudgetConfig(toolBudgetInput, s.toolBudget ? "toolBudget" : a.toolBudget ? "agent.toolBudget" : "config.toolBudget");
|
|
911
|
+
if (resolvedToolBudget.error)
|
|
912
|
+
throw new AsyncStartValidationError(resolvedToolBudget.error);
|
|
913
|
+
const resolvedToolTimeout = resolveToolTimeoutMs({
|
|
914
|
+
callValue: params.callToolTimeoutMs,
|
|
915
|
+
agentValue: a.defaultToolTimeoutMs,
|
|
916
|
+
configValue: params.configToolTimeoutMs,
|
|
917
|
+
envValue: params.toolTimeoutMsEnv ?? toolTimeoutFromEnv(),
|
|
918
|
+
});
|
|
919
|
+
if (resolvedToolTimeout.error)
|
|
920
|
+
throw new AsyncStartValidationError(resolvedToolTimeout.error);
|
|
921
|
+
const launchPlan = planChildLaunch({
|
|
922
|
+
agentConfig: a,
|
|
923
|
+
stepOverrides: buildStepOverrides(s),
|
|
924
|
+
task: s.task,
|
|
925
|
+
originalTask,
|
|
926
|
+
runnerCwd,
|
|
927
|
+
runtimeCwd: ctx.cwd,
|
|
928
|
+
stepCwdInput: s.cwd,
|
|
929
|
+
behaviorCwd,
|
|
930
|
+
...(machine ? { machineCwd: machine.cwd } : {}),
|
|
931
|
+
chainSkills,
|
|
932
|
+
outputBaseDir,
|
|
933
|
+
parallelOutputNamespace,
|
|
934
|
+
resolvedBehavior: effectiveBehavior,
|
|
935
|
+
});
|
|
936
|
+
const { stepCwd, instructionCwd, readExistenceCwd, behavior, namespaceOutputPath, outputPath, skillNames } = launchPlan;
|
|
937
|
+
const profileChildCwd = behaviorCwd ?? stepCwd;
|
|
938
|
+
if (a.sandbox && (a.source === "project" || a.override?.scope === "project") && !profileProjectTrustedForCwd(ctx, profileChildCwd)) {
|
|
939
|
+
throw new AsyncStartValidationError(profileProjectTrustError(a, ctx));
|
|
940
|
+
}
|
|
941
|
+
const { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(skillNames, stepCwd, ctx.cwd, a.skillPath, a.filePath ? path.dirname(a.filePath) : stepCwd);
|
|
942
|
+
if (missingSkills.includes("pi-subagents"))
|
|
943
|
+
throw new UnavailableSubagentSkillError(UNAVAILABLE_SUBAGENT_SKILL_ERROR);
|
|
944
|
+
const systemPrompt = buildEffectiveSystemPrompt({ agent: a, resolvedSkills, cwd: stepCwd });
|
|
945
|
+
const readInstructions = buildChainInstructions({ ...behavior, output: false, progress: false }, instructionCwd, false, undefined, readExistenceCwd);
|
|
946
|
+
const isFirstProgressAgent = behavior.progress && !progressPrecreated && !progressInstructionCreated;
|
|
947
|
+
if (behavior.progress)
|
|
948
|
+
progressInstructionCreated = true;
|
|
949
|
+
const progressInstructions = buildChainInstructions({ ...behavior, output: false, reads: false }, progressDir, isFirstProgressAgent);
|
|
950
|
+
const validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Async step (${s.agent})`);
|
|
951
|
+
if (validationError)
|
|
952
|
+
throw new AsyncStartValidationError(validationError);
|
|
953
|
+
let taskTemplate = s.task ?? "{previous}";
|
|
954
|
+
taskTemplate = taskTemplate.replace(/\{task\}/g, originalTask ?? "");
|
|
955
|
+
taskTemplate = taskTemplate.replace(/\{chain_dir\}/g, behaviorCwd ?? runnerCwd);
|
|
956
|
+
const taskText = `${readInstructions.prefix}${taskTemplate}${progressInstructions.suffix}`;
|
|
957
|
+
// A namespaced parallel output path is added to each child's task by the runner.
|
|
958
|
+
const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a);
|
|
959
|
+
const modelScopes = resolveModelScopesForAgent(ctx.modelScope, a.name, ctx.currentModel, ctx.scopedModelIds);
|
|
960
|
+
const modelOrigin = resolveModelOrigin({ explicitModel: s.model, agentModel: a.model, parentModel: ctx.currentModel });
|
|
961
|
+
const primaryModelFromParent = modelOrigin === "inherited";
|
|
962
|
+
const primaryModel = externalRunner ? undefined : resolveEffectiveSubagentModel(s.model, a.model, ctx.currentModel, availableModels, a.modelProvider ?? ctx.currentModelProvider, { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" });
|
|
963
|
+
const thinkingOverride = flatIndex === undefined ? undefined : thinkingOverridesByFlatIndex?.[flatIndex];
|
|
964
|
+
let claudeCodeOverride;
|
|
965
|
+
if (claudeCodeAdapter) {
|
|
966
|
+
try {
|
|
967
|
+
claudeCodeOverride = resolveClaudeCodeOverride({
|
|
968
|
+
model: typeof s.model === "string" ? s.model : undefined,
|
|
969
|
+
agent: a,
|
|
970
|
+
thinking: resolveClaudeCodeThinking(thinkingOverride, a.thinking),
|
|
971
|
+
thinkingCeiling: intersectThinkingCeilings(params.thinkingCeiling, a.maxThinking, ctx.childRuntime?.thinkingCeiling),
|
|
972
|
+
agentName: a.name,
|
|
973
|
+
runId: id,
|
|
974
|
+
});
|
|
975
|
+
assertClaudeCodeModelScope({ scopes: modelScopes, model: claudeCodeOverride?.model, agent: a.name, runId: id });
|
|
976
|
+
assertClaudeCodeOverrideIsLocal(a.name, machine ? requestedMachine : undefined, claudeCodeOverride);
|
|
977
|
+
}
|
|
978
|
+
catch (error) {
|
|
979
|
+
throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
const effectiveThinking = externalRunner ? undefined : thinkingOverride ?? a.thinking;
|
|
983
|
+
const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinking, thinkingOverride !== undefined);
|
|
984
|
+
const contextLimit = model ? findModelInfo(model, availableModels, a.modelProvider ?? ctx.currentModelProvider)?.contextWindow : undefined;
|
|
985
|
+
const thinkingCeiling = externalRunner ? undefined : intersectThinkingCeilings(params.thinkingCeiling, a.maxThinking, ctx.childRuntime?.thinkingCeiling);
|
|
986
|
+
if (!externalRunner) {
|
|
987
|
+
try {
|
|
988
|
+
assertThinkingWithinCeiling({ model, configThinking: effectiveThinking, ceiling: thinkingCeiling, agent: a.name, runId: id });
|
|
989
|
+
}
|
|
990
|
+
catch (error) {
|
|
991
|
+
throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
const agentContract = s.agentContract ?? params.agentContract;
|
|
995
|
+
const permissionRules = resolvePermissionRules(ctx.permissions, a.permissions);
|
|
996
|
+
let selectedModel = model;
|
|
997
|
+
let requestedModel;
|
|
998
|
+
if (!externalRunner) {
|
|
999
|
+
try {
|
|
1000
|
+
const modelEvidence = resolveModelSelection(primaryModel, availableModels, a.modelProvider ?? ctx.currentModelProvider, {
|
|
1001
|
+
scope: modelScopes,
|
|
1002
|
+
primaryModelFromParent,
|
|
1003
|
+
origin: modelOrigin,
|
|
1004
|
+
});
|
|
1005
|
+
requestedModel = modelEvidence.requestedModel;
|
|
1006
|
+
selectedModel = applyThinkingSuffix(modelEvidence.model, effectiveThinking, thinkingOverride !== undefined);
|
|
1007
|
+
assertThinkingWithinCeiling({ model: selectedModel, configThinking: effectiveThinking, ceiling: thinkingCeiling, agent: a.name, runId: id });
|
|
1008
|
+
}
|
|
1009
|
+
catch (error) {
|
|
1010
|
+
throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
const launchRuleError = applyWatchdogLaunchRules({ cwd: machine ? runnerCwd : stepCwd, agent: a.name, model: selectedModel, warn: (violation) => sendRuleViolationWarning(ctx.pi, violation) });
|
|
1014
|
+
if (launchRuleError)
|
|
1015
|
+
throw new AsyncStartValidationError(launchRuleError);
|
|
1016
|
+
const fast = s.fast ?? params.fast ?? a.fast;
|
|
1017
|
+
const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
|
|
1018
|
+
const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
|
|
1019
|
+
const toolPlan = resolvePiLaunchToolPlan({
|
|
1020
|
+
tools: a.tools,
|
|
1021
|
+
excludeTools: a.excludeTools,
|
|
1022
|
+
allowNestedSubagents: a.allowNestedSubagents,
|
|
1023
|
+
extensions: a.extensions,
|
|
1024
|
+
subagentOnlyExtensions: a.subagentOnlyExtensions,
|
|
1025
|
+
requiredExtensions,
|
|
1026
|
+
mcpDirectTools: a.mcpDirectTools,
|
|
1027
|
+
cwd: stepCwd,
|
|
1028
|
+
requireReadTool: Boolean(resolvedSkills.length),
|
|
1029
|
+
structuredOutput: Boolean(behavior.outputSchema),
|
|
1030
|
+
fast,
|
|
1031
|
+
model: selectedModel,
|
|
1032
|
+
capabilityCeiling: params.capabilityCeiling,
|
|
1033
|
+
inheritedCapabilityCeiling: ctx.childRuntime?.capabilityCeiling,
|
|
1034
|
+
agentName: a.name,
|
|
1035
|
+
permissionRules,
|
|
1036
|
+
runtimeSnapshotHost: ctx.pi,
|
|
1037
|
+
sandbox: a.sandbox,
|
|
1038
|
+
permissionProfile: a.permissionProfile,
|
|
1039
|
+
hostAvailableBuiltins,
|
|
1040
|
+
});
|
|
1041
|
+
const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
|
|
1042
|
+
const parentExtensionProvider = externalRunner || machine ? undefined : parentExtensionProviderForChild(ctx, toolPlan.disableAmbientExtensions, selectedModel, availableModels, a.modelProvider ?? ctx.currentModelProvider);
|
|
1043
|
+
if (externalRunner && permissionRules) {
|
|
1044
|
+
throw new AsyncStartValidationError(`Agent '${a.name}' uses runner.type='${externalRunnerType}', which cannot enforce native Pi child permission rules.`);
|
|
1045
|
+
}
|
|
1046
|
+
return {
|
|
1047
|
+
parentSessionId: launchParentSessionId,
|
|
1048
|
+
...(ctx.parentSessionFile ? { parentSessionFile: ctx.parentSessionFile } : {}),
|
|
1049
|
+
permissionRules,
|
|
1050
|
+
...(ctx.projectTrusted !== undefined ? { projectTrusted: ctx.projectTrusted } : {}),
|
|
1051
|
+
...(ctx.trustedProjectCwd ? { trustedProjectCwd: ctx.trustedProjectCwd } : {}),
|
|
1052
|
+
...(params.capabilityCeiling ? { capabilityCeiling: params.capabilityCeiling } : {}),
|
|
1053
|
+
...(runFanoutPath ? { runFanoutPath } : {}),
|
|
1054
|
+
agent: s.agent,
|
|
1055
|
+
task,
|
|
1056
|
+
...(a.runner ? { runner: a.runner } : {}),
|
|
1057
|
+
...(claudeCodeOverride ? { claudeCodeOverrideArgs: claudeCodeOverride.args } : {}),
|
|
1058
|
+
...(machine ? { machine } : {}),
|
|
1059
|
+
...(machineEnv ? { machineEnv } : {}),
|
|
1060
|
+
...(params.contextForAgent ? { context: params.contextForAgent(s.agent) } : {}),
|
|
1061
|
+
...(agentContract ? { agentContract } : {}),
|
|
1062
|
+
phase: s.phase,
|
|
1063
|
+
label: s.label,
|
|
1064
|
+
outputName: s.as,
|
|
1065
|
+
structured: Boolean(behavior.outputSchema),
|
|
1066
|
+
cwd: stepCwd,
|
|
1067
|
+
requestedCwd: machine ? machine.cwd : s.cwd ?? stepCwd,
|
|
1068
|
+
model: selectedModel,
|
|
1069
|
+
...(contextLimit !== undefined ? { contextLimit } : {}),
|
|
1070
|
+
...(fast !== undefined ? { fast } : {}),
|
|
1071
|
+
thinking: resolveEffectiveThinking(selectedModel, effectiveThinking),
|
|
1072
|
+
...(thinkingCeiling ? { thinkingCeiling } : {}),
|
|
1073
|
+
launchResolvedExtensions,
|
|
1074
|
+
...(parentExtensionProvider ? { parentExtensionProvider } : {}),
|
|
1075
|
+
...(requestedModel ? { requestedModel } : {}),
|
|
1076
|
+
...(primaryModelFromParent ? { skipPrimaryModelVerification: true } : {}),
|
|
1077
|
+
...(availableModels && availableModels.length > 0 ? { modelVerificationRegistry: availableModels } : {}),
|
|
1078
|
+
...(ctx.modelResponseAliases ? { modelResponseAliases: ctx.modelResponseAliases } : {}),
|
|
1079
|
+
tools: a.tools,
|
|
1080
|
+
excludeTools: a.excludeTools,
|
|
1081
|
+
allowNestedSubagents: a.allowNestedSubagents,
|
|
1082
|
+
allowedAgents: a.allowedAgents,
|
|
1083
|
+
extensions: a.extensions,
|
|
1084
|
+
subagentOnlyExtensions: a.subagentOnlyExtensions,
|
|
1085
|
+
...(!externalRunner ? { requiredExtensions } : {}),
|
|
1086
|
+
mcpDirectTools: a.mcpDirectTools,
|
|
1087
|
+
...(toolPlan.builtinMcpTools ? { builtinMcpTools: toolPlan.builtinMcpTools } : {}),
|
|
1088
|
+
mutationTools: a.mutationTools,
|
|
1089
|
+
...(a.sandbox ? { sandbox: a.sandbox } : {}),
|
|
1090
|
+
...(a.permissionProfile ? { permissionProfile: a.permissionProfile } : {}),
|
|
1091
|
+
systemPrompt,
|
|
1092
|
+
systemPromptMode: a.systemPromptMode,
|
|
1093
|
+
inheritProjectContext: a.inheritProjectContext,
|
|
1094
|
+
inheritGlobalContext: a.inheritGlobalContext,
|
|
1095
|
+
inheritSkills: a.inheritSkills,
|
|
1096
|
+
skills: resolvedSkills.map((r) => r.name),
|
|
1097
|
+
outputPath,
|
|
1098
|
+
...(namespaceOutputPath ? { namespaceOutputPath: true } : {}),
|
|
1099
|
+
outputMode: behavior.outputMode,
|
|
1100
|
+
sessionFile,
|
|
1101
|
+
maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, a.maxSubagentDepth),
|
|
1102
|
+
timeoutMs: a.defaultTimeoutMs ?? DEFAULT_ASYNC_TIMEOUT_MS,
|
|
1103
|
+
toolTimeoutMs: resolvedToolTimeout.toolTimeoutMs,
|
|
1104
|
+
waitToolEnabled: params.waitToolEnabled,
|
|
1105
|
+
waitToolDefaultTimeoutMs: params.waitToolDefaultTimeoutMs,
|
|
1106
|
+
effectiveAcceptance: resolveEffectiveAcceptance({
|
|
1107
|
+
explicit: s.acceptance,
|
|
1108
|
+
agentName: s.agent,
|
|
1109
|
+
acceptanceRole: a.acceptanceRole,
|
|
1110
|
+
task,
|
|
1111
|
+
mode: resultMode,
|
|
1112
|
+
async: true,
|
|
1113
|
+
dynamic: false,
|
|
1114
|
+
agentContract,
|
|
1115
|
+
}),
|
|
1116
|
+
acceptanceInput: s.acceptance,
|
|
1117
|
+
acceptanceRole: a.acceptanceRole,
|
|
1118
|
+
...(s.gateOn ? { gateOn: s.gateOn } : {}),
|
|
1119
|
+
...(behavior.outputSchema ? { structuredOutputSchema: behavior.outputSchema } : {}),
|
|
1120
|
+
...(behavior.outputSchema ? { structuredOutput: createStructuredOutputRuntime(behavior.outputSchema, path.join(asyncDir, "structured-output"), { acceptanceReport: resolveAcceptanceReportMode(s.acceptance) }) } : {}),
|
|
1121
|
+
...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),
|
|
1122
|
+
...(s.worktree ? { worktree: true } : {}),
|
|
1123
|
+
};
|
|
1124
|
+
};
|
|
1125
|
+
let flatStepIndex = 0;
|
|
1126
|
+
const nextFlatStep = () => {
|
|
1127
|
+
const index = flatStepIndex;
|
|
1128
|
+
const sessionFile = sessionFilesByFlatIndex?.[flatStepIndex];
|
|
1129
|
+
const thinkingOverride = thinkingOverridesByFlatIndex?.[flatStepIndex];
|
|
1130
|
+
flatStepIndex++;
|
|
1131
|
+
return {
|
|
1132
|
+
index,
|
|
1133
|
+
...(sessionFile ? { sessionFile } : {}),
|
|
1134
|
+
...(thinkingOverride ? { thinkingOverride } : {}),
|
|
1135
|
+
};
|
|
1136
|
+
};
|
|
1137
|
+
try {
|
|
1138
|
+
const builtSteps = chain.map((s, stepIndex) => {
|
|
1139
|
+
if (isParallelStep(s)) {
|
|
1140
|
+
const parallelBehaviors = s.parallel.map((task) => {
|
|
1141
|
+
const agent = agents.find((candidate) => candidate.name === task.agent);
|
|
1142
|
+
return suppressProgressForReadOnlyTask(resolveStepBehavior(agent, buildStepOverrides(task), chainSkills), task.task, originalTask);
|
|
1143
|
+
});
|
|
1144
|
+
const progressPrecreated = parallelBehaviors.some((behavior) => behavior.progress);
|
|
1145
|
+
if (progressPrecreated) {
|
|
1146
|
+
if (!s.worktree || params.progressDir)
|
|
1147
|
+
writeInitialProgressFile(progressDir);
|
|
1148
|
+
progressInstructionCreated = true;
|
|
1149
|
+
}
|
|
1150
|
+
return {
|
|
1151
|
+
parallel: s.parallel.map((t, taskIndex) => {
|
|
1152
|
+
let behaviorCwd;
|
|
1153
|
+
if (s.worktree && managedWorktreeProvider === "worktrunk") {
|
|
1154
|
+
behaviorCwd = WORKTREE_AGENT_CWD_PLACEHOLDER;
|
|
1155
|
+
}
|
|
1156
|
+
else if (s.worktree && managedWorktreeProvider === "native") {
|
|
1157
|
+
try {
|
|
1158
|
+
behaviorCwd = resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s${stepIndex}`, taskIndex, worktreeBaseDir);
|
|
1159
|
+
}
|
|
1160
|
+
catch {
|
|
1161
|
+
behaviorCwd = undefined;
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
const staticStep = nextFlatStep();
|
|
1165
|
+
return buildSeqStep({ ...t, machine: t.machine ?? s.machine, worktree: s.worktree, agentContract: t.agentContract ?? s.agentContract, gateOn: t.gateOn ?? s.gateOn }, staticStep.sessionFile, behaviorCwd, progressPrecreated, parallelBehaviors[taskIndex], staticStep.index, { stepIndex, taskIndex }, resultMode === "parallel" ? `tasks[${taskIndex}]` : `chain[${stepIndex}].parallel[${taskIndex}]`);
|
|
1166
|
+
}),
|
|
1167
|
+
concurrency: s.concurrency,
|
|
1168
|
+
failFast: s.failFast,
|
|
1169
|
+
worktree: s.worktree,
|
|
1170
|
+
};
|
|
1171
|
+
}
|
|
1172
|
+
if (isDynamicParallelStep(s)) {
|
|
1173
|
+
const agent = agents.find((candidate) => candidate.name === s.parallel.agent);
|
|
1174
|
+
const behavior = suppressProgressForReadOnlyTask(resolveStepBehavior(agent, buildStepOverrides(s.parallel), chainSkills), s.parallel.task, originalTask);
|
|
1175
|
+
const progressPrecreated = behavior.progress;
|
|
1176
|
+
if (progressPrecreated) {
|
|
1177
|
+
writeInitialProgressFile(progressDir);
|
|
1178
|
+
progressInstructionCreated = true;
|
|
1179
|
+
}
|
|
1180
|
+
const maxItems = s.expand.maxItems ?? params.dynamicFanoutMaxItems ?? 0;
|
|
1181
|
+
const dynamicFlatSteps = Array.from({ length: maxItems }, () => nextFlatStep());
|
|
1182
|
+
const parallel = buildSeqStep({ ...s.parallel, agentContract: s.parallel.agentContract ?? s.agentContract, gateOn: s.parallel.gateOn ?? s.gateOn }, undefined, undefined, progressPrecreated, behavior, undefined, { stepIndex });
|
|
1183
|
+
return {
|
|
1184
|
+
expand: s.expand,
|
|
1185
|
+
parallel,
|
|
1186
|
+
collect: s.collect,
|
|
1187
|
+
concurrency: s.concurrency,
|
|
1188
|
+
failFast: s.failFast,
|
|
1189
|
+
phase: s.phase,
|
|
1190
|
+
label: s.label,
|
|
1191
|
+
sessionFiles: dynamicFlatSteps.map((step) => step.sessionFile),
|
|
1192
|
+
thinkingOverrides: dynamicFlatSteps.map((step) => step.thinkingOverride),
|
|
1193
|
+
effectiveAcceptance: resolveEffectiveAcceptance({
|
|
1194
|
+
explicit: s.acceptance,
|
|
1195
|
+
agentName: s.parallel.agent,
|
|
1196
|
+
acceptanceRole: agent.acceptanceRole,
|
|
1197
|
+
task: parallel.task,
|
|
1198
|
+
mode: resultMode,
|
|
1199
|
+
async: true,
|
|
1200
|
+
dynamicGroup: true,
|
|
1201
|
+
agentContract: s.agentContract ?? params.agentContract,
|
|
1202
|
+
}),
|
|
1203
|
+
acceptanceInput: s.acceptance,
|
|
1204
|
+
acceptanceRole: agent.acceptanceRole,
|
|
1205
|
+
...(s.agentContract ?? params.agentContract ? { agentContract: s.agentContract ?? params.agentContract } : {}),
|
|
1206
|
+
...(s.gateOn ? { gateOn: s.gateOn } : {}),
|
|
1207
|
+
...(parallel.thinkingCeiling ? { thinkingCeiling: parallel.thinkingCeiling } : {}),
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
const sequential = s;
|
|
1211
|
+
let behaviorCwd;
|
|
1212
|
+
if (sequential.worktree && managedWorktreeProvider === "worktrunk") {
|
|
1213
|
+
behaviorCwd = WORKTREE_AGENT_CWD_PLACEHOLDER;
|
|
1214
|
+
}
|
|
1215
|
+
else if (sequential.worktree && managedWorktreeProvider === "native") {
|
|
1216
|
+
try {
|
|
1217
|
+
behaviorCwd = resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s${stepIndex}`, 0, worktreeBaseDir);
|
|
1218
|
+
}
|
|
1219
|
+
catch {
|
|
1220
|
+
behaviorCwd = undefined;
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
const staticStep = nextFlatStep();
|
|
1224
|
+
return buildSeqStep(sequential, staticStep.sessionFile, behaviorCwd, false, undefined, staticStep.index, undefined, `chain[${stepIndex}]`);
|
|
1225
|
+
});
|
|
1226
|
+
const steps = params.attachRoot
|
|
1227
|
+
? [{
|
|
1228
|
+
parentSessionId: launchParentSessionId,
|
|
1229
|
+
...(ctx.parentSessionFile ? { parentSessionFile: ctx.parentSessionFile } : {}),
|
|
1230
|
+
agent: params.attachRoot.agent,
|
|
1231
|
+
task: "",
|
|
1232
|
+
label: params.attachRoot.label ?? `Attached root ${params.attachRoot.runId}`,
|
|
1233
|
+
outputName: params.attachRoot.outputName,
|
|
1234
|
+
importAsyncRoot: {
|
|
1235
|
+
runId: params.attachRoot.runId,
|
|
1236
|
+
asyncDir: params.attachRoot.asyncDir,
|
|
1237
|
+
resultPath: params.attachRoot.resultPath,
|
|
1238
|
+
index: params.attachRoot.index,
|
|
1239
|
+
},
|
|
1240
|
+
inheritProjectContext: false,
|
|
1241
|
+
inheritGlobalContext: false,
|
|
1242
|
+
inheritSkills: false,
|
|
1243
|
+
}, ...builtSteps]
|
|
1244
|
+
: builtSteps;
|
|
1245
|
+
for (const step of steps) {
|
|
1246
|
+
if (!("parallel" in step) || !Array.isArray(step.parallel))
|
|
1247
|
+
continue;
|
|
1248
|
+
const seen = new Map();
|
|
1249
|
+
for (let index = 0; index < step.parallel.length; index++) {
|
|
1250
|
+
const task = step.parallel[index];
|
|
1251
|
+
if (!task.outputPath)
|
|
1252
|
+
continue;
|
|
1253
|
+
const previous = seen.get(task.outputPath);
|
|
1254
|
+
if (previous) {
|
|
1255
|
+
throw new AsyncStartValidationError(`Parallel tasks ${previous.index + 1} (${previous.agent}) and ${index + 1} (${task.agent}) resolve output to the same path: ${task.outputPath}. Use distinct output paths.`);
|
|
1256
|
+
}
|
|
1257
|
+
seen.set(task.outputPath, { index, agent: task.agent });
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
return { steps: steps, runnerCwd, workflowGraph, eventChain: graphChain, ...(originalTask !== undefined ? { originalTask } : {}), ...(launcher !== undefined ? { launcher } : {}) };
|
|
1261
|
+
}
|
|
1262
|
+
catch (error) {
|
|
1263
|
+
if (error instanceof UnavailableSubagentSkillError || error instanceof AsyncStartValidationError)
|
|
1264
|
+
return { error: error.message };
|
|
1265
|
+
throw error;
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
/**
|
|
1269
|
+
* Execute a chain asynchronously
|
|
1270
|
+
*/
|
|
1271
|
+
export function executeAsyncChain(id, params) {
|
|
1272
|
+
const { chain, agents, ctx, cwd, maxOutput, artifactsDir, artifactConfig, shareEnabled, sessionRoot, sessionFilesByFlatIndex, thinkingOverridesByFlatIndex, maxSubagentDepth, worktreeSetupHook, worktreeSetupHookTimeoutMs, worktreeBaseDir, baseRef, worktreeProvider, worktreeBranchPrefix, controlConfig, controlIntercomTarget, childIntercomTarget, nestedRoute, } = params;
|
|
1273
|
+
const resultMode = params.resultMode ?? "chain";
|
|
1274
|
+
const acceptanceErrors = validateExecutionAcceptance({
|
|
1275
|
+
chain: projectChainOutputSchemas(chain, agents, (step, outputSchema) => ({ acceptance: step.acceptance, outputSchema }), (step, parallel) => Array.isArray(step.parallel) ? { parallel } : { acceptance: "acceptance" in step ? step.acceptance : undefined, parallel }),
|
|
1276
|
+
});
|
|
1277
|
+
if (acceptanceErrors.length > 0)
|
|
1278
|
+
return formatAsyncStartError(resultMode, acceptanceErrors.join(" "));
|
|
1279
|
+
// Refuse an undefined launcher before the run directory exists and before step building can write progress files.
|
|
1280
|
+
const undefinedLauncher = chain.flatMap(getStepAgents).map((name) => agents.find((agent) => agent.name === name)?.launcher)
|
|
1281
|
+
.find((name) => name !== undefined && !lookupRunnerLauncher(ctx.runnerLaunchers, name));
|
|
1282
|
+
if (undefinedLauncher !== undefined)
|
|
1283
|
+
return formatAsyncStartError(resultMode, `Launcher '${undefinedLauncher}' used by this ${resultMode} is not defined in runnerLaunchers in the user subagent config.`);
|
|
1284
|
+
const launchParentSessionId = ctx.parentSessionId ?? ctx.currentSessionId;
|
|
1285
|
+
const capabilityCeiling = params.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(launchParentSessionId);
|
|
1286
|
+
const inheritedNestedRoute = inheritedNestedRouteOf(ctx.childRuntime);
|
|
1287
|
+
const nestedAddress = inheritedNestedRoute ? inheritedNestedParentAddressOf(ctx.childRuntime) : undefined;
|
|
1288
|
+
const asyncDir = inheritedNestedRoute
|
|
1289
|
+
? path.join(TEMP_ROOT_DIR, "nested-subagent-runs", inheritedNestedRoute.rootRunId, id)
|
|
1290
|
+
: path.join(DIRS.async, id);
|
|
1291
|
+
let runFanoutBudget;
|
|
1292
|
+
try {
|
|
1293
|
+
runFanoutBudget = params.runFanoutBudget ?? createRunFanoutBudget(id, 64);
|
|
1294
|
+
fs.mkdirSync(asyncDir, { recursive: true });
|
|
1295
|
+
writeRunFanoutBudgetDescriptor(asyncDir, runFanoutBudget);
|
|
1296
|
+
}
|
|
1297
|
+
catch (error) {
|
|
1298
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1299
|
+
return {
|
|
1300
|
+
content: [{ type: "text", text: `Failed to create async run directory '${asyncDir}': ${message}` }],
|
|
1301
|
+
isError: true,
|
|
1302
|
+
details: { mode: resultMode, results: [] },
|
|
1303
|
+
};
|
|
1304
|
+
}
|
|
1305
|
+
const built = buildAsyncRunnerSteps(id, {
|
|
1306
|
+
chain,
|
|
1307
|
+
task: params.task,
|
|
1308
|
+
attachRoot: params.attachRoot,
|
|
1309
|
+
resultMode,
|
|
1310
|
+
agents,
|
|
1311
|
+
unknownAgentDiagnosticContext: params.unknownAgentDiagnosticContext,
|
|
1312
|
+
ctx,
|
|
1313
|
+
availableModels: params.availableModels,
|
|
1314
|
+
cwd,
|
|
1315
|
+
chainSkills: params.chainSkills,
|
|
1316
|
+
machine: params.machine,
|
|
1317
|
+
machineCwd: params.machineCwd,
|
|
1318
|
+
sessionFilesByFlatIndex,
|
|
1319
|
+
thinkingOverridesByFlatIndex,
|
|
1320
|
+
contextForAgent: params.contextForAgent,
|
|
1321
|
+
progressDir: params.progressDir ?? (artifactsDir ? path.join(artifactsDir, "progress", id) : resultMode === "parallel" ? path.join(asyncDir, "progress") : undefined),
|
|
1322
|
+
agentContract: params.agentContract,
|
|
1323
|
+
outputBaseDir: artifactsDir ? path.join(artifactsDir, "outputs", id) : undefined,
|
|
1324
|
+
dynamicFanoutMaxItems: params.dynamicFanoutMaxItems,
|
|
1325
|
+
maxSubagentDepth,
|
|
1326
|
+
waitToolEnabled: params.waitToolEnabled,
|
|
1327
|
+
waitToolDefaultTimeoutMs: params.waitToolDefaultTimeoutMs,
|
|
1328
|
+
worktreeBaseDir,
|
|
1329
|
+
worktreeProvider,
|
|
1330
|
+
worktreeBranchPrefix,
|
|
1331
|
+
asyncDir,
|
|
1332
|
+
fast: params.fast,
|
|
1333
|
+
toolBudget: params.toolBudget,
|
|
1334
|
+
configToolBudget: params.configToolBudget,
|
|
1335
|
+
callToolTimeoutMs: params.callToolTimeoutMs,
|
|
1336
|
+
configToolTimeoutMs: params.configToolTimeoutMs,
|
|
1337
|
+
toolTimeoutMsEnv: params.toolTimeoutMsEnv ?? toolTimeoutFromEnv(),
|
|
1338
|
+
capabilityCeiling,
|
|
1339
|
+
thinkingCeiling: params.thinkingCeiling,
|
|
1340
|
+
requiredExtensions: params.requiredExtensions,
|
|
1341
|
+
});
|
|
1342
|
+
if ("error" in built) {
|
|
1343
|
+
try {
|
|
1344
|
+
fs.rmSync(asyncDir, { recursive: true, force: true });
|
|
1345
|
+
}
|
|
1346
|
+
catch {
|
|
1347
|
+
// Best-effort cleanup for validation failures before the runner is spawned.
|
|
1348
|
+
}
|
|
1349
|
+
return formatAsyncStartError(resultMode, built.error);
|
|
1350
|
+
}
|
|
1351
|
+
const { steps, runnerCwd, workflowGraph, eventChain } = built;
|
|
1352
|
+
const launcher = built.launcher === undefined ? undefined : lookupRunnerLauncher(ctx.runnerLaunchers, built.launcher);
|
|
1353
|
+
const deadlineAt = params.timeoutMs !== undefined ? Date.now() + params.timeoutMs : undefined;
|
|
1354
|
+
const initialUsageBudget = usageBudgetState(params.usageBudget, undefined);
|
|
1355
|
+
let childTargetIndex = 0;
|
|
1356
|
+
const childIntercomTargets = childIntercomTarget ? steps.flatMap((step) => {
|
|
1357
|
+
if (!("parallel" in step) && "importAsyncRoot" in step && step.importAsyncRoot) {
|
|
1358
|
+
childTargetIndex++;
|
|
1359
|
+
return [undefined];
|
|
1360
|
+
}
|
|
1361
|
+
if ("parallel" in step) {
|
|
1362
|
+
if (!Array.isArray(step.parallel)) {
|
|
1363
|
+
childTargetIndex++;
|
|
1364
|
+
return [undefined];
|
|
1365
|
+
}
|
|
1366
|
+
return step.parallel.map((task) => childIntercomTarget(task.agent, childTargetIndex++));
|
|
1367
|
+
}
|
|
1368
|
+
return "agent" in step ? [childIntercomTarget(step.agent, childTargetIndex++)] : [undefined];
|
|
1369
|
+
}) : undefined;
|
|
1370
|
+
const initialStatusSteps = eventChain.flatMap((step) => isParallelStep(step)
|
|
1371
|
+
? step.parallel.map((task) => ({ agent: task.agent, ...(statusStepDescription(task.task) ? { description: statusStepDescription(task.task) } : {}), ...(task.label ? { label: task.label } : {}), ...(task.as ? { outputName: task.as } : {}), status: "pending" }))
|
|
1372
|
+
: isDynamicParallelStep(step)
|
|
1373
|
+
? [{ agent: `expand:${step.parallel.agent}`, label: step.label ?? step.parallel.label ?? `Dynamic fanout (${step.collect.as})`, outputName: step.collect.as, status: "pending" }]
|
|
1374
|
+
: [{ agent: step.agent, ...(statusStepDescription(step.task) ? { description: statusStepDescription(step.task) } : {}), ...(step.label ? { label: step.label } : {}), ...(step.as ? { outputName: step.as } : {}), status: "pending" }]);
|
|
1375
|
+
const initialParallelGroups = [];
|
|
1376
|
+
let initialFlatIndex = 0;
|
|
1377
|
+
for (let stepIndex = 0; stepIndex < eventChain.length; stepIndex++) {
|
|
1378
|
+
const step = eventChain[stepIndex];
|
|
1379
|
+
if (isParallelStep(step))
|
|
1380
|
+
initialParallelGroups.push({ start: initialFlatIndex, count: step.parallel.length, stepIndex });
|
|
1381
|
+
else if (isDynamicParallelStep(step))
|
|
1382
|
+
initialParallelGroups.push({ start: initialFlatIndex, count: 1, stepIndex });
|
|
1383
|
+
initialFlatIndex += isParallelStep(step) ? step.parallel.length : 1;
|
|
1384
|
+
}
|
|
1385
|
+
const initialStatusAt = Date.now();
|
|
1386
|
+
const initialCompletionOwnerId = ctx.completionOwnerId ?? currentCompletionOwnerId();
|
|
1387
|
+
const completionOwnerProcess = currentRecordedPid();
|
|
1388
|
+
try {
|
|
1389
|
+
writeRetainedRequiredChildExtensions(asyncDir, params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(launchParentSessionId ?? undefined));
|
|
1390
|
+
}
|
|
1391
|
+
catch (error) {
|
|
1392
|
+
fs.rmSync(asyncDir, { recursive: true, force: true });
|
|
1393
|
+
return formatAsyncStartError(resultMode, `Failed to record required child extensions: ${error instanceof Error ? error.message : String(error)}`);
|
|
1394
|
+
}
|
|
1395
|
+
let spawnResultOrPromise = {};
|
|
1396
|
+
try {
|
|
1397
|
+
spawnResultOrPromise = spawnRunner({
|
|
1398
|
+
id,
|
|
1399
|
+
steps,
|
|
1400
|
+
resultPath: inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) : resultFilePath(DIRS.results, id),
|
|
1401
|
+
cwd: runnerCwd,
|
|
1402
|
+
placeholder: "{previous}",
|
|
1403
|
+
maxOutput,
|
|
1404
|
+
artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
|
|
1405
|
+
artifactConfig,
|
|
1406
|
+
share: shareEnabled,
|
|
1407
|
+
sessionDir: sessionRoot ? path.join(sessionRoot, `async-${id}`) : undefined,
|
|
1408
|
+
asyncDir,
|
|
1409
|
+
sessionId: ctx.currentSessionId,
|
|
1410
|
+
completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
|
|
1411
|
+
completionOwnerProcess,
|
|
1412
|
+
...(capabilityCeiling ? { capabilityCeiling } : {}),
|
|
1413
|
+
piPackageRoot,
|
|
1414
|
+
childSessionFactoryModule: childSessionFactoryModule(),
|
|
1415
|
+
inheritedChildRuntime: inheritedChildRuntime(ctx.childRuntime),
|
|
1416
|
+
projectTrusted: ctx.projectTrusted,
|
|
1417
|
+
worktreeSetupHook,
|
|
1418
|
+
worktreeSetupHookTimeoutMs,
|
|
1419
|
+
worktreeBaseDir,
|
|
1420
|
+
baseRef,
|
|
1421
|
+
worktreeProvider,
|
|
1422
|
+
worktreeBranchPrefix,
|
|
1423
|
+
controlConfig,
|
|
1424
|
+
toolBudget: params.toolBudget,
|
|
1425
|
+
usageBudget: params.usageBudget,
|
|
1426
|
+
controlIntercomTarget,
|
|
1427
|
+
childIntercomTargets,
|
|
1428
|
+
resultMode,
|
|
1429
|
+
dynamicFanoutMaxItems: params.dynamicFanoutMaxItems,
|
|
1430
|
+
timeoutMs: params.timeoutMs,
|
|
1431
|
+
deadlineAt,
|
|
1432
|
+
globalConcurrencyLimit: params.globalConcurrencyLimit,
|
|
1433
|
+
runFanoutBudget,
|
|
1434
|
+
workflowGraph,
|
|
1435
|
+
...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
|
|
1436
|
+
...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
|
|
1437
|
+
nestedRoute: nestedRoute ?? inheritedNestedRoute,
|
|
1438
|
+
nestedSelf: inheritedNestedRoute && nestedAddress ? {
|
|
1439
|
+
parentRunId: nestedAddress.parentRunId,
|
|
1440
|
+
parentStepIndex: nestedAddress.parentStepIndex,
|
|
1441
|
+
depth: nestedAddress.depth,
|
|
1442
|
+
path: nestedAddress.path,
|
|
1443
|
+
} : undefined,
|
|
1444
|
+
...(launcher ? { launcher } : {}),
|
|
1445
|
+
}, id, runnerCwd, {
|
|
1446
|
+
lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
|
|
1447
|
+
runId: id,
|
|
1448
|
+
...(ctx.currentSessionId ? { sessionId: ctx.currentSessionId } : {}),
|
|
1449
|
+
...(initialCompletionOwnerId ? { completionOwnerId: initialCompletionOwnerId } : {}),
|
|
1450
|
+
completionOwnerProcess,
|
|
1451
|
+
mode: resultMode,
|
|
1452
|
+
state: "running",
|
|
1453
|
+
startedAt: initialStatusAt,
|
|
1454
|
+
lastUpdate: initialStatusAt,
|
|
1455
|
+
currentStep: 0,
|
|
1456
|
+
chainStepCount: eventChain.length,
|
|
1457
|
+
...(initialParallelGroups.length ? { parallelGroups: initialParallelGroups } : {}),
|
|
1458
|
+
...(launcher ? { launcher } : {}),
|
|
1459
|
+
steps: initialStatusSteps,
|
|
1460
|
+
}, path.join(asyncDir, "status.json"), launchParentSessionId, (proof) => emitProcessTerminalEvent(ctx, proof), (runnerProcessInstanceId) => params.activeAsyncCapacity?.markStarted(runnerProcessInstanceId));
|
|
1461
|
+
}
|
|
1462
|
+
catch (error) {
|
|
1463
|
+
params.activeAsyncCapacity?.rollback();
|
|
1464
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1465
|
+
return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': ${message}`);
|
|
1466
|
+
}
|
|
1467
|
+
// A launcher run's spawn resolves once the runner reports its identity.
|
|
1468
|
+
const finishSpawnResult = (spawnResult) => {
|
|
1469
|
+
if (spawnResult.error) {
|
|
1470
|
+
if (spawnResult.startupDidNotProceed) {
|
|
1471
|
+
if (!spawnResult.runnerProcessInstanceId || params.activeAsyncCapacity?.rollbackBeforeRunnerProceed(spawnResult.runnerProcessInstanceId) !== true)
|
|
1472
|
+
params.activeAsyncCapacity?.rollback();
|
|
1473
|
+
}
|
|
1474
|
+
else if (!spawnResult.pid || !spawnResult.runnerProcessInstanceId)
|
|
1475
|
+
params.activeAsyncCapacity?.rollback();
|
|
1476
|
+
else
|
|
1477
|
+
params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
|
|
1478
|
+
return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': ${spawnResult.error}`);
|
|
1479
|
+
}
|
|
1480
|
+
if (!spawnResult.pid || !spawnResult.runnerProcessInstanceId) {
|
|
1481
|
+
params.activeAsyncCapacity?.rollback();
|
|
1482
|
+
return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': runner identity unavailable`);
|
|
1483
|
+
}
|
|
1484
|
+
if (spawnResult.pid) {
|
|
1485
|
+
const eventFirstStep = eventChain[0];
|
|
1486
|
+
if (!eventFirstStep) {
|
|
1487
|
+
return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': event chain has no steps`);
|
|
1488
|
+
}
|
|
1489
|
+
const firstAgents = isParallelStep(eventFirstStep)
|
|
1490
|
+
? eventFirstStep.parallel.map((t) => t.agent)
|
|
1491
|
+
: isDynamicParallelStep(eventFirstStep)
|
|
1492
|
+
? [eventFirstStep.parallel.agent]
|
|
1493
|
+
: [eventFirstStep.agent];
|
|
1494
|
+
const firstTask = isParallelStep(eventFirstStep)
|
|
1495
|
+
? eventFirstStep.parallel[0]?.task
|
|
1496
|
+
: isDynamicParallelStep(eventFirstStep)
|
|
1497
|
+
? eventFirstStep.parallel.task
|
|
1498
|
+
: eventFirstStep.task;
|
|
1499
|
+
const workflowGoal = params.goal ?? (params.task?.trim() || firstTask);
|
|
1500
|
+
const parallelGroups = [];
|
|
1501
|
+
const flatAgents = [];
|
|
1502
|
+
let flatStepStart = 0;
|
|
1503
|
+
for (let stepIndex = 0; stepIndex < eventChain.length; stepIndex++) {
|
|
1504
|
+
const step = eventChain[stepIndex];
|
|
1505
|
+
if (isParallelStep(step)) {
|
|
1506
|
+
parallelGroups.push({ start: flatStepStart, count: step.parallel.length, stepIndex });
|
|
1507
|
+
flatAgents.push(...step.parallel.map((task) => task.agent));
|
|
1508
|
+
flatStepStart += step.parallel.length;
|
|
1509
|
+
}
|
|
1510
|
+
else if (isDynamicParallelStep(step)) {
|
|
1511
|
+
parallelGroups.push({ start: flatStepStart, count: 1, stepIndex });
|
|
1512
|
+
flatAgents.push(step.parallel.agent);
|
|
1513
|
+
flatStepStart++;
|
|
1514
|
+
}
|
|
1515
|
+
else {
|
|
1516
|
+
flatAgents.push(step.agent);
|
|
1517
|
+
flatStepStart++;
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
if (inheritedNestedRoute && nestedAddress) {
|
|
1521
|
+
const now = Date.now();
|
|
1522
|
+
try {
|
|
1523
|
+
writeNestedEvent(inheritedNestedRoute, {
|
|
1524
|
+
type: "subagent.nested.started",
|
|
1525
|
+
ts: now,
|
|
1526
|
+
parentRunId: nestedAddress.parentRunId,
|
|
1527
|
+
parentStepIndex: nestedAddress.parentStepIndex,
|
|
1528
|
+
child: {
|
|
1529
|
+
id,
|
|
1530
|
+
parentRunId: nestedAddress.parentRunId,
|
|
1531
|
+
parentStepIndex: nestedAddress.parentStepIndex,
|
|
1532
|
+
depth: nestedAddress.depth,
|
|
1533
|
+
path: nestedAddress.path,
|
|
1534
|
+
asyncDir,
|
|
1535
|
+
pid: spawnResult.pid,
|
|
1536
|
+
ownerIntercomTarget: ctx.childRuntime?.intercomSessionName,
|
|
1537
|
+
leafIntercomTarget: childIntercomTargets?.[0],
|
|
1538
|
+
intercomTarget: childIntercomTargets?.[0],
|
|
1539
|
+
ownerState: "live",
|
|
1540
|
+
mode: resultMode,
|
|
1541
|
+
state: "running",
|
|
1542
|
+
agent: firstAgents[0],
|
|
1543
|
+
agents: flatAgents,
|
|
1544
|
+
chainStepCount: eventChain.length,
|
|
1545
|
+
parallelGroups,
|
|
1546
|
+
...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}),
|
|
1547
|
+
startedAt: now,
|
|
1548
|
+
lastUpdate: now,
|
|
1549
|
+
...(capabilityCeiling ? { capabilityCeiling } : {}),
|
|
1550
|
+
},
|
|
1551
|
+
});
|
|
1552
|
+
}
|
|
1553
|
+
catch (error) {
|
|
1554
|
+
console.error("Failed to emit nested async start event:", error);
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
ctx.pi.events.emit(SUBAGENT_ASYNC_STARTED_EVENT, {
|
|
1558
|
+
lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
|
|
1559
|
+
id,
|
|
1560
|
+
pid: spawnResult.pid,
|
|
1561
|
+
sessionId: ctx.currentSessionId,
|
|
1562
|
+
completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
|
|
1563
|
+
mode: resultMode,
|
|
1564
|
+
agent: firstAgents[0],
|
|
1565
|
+
agents: flatAgents,
|
|
1566
|
+
task: firstTask?.trim() ? PROMPT_REDACTED : undefined,
|
|
1567
|
+
goal: workflowGoal?.trim() ? PROMPT_REDACTED : undefined,
|
|
1568
|
+
chain: eventChain.map((s) => isParallelStep(s) ? `[${s.parallel.map((t) => t.agent).join("+")}]` : isDynamicParallelStep(s) ? `expand:${s.parallel.agent}` : s.agent),
|
|
1569
|
+
chainStepCount: eventChain.length,
|
|
1570
|
+
parallelGroups,
|
|
1571
|
+
workflowGraph,
|
|
1572
|
+
cwd: runnerCwd,
|
|
1573
|
+
asyncDir,
|
|
1574
|
+
...(sessionRoot ? { sessionRoot } : {}),
|
|
1575
|
+
...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}),
|
|
1576
|
+
...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}),
|
|
1577
|
+
...(capabilityCeiling ? { capabilityCeiling } : {}),
|
|
1578
|
+
...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
|
|
1579
|
+
...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
|
|
1580
|
+
nestedRoute,
|
|
1581
|
+
});
|
|
1582
|
+
}
|
|
1583
|
+
const chainDesc = chain
|
|
1584
|
+
.map((s) => isParallelStep(s) ? `[${s.parallel.map((t) => t.agent).join("+")}]` : isDynamicParallelStep(s) ? `expand:${s.parallel.agent}` : s.agent)
|
|
1585
|
+
.join(" -> ");
|
|
1586
|
+
return {
|
|
1587
|
+
content: [{ type: "text", text: formatAsyncStartedMessage(`Async ${resultMode}: ${chainDesc} [${id}]`, ctx.interactive === true) }],
|
|
1588
|
+
details: { mode: resultMode, runId: id, results: [], asyncId: id, asyncDir, workflowGraph, ...(capabilityCeiling ? { capabilityCeiling } : {}), ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}), ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}), ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}), ...(params.toolBudget ? { toolBudget: params.toolBudget } : {}), ...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}) },
|
|
1589
|
+
};
|
|
1590
|
+
};
|
|
1591
|
+
return spawnResultOrPromise instanceof Promise ? spawnResultOrPromise.then(finishSpawnResult) : finishSpawnResult(spawnResultOrPromise);
|
|
1592
|
+
}
|
|
1593
|
+
/**
|
|
1594
|
+
* Execute a single agent asynchronously
|
|
1595
|
+
*/
|
|
1596
|
+
export function workflowAwaitedAsyncResultPath(asyncDir) {
|
|
1597
|
+
return path.join(asyncDir, "workflow-result.json");
|
|
1598
|
+
}
|
|
1599
|
+
export function executeAsyncSingle(id, params) {
|
|
1600
|
+
const { agent, agentConfig, ctx, cwd, maxOutput, artifactsDir, artifactConfig, shareEnabled, sessionRoot, sessionFile, maxSubagentDepth, worktreeSetupHook, worktreeSetupHookTimeoutMs, worktreeBaseDir, baseRef, worktreeProvider, worktreeBranchPrefix, controlConfig, controlIntercomTarget, childIntercomTarget, nestedRoute, } = params;
|
|
1601
|
+
let lane;
|
|
1602
|
+
try {
|
|
1603
|
+
lane = normalizeWorkflowLaneMetadata(params.lane, "lane");
|
|
1604
|
+
assertWorkflowLaneKey(lane, params.workflowKey, "lane");
|
|
1605
|
+
}
|
|
1606
|
+
catch (error) {
|
|
1607
|
+
return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
|
|
1608
|
+
}
|
|
1609
|
+
const task = params.task ?? "";
|
|
1610
|
+
let extensionBindings;
|
|
1611
|
+
try {
|
|
1612
|
+
extensionBindings = normalizeExtensionBindings(params.extensionBindings)?.value;
|
|
1613
|
+
}
|
|
1614
|
+
catch (error) {
|
|
1615
|
+
return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
|
|
1616
|
+
}
|
|
1617
|
+
const acceptanceErrors = validateAcceptanceInput(params.acceptance);
|
|
1618
|
+
if (acceptanceErrors.length > 0)
|
|
1619
|
+
return formatAsyncStartError("single", acceptanceErrors.join(" "));
|
|
1620
|
+
const externalRunner = agentConfig.runner?.type === "external-cli" || agentConfig.runner?.type === "external-job";
|
|
1621
|
+
const externalRunnerType = agentConfig.runner?.type;
|
|
1622
|
+
const permissionRules = resolvePermissionRules(ctx.permissions, agentConfig.permissions);
|
|
1623
|
+
const sandbox = params.sandbox ?? agentConfig.sandbox;
|
|
1624
|
+
// See the chain path: the Claude Code adapter accepts an explicit model/thinking
|
|
1625
|
+
// request even though no other external runner does.
|
|
1626
|
+
const claudeCodeAdapter = agentConfig.runner?.type === "external-cli" && isClaudeCodeAdapterId(agentConfig.runner.adapter);
|
|
1627
|
+
if (externalRunner) {
|
|
1628
|
+
const unsupported = [];
|
|
1629
|
+
if (params.modelOverride !== undefined && !claudeCodeAdapter)
|
|
1630
|
+
unsupported.push("model override");
|
|
1631
|
+
if ((params.fast ?? agentConfig.fast) === true)
|
|
1632
|
+
unsupported.push("fast mode");
|
|
1633
|
+
if (params.thinkingOverride !== undefined && !claudeCodeAdapter)
|
|
1634
|
+
unsupported.push("thinking override");
|
|
1635
|
+
if (params.structuredOutputSchema !== undefined)
|
|
1636
|
+
unsupported.push("structured output");
|
|
1637
|
+
if (params.acceptance !== undefined || params.agentContract !== undefined)
|
|
1638
|
+
unsupported.push("acceptance/agent contract");
|
|
1639
|
+
if (params.toolBudget !== undefined || agentConfig.toolBudget !== undefined || params.configToolBudget !== undefined)
|
|
1640
|
+
unsupported.push("tool budget");
|
|
1641
|
+
if (sandbox !== undefined)
|
|
1642
|
+
unsupported.push("sandbox profile");
|
|
1643
|
+
if (params.context === "fork")
|
|
1644
|
+
unsupported.push("fork context");
|
|
1645
|
+
if ((params.skills?.length ?? 0) > 0)
|
|
1646
|
+
unsupported.push("skills");
|
|
1647
|
+
if (permissionRules)
|
|
1648
|
+
unsupported.push("native Pi child permissions");
|
|
1649
|
+
if (extensionBindings !== undefined)
|
|
1650
|
+
unsupported.push("extension bindings");
|
|
1651
|
+
if (unsupported.length > 0)
|
|
1652
|
+
return formatAsyncStartError("single", `Agent '${agentConfig.name}' uses runner.type='${externalRunnerType}' and does not support: ${unsupported.join(", ")}.`);
|
|
1653
|
+
}
|
|
1654
|
+
const capabilityCeiling = intersectSubagentCapabilityCeilings(params.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(ctx.parentSessionId ?? ctx.currentSessionId), ctx.childRuntime?.capabilityCeiling);
|
|
1655
|
+
try {
|
|
1656
|
+
assertAgentAllowedByCapabilityCeiling(agentConfig.name, capabilityCeiling);
|
|
1657
|
+
}
|
|
1658
|
+
catch (error) {
|
|
1659
|
+
return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
|
|
1660
|
+
}
|
|
1661
|
+
const runnerCwd = resolveChildCwd(ctx.cwd, cwd);
|
|
1662
|
+
const requestedMachine = params.machine ?? agentConfig.machine;
|
|
1663
|
+
const machineUnsupported = formatHerdrMachineRunnerUnsupported({ machine: requestedMachine, agentName: agentConfig.name, runnerType: agentConfig.runner?.type, adapter: agentConfig.runner?.type === "external-cli" ? agentConfig.runner.adapter : undefined, worktree: params.worktree });
|
|
1664
|
+
if (machineUnsupported)
|
|
1665
|
+
return formatAsyncStartError("single", machineUnsupported);
|
|
1666
|
+
// Refuse before the runner starts; the placed launch would refuse only after the run exists.
|
|
1667
|
+
if (requestedMachine && params.revivalLease)
|
|
1668
|
+
return formatAsyncStartError("single", PLACED_RESTORE_UNSUPPORTED);
|
|
1669
|
+
const resolvedLauncher = resolveAgentRunnerLauncher(agentConfig, ctx.runnerLaunchers, requestedMachine);
|
|
1670
|
+
if (resolvedLauncher.error)
|
|
1671
|
+
return formatAsyncStartError("single", resolvedLauncher.error);
|
|
1672
|
+
const launcher = resolvedLauncher.launcher;
|
|
1673
|
+
const registeredExtensions = resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
|
|
1674
|
+
try {
|
|
1675
|
+
assertRequiredChildExtensionsAdmitted([params.requiredExtensions, ctx.childRuntime?.requiredExtensions, registeredExtensions], { agent: agentConfig.name, runnerType: agentConfig.runner?.type, machine: requestedMachine });
|
|
1676
|
+
}
|
|
1677
|
+
catch (error) {
|
|
1678
|
+
return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
|
|
1679
|
+
}
|
|
1680
|
+
let machine;
|
|
1681
|
+
let machineEnv;
|
|
1682
|
+
if (requestedMachine) {
|
|
1683
|
+
try {
|
|
1684
|
+
const placement = resolveMachinePlacement({ machine: requestedMachine, cwd: runnerCwd, stepCwd: params.machineCwd });
|
|
1685
|
+
machine = placement.machine;
|
|
1686
|
+
machineEnv = placement.env;
|
|
1687
|
+
}
|
|
1688
|
+
catch (error) {
|
|
1689
|
+
return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
let managedWorktreeProvider;
|
|
1693
|
+
if (params.worktree === true) {
|
|
1694
|
+
try {
|
|
1695
|
+
const resolved = resolveWorktreeProvider(params.worktreeProvider, worktreeBaseDir);
|
|
1696
|
+
managedWorktreeProvider = shouldDeferWorktreeCwd(params.worktreeProvider, worktreeBaseDir) ? "worktrunk" : resolved;
|
|
1697
|
+
}
|
|
1698
|
+
catch (error) {
|
|
1699
|
+
return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
const instructionCwd = params.worktree === true && managedWorktreeProvider === "worktrunk"
|
|
1703
|
+
? WORKTREE_AGENT_CWD_PLACEHOLDER
|
|
1704
|
+
: params.worktree === true && managedWorktreeProvider === "native"
|
|
1705
|
+
? resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s0`, 0, worktreeBaseDir)
|
|
1706
|
+
: machine?.cwd ?? runnerCwd;
|
|
1707
|
+
if (sandbox && (agentConfig.source === "project" || agentConfig.override?.scope === "project") && !profileProjectTrustedForCwd(ctx, instructionCwd)) {
|
|
1708
|
+
return formatAsyncStartError("single", profileProjectTrustError(agentConfig, ctx));
|
|
1709
|
+
}
|
|
1710
|
+
const readExistenceCwd = params.worktree === true ? runnerCwd : instructionCwd;
|
|
1711
|
+
const skillNames = params.skills ?? agentConfig.skills ?? [];
|
|
1712
|
+
const availableModels = params.availableModels;
|
|
1713
|
+
const { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(skillNames, runnerCwd, ctx.cwd, agentConfig.skillPath, agentConfig.filePath ? path.dirname(agentConfig.filePath) : runnerCwd);
|
|
1714
|
+
if (missingSkills.includes("pi-subagents"))
|
|
1715
|
+
return formatAsyncStartError("single", UNAVAILABLE_SUBAGENT_SKILL_ERROR);
|
|
1716
|
+
const inheritedNestedRoute = inheritedNestedRouteOf(ctx.childRuntime);
|
|
1717
|
+
const nestedAddress = inheritedNestedRoute ? inheritedNestedParentAddressOf(ctx.childRuntime) : undefined;
|
|
1718
|
+
const asyncDir = inheritedNestedRoute
|
|
1719
|
+
? path.join(TEMP_ROOT_DIR, "nested-subagent-runs", inheritedNestedRoute.rootRunId, id)
|
|
1720
|
+
: path.join(DIRS.async, id);
|
|
1721
|
+
let runFanoutBudget;
|
|
1722
|
+
try {
|
|
1723
|
+
runFanoutBudget = params.runFanoutBudget ?? createRunFanoutBudget(id, 64);
|
|
1724
|
+
fs.mkdirSync(asyncDir, { recursive: true });
|
|
1725
|
+
writeRunFanoutBudgetDescriptor(asyncDir, runFanoutBudget);
|
|
1726
|
+
}
|
|
1727
|
+
catch (error) {
|
|
1728
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1729
|
+
return {
|
|
1730
|
+
content: [{ type: "text", text: `Failed to create async run directory '${asyncDir}': ${message}` }],
|
|
1731
|
+
isError: true,
|
|
1732
|
+
details: { mode: "single", results: [] },
|
|
1733
|
+
};
|
|
1734
|
+
}
|
|
1735
|
+
const effectiveOutput = normalizeSingleOutputOverride(params.output, agentConfig.output);
|
|
1736
|
+
const outputPath = resolveSingleOutputPath(effectiveOutput, ctx.cwd, instructionCwd, params.outputBaseDir ?? (artifactsDir ? path.join(artifactsDir, "outputs", id) : undefined));
|
|
1737
|
+
const systemPrompt = buildEffectiveSystemPrompt({ agent: agentConfig, resolvedSkills, cwd: runnerCwd });
|
|
1738
|
+
const outputMode = params.outputMode ?? agentConfig.outputMode ?? "inline";
|
|
1739
|
+
const validationError = validateFileOnlyOutputMode(outputMode, outputPath, `Async single run (${agent})`);
|
|
1740
|
+
if (validationError)
|
|
1741
|
+
return formatAsyncStartError("single", validationError);
|
|
1742
|
+
const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, agentConfig);
|
|
1743
|
+
// Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
|
|
1744
|
+
// absolute paths pass through; relative paths resolve against the child cwd.
|
|
1745
|
+
const reads = params.reads !== undefined ? params.reads : agentConfig.defaultReads ?? false;
|
|
1746
|
+
const readPaths = Array.isArray(reads)
|
|
1747
|
+
? machine
|
|
1748
|
+
? externalRunner
|
|
1749
|
+
? reads.map((read) => read === "~" || read.startsWith("~/") || path.posix.isAbsolute(read) ? read : path.posix.resolve(instructionCwd, read))
|
|
1750
|
+
: []
|
|
1751
|
+
: managedWorktreeProvider === "worktrunk"
|
|
1752
|
+
? resolveExistingReadInstructionPaths(reads, instructionCwd, readExistenceCwd)
|
|
1753
|
+
: resolveExistingReadPaths(reads, readExistenceCwd)
|
|
1754
|
+
: [];
|
|
1755
|
+
const readsInstruction = readPaths.length > 0
|
|
1756
|
+
? `[Read from: ${readPaths.join(", ")}]\n\n`
|
|
1757
|
+
: "";
|
|
1758
|
+
const taskText = readsInstruction + taskWithOutputInstruction;
|
|
1759
|
+
const modelScopes = resolveModelScopesForAgent(ctx.modelScope, agentConfig.name, ctx.currentModel, ctx.scopedModelIds);
|
|
1760
|
+
const modelOrigin = resolveModelOrigin({
|
|
1761
|
+
fromParent: params.modelOverrideFromParent,
|
|
1762
|
+
storedOrigin: params.modelOrigin,
|
|
1763
|
+
explicitModel: params.modelOverrideFromParent ? undefined : params.modelOverride,
|
|
1764
|
+
agentModel: agentConfig.model,
|
|
1765
|
+
parentModel: ctx.currentModel,
|
|
1766
|
+
});
|
|
1767
|
+
let primaryModel;
|
|
1768
|
+
try {
|
|
1769
|
+
primaryModel = externalRunner ? undefined : modelOrigin === "inherited"
|
|
1770
|
+
? params.modelOverride ?? (ctx.currentModel ? `${ctx.currentModel.provider}/${ctx.currentModel.id}` : undefined)
|
|
1771
|
+
: resolveSubagentModelOverride(params.modelOverride ?? agentConfig.model, ctx.currentModel, availableModels, ctx.currentModelProvider, { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" });
|
|
1772
|
+
}
|
|
1773
|
+
catch (error) {
|
|
1774
|
+
return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
|
|
1775
|
+
}
|
|
1776
|
+
let singleClaudeCodeOverride;
|
|
1777
|
+
if (claudeCodeAdapter) {
|
|
1778
|
+
try {
|
|
1779
|
+
singleClaudeCodeOverride = resolveClaudeCodeOverride({
|
|
1780
|
+
model: typeof params.modelOverride === "string" ? params.modelOverride : undefined,
|
|
1781
|
+
agent: agentConfig,
|
|
1782
|
+
thinking: resolveClaudeCodeThinking(params.thinkingOverride, agentConfig.thinking),
|
|
1783
|
+
thinkingCeiling: intersectThinkingCeilings(params.thinkingCeiling, agentConfig.maxThinking, ctx.childRuntime?.thinkingCeiling),
|
|
1784
|
+
agentName: agentConfig.name,
|
|
1785
|
+
runId: id,
|
|
1786
|
+
});
|
|
1787
|
+
assertClaudeCodeModelScope({ scopes: modelScopes, model: singleClaudeCodeOverride?.model, agent: agentConfig.name, runId: id });
|
|
1788
|
+
assertClaudeCodeOverrideIsLocal(agentConfig.name, machine ? requestedMachine : undefined, singleClaudeCodeOverride);
|
|
1789
|
+
}
|
|
1790
|
+
catch (error) {
|
|
1791
|
+
return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
|
|
1792
|
+
}
|
|
1793
|
+
}
|
|
1794
|
+
const effectiveThinking = externalRunner ? undefined : params.thinkingOverride ?? agentConfig.thinking;
|
|
1795
|
+
const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinking, params.thinkingOverride !== undefined);
|
|
1796
|
+
const contextLimit = model ? findModelInfo(model, availableModels, agentConfig.modelProvider ?? ctx.currentModelProvider)?.contextWindow : undefined;
|
|
1797
|
+
const thinkingCeiling = externalRunner ? undefined : intersectThinkingCeilings(params.thinkingCeiling, agentConfig.maxThinking, ctx.childRuntime?.thinkingCeiling);
|
|
1798
|
+
if (!externalRunner) {
|
|
1799
|
+
try {
|
|
1800
|
+
assertThinkingWithinCeiling({ model, configThinking: effectiveThinking, ceiling: thinkingCeiling, agent: agentConfig.name, runId: id });
|
|
1801
|
+
}
|
|
1802
|
+
catch (error) {
|
|
1803
|
+
return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
const toolBudgetInput = params.toolBudget ?? agentConfig.toolBudget ?? params.configToolBudget;
|
|
1807
|
+
const resolvedToolBudget = validateToolBudgetConfig(toolBudgetInput, params.toolBudget ? "toolBudget" : agentConfig.toolBudget ? "agent.toolBudget" : "config.toolBudget");
|
|
1808
|
+
if (resolvedToolBudget.error)
|
|
1809
|
+
return formatAsyncStartError("single", resolvedToolBudget.error);
|
|
1810
|
+
const deadlineAt = params.absoluteDeadlineAt ?? (params.timeoutMs !== undefined ? Date.now() + params.timeoutMs : undefined);
|
|
1811
|
+
const timeoutMs = params.absoluteDeadlineAt !== undefined && deadlineAt !== undefined
|
|
1812
|
+
? deadlineAt - Date.now()
|
|
1813
|
+
: params.timeoutMs;
|
|
1814
|
+
if (timeoutMs !== undefined && timeoutMs <= 0)
|
|
1815
|
+
return formatAsyncStartError("single", "The source run's absolute deadline expired before recovery could launch.");
|
|
1816
|
+
const resolvedToolTimeout = resolveToolTimeoutMs({
|
|
1817
|
+
callValue: params.toolTimeoutMs,
|
|
1818
|
+
agentValue: agentConfig.defaultToolTimeoutMs,
|
|
1819
|
+
configValue: params.configToolTimeoutMs,
|
|
1820
|
+
envValue: params.toolTimeoutMsEnv ?? toolTimeoutFromEnv(),
|
|
1821
|
+
});
|
|
1822
|
+
if (resolvedToolTimeout.error)
|
|
1823
|
+
return formatAsyncStartError("single", resolvedToolTimeout.error);
|
|
1824
|
+
const toolTimeoutMs = resolvedToolTimeout.toolTimeoutMs;
|
|
1825
|
+
const initialUsageBudget = usageBudgetState(params.usageBudget, undefined);
|
|
1826
|
+
const resolvedSessionDir = params.sessionDir ?? (sessionRoot ? path.join(sessionRoot, `async-${id}`) : undefined);
|
|
1827
|
+
const structuredOutput = params.structuredOutputSchema
|
|
1828
|
+
? createStructuredOutputRuntime(params.structuredOutputSchema, path.join(asyncDir, "structured-output"), { acceptanceReport: resolveAcceptanceReportMode(params.acceptance) })
|
|
1829
|
+
: undefined;
|
|
1830
|
+
let selectedModel = model;
|
|
1831
|
+
let requestedModel;
|
|
1832
|
+
if (!externalRunner) {
|
|
1833
|
+
try {
|
|
1834
|
+
const modelEvidence = resolveModelSelection(primaryModel, availableModels, agentConfig.modelProvider ?? ctx.currentModelProvider, {
|
|
1835
|
+
scope: modelScopes,
|
|
1836
|
+
primaryModelFromParent: modelOrigin === "inherited",
|
|
1837
|
+
origin: modelOrigin,
|
|
1838
|
+
});
|
|
1839
|
+
requestedModel = modelEvidence.requestedModel;
|
|
1840
|
+
selectedModel = applyThinkingSuffix(modelEvidence.model, effectiveThinking, params.thinkingOverride !== undefined);
|
|
1841
|
+
assertThinkingWithinCeiling({ model: selectedModel, configThinking: effectiveThinking, ceiling: thinkingCeiling, agent: agentConfig.name, runId: id });
|
|
1842
|
+
}
|
|
1843
|
+
catch (error) {
|
|
1844
|
+
return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
|
|
1848
|
+
const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
|
|
1849
|
+
const toolPlan = resolvePiLaunchToolPlan({
|
|
1850
|
+
tools: agentConfig.tools,
|
|
1851
|
+
excludeTools: agentConfig.excludeTools,
|
|
1852
|
+
allowNestedSubagents: agentConfig.allowNestedSubagents,
|
|
1853
|
+
extensions: agentConfig.extensions,
|
|
1854
|
+
subagentOnlyExtensions: agentConfig.subagentOnlyExtensions,
|
|
1855
|
+
requiredExtensions,
|
|
1856
|
+
mcpDirectTools: agentConfig.mcpDirectTools,
|
|
1857
|
+
cwd: runnerCwd,
|
|
1858
|
+
requireReadTool: Boolean(resolvedSkills.length),
|
|
1859
|
+
structuredOutput: Boolean(params.structuredOutputSchema),
|
|
1860
|
+
fast: params.fast ?? agentConfig.fast,
|
|
1861
|
+
model: selectedModel,
|
|
1862
|
+
capabilityCeiling,
|
|
1863
|
+
inheritedCapabilityCeiling: ctx.childRuntime?.capabilityCeiling,
|
|
1864
|
+
agentName: agentConfig.name,
|
|
1865
|
+
permissionRules: resolvePermissionRules(ctx.permissions, agentConfig.permissions),
|
|
1866
|
+
runtimeSnapshotHost: ctx.pi,
|
|
1867
|
+
sandbox,
|
|
1868
|
+
permissionProfile: agentConfig.permissionProfile,
|
|
1869
|
+
hostAvailableBuiltins,
|
|
1870
|
+
});
|
|
1871
|
+
const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
|
|
1872
|
+
const parentExtensionProvider = externalRunner || machine ? undefined : parentExtensionProviderForChild(ctx, toolPlan.disableAmbientExtensions, selectedModel, availableModels, agentConfig.modelProvider ?? ctx.currentModelProvider);
|
|
1873
|
+
const fast = params.fast ?? agentConfig.fast;
|
|
1874
|
+
const launchThinking = resolveEffectiveThinking(selectedModel, effectiveThinking);
|
|
1875
|
+
const { definitionDigest, launchContractDigest } = resolveLaunchBinding({
|
|
1876
|
+
agent: agentConfig,
|
|
1877
|
+
task,
|
|
1878
|
+
model: selectedModel,
|
|
1879
|
+
...(fast !== undefined ? { fast } : {}),
|
|
1880
|
+
...(launchThinking ? { thinking: launchThinking } : {}),
|
|
1881
|
+
systemPrompt,
|
|
1882
|
+
systemPromptMode: agentConfig.systemPromptMode,
|
|
1883
|
+
inheritProjectContext: agentConfig.inheritProjectContext,
|
|
1884
|
+
inheritGlobalContext: agentConfig.inheritGlobalContext,
|
|
1885
|
+
inheritSkills: agentConfig.inheritSkills,
|
|
1886
|
+
sandbox,
|
|
1887
|
+
skills: resolvedSkills.map((skill) => skill.name),
|
|
1888
|
+
toolPlan,
|
|
1889
|
+
...(outputPath ? { outputPath } : {}),
|
|
1890
|
+
outputMode,
|
|
1891
|
+
...(params.structuredOutputSchema ? { structuredOutputSchema: params.structuredOutputSchema } : {}),
|
|
1892
|
+
...(extensionBindings ? { extensionBindings } : {}),
|
|
1893
|
+
});
|
|
1894
|
+
const resolvedAcceptance = resolveEffectiveAcceptance({
|
|
1895
|
+
explicit: params.acceptance,
|
|
1896
|
+
agentName: agent,
|
|
1897
|
+
acceptanceRole: agentConfig.acceptanceRole,
|
|
1898
|
+
task,
|
|
1899
|
+
mode: "single",
|
|
1900
|
+
async: true,
|
|
1901
|
+
agentContract: params.agentContract,
|
|
1902
|
+
});
|
|
1903
|
+
const recoveryAgentConfig = params.recoveryAgentConfig ?? agentConfig;
|
|
1904
|
+
const recoveryDescriptor = {
|
|
1905
|
+
...(ctx.modelResponseAliases ? { modelResponseAliases: ctx.modelResponseAliases } : {}),
|
|
1906
|
+
version: 1,
|
|
1907
|
+
...(lane ? { lane } : {}),
|
|
1908
|
+
launchContractDigest,
|
|
1909
|
+
...(extensionBindings ? { extensionBindings } : {}),
|
|
1910
|
+
...(requiredExtensions.length > 0 ? { requiredExtensions } : {}),
|
|
1911
|
+
runFanoutBudget,
|
|
1912
|
+
sourceRunId: id,
|
|
1913
|
+
...(params.agentContract ? { agentContract: params.agentContract } : {}),
|
|
1914
|
+
agent,
|
|
1915
|
+
...(sandbox ? { sandbox } : {}),
|
|
1916
|
+
launchResolvedExtensions,
|
|
1917
|
+
...(sessionFile ? { sessionFile } : {}),
|
|
1918
|
+
cwd: runnerCwd,
|
|
1919
|
+
...(selectedModel ? { model: selectedModel } : {}),
|
|
1920
|
+
...(params.fast ?? recoveryAgentConfig.fast ? { fast: params.fast ?? recoveryAgentConfig.fast } : {}),
|
|
1921
|
+
...(recoveryAgentConfig.modelProvider ? { modelProvider: recoveryAgentConfig.modelProvider } : {}),
|
|
1922
|
+
...(modelOrigin === "inherited" ? { modelOverrideFromParent: true } : {}),
|
|
1923
|
+
modelOrigin,
|
|
1924
|
+
...(effectiveThinking ? { thinking: resolveEffectiveThinking(selectedModel, effectiveThinking) } : {}),
|
|
1925
|
+
...(thinkingCeiling ? { thinkingCeiling } : {}),
|
|
1926
|
+
...(recoveryAgentConfig.tools ? { tools: [...recoveryAgentConfig.tools] } : {}),
|
|
1927
|
+
...(recoveryAgentConfig.excludeTools ? { excludeTools: [...recoveryAgentConfig.excludeTools] } : {}),
|
|
1928
|
+
...(recoveryAgentConfig.allowNestedSubagents !== undefined ? { allowNestedSubagents: recoveryAgentConfig.allowNestedSubagents } : {}),
|
|
1929
|
+
...(recoveryAgentConfig.allowedAgents !== undefined ? { allowedAgents: [...recoveryAgentConfig.allowedAgents] } : {}),
|
|
1930
|
+
...(recoveryAgentConfig.extensions ? { extensions: [...recoveryAgentConfig.extensions] } : {}),
|
|
1931
|
+
...(recoveryAgentConfig.subagentOnlyExtensions ? { subagentOnlyExtensions: [...recoveryAgentConfig.subagentOnlyExtensions] } : {}),
|
|
1932
|
+
...(recoveryAgentConfig.mcpDirectTools ? { mcpDirectTools: [...recoveryAgentConfig.mcpDirectTools] } : {}),
|
|
1933
|
+
...(recoveryAgentConfig.mutationTools ? { mutationTools: [...recoveryAgentConfig.mutationTools] } : {}),
|
|
1934
|
+
...(recoveryAgentConfig.systemPrompt ? { systemPrompt: recoveryAgentConfig.systemPrompt } : {}),
|
|
1935
|
+
systemPromptMode: recoveryAgentConfig.systemPromptMode,
|
|
1936
|
+
inheritProjectContext: recoveryAgentConfig.inheritProjectContext,
|
|
1937
|
+
inheritGlobalContext: recoveryAgentConfig.inheritGlobalContext,
|
|
1938
|
+
inheritSkills: recoveryAgentConfig.inheritSkills,
|
|
1939
|
+
...(resolvedSkills.length ? { skills: resolvedSkills.map((skill) => skill.name) } : {}),
|
|
1940
|
+
...(recoveryAgentConfig.skillPath ? { skillPath: [...recoveryAgentConfig.skillPath] } : {}),
|
|
1941
|
+
...(recoveryAgentConfig.filePath ? { agentFilePath: recoveryAgentConfig.filePath } : {}),
|
|
1942
|
+
...(recoveryAgentConfig.memory ? { memory: { ...recoveryAgentConfig.memory } } : {}),
|
|
1943
|
+
...(outputPath ? { outputPath } : {}),
|
|
1944
|
+
outputMode,
|
|
1945
|
+
...(params.structuredOutputSchema ? { structuredOutputSchema: params.structuredOutputSchema } : {}),
|
|
1946
|
+
...(params.acceptance !== undefined ? { acceptance: params.acceptance } : {}),
|
|
1947
|
+
...(controlConfig ? { controlConfig } : {}),
|
|
1948
|
+
...(params.context ? { context: params.context } : {}),
|
|
1949
|
+
...(params.intercomBridge !== undefined ? { intercomBridge: params.intercomBridge } : {}),
|
|
1950
|
+
...(params.baseRef !== undefined ? { baseRef: params.baseRef } : {}),
|
|
1951
|
+
...(launcher ? { launcher: launcher.name } : {}),
|
|
1952
|
+
...(deadlineAt !== undefined ? { absoluteDeadlineAt: deadlineAt } : {}),
|
|
1953
|
+
...(resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {}),
|
|
1954
|
+
maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, recoveryAgentConfig.maxSubagentDepth),
|
|
1955
|
+
...(maxOutput ? { maxOutput } : {}),
|
|
1956
|
+
share: shareEnabled,
|
|
1957
|
+
...(resolvedSessionDir ? { sessionDir: resolvedSessionDir } : {}),
|
|
1958
|
+
...(artifactsDir ? { artifactsDir } : {}),
|
|
1959
|
+
artifactConfig,
|
|
1960
|
+
...(capabilityCeiling ? { capabilityCeiling } : {}),
|
|
1961
|
+
};
|
|
1962
|
+
if (!externalRunner) {
|
|
1963
|
+
try {
|
|
1964
|
+
writePrivateAtomicJson(path.join(asyncDir, "recovery-descriptor.json"), recoveryDescriptor);
|
|
1965
|
+
}
|
|
1966
|
+
catch (error) {
|
|
1967
|
+
return formatAsyncStartError("single", `Failed to persist async recovery descriptor for '${id}': ${error instanceof Error ? error.message : String(error)}`);
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
let spawnResultOrPromise = {};
|
|
1971
|
+
const initialStatusAt = Date.now();
|
|
1972
|
+
const initialCompletionOwnerId = ctx.completionOwnerId ?? currentCompletionOwnerId();
|
|
1973
|
+
const completionOwnerProcess = currentRecordedPid();
|
|
1974
|
+
const launchParentSessionId = ctx.parentSessionId ?? ctx.currentSessionId;
|
|
1975
|
+
try {
|
|
1976
|
+
spawnResultOrPromise = spawnRunner({
|
|
1977
|
+
id,
|
|
1978
|
+
...(params.toolCallId ? { toolCallId: params.toolCallId } : {}),
|
|
1979
|
+
steps: [
|
|
1980
|
+
{
|
|
1981
|
+
parentSessionId: launchParentSessionId,
|
|
1982
|
+
...(ctx.parentSessionFile ? { parentSessionFile: ctx.parentSessionFile } : {}),
|
|
1983
|
+
permissionRules,
|
|
1984
|
+
...(ctx.projectTrusted !== undefined ? { projectTrusted: ctx.projectTrusted } : {}),
|
|
1985
|
+
...(ctx.trustedProjectCwd ? { trustedProjectCwd: ctx.trustedProjectCwd } : {}),
|
|
1986
|
+
...(capabilityCeiling ? { capabilityCeiling } : {}),
|
|
1987
|
+
agent,
|
|
1988
|
+
task: taskText,
|
|
1989
|
+
...(agentConfig.runner ? { runner: agentConfig.runner } : {}),
|
|
1990
|
+
...(singleClaudeCodeOverride ? { claudeCodeOverrideArgs: singleClaudeCodeOverride.args } : {}),
|
|
1991
|
+
...(machine ? { machine } : {}),
|
|
1992
|
+
...(!externalRunner && machine && params.reads !== undefined ? { remoteReads: params.reads } : {}),
|
|
1993
|
+
...(machineEnv ? { machineEnv } : {}),
|
|
1994
|
+
...(params.externalJobFollowUp ? { externalJobFollowUp: params.externalJobFollowUp } : {}),
|
|
1995
|
+
...(params.context ? { context: params.context } : {}),
|
|
1996
|
+
cwd: machine?.cwd ?? runnerCwd,
|
|
1997
|
+
requestedCwd: machine?.cwd ?? params.requestedCwd ?? runnerCwd,
|
|
1998
|
+
model: selectedModel,
|
|
1999
|
+
...(contextLimit !== undefined ? { contextLimit } : {}),
|
|
2000
|
+
...(params.fast ?? agentConfig.fast ? { fast: params.fast ?? agentConfig.fast } : {}),
|
|
2001
|
+
thinking: resolveEffectiveThinking(selectedModel, effectiveThinking),
|
|
2002
|
+
...(thinkingCeiling ? { thinkingCeiling } : {}),
|
|
2003
|
+
...(parentExtensionProvider ? { parentExtensionProvider } : {}),
|
|
2004
|
+
...(requestedModel ? { requestedModel } : {}),
|
|
2005
|
+
...(modelOrigin === "inherited" ? { skipPrimaryModelVerification: true } : {}),
|
|
2006
|
+
...(availableModels && availableModels.length > 0 ? { modelVerificationRegistry: availableModels } : {}),
|
|
2007
|
+
...(ctx.modelResponseAliases ? { modelResponseAliases: ctx.modelResponseAliases } : {}),
|
|
2008
|
+
tools: agentConfig.tools,
|
|
2009
|
+
excludeTools: agentConfig.excludeTools,
|
|
2010
|
+
allowNestedSubagents: agentConfig.allowNestedSubagents,
|
|
2011
|
+
allowedAgents: agentConfig.allowedAgents,
|
|
2012
|
+
extensions: agentConfig.extensions,
|
|
2013
|
+
subagentOnlyExtensions: agentConfig.subagentOnlyExtensions,
|
|
2014
|
+
...(!externalRunner ? { requiredExtensions } : {}),
|
|
2015
|
+
mcpDirectTools: agentConfig.mcpDirectTools,
|
|
2016
|
+
...(toolPlan.builtinMcpTools ? { builtinMcpTools: toolPlan.builtinMcpTools } : {}),
|
|
2017
|
+
mutationTools: agentConfig.mutationTools,
|
|
2018
|
+
...(sandbox ? { sandbox } : {}),
|
|
2019
|
+
...(agentConfig.permissionProfile ? { permissionProfile: agentConfig.permissionProfile } : {}),
|
|
2020
|
+
systemPrompt,
|
|
2021
|
+
systemPromptMode: agentConfig.systemPromptMode,
|
|
2022
|
+
inheritProjectContext: agentConfig.inheritProjectContext,
|
|
2023
|
+
inheritGlobalContext: agentConfig.inheritGlobalContext,
|
|
2024
|
+
inheritSkills: agentConfig.inheritSkills,
|
|
2025
|
+
skills: resolvedSkills.map((r) => r.name),
|
|
2026
|
+
outputPath,
|
|
2027
|
+
...(params.outputClaimPath ? { outputClaimPath: params.outputClaimPath } : {}),
|
|
2028
|
+
outputMode,
|
|
2029
|
+
...(!externalRunner && sessionFile ? { sessionFile } : {}),
|
|
2030
|
+
maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, agentConfig.maxSubagentDepth),
|
|
2031
|
+
waitToolEnabled: params.waitToolEnabled,
|
|
2032
|
+
waitToolDefaultTimeoutMs: params.waitToolDefaultTimeoutMs,
|
|
2033
|
+
...(params.agentContract ? { agentContract: params.agentContract } : {}),
|
|
2034
|
+
definitionDigest,
|
|
2035
|
+
launchBindingTask: task,
|
|
2036
|
+
launchContractDigest,
|
|
2037
|
+
...(extensionBindings ? { extensionBindings } : {}),
|
|
2038
|
+
launchResolvedExtensions,
|
|
2039
|
+
effectiveAcceptance: resolvedAcceptance,
|
|
2040
|
+
acceptanceInput: params.acceptance,
|
|
2041
|
+
...(structuredOutput ? { structuredOutput } : {}),
|
|
2042
|
+
...(params.structuredOutputSchema ? { structuredOutputSchema: params.structuredOutputSchema } : {}),
|
|
2043
|
+
...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),
|
|
2044
|
+
...(params.worktree === true ? { worktree: true } : {}),
|
|
2045
|
+
...(lane ? { lane } : {}),
|
|
2046
|
+
},
|
|
2047
|
+
],
|
|
2048
|
+
resultPath: params.parentWorkflowRunId !== undefined && (params.revivalLease !== undefined || params.workflowAwaitAsync === true)
|
|
2049
|
+
? workflowAwaitedAsyncResultPath(asyncDir)
|
|
2050
|
+
: inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) : resultFilePath(DIRS.results, id),
|
|
2051
|
+
cwd: runnerCwd,
|
|
2052
|
+
placeholder: "{previous}",
|
|
2053
|
+
maxOutput,
|
|
2054
|
+
artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
|
|
2055
|
+
artifactConfig,
|
|
2056
|
+
share: shareEnabled,
|
|
2057
|
+
sessionDir: resolvedSessionDir,
|
|
2058
|
+
asyncDir,
|
|
2059
|
+
sessionId: ctx.currentSessionId,
|
|
2060
|
+
completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
|
|
2061
|
+
completionOwnerProcess,
|
|
2062
|
+
...(capabilityCeiling ? { capabilityCeiling } : {}),
|
|
2063
|
+
piPackageRoot,
|
|
2064
|
+
childSessionFactoryModule: childSessionFactoryModule(),
|
|
2065
|
+
projectTrusted: ctx.projectTrusted,
|
|
2066
|
+
inheritedChildRuntime: inheritedChildRuntime(ctx.childRuntime),
|
|
2067
|
+
worktreeSetupHook,
|
|
2068
|
+
worktreeSetupHookTimeoutMs,
|
|
2069
|
+
worktreeBaseDir,
|
|
2070
|
+
baseRef,
|
|
2071
|
+
worktreeProvider,
|
|
2072
|
+
worktreeBranchPrefix,
|
|
2073
|
+
controlConfig,
|
|
2074
|
+
timeoutMs,
|
|
2075
|
+
deadlineAt,
|
|
2076
|
+
toolTimeoutMs,
|
|
2077
|
+
checkpointBeforeDeadlineMs: params.checkpointBeforeDeadlineMs,
|
|
2078
|
+
toolBudget: params.toolBudget,
|
|
2079
|
+
usageBudget: params.usageBudget,
|
|
2080
|
+
controlIntercomTarget,
|
|
2081
|
+
childIntercomTargets: childIntercomTarget ? [childIntercomTarget(agent, 0)] : undefined,
|
|
2082
|
+
resultMode: "single",
|
|
2083
|
+
launchContractDigest,
|
|
2084
|
+
launchResolvedExtensions,
|
|
2085
|
+
runFanoutBudget,
|
|
2086
|
+
...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
|
|
2087
|
+
...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
|
|
2088
|
+
...(lane ? { lane } : {}),
|
|
2089
|
+
...(params.revivalLease ? { revivalLease: params.revivalLease } : {}),
|
|
2090
|
+
nestedRoute: nestedRoute ?? inheritedNestedRoute,
|
|
2091
|
+
...(launcher ? { launcher } : {}),
|
|
2092
|
+
nestedSelf: inheritedNestedRoute && nestedAddress ? {
|
|
2093
|
+
parentRunId: nestedAddress.parentRunId,
|
|
2094
|
+
parentStepIndex: nestedAddress.parentStepIndex,
|
|
2095
|
+
depth: nestedAddress.depth,
|
|
2096
|
+
path: nestedAddress.path,
|
|
2097
|
+
} : undefined,
|
|
2098
|
+
}, id, runnerCwd, {
|
|
2099
|
+
lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
|
|
2100
|
+
runId: id,
|
|
2101
|
+
...(ctx.currentSessionId ? { sessionId: ctx.currentSessionId } : {}),
|
|
2102
|
+
...(initialCompletionOwnerId ? { completionOwnerId: initialCompletionOwnerId } : {}),
|
|
2103
|
+
completionOwnerProcess,
|
|
2104
|
+
mode: "single",
|
|
2105
|
+
...(params.toolCallId ? { toolCallId: params.toolCallId } : {}),
|
|
2106
|
+
state: "running",
|
|
2107
|
+
startedAt: initialStatusAt,
|
|
2108
|
+
lastUpdate: initialStatusAt,
|
|
2109
|
+
currentStep: 0,
|
|
2110
|
+
chainStepCount: 1,
|
|
2111
|
+
...(lane ? { lane } : {}),
|
|
2112
|
+
...(launcher ? { launcher } : {}),
|
|
2113
|
+
steps: [{ agent, status: "pending", ...(lane ? { lane } : {}), ...(model ? { model } : {}), ...(contextLimit !== undefined ? { contextLimit } : {}) }],
|
|
2114
|
+
}, path.join(asyncDir, "status.json"), launchParentSessionId, (proof) => emitProcessTerminalEvent(ctx, proof), (runnerProcessInstanceId) => params.activeAsyncCapacity?.markStarted(runnerProcessInstanceId), params.requestedCwd ?? runnerCwd);
|
|
2115
|
+
}
|
|
2116
|
+
catch (error) {
|
|
2117
|
+
params.activeAsyncCapacity?.rollback();
|
|
2118
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2119
|
+
return formatAsyncStartError("single", `Failed to start async run '${id}': ${message}`);
|
|
2120
|
+
}
|
|
2121
|
+
const finishSpawnResult = (spawnResult) => {
|
|
2122
|
+
if (spawnResult.error) {
|
|
2123
|
+
if (spawnResult.startupDidNotProceed) {
|
|
2124
|
+
if (!spawnResult.runnerProcessInstanceId || params.activeAsyncCapacity?.rollbackBeforeRunnerProceed(spawnResult.runnerProcessInstanceId) !== true)
|
|
2125
|
+
params.activeAsyncCapacity?.rollback();
|
|
2126
|
+
}
|
|
2127
|
+
else if (!spawnResult.pid || !spawnResult.runnerProcessInstanceId)
|
|
2128
|
+
params.activeAsyncCapacity?.rollback();
|
|
2129
|
+
else
|
|
2130
|
+
params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
|
|
2131
|
+
return formatAsyncStartError("single", `Failed to start async run '${id}': ${spawnResult.error}`);
|
|
2132
|
+
}
|
|
2133
|
+
if (!spawnResult.pid || !spawnResult.runnerProcessInstanceId) {
|
|
2134
|
+
params.activeAsyncCapacity?.rollback();
|
|
2135
|
+
return formatAsyncStartError("single", `Failed to start async run '${id}': runner identity unavailable`);
|
|
2136
|
+
}
|
|
2137
|
+
if (spawnResult.pid) {
|
|
2138
|
+
if (inheritedNestedRoute && nestedAddress) {
|
|
2139
|
+
const now = Date.now();
|
|
2140
|
+
try {
|
|
2141
|
+
writeNestedEvent(inheritedNestedRoute, {
|
|
2142
|
+
type: "subagent.nested.started",
|
|
2143
|
+
ts: now,
|
|
2144
|
+
parentRunId: nestedAddress.parentRunId,
|
|
2145
|
+
parentStepIndex: nestedAddress.parentStepIndex,
|
|
2146
|
+
child: {
|
|
2147
|
+
id,
|
|
2148
|
+
parentRunId: nestedAddress.parentRunId,
|
|
2149
|
+
parentStepIndex: nestedAddress.parentStepIndex,
|
|
2150
|
+
depth: nestedAddress.depth,
|
|
2151
|
+
path: nestedAddress.path,
|
|
2152
|
+
asyncDir,
|
|
2153
|
+
pid: spawnResult.pid,
|
|
2154
|
+
ownerIntercomTarget: ctx.childRuntime?.intercomSessionName,
|
|
2155
|
+
leafIntercomTarget: childIntercomTarget?.(agent, 0),
|
|
2156
|
+
intercomTarget: childIntercomTarget?.(agent, 0),
|
|
2157
|
+
ownerState: "live",
|
|
2158
|
+
mode: "single",
|
|
2159
|
+
state: "running",
|
|
2160
|
+
agent,
|
|
2161
|
+
...(sandbox ? { sandbox } : {}),
|
|
2162
|
+
agents: [agent],
|
|
2163
|
+
chainStepCount: 1,
|
|
2164
|
+
...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}),
|
|
2165
|
+
startedAt: now,
|
|
2166
|
+
lastUpdate: now,
|
|
2167
|
+
...(capabilityCeiling ? { capabilityCeiling } : {}),
|
|
2168
|
+
},
|
|
2169
|
+
});
|
|
2170
|
+
}
|
|
2171
|
+
catch (error) {
|
|
2172
|
+
console.error("Failed to emit nested async start event:", error);
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
ctx.pi.events.emit(SUBAGENT_ASYNC_STARTED_EVENT, {
|
|
2176
|
+
lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
|
|
2177
|
+
id,
|
|
2178
|
+
pid: spawnResult.pid,
|
|
2179
|
+
sessionId: ctx.currentSessionId,
|
|
2180
|
+
completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
|
|
2181
|
+
mode: "single",
|
|
2182
|
+
...(params.toolCallId ? { toolCallId: params.toolCallId } : {}),
|
|
2183
|
+
agent,
|
|
2184
|
+
...(sandbox ? { sandbox } : {}),
|
|
2185
|
+
task: task?.trim() ? PROMPT_REDACTED : undefined,
|
|
2186
|
+
goal: (params.goal ?? task).trim() ? PROMPT_REDACTED : undefined,
|
|
2187
|
+
cwd: runnerCwd,
|
|
2188
|
+
asyncDir,
|
|
2189
|
+
...(sessionRoot ? { sessionRoot } : {}),
|
|
2190
|
+
launchContractDigest,
|
|
2191
|
+
launchResolvedExtensions,
|
|
2192
|
+
...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
|
|
2193
|
+
...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
|
|
2194
|
+
...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}),
|
|
2195
|
+
...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}),
|
|
2196
|
+
...(capabilityCeiling ? { capabilityCeiling } : {}),
|
|
2197
|
+
nestedRoute,
|
|
2198
|
+
});
|
|
2199
|
+
}
|
|
2200
|
+
return {
|
|
2201
|
+
content: [{ type: "text", text: formatAsyncStartedMessage(`Async: ${agent} [${id}]`, ctx.interactive === true) }],
|
|
2202
|
+
details: { mode: "single", runId: id, ...(params.toolCallId ? { toolCallId: params.toolCallId } : {}), results: [], asyncId: id, asyncDir, launchContractDigest, launchResolvedExtensions, ...(capabilityCeiling ? { capabilityCeiling } : {}), ...(params.context ? { context: params.context } : {}), ...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}), ...(params.toolBudget ? { toolBudget: resolvedToolBudget.budget ?? params.toolBudget } : {}), ...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}) },
|
|
2203
|
+
};
|
|
2204
|
+
};
|
|
2205
|
+
return spawnResultOrPromise instanceof Promise ? spawnResultOrPromise.then(finishSpawnResult) : finishSpawnResult(spawnResultOrPromise);
|
|
2206
|
+
}
|