pi-subagents 0.84.0 → 0.85.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 (204) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-235AWJUQ.js → chunk-3UZ5FVVJ.js} +310 -101
  5. package/bundle/{chunk-F4ASL6OV.js → chunk-7MAE3DJV.js} +1 -1
  6. package/bundle/{chunk-4E7BKDTX.js → chunk-CS4O36CZ.js} +11 -156
  7. package/bundle/{chunk-VQVVHSY6.js → chunk-DV2NCNPR.js} +22 -11
  8. package/bundle/{chunk-G2Z6ZH26.js → chunk-GCSLVFCX.js} +1 -1
  9. package/bundle/{chunk-2S4K53MV.js → chunk-H2NLFTC5.js} +1 -1
  10. package/bundle/{chunk-NKQ6JNAS.js → chunk-HFTBF7SG.js} +2 -1
  11. package/bundle/chunk-HXRB42AF.js +108 -0
  12. package/bundle/{chunk-7BWGNDNK.js → chunk-IQIWF2VX.js} +190 -1177
  13. package/bundle/{chunk-XDQORLZ5.js → chunk-JNXT3MPI.js} +15 -6
  14. package/bundle/{chunk-J5YL7LYR.js → chunk-JO67XSKD.js} +59 -27
  15. package/bundle/{chunk-JG4QKI5M.js → chunk-JWYG26RE.js} +209 -93
  16. package/bundle/{chunk-C5P5CHYK.js → chunk-KDMFBYFM.js} +1 -1
  17. package/bundle/{chunk-V2BZYLEP.js → chunk-KEY3UQMQ.js} +7 -2
  18. package/bundle/{chunk-NENDSQUY.js → chunk-KZ34KQQH.js} +9 -6
  19. package/bundle/{chunk-AKOIVLA5.js → chunk-L2ENOFVZ.js} +76 -58
  20. package/bundle/{chunk-CGN2TVE7.js → chunk-LGMILZNE.js} +322 -18
  21. package/bundle/{chunk-L3WFKBEI.js → chunk-LTPH2DXH.js} +247 -153
  22. package/bundle/{chunk-2D52JFLF.js → chunk-N7B2KD74.js} +41 -117
  23. package/bundle/{chunk-PV63UFUR.js → chunk-O7CPL6H4.js} +183 -28
  24. package/bundle/{chunk-D3JAFGMO.js → chunk-PHZP3KHB.js} +1 -1
  25. package/bundle/{chunk-2DHZTCOL.js → chunk-PVIVCDG2.js} +2 -2
  26. package/bundle/{chunk-LFDBD4PW.js → chunk-QO75KJBT.js} +2 -2
  27. package/bundle/{chunk-SSG7IEP5.js → chunk-RQAUNAWG.js} +2 -2
  28. package/bundle/{chunk-PALJGGYC.js → chunk-RV5OGHLO.js} +6 -3
  29. package/bundle/chunk-T5V5BRCL.js +1067 -0
  30. package/bundle/{chunk-LNRJCP2Y.js → chunk-UX4SCV5N.js} +337 -207
  31. package/bundle/{chunk-DZDETGRJ.js → chunk-WOVMHDES.js} +231 -182
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +8 -8
  36. package/bundle/project-panes.js +3 -3
  37. package/docs/agents.md +17 -2
  38. package/docs/configuration.md +2 -2
  39. package/docs/extension-api.md +16 -1
  40. package/docs/workflows.md +30 -2
  41. package/package.json +1 -1
  42. package/src/agents/agent-management.js +27 -11
  43. package/src/agents/agent-memory.d.ts +1 -4
  44. package/src/agents/agent-memory.js +1 -4
  45. package/src/agents/agents.d.ts +1 -3
  46. package/src/agents/agents.js +7 -6
  47. package/src/agents/frontmatter.js +1 -8
  48. package/src/agents/global-npm-root.d.ts +1 -0
  49. package/src/agents/global-npm-root.js +11 -3
  50. package/src/agents/skills.d.ts +0 -3
  51. package/src/agents/skills.js +0 -3
  52. package/src/extension/config.js +7 -1
  53. package/src/extension/herdr-pi-bridge.js +10 -2
  54. package/src/extension/index.d.ts +0 -13
  55. package/src/extension/index.js +43 -32
  56. package/src/extension/public-execution.d.ts +1 -0
  57. package/src/extension/public-execution.js +4 -0
  58. package/src/extension/reply-workflow-script.js +24 -4
  59. package/src/extension/schemas.d.ts +8 -3
  60. package/src/extension/schemas.js +5 -3
  61. package/src/extension/session-switch.d.ts +25 -0
  62. package/src/extension/session-switch.js +138 -0
  63. package/src/extension/subagent-guide.d.ts +1 -1
  64. package/src/extension/subagent-guide.js +1 -1
  65. package/src/extension/subagent-launch-tool.d.ts +25 -0
  66. package/src/extension/subagent-launch-tool.js +48 -0
  67. package/src/extension/tool-activation.js +25 -11
  68. package/src/extension/tool-description.js +6 -0
  69. package/src/inspectors/herdr/actions.d.ts +0 -1
  70. package/src/inspectors/herdr/actions.js +0 -1
  71. package/src/inspectors/session-roots-codec.d.ts +0 -1
  72. package/src/inspectors/session-roots-codec.js +0 -1
  73. package/src/inspectors/tmux/actions.d.ts +0 -1
  74. package/src/inspectors/tmux/actions.js +0 -1
  75. package/src/integrations/herdr-status.js +3 -8
  76. package/src/intercom/native-supervisor-channel.js +65 -9
  77. package/src/runs/background/async-execution.d.ts +5 -9
  78. package/src/runs/background/async-execution.js +62 -27
  79. package/src/runs/background/async-job-tracker.js +12 -0
  80. package/src/runs/background/async-resume.d.ts +2 -1
  81. package/src/runs/background/async-resume.js +112 -39
  82. package/src/runs/background/async-retention.js +6 -1
  83. package/src/runs/background/auto-drain.js +2 -1
  84. package/src/runs/background/boot-id.d.ts +1 -3
  85. package/src/runs/background/boot-id.js +1 -3
  86. package/src/runs/background/completion-batcher.d.ts +3 -4
  87. package/src/runs/background/completion-batcher.js +2 -3
  88. package/src/runs/background/control-channel.d.ts +0 -6
  89. package/src/runs/background/control-channel.js +0 -6
  90. package/src/runs/background/fleet-view.js +2 -3
  91. package/src/runs/background/notify.d.ts +0 -2
  92. package/src/runs/background/notify.js +0 -2
  93. package/src/runs/background/result-watcher.d.ts +1 -0
  94. package/src/runs/background/result-watcher.js +59 -29
  95. package/src/runs/background/resume-guidance.js +4 -2
  96. package/src/runs/background/retained-children.js +2 -1
  97. package/src/runs/background/run-child-session.d.ts +0 -1
  98. package/src/runs/background/run-child-session.js +1 -1
  99. package/src/runs/background/run-status.js +4 -3
  100. package/src/runs/background/scheduled-runs.d.ts +3 -1
  101. package/src/runs/background/scheduled-runs.js +13 -16
  102. package/src/runs/background/subagent-runner.d.ts +2 -4
  103. package/src/runs/background/subagent-runner.js +9 -6
  104. package/src/runs/background/subagent-wait.js +12 -15
  105. package/src/runs/background/wait-config.d.ts +2 -0
  106. package/src/runs/background/wait-config.js +17 -3
  107. package/src/runs/background/wait-tool.js +4 -2
  108. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  109. package/src/runs/background/workflow-terminal-proof.js +0 -1
  110. package/src/runs/foreground/execution.d.ts +0 -3
  111. package/src/runs/foreground/execution.js +17 -9
  112. package/src/runs/foreground/subagent-executor.d.ts +3 -2
  113. package/src/runs/foreground/subagent-executor.js +107 -26
  114. package/src/runs/shared/child-commands.js +15 -2
  115. package/src/runs/shared/child-hooks.d.ts +1 -7
  116. package/src/runs/shared/child-hooks.js +13 -5
  117. package/src/runs/shared/child-launch.js +6 -2
  118. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  119. package/src/runs/shared/child-session.d.ts +1 -1
  120. package/src/runs/shared/child-session.js +21 -2
  121. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  122. package/src/runs/shared/child-tool-plan.js +0 -1
  123. package/src/runs/shared/claude-code-adapter.js +11 -0
  124. package/src/runs/shared/external-cli-runner.js +26 -6
  125. package/src/runs/shared/herdr-connection.js +2 -1
  126. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  127. package/src/runs/shared/herdr-pane-host.js +17 -1
  128. package/src/runs/shared/herdr-placed-run.js +48 -22
  129. package/src/runs/shared/lane-metadata.d.ts +0 -1
  130. package/src/runs/shared/lane-metadata.js +0 -1
  131. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  132. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  133. package/src/runs/shared/model-resolution.d.ts +2 -2
  134. package/src/runs/shared/model-resolution.js +7 -1
  135. package/src/runs/shared/model-scope.d.ts +1 -5
  136. package/src/runs/shared/model-scope.js +1 -5
  137. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  138. package/src/runs/shared/mutation-evidence.js +52 -7
  139. package/src/runs/shared/nested-events.d.ts +1 -0
  140. package/src/runs/shared/nested-events.js +1 -1
  141. package/src/runs/shared/parallel-utils.d.ts +0 -1
  142. package/src/runs/shared/permissions.js +5 -3
  143. package/src/runs/shared/placement-host.d.ts +5 -1
  144. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  145. package/src/runs/shared/rex-pane-host.js +0 -2
  146. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  147. package/src/runs/shared/run-launch-folder.js +21 -0
  148. package/src/runs/shared/runner-launcher.d.ts +12 -1
  149. package/src/runs/shared/runner-launcher.js +16 -0
  150. package/src/runs/shared/single-output.d.ts +3 -3
  151. package/src/runs/shared/single-output.js +5 -3
  152. package/src/runs/shared/structured-output.d.ts +8 -0
  153. package/src/runs/shared/structured-output.js +30 -2
  154. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  155. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  156. package/src/runs/shared/tool-timeout.js +2 -1
  157. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  158. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  159. package/src/runs/shared/worktree.d.ts +3 -0
  160. package/src/runs/shared/worktree.js +20 -0
  161. package/src/shared/capacity-resilient-json.d.ts +1 -1
  162. package/src/shared/child-cache-retention.d.ts +1 -2
  163. package/src/shared/child-cache-retention.js +1 -2
  164. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  165. package/src/shared/fleet-transcript-reader.js +333 -0
  166. package/src/shared/formatters.d.ts +0 -18
  167. package/src/shared/formatters.js +0 -18
  168. package/src/shared/session-succession.d.ts +16 -1
  169. package/src/shared/session-succession.js +41 -2
  170. package/src/shared/session-warnings.d.ts +7 -0
  171. package/src/shared/session-warnings.js +26 -0
  172. package/src/shared/settings.d.ts +0 -23
  173. package/src/shared/settings.js +3 -35
  174. package/src/shared/types.d.ts +28 -11
  175. package/src/shared/types.js +0 -12
  176. package/src/shared/utils.d.ts +0 -14
  177. package/src/shared/utils.js +0 -22
  178. package/src/shared/wait-tool-name.d.ts +8 -0
  179. package/src/shared/wait-tool-name.js +13 -0
  180. package/src/slash/slash-commands.js +2 -1
  181. package/src/slash/subagent-cost.d.ts +3 -2
  182. package/src/slash/subagent-cost.js +22 -3
  183. package/src/slash/subagents-admin.js +0 -1
  184. package/src/tui/fleet-status.d.ts +0 -5
  185. package/src/tui/fleet-status.js +4 -24
  186. package/src/tui/fleet-transcript.d.ts +1 -44
  187. package/src/tui/fleet-transcript.js +1 -327
  188. package/src/tui/fleet.js +6 -4
  189. package/src/tui/render.d.ts +0 -9
  190. package/src/tui/render.js +81 -47
  191. package/src/tui/subagent-messages.js +3 -2
  192. package/src/watchdog/register-child.d.ts +2 -3
  193. package/src/watchdog/register-child.js +2 -3
  194. package/src/watchdog/turn-delta.js +2 -1
  195. package/src/workflows/scripted-workflow.js +241 -20
  196. package/src/workflows/workflow-launch-record.d.ts +15 -6
  197. package/src/workflows/workflow-launch-record.js +30 -12
  198. package/src/workflows/workflow-resume-claim.js +2 -2
  199. package/src/workflows/workflow-resume.d.ts +1 -1
  200. package/src/workflows/workflow-resume.js +11 -8
  201. package/src/workflows/workflow-script-worker.d.ts +13 -0
  202. package/src/workflows/workflow-script-worker.js +79 -0
  203. package/workflow-script-process.cjs +36 -0
  204. package/workflow-script-worker.cjs +4 -1
@@ -1,6 +1,3 @@
1
- /**
2
- * Async execution logic for subagent tool
3
- */
4
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
2
  import type { ParentProviderRegistry } from "../shared/child-session.ts";
6
3
  import { type AgentConfig, type UnknownAgentDiagnosticContext } from "../../agents/agents.ts";
@@ -17,6 +14,7 @@ import { type ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
17
14
  import type { ImportedAsyncRoot } from "./chain-root-attachment.ts";
18
15
  import type { SessionLeaseRequest } from "../shared/session-lease.ts";
19
16
  import type { ActiveAsyncCapacityHandle } from "./active-async-capacity.ts";
17
+ import { type RequiredRunnerLauncher } from "../../shared/types.ts";
20
18
  import { type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
21
19
  import { type PermissionConfig } from "../shared/permissions.ts";
22
20
  import { type ExtensionBindings } from "../shared/extension-bindings.ts";
@@ -134,6 +132,10 @@ interface AsyncSingleParams {
134
132
  machine?: string;
135
133
  /** Launch cwd as typed when a machine is set: a path on that machine, never resolved locally. */
136
134
  machineCwd?: string;
135
+ /** The launcher and agent definition digest the call requires; checked here, on what this launch spawns. */
136
+ requireLauncher?: RequiredRunnerLauncher;
137
+ /** A revived run's inherited requirement: recorded for its own resumes, not checked here (resume already checked it). */
138
+ carriedRequiredLauncher?: RequiredRunnerLauncher;
137
139
  maxOutput?: MaxOutputConfig;
138
140
  artifactsDir?: string;
139
141
  artifactConfig: ArtifactConfig;
@@ -288,13 +290,7 @@ export declare function resolveClaudeCodeThinking(source: string | false | undef
288
290
  * owns the remote model registry, so the combination fails instead of losing both flags. */
289
291
  export declare function assertClaudeCodeOverrideIsLocal(agent: string, machine: string | undefined, override: ClaudeCodeOverride | undefined): void;
290
292
  export declare function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildParams): AsyncRunnerStepBuildResult;
291
- /**
292
- * Execute a chain asynchronously
293
- */
294
293
  export declare function executeAsyncChain(id: string, params: AsyncChainParams): AsyncExecutionResult | Promise<AsyncExecutionResult>;
295
- /**
296
- * Execute a single agent asynchronously
297
- */
298
294
  export declare function workflowAwaitedAsyncResultPath(asyncDir: string): string;
299
295
  export declare function executeAsyncSingle(id: string, params: AsyncSingleParams): AsyncExecutionResult | Promise<AsyncExecutionResult>;
300
296
  export {};
@@ -1,7 +1,4 @@
1
- /**
2
- * Async execution logic for subagent tool
3
- */
4
- import { spawn } from "node:child_process";
1
+ import { spawn, spawnSync } from "node:child_process";
5
2
  import { randomUUID } from "node:crypto";
6
3
  import * as fs from "node:fs";
7
4
  import * as path from "node:path";
@@ -33,7 +30,7 @@ import { resolveToolTimeoutMs, toolTimeoutFromEnv } from "../shared/tool-timeout
33
30
  import { resolveModelScopesForAgent } from "../shared/model-scope.js";
34
31
  import { findModelInfo, resolveEffectiveThinking } from "../../shared/model-info.js";
35
32
  import { assertThinkingWithinCeiling, intersectThinkingCeilings } from "../../shared/thinking-ceiling.js";
36
- import { resolveExpectedWorktreeAgentCwd, resolveWorktreeProvider, shouldDeferWorktreeCwd, WORKTREE_AGENT_CWD_PLACEHOLDER } from "../shared/worktree.js";
33
+ import { buildWorktreeNaming, resolveExpectedWorktreeAgentCwd, resolveWorktreeProvider, shouldDeferWorktreeCwd, WORKTREE_AGENT_CWD_PLACEHOLDER } from "../shared/worktree.js";
37
34
  import { buildWorkflowGraphSnapshot } from "../shared/workflow-graph.js";
38
35
  import { ChainOutputValidationError, validateChainOutputBindings } from "../shared/chain-outputs.js";
39
36
  import { createStructuredOutputRuntime } from "../shared/structured-output.js";
@@ -54,7 +51,7 @@ import { statusStepDescription } from "./chain-append.js";
54
51
  import { currentBootId, currentRecordedPid } from "./boot-id.js";
55
52
  import { currentPidNamespaceScope } from "./pid-namespace.js";
56
53
  import { checkRecordedPidLiveness } from "./stale-run-reconciler.js";
57
- import { lookupRunnerLauncher, resolveAgentRunnerLauncher, runnerLauncherPlacementError } from "../shared/runner-launcher.js";
54
+ import { checkRequiredRunnerLauncher, lookupRunnerLauncher, resolveAgentRunnerLauncher, runnerLauncherPlacementError } from "../shared/runner-launcher.js";
58
55
  import { SUBAGENT_PROCESS_TERMINAL_EVENT } from "../../shared/types.js";
59
56
  import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling } from "../shared/capability-ceiling.js";
60
57
  import { resolveLaunchBinding } from "../../shared/launch-contract.js";
@@ -62,7 +59,9 @@ import { resolvePermissionRules } from "../shared/permissions.js";
62
59
  import { normalizeExtensionBindings, omitExtensionBindingsEnv } from "../shared/extension-bindings.js";
63
60
  import { omitGitRoutingEnv } from "../shared/git-environment.js";
64
61
  import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.js";
62
+ import { recoveryDescriptorPath } from "../shared/run-launch-folder.js";
65
63
  import { assertRequiredChildExtensionsAdmitted, resolveRequiredChildExtensions, writeRetainedRequiredChildExtensions } from "../../shared/required-child-extensions.js";
64
+ import { DEFAULT_WAIT_TOOL_NAME, waitToolName } from "../../shared/wait-tool-name.js";
66
65
  const require = nodeModule.createRequire(import.meta.url);
67
66
  // Cache failures as well as roots: management must remain loadable, and launches must not retry another SDK.
68
67
  const piPackageSelection = (() => {
@@ -150,11 +149,11 @@ export const DEFAULT_ASYNC_TIMEOUT_MS = 30 * 60 * 1000;
150
149
  export function formatAsyncStartedMessage(headline, interactive) {
151
150
  const guidance = interactive
152
151
  ? [
153
- "Detached. Return control now: native completion wakes you, so do not sleep, poll, or call bg_wait for it.",
152
+ `Detached. Return control now: native completion wakes you, so do not sleep, poll, or call ${waitToolName()} for it.`,
154
153
  "One-shot check: subagent({ action: \"status\", id: \"...\" }).",
155
154
  ]
156
155
  : [
157
- "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.",
156
+ `Detached non-interactive run: Pi auto-drains current-session subagent work at agent_end. Do not run sleep timers or polling loops. Use ${waitToolName()} only for results this turn needs from work without native notification, and subagent({ action: \"status\", id: \"...\" }) for a one-shot check.`,
158
157
  ];
159
158
  return [headline, "", ...guidance].join("\n");
160
159
  }
@@ -183,9 +182,6 @@ function closeFd(fd) {
183
182
  // Best-effort cleanup; child process already owns its duplicated stdio fd.
184
183
  }
185
184
  }
186
- /**
187
- * Spawn the async runner process
188
- */
189
185
  const RUNNER_STARTUP_TIMEOUT_MS = 10_000;
190
186
  function waitForStartupInterval(delayMs = 20) {
191
187
  return new Promise((resolve) => setTimeout(resolve, delayMs));
@@ -287,6 +283,33 @@ function terminateRunnerBeforeProceed(pid) {
287
283
  }
288
284
  return !runnerIsAlive(pid);
289
285
  }
286
+ function parentPid(pid) {
287
+ let ppid;
288
+ if (process.platform === "linux") {
289
+ try {
290
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf-8");
291
+ ppid = Number(stat.slice(stat.lastIndexOf(")") + 1).trim().split(/\s+/)[1]);
292
+ }
293
+ catch {
294
+ return undefined;
295
+ }
296
+ }
297
+ else {
298
+ const result = spawnSync("ps", ["-o", "ppid=", "-p", String(pid)], { encoding: "utf-8" });
299
+ if (result.error || result.status !== 0)
300
+ return undefined;
301
+ ppid = Number(result.stdout.trim());
302
+ }
303
+ return Number.isSafeInteger(ppid) && ppid > 0 ? ppid : undefined;
304
+ }
305
+ /** The runner reports its own pid, so behind a launcher only a pid inside the spawned launcher's tree may be signalled. */
306
+ function isInProcessTree(pid, rootPid) {
307
+ for (let current = pid; current !== undefined && current > 1; current = parentPid(current)) {
308
+ if (current === rootPid)
309
+ return true;
310
+ }
311
+ return false;
312
+ }
290
313
  async function terminateRunnerBeforeProceedAsyncDefault(proc, processClosed) {
291
314
  for (const signal of ["SIGTERM", "SIGKILL"]) {
292
315
  if (proc.pid === undefined || !runnerIsAlive(proc.pid))
@@ -449,7 +472,7 @@ function spawnRunner(cfg, suffix, cwd, initialStatus, initialStatusPath, launchP
449
472
  // its own identity before it is allowed to proceed.
450
473
  const launcher = cfg.launcher;
451
474
  const bootId = launcher ? undefined : currentBootId();
452
- const launchConfig = { ...cfg, runnerProcessInstanceId, ...(launchBarrierToken ? { launchBarrierToken } : {}), ...(bootId ? { bootId } : {}) };
475
+ const launchConfig = { ...cfg, runnerProcessInstanceId, ...(launchBarrierToken ? { launchBarrierToken } : {}), ...(bootId ? { bootId } : {}), ...(waitToolName() !== DEFAULT_WAIT_TOOL_NAME ? { waitToolName: waitToolName() } : {}) };
453
476
  writePrivateAtomicJson(cfgPath, launchConfig);
454
477
  const command = binaryHost ?? nodeExecutable;
455
478
  const launchForStartup = launchConfig;
@@ -477,10 +500,12 @@ function spawnRunner(cfg, suffix, cwd, initialStatus, initialStatusPath, launchP
477
500
  if (identityPath)
478
501
  fs.rmSync(identityPath, { force: true });
479
502
  let runnerIdentity;
480
- // Wrapper exit is not runner exit, so only a reported runner in this namespace may be signalled.
503
+ // Wrapper exit is not runner exit, so only a reported runner in this namespace may be signalled, and only
504
+ // inside the spawned launcher's process tree. Otherwise the runner exits when proceed never arrives.
481
505
  const terminateBeforeProceed = (pid) => !launcher
482
506
  ? terminateRunnerBeforeProceed(pid)
483
- : runnerIdentity !== undefined && runnerIdentity.pidNamespaceScope === currentPidNamespaceScope() && terminateRunnerBeforeProceed(runnerIdentity.pid);
507
+ : runnerIdentity !== undefined && runnerIdentity.pidNamespaceScope === currentPidNamespaceScope()
508
+ && isInProcessTree(runnerIdentity.pid, pid) && terminateRunnerBeforeProceed(runnerIdentity.pid);
484
509
  const adoptRunnerIdentity = (pid, pidNamespaceScope) => {
485
510
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid < 1)
486
511
  return `Async runner reported an invalid process identity in '${launchAsyncDir}'.`;
@@ -928,7 +953,7 @@ export function buildAsyncRunnerSteps(id, params) {
928
953
  taskTemplate = taskTemplate.replace(/\{chain_dir\}/g, behaviorCwd ?? runnerCwd);
929
954
  const taskText = `${readInstructions.prefix}${taskTemplate}${progressInstructions.suffix}`;
930
955
  // A namespaced parallel output path is added to each child's task by the runner.
931
- const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a);
956
+ const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a, machine);
932
957
  const modelScopes = resolveModelScopesForAgent(ctx.modelScope, a.name, ctx.currentModel, ctx.scopedModelIds);
933
958
  const modelOrigin = resolveModelOrigin({ explicitModel: s.model, agentModel: a.model, parentModel: ctx.currentModel });
934
959
  const primaryModelFromParent = modelOrigin === "inherited";
@@ -987,7 +1012,8 @@ export function buildAsyncRunnerSteps(id, params) {
987
1012
  if (launchRuleError)
988
1013
  throw new AsyncStartValidationError(launchRuleError);
989
1014
  const fast = s.fast ?? params.fast ?? a.fast;
990
- const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
1015
+ // Admission already refused mandatory entries for a placed child, which skips the rest.
1016
+ const requiredExtensions = externalRunner || machine ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
991
1017
  const toolPlan = resolvePiLaunchToolPlan({
992
1018
  tools: a.tools,
993
1019
  excludeTools: a.excludeTools,
@@ -1230,9 +1256,6 @@ export function buildAsyncRunnerSteps(id, params) {
1230
1256
  throw error;
1231
1257
  }
1232
1258
  }
1233
- /**
1234
- * Execute a chain asynchronously
1235
- */
1236
1259
  export function executeAsyncChain(id, params) {
1237
1260
  const { chain, agents, ctx, cwd, maxOutput, artifactsDir, artifactConfig, shareEnabled, sessionRoot, sessionFilesByFlatIndex, thinkingOverridesByFlatIndex, maxSubagentDepth, worktreeSetupHook, worktreeSetupHookTimeoutMs, worktreeBaseDir, baseRef, worktreeProvider, worktreeBranchPrefix, controlConfig, controlIntercomTarget, childIntercomTarget, nestedRoute, } = params;
1238
1261
  const resultMode = params.resultMode ?? "chain";
@@ -1555,14 +1578,12 @@ export function executeAsyncChain(id, params) {
1555
1578
  };
1556
1579
  return spawnResultOrPromise instanceof Promise ? spawnResultOrPromise.then(finishSpawnResult) : finishSpawnResult(spawnResultOrPromise);
1557
1580
  }
1558
- /**
1559
- * Execute a single agent asynchronously
1560
- */
1561
1581
  export function workflowAwaitedAsyncResultPath(asyncDir) {
1562
1582
  return path.join(asyncDir, "workflow-result.json");
1563
1583
  }
1564
1584
  export function executeAsyncSingle(id, params) {
1565
- const { agent, agentConfig, ctx, cwd, maxOutput, artifactsDir, artifactConfig, shareEnabled, sessionRoot, sessionFile, maxSubagentDepth, worktreeSetupHook, worktreeSetupHookTimeoutMs, worktreeBaseDir, baseRef, worktreeProvider, worktreeBranchPrefix, controlConfig, controlIntercomTarget, childIntercomTarget, nestedRoute, } = params;
1585
+ const { agent, ctx, cwd, maxOutput, artifactsDir, artifactConfig, shareEnabled, sessionRoot, sessionFile, maxSubagentDepth, worktreeSetupHook, worktreeSetupHookTimeoutMs, worktreeBaseDir, baseRef, worktreeProvider, worktreeBranchPrefix, controlConfig, controlIntercomTarget, childIntercomTarget, nestedRoute, } = params;
1586
+ let agentConfig = params.agentConfig;
1566
1587
  let lane;
1567
1588
  try {
1568
1589
  lane = normalizeWorkflowLaneMetadata(params.lane, "lane");
@@ -1632,6 +1653,13 @@ export function executeAsyncSingle(id, params) {
1632
1653
  if (resolvedLauncher.error)
1633
1654
  return formatAsyncStartError("single", resolvedLauncher.error);
1634
1655
  const launcher = resolvedLauncher.launcher;
1656
+ if (params.requireLauncher) {
1657
+ const required = checkRequiredRunnerLauncher(agentConfig, launcher?.name, params.requireLauncher);
1658
+ if (required.error !== undefined)
1659
+ return formatAsyncStartError("single", required.error);
1660
+ // The launch records the digest it checked, not a second hash of an agent file that may have changed since.
1661
+ agentConfig = { ...agentConfig, definitionDigest: required.definitionDigest };
1662
+ }
1635
1663
  const registeredExtensions = resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1636
1664
  try {
1637
1665
  assertRequiredChildExtensionsAdmitted([params.requiredExtensions, ctx.childRuntime?.requiredExtensions, registeredExtensions], { agent: agentConfig.name, runnerType: agentConfig.runner?.type, machine: requestedMachine });
@@ -1698,7 +1726,7 @@ export function executeAsyncSingle(id, params) {
1698
1726
  const validationError = validateFileOnlyOutputMode(outputMode, outputPath, `Async single run (${agent})`);
1699
1727
  if (validationError)
1700
1728
  return formatAsyncStartError("single", validationError);
1701
- const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, agentConfig);
1729
+ const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, agentConfig, machine);
1702
1730
  // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
1703
1731
  // absolute paths pass through; relative paths resolve against the child cwd.
1704
1732
  const reads = params.reads !== undefined ? params.reads : agentConfig.defaultReads ?? false;
@@ -1803,7 +1831,8 @@ export function executeAsyncSingle(id, params) {
1803
1831
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1804
1832
  }
1805
1833
  }
1806
- const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
1834
+ // Admission already refused mandatory entries for a placed child, which skips the rest.
1835
+ const requiredExtensions = externalRunner || machine ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
1807
1836
  const toolPlan = resolvePiLaunchToolPlan({
1808
1837
  tools: agentConfig.tools,
1809
1838
  excludeTools: agentConfig.excludeTools,
@@ -1851,6 +1880,7 @@ export function executeAsyncSingle(id, params) {
1851
1880
  agentContract: params.agentContract,
1852
1881
  });
1853
1882
  const recoveryAgentConfig = params.recoveryAgentConfig ?? agentConfig;
1883
+ const requiredLauncher = params.requireLauncher ?? params.carriedRequiredLauncher;
1854
1884
  const recoveryDescriptor = {
1855
1885
  ...(ctx.modelResponseAliases ? { modelResponseAliases: ctx.modelResponseAliases } : {}),
1856
1886
  version: 1,
@@ -1860,6 +1890,10 @@ export function executeAsyncSingle(id, params) {
1860
1890
  ...(requiredExtensions.length > 0 ? { requiredExtensions } : {}),
1861
1891
  runFanoutBudget,
1862
1892
  sourceRunId: id,
1893
+ ...(ctx.currentSessionId ? { sessionId: ctx.currentSessionId } : {}),
1894
+ // The worktree the runner will create, fixed here from launch inputs (the runner's own naming call).
1895
+ ...(managedWorktreeProvider === "native" ? { managedWorktree: { provider: "native", cwd: instructionCwd } } : {}),
1896
+ ...(managedWorktreeProvider === "worktrunk" ? { managedWorktree: { provider: "worktrunk", branch: buildWorktreeNaming({ runId: `${id}-s0`, index: 0, agent, label: lane?.key ?? params.workflowKey, task: taskText, branchPrefix: worktreeBranchPrefix }).requestedBranch } } : {}),
1863
1897
  ...(params.agentContract ? { agentContract: params.agentContract } : {}),
1864
1898
  agent,
1865
1899
  launchResolvedExtensions,
@@ -1897,7 +1931,8 @@ export function executeAsyncSingle(id, params) {
1897
1931
  ...(params.context ? { context: params.context } : {}),
1898
1932
  ...(params.intercomBridge !== undefined ? { intercomBridge: params.intercomBridge } : {}),
1899
1933
  ...(params.baseRef !== undefined ? { baseRef: params.baseRef } : {}),
1900
- ...(launcher ? { launcher: launcher.name } : {}),
1934
+ launcher: launcher ? launcher.name : null,
1935
+ ...(requiredLauncher ? { requiredLauncher } : {}),
1901
1936
  ...(deadlineAt !== undefined ? { absoluteDeadlineAt: deadlineAt } : {}),
1902
1937
  ...(resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {}),
1903
1938
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, recoveryAgentConfig.maxSubagentDepth),
@@ -1910,7 +1945,7 @@ export function executeAsyncSingle(id, params) {
1910
1945
  };
1911
1946
  if (!externalRunner) {
1912
1947
  try {
1913
- writePrivateAtomicJson(path.join(asyncDir, "recovery-descriptor.json"), recoveryDescriptor);
1948
+ writePrivateAtomicJson(recoveryDescriptorPath(path.dirname(asyncDir), id), recoveryDescriptor);
1914
1949
  }
1915
1950
  catch (error) {
1916
1951
  return formatAsyncStartError("single", `Failed to persist async recovery descriptor for '${id}': ${error instanceof Error ? error.message : String(error)}`);
@@ -16,6 +16,7 @@ import { validHostStepNodes } from "../shared/host-step-status.js";
16
16
  import { readProcessTerminal } from "./process-terminal.js";
17
17
  import { withCachedUiContext } from "../../shared/extension-context.js";
18
18
  import { OWNING_SESSION_COMPLETION_OWNER } from "../../shared/completion-owner.js";
19
+ import { ownerSessionIds } from "../shared/run-ownership.js";
19
20
  const CONTROL_EVENT_READ_CHUNK_BYTES = 64 * 1024;
20
21
  const MAX_CONTROL_EVENT_LINE_BYTES = 1024 * 1024;
21
22
  const CONTROL_EVENT_SCAN_WINDOW_BYTES = 2 * 1024 * 1024;
@@ -746,7 +747,18 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
746
747
  if (now >= nextLivenessAt) {
747
748
  nextLivenessAt = now + livenessIntervalMs;
748
749
  let widgetChanged = false;
750
+ // A session reopened in this process takes its runs back from the session that replaced it.
751
+ const owners = state.currentSessionId ? ownerSessionIds(state.currentSessionId) : undefined;
749
752
  for (const job of state.asyncJobs.values()) {
753
+ if (owners && job.sessionId !== undefined && !owners.has(job.sessionId)) {
754
+ cancelCleanup(job.asyncId);
755
+ closeJobWatcher(job.asyncId);
756
+ state.asyncJobs.delete(job.asyncId);
757
+ state.fleetJobs?.delete(job.asyncId);
758
+ options.onJobCleanup?.(job.asyncId);
759
+ widgetChanged = true;
760
+ continue;
761
+ }
750
762
  watchJob(job);
751
763
  if (refreshJob(job))
752
764
  widgetChanged = true;
@@ -51,8 +51,9 @@ export declare function findAsyncRunPrefixMatches(prefix: string, asyncDirRoot:
51
51
  location: AsyncRunLocation;
52
52
  }>;
53
53
  export declare function resolveAsyncRunLocation(params: AsyncResumeParams, asyncDirRoot: string, resultsDir: string): AsyncRunLocation;
54
+ /** A workflow-mode target has a ceiling only when its parent-owned launch record exists (resolveAsyncResumeTarget). */
54
55
  export declare function asyncReviveRequiresRecoveryDescriptor(target: Pick<AsyncResumeTarget, "recoveryDescriptor" | "mode" | "sessionFile" | "capabilityCeiling">): boolean;
55
- export declare function readAsyncRecoveryDescriptor(asyncDir: string | undefined): SteeringRecoveryDescriptor | undefined;
56
+ export declare function readAsyncRecoveryDescriptor(runsRoot: string, runId: string): SteeringRecoveryDescriptor | undefined;
56
57
  export declare function resolveAsyncResumeTarget(params: AsyncResumeParams, deps?: AsyncResumeDeps, options?: AsyncResumeOptions): AsyncResumeTarget;
57
58
  export declare function applySteeringRecoveryAgentConfig(agentConfig: AgentConfig, descriptor: SteeringRecoveryDescriptor): AgentConfig;
58
59
  export declare function buildRevivedAsyncTask(target: AsyncResumeTarget, message: string): string;
@@ -13,11 +13,13 @@ import { reconcileAsyncRun } from "./stale-run-reconciler.js";
13
13
  import { resultFilePath, resultPayloadPathForIndexedRun } from "./result-files.js";
14
14
  import { canScanAsyncRunPrefix, MIN_SAFE_ASYNC_RUN_PREFIX_LENGTH } from "./run-id-query.js";
15
15
  import { parallelHandoffPath, resolveRetainedWorktreeCwd } from "../shared/parallel-handoff.js";
16
- import { normalizeWorktreeBaseRef } from "../shared/worktree.js";
16
+ import { findListedWorktreeAgentCwd, findListedWorktreeOnBranch, isComparablePathInside, normalizeWorktreeBaseRef } from "../shared/worktree.js";
17
17
  import { intersectThinkingCeilings, parseThinkingLevel } from "../../shared/thinking-ceiling.js";
18
18
  import { assertWorkflowGraphHostSteps } from "../shared/host-step-status.js";
19
19
  import { validateIntercomBridgeConfig } from "../../intercom/intercom-bridge.js";
20
20
  import { validateModelResponseAliases } from "../../shared/model-response-aliases.js";
21
+ import { readWorkflowLaunchRecord } from "../../workflows/workflow-launch-record.js";
22
+ import { recoveryDescriptorPath } from "../shared/run-launch-folder.js";
21
23
  function getErrorMessage(error) {
22
24
  return error instanceof Error ? error.message : String(error);
23
25
  }
@@ -251,6 +253,7 @@ function normalizeRecoveryAcceptance(value, descriptorPath) {
251
253
  throw new Error(`Invalid async recovery descriptor '${descriptorPath}': ${errors.join(" ")}`);
252
254
  return value;
253
255
  }
256
+ /** A workflow-mode target has a ceiling only when its parent-owned launch record exists (resolveAsyncResumeTarget). */
254
257
  export function asyncReviveRequiresRecoveryDescriptor(target) {
255
258
  if (target.recoveryDescriptor)
256
259
  return false;
@@ -263,10 +266,8 @@ function resumeTargetMode(status, result) {
263
266
  return result.mode;
264
267
  return undefined;
265
268
  }
266
- export function readAsyncRecoveryDescriptor(asyncDir) {
267
- if (!asyncDir)
268
- return undefined;
269
- const descriptorPath = path.join(asyncDir, "recovery-descriptor.json");
269
+ export function readAsyncRecoveryDescriptor(runsRoot, runId) {
270
+ const descriptorPath = recoveryDescriptorPath(runsRoot, runId);
270
271
  if (!fs.existsSync(descriptorPath))
271
272
  return undefined;
272
273
  let value;
@@ -284,7 +285,7 @@ export function readAsyncRecoveryDescriptor(asyncDir) {
284
285
  "subagentOnlyExtensions", "mcpDirectTools", "excludeTools", "mutationTools", "systemPrompt", "systemPromptMode", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "skills",
285
286
  "skillPath", "agentFilePath", "memory", "outputPath", "outputMode", "structuredOutputSchema", "acceptance", "sessionDir", "artifactConfig",
286
287
  "artifactsDir", "maxOutput", "controlConfig", "context", "intercomBridge", "absoluteDeadlineAt", "initialTurnBudget", "initialToolBudget", "maxSubagentDepth", "share", "capabilityCeiling",
287
- "launchResolvedExtensions", "runFanoutBudget", "lane", "baseRef", "launcher",
288
+ "launchResolvedExtensions", "runFanoutBudget", "lane", "baseRef", "launcher", "requiredLauncher", "sessionId", "managedWorktree",
288
289
  "extensionBindings",
289
290
  "requiredExtensions",
290
291
  ]);
@@ -299,8 +300,16 @@ export function readAsyncRecoveryDescriptor(asyncDir) {
299
300
  }
300
301
  if (parsed.version !== 1)
301
302
  throw new Error(`Invalid async recovery descriptor '${descriptorPath}': version must be 1.`);
302
- if (parsed.launcher !== undefined && (typeof parsed.launcher !== "string" || !RUNNER_LAUNCHER_NAME_PATTERN.test(parsed.launcher)))
303
- throw new Error(`Invalid async recovery descriptor '${descriptorPath}': launcher must be a launcher name.`);
303
+ if (parsed.launcher !== undefined && parsed.launcher !== null && (typeof parsed.launcher !== "string" || !RUNNER_LAUNCHER_NAME_PATTERN.test(parsed.launcher)))
304
+ throw new Error(`Invalid async recovery descriptor '${descriptorPath}': launcher must be a launcher name or null.`);
305
+ if (parsed.requiredLauncher !== undefined) {
306
+ const required = parsed.requiredLauncher;
307
+ if (!required || typeof required !== "object" || Array.isArray(required) || Object.keys(required).some((key) => key !== "name" && key !== "definitionDigest")
308
+ || typeof required.name !== "string" || !RUNNER_LAUNCHER_NAME_PATTERN.test(required.name)
309
+ || typeof required.definitionDigest !== "string" || !/^[0-9a-f]{64}$/.test(required.definitionDigest)) {
310
+ throw new Error(`Invalid async recovery descriptor '${descriptorPath}': requiredLauncher must be { name, definitionDigest }.`);
311
+ }
312
+ }
304
313
  try {
305
314
  parsed.runFanoutBudget = validateRunFanoutBudgetDescriptor(parsed.runFanoutBudget);
306
315
  }
@@ -372,7 +381,14 @@ export function readAsyncRecoveryDescriptor(asyncDir) {
372
381
  }
373
382
  if (parsed.systemPrompt !== undefined && typeof parsed.systemPrompt !== "string")
374
383
  throw new Error(`Invalid async recovery descriptor '${descriptorPath}': systemPrompt must be a string.`);
375
- for (const field of ["launchContractDigest", "sessionFile", "model", "modelProvider", "thinking", "agentFilePath", "outputPath", "sessionDir", "artifactsDir"]) {
384
+ if (parsed.managedWorktree !== undefined) {
385
+ const worktree = parsed.managedWorktree;
386
+ const valid = !!worktree && typeof worktree === "object" && !Array.isArray(worktree) && ((worktree.provider === "native" && typeof worktree.cwd === "string" && path.isAbsolute(worktree.cwd) && Object.keys(worktree).length === 2)
387
+ || (worktree.provider === "worktrunk" && typeof worktree.branch === "string" && !!worktree.branch.trim() && Object.keys(worktree).length === 2));
388
+ if (!valid)
389
+ throw new Error(`Invalid async recovery descriptor '${descriptorPath}': managedWorktree is invalid.`);
390
+ }
391
+ for (const field of ["sessionId", "launchContractDigest", "sessionFile", "model", "modelProvider", "thinking", "agentFilePath", "outputPath", "sessionDir", "artifactsDir"]) {
376
392
  if (parsed[field] !== undefined && (typeof parsed[field] !== "string" || !parsed[field].trim()))
377
393
  throw new Error(`Invalid async recovery descriptor '${descriptorPath}': ${field} must be a non-empty string.`);
378
394
  }
@@ -457,6 +473,27 @@ export function readAsyncRecoveryDescriptor(asyncDir) {
457
473
  parsed.acceptance = normalizeRecoveryAcceptance(parsed.acceptance, descriptorPath);
458
474
  return parsed;
459
475
  }
476
+ /**
477
+ * handoff.json sits in the run directory, so its worktree cwd must be the one the launch chose: the
478
+ * native path the parent computed, or a worktree git itself lists on the requested Worktrunk branch.
479
+ */
480
+ function assertLaunchedWorktreeCwd(runId, launchCwd, launched, handoffCwd) {
481
+ const listed = launched.provider === "native" ? undefined : findListedWorktreeOnBranch(launchCwd, launched.branch);
482
+ const matches = launched.provider === "native"
483
+ ? isComparablePathInside(launched.cwd, handoffCwd) && isComparablePathInside(handoffCwd, launched.cwd)
484
+ : listed !== undefined && isComparablePathInside(listed, handoffCwd);
485
+ if (!matches)
486
+ throw new Error(`Async run '${runId}' managed worktree ${handoffCwd} is not the worktree its launch created.`);
487
+ return handoffCwd;
488
+ }
489
+ /** A run launched in a worktree resumes in it, never in the source checkout, even when handoff.json is missing. */
490
+ function launchedWorktreeCwdWithoutHandoff(runId, launchCwd, launched) {
491
+ const cwd = launched.provider === "native" ? launched.cwd : findListedWorktreeAgentCwd(launchCwd, launched.branch);
492
+ if (cwd === undefined || !fs.statSync(cwd, { throwIfNoEntry: false })?.isDirectory()) {
493
+ throw new Error(`Async run '${runId}' ran in a managed worktree (${launched.provider === "native" ? launched.cwd : `branch ${launched.branch}`}) that no longer exists; it cannot resume in the source checkout.`);
494
+ }
495
+ return cwd;
496
+ }
460
497
  function validateResumeSessionFile(runId, sessionFile) {
461
498
  if (path.extname(sessionFile) !== ".jsonl")
462
499
  throw new Error(`Async run '${runId}' session file must be a .jsonl file: ${sessionFile}`);
@@ -487,20 +524,40 @@ export function resolveAsyncResumeTarget(params, deps = {}, options = {}) {
487
524
  const requested = params.id ?? params.runId;
488
525
  throw new Error(requested ? `Async run not found for '${requested}'.` : "Async run not found. Provide id or dir.");
489
526
  }
527
+ // A run directory is always named for its run, so a status file naming another run is refused, and
528
+ // before reconciling: its repair publishes a result under the status file's run id.
529
+ if (location.asyncDir) {
530
+ let recordedRunId;
531
+ try {
532
+ recordedRunId = JSON.parse(fs.readFileSync(path.join(location.asyncDir, "status.json"), "utf-8")).runId;
533
+ }
534
+ catch { /* missing or unreadable: validateStatusForResume reports it */ }
535
+ if (typeof recordedRunId === "string" && recordedRunId !== path.basename(location.asyncDir))
536
+ throw new Error(`Async run '${path.basename(location.asyncDir)}' has a status file for a different run '${recordedRunId}'.`);
537
+ }
490
538
  const reconciliation = location.asyncDir
491
539
  ? reconcileAsyncRun(location.asyncDir, { resultsDir, kill: deps.kill, now: deps.now })
492
540
  : undefined;
493
541
  const status = reconciliation?.status ?? null;
494
542
  validateStatusForResume(status, location.asyncDir ? path.join(location.asyncDir, "status.json") : "status.json");
495
- const recoveryDescriptor = readAsyncRecoveryDescriptor(location.asyncDir ?? undefined);
543
+ // Records are trusted only for a run folder directly under the runs root: `dir` may name a
544
+ // runs-shaped tree a run built inside its own folder.
545
+ const directRunFolder = location.asyncDir !== null && path.dirname(location.asyncDir) === path.resolve(asyncDirRoot);
546
+ const recoveryDescriptor = directRunFolder ? readAsyncRecoveryDescriptor(asyncDirRoot, path.basename(location.asyncDir)) : undefined;
496
547
  const result = location.resultPath ? readResultFile(location.resultPath) : undefined;
497
- const runId = status?.runId ?? result?.runId ?? result?.id ?? location.resolvedId ?? (location.asyncDir ? path.basename(location.asyncDir) : "unknown");
498
- const mode = resumeTargetMode(status, result);
499
- if (options.sessionId && ((status && !ownsRun(options.sessionId, status.sessionId)) || (result && !ownsRun(options.sessionId, result.sessionId)))) {
548
+ const runId = location.asyncDir ? path.basename(location.asyncDir) : result?.runId ?? result?.id ?? location.resolvedId ?? "unknown";
549
+ // Only a single run writes a recovery descriptor. When one exists, the run's identity (agent,
550
+ // session, cwd, model, ceilings) comes from it alone: status.json and the shared results directory
551
+ // are writable by a run behind a runner launcher.
552
+ const mode = recoveryDescriptor ? "single" : resumeTargetMode(status, result);
553
+ const notOwned = recoveryDescriptor
554
+ ? !ownsRun(options.sessionId, recoveryDescriptor.sessionId)
555
+ : (status && !ownsRun(options.sessionId, status.sessionId)) || (result && !ownsRun(options.sessionId, result.sessionId));
556
+ if (options.sessionId && notOwned) {
500
557
  throw new Error(`Async run '${runId}' was not found in the active session.`);
501
558
  }
502
559
  if (recoveryDescriptor && recoveryDescriptor.sourceRunId !== runId)
503
- throw new Error(`Async run '${runId}' has a recovery descriptor for a different source run.`);
560
+ throw new Error(`Async run '${runId}' has a recovery descriptor for a different source run '${recoveryDescriptor.sourceRunId}'.`);
504
561
  const state = status?.state ?? (result ? resultState(result) : undefined);
505
562
  if (!state)
506
563
  throw new Error(`Status file not found for async run '${runId}'.`);
@@ -519,18 +576,18 @@ export function resolveAsyncResumeTarget(params, deps = {}, options = {}) {
519
576
  throw new Error(`Async run '${runId}' has ${stepCount} children. Index ${requestedIndex} is out of range.`);
520
577
  const selectedStep = statusSteps[requestedIndex];
521
578
  if (selectedStep?.status === "running") {
522
- const capabilityCeiling = intersectSubagentCapabilityCeilings(status?.capabilityCeiling, selectedStep.capabilityCeiling);
579
+ const capabilityCeiling = recoveryDescriptor ? recoveryDescriptor.capabilityCeiling : intersectSubagentCapabilityCeilings(status?.capabilityCeiling, selectedStep.capabilityCeiling);
523
580
  return {
524
581
  kind: "live",
525
582
  runId,
526
583
  asyncDir: location.asyncDir ?? undefined,
527
584
  state,
528
585
  ...(mode ? { mode } : {}),
529
- agent: selectedStep.agent,
586
+ agent: recoveryDescriptor?.agent ?? selectedStep.agent,
530
587
  ...(selectedStep.sessionName ?? result?.results?.[requestedIndex]?.sessionName ? { sessionName: selectedStep.sessionName ?? result?.results?.[requestedIndex]?.sessionName } : {}),
531
588
  index: requestedIndex,
532
589
  cwd: status?.cwd ?? result?.cwd,
533
- sessionFile: selectedStep.sessionFile ?? status?.sessionFile ?? result?.sessionFile,
590
+ sessionFile: recoveryDescriptor ? recoveryDescriptor.sessionFile : selectedStep.sessionFile ?? status?.sessionFile ?? result?.sessionFile,
534
591
  model: selectedStep.model,
535
592
  thinking: selectedStep.thinking,
536
593
  launchContractDigest: selectedStep.launchContractDigest ?? result?.results?.[requestedIndex]?.launchContractDigest ?? result?.launchContractDigest ?? recoveryDescriptor?.launchContractDigest,
@@ -554,18 +611,18 @@ export function resolveAsyncResumeTarget(params, deps = {}, options = {}) {
554
611
  if (!selected) {
555
612
  throw new Error(`Async run '${runId}' has ${running.length} running children. Provide index to choose one.`);
556
613
  }
557
- const capabilityCeiling = intersectSubagentCapabilityCeilings(status?.capabilityCeiling, selected.step.capabilityCeiling);
614
+ const capabilityCeiling = recoveryDescriptor ? recoveryDescriptor.capabilityCeiling : intersectSubagentCapabilityCeilings(status?.capabilityCeiling, selected.step.capabilityCeiling);
558
615
  return {
559
616
  kind: "live",
560
617
  runId,
561
618
  asyncDir: location.asyncDir ?? undefined,
562
619
  state,
563
620
  ...(mode ? { mode } : {}),
564
- agent: selected.step.agent,
621
+ agent: recoveryDescriptor?.agent ?? selected.step.agent,
565
622
  ...(selected.step.sessionName ?? result?.results?.[selected.index]?.sessionName ? { sessionName: selected.step.sessionName ?? result?.results?.[selected.index]?.sessionName } : {}),
566
623
  index: selected.index,
567
624
  cwd: status?.cwd ?? result?.cwd,
568
- sessionFile: selected.step.sessionFile ?? status?.sessionFile ?? result?.sessionFile,
625
+ sessionFile: recoveryDescriptor ? recoveryDescriptor.sessionFile : selected.step.sessionFile ?? status?.sessionFile ?? result?.sessionFile,
569
626
  model: selected.step.model,
570
627
  thinking: selected.step.thinking,
571
628
  launchContractDigest: selected.step.launchContractDigest ?? result?.results?.[selected.index]?.launchContractDigest ?? result?.launchContractDigest ?? recoveryDescriptor?.launchContractDigest,
@@ -589,27 +646,41 @@ export function resolveAsyncResumeTarget(params, deps = {}, options = {}) {
589
646
  if (selectedStatusStep?.status === "stopped" || selectedStatusStep?.stopped === true) {
590
647
  throw new Error(`Async run '${runId}' child ${index} was stopped and cannot be resumed. Start a new run instead.`);
591
648
  }
592
- const agent = selectedStatusStep?.agent ?? resultSteps[index]?.agent ?? result?.agent;
649
+ const agent = recoveryDescriptor ? recoveryDescriptor.agent : selectedStatusStep?.agent ?? resultSteps[index]?.agent ?? result?.agent;
593
650
  if (!agent)
594
651
  throw new Error(`Could not determine child agent for async run '${runId}'.`);
595
- if (recoveryDescriptor && recoveryDescriptor.agent !== agent)
596
- throw new Error(`Async run '${runId}' has a recovery descriptor for '${recoveryDescriptor.agent}', not '${agent}'.`);
597
- const sessionFile = statusSteps[index]?.sessionFile
598
- ?? resultSteps[index]?.sessionFile
599
- ?? (stepCount === 1 ? status?.sessionFile ?? result?.sessionFile : undefined);
652
+ const sessionFile = recoveryDescriptor
653
+ ? recoveryDescriptor.sessionFile
654
+ : statusSteps[index]?.sessionFile
655
+ ?? resultSteps[index]?.sessionFile
656
+ ?? (stepCount === 1 ? status?.sessionFile ?? result?.sessionFile : undefined);
600
657
  if (!sessionFile && requireSessionFile)
601
658
  throw new Error(`Async run '${runId}' child ${index} does not have a persisted session file to resume from.`);
602
659
  const resolvedSessionFile = sessionFile ? validateResumeSessionFile(runId, sessionFile) : undefined;
603
- const stepModel = statusSteps[index]?.launchModel ?? statusSteps[index]?.model ?? resultSteps[index]?.model ?? (stepCount === 1 ? result?.model : undefined);
604
- const stepThinking = statusSteps[index]?.thinking ?? resultSteps[index]?.thinking ?? (stepCount === 1 ? result?.thinking : undefined);
605
- const thinkingCeiling = statusSteps[index]?.thinkingCeiling ?? (stepCount === 1 ? recoveryDescriptor?.thinkingCeiling : undefined);
606
- const capabilityCeiling = mode === "workflow"
607
- ? intersectSubagentCapabilityCeilings(status?.admissionCapabilityCeiling, result?.admissionCapabilityCeiling)
608
- : intersectSubagentCapabilityCeilings(status?.capabilityCeiling, statusSteps[index]?.capabilityCeiling, result?.capabilityCeiling, resultSteps[index]?.capabilityCeiling);
609
- const managedWorktreeCwd = location.asyncDir
660
+ const stepModel = recoveryDescriptor ? recoveryDescriptor.model : statusSteps[index]?.launchModel ?? statusSteps[index]?.model ?? resultSteps[index]?.model ?? (stepCount === 1 ? result?.model : undefined);
661
+ const stepThinking = recoveryDescriptor ? recoveryDescriptor.thinking : statusSteps[index]?.thinking ?? resultSteps[index]?.thinking ?? (stepCount === 1 ? result?.thinking : undefined);
662
+ const thinkingCeiling = recoveryDescriptor ? recoveryDescriptor.thinkingCeiling : statusSteps[index]?.thinkingCeiling;
663
+ // A workflow's admission ceiling comes only from the parent-owned launch record of its run directory:
664
+ // a run behind a launcher can write its own status.json (including a directory nested in it) and the
665
+ // shared results directory. Without a record there is no ceiling, so a revive without a recovery
666
+ // descriptor is refused.
667
+ const workflowLaunch = mode === "workflow" && directRunFolder
668
+ ? readWorkflowLaunchRecord(asyncDirRoot, runId)
669
+ : undefined;
670
+ const capabilityCeiling = recoveryDescriptor
671
+ ? recoveryDescriptor.capabilityCeiling
672
+ : mode === "workflow"
673
+ ? (workflowLaunch?.ok ? workflowLaunch.record.admissionCapabilityCeiling : undefined)
674
+ : intersectSubagentCapabilityCeilings(status?.capabilityCeiling, statusSteps[index]?.capabilityCeiling, result?.capabilityCeiling, resultSteps[index]?.capabilityCeiling);
675
+ const handoffWorktreeCwd = location.asyncDir && (!recoveryDescriptor || recoveryDescriptor.managedWorktree)
610
676
  ? resolveRetainedWorktreeCwd(parallelHandoffPath(location.asyncDir), runId, index, statusSteps[index]?.worktreePath)
611
677
  : undefined;
612
- const resumeCwd = validateResumeCwd(runId, managedWorktreeCwd ?? status?.cwd ?? result?.cwd ?? recoveryDescriptor?.cwd);
678
+ const managedWorktreeCwd = recoveryDescriptor?.managedWorktree
679
+ ? handoffWorktreeCwd
680
+ ? assertLaunchedWorktreeCwd(runId, recoveryDescriptor.cwd, recoveryDescriptor.managedWorktree, handoffWorktreeCwd)
681
+ : launchedWorktreeCwdWithoutHandoff(runId, recoveryDescriptor.cwd, recoveryDescriptor.managedWorktree)
682
+ : handoffWorktreeCwd;
683
+ const resumeCwd = validateResumeCwd(runId, managedWorktreeCwd ?? (recoveryDescriptor ? recoveryDescriptor.cwd : status?.cwd ?? result?.cwd));
613
684
  return {
614
685
  kind: "revive",
615
686
  runId,
@@ -624,9 +695,10 @@ export function resolveAsyncResumeTarget(params, deps = {}, options = {}) {
624
695
  ...(resolvedSessionFile ? { sessionFile: resolvedSessionFile } : {}),
625
696
  ...(stepModel ? { model: stepModel } : {}),
626
697
  ...(stepThinking ? { thinking: stepThinking } : {}),
627
- launchContractDigest: statusSteps[index]?.launchContractDigest ?? resultSteps[index]?.launchContractDigest ?? result?.launchContractDigest ?? recoveryDescriptor?.launchContractDigest,
628
- ...(statusSteps[index]?.runner ? { runner: statusSteps[index].runner } : {}),
629
- ...(statusSteps[index]?.externalJob ? { externalJob: statusSteps[index].externalJob } : {}),
698
+ launchContractDigest: recoveryDescriptor ? recoveryDescriptor.launchContractDigest : statusSteps[index]?.launchContractDigest ?? resultSteps[index]?.launchContractDigest ?? result?.launchContractDigest,
699
+ // External runners write no recovery descriptor.
700
+ ...(!recoveryDescriptor && statusSteps[index]?.runner ? { runner: statusSteps[index].runner } : {}),
701
+ ...(!recoveryDescriptor && statusSteps[index]?.externalJob ? { externalJob: statusSteps[index].externalJob } : {}),
630
702
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
631
703
  ...(thinkingCeiling ? { thinkingCeiling } : {}),
632
704
  ...(recoveryDescriptor ? { recoveryDescriptor } : {}),
@@ -659,8 +731,9 @@ export function applySteeringRecoveryAgentConfig(agentConfig, descriptor) {
659
731
  output: descriptor.outputPath,
660
732
  toolBudget: descriptor.initialToolBudget,
661
733
  maxSubagentDepth: descriptor.maxSubagentDepth,
662
- // The recorded launcher wins over the current agent file, including recorded absence.
663
- launcher: descriptor.launcher,
734
+ // A recorded launcher, or a recorded null (ran unwrapped), wins over the current agent file.
735
+ // A missing field says nothing, so the run never loses the agent file's launcher.
736
+ launcher: descriptor.launcher === undefined ? agentConfig.launcher : descriptor.launcher ?? undefined,
664
737
  };
665
738
  }
666
739
  export function buildRevivedAsyncTask(target, message) {
@@ -11,6 +11,7 @@ import { REVIVAL_ORIGIN_FILE } from "../../workflows/workflow-revival.js";
11
11
  import { ACTIVE_RUN_INDEX_DIR } from "./active-run-index.js";
12
12
  import { encodeIndexSegment } from "./index-segment.js";
13
13
  import { reconcileAsyncRun } from "./stale-run-reconciler.js";
14
+ import { recoveryDescriptorPath, runLaunchDir } from "../shared/run-launch-folder.js";
14
15
  export const ASYNC_RETENTION_DAYS = 30;
15
16
  export const ASYNC_RETENTION_BATCH_SIZE = 100;
16
17
  export const ASYNC_RETENTION_DELAY_MS = 60_000;
@@ -106,7 +107,8 @@ function hasResumableContract(runDir, status) {
106
107
  const statusSessionFiles = [status.sessionFile, ...(status.steps ?? []).map((step) => step.sessionFile)];
107
108
  if (statusSessionFiles.some(existingRegularFile))
108
109
  return true;
109
- const descriptorPath = path.join(runDir, "recovery-descriptor.json");
110
+ // runDir may be a tombstone; the launch folder is keyed by the run id.
111
+ const descriptorPath = recoveryDescriptorPath(path.dirname(runDir), status.runId);
110
112
  if (!fs.existsSync(descriptorPath))
111
113
  return false;
112
114
  const descriptor = readJson(descriptorPath);
@@ -793,6 +795,7 @@ export async function cleanupAsyncRetention(options) {
793
795
  }
794
796
  mutationStateChanged = true;
795
797
  fs.rmSync(runDir, { recursive: true });
798
+ fs.rmSync(runLaunchDir(options.asyncDirRoot, status.runId), { recursive: true, force: true });
796
799
  removeRunTombstoneMarker(maintenanceRoot, status.runId);
797
800
  result.reapedTombstones += 1;
798
801
  deletedIds.push(`run-tombstone:${status.runId}`);
@@ -824,6 +827,8 @@ export async function cleanupAsyncRetention(options) {
824
827
  continue;
825
828
  }
826
829
  fs.rmSync(tombstone, { recursive: true });
830
+ // Retention never deletes a workflow run, so this removes only a single run's recovery descriptor.
831
+ fs.rmSync(runLaunchDir(options.asyncDirRoot, status.runId), { recursive: true, force: true });
827
832
  removeRunTombstoneMarker(maintenanceRoot, status.runId);
828
833
  result.deletedRuns += 1;
829
834
  deletedIds.push(`run:${status.runId}`);