@xzzpig/pi-subagents 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/CHANGELOG.md +456 -4
  2. package/README.md +3 -3
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +13 -3
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +154 -42
  12. package/docs/configuration.md +85 -26
  13. package/docs/extension-api.md +81 -16
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +75 -11
  16. package/docs/observability.md +34 -21
  17. package/docs/tool-reference.md +142 -18
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +148 -4
  20. package/index.ts +10 -1
  21. package/install.mjs +1 -1
  22. package/package.json +7 -6
  23. package/prompts/council.md +19 -7
  24. package/prompts/parallel-review.md +5 -1
  25. package/prompts/review-loop.md +11 -7
  26. package/skills/council-mode/SKILL.md +44 -215
  27. package/skills/council-mode/references/pass-contracts.md +150 -0
  28. package/skills/pi-subagents/SKILL.md +90 -32
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
  30. package/skills/pi-subagents/references/execution-controls.md +104 -19
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
  33. package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
  34. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  35. package/src/agents/agent-management.ts +471 -114
  36. package/src/agents/agent-refinements.ts +4 -4
  37. package/src/agents/agent-serializer.ts +16 -4
  38. package/src/agents/agents.ts +1076 -351
  39. package/src/agents/builtin-names.ts +6 -0
  40. package/src/agents/runtime-agent-events.ts +70 -0
  41. package/src/agents/runtime-agent-registry.ts +31 -20
  42. package/src/api/agents.ts +10 -5
  43. package/src/api/background-work.ts +12 -3
  44. package/src/api/capability-ceiling.ts +0 -1
  45. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  46. package/src/api/delegation.ts +0 -7
  47. package/src/api/external-job-provider.ts +10 -1
  48. package/src/api/external-runs.ts +67 -4
  49. package/src/api/preflight.ts +97 -34
  50. package/src/api/project-panes.ts +2 -0
  51. package/src/api/shared-types.ts +6 -0
  52. package/src/extension/config.ts +90 -0
  53. package/src/extension/doctor.ts +15 -13
  54. package/src/extension/fanout-child.ts +17 -16
  55. package/src/extension/index.ts +139 -41
  56. package/src/extension/public-execution.ts +113 -22
  57. package/src/extension/rpc.ts +182 -13
  58. package/src/extension/schemas.ts +63 -21
  59. package/src/extension/tool-description.ts +48 -23
  60. package/src/extension/tool-result.ts +19 -0
  61. package/src/inspectors/herdr/actions.ts +2 -1
  62. package/src/inspectors/herdr/client.ts +3 -3
  63. package/src/inspectors/herdr/focus.ts +55 -0
  64. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  65. package/src/inspectors/herdr/project-panes.ts +228 -44
  66. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  67. package/src/integrations/herdr-status.ts +75 -5
  68. package/src/intercom/native-supervisor-channel.ts +138 -60
  69. package/src/intercom/result-intercom.ts +2 -0
  70. package/src/intercom/supervisor-ui.ts +243 -0
  71. package/src/profiles/profiles.ts +5 -6
  72. package/src/runs/background/active-async-capacity.ts +103 -18
  73. package/src/runs/background/async-execution.ts +492 -125
  74. package/src/runs/background/async-job-tracker.ts +127 -28
  75. package/src/runs/background/async-resume.ts +67 -29
  76. package/src/runs/background/async-retention.ts +21 -4
  77. package/src/runs/background/async-status-snapshot.ts +23 -261
  78. package/src/runs/background/async-status.ts +199 -14
  79. package/src/runs/background/auto-drain.ts +1 -1
  80. package/src/runs/background/chain-append.ts +8 -3
  81. package/src/runs/background/chain-root-attachment.ts +79 -8
  82. package/src/runs/background/control-channel.ts +101 -214
  83. package/src/runs/background/fleet-view.ts +38 -22
  84. package/src/runs/background/inspect-rpc.ts +8 -8
  85. package/src/runs/background/notify.ts +295 -8
  86. package/src/runs/background/process-terminal.ts +16 -0
  87. package/src/runs/background/result-delivery-ownership.ts +45 -0
  88. package/src/runs/background/result-files.ts +28 -14
  89. package/src/runs/background/result-watcher.ts +43 -19
  90. package/src/runs/background/resume-guidance.ts +2 -2
  91. package/src/runs/background/retained-children.ts +1 -1
  92. package/src/runs/background/run-child-session.ts +613 -0
  93. package/src/runs/background/run-status.ts +99 -18
  94. package/src/runs/background/runner-aliases.ts +125 -0
  95. package/src/runs/background/runner-child-sessions.ts +31 -0
  96. package/src/runs/background/scheduled-runs.ts +174 -18
  97. package/src/runs/background/stale-run-reconciler.ts +13 -4
  98. package/src/runs/background/steering.ts +8 -15
  99. package/src/runs/background/subagent-runner.ts +959 -1159
  100. package/src/runs/background/subagent-wait.ts +86 -31
  101. package/src/runs/background/terminal-run-index.ts +1 -1
  102. package/src/runs/background/wait-completions.ts +45 -2
  103. package/src/runs/background/wait-config.ts +23 -9
  104. package/src/runs/background/wait-tool.ts +27 -19
  105. package/src/runs/foreground/async-steering-action.ts +3 -19
  106. package/src/runs/foreground/async-stop-action.ts +23 -2
  107. package/src/runs/foreground/execution.ts +585 -481
  108. package/src/runs/foreground/foreground-control.ts +13 -0
  109. package/src/runs/foreground/foreground-history.ts +26 -3
  110. package/src/runs/foreground/subagent-executor.ts +1549 -410
  111. package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
  112. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  113. package/src/runs/shared/abort-recovery.ts +119 -0
  114. package/src/runs/shared/acceptance.ts +147 -39
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +565 -0
  117. package/src/runs/shared/background-process-options.ts +9 -0
  118. package/src/runs/shared/capability-ceiling.ts +2 -2
  119. package/src/runs/shared/child-hooks.ts +25 -0
  120. package/src/runs/shared/child-identity.ts +62 -0
  121. package/src/runs/shared/child-launch-plan.ts +151 -0
  122. package/src/runs/shared/child-launch.ts +314 -0
  123. package/src/runs/shared/child-lifecycle.ts +25 -0
  124. package/src/runs/shared/child-runtime-config.ts +126 -0
  125. package/src/runs/shared/child-session.ts +342 -0
  126. package/src/runs/shared/child-tool-plan.ts +540 -0
  127. package/src/runs/shared/claude-code-adapter.ts +133 -0
  128. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  129. package/src/runs/shared/completion-evidence.ts +89 -0
  130. package/src/runs/shared/completion-guard.ts +57 -6
  131. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  132. package/src/runs/shared/dynamic-fanout.ts +4 -4
  133. package/src/runs/shared/extension-bindings.ts +78 -0
  134. package/src/runs/shared/external-cli-contract.ts +167 -0
  135. package/src/runs/shared/external-cli-preflight.ts +138 -0
  136. package/src/runs/shared/external-cli-runner.ts +349 -54
  137. package/src/runs/shared/external-job-bridge.ts +53 -37
  138. package/src/runs/shared/external-job-runner.ts +126 -23
  139. package/src/runs/shared/fast-mode-extension.ts +10 -0
  140. package/src/runs/shared/host-step-status.ts +231 -0
  141. package/src/runs/shared/lane-metadata.ts +126 -0
  142. package/src/runs/shared/launch-cwd.ts +16 -0
  143. package/src/runs/shared/long-running-guard.ts +2 -1
  144. package/src/runs/shared/mcp-config-sources.ts +422 -0
  145. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  146. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  147. package/src/runs/shared/model-exclusions.ts +141 -10
  148. package/src/runs/shared/model-fallback.ts +187 -33
  149. package/src/runs/shared/model-scope.ts +106 -39
  150. package/src/runs/shared/mutation-evidence.ts +199 -0
  151. package/src/runs/shared/nested-events.ts +38 -48
  152. package/src/runs/shared/nested-path.ts +0 -14
  153. package/src/runs/shared/nested-render.ts +9 -5
  154. package/src/runs/shared/orca-progress-tabs.ts +83 -16
  155. package/src/runs/shared/parallel-handoff.ts +423 -7
  156. package/src/runs/shared/parallel-utils.ts +28 -5
  157. package/src/runs/shared/permissions.ts +1 -14
  158. package/src/runs/shared/pi-spawn.ts +69 -35
  159. package/src/runs/shared/process-signal.ts +16 -0
  160. package/src/runs/shared/run-fanout-budget.ts +0 -13
  161. package/src/runs/shared/run-history.ts +21 -1
  162. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  163. package/src/runs/shared/single-output.ts +89 -22
  164. package/src/runs/shared/structured-output.ts +61 -7
  165. package/src/runs/shared/subagent-control.ts +6 -2
  166. package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
  167. package/src/runs/shared/task-intent.ts +21 -7
  168. package/src/runs/shared/tool-availability.ts +18 -64
  169. package/src/runs/shared/tool-budget.ts +0 -14
  170. package/src/runs/shared/tool-timeout.ts +1 -1
  171. package/src/runs/shared/workflow-graph.ts +16 -0
  172. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  173. package/src/runs/shared/worktree.ts +571 -62
  174. package/src/shared/atomic-json.ts +3 -1
  175. package/src/shared/child-session-name.ts +46 -0
  176. package/src/shared/extension-context.ts +24 -0
  177. package/src/shared/fork-context.ts +21 -12
  178. package/src/shared/fork-session-cwd.ts +27 -0
  179. package/src/shared/formatters.ts +18 -3
  180. package/src/shared/jsonl-writer.ts +11 -0
  181. package/src/shared/launch-contract.ts +20 -6
  182. package/src/shared/pruned-fork.ts +450 -0
  183. package/src/shared/session-file-trust.ts +19 -0
  184. package/src/shared/session-tokens.ts +14 -3
  185. package/src/shared/settings.ts +21 -102
  186. package/src/shared/shortcuts.ts +17 -0
  187. package/src/shared/thinking-ceiling.ts +46 -0
  188. package/src/shared/types.ts +644 -75
  189. package/src/shared/utils.ts +60 -93
  190. package/src/shared/workflow-child-permit.ts +207 -0
  191. package/src/slash/delegation-adapters.ts +1 -9
  192. package/src/slash/delegation-request.ts +0 -4
  193. package/src/slash/prompt-template-bridge.ts +37 -1
  194. package/src/slash/slash-bridge.ts +1 -2
  195. package/src/slash/slash-commands.ts +383 -116
  196. package/src/slash/slash-live-state.ts +22 -11
  197. package/src/slash/subagents-admin.ts +29 -12
  198. package/src/tui/fleet-native-transcript.ts +4 -0
  199. package/src/tui/fleet-status.ts +278 -90
  200. package/src/tui/fleet-transcript.ts +11 -5
  201. package/src/tui/fleet.ts +54 -28
  202. package/src/tui/render-helpers.ts +31 -0
  203. package/src/tui/render.ts +1433 -166
  204. package/src/watchdog/change-signature.ts +40 -1
  205. package/src/watchdog/child-status.ts +54 -34
  206. package/src/watchdog/diff-tool.ts +77 -0
  207. package/src/watchdog/emission-guard.ts +5 -3
  208. package/src/watchdog/guidance.ts +20 -0
  209. package/src/watchdog/permission-arbiter.ts +59 -52
  210. package/src/watchdog/register-child.ts +28 -25
  211. package/src/watchdog/register-main.ts +10 -9
  212. package/src/watchdog/render.ts +4 -5
  213. package/src/watchdog/review.ts +15 -4
  214. package/src/watchdog/rules.ts +70 -0
  215. package/src/watchdog/runtime.ts +75 -92
  216. package/src/watchdog/scope.ts +0 -11
  217. package/src/watchdog/settings.ts +48 -104
  218. package/src/watchdog/turn-delta.ts +1 -1
  219. package/src/watchdog/types.ts +18 -32
  220. package/src/watchdog/warning-format.ts +0 -1
  221. package/src/workflows/chat-progress.ts +7 -3
  222. package/src/workflows/host-command.ts +235 -0
  223. package/src/workflows/scripted-workflow.ts +1142 -69
  224. package/src/workflows/workflow-checklist.ts +439 -0
  225. package/src/workflows/workflow-child-summary.ts +121 -0
  226. package/src/workflows/workflow-preflight.ts +297 -0
  227. package/src/workflows/workflow-receipt.ts +232 -6
  228. package/src/workflows/workflow-resources.ts +150 -0
  229. package/src/workflows/workflow-settlement.ts +246 -0
  230. package/src/runs/shared/child-protocol.ts +0 -401
  231. package/src/runs/shared/pi-args.ts +0 -858
  232. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  233. package/src/runs/shared/turn-budget.ts +0 -98
  234. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -5,38 +5,45 @@
5
5
  import { spawn } from "node:child_process";
6
6
  import { randomUUID } from "node:crypto";
7
7
  import * as fs from "node:fs";
8
- import * as os from "node:os";
9
8
  import * as path from "node:path";
10
9
  import { fileURLToPath } from "node:url";
11
10
  import { createRequire } from "node:module";
12
11
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
13
- import type { AgentConfig } from "../../agents/agents.ts";
12
+ import { discoverAgents, formatUnknownAgentError, unknownAgentDiagnosticContext, type AgentConfig, type UnknownAgentDiagnosticContext } from "../../agents/agents.ts";
14
13
  import { appendAgentRefinementOverlay } from "../../agents/agent-refinements.ts";
15
- import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
14
+ import { createAtomicJsonWriter, writePrivateAtomicJson } from "../../shared/atomic-json.ts";
16
15
  import { currentCompletionOwnerId } from "../../shared/completion-owner.ts";
17
- import { applyThinkingSuffix, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan } from "../shared/pi-args.ts";
16
+ import { planChildLaunch, resolveStepBehavior, suppressProgressForReadOnlyTask, type ResolvedStepBehavior } from "../shared/child-launch-plan.ts";
17
+ import { applyThinkingSuffix, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan } from "../shared/child-tool-plan.ts";
18
18
  import { injectOutputPathSystemPrompt, injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
19
- import { buildChainInstructions, isDynamicParallelStep, isParallelStep, resolveChainPath, resolveExistingReadPaths, resolveStepBehavior, suppressProgressForReadOnlyTask, writeInitialProgressFile, type ChainStep, type ResolvedStepBehavior, type SequentialStep, type StepOverrides } from "../../shared/settings.ts";
19
+ import { applyWatchdogLaunchRules, sendRuleViolationWarning } from "../../watchdog/rules.ts";
20
+ import { buildChainInstructions, isDynamicParallelStep, isParallelStep, resolveExistingReadInstructionPaths, resolveExistingReadPaths, writeInitialProgressFile, type ChainStep, type SequentialStep, type StepOverrides } from "../../shared/settings.ts";
20
21
  import type { RunnerStep } from "../shared/parallel-utils.ts";
21
22
  import type { ContextMode } from "../shared/context-mode.ts";
22
- import { resolvePiPackageRoot } from "../shared/pi-spawn.ts";
23
+ import { PI_CODING_AGENT_PACKAGE, resolveInstalledPiPackageRoot, resolvePiPackageRoot } from "../shared/pi-spawn.ts";
24
+ import { JITI_ALIAS_ENV, resolveHostPeerAliases } from "./runner-aliases.ts";
25
+ import { preflightLaunchCwd } from "../shared/launch-cwd.ts";
23
26
  import { resolveNodeExecutable } from "../../shared/node-executable.ts";
27
+ import { backgroundProcessOptions } from "../shared/background-process-options.ts";
24
28
  import { buildSkillInjection, normalizeSkillInput, resolveSkillsWithFallback } from "../../agents/skills.ts";
25
29
  import { buildAgentMemoryInjection } from "../../agents/agent-memory.ts";
26
30
  import { PI_CODING_AGENT_PACKAGE_ROOT_ENV, PROMPT_REDACTED, resolveChildCwd } from "../../shared/utils.ts";
27
- import { buildModelCandidates, inheritsParentModel, resolveEffectiveSubagentModel, resolveModelCandidate, resolveSubagentModelOverride, type AvailableModelInfo, type ParentModel } from "../shared/model-fallback.ts";
31
+ import { buildModelCandidates, resolveEffectiveSubagentModel, resolveModelOrigin, resolveSubagentModelOverride, type AvailableModelInfo, type ModelOrigin, type ParentModel } from "../shared/model-fallback.ts";
28
32
  import { resolveToolTimeoutMs, toolTimeoutFromEnv } from "../shared/tool-timeout.ts";
29
- import type { ModelScopeConfig } from "../shared/model-scope.ts";
30
- import { resolveEffectiveThinking } from "../../shared/model-info.ts";
31
- import { resolveExpectedWorktreeAgentCwd } from "../shared/worktree.ts";
33
+ import { resolveModelScopesForAgent, type ModelScopeConfig } from "../shared/model-scope.ts";
34
+ import { findModelInfo, resolveEffectiveThinking } from "../../shared/model-info.ts";
35
+ import { assertThinkingWithinCeiling, intersectThinkingCeilings, type ThinkingLevel } from "../../shared/thinking-ceiling.ts";
36
+ import { resolveExpectedWorktreeAgentCwd, resolveWorktreeProvider, shouldDeferWorktreeCwd, WORKTREE_AGENT_CWD_PLACEHOLDER } from "../shared/worktree.ts";
32
37
  import { buildWorkflowGraphSnapshot } from "../shared/workflow-graph.ts";
33
38
  import { ChainOutputValidationError, validateChainOutputBindings } from "../shared/chain-outputs.ts";
34
39
  import { createStructuredOutputRuntime } from "../shared/structured-output.ts";
35
- import { resolveEffectiveAcceptance, validateAcceptanceInput, validateExecutionAcceptance } from "../shared/acceptance.ts";
40
+ import { resolveAcceptanceReportMode, resolveEffectiveAcceptance, validateAcceptanceInput, validateExecutionAcceptance } from "../shared/acceptance.ts";
36
41
  import { createRunFanoutBudget, writeRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
42
+ import { validateImplementationToolContract } from "../shared/completion-guard.ts";
37
43
  import {
38
44
  type AcceptanceInput,
39
45
  type AgentContract,
46
+ type AsyncParallelGroupStatus,
40
47
  type AsyncStatus,
41
48
  type ArtifactConfig,
42
49
  type Details,
@@ -45,12 +52,12 @@ import {
45
52
  type MaxOutputConfig,
46
53
  type NestedRouteInfo,
47
54
  type ResolvedControlConfig,
48
- type ResolvedTurnBudget,
49
55
  type ResolvedToolBudget,
50
56
  type RunFanoutBudgetDescriptor,
51
57
  type ToolBudgetConfig,
52
58
  type SubagentRunMode,
53
59
  type SteeringRecoveryDescriptor,
60
+ type WorkflowLaneMetadata,
54
61
  type UsageBudgetConfig,
55
62
  DIRS,
56
63
  SUBAGENT_ASYNC_STARTED_EVENT,
@@ -59,22 +66,27 @@ import {
59
66
  getAsyncConfigPath,
60
67
  resolveChildMaxSubagentDepth,
61
68
  } from "../../shared/types.ts";
62
- import { nestedResultsPath, nestedSummaryFromAsyncStatus, resolveInheritedNestedRouteFromEnv, resolveNestedParentAddressFromEnv, writeNestedEvent } from "../shared/nested-events.ts";
69
+ import { inheritedNestedParentAddressOf, inheritedNestedRouteOf, nestedResultsPath, nestedSummaryFromAsyncStatus, writeNestedEvent } from "../shared/nested-events.ts";
70
+ import type { ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
71
+ import { childSessionFactoryModule } from "../shared/child-session.ts";
72
+ import { inheritedChildRuntime } from "../shared/child-launch.ts";
63
73
  import { resultFilePath } from "./result-files.ts";
64
- import { appendTurnBudgetSystemPrompt, initialTurnBudgetState } from "../shared/turn-budget.ts";
65
74
  import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
66
75
  import { usageBudgetState } from "../shared/usage-budget.ts";
67
76
  import type { ImportedAsyncRoot } from "./chain-root-attachment.ts";
68
77
  import type { SessionLeaseRequest } from "../shared/session-lease.ts";
69
- import { finalizeProcessTerminal, readProcessTerminal } from "./process-terminal.ts";
78
+ import { finalizeProcessTerminal, initializeProcessTerminal, readProcessTerminal } from "./process-terminal.ts";
70
79
  import type { ActiveAsyncCapacityHandle } from "./active-async-capacity.ts";
80
+ import { statusStepDescription } from "./chain-append.ts";
71
81
  import { SUBAGENT_PROCESS_TERMINAL_EVENT } from "../../shared/types.ts";
72
- import { assertAgentAllowedByCapabilityCeiling, decodeSubagentCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, SUBAGENT_CAPABILITY_CEILING_ENV, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
82
+ import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
73
83
  import { agentDefinitionDigest, launchBindingDigest } from "../../shared/launch-contract.ts";
74
84
  import { resolvePermissionRules, type PermissionConfig } from "../shared/permissions.ts";
85
+ import { normalizeExtensionBindings, omitExtensionBindingsEnv, type ExtensionBindings } from "../shared/extension-bindings.ts";
86
+ import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
75
87
 
76
88
  const require = createRequire(import.meta.url);
77
- const piPackageRoot = resolvePiPackageRoot();
89
+ const piPackageRoot = resolvePiPackageRoot() ?? resolveInstalledPiPackageRoot();
78
90
 
79
91
  function resolveJitiCliFromPackageJson(packageJsonPath: string): string | undefined {
80
92
  if (!fs.existsSync(packageJsonPath)) return undefined;
@@ -136,6 +148,8 @@ interface AsyncExecutionContext {
136
148
  modelScope?: ModelScopeConfig;
137
149
  /** Whether the parent session has an interactive UI. */
138
150
  interactive?: boolean;
151
+ /** The executor's own child runtime when the launch comes from an in-process child. */
152
+ childRuntime?: ChildRuntimeConfig;
139
153
  }
140
154
 
141
155
  export const DEFAULT_ASYNC_TIMEOUT_MS = 30 * 60 * 1000;
@@ -148,6 +162,8 @@ interface AsyncChainParams {
148
162
  attachRoot?: ImportedAsyncRoot & { agent: string; outputName?: string; label?: string };
149
163
  resultMode?: SubagentRunMode;
150
164
  agents: AgentConfig[];
165
+ /** Original discovery provenance, retained by normal callers for unknown-agent diagnostics. */
166
+ unknownAgentDiagnosticContext?: UnknownAgentDiagnosticContext;
151
167
  ctx: AsyncExecutionContext;
152
168
  availableModels?: AvailableModelInfo[];
153
169
  cwd?: string;
@@ -165,16 +181,20 @@ interface AsyncChainParams {
165
181
  dynamicFanoutMaxItems?: number;
166
182
  maxSubagentDepth: number;
167
183
  waitToolEnabled?: boolean;
184
+ waitToolDefaultTimeoutMs?: number;
168
185
  worktreeSetupHook?: string;
169
186
  worktreeSetupHookTimeoutMs?: number;
170
187
  worktreeBaseDir?: string;
188
+ baseRef?: string;
189
+ worktreeProvider?: import("../../shared/types.ts").WorktreeProvider;
190
+ worktreeBranchPrefix?: string;
171
191
  controlConfig?: ResolvedControlConfig;
172
192
  controlIntercomTarget?: string;
173
193
  childIntercomTarget?: (agent: string, index: number) => string | undefined;
174
194
  nestedRoute?: NestedRouteInfo;
175
195
  acceptance?: AcceptanceInput;
196
+ fast?: boolean;
176
197
  timeoutMs?: number;
177
- turnBudget?: ResolvedTurnBudget;
178
198
  toolBudget?: ResolvedToolBudget;
179
199
  usageBudget?: UsageBudgetConfig;
180
200
  configToolBudget?: ResolvedToolBudget;
@@ -187,9 +207,11 @@ interface AsyncChainParams {
187
207
  /** Global cap on simultaneously-running subagent tasks within the async run. */
188
208
  globalConcurrencyLimit?: number;
189
209
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
210
+ thinkingCeiling?: ThinkingLevel;
190
211
  runFanoutBudget?: RunFanoutBudgetDescriptor;
191
212
  parentWorkflowRunId?: string;
192
213
  workflowKey?: string;
214
+ lane?: WorkflowLaneMetadata;
193
215
  activeAsyncCapacity?: ActiveAsyncCapacityHandle;
194
216
  }
195
217
 
@@ -203,6 +225,7 @@ interface AsyncSingleParams {
203
225
  recoveryAgentConfig?: AgentConfig;
204
226
  ctx: AsyncExecutionContext;
205
227
  cwd?: string;
228
+ requestedCwd?: string;
206
229
  maxOutput?: MaxOutputConfig;
207
230
  artifactsDir?: string;
208
231
  artifactConfig: ArtifactConfig;
@@ -217,17 +240,24 @@ interface AsyncSingleParams {
217
240
  reads?: string[] | false;
218
241
  outputMode?: "inline" | "file-only";
219
242
  outputBaseDir?: string;
243
+ outputClaimPath?: string;
220
244
  agentContract?: AgentContract;
221
245
  structuredOutputSchema?: JsonSchemaObject;
222
246
  modelOverride?: string;
223
247
  modelOverrideFromParent?: boolean;
248
+ modelOrigin?: ModelOrigin;
249
+ fast?: boolean;
224
250
  thinkingOverride?: AgentConfig["thinking"];
225
251
  availableModels?: AvailableModelInfo[];
226
252
  maxSubagentDepth: number;
227
253
  waitToolEnabled?: boolean;
254
+ waitToolDefaultTimeoutMs?: number;
228
255
  worktreeSetupHook?: string;
229
256
  worktreeSetupHookTimeoutMs?: number;
230
257
  worktreeBaseDir?: string;
258
+ baseRef?: string;
259
+ worktreeProvider?: import("../../shared/types.ts").WorktreeProvider;
260
+ worktreeBranchPrefix?: string;
231
261
  worktree?: boolean;
232
262
  controlConfig?: ResolvedControlConfig;
233
263
  intercomBridge?: IntercomBridgeConfig;
@@ -239,7 +269,6 @@ interface AsyncSingleParams {
239
269
  absoluteDeadlineAt?: number;
240
270
  /** Optional per-call hard toolTimeoutMs override (highest precedence). */
241
271
  toolTimeoutMs?: number;
242
- turnBudget?: { maxTurns: number; graceTurns?: number };
243
272
  toolBudget?: ResolvedToolBudget | ToolBudgetConfig;
244
273
  usageBudget?: UsageBudgetConfig;
245
274
  configToolBudget?: ResolvedToolBudget;
@@ -249,10 +278,21 @@ interface AsyncSingleParams {
249
278
  toolTimeoutMsEnv?: string | undefined;
250
279
  allowZeroToolBudget?: boolean;
251
280
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
281
+ thinkingCeiling?: ThinkingLevel;
252
282
  runFanoutBudget?: RunFanoutBudgetDescriptor;
253
283
  parentWorkflowRunId?: string;
254
284
  workflowKey?: string;
285
+ lane?: WorkflowLaneMetadata;
286
+ workflowAwaitAsync?: boolean;
255
287
  activeAsyncCapacity?: ActiveAsyncCapacityHandle;
288
+ externalJobFollowUp?: {
289
+ sourceRunId: string;
290
+ sourceStepIndex: number;
291
+ parentProviderJobId: string;
292
+ requestId: string;
293
+ requestDigest: string;
294
+ };
295
+ extensionBindings?: ExtensionBindings;
256
296
  }
257
297
 
258
298
  interface AsyncExecutionResult {
@@ -267,6 +307,8 @@ export interface AsyncRunnerStepBuildParams {
267
307
  attachRoot?: ImportedAsyncRoot & { agent: string; outputName?: string; label?: string };
268
308
  resultMode?: SubagentRunMode;
269
309
  agents: AgentConfig[];
310
+ /** Exact discovery provenance for failed resolution; omission triggers defensive fallback discovery. */
311
+ unknownAgentDiagnosticContext?: UnknownAgentDiagnosticContext;
270
312
  ctx: AsyncExecutionContext;
271
313
  availableModels?: AvailableModelInfo[];
272
314
  cwd?: string;
@@ -279,10 +321,14 @@ export interface AsyncRunnerStepBuildParams {
279
321
  dynamicFanoutMaxItems?: number;
280
322
  maxSubagentDepth: number;
281
323
  waitToolEnabled?: boolean;
324
+ waitToolDefaultTimeoutMs?: number;
282
325
  worktreeBaseDir?: string;
326
+ worktreeProvider?: import("../../shared/types.ts").WorktreeProvider;
327
+ worktreeBranchPrefix?: string;
283
328
  asyncDir: string;
284
329
  outputBaseDir?: string;
285
330
  validateOutputBindings?: boolean;
331
+ fast?: boolean;
286
332
  toolBudget?: ResolvedToolBudget;
287
333
  configToolBudget?: ResolvedToolBudget;
288
334
  /** Optional per-call hard toolTimeoutMs override from the subagent invocation. */
@@ -292,6 +338,7 @@ export interface AsyncRunnerStepBuildParams {
292
338
  /** PI_SUBAGENT_TOOL_TIMEOUT_MS override (lowest precedence). */
293
339
  toolTimeoutMsEnv?: string | undefined;
294
340
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
341
+ thinkingCeiling?: ThinkingLevel;
295
342
  }
296
343
 
297
344
  export type AsyncRunnerStepBuildResult =
@@ -308,15 +355,15 @@ export function formatAsyncStartedMessage(headline: string, interactive: boolean
308
355
  const guidance = interactive
309
356
  ? [
310
357
  "The async run is detached and running in the background.",
311
- "You are in an interactive session. By default, return control to the user now; Pi will wake you on completion when the run finishes or needs attention. Do NOT call subagent_wait() merely to wait, and do not run sleep/polling loops to wait for it.",
312
- "When you need an explicit wake for one known run but do not need same-turn results, call subagent_wait({ id: \"...\", nonBlocking: true }) to arm a subscription and return immediately.",
313
- "Override the default and call blocking subagent_wait() before ending the turn only when the current request is run-to-completion — for example, the user asked you to report results back here before continuing, or a skill must finish in one turn. In that case, call subagent_wait() to block until the run completes so its results are delivered in this turn instead of deferred.",
358
+ "You are in an interactive session. Return control to the user now; Pi will wake you through the native completion notification when this subagent completes or needs attention. Do not run sleep/polling loops to wait for this async subagent; it does not need a wait call.",
359
+ "Use bg_wait only for provider, detached, or other background work that lacks a native completion notification.",
360
+ "If the current turn must receive results from work without a native notification before it ends, call blocking bg_wait(); ordinary async subagent runs do not need a wait call because their completion is delivered natively.",
314
361
  "Otherwise, continue any independent work or return control to the user. Use subagent({ action: \"status\", id: \"...\" }) for a one-shot status/result or to inspect a blocked/stale run, never as a wait loop.",
315
362
  ]
316
363
  : [
317
364
  "The async run is detached. Do not run sleep timers or polling loops just to wait for it.",
318
- "This is a non-interactive run: Pi auto-drains current-session background work at agent_end so detached children are not abandoned; call subagent_wait() when this turn must receive the run's results before it ends, otherwise let the headless auto-drain finish the work.",
319
- "Use subagent({ action: \"status\", id: \"...\" }) when you need a one-shot status/result or to inspect a blocked/stale run. To block until completion, use subagent_wait() — do not poll in a loop.",
365
+ "This is a non-interactive run: Pi auto-drains current-session subagent work at agent_end so detached children are not abandoned. Use bg_wait only when this turn must receive provider, detached, or other background-work results that have no native completion notification.",
366
+ "Use subagent({ action: \"status\", id: \"...\" }) when you need a one-shot status/result or to inspect a blocked/stale run; do not poll in a loop.",
320
367
  ];
321
368
  return [headline, "", ...guidance].join("\n");
322
369
  }
@@ -400,13 +447,15 @@ function waitForRunnerStartup(startupPath: string, expectedState: RunnerStartupS
400
447
  return { ok: false, error: `Timed out after ${timeoutMs}ms waiting for the async runner startup state '${expectedState}'.`, startupDidNotProceed: true };
401
448
  }
402
449
 
450
+ const writePrivateStartupControlJson = createAtomicJsonWriter({ mode: 0o600, ignoreCleanupErrorAfterSuccess: true });
451
+
403
452
  function writeRunnerStartupControl(filePath: string, payload: { action: "ack" | "proceed"; token: string }): void {
404
453
  // Delegate to the shared atomic JSON writer (temp file + rename, retrying
405
454
  // transient Windows EPERM/EBUSY/EACCES locks and cleaning up the temp file
406
455
  // on failure), so the startup handshake gets the same locking resilience as
407
456
  // every other async control/result file. This is exercised by
408
457
  // test/unit/atomic-json.test.ts.
409
- writePrivateAtomicJson(filePath, payload);
458
+ writePrivateStartupControlJson(filePath, payload);
410
459
  }
411
460
 
412
461
  function runnerIsAlive(pid: number): boolean {
@@ -475,25 +524,41 @@ interface SpawnRunnerResult {
475
524
  startupDidNotProceed?: boolean;
476
525
  }
477
526
 
478
- function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal?: (proof: unknown) => void): SpawnRunnerResult {
527
+ function isStaleExtensionContextError(error: unknown): boolean {
528
+ return error instanceof Error && /extension ctx is stale|stale after session replacement or reload/i.test(error.message);
529
+ }
530
+
531
+ export function emitProcessTerminalEvent(ctx: AsyncExecutionContext, proof: unknown): void {
532
+ try {
533
+ ctx.pi.events.emit(SUBAGENT_PROCESS_TERMINAL_EVENT, proof);
534
+ } catch (error) {
535
+ if (isStaleExtensionContextError(error)) return;
536
+ console.error("Failed to emit subagent process-terminal event:", error);
537
+ }
538
+ }
539
+
540
+ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Omit<AsyncStatus, "pid" | "processTerminal">, initialStatusPath: string, onProcessTerminal?: (proof: unknown) => void, onBeforeProceed?: (runnerProcessInstanceId: string) => void, requestedCwd = cwd): SpawnRunnerResult {
541
+ const cwdError = preflightLaunchCwd(requestedCwd, cwd);
542
+ if (cwdError) return { error: cwdError };
543
+
479
544
  if (!jitiCliPath) {
480
545
  return { error: "upstream jiti for TypeScript execution could not be found; ensure package dependencies are installed" };
481
546
  }
482
-
483
- try {
484
- const cwdStats = fs.statSync(cwd);
485
- if (!cwdStats.isDirectory()) {
486
- return { error: `cwd is not a directory: ${cwd}` };
487
- }
488
- } catch {
489
- return { error: `cwd does not exist: ${cwd}` };
547
+ if (!piPackageRoot) {
548
+ return { error: `Background children require pi installed as the npm package (${PI_CODING_AGENT_PACKAGE}); a standalone pi binary has no package directory, so the async runner cannot create child sessions. Run this child in the foreground (async: false) or install pi from npm.` };
549
+ }
550
+ const hostPeerAliases = resolveHostPeerAliases(piPackageRoot);
551
+ if (hostPeerAliases.missing.length > 0) {
552
+ return { error: `Background children require pi installed as the npm package (${PI_CODING_AGENT_PACKAGE}) with its dependencies; ${piPackageRoot} does not provide ${hostPeerAliases.missing.join(", ")}, so the async runner cannot create child sessions. A standalone pi binary cannot run background children.` };
490
553
  }
491
554
 
492
555
  fs.mkdirSync(TEMP_ROOT_DIR, { recursive: true });
493
556
  const cfgPath = getAsyncConfigPath(suffix);
494
557
  const runnerProcessInstanceId = randomUUID();
495
- const launchConfig = { ...cfg, runnerProcessInstanceId };
496
- fs.writeFileSync(cfgPath, JSON.stringify(launchConfig));
558
+ const hasRevivalLease = typeof (cfg as { revivalLease?: unknown }).revivalLease === "object";
559
+ const launchBarrierToken = hasRevivalLease ? undefined : runnerProcessInstanceId;
560
+ const launchConfig = { ...cfg, runnerProcessInstanceId, ...(launchBarrierToken ? { launchBarrierToken } : {}) };
561
+ writePrivateAtomicJson(cfgPath, launchConfig);
497
562
  const runner = path.join(path.dirname(fileURLToPath(import.meta.url)), "subagent-runner.ts");
498
563
  const nodeCommand = resolveNodeExecutable();
499
564
  const launchForStartup = launchConfig as typeof launchConfig & { asyncDir?: unknown; id?: unknown; sessionId?: unknown; completionOwnerId?: unknown; revivalLease?: unknown };
@@ -505,7 +570,9 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal
505
570
  ? path.join(launchAsyncDir, "runner-startup.json")
506
571
  : undefined;
507
572
  const startupAckPath = startupPath ? path.join(path.dirname(startupPath), "runner-startup-ack.json") : undefined;
508
- const startupProceedPath = startupPath ? path.join(path.dirname(startupPath), "runner-startup-proceed.json") : undefined;
573
+ const startupProceedPath = launchAsyncDir && (startupPath || launchBarrierToken)
574
+ ? path.join(launchAsyncDir, "runner-startup-proceed.json")
575
+ : undefined;
509
576
  if (startupPath) fs.rmSync(startupPath, { force: true });
510
577
  if (startupAckPath) fs.rmSync(startupAckPath, { force: true });
511
578
  if (startupProceedPath) fs.rmSync(startupProceedPath, { force: true });
@@ -521,12 +588,12 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal
521
588
  }
522
589
  const proc = spawn(nodeCommand, [jitiCliPath, runner, cfgPath], {
523
590
  cwd,
524
- detached: true,
591
+ ...backgroundProcessOptions(),
525
592
  stdio: ["ignore", stdoutFd ?? "ignore", stderrFd ?? "ignore"],
526
- windowsHide: true,
527
593
  env: {
528
- ...process.env,
529
- ...(piPackageRoot ? { [PI_CODING_AGENT_PACKAGE_ROOT_ENV]: piPackageRoot } : {}),
594
+ ...omitExtensionBindingsEnv(process.env),
595
+ [PI_CODING_AGENT_PACKAGE_ROOT_ENV]: piPackageRoot,
596
+ [JITI_ALIAS_ENV]: JSON.stringify(hostPeerAliases.aliases),
530
597
  },
531
598
  });
532
599
  closeFd(stdoutFd);
@@ -587,6 +654,45 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal
587
654
  if (typeof proc.pid !== "number") {
588
655
  return { error: `async runner did not produce a pid for cwd: ${cwd}` };
589
656
  }
657
+ try {
658
+ writePrivateAtomicJson(initialStatusPath, {
659
+ ...initialStatus,
660
+ pid: proc.pid,
661
+ processTerminal: { version: 1, state: "pending", runId: initialStatus.runId, runnerProcessInstanceId },
662
+ });
663
+ } catch (error) {
664
+ const message = `Failed to persist initial async status: ${error instanceof Error ? error.message : String(error)}`;
665
+ if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
666
+ const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
667
+ return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
668
+ }
669
+ try {
670
+ if (!launchAsyncDir) throw new Error("Async runner is missing its lifecycle directory.");
671
+ initializeProcessTerminal(launchAsyncDir, launchRunId, runnerProcessInstanceId);
672
+ } catch (error) {
673
+ const message = `Failed to establish async runner lifecycle sidecar: ${error instanceof Error ? error.message : String(error)}`;
674
+ if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
675
+ const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
676
+ return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
677
+ }
678
+ try {
679
+ onBeforeProceed?.(runnerProcessInstanceId);
680
+ } catch (error) {
681
+ const message = `Failed to establish async runner capacity ownership: ${error instanceof Error ? error.message : String(error)}`;
682
+ if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
683
+ const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
684
+ return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
685
+ }
686
+ if (launchBarrierToken && startupProceedPath) {
687
+ try {
688
+ writeRunnerStartupControl(startupProceedPath, { action: "proceed", token: launchBarrierToken });
689
+ } catch (error) {
690
+ const message = `Failed to authorize async runner startup: ${error instanceof Error ? error.message : String(error)}`;
691
+ if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
692
+ const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
693
+ return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
694
+ }
695
+ }
590
696
  proc.unref();
591
697
  if (startupPath && startupAckPath && startupProceedPath) {
592
698
  const persistStartupFailure = (message: string) => {
@@ -657,6 +763,8 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
657
763
  thinkingOverridesByFlatIndex,
658
764
  maxSubagentDepth,
659
765
  worktreeBaseDir,
766
+ worktreeProvider,
767
+ worktreeBranchPrefix,
660
768
  asyncDir,
661
769
  } = params;
662
770
  const outputBaseDir = params.outputBaseDir;
@@ -664,6 +772,15 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
664
772
  const chainSkills = params.chainSkills ?? [];
665
773
  const availableModels = params.availableModels;
666
774
  const runnerCwd = resolveChildCwd(ctx.cwd, cwd);
775
+ let managedWorktreeProvider: "native" | "worktrunk" | undefined;
776
+ try {
777
+ if (chain.some((step) => "worktree" in step && step.worktree === true)) {
778
+ const resolved = resolveWorktreeProvider(worktreeProvider, worktreeBaseDir);
779
+ managedWorktreeProvider = shouldDeferWorktreeCwd(worktreeProvider, worktreeBaseDir) ? "worktrunk" : resolved;
780
+ }
781
+ } catch (error) {
782
+ return { error: error instanceof Error ? error.message : String(error) };
783
+ }
667
784
  const progressDir = params.progressDir ?? runnerCwd;
668
785
  const graphChain: ChainStep[] = params.attachRoot
669
786
  ? [{
@@ -691,6 +808,8 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
691
808
  }
692
809
  const workflowGraph = buildWorkflowGraphSnapshot({ runId: id, mode: resultMode, steps: graphChain });
693
810
 
811
+ const diagnosticContext = params.unknownAgentDiagnosticContext
812
+ ?? unknownAgentDiagnosticContext(discoverAgents(path.resolve(runnerCwd), "both"));
694
813
  for (const s of chain) {
695
814
  const stepAgents = isParallelStep(s)
696
815
  ? s.parallel.map((t) => t.agent)
@@ -698,9 +817,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
698
817
  ? [s.parallel.agent]
699
818
  : [(s as SequentialStep).agent];
700
819
  for (const agentName of stepAgents) {
701
- if (!agents.find((x) => x.name === agentName)) {
702
- return { error: `Unknown agent: ${agentName}` };
703
- }
820
+ if (!agents.find((x) => x.name === agentName)) return { error: formatUnknownAgentError(agentName, diagnosticContext) };
704
821
  }
705
822
  }
706
823
 
@@ -714,6 +831,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
714
831
  ...(s.progress !== undefined ? { progress: s.progress } : {}),
715
832
  ...(stepSkillInput !== undefined ? { skills: stepSkillInput } : {}),
716
833
  ...(s.model !== undefined ? { model: s.model } : {}),
834
+ ...(s.fast !== undefined ? { fast: s.fast } : {}),
717
835
  };
718
836
  };
719
837
  const buildSeqStep = (s: SequentialStep, sessionFile?: string, behaviorCwd?: string, progressPrecreated = false, resolvedBehavior?: ResolvedStepBehavior, flatIndex?: number, parallelOutputNamespace?: { stepIndex: number; taskIndex?: number }, runFanoutPath?: string) => {
@@ -726,11 +844,12 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
726
844
  if (s.outputSchema !== undefined) unsupported.push("structured output");
727
845
  if (s.acceptance !== undefined || params.agentContract !== undefined || s.agentContract !== undefined) unsupported.push("acceptance/agent contract");
728
846
  if (s.toolBudget !== undefined || params.toolBudget !== undefined || a.toolBudget !== undefined || params.configToolBudget !== undefined) unsupported.push("tool budget");
847
+ if ((s.fast ?? params.fast ?? a.fast) === true) unsupported.push("fast mode");
729
848
  if (params.contextForAgent?.(s.agent) === "fork") unsupported.push("fork context");
730
849
  if (unsupported.length > 0) throw new AsyncStartValidationError(`Agent '${a.name}' uses runner.type='${externalRunnerType}' and does not support: ${unsupported.join(", ")}.`);
731
850
  }
732
851
  try {
733
- assertAgentAllowedByCapabilityCeiling(a.name, intersectSubagentCapabilityCeilings(params.capabilityCeiling, decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV])));
852
+ assertAgentAllowedByCapabilityCeiling(a.name, intersectSubagentCapabilityCeilings(params.capabilityCeiling, ctx.childRuntime?.capabilityCeiling));
734
853
  } catch (error) {
735
854
  throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
736
855
  }
@@ -744,19 +863,21 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
744
863
  envValue: params.toolTimeoutMsEnv ?? toolTimeoutFromEnv(),
745
864
  });
746
865
  if (resolvedToolTimeout.error) throw new AsyncStartValidationError(resolvedToolTimeout.error);
747
- const stepCwd = resolveChildCwd(runnerCwd, s.cwd);
748
- const instructionCwd = behaviorCwd ?? stepCwd;
749
- const readExistenceCwd = behaviorCwd ? stepCwd : instructionCwd;
750
- let behavior = suppressProgressForReadOnlyTask(resolvedBehavior ?? resolveStepBehavior(a, buildStepOverrides(s), chainSkills), s.task, originalTask);
751
- const inheritedRelativeParallelOutput = parallelOutputNamespace && s.output === undefined && typeof behavior.output === "string" && !path.isAbsolute(behavior.output);
752
- if (inheritedRelativeParallelOutput && parallelOutputNamespace.taskIndex !== undefined) {
753
- behavior = {
754
- ...behavior,
755
- output: path.join(`parallel-${parallelOutputNamespace.stepIndex}`, `${parallelOutputNamespace.taskIndex}-${s.agent}`, behavior.output as string),
756
- };
757
- }
758
- const namespaceOutputPath = Boolean(inheritedRelativeParallelOutput && parallelOutputNamespace.taskIndex === undefined);
759
- const skillNames = behavior.skills === false ? [] : behavior.skills;
866
+ const launchPlan = planChildLaunch({
867
+ agentConfig: a,
868
+ stepOverrides: buildStepOverrides(s),
869
+ task: s.task,
870
+ originalTask,
871
+ runnerCwd,
872
+ runtimeCwd: ctx.cwd,
873
+ stepCwdInput: s.cwd,
874
+ behaviorCwd,
875
+ chainSkills,
876
+ outputBaseDir,
877
+ parallelOutputNamespace,
878
+ resolvedBehavior,
879
+ });
880
+ const { stepCwd, instructionCwd, readExistenceCwd, behavior, namespaceOutputPath, outputPath, skillNames } = launchPlan;
760
881
  const { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(
761
882
  skillNames,
762
883
  stepCwd,
@@ -781,45 +902,100 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
781
902
  const isFirstProgressAgent = behavior.progress && !progressPrecreated && !progressInstructionCreated;
782
903
  if (behavior.progress) progressInstructionCreated = true;
783
904
  const progressInstructions = buildChainInstructions({ ...behavior, output: false, reads: false }, progressDir, isFirstProgressAgent);
784
- const outputPath = resolveSingleOutputPath(behavior.output, ctx.cwd, instructionCwd, outputBaseDir);
785
905
  if (!namespaceOutputPath) systemPrompt = injectOutputPathSystemPrompt(systemPrompt, outputPath, a);
786
906
  const validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Async step (${s.agent})`);
787
907
  if (validationError) throw new AsyncStartValidationError(validationError);
788
908
  let taskTemplate = s.task ?? "{previous}";
789
909
  taskTemplate = taskTemplate.replace(/\{task\}/g, originalTask ?? "");
790
- taskTemplate = taskTemplate.replace(/\{chain_dir\}/g, runnerCwd);
910
+ taskTemplate = taskTemplate.replace(/\{chain_dir\}/g, behaviorCwd ?? runnerCwd);
791
911
  const taskText = `${readInstructions.prefix}${taskTemplate}${progressInstructions.suffix}`;
792
912
  const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a);
793
913
 
914
+ const modelScopes = resolveModelScopesForAgent(ctx.modelScope, a.name, ctx.currentModel);
915
+ const modelOrigin = resolveModelOrigin({ explicitModel: s.model, agentModel: a.model, parentModel: ctx.currentModel });
916
+ const primaryModelFromParent = modelOrigin === "inherited";
794
917
  const primaryModel = externalRunner ? undefined : resolveEffectiveSubagentModel(
795
918
  s.model,
796
919
  a.model,
797
920
  ctx.currentModel,
798
921
  availableModels,
799
- ctx.currentModelProvider,
800
- { scope: ctx.modelScope },
922
+ a.modelProvider ?? ctx.currentModelProvider,
923
+ { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" },
801
924
  );
802
925
  const thinkingOverride = flatIndex === undefined ? undefined : thinkingOverridesByFlatIndex?.[flatIndex];
803
926
  const effectiveThinking = externalRunner ? undefined : thinkingOverride ?? a.thinking;
804
927
  const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinking, thinkingOverride !== undefined);
928
+ const contextLimit = model ? findModelInfo(model, availableModels, a.modelProvider ?? ctx.currentModelProvider)?.contextWindow : undefined;
929
+ const thinkingCeiling = externalRunner ? undefined : intersectThinkingCeilings(
930
+ params.thinkingCeiling,
931
+ a.maxThinking,
932
+ ctx.childRuntime?.thinkingCeiling,
933
+ );
934
+ if (!externalRunner) {
935
+ try {
936
+ assertThinkingWithinCeiling({ model, configThinking: effectiveThinking, ceiling: thinkingCeiling, agent: a.name, runId: id });
937
+ } catch (error) {
938
+ throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
939
+ }
940
+ }
805
941
  const agentContract = s.agentContract ?? params.agentContract;
942
+ const permissionRules = resolvePermissionRules(ctx.permissions, a.permissions);
943
+ let modelCandidates: string[] = [];
944
+ if (!externalRunner) {
945
+ try {
946
+ modelCandidates = buildModelCandidates(primaryModel, a.fallbackModels, availableModels, a.modelProvider ?? ctx.currentModelProvider, {
947
+ scope: modelScopes,
948
+ primaryModelFromParent,
949
+ origin: modelOrigin,
950
+ }).flatMap((candidate) => {
951
+ const resolved = applyThinkingSuffix(candidate, effectiveThinking, thinkingOverride !== undefined);
952
+ return resolved ? [resolved] : [];
953
+ });
954
+ for (const candidate of modelCandidates) assertThinkingWithinCeiling({ model: candidate, configThinking: effectiveThinking, ceiling: thinkingCeiling, agent: a.name, runId: id });
955
+ } catch (error) {
956
+ throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
957
+ }
958
+ }
959
+ const launchRuleError = applyWatchdogLaunchRules({ cwd: stepCwd, agent: a.name, model: modelCandidates[0] ?? model, warn: (violation) => sendRuleViolationWarning(ctx.pi, violation) });
960
+ if (launchRuleError) throw new AsyncStartValidationError(launchRuleError);
961
+ const fast = s.fast ?? params.fast ?? a.fast;
806
962
  const toolPlan = resolvePiLaunchToolPlan({
807
963
  tools: a.tools,
964
+ excludeTools: a.excludeTools,
965
+ allowNestedSubagents: a.allowNestedSubagents,
808
966
  extensions: a.extensions,
809
967
  subagentOnlyExtensions: a.subagentOnlyExtensions,
810
968
  mcpDirectTools: a.mcpDirectTools,
811
969
  cwd: stepCwd,
812
970
  requireReadTool: Boolean(resolvedSkills.length),
813
971
  structuredOutput: Boolean(s.outputSchema),
972
+ fast,
973
+ model,
974
+ modelCandidates,
814
975
  capabilityCeiling: params.capabilityCeiling,
815
- inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
976
+ inheritedCapabilityCeiling: ctx.childRuntime?.capabilityCeiling,
816
977
  agentName: a.name,
978
+ permissionRules,
979
+ runtimeSnapshotHost: ctx.pi,
817
980
  });
818
981
  const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
819
- const permissionRules = resolvePermissionRules(ctx.permissions, a.permissions);
820
982
  if (externalRunner && permissionRules) {
821
983
  throw new AsyncStartValidationError(`Agent '${a.name}' uses runner.type='${externalRunnerType}', which cannot enforce native Pi child permission rules.`);
822
984
  }
985
+ if (!externalRunner) {
986
+ const contractTools = toolPlan.explicitToolAllowlist ? toolPlan.effectiveToolAllowlist : undefined;
987
+ const contractError = validateImplementationToolContract({
988
+ agent: a.name,
989
+ task,
990
+ tools: contractTools,
991
+ mcpDirectTools: toolPlan.effectiveMcpTools,
992
+ configuredExtensions: toolPlan.configuredExtensions,
993
+ requestedTools: toolPlan.requestedBuiltinTools,
994
+ acceptanceRole: a.acceptanceRole,
995
+ completionGuard: a.completionGuard,
996
+ });
997
+ if (contractError) throw new AsyncStartValidationError(contractError);
998
+ }
823
999
  return {
824
1000
  parentSessionId: ctx.parentSessionId ?? ctx.currentSessionId,
825
1001
  permissionRules,
@@ -835,23 +1011,28 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
835
1011
  outputName: s.as,
836
1012
  structured: Boolean(s.outputSchema),
837
1013
  cwd: stepCwd,
1014
+ requestedCwd: s.cwd ?? stepCwd,
838
1015
  model,
1016
+ ...(contextLimit !== undefined ? { contextLimit } : {}),
1017
+ ...(fast !== undefined ? { fast } : {}),
839
1018
  thinking: resolveEffectiveThinking(model, effectiveThinking),
1019
+ ...(thinkingCeiling ? { thinkingCeiling } : {}),
840
1020
  launchResolvedExtensions,
841
- modelCandidates: externalRunner ? undefined : buildModelCandidates(primaryModel, a.fallbackModels, availableModels, ctx.currentModelProvider, {
842
- scope: ctx.modelScope,
843
- primaryModelFromParent: inheritsParentModel(s.model, a.model, ctx.currentModel),
844
- }).map((candidate) =>
845
- applyThinkingSuffix(candidate, effectiveThinking, thinkingOverride !== undefined),
846
- ),
1021
+ modelCandidates: externalRunner ? undefined : modelCandidates,
1022
+ ...(primaryModelFromParent ? { skipPrimaryModelVerification: true } : {}),
1023
+ ...(availableModels && availableModels.length > 0 ? { modelVerificationRegistry: availableModels } : {}),
847
1024
  tools: a.tools,
1025
+ excludeTools: a.excludeTools,
1026
+ allowNestedSubagents: a.allowNestedSubagents,
848
1027
  extensions: a.extensions,
849
1028
  subagentOnlyExtensions: a.subagentOnlyExtensions,
850
1029
  mcpDirectTools: a.mcpDirectTools,
1030
+ mutationTools: a.mutationTools,
851
1031
  completionGuard: a.completionGuard,
852
1032
  systemPrompt,
853
1033
  systemPromptMode: a.systemPromptMode,
854
1034
  inheritProjectContext: a.inheritProjectContext,
1035
+ inheritGlobalContext: a.inheritGlobalContext,
855
1036
  inheritSkills: a.inheritSkills,
856
1037
  skills: resolvedSkills.map((r) => r.name),
857
1038
  outputPath,
@@ -862,6 +1043,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
862
1043
  timeoutMs: a.defaultTimeoutMs ?? DEFAULT_ASYNC_TIMEOUT_MS,
863
1044
  toolTimeoutMs: resolvedToolTimeout.toolTimeoutMs,
864
1045
  waitToolEnabled: params.waitToolEnabled,
1046
+ waitToolDefaultTimeoutMs: params.waitToolDefaultTimeoutMs,
865
1047
  effectiveAcceptance: resolveEffectiveAcceptance({
866
1048
  explicit: s.acceptance,
867
1049
  agentName: s.agent,
@@ -876,7 +1058,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
876
1058
  acceptanceRole: a.acceptanceRole,
877
1059
  ...(s.gateOn ? { gateOn: s.gateOn } : {}),
878
1060
  ...(s.outputSchema ? { structuredOutputSchema: s.outputSchema } : {}),
879
- ...(s.outputSchema ? { structuredOutput: createStructuredOutputRuntime(s.outputSchema, path.join(asyncDir, "structured-output")) } : {}),
1061
+ ...(s.outputSchema ? { structuredOutput: createStructuredOutputRuntime(s.outputSchema, path.join(asyncDir, "structured-output"), { acceptanceReport: resolveAcceptanceReportMode(s.acceptance) }) } : {}),
880
1062
  ...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),
881
1063
  ...(s.worktree ? { worktree: true } : {}),
882
1064
  };
@@ -910,7 +1092,9 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
910
1092
  return {
911
1093
  parallel: s.parallel.map((t, taskIndex) => {
912
1094
  let behaviorCwd: string | undefined;
913
- if (s.worktree) {
1095
+ if (s.worktree && managedWorktreeProvider === "worktrunk") {
1096
+ behaviorCwd = WORKTREE_AGENT_CWD_PLACEHOLDER;
1097
+ } else if (s.worktree && managedWorktreeProvider === "native") {
914
1098
  try {
915
1099
  behaviorCwd = resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s${stepIndex}`, taskIndex, worktreeBaseDir);
916
1100
  } catch {
@@ -960,11 +1144,14 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
960
1144
  acceptanceRole: agent.acceptanceRole,
961
1145
  ...(s.agentContract ?? params.agentContract ? { agentContract: s.agentContract ?? params.agentContract } : {}),
962
1146
  ...(s.gateOn ? { gateOn: s.gateOn } : {}),
1147
+ ...(parallel.thinkingCeiling ? { thinkingCeiling: parallel.thinkingCeiling } : {}),
963
1148
  };
964
1149
  }
965
1150
  const sequential = s as SequentialStep;
966
1151
  let behaviorCwd: string | undefined;
967
- if (sequential.worktree) {
1152
+ if (sequential.worktree && managedWorktreeProvider === "worktrunk") {
1153
+ behaviorCwd = WORKTREE_AGENT_CWD_PLACEHOLDER;
1154
+ } else if (sequential.worktree && managedWorktreeProvider === "native") {
968
1155
  try {
969
1156
  behaviorCwd = resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s${stepIndex}`, 0, worktreeBaseDir);
970
1157
  } catch {
@@ -987,6 +1174,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
987
1174
  index: params.attachRoot.index,
988
1175
  },
989
1176
  inheritProjectContext: false,
1177
+ inheritGlobalContext: false,
990
1178
  inheritSkills: false,
991
1179
  }, ...builtSteps]
992
1180
  : builtSteps;
@@ -1033,6 +1221,9 @@ export function executeAsyncChain(
1033
1221
  worktreeSetupHook,
1034
1222
  worktreeSetupHookTimeoutMs,
1035
1223
  worktreeBaseDir,
1224
+ baseRef,
1225
+ worktreeProvider,
1226
+ worktreeBranchPrefix,
1036
1227
  controlConfig,
1037
1228
  controlIntercomTarget,
1038
1229
  childIntercomTarget,
@@ -1043,13 +1234,13 @@ export function executeAsyncChain(
1043
1234
  chain: chain.map((step) => {
1044
1235
  if (isParallelStep(step)) return { parallel: step.parallel };
1045
1236
  if (isDynamicParallelStep(step)) return { acceptance: step.acceptance, parallel: step.parallel };
1046
- return { acceptance: step.acceptance };
1237
+ return { acceptance: step.acceptance, outputSchema: step.outputSchema };
1047
1238
  }),
1048
1239
  });
1049
1240
  if (acceptanceErrors.length > 0) return formatAsyncStartError(resultMode, acceptanceErrors.join(" "));
1050
1241
  const capabilityCeiling = params.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(ctx.currentSessionId);
1051
- const inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();
1052
- const nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;
1242
+ const inheritedNestedRoute = inheritedNestedRouteOf(ctx.childRuntime);
1243
+ const nestedAddress = inheritedNestedRoute ? inheritedNestedParentAddressOf(ctx.childRuntime) : undefined;
1053
1244
  const asyncDir = inheritedNestedRoute
1054
1245
  ? path.join(TEMP_ROOT_DIR, "nested-subagent-runs", inheritedNestedRoute.rootRunId, id)
1055
1246
  : path.join(DIRS.async, id);
@@ -1073,6 +1264,7 @@ export function executeAsyncChain(
1073
1264
  attachRoot: params.attachRoot,
1074
1265
  resultMode,
1075
1266
  agents,
1267
+ unknownAgentDiagnosticContext: params.unknownAgentDiagnosticContext,
1076
1268
  ctx,
1077
1269
  availableModels: params.availableModels,
1078
1270
  cwd,
@@ -1086,14 +1278,19 @@ export function executeAsyncChain(
1086
1278
  dynamicFanoutMaxItems: params.dynamicFanoutMaxItems,
1087
1279
  maxSubagentDepth,
1088
1280
  waitToolEnabled: params.waitToolEnabled,
1281
+ waitToolDefaultTimeoutMs: params.waitToolDefaultTimeoutMs,
1089
1282
  worktreeBaseDir,
1283
+ worktreeProvider,
1284
+ worktreeBranchPrefix,
1090
1285
  asyncDir,
1286
+ fast: params.fast,
1091
1287
  toolBudget: params.toolBudget,
1092
1288
  configToolBudget: params.configToolBudget,
1093
1289
  callToolTimeoutMs: params.callToolTimeoutMs,
1094
1290
  configToolTimeoutMs: params.configToolTimeoutMs,
1095
1291
  toolTimeoutMsEnv: params.toolTimeoutMsEnv ?? toolTimeoutFromEnv(),
1096
1292
  capabilityCeiling,
1293
+ thinkingCeiling: params.thinkingCeiling,
1097
1294
  });
1098
1295
  if ("error" in built) {
1099
1296
  try {
@@ -1105,7 +1302,6 @@ export function executeAsyncChain(
1105
1302
  }
1106
1303
  const { steps, runnerCwd, workflowGraph, eventChain } = built;
1107
1304
  const deadlineAt = params.timeoutMs !== undefined ? Date.now() + params.timeoutMs : undefined;
1108
- const initialTurnBudget = params.turnBudget ? initialTurnBudgetState(params.turnBudget) : undefined;
1109
1305
  const initialUsageBudget = usageBudgetState(params.usageBudget, undefined);
1110
1306
  let childTargetIndex = 0;
1111
1307
  const childIntercomTargets = childIntercomTarget ? steps.flatMap((step) => {
@@ -1122,6 +1318,21 @@ export function executeAsyncChain(
1122
1318
  }
1123
1319
  return "agent" in step ? [childIntercomTarget(step.agent, childTargetIndex++)] : [undefined];
1124
1320
  }) : undefined;
1321
+ const initialStatusSteps = eventChain.flatMap((step) => isParallelStep(step)
1322
+ ? 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" as const }))
1323
+ : isDynamicParallelStep(step)
1324
+ ? [{ agent: `expand:${step.parallel.agent}`, label: step.label ?? step.parallel.label ?? `Dynamic fanout (${step.collect.as})`, outputName: step.collect.as, status: "pending" as const }]
1325
+ : [{ agent: (step as SequentialStep).agent, ...(statusStepDescription((step as SequentialStep).task) ? { description: statusStepDescription((step as SequentialStep).task) } : {}), ...((step as SequentialStep).label ? { label: (step as SequentialStep).label } : {}), ...((step as SequentialStep).as ? { outputName: (step as SequentialStep).as } : {}), status: "pending" as const }]);
1326
+ const initialParallelGroups: AsyncParallelGroupStatus[] = [];
1327
+ let initialFlatIndex = 0;
1328
+ for (let stepIndex = 0; stepIndex < eventChain.length; stepIndex++) {
1329
+ const step = eventChain[stepIndex]!;
1330
+ if (isParallelStep(step)) initialParallelGroups.push({ start: initialFlatIndex, count: step.parallel.length, stepIndex });
1331
+ else if (isDynamicParallelStep(step)) initialParallelGroups.push({ start: initialFlatIndex, count: 1, stepIndex });
1332
+ initialFlatIndex += isParallelStep(step) ? step.parallel.length : 1;
1333
+ }
1334
+ const initialStatusAt = Date.now();
1335
+ const initialCompletionOwnerId = ctx.completionOwnerId ?? currentCompletionOwnerId();
1125
1336
 
1126
1337
  let spawnResult: SpawnRunnerResult = {};
1127
1338
  try {
@@ -1142,12 +1353,15 @@ export function executeAsyncChain(
1142
1353
  completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
1143
1354
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
1144
1355
  piPackageRoot,
1145
- piArgv1: process.argv[1],
1356
+ childSessionFactoryModule: childSessionFactoryModule(),
1357
+ inheritedChildRuntime: inheritedChildRuntime(ctx.childRuntime),
1146
1358
  worktreeSetupHook,
1147
1359
  worktreeSetupHookTimeoutMs,
1148
1360
  worktreeBaseDir,
1361
+ baseRef,
1362
+ worktreeProvider,
1363
+ worktreeBranchPrefix,
1149
1364
  controlConfig,
1150
- turnBudget: params.turnBudget,
1151
1365
  toolBudget: params.toolBudget,
1152
1366
  usageBudget: params.usageBudget,
1153
1367
  controlIntercomTarget,
@@ -1171,7 +1385,23 @@ export function executeAsyncChain(
1171
1385
  },
1172
1386
  id,
1173
1387
  runnerCwd,
1174
- (proof) => ctx.pi.events.emit(SUBAGENT_PROCESS_TERMINAL_EVENT, proof),
1388
+ {
1389
+ lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
1390
+ runId: id,
1391
+ ...(ctx.currentSessionId ? { sessionId: ctx.currentSessionId } : {}),
1392
+ ...(initialCompletionOwnerId ? { completionOwnerId: initialCompletionOwnerId } : {}),
1393
+ mode: resultMode,
1394
+ state: "running",
1395
+ startedAt: initialStatusAt,
1396
+ lastUpdate: initialStatusAt,
1397
+ currentStep: 0,
1398
+ chainStepCount: eventChain.length,
1399
+ ...(initialParallelGroups.length ? { parallelGroups: initialParallelGroups } : {}),
1400
+ steps: initialStatusSteps,
1401
+ },
1402
+ path.join(asyncDir, "status.json"),
1403
+ (proof) => emitProcessTerminalEvent(ctx, proof),
1404
+ (runnerProcessInstanceId) => params.activeAsyncCapacity?.markStarted(runnerProcessInstanceId),
1175
1405
  );
1176
1406
  } catch (error) {
1177
1407
  params.activeAsyncCapacity?.rollback();
@@ -1180,7 +1410,10 @@ export function executeAsyncChain(
1180
1410
  }
1181
1411
 
1182
1412
  if (spawnResult.error) {
1183
- if (!spawnResult.pid || !spawnResult.runnerProcessInstanceId || (spawnResult.startupDidNotProceed && spawnResult.terminationObserved)) params.activeAsyncCapacity?.rollback();
1413
+ if (spawnResult.startupDidNotProceed) {
1414
+ if (!spawnResult.runnerProcessInstanceId || params.activeAsyncCapacity?.rollbackBeforeRunnerProceed(spawnResult.runnerProcessInstanceId) !== true) params.activeAsyncCapacity?.rollback();
1415
+ }
1416
+ else if (!spawnResult.pid || !spawnResult.runnerProcessInstanceId) params.activeAsyncCapacity?.rollback();
1184
1417
  else params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
1185
1418
  return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': ${spawnResult.error}`);
1186
1419
  }
@@ -1188,8 +1421,6 @@ export function executeAsyncChain(
1188
1421
  params.activeAsyncCapacity?.rollback();
1189
1422
  return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': runner identity unavailable`);
1190
1423
  }
1191
- params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
1192
-
1193
1424
  if (spawnResult.pid) {
1194
1425
  const eventFirstStep = eventChain[0];
1195
1426
  if (!eventFirstStep) {
@@ -1240,7 +1471,7 @@ export function executeAsyncChain(
1240
1471
  path: nestedAddress.path,
1241
1472
  asyncDir,
1242
1473
  pid: spawnResult.pid,
1243
- ownerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,
1474
+ ownerIntercomTarget: ctx.childRuntime?.intercomSessionName,
1244
1475
  leafIntercomTarget: childIntercomTargets?.[0],
1245
1476
  intercomTarget: childIntercomTargets?.[0],
1246
1477
  ownerState: "live",
@@ -1251,7 +1482,6 @@ export function executeAsyncChain(
1251
1482
  chainStepCount: eventChain.length,
1252
1483
  parallelGroups,
1253
1484
  ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}),
1254
- ...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),
1255
1485
  startedAt: now,
1256
1486
  lastUpdate: now,
1257
1487
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
@@ -1282,7 +1512,6 @@ export function executeAsyncChain(
1282
1512
  asyncDir,
1283
1513
  ...(sessionRoot ? { sessionRoot } : {}),
1284
1514
  ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}),
1285
- ...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),
1286
1515
  ...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}),
1287
1516
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
1288
1517
  ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
@@ -1299,7 +1528,7 @@ export function executeAsyncChain(
1299
1528
 
1300
1529
  return {
1301
1530
  content: [{ type: "text", text: formatAsyncStartedMessage(`Async ${resultMode}: ${chainDesc} [${id}]`, ctx.interactive === true) }],
1302
- 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.turnBudget ? { turnBudget: params.turnBudget } : {}), ...(params.toolBudget ? { toolBudget: params.toolBudget } : {}), ...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}) },
1531
+ 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 } : {}) },
1303
1532
  };
1304
1533
  }
1305
1534
 
@@ -1329,12 +1558,28 @@ export function executeAsyncSingle(
1329
1558
  worktreeSetupHook,
1330
1559
  worktreeSetupHookTimeoutMs,
1331
1560
  worktreeBaseDir,
1561
+ baseRef,
1562
+ worktreeProvider,
1563
+ worktreeBranchPrefix,
1332
1564
  controlConfig,
1333
1565
  controlIntercomTarget,
1334
1566
  childIntercomTarget,
1335
1567
  nestedRoute,
1336
1568
  } = params;
1569
+ let lane: WorkflowLaneMetadata | undefined;
1570
+ try {
1571
+ lane = normalizeWorkflowLaneMetadata(params.lane, "lane");
1572
+ assertWorkflowLaneKey(lane, params.workflowKey, "lane");
1573
+ } catch (error) {
1574
+ return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1575
+ }
1337
1576
  const task = params.task ?? "";
1577
+ let extensionBindings: ExtensionBindings | undefined;
1578
+ try {
1579
+ extensionBindings = normalizeExtensionBindings(params.extensionBindings)?.value;
1580
+ } catch (error) {
1581
+ return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1582
+ }
1338
1583
  const acceptanceErrors = validateAcceptanceInput(params.acceptance);
1339
1584
  if (acceptanceErrors.length > 0) return formatAsyncStartError("single", acceptanceErrors.join(" "));
1340
1585
  const externalRunner = agentConfig.runner?.type === "external-cli" || agentConfig.runner?.type === "external-job";
@@ -1343,6 +1588,7 @@ export function executeAsyncSingle(
1343
1588
  if (externalRunner) {
1344
1589
  const unsupported: string[] = [];
1345
1590
  if (params.modelOverride !== undefined) unsupported.push("model override");
1591
+ if ((params.fast ?? agentConfig.fast) === true) unsupported.push("fast mode");
1346
1592
  if (params.thinkingOverride !== undefined) unsupported.push("thinking override");
1347
1593
  if (params.structuredOutputSchema !== undefined) unsupported.push("structured output");
1348
1594
  if (params.acceptance !== undefined || params.agentContract !== undefined) unsupported.push("acceptance/agent contract");
@@ -1350,16 +1596,28 @@ export function executeAsyncSingle(
1350
1596
  if (params.context === "fork") unsupported.push("fork context");
1351
1597
  if ((params.skills?.length ?? 0) > 0) unsupported.push("skills");
1352
1598
  if (permissionRules) unsupported.push("native Pi child permissions");
1599
+ if (extensionBindings !== undefined) unsupported.push("extension bindings");
1353
1600
  if (unsupported.length > 0) return formatAsyncStartError("single", `Agent '${agentConfig.name}' uses runner.type='${externalRunnerType}' and does not support: ${unsupported.join(", ")}.`);
1354
1601
  }
1355
- const capabilityCeiling = intersectSubagentCapabilityCeilings(params.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(ctx.currentSessionId), decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]));
1602
+ const capabilityCeiling = intersectSubagentCapabilityCeilings(params.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(ctx.currentSessionId), ctx.childRuntime?.capabilityCeiling);
1356
1603
  try {
1357
1604
  assertAgentAllowedByCapabilityCeiling(agentConfig.name, capabilityCeiling);
1358
1605
  } catch (error) {
1359
1606
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1360
1607
  }
1361
1608
  const runnerCwd = resolveChildCwd(ctx.cwd, cwd);
1362
- const instructionCwd = params.worktree === true
1609
+ let managedWorktreeProvider: "native" | "worktrunk" | undefined;
1610
+ if (params.worktree === true) {
1611
+ try {
1612
+ const resolved = resolveWorktreeProvider(params.worktreeProvider, worktreeBaseDir);
1613
+ managedWorktreeProvider = shouldDeferWorktreeCwd(params.worktreeProvider, worktreeBaseDir) ? "worktrunk" : resolved;
1614
+ } catch (error) {
1615
+ return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1616
+ }
1617
+ }
1618
+ const instructionCwd = params.worktree === true && managedWorktreeProvider === "worktrunk"
1619
+ ? WORKTREE_AGENT_CWD_PLACEHOLDER
1620
+ : params.worktree === true && managedWorktreeProvider === "native"
1363
1621
  ? resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s0`, 0, worktreeBaseDir)
1364
1622
  : runnerCwd;
1365
1623
  const readExistenceCwd = params.worktree === true ? runnerCwd : instructionCwd;
@@ -1384,8 +1642,8 @@ export function executeAsyncSingle(
1384
1642
  }
1385
1643
  systemPrompt = appendAgentRefinementOverlay(systemPrompt, { cwd: runnerCwd, agentName: agentConfig.name });
1386
1644
 
1387
- const inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();
1388
- const nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;
1645
+ const inheritedNestedRoute = inheritedNestedRouteOf(ctx.childRuntime);
1646
+ const nestedAddress = inheritedNestedRoute ? inheritedNestedParentAddressOf(ctx.childRuntime) : undefined;
1389
1647
  const asyncDir = inheritedNestedRoute
1390
1648
  ? path.join(TEMP_ROOT_DIR, "nested-subagent-runs", inheritedNestedRoute.rootRunId, id)
1391
1649
  : path.join(DIRS.async, id);
@@ -1413,21 +1671,52 @@ export function executeAsyncSingle(
1413
1671
  // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
1414
1672
  // absolute paths pass through; relative paths resolve against the child cwd.
1415
1673
  const reads = params.reads !== undefined ? params.reads : agentConfig.defaultReads ?? false;
1416
- const readPaths = Array.isArray(reads) ? resolveExistingReadPaths(reads, readExistenceCwd) : [];
1674
+ const readPaths = Array.isArray(reads)
1675
+ ? managedWorktreeProvider === "worktrunk"
1676
+ ? resolveExistingReadInstructionPaths(reads, instructionCwd, readExistenceCwd)
1677
+ : resolveExistingReadPaths(reads, readExistenceCwd)
1678
+ : [];
1417
1679
  const readsInstruction = readPaths.length > 0
1418
1680
  ? `[Read from: ${readPaths.join(", ")}]\n\n`
1419
1681
  : "";
1420
1682
  const taskText = readsInstruction + taskWithOutputInstruction;
1421
- const primaryModel = externalRunner ? undefined : params.modelOverrideFromParent
1422
- ? params.modelOverride
1423
- : resolveSubagentModelOverride(
1424
- params.modelOverride ?? agentConfig.model,
1425
- ctx.currentModel,
1426
- availableModels,
1427
- ctx.currentModelProvider,
1428
- );
1683
+ const modelScopes = resolveModelScopesForAgent(ctx.modelScope, agentConfig.name, ctx.currentModel);
1684
+ const modelOrigin = resolveModelOrigin({
1685
+ fromParent: params.modelOverrideFromParent,
1686
+ storedOrigin: params.modelOrigin,
1687
+ explicitModel: params.modelOverrideFromParent ? undefined : params.modelOverride,
1688
+ agentModel: agentConfig.model,
1689
+ parentModel: ctx.currentModel,
1690
+ });
1691
+ let primaryModel: string | undefined;
1692
+ try {
1693
+ primaryModel = externalRunner ? undefined : modelOrigin === "inherited"
1694
+ ? params.modelOverride ?? (ctx.currentModel ? `${ctx.currentModel.provider}/${ctx.currentModel.id}` : undefined)
1695
+ : resolveSubagentModelOverride(
1696
+ params.modelOverride ?? agentConfig.model,
1697
+ ctx.currentModel,
1698
+ availableModels,
1699
+ ctx.currentModelProvider,
1700
+ { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" },
1701
+ );
1702
+ } catch (error) {
1703
+ return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1704
+ }
1429
1705
  const effectiveThinking = externalRunner ? undefined : params.thinkingOverride ?? agentConfig.thinking;
1430
1706
  const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinking, params.thinkingOverride !== undefined);
1707
+ const contextLimit = model ? findModelInfo(model, availableModels, agentConfig.modelProvider ?? ctx.currentModelProvider)?.contextWindow : undefined;
1708
+ const thinkingCeiling = externalRunner ? undefined : intersectThinkingCeilings(
1709
+ params.thinkingCeiling,
1710
+ agentConfig.maxThinking,
1711
+ ctx.childRuntime?.thinkingCeiling,
1712
+ );
1713
+ if (!externalRunner) {
1714
+ try {
1715
+ assertThinkingWithinCeiling({ model, configThinking: effectiveThinking, ceiling: thinkingCeiling, agent: agentConfig.name, runId: id });
1716
+ } catch (error) {
1717
+ return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1718
+ }
1719
+ }
1431
1720
  const toolBudgetInput = params.toolBudget ?? agentConfig.toolBudget ?? params.configToolBudget;
1432
1721
  const resolvedToolBudget = validateToolBudgetConfig(toolBudgetInput, params.toolBudget ? "toolBudget" : agentConfig.toolBudget ? "agent.toolBudget" : "config.toolBudget");
1433
1722
  if (resolvedToolBudget.error) return formatAsyncStartError("single", resolvedToolBudget.error);
@@ -1444,53 +1733,83 @@ export function executeAsyncSingle(
1444
1733
  });
1445
1734
  if (resolvedToolTimeout.error) return formatAsyncStartError("single", resolvedToolTimeout.error);
1446
1735
  const toolTimeoutMs = resolvedToolTimeout.toolTimeoutMs;
1447
- const initialTurnBudget = params.turnBudget ? initialTurnBudgetState(params.turnBudget) : undefined;
1448
1736
  const initialUsageBudget = usageBudgetState(params.usageBudget, undefined);
1449
1737
  const resolvedSessionDir = params.sessionDir ?? (sessionRoot ? path.join(sessionRoot, `async-${id}`) : undefined);
1450
1738
  const structuredOutput = params.structuredOutputSchema
1451
- ? createStructuredOutputRuntime(params.structuredOutputSchema, path.join(asyncDir, "structured-output"))
1739
+ ? createStructuredOutputRuntime(params.structuredOutputSchema, path.join(asyncDir, "structured-output"), { acceptanceReport: resolveAcceptanceReportMode(params.acceptance) })
1452
1740
  : undefined;
1453
- const modelCandidates = externalRunner
1454
- ? []
1455
- : buildModelCandidates(primaryModel, agentConfig.fallbackModels, availableModels, ctx.currentModelProvider, {
1456
- scope: ctx.modelScope,
1457
- primaryModelFromParent: params.modelOverrideFromParent,
1458
- })
1459
- .flatMap((candidate) => {
1741
+ let modelCandidates: string[] = [];
1742
+ if (!externalRunner) {
1743
+ try {
1744
+ modelCandidates = buildModelCandidates(primaryModel, agentConfig.fallbackModels, availableModels, agentConfig.modelProvider ?? ctx.currentModelProvider, {
1745
+ scope: modelScopes,
1746
+ primaryModelFromParent: modelOrigin === "inherited",
1747
+ origin: modelOrigin,
1748
+ }).flatMap((candidate) => {
1460
1749
  const resolved = applyThinkingSuffix(candidate, effectiveThinking, params.thinkingOverride !== undefined);
1461
1750
  return resolved ? [resolved] : [];
1462
1751
  });
1463
- const effectiveSystemPrompt = appendTurnBudgetSystemPrompt(systemPrompt, params.turnBudget);
1752
+ for (const candidate of modelCandidates) assertThinkingWithinCeiling({ model: candidate, configThinking: effectiveThinking, ceiling: thinkingCeiling, agent: agentConfig.name, runId: id });
1753
+ } catch (error) {
1754
+ return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1755
+ }
1756
+ }
1464
1757
  const toolPlan = resolvePiLaunchToolPlan({
1465
1758
  tools: agentConfig.tools,
1759
+ excludeTools: agentConfig.excludeTools,
1760
+ allowNestedSubagents: agentConfig.allowNestedSubagents,
1466
1761
  extensions: agentConfig.extensions,
1467
1762
  subagentOnlyExtensions: agentConfig.subagentOnlyExtensions,
1468
1763
  mcpDirectTools: agentConfig.mcpDirectTools,
1469
1764
  cwd: runnerCwd,
1470
1765
  requireReadTool: Boolean(resolvedSkills.length),
1471
1766
  structuredOutput: Boolean(params.structuredOutputSchema),
1767
+ fast: params.fast ?? agentConfig.fast,
1768
+ model,
1769
+ modelCandidates,
1472
1770
  capabilityCeiling,
1473
- inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
1771
+ inheritedCapabilityCeiling: ctx.childRuntime?.capabilityCeiling,
1474
1772
  agentName: agentConfig.name,
1773
+ permissionRules: resolvePermissionRules(ctx.permissions, agentConfig.permissions),
1774
+ runtimeSnapshotHost: ctx.pi,
1475
1775
  });
1476
1776
  const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
1777
+ if (!externalRunner) {
1778
+ const contractTools = toolPlan.explicitToolAllowlist ? toolPlan.effectiveToolAllowlist : undefined;
1779
+ const contractError = validateImplementationToolContract({
1780
+ agent: agentConfig.name,
1781
+ task: taskText,
1782
+ tools: contractTools,
1783
+ mcpDirectTools: toolPlan.effectiveMcpTools,
1784
+ configuredExtensions: toolPlan.configuredExtensions,
1785
+ requestedTools: toolPlan.requestedBuiltinTools,
1786
+ acceptanceRole: agentConfig.acceptanceRole,
1787
+ completionGuard: agentConfig.completionGuard,
1788
+ });
1789
+ if (contractError) return formatAsyncStartError("single", contractError);
1790
+ }
1477
1791
  const launchContractDigest = launchBindingDigest({
1478
1792
  definitionDigest: agentDefinitionDigest(agentConfig),
1479
1793
  task,
1480
1794
  ...(model ? { model } : {}),
1481
1795
  modelCandidates,
1796
+ ...((params.fast ?? agentConfig.fast) !== undefined ? { fast: params.fast ?? agentConfig.fast } : {}),
1482
1797
  ...(resolveEffectiveThinking(model, effectiveThinking) ? { thinking: resolveEffectiveThinking(model, effectiveThinking) } : {}),
1483
- systemPrompt: effectiveSystemPrompt,
1798
+ ...(thinkingCeiling ? { thinkingCeiling } : {}),
1799
+ systemPrompt,
1484
1800
  systemPromptMode: agentConfig.systemPromptMode,
1485
1801
  inheritProjectContext: agentConfig.inheritProjectContext,
1802
+ inheritGlobalContext: agentConfig.inheritGlobalContext,
1486
1803
  inheritSkills: agentConfig.inheritSkills,
1487
1804
  skills: resolvedSkills.map((skill) => skill.name),
1488
1805
  tools: toolPlan.effectiveToolAllowlist,
1806
+ ...(toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
1489
1807
  extensions: toolPlan.extensionArgs,
1490
1808
  mcpDirectTools: toolPlan.effectiveMcpTools,
1491
1809
  ...(outputPath ? { outputPath } : {}),
1492
1810
  outputMode,
1493
1811
  ...(params.structuredOutputSchema ? { structuredOutputSchema: params.structuredOutputSchema } : {}),
1812
+ ...(extensionBindings ? { extensionBindings } : {}),
1494
1813
  });
1495
1814
  const resolvedAcceptance = resolveEffectiveAcceptance({
1496
1815
  explicit: params.acceptance,
@@ -1504,7 +1823,9 @@ export function executeAsyncSingle(
1504
1823
  const recoveryAgentConfig = params.recoveryAgentConfig ?? agentConfig;
1505
1824
  const recoveryDescriptor: SteeringRecoveryDescriptor = {
1506
1825
  version: 1,
1826
+ ...(lane ? { lane } : {}),
1507
1827
  launchContractDigest,
1828
+ ...(extensionBindings ? { extensionBindings } : {}),
1508
1829
  runFanoutBudget,
1509
1830
  sourceRunId: id,
1510
1831
  ...(params.agentContract ? { agentContract: params.agentContract } : {}),
@@ -1513,16 +1834,24 @@ export function executeAsyncSingle(
1513
1834
  ...(sessionFile ? { sessionFile } : {}),
1514
1835
  cwd: runnerCwd,
1515
1836
  ...(model ? { model } : {}),
1516
- ...(params.modelOverrideFromParent ? { modelOverrideFromParent: true } : {}),
1837
+ ...(params.fast ?? recoveryAgentConfig.fast ? { fast: params.fast ?? recoveryAgentConfig.fast } : {}),
1838
+ ...(recoveryAgentConfig.modelProvider ? { modelProvider: recoveryAgentConfig.modelProvider } : {}),
1839
+ ...(modelOrigin === "inherited" ? { modelOverrideFromParent: true } : {}),
1840
+ modelOrigin,
1517
1841
  ...(recoveryAgentConfig.fallbackModels ? { fallbackModels: [...recoveryAgentConfig.fallbackModels] } : {}),
1518
1842
  ...(effectiveThinking ? { thinking: resolveEffectiveThinking(model, effectiveThinking) } : {}),
1843
+ ...(thinkingCeiling ? { thinkingCeiling } : {}),
1519
1844
  ...(recoveryAgentConfig.tools ? { tools: [...recoveryAgentConfig.tools] } : {}),
1845
+ ...(recoveryAgentConfig.excludeTools ? { excludeTools: [...recoveryAgentConfig.excludeTools] } : {}),
1846
+ ...(recoveryAgentConfig.allowNestedSubagents !== undefined ? { allowNestedSubagents: recoveryAgentConfig.allowNestedSubagents } : {}),
1520
1847
  ...(recoveryAgentConfig.extensions ? { extensions: [...recoveryAgentConfig.extensions] } : {}),
1521
1848
  ...(recoveryAgentConfig.subagentOnlyExtensions ? { subagentOnlyExtensions: [...recoveryAgentConfig.subagentOnlyExtensions] } : {}),
1522
1849
  ...(recoveryAgentConfig.mcpDirectTools ? { mcpDirectTools: [...recoveryAgentConfig.mcpDirectTools] } : {}),
1850
+ ...(recoveryAgentConfig.mutationTools ? { mutationTools: [...recoveryAgentConfig.mutationTools] } : {}),
1523
1851
  ...(recoveryAgentConfig.systemPrompt ? { systemPrompt: recoveryAgentConfig.systemPrompt } : {}),
1524
1852
  systemPromptMode: recoveryAgentConfig.systemPromptMode,
1525
1853
  inheritProjectContext: recoveryAgentConfig.inheritProjectContext,
1854
+ inheritGlobalContext: recoveryAgentConfig.inheritGlobalContext,
1526
1855
  inheritSkills: recoveryAgentConfig.inheritSkills,
1527
1856
  ...(resolvedSkills.length ? { skills: resolvedSkills.map((skill) => skill.name) } : {}),
1528
1857
  ...(recoveryAgentConfig.skillPath ? { skillPath: [...recoveryAgentConfig.skillPath] } : {}),
@@ -1536,8 +1865,8 @@ export function executeAsyncSingle(
1536
1865
  ...(controlConfig ? { controlConfig } : {}),
1537
1866
  ...(params.context ? { context: params.context } : {}),
1538
1867
  ...(params.intercomBridge !== undefined ? { intercomBridge: params.intercomBridge } : {}),
1868
+ ...(params.baseRef !== undefined ? { baseRef: params.baseRef } : {}),
1539
1869
  ...(deadlineAt !== undefined ? { absoluteDeadlineAt: deadlineAt } : {}),
1540
- ...(initialTurnBudget ? { initialTurnBudget: { maxTurns: initialTurnBudget.maxTurns, graceTurns: initialTurnBudget.graceTurns } } : {}),
1541
1870
  ...(resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {}),
1542
1871
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, recoveryAgentConfig.maxSubagentDepth),
1543
1872
  ...(maxOutput ? { maxOutput } : {}),
@@ -1555,6 +1884,8 @@ export function executeAsyncSingle(
1555
1884
  }
1556
1885
  }
1557
1886
  let spawnResult: SpawnRunnerResult = {};
1887
+ const initialStatusAt = Date.now();
1888
+ const initialCompletionOwnerId = ctx.completionOwnerId ?? currentCompletionOwnerId();
1558
1889
  try {
1559
1890
  spawnResult = spawnRunner(
1560
1891
  {
@@ -1567,39 +1898,55 @@ export function executeAsyncSingle(
1567
1898
  agent,
1568
1899
  task: taskText,
1569
1900
  ...(agentConfig.runner ? { runner: agentConfig.runner } : {}),
1901
+ ...(params.externalJobFollowUp ? { externalJobFollowUp: params.externalJobFollowUp } : {}),
1570
1902
  ...(params.context ? { context: params.context } : {}),
1571
1903
  cwd: runnerCwd,
1904
+ requestedCwd: params.requestedCwd ?? runnerCwd,
1572
1905
  model,
1906
+ ...(contextLimit !== undefined ? { contextLimit } : {}),
1907
+ ...(params.fast ?? agentConfig.fast ? { fast: params.fast ?? agentConfig.fast } : {}),
1573
1908
  thinking: resolveEffectiveThinking(model, effectiveThinking),
1909
+ ...(thinkingCeiling ? { thinkingCeiling } : {}),
1574
1910
  modelCandidates,
1911
+ ...(modelOrigin === "inherited" ? { skipPrimaryModelVerification: true } : {}),
1912
+ ...(availableModels && availableModels.length > 0 ? { modelVerificationRegistry: availableModels } : {}),
1575
1913
  tools: agentConfig.tools,
1914
+ excludeTools: agentConfig.excludeTools,
1915
+ allowNestedSubagents: agentConfig.allowNestedSubagents,
1576
1916
  extensions: agentConfig.extensions,
1577
1917
  subagentOnlyExtensions: agentConfig.subagentOnlyExtensions,
1578
1918
  mcpDirectTools: agentConfig.mcpDirectTools,
1919
+ mutationTools: agentConfig.mutationTools,
1579
1920
  completionGuard: agentConfig.completionGuard,
1580
1921
  systemPrompt,
1581
1922
  systemPromptMode: agentConfig.systemPromptMode,
1582
1923
  inheritProjectContext: agentConfig.inheritProjectContext,
1924
+ inheritGlobalContext: agentConfig.inheritGlobalContext,
1583
1925
  inheritSkills: agentConfig.inheritSkills,
1584
1926
  skills: resolvedSkills.map((r) => r.name),
1585
1927
  outputPath,
1928
+ ...(params.outputClaimPath ? { outputClaimPath: params.outputClaimPath } : {}),
1586
1929
  outputMode,
1587
1930
  ...(!externalRunner && sessionFile ? { sessionFile } : {}),
1588
1931
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, agentConfig.maxSubagentDepth),
1589
1932
  waitToolEnabled: params.waitToolEnabled,
1933
+ waitToolDefaultTimeoutMs: params.waitToolDefaultTimeoutMs,
1590
1934
  ...(params.agentContract ? { agentContract: params.agentContract } : {}),
1591
1935
  definitionDigest: agentDefinitionDigest(agentConfig),
1592
1936
  launchBindingTask: task,
1593
1937
  launchContractDigest,
1938
+ ...(extensionBindings ? { extensionBindings } : {}),
1594
1939
  launchResolvedExtensions,
1595
1940
  effectiveAcceptance: resolvedAcceptance,
1941
+ acceptanceInput: params.acceptance,
1596
1942
  ...(structuredOutput ? { structuredOutput } : {}),
1597
1943
  ...(params.structuredOutputSchema ? { structuredOutputSchema: params.structuredOutputSchema } : {}),
1598
1944
  ...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),
1599
1945
  ...(params.worktree === true ? { worktree: true } : {}),
1946
+ ...(lane ? { lane } : {}),
1600
1947
  },
1601
1948
  ],
1602
- resultPath: params.parentWorkflowRunId !== undefined && params.revivalLease !== undefined
1949
+ resultPath: params.parentWorkflowRunId !== undefined && (params.revivalLease !== undefined || params.workflowAwaitAsync === true)
1603
1950
  ? workflowAwaitedAsyncResultPath(asyncDir)
1604
1951
  : inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) : resultFilePath(DIRS.results, id),
1605
1952
  cwd: runnerCwd,
@@ -1614,15 +1961,18 @@ export function executeAsyncSingle(
1614
1961
  completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
1615
1962
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
1616
1963
  piPackageRoot,
1617
- piArgv1: process.argv[1],
1964
+ childSessionFactoryModule: childSessionFactoryModule(),
1965
+ inheritedChildRuntime: inheritedChildRuntime(ctx.childRuntime),
1618
1966
  worktreeSetupHook,
1619
1967
  worktreeSetupHookTimeoutMs,
1620
1968
  worktreeBaseDir,
1969
+ baseRef,
1970
+ worktreeProvider,
1971
+ worktreeBranchPrefix,
1621
1972
  controlConfig,
1622
1973
  timeoutMs,
1623
1974
  deadlineAt,
1624
1975
  toolTimeoutMs,
1625
- turnBudget: params.turnBudget,
1626
1976
  toolBudget: params.toolBudget,
1627
1977
  usageBudget: params.usageBudget,
1628
1978
  controlIntercomTarget,
@@ -1633,6 +1983,7 @@ export function executeAsyncSingle(
1633
1983
  runFanoutBudget,
1634
1984
  ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
1635
1985
  ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
1986
+ ...(lane ? { lane } : {}),
1636
1987
  ...(params.revivalLease ? { revivalLease: params.revivalLease } : {}),
1637
1988
  nestedRoute: nestedRoute ?? inheritedNestedRoute,
1638
1989
  nestedSelf: inheritedNestedRoute && nestedAddress ? {
@@ -1644,7 +1995,24 @@ export function executeAsyncSingle(
1644
1995
  },
1645
1996
  id,
1646
1997
  runnerCwd,
1647
- (proof) => ctx.pi.events.emit(SUBAGENT_PROCESS_TERMINAL_EVENT, proof),
1998
+ {
1999
+ lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
2000
+ runId: id,
2001
+ ...(ctx.currentSessionId ? { sessionId: ctx.currentSessionId } : {}),
2002
+ ...(initialCompletionOwnerId ? { completionOwnerId: initialCompletionOwnerId } : {}),
2003
+ mode: "single",
2004
+ state: "running",
2005
+ startedAt: initialStatusAt,
2006
+ lastUpdate: initialStatusAt,
2007
+ currentStep: 0,
2008
+ chainStepCount: 1,
2009
+ ...(lane ? { lane } : {}),
2010
+ steps: [{ agent, status: "pending", ...(lane ? { lane } : {}), ...(model ? { model } : {}), ...(contextLimit !== undefined ? { contextLimit } : {}) }],
2011
+ },
2012
+ path.join(asyncDir, "status.json"),
2013
+ (proof) => emitProcessTerminalEvent(ctx, proof),
2014
+ (runnerProcessInstanceId) => params.activeAsyncCapacity?.markStarted(runnerProcessInstanceId),
2015
+ params.requestedCwd ?? runnerCwd,
1648
2016
  );
1649
2017
  } catch (error) {
1650
2018
  params.activeAsyncCapacity?.rollback();
@@ -1653,7 +2021,10 @@ export function executeAsyncSingle(
1653
2021
  }
1654
2022
 
1655
2023
  if (spawnResult.error) {
1656
- if (!spawnResult.pid || !spawnResult.runnerProcessInstanceId || (spawnResult.startupDidNotProceed && spawnResult.terminationObserved)) params.activeAsyncCapacity?.rollback();
2024
+ if (spawnResult.startupDidNotProceed) {
2025
+ if (!spawnResult.runnerProcessInstanceId || params.activeAsyncCapacity?.rollbackBeforeRunnerProceed(spawnResult.runnerProcessInstanceId) !== true) params.activeAsyncCapacity?.rollback();
2026
+ }
2027
+ else if (!spawnResult.pid || !spawnResult.runnerProcessInstanceId) params.activeAsyncCapacity?.rollback();
1657
2028
  else params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
1658
2029
  return formatAsyncStartError("single", `Failed to start async run '${id}': ${spawnResult.error}`);
1659
2030
  }
@@ -1661,8 +2032,6 @@ export function executeAsyncSingle(
1661
2032
  params.activeAsyncCapacity?.rollback();
1662
2033
  return formatAsyncStartError("single", `Failed to start async run '${id}': runner identity unavailable`);
1663
2034
  }
1664
- params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
1665
-
1666
2035
  if (spawnResult.pid) {
1667
2036
  if (inheritedNestedRoute && nestedAddress) {
1668
2037
  const now = Date.now();
@@ -1680,7 +2049,7 @@ export function executeAsyncSingle(
1680
2049
  path: nestedAddress.path,
1681
2050
  asyncDir,
1682
2051
  pid: spawnResult.pid,
1683
- ownerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,
2052
+ ownerIntercomTarget: ctx.childRuntime?.intercomSessionName,
1684
2053
  leafIntercomTarget: childIntercomTarget?.(agent, 0),
1685
2054
  intercomTarget: childIntercomTarget?.(agent, 0),
1686
2055
  ownerState: "live",
@@ -1690,7 +2059,6 @@ export function executeAsyncSingle(
1690
2059
  agents: [agent],
1691
2060
  chainStepCount: 1,
1692
2061
  ...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}),
1693
- ...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),
1694
2062
  startedAt: now,
1695
2063
  lastUpdate: now,
1696
2064
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
@@ -1718,7 +2086,6 @@ export function executeAsyncSingle(
1718
2086
  ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
1719
2087
  ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
1720
2088
  ...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}),
1721
- ...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),
1722
2089
  ...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}),
1723
2090
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
1724
2091
  nestedRoute,
@@ -1727,6 +2094,6 @@ export function executeAsyncSingle(
1727
2094
 
1728
2095
  return {
1729
2096
  content: [{ type: "text", text: formatAsyncStartedMessage(`Async: ${agent} [${id}]`, ctx.interactive === true) }],
1730
- details: { mode: "single", runId: id, results: [], asyncId: id, asyncDir, launchContractDigest, launchResolvedExtensions, ...(capabilityCeiling ? { capabilityCeiling } : {}), ...(params.context ? { context: params.context } : {}), ...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}), ...(params.turnBudget ? { turnBudget: params.turnBudget } : {}), ...(params.toolBudget ? { toolBudget: resolvedToolBudget.budget ?? params.toolBudget } : {}), ...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}) } as Details,
2097
+ details: { mode: "single", runId: id, 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 } : {}) } as Details,
1731
2098
  };
1732
2099
  }