@vicary/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 (207) 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-F4ASL6OV.js → chunk-7MAE3DJV.js} +1 -1
  5. package/bundle/{chunk-7BWGNDNK.js → chunk-A7VJ5XXE.js} +196 -1183
  6. package/bundle/{chunk-DZDETGRJ.js → chunk-B3OOJJA6.js} +231 -182
  7. package/bundle/{chunk-4E7BKDTX.js → chunk-CS4O36CZ.js} +11 -156
  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-XDQORLZ5.js → chunk-HS4WPO6B.js} +15 -6
  12. package/bundle/chunk-HXRB42AF.js +108 -0
  13. package/bundle/{chunk-4NIY3BE6.js → chunk-JHBQ7N2L.js} +2 -2
  14. package/bundle/{chunk-J5YL7LYR.js → chunk-JO67XSKD.js} +59 -27
  15. package/bundle/{chunk-C5P5CHYK.js → chunk-KDMFBYFM.js} +1 -1
  16. package/bundle/{chunk-V2BZYLEP.js → chunk-KEY3UQMQ.js} +7 -2
  17. package/bundle/{chunk-NENDSQUY.js → chunk-KZ34KQQH.js} +9 -6
  18. package/bundle/{chunk-AKOIVLA5.js → chunk-L2ENOFVZ.js} +76 -58
  19. package/bundle/{chunk-CGN2TVE7.js → chunk-LGMILZNE.js} +322 -18
  20. package/bundle/{chunk-L3WFKBEI.js → chunk-LTPH2DXH.js} +247 -153
  21. package/bundle/{chunk-2D52JFLF.js → chunk-N7B2KD74.js} +41 -117
  22. package/bundle/{chunk-PV63UFUR.js → chunk-O7CPL6H4.js} +183 -28
  23. package/bundle/{chunk-D3JAFGMO.js → chunk-PHZP3KHB.js} +1 -1
  24. package/bundle/{chunk-2DHZTCOL.js → chunk-PVIVCDG2.js} +2 -2
  25. package/bundle/{chunk-LFDBD4PW.js → chunk-QO75KJBT.js} +2 -2
  26. package/bundle/{chunk-VQVVHSY6.js → chunk-QZL2ZZPM.js} +22 -11
  27. package/bundle/{chunk-PALJGGYC.js → chunk-RV5OGHLO.js} +6 -3
  28. package/bundle/chunk-T5V5BRCL.js +1067 -0
  29. package/bundle/{chunk-LNRJCP2Y.js → chunk-UX4SCV5N.js} +337 -207
  30. package/bundle/{chunk-RWPNQZHS.js → chunk-VEZMZDTW.js} +212 -102
  31. package/bundle/{chunk-RSLHTEQV.js → chunk-YZBCREP5.js} +310 -101
  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 +18 -3
  38. package/docs/configuration.md +7 -7
  39. package/docs/extension-api.md +16 -1
  40. package/docs/observability.md +1 -1
  41. package/docs/tool-reference.md +1 -1
  42. package/docs/workflows.md +31 -3
  43. package/package.json +2 -2
  44. package/src/agents/agent-management.js +27 -11
  45. package/src/agents/agent-memory.d.ts +1 -4
  46. package/src/agents/agent-memory.js +1 -4
  47. package/src/agents/agents.d.ts +1 -3
  48. package/src/agents/agents.js +7 -6
  49. package/src/agents/frontmatter.js +1 -8
  50. package/src/agents/global-npm-root.d.ts +1 -0
  51. package/src/agents/global-npm-root.js +11 -3
  52. package/src/agents/skills.d.ts +0 -3
  53. package/src/agents/skills.js +0 -3
  54. package/src/extension/config.js +7 -1
  55. package/src/extension/herdr-pi-bridge.js +10 -2
  56. package/src/extension/index.d.ts +0 -13
  57. package/src/extension/index.js +43 -32
  58. package/src/extension/public-execution.d.ts +1 -0
  59. package/src/extension/public-execution.js +4 -0
  60. package/src/extension/reply-workflow-script.js +24 -4
  61. package/src/extension/schemas.d.ts +8 -3
  62. package/src/extension/schemas.js +6 -4
  63. package/src/extension/session-switch.d.ts +25 -0
  64. package/src/extension/session-switch.js +138 -0
  65. package/src/extension/subagent-guide.d.ts +1 -1
  66. package/src/extension/subagent-guide.js +1 -1
  67. package/src/extension/subagent-launch-tool.d.ts +25 -0
  68. package/src/extension/subagent-launch-tool.js +48 -0
  69. package/src/extension/tool-activation.js +25 -11
  70. package/src/extension/tool-description.js +6 -0
  71. package/src/inspectors/herdr/actions.d.ts +0 -1
  72. package/src/inspectors/herdr/actions.js +0 -1
  73. package/src/inspectors/session-roots-codec.d.ts +0 -1
  74. package/src/inspectors/session-roots-codec.js +0 -1
  75. package/src/inspectors/tmux/actions.d.ts +0 -1
  76. package/src/inspectors/tmux/actions.js +0 -1
  77. package/src/integrations/herdr-status.js +3 -8
  78. package/src/intercom/native-supervisor-channel.js +65 -9
  79. package/src/runs/background/async-execution.d.ts +5 -10
  80. package/src/runs/background/async-execution.js +63 -29
  81. package/src/runs/background/async-job-tracker.js +12 -0
  82. package/src/runs/background/async-resume.d.ts +2 -1
  83. package/src/runs/background/async-resume.js +112 -39
  84. package/src/runs/background/async-retention.js +6 -1
  85. package/src/runs/background/auto-drain.d.ts +0 -1
  86. package/src/runs/background/auto-drain.js +7 -6
  87. package/src/runs/background/boot-id.d.ts +1 -3
  88. package/src/runs/background/boot-id.js +1 -3
  89. package/src/runs/background/completion-batcher.d.ts +3 -4
  90. package/src/runs/background/completion-batcher.js +2 -3
  91. package/src/runs/background/control-channel.d.ts +0 -6
  92. package/src/runs/background/control-channel.js +0 -6
  93. package/src/runs/background/fleet-view.js +2 -3
  94. package/src/runs/background/notify.d.ts +0 -2
  95. package/src/runs/background/notify.js +0 -2
  96. package/src/runs/background/result-watcher.d.ts +1 -0
  97. package/src/runs/background/result-watcher.js +59 -29
  98. package/src/runs/background/resume-guidance.js +4 -2
  99. package/src/runs/background/retained-children.js +2 -1
  100. package/src/runs/background/run-child-session.d.ts +0 -1
  101. package/src/runs/background/run-child-session.js +1 -1
  102. package/src/runs/background/run-status.js +4 -3
  103. package/src/runs/background/scheduled-runs.d.ts +3 -1
  104. package/src/runs/background/scheduled-runs.js +13 -16
  105. package/src/runs/background/subagent-runner.d.ts +2 -4
  106. package/src/runs/background/subagent-runner.js +9 -6
  107. package/src/runs/background/subagent-wait.js +12 -15
  108. package/src/runs/background/wait-config.d.ts +2 -0
  109. package/src/runs/background/wait-config.js +17 -3
  110. package/src/runs/background/wait-tool.js +4 -2
  111. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  112. package/src/runs/background/workflow-terminal-proof.js +0 -1
  113. package/src/runs/foreground/execution.d.ts +0 -3
  114. package/src/runs/foreground/execution.js +17 -9
  115. package/src/runs/foreground/subagent-executor.d.ts +7 -8
  116. package/src/runs/foreground/subagent-executor.js +113 -44
  117. package/src/runs/shared/child-commands.js +15 -2
  118. package/src/runs/shared/child-hooks.d.ts +1 -7
  119. package/src/runs/shared/child-hooks.js +13 -5
  120. package/src/runs/shared/child-launch.js +6 -2
  121. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  122. package/src/runs/shared/child-session.d.ts +1 -1
  123. package/src/runs/shared/child-session.js +21 -2
  124. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  125. package/src/runs/shared/child-tool-plan.js +0 -1
  126. package/src/runs/shared/claude-code-adapter.js +11 -0
  127. package/src/runs/shared/external-cli-runner.js +26 -6
  128. package/src/runs/shared/herdr-connection.js +2 -1
  129. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  130. package/src/runs/shared/herdr-pane-host.js +17 -1
  131. package/src/runs/shared/herdr-placed-run.js +48 -22
  132. package/src/runs/shared/lane-metadata.d.ts +0 -1
  133. package/src/runs/shared/lane-metadata.js +0 -1
  134. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  135. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  136. package/src/runs/shared/model-resolution.d.ts +2 -2
  137. package/src/runs/shared/model-resolution.js +7 -1
  138. package/src/runs/shared/model-scope.d.ts +1 -5
  139. package/src/runs/shared/model-scope.js +1 -5
  140. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  141. package/src/runs/shared/mutation-evidence.js +52 -7
  142. package/src/runs/shared/nested-events.d.ts +1 -0
  143. package/src/runs/shared/nested-events.js +1 -1
  144. package/src/runs/shared/parallel-utils.d.ts +0 -1
  145. package/src/runs/shared/permissions.js +5 -3
  146. package/src/runs/shared/placement-host.d.ts +5 -1
  147. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  148. package/src/runs/shared/rex-pane-host.js +0 -2
  149. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  150. package/src/runs/shared/run-launch-folder.js +21 -0
  151. package/src/runs/shared/runner-launcher.d.ts +12 -1
  152. package/src/runs/shared/runner-launcher.js +16 -0
  153. package/src/runs/shared/single-output.d.ts +3 -3
  154. package/src/runs/shared/single-output.js +5 -3
  155. package/src/runs/shared/structured-output.d.ts +8 -0
  156. package/src/runs/shared/structured-output.js +30 -2
  157. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  158. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  159. package/src/runs/shared/tool-timeout.js +2 -1
  160. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  161. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  162. package/src/runs/shared/worktree.d.ts +3 -0
  163. package/src/runs/shared/worktree.js +20 -0
  164. package/src/shared/capacity-resilient-json.d.ts +1 -1
  165. package/src/shared/child-cache-retention.d.ts +1 -2
  166. package/src/shared/child-cache-retention.js +1 -2
  167. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  168. package/src/shared/fleet-transcript-reader.js +333 -0
  169. package/src/shared/formatters.d.ts +0 -18
  170. package/src/shared/formatters.js +0 -18
  171. package/src/shared/session-succession.d.ts +16 -1
  172. package/src/shared/session-succession.js +41 -2
  173. package/src/shared/session-warnings.d.ts +7 -0
  174. package/src/shared/session-warnings.js +26 -0
  175. package/src/shared/settings.d.ts +0 -23
  176. package/src/shared/settings.js +3 -35
  177. package/src/shared/types.d.ts +33 -17
  178. package/src/shared/types.js +0 -12
  179. package/src/shared/utils.d.ts +0 -14
  180. package/src/shared/utils.js +0 -22
  181. package/src/shared/wait-tool-name.d.ts +8 -0
  182. package/src/shared/wait-tool-name.js +13 -0
  183. package/src/slash/slash-commands.js +2 -1
  184. package/src/slash/subagent-cost.d.ts +3 -2
  185. package/src/slash/subagent-cost.js +22 -3
  186. package/src/slash/subagents-admin.js +0 -1
  187. package/src/tui/fleet-status.d.ts +0 -5
  188. package/src/tui/fleet-status.js +4 -24
  189. package/src/tui/fleet-transcript.d.ts +1 -44
  190. package/src/tui/fleet-transcript.js +1 -327
  191. package/src/tui/fleet.js +6 -4
  192. package/src/tui/render.d.ts +0 -9
  193. package/src/tui/render.js +81 -47
  194. package/src/tui/subagent-messages.js +3 -2
  195. package/src/watchdog/register-child.d.ts +2 -3
  196. package/src/watchdog/register-child.js +2 -3
  197. package/src/watchdog/turn-delta.js +2 -1
  198. package/src/workflows/scripted-workflow.js +241 -20
  199. package/src/workflows/workflow-launch-record.d.ts +15 -6
  200. package/src/workflows/workflow-launch-record.js +30 -12
  201. package/src/workflows/workflow-resume-claim.js +2 -2
  202. package/src/workflows/workflow-resume.d.ts +1 -1
  203. package/src/workflows/workflow-resume.js +11 -8
  204. package/src/workflows/workflow-script-worker.d.ts +13 -0
  205. package/src/workflows/workflow-script-worker.js +79 -0
  206. package/workflow-script-process.cjs +36 -0
  207. 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";
@@ -48,7 +46,6 @@ interface AsyncExecutionContext {
48
46
  /** The parent's model registry, read at launch to name a provider an extension registered there. */
49
47
  parentProviderRegistry?: Pick<ParentProviderRegistry, "getRegisteredProviderIds">;
50
48
  }
51
- export declare const DEFAULT_ASYNC_TIMEOUT_MS: number;
52
49
  interface AsyncChainParams {
53
50
  chain: ChainStep[];
54
51
  task?: string;
@@ -134,6 +131,10 @@ interface AsyncSingleParams {
134
131
  machine?: string;
135
132
  /** Launch cwd as typed when a machine is set: a path on that machine, never resolved locally. */
136
133
  machineCwd?: string;
134
+ /** The launcher and agent definition digest the call requires; checked here, on what this launch spawns. */
135
+ requireLauncher?: RequiredRunnerLauncher;
136
+ /** A revived run's inherited requirement: recorded for its own resumes, not checked here (resume already checked it). */
137
+ carriedRequiredLauncher?: RequiredRunnerLauncher;
137
138
  maxOutput?: MaxOutputConfig;
138
139
  artifactsDir?: string;
139
140
  artifactConfig: ArtifactConfig;
@@ -288,13 +289,7 @@ export declare function resolveClaudeCodeThinking(source: string | false | undef
288
289
  * owns the remote model registry, so the combination fails instead of losing both flags. */
289
290
  export declare function assertClaudeCodeOverrideIsLocal(agent: string, machine: string | undefined, override: ClaudeCodeOverride | undefined): void;
290
291
  export declare function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildParams): AsyncRunnerStepBuildResult;
291
- /**
292
- * Execute a chain asynchronously
293
- */
294
292
  export declare function executeAsyncChain(id: string, params: AsyncChainParams): AsyncExecutionResult | Promise<AsyncExecutionResult>;
295
- /**
296
- * Execute a single agent asynchronously
297
- */
298
293
  export declare function workflowAwaitedAsyncResultPath(asyncDir: string): string;
299
294
  export declare function executeAsyncSingle(id: string, params: AsyncSingleParams): AsyncExecutionResult | Promise<AsyncExecutionResult>;
300
295
  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 = (() => {
@@ -146,15 +145,14 @@ function parentExtensionProviderForChild(ctx, disableAmbientExtensions, model, a
146
145
  const provider = findModelInfo(model, availableModels, preferredProvider)?.provider;
147
146
  return provider && ctx.parentProviderRegistry.getRegisteredProviderIds().includes(provider) ? provider : undefined;
148
147
  }
149
- export const DEFAULT_ASYNC_TIMEOUT_MS = 30 * 60 * 1000;
150
148
  export function formatAsyncStartedMessage(headline, interactive) {
151
149
  const guidance = interactive
152
150
  ? [
153
- "Detached. Return control now: native completion wakes you, so do not sleep, poll, or call bg_wait for it.",
151
+ `Detached. Return control now: native completion wakes you, so do not sleep, poll, or call ${waitToolName()} for it.`,
154
152
  "One-shot check: subagent({ action: \"status\", id: \"...\" }).",
155
153
  ]
156
154
  : [
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.",
155
+ `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
156
  ];
159
157
  return [headline, "", ...guidance].join("\n");
160
158
  }
@@ -183,9 +181,6 @@ function closeFd(fd) {
183
181
  // Best-effort cleanup; child process already owns its duplicated stdio fd.
184
182
  }
185
183
  }
186
- /**
187
- * Spawn the async runner process
188
- */
189
184
  const RUNNER_STARTUP_TIMEOUT_MS = 10_000;
190
185
  function waitForStartupInterval(delayMs = 20) {
191
186
  return new Promise((resolve) => setTimeout(resolve, delayMs));
@@ -287,6 +282,33 @@ function terminateRunnerBeforeProceed(pid) {
287
282
  }
288
283
  return !runnerIsAlive(pid);
289
284
  }
285
+ function parentPid(pid) {
286
+ let ppid;
287
+ if (process.platform === "linux") {
288
+ try {
289
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf-8");
290
+ ppid = Number(stat.slice(stat.lastIndexOf(")") + 1).trim().split(/\s+/)[1]);
291
+ }
292
+ catch {
293
+ return undefined;
294
+ }
295
+ }
296
+ else {
297
+ const result = spawnSync("ps", ["-o", "ppid=", "-p", String(pid)], { encoding: "utf-8" });
298
+ if (result.error || result.status !== 0)
299
+ return undefined;
300
+ ppid = Number(result.stdout.trim());
301
+ }
302
+ return Number.isSafeInteger(ppid) && ppid > 0 ? ppid : undefined;
303
+ }
304
+ /** The runner reports its own pid, so behind a launcher only a pid inside the spawned launcher's tree may be signalled. */
305
+ function isInProcessTree(pid, rootPid) {
306
+ for (let current = pid; current !== undefined && current > 1; current = parentPid(current)) {
307
+ if (current === rootPid)
308
+ return true;
309
+ }
310
+ return false;
311
+ }
290
312
  async function terminateRunnerBeforeProceedAsyncDefault(proc, processClosed) {
291
313
  for (const signal of ["SIGTERM", "SIGKILL"]) {
292
314
  if (proc.pid === undefined || !runnerIsAlive(proc.pid))
@@ -449,7 +471,7 @@ function spawnRunner(cfg, suffix, cwd, initialStatus, initialStatusPath, launchP
449
471
  // its own identity before it is allowed to proceed.
450
472
  const launcher = cfg.launcher;
451
473
  const bootId = launcher ? undefined : currentBootId();
452
- const launchConfig = { ...cfg, runnerProcessInstanceId, ...(launchBarrierToken ? { launchBarrierToken } : {}), ...(bootId ? { bootId } : {}) };
474
+ const launchConfig = { ...cfg, runnerProcessInstanceId, ...(launchBarrierToken ? { launchBarrierToken } : {}), ...(bootId ? { bootId } : {}), ...(waitToolName() !== DEFAULT_WAIT_TOOL_NAME ? { waitToolName: waitToolName() } : {}) };
453
475
  writePrivateAtomicJson(cfgPath, launchConfig);
454
476
  const command = binaryHost ?? nodeExecutable;
455
477
  const launchForStartup = launchConfig;
@@ -477,10 +499,12 @@ function spawnRunner(cfg, suffix, cwd, initialStatus, initialStatusPath, launchP
477
499
  if (identityPath)
478
500
  fs.rmSync(identityPath, { force: true });
479
501
  let runnerIdentity;
480
- // Wrapper exit is not runner exit, so only a reported runner in this namespace may be signalled.
502
+ // Wrapper exit is not runner exit, so only a reported runner in this namespace may be signalled, and only
503
+ // inside the spawned launcher's process tree. Otherwise the runner exits when proceed never arrives.
481
504
  const terminateBeforeProceed = (pid) => !launcher
482
505
  ? terminateRunnerBeforeProceed(pid)
483
- : runnerIdentity !== undefined && runnerIdentity.pidNamespaceScope === currentPidNamespaceScope() && terminateRunnerBeforeProceed(runnerIdentity.pid);
506
+ : runnerIdentity !== undefined && runnerIdentity.pidNamespaceScope === currentPidNamespaceScope()
507
+ && isInProcessTree(runnerIdentity.pid, pid) && terminateRunnerBeforeProceed(runnerIdentity.pid);
484
508
  const adoptRunnerIdentity = (pid, pidNamespaceScope) => {
485
509
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid < 1)
486
510
  return `Async runner reported an invalid process identity in '${launchAsyncDir}'.`;
@@ -928,7 +952,7 @@ export function buildAsyncRunnerSteps(id, params) {
928
952
  taskTemplate = taskTemplate.replace(/\{chain_dir\}/g, behaviorCwd ?? runnerCwd);
929
953
  const taskText = `${readInstructions.prefix}${taskTemplate}${progressInstructions.suffix}`;
930
954
  // A namespaced parallel output path is added to each child's task by the runner.
931
- const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a);
955
+ const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a, machine);
932
956
  const modelScopes = resolveModelScopesForAgent(ctx.modelScope, a.name, ctx.currentModel, ctx.scopedModelIds);
933
957
  const modelOrigin = resolveModelOrigin({ explicitModel: s.model, agentModel: a.model, parentModel: ctx.currentModel });
934
958
  const primaryModelFromParent = modelOrigin === "inherited";
@@ -987,7 +1011,8 @@ export function buildAsyncRunnerSteps(id, params) {
987
1011
  if (launchRuleError)
988
1012
  throw new AsyncStartValidationError(launchRuleError);
989
1013
  const fast = s.fast ?? params.fast ?? a.fast;
990
- const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
1014
+ // Admission already refused mandatory entries for a placed child, which skips the rest.
1015
+ const requiredExtensions = externalRunner || machine ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
991
1016
  const toolPlan = resolvePiLaunchToolPlan({
992
1017
  tools: a.tools,
993
1018
  excludeTools: a.excludeTools,
@@ -1064,7 +1089,7 @@ export function buildAsyncRunnerSteps(id, params) {
1064
1089
  outputMode: behavior.outputMode,
1065
1090
  sessionFile,
1066
1091
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, a.maxSubagentDepth),
1067
- timeoutMs: a.defaultTimeoutMs ?? DEFAULT_ASYNC_TIMEOUT_MS,
1092
+ timeoutMs: a.defaultTimeoutMs,
1068
1093
  toolTimeoutMs: resolvedToolTimeout.toolTimeoutMs,
1069
1094
  waitToolEnabled: params.waitToolEnabled,
1070
1095
  waitToolDefaultTimeoutMs: params.waitToolDefaultTimeoutMs,
@@ -1230,9 +1255,6 @@ export function buildAsyncRunnerSteps(id, params) {
1230
1255
  throw error;
1231
1256
  }
1232
1257
  }
1233
- /**
1234
- * Execute a chain asynchronously
1235
- */
1236
1258
  export function executeAsyncChain(id, params) {
1237
1259
  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
1260
  const resultMode = params.resultMode ?? "chain";
@@ -1555,14 +1577,12 @@ export function executeAsyncChain(id, params) {
1555
1577
  };
1556
1578
  return spawnResultOrPromise instanceof Promise ? spawnResultOrPromise.then(finishSpawnResult) : finishSpawnResult(spawnResultOrPromise);
1557
1579
  }
1558
- /**
1559
- * Execute a single agent asynchronously
1560
- */
1561
1580
  export function workflowAwaitedAsyncResultPath(asyncDir) {
1562
1581
  return path.join(asyncDir, "workflow-result.json");
1563
1582
  }
1564
1583
  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;
1584
+ const { agent, ctx, cwd, maxOutput, artifactsDir, artifactConfig, shareEnabled, sessionRoot, sessionFile, maxSubagentDepth, worktreeSetupHook, worktreeSetupHookTimeoutMs, worktreeBaseDir, baseRef, worktreeProvider, worktreeBranchPrefix, controlConfig, controlIntercomTarget, childIntercomTarget, nestedRoute, } = params;
1585
+ let agentConfig = params.agentConfig;
1566
1586
  let lane;
1567
1587
  try {
1568
1588
  lane = normalizeWorkflowLaneMetadata(params.lane, "lane");
@@ -1632,6 +1652,13 @@ export function executeAsyncSingle(id, params) {
1632
1652
  if (resolvedLauncher.error)
1633
1653
  return formatAsyncStartError("single", resolvedLauncher.error);
1634
1654
  const launcher = resolvedLauncher.launcher;
1655
+ if (params.requireLauncher) {
1656
+ const required = checkRequiredRunnerLauncher(agentConfig, launcher?.name, params.requireLauncher);
1657
+ if (required.error !== undefined)
1658
+ return formatAsyncStartError("single", required.error);
1659
+ // The launch records the digest it checked, not a second hash of an agent file that may have changed since.
1660
+ agentConfig = { ...agentConfig, definitionDigest: required.definitionDigest };
1661
+ }
1635
1662
  const registeredExtensions = resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1636
1663
  try {
1637
1664
  assertRequiredChildExtensionsAdmitted([params.requiredExtensions, ctx.childRuntime?.requiredExtensions, registeredExtensions], { agent: agentConfig.name, runnerType: agentConfig.runner?.type, machine: requestedMachine });
@@ -1698,7 +1725,7 @@ export function executeAsyncSingle(id, params) {
1698
1725
  const validationError = validateFileOnlyOutputMode(outputMode, outputPath, `Async single run (${agent})`);
1699
1726
  if (validationError)
1700
1727
  return formatAsyncStartError("single", validationError);
1701
- const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, agentConfig);
1728
+ const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, agentConfig, machine);
1702
1729
  // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
1703
1730
  // absolute paths pass through; relative paths resolve against the child cwd.
1704
1731
  const reads = params.reads !== undefined ? params.reads : agentConfig.defaultReads ?? false;
@@ -1803,7 +1830,8 @@ export function executeAsyncSingle(id, params) {
1803
1830
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1804
1831
  }
1805
1832
  }
1806
- const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
1833
+ // Admission already refused mandatory entries for a placed child, which skips the rest.
1834
+ const requiredExtensions = externalRunner || machine ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
1807
1835
  const toolPlan = resolvePiLaunchToolPlan({
1808
1836
  tools: agentConfig.tools,
1809
1837
  excludeTools: agentConfig.excludeTools,
@@ -1851,6 +1879,7 @@ export function executeAsyncSingle(id, params) {
1851
1879
  agentContract: params.agentContract,
1852
1880
  });
1853
1881
  const recoveryAgentConfig = params.recoveryAgentConfig ?? agentConfig;
1882
+ const requiredLauncher = params.requireLauncher ?? params.carriedRequiredLauncher;
1854
1883
  const recoveryDescriptor = {
1855
1884
  ...(ctx.modelResponseAliases ? { modelResponseAliases: ctx.modelResponseAliases } : {}),
1856
1885
  version: 1,
@@ -1860,6 +1889,10 @@ export function executeAsyncSingle(id, params) {
1860
1889
  ...(requiredExtensions.length > 0 ? { requiredExtensions } : {}),
1861
1890
  runFanoutBudget,
1862
1891
  sourceRunId: id,
1892
+ ...(ctx.currentSessionId ? { sessionId: ctx.currentSessionId } : {}),
1893
+ // The worktree the runner will create, fixed here from launch inputs (the runner's own naming call).
1894
+ ...(managedWorktreeProvider === "native" ? { managedWorktree: { provider: "native", cwd: instructionCwd } } : {}),
1895
+ ...(managedWorktreeProvider === "worktrunk" ? { managedWorktree: { provider: "worktrunk", branch: buildWorktreeNaming({ runId: `${id}-s0`, index: 0, agent, label: lane?.key ?? params.workflowKey, task: taskText, branchPrefix: worktreeBranchPrefix }).requestedBranch } } : {}),
1863
1896
  ...(params.agentContract ? { agentContract: params.agentContract } : {}),
1864
1897
  agent,
1865
1898
  launchResolvedExtensions,
@@ -1897,7 +1930,8 @@ export function executeAsyncSingle(id, params) {
1897
1930
  ...(params.context ? { context: params.context } : {}),
1898
1931
  ...(params.intercomBridge !== undefined ? { intercomBridge: params.intercomBridge } : {}),
1899
1932
  ...(params.baseRef !== undefined ? { baseRef: params.baseRef } : {}),
1900
- ...(launcher ? { launcher: launcher.name } : {}),
1933
+ launcher: launcher ? launcher.name : null,
1934
+ ...(requiredLauncher ? { requiredLauncher } : {}),
1901
1935
  ...(deadlineAt !== undefined ? { absoluteDeadlineAt: deadlineAt } : {}),
1902
1936
  ...(resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {}),
1903
1937
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, recoveryAgentConfig.maxSubagentDepth),
@@ -1910,7 +1944,7 @@ export function executeAsyncSingle(id, params) {
1910
1944
  };
1911
1945
  if (!externalRunner) {
1912
1946
  try {
1913
- writePrivateAtomicJson(path.join(asyncDir, "recovery-descriptor.json"), recoveryDescriptor);
1947
+ writePrivateAtomicJson(recoveryDescriptorPath(path.dirname(asyncDir), id), recoveryDescriptor);
1914
1948
  }
1915
1949
  catch (error) {
1916
1950
  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) {