@xzzpig/pi-subagents 0.20.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 (140) hide show
  1. package/CHANGELOG.md +154 -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 +72 -7
  9. package/docs/configuration.md +58 -7
  10. package/docs/extension-api.md +36 -11
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +34 -17
  13. package/docs/models.md +1 -1
  14. package/docs/observability.md +10 -5
  15. package/docs/tool-reference.md +117 -84
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +16 -7
  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 +191 -145
  32. package/src/api/preflight.ts +8 -4
  33. package/src/extension/config.ts +21 -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 +114 -132
  40. package/src/extension/reply-workflow-script.ts +20 -11
  41. package/src/extension/rpc.ts +11 -6
  42. package/src/extension/schemas.ts +34 -30
  43. package/src/extension/subagent-guide.ts +86 -6
  44. package/src/extension/subagent-options.ts +47 -0
  45. package/src/extension/tool-activation.ts +3 -2
  46. package/src/extension/tool-description.ts +51 -68
  47. package/src/inspectors/actions.ts +37 -11
  48. package/src/inspectors/plugins.ts +3 -2
  49. package/src/inspectors/tmux/actions.ts +204 -0
  50. package/src/inspectors/tmux/client.ts +85 -0
  51. package/src/inspectors/tmux/plugin.ts +21 -0
  52. package/src/integrations/herdr-status.ts +18 -49
  53. package/src/integrations/program-status.ts +215 -0
  54. package/src/intercom/native-supervisor-channel.ts +77 -4
  55. package/src/intercom/result-intercom.ts +3 -2
  56. package/src/intercom/supervisor-ui.ts +2 -174
  57. package/src/missions/store.ts +25 -5
  58. package/src/profiles/profiles.ts +24 -21
  59. package/src/runs/background/active-async-capacity.ts +58 -8
  60. package/src/runs/background/async-execution.ts +143 -38
  61. package/src/runs/background/async-job-tracker.ts +11 -4
  62. package/src/runs/background/async-resume.ts +5 -2
  63. package/src/runs/background/await-async-run.ts +14 -9
  64. package/src/runs/background/binary-bootstrap.ts +2 -1
  65. package/src/runs/background/calendar-schedule.ts +90 -0
  66. package/src/runs/background/chain-root-attachment.ts +9 -5
  67. package/src/runs/background/fleet-view.ts +5 -5
  68. package/src/runs/background/notify.ts +185 -12
  69. package/src/runs/background/result-files.ts +116 -5
  70. package/src/runs/background/result-watcher.ts +99 -66
  71. package/src/runs/background/resume-guidance.ts +2 -2
  72. package/src/runs/background/run-child-session.ts +16 -2
  73. package/src/runs/background/run-id-resolver.ts +8 -5
  74. package/src/runs/background/run-status.ts +21 -16
  75. package/src/runs/background/runner-child-launch.ts +1 -0
  76. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  77. package/src/runs/background/scheduled-runs.ts +256 -61
  78. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  79. package/src/runs/background/subagent-runner.ts +32 -12
  80. package/src/runs/background/subagent-wait.ts +38 -19
  81. package/src/runs/background/terminal-run-index.ts +46 -1
  82. package/src/runs/background/wait-completions.ts +1 -0
  83. package/src/runs/background/wait-tool.ts +33 -23
  84. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  85. package/src/runs/foreground/async-stop-action.ts +48 -22
  86. package/src/runs/foreground/execution.ts +94 -52
  87. package/src/runs/foreground/foreground-history.ts +1 -0
  88. package/src/runs/foreground/subagent-executor.ts +207 -77
  89. package/src/runs/shared/child-commands.ts +2 -1
  90. package/src/runs/shared/child-hooks.ts +4 -3
  91. package/src/runs/shared/child-launch.ts +3 -0
  92. package/src/runs/shared/child-session.ts +41 -24
  93. package/src/runs/shared/child-tool-plan.ts +13 -26
  94. package/src/runs/shared/dynamic-fanout.ts +1 -1
  95. package/src/runs/shared/fork-command-result.ts +10 -0
  96. package/src/runs/shared/herdr-placed-run.ts +5 -4
  97. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  98. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  99. package/src/runs/shared/model-resolution.ts +30 -1
  100. package/src/runs/shared/nested-events.ts +5 -0
  101. package/src/runs/shared/parallel-handoff.ts +56 -8
  102. package/src/runs/shared/parallel-utils.ts +2 -0
  103. package/src/runs/shared/partial-output.ts +48 -0
  104. package/src/runs/shared/runner-launcher.ts +25 -0
  105. package/src/runs/shared/single-output.ts +53 -0
  106. package/src/runs/shared/structured-output.ts +14 -7
  107. package/src/runs/shared/subagent-control.ts +3 -3
  108. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  109. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  110. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  111. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  112. package/src/runs/shared/worktree-lock.ts +29 -0
  113. package/src/runs/shared/worktree.ts +12 -1
  114. package/src/shared/atomic-json.ts +4 -2
  115. package/src/shared/edit-distance.ts +33 -0
  116. package/src/shared/file-lease.ts +74 -0
  117. package/src/shared/formatters.ts +1 -5
  118. package/src/shared/model-info.ts +22 -0
  119. package/src/shared/package-version.ts +17 -0
  120. package/src/shared/parent-wake.ts +79 -0
  121. package/src/shared/pruned-fork.ts +7 -1
  122. package/src/shared/runtime-module-path.ts +19 -0
  123. package/src/shared/settings-file-lease.ts +36 -0
  124. package/src/shared/types.ts +36 -2
  125. package/src/shared/utils.ts +8 -6
  126. package/src/slash/slash-commands.ts +3 -3
  127. package/src/slash/subagents-admin.ts +2 -1
  128. package/src/tui/fleet-native-transcript.ts +2 -0
  129. package/src/tui/fleet-transcript.ts +12 -3
  130. package/src/tui/fleet.ts +11 -8
  131. package/src/tui/render.ts +27 -19
  132. package/src/tui/subagent-messages.ts +305 -0
  133. package/src/watchdog/diff-tool.ts +2 -2
  134. package/src/watchdog/register-main.ts +2 -22
  135. package/src/watchdog/render.ts +2 -24
  136. package/src/watchdog/runtime.ts +6 -4
  137. package/src/watchdog/settings.ts +18 -13
  138. package/src/watchdog/tool-actions.ts +2 -2
  139. package/src/workflows/scripted-workflow.ts +20 -6
  140. package/src/workflows/workflow-resources.ts +11 -0
@@ -20,13 +20,14 @@ import { applyThinkingSuffix, getHostBuiltinToolNames, projectLaunchResolvedChil
20
20
  import { assertClaudeCodeModelScope, isClaudeCodeAdapterId, resolveClaudeCodeOverride, type ClaudeCodeOverride } from "../shared/claude-code-adapter.ts";
21
21
  import { injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
22
22
  import { applyWatchdogLaunchRules, sendRuleViolationWarning } from "../../watchdog/rules.ts";
23
- 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";
24
24
  import { isDynamicRunnerGroup, isParallelGroup, type RunnerStep } from "../shared/parallel-utils.ts";
25
25
  import type { ContextMode } from "../shared/context-mode.ts";
26
26
  import { PI_CODING_AGENT_PACKAGE, resolveBunPiExecutable, resolveInstalledPiPackageRoot, resolvePiPackageRoot } from "../shared/pi-spawn.ts";
27
27
  import { JITI_ALIAS_ENV, resolveHostPeerAliases } from "./runner-aliases.ts";
28
28
  import { preflightLaunchCwd } from "../shared/launch-cwd.ts";
29
29
  import { resolveNodeExecutable } from "../../shared/node-executable.ts";
30
+ import { resolveRuntimeModulePath } from "../../shared/runtime-module-path.ts";
30
31
  import { backgroundProcessOptions } from "../shared/background-process-options.ts";
31
32
  import { normalizeSkillInput, resolveSkillsWithFallback } from "../../agents/skills.ts";
32
33
  import { PI_CODING_AGENT_PACKAGE_ROOT_ENV, PROMPT_REDACTED, resolveChildCwd } from "../../shared/utils.ts";
@@ -83,7 +84,9 @@ import { persistRunnerStartupFailure } from "./runner-startup-failure.ts";
83
84
  import type { ActiveAsyncCapacityHandle } from "./active-async-capacity.ts";
84
85
  import { statusStepDescription } from "./chain-append.ts";
85
86
  import { currentPidNamespaceScope } from "./pid-namespace.ts";
86
- 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";
87
90
  import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
88
91
  import { resolveLaunchBinding } from "../../shared/launch-contract.ts";
89
92
  import { resolvePermissionRules, type PermissionConfig } from "../shared/permissions.ts";
@@ -160,16 +163,19 @@ function resolveJitiCliPath(): string | undefined {
160
163
  }
161
164
 
162
165
  const jitiCliPath = resolveJitiCliPath();
163
- const asyncRunnerSourcePath = path.join(
164
- path.dirname(fileURLToPath(import.meta.url)),
165
- `subagent-runner-bootstrap${path.extname(fileURLToPath(import.meta.url))}`,
166
- );
167
- 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
+ }
168
174
  function supportsNativeRunner(nodeExecutable: string): boolean {
169
175
  return Boolean(process.features.typescript)
170
176
  && typeof nodeModule.registerHooks === "function"
171
177
  && nodeExecutable === process.execPath
172
- && !sourceUnderNodeModules;
178
+ && !sourceUnderNodeModules();
173
179
  }
174
180
 
175
181
  interface AsyncExecutionContext {
@@ -179,6 +185,8 @@ interface AsyncExecutionContext {
179
185
  completionOwnerId?: string;
180
186
  /** Parent session id used by permission-system ask forwarding. */
181
187
  parentSessionId?: string;
188
+ /** Parent session file, recorded as each new child session's `parentSession` header. */
189
+ parentSessionFile?: string;
182
190
  permissions?: PermissionConfig;
183
191
  currentModelProvider?: string;
184
192
  currentModel?: ParentModel;
@@ -192,6 +200,8 @@ trustedProjectCwd?: string;
192
200
  modelResponseAliases?: Record<string, string[]>;
193
201
  /** Whether the parent session has an interactive UI. */
194
202
  interactive?: boolean;
203
+ /** User-configured runner launchers; an agent's `launcher` must name one of them. */
204
+ runnerLaunchers?: Record<string, string[]>;
195
205
  /** The executor's own child runtime when the launch comes from an in-process child. */
196
206
  childRuntime?: ChildRuntimeConfig;
197
207
  }
@@ -264,6 +274,8 @@ interface AsyncChainParams {
264
274
  }
265
275
 
266
276
  interface AsyncSingleParams {
277
+ /** Originating executor invocation, distinct from the async run id. */
278
+ toolCallId?: string;
267
279
  agent: string;
268
280
  task?: string;
269
281
  /** Raw caller-facing goal used only by the started event. */
@@ -408,22 +420,19 @@ export type AsyncRunnerStepBuildResult =
408
420
  workflowGraph: ReturnType<typeof buildWorkflowGraphSnapshot>;
409
421
  eventChain: ChainStep[];
410
422
  originalTask?: string;
423
+ /** Launcher name shared by every new step; absent when they run unwrapped. */
424
+ launcher?: string;
411
425
  }
412
426
  | { error: string };
413
427
 
414
428
  export function formatAsyncStartedMessage(headline: string, interactive: boolean): string {
415
429
  const guidance = interactive
416
430
  ? [
417
- "The async run is detached and running in the background.",
418
- "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.",
419
- "Use bg_wait only for provider, detached, or other background work that lacks a native completion notification.",
420
- "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.",
421
- "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: \"...\" }).",
422
433
  ]
423
434
  : [
424
- "The async run is detached. Do not run sleep timers or polling loops just to wait for it.",
425
- "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.",
426
- "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.",
427
436
  ];
428
437
  return [headline, "", ...guidance].join("\n");
429
438
  }
@@ -457,10 +466,10 @@ function closeFd(fd: number | undefined): void {
457
466
  * Spawn the async runner process
458
467
  */
459
468
  const RUNNER_STARTUP_TIMEOUT_MS = 10_000;
460
- type RunnerStartupState = "ready" | "acknowledged" | "confirmed";
469
+ type RunnerStartupState = "ready" | "acknowledged" | "confirmed" | "identified";
461
470
 
462
471
  type RunnerStartupWaitResult =
463
- | { ok: true; token: string }
472
+ | { ok: true; token: string; pid?: unknown; pidNamespaceScope?: unknown }
464
473
  | { ok: false; error: string; startupDidNotProceed?: boolean };
465
474
 
466
475
  function waitForStartupInterval(delayMs = 20): Promise<void> {
@@ -470,13 +479,13 @@ function waitForStartupInterval(delayMs = 20): Promise<void> {
470
479
  function readRunnerStartup(startupPath: string, expectedState: RunnerStartupState, expectedToken?: string): RunnerStartupWaitResult | undefined {
471
480
  if (!fs.existsSync(startupPath)) return undefined;
472
481
  try {
473
- 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 };
474
483
  if (payload.state === "error" && typeof payload.error === "string") return { ok: false, error: payload.error, startupDidNotProceed: true };
475
484
  if (payload.state !== expectedState) return undefined;
476
485
  if (typeof payload.token !== "string" || (expectedToken !== undefined && payload.token !== expectedToken)) {
477
486
  return { ok: false, error: `Async runner wrote an invalid ${expectedState} startup handshake: ${startupPath}`, startupDidNotProceed: true };
478
487
  }
479
- return { ok: true, token: payload.token };
488
+ return { ok: true, token: payload.token, pid: payload.pid, pidNamespaceScope: payload.pidNamespaceScope };
480
489
  } catch (error) {
481
490
  return { ok: false, error: `Failed to read async runner startup handshake '${startupPath}': ${error instanceof Error ? error.message : String(error)}`, startupDidNotProceed: true };
482
491
  }
@@ -555,7 +564,7 @@ function terminateRunnerBeforeProceed(pid: number): boolean {
555
564
  return !runnerIsAlive(pid);
556
565
  }
557
566
 
558
- 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> {
559
568
  for (const signal of ["SIGTERM", "SIGKILL"] as const) {
560
569
  if (proc.pid === undefined || !runnerIsAlive(proc.pid)) return true;
561
570
  try { process.kill(proc.pid, signal); } catch {
@@ -577,9 +586,17 @@ async function completeRunnerStartupHandshake(
577
586
  getObservedProcessExit: () => { exitCode: number | null; signal: NodeJS.Signals | null } | undefined,
578
587
  runnerProcessInstanceId: string,
579
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 },
580
591
  ): Promise<SpawnRunnerResult> {
592
+ const terminateRunnerBeforeProceedAsync = async (proc: ChildProcess, processClosed: Promise<{ exitCode: number | null; signal: NodeJS.Signals | null }>) => launcherIdentity ? launcherIdentity.terminate() : terminateRunnerBeforeProceedAsyncDefault(proc, processClosed);
581
593
  try {
582
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
+ }
583
600
  if (ready.ok === false) {
584
601
  persistStartupFailure(ready.error);
585
602
  const terminationObserved = await terminateRunnerBeforeProceedAsync(proc, processClosed);
@@ -679,12 +696,12 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
679
696
  const binaryHost = resolveBunPiExecutable();
680
697
  const nodeExecutable = resolveNodeExecutable();
681
698
  const nativeRunnerSupported = supportsNativeRunner(nodeExecutable);
682
- const runner = asyncRunnerSourcePath;
699
+ const runner = asyncRunnerSourcePath();
683
700
  const runnerIsJavaScript = path.extname(runner) === ".js";
684
- const bootstrap = path.join(path.dirname(runner), `binary-bootstrap${path.extname(fileURLToPath(import.meta.url))}`);
701
+ const bootstrap = resolveRuntimeModulePath(path.dirname(runner), "binary-bootstrap");
685
702
  if (binaryHost && !fs.existsSync(bootstrap)) return { error: `Background runner bootstrap not found: ${bootstrap}` };
686
703
  if (!binaryHost && !runnerIsJavaScript && !nativeRunnerSupported && !jitiCliPath) {
687
- return { error: sourceUnderNodeModules
704
+ return { error: sourceUnderNodeModules()
688
705
  ? "Background runner source is installed under node_modules, so upstream jiti is required for TypeScript execution."
689
706
  : "Background runner requires enabled native TypeScript with synchronous module hooks, or installed upstream jiti for TypeScript execution." };
690
707
  }
@@ -721,6 +738,27 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
721
738
  if (startupAckPath) fs.rmSync(startupAckPath, { force: true });
722
739
  if (startupConfirmPath) fs.rmSync(startupConfirmPath, { force: true });
723
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
+ };
724
762
 
725
763
  const logPaths = resolveAsyncRunnerLogPaths(launchConfig);
726
764
  let stdoutFd: number | undefined;
@@ -755,7 +793,8 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
755
793
  };
756
794
  if (launchParentSessionId === undefined) delete runnerEnv[SUBAGENT_PARENT_SESSION_ENV];
757
795
  else runnerEnv[SUBAGENT_PARENT_SESSION_ENV] = launchParentSessionId;
758
- const proc = spawn(command, args, {
796
+ const [spawnCommand, ...spawnArgs] = launcher ? [...launcher.argv, command, ...args] : [command, ...args];
797
+ const proc = spawn(spawnCommand!, spawnArgs, {
759
798
  cwd,
760
799
  ...backgroundProcessOptions(),
761
800
  stdio: ["ignore", stdoutFd ?? "ignore", stderrFd ?? "ignore"],
@@ -780,6 +819,16 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
780
819
  const asyncDir = launch.asyncDir;
781
820
  const runId = launch.id;
782
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
+ }
783
832
  finalizeProcessTerminal(asyncDir, runId, {
784
833
  processInstanceId: runnerProcessInstanceId,
785
834
  closeObservedAt: Date.now(),
@@ -834,8 +883,7 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
834
883
  try {
835
884
  writePrivateAtomicJson(initialStatusPath, {
836
885
  ...initialStatus,
837
- pid: proc.pid,
838
- pidNamespaceScope: currentPidNamespaceScope(),
886
+ ...(launcher ? {} : { pid: proc.pid, pidNamespaceScope: currentPidNamespaceScope() }),
839
887
  processTerminal: { version: 1, state: "pending", runId: initialStatus.runId, runnerProcessInstanceId },
840
888
  });
841
889
  // Aggregate waits must see the launch before the runner's first status update.
@@ -843,7 +891,7 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
843
891
  } catch (error) {
844
892
  const message = `Failed to persist initial async status: ${error instanceof Error ? error.message : String(error)}`;
845
893
  if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
846
- const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
894
+ const terminationObserved = terminateBeforeProceed(proc.pid);
847
895
  return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
848
896
  }
849
897
  try {
@@ -852,7 +900,7 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
852
900
  } catch (error) {
853
901
  const message = `Failed to establish async runner lifecycle sidecar: ${error instanceof Error ? error.message : String(error)}`;
854
902
  if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
855
- const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
903
+ const terminationObserved = terminateBeforeProceed(proc.pid);
856
904
  return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
857
905
  }
858
906
  try {
@@ -860,16 +908,34 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
860
908
  } catch (error) {
861
909
  const message = `Failed to establish async runner capacity ownership: ${error instanceof Error ? error.message : String(error)}`;
862
910
  if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
863
- const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
911
+ const terminationObserved = terminateBeforeProceed(proc.pid);
864
912
  return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
865
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
+ }
866
932
  if (launchBarrierToken && startupProceedPath) {
867
933
  try {
868
934
  writeRunnerStartupControl(startupProceedPath, { action: "proceed", token: launchBarrierToken });
869
935
  } catch (error) {
870
936
  const message = `Failed to authorize async runner startup: ${error instanceof Error ? error.message : String(error)}`;
871
937
  if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
872
- const terminationObserved = terminateRunnerBeforeProceed(proc.pid);
938
+ const terminationObserved = terminateBeforeProceed(proc.pid);
873
939
  return { pid: proc.pid, runnerProcessInstanceId, error: message, terminationObserved, startupDidNotProceed: true };
874
940
  }
875
941
  }
@@ -878,7 +944,9 @@ function spawnRunner(cfg: object, suffix: string, cwd: string, initialStatus: Om
878
944
  const persistStartupFailure = (message: string) => {
879
945
  if (launchAsyncDir) persistPreProceedStartupFailure(launchAsyncDir, launchRunId, runnerProcessInstanceId, launchSessionId, launchCompletionOwnerId, message);
880
946
  };
881
- 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 } : {}) }));
882
950
  }
883
951
  return { pid: proc.pid, runnerProcessInstanceId };
884
952
  } catch (error) {
@@ -944,6 +1012,14 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
944
1012
  worktreeProvider,
945
1013
  asyncDir,
946
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];
947
1023
  const launchParentSessionId = ctx.parentSessionId ?? ctx.currentSessionId;
948
1024
  const outputBaseDir = params.outputBaseDir;
949
1025
  const resultMode = params.resultMode ?? "chain";
@@ -1022,6 +1098,8 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1022
1098
  const externalRunnerType = a.runner?.type;
1023
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 });
1024
1100
  if (machineUnsupported) throw new AsyncStartValidationError(machineUnsupported);
1101
+ const launcherError = runnerLauncherPlacementError(a, requestedMachine);
1102
+ if (launcherError) throw new AsyncStartValidationError(launcherError);
1025
1103
  const registeredExtensions = resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1026
1104
  try {
1027
1105
  assertRequiredChildExtensionsAdmitted([params.requiredExtensions, ctx.childRuntime?.requiredExtensions, registeredExtensions], { agent: a.name, runnerType: a.runner?.type, machine: requestedMachine });
@@ -1198,6 +1276,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1198
1276
  permissionRules,
1199
1277
  runtimeSnapshotHost: ctx.pi,
1200
1278
  sandbox: a.sandbox,
1279
+ permissionProfile: a.permissionProfile,
1201
1280
  hostAvailableBuiltins,
1202
1281
  });
1203
1282
  const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
@@ -1206,6 +1285,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1206
1285
  }
1207
1286
  return {
1208
1287
  parentSessionId: launchParentSessionId,
1288
+ ...(ctx.parentSessionFile ? { parentSessionFile: ctx.parentSessionFile } : {}),
1209
1289
  permissionRules,
1210
1290
  ...(ctx.projectTrusted !== undefined ? { projectTrusted: ctx.projectTrusted } : {}),
1211
1291
  ...(ctx.trustedProjectCwd ? { trustedProjectCwd: ctx.trustedProjectCwd } : {}),
@@ -1246,6 +1326,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1246
1326
  ...(toolPlan.builtinMcpTools ? { builtinMcpTools: toolPlan.builtinMcpTools } : {}),
1247
1327
  mutationTools: a.mutationTools,
1248
1328
  ...(a.sandbox ? { sandbox: a.sandbox } : {}),
1329
+ ...(a.permissionProfile ? { permissionProfile: a.permissionProfile } : {}),
1249
1330
  systemPrompt,
1250
1331
  systemPromptMode: a.systemPromptMode,
1251
1332
  inheritProjectContext: a.inheritProjectContext,
@@ -1381,6 +1462,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1381
1462
  const steps = params.attachRoot
1382
1463
  ? [{
1383
1464
  parentSessionId: launchParentSessionId,
1465
+ ...(ctx.parentSessionFile ? { parentSessionFile: ctx.parentSessionFile } : {}),
1384
1466
  agent: params.attachRoot.agent,
1385
1467
  task: "",
1386
1468
  label: params.attachRoot.label ?? `Attached root ${params.attachRoot.runId}`,
@@ -1409,7 +1491,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1409
1491
  seen.set(task.outputPath, { index, agent: task.agent });
1410
1492
  }
1411
1493
  }
1412
- 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 } : {}) };
1413
1495
  } catch (error) {
1414
1496
  if (error instanceof UnavailableSubagentSkillError || error instanceof AsyncStartValidationError) return { error: error.message };
1415
1497
  throw error;
@@ -1422,7 +1504,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
1422
1504
  export function executeAsyncChain(
1423
1505
  id: string,
1424
1506
  params: AsyncChainParams,
1425
- ): AsyncExecutionResult {
1507
+ ): AsyncExecutionResult | Promise<AsyncExecutionResult> {
1426
1508
  const {
1427
1509
  chain,
1428
1510
  agents,
@@ -1454,6 +1536,10 @@ export function executeAsyncChain(
1454
1536
  (step, parallel) => Array.isArray(step.parallel) ? { parallel } : { acceptance: "acceptance" in step ? step.acceptance : undefined, parallel }),
1455
1537
  });
1456
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.`);
1457
1543
  const capabilityCeiling = params.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(ctx.currentSessionId);
1458
1544
  const inheritedNestedRoute = inheritedNestedRouteOf(ctx.childRuntime);
1459
1545
  const nestedAddress = inheritedNestedRoute ? inheritedNestedParentAddressOf(ctx.childRuntime) : undefined;
@@ -1520,6 +1606,7 @@ export function executeAsyncChain(
1520
1606
  return formatAsyncStartError(resultMode, built.error);
1521
1607
  }
1522
1608
  const { steps, runnerCwd, workflowGraph, eventChain } = built;
1609
+ const launcher = built.launcher === undefined ? undefined : lookupRunnerLauncher(ctx.runnerLaunchers, built.launcher);
1523
1610
  const deadlineAt = params.timeoutMs !== undefined ? Date.now() + params.timeoutMs : undefined;
1524
1611
  const initialUsageBudget = usageBudgetState(params.usageBudget, undefined);
1525
1612
  let childTargetIndex = 0;
@@ -1560,9 +1647,9 @@ export function executeAsyncChain(
1560
1647
  return formatAsyncStartError(resultMode, `Failed to record required child extensions: ${error instanceof Error ? error.message : String(error)}`);
1561
1648
  }
1562
1649
 
1563
- let spawnResult: SpawnRunnerResult = {};
1650
+ let spawnResultOrPromise: SpawnRunnerResult | Promise<SpawnRunnerResult> = {};
1564
1651
  try {
1565
- spawnResult = spawnRunner(
1652
+ spawnResultOrPromise = spawnRunner(
1566
1653
  {
1567
1654
  id,
1568
1655
  steps,
@@ -1609,6 +1696,7 @@ export function executeAsyncChain(
1609
1696
  depth: nestedAddress.depth,
1610
1697
  path: nestedAddress.path,
1611
1698
  } : undefined,
1699
+ ...(launcher ? { launcher } : {}),
1612
1700
  },
1613
1701
  id,
1614
1702
  runnerCwd,
@@ -1624,19 +1712,22 @@ export function executeAsyncChain(
1624
1712
  currentStep: 0,
1625
1713
  chainStepCount: eventChain.length,
1626
1714
  ...(initialParallelGroups.length ? { parallelGroups: initialParallelGroups } : {}),
1715
+ ...(launcher ? { launcher } : {}),
1627
1716
  steps: initialStatusSteps,
1628
1717
  },
1629
1718
  path.join(asyncDir, "status.json"),
1630
1719
  launchParentSessionId,
1631
1720
  (proof) => emitProcessTerminalEvent(ctx, proof),
1632
1721
  (runnerProcessInstanceId) => params.activeAsyncCapacity?.markStarted(runnerProcessInstanceId),
1633
- ) as SpawnRunnerResult;
1722
+ );
1634
1723
  } catch (error) {
1635
1724
  params.activeAsyncCapacity?.rollback();
1636
1725
  const message = error instanceof Error ? error.message : String(error);
1637
1726
  return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': ${message}`);
1638
1727
  }
1639
1728
 
1729
+ // A launcher run's spawn resolves once the runner reports its identity.
1730
+ const finishSpawnResult = (spawnResult: SpawnRunnerResult): AsyncExecutionResult => {
1640
1731
  if (spawnResult.error) {
1641
1732
  if (spawnResult.startupDidNotProceed) {
1642
1733
  if (!spawnResult.runnerProcessInstanceId || params.activeAsyncCapacity?.rollbackBeforeRunnerProceed(spawnResult.runnerProcessInstanceId) !== true) params.activeAsyncCapacity?.rollback();
@@ -1758,6 +1849,8 @@ export function executeAsyncChain(
1758
1849
  content: [{ type: "text", text: formatAsyncStartedMessage(`Async ${resultMode}: ${chainDesc} [${id}]`, ctx.interactive === true) }],
1759
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 } : {}) },
1760
1851
  };
1852
+ };
1853
+ return spawnResultOrPromise instanceof Promise ? spawnResultOrPromise.then(finishSpawnResult) : finishSpawnResult(spawnResultOrPromise);
1761
1854
  }
1762
1855
 
1763
1856
  /**
@@ -1842,6 +1935,9 @@ export function executeAsyncSingle(
1842
1935
  const requestedMachine = params.machine ?? agentConfig.machine;
1843
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 });
1844
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;
1845
1941
  const registeredExtensions = resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1846
1942
  try {
1847
1943
  assertRequiredChildExtensionsAdmitted([params.requiredExtensions, ctx.childRuntime?.requiredExtensions, registeredExtensions], { agent: agentConfig.name, runnerType: agentConfig.runner?.type, machine: requestedMachine });
@@ -2042,6 +2138,7 @@ export function executeAsyncSingle(
2042
2138
  permissionRules: resolvePermissionRules(ctx.permissions, agentConfig.permissions),
2043
2139
  runtimeSnapshotHost: ctx.pi,
2044
2140
  sandbox,
2141
+ permissionProfile: agentConfig.permissionProfile,
2045
2142
  hostAvailableBuiltins,
2046
2143
  });
2047
2144
  const launchResolvedExtensions = externalRunner ? undefined : projectLaunchResolvedChildExtensions(toolPlan);
@@ -2123,6 +2220,7 @@ export function executeAsyncSingle(
2123
2220
  ...(params.context ? { context: params.context } : {}),
2124
2221
  ...(params.intercomBridge !== undefined ? { intercomBridge: params.intercomBridge } : {}),
2125
2222
  ...(params.baseRef !== undefined ? { baseRef: params.baseRef } : {}),
2223
+ ...(launcher ? { launcher: launcher.name } : {}),
2126
2224
  ...(deadlineAt !== undefined ? { absoluteDeadlineAt: deadlineAt } : {}),
2127
2225
  ...(resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {}),
2128
2226
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, recoveryAgentConfig.maxSubagentDepth),
@@ -2148,9 +2246,11 @@ export function executeAsyncSingle(
2148
2246
  spawnResultOrPromise = spawnRunner(
2149
2247
  {
2150
2248
  id,
2249
+ ...(params.toolCallId ? { toolCallId: params.toolCallId } : {}),
2151
2250
  steps: [
2152
2251
  {
2153
2252
  parentSessionId: launchParentSessionId,
2253
+ ...(ctx.parentSessionFile ? { parentSessionFile: ctx.parentSessionFile } : {}),
2154
2254
  permissionRules,
2155
2255
  ...(ctx.projectTrusted !== undefined ? { projectTrusted: ctx.projectTrusted } : {}),
2156
2256
  ...(ctx.trustedProjectCwd ? { trustedProjectCwd: ctx.trustedProjectCwd } : {}),
@@ -2186,6 +2286,7 @@ export function executeAsyncSingle(
2186
2286
  ...(toolPlan.builtinMcpTools ? { builtinMcpTools: toolPlan.builtinMcpTools } : {}),
2187
2287
  mutationTools: agentConfig.mutationTools,
2188
2288
  ...(sandbox ? { sandbox } : {}),
2289
+ ...(agentConfig.permissionProfile ? { permissionProfile: agentConfig.permissionProfile } : {}),
2189
2290
  systemPrompt,
2190
2291
  systemPromptMode: agentConfig.systemPromptMode,
2191
2292
  inheritProjectContext: agentConfig.inheritProjectContext,
@@ -2256,6 +2357,7 @@ export function executeAsyncSingle(
2256
2357
  ...(lane ? { lane } : {}),
2257
2358
  ...(params.revivalLease ? { revivalLease: params.revivalLease } : {}),
2258
2359
  nestedRoute: nestedRoute ?? inheritedNestedRoute,
2360
+ ...(launcher ? { launcher } : {}),
2259
2361
  nestedSelf: inheritedNestedRoute && nestedAddress ? {
2260
2362
  parentRunId: nestedAddress.parentRunId,
2261
2363
  parentStepIndex: nestedAddress.parentStepIndex,
@@ -2271,12 +2373,14 @@ export function executeAsyncSingle(
2271
2373
  ...(ctx.currentSessionId ? { sessionId: ctx.currentSessionId } : {}),
2272
2374
  ...(initialCompletionOwnerId ? { completionOwnerId: initialCompletionOwnerId } : {}),
2273
2375
  mode: "single",
2376
+ ...(params.toolCallId ? { toolCallId: params.toolCallId } : {}),
2274
2377
  state: "running",
2275
2378
  startedAt: initialStatusAt,
2276
2379
  lastUpdate: initialStatusAt,
2277
2380
  currentStep: 0,
2278
2381
  chainStepCount: 1,
2279
2382
  ...(lane ? { lane } : {}),
2383
+ ...(launcher ? { launcher } : {}),
2280
2384
  steps: [{ agent, status: "pending", ...(lane ? { lane } : {}), ...(model ? { model } : {}), ...(contextLimit !== undefined ? { contextLimit } : {}) }],
2281
2385
  },
2282
2386
  path.join(asyncDir, "status.json"),
@@ -2347,6 +2451,7 @@ export function executeAsyncSingle(
2347
2451
  sessionId: ctx.currentSessionId,
2348
2452
  completionOwnerId: ctx.completionOwnerId ?? currentCompletionOwnerId(),
2349
2453
  mode: "single",
2454
+ ...(params.toolCallId ? { toolCallId: params.toolCallId } : {}),
2350
2455
  agent,
2351
2456
  ...(sandbox ? { sandbox } : {}),
2352
2457
  task: task?.trim() ? PROMPT_REDACTED : undefined,
@@ -2367,7 +2472,7 @@ export function executeAsyncSingle(
2367
2472
 
2368
2473
  return {
2369
2474
  content: [{ type: "text", text: formatAsyncStartedMessage(`Async: ${agent} [${id}]`, ctx.interactive === true) }],
2370
- 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,
2371
2476
  };
2372
2477
  };
2373
2478
  return spawnResultOrPromise instanceof Promise ? spawnResultOrPromise.then(finishSpawnResult) : finishSpawnResult(spawnResultOrPromise);
@@ -6,6 +6,7 @@ import { formatControlNoticeMessage } from "../shared/subagent-control.ts";
6
6
  import {
7
7
  type AsyncJobState,
8
8
  type AsyncStartedEvent,
9
+ type AsyncWidgetLayout,
9
10
  type ControlEvent,
10
11
  type SteeringNotice,
11
12
  type SubagentChildStatusEvent,
@@ -36,13 +37,17 @@ interface AsyncJobTrackerOptions {
36
37
  resultsDir?: string;
37
38
  widgetEnabled?: boolean;
38
39
  widgetCollapsed?: boolean;
40
+ widgetLayout?: AsyncWidgetLayout;
39
41
  platform?: NodeJS.Platform;
40
- onJobTerminal?: () => void;
42
+ onJobTerminal?: (job: AsyncJobState) => void;
43
+ onJobCleanup?: (asyncId: string) => void;
41
44
  watch?: typeof fs.watch;
42
45
  kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
43
46
  now?: () => number;
44
47
  /** Resolve native supervisor requests without scanning supervisor mailboxes. */
45
48
  supervisorRequestState?: (event: ControlEvent) => "pending" | "resolved" | "unknown";
49
+ /** Called whenever the tracked jobs changed enough to re-render the widget. */
50
+ onJobsChanged?: () => void;
46
51
  }
47
52
 
48
53
  const CONTROL_EVENT_READ_CHUNK_BYTES = 64 * 1024;
@@ -104,8 +109,9 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
104
109
  }, run);
105
110
  };
106
111
  const rerenderWidget = (ctx: ExtensionContext, jobs = Array.from(state.asyncJobs.values())) => {
112
+ options.onJobsChanged?.();
107
113
  if (state.widgetsSuspended) return;
108
- renderWidget(ctx, options.widgetEnabled === false ? [] : jobs, options.widgetCollapsed);
114
+ renderWidget(ctx, options.widgetEnabled === false ? [] : jobs, options.widgetCollapsed, options.widgetLayout);
109
115
  (ctx.ui as { requestRender?: () => void }).requestRender?.();
110
116
  };
111
117
  const rerenderLastWidget = (jobs = Array.from(state.asyncJobs.values())) => {
@@ -125,7 +131,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
125
131
  if (state.widgetsSuspended) return;
126
132
  const requestRender = (ctx.ui as { requestRender?: () => void }).requestRender;
127
133
  if (requestRender) requestRender.call(ctx.ui);
128
- else renderWidget(ctx, Array.from(state.asyncJobs.values()), options.widgetCollapsed);
134
+ else renderWidget(ctx, Array.from(state.asyncJobs.values()), options.widgetCollapsed, options.widgetLayout);
129
135
  });
130
136
  };
131
137
  const refreshWidget = (ctx: ExtensionContext) => rerenderWidget(ctx);
@@ -220,6 +226,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
220
226
  const job = state.asyncJobs.get(asyncId);
221
227
  retainNestedLookupRoute(state, job?.nestedRoute, job?.sessionId);
222
228
  state.asyncJobs.delete(asyncId);
229
+ options.onJobCleanup?.(asyncId);
223
230
  rerenderLastWidget();
224
231
  }, completionRetentionMs);
225
232
  state.cleanupTimers.set(asyncId, timer);
@@ -560,7 +567,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
560
567
  } else cancelCleanup(job.asyncId);
561
568
  }
562
569
  // Scan on close too: publication may have raced the payload check.
563
- if (!isTerminalJobStatus(previousStatus) || (wasPending && !publication?.pending)) options.onJobTerminal?.();
570
+ if (!isTerminalJobStatus(previousStatus) || (wasPending && !publication?.pending)) options.onJobTerminal?.(job);
564
571
  rememberFleetJob(state, job);
565
572
  if (!publication?.pending && !nestedRefreshFailed && !hasLiveNestedDescendants(job.nestedChildren) && (previousStatus !== job.status || !state.cleanupTimers.has(job.asyncId))) {
566
573
  scheduleCleanup(job.asyncId);
@@ -1,6 +1,6 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
- import { DIRS, type AcceptanceInput, type AsyncStatus, type SteeringRecoveryDescriptor, type SubagentRunMode } from "../../shared/types.ts";
3
+ import { DIRS, RUNNER_LAUNCHER_NAME_PATTERN, type AcceptanceInput, type AsyncStatus, type SteeringRecoveryDescriptor, type SubagentRunMode } from "../../shared/types.ts";
4
4
  import type { AgentConfig } from "../../agents/agents.ts";
5
5
  import { normalizeExtensionBindings } from "../shared/extension-bindings.ts";
6
6
  import { snapshotRequiredChildExtensions } from "../../shared/required-child-extensions.ts";
@@ -343,7 +343,7 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
343
343
  "subagentOnlyExtensions", "mcpDirectTools", "excludeTools", "mutationTools", "systemPrompt", "systemPromptMode", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "skills",
344
344
  "skillPath", "agentFilePath", "memory", "outputPath", "outputMode", "structuredOutputSchema", "acceptance", "sessionDir", "artifactConfig",
345
345
  "artifactsDir", "maxOutput", "controlConfig", "context", "intercomBridge", "absoluteDeadlineAt", "initialTurnBudget", "initialToolBudget", "maxSubagentDepth", "share", "capabilityCeiling",
346
- "launchResolvedExtensions", "runFanoutBudget", "lane", "baseRef",
346
+ "launchResolvedExtensions", "runFanoutBudget", "lane", "baseRef", "launcher",
347
347
  "extensionBindings",
348
348
  "requiredExtensions",
349
349
  ]);
@@ -355,6 +355,7 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
355
355
  if (typeof parsed[field] !== "string" || !(parsed[field] as string).trim()) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': ${field} must be a non-empty string.`);
356
356
  }
357
357
  if (parsed.version !== 1) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': version must be 1.`);
358
+ if (parsed.launcher !== undefined && (typeof parsed.launcher !== "string" || !RUNNER_LAUNCHER_NAME_PATTERN.test(parsed.launcher))) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': launcher must be a launcher name.`);
358
359
  try {
359
360
  parsed.runFanoutBudget = validateRunFanoutBudgetDescriptor(parsed.runFanoutBudget);
360
361
  } catch (error) {
@@ -664,6 +665,8 @@ export function applySteeringRecoveryAgentConfig(agentConfig: AgentConfig, descr
664
665
  output: descriptor.outputPath,
665
666
  toolBudget: descriptor.initialToolBudget,
666
667
  maxSubagentDepth: descriptor.maxSubagentDepth,
668
+ // The recorded launcher wins over the current agent file, including recorded absence.
669
+ launcher: descriptor.launcher,
667
670
  };
668
671
  }
669
672