@xzzpig/pi-subagents 0.8.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 (218) hide show
  1. package/CHANGELOG.md +443 -0
  2. package/README.md +2 -2
  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 +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +151 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +5 -4
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +370 -114
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +12 -2
  35. package/src/agents/agents.ts +919 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +31 -20
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +48 -18
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +57 -21
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +2 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +366 -128
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +45 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +189 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +676 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +468 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1172 -400
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +314 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +342 -0
  115. package/src/runs/shared/child-tool-plan.ts +540 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +142 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +38 -48
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +15 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/single-output.ts +89 -22
  149. package/src/runs/shared/structured-output.ts +49 -9
  150. package/src/runs/shared/subagent-control.ts +6 -2
  151. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  152. package/src/runs/shared/task-intent.ts +21 -7
  153. package/src/runs/shared/tool-availability.ts +18 -62
  154. package/src/runs/shared/tool-budget.ts +0 -14
  155. package/src/runs/shared/tool-timeout.ts +1 -1
  156. package/src/runs/shared/workflow-graph.ts +16 -0
  157. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  158. package/src/runs/shared/worktree.ts +571 -62
  159. package/src/shared/atomic-json.ts +3 -1
  160. package/src/shared/child-session-name.ts +46 -0
  161. package/src/shared/extension-context.ts +24 -0
  162. package/src/shared/fork-context.ts +21 -12
  163. package/src/shared/fork-session-cwd.ts +27 -0
  164. package/src/shared/formatters.ts +18 -3
  165. package/src/shared/jsonl-writer.ts +11 -0
  166. package/src/shared/launch-contract.ts +8 -1
  167. package/src/shared/pruned-fork.ts +450 -0
  168. package/src/shared/session-file-trust.ts +19 -0
  169. package/src/shared/session-tokens.ts +14 -3
  170. package/src/shared/settings.ts +19 -105
  171. package/src/shared/shortcuts.ts +17 -0
  172. package/src/shared/thinking-ceiling.ts +0 -6
  173. package/src/shared/types.ts +524 -70
  174. package/src/shared/utils.ts +60 -93
  175. package/src/shared/workflow-child-permit.ts +207 -0
  176. package/src/slash/delegation-adapters.ts +1 -9
  177. package/src/slash/delegation-request.ts +0 -4
  178. package/src/slash/prompt-template-bridge.ts +37 -1
  179. package/src/slash/slash-bridge.ts +1 -2
  180. package/src/slash/slash-commands.ts +383 -116
  181. package/src/slash/slash-live-state.ts +22 -11
  182. package/src/slash/subagents-admin.ts +29 -12
  183. package/src/tui/fleet-native-transcript.ts +4 -0
  184. package/src/tui/fleet-status.ts +217 -82
  185. package/src/tui/fleet-transcript.ts +11 -5
  186. package/src/tui/fleet.ts +54 -28
  187. package/src/tui/render-helpers.ts +31 -0
  188. package/src/tui/render.ts +1429 -163
  189. package/src/watchdog/change-signature.ts +40 -1
  190. package/src/watchdog/child-status.ts +54 -34
  191. package/src/watchdog/diff-tool.ts +77 -0
  192. package/src/watchdog/emission-guard.ts +5 -3
  193. package/src/watchdog/guidance.ts +20 -0
  194. package/src/watchdog/register-child.ts +28 -25
  195. package/src/watchdog/register-main.ts +10 -9
  196. package/src/watchdog/render.ts +4 -5
  197. package/src/watchdog/review.ts +15 -4
  198. package/src/watchdog/rules.ts +70 -0
  199. package/src/watchdog/runtime.ts +75 -92
  200. package/src/watchdog/scope.ts +0 -11
  201. package/src/watchdog/settings.ts +48 -104
  202. package/src/watchdog/turn-delta.ts +1 -1
  203. package/src/watchdog/types.ts +18 -32
  204. package/src/watchdog/warning-format.ts +0 -1
  205. package/src/workflows/chat-progress.ts +7 -3
  206. package/src/workflows/host-command.ts +235 -0
  207. package/src/workflows/scripted-workflow.ts +988 -59
  208. package/src/workflows/workflow-checklist.ts +439 -0
  209. package/src/workflows/workflow-child-summary.ts +121 -0
  210. package/src/workflows/workflow-preflight.ts +297 -0
  211. package/src/workflows/workflow-receipt.ts +232 -6
  212. package/src/workflows/workflow-resources.ts +150 -0
  213. package/src/workflows/workflow-settlement.ts +246 -0
  214. package/src/runs/shared/child-protocol.ts +0 -401
  215. package/src/runs/shared/pi-args.ts +0 -935
  216. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  217. package/src/runs/shared/turn-budget.ts +0 -98
  218. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -5,40 +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
33
  import { resolveModelScopesForAgent, type ModelScopeConfig } from "../shared/model-scope.ts";
30
- import { resolveEffectiveThinking } from "../../shared/model-info.ts";
31
- import { assertThinkingWithinCeiling, decodeThinkingCeiling, intersectThinkingCeilings, SUBAGENT_THINKING_CEILING_ENV, type ThinkingLevel } from "../../shared/thinking-ceiling.ts";
32
- import { resolveExpectedWorktreeAgentCwd } from "../shared/worktree.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";
33
37
  import { buildWorkflowGraphSnapshot } from "../shared/workflow-graph.ts";
34
38
  import { ChainOutputValidationError, validateChainOutputBindings } from "../shared/chain-outputs.ts";
35
39
  import { createStructuredOutputRuntime } from "../shared/structured-output.ts";
36
- import { resolveEffectiveAcceptance, validateAcceptanceInput, validateExecutionAcceptance } from "../shared/acceptance.ts";
40
+ import { resolveAcceptanceReportMode, resolveEffectiveAcceptance, validateAcceptanceInput, validateExecutionAcceptance } from "../shared/acceptance.ts";
37
41
  import { createRunFanoutBudget, writeRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
38
42
  import { validateImplementationToolContract } from "../shared/completion-guard.ts";
39
43
  import {
40
44
  type AcceptanceInput,
41
45
  type AgentContract,
46
+ type AsyncParallelGroupStatus,
42
47
  type AsyncStatus,
43
48
  type ArtifactConfig,
44
49
  type Details,
@@ -47,12 +52,12 @@ import {
47
52
  type MaxOutputConfig,
48
53
  type NestedRouteInfo,
49
54
  type ResolvedControlConfig,
50
- type ResolvedTurnBudget,
51
55
  type ResolvedToolBudget,
52
56
  type RunFanoutBudgetDescriptor,
53
57
  type ToolBudgetConfig,
54
58
  type SubagentRunMode,
55
59
  type SteeringRecoveryDescriptor,
60
+ type WorkflowLaneMetadata,
56
61
  type UsageBudgetConfig,
57
62
  DIRS,
58
63
  SUBAGENT_ASYNC_STARTED_EVENT,
@@ -61,23 +66,27 @@ import {
61
66
  getAsyncConfigPath,
62
67
  resolveChildMaxSubagentDepth,
63
68
  } from "../../shared/types.ts";
64
- 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";
65
73
  import { resultFilePath } from "./result-files.ts";
66
- import { appendTurnBudgetSystemPrompt, initialTurnBudgetState } from "../shared/turn-budget.ts";
67
74
  import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
68
75
  import { usageBudgetState } from "../shared/usage-budget.ts";
69
76
  import type { ImportedAsyncRoot } from "./chain-root-attachment.ts";
70
77
  import type { SessionLeaseRequest } from "../shared/session-lease.ts";
71
- import { finalizeProcessTerminal, readProcessTerminal } from "./process-terminal.ts";
78
+ import { finalizeProcessTerminal, initializeProcessTerminal, readProcessTerminal } from "./process-terminal.ts";
72
79
  import type { ActiveAsyncCapacityHandle } from "./active-async-capacity.ts";
80
+ import { statusStepDescription } from "./chain-append.ts";
73
81
  import { SUBAGENT_PROCESS_TERMINAL_EVENT } from "../../shared/types.ts";
74
- 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";
75
83
  import { agentDefinitionDigest, launchBindingDigest } from "../../shared/launch-contract.ts";
76
84
  import { resolvePermissionRules, type PermissionConfig } from "../shared/permissions.ts";
77
85
  import { normalizeExtensionBindings, omitExtensionBindingsEnv, type ExtensionBindings } from "../shared/extension-bindings.ts";
86
+ import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
78
87
 
79
88
  const require = createRequire(import.meta.url);
80
- const piPackageRoot = resolvePiPackageRoot();
89
+ const piPackageRoot = resolvePiPackageRoot() ?? resolveInstalledPiPackageRoot();
81
90
 
82
91
  function resolveJitiCliFromPackageJson(packageJsonPath: string): string | undefined {
83
92
  if (!fs.existsSync(packageJsonPath)) return undefined;
@@ -139,6 +148,8 @@ interface AsyncExecutionContext {
139
148
  modelScope?: ModelScopeConfig;
140
149
  /** Whether the parent session has an interactive UI. */
141
150
  interactive?: boolean;
151
+ /** The executor's own child runtime when the launch comes from an in-process child. */
152
+ childRuntime?: ChildRuntimeConfig;
142
153
  }
143
154
 
144
155
  export const DEFAULT_ASYNC_TIMEOUT_MS = 30 * 60 * 1000;
@@ -151,6 +162,8 @@ interface AsyncChainParams {
151
162
  attachRoot?: ImportedAsyncRoot & { agent: string; outputName?: string; label?: string };
152
163
  resultMode?: SubagentRunMode;
153
164
  agents: AgentConfig[];
165
+ /** Original discovery provenance, retained by normal callers for unknown-agent diagnostics. */
166
+ unknownAgentDiagnosticContext?: UnknownAgentDiagnosticContext;
154
167
  ctx: AsyncExecutionContext;
155
168
  availableModels?: AvailableModelInfo[];
156
169
  cwd?: string;
@@ -168,9 +181,13 @@ interface AsyncChainParams {
168
181
  dynamicFanoutMaxItems?: number;
169
182
  maxSubagentDepth: number;
170
183
  waitToolEnabled?: boolean;
184
+ waitToolDefaultTimeoutMs?: number;
171
185
  worktreeSetupHook?: string;
172
186
  worktreeSetupHookTimeoutMs?: number;
173
187
  worktreeBaseDir?: string;
188
+ baseRef?: string;
189
+ worktreeProvider?: import("../../shared/types.ts").WorktreeProvider;
190
+ worktreeBranchPrefix?: string;
174
191
  controlConfig?: ResolvedControlConfig;
175
192
  controlIntercomTarget?: string;
176
193
  childIntercomTarget?: (agent: string, index: number) => string | undefined;
@@ -178,7 +195,6 @@ interface AsyncChainParams {
178
195
  acceptance?: AcceptanceInput;
179
196
  fast?: boolean;
180
197
  timeoutMs?: number;
181
- turnBudget?: ResolvedTurnBudget;
182
198
  toolBudget?: ResolvedToolBudget;
183
199
  usageBudget?: UsageBudgetConfig;
184
200
  configToolBudget?: ResolvedToolBudget;
@@ -195,6 +211,7 @@ interface AsyncChainParams {
195
211
  runFanoutBudget?: RunFanoutBudgetDescriptor;
196
212
  parentWorkflowRunId?: string;
197
213
  workflowKey?: string;
214
+ lane?: WorkflowLaneMetadata;
198
215
  activeAsyncCapacity?: ActiveAsyncCapacityHandle;
199
216
  }
200
217
 
@@ -208,6 +225,7 @@ interface AsyncSingleParams {
208
225
  recoveryAgentConfig?: AgentConfig;
209
226
  ctx: AsyncExecutionContext;
210
227
  cwd?: string;
228
+ requestedCwd?: string;
211
229
  maxOutput?: MaxOutputConfig;
212
230
  artifactsDir?: string;
213
231
  artifactConfig: ArtifactConfig;
@@ -222,18 +240,24 @@ interface AsyncSingleParams {
222
240
  reads?: string[] | false;
223
241
  outputMode?: "inline" | "file-only";
224
242
  outputBaseDir?: string;
243
+ outputClaimPath?: string;
225
244
  agentContract?: AgentContract;
226
245
  structuredOutputSchema?: JsonSchemaObject;
227
246
  modelOverride?: string;
228
247
  modelOverrideFromParent?: boolean;
248
+ modelOrigin?: ModelOrigin;
229
249
  fast?: boolean;
230
250
  thinkingOverride?: AgentConfig["thinking"];
231
251
  availableModels?: AvailableModelInfo[];
232
252
  maxSubagentDepth: number;
233
253
  waitToolEnabled?: boolean;
254
+ waitToolDefaultTimeoutMs?: number;
234
255
  worktreeSetupHook?: string;
235
256
  worktreeSetupHookTimeoutMs?: number;
236
257
  worktreeBaseDir?: string;
258
+ baseRef?: string;
259
+ worktreeProvider?: import("../../shared/types.ts").WorktreeProvider;
260
+ worktreeBranchPrefix?: string;
237
261
  worktree?: boolean;
238
262
  controlConfig?: ResolvedControlConfig;
239
263
  intercomBridge?: IntercomBridgeConfig;
@@ -245,7 +269,6 @@ interface AsyncSingleParams {
245
269
  absoluteDeadlineAt?: number;
246
270
  /** Optional per-call hard toolTimeoutMs override (highest precedence). */
247
271
  toolTimeoutMs?: number;
248
- turnBudget?: { maxTurns: number; graceTurns?: number };
249
272
  toolBudget?: ResolvedToolBudget | ToolBudgetConfig;
250
273
  usageBudget?: UsageBudgetConfig;
251
274
  configToolBudget?: ResolvedToolBudget;
@@ -259,6 +282,7 @@ interface AsyncSingleParams {
259
282
  runFanoutBudget?: RunFanoutBudgetDescriptor;
260
283
  parentWorkflowRunId?: string;
261
284
  workflowKey?: string;
285
+ lane?: WorkflowLaneMetadata;
262
286
  workflowAwaitAsync?: boolean;
263
287
  activeAsyncCapacity?: ActiveAsyncCapacityHandle;
264
288
  externalJobFollowUp?: {
@@ -283,6 +307,8 @@ export interface AsyncRunnerStepBuildParams {
283
307
  attachRoot?: ImportedAsyncRoot & { agent: string; outputName?: string; label?: string };
284
308
  resultMode?: SubagentRunMode;
285
309
  agents: AgentConfig[];
310
+ /** Exact discovery provenance for failed resolution; omission triggers defensive fallback discovery. */
311
+ unknownAgentDiagnosticContext?: UnknownAgentDiagnosticContext;
286
312
  ctx: AsyncExecutionContext;
287
313
  availableModels?: AvailableModelInfo[];
288
314
  cwd?: string;
@@ -295,7 +321,10 @@ export interface AsyncRunnerStepBuildParams {
295
321
  dynamicFanoutMaxItems?: number;
296
322
  maxSubagentDepth: number;
297
323
  waitToolEnabled?: boolean;
324
+ waitToolDefaultTimeoutMs?: number;
298
325
  worktreeBaseDir?: string;
326
+ worktreeProvider?: import("../../shared/types.ts").WorktreeProvider;
327
+ worktreeBranchPrefix?: string;
299
328
  asyncDir: string;
300
329
  outputBaseDir?: string;
301
330
  validateOutputBindings?: boolean;
@@ -326,15 +355,15 @@ export function formatAsyncStartedMessage(headline: string, interactive: boolean
326
355
  const guidance = interactive
327
356
  ? [
328
357
  "The async run is detached and running in the background.",
329
- "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.",
330
- "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.",
331
- "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.",
332
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.",
333
362
  ]
334
363
  : [
335
364
  "The async run is detached. Do not run sleep timers or polling loops just to wait for it.",
336
- "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.",
337
- "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.",
338
367
  ];
339
368
  return [headline, "", ...guidance].join("\n");
340
369
  }
@@ -418,13 +447,15 @@ function waitForRunnerStartup(startupPath: string, expectedState: RunnerStartupS
418
447
  return { ok: false, error: `Timed out after ${timeoutMs}ms waiting for the async runner startup state '${expectedState}'.`, startupDidNotProceed: true };
419
448
  }
420
449
 
450
+ const writePrivateStartupControlJson = createAtomicJsonWriter({ mode: 0o600, ignoreCleanupErrorAfterSuccess: true });
451
+
421
452
  function writeRunnerStartupControl(filePath: string, payload: { action: "ack" | "proceed"; token: string }): void {
422
453
  // Delegate to the shared atomic JSON writer (temp file + rename, retrying
423
454
  // transient Windows EPERM/EBUSY/EACCES locks and cleaning up the temp file
424
455
  // on failure), so the startup handshake gets the same locking resilience as
425
456
  // every other async control/result file. This is exercised by
426
457
  // test/unit/atomic-json.test.ts.
427
- writePrivateAtomicJson(filePath, payload);
458
+ writePrivateStartupControlJson(filePath, payload);
428
459
  }
429
460
 
430
461
  function runnerIsAlive(pid: number): boolean {
@@ -493,24 +524,40 @@ interface SpawnRunnerResult {
493
524
  startupDidNotProceed?: boolean;
494
525
  }
495
526
 
496
- 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
+
497
544
  if (!jitiCliPath) {
498
545
  return { error: "upstream jiti for TypeScript execution could not be found; ensure package dependencies are installed" };
499
546
  }
500
-
501
- try {
502
- const cwdStats = fs.statSync(cwd);
503
- if (!cwdStats.isDirectory()) {
504
- return { error: `cwd is not a directory: ${cwd}` };
505
- }
506
- } catch {
507
- 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.` };
508
553
  }
509
554
 
510
555
  fs.mkdirSync(TEMP_ROOT_DIR, { recursive: true });
511
556
  const cfgPath = getAsyncConfigPath(suffix);
512
557
  const runnerProcessInstanceId = randomUUID();
513
- const launchConfig = { ...cfg, runnerProcessInstanceId };
558
+ const hasRevivalLease = typeof (cfg as { revivalLease?: unknown }).revivalLease === "object";
559
+ const launchBarrierToken = hasRevivalLease ? undefined : runnerProcessInstanceId;
560
+ const launchConfig = { ...cfg, runnerProcessInstanceId, ...(launchBarrierToken ? { launchBarrierToken } : {}) };
514
561
  writePrivateAtomicJson(cfgPath, launchConfig);
515
562
  const runner = path.join(path.dirname(fileURLToPath(import.meta.url)), "subagent-runner.ts");
516
563
  const nodeCommand = resolveNodeExecutable();
@@ -523,7 +570,9 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal
523
570
  ? path.join(launchAsyncDir, "runner-startup.json")
524
571
  : undefined;
525
572
  const startupAckPath = startupPath ? path.join(path.dirname(startupPath), "runner-startup-ack.json") : undefined;
526
- 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;
527
576
  if (startupPath) fs.rmSync(startupPath, { force: true });
528
577
  if (startupAckPath) fs.rmSync(startupAckPath, { force: true });
529
578
  if (startupProceedPath) fs.rmSync(startupProceedPath, { force: true });
@@ -539,12 +588,12 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal
539
588
  }
540
589
  const proc = spawn(nodeCommand, [jitiCliPath, runner, cfgPath], {
541
590
  cwd,
542
- detached: true,
591
+ ...backgroundProcessOptions(),
543
592
  stdio: ["ignore", stdoutFd ?? "ignore", stderrFd ?? "ignore"],
544
- windowsHide: true,
545
593
  env: {
546
594
  ...omitExtensionBindingsEnv(process.env),
547
- ...(piPackageRoot ? { [PI_CODING_AGENT_PACKAGE_ROOT_ENV]: piPackageRoot } : {}),
595
+ [PI_CODING_AGENT_PACKAGE_ROOT_ENV]: piPackageRoot,
596
+ [JITI_ALIAS_ENV]: JSON.stringify(hostPeerAliases.aliases),
548
597
  },
549
598
  });
550
599
  closeFd(stdoutFd);
@@ -605,6 +654,45 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal
605
654
  if (typeof proc.pid !== "number") {
606
655
  return { error: `async runner did not produce a pid for cwd: ${cwd}` };
607
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
+ }
608
696
  proc.unref();
609
697
  if (startupPath && startupAckPath && startupProceedPath) {
610
698
  const persistStartupFailure = (message: string) => {
@@ -675,6 +763,8 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
675
763
  thinkingOverridesByFlatIndex,
676
764
  maxSubagentDepth,
677
765
  worktreeBaseDir,
766
+ worktreeProvider,
767
+ worktreeBranchPrefix,
678
768
  asyncDir,
679
769
  } = params;
680
770
  const outputBaseDir = params.outputBaseDir;
@@ -682,6 +772,15 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
682
772
  const chainSkills = params.chainSkills ?? [];
683
773
  const availableModels = params.availableModels;
684
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
+ }
685
784
  const progressDir = params.progressDir ?? runnerCwd;
686
785
  const graphChain: ChainStep[] = params.attachRoot
687
786
  ? [{
@@ -709,6 +808,8 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
709
808
  }
710
809
  const workflowGraph = buildWorkflowGraphSnapshot({ runId: id, mode: resultMode, steps: graphChain });
711
810
 
811
+ const diagnosticContext = params.unknownAgentDiagnosticContext
812
+ ?? unknownAgentDiagnosticContext(discoverAgents(path.resolve(runnerCwd), "both"));
712
813
  for (const s of chain) {
713
814
  const stepAgents = isParallelStep(s)
714
815
  ? s.parallel.map((t) => t.agent)
@@ -716,9 +817,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
716
817
  ? [s.parallel.agent]
717
818
  : [(s as SequentialStep).agent];
718
819
  for (const agentName of stepAgents) {
719
- if (!agents.find((x) => x.name === agentName)) {
720
- return { error: `Unknown agent: ${agentName}` };
721
- }
820
+ if (!agents.find((x) => x.name === agentName)) return { error: formatUnknownAgentError(agentName, diagnosticContext) };
722
821
  }
723
822
  }
724
823
 
@@ -750,7 +849,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
750
849
  if (unsupported.length > 0) throw new AsyncStartValidationError(`Agent '${a.name}' uses runner.type='${externalRunnerType}' and does not support: ${unsupported.join(", ")}.`);
751
850
  }
752
851
  try {
753
- assertAgentAllowedByCapabilityCeiling(a.name, intersectSubagentCapabilityCeilings(params.capabilityCeiling, decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV])));
852
+ assertAgentAllowedByCapabilityCeiling(a.name, intersectSubagentCapabilityCeilings(params.capabilityCeiling, ctx.childRuntime?.capabilityCeiling));
754
853
  } catch (error) {
755
854
  throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
756
855
  }
@@ -764,19 +863,21 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
764
863
  envValue: params.toolTimeoutMsEnv ?? toolTimeoutFromEnv(),
765
864
  });
766
865
  if (resolvedToolTimeout.error) throw new AsyncStartValidationError(resolvedToolTimeout.error);
767
- const stepCwd = resolveChildCwd(runnerCwd, s.cwd);
768
- const instructionCwd = behaviorCwd ?? stepCwd;
769
- const readExistenceCwd = behaviorCwd ? stepCwd : instructionCwd;
770
- let behavior = suppressProgressForReadOnlyTask(resolvedBehavior ?? resolveStepBehavior(a, buildStepOverrides(s), chainSkills), s.task, originalTask);
771
- const inheritedRelativeParallelOutput = parallelOutputNamespace && s.output === undefined && typeof behavior.output === "string" && !path.isAbsolute(behavior.output);
772
- if (inheritedRelativeParallelOutput && parallelOutputNamespace.taskIndex !== undefined) {
773
- behavior = {
774
- ...behavior,
775
- output: path.join(`parallel-${parallelOutputNamespace.stepIndex}`, `${parallelOutputNamespace.taskIndex}-${s.agent}`, behavior.output as string),
776
- };
777
- }
778
- const namespaceOutputPath = Boolean(inheritedRelativeParallelOutput && parallelOutputNamespace.taskIndex === undefined);
779
- 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;
780
881
  const { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(
781
882
  skillNames,
782
883
  stepCwd,
@@ -801,33 +902,34 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
801
902
  const isFirstProgressAgent = behavior.progress && !progressPrecreated && !progressInstructionCreated;
802
903
  if (behavior.progress) progressInstructionCreated = true;
803
904
  const progressInstructions = buildChainInstructions({ ...behavior, output: false, reads: false }, progressDir, isFirstProgressAgent);
804
- const outputPath = resolveSingleOutputPath(behavior.output, ctx.cwd, instructionCwd, outputBaseDir);
805
905
  if (!namespaceOutputPath) systemPrompt = injectOutputPathSystemPrompt(systemPrompt, outputPath, a);
806
906
  const validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Async step (${s.agent})`);
807
907
  if (validationError) throw new AsyncStartValidationError(validationError);
808
908
  let taskTemplate = s.task ?? "{previous}";
809
909
  taskTemplate = taskTemplate.replace(/\{task\}/g, originalTask ?? "");
810
- taskTemplate = taskTemplate.replace(/\{chain_dir\}/g, runnerCwd);
910
+ taskTemplate = taskTemplate.replace(/\{chain_dir\}/g, behaviorCwd ?? runnerCwd);
811
911
  const taskText = `${readInstructions.prefix}${taskTemplate}${progressInstructions.suffix}`;
812
912
  const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a);
813
913
 
814
914
  const modelScopes = resolveModelScopesForAgent(ctx.modelScope, a.name, ctx.currentModel);
815
- const primaryModelFromParent = inheritsParentModel(s.model, a.model, ctx.currentModel);
915
+ const modelOrigin = resolveModelOrigin({ explicitModel: s.model, agentModel: a.model, parentModel: ctx.currentModel });
916
+ const primaryModelFromParent = modelOrigin === "inherited";
816
917
  const primaryModel = externalRunner ? undefined : resolveEffectiveSubagentModel(
817
918
  s.model,
818
919
  a.model,
819
920
  ctx.currentModel,
820
921
  availableModels,
821
922
  a.modelProvider ?? ctx.currentModelProvider,
822
- { scope: modelScopes },
923
+ { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" },
823
924
  );
824
925
  const thinkingOverride = flatIndex === undefined ? undefined : thinkingOverridesByFlatIndex?.[flatIndex];
825
926
  const effectiveThinking = externalRunner ? undefined : thinkingOverride ?? a.thinking;
826
927
  const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinking, thinkingOverride !== undefined);
928
+ const contextLimit = model ? findModelInfo(model, availableModels, a.modelProvider ?? ctx.currentModelProvider)?.contextWindow : undefined;
827
929
  const thinkingCeiling = externalRunner ? undefined : intersectThinkingCeilings(
828
930
  params.thinkingCeiling,
829
931
  a.maxThinking,
830
- decodeThinkingCeiling(process.env[SUBAGENT_THINKING_CEILING_ENV]),
932
+ ctx.childRuntime?.thinkingCeiling,
831
933
  );
832
934
  if (!externalRunner) {
833
935
  try {
@@ -838,23 +940,29 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
838
940
  }
839
941
  const agentContract = s.agentContract ?? params.agentContract;
840
942
  const permissionRules = resolvePermissionRules(ctx.permissions, a.permissions);
841
- const modelCandidates = externalRunner ? [] : buildModelCandidates(primaryModel, a.fallbackModels, availableModels, a.modelProvider ?? ctx.currentModelProvider, {
842
- scope: modelScopes,
843
- primaryModelFromParent,
844
- }).flatMap((candidate) => {
845
- const resolved = applyThinkingSuffix(candidate, effectiveThinking, thinkingOverride !== undefined);
846
- return resolved ? [resolved] : [];
847
- });
943
+ let modelCandidates: string[] = [];
848
944
  if (!externalRunner) {
849
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
+ });
850
954
  for (const candidate of modelCandidates) assertThinkingWithinCeiling({ model: candidate, configThinking: effectiveThinking, ceiling: thinkingCeiling, agent: a.name, runId: id });
851
955
  } catch (error) {
852
956
  throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
853
957
  }
854
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);
855
961
  const fast = s.fast ?? params.fast ?? a.fast;
856
962
  const toolPlan = resolvePiLaunchToolPlan({
857
963
  tools: a.tools,
964
+ excludeTools: a.excludeTools,
965
+ allowNestedSubagents: a.allowNestedSubagents,
858
966
  extensions: a.extensions,
859
967
  subagentOnlyExtensions: a.subagentOnlyExtensions,
860
968
  mcpDirectTools: a.mcpDirectTools,
@@ -865,9 +973,10 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
865
973
  model,
866
974
  modelCandidates,
867
975
  capabilityCeiling: params.capabilityCeiling,
868
- inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
976
+ inheritedCapabilityCeiling: ctx.childRuntime?.capabilityCeiling,
869
977
  agentName: a.name,
870
978
  permissionRules,
979
+ runtimeSnapshotHost: ctx.pi,
871
980
  });
872
981
  const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
873
982
  if (externalRunner && permissionRules) {
@@ -902,7 +1011,9 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
902
1011
  outputName: s.as,
903
1012
  structured: Boolean(s.outputSchema),
904
1013
  cwd: stepCwd,
1014
+ requestedCwd: s.cwd ?? stepCwd,
905
1015
  model,
1016
+ ...(contextLimit !== undefined ? { contextLimit } : {}),
906
1017
  ...(fast !== undefined ? { fast } : {}),
907
1018
  thinking: resolveEffectiveThinking(model, effectiveThinking),
908
1019
  ...(thinkingCeiling ? { thinkingCeiling } : {}),
@@ -911,13 +1022,17 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
911
1022
  ...(primaryModelFromParent ? { skipPrimaryModelVerification: true } : {}),
912
1023
  ...(availableModels && availableModels.length > 0 ? { modelVerificationRegistry: availableModels } : {}),
913
1024
  tools: a.tools,
1025
+ excludeTools: a.excludeTools,
1026
+ allowNestedSubagents: a.allowNestedSubagents,
914
1027
  extensions: a.extensions,
915
1028
  subagentOnlyExtensions: a.subagentOnlyExtensions,
916
1029
  mcpDirectTools: a.mcpDirectTools,
1030
+ mutationTools: a.mutationTools,
917
1031
  completionGuard: a.completionGuard,
918
1032
  systemPrompt,
919
1033
  systemPromptMode: a.systemPromptMode,
920
1034
  inheritProjectContext: a.inheritProjectContext,
1035
+ inheritGlobalContext: a.inheritGlobalContext,
921
1036
  inheritSkills: a.inheritSkills,
922
1037
  skills: resolvedSkills.map((r) => r.name),
923
1038
  outputPath,
@@ -928,6 +1043,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
928
1043
  timeoutMs: a.defaultTimeoutMs ?? DEFAULT_ASYNC_TIMEOUT_MS,
929
1044
  toolTimeoutMs: resolvedToolTimeout.toolTimeoutMs,
930
1045
  waitToolEnabled: params.waitToolEnabled,
1046
+ waitToolDefaultTimeoutMs: params.waitToolDefaultTimeoutMs,
931
1047
  effectiveAcceptance: resolveEffectiveAcceptance({
932
1048
  explicit: s.acceptance,
933
1049
  agentName: s.agent,
@@ -942,7 +1058,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
942
1058
  acceptanceRole: a.acceptanceRole,
943
1059
  ...(s.gateOn ? { gateOn: s.gateOn } : {}),
944
1060
  ...(s.outputSchema ? { structuredOutputSchema: s.outputSchema } : {}),
945
- ...(s.outputSchema ? { structuredOutput: createStructuredOutputRuntime(s.outputSchema, path.join(asyncDir, "structured-output"), { captureAcceptanceReport: s.acceptance !== false }) } : {}),
1061
+ ...(s.outputSchema ? { structuredOutput: createStructuredOutputRuntime(s.outputSchema, path.join(asyncDir, "structured-output"), { acceptanceReport: resolveAcceptanceReportMode(s.acceptance) }) } : {}),
946
1062
  ...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),
947
1063
  ...(s.worktree ? { worktree: true } : {}),
948
1064
  };
@@ -976,7 +1092,9 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
976
1092
  return {
977
1093
  parallel: s.parallel.map((t, taskIndex) => {
978
1094
  let behaviorCwd: string | undefined;
979
- if (s.worktree) {
1095
+ if (s.worktree && managedWorktreeProvider === "worktrunk") {
1096
+ behaviorCwd = WORKTREE_AGENT_CWD_PLACEHOLDER;
1097
+ } else if (s.worktree && managedWorktreeProvider === "native") {
980
1098
  try {
981
1099
  behaviorCwd = resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s${stepIndex}`, taskIndex, worktreeBaseDir);
982
1100
  } catch {
@@ -1031,7 +1149,9 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1031
1149
  }
1032
1150
  const sequential = s as SequentialStep;
1033
1151
  let behaviorCwd: string | undefined;
1034
- if (sequential.worktree) {
1152
+ if (sequential.worktree && managedWorktreeProvider === "worktrunk") {
1153
+ behaviorCwd = WORKTREE_AGENT_CWD_PLACEHOLDER;
1154
+ } else if (sequential.worktree && managedWorktreeProvider === "native") {
1035
1155
  try {
1036
1156
  behaviorCwd = resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s${stepIndex}`, 0, worktreeBaseDir);
1037
1157
  } catch {
@@ -1054,6 +1174,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1054
1174
  index: params.attachRoot.index,
1055
1175
  },
1056
1176
  inheritProjectContext: false,
1177
+ inheritGlobalContext: false,
1057
1178
  inheritSkills: false,
1058
1179
  }, ...builtSteps]
1059
1180
  : builtSteps;
@@ -1100,6 +1221,9 @@ export function executeAsyncChain(
1100
1221
  worktreeSetupHook,
1101
1222
  worktreeSetupHookTimeoutMs,
1102
1223
  worktreeBaseDir,
1224
+ baseRef,
1225
+ worktreeProvider,
1226
+ worktreeBranchPrefix,
1103
1227
  controlConfig,
1104
1228
  controlIntercomTarget,
1105
1229
  childIntercomTarget,
@@ -1110,13 +1234,13 @@ export function executeAsyncChain(
1110
1234
  chain: chain.map((step) => {
1111
1235
  if (isParallelStep(step)) return { parallel: step.parallel };
1112
1236
  if (isDynamicParallelStep(step)) return { acceptance: step.acceptance, parallel: step.parallel };
1113
- return { acceptance: step.acceptance };
1237
+ return { acceptance: step.acceptance, outputSchema: step.outputSchema };
1114
1238
  }),
1115
1239
  });
1116
1240
  if (acceptanceErrors.length > 0) return formatAsyncStartError(resultMode, acceptanceErrors.join(" "));
1117
1241
  const capabilityCeiling = params.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(ctx.currentSessionId);
1118
- const inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();
1119
- const nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;
1242
+ const inheritedNestedRoute = inheritedNestedRouteOf(ctx.childRuntime);
1243
+ const nestedAddress = inheritedNestedRoute ? inheritedNestedParentAddressOf(ctx.childRuntime) : undefined;
1120
1244
  const asyncDir = inheritedNestedRoute
1121
1245
  ? path.join(TEMP_ROOT_DIR, "nested-subagent-runs", inheritedNestedRoute.rootRunId, id)
1122
1246
  : path.join(DIRS.async, id);
@@ -1140,6 +1264,7 @@ export function executeAsyncChain(
1140
1264
  attachRoot: params.attachRoot,
1141
1265
  resultMode,
1142
1266
  agents,
1267
+ unknownAgentDiagnosticContext: params.unknownAgentDiagnosticContext,
1143
1268
  ctx,
1144
1269
  availableModels: params.availableModels,
1145
1270
  cwd,
@@ -1153,7 +1278,10 @@ export function executeAsyncChain(
1153
1278
  dynamicFanoutMaxItems: params.dynamicFanoutMaxItems,
1154
1279
  maxSubagentDepth,
1155
1280
  waitToolEnabled: params.waitToolEnabled,
1281
+ waitToolDefaultTimeoutMs: params.waitToolDefaultTimeoutMs,
1156
1282
  worktreeBaseDir,
1283
+ worktreeProvider,
1284
+ worktreeBranchPrefix,
1157
1285
  asyncDir,
1158
1286
  fast: params.fast,
1159
1287
  toolBudget: params.toolBudget,
@@ -1174,7 +1302,6 @@ export function executeAsyncChain(
1174
1302
  }
1175
1303
  const { steps, runnerCwd, workflowGraph, eventChain } = built;
1176
1304
  const deadlineAt = params.timeoutMs !== undefined ? Date.now() + params.timeoutMs : undefined;
1177
- const initialTurnBudget = params.turnBudget ? initialTurnBudgetState(params.turnBudget) : undefined;
1178
1305
  const initialUsageBudget = usageBudgetState(params.usageBudget, undefined);
1179
1306
  let childTargetIndex = 0;
1180
1307
  const childIntercomTargets = childIntercomTarget ? steps.flatMap((step) => {
@@ -1191,6 +1318,21 @@ export function executeAsyncChain(
1191
1318
  }
1192
1319
  return "agent" in step ? [childIntercomTarget(step.agent, childTargetIndex++)] : [undefined];
1193
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();
1194
1336
 
1195
1337
  let spawnResult: SpawnRunnerResult = {};
1196
1338
  try {
@@ -1211,12 +1353,15 @@ export function executeAsyncChain(
1211
1353
  completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
1212
1354
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
1213
1355
  piPackageRoot,
1214
- piArgv1: process.argv[1],
1356
+ childSessionFactoryModule: childSessionFactoryModule(),
1357
+ inheritedChildRuntime: inheritedChildRuntime(ctx.childRuntime),
1215
1358
  worktreeSetupHook,
1216
1359
  worktreeSetupHookTimeoutMs,
1217
1360
  worktreeBaseDir,
1361
+ baseRef,
1362
+ worktreeProvider,
1363
+ worktreeBranchPrefix,
1218
1364
  controlConfig,
1219
- turnBudget: params.turnBudget,
1220
1365
  toolBudget: params.toolBudget,
1221
1366
  usageBudget: params.usageBudget,
1222
1367
  controlIntercomTarget,
@@ -1240,7 +1385,23 @@ export function executeAsyncChain(
1240
1385
  },
1241
1386
  id,
1242
1387
  runnerCwd,
1243
- (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),
1244
1405
  );
1245
1406
  } catch (error) {
1246
1407
  params.activeAsyncCapacity?.rollback();
@@ -1249,7 +1410,10 @@ export function executeAsyncChain(
1249
1410
  }
1250
1411
 
1251
1412
  if (spawnResult.error) {
1252
- 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();
1253
1417
  else params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
1254
1418
  return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': ${spawnResult.error}`);
1255
1419
  }
@@ -1257,8 +1421,6 @@ export function executeAsyncChain(
1257
1421
  params.activeAsyncCapacity?.rollback();
1258
1422
  return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': runner identity unavailable`);
1259
1423
  }
1260
- params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
1261
-
1262
1424
  if (spawnResult.pid) {
1263
1425
  const eventFirstStep = eventChain[0];
1264
1426
  if (!eventFirstStep) {
@@ -1309,7 +1471,7 @@ export function executeAsyncChain(
1309
1471
  path: nestedAddress.path,
1310
1472
  asyncDir,
1311
1473
  pid: spawnResult.pid,
1312
- ownerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,
1474
+ ownerIntercomTarget: ctx.childRuntime?.intercomSessionName,
1313
1475
  leafIntercomTarget: childIntercomTargets?.[0],
1314
1476
  intercomTarget: childIntercomTargets?.[0],
1315
1477
  ownerState: "live",
@@ -1320,7 +1482,6 @@ export function executeAsyncChain(
1320
1482
  chainStepCount: eventChain.length,
1321
1483
  parallelGroups,
1322
1484
  ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}),
1323
- ...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),
1324
1485
  startedAt: now,
1325
1486
  lastUpdate: now,
1326
1487
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
@@ -1351,7 +1512,6 @@ export function executeAsyncChain(
1351
1512
  asyncDir,
1352
1513
  ...(sessionRoot ? { sessionRoot } : {}),
1353
1514
  ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}),
1354
- ...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),
1355
1515
  ...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}),
1356
1516
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
1357
1517
  ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
@@ -1368,7 +1528,7 @@ export function executeAsyncChain(
1368
1528
 
1369
1529
  return {
1370
1530
  content: [{ type: "text", text: formatAsyncStartedMessage(`Async ${resultMode}: ${chainDesc} [${id}]`, ctx.interactive === true) }],
1371
- 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 } : {}) },
1372
1532
  };
1373
1533
  }
1374
1534
 
@@ -1398,11 +1558,21 @@ export function executeAsyncSingle(
1398
1558
  worktreeSetupHook,
1399
1559
  worktreeSetupHookTimeoutMs,
1400
1560
  worktreeBaseDir,
1561
+ baseRef,
1562
+ worktreeProvider,
1563
+ worktreeBranchPrefix,
1401
1564
  controlConfig,
1402
1565
  controlIntercomTarget,
1403
1566
  childIntercomTarget,
1404
1567
  nestedRoute,
1405
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
+ }
1406
1576
  const task = params.task ?? "";
1407
1577
  let extensionBindings: ExtensionBindings | undefined;
1408
1578
  try {
@@ -1429,14 +1599,25 @@ export function executeAsyncSingle(
1429
1599
  if (extensionBindings !== undefined) unsupported.push("extension bindings");
1430
1600
  if (unsupported.length > 0) return formatAsyncStartError("single", `Agent '${agentConfig.name}' uses runner.type='${externalRunnerType}' and does not support: ${unsupported.join(", ")}.`);
1431
1601
  }
1432
- 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);
1433
1603
  try {
1434
1604
  assertAgentAllowedByCapabilityCeiling(agentConfig.name, capabilityCeiling);
1435
1605
  } catch (error) {
1436
1606
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1437
1607
  }
1438
1608
  const runnerCwd = resolveChildCwd(ctx.cwd, cwd);
1439
- 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"
1440
1621
  ? resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s0`, 0, worktreeBaseDir)
1441
1622
  : runnerCwd;
1442
1623
  const readExistenceCwd = params.worktree === true ? runnerCwd : instructionCwd;
@@ -1461,8 +1642,8 @@ export function executeAsyncSingle(
1461
1642
  }
1462
1643
  systemPrompt = appendAgentRefinementOverlay(systemPrompt, { cwd: runnerCwd, agentName: agentConfig.name });
1463
1644
 
1464
- const inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();
1465
- const nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;
1645
+ const inheritedNestedRoute = inheritedNestedRouteOf(ctx.childRuntime);
1646
+ const nestedAddress = inheritedNestedRoute ? inheritedNestedParentAddressOf(ctx.childRuntime) : undefined;
1466
1647
  const asyncDir = inheritedNestedRoute
1467
1648
  ? path.join(TEMP_ROOT_DIR, "nested-subagent-runs", inheritedNestedRoute.rootRunId, id)
1468
1649
  : path.join(DIRS.async, id);
@@ -1490,27 +1671,44 @@ export function executeAsyncSingle(
1490
1671
  // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
1491
1672
  // absolute paths pass through; relative paths resolve against the child cwd.
1492
1673
  const reads = params.reads !== undefined ? params.reads : agentConfig.defaultReads ?? false;
1493
- 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
+ : [];
1494
1679
  const readsInstruction = readPaths.length > 0
1495
1680
  ? `[Read from: ${readPaths.join(", ")}]\n\n`
1496
1681
  : "";
1497
1682
  const taskText = readsInstruction + taskWithOutputInstruction;
1498
1683
  const modelScopes = resolveModelScopesForAgent(ctx.modelScope, agentConfig.name, ctx.currentModel);
1499
- const primaryModel = externalRunner ? undefined : params.modelOverrideFromParent
1500
- ? params.modelOverride
1501
- : resolveSubagentModelOverride(
1502
- params.modelOverride ?? agentConfig.model,
1503
- ctx.currentModel,
1504
- availableModels,
1505
- ctx.currentModelProvider,
1506
- { scope: modelScopes },
1507
- );
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
+ }
1508
1705
  const effectiveThinking = externalRunner ? undefined : params.thinkingOverride ?? agentConfig.thinking;
1509
1706
  const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinking, params.thinkingOverride !== undefined);
1707
+ const contextLimit = model ? findModelInfo(model, availableModels, agentConfig.modelProvider ?? ctx.currentModelProvider)?.contextWindow : undefined;
1510
1708
  const thinkingCeiling = externalRunner ? undefined : intersectThinkingCeilings(
1511
1709
  params.thinkingCeiling,
1512
1710
  agentConfig.maxThinking,
1513
- decodeThinkingCeiling(process.env[SUBAGENT_THINKING_CEILING_ENV]),
1711
+ ctx.childRuntime?.thinkingCeiling,
1514
1712
  );
1515
1713
  if (!externalRunner) {
1516
1714
  try {
@@ -1535,32 +1733,31 @@ export function executeAsyncSingle(
1535
1733
  });
1536
1734
  if (resolvedToolTimeout.error) return formatAsyncStartError("single", resolvedToolTimeout.error);
1537
1735
  const toolTimeoutMs = resolvedToolTimeout.toolTimeoutMs;
1538
- const initialTurnBudget = params.turnBudget ? initialTurnBudgetState(params.turnBudget) : undefined;
1539
1736
  const initialUsageBudget = usageBudgetState(params.usageBudget, undefined);
1540
1737
  const resolvedSessionDir = params.sessionDir ?? (sessionRoot ? path.join(sessionRoot, `async-${id}`) : undefined);
1541
1738
  const structuredOutput = params.structuredOutputSchema
1542
- ? createStructuredOutputRuntime(params.structuredOutputSchema, path.join(asyncDir, "structured-output"), { captureAcceptanceReport: params.acceptance !== false })
1739
+ ? createStructuredOutputRuntime(params.structuredOutputSchema, path.join(asyncDir, "structured-output"), { acceptanceReport: resolveAcceptanceReportMode(params.acceptance) })
1543
1740
  : undefined;
1544
- const modelCandidates = externalRunner
1545
- ? []
1546
- : buildModelCandidates(primaryModel, agentConfig.fallbackModels, availableModels, agentConfig.modelProvider ?? ctx.currentModelProvider, {
1547
- scope: modelScopes,
1548
- primaryModelFromParent: params.modelOverrideFromParent,
1549
- })
1550
- .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) => {
1551
1749
  const resolved = applyThinkingSuffix(candidate, effectiveThinking, params.thinkingOverride !== undefined);
1552
1750
  return resolved ? [resolved] : [];
1553
1751
  });
1554
- if (!externalRunner) {
1555
- try {
1556
1752
  for (const candidate of modelCandidates) assertThinkingWithinCeiling({ model: candidate, configThinking: effectiveThinking, ceiling: thinkingCeiling, agent: agentConfig.name, runId: id });
1557
1753
  } catch (error) {
1558
1754
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1559
1755
  }
1560
1756
  }
1561
- const effectiveSystemPrompt = appendTurnBudgetSystemPrompt(systemPrompt, params.turnBudget);
1562
1757
  const toolPlan = resolvePiLaunchToolPlan({
1563
1758
  tools: agentConfig.tools,
1759
+ excludeTools: agentConfig.excludeTools,
1760
+ allowNestedSubagents: agentConfig.allowNestedSubagents,
1564
1761
  extensions: agentConfig.extensions,
1565
1762
  subagentOnlyExtensions: agentConfig.subagentOnlyExtensions,
1566
1763
  mcpDirectTools: agentConfig.mcpDirectTools,
@@ -1571,9 +1768,10 @@ export function executeAsyncSingle(
1571
1768
  model,
1572
1769
  modelCandidates,
1573
1770
  capabilityCeiling,
1574
- inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
1771
+ inheritedCapabilityCeiling: ctx.childRuntime?.capabilityCeiling,
1575
1772
  agentName: agentConfig.name,
1576
1773
  permissionRules: resolvePermissionRules(ctx.permissions, agentConfig.permissions),
1774
+ runtimeSnapshotHost: ctx.pi,
1577
1775
  });
1578
1776
  const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
1579
1777
  if (!externalRunner) {
@@ -1598,12 +1796,14 @@ export function executeAsyncSingle(
1598
1796
  ...((params.fast ?? agentConfig.fast) !== undefined ? { fast: params.fast ?? agentConfig.fast } : {}),
1599
1797
  ...(resolveEffectiveThinking(model, effectiveThinking) ? { thinking: resolveEffectiveThinking(model, effectiveThinking) } : {}),
1600
1798
  ...(thinkingCeiling ? { thinkingCeiling } : {}),
1601
- systemPrompt: effectiveSystemPrompt,
1799
+ systemPrompt,
1602
1800
  systemPromptMode: agentConfig.systemPromptMode,
1603
1801
  inheritProjectContext: agentConfig.inheritProjectContext,
1802
+ inheritGlobalContext: agentConfig.inheritGlobalContext,
1604
1803
  inheritSkills: agentConfig.inheritSkills,
1605
1804
  skills: resolvedSkills.map((skill) => skill.name),
1606
1805
  tools: toolPlan.effectiveToolAllowlist,
1806
+ ...(toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
1607
1807
  extensions: toolPlan.extensionArgs,
1608
1808
  mcpDirectTools: toolPlan.effectiveMcpTools,
1609
1809
  ...(outputPath ? { outputPath } : {}),
@@ -1623,6 +1823,7 @@ export function executeAsyncSingle(
1623
1823
  const recoveryAgentConfig = params.recoveryAgentConfig ?? agentConfig;
1624
1824
  const recoveryDescriptor: SteeringRecoveryDescriptor = {
1625
1825
  version: 1,
1826
+ ...(lane ? { lane } : {}),
1626
1827
  launchContractDigest,
1627
1828
  ...(extensionBindings ? { extensionBindings } : {}),
1628
1829
  runFanoutBudget,
@@ -1635,17 +1836,22 @@ export function executeAsyncSingle(
1635
1836
  ...(model ? { model } : {}),
1636
1837
  ...(params.fast ?? recoveryAgentConfig.fast ? { fast: params.fast ?? recoveryAgentConfig.fast } : {}),
1637
1838
  ...(recoveryAgentConfig.modelProvider ? { modelProvider: recoveryAgentConfig.modelProvider } : {}),
1638
- ...(params.modelOverrideFromParent ? { modelOverrideFromParent: true } : {}),
1839
+ ...(modelOrigin === "inherited" ? { modelOverrideFromParent: true } : {}),
1840
+ modelOrigin,
1639
1841
  ...(recoveryAgentConfig.fallbackModels ? { fallbackModels: [...recoveryAgentConfig.fallbackModels] } : {}),
1640
1842
  ...(effectiveThinking ? { thinking: resolveEffectiveThinking(model, effectiveThinking) } : {}),
1641
1843
  ...(thinkingCeiling ? { thinkingCeiling } : {}),
1642
1844
  ...(recoveryAgentConfig.tools ? { tools: [...recoveryAgentConfig.tools] } : {}),
1845
+ ...(recoveryAgentConfig.excludeTools ? { excludeTools: [...recoveryAgentConfig.excludeTools] } : {}),
1846
+ ...(recoveryAgentConfig.allowNestedSubagents !== undefined ? { allowNestedSubagents: recoveryAgentConfig.allowNestedSubagents } : {}),
1643
1847
  ...(recoveryAgentConfig.extensions ? { extensions: [...recoveryAgentConfig.extensions] } : {}),
1644
1848
  ...(recoveryAgentConfig.subagentOnlyExtensions ? { subagentOnlyExtensions: [...recoveryAgentConfig.subagentOnlyExtensions] } : {}),
1645
1849
  ...(recoveryAgentConfig.mcpDirectTools ? { mcpDirectTools: [...recoveryAgentConfig.mcpDirectTools] } : {}),
1850
+ ...(recoveryAgentConfig.mutationTools ? { mutationTools: [...recoveryAgentConfig.mutationTools] } : {}),
1646
1851
  ...(recoveryAgentConfig.systemPrompt ? { systemPrompt: recoveryAgentConfig.systemPrompt } : {}),
1647
1852
  systemPromptMode: recoveryAgentConfig.systemPromptMode,
1648
1853
  inheritProjectContext: recoveryAgentConfig.inheritProjectContext,
1854
+ inheritGlobalContext: recoveryAgentConfig.inheritGlobalContext,
1649
1855
  inheritSkills: recoveryAgentConfig.inheritSkills,
1650
1856
  ...(resolvedSkills.length ? { skills: resolvedSkills.map((skill) => skill.name) } : {}),
1651
1857
  ...(recoveryAgentConfig.skillPath ? { skillPath: [...recoveryAgentConfig.skillPath] } : {}),
@@ -1659,8 +1865,8 @@ export function executeAsyncSingle(
1659
1865
  ...(controlConfig ? { controlConfig } : {}),
1660
1866
  ...(params.context ? { context: params.context } : {}),
1661
1867
  ...(params.intercomBridge !== undefined ? { intercomBridge: params.intercomBridge } : {}),
1868
+ ...(params.baseRef !== undefined ? { baseRef: params.baseRef } : {}),
1662
1869
  ...(deadlineAt !== undefined ? { absoluteDeadlineAt: deadlineAt } : {}),
1663
- ...(initialTurnBudget ? { initialTurnBudget: { maxTurns: initialTurnBudget.maxTurns, graceTurns: initialTurnBudget.graceTurns } } : {}),
1664
1870
  ...(resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {}),
1665
1871
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, recoveryAgentConfig.maxSubagentDepth),
1666
1872
  ...(maxOutput ? { maxOutput } : {}),
@@ -1678,6 +1884,8 @@ export function executeAsyncSingle(
1678
1884
  }
1679
1885
  }
1680
1886
  let spawnResult: SpawnRunnerResult = {};
1887
+ const initialStatusAt = Date.now();
1888
+ const initialCompletionOwnerId = ctx.completionOwnerId ?? currentCompletionOwnerId();
1681
1889
  try {
1682
1890
  spawnResult = spawnRunner(
1683
1891
  {
@@ -1693,28 +1901,36 @@ export function executeAsyncSingle(
1693
1901
  ...(params.externalJobFollowUp ? { externalJobFollowUp: params.externalJobFollowUp } : {}),
1694
1902
  ...(params.context ? { context: params.context } : {}),
1695
1903
  cwd: runnerCwd,
1904
+ requestedCwd: params.requestedCwd ?? runnerCwd,
1696
1905
  model,
1906
+ ...(contextLimit !== undefined ? { contextLimit } : {}),
1697
1907
  ...(params.fast ?? agentConfig.fast ? { fast: params.fast ?? agentConfig.fast } : {}),
1698
1908
  thinking: resolveEffectiveThinking(model, effectiveThinking),
1699
1909
  ...(thinkingCeiling ? { thinkingCeiling } : {}),
1700
1910
  modelCandidates,
1701
- ...(params.modelOverrideFromParent ? { skipPrimaryModelVerification: true } : {}),
1911
+ ...(modelOrigin === "inherited" ? { skipPrimaryModelVerification: true } : {}),
1702
1912
  ...(availableModels && availableModels.length > 0 ? { modelVerificationRegistry: availableModels } : {}),
1703
1913
  tools: agentConfig.tools,
1914
+ excludeTools: agentConfig.excludeTools,
1915
+ allowNestedSubagents: agentConfig.allowNestedSubagents,
1704
1916
  extensions: agentConfig.extensions,
1705
1917
  subagentOnlyExtensions: agentConfig.subagentOnlyExtensions,
1706
1918
  mcpDirectTools: agentConfig.mcpDirectTools,
1919
+ mutationTools: agentConfig.mutationTools,
1707
1920
  completionGuard: agentConfig.completionGuard,
1708
1921
  systemPrompt,
1709
1922
  systemPromptMode: agentConfig.systemPromptMode,
1710
1923
  inheritProjectContext: agentConfig.inheritProjectContext,
1924
+ inheritGlobalContext: agentConfig.inheritGlobalContext,
1711
1925
  inheritSkills: agentConfig.inheritSkills,
1712
1926
  skills: resolvedSkills.map((r) => r.name),
1713
1927
  outputPath,
1928
+ ...(params.outputClaimPath ? { outputClaimPath: params.outputClaimPath } : {}),
1714
1929
  outputMode,
1715
1930
  ...(!externalRunner && sessionFile ? { sessionFile } : {}),
1716
1931
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, agentConfig.maxSubagentDepth),
1717
1932
  waitToolEnabled: params.waitToolEnabled,
1933
+ waitToolDefaultTimeoutMs: params.waitToolDefaultTimeoutMs,
1718
1934
  ...(params.agentContract ? { agentContract: params.agentContract } : {}),
1719
1935
  definitionDigest: agentDefinitionDigest(agentConfig),
1720
1936
  launchBindingTask: task,
@@ -1722,10 +1938,12 @@ export function executeAsyncSingle(
1722
1938
  ...(extensionBindings ? { extensionBindings } : {}),
1723
1939
  launchResolvedExtensions,
1724
1940
  effectiveAcceptance: resolvedAcceptance,
1941
+ acceptanceInput: params.acceptance,
1725
1942
  ...(structuredOutput ? { structuredOutput } : {}),
1726
1943
  ...(params.structuredOutputSchema ? { structuredOutputSchema: params.structuredOutputSchema } : {}),
1727
1944
  ...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),
1728
1945
  ...(params.worktree === true ? { worktree: true } : {}),
1946
+ ...(lane ? { lane } : {}),
1729
1947
  },
1730
1948
  ],
1731
1949
  resultPath: params.parentWorkflowRunId !== undefined && (params.revivalLease !== undefined || params.workflowAwaitAsync === true)
@@ -1743,15 +1961,18 @@ export function executeAsyncSingle(
1743
1961
  completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
1744
1962
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
1745
1963
  piPackageRoot,
1746
- piArgv1: process.argv[1],
1964
+ childSessionFactoryModule: childSessionFactoryModule(),
1965
+ inheritedChildRuntime: inheritedChildRuntime(ctx.childRuntime),
1747
1966
  worktreeSetupHook,
1748
1967
  worktreeSetupHookTimeoutMs,
1749
1968
  worktreeBaseDir,
1969
+ baseRef,
1970
+ worktreeProvider,
1971
+ worktreeBranchPrefix,
1750
1972
  controlConfig,
1751
1973
  timeoutMs,
1752
1974
  deadlineAt,
1753
1975
  toolTimeoutMs,
1754
- turnBudget: params.turnBudget,
1755
1976
  toolBudget: params.toolBudget,
1756
1977
  usageBudget: params.usageBudget,
1757
1978
  controlIntercomTarget,
@@ -1762,6 +1983,7 @@ export function executeAsyncSingle(
1762
1983
  runFanoutBudget,
1763
1984
  ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
1764
1985
  ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
1986
+ ...(lane ? { lane } : {}),
1765
1987
  ...(params.revivalLease ? { revivalLease: params.revivalLease } : {}),
1766
1988
  nestedRoute: nestedRoute ?? inheritedNestedRoute,
1767
1989
  nestedSelf: inheritedNestedRoute && nestedAddress ? {
@@ -1773,7 +1995,24 @@ export function executeAsyncSingle(
1773
1995
  },
1774
1996
  id,
1775
1997
  runnerCwd,
1776
- (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,
1777
2016
  );
1778
2017
  } catch (error) {
1779
2018
  params.activeAsyncCapacity?.rollback();
@@ -1782,7 +2021,10 @@ export function executeAsyncSingle(
1782
2021
  }
1783
2022
 
1784
2023
  if (spawnResult.error) {
1785
- 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();
1786
2028
  else params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
1787
2029
  return formatAsyncStartError("single", `Failed to start async run '${id}': ${spawnResult.error}`);
1788
2030
  }
@@ -1790,8 +2032,6 @@ export function executeAsyncSingle(
1790
2032
  params.activeAsyncCapacity?.rollback();
1791
2033
  return formatAsyncStartError("single", `Failed to start async run '${id}': runner identity unavailable`);
1792
2034
  }
1793
- params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
1794
-
1795
2035
  if (spawnResult.pid) {
1796
2036
  if (inheritedNestedRoute && nestedAddress) {
1797
2037
  const now = Date.now();
@@ -1809,7 +2049,7 @@ export function executeAsyncSingle(
1809
2049
  path: nestedAddress.path,
1810
2050
  asyncDir,
1811
2051
  pid: spawnResult.pid,
1812
- ownerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,
2052
+ ownerIntercomTarget: ctx.childRuntime?.intercomSessionName,
1813
2053
  leafIntercomTarget: childIntercomTarget?.(agent, 0),
1814
2054
  intercomTarget: childIntercomTarget?.(agent, 0),
1815
2055
  ownerState: "live",
@@ -1819,7 +2059,6 @@ export function executeAsyncSingle(
1819
2059
  agents: [agent],
1820
2060
  chainStepCount: 1,
1821
2061
  ...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}),
1822
- ...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),
1823
2062
  startedAt: now,
1824
2063
  lastUpdate: now,
1825
2064
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
@@ -1847,7 +2086,6 @@ export function executeAsyncSingle(
1847
2086
  ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
1848
2087
  ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
1849
2088
  ...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}),
1850
- ...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),
1851
2089
  ...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}),
1852
2090
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
1853
2091
  nestedRoute,
@@ -1856,6 +2094,6 @@ export function executeAsyncSingle(
1856
2094
 
1857
2095
  return {
1858
2096
  content: [{ type: "text", text: formatAsyncStartedMessage(`Async: ${agent} [${id}]`, ctx.interactive === true) }],
1859
- 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,
1860
2098
  };
1861
2099
  }