@xzzpig/pi-subagents 0.19.0 → 0.21.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 (153) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +86 -11
  9. package/docs/configuration.md +68 -7
  10. package/docs/extension-api.md +37 -12
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +48 -17
  13. package/docs/models.md +7 -3
  14. package/docs/observability.md +18 -8
  15. package/docs/tool-reference.md +138 -80
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +18 -9
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +224 -122
  32. package/src/api/preflight.ts +50 -5
  33. package/src/extension/config.ts +24 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +134 -145
  40. package/src/extension/public-execution.ts +3 -0
  41. package/src/extension/reply-workflow-script.ts +21 -12
  42. package/src/extension/rpc.ts +12 -7
  43. package/src/extension/schemas.ts +39 -33
  44. package/src/extension/subagent-guide.ts +86 -6
  45. package/src/extension/subagent-options.ts +47 -0
  46. package/src/extension/tool-activation.ts +3 -2
  47. package/src/extension/tool-description.ts +51 -68
  48. package/src/inspectors/actions.ts +37 -11
  49. package/src/inspectors/plugins.ts +3 -2
  50. package/src/inspectors/tmux/actions.ts +204 -0
  51. package/src/inspectors/tmux/client.ts +85 -0
  52. package/src/inspectors/tmux/plugin.ts +21 -0
  53. package/src/integrations/herdr-status.ts +18 -49
  54. package/src/integrations/program-status.ts +215 -0
  55. package/src/intercom/native-supervisor-channel.ts +77 -4
  56. package/src/intercom/result-intercom.ts +3 -2
  57. package/src/intercom/supervisor-ui.ts +2 -174
  58. package/src/missions/goal-driver.ts +44 -31
  59. package/src/missions/store.ts +35 -6
  60. package/src/profiles/profiles.ts +29 -23
  61. package/src/runs/background/active-async-capacity.ts +58 -8
  62. package/src/runs/background/async-execution.ts +231 -44
  63. package/src/runs/background/async-job-tracker.ts +12 -4
  64. package/src/runs/background/async-resume.ts +5 -2
  65. package/src/runs/background/await-async-run.ts +18 -11
  66. package/src/runs/background/binary-bootstrap.ts +2 -1
  67. package/src/runs/background/calendar-schedule.ts +90 -0
  68. package/src/runs/background/chain-root-attachment.ts +9 -5
  69. package/src/runs/background/control-channel.ts +43 -0
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +29 -8
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-aliases.ts +7 -4
  79. package/src/runs/background/runner-child-launch.ts +1 -0
  80. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  81. package/src/runs/background/scheduled-runs.ts +282 -72
  82. package/src/runs/background/stale-run-reconciler.ts +13 -2
  83. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  84. package/src/runs/background/subagent-runner.ts +75 -16
  85. package/src/runs/background/subagent-wait.ts +38 -19
  86. package/src/runs/background/terminal-run-index.ts +46 -1
  87. package/src/runs/background/wait-completions.ts +1 -0
  88. package/src/runs/background/wait-tool.ts +33 -23
  89. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  90. package/src/runs/foreground/async-stop-action.ts +48 -22
  91. package/src/runs/foreground/command-action.ts +41 -0
  92. package/src/runs/foreground/execution.ts +109 -58
  93. package/src/runs/foreground/foreground-history.ts +1 -0
  94. package/src/runs/foreground/subagent-executor.ts +270 -89
  95. package/src/runs/shared/child-commands.ts +229 -0
  96. package/src/runs/shared/child-hooks.ts +4 -3
  97. package/src/runs/shared/child-launch.ts +3 -0
  98. package/src/runs/shared/child-session.ts +131 -40
  99. package/src/runs/shared/child-tool-plan.ts +14 -27
  100. package/src/runs/shared/claude-code-adapter.ts +157 -2
  101. package/src/runs/shared/dynamic-fanout.ts +2 -2
  102. package/src/runs/shared/external-cli-preflight.ts +54 -6
  103. package/src/runs/shared/external-cli-runner.ts +5 -1
  104. package/src/runs/shared/fork-command-result.ts +10 -0
  105. package/src/runs/shared/herdr-placed-run.ts +5 -4
  106. package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
  107. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  108. package/src/runs/shared/model-resolution.ts +39 -2
  109. package/src/runs/shared/nested-events.ts +5 -0
  110. package/src/runs/shared/parallel-handoff.ts +56 -8
  111. package/src/runs/shared/parallel-utils.ts +4 -0
  112. package/src/runs/shared/partial-output.ts +48 -0
  113. package/src/runs/shared/run-history.ts +87 -0
  114. package/src/runs/shared/runner-launcher.ts +25 -0
  115. package/src/runs/shared/single-output.ts +53 -0
  116. package/src/runs/shared/structured-output.ts +14 -7
  117. package/src/runs/shared/subagent-control.ts +33 -18
  118. package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
  119. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  120. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  121. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  122. package/src/runs/shared/worktree-lock.ts +29 -0
  123. package/src/runs/shared/worktree.ts +12 -1
  124. package/src/shared/atomic-json.ts +4 -2
  125. package/src/shared/edit-distance.ts +33 -0
  126. package/src/shared/file-lease.ts +74 -0
  127. package/src/shared/formatters.ts +1 -5
  128. package/src/shared/model-info.ts +22 -0
  129. package/src/shared/package-version.ts +17 -0
  130. package/src/shared/parent-wake.ts +79 -0
  131. package/src/shared/pruned-fork.ts +7 -1
  132. package/src/shared/required-child-extensions.ts +39 -5
  133. package/src/shared/runtime-module-path.ts +19 -0
  134. package/src/shared/settings-file-lease.ts +36 -0
  135. package/src/shared/types.ts +42 -3
  136. package/src/shared/utils.ts +8 -6
  137. package/src/slash/slash-commands.ts +3 -3
  138. package/src/slash/subagent-cost.ts +9 -5
  139. package/src/slash/subagents-admin.ts +2 -1
  140. package/src/tui/fleet-native-transcript.ts +2 -0
  141. package/src/tui/fleet-transcript.ts +12 -3
  142. package/src/tui/fleet.ts +11 -8
  143. package/src/tui/render.ts +28 -20
  144. package/src/tui/subagent-messages.ts +305 -0
  145. package/src/watchdog/diff-tool.ts +2 -2
  146. package/src/watchdog/register-main.ts +2 -22
  147. package/src/watchdog/render.ts +2 -24
  148. package/src/watchdog/runtime.ts +6 -4
  149. package/src/watchdog/settings.ts +18 -13
  150. package/src/watchdog/tool-actions.ts +2 -2
  151. package/src/workflows/scripted-workflow.ts +20 -6
  152. package/src/workflows/workflow-receipt.ts +2 -2
  153. package/src/workflows/workflow-resources.ts +18 -4
@@ -17,15 +17,17 @@ import { currentCompletionOwnerId } from "../../shared/completion-owner.ts";
17
17
  import { planChildLaunch, projectChainOutputSchemas, resolveStepBehavior, suppressProgressForReadOnlyTask, type ResolvedStepBehavior } from "../shared/child-launch-plan.ts";
18
18
  import { formatHerdrMachineRunnerUnsupported, resolveHerdrMachinePlacement } from "../shared/herdr-machine.ts";
19
19
  import { applyThinkingSuffix, getHostBuiltinToolNames, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan } from "../shared/child-tool-plan.ts";
20
+ import { assertClaudeCodeModelScope, isClaudeCodeAdapterId, resolveClaudeCodeOverride, type ClaudeCodeOverride } from "../shared/claude-code-adapter.ts";
20
21
  import { injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
21
22
  import { applyWatchdogLaunchRules, sendRuleViolationWarning } from "../../watchdog/rules.ts";
22
- import { buildChainInstructions, isDynamicParallelStep, isParallelStep, resolveExistingReadInstructionPaths, resolveExistingReadPaths, writeInitialProgressFile, type ChainStep, type SequentialStep, type StepOverrides } from "../../shared/settings.ts";
23
+ import { buildChainInstructions, getStepAgents, isDynamicParallelStep, isParallelStep, resolveExistingReadInstructionPaths, resolveExistingReadPaths, writeInitialProgressFile, type ChainStep, type SequentialStep, type StepOverrides } from "../../shared/settings.ts";
23
24
  import { isDynamicRunnerGroup, isParallelGroup, type RunnerStep } from "../shared/parallel-utils.ts";
24
25
  import type { ContextMode } from "../shared/context-mode.ts";
25
26
  import { PI_CODING_AGENT_PACKAGE, resolveBunPiExecutable, resolveInstalledPiPackageRoot, resolvePiPackageRoot } from "../shared/pi-spawn.ts";
26
27
  import { JITI_ALIAS_ENV, resolveHostPeerAliases } from "./runner-aliases.ts";
27
28
  import { preflightLaunchCwd } from "../shared/launch-cwd.ts";
28
29
  import { resolveNodeExecutable } from "../../shared/node-executable.ts";
30
+ import { resolveRuntimeModulePath } from "../../shared/runtime-module-path.ts";
29
31
  import { backgroundProcessOptions } from "../shared/background-process-options.ts";
30
32
  import { normalizeSkillInput, resolveSkillsWithFallback } from "../../agents/skills.ts";
31
33
  import { PI_CODING_AGENT_PACKAGE_ROOT_ENV, PROMPT_REDACTED, resolveChildCwd } from "../../shared/utils.ts";
@@ -82,14 +84,16 @@ import { persistRunnerStartupFailure } from "./runner-startup-failure.ts";
82
84
  import type { ActiveAsyncCapacityHandle } from "./active-async-capacity.ts";
83
85
  import { statusStepDescription } from "./chain-append.ts";
84
86
  import { currentPidNamespaceScope } from "./pid-namespace.ts";
85
- import { SUBAGENT_PROCESS_TERMINAL_EVENT } from "../../shared/types.ts";
87
+ import { checkPidLiveness } from "./stale-run-reconciler.ts";
88
+ import { lookupRunnerLauncher, resolveAgentRunnerLauncher, runnerLauncherPlacementError } from "../shared/runner-launcher.ts";
89
+ import { SUBAGENT_PROCESS_TERMINAL_EVENT, type RunnerLauncher } from "../../shared/types.ts";
86
90
  import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
87
91
  import { resolveLaunchBinding } from "../../shared/launch-contract.ts";
88
92
  import { resolvePermissionRules, type PermissionConfig } from "../shared/permissions.ts";
89
93
  import { normalizeExtensionBindings, omitExtensionBindingsEnv, omitInheritedProfileEnv, type ExtensionBindings } from "../shared/extension-bindings.ts";
90
94
  import { omitGitRoutingEnv } from "../shared/git-environment.ts";
91
95
  import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
92
- import { resolveRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
96
+ import { assertRequiredChildExtensionsAdmitted, resolveRequiredChildExtensions, writeRetainedRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
93
97
 
94
98
  const require = nodeModule.createRequire(import.meta.url);
95
99
  const piPackageRoot = resolveAsyncPiPackageRoot();
@@ -159,16 +163,19 @@ function resolveJitiCliPath(): string | undefined {
159
163
  }
160
164
 
161
165
  const jitiCliPath = resolveJitiCliPath();
162
- const asyncRunnerSourcePath = path.join(
163
- path.dirname(fileURLToPath(import.meta.url)),
164
- `subagent-runner-bootstrap${path.extname(fileURLToPath(import.meta.url))}`,
165
- );
166
- const sourceUnderNodeModules = asyncRunnerSourcePath.split(path.sep).some((segment) => segment.toLowerCase() === "node_modules");
166
+ const asyncRunnerModuleDir = path.dirname(fileURLToPath(import.meta.url));
167
+ // Resolved per launch: an in-place package update can swap a sibling's .ts for .js.
168
+ function asyncRunnerSourcePath(): string {
169
+ return resolveRuntimeModulePath(asyncRunnerModuleDir, "subagent-runner-bootstrap");
170
+ }
171
+ function sourceUnderNodeModules(): boolean {
172
+ return asyncRunnerSourcePath().split(path.sep).some((segment) => segment.toLowerCase() === "node_modules");
173
+ }
167
174
  function supportsNativeRunner(nodeExecutable: string): boolean {
168
175
  return Boolean(process.features.typescript)
169
176
  && typeof nodeModule.registerHooks === "function"
170
177
  && nodeExecutable === process.execPath
171
- && !sourceUnderNodeModules;
178
+ && !sourceUnderNodeModules();
172
179
  }
173
180
 
174
181
  interface AsyncExecutionContext {
@@ -178,6 +185,8 @@ interface AsyncExecutionContext {
178
185
  completionOwnerId?: string;
179
186
  /** Parent session id used by permission-system ask forwarding. */
180
187
  parentSessionId?: string;
188
+ /** Parent session file, recorded as each new child session's `parentSession` header. */
189
+ parentSessionFile?: string;
181
190
  permissions?: PermissionConfig;
182
191
  currentModelProvider?: string;
183
192
  currentModel?: ParentModel;
@@ -191,6 +200,8 @@ trustedProjectCwd?: string;
191
200
  modelResponseAliases?: Record<string, string[]>;
192
201
  /** Whether the parent session has an interactive UI. */
193
202
  interactive?: boolean;
203
+ /** User-configured runner launchers; an agent's `launcher` must name one of them. */
204
+ runnerLaunchers?: Record<string, string[]>;
194
205
  /** The executor's own child runtime when the launch comes from an in-process child. */
195
206
  childRuntime?: ChildRuntimeConfig;
196
207
  }
@@ -253,6 +264,7 @@ interface AsyncChainParams {
253
264
  /** Global cap on simultaneously-running subagent tasks within the async run. */
254
265
  globalConcurrencyLimit?: number;
255
266
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
267
+ requiredExtensions?: RequiredChildExtensionSnapshot;
256
268
  thinkingCeiling?: ThinkingLevel;
257
269
  runFanoutBudget?: RunFanoutBudgetDescriptor;
258
270
  parentWorkflowRunId?: string;
@@ -262,6 +274,8 @@ interface AsyncChainParams {
262
274
  }
263
275
 
264
276
  interface AsyncSingleParams {
277
+ /** Originating executor invocation, distinct from the async run id. */
278
+ toolCallId?: string;
265
279
  agent: string;
266
280
  task?: string;
267
281
  /** Raw caller-facing goal used only by the started event. */
@@ -394,6 +408,8 @@ export interface AsyncRunnerStepBuildParams {
394
408
  /** PI_SUBAGENT_TOOL_TIMEOUT_MS override (lowest precedence). */
395
409
  toolTimeoutMsEnv?: string | undefined;
396
410
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
411
+ /** Retained snapshot from the launch being continued; takes precedence over the live registry, as in single launches. */
412
+ requiredExtensions?: RequiredChildExtensionSnapshot;
397
413
  thinkingCeiling?: ThinkingLevel;
398
414
  }
399
415
 
@@ -404,22 +420,19 @@ export type AsyncRunnerStepBuildResult =
404
420
  workflowGraph: ReturnType<typeof buildWorkflowGraphSnapshot>;
405
421
  eventChain: ChainStep[];
406
422
  originalTask?: string;
423
+ /** Launcher name shared by every new step; absent when they run unwrapped. */
424
+ launcher?: string;
407
425
  }
408
426
  | { error: string };
409
427
 
410
428
  export function formatAsyncStartedMessage(headline: string, interactive: boolean): string {
411
429
  const guidance = interactive
412
430
  ? [
413
- "The async run is detached and running in the background.",
414
- "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.",
415
- "Use bg_wait only for provider, detached, or other background work that lacks a native completion notification.",
416
- "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.",
417
- "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.",
431
+ "Detached. Return control now: native completion wakes you, so do not sleep, poll, or call bg_wait for it.",
432
+ "One-shot check: subagent({ action: \"status\", id: \"...\" }).",
418
433
  ]
419
434
  : [
420
- "The async run is detached. Do not run sleep timers or polling loops just to wait for it.",
421
- "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.",
422
- "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.",
435
+ "Detached non-interactive run: Pi auto-drains current-session subagent work at agent_end. Do not run sleep timers or polling loops. Use bg_wait only for results this turn needs from work without native notification, and subagent({ action: \"status\", id: \"...\" }) for a one-shot check.",
423
436
  ];
424
437
  return [headline, "", ...guidance].join("\n");
425
438
  }
@@ -453,10 +466,10 @@ function closeFd(fd: number | undefined): void {
453
466
  * Spawn the async runner process
454
467
  */
455
468
  const RUNNER_STARTUP_TIMEOUT_MS = 10_000;
456
- type RunnerStartupState = "ready" | "acknowledged" | "confirmed";
469
+ type RunnerStartupState = "ready" | "acknowledged" | "confirmed" | "identified";
457
470
 
458
471
  type RunnerStartupWaitResult =
459
- | { ok: true; token: string }
472
+ | { ok: true; token: string; pid?: unknown; pidNamespaceScope?: unknown }
460
473
  | { ok: false; error: string; startupDidNotProceed?: boolean };
461
474
 
462
475
  function waitForStartupInterval(delayMs = 20): Promise<void> {
@@ -466,13 +479,13 @@ function waitForStartupInterval(delayMs = 20): Promise<void> {
466
479
  function readRunnerStartup(startupPath: string, expectedState: RunnerStartupState, expectedToken?: string): RunnerStartupWaitResult | undefined {
467
480
  if (!fs.existsSync(startupPath)) return undefined;
468
481
  try {
469
- const payload = JSON.parse(fs.readFileSync(startupPath, "utf-8")) as { state?: unknown; token?: unknown; error?: unknown };
482
+ const payload = JSON.parse(fs.readFileSync(startupPath, "utf-8")) as { state?: unknown; token?: unknown; error?: unknown; pid?: unknown; pidNamespaceScope?: unknown };
470
483
  if (payload.state === "error" && typeof payload.error === "string") return { ok: false, error: payload.error, startupDidNotProceed: true };
471
484
  if (payload.state !== expectedState) return undefined;
472
485
  if (typeof payload.token !== "string" || (expectedToken !== undefined && payload.token !== expectedToken)) {
473
486
  return { ok: false, error: `Async runner wrote an invalid ${expectedState} startup handshake: ${startupPath}`, startupDidNotProceed: true };
474
487
  }
475
- return { ok: true, token: payload.token };
488
+ return { ok: true, token: payload.token, pid: payload.pid, pidNamespaceScope: payload.pidNamespaceScope };
476
489
  } catch (error) {
477
490
  return { ok: false, error: `Failed to read async runner startup handshake '${startupPath}': ${error instanceof Error ? error.message : String(error)}`, startupDidNotProceed: true };
478
491
  }
@@ -551,7 +564,7 @@ function terminateRunnerBeforeProceed(pid: number): boolean {
551
564
  return !runnerIsAlive(pid);
552
565
  }
553
566
 
554
- async function terminateRunnerBeforeProceedAsync(proc: ChildProcess, processClosed: Promise<{ exitCode: number | null; signal: NodeJS.Signals | null }>): Promise<boolean> {
567
+ async function terminateRunnerBeforeProceedAsyncDefault(proc: ChildProcess, processClosed: Promise<{ exitCode: number | null; signal: NodeJS.Signals | null }>): Promise<boolean> {
555
568
  for (const signal of ["SIGTERM", "SIGKILL"] as const) {
556
569
  if (proc.pid === undefined || !runnerIsAlive(proc.pid)) return true;
557
570
  try { process.kill(proc.pid, signal); } catch {
@@ -573,9 +586,17 @@ async function completeRunnerStartupHandshake(
573
586
  getObservedProcessExit: () => { exitCode: number | null; signal: NodeJS.Signals | null } | undefined,
574
587
  runnerProcessInstanceId: string,
575
588
  persistStartupFailure: (message: string) => void,
589
+ // Behind a launcher the spawned pid is only the wrapper's: adopt the runner-reported pid and never signal the wrapper.
590
+ launcherIdentity?: { adopt: (pid: unknown, pidNamespaceScope: unknown) => string | undefined; terminate: () => boolean },
576
591
  ): Promise<SpawnRunnerResult> {
592
+ const terminateRunnerBeforeProceedAsync = async (proc: ChildProcess, processClosed: Promise<{ exitCode: number | null; signal: NodeJS.Signals | null }>) => launcherIdentity ? launcherIdentity.terminate() : terminateRunnerBeforeProceedAsyncDefault(proc, processClosed);
577
593
  try {
578
594
  const ready = await waitForRunnerStartup(startupPath, "ready", RUNNER_STARTUP_TIMEOUT_MS, undefined, processClosed);
595
+ const identityError = ready.ok && launcherIdentity ? launcherIdentity.adopt(ready.pid, ready.pidNamespaceScope) : undefined;
596
+ if (identityError) {
597
+ persistStartupFailure(identityError);
598
+ return { runnerProcessInstanceId, error: identityError, terminationObserved: await terminateRunnerBeforeProceedAsync(proc, processClosed), startupDidNotProceed: true };
599
+ }
579
600
  if (ready.ok === false) {
580
601
  persistStartupFailure(ready.error);
581
602
  const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
@@ -675,12 +696,12 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
675
696
  const binaryHost = resolveBunPiExecutable();
676
697
  const nodeExecutable = resolveNodeExecutable();
677
698
  const nativeRunnerSupported = supportsNativeRunner(nodeExecutable);
678
- const runner = asyncRunnerSourcePath;
699
+ const runner = asyncRunnerSourcePath();
679
700
  const runnerIsJavaScript = path.extname(runner) === ".js";
680
- const bootstrap = path.join(path.dirname(runner), `binary-bootstrap${path.extname(fileURLToPath(import.meta.url))}`);
701
+ const bootstrap = resolveRuntimeModulePath(path.dirname(runner), "binary-bootstrap");
681
702
  if (binaryHost && !fs.existsSync(bootstrap)) return { error: `Background runner bootstrap not found: ${bootstrap}` };
682
703
  if (!binaryHost && !runnerIsJavaScript && !nativeRunnerSupported && !jitiCliPath) {
683
- return { error: sourceUnderNodeModules
704
+ return { error: sourceUnderNodeModules()
684
705
  ? "Background runner source is installed under node_modules, so upstream jiti is required for TypeScript execution."
685
706
  : "Background runner requires enabled native TypeScript with synchronous module hooks, or installed upstream jiti for TypeScript execution." };
686
707
  }
@@ -717,6 +738,27 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
717
738
  if (startupAckPath) fs.rmSync(startupAckPath, { force: true });
718
739
  if (startupConfirmPath) fs.rmSync(startupConfirmPath, { force: true });
719
740
  if (startupProceedPath) fs.rmSync(startupProceedPath, { force: true });
741
+ // A broker launcher may start the runner outside its own process, so the spawned pid is only the
742
+ // wrapper's. The runner reports its own identity before it is allowed to proceed.
743
+ const launcher = (launchConfig as { launcher?: RunnerLauncher }).launcher;
744
+ const identityPath = launcher && launchBarrierToken && launchAsyncDir ? path.join(launchAsyncDir, "runner-startup.json") : undefined;
745
+ if (identityPath) fs.rmSync(identityPath, { force: true });
746
+ let runnerIdentity: { pid: number; pidNamespaceScope?: string } | undefined;
747
+ // Wrapper exit is not runner exit, so only a reported runner in this namespace may be signalled.
748
+ const terminateBeforeProceed = (pid: number): boolean => !launcher
749
+ ? terminateRunnerBeforeProceed(pid)
750
+ : runnerIdentity !== undefined && runnerIdentity.pidNamespaceScope === currentPidNamespaceScope() && terminateRunnerBeforeProceed(runnerIdentity.pid);
751
+ const adoptRunnerIdentity = (pid: unknown, pidNamespaceScope: unknown): string | undefined => {
752
+ if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid < 1) return `Async runner reported an invalid process identity in '${launchAsyncDir}'.`;
753
+ runnerIdentity = { pid, ...(typeof pidNamespaceScope === "string" ? { pidNamespaceScope } : {}) };
754
+ try {
755
+ const status = JSON.parse(fs.readFileSync(initialStatusPath, "utf-8")) as AsyncStatus;
756
+ writePrivateAtomicJson(initialStatusPath, { ...status, pid, ...(runnerIdentity.pidNamespaceScope !== undefined ? { pidNamespaceScope: runnerIdentity.pidNamespaceScope } : {}) });
757
+ return undefined;
758
+ } catch (error) {
759
+ return `Failed to record async runner identity: ${error instanceof Error ? error.message : String(error)}`;
760
+ }
761
+ };
720
762
 
721
763
  const logPaths = resolveAsyncRunnerLogPaths(launchConfig);
722
764
  let stdoutFd: number | undefined;
@@ -751,7 +793,8 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
751
793
  };
752
794
  if (launchParentSessionId === undefined) delete runnerEnv[SUBAGENT_PARENT_SESSION_ENV];
753
795
  else runnerEnv[SUBAGENT_PARENT_SESSION_ENV] = launchParentSessionId;
754
- const proc = spawn(command, args, {
796
+ const [spawnCommand, ...spawnArgs] = launcher ? [...launcher.argv, command, ...args] : [command, ...args];
797
+ const proc = spawn(spawnCommand!, spawnArgs, {
755
798
  cwd,
756
799
  ...backgroundProcessOptions(),
757
800
  stdio: ["ignore", stdoutFd ?? "ignore", stderrFd ?? "ignore"],
@@ -776,6 +819,16 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
776
819
  const asyncDir = launch.asyncDir;
777
820
  const runId = launch.id;
778
821
  if (typeof asyncDir !== "string" || typeof runId !== "string") return;
822
+ if (launcher) {
823
+ try {
824
+ writePrivateAtomicJson(path.join(asyncDir, "launcher-close.json"), { version: 1, runId, runnerProcessInstanceId, closeObservedAt: Date.now(), exitCode, signal, ...(runnerIdentity ? { runnerPid: runnerIdentity.pid } : {}) });
825
+ } catch {
826
+ // Diagnostic only; process-terminal proof stays authoritative.
827
+ }
828
+ // The runner may outlive its wrapper; only a confirmed-dead runner in this pid namespace finalizes here,
829
+ // otherwise status-pid reconciliation does it later.
830
+ if (!runnerIdentity || runnerIdentity.pidNamespaceScope !== currentPidNamespaceScope() || checkPidLiveness(runnerIdentity.pid, process.kill, runnerIdentity.pidNamespaceScope !== undefined) !== "dead") return;
831
+ }
779
832
  finalizeProcessTerminal(asyncDir, runId, {
780
833
  processInstanceId: runnerProcessInstanceId,
781
834
  closeObservedAt: Date.now(),
@@ -830,8 +883,7 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
830
883
  try {
831
884
  writePrivateAtomicJson(initialStatusPath, {
832
885
  ...initialStatus,
833
- pid: proc.pid,
834
- pidNamespaceScope: currentPidNamespaceScope(),
886
+ ...(launcher ? {} : { pid: proc.pid, pidNamespaceScope: currentPidNamespaceScope() }),
835
887
  processTerminal: { version: 1, state: "pending", runId: initialStatus.runId, runnerProcessInstanceId },
836
888
  });
837
889
  // Aggregate waits must see the launch before the runner's first status update.
@@ -839,7 +891,7 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
839
891
  } catch (error) {
840
892
  const message = `Failed to persist initial async status: ${error instanceof Error ? error.message : String(error)}`;
841
893
  if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
842
- const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
894
+ const terminationObserved = terminateBeforeProceed(proc.pid);
843
895
  return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
844
896
  }
845
897
  try {
@@ -848,7 +900,7 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
848
900
  } catch (error) {
849
901
  const message = `Failed to establish async runner lifecycle sidecar: ${error instanceof Error ? error.message : String(error)}`;
850
902
  if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
851
- const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
903
+ const terminationObserved = terminateBeforeProceed(proc.pid);
852
904
  return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
853
905
  }
854
906
  try {
@@ -856,16 +908,34 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
856
908
  } catch (error) {
857
909
  const message = `Failed to establish async runner capacity ownership: ${error instanceof Error ? error.message : String(error)}`;
858
910
  if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
859
- const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
911
+ const terminationObserved = terminateBeforeProceed(proc.pid);
860
912
  return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
861
913
  }
914
+ if (identityPath && launchBarrierToken && startupProceedPath) {
915
+ proc.unref();
916
+ const fail = (message: string): SpawnRunnerResult => {
917
+ if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
918
+ return { ...(runnerIdentity ? { pid: runnerIdentity.pid } : {}), runnerProcessInstanceId, error: message, terminationObserved: terminateBeforeProceed(proc.pid!), startupDidNotProceed: true };
919
+ };
920
+ return waitForRunnerStartup(identityPath, "identified", RUNNER_STARTUP_TIMEOUT_MS, launchBarrierToken, processClosed).then((identified) => {
921
+ if (identified.ok === false) return fail(identified.error);
922
+ const identityError = adoptRunnerIdentity(identified.pid, identified.pidNamespaceScope);
923
+ if (identityError) return fail(identityError);
924
+ try {
925
+ writeRunnerStartupControl(startupProceedPath, { action: "proceed", token: launchBarrierToken });
926
+ } catch (error) {
927
+ return fail(`Failed to authorize async runner startup: ${error instanceof Error ? error.message : String(error)}`);
928
+ }
929
+ return { pid: identified.pid as number, runnerProcessInstanceId };
930
+ });
931
+ }
862
932
  if (launchBarrierToken && startupProceedPath) {
863
933
  try {
864
934
  writeRunnerStartupControl(startupProceedPath, { action: "proceed", token: launchBarrierToken });
865
935
  } catch (error) {
866
936
  const message = `Failed to authorize async runner startup: ${error instanceof Error ? error.message : String(error)}`;
867
937
  if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
868
- const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
938
+ const terminationObserved = terminateBeforeProceed(proc.pid);
869
939
  return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
870
940
  }
871
941
  }
@@ -874,7 +944,9 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
874
944
  const persistStartupFailure = (message: string) => {
875
945
  if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
876
946
  };
877
- return completeRunnerStartupHandshake(startupPath, startupAckPath, startupConfirmPath, startupProceedPath, proc, processClosed, () => observedProcessExit ?? (proc.exitCode !== null || proc.signalCode !== null ? { exitCode: proc.exitCode, signal: proc.signalCode } : undefined), runnerProcessInstanceId, persistStartupFailure);
947
+ const handshake = completeRunnerStartupHandshake(startupPath, startupAckPath, startupConfirmPath, startupProceedPath, proc, processClosed, () => observedProcessExit ?? (proc.exitCode !== null || proc.signalCode !== null ? { exitCode: proc.exitCode, signal: proc.signalCode } : undefined), runnerProcessInstanceId, persistStartupFailure, launcher ? { adopt: adoptRunnerIdentity, terminate: () => terminateBeforeProceed(proc.pid!) } : undefined);
948
+ if (!launcher) return handshake;
949
+ return handshake.then(({ pid: _wrapperPid, ...result }) => ({ ...result, ...(runnerIdentity ? { pid: runnerIdentity.pid } : {}) }));
878
950
  }
879
951
  return { pid: proc.pid, runnerProcessInstanceId };
880
952
  } catch (error) {
@@ -884,6 +956,23 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
884
956
  }
885
957
  }
886
958
 
959
+ /**
960
+ * An explicit `thinking: false` clears the level, so only `undefined` falls
961
+ * through to the agent's own value. Treating `false` as absent would silently
962
+ * apply the agent default the caller just cleared.
963
+ */
964
+ export function resolveClaudeCodeThinking(source: string | false | undefined, fallback: string | false | undefined): string | undefined {
965
+ const value = source === undefined ? fallback : source;
966
+ return typeof value === "string" ? value : undefined;
967
+ }
968
+
969
+ /** A pinned Claude Code model cannot survive pane-native saved-machine placement, which
970
+ * owns the remote model registry, so the combination fails instead of losing both flags. */
971
+ export function assertClaudeCodeOverrideIsLocal(agent: string, machine: string | undefined, override: ClaudeCodeOverride | undefined): void {
972
+ if (!machine || !override) return;
973
+ throw new Error(`Agent '${agent}' requested machine '${machine}', but a Claude Code model or thinking level cannot be honored on a saved machine. Remove the model or thinking request, or run the agent locally.`);
974
+ }
975
+
887
976
  function formatAsyncStartError(mode: SubagentRunMode, message: string): AsyncExecutionResult {
888
977
  return {
889
978
  content: [{ type: "text", text: message }],
@@ -923,6 +1012,14 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
923
1012
  worktreeProvider,
924
1013
  asyncDir,
925
1014
  } = params;
1015
+ // One runner hosts every new step, so they share one launcher or none. Covers initial chains and
1016
+ // appends to a running runner; the attached root runs in its own runner.
1017
+ const stepLaunchers = [...new Set(chain.flatMap(getStepAgents))].map((name) => ({ name, launcher: agents.find((agent) => agent.name === name)?.launcher }));
1018
+ const launcherNames = new Set(stepLaunchers.map(({ launcher }) => launcher));
1019
+ if (launcherNames.size > 1) {
1020
+ return { error: `Every agent in one background runner must use the same launcher or none: ${stepLaunchers.map(({ name, launcher }) => `${name} (${launcher ?? "none"})`).join(", ")}.` };
1021
+ }
1022
+ const launcher = [...launcherNames][0];
926
1023
  const launchParentSessionId = ctx.parentSessionId ?? ctx.currentSessionId;
927
1024
  const outputBaseDir = params.outputBaseDir;
928
1025
  const resultMode = params.resultMode ?? "chain";
@@ -1001,6 +1098,14 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1001
1098
  const externalRunnerType = a.runner?.type;
1002
1099
  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 });
1003
1100
  if (machineUnsupported) throw new AsyncStartValidationError(machineUnsupported);
1101
+ const launcherError = runnerLauncherPlacementError(a, requestedMachine);
1102
+ if (launcherError) throw new AsyncStartValidationError(launcherError);
1103
+ const registeredExtensions = resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1104
+ try {
1105
+ assertRequiredChildExtensionsAdmitted([params.requiredExtensions, ctx.childRuntime?.requiredExtensions, registeredExtensions], { agent: a.name, runnerType: a.runner?.type, machine: requestedMachine });
1106
+ } catch (error) {
1107
+ throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
1108
+ }
1004
1109
  let machine: HerdrMachineReference | undefined;
1005
1110
  let machineEnv: Record<string, string> | undefined;
1006
1111
  if (requestedMachine) {
@@ -1012,9 +1117,12 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1012
1117
  throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
1013
1118
  }
1014
1119
  }
1120
+ // A code-owned Claude Code adapter owns its argv, but it does accept an explicit
1121
+ // model/thinking request; those become --model/--effort on the launch below.
1122
+ const claudeCodeAdapter = a.runner?.type === "external-cli" && isClaudeCodeAdapterId(a.runner.adapter);
1015
1123
  if (externalRunner) {
1016
1124
  const unsupported: string[] = [];
1017
- if (s.model !== undefined) unsupported.push("model override");
1125
+ if (s.model !== undefined && !claudeCodeAdapter) unsupported.push("model override");
1018
1126
  if (effectiveBehavior.outputSchema !== undefined) unsupported.push("structured output");
1019
1127
  if (s.acceptance !== undefined || params.agentContract !== undefined || s.agentContract !== undefined) unsupported.push("acceptance/agent contract");
1020
1128
  if (s.toolBudget !== undefined || params.toolBudget !== undefined || a.toolBudget !== undefined || params.configToolBudget !== undefined) unsupported.push("tool budget");
@@ -1094,6 +1202,23 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1094
1202
  { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" },
1095
1203
  );
1096
1204
  const thinkingOverride = flatIndex === undefined ? undefined : thinkingOverridesByFlatIndex?.[flatIndex];
1205
+ let claudeCodeOverride: ClaudeCodeOverride | undefined;
1206
+ if (claudeCodeAdapter) {
1207
+ try {
1208
+ claudeCodeOverride = resolveClaudeCodeOverride({
1209
+ model: typeof s.model === "string" ? s.model : undefined,
1210
+ agent: a,
1211
+ thinking: resolveClaudeCodeThinking(thinkingOverride, a.thinking),
1212
+ thinkingCeiling: intersectThinkingCeilings(params.thinkingCeiling, a.maxThinking, ctx.childRuntime?.thinkingCeiling),
1213
+ agentName: a.name,
1214
+ runId: id,
1215
+ });
1216
+ assertClaudeCodeModelScope({ scopes: modelScopes, model: claudeCodeOverride?.model, agent: a.name, runId: id });
1217
+ assertClaudeCodeOverrideIsLocal(a.name, machine ? requestedMachine : undefined, claudeCodeOverride);
1218
+ } catch (error) {
1219
+ throw new AsyncStartValidationError(error instanceof Error ? error.message : String(error));
1220
+ }
1221
+ }
1097
1222
  const effectiveThinking = externalRunner ? undefined : thinkingOverride ?? a.thinking;
1098
1223
  const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinking, thinkingOverride !== undefined);
1099
1224
  const contextLimit = model ? findModelInfo(model, availableModels, a.modelProvider ?? ctx.currentModelProvider)?.contextWindow : undefined;
@@ -1130,7 +1255,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1130
1255
  const launchRuleError = applyWatchdogLaunchRules({ cwd: machine ? runnerCwd : stepCwd, agent: a.name, model: selectedModel, warn: (violation) => sendRuleViolationWarning(ctx.pi, violation) });
1131
1256
  if (launchRuleError) throw new AsyncStartValidationError(launchRuleError);
1132
1257
  const fast = s.fast ?? params.fast ?? a.fast;
1133
- const requiredExtensions = externalRunner ? [] : ctx.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1258
+ const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
1134
1259
  const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
1135
1260
  const toolPlan = resolvePiLaunchToolPlan({
1136
1261
  tools: a.tools,
@@ -1151,6 +1276,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1151
1276
  permissionRules,
1152
1277
  runtimeSnapshotHost: ctx.pi,
1153
1278
  sandbox: a.sandbox,
1279
+ permissionProfile: a.permissionProfile,
1154
1280
  hostAvailableBuiltins,
1155
1281
  });
1156
1282
  const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
@@ -1159,6 +1285,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1159
1285
  }
1160
1286
  return {
1161
1287
  parentSessionId: launchParentSessionId,
1288
+ ...(ctx.parentSessionFile ? { parentSessionFile: ctx.parentSessionFile } : {}),
1162
1289
  permissionRules,
1163
1290
  ...(ctx.projectTrusted !== undefined ? { projectTrusted: ctx.projectTrusted } : {}),
1164
1291
  ...(ctx.trustedProjectCwd ? { trustedProjectCwd: ctx.trustedProjectCwd } : {}),
@@ -1167,6 +1294,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1167
1294
  agent: s.agent,
1168
1295
  task,
1169
1296
  ...(a.runner ? { runner: a.runner } : {}),
1297
+ ...(claudeCodeOverride ? { claudeCodeOverrideArgs: claudeCodeOverride.args } : {}),
1170
1298
  ...(machine ? { machine } : {}),
1171
1299
  ...(machineEnv ? { machineEnv } : {}),
1172
1300
  ...(params.contextForAgent ? { context: params.contextForAgent(s.agent) } : {}),
@@ -1198,6 +1326,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1198
1326
  ...(toolPlan.builtinMcpTools ? { builtinMcpTools: toolPlan.builtinMcpTools } : {}),
1199
1327
  mutationTools: a.mutationTools,
1200
1328
  ...(a.sandbox ? { sandbox: a.sandbox } : {}),
1329
+ ...(a.permissionProfile ? { permissionProfile: a.permissionProfile } : {}),
1201
1330
  systemPrompt,
1202
1331
  systemPromptMode: a.systemPromptMode,
1203
1332
  inheritProjectContext: a.inheritProjectContext,
@@ -1333,6 +1462,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1333
1462
  const steps = params.attachRoot
1334
1463
  ? [{
1335
1464
  parentSessionId: launchParentSessionId,
1465
+ ...(ctx.parentSessionFile ? { parentSessionFile: ctx.parentSessionFile } : {}),
1336
1466
  agent: params.attachRoot.agent,
1337
1467
  task: "",
1338
1468
  label: params.attachRoot.label ?? `Attached root ${params.attachRoot.runId}`,
@@ -1361,7 +1491,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1361
1491
  seen.set(task.outputPath, { index, agent: task.agent });
1362
1492
  }
1363
1493
  }
1364
- return { steps: steps as RunnerStep[], runnerCwd, workflowGraph, eventChain: graphChain, ...(originalTask !== undefined ? { originalTask } : {}) };
1494
+ return { steps: steps as RunnerStep[], runnerCwd, workflowGraph, eventChain: graphChain, ...(originalTask !== undefined ? { originalTask } : {}), ...(launcher !== undefined ? { launcher } : {}) };
1365
1495
  } catch (error) {
1366
1496
  if (error instanceof UnavailableSubagentSkillError || error instanceof AsyncStartValidationError) return { error: error.message };
1367
1497
  throw error;
@@ -1374,7 +1504,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1374
1504
  export function executeAsyncChain(
1375
1505
  id: string,
1376
1506
  params: AsyncChainParams,
1377
- ): AsyncExecutionResult {
1507
+ ): AsyncExecutionResult | Promise<AsyncExecutionResult> {
1378
1508
  const {
1379
1509
  chain,
1380
1510
  agents,
@@ -1406,6 +1536,10 @@ export function executeAsyncChain(
1406
1536
  (step, parallel) => Array.isArray(step.parallel) ? { parallel } : { acceptance: "acceptance" in step ? step.acceptance : undefined, parallel }),
1407
1537
  });
1408
1538
  if (acceptanceErrors.length > 0) return formatAsyncStartError(resultMode, acceptanceErrors.join(" "));
1539
+ // Refuse an undefined launcher before the run directory exists and before step building can write progress files.
1540
+ const undefinedLauncher = chain.flatMap(getStepAgents).map((name) => agents.find((agent) => agent.name === name)?.launcher)
1541
+ .find((name) => name !== undefined && !lookupRunnerLauncher(ctx.runnerLaunchers, name));
1542
+ if (undefinedLauncher !== undefined) return formatAsyncStartError(resultMode, `Launcher '${undefinedLauncher}' used by this ${resultMode} is not defined in runnerLaunchers in the user subagent config.`);
1409
1543
  const capabilityCeiling = params.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(ctx.currentSessionId);
1410
1544
  const inheritedNestedRoute = inheritedNestedRouteOf(ctx.childRuntime);
1411
1545
  const nestedAddress = inheritedNestedRoute ? inheritedNestedParentAddressOf(ctx.childRuntime) : undefined;
@@ -1461,6 +1595,7 @@ export function executeAsyncChain(
1461
1595
  toolTimeoutMsEnv: params.toolTimeoutMsEnv ?? toolTimeoutFromEnv(),
1462
1596
  capabilityCeiling,
1463
1597
  thinkingCeiling: params.thinkingCeiling,
1598
+ requiredExtensions: params.requiredExtensions,
1464
1599
  });
1465
1600
  if ("error" in built) {
1466
1601
  try {
@@ -1471,6 +1606,7 @@ export function executeAsyncChain(
1471
1606
  return formatAsyncStartError(resultMode, built.error);
1472
1607
  }
1473
1608
  const { steps, runnerCwd, workflowGraph, eventChain } = built;
1609
+ const launcher = built.launcher === undefined ? undefined : lookupRunnerLauncher(ctx.runnerLaunchers, built.launcher);
1474
1610
  const deadlineAt = params.timeoutMs !== undefined ? Date.now() + params.timeoutMs : undefined;
1475
1611
  const initialUsageBudget = usageBudgetState(params.usageBudget, undefined);
1476
1612
  let childTargetIndex = 0;
@@ -1504,10 +1640,16 @@ export function executeAsyncChain(
1504
1640
  const initialStatusAt = Date.now();
1505
1641
  const initialCompletionOwnerId = ctx.completionOwnerId ?? currentCompletionOwnerId();
1506
1642
  const launchParentSessionId = ctx.parentSessionId ?? ctx.currentSessionId;
1643
+ try {
1644
+ writeRetainedRequiredChildExtensions(asyncDir, params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(launchParentSessionId ?? undefined));
1645
+ } catch (error) {
1646
+ fs.rmSync(asyncDir, { recursive: true, force: true });
1647
+ return formatAsyncStartError(resultMode, `Failed to record required child extensions: ${error instanceof Error ? error.message : String(error)}`);
1648
+ }
1507
1649
 
1508
- let spawnResult: SpawnRunnerResult = {};
1650
+ let spawnResultOrPromise: SpawnRunnerResult | Promise<SpawnRunnerResult> = {};
1509
1651
  try {
1510
- spawnResult = spawnRunner(
1652
+ spawnResultOrPromise = spawnRunner(
1511
1653
  {
1512
1654
  id,
1513
1655
  steps,
@@ -1554,6 +1696,7 @@ export function executeAsyncChain(
1554
1696
  depth: nestedAddress.depth,
1555
1697
  path: nestedAddress.path,
1556
1698
  } : undefined,
1699
+ ...(launcher ? { launcher } : {}),
1557
1700
  },
1558
1701
  id,
1559
1702
  runnerCwd,
@@ -1569,19 +1712,22 @@ export function executeAsyncChain(
1569
1712
  currentStep: 0,
1570
1713
  chainStepCount: eventChain.length,
1571
1714
  ...(initialParallelGroups.length ? { parallelGroups: initialParallelGroups } : {}),
1715
+ ...(launcher ? { launcher } : {}),
1572
1716
  steps: initialStatusSteps,
1573
1717
  },
1574
1718
  path.join(asyncDir, "status.json"),
1575
1719
  launchParentSessionId,
1576
1720
  (proof) => emitProcessTerminalEvent(ctx, proof),
1577
1721
  (runnerProcessInstanceId) => params.activeAsyncCapacity?.markStarted(runnerProcessInstanceId),
1578
- ) as SpawnRunnerResult;
1722
+ );
1579
1723
  } catch (error) {
1580
1724
  params.activeAsyncCapacity?.rollback();
1581
1725
  const message = error instanceof Error ? error.message : String(error);
1582
1726
  return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': ${message}`);
1583
1727
  }
1584
1728
 
1729
+ // A launcher run's spawn resolves once the runner reports its identity.
1730
+ const finishSpawnResult = (spawnResult: SpawnRunnerResult): AsyncExecutionResult => {
1585
1731
  if (spawnResult.error) {
1586
1732
  if (spawnResult.startupDidNotProceed) {
1587
1733
  if (!spawnResult.runnerProcessInstanceId || params.activeAsyncCapacity?.rollbackBeforeRunnerProceed(spawnResult.runnerProcessInstanceId) !== true) params.activeAsyncCapacity?.rollback();
@@ -1703,6 +1849,8 @@ export function executeAsyncChain(
1703
1849
  content: [{ type: "text", text: formatAsyncStartedMessage(`Async ${resultMode}: ${chainDesc} [${id}]`, ctx.interactive === true) }],
1704
1850
  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 } : {}) },
1705
1851
  };
1852
+ };
1853
+ return spawnResultOrPromise instanceof Promise ? spawnResultOrPromise.then(finishSpawnResult) : finishSpawnResult(spawnResultOrPromise);
1706
1854
  }
1707
1855
 
1708
1856
  /**
@@ -1759,11 +1907,14 @@ export function executeAsyncSingle(
1759
1907
  const externalRunnerType = agentConfig.runner?.type;
1760
1908
  const permissionRules = resolvePermissionRules(ctx.permissions, agentConfig.permissions);
1761
1909
  const sandbox = params.sandbox ?? agentConfig.sandbox;
1910
+ // See the chain path: the Claude Code adapter accepts an explicit model/thinking
1911
+ // request even though no other external runner does.
1912
+ const claudeCodeAdapter = agentConfig.runner?.type === "external-cli" && isClaudeCodeAdapterId(agentConfig.runner.adapter);
1762
1913
  if (externalRunner) {
1763
1914
  const unsupported: string[] = [];
1764
- if (params.modelOverride !== undefined) unsupported.push("model override");
1915
+ if (params.modelOverride !== undefined && !claudeCodeAdapter) unsupported.push("model override");
1765
1916
  if ((params.fast ?? agentConfig.fast) === true) unsupported.push("fast mode");
1766
- if (params.thinkingOverride !== undefined) unsupported.push("thinking override");
1917
+ if (params.thinkingOverride !== undefined && !claudeCodeAdapter) unsupported.push("thinking override");
1767
1918
  if (params.structuredOutputSchema !== undefined) unsupported.push("structured output");
1768
1919
  if (params.acceptance !== undefined || params.agentContract !== undefined) unsupported.push("acceptance/agent contract");
1769
1920
  if (params.toolBudget !== undefined || agentConfig.toolBudget !== undefined || params.configToolBudget !== undefined) unsupported.push("tool budget");
@@ -1784,6 +1935,15 @@ export function executeAsyncSingle(
1784
1935
  const requestedMachine = params.machine ?? agentConfig.machine;
1785
1936
  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 });
1786
1937
  if (machineUnsupported) return formatAsyncStartError("single", machineUnsupported);
1938
+ const resolvedLauncher = resolveAgentRunnerLauncher(agentConfig, ctx.runnerLaunchers, requestedMachine);
1939
+ if (resolvedLauncher.error) return formatAsyncStartError("single", resolvedLauncher.error);
1940
+ const launcher = resolvedLauncher.launcher;
1941
+ const registeredExtensions = resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1942
+ try {
1943
+ assertRequiredChildExtensionsAdmitted([params.requiredExtensions, ctx.childRuntime?.requiredExtensions, registeredExtensions], { agent: agentConfig.name, runnerType: agentConfig.runner?.type, machine: requestedMachine });
1944
+ } catch (error) {
1945
+ return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1946
+ }
1787
1947
  let machine: HerdrMachineReference | undefined;
1788
1948
  let machineEnv: Record<string, string> | undefined;
1789
1949
  if (requestedMachine) {
@@ -1888,6 +2048,23 @@ export function executeAsyncSingle(
1888
2048
  } catch (error) {
1889
2049
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1890
2050
  }
2051
+ let singleClaudeCodeOverride: ClaudeCodeOverride | undefined;
2052
+ if (claudeCodeAdapter) {
2053
+ try {
2054
+ singleClaudeCodeOverride = resolveClaudeCodeOverride({
2055
+ model: typeof params.modelOverride === "string" ? params.modelOverride : undefined,
2056
+ agent: agentConfig,
2057
+ thinking: resolveClaudeCodeThinking(params.thinkingOverride, agentConfig.thinking),
2058
+ thinkingCeiling: intersectThinkingCeilings(params.thinkingCeiling, agentConfig.maxThinking, ctx.childRuntime?.thinkingCeiling),
2059
+ agentName: agentConfig.name,
2060
+ runId: id,
2061
+ });
2062
+ assertClaudeCodeModelScope({ scopes: modelScopes, model: singleClaudeCodeOverride?.model, agent: agentConfig.name, runId: id });
2063
+ assertClaudeCodeOverrideIsLocal(agentConfig.name, machine ? requestedMachine : undefined, singleClaudeCodeOverride);
2064
+ } catch (error) {
2065
+ return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
2066
+ }
2067
+ }
1891
2068
  const effectiveThinking = externalRunner ? undefined : params.thinkingOverride ?? agentConfig.thinking;
1892
2069
  const model = externalRunner ? undefined : applyThinkingSuffix(primaryModel, effectiveThinking, params.thinkingOverride !== undefined);
1893
2070
  const contextLimit = model ? findModelInfo(model, availableModels, agentConfig.modelProvider ?? ctx.currentModelProvider)?.contextWindow : undefined;
@@ -1940,7 +2117,7 @@ export function executeAsyncSingle(
1940
2117
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1941
2118
  }
1942
2119
  }
1943
- const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
2120
+ const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
1944
2121
  const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
1945
2122
  const toolPlan = resolvePiLaunchToolPlan({
1946
2123
  tools: agentConfig.tools,
@@ -1961,6 +2138,7 @@ export function executeAsyncSingle(
1961
2138
  permissionRules: resolvePermissionRules(ctx.permissions, agentConfig.permissions),
1962
2139
  runtimeSnapshotHost: ctx.pi,
1963
2140
  sandbox,
2141
+ permissionProfile: agentConfig.permissionProfile,
1964
2142
  hostAvailableBuiltins,
1965
2143
  });
1966
2144
  const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
@@ -2042,6 +2220,7 @@ export function executeAsyncSingle(
2042
2220
  ...(params.context ? { context: params.context } : {}),
2043
2221
  ...(params.intercomBridge !== undefined ? { intercomBridge: params.intercomBridge } : {}),
2044
2222
  ...(params.baseRef !== undefined ? { baseRef: params.baseRef } : {}),
2223
+ ...(launcher ? { launcher: launcher.name } : {}),
2045
2224
  ...(deadlineAt !== undefined ? { absoluteDeadlineAt: deadlineAt } : {}),
2046
2225
  ...(resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {}),
2047
2226
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, recoveryAgentConfig.maxSubagentDepth),
@@ -2067,9 +2246,11 @@ export function executeAsyncSingle(
2067
2246
  spawnResultOrPromise = spawnRunner(
2068
2247
  {
2069
2248
  id,
2249
+ ...(params.toolCallId ? { toolCallId: params.toolCallId } : {}),
2070
2250
  steps: [
2071
2251
  {
2072
2252
  parentSessionId: launchParentSessionId,
2253
+ ...(ctx.parentSessionFile ? { parentSessionFile: ctx.parentSessionFile } : {}),
2073
2254
  permissionRules,
2074
2255
  ...(ctx.projectTrusted !== undefined ? { projectTrusted: ctx.projectTrusted } : {}),
2075
2256
  ...(ctx.trustedProjectCwd ? { trustedProjectCwd: ctx.trustedProjectCwd } : {}),
@@ -2077,6 +2258,7 @@ export function executeAsyncSingle(
2077
2258
  agent,
2078
2259
  task: taskText,
2079
2260
  ...(agentConfig.runner ? { runner: agentConfig.runner } : {}),
2261
+ ...(singleClaudeCodeOverride ? { claudeCodeOverrideArgs: singleClaudeCodeOverride.args } : {}),
2080
2262
  ...(machine ? { machine } : {}),
2081
2263
  ...(!externalRunner && machine && params.reads !== undefined ? { remoteReads: params.reads } : {}),
2082
2264
  ...(machineEnv ? { machineEnv } : {}),
@@ -2104,6 +2286,7 @@ export function executeAsyncSingle(
2104
2286
  ...(toolPlan.builtinMcpTools ? { builtinMcpTools: toolPlan.builtinMcpTools } : {}),
2105
2287
  mutationTools: agentConfig.mutationTools,
2106
2288
  ...(sandbox ? { sandbox } : {}),
2289
+ ...(agentConfig.permissionProfile ? { permissionProfile: agentConfig.permissionProfile } : {}),
2107
2290
  systemPrompt,
2108
2291
  systemPromptMode: agentConfig.systemPromptMode,
2109
2292
  inheritProjectContext: agentConfig.inheritProjectContext,
@@ -2174,6 +2357,7 @@ export function executeAsyncSingle(
2174
2357
  ...(lane ? { lane } : {}),
2175
2358
  ...(params.revivalLease ? { revivalLease: params.revivalLease } : {}),
2176
2359
  nestedRoute: nestedRoute ?? inheritedNestedRoute,
2360
+ ...(launcher ? { launcher } : {}),
2177
2361
  nestedSelf: inheritedNestedRoute && nestedAddress ? {
2178
2362
  parentRunId: nestedAddress.parentRunId,
2179
2363
  parentStepIndex: nestedAddress.parentStepIndex,
@@ -2189,12 +2373,14 @@ export function executeAsyncSingle(
2189
2373
  ...(ctx.currentSessionId ? { sessionId: ctx.currentSessionId } : {}),
2190
2374
  ...(initialCompletionOwnerId ? { completionOwnerId: initialCompletionOwnerId } : {}),
2191
2375
  mode: "single",
2376
+ ...(params.toolCallId ? { toolCallId: params.toolCallId } : {}),
2192
2377
  state: "running",
2193
2378
  startedAt: initialStatusAt,
2194
2379
  lastUpdate: initialStatusAt,
2195
2380
  currentStep: 0,
2196
2381
  chainStepCount: 1,
2197
2382
  ...(lane ? { lane } : {}),
2383
+ ...(launcher ? { launcher } : {}),
2198
2384
  steps: [{ agent, status: "pending", ...(lane ? { lane } : {}), ...(model ? { model } : {}), ...(contextLimit !== undefined ? { contextLimit } : {}) }],
2199
2385
  },
2200
2386
  path.join(asyncDir, "status.json"),
@@ -2265,6 +2451,7 @@ export function executeAsyncSingle(
2265
2451
  sessionId: ctx.currentSessionId,
2266
2452
  completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
2267
2453
  mode: "single",
2454
+ ...(params.toolCallId ? { toolCallId: params.toolCallId } : {}),
2268
2455
  agent,
2269
2456
  ...(sandbox ? { sandbox } : {}),
2270
2457
  task: task?.trim() ? PROMPT_REDACTED : undefined,
@@ -2285,7 +2472,7 @@ export function executeAsyncSingle(
2285
2472
 
2286
2473
  return {
2287
2474
  content: [{ type: "text", text: formatAsyncStartedMessage(`Async: ${agent} [${id}]`, ctx.interactive === true) }],
2288
- 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,
2475
+ details: { mode: "single", runId: id, ...(params.toolCallId ? { toolCallId: params.toolCallId } : {}), results: [], asyncId: id, asyncDir, launchContractDigest, launchResolvedExtensions, ...(capabilityCeiling ? { capabilityCeiling } : {}), ...(params.context ? { context: params.context } : {}), ...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}), ...(params.toolBudget ? { toolBudget: resolvedToolBudget.budget ?? params.toolBudget } : {}), ...(initialUsageBudget ? { usageBudget: initialUsageBudget } : {}) } as Details,
2289
2476
  };
2290
2477
  };
2291
2478
  return spawnResultOrPromise instanceof Promise ? spawnResultOrPromise.then(finishSpawnResult) : finishSpawnResult(spawnResultOrPromise);