@xzzpig/pi-subagents 0.8.0 → 0.10.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 (221) hide show
  1. package/CHANGELOG.md +477 -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 +195 -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 +7 -6
  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 +384 -115
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +14 -2
  35. package/src/agents/agents.ts +935 -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 +42 -21
  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 +77 -21
  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 +65 -29
  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 +7 -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 +417 -133
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +60 -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 +204 -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 +718 -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 +489 -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 +1223 -402
  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 +364 -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 +366 -0
  115. package/src/runs/shared/child-tool-plan.ts +632 -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 +146 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +99 -77
  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 +20 -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/sandbox-profile-guard.ts +85 -0
  149. package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
  150. package/src/runs/shared/single-output.ts +89 -22
  151. package/src/runs/shared/structured-output.ts +49 -9
  152. package/src/runs/shared/subagent-control.ts +6 -2
  153. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  154. package/src/runs/shared/task-intent.ts +21 -7
  155. package/src/runs/shared/tool-availability.ts +18 -62
  156. package/src/runs/shared/tool-budget.ts +0 -14
  157. package/src/runs/shared/tool-timeout.ts +1 -1
  158. package/src/runs/shared/workflow-graph.ts +16 -0
  159. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  160. package/src/runs/shared/worktree.ts +571 -62
  161. package/src/shared/atomic-json.ts +3 -1
  162. package/src/shared/child-session-name.ts +46 -0
  163. package/src/shared/extension-context.ts +24 -0
  164. package/src/shared/fork-context.ts +21 -12
  165. package/src/shared/fork-session-cwd.ts +27 -0
  166. package/src/shared/formatters.ts +18 -3
  167. package/src/shared/jsonl-writer.ts +11 -0
  168. package/src/shared/launch-contract.ts +11 -1
  169. package/src/shared/pruned-fork.ts +450 -0
  170. package/src/shared/sandbox-profile.ts +23 -0
  171. package/src/shared/session-file-trust.ts +19 -0
  172. package/src/shared/session-tokens.ts +14 -3
  173. package/src/shared/settings.ts +19 -105
  174. package/src/shared/shortcuts.ts +17 -0
  175. package/src/shared/thinking-ceiling.ts +0 -6
  176. package/src/shared/types.ts +545 -70
  177. package/src/shared/utils.ts +60 -93
  178. package/src/shared/workflow-child-permit.ts +207 -0
  179. package/src/slash/delegation-adapters.ts +1 -9
  180. package/src/slash/delegation-request.ts +0 -4
  181. package/src/slash/prompt-template-bridge.ts +37 -1
  182. package/src/slash/slash-bridge.ts +1 -2
  183. package/src/slash/slash-commands.ts +383 -116
  184. package/src/slash/slash-live-state.ts +22 -11
  185. package/src/slash/subagents-admin.ts +29 -12
  186. package/src/tui/fleet-native-transcript.ts +4 -0
  187. package/src/tui/fleet-status.ts +217 -82
  188. package/src/tui/fleet-transcript.ts +11 -5
  189. package/src/tui/fleet.ts +54 -28
  190. package/src/tui/render-helpers.ts +31 -0
  191. package/src/tui/render.ts +1429 -163
  192. package/src/watchdog/change-signature.ts +40 -1
  193. package/src/watchdog/child-status.ts +54 -34
  194. package/src/watchdog/diff-tool.ts +77 -0
  195. package/src/watchdog/emission-guard.ts +5 -3
  196. package/src/watchdog/guidance.ts +20 -0
  197. package/src/watchdog/register-child.ts +28 -25
  198. package/src/watchdog/register-main.ts +10 -9
  199. package/src/watchdog/render.ts +4 -5
  200. package/src/watchdog/review.ts +15 -4
  201. package/src/watchdog/rules.ts +70 -0
  202. package/src/watchdog/runtime.ts +75 -92
  203. package/src/watchdog/scope.ts +0 -11
  204. package/src/watchdog/settings.ts +48 -104
  205. package/src/watchdog/turn-delta.ts +1 -1
  206. package/src/watchdog/types.ts +18 -32
  207. package/src/watchdog/warning-format.ts +0 -1
  208. package/src/workflows/chat-progress.ts +7 -3
  209. package/src/workflows/host-command.ts +235 -0
  210. package/src/workflows/scripted-workflow.ts +988 -59
  211. package/src/workflows/workflow-checklist.ts +439 -0
  212. package/src/workflows/workflow-child-summary.ts +121 -0
  213. package/src/workflows/workflow-preflight.ts +297 -0
  214. package/src/workflows/workflow-receipt.ts +232 -6
  215. package/src/workflows/workflow-resources.ts +150 -0
  216. package/src/workflows/workflow-settlement.ts +246 -0
  217. package/src/runs/shared/child-protocol.ts +0 -401
  218. package/src/runs/shared/pi-args.ts +0 -935
  219. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  220. package/src/runs/shared/turn-budget.ts +0 -98
  221. 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, inheritsParentModel, 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,30 +66,39 @@ 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;
84
93
  const packageRoot = path.dirname(packageJsonPath);
85
- const pkg = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")) as {
86
- bin?: string | Record<string, string>;
87
- };
94
+ let parsed: unknown;
95
+ try {
96
+ parsed = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
97
+ } catch {
98
+ return undefined;
99
+ }
100
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
101
+ const pkg = parsed as { bin?: string | Record<string, string> };
88
102
  const binField = pkg.bin;
89
103
  const binPath = typeof binField === "string"
90
104
  ? binField
@@ -137,8 +151,14 @@ interface AsyncExecutionContext {
137
151
  currentModel?: ParentModel;
138
152
  /** Optional model-scope enforcement resolved from subagent settings. */
139
153
  modelScope?: ModelScopeConfig;
154
+ /** Parent-authoritative trust state for profile-aware project config merging. */
155
+ projectTrusted?: boolean;
156
+ /** Exact trusted parent cwd; project config applies only when it matches the child cwd. */
157
+ trustedProjectCwd?: string;
140
158
  /** Whether the parent session has an interactive UI. */
141
159
  interactive?: boolean;
160
+ /** The executor's own child runtime when the launch comes from an in-process child. */
161
+ childRuntime?: ChildRuntimeConfig;
142
162
  }
143
163
 
144
164
  export const DEFAULT_ASYNC_TIMEOUT_MS = 30 * 60 * 1000;
@@ -151,6 +171,8 @@ interface AsyncChainParams {
151
171
  attachRoot?: ImportedAsyncRoot & { agent: string; outputName?: string; label?: string };
152
172
  resultMode?: SubagentRunMode;
153
173
  agents: AgentConfig[];
174
+ /** Original discovery provenance, retained by normal callers for unknown-agent diagnostics. */
175
+ unknownAgentDiagnosticContext?: UnknownAgentDiagnosticContext;
154
176
  ctx: AsyncExecutionContext;
155
177
  availableModels?: AvailableModelInfo[];
156
178
  cwd?: string;
@@ -168,9 +190,13 @@ interface AsyncChainParams {
168
190
  dynamicFanoutMaxItems?: number;
169
191
  maxSubagentDepth: number;
170
192
  waitToolEnabled?: boolean;
193
+ waitToolDefaultTimeoutMs?: number;
171
194
  worktreeSetupHook?: string;
172
195
  worktreeSetupHookTimeoutMs?: number;
173
196
  worktreeBaseDir?: string;
197
+ baseRef?: string;
198
+ worktreeProvider?: import("../../shared/types.ts").WorktreeProvider;
199
+ worktreeBranchPrefix?: string;
174
200
  controlConfig?: ResolvedControlConfig;
175
201
  controlIntercomTarget?: string;
176
202
  childIntercomTarget?: (agent: string, index: number) => string | undefined;
@@ -178,7 +204,6 @@ interface AsyncChainParams {
178
204
  acceptance?: AcceptanceInput;
179
205
  fast?: boolean;
180
206
  timeoutMs?: number;
181
- turnBudget?: ResolvedTurnBudget;
182
207
  toolBudget?: ResolvedToolBudget;
183
208
  usageBudget?: UsageBudgetConfig;
184
209
  configToolBudget?: ResolvedToolBudget;
@@ -195,6 +220,7 @@ interface AsyncChainParams {
195
220
  runFanoutBudget?: RunFanoutBudgetDescriptor;
196
221
  parentWorkflowRunId?: string;
197
222
  workflowKey?: string;
223
+ lane?: WorkflowLaneMetadata;
198
224
  activeAsyncCapacity?: ActiveAsyncCapacityHandle;
199
225
  }
200
226
 
@@ -206,8 +232,11 @@ interface AsyncSingleParams {
206
232
  agentConfig: AgentConfig;
207
233
  /** Agent contract before per-run bridge injection, used only for recovery persistence. */
208
234
  recoveryAgentConfig?: AgentConfig;
235
+ /** Selected global sandbox profile carried across revival. */
236
+ sandbox?: string;
209
237
  ctx: AsyncExecutionContext;
210
238
  cwd?: string;
239
+ requestedCwd?: string;
211
240
  maxOutput?: MaxOutputConfig;
212
241
  artifactsDir?: string;
213
242
  artifactConfig: ArtifactConfig;
@@ -222,18 +251,24 @@ interface AsyncSingleParams {
222
251
  reads?: string[] | false;
223
252
  outputMode?: "inline" | "file-only";
224
253
  outputBaseDir?: string;
254
+ outputClaimPath?: string;
225
255
  agentContract?: AgentContract;
226
256
  structuredOutputSchema?: JsonSchemaObject;
227
257
  modelOverride?: string;
228
258
  modelOverrideFromParent?: boolean;
259
+ modelOrigin?: ModelOrigin;
229
260
  fast?: boolean;
230
261
  thinkingOverride?: AgentConfig["thinking"];
231
262
  availableModels?: AvailableModelInfo[];
232
263
  maxSubagentDepth: number;
233
264
  waitToolEnabled?: boolean;
265
+ waitToolDefaultTimeoutMs?: number;
234
266
  worktreeSetupHook?: string;
235
267
  worktreeSetupHookTimeoutMs?: number;
236
268
  worktreeBaseDir?: string;
269
+ baseRef?: string;
270
+ worktreeProvider?: import("../../shared/types.ts").WorktreeProvider;
271
+ worktreeBranchPrefix?: string;
237
272
  worktree?: boolean;
238
273
  controlConfig?: ResolvedControlConfig;
239
274
  intercomBridge?: IntercomBridgeConfig;
@@ -245,7 +280,6 @@ interface AsyncSingleParams {
245
280
  absoluteDeadlineAt?: number;
246
281
  /** Optional per-call hard toolTimeoutMs override (highest precedence). */
247
282
  toolTimeoutMs?: number;
248
- turnBudget?: { maxTurns: number; graceTurns?: number };
249
283
  toolBudget?: ResolvedToolBudget | ToolBudgetConfig;
250
284
  usageBudget?: UsageBudgetConfig;
251
285
  configToolBudget?: ResolvedToolBudget;
@@ -259,6 +293,7 @@ interface AsyncSingleParams {
259
293
  runFanoutBudget?: RunFanoutBudgetDescriptor;
260
294
  parentWorkflowRunId?: string;
261
295
  workflowKey?: string;
296
+ lane?: WorkflowLaneMetadata;
262
297
  workflowAwaitAsync?: boolean;
263
298
  activeAsyncCapacity?: ActiveAsyncCapacityHandle;
264
299
  externalJobFollowUp?: {
@@ -283,6 +318,8 @@ export interface AsyncRunnerStepBuildParams {
283
318
  attachRoot?: ImportedAsyncRoot & { agent: string; outputName?: string; label?: string };
284
319
  resultMode?: SubagentRunMode;
285
320
  agents: AgentConfig[];
321
+ /** Exact discovery provenance for failed resolution; omission triggers defensive fallback discovery. */
322
+ unknownAgentDiagnosticContext?: UnknownAgentDiagnosticContext;
286
323
  ctx: AsyncExecutionContext;
287
324
  availableModels?: AvailableModelInfo[];
288
325
  cwd?: string;
@@ -295,7 +332,10 @@ export interface AsyncRunnerStepBuildParams {
295
332
  dynamicFanoutMaxItems?: number;
296
333
  maxSubagentDepth: number;
297
334
  waitToolEnabled?: boolean;
335
+ waitToolDefaultTimeoutMs?: number;
298
336
  worktreeBaseDir?: string;
337
+ worktreeProvider?: import("../../shared/types.ts").WorktreeProvider;
338
+ worktreeBranchPrefix?: string;
299
339
  asyncDir: string;
300
340
  outputBaseDir?: string;
301
341
  validateOutputBindings?: boolean;
@@ -326,15 +366,15 @@ export function formatAsyncStartedMessage(headline: string, interactive: boolean
326
366
  const guidance = interactive
327
367
  ? [
328
368
  "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.",
369
+ "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.",
370
+ "Use bg_wait only for provider, detached, or other background work that lacks a native completion notification.",
371
+ "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
372
  "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
373
  ]
334
374
  : [
335
375
  "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.",
376
+ "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.",
377
+ "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
378
  ];
339
379
  return [headline, "", ...guidance].join("\n");
340
380
  }
@@ -346,9 +386,9 @@ export function isAsyncAvailable(): boolean {
346
386
  return jitiCliPath !== undefined;
347
387
  }
348
388
 
349
- export function resolveAsyncRunnerLogPaths(cfg: object): { stdoutPath: string; stderrPath: string } | undefined {
350
- const asyncDir = typeof (cfg as { asyncDir?: unknown }).asyncDir === "string"
351
- ? (cfg as { asyncDir: string }).asyncDir
389
+ export function resolveAsyncRunnerLogPaths(cfg: Record<string, unknown>): { stdoutPath: string; stderrPath: string } | undefined {
390
+ const asyncDir = typeof cfg.asyncDir === "string"
391
+ ? cfg.asyncDir
352
392
  : undefined;
353
393
  if (!asyncDir) return undefined;
354
394
  return {
@@ -418,13 +458,15 @@ function waitForRunnerStartup(startupPath: string, expectedState: RunnerStartupS
418
458
  return { ok: false, error: `Timed out after ${timeoutMs}ms waiting for the async runner startup state '${expectedState}'.`, startupDidNotProceed: true };
419
459
  }
420
460
 
461
+ const writePrivateStartupControlJson = createAtomicJsonWriter({ mode: 0o600, ignoreCleanupErrorAfterSuccess: true });
462
+
421
463
  function writeRunnerStartupControl(filePath: string, payload: { action: "ack" | "proceed"; token: string }): void {
422
464
  // Delegate to the shared atomic JSON writer (temp file + rename, retrying
423
465
  // transient Windows EPERM/EBUSY/EACCES locks and cleaning up the temp file
424
466
  // on failure), so the startup handshake gets the same locking resilience as
425
467
  // every other async control/result file. This is exercised by
426
468
  // test/unit/atomic-json.test.ts.
427
- writePrivateAtomicJson(filePath, payload);
469
+ writePrivateStartupControlJson(filePath, payload);
428
470
  }
429
471
 
430
472
  function runnerIsAlive(pid: number): boolean {
@@ -493,24 +535,40 @@ interface SpawnRunnerResult {
493
535
  startupDidNotProceed?: boolean;
494
536
  }
495
537
 
496
- function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal?: (proof: unknown) => void): SpawnRunnerResult {
538
+ function isStaleExtensionContextError(error: unknown): boolean {
539
+ return error instanceof Error && /extension ctx is stale|stale after session replacement or reload/i.test(error.message);
540
+ }
541
+
542
+ export function emitProcessTerminalEvent(ctx: AsyncExecutionContext, proof: unknown): void {
543
+ try {
544
+ ctx.pi.events.emit(SUBAGENT_PROCESS_TERMINAL_EVENT, proof);
545
+ } catch (error) {
546
+ if (isStaleExtensionContextError(error)) return;
547
+ console.error("Failed to emit subagent process-terminal event:", error);
548
+ }
549
+ }
550
+
551
+ function spawnRunner(cfg: Record<string, unknown>, suffix: string, cwd: string, initialStatus: Omit<AsyncStatus, "pid" | "processTerminal">, initialStatusPath: string, onProcessTerminal?: (proof: unknown) => void, onBeforeProceed?: (runnerProcessInstanceId: string) => void, requestedCwd = cwd): SpawnRunnerResult {
552
+ const cwdError = preflightLaunchCwd(requestedCwd, cwd);
553
+ if (cwdError) return { error: cwdError };
554
+
497
555
  if (!jitiCliPath) {
498
556
  return { error: "upstream jiti for TypeScript execution could not be found; ensure package dependencies are installed" };
499
557
  }
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}` };
558
+ if (!piPackageRoot) {
559
+ 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.` };
560
+ }
561
+ const hostPeerAliases = resolveHostPeerAliases(piPackageRoot);
562
+ if (hostPeerAliases.missing.length > 0) {
563
+ 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
564
  }
509
565
 
510
566
  fs.mkdirSync(TEMP_ROOT_DIR, { recursive: true });
511
567
  const cfgPath = getAsyncConfigPath(suffix);
512
568
  const runnerProcessInstanceId = randomUUID();
513
- const launchConfig = { ...cfg, runnerProcessInstanceId };
569
+ const hasRevivalLease = typeof (cfg as { revivalLease?: unknown }).revivalLease === "object";
570
+ const launchBarrierToken = hasRevivalLease ? undefined : runnerProcessInstanceId;
571
+ const launchConfig = { ...cfg, runnerProcessInstanceId, ...(launchBarrierToken ? { launchBarrierToken } : {}) };
514
572
  writePrivateAtomicJson(cfgPath, launchConfig);
515
573
  const runner = path.join(path.dirname(fileURLToPath(import.meta.url)), "subagent-runner.ts");
516
574
  const nodeCommand = resolveNodeExecutable();
@@ -523,7 +581,9 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal
523
581
  ? path.join(launchAsyncDir, "runner-startup.json")
524
582
  : undefined;
525
583
  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;
584
+ const startupProceedPath = launchAsyncDir && (startupPath || launchBarrierToken)
585
+ ? path.join(launchAsyncDir, "runner-startup-proceed.json")
586
+ : undefined;
527
587
  if (startupPath) fs.rmSync(startupPath, { force: true });
528
588
  if (startupAckPath) fs.rmSync(startupAckPath, { force: true });
529
589
  if (startupProceedPath) fs.rmSync(startupProceedPath, { force: true });
@@ -539,12 +599,12 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal
539
599
  }
540
600
  const proc = spawn(nodeCommand, [jitiCliPath, runner, cfgPath], {
541
601
  cwd,
542
- detached: true,
602
+ ...backgroundProcessOptions(),
543
603
  stdio: ["ignore", stdoutFd ?? "ignore", stderrFd ?? "ignore"],
544
- windowsHide: true,
545
604
  env: {
546
605
  ...omitExtensionBindingsEnv(process.env),
547
- ...(piPackageRoot ? { [PI_CODING_AGENT_PACKAGE_ROOT_ENV]: piPackageRoot } : {}),
606
+ [PI_CODING_AGENT_PACKAGE_ROOT_ENV]: piPackageRoot,
607
+ [JITI_ALIAS_ENV]: JSON.stringify(hostPeerAliases.aliases),
548
608
  },
549
609
  });
550
610
  closeFd(stdoutFd);
@@ -605,6 +665,45 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, onProcessTerminal
605
665
  if (typeof proc.pid !== "number") {
606
666
  return { error: `async runner did not produce a pid for cwd: ${cwd}` };
607
667
  }
668
+ try {
669
+ writePrivateAtomicJson(initialStatusPath, {
670
+ ...initialStatus,
671
+ pid: proc.pid,
672
+ processTerminal: { version: 1, state: "pending", runId: initialStatus.runId, runnerProcessInstanceId },
673
+ });
674
+ } catch (error) {
675
+ const message = `Failed to persist initial async status: ${error instanceof Error ? error.message : String(error)}`;
676
+ if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
677
+ const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
678
+ return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
679
+ }
680
+ try {
681
+ if (!launchAsyncDir) throw new Error("Async runner is missing its lifecycle directory.");
682
+ initializeProcessTerminal(launchAsyncDir, launchRunId, runnerProcessInstanceId);
683
+ } catch (error) {
684
+ const message = `Failed to establish async runner lifecycle sidecar: ${error instanceof Error ? error.message : String(error)}`;
685
+ if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
686
+ const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
687
+ return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
688
+ }
689
+ try {
690
+ onBeforeProceed?.(runnerProcessInstanceId);
691
+ } catch (error) {
692
+ const message = `Failed to establish async runner capacity ownership: ${error instanceof Error ? error.message : String(error)}`;
693
+ if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
694
+ const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
695
+ return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
696
+ }
697
+ if (launchBarrierToken && startupProceedPath) {
698
+ try {
699
+ writeRunnerStartupControl(startupProceedPath, { action: "proceed", token: launchBarrierToken });
700
+ } catch (error) {
701
+ const message = `Failed to authorize async runner startup: ${error instanceof Error ? error.message : String(error)}`;
702
+ if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
703
+ const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
704
+ return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
705
+ }
706
+ }
608
707
  proc.unref();
609
708
  if (startupPath && startupAckPath && startupProceedPath) {
610
709
  const persistStartupFailure = (message: string) => {
@@ -665,6 +764,19 @@ const UNAVAILABLE_SUBAGENT_SKILL_ERROR = "Skills not found: pi-subagents";
665
764
  class UnavailableSubagentSkillError extends Error {}
666
765
  class AsyncStartValidationError extends Error {}
667
766
 
767
+ function profileProjectTrustedForCwd(ctx: AsyncExecutionContext, cwd: string): boolean {
768
+ return ctx.projectTrusted === true
769
+ && ctx.trustedProjectCwd !== undefined
770
+ && path.resolve(ctx.trustedProjectCwd) === path.resolve(cwd);
771
+ }
772
+
773
+ function profileProjectTrustError(agent: AgentConfig, ctx: AsyncExecutionContext, cwd: string): string {
774
+ if (ctx.projectTrusted !== true) {
775
+ return `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but the project is not trusted. Trust the project and retry.`;
776
+ }
777
+ return `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but the child cwd is not an exact trusted project root. Launch from that trusted cwd and retry.`;
778
+ }
779
+
668
780
  export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildParams): AsyncRunnerStepBuildResult {
669
781
  const {
670
782
  chain,
@@ -675,6 +787,8 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
675
787
  thinkingOverridesByFlatIndex,
676
788
  maxSubagentDepth,
677
789
  worktreeBaseDir,
790
+ worktreeProvider,
791
+ worktreeBranchPrefix,
678
792
  asyncDir,
679
793
  } = params;
680
794
  const outputBaseDir = params.outputBaseDir;
@@ -682,6 +796,15 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
682
796
  const chainSkills = params.chainSkills ?? [];
683
797
  const availableModels = params.availableModels;
684
798
  const runnerCwd = resolveChildCwd(ctx.cwd, cwd);
799
+ let managedWorktreeProvider: "native" | "worktrunk" | undefined;
800
+ try {
801
+ if (chain.some((step) => "worktree" in step && step.worktree === true)) {
802
+ const resolved = resolveWorktreeProvider(worktreeProvider, worktreeBaseDir);
803
+ managedWorktreeProvider = shouldDeferWorktreeCwd(worktreeProvider, worktreeBaseDir) ? "worktrunk" : resolved;
804
+ }
805
+ } catch (error) {
806
+ return { error: error instanceof Error ? error.message : String(error) };
807
+ }
685
808
  const progressDir = params.progressDir ?? runnerCwd;
686
809
  const graphChain: ChainStep[] = params.attachRoot
687
810
  ? [{
@@ -709,6 +832,8 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
709
832
  }
710
833
  const workflowGraph = buildWorkflowGraphSnapshot({ runId: id, mode: resultMode, steps: graphChain });
711
834
 
835
+ const diagnosticContext = params.unknownAgentDiagnosticContext
836
+ ?? unknownAgentDiagnosticContext(discoverAgents(path.resolve(runnerCwd), "both"));
712
837
  for (const s of chain) {
713
838
  const stepAgents = isParallelStep(s)
714
839
  ? s.parallel.map((t) => t.agent)
@@ -716,9 +841,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
716
841
  ? [s.parallel.agent]
717
842
  : [(s as SequentialStep).agent];
718
843
  for (const agentName of stepAgents) {
719
- if (!agents.find((x) => x.name === agentName)) {
720
- return { error: `Unknown agent: ${agentName}` };
721
- }
844
+ if (!agents.find((x) => x.name === agentName)) return { error: formatUnknownAgentError(agentName, diagnosticContext) };
722
845
  }
723
846
  }
724
847
 
@@ -745,12 +868,13 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
745
868
  if (s.outputSchema !== undefined) unsupported.push("structured output");
746
869
  if (s.acceptance !== undefined || params.agentContract !== undefined || s.agentContract !== undefined) unsupported.push("acceptance/agent contract");
747
870
  if (s.toolBudget !== undefined || params.toolBudget !== undefined || a.toolBudget !== undefined || params.configToolBudget !== undefined) unsupported.push("tool budget");
871
+ if (a.sandbox !== undefined) unsupported.push("sandbox profile");
748
872
  if ((s.fast ?? params.fast ?? a.fast) === true) unsupported.push("fast mode");
749
873
  if (params.contextForAgent?.(s.agent) === "fork") unsupported.push("fork context");
750
874
  if (unsupported.length > 0) throw new AsyncStartValidationError(`Agent '${a.name}' uses runner.type='${externalRunnerType}' and does not support: ${unsupported.join(", ")}.`);
751
875
  }
752
876
  try {
753
- assertAgentAllowedByCapabilityCeiling(a.name, intersectSubagentCapabilityCeilings(params.capabilityCeiling, decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV])));
877
+ assertAgentAllowedByCapabilityCeiling(a.name, intersectSubagentCapabilityCeilings(params.capabilityCeiling, ctx.childRuntime?.capabilityCeiling));
754
878
  } catch (error) {
755
879
  throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
756
880
  }
@@ -764,19 +888,25 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
764
888
  envValue: params.toolTimeoutMsEnv ?? toolTimeoutFromEnv(),
765
889
  });
766
890
  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
- };
891
+ const launchPlan = planChildLaunch({
892
+ agentConfig: a,
893
+ stepOverrides: buildStepOverrides(s),
894
+ task: s.task,
895
+ originalTask,
896
+ runnerCwd,
897
+ runtimeCwd: ctx.cwd,
898
+ stepCwdInput: s.cwd,
899
+ behaviorCwd,
900
+ chainSkills,
901
+ outputBaseDir,
902
+ parallelOutputNamespace,
903
+ resolvedBehavior,
904
+ });
905
+ const { stepCwd, instructionCwd, readExistenceCwd, behavior, namespaceOutputPath, outputPath, skillNames } = launchPlan;
906
+ const profileChildCwd = behaviorCwd ?? stepCwd;
907
+ if (a.sandbox && (a.source === "project" || a.override?.scope === "project") && !profileProjectTrustedForCwd(ctx, profileChildCwd)) {
908
+ throw new AsyncStartValidationError(profileProjectTrustError(a, ctx, profileChildCwd));
777
909
  }
778
- const namespaceOutputPath = Boolean(inheritedRelativeParallelOutput && parallelOutputNamespace.taskIndex === undefined);
779
- const skillNames = behavior.skills === false ? [] : behavior.skills;
780
910
  const { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(
781
911
  skillNames,
782
912
  stepCwd,
@@ -801,33 +931,34 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
801
931
  const isFirstProgressAgent = behavior.progress && !progressPrecreated && !progressInstructionCreated;
802
932
  if (behavior.progress) progressInstructionCreated = true;
803
933
  const progressInstructions = buildChainInstructions({ ...behavior, output: false, reads: false }, progressDir, isFirstProgressAgent);
804
- const outputPath = resolveSingleOutputPath(behavior.output, ctx.cwd, instructionCwd, outputBaseDir);
805
934
  if (!namespaceOutputPath) systemPrompt = injectOutputPathSystemPrompt(systemPrompt, outputPath, a);
806
935
  const validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Async step (${s.agent})`);
807
936
  if (validationError) throw new AsyncStartValidationError(validationError);
808
937
  let taskTemplate = s.task ?? "{previous}";
809
938
  taskTemplate = taskTemplate.replace(/\{task\}/g, originalTask ?? "");
810
- taskTemplate = taskTemplate.replace(/\{chain_dir\}/g, runnerCwd);
939
+ taskTemplate = taskTemplate.replace(/\{chain_dir\}/g, behaviorCwd ?? runnerCwd);
811
940
  const taskText = `${readInstructions.prefix}${taskTemplate}${progressInstructions.suffix}`;
812
941
  const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a);
813
942
 
814
943
  const modelScopes = resolveModelScopesForAgent(ctx.modelScope, a.name, ctx.currentModel);
815
- const primaryModelFromParent = inheritsParentModel(s.model, a.model, ctx.currentModel);
944
+ const modelOrigin = resolveModelOrigin({ explicitModel: s.model, agentModel: a.model, parentModel: ctx.currentModel });
945
+ const primaryModelFromParent = modelOrigin === "inherited";
816
946
  const primaryModel = externalRunner ? undefined : resolveEffectiveSubagentModel(
817
947
  s.model,
818
948
  a.model,
819
949
  ctx.currentModel,
820
950
  availableModels,
821
951
  a.modelProvider ?? ctx.currentModelProvider,
822
- { scope: modelScopes },
952
+ { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" },
823
953
  );
824
954
  const thinkingOverride = flatIndex === undefined ? undefined : thinkingOverridesByFlatIndex?.[flatIndex];
825
955
  const effectiveThinking = externalRunner ? undefined : thinkingOverride ?? a.thinking;
826
956
  const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinking, thinkingOverride !== undefined);
957
+ const contextLimit = model ? findModelInfo(model, availableModels, a.modelProvider ?? ctx.currentModelProvider)?.contextWindow : undefined;
827
958
  const thinkingCeiling = externalRunner ? undefined : intersectThinkingCeilings(
828
959
  params.thinkingCeiling,
829
960
  a.maxThinking,
830
- decodeThinkingCeiling(process.env[SUBAGENT_THINKING_CEILING_ENV]),
961
+ ctx.childRuntime?.thinkingCeiling,
831
962
  );
832
963
  if (!externalRunner) {
833
964
  try {
@@ -838,23 +969,29 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
838
969
  }
839
970
  const agentContract = s.agentContract ?? params.agentContract;
840
971
  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
- });
972
+ let modelCandidates: string[] = [];
848
973
  if (!externalRunner) {
849
974
  try {
975
+ modelCandidates = buildModelCandidates(primaryModel, a.fallbackModels, availableModels, a.modelProvider ?? ctx.currentModelProvider, {
976
+ scope: modelScopes,
977
+ primaryModelFromParent,
978
+ origin: modelOrigin,
979
+ }).flatMap((candidate) => {
980
+ const resolved = applyThinkingSuffix(candidate, effectiveThinking, thinkingOverride !== undefined);
981
+ return resolved ? [resolved] : [];
982
+ });
850
983
  for (const candidate of modelCandidates) assertThinkingWithinCeiling({ model: candidate, configThinking: effectiveThinking, ceiling: thinkingCeiling, agent: a.name, runId: id });
851
984
  } catch (error) {
852
985
  throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
853
986
  }
854
987
  }
988
+ const launchRuleError = applyWatchdogLaunchRules({ cwd: stepCwd, agent: a.name, model: modelCandidates[0] ?? model, warn: (violation) => sendRuleViolationWarning(ctx.pi, violation) });
989
+ if (launchRuleError) throw new AsyncStartValidationError(launchRuleError);
855
990
  const fast = s.fast ?? params.fast ?? a.fast;
856
991
  const toolPlan = resolvePiLaunchToolPlan({
857
992
  tools: a.tools,
993
+ excludeTools: a.excludeTools,
994
+ allowNestedSubagents: a.allowNestedSubagents,
858
995
  extensions: a.extensions,
859
996
  subagentOnlyExtensions: a.subagentOnlyExtensions,
860
997
  mcpDirectTools: a.mcpDirectTools,
@@ -865,9 +1002,11 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
865
1002
  model,
866
1003
  modelCandidates,
867
1004
  capabilityCeiling: params.capabilityCeiling,
868
- inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
1005
+ inheritedCapabilityCeiling: ctx.childRuntime?.capabilityCeiling,
869
1006
  agentName: a.name,
870
1007
  permissionRules,
1008
+ runtimeSnapshotHost: ctx.pi,
1009
+ sandbox: a.sandbox,
871
1010
  });
872
1011
  const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
873
1012
  if (externalRunner && permissionRules) {
@@ -890,6 +1029,8 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
890
1029
  return {
891
1030
  parentSessionId: ctx.parentSessionId ?? ctx.currentSessionId,
892
1031
  permissionRules,
1032
+ ...(ctx.projectTrusted !== undefined ? { projectTrusted: ctx.projectTrusted } : {}),
1033
+ ...(ctx.trustedProjectCwd ? { trustedProjectCwd: ctx.trustedProjectCwd } : {}),
893
1034
  ...(params.capabilityCeiling ? { capabilityCeiling: params.capabilityCeiling } : {}),
894
1035
  ...(runFanoutPath ? { runFanoutPath } : {}),
895
1036
  agent: s.agent,
@@ -902,7 +1043,9 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
902
1043
  outputName: s.as,
903
1044
  structured: Boolean(s.outputSchema),
904
1045
  cwd: stepCwd,
1046
+ requestedCwd: s.cwd ?? stepCwd,
905
1047
  model,
1048
+ ...(contextLimit !== undefined ? { contextLimit } : {}),
906
1049
  ...(fast !== undefined ? { fast } : {}),
907
1050
  thinking: resolveEffectiveThinking(model, effectiveThinking),
908
1051
  ...(thinkingCeiling ? { thinkingCeiling } : {}),
@@ -911,13 +1054,18 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
911
1054
  ...(primaryModelFromParent ? { skipPrimaryModelVerification: true } : {}),
912
1055
  ...(availableModels && availableModels.length > 0 ? { modelVerificationRegistry: availableModels } : {}),
913
1056
  tools: a.tools,
1057
+ excludeTools: a.excludeTools,
1058
+ allowNestedSubagents: a.allowNestedSubagents,
914
1059
  extensions: a.extensions,
915
1060
  subagentOnlyExtensions: a.subagentOnlyExtensions,
916
1061
  mcpDirectTools: a.mcpDirectTools,
1062
+ mutationTools: a.mutationTools,
917
1063
  completionGuard: a.completionGuard,
1064
+ ...(a.sandbox ? { sandbox: a.sandbox } : {}),
918
1065
  systemPrompt,
919
1066
  systemPromptMode: a.systemPromptMode,
920
1067
  inheritProjectContext: a.inheritProjectContext,
1068
+ inheritGlobalContext: a.inheritGlobalContext,
921
1069
  inheritSkills: a.inheritSkills,
922
1070
  skills: resolvedSkills.map((r) => r.name),
923
1071
  outputPath,
@@ -928,6 +1076,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
928
1076
  timeoutMs: a.defaultTimeoutMs ?? DEFAULT_ASYNC_TIMEOUT_MS,
929
1077
  toolTimeoutMs: resolvedToolTimeout.toolTimeoutMs,
930
1078
  waitToolEnabled: params.waitToolEnabled,
1079
+ waitToolDefaultTimeoutMs: params.waitToolDefaultTimeoutMs,
931
1080
  effectiveAcceptance: resolveEffectiveAcceptance({
932
1081
  explicit: s.acceptance,
933
1082
  agentName: s.agent,
@@ -942,7 +1091,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
942
1091
  acceptanceRole: a.acceptanceRole,
943
1092
  ...(s.gateOn ? { gateOn: s.gateOn } : {}),
944
1093
  ...(s.outputSchema ? { structuredOutputSchema: s.outputSchema } : {}),
945
- ...(s.outputSchema ? { structuredOutput: createStructuredOutputRuntime(s.outputSchema, path.join(asyncDir, "structured-output"), { captureAcceptanceReport: s.acceptance !== false }) } : {}),
1094
+ ...(s.outputSchema ? { structuredOutput: createStructuredOutputRuntime(s.outputSchema, path.join(asyncDir, "structured-output"), { acceptanceReport: resolveAcceptanceReportMode(s.acceptance) }) } : {}),
946
1095
  ...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),
947
1096
  ...(s.worktree ? { worktree: true } : {}),
948
1097
  };
@@ -976,7 +1125,9 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
976
1125
  return {
977
1126
  parallel: s.parallel.map((t, taskIndex) => {
978
1127
  let behaviorCwd: string | undefined;
979
- if (s.worktree) {
1128
+ if (s.worktree && managedWorktreeProvider === "worktrunk") {
1129
+ behaviorCwd = WORKTREE_AGENT_CWD_PLACEHOLDER;
1130
+ } else if (s.worktree && managedWorktreeProvider === "native") {
980
1131
  try {
981
1132
  behaviorCwd = resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s${stepIndex}`, taskIndex, worktreeBaseDir);
982
1133
  } catch {
@@ -1031,7 +1182,9 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1031
1182
  }
1032
1183
  const sequential = s as SequentialStep;
1033
1184
  let behaviorCwd: string | undefined;
1034
- if (sequential.worktree) {
1185
+ if (sequential.worktree && managedWorktreeProvider === "worktrunk") {
1186
+ behaviorCwd = WORKTREE_AGENT_CWD_PLACEHOLDER;
1187
+ } else if (sequential.worktree && managedWorktreeProvider === "native") {
1035
1188
  try {
1036
1189
  behaviorCwd = resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s${stepIndex}`, 0, worktreeBaseDir);
1037
1190
  } catch {
@@ -1054,6 +1207,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1054
1207
  index: params.attachRoot.index,
1055
1208
  },
1056
1209
  inheritProjectContext: false,
1210
+ inheritGlobalContext: false,
1057
1211
  inheritSkills: false,
1058
1212
  }, ...builtSteps]
1059
1213
  : builtSteps;
@@ -1100,6 +1254,9 @@ export function executeAsyncChain(
1100
1254
  worktreeSetupHook,
1101
1255
  worktreeSetupHookTimeoutMs,
1102
1256
  worktreeBaseDir,
1257
+ baseRef,
1258
+ worktreeProvider,
1259
+ worktreeBranchPrefix,
1103
1260
  controlConfig,
1104
1261
  controlIntercomTarget,
1105
1262
  childIntercomTarget,
@@ -1110,13 +1267,13 @@ export function executeAsyncChain(
1110
1267
  chain: chain.map((step) => {
1111
1268
  if (isParallelStep(step)) return { parallel: step.parallel };
1112
1269
  if (isDynamicParallelStep(step)) return { acceptance: step.acceptance, parallel: step.parallel };
1113
- return { acceptance: step.acceptance };
1270
+ return { acceptance: step.acceptance, outputSchema: step.outputSchema };
1114
1271
  }),
1115
1272
  });
1116
1273
  if (acceptanceErrors.length > 0) return formatAsyncStartError(resultMode, acceptanceErrors.join(" "));
1117
1274
  const capabilityCeiling = params.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(ctx.currentSessionId);
1118
- const inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();
1119
- const nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;
1275
+ const inheritedNestedRoute = inheritedNestedRouteOf(ctx.childRuntime);
1276
+ const nestedAddress = inheritedNestedRoute ? inheritedNestedParentAddressOf(ctx.childRuntime) : undefined;
1120
1277
  const asyncDir = inheritedNestedRoute
1121
1278
  ? path.join(TEMP_ROOT_DIR, "nested-subagent-runs", inheritedNestedRoute.rootRunId, id)
1122
1279
  : path.join(DIRS.async, id);
@@ -1140,6 +1297,7 @@ export function executeAsyncChain(
1140
1297
  attachRoot: params.attachRoot,
1141
1298
  resultMode,
1142
1299
  agents,
1300
+ unknownAgentDiagnosticContext: params.unknownAgentDiagnosticContext,
1143
1301
  ctx,
1144
1302
  availableModels: params.availableModels,
1145
1303
  cwd,
@@ -1153,7 +1311,10 @@ export function executeAsyncChain(
1153
1311
  dynamicFanoutMaxItems: params.dynamicFanoutMaxItems,
1154
1312
  maxSubagentDepth,
1155
1313
  waitToolEnabled: params.waitToolEnabled,
1314
+ waitToolDefaultTimeoutMs: params.waitToolDefaultTimeoutMs,
1156
1315
  worktreeBaseDir,
1316
+ worktreeProvider,
1317
+ worktreeBranchPrefix,
1157
1318
  asyncDir,
1158
1319
  fast: params.fast,
1159
1320
  toolBudget: params.toolBudget,
@@ -1174,7 +1335,6 @@ export function executeAsyncChain(
1174
1335
  }
1175
1336
  const { steps, runnerCwd, workflowGraph, eventChain } = built;
1176
1337
  const deadlineAt = params.timeoutMs !== undefined ? Date.now() + params.timeoutMs : undefined;
1177
- const initialTurnBudget = params.turnBudget ? initialTurnBudgetState(params.turnBudget) : undefined;
1178
1338
  const initialUsageBudget = usageBudgetState(params.usageBudget, undefined);
1179
1339
  let childTargetIndex = 0;
1180
1340
  const childIntercomTargets = childIntercomTarget ? steps.flatMap((step) => {
@@ -1191,6 +1351,21 @@ export function executeAsyncChain(
1191
1351
  }
1192
1352
  return "agent" in step ? [childIntercomTarget(step.agent, childTargetIndex++)] : [undefined];
1193
1353
  }) : undefined;
1354
+ const initialStatusSteps = eventChain.flatMap((step) => isParallelStep(step)
1355
+ ? 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 }))
1356
+ : isDynamicParallelStep(step)
1357
+ ? [{ agent: `expand:${step.parallel.agent}`, label: step.label ?? step.parallel.label ?? `Dynamic fanout (${step.collect.as})`, outputName: step.collect.as, status: "pending" as const }]
1358
+ : [{ 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 }]);
1359
+ const initialParallelGroups: AsyncParallelGroupStatus[] = [];
1360
+ let initialFlatIndex = 0;
1361
+ for (let stepIndex = 0; stepIndex < eventChain.length; stepIndex++) {
1362
+ const step = eventChain[stepIndex]!;
1363
+ if (isParallelStep(step)) initialParallelGroups.push({ start: initialFlatIndex, count: step.parallel.length, stepIndex });
1364
+ else if (isDynamicParallelStep(step)) initialParallelGroups.push({ start: initialFlatIndex, count: 1, stepIndex });
1365
+ initialFlatIndex += isParallelStep(step) ? step.parallel.length : 1;
1366
+ }
1367
+ const initialStatusAt = Date.now();
1368
+ const initialCompletionOwnerId = ctx.completionOwnerId ?? currentCompletionOwnerId();
1194
1369
 
1195
1370
  let spawnResult: SpawnRunnerResult = {};
1196
1371
  try {
@@ -1211,12 +1386,15 @@ export function executeAsyncChain(
1211
1386
  completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
1212
1387
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
1213
1388
  piPackageRoot,
1214
- piArgv1: process.argv[1],
1389
+ childSessionFactoryModule: childSessionFactoryModule(),
1390
+ inheritedChildRuntime: inheritedChildRuntime(ctx.childRuntime),
1215
1391
  worktreeSetupHook,
1216
1392
  worktreeSetupHookTimeoutMs,
1217
1393
  worktreeBaseDir,
1394
+ baseRef,
1395
+ worktreeProvider,
1396
+ worktreeBranchPrefix,
1218
1397
  controlConfig,
1219
- turnBudget: params.turnBudget,
1220
1398
  toolBudget: params.toolBudget,
1221
1399
  usageBudget: params.usageBudget,
1222
1400
  controlIntercomTarget,
@@ -1240,7 +1418,23 @@ export function executeAsyncChain(
1240
1418
  },
1241
1419
  id,
1242
1420
  runnerCwd,
1243
- (proof) => ctx.pi.events.emit(SUBAGENT_PROCESS_TERMINAL_EVENT, proof),
1421
+ {
1422
+ lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
1423
+ runId: id,
1424
+ ...(ctx.currentSessionId ? { sessionId: ctx.currentSessionId } : {}),
1425
+ ...(initialCompletionOwnerId ? { completionOwnerId: initialCompletionOwnerId } : {}),
1426
+ mode: resultMode,
1427
+ state: "running",
1428
+ startedAt: initialStatusAt,
1429
+ lastUpdate: initialStatusAt,
1430
+ currentStep: 0,
1431
+ chainStepCount: eventChain.length,
1432
+ ...(initialParallelGroups.length ? { parallelGroups: initialParallelGroups } : {}),
1433
+ steps: initialStatusSteps,
1434
+ },
1435
+ path.join(asyncDir, "status.json"),
1436
+ (proof) => emitProcessTerminalEvent(ctx, proof),
1437
+ (runnerProcessInstanceId) => params.activeAsyncCapacity?.markStarted(runnerProcessInstanceId),
1244
1438
  );
1245
1439
  } catch (error) {
1246
1440
  params.activeAsyncCapacity?.rollback();
@@ -1249,7 +1443,10 @@ export function executeAsyncChain(
1249
1443
  }
1250
1444
 
1251
1445
  if (spawnResult.error) {
1252
- if (!spawnResult.pid || !spawnResult.runnerProcessInstanceId || (spawnResult.startupDidNotProceed && spawnResult.terminationObserved)) params.activeAsyncCapacity?.rollback();
1446
+ if (spawnResult.startupDidNotProceed) {
1447
+ if (!spawnResult.runnerProcessInstanceId || params.activeAsyncCapacity?.rollbackBeforeRunnerProceed(spawnResult.runnerProcessInstanceId) !== true) params.activeAsyncCapacity?.rollback();
1448
+ }
1449
+ else if (!spawnResult.pid || !spawnResult.runnerProcessInstanceId) params.activeAsyncCapacity?.rollback();
1253
1450
  else params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
1254
1451
  return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': ${spawnResult.error}`);
1255
1452
  }
@@ -1257,8 +1454,6 @@ export function executeAsyncChain(
1257
1454
  params.activeAsyncCapacity?.rollback();
1258
1455
  return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': runner identity unavailable`);
1259
1456
  }
1260
- params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
1261
-
1262
1457
  if (spawnResult.pid) {
1263
1458
  const eventFirstStep = eventChain[0];
1264
1459
  if (!eventFirstStep) {
@@ -1309,7 +1504,7 @@ export function executeAsyncChain(
1309
1504
  path: nestedAddress.path,
1310
1505
  asyncDir,
1311
1506
  pid: spawnResult.pid,
1312
- ownerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,
1507
+ ownerIntercomTarget: ctx.childRuntime?.intercomSessionName,
1313
1508
  leafIntercomTarget: childIntercomTargets?.[0],
1314
1509
  intercomTarget: childIntercomTargets?.[0],
1315
1510
  ownerState: "live",
@@ -1320,7 +1515,6 @@ export function executeAsyncChain(
1320
1515
  chainStepCount: eventChain.length,
1321
1516
  parallelGroups,
1322
1517
  ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}),
1323
- ...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),
1324
1518
  startedAt: now,
1325
1519
  lastUpdate: now,
1326
1520
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
@@ -1351,7 +1545,6 @@ export function executeAsyncChain(
1351
1545
  asyncDir,
1352
1546
  ...(sessionRoot ? { sessionRoot } : {}),
1353
1547
  ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}),
1354
- ...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),
1355
1548
  ...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}),
1356
1549
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
1357
1550
  ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
@@ -1368,7 +1561,7 @@ export function executeAsyncChain(
1368
1561
 
1369
1562
  return {
1370
1563
  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 } : {}) },
1564
+ 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
1565
  };
1373
1566
  }
1374
1567
 
@@ -1398,11 +1591,21 @@ export function executeAsyncSingle(
1398
1591
  worktreeSetupHook,
1399
1592
  worktreeSetupHookTimeoutMs,
1400
1593
  worktreeBaseDir,
1594
+ baseRef,
1595
+ worktreeProvider,
1596
+ worktreeBranchPrefix,
1401
1597
  controlConfig,
1402
1598
  controlIntercomTarget,
1403
1599
  childIntercomTarget,
1404
1600
  nestedRoute,
1405
1601
  } = params;
1602
+ let lane: WorkflowLaneMetadata | undefined;
1603
+ try {
1604
+ lane = normalizeWorkflowLaneMetadata(params.lane, "lane");
1605
+ assertWorkflowLaneKey(lane, params.workflowKey, "lane");
1606
+ } catch (error) {
1607
+ return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1608
+ }
1406
1609
  const task = params.task ?? "";
1407
1610
  let extensionBindings: ExtensionBindings | undefined;
1408
1611
  try {
@@ -1415,6 +1618,7 @@ export function executeAsyncSingle(
1415
1618
  const externalRunner = agentConfig.runner?.type === "external-cli" || agentConfig.runner?.type === "external-job";
1416
1619
  const externalRunnerType = agentConfig.runner?.type;
1417
1620
  const permissionRules = resolvePermissionRules(ctx.permissions, agentConfig.permissions);
1621
+ const sandbox = params.sandbox ?? agentConfig.sandbox;
1418
1622
  if (externalRunner) {
1419
1623
  const unsupported: string[] = [];
1420
1624
  if (params.modelOverride !== undefined) unsupported.push("model override");
@@ -1423,22 +1627,37 @@ export function executeAsyncSingle(
1423
1627
  if (params.structuredOutputSchema !== undefined) unsupported.push("structured output");
1424
1628
  if (params.acceptance !== undefined || params.agentContract !== undefined) unsupported.push("acceptance/agent contract");
1425
1629
  if (params.toolBudget !== undefined || agentConfig.toolBudget !== undefined || params.configToolBudget !== undefined) unsupported.push("tool budget");
1630
+ if (sandbox !== undefined) unsupported.push("sandbox profile");
1426
1631
  if (params.context === "fork") unsupported.push("fork context");
1427
1632
  if ((params.skills?.length ?? 0) > 0) unsupported.push("skills");
1428
1633
  if (permissionRules) unsupported.push("native Pi child permissions");
1429
1634
  if (extensionBindings !== undefined) unsupported.push("extension bindings");
1430
1635
  if (unsupported.length > 0) return formatAsyncStartError("single", `Agent '${agentConfig.name}' uses runner.type='${externalRunnerType}' and does not support: ${unsupported.join(", ")}.`);
1431
1636
  }
1432
- const capabilityCeiling = intersectSubagentCapabilityCeilings(params.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(ctx.currentSessionId), decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]));
1637
+ const capabilityCeiling = intersectSubagentCapabilityCeilings(params.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(ctx.currentSessionId), ctx.childRuntime?.capabilityCeiling);
1433
1638
  try {
1434
1639
  assertAgentAllowedByCapabilityCeiling(agentConfig.name, capabilityCeiling);
1435
1640
  } catch (error) {
1436
1641
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1437
1642
  }
1438
1643
  const runnerCwd = resolveChildCwd(ctx.cwd, cwd);
1439
- const instructionCwd = params.worktree === true
1644
+ let managedWorktreeProvider: "native" | "worktrunk" | undefined;
1645
+ if (params.worktree === true) {
1646
+ try {
1647
+ const resolved = resolveWorktreeProvider(params.worktreeProvider, worktreeBaseDir);
1648
+ managedWorktreeProvider = shouldDeferWorktreeCwd(params.worktreeProvider, worktreeBaseDir) ? "worktrunk" : resolved;
1649
+ } catch (error) {
1650
+ return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1651
+ }
1652
+ }
1653
+ const instructionCwd = params.worktree === true && managedWorktreeProvider === "worktrunk"
1654
+ ? WORKTREE_AGENT_CWD_PLACEHOLDER
1655
+ : params.worktree === true && managedWorktreeProvider === "native"
1440
1656
  ? resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s0`, 0, worktreeBaseDir)
1441
1657
  : runnerCwd;
1658
+ if (sandbox && (agentConfig.source === "project" || agentConfig.override?.scope === "project") && !profileProjectTrustedForCwd(ctx, instructionCwd)) {
1659
+ return formatAsyncStartError("single", profileProjectTrustError(agentConfig, ctx, instructionCwd));
1660
+ }
1442
1661
  const readExistenceCwd = params.worktree === true ? runnerCwd : instructionCwd;
1443
1662
  const skillNames = params.skills ?? agentConfig.skills ?? [];
1444
1663
  const availableModels = params.availableModels;
@@ -1461,8 +1680,8 @@ export function executeAsyncSingle(
1461
1680
  }
1462
1681
  systemPrompt = appendAgentRefinementOverlay(systemPrompt, { cwd: runnerCwd, agentName: agentConfig.name });
1463
1682
 
1464
- const inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();
1465
- const nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;
1683
+ const inheritedNestedRoute = inheritedNestedRouteOf(ctx.childRuntime);
1684
+ const nestedAddress = inheritedNestedRoute ? inheritedNestedParentAddressOf(ctx.childRuntime) : undefined;
1466
1685
  const asyncDir = inheritedNestedRoute
1467
1686
  ? path.join(TEMP_ROOT_DIR, "nested-subagent-runs", inheritedNestedRoute.rootRunId, id)
1468
1687
  : path.join(DIRS.async, id);
@@ -1490,27 +1709,44 @@ export function executeAsyncSingle(
1490
1709
  // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
1491
1710
  // absolute paths pass through; relative paths resolve against the child cwd.
1492
1711
  const reads = params.reads !== undefined ? params.reads : agentConfig.defaultReads ?? false;
1493
- const readPaths = Array.isArray(reads) ? resolveExistingReadPaths(reads, readExistenceCwd) : [];
1712
+ const readPaths = Array.isArray(reads)
1713
+ ? managedWorktreeProvider === "worktrunk"
1714
+ ? resolveExistingReadInstructionPaths(reads, instructionCwd, readExistenceCwd)
1715
+ : resolveExistingReadPaths(reads, readExistenceCwd)
1716
+ : [];
1494
1717
  const readsInstruction = readPaths.length > 0
1495
1718
  ? `[Read from: ${readPaths.join(", ")}]\n\n`
1496
1719
  : "";
1497
1720
  const taskText = readsInstruction + taskWithOutputInstruction;
1498
1721
  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
- );
1722
+ const modelOrigin = resolveModelOrigin({
1723
+ fromParent: params.modelOverrideFromParent,
1724
+ storedOrigin: params.modelOrigin,
1725
+ explicitModel: params.modelOverrideFromParent ? undefined : params.modelOverride,
1726
+ agentModel: agentConfig.model,
1727
+ parentModel: ctx.currentModel,
1728
+ });
1729
+ let primaryModel: string | undefined;
1730
+ try {
1731
+ primaryModel = externalRunner ? undefined : modelOrigin === "inherited"
1732
+ ? params.modelOverride ?? (ctx.currentModel ? `${ctx.currentModel.provider}/${ctx.currentModel.id}` : undefined)
1733
+ : resolveSubagentModelOverride(
1734
+ params.modelOverride ?? agentConfig.model,
1735
+ ctx.currentModel,
1736
+ availableModels,
1737
+ ctx.currentModelProvider,
1738
+ { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" },
1739
+ );
1740
+ } catch (error) {
1741
+ return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1742
+ }
1508
1743
  const effectiveThinking = externalRunner ? undefined : params.thinkingOverride ?? agentConfig.thinking;
1509
1744
  const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinking, params.thinkingOverride !== undefined);
1745
+ const contextLimit = model ? findModelInfo(model, availableModels, agentConfig.modelProvider ?? ctx.currentModelProvider)?.contextWindow : undefined;
1510
1746
  const thinkingCeiling = externalRunner ? undefined : intersectThinkingCeilings(
1511
1747
  params.thinkingCeiling,
1512
1748
  agentConfig.maxThinking,
1513
- decodeThinkingCeiling(process.env[SUBAGENT_THINKING_CEILING_ENV]),
1749
+ ctx.childRuntime?.thinkingCeiling,
1514
1750
  );
1515
1751
  if (!externalRunner) {
1516
1752
  try {
@@ -1535,32 +1771,31 @@ export function executeAsyncSingle(
1535
1771
  });
1536
1772
  if (resolvedToolTimeout.error) return formatAsyncStartError("single", resolvedToolTimeout.error);
1537
1773
  const toolTimeoutMs = resolvedToolTimeout.toolTimeoutMs;
1538
- const initialTurnBudget = params.turnBudget ? initialTurnBudgetState(params.turnBudget) : undefined;
1539
1774
  const initialUsageBudget = usageBudgetState(params.usageBudget, undefined);
1540
1775
  const resolvedSessionDir = params.sessionDir ?? (sessionRoot ? path.join(sessionRoot, `async-${id}`) : undefined);
1541
1776
  const structuredOutput = params.structuredOutputSchema
1542
- ? createStructuredOutputRuntime(params.structuredOutputSchema, path.join(asyncDir, "structured-output"), { captureAcceptanceReport: params.acceptance !== false })
1777
+ ? createStructuredOutputRuntime(params.structuredOutputSchema, path.join(asyncDir, "structured-output"), { acceptanceReport: resolveAcceptanceReportMode(params.acceptance) })
1543
1778
  : 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) => {
1779
+ let modelCandidates: string[] = [];
1780
+ if (!externalRunner) {
1781
+ try {
1782
+ modelCandidates = buildModelCandidates(primaryModel, agentConfig.fallbackModels, availableModels, agentConfig.modelProvider ?? ctx.currentModelProvider, {
1783
+ scope: modelScopes,
1784
+ primaryModelFromParent: modelOrigin === "inherited",
1785
+ origin: modelOrigin,
1786
+ }).flatMap((candidate) => {
1551
1787
  const resolved = applyThinkingSuffix(candidate, effectiveThinking, params.thinkingOverride !== undefined);
1552
1788
  return resolved ? [resolved] : [];
1553
1789
  });
1554
- if (!externalRunner) {
1555
- try {
1556
1790
  for (const candidate of modelCandidates) assertThinkingWithinCeiling({ model: candidate, configThinking: effectiveThinking, ceiling: thinkingCeiling, agent: agentConfig.name, runId: id });
1557
1791
  } catch (error) {
1558
1792
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1559
1793
  }
1560
1794
  }
1561
- const effectiveSystemPrompt = appendTurnBudgetSystemPrompt(systemPrompt, params.turnBudget);
1562
1795
  const toolPlan = resolvePiLaunchToolPlan({
1563
1796
  tools: agentConfig.tools,
1797
+ excludeTools: agentConfig.excludeTools,
1798
+ allowNestedSubagents: agentConfig.allowNestedSubagents,
1564
1799
  extensions: agentConfig.extensions,
1565
1800
  subagentOnlyExtensions: agentConfig.subagentOnlyExtensions,
1566
1801
  mcpDirectTools: agentConfig.mcpDirectTools,
@@ -1571,9 +1806,11 @@ export function executeAsyncSingle(
1571
1806
  model,
1572
1807
  modelCandidates,
1573
1808
  capabilityCeiling,
1574
- inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
1809
+ inheritedCapabilityCeiling: ctx.childRuntime?.capabilityCeiling,
1575
1810
  agentName: agentConfig.name,
1576
1811
  permissionRules: resolvePermissionRules(ctx.permissions, agentConfig.permissions),
1812
+ runtimeSnapshotHost: ctx.pi,
1813
+ sandbox,
1577
1814
  });
1578
1815
  const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
1579
1816
  if (!externalRunner) {
@@ -1598,12 +1835,15 @@ export function executeAsyncSingle(
1598
1835
  ...((params.fast ?? agentConfig.fast) !== undefined ? { fast: params.fast ?? agentConfig.fast } : {}),
1599
1836
  ...(resolveEffectiveThinking(model, effectiveThinking) ? { thinking: resolveEffectiveThinking(model, effectiveThinking) } : {}),
1600
1837
  ...(thinkingCeiling ? { thinkingCeiling } : {}),
1601
- systemPrompt: effectiveSystemPrompt,
1838
+ systemPrompt,
1602
1839
  systemPromptMode: agentConfig.systemPromptMode,
1603
1840
  inheritProjectContext: agentConfig.inheritProjectContext,
1841
+ inheritGlobalContext: agentConfig.inheritGlobalContext,
1604
1842
  inheritSkills: agentConfig.inheritSkills,
1843
+ sandbox,
1605
1844
  skills: resolvedSkills.map((skill) => skill.name),
1606
1845
  tools: toolPlan.effectiveToolAllowlist,
1846
+ ...(toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
1607
1847
  extensions: toolPlan.extensionArgs,
1608
1848
  mcpDirectTools: toolPlan.effectiveMcpTools,
1609
1849
  ...(outputPath ? { outputPath } : {}),
@@ -1623,29 +1863,36 @@ export function executeAsyncSingle(
1623
1863
  const recoveryAgentConfig = params.recoveryAgentConfig ?? agentConfig;
1624
1864
  const recoveryDescriptor: SteeringRecoveryDescriptor = {
1625
1865
  version: 1,
1866
+ ...(lane ? { lane } : {}),
1626
1867
  launchContractDigest,
1627
1868
  ...(extensionBindings ? { extensionBindings } : {}),
1628
1869
  runFanoutBudget,
1629
1870
  sourceRunId: id,
1630
1871
  ...(params.agentContract ? { agentContract: params.agentContract } : {}),
1631
1872
  agent,
1873
+ ...(sandbox ? { sandbox } : {}),
1632
1874
  launchResolvedExtensions,
1633
1875
  ...(sessionFile ? { sessionFile } : {}),
1634
1876
  cwd: runnerCwd,
1635
1877
  ...(model ? { model } : {}),
1636
1878
  ...(params.fast ?? recoveryAgentConfig.fast ? { fast: params.fast ?? recoveryAgentConfig.fast } : {}),
1637
1879
  ...(recoveryAgentConfig.modelProvider ? { modelProvider: recoveryAgentConfig.modelProvider } : {}),
1638
- ...(params.modelOverrideFromParent ? { modelOverrideFromParent: true } : {}),
1880
+ ...(modelOrigin === "inherited" ? { modelOverrideFromParent: true } : {}),
1881
+ modelOrigin,
1639
1882
  ...(recoveryAgentConfig.fallbackModels ? { fallbackModels: [...recoveryAgentConfig.fallbackModels] } : {}),
1640
1883
  ...(effectiveThinking ? { thinking: resolveEffectiveThinking(model, effectiveThinking) } : {}),
1641
1884
  ...(thinkingCeiling ? { thinkingCeiling } : {}),
1642
1885
  ...(recoveryAgentConfig.tools ? { tools: [...recoveryAgentConfig.tools] } : {}),
1886
+ ...(recoveryAgentConfig.excludeTools ? { excludeTools: [...recoveryAgentConfig.excludeTools] } : {}),
1887
+ ...(recoveryAgentConfig.allowNestedSubagents !== undefined ? { allowNestedSubagents: recoveryAgentConfig.allowNestedSubagents } : {}),
1643
1888
  ...(recoveryAgentConfig.extensions ? { extensions: [...recoveryAgentConfig.extensions] } : {}),
1644
1889
  ...(recoveryAgentConfig.subagentOnlyExtensions ? { subagentOnlyExtensions: [...recoveryAgentConfig.subagentOnlyExtensions] } : {}),
1645
1890
  ...(recoveryAgentConfig.mcpDirectTools ? { mcpDirectTools: [...recoveryAgentConfig.mcpDirectTools] } : {}),
1891
+ ...(recoveryAgentConfig.mutationTools ? { mutationTools: [...recoveryAgentConfig.mutationTools] } : {}),
1646
1892
  ...(recoveryAgentConfig.systemPrompt ? { systemPrompt: recoveryAgentConfig.systemPrompt } : {}),
1647
1893
  systemPromptMode: recoveryAgentConfig.systemPromptMode,
1648
1894
  inheritProjectContext: recoveryAgentConfig.inheritProjectContext,
1895
+ inheritGlobalContext: recoveryAgentConfig.inheritGlobalContext,
1649
1896
  inheritSkills: recoveryAgentConfig.inheritSkills,
1650
1897
  ...(resolvedSkills.length ? { skills: resolvedSkills.map((skill) => skill.name) } : {}),
1651
1898
  ...(recoveryAgentConfig.skillPath ? { skillPath: [...recoveryAgentConfig.skillPath] } : {}),
@@ -1659,8 +1906,8 @@ export function executeAsyncSingle(
1659
1906
  ...(controlConfig ? { controlConfig } : {}),
1660
1907
  ...(params.context ? { context: params.context } : {}),
1661
1908
  ...(params.intercomBridge !== undefined ? { intercomBridge: params.intercomBridge } : {}),
1909
+ ...(params.baseRef !== undefined ? { baseRef: params.baseRef } : {}),
1662
1910
  ...(deadlineAt !== undefined ? { absoluteDeadlineAt: deadlineAt } : {}),
1663
- ...(initialTurnBudget ? { initialTurnBudget: { maxTurns: initialTurnBudget.maxTurns, graceTurns: initialTurnBudget.graceTurns } } : {}),
1664
1911
  ...(resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {}),
1665
1912
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, recoveryAgentConfig.maxSubagentDepth),
1666
1913
  ...(maxOutput ? { maxOutput } : {}),
@@ -1678,6 +1925,8 @@ export function executeAsyncSingle(
1678
1925
  }
1679
1926
  }
1680
1927
  let spawnResult: SpawnRunnerResult = {};
1928
+ const initialStatusAt = Date.now();
1929
+ const initialCompletionOwnerId = ctx.completionOwnerId ?? currentCompletionOwnerId();
1681
1930
  try {
1682
1931
  spawnResult = spawnRunner(
1683
1932
  {
@@ -1686,6 +1935,8 @@ export function executeAsyncSingle(
1686
1935
  {
1687
1936
  parentSessionId: ctx.parentSessionId ?? ctx.currentSessionId,
1688
1937
  permissionRules,
1938
+ ...(ctx.projectTrusted !== undefined ? { projectTrusted: ctx.projectTrusted } : {}),
1939
+ ...(ctx.trustedProjectCwd ? { trustedProjectCwd: ctx.trustedProjectCwd } : {}),
1689
1940
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
1690
1941
  agent,
1691
1942
  task: taskText,
@@ -1693,28 +1944,37 @@ export function executeAsyncSingle(
1693
1944
  ...(params.externalJobFollowUp ? { externalJobFollowUp: params.externalJobFollowUp } : {}),
1694
1945
  ...(params.context ? { context: params.context } : {}),
1695
1946
  cwd: runnerCwd,
1947
+ requestedCwd: params.requestedCwd ?? runnerCwd,
1696
1948
  model,
1949
+ ...(contextLimit !== undefined ? { contextLimit } : {}),
1697
1950
  ...(params.fast ?? agentConfig.fast ? { fast: params.fast ?? agentConfig.fast } : {}),
1698
1951
  thinking: resolveEffectiveThinking(model, effectiveThinking),
1699
1952
  ...(thinkingCeiling ? { thinkingCeiling } : {}),
1700
1953
  modelCandidates,
1701
- ...(params.modelOverrideFromParent ? { skipPrimaryModelVerification: true } : {}),
1954
+ ...(modelOrigin === "inherited" ? { skipPrimaryModelVerification: true } : {}),
1702
1955
  ...(availableModels && availableModels.length > 0 ? { modelVerificationRegistry: availableModels } : {}),
1703
1956
  tools: agentConfig.tools,
1957
+ excludeTools: agentConfig.excludeTools,
1958
+ allowNestedSubagents: agentConfig.allowNestedSubagents,
1704
1959
  extensions: agentConfig.extensions,
1705
1960
  subagentOnlyExtensions: agentConfig.subagentOnlyExtensions,
1706
1961
  mcpDirectTools: agentConfig.mcpDirectTools,
1962
+ mutationTools: agentConfig.mutationTools,
1707
1963
  completionGuard: agentConfig.completionGuard,
1964
+ ...(sandbox ? { sandbox } : {}),
1708
1965
  systemPrompt,
1709
1966
  systemPromptMode: agentConfig.systemPromptMode,
1710
1967
  inheritProjectContext: agentConfig.inheritProjectContext,
1968
+ inheritGlobalContext: agentConfig.inheritGlobalContext,
1711
1969
  inheritSkills: agentConfig.inheritSkills,
1712
1970
  skills: resolvedSkills.map((r) => r.name),
1713
1971
  outputPath,
1972
+ ...(params.outputClaimPath ? { outputClaimPath: params.outputClaimPath } : {}),
1714
1973
  outputMode,
1715
1974
  ...(!externalRunner && sessionFile ? { sessionFile } : {}),
1716
1975
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, agentConfig.maxSubagentDepth),
1717
1976
  waitToolEnabled: params.waitToolEnabled,
1977
+ waitToolDefaultTimeoutMs: params.waitToolDefaultTimeoutMs,
1718
1978
  ...(params.agentContract ? { agentContract: params.agentContract } : {}),
1719
1979
  definitionDigest: agentDefinitionDigest(agentConfig),
1720
1980
  launchBindingTask: task,
@@ -1722,10 +1982,12 @@ export function executeAsyncSingle(
1722
1982
  ...(extensionBindings ? { extensionBindings } : {}),
1723
1983
  launchResolvedExtensions,
1724
1984
  effectiveAcceptance: resolvedAcceptance,
1985
+ acceptanceInput: params.acceptance,
1725
1986
  ...(structuredOutput ? { structuredOutput } : {}),
1726
1987
  ...(params.structuredOutputSchema ? { structuredOutputSchema: params.structuredOutputSchema } : {}),
1727
1988
  ...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),
1728
1989
  ...(params.worktree === true ? { worktree: true } : {}),
1990
+ ...(lane ? { lane } : {}),
1729
1991
  },
1730
1992
  ],
1731
1993
  resultPath: params.parentWorkflowRunId !== undefined && (params.revivalLease !== undefined || params.workflowAwaitAsync === true)
@@ -1743,15 +2005,18 @@ export function executeAsyncSingle(
1743
2005
  completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
1744
2006
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
1745
2007
  piPackageRoot,
1746
- piArgv1: process.argv[1],
2008
+ childSessionFactoryModule: childSessionFactoryModule(),
2009
+ inheritedChildRuntime: inheritedChildRuntime(ctx.childRuntime),
1747
2010
  worktreeSetupHook,
1748
2011
  worktreeSetupHookTimeoutMs,
1749
2012
  worktreeBaseDir,
2013
+ baseRef,
2014
+ worktreeProvider,
2015
+ worktreeBranchPrefix,
1750
2016
  controlConfig,
1751
2017
  timeoutMs,
1752
2018
  deadlineAt,
1753
2019
  toolTimeoutMs,
1754
- turnBudget: params.turnBudget,
1755
2020
  toolBudget: params.toolBudget,
1756
2021
  usageBudget: params.usageBudget,
1757
2022
  controlIntercomTarget,
@@ -1762,6 +2027,7 @@ export function executeAsyncSingle(
1762
2027
  runFanoutBudget,
1763
2028
  ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
1764
2029
  ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
2030
+ ...(lane ? { lane } : {}),
1765
2031
  ...(params.revivalLease ? { revivalLease: params.revivalLease } : {}),
1766
2032
  nestedRoute: nestedRoute ?? inheritedNestedRoute,
1767
2033
  nestedSelf: inheritedNestedRoute && nestedAddress ? {
@@ -1773,7 +2039,24 @@ export function executeAsyncSingle(
1773
2039
  },
1774
2040
  id,
1775
2041
  runnerCwd,
1776
- (proof) => ctx.pi.events.emit(SUBAGENT_PROCESS_TERMINAL_EVENT, proof),
2042
+ {
2043
+ lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
2044
+ runId: id,
2045
+ ...(ctx.currentSessionId ? { sessionId: ctx.currentSessionId } : {}),
2046
+ ...(initialCompletionOwnerId ? { completionOwnerId: initialCompletionOwnerId } : {}),
2047
+ mode: "single",
2048
+ state: "running",
2049
+ startedAt: initialStatusAt,
2050
+ lastUpdate: initialStatusAt,
2051
+ currentStep: 0,
2052
+ chainStepCount: 1,
2053
+ ...(lane ? { lane } : {}),
2054
+ steps: [{ agent, status: "pending", ...(lane ? { lane } : {}), ...(model ? { model } : {}), ...(contextLimit !== undefined ? { contextLimit } : {}) }],
2055
+ },
2056
+ path.join(asyncDir, "status.json"),
2057
+ (proof) => emitProcessTerminalEvent(ctx, proof),
2058
+ (runnerProcessInstanceId) => params.activeAsyncCapacity?.markStarted(runnerProcessInstanceId),
2059
+ params.requestedCwd ?? runnerCwd,
1777
2060
  );
1778
2061
  } catch (error) {
1779
2062
  params.activeAsyncCapacity?.rollback();
@@ -1782,7 +2065,10 @@ export function executeAsyncSingle(
1782
2065
  }
1783
2066
 
1784
2067
  if (spawnResult.error) {
1785
- if (!spawnResult.pid || !spawnResult.runnerProcessInstanceId || (spawnResult.startupDidNotProceed && spawnResult.terminationObserved)) params.activeAsyncCapacity?.rollback();
2068
+ if (spawnResult.startupDidNotProceed) {
2069
+ if (!spawnResult.runnerProcessInstanceId || params.activeAsyncCapacity?.rollbackBeforeRunnerProceed(spawnResult.runnerProcessInstanceId) !== true) params.activeAsyncCapacity?.rollback();
2070
+ }
2071
+ else if (!spawnResult.pid || !spawnResult.runnerProcessInstanceId) params.activeAsyncCapacity?.rollback();
1786
2072
  else params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
1787
2073
  return formatAsyncStartError("single", `Failed to start async run '${id}': ${spawnResult.error}`);
1788
2074
  }
@@ -1790,8 +2076,6 @@ export function executeAsyncSingle(
1790
2076
  params.activeAsyncCapacity?.rollback();
1791
2077
  return formatAsyncStartError("single", `Failed to start async run '${id}': runner identity unavailable`);
1792
2078
  }
1793
- params.activeAsyncCapacity?.markStarted(spawnResult.runnerProcessInstanceId);
1794
-
1795
2079
  if (spawnResult.pid) {
1796
2080
  if (inheritedNestedRoute && nestedAddress) {
1797
2081
  const now = Date.now();
@@ -1809,17 +2093,17 @@ export function executeAsyncSingle(
1809
2093
  path: nestedAddress.path,
1810
2094
  asyncDir,
1811
2095
  pid: spawnResult.pid,
1812
- ownerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,
2096
+ ownerIntercomTarget: ctx.childRuntime?.intercomSessionName,
1813
2097
  leafIntercomTarget: childIntercomTarget?.(agent, 0),
1814
2098
  intercomTarget: childIntercomTarget?.(agent, 0),
1815
2099
  ownerState: "live",
1816
2100
  mode: "single",
1817
2101
  state: "running",
1818
2102
  agent,
2103
+ ...(sandbox ? { sandbox } : {}),
1819
2104
  agents: [agent],
1820
2105
  chainStepCount: 1,
1821
2106
  ...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}),
1822
- ...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),
1823
2107
  startedAt: now,
1824
2108
  lastUpdate: now,
1825
2109
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
@@ -1837,6 +2121,7 @@ export function executeAsyncSingle(
1837
2121
  completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
1838
2122
  mode: "single",
1839
2123
  agent,
2124
+ ...(sandbox ? { sandbox } : {}),
1840
2125
  task: task?.trim() ? PROMPT_REDACTED : undefined,
1841
2126
  goal: (params.goal ?? task).trim() ? PROMPT_REDACTED : undefined,
1842
2127
  cwd: runnerCwd,
@@ -1847,7 +2132,6 @@ export function executeAsyncSingle(
1847
2132
  ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
1848
2133
  ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
1849
2134
  ...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}),
1850
- ...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),
1851
2135
  ...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}),
1852
2136
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
1853
2137
  nestedRoute,
@@ -1856,6 +2140,6 @@ export function executeAsyncSingle(
1856
2140
 
1857
2141
  return {
1858
2142
  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,
2143
+ 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
2144
  };
1861
2145
  }