@xzzpig/pi-subagents 0.14.0 → 0.15.1

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 (206) hide show
  1. package/CHANGELOG.md +239 -0
  2. package/README.md +7 -6
  3. package/agents/evidence-auditor.md +34 -0
  4. package/agents/researcher.md +23 -13
  5. package/agents/reviewer.md +3 -2
  6. package/docs/agents.md +55 -136
  7. package/docs/configuration.md +92 -14
  8. package/docs/extension-api.md +132 -74
  9. package/docs/fork-extensions.md +184 -0
  10. package/docs/missions.md +10 -2
  11. package/docs/models.md +11 -22
  12. package/docs/observability.md +63 -11
  13. package/docs/standalone-background.md +59 -0
  14. package/docs/tool-reference.md +42 -23
  15. package/docs/watchdog.md +39 -10
  16. package/docs/workflows.md +58 -19
  17. package/index.ts +5 -2
  18. package/inspector-runner.mjs +2 -2
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +13 -3
  20. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +18 -6
  21. package/node_modules/@xzzpig/pi-components/src/transcript.ts +26 -6
  22. package/package.json +9 -4
  23. package/prompts/parallel-review.md +1 -1
  24. package/runner-peer-loader.mjs +24 -0
  25. package/runner-peer-preload.mjs +36 -0
  26. package/skills/pi-subagents/SKILL.md +34 -22
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  28. package/skills/pi-subagents/references/execution-controls.md +27 -8
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  32. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  33. package/src/agents/advertised-agent-prompt.ts +94 -0
  34. package/src/agents/agent-eject.ts +339 -0
  35. package/src/agents/agent-management.ts +79 -387
  36. package/src/agents/agent-serializer.ts +6 -3
  37. package/src/agents/agents.ts +198 -72
  38. package/src/agents/builtin-names.ts +1 -0
  39. package/src/agents/chain-serializer.ts +5 -0
  40. package/src/agents/runtime-agent-registry.ts +7 -6
  41. package/src/api/agent-management.ts +2 -2
  42. package/src/api/delegation.ts +4 -0
  43. package/src/api/preflight.ts +131 -86
  44. package/src/api/required-child-extensions.ts +6 -0
  45. package/src/api/shared-types.ts +3 -1
  46. package/src/api/workflow-resources.ts +6 -0
  47. package/src/extension/config.ts +14 -37
  48. package/src/extension/fanout-child.ts +68 -5
  49. package/src/extension/herdr-pi-bridge.ts +164 -0
  50. package/src/extension/index.ts +141 -51
  51. package/src/extension/public-execution.ts +7 -6
  52. package/src/extension/rpc.ts +8 -21
  53. package/src/extension/schemas.ts +86 -84
  54. package/src/extension/tool-description.ts +32 -79
  55. package/src/inspectors/actions.ts +148 -0
  56. package/src/inspectors/ghostty/actions.ts +74 -0
  57. package/src/inspectors/ghostty/plugin.ts +17 -0
  58. package/src/inspectors/herdr/actions.ts +99 -179
  59. package/src/inspectors/herdr/plugin.ts +20 -0
  60. package/src/inspectors/herdr/project-panes.ts +4 -1
  61. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  62. package/src/inspectors/plugins.ts +8 -0
  63. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  64. package/src/inspectors/types.ts +51 -0
  65. package/src/integrations/pi-web-session-liveness.ts +73 -0
  66. package/src/intercom/intercom-bridge.ts +50 -8
  67. package/src/intercom/native-supervisor-channel.ts +142 -115
  68. package/src/intercom/supervisor-ui.ts +3 -2
  69. package/src/missions/workflow-state.ts +37 -16
  70. package/src/policy/authority.ts +4 -0
  71. package/src/profiles/profiles.ts +12 -6
  72. package/src/runs/background/active-async-capacity.ts +22 -18
  73. package/src/runs/background/active-run-index.ts +17 -1
  74. package/src/runs/background/async-execution.ts +359 -176
  75. package/src/runs/background/async-job-tracker.ts +41 -7
  76. package/src/runs/background/async-resume.ts +19 -12
  77. package/src/runs/background/async-retention.ts +20 -0
  78. package/src/runs/background/async-status-snapshot.ts +10 -12
  79. package/src/runs/background/async-status.ts +38 -35
  80. package/src/runs/background/auto-drain.ts +59 -35
  81. package/src/runs/background/binary-bootstrap.ts +38 -0
  82. package/src/runs/background/chain-append.ts +1 -1
  83. package/src/runs/background/chain-root-attachment.ts +22 -33
  84. package/src/runs/background/control-channel.ts +78 -44
  85. package/src/runs/background/fleet-view.ts +30 -2
  86. package/src/runs/background/notify.ts +193 -19
  87. package/src/runs/background/owned-process-tree.ts +35 -8
  88. package/src/runs/background/process-terminal.ts +23 -23
  89. package/src/runs/background/result-files.ts +8 -4
  90. package/src/runs/background/result-watcher.ts +19 -2
  91. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  92. package/src/runs/background/run-child-session.ts +118 -41
  93. package/src/runs/background/run-status.ts +78 -5
  94. package/src/runs/background/runner-aliases.ts +22 -5
  95. package/src/runs/background/runner-child-launch.ts +93 -0
  96. package/src/runs/background/runner-child-sessions.ts +5 -4
  97. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  98. package/src/runs/background/scheduled-runs.ts +51 -18
  99. package/src/runs/background/stale-run-reconciler.ts +38 -12
  100. package/src/runs/background/steering.ts +20 -2
  101. package/src/runs/background/subagent-runner.ts +770 -444
  102. package/src/runs/background/subagent-wait.ts +179 -28
  103. package/src/runs/background/wait-completions.ts +79 -27
  104. package/src/runs/background/wait-subscriptions.ts +9 -3
  105. package/src/runs/background/wait-tool.ts +5 -3
  106. package/src/runs/foreground/async-steering-action.ts +37 -7
  107. package/src/runs/foreground/async-stop-action.ts +93 -3
  108. package/src/runs/foreground/execution.ts +174 -194
  109. package/src/runs/foreground/foreground-history.ts +5 -2
  110. package/src/runs/foreground/prompt-audit.ts +12 -6
  111. package/src/runs/foreground/subagent-executor.ts +915 -411
  112. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  113. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  114. package/src/runs/shared/acceptance.ts +54 -14
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +172 -78
  117. package/src/runs/shared/capability-ceiling.ts +2 -0
  118. package/src/runs/shared/child-hooks.ts +167 -3
  119. package/src/runs/shared/child-launch-plan.ts +15 -3
  120. package/src/runs/shared/child-launch.ts +49 -85
  121. package/src/runs/shared/child-lifecycle.ts +6 -3
  122. package/src/runs/shared/child-runtime-config.ts +8 -1
  123. package/src/runs/shared/child-session.ts +130 -24
  124. package/src/runs/shared/child-tool-plan.ts +149 -112
  125. package/src/runs/shared/completion-evidence.ts +2 -2
  126. package/src/runs/shared/completion-guard.ts +6 -3
  127. package/src/runs/shared/dynamic-fanout.ts +2 -2
  128. package/src/runs/shared/effective-system-prompt.ts +33 -0
  129. package/src/runs/shared/external-cli-contract.ts +11 -1
  130. package/src/runs/shared/external-cli-preflight.ts +6 -2
  131. package/src/runs/shared/external-cli-runner.ts +9 -7
  132. package/src/runs/shared/herdr-connection.ts +134 -0
  133. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  134. package/src/runs/shared/herdr-machine.ts +279 -0
  135. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  136. package/src/runs/shared/herdr-placed-run.ts +263 -0
  137. package/src/runs/shared/host-step-status.ts +11 -11
  138. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  139. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  140. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  141. package/src/runs/shared/model-scope.ts +1 -1
  142. package/src/runs/shared/nested-events.ts +27 -34
  143. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  144. package/src/runs/shared/parallel-handoff.ts +57 -12
  145. package/src/runs/shared/parallel-utils.ts +10 -4
  146. package/src/runs/shared/pi-spawn.ts +10 -0
  147. package/src/runs/shared/profile-extensions.ts +134 -0
  148. package/src/runs/shared/profile-launch-env.ts +113 -0
  149. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  150. package/src/runs/shared/run-fanout-budget.ts +8 -8
  151. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  152. package/src/runs/shared/sandbox-profile-guard.ts +34 -0
  153. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  154. package/src/runs/shared/task-intent.ts +46 -13
  155. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  156. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  157. package/src/runs/shared/worktree-setup-command.ts +213 -0
  158. package/src/runs/shared/worktree.ts +437 -214
  159. package/src/shared/child-cache-retention.ts +43 -0
  160. package/src/shared/fork-context.ts +15 -72
  161. package/src/shared/launch-contract.ts +70 -8
  162. package/src/shared/model-response-aliases.ts +13 -0
  163. package/src/shared/opencode-session-headers.ts +30 -0
  164. package/src/shared/permission-profile.ts +14 -0
  165. package/src/shared/pruned-fork.ts +1 -1
  166. package/src/shared/required-child-extensions.ts +81 -0
  167. package/src/shared/sandbox-profile.ts +14 -0
  168. package/src/shared/settings.ts +5 -2
  169. package/src/shared/shortcuts.ts +0 -4
  170. package/src/shared/types.ts +163 -90
  171. package/src/shared/utils.ts +10 -2
  172. package/src/shared/watch-strategy.ts +2 -0
  173. package/src/shared/workflow-child-permit.ts +18 -13
  174. package/src/slash/delegation-adapters.ts +3 -1
  175. package/src/slash/delegation-request.ts +14 -0
  176. package/src/slash/slash-commands.ts +2 -7
  177. package/src/slash/subagents-admin.ts +31 -14
  178. package/src/tui/fleet-status.ts +165 -20
  179. package/src/tui/fleet.ts +30 -19
  180. package/src/tui/render.ts +210 -50
  181. package/src/watchdog/child-status.ts +28 -28
  182. package/src/watchdog/lsp-diagnostics.ts +1 -1
  183. package/src/watchdog/model-selection.ts +21 -1
  184. package/src/watchdog/permission-arbiter.ts +5 -2
  185. package/src/watchdog/register-child.ts +10 -2
  186. package/src/watchdog/register-main.ts +39 -35
  187. package/src/watchdog/render.ts +1 -1
  188. package/src/watchdog/review.ts +122 -74
  189. package/src/watchdog/rules.ts +1 -1
  190. package/src/watchdog/runtime.ts +100 -27
  191. package/src/watchdog/scope.ts +1 -1
  192. package/src/watchdog/settings.ts +3 -0
  193. package/src/watchdog/tool-actions.ts +13 -12
  194. package/src/watchdog/turn-delta.ts +23 -0
  195. package/src/watchdog/types.ts +5 -3
  196. package/src/watchdog/warning-format.ts +1 -1
  197. package/src/workflows/chat-progress.ts +3 -3
  198. package/src/workflows/scripted-workflow.ts +349 -26
  199. package/src/workflows/workflow-checklist.ts +17 -20
  200. package/src/workflows/workflow-child-summary.ts +57 -8
  201. package/src/workflows/workflow-preflight.ts +19 -19
  202. package/src/workflows/workflow-receipt.ts +24 -6
  203. package/src/workflows/workflow-resources.ts +108 -22
  204. package/src/workflows/workflow-settlement.ts +3 -0
  205. package/src/runs/shared/model-exclusions.ts +0 -373
  206. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -2,33 +2,34 @@
2
2
  * Async execution logic for subagent tool
3
3
  */
4
4
 
5
- import { spawn } from "node:child_process";
5
+ import { spawn, type ChildProcess } from "node:child_process";
6
6
  import { randomUUID } from "node:crypto";
7
7
  import * as fs from "node:fs";
8
8
  import * as path from "node:path";
9
9
  import { fileURLToPath } from "node:url";
10
- import { createRequire } from "node:module";
10
+ import * as nodeModule from "node:module";
11
11
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
12
12
  import { discoverAgents, formatUnknownAgentError, unknownAgentDiagnosticContext, type AgentConfig, type UnknownAgentDiagnosticContext } from "../../agents/agents.ts";
13
- import { appendAgentRefinementOverlay } from "../../agents/agent-refinements.ts";
14
13
  import { createAtomicJsonWriter, writePrivateAtomicJson } from "../../shared/atomic-json.ts";
14
+ import { childCacheRetentionEnv } from "../../shared/child-cache-retention.ts";
15
+ import { buildEffectiveSystemPrompt } from "../shared/effective-system-prompt.ts";
15
16
  import { currentCompletionOwnerId } from "../../shared/completion-owner.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
- import { injectOutputPathSystemPrompt, injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
17
+ import { planChildLaunch, projectChainOutputSchemas, resolveStepBehavior, suppressProgressForReadOnlyTask, type ResolvedStepBehavior } from "../shared/child-launch-plan.ts";
18
+ import { formatHerdrMachineRunnerUnsupported, resolveHerdrMachinePlacement } from "../shared/herdr-machine.ts";
19
+ import { applyThinkingSuffix, getHostBuiltinToolNames, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan } from "../shared/child-tool-plan.ts";
20
+ import { injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
19
21
  import { applyWatchdogLaunchRules, sendRuleViolationWarning } from "../../watchdog/rules.ts";
20
22
  import { buildChainInstructions, isDynamicParallelStep, isParallelStep, resolveExistingReadInstructionPaths, resolveExistingReadPaths, writeInitialProgressFile, type ChainStep, type SequentialStep, type StepOverrides } from "../../shared/settings.ts";
21
23
  import type { RunnerStep } from "../shared/parallel-utils.ts";
22
24
  import type { ContextMode } from "../shared/context-mode.ts";
23
- import { PI_CODING_AGENT_PACKAGE, resolveInstalledPiPackageRoot, resolvePiPackageRoot } from "../shared/pi-spawn.ts";
25
+ import { PI_CODING_AGENT_PACKAGE, resolveBunPiExecutable, resolveInstalledPiPackageRoot, resolvePiPackageRoot } from "../shared/pi-spawn.ts";
24
26
  import { JITI_ALIAS_ENV, resolveHostPeerAliases } from "./runner-aliases.ts";
25
27
  import { preflightLaunchCwd } from "../shared/launch-cwd.ts";
26
28
  import { resolveNodeExecutable } from "../../shared/node-executable.ts";
27
29
  import { backgroundProcessOptions } from "../shared/background-process-options.ts";
28
- import { buildSkillInjection, normalizeSkillInput, resolveSkillsWithFallback } from "../../agents/skills.ts";
29
- import { buildAgentMemoryInjection } from "../../agents/agent-memory.ts";
30
+ import { normalizeSkillInput, resolveSkillsWithFallback } from "../../agents/skills.ts";
30
31
  import { PI_CODING_AGENT_PACKAGE_ROOT_ENV, PROMPT_REDACTED, resolveChildCwd } from "../../shared/utils.ts";
31
- import { buildModelCandidates, resolveEffectiveSubagentModel, resolveModelOrigin, resolveSubagentModelOverride, type AvailableModelInfo, type ModelOrigin, type ParentModel } from "../shared/model-fallback.ts";
32
+ import { resolveEffectiveSubagentModel, resolveModelOrigin, resolveModelSelection, resolveSubagentModelOverride, type AvailableModelInfo, type ModelOrigin, type ParentModel } from "../shared/model-resolution.ts";
32
33
  import { resolveToolTimeoutMs, toolTimeoutFromEnv } from "../shared/tool-timeout.ts";
33
34
  import { resolveModelScopesForAgent, type ModelScopeConfig } from "../shared/model-scope.ts";
34
35
  import { findModelInfo, resolveEffectiveThinking } from "../../shared/model-info.ts";
@@ -48,6 +49,7 @@ import {
48
49
  type ArtifactConfig,
49
50
  type Details,
50
51
  type IntercomBridgeConfig,
52
+ type HerdrMachineReference,
51
53
  type JsonSchemaObject,
52
54
  type MaxOutputConfig,
53
55
  type NestedRouteInfo,
@@ -71,6 +73,7 @@ import type { ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
71
73
  import { childSessionFactoryModule } from "../shared/child-session.ts";
72
74
  import { inheritedChildRuntime } from "../shared/child-launch.ts";
73
75
  import { resultFilePath } from "./result-files.ts";
76
+ import { updateActiveRunIndex } from "./active-run-index.ts";
74
77
  import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
75
78
  import { usageBudgetState } from "../shared/usage-budget.ts";
76
79
  import type { ImportedAsyncRoot } from "./chain-root-attachment.ts";
@@ -80,13 +83,29 @@ import type { ActiveAsyncCapacityHandle } from "./active-async-capacity.ts";
80
83
  import { statusStepDescription } from "./chain-append.ts";
81
84
  import { SUBAGENT_PROCESS_TERMINAL_EVENT } from "../../shared/types.ts";
82
85
  import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
83
- import { agentDefinitionDigest, launchBindingDigest } from "../../shared/launch-contract.ts";
86
+ import { resolveLaunchBinding } from "../../shared/launch-contract.ts";
84
87
  import { resolvePermissionRules, type PermissionConfig } from "../shared/permissions.ts";
85
88
  import { normalizeExtensionBindings, omitExtensionBindingsEnv, omitInheritedProfileEnv, type ExtensionBindings } from "../shared/extension-bindings.ts";
86
89
  import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
90
+ import { resolveRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
87
91
 
88
- const require = createRequire(import.meta.url);
89
- const piPackageRoot = resolvePiPackageRoot() ?? resolveInstalledPiPackageRoot();
92
+ const require = nodeModule.createRequire(import.meta.url);
93
+ const piPackageRoot = resolveAsyncPiPackageRoot();
94
+
95
+ /**
96
+ * The detached runner resolves the same host package the foreground
97
+ * `resolvePiCliScript` path resolves, so an explicit
98
+ * `PI_SUBAGENTS_PI_CODING_AGENT_PACKAGE_ROOT` override must be honored here
99
+ * too. Precedence mirrors the foreground resolver: argv-based discovery wins
100
+ * first (the foreground returns the argv script before any candidate), the
101
+ * environment override is consulted when that discovery cannot identify the
102
+ * host (wrapper installs, non-standard layouts), and the
103
+ * package-manager entry is last. Without the override, such hosts fail
104
+ * closed with "neither is available" while foreground children launch fine.
105
+ */
106
+ function resolveAsyncPiPackageRoot(env: NodeJS.ProcessEnv = process.env): string | undefined {
107
+ return resolvePiPackageRoot() || env[PI_CODING_AGENT_PACKAGE_ROOT_ENV]?.trim() || resolveInstalledPiPackageRoot();
108
+ }
90
109
 
91
110
  function resolveJitiCliFromPackageJson(packageJsonPath: string): string | undefined {
92
111
  if (!fs.existsSync(packageJsonPath)) return undefined;
@@ -115,12 +134,12 @@ function resolveJitiCliPath(): string | undefined {
115
134
  const candidates: Array<() => string | undefined> = [
116
135
  () => require.resolve("jiti/package.json"),
117
136
  () => piPackageRoot
118
- ? createRequire(path.join(piPackageRoot, "package.json")).resolve("jiti/package.json")
137
+ ? nodeModule.createRequire(path.join(piPackageRoot, "package.json")).resolve("jiti/package.json")
119
138
  : undefined,
120
139
  () => {
121
140
  if (!process.argv[1]) return undefined;
122
141
  const piEntry = fs.realpathSync(process.argv[1]);
123
- return createRequire(piEntry).resolve("jiti/package.json");
142
+ return nodeModule.createRequire(piEntry).resolve("jiti/package.json");
124
143
  },
125
144
  () => piPackageRoot ? path.join(piPackageRoot, "node_modules", "jiti", "package.json") : undefined,
126
145
  ];
@@ -138,6 +157,17 @@ function resolveJitiCliPath(): string | undefined {
138
157
  }
139
158
 
140
159
  const jitiCliPath = resolveJitiCliPath();
160
+ const asyncRunnerSourcePath = path.join(
161
+ path.dirname(fileURLToPath(import.meta.url)),
162
+ `subagent-runner${path.extname(fileURLToPath(import.meta.url))}`,
163
+ );
164
+ const sourceUnderNodeModules = asyncRunnerSourcePath.split(path.sep).some((segment) => segment.toLowerCase() === "node_modules");
165
+ function supportsNativeRunner(nodeExecutable: string): boolean {
166
+ return Boolean(process.features.typescript)
167
+ && typeof nodeModule.registerHooks === "function"
168
+ && nodeExecutable === process.execPath
169
+ && !sourceUnderNodeModules;
170
+ }
141
171
 
142
172
  interface AsyncExecutionContext {
143
173
  pi: ExtensionAPI;
@@ -151,10 +181,11 @@ interface AsyncExecutionContext {
151
181
  currentModel?: ParentModel;
152
182
  /** Optional model-scope enforcement resolved from subagent settings. */
153
183
  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;
184
+ /** Parent-authoritative trust state for profile-aware project config merging. */
185
+ projectTrusted?: boolean;
186
+ /** Exact trusted parent cwd; project config applies only when it matches the child cwd. */
187
+ trustedProjectCwd?: string;
188
+ modelResponseAliases?: Record<string, string[]>;
158
189
  /** Whether the parent session has an interactive UI. */
159
190
  interactive?: boolean;
160
191
  /** The executor's own child runtime when the launch comes from an in-process child. */
@@ -177,6 +208,9 @@ interface AsyncChainParams {
177
208
  availableModels?: AvailableModelInfo[];
178
209
  cwd?: string;
179
210
  maxOutput?: MaxOutputConfig;
211
+ machine?: string;
212
+ /** Launch cwd as typed when a machine is set: a path on that machine, never resolved locally. */
213
+ machineCwd?: string;
180
214
  artifactsDir?: string;
181
215
  artifactConfig: ArtifactConfig;
182
216
  shareEnabled: boolean;
@@ -232,11 +266,15 @@ interface AsyncSingleParams {
232
266
  agentConfig: AgentConfig;
233
267
  /** Agent contract before per-run bridge injection, used only for recovery persistence. */
234
268
  recoveryAgentConfig?: AgentConfig;
235
- /** Selected global sandbox profile carried across revival. */
236
- sandbox?: string;
269
+ /** Selected global sandbox profile carried across revival. */
270
+ sandbox?: string;
271
+ requiredExtensions?: RequiredChildExtensionSnapshot;
237
272
  ctx: AsyncExecutionContext;
238
273
  cwd?: string;
239
274
  requestedCwd?: string;
275
+ machine?: string;
276
+ /** Launch cwd as typed when a machine is set: a path on that machine, never resolved locally. */
277
+ machineCwd?: string;
240
278
  maxOutput?: MaxOutputConfig;
241
279
  artifactsDir?: string;
242
280
  artifactConfig: ArtifactConfig;
@@ -280,6 +318,8 @@ interface AsyncSingleParams {
280
318
  absoluteDeadlineAt?: number;
281
319
  /** Optional per-call hard toolTimeoutMs override (highest precedence). */
282
320
  toolTimeoutMs?: number;
321
+ /** Steer the child to checkpoint and stop this many ms before the run deadline (resolved call param ?? config). */
322
+ checkpointBeforeDeadlineMs?: number;
283
323
  toolBudget?: ResolvedToolBudget | ToolBudgetConfig;
284
324
  usageBudget?: UsageBudgetConfig;
285
325
  configToolBudget?: ResolvedToolBudget;
@@ -323,6 +363,8 @@ export interface AsyncRunnerStepBuildParams {
323
363
  ctx: AsyncExecutionContext;
324
364
  availableModels?: AvailableModelInfo[];
325
365
  cwd?: string;
366
+ machine?: string;
367
+ machineCwd?: string;
326
368
  chainSkills?: string[];
327
369
  sessionFilesByFlatIndex?: (string | undefined)[];
328
370
  thinkingOverridesByFlatIndex?: (AgentConfig["thinking"] | undefined)[];
@@ -379,11 +421,9 @@ export function formatAsyncStartedMessage(headline: string, interactive: boolean
379
421
  return [headline, "", ...guidance].join("\n");
380
422
  }
381
423
 
382
- /**
383
- * Check if jiti is available for async execution
384
- */
424
+ /** Check whether detached async execution has a supported runtime. */
385
425
  export function isAsyncAvailable(): boolean {
386
- return jitiCliPath !== undefined;
426
+ return resolveBunPiExecutable() !== undefined || supportsNativeRunner(resolveNodeExecutable()) || jitiCliPath !== undefined;
387
427
  }
388
428
 
389
429
  export function resolveAsyncRunnerLogPaths(cfg: Record<string, unknown>): { stdoutPath: string; stderrPath: string } | undefined {
@@ -410,24 +450,14 @@ function closeFd(fd: number | undefined): void {
410
450
  * Spawn the async runner process
411
451
  */
412
452
  const RUNNER_STARTUP_TIMEOUT_MS = 10_000;
413
- const RUNNER_STARTUP_WAIT_BUFFER = typeof SharedArrayBuffer !== "undefined" ? new SharedArrayBuffer(4) : undefined;
414
- const RUNNER_STARTUP_WAIT_VIEW = RUNNER_STARTUP_WAIT_BUFFER ? new Int32Array(RUNNER_STARTUP_WAIT_BUFFER) : undefined;
415
-
416
- type RunnerStartupState = "ready" | "acknowledged";
453
+ type RunnerStartupState = "ready" | "acknowledged" | "confirmed";
417
454
 
418
455
  type RunnerStartupWaitResult =
419
456
  | { ok: true; token: string }
420
457
  | { ok: false; error: string; startupDidNotProceed?: boolean };
421
458
 
422
- function waitForStartupInterval(delayMs = 20): void {
423
- if (RUNNER_STARTUP_WAIT_VIEW) {
424
- Atomics.wait(RUNNER_STARTUP_WAIT_VIEW, 0, 0, delayMs);
425
- return;
426
- }
427
- const waitUntil = Date.now() + delayMs;
428
- while (Date.now() < waitUntil) {
429
- // Startup handshakes are synchronous so resume rejects before reporting a run as started.
430
- }
459
+ function waitForStartupInterval(delayMs = 20): Promise<void> {
460
+ return new Promise((resolve) => setTimeout(resolve, delayMs));
431
461
  }
432
462
 
433
463
  function readRunnerStartup(startupPath: string, expectedState: RunnerStartupState, expectedToken?: string): RunnerStartupWaitResult | undefined {
@@ -445,13 +475,32 @@ function readRunnerStartup(startupPath: string, expectedState: RunnerStartupStat
445
475
  }
446
476
  }
447
477
 
448
- function waitForRunnerStartup(startupPath: string, expectedState: RunnerStartupState, timeoutMs: number, expectedToken?: string): RunnerStartupWaitResult {
478
+ async function waitForRunnerStartup(startupPath: string, expectedState: RunnerStartupState, timeoutMs: number, expectedToken?: string, processClosed?: Promise<{ exitCode: number | null; signal: NodeJS.Signals | null }>): Promise<RunnerStartupWaitResult> {
479
+ const confirmOpen = async (result: RunnerStartupWaitResult): Promise<RunnerStartupWaitResult> => {
480
+ if (!processClosed || result.ok === false) return result;
481
+ const outcome = await Promise.race([processClosed.then((exit) => ({ exit })), new Promise<undefined>((resolve) => setImmediate(() => resolve(undefined)))]);
482
+ if (!outcome) return result;
483
+ const finalResult = readRunnerStartup(startupPath, expectedState, expectedToken);
484
+ if (finalResult?.ok === false) return finalResult;
485
+ const { exitCode, signal } = outcome.exit;
486
+ return { ok: false, error: `Async runner exited before startup state '${expectedState}' (exit code ${exitCode ?? "unknown"}, signal ${signal ?? "none"}).`, startupDidNotProceed: true };
487
+ };
449
488
  const deadline = Date.now() + timeoutMs;
450
- for (;;) {
489
+ while (Date.now() <= deadline) {
451
490
  const result = readRunnerStartup(startupPath, expectedState, expectedToken);
452
- if (result) return result;
453
- if (Date.now() >= deadline) break;
454
- waitForStartupInterval(Math.min(20, Math.max(1, deadline - Date.now())));
491
+ if (result) return await confirmOpen(result);
492
+ const delay = waitForStartupInterval(Math.min(20, Math.max(1, deadline - Date.now())));
493
+ if (processClosed) {
494
+ const outcome = await Promise.race([delay.then(() => undefined), processClosed.then((exit) => ({ exit }))]);
495
+ if (outcome) {
496
+ const finalResult = readRunnerStartup(startupPath, expectedState, expectedToken);
497
+ if (finalResult?.ok === false) return finalResult;
498
+ const { exitCode, signal } = outcome.exit;
499
+ return { ok: false, error: `Async runner exited before startup state '${expectedState}' (exit code ${exitCode ?? "unknown"}, signal ${signal ?? "none"}).`, startupDidNotProceed: true };
500
+ }
501
+ } else {
502
+ await delay;
503
+ }
455
504
  }
456
505
  const finalResult = readRunnerStartup(startupPath, expectedState, expectedToken);
457
506
  if (finalResult) return finalResult;
@@ -460,7 +509,7 @@ function waitForRunnerStartup(startupPath: string, expectedState: RunnerStartupS
460
509
 
461
510
  const writePrivateStartupControlJson = createAtomicJsonWriter({ mode: 0o600, ignoreCleanupErrorAfterSuccess: true });
462
511
 
463
- function writeRunnerStartupControl(filePath: string, payload: { action: "ack" | "proceed"; token: string }): void {
512
+ function writeRunnerStartupControl(filePath: string, payload: { action: "ack" | "confirm" | "proceed"; token: string }): void {
464
513
  // Delegate to the shared atomic JSON writer (temp file + rename, retrying
465
514
  // transient Windows EPERM/EBUSY/EACCES locks and cleaning up the temp file
466
515
  // on failure), so the startup handshake gets the same locking resilience as
@@ -478,6 +527,13 @@ function runnerIsAlive(pid: number): boolean {
478
527
  }
479
528
  }
480
529
 
530
+ function waitForStartupIntervalSync(delayMs = 20): void {
531
+ const waitUntil = Date.now() + delayMs;
532
+ while (Date.now() < waitUntil) {
533
+ // Pre-handshake failures happen before the runner can be observed asynchronously.
534
+ }
535
+ }
536
+
481
537
  function terminateRunnerBeforeProceed(pid: number): boolean {
482
538
  for (const signal of ["SIGTERM", "SIGKILL"] as const) {
483
539
  if (!runnerIsAlive(pid)) return true;
@@ -487,11 +543,88 @@ function terminateRunnerBeforeProceed(pid: number): boolean {
487
543
  if (!runnerIsAlive(pid)) return true;
488
544
  }
489
545
  const deadline = Date.now() + 1000;
490
- while (runnerIsAlive(pid) && Date.now() < deadline) waitForStartupInterval();
546
+ while (runnerIsAlive(pid) && Date.now() < deadline) waitForStartupIntervalSync();
491
547
  }
492
548
  return !runnerIsAlive(pid);
493
549
  }
494
550
 
551
+ async function terminateRunnerBeforeProceedAsync(proc: ChildProcess, processClosed: Promise<{ exitCode: number | null; signal: NodeJS.Signals | null }>): Promise<boolean> {
552
+ for (const signal of ["SIGTERM", "SIGKILL"] as const) {
553
+ if (proc.pid === undefined || !runnerIsAlive(proc.pid)) return true;
554
+ try { process.kill(proc.pid, signal); } catch {
555
+ if (proc.pid === undefined || !runnerIsAlive(proc.pid)) return true;
556
+ }
557
+ const exited = await Promise.race([processClosed.then(() => true), waitForStartupInterval(1000).then(() => false)]);
558
+ if (exited || proc.pid === undefined || !runnerIsAlive(proc.pid)) return true;
559
+ }
560
+ return proc.pid === undefined || !runnerIsAlive(proc.pid);
561
+ }
562
+
563
+ async function completeRunnerStartupHandshake(
564
+ startupPath: string,
565
+ startupAckPath: string,
566
+ startupProceedPath: string,
567
+ proc: ChildProcess,
568
+ processClosed: Promise<{ exitCode: number | null; signal: NodeJS.Signals | null }>,
569
+ getObservedProcessExit: () => { exitCode: number | null; signal: NodeJS.Signals | null } | undefined,
570
+ runnerProcessInstanceId: string,
571
+ persistStartupFailure: (message: string) => void,
572
+ ): Promise<SpawnRunnerResult> {
573
+ try {
574
+ const ready = await waitForRunnerStartup(startupPath, "ready", RUNNER_STARTUP_TIMEOUT_MS, undefined, processClosed);
575
+ if (ready.ok === false) {
576
+ persistStartupFailure(ready.error);
577
+ const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
578
+ return { pid: proc.pid, runnerProcessInstanceId, error: ready.error, terminationObserved, startupDidNotProceed: true };
579
+ }
580
+ try { writeRunnerStartupControl(startupAckPath, { action: "ack", token: ready.token }); } catch (error) {
581
+ const message = `Failed to acknowledge async runner startup: ${error instanceof Error ? error.message : String(error)}`;
582
+ persistStartupFailure(message);
583
+ const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
584
+ return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
585
+ }
586
+ const acknowledged = await waitForRunnerStartup(startupPath, "acknowledged", RUNNER_STARTUP_TIMEOUT_MS, ready.token, processClosed);
587
+ if (acknowledged.ok === false) {
588
+ persistStartupFailure(acknowledged.error);
589
+ const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
590
+ return { pid: proc.pid, runnerProcessInstanceId, error: acknowledged.error, terminationObserved, startupDidNotProceed: true };
591
+ }
592
+ try { writeRunnerStartupControl(startupAckPath, { action: "confirm", token: ready.token }); } catch (error) {
593
+ const message = `Failed to confirm async runner startup: ${error instanceof Error ? error.message : String(error)}`;
594
+ persistStartupFailure(message);
595
+ const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
596
+ return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
597
+ }
598
+ const confirmed = await waitForRunnerStartup(startupPath, "confirmed", RUNNER_STARTUP_TIMEOUT_MS, ready.token, processClosed);
599
+ if (confirmed.ok === false) {
600
+ persistStartupFailure(confirmed.error);
601
+ const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
602
+ return { pid: proc.pid, runnerProcessInstanceId, error: confirmed.error, terminationObserved, startupDidNotProceed: true };
603
+ }
604
+ const closedAtCommit = await Promise.race([
605
+ processClosed.then((exit) => exit),
606
+ new Promise<undefined>((resolve) => setImmediate(() => resolve(undefined))),
607
+ ]);
608
+ const observedExit = closedAtCommit ?? getObservedProcessExit();
609
+ if (observedExit) {
610
+ const message = `Async runner exited after startup state 'acknowledged' before proceed (exit code ${observedExit.exitCode ?? "unknown"}, signal ${observedExit.signal ?? "none"}).`;
611
+ persistStartupFailure(message);
612
+ const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
613
+ return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
614
+ }
615
+ try { writeRunnerStartupControl(startupProceedPath, { action: "proceed", token: ready.token }); } catch (error) {
616
+ const message = `Failed to authorize async runner startup: ${error instanceof Error ? error.message : String(error)}`;
617
+ persistStartupFailure(message);
618
+ const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
619
+ return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
620
+ }
621
+ try { fs.rmSync(startupPath, { force: true }); } catch {}
622
+ return { pid: proc.pid, runnerProcessInstanceId };
623
+ } finally {
624
+ await new Promise<void>((resolve) => setImmediate(resolve));
625
+ }
626
+ }
627
+
495
628
  function persistPreProceedStartupFailure(asyncDir: string, runId: string, runnerProcessInstanceId: string, sessionId: string | undefined, completionOwnerId: string | undefined, message: string): void {
496
629
  const now = Date.now();
497
630
  try {
@@ -500,6 +633,8 @@ function persistPreProceedStartupFailure(asyncDir: string, runId: string, runner
500
633
  try {
501
634
  status = JSON.parse(fs.readFileSync(statusPath, "utf-8")) as Partial<AsyncStatus>;
502
635
  } catch {}
636
+ const existingProcessTerminal = status.processTerminal?.state === "observed" || status.processTerminal?.state === "unknown"
637
+ ? status.processTerminal : undefined;
503
638
  writePrivateAtomicJson(statusPath, {
504
639
  ...status,
505
640
  runId,
@@ -508,7 +643,7 @@ function persistPreProceedStartupFailure(asyncDir: string, runId: string, runner
508
643
  state: "failed",
509
644
  lastUpdate: now,
510
645
  error: message,
511
- processTerminal: {
646
+ processTerminal: existingProcessTerminal ?? {
512
647
  version: 1,
513
648
  state: "not-started",
514
649
  runId,
@@ -548,19 +683,34 @@ export function emitProcessTerminalEvent(ctx: AsyncExecutionContext, proof: unkn
548
683
  }
549
684
  }
550
685
 
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 {
686
+ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Omit<AsyncStatus, "pid" | "processTerminal">, initialStatusPath: string, onProcessTerminal?: (proof: unknown) => void, onBeforeProceed?: (runnerProcessInstanceId: string) => void, requestedCwd = cwd): SpawnRunnerResult | Promise<SpawnRunnerResult> {
552
687
  const cwdError = preflightLaunchCwd(requestedCwd, cwd);
553
688
  if (cwdError) return { error: cwdError };
554
689
 
555
- if (!jitiCliPath) {
556
- return { error: "upstream jiti for TypeScript execution could not be found; ensure package dependencies are installed" };
690
+ // The compiled host exposes its SDK only through Pi's extension loader.
691
+ const binaryHost = resolveBunPiExecutable();
692
+ const nodeExecutable = resolveNodeExecutable();
693
+ const configuredExtensions = (cfg as { steps?: Array<{ extensions?: unknown[]; subagentOnlyExtensions?: unknown[]; requiredExtensions?: unknown[] }> }).steps?.some(
694
+ (step) => (step.extensions?.length ?? 0) > 0 || (step.subagentOnlyExtensions?.length ?? 0) > 0 || (step.requiredExtensions?.length ?? 0) > 0,
695
+ ) ?? false;
696
+ // Keep provider/tool extensions in Jiti's host-alias boundary; the native preload
697
+ // only certifies the runner's imports, not a separately loaded extension graph.
698
+ const nativeRunnerSupported = supportsNativeRunner(nodeExecutable) && !configuredExtensions;
699
+ const runner = asyncRunnerSourcePath;
700
+ const runnerIsJavaScript = path.extname(runner) === ".js";
701
+ const bootstrap = path.join(path.dirname(runner), `binary-bootstrap${path.extname(fileURLToPath(import.meta.url))}`);
702
+ if (binaryHost && !fs.existsSync(bootstrap)) return { error: `Background runner bootstrap not found: ${bootstrap}` };
703
+ if (!binaryHost && !runnerIsJavaScript && !nativeRunnerSupported && !jitiCliPath) {
704
+ return { error: sourceUnderNodeModules
705
+ ? "Background runner source is installed under node_modules, so upstream jiti is required for TypeScript execution."
706
+ : "Background runner requires enabled native TypeScript with synchronous module hooks, or installed upstream jiti for TypeScript execution." };
557
707
  }
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.` };
708
+ if (!binaryHost && !piPackageRoot) {
709
+ return { error: `Background children require a supported standalone Pi host or the installed npm package (${PI_CODING_AGENT_PACKAGE}); neither is available.` };
560
710
  }
561
- const hostPeerAliases = resolveHostPeerAliases(piPackageRoot);
711
+ const hostPeerAliases = !binaryHost && piPackageRoot ? resolveHostPeerAliases(piPackageRoot) : { aliases: {}, missing: [] };
562
712
  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.` };
713
+ return { error: `Background children require the host npm package (${PI_CODING_AGENT_PACKAGE}) with its dependencies; ${piPackageRoot} does not provide ${hostPeerAliases.missing.join(", ")}.` };
564
714
  }
565
715
 
566
716
  fs.mkdirSync(TEMP_ROOT_DIR, { recursive: true });
@@ -570,8 +720,7 @@ function spawnRunner(cfg: Record<string, unknown>, suffix: string, cwd: string,
570
720
  const launchBarrierToken = hasRevivalLease ? undefined : runnerProcessInstanceId;
571
721
  const launchConfig = { ...cfg, runnerProcessInstanceId, ...(launchBarrierToken ? { launchBarrierToken } : {}) };
572
722
  writePrivateAtomicJson(cfgPath, launchConfig);
573
- const runner = path.join(path.dirname(fileURLToPath(import.meta.url)), "subagent-runner.ts");
574
- const nodeCommand = resolveNodeExecutable();
723
+ const command = binaryHost ?? nodeExecutable;
575
724
  const launchForStartup = launchConfig as typeof launchConfig & { asyncDir?: unknown; id?: unknown; sessionId?: unknown; completionOwnerId?: unknown; revivalLease?: unknown };
576
725
  const launchAsyncDir = typeof launchForStartup.asyncDir === "string" ? launchForStartup.asyncDir : undefined;
577
726
  const launchRunId = typeof launchForStartup.id === "string" ? launchForStartup.id : suffix;
@@ -597,23 +746,49 @@ function spawnRunner(cfg: Record<string, unknown>, suffix: string, cwd: string,
597
746
  stdoutFd = fs.openSync(logPaths.stdoutPath, "a");
598
747
  stderrFd = fs.openSync(logPaths.stderrPath, "a");
599
748
  }
600
- const proc = spawn(nodeCommand, [jitiCliPath, runner, cfgPath], {
749
+ const preload = Object.keys(hostPeerAliases.aliases).length > 0
750
+ ? ["--import", new URL("../../../runner-peer-preload.mjs", import.meta.url).href]
751
+ : [];
752
+ const args = binaryHost
753
+ ? ["--no-extensions", "--no-skills", "--no-prompt-templates", "--no-session", "--mode", "rpc", "--extension", bootstrap]
754
+ : runnerIsJavaScript
755
+ ? [...preload, runner, cfgPath]
756
+ : nativeRunnerSupported
757
+ ? [...preload, "--experimental-strip-types", runner, cfgPath]
758
+ : [...preload, jitiCliPath!, runner, cfgPath];
759
+ const proc = spawn(command, args, {
601
760
  cwd,
602
761
  ...backgroundProcessOptions(),
603
762
  stdio: ["ignore", stdoutFd ?? "ignore", stderrFd ?? "ignore"],
604
763
  env: {
605
764
  ...omitInheritedProfileEnv(omitExtensionBindingsEnv(process.env)),
606
- [PI_CODING_AGENT_PACKAGE_ROOT_ENV]: piPackageRoot,
607
- [JITI_ALIAS_ENV]: JSON.stringify(hostPeerAliases.aliases),
765
+ // Unset leaves the inherited parent value in place. See childCacheRetention.
766
+ ...childCacheRetentionEnv(),
767
+ [PI_CODING_AGENT_PACKAGE_ROOT_ENV]: binaryHost ? undefined : piPackageRoot,
768
+ // npm must override inherited bundled layouts (#2071); binaries retain release assets.
769
+ PI_PACKAGE_DIR: binaryHost ? process.env.PI_PACKAGE_DIR : piPackageRoot,
770
+ [JITI_ALIAS_ENV]: binaryHost ? undefined : JSON.stringify(hostPeerAliases.aliases),
771
+ PI_ASYNC_NATIVE_RUNNER: !binaryHost && (runnerIsJavaScript || nativeRunnerSupported) ? "1" : "0",
772
+ PI_ASYNC_COMPILED_RUNNER: !binaryHost && runnerIsJavaScript ? "1" : "0",
773
+ PI_SUBAGENT_RUNNER_CONFIG: binaryHost ? cfgPath : undefined,
608
774
  },
609
775
  });
776
+ let observedProcessExit: { exitCode: number | null; signal: NodeJS.Signals | null } | undefined;
777
+ proc.once("exit", (exitCode, signal) => { observedProcessExit = { exitCode, signal }; });
778
+ const processClosed = new Promise<{ exitCode: number | null; signal: NodeJS.Signals | null }>((resolve) => {
779
+ proc.once("close", (exitCode, signal) => {
780
+ observedProcessExit ??= { exitCode, signal };
781
+ resolve({ exitCode, signal });
782
+ });
783
+ });
610
784
  closeFd(stdoutFd);
611
785
  closeFd(stderrFd);
612
786
  proc.on("error", (error) => {
613
787
  console.error(`[pi-subagents] async spawn failed: ${error.message}`);
614
788
  });
615
789
  proc.once("close", (exitCode, signal) => {
616
- const launch = launchConfig as { asyncDir?: unknown; id?: unknown; nestedRoute?: NestedRouteInfo; nestedSelf?: { parentRunId: string; parentStepIndex?: number; depth: number; path?: Array<{ runId: string; stepIndex?: number; agent?: string }> } };
790
+ const finalize = () => {
791
+ const launch = launchConfig as { asyncDir?: unknown; id?: unknown; nestedRoute?: NestedRouteInfo; nestedSelf?: { parentRunId: string; parentStepIndex?: number; depth: number; path?: Array<{ runId: string; stepIndex?: number; agent?: string }> } };
617
792
  const asyncDir = launch.asyncDir;
618
793
  const runId = launch.id;
619
794
  if (typeof asyncDir !== "string" || typeof runId !== "string") return;
@@ -661,6 +836,9 @@ function spawnRunner(cfg: Record<string, unknown>, suffix: string, cwd: string,
661
836
  }
662
837
  }
663
838
  onProcessTerminal?.(persisted);
839
+ };
840
+ if (startupPath) setImmediate(finalize);
841
+ else finalize();
664
842
  });
665
843
  if (typeof proc.pid !== "number") {
666
844
  return { error: `async runner did not produce a pid for cwd: ${cwd}` };
@@ -671,6 +849,8 @@ function spawnRunner(cfg: Record<string, unknown>, suffix: string, cwd: string,
671
849
  pid: proc.pid,
672
850
  processTerminal: { version: 1, state: "pending", runId: initialStatus.runId, runnerProcessInstanceId },
673
851
  });
852
+ // Aggregate waits must see the launch before the runner's first status update.
853
+ updateActiveRunIndex(path.dirname(initialStatusPath), initialStatus.state, initialStatus.toolCallId);
674
854
  } catch (error) {
675
855
  const message = `Failed to persist initial async status: ${error instanceof Error ? error.message : String(error)}`;
676
856
  if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
@@ -709,39 +889,7 @@ function spawnRunner(cfg: Record<string, unknown>, suffix: string, cwd: string,
709
889
  const persistStartupFailure = (message: string) => {
710
890
  if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
711
891
  };
712
- const ready = waitForRunnerStartup(startupPath, "ready", RUNNER_STARTUP_TIMEOUT_MS);
713
- if (ready.ok === false) {
714
- persistStartupFailure(ready.error);
715
- const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
716
- return { pid: proc.pid, runnerProcessInstanceId, error: ready.error, terminationObserved, startupDidNotProceed: ready.startupDidNotProceed };
717
- }
718
- try {
719
- writeRunnerStartupControl(startupAckPath, { action: "ack", token: ready.token });
720
- } catch (error) {
721
- const message = `Failed to acknowledge async runner startup: ${error instanceof Error ? error.message : String(error)}`;
722
- persistStartupFailure(message);
723
- const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
724
- return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
725
- }
726
- const acknowledged = waitForRunnerStartup(startupPath, "acknowledged", RUNNER_STARTUP_TIMEOUT_MS, ready.token);
727
- if (acknowledged.ok === false) {
728
- persistStartupFailure(acknowledged.error);
729
- const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
730
- return { pid: proc.pid, runnerProcessInstanceId, error: acknowledged.error, terminationObserved, startupDidNotProceed: acknowledged.startupDidNotProceed };
731
- }
732
- try {
733
- writeRunnerStartupControl(startupProceedPath, { action: "proceed", token: ready.token });
734
- } catch (error) {
735
- const message = `Failed to authorize async runner startup: ${error instanceof Error ? error.message : String(error)}`;
736
- persistStartupFailure(message);
737
- const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
738
- return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
739
- }
740
- try {
741
- fs.rmSync(startupPath, { force: true });
742
- } catch {
743
- // Proceed is the commit point; handshake cleanup cannot turn a running revival into a start error.
744
- }
892
+ return completeRunnerStartupHandshake(startupPath, startupAckPath, startupProceedPath, proc, processClosed, () => observedProcessExit ?? (proc.exitCode !== null || proc.signalCode !== null ? { exitCode: proc.exitCode, signal: proc.signalCode } : undefined), runnerProcessInstanceId, persistStartupFailure);
745
893
  }
746
894
  return { pid: proc.pid, runnerProcessInstanceId };
747
895
  } catch (error) {
@@ -795,6 +943,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
795
943
  const chainSkills = params.chainSkills ?? [];
796
944
  const availableModels = params.availableModels;
797
945
  const runnerCwd = resolveChildCwd(ctx.cwd, cwd);
946
+ const launchMachine = params.machine;
798
947
  let managedWorktreeProvider: "native" | "worktrunk" | undefined;
799
948
  try {
800
949
  if (chain.some((step) => "worktree" in step && step.worktree === true)) {
@@ -829,8 +978,6 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
829
978
  if (error instanceof ChainOutputValidationError) return { error: error.message };
830
979
  throw error;
831
980
  }
832
- const workflowGraph = buildWorkflowGraphSnapshot({ runId: id, mode: resultMode, steps: graphChain });
833
-
834
981
  const diagnosticContext = params.unknownAgentDiagnosticContext
835
982
  ?? unknownAgentDiagnosticContext(discoverAgents(path.resolve(runnerCwd), "both"));
836
983
  for (const s of chain) {
@@ -843,6 +990,8 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
843
990
  if (!agents.find((x) => x.name === agentName)) return { error: formatUnknownAgentError(agentName, diagnosticContext) };
844
991
  }
845
992
  }
993
+ const graphSteps = projectChainOutputSchemas(graphChain, agents) as ChainStep[];
994
+ const workflowGraph = buildWorkflowGraphSnapshot({ runId: id, mode: resultMode, steps: graphSteps });
846
995
 
847
996
  let progressInstructionCreated = false;
848
997
  const buildStepOverrides = (s: SequentialStep): StepOverrides => {
@@ -855,16 +1004,32 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
855
1004
  ...(stepSkillInput !== undefined ? { skills: stepSkillInput } : {}),
856
1005
  ...(s.model !== undefined ? { model: s.model } : {}),
857
1006
  ...(s.fast !== undefined ? { fast: s.fast } : {}),
1007
+ ...(s.outputSchema !== undefined ? { outputSchema: s.outputSchema } : {}),
858
1008
  };
859
1009
  };
860
1010
  const buildSeqStep = (s: SequentialStep, sessionFile?: string, behaviorCwd?: string, progressPrecreated = false, resolvedBehavior?: ResolvedStepBehavior, flatIndex?: number, parallelOutputNamespace?: { stepIndex: number; taskIndex?: number }, runFanoutPath?: string) => {
861
1011
  const a = agents.find((x) => x.name === s.agent)!;
1012
+ const effectiveBehavior = resolvedBehavior ?? suppressProgressForReadOnlyTask(resolveStepBehavior(a, buildStepOverrides(s), chainSkills), s.task, originalTask);
1013
+ const requestedMachine = s.machine ?? launchMachine ?? a.machine;
862
1014
  const externalRunner = a.runner?.type === "external-cli" || a.runner?.type === "external-job";
863
1015
  const externalRunnerType = a.runner?.type;
1016
+ const machineUnsupported = formatHerdrMachineRunnerUnsupported({ machine: requestedMachine, agentName: a.name, runnerType: a.runner?.type, adapter: a.runner?.type === "external-cli" ? a.runner.adapter : undefined, worktree: s.worktree });
1017
+ if (machineUnsupported) throw new AsyncStartValidationError(machineUnsupported);
1018
+ let machine: HerdrMachineReference | undefined;
1019
+ let machineEnv: Record<string, string> | undefined;
1020
+ if (requestedMachine) {
1021
+ try {
1022
+ const placement = resolveHerdrMachinePlacement({ machine: requestedMachine, cwd: runnerCwd, stepCwd: s.cwd ?? params.machineCwd });
1023
+ machine = placement.machine;
1024
+ machineEnv = placement.env;
1025
+ } catch (error) {
1026
+ throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
1027
+ }
1028
+ }
864
1029
  if (externalRunner) {
865
1030
  const unsupported: string[] = [];
866
1031
  if (s.model !== undefined) unsupported.push("model override");
867
- if (s.outputSchema !== undefined) unsupported.push("structured output");
1032
+ if (effectiveBehavior.outputSchema !== undefined) unsupported.push("structured output");
868
1033
  if (s.acceptance !== undefined || params.agentContract !== undefined || s.agentContract !== undefined) unsupported.push("acceptance/agent contract");
869
1034
  if (s.toolBudget !== undefined || params.toolBudget !== undefined || a.toolBudget !== undefined || params.configToolBudget !== undefined) unsupported.push("tool budget");
870
1035
  if (a.sandbox !== undefined) unsupported.push("sandbox profile");
@@ -896,10 +1061,11 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
896
1061
  runtimeCwd: ctx.cwd,
897
1062
  stepCwdInput: s.cwd,
898
1063
  behaviorCwd,
1064
+ ...(machine ? { machineCwd: machine.cwd } : {}),
899
1065
  chainSkills,
900
1066
  outputBaseDir,
901
1067
  parallelOutputNamespace,
902
- resolvedBehavior,
1068
+ resolvedBehavior: effectiveBehavior,
903
1069
  });
904
1070
  const { stepCwd, instructionCwd, readExistenceCwd, behavior, namespaceOutputPath, outputPath, skillNames } = launchPlan;
905
1071
  const profileChildCwd = behaviorCwd ?? stepCwd;
@@ -915,22 +1081,13 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
915
1081
  );
916
1082
  if (missingSkills.includes("pi-subagents")) throw new UnavailableSubagentSkillError(UNAVAILABLE_SUBAGENT_SKILL_ERROR);
917
1083
 
918
- let systemPrompt = a.systemPrompt?.trim() ?? "";
919
- if (resolvedSkills.length > 0) {
920
- const injection = buildSkillInjection(resolvedSkills);
921
- systemPrompt = systemPrompt ? `${systemPrompt}\n\n${injection}` : injection;
922
- }
923
- const memoryInjection = buildAgentMemoryInjection(a, stepCwd);
924
- if (memoryInjection) {
925
- systemPrompt = systemPrompt ? `${systemPrompt}\n\n${memoryInjection}` : memoryInjection;
926
- }
927
- systemPrompt = appendAgentRefinementOverlay(systemPrompt, { cwd: stepCwd, agentName: a.name });
1084
+ // A namespaced parallel output is injected by the runner, not the prompt.
1085
+ const systemPrompt = buildEffectiveSystemPrompt({ agent: a, resolvedSkills, cwd: stepCwd, ...(!namespaceOutputPath && outputPath ? { outputPath } : {}) });
928
1086
 
929
1087
  const readInstructions = buildChainInstructions({ ...behavior, output: false, progress: false }, instructionCwd, false, undefined, readExistenceCwd);
930
1088
  const isFirstProgressAgent = behavior.progress && !progressPrecreated && !progressInstructionCreated;
931
1089
  if (behavior.progress) progressInstructionCreated = true;
932
1090
  const progressInstructions = buildChainInstructions({ ...behavior, output: false, reads: false }, progressDir, isFirstProgressAgent);
933
- if (!namespaceOutputPath) systemPrompt = injectOutputPathSystemPrompt(systemPrompt, outputPath, a);
934
1091
  const validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Async step (${s.agent})`);
935
1092
  if (validationError) throw new AsyncStartValidationError(validationError);
936
1093
  let taskTemplate = s.task ?? "{previous}";
@@ -968,44 +1125,47 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
968
1125
  }
969
1126
  const agentContract = s.agentContract ?? params.agentContract;
970
1127
  const permissionRules = resolvePermissionRules(ctx.permissions, a.permissions);
971
- let modelCandidates: string[] = [];
1128
+ let selectedModel = model;
1129
+ let requestedModel: string | undefined;
972
1130
  if (!externalRunner) {
973
1131
  try {
974
- modelCandidates = buildModelCandidates(primaryModel, a.fallbackModels, availableModels, a.modelProvider ?? ctx.currentModelProvider, {
1132
+ const modelEvidence = resolveModelSelection(primaryModel, availableModels, a.modelProvider ?? ctx.currentModelProvider, {
975
1133
  scope: modelScopes,
976
1134
  primaryModelFromParent,
977
1135
  origin: modelOrigin,
978
- }).flatMap((candidate) => {
979
- const resolved = applyThinkingSuffix(candidate, effectiveThinking, thinkingOverride !== undefined);
980
- return resolved ? [resolved] : [];
981
1136
  });
982
- for (const candidate of modelCandidates) assertThinkingWithinCeiling({ model: candidate, configThinking: effectiveThinking, ceiling: thinkingCeiling, agent: a.name, runId: id });
1137
+ requestedModel = modelEvidence.requestedModel;
1138
+ selectedModel = applyThinkingSuffix(modelEvidence.model, effectiveThinking, thinkingOverride !== undefined);
1139
+ assertThinkingWithinCeiling({ model: selectedModel, configThinking: effectiveThinking, ceiling: thinkingCeiling, agent: a.name, runId: id });
983
1140
  } catch (error) {
984
1141
  throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
985
1142
  }
986
1143
  }
987
- const launchRuleError = applyWatchdogLaunchRules({ cwd: stepCwd, agent: a.name, model: modelCandidates[0] ?? model, warn: (violation) => sendRuleViolationWarning(ctx.pi, violation) });
1144
+ const launchRuleError = applyWatchdogLaunchRules({ cwd: machine ? runnerCwd : stepCwd, agent: a.name, model: selectedModel, warn: (violation) => sendRuleViolationWarning(ctx.pi, violation) });
988
1145
  if (launchRuleError) throw new AsyncStartValidationError(launchRuleError);
989
1146
  const fast = s.fast ?? params.fast ?? a.fast;
1147
+ const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
1148
+ const requiredExtensions = externalRunner ? [] : ctx.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
990
1149
  const toolPlan = resolvePiLaunchToolPlan({
991
1150
  tools: a.tools,
992
1151
  excludeTools: a.excludeTools,
993
1152
  allowNestedSubagents: a.allowNestedSubagents,
994
1153
  extensions: a.extensions,
995
1154
  subagentOnlyExtensions: a.subagentOnlyExtensions,
1155
+ requiredExtensions,
996
1156
  mcpDirectTools: a.mcpDirectTools,
997
1157
  cwd: stepCwd,
998
1158
  requireReadTool: Boolean(resolvedSkills.length),
999
- structuredOutput: Boolean(s.outputSchema),
1159
+ structuredOutput: Boolean(behavior.outputSchema),
1000
1160
  fast,
1001
- model,
1002
- modelCandidates,
1161
+ model: selectedModel,
1003
1162
  capabilityCeiling: params.capabilityCeiling,
1004
1163
  inheritedCapabilityCeiling: ctx.childRuntime?.capabilityCeiling,
1005
1164
  agentName: a.name,
1006
1165
  permissionRules,
1007
1166
  runtimeSnapshotHost: ctx.pi,
1008
1167
  sandbox: a.sandbox,
1168
+ hostAvailableBuiltins,
1009
1169
  });
1010
1170
  const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
1011
1171
  if (externalRunner && permissionRules) {
@@ -1035,28 +1195,32 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1035
1195
  agent: s.agent,
1036
1196
  task,
1037
1197
  ...(a.runner ? { runner: a.runner } : {}),
1198
+ ...(machine ? { machine } : {}),
1199
+ ...(machineEnv ? { machineEnv } : {}),
1038
1200
  ...(params.contextForAgent ? { context: params.contextForAgent(s.agent) } : {}),
1039
1201
  ...(agentContract ? { agentContract } : {}),
1040
1202
  phase: s.phase,
1041
1203
  label: s.label,
1042
1204
  outputName: s.as,
1043
- structured: Boolean(s.outputSchema),
1205
+ structured: Boolean(behavior.outputSchema),
1044
1206
  cwd: stepCwd,
1045
- requestedCwd: s.cwd ?? stepCwd,
1046
- model,
1207
+ requestedCwd: machine ? machine.cwd : s.cwd ?? stepCwd,
1208
+ model: selectedModel,
1047
1209
  ...(contextLimit !== undefined ? { contextLimit } : {}),
1048
1210
  ...(fast !== undefined ? { fast } : {}),
1049
- thinking: resolveEffectiveThinking(model, effectiveThinking),
1211
+ thinking: resolveEffectiveThinking(selectedModel, effectiveThinking),
1050
1212
  ...(thinkingCeiling ? { thinkingCeiling } : {}),
1051
1213
  launchResolvedExtensions,
1052
- modelCandidates: externalRunner ? undefined : modelCandidates,
1214
+ ...(requestedModel ? { requestedModel } : {}),
1053
1215
  ...(primaryModelFromParent ? { skipPrimaryModelVerification: true } : {}),
1054
1216
  ...(availableModels && availableModels.length > 0 ? { modelVerificationRegistry: availableModels } : {}),
1217
+ ...(ctx.modelResponseAliases ? { modelResponseAliases: ctx.modelResponseAliases } : {}),
1055
1218
  tools: a.tools,
1056
1219
  excludeTools: a.excludeTools,
1057
1220
  allowNestedSubagents: a.allowNestedSubagents,
1058
1221
  extensions: a.extensions,
1059
1222
  subagentOnlyExtensions: a.subagentOnlyExtensions,
1223
+ ...(!externalRunner ? { requiredExtensions } : {}),
1060
1224
  mcpDirectTools: a.mcpDirectTools,
1061
1225
  mutationTools: a.mutationTools,
1062
1226
  completionGuard: a.completionGuard,
@@ -1089,8 +1253,8 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1089
1253
  acceptanceInput: s.acceptance,
1090
1254
  acceptanceRole: a.acceptanceRole,
1091
1255
  ...(s.gateOn ? { gateOn: s.gateOn } : {}),
1092
- ...(s.outputSchema ? { structuredOutputSchema: s.outputSchema } : {}),
1093
- ...(s.outputSchema ? { structuredOutput: createStructuredOutputRuntime(s.outputSchema, path.join(asyncDir, "structured-output"), { acceptanceReport: resolveAcceptanceReportMode(s.acceptance) }) } : {}),
1256
+ ...(behavior.outputSchema ? { structuredOutputSchema: behavior.outputSchema } : {}),
1257
+ ...(behavior.outputSchema ? { structuredOutput: createStructuredOutputRuntime(behavior.outputSchema, path.join(asyncDir, "structured-output"), { acceptanceReport: resolveAcceptanceReportMode(s.acceptance) }) } : {}),
1094
1258
  ...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),
1095
1259
  ...(s.worktree ? { worktree: true } : {}),
1096
1260
  };
@@ -1134,7 +1298,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1134
1298
  }
1135
1299
  }
1136
1300
  const staticStep = nextFlatStep();
1137
- return buildSeqStep({ ...t, agentContract: t.agentContract ?? s.agentContract, gateOn: t.gateOn ?? s.gateOn }, staticStep.sessionFile, behaviorCwd, progressPrecreated, parallelBehaviors[taskIndex], staticStep.index, { stepIndex, taskIndex }, resultMode === "parallel" ? `tasks[${taskIndex}]` : `chain[${stepIndex}].parallel[${taskIndex}]`);
1301
+ return buildSeqStep({ ...t, machine: t.machine ?? s.machine, worktree: s.worktree, agentContract: t.agentContract ?? s.agentContract, gateOn: t.gateOn ?? s.gateOn }, staticStep.sessionFile, behaviorCwd, progressPrecreated, parallelBehaviors[taskIndex], staticStep.index, { stepIndex, taskIndex }, resultMode === "parallel" ? `tasks[${taskIndex}]` : `chain[${stepIndex}].parallel[${taskIndex}]`);
1138
1302
  }),
1139
1303
  concurrency: s.concurrency,
1140
1304
  failFast: s.failFast,
@@ -1263,11 +1427,9 @@ export function executeAsyncChain(
1263
1427
  } = params;
1264
1428
  const resultMode = params.resultMode ?? "chain";
1265
1429
  const acceptanceErrors = validateExecutionAcceptance({
1266
- chain: chain.map((step) => {
1267
- if (isParallelStep(step)) return { parallel: step.parallel };
1268
- if (isDynamicParallelStep(step)) return { acceptance: step.acceptance, parallel: step.parallel };
1269
- return { acceptance: step.acceptance, outputSchema: step.outputSchema };
1270
- }),
1430
+ chain: projectChainOutputSchemas(chain, agents,
1431
+ (step, outputSchema) => ({ acceptance: step.acceptance, outputSchema }),
1432
+ (step, parallel) => Array.isArray(step.parallel) ? { parallel } : { acceptance: "acceptance" in step ? step.acceptance : undefined, parallel }),
1271
1433
  });
1272
1434
  if (acceptanceErrors.length > 0) return formatAsyncStartError(resultMode, acceptanceErrors.join(" "));
1273
1435
  const capabilityCeiling = params.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(ctx.currentSessionId);
@@ -1301,6 +1463,8 @@ export function executeAsyncChain(
1301
1463
  availableModels: params.availableModels,
1302
1464
  cwd,
1303
1465
  chainSkills: params.chainSkills,
1466
+ machine: params.machine,
1467
+ machineCwd: params.machineCwd,
1304
1468
  sessionFilesByFlatIndex,
1305
1469
  thinkingOverridesByFlatIndex,
1306
1470
  contextForAgent: params.contextForAgent,
@@ -1404,6 +1568,7 @@ export function executeAsyncChain(
1404
1568
  deadlineAt,
1405
1569
  globalConcurrencyLimit: params.globalConcurrencyLimit,
1406
1570
  runFanoutBudget,
1571
+ hostAvailableBuiltins: getHostBuiltinToolNames(ctx.pi),
1407
1572
  workflowGraph,
1408
1573
  ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
1409
1574
  ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
@@ -1434,7 +1599,7 @@ export function executeAsyncChain(
1434
1599
  path.join(asyncDir, "status.json"),
1435
1600
  (proof) => emitProcessTerminalEvent(ctx, proof),
1436
1601
  (runnerProcessInstanceId) => params.activeAsyncCapacity?.markStarted(runnerProcessInstanceId),
1437
- );
1602
+ ) as SpawnRunnerResult;
1438
1603
  } catch (error) {
1439
1604
  params.activeAsyncCapacity?.rollback();
1440
1605
  const message = error instanceof Error ? error.message : String(error);
@@ -1574,7 +1739,7 @@ export function workflowAwaitedAsyncResultPath(asyncDir: string): string {
1574
1739
  export function executeAsyncSingle(
1575
1740
  id: string,
1576
1741
  params: AsyncSingleParams,
1577
- ): AsyncExecutionResult {
1742
+ ): AsyncExecutionResult | Promise<AsyncExecutionResult> {
1578
1743
  const {
1579
1744
  agent,
1580
1745
  agentConfig,
@@ -1640,6 +1805,20 @@ export function executeAsyncSingle(
1640
1805
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1641
1806
  }
1642
1807
  const runnerCwd = resolveChildCwd(ctx.cwd, cwd);
1808
+ const requestedMachine = params.machine ?? agentConfig.machine;
1809
+ const machineUnsupported = formatHerdrMachineRunnerUnsupported({ machine: requestedMachine, agentName: agentConfig.name, runnerType: agentConfig.runner?.type, adapter: agentConfig.runner?.type === "external-cli" ? agentConfig.runner.adapter : undefined, worktree: params.worktree });
1810
+ if (machineUnsupported) return formatAsyncStartError("single", machineUnsupported);
1811
+ let machine: HerdrMachineReference | undefined;
1812
+ let machineEnv: Record<string, string> | undefined;
1813
+ if (requestedMachine) {
1814
+ try {
1815
+ const placement = resolveHerdrMachinePlacement({ machine: requestedMachine, cwd: runnerCwd, stepCwd: params.machineCwd });
1816
+ machine = placement.machine;
1817
+ machineEnv = placement.env;
1818
+ } catch (error) {
1819
+ return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1820
+ }
1821
+ }
1643
1822
  let managedWorktreeProvider: "native" | "worktrunk" | undefined;
1644
1823
  if (params.worktree === true) {
1645
1824
  try {
@@ -1653,7 +1832,7 @@ export function executeAsyncSingle(
1653
1832
  ? WORKTREE_AGENT_CWD_PLACEHOLDER
1654
1833
  : params.worktree === true && managedWorktreeProvider === "native"
1655
1834
  ? resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s0`, 0, worktreeBaseDir)
1656
- : runnerCwd;
1835
+ : machine?.cwd ?? runnerCwd;
1657
1836
  if (sandbox && (agentConfig.source === "project" || agentConfig.override?.scope === "project") && !profileProjectTrustedForCwd(ctx, instructionCwd)) {
1658
1837
  return formatAsyncStartError("single", profileProjectTrustError(agentConfig, ctx));
1659
1838
  }
@@ -1668,16 +1847,6 @@ export function executeAsyncSingle(
1668
1847
  agentConfig.filePath ? path.dirname(agentConfig.filePath) : runnerCwd,
1669
1848
  );
1670
1849
  if (missingSkills.includes("pi-subagents")) return formatAsyncStartError("single", UNAVAILABLE_SUBAGENT_SKILL_ERROR);
1671
- let systemPrompt = agentConfig.systemPrompt?.trim() ?? "";
1672
- if (resolvedSkills.length > 0) {
1673
- const injection = buildSkillInjection(resolvedSkills);
1674
- systemPrompt = systemPrompt ? `${systemPrompt}\n\n${injection}` : injection;
1675
- }
1676
- const memoryInjection = buildAgentMemoryInjection(agentConfig, runnerCwd);
1677
- if (memoryInjection) {
1678
- systemPrompt = systemPrompt ? `${systemPrompt}\n\n${memoryInjection}` : memoryInjection;
1679
- }
1680
- systemPrompt = appendAgentRefinementOverlay(systemPrompt, { cwd: runnerCwd, agentName: agentConfig.name });
1681
1850
 
1682
1851
  const inheritedNestedRoute = inheritedNestedRouteOf(ctx.childRuntime);
1683
1852
  const nestedAddress = inheritedNestedRoute ? inheritedNestedParentAddressOf(ctx.childRuntime) : undefined;
@@ -1700,7 +1869,7 @@ export function executeAsyncSingle(
1700
1869
 
1701
1870
  const effectiveOutput = normalizeSingleOutputOverride(params.output, agentConfig.output);
1702
1871
  const outputPath = resolveSingleOutputPath(effectiveOutput, ctx.cwd, instructionCwd, params.outputBaseDir ?? (artifactsDir ? path.join(artifactsDir, "outputs", id) : undefined));
1703
- systemPrompt = injectOutputPathSystemPrompt(systemPrompt, outputPath, agentConfig);
1872
+ const systemPrompt = buildEffectiveSystemPrompt({ agent: agentConfig, resolvedSkills, cwd: runnerCwd, ...(outputPath ? { outputPath } : {}) });
1704
1873
  const outputMode = params.outputMode ?? agentConfig.outputMode ?? "inline";
1705
1874
  const validationError = validateFileOnlyOutputMode(outputMode, outputPath, `Async single run (${agent})`);
1706
1875
  if (validationError) return formatAsyncStartError("single", validationError);
@@ -1709,7 +1878,11 @@ export function executeAsyncSingle(
1709
1878
  // absolute paths pass through; relative paths resolve against the child cwd.
1710
1879
  const reads = params.reads !== undefined ? params.reads : agentConfig.defaultReads ?? false;
1711
1880
  const readPaths = Array.isArray(reads)
1712
- ? managedWorktreeProvider === "worktrunk"
1881
+ ? machine
1882
+ ? externalRunner
1883
+ ? reads.map((read) => read === "~" || read.startsWith("~/") || path.posix.isAbsolute(read) ? read : path.posix.resolve(instructionCwd, read))
1884
+ : []
1885
+ : managedWorktreeProvider === "worktrunk"
1713
1886
  ? resolveExistingReadInstructionPaths(reads, instructionCwd, readExistenceCwd)
1714
1887
  : resolveExistingReadPaths(reads, readExistenceCwd)
1715
1888
  : [];
@@ -1775,41 +1948,44 @@ export function executeAsyncSingle(
1775
1948
  const structuredOutput = params.structuredOutputSchema
1776
1949
  ? createStructuredOutputRuntime(params.structuredOutputSchema, path.join(asyncDir, "structured-output"), { acceptanceReport: resolveAcceptanceReportMode(params.acceptance) })
1777
1950
  : undefined;
1778
- let modelCandidates: string[] = [];
1951
+ let selectedModel = model;
1952
+ let requestedModel: string | undefined;
1779
1953
  if (!externalRunner) {
1780
1954
  try {
1781
- modelCandidates = buildModelCandidates(primaryModel, agentConfig.fallbackModels, availableModels, agentConfig.modelProvider ?? ctx.currentModelProvider, {
1955
+ const modelEvidence = resolveModelSelection(primaryModel, availableModels, agentConfig.modelProvider ?? ctx.currentModelProvider, {
1782
1956
  scope: modelScopes,
1783
1957
  primaryModelFromParent: modelOrigin === "inherited",
1784
1958
  origin: modelOrigin,
1785
- }).flatMap((candidate) => {
1786
- const resolved = applyThinkingSuffix(candidate, effectiveThinking, params.thinkingOverride !== undefined);
1787
- return resolved ? [resolved] : [];
1788
1959
  });
1789
- for (const candidate of modelCandidates) assertThinkingWithinCeiling({ model: candidate, configThinking: effectiveThinking, ceiling: thinkingCeiling, agent: agentConfig.name, runId: id });
1960
+ requestedModel = modelEvidence.requestedModel;
1961
+ selectedModel = applyThinkingSuffix(modelEvidence.model, effectiveThinking, params.thinkingOverride !== undefined);
1962
+ assertThinkingWithinCeiling({ model: selectedModel, configThinking: effectiveThinking, ceiling: thinkingCeiling, agent: agentConfig.name, runId: id });
1790
1963
  } catch (error) {
1791
1964
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1792
1965
  }
1793
1966
  }
1967
+ const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
1968
+ const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1794
1969
  const toolPlan = resolvePiLaunchToolPlan({
1795
1970
  tools: agentConfig.tools,
1796
1971
  excludeTools: agentConfig.excludeTools,
1797
1972
  allowNestedSubagents: agentConfig.allowNestedSubagents,
1798
1973
  extensions: agentConfig.extensions,
1799
1974
  subagentOnlyExtensions: agentConfig.subagentOnlyExtensions,
1975
+ requiredExtensions,
1800
1976
  mcpDirectTools: agentConfig.mcpDirectTools,
1801
1977
  cwd: runnerCwd,
1802
1978
  requireReadTool: Boolean(resolvedSkills.length),
1803
1979
  structuredOutput: Boolean(params.structuredOutputSchema),
1804
1980
  fast: params.fast ?? agentConfig.fast,
1805
- model,
1806
- modelCandidates,
1981
+ model: selectedModel,
1807
1982
  capabilityCeiling,
1808
1983
  inheritedCapabilityCeiling: ctx.childRuntime?.capabilityCeiling,
1809
1984
  agentName: agentConfig.name,
1810
1985
  permissionRules: resolvePermissionRules(ctx.permissions, agentConfig.permissions),
1811
1986
  runtimeSnapshotHost: ctx.pi,
1812
1987
  sandbox,
1988
+ hostAvailableBuiltins,
1813
1989
  });
1814
1990
  const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
1815
1991
  if (!externalRunner) {
@@ -1826,14 +2002,14 @@ export function executeAsyncSingle(
1826
2002
  });
1827
2003
  if (contractError) return formatAsyncStartError("single", contractError);
1828
2004
  }
1829
- const launchContractDigest = launchBindingDigest({
1830
- definitionDigest: agentDefinitionDigest(agentConfig),
2005
+ const fast = params.fast ?? agentConfig.fast;
2006
+ const launchThinking = resolveEffectiveThinking(selectedModel, effectiveThinking);
2007
+ const { definitionDigest, launchContractDigest } = resolveLaunchBinding({
2008
+ agent: agentConfig,
1831
2009
  task,
1832
- ...(model ? { model } : {}),
1833
- modelCandidates,
1834
- ...((params.fast ?? agentConfig.fast) !== undefined ? { fast: params.fast ?? agentConfig.fast } : {}),
1835
- ...(resolveEffectiveThinking(model, effectiveThinking) ? { thinking: resolveEffectiveThinking(model, effectiveThinking) } : {}),
1836
- ...(thinkingCeiling ? { thinkingCeiling } : {}),
2010
+ model: selectedModel,
2011
+ ...(fast !== undefined ? { fast } : {}),
2012
+ ...(launchThinking ? { thinking: launchThinking } : {}),
1837
2013
  systemPrompt,
1838
2014
  systemPromptMode: agentConfig.systemPromptMode,
1839
2015
  inheritProjectContext: agentConfig.inheritProjectContext,
@@ -1841,10 +2017,7 @@ export function executeAsyncSingle(
1841
2017
  inheritSkills: agentConfig.inheritSkills,
1842
2018
  sandbox,
1843
2019
  skills: resolvedSkills.map((skill) => skill.name),
1844
- tools: toolPlan.effectiveToolAllowlist,
1845
- ...(toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
1846
- extensions: toolPlan.extensionArgs,
1847
- mcpDirectTools: toolPlan.effectiveMcpTools,
2020
+ toolPlan,
1848
2021
  ...(outputPath ? { outputPath } : {}),
1849
2022
  outputMode,
1850
2023
  ...(params.structuredOutputSchema ? { structuredOutputSchema: params.structuredOutputSchema } : {}),
@@ -1861,10 +2034,12 @@ export function executeAsyncSingle(
1861
2034
  });
1862
2035
  const recoveryAgentConfig = params.recoveryAgentConfig ?? agentConfig;
1863
2036
  const recoveryDescriptor: SteeringRecoveryDescriptor = {
2037
+ ...(ctx.modelResponseAliases ? { modelResponseAliases: ctx.modelResponseAliases } : {}),
1864
2038
  version: 1,
1865
2039
  ...(lane ? { lane } : {}),
1866
2040
  launchContractDigest,
1867
2041
  ...(extensionBindings ? { extensionBindings } : {}),
2042
+ ...(requiredExtensions.length > 0 ? { requiredExtensions } : {}),
1868
2043
  runFanoutBudget,
1869
2044
  sourceRunId: id,
1870
2045
  ...(params.agentContract ? { agentContract: params.agentContract } : {}),
@@ -1873,13 +2048,12 @@ export function executeAsyncSingle(
1873
2048
  launchResolvedExtensions,
1874
2049
  ...(sessionFile ? { sessionFile } : {}),
1875
2050
  cwd: runnerCwd,
1876
- ...(model ? { model } : {}),
2051
+ ...(selectedModel ? { model: selectedModel } : {}),
1877
2052
  ...(params.fast ?? recoveryAgentConfig.fast ? { fast: params.fast ?? recoveryAgentConfig.fast } : {}),
1878
2053
  ...(recoveryAgentConfig.modelProvider ? { modelProvider: recoveryAgentConfig.modelProvider } : {}),
1879
2054
  ...(modelOrigin === "inherited" ? { modelOverrideFromParent: true } : {}),
1880
2055
  modelOrigin,
1881
- ...(recoveryAgentConfig.fallbackModels ? { fallbackModels: [...recoveryAgentConfig.fallbackModels] } : {}),
1882
- ...(effectiveThinking ? { thinking: resolveEffectiveThinking(model, effectiveThinking) } : {}),
2056
+ ...(effectiveThinking ? { thinking: resolveEffectiveThinking(selectedModel, effectiveThinking) } : {}),
1883
2057
  ...(thinkingCeiling ? { thinkingCeiling } : {}),
1884
2058
  ...(recoveryAgentConfig.tools ? { tools: [...recoveryAgentConfig.tools] } : {}),
1885
2059
  ...(recoveryAgentConfig.excludeTools ? { excludeTools: [...recoveryAgentConfig.excludeTools] } : {}),
@@ -1923,11 +2097,11 @@ export function executeAsyncSingle(
1923
2097
  return formatAsyncStartError("single", `Failed to persist async recovery descriptor for '${id}': ${error instanceof Error ? error.message : String(error)}`);
1924
2098
  }
1925
2099
  }
1926
- let spawnResult: SpawnRunnerResult = {};
2100
+ let spawnResultOrPromise: SpawnRunnerResult | Promise<SpawnRunnerResult> = {};
1927
2101
  const initialStatusAt = Date.now();
1928
2102
  const initialCompletionOwnerId = ctx.completionOwnerId ?? currentCompletionOwnerId();
1929
2103
  try {
1930
- spawnResult = spawnRunner(
2104
+ spawnResultOrPromise = spawnRunner(
1931
2105
  {
1932
2106
  id,
1933
2107
  steps: [
@@ -1940,23 +2114,28 @@ export function executeAsyncSingle(
1940
2114
  agent,
1941
2115
  task: taskText,
1942
2116
  ...(agentConfig.runner ? { runner: agentConfig.runner } : {}),
2117
+ ...(machine ? { machine } : {}),
2118
+ ...(!externalRunner && machine && params.reads !== undefined ? { remoteReads: params.reads } : {}),
2119
+ ...(machineEnv ? { machineEnv } : {}),
1943
2120
  ...(params.externalJobFollowUp ? { externalJobFollowUp: params.externalJobFollowUp } : {}),
1944
2121
  ...(params.context ? { context: params.context } : {}),
1945
- cwd: runnerCwd,
1946
- requestedCwd: params.requestedCwd ?? runnerCwd,
1947
- model,
2122
+ cwd: machine?.cwd ?? runnerCwd,
2123
+ requestedCwd: machine?.cwd ?? params.requestedCwd ?? runnerCwd,
2124
+ model: selectedModel,
1948
2125
  ...(contextLimit !== undefined ? { contextLimit } : {}),
1949
2126
  ...(params.fast ?? agentConfig.fast ? { fast: params.fast ?? agentConfig.fast } : {}),
1950
- thinking: resolveEffectiveThinking(model, effectiveThinking),
2127
+ thinking: resolveEffectiveThinking(selectedModel, effectiveThinking),
1951
2128
  ...(thinkingCeiling ? { thinkingCeiling } : {}),
1952
- modelCandidates,
2129
+ ...(requestedModel ? { requestedModel } : {}),
1953
2130
  ...(modelOrigin === "inherited" ? { skipPrimaryModelVerification: true } : {}),
1954
2131
  ...(availableModels && availableModels.length > 0 ? { modelVerificationRegistry: availableModels } : {}),
2132
+ ...(ctx.modelResponseAliases ? { modelResponseAliases: ctx.modelResponseAliases } : {}),
1955
2133
  tools: agentConfig.tools,
1956
2134
  excludeTools: agentConfig.excludeTools,
1957
2135
  allowNestedSubagents: agentConfig.allowNestedSubagents,
1958
2136
  extensions: agentConfig.extensions,
1959
2137
  subagentOnlyExtensions: agentConfig.subagentOnlyExtensions,
2138
+ ...(!externalRunner ? { requiredExtensions } : {}),
1960
2139
  mcpDirectTools: agentConfig.mcpDirectTools,
1961
2140
  mutationTools: agentConfig.mutationTools,
1962
2141
  completionGuard: agentConfig.completionGuard,
@@ -1975,7 +2154,7 @@ export function executeAsyncSingle(
1975
2154
  waitToolEnabled: params.waitToolEnabled,
1976
2155
  waitToolDefaultTimeoutMs: params.waitToolDefaultTimeoutMs,
1977
2156
  ...(params.agentContract ? { agentContract: params.agentContract } : {}),
1978
- definitionDigest: agentDefinitionDigest(agentConfig),
2157
+ definitionDigest,
1979
2158
  launchBindingTask: task,
1980
2159
  launchContractDigest,
1981
2160
  ...(extensionBindings ? { extensionBindings } : {}),
@@ -2016,6 +2195,7 @@ export function executeAsyncSingle(
2016
2195
  timeoutMs,
2017
2196
  deadlineAt,
2018
2197
  toolTimeoutMs,
2198
+ checkpointBeforeDeadlineMs: params.checkpointBeforeDeadlineMs,
2019
2199
  toolBudget: params.toolBudget,
2020
2200
  usageBudget: params.usageBudget,
2021
2201
  controlIntercomTarget,
@@ -2024,6 +2204,7 @@ export function executeAsyncSingle(
2024
2204
  launchContractDigest,
2025
2205
  launchResolvedExtensions,
2026
2206
  runFanoutBudget,
2207
+ hostAvailableBuiltins,
2027
2208
  ...(params.parentWorkflowRunId ? { parentWorkflowRunId: params.parentWorkflowRunId } : {}),
2028
2209
  ...(params.workflowKey ? { workflowKey: params.workflowKey } : {}),
2029
2210
  ...(lane ? { lane } : {}),
@@ -2062,7 +2243,7 @@ export function executeAsyncSingle(
2062
2243
  const message = error instanceof Error ? error.message : String(error);
2063
2244
  return formatAsyncStartError("single", `Failed to start async run '${id}': ${message}`);
2064
2245
  }
2065
-
2246
+ const finishSpawnResult = (spawnResult: SpawnRunnerResult): AsyncExecutionResult => {
2066
2247
  if (spawnResult.error) {
2067
2248
  if (spawnResult.startupDidNotProceed) {
2068
2249
  if (!spawnResult.runnerProcessInstanceId || params.activeAsyncCapacity?.rollbackBeforeRunnerProceed(spawnResult.runnerProcessInstanceId) !== true) params.activeAsyncCapacity?.rollback();
@@ -2141,4 +2322,6 @@ export function executeAsyncSingle(
2141
2322
  content: [{ type: "text", text: formatAsyncStartedMessage(`Async: ${agent} [${id}]`, ctx.interactive === true) }],
2142
2323
  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,
2143
2324
  };
2325
+ };
2326
+ return spawnResultOrPromise instanceof Promise ? spawnResultOrPromise.then(finishSpawnResult) : finishSpawnResult(spawnResultOrPromise);
2144
2327
  }