@xzzpig/pi-subagents 0.24.1 → 0.25.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 (263) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/bundle/agent-management.js +4 -4
  3. package/bundle/agents.js +3 -3
  4. package/bundle/child-tool-plan.js +2 -2
  5. package/bundle/chunk-34TUUBRN.js +1107 -0
  6. package/bundle/{chunk-SW2VMNIU.js → chunk-5OD3OWTE.js} +2 -2
  7. package/bundle/{chunk-ZWXU5SPQ.js → chunk-5YEOWNSD.js} +371 -135
  8. package/bundle/{chunk-EUPJB4S7.js → chunk-5Z7JAORM.js} +196 -1219
  9. package/bundle/{chunk-LCDJWBVM.js → chunk-66JNFRFS.js} +1 -1
  10. package/bundle/{chunk-6BJUEES3.js → chunk-6MNRKUHY.js} +23 -12
  11. package/bundle/{chunk-ED55MIC2.js → chunk-CGFF4WA3.js} +42 -19
  12. package/bundle/{chunk-TMHVDPYW.js → chunk-DLVPMML3.js} +263 -154
  13. package/bundle/chunk-HXRB42AF.js +108 -0
  14. package/bundle/{chunk-355ECEP2.js → chunk-IH7LQVEE.js} +29 -14
  15. package/bundle/{chunk-SLNMBXLL.js → chunk-IJWITCC6.js} +411 -249
  16. package/bundle/{chunk-RU522D5W.js → chunk-IKFKH5EL.js} +369 -50
  17. package/bundle/{chunk-Z6TFJ6BR.js → chunk-INWSUNI6.js} +1 -1
  18. package/bundle/{chunk-JEA2ZKUA.js → chunk-IUDEI6FJ.js} +35 -200
  19. package/bundle/{chunk-WW76JRIX.js → chunk-JAXVBXGF.js} +1 -1
  20. package/bundle/{chunk-ICNYIALB.js → chunk-JH5H4CYJ.js} +784 -474
  21. package/bundle/{chunk-35GII5EF.js → chunk-JWFLPSTP.js} +41 -117
  22. package/bundle/{chunk-LMGQAJ3O.js → chunk-KCJFGKVK.js} +350 -123
  23. package/bundle/{chunk-RB4GELQA.js → chunk-LPJEKHOY.js} +1 -1
  24. package/bundle/chunk-LYKG4FKH.js +523 -0
  25. package/bundle/{chunk-X6LOM3Z4.js → chunk-LZ3HBDTR.js} +161 -78
  26. package/bundle/{chunk-FG6SQJAR.js → chunk-OGPOCGWX.js} +24 -6
  27. package/bundle/{chunk-Y6H2G6KX.js → chunk-OSVXFWPG.js} +67 -30
  28. package/bundle/{chunk-FJWI64H7.js → chunk-RMSABUN3.js} +27 -13
  29. package/bundle/{chunk-H36HBZB2.js → chunk-SJPABBZG.js} +2 -2
  30. package/bundle/{chunk-3U633XDZ.js → chunk-U3ZDUUTM.js} +11 -3
  31. package/bundle/{chunk-LVWU2HOO.js → chunk-ULGMXABL.js} +16 -7
  32. package/bundle/{chunk-WPW4V6HM.js → chunk-W7ZA6TYD.js} +2 -2
  33. package/bundle/{chunk-V2KFIGFH.js → chunk-XAC2XNAP.js} +503 -304
  34. package/bundle/{chunk-TGLFTQWJ.js → chunk-YWXILP5N.js} +5 -4
  35. package/bundle/control-channel.js +2 -2
  36. package/bundle/index.js +1 -1
  37. package/bundle/intercom-bridge.js +2 -2
  38. package/bundle/preflight.js +12 -10
  39. package/bundle/project-panes.js +3 -3
  40. package/bundle/workflow-resources.js +1 -1
  41. package/docs/agents.md +27 -6
  42. package/docs/configuration.md +20 -8
  43. package/docs/extension-api.md +18 -1
  44. package/docs/models.md +6 -2
  45. package/docs/observability.md +2 -0
  46. package/docs/tool-reference.md +7 -1
  47. package/docs/workflows.md +30 -2
  48. package/node_modules/@xzzpig/pi-components/CHANGELOG.md +12 -0
  49. package/node_modules/@xzzpig/pi-components/README.md +94 -0
  50. package/node_modules/@xzzpig/pi-components/dist/src/transcript-presenter.d.ts +186 -0
  51. package/node_modules/@xzzpig/pi-components/dist/src/transcript-presenter.js +693 -0
  52. package/node_modules/@xzzpig/pi-components/package.json +5 -1
  53. package/package.json +4 -4
  54. package/skills/pi-subagents/SKILL.md +15 -6
  55. package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
  56. package/src/agents/agent-management.d.ts +1 -0
  57. package/src/agents/agent-management.js +46 -18
  58. package/src/agents/agent-memory.d.ts +1 -4
  59. package/src/agents/agent-memory.js +1 -4
  60. package/src/agents/agent-serializer.d.ts +2 -0
  61. package/src/agents/agent-serializer.js +1 -1
  62. package/src/agents/agents.d.ts +2 -3
  63. package/src/agents/agents.js +46 -20
  64. package/src/agents/frontmatter.js +1 -8
  65. package/src/agents/global-npm-root.d.ts +1 -0
  66. package/src/agents/global-npm-root.js +11 -3
  67. package/src/agents/skills.d.ts +0 -3
  68. package/src/agents/skills.js +0 -3
  69. package/src/api/preflight.d.ts +3 -1
  70. package/src/api/preflight.js +2 -0
  71. package/src/extension/config.d.ts +1 -0
  72. package/src/extension/config.js +13 -1
  73. package/src/extension/herdr-pi-bridge.js +10 -2
  74. package/src/extension/index.d.ts +0 -13
  75. package/src/extension/index.js +51 -37
  76. package/src/extension/public-execution.d.ts +1 -0
  77. package/src/extension/public-execution.js +4 -0
  78. package/src/extension/reply-workflow-script.js +24 -4
  79. package/src/extension/schemas.d.ts +12 -3
  80. package/src/extension/schemas.js +7 -3
  81. package/src/extension/session-switch.d.ts +25 -0
  82. package/src/extension/session-switch.js +138 -0
  83. package/src/extension/subagent-guide.d.ts +1 -1
  84. package/src/extension/subagent-guide.js +1 -1
  85. package/src/extension/subagent-launch-tool.d.ts +25 -0
  86. package/src/extension/subagent-launch-tool.js +48 -0
  87. package/src/extension/tool-activation.js +55 -15
  88. package/src/extension/tool-description.d.ts +1 -1
  89. package/src/extension/tool-description.js +14 -8
  90. package/src/inspectors/herdr/actions.d.ts +0 -1
  91. package/src/inspectors/herdr/actions.js +0 -1
  92. package/src/inspectors/session-roots-codec.d.ts +0 -1
  93. package/src/inspectors/session-roots-codec.js +0 -1
  94. package/src/inspectors/tmux/actions.d.ts +0 -1
  95. package/src/inspectors/tmux/actions.js +0 -1
  96. package/src/integrations/herdr-status.js +3 -8
  97. package/src/intercom/native-supervisor-channel.js +65 -9
  98. package/src/runs/background/async-execution.d.ts +7 -10
  99. package/src/runs/background/async-execution.js +66 -29
  100. package/src/runs/background/async-job-tracker.js +12 -0
  101. package/src/runs/background/async-resume.d.ts +2 -1
  102. package/src/runs/background/async-resume.js +114 -40
  103. package/src/runs/background/async-retention.d.ts +0 -2
  104. package/src/runs/background/async-retention.js +17 -6
  105. package/src/runs/background/async-status.d.ts +2 -0
  106. package/src/runs/background/async-status.js +4 -0
  107. package/src/runs/background/auto-drain.js +2 -1
  108. package/src/runs/background/boot-id.d.ts +1 -3
  109. package/src/runs/background/boot-id.js +1 -3
  110. package/src/runs/background/completion-batcher.d.ts +3 -4
  111. package/src/runs/background/completion-batcher.js +2 -3
  112. package/src/runs/background/control-channel.d.ts +0 -6
  113. package/src/runs/background/control-channel.js +0 -6
  114. package/src/runs/background/fleet-view.js +2 -3
  115. package/src/runs/background/notify.d.ts +0 -2
  116. package/src/runs/background/notify.js +0 -2
  117. package/src/runs/background/result-watcher.d.ts +1 -0
  118. package/src/runs/background/result-watcher.js +59 -29
  119. package/src/runs/background/resume-guidance.js +4 -2
  120. package/src/runs/background/retained-children.js +2 -1
  121. package/src/runs/background/run-child-session.d.ts +2 -3
  122. package/src/runs/background/run-child-session.js +5 -8
  123. package/src/runs/background/run-status.js +9 -7
  124. package/src/runs/background/runner-aliases.js +15 -0
  125. package/src/runs/background/scheduled-runs.d.ts +3 -1
  126. package/src/runs/background/scheduled-runs.js +13 -16
  127. package/src/runs/background/steering.d.ts +2 -11
  128. package/src/runs/background/steering.js +11 -6
  129. package/src/runs/background/subagent-runner.d.ts +2 -6
  130. package/src/runs/background/subagent-runner.js +88 -70
  131. package/src/runs/background/subagent-wait.js +12 -15
  132. package/src/runs/background/wait-config.d.ts +2 -0
  133. package/src/runs/background/wait-config.js +17 -3
  134. package/src/runs/background/wait-subscriptions.js +124 -12
  135. package/src/runs/background/wait-tool.js +4 -2
  136. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  137. package/src/runs/background/workflow-terminal-proof.js +0 -1
  138. package/src/runs/foreground/async-steering-action.js +24 -9
  139. package/src/runs/foreground/async-stop-action.d.ts +1 -1
  140. package/src/runs/foreground/async-stop-action.js +9 -1
  141. package/src/runs/foreground/execution.d.ts +0 -3
  142. package/src/runs/foreground/execution.js +56 -24
  143. package/src/runs/foreground/prompt-audit.js +1 -0
  144. package/src/runs/foreground/subagent-executor.d.ts +5 -10
  145. package/src/runs/foreground/subagent-executor.js +164 -49
  146. package/src/runs/shared/acceptance.js +69 -26
  147. package/src/runs/shared/async-status-projection.d.ts +2 -0
  148. package/src/runs/shared/async-status-projection.js +10 -0
  149. package/src/runs/shared/child-commands.js +15 -2
  150. package/src/runs/shared/child-hooks.d.ts +1 -7
  151. package/src/runs/shared/child-hooks.js +13 -5
  152. package/src/runs/shared/child-launch.js +6 -2
  153. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  154. package/src/runs/shared/child-session.d.ts +6 -5
  155. package/src/runs/shared/child-session.js +85 -38
  156. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  157. package/src/runs/shared/child-tool-plan.js +0 -1
  158. package/src/runs/shared/claude-code-adapter.js +11 -0
  159. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  160. package/src/runs/shared/external-cli-contract.js +18 -13
  161. package/src/runs/shared/external-cli-runner.js +26 -6
  162. package/src/runs/shared/herdr-connection.js +2 -1
  163. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  164. package/src/runs/shared/herdr-pane-host.js +17 -1
  165. package/src/runs/shared/herdr-placed-run.js +51 -24
  166. package/src/runs/shared/lane-metadata.d.ts +0 -1
  167. package/src/runs/shared/lane-metadata.js +0 -1
  168. package/src/runs/shared/mcp-config-sources.d.ts +4 -1
  169. package/src/runs/shared/mcp-config-sources.js +1 -1
  170. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -3
  171. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -17
  172. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  173. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  174. package/src/runs/shared/model-resolution.d.ts +20 -5
  175. package/src/runs/shared/model-resolution.js +55 -50
  176. package/src/runs/shared/model-scope.d.ts +1 -5
  177. package/src/runs/shared/model-scope.js +1 -5
  178. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  179. package/src/runs/shared/mutation-evidence.js +52 -7
  180. package/src/runs/shared/nested-events.d.ts +1 -0
  181. package/src/runs/shared/nested-events.js +1 -1
  182. package/src/runs/shared/parallel-utils.d.ts +0 -1
  183. package/src/runs/shared/permissions.js +5 -3
  184. package/src/runs/shared/placement-host.d.ts +5 -1
  185. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  186. package/src/runs/shared/rex-pane-host.js +0 -2
  187. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  188. package/src/runs/shared/run-launch-folder.js +21 -0
  189. package/src/runs/shared/runner-launcher.d.ts +12 -1
  190. package/src/runs/shared/runner-launcher.js +16 -0
  191. package/src/runs/shared/single-output.d.ts +3 -3
  192. package/src/runs/shared/single-output.js +5 -3
  193. package/src/runs/shared/structured-output.d.ts +8 -0
  194. package/src/runs/shared/structured-output.js +40 -5
  195. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  196. package/src/runs/shared/subagent-prompt-runtime.js +18 -4
  197. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  198. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  199. package/src/runs/shared/tool-timeout.js +2 -1
  200. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  201. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  202. package/src/runs/shared/worktree.d.ts +3 -0
  203. package/src/runs/shared/worktree.js +20 -0
  204. package/src/shared/artifacts.d.ts +1 -0
  205. package/src/shared/artifacts.js +132 -22
  206. package/src/shared/capacity-resilient-json.d.ts +1 -1
  207. package/src/shared/child-cache-retention.d.ts +1 -2
  208. package/src/shared/child-cache-retention.js +1 -2
  209. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  210. package/src/shared/fleet-transcript-reader.js +333 -0
  211. package/src/shared/formatters.d.ts +0 -18
  212. package/src/shared/formatters.js +0 -18
  213. package/src/shared/pruned-fork.js +2 -2
  214. package/src/shared/reported-progress.d.ts +1 -0
  215. package/src/shared/reported-progress.js +12 -0
  216. package/src/shared/session-succession.d.ts +16 -1
  217. package/src/shared/session-succession.js +41 -2
  218. package/src/shared/session-warnings.d.ts +7 -0
  219. package/src/shared/session-warnings.js +26 -0
  220. package/src/shared/settings.d.ts +0 -23
  221. package/src/shared/settings.js +3 -35
  222. package/src/shared/status-format.d.ts +1 -0
  223. package/src/shared/status-format.js +1 -1
  224. package/src/shared/types.d.ts +108 -59
  225. package/src/shared/types.js +0 -12
  226. package/src/shared/utils.d.ts +3 -15
  227. package/src/shared/utils.js +4 -22
  228. package/src/shared/wait-tool-name.d.ts +8 -0
  229. package/src/shared/wait-tool-name.js +13 -0
  230. package/src/slash/slash-commands.js +2 -1
  231. package/src/slash/subagent-cost.d.ts +3 -2
  232. package/src/slash/subagent-cost.js +22 -3
  233. package/src/slash/subagents-admin.js +0 -1
  234. package/src/tui/fleet-status.d.ts +0 -5
  235. package/src/tui/fleet-status.js +4 -24
  236. package/src/tui/fleet.js +6 -4
  237. package/src/tui/render.d.ts +0 -9
  238. package/src/tui/render.js +194 -68
  239. package/src/tui/subagent-messages.js +3 -2
  240. package/src/watchdog/model-selection.js +2 -2
  241. package/src/watchdog/permission-arbiter.js +1 -0
  242. package/src/watchdog/register-child.d.ts +2 -3
  243. package/src/watchdog/register-child.js +2 -3
  244. package/src/watchdog/review.d.ts +0 -5
  245. package/src/watchdog/review.js +4 -3
  246. package/src/watchdog/turn-delta.js +2 -1
  247. package/src/workflows/scripted-workflow.d.ts +2 -0
  248. package/src/workflows/scripted-workflow.js +344 -59
  249. package/src/workflows/structured-workflow-scripts.d.ts +4 -3
  250. package/src/workflows/structured-workflow-scripts.js +32 -11
  251. package/src/workflows/workflow-launch-record.d.ts +15 -6
  252. package/src/workflows/workflow-launch-record.js +30 -12
  253. package/src/workflows/workflow-receipt.js +36 -53
  254. package/src/workflows/workflow-resources.js +4 -4
  255. package/src/workflows/workflow-resume-claim.d.ts +2 -0
  256. package/src/workflows/workflow-resume-claim.js +3 -3
  257. package/src/workflows/workflow-resume.d.ts +1 -1
  258. package/src/workflows/workflow-resume.js +13 -8
  259. package/src/workflows/workflow-script-worker.d.ts +13 -0
  260. package/src/workflows/workflow-script-worker.js +81 -0
  261. package/workflow-script-process.cjs +36 -0
  262. package/workflow-script-worker.cjs +4 -1
  263. package/bundle/chunk-U4ODUYAG.js +0 -235
@@ -9,6 +9,7 @@ import { ownsRun } from "../runs/shared/run-ownership.js";
9
9
  import { writeAtomicJson, writePrivateAtomicJson } from "../shared/atomic-json.js";
10
10
  import { shouldUseNativeFsWatch } from "../shared/watch-strategy.js";
11
11
  import { MODEL_ONLY_TOOL } from "../shared/extension-context.js";
12
+ import { reportSessionWarning } from "../shared/session-warnings.js";
12
13
  import { SUPERVISOR_REQUEST_MESSAGE_TYPE, SUPERVISOR_REPLY_ENTRY_TYPE, supervisorReplyHint, } from "./supervisor-ui.js";
13
14
  const SUPERVISOR_CHANNEL_ROOT = path.join(TEMP_ROOT_DIR, "supervisor-channels");
14
15
  const REQUESTS_DIR = "requests";
@@ -546,7 +547,22 @@ export function appendSupervisorReplyEntry(pi, request, reply) {
546
547
  console.error("Failed to journal native supervisor reply: error details omitted");
547
548
  }
548
549
  }
549
- function resolvePendingRequest(pending, params) {
550
+ function endedRequestText(ended, runState) {
551
+ const { request } = ended;
552
+ const iso = (time) => new Date(time).toISOString();
553
+ const when = ended.eventAt !== undefined ? ` at ${iso(ended.eventAt)}` : ` (noticed at ${iso(ended.endedAt)})`;
554
+ const subject = `Supervisor request '${request.id}' from ${request.agent} [${request.runId}#${request.childIndex}]`;
555
+ const runStatus = runState.asyncJobs.get(request.runId)?.status;
556
+ const runNow = runStatus && runStatus !== "queued" && runStatus !== "running" ? ` Run ${request.runId} is now ${runStatus}.` : "";
557
+ switch (ended.lifecycle) {
558
+ case "resolved": return `${subject} was already answered${when}.`;
559
+ case "expired": return `${subject} expired${when}: no reply arrived before the child's ask timeout.`;
560
+ case "deadline": return `${subject} ended around its ask deadline${when}: either no reply arrived before the child's ask timeout, or its run was stopped just before then.${runNow}`;
561
+ case "inactive": return `${subject} was closed because its child run ended${when}.${runNow}`;
562
+ case "missing": return `${subject} was withdrawn by the child before its ask deadline${when}. A child withdraws its request when its run is stopped, interrupted or times out, for example when a workflow aborts its other children after one fails.${runNow}`;
563
+ }
564
+ }
565
+ function resolvePendingRequest(pending, params, ended, runState) {
550
566
  const requests = [...pending.values()].filter((request) => request.expectsReply);
551
567
  if (params.replyTo) {
552
568
  const request = pending.get(params.replyTo);
@@ -554,6 +570,9 @@ function resolvePendingRequest(pending, params) {
554
570
  // A child stops waiting after its ask timeout and may ask again under a new id. Its first
555
571
  // notice can reach a busy parent after that, so name what can still be answered.
556
572
  const current = requests.length ? `Pending now:\n${requests.map(pendingHeader).join("\n")}` : "No pending supervisor requests.";
573
+ const endedRequest = ended.get(params.replyTo);
574
+ if (endedRequest)
575
+ throw new Error(`${endedRequestText(endedRequest, runState(endedRequest.request))} ${current}`);
557
576
  throw new Error(`No pending supervisor request found for replyTo '${params.replyTo}'. It was answered, expired or withdrawn. ${current}`);
558
577
  }
559
578
  return request;
@@ -585,7 +604,7 @@ function publicPendingRequests(pending) {
585
604
  expectsReply: request.expectsReply,
586
605
  }));
587
606
  }
588
- function buildParentSupervisorTool(pi, pending, state, onLifecycle, discover, runState, isClaimed = () => false) {
607
+ function buildParentSupervisorTool(pi, pending, state, onLifecycle, discover, runState, ended, isClaimed = () => false) {
589
608
  return {
590
609
  name: NATIVE_SUPERVISOR_TOOL_NAME,
591
610
  ...MODEL_ONLY_TOOL,
@@ -607,14 +626,14 @@ function buildParentSupervisorTool(pi, pending, state, onLifecycle, discover, ru
607
626
  return { content: [{ type: "text", text: lines.length ? lines.join("\n") : "No pending supervisor requests." }], details: { pending: publicPendingRequests(new Map(answerable.map((request) => [request.id, request]))) } };
608
627
  }
609
628
  if (input.action === "reply") {
610
- const request = resolvePendingRequest(pending, input);
629
+ const request = resolvePendingRequest(pending, input, ended, runState);
611
630
  if (isClaimed(request.id)) {
612
631
  throw new Error(`Supervisor request ${request.id} is responder-managed; it can only be answered by its registered responder.`);
613
632
  }
614
633
  const reply = writeReply(request, input.message ?? "");
615
634
  appendSupervisorReplyEntry(pi, request, reply);
616
635
  pending.delete(request.id);
617
- onLifecycle(request, "resolved");
636
+ onLifecycle(request, "resolved", reply.createdAt);
618
637
  clearForegroundSupervisorAttention(request, pending, state);
619
638
  return { content: [{ type: "text", text: `Replied to supervisor request ${request.id}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent } };
620
639
  }
@@ -675,12 +694,37 @@ export function createNativeSupervisorChannel(pi, state, deps = {}) {
675
694
  requestCorrelations.set(key, { request, state: "resolved", updatedAt: Date.now() });
676
695
  pruneRequestCorrelations();
677
696
  };
678
- const observeRequestLifecycle = (request, lifecycle) => {
697
+ // How each request ended, so a late reply can say why it is gone instead of a generic miss.
698
+ const endedRequests = new Map();
699
+ const rememberEndedRequest = (request, lifecycle, eventAt) => {
700
+ if (!request.expectsReply)
701
+ return;
702
+ const now = Date.now();
703
+ endedRequests.delete(request.id);
704
+ endedRequests.set(request.id, { request, lifecycle, endedAt: now, ...(eventAt !== undefined ? { eventAt } : {}) });
705
+ for (const [id, ended] of endedRequests) {
706
+ if (now - ended.endedAt <= SUPERVISOR_REQUEST_CORRELATION_RETENTION_MS && endedRequests.size <= MAX_SUPERVISOR_REQUEST_CORRELATIONS)
707
+ break;
708
+ endedRequests.delete(id);
709
+ }
710
+ };
711
+ const observeRequestLifecycle = (request, lifecycle, eventAt) => {
679
712
  settleNotices.delete(request.id);
680
713
  if (queuedNotices.delete(request.id))
681
714
  updateDeliverySubscription();
682
715
  if (lifecycle !== "wrong-session")
683
716
  rememberResolvedRequest(request);
717
+ // A child that hits its ask deadline deletes its own request file, so a missing file past the deadline can be
718
+ // that timeout or a stop just before it. The parent extends a queued ask's expiresAt in memory too, so a live
719
+ // ask never reads as past it.
720
+ if (lifecycle !== "wrong-session" && lifecycle !== "pending") {
721
+ const now = Date.now();
722
+ const expiresAt = requestExpiresAt(request, now);
723
+ if (lifecycle === "missing" && now > expiresAt)
724
+ rememberEndedRequest(request, "deadline", expiresAt);
725
+ else
726
+ rememberEndedRequest(request, lifecycle, lifecycle === "expired" ? expiresAt : eventAt);
727
+ }
684
728
  if (lifecycle !== "pending")
685
729
  deps.supervisorDispatcher?.observe(request.id, lifecycle);
686
730
  updateSettleSubscription();
@@ -739,7 +783,7 @@ export function createNativeSupervisorChannel(pi, state, deps = {}) {
739
783
  };
740
784
  const registerParentTools = () => {
741
785
  if (!hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME))
742
- pi.registerTool(buildParentSupervisorTool(pi, pending, state, observeRequestLifecycle, () => poll(), runState, (requestId) => claimedAsks.has(requestId)));
786
+ pi.registerTool(buildParentSupervisorTool(pi, pending, state, observeRequestLifecycle, () => pollOnce(), runState, endedRequests, (requestId) => claimedAsks.has(requestId)));
743
787
  };
744
788
  /**
745
789
  * Write a responder's answer through the same file-authoritative path the
@@ -786,7 +830,7 @@ export function createNativeSupervisorChannel(pi, state, deps = {}) {
786
830
  // Supervisor delivery must not fail because best-effort temp cleanup failed.
787
831
  }
788
832
  };
789
- const poll = () => {
833
+ const pollOnce = () => {
790
834
  cleanupStaleChannelsIfDue();
791
835
  // Only display notifications require a live UI context, not request registration.
792
836
  refreshPendingRequests(pending, state, observeRequestLifecycle, runState);
@@ -821,7 +865,7 @@ export function createNativeSupervisorChannel(pi, state, deps = {}) {
821
865
  continue;
822
866
  }
823
867
  seenFiles.add(file);
824
- observeRequestLifecycle(request, "resolved");
868
+ observeRequestLifecycle(request, "resolved", now);
825
869
  cleanupRequestLifecycle(request, "resolved");
826
870
  continue;
827
871
  }
@@ -897,6 +941,17 @@ export function createNativeSupervisorChannel(pi, state, deps = {}) {
897
941
  channels?.retire?.();
898
942
  updateSettleSubscription();
899
943
  };
944
+ // Never throws: this runs from timers, watchers, setImmediate and event handlers, and Pi exits the process on an
945
+ // uncaught exception, so one unreadable temp directory must not end the session. Callers whose answer a model or a
946
+ // drain decision reads use pollOnce, so a failed scan is not mistaken for "no pending requests".
947
+ const poll = () => {
948
+ try {
949
+ pollOnce();
950
+ }
951
+ catch (error) {
952
+ reportSessionWarning(state, `Supervisor channel poll failed: ${error instanceof Error ? error.message : String(error)}`, "supervisor-channel-poll");
953
+ }
954
+ };
900
955
  const handleBeforeSettle = (event) => {
901
956
  if (!started || event.outcome !== "completed")
902
957
  return;
@@ -1112,7 +1167,7 @@ export function createNativeSupervisorChannel(pi, state, deps = {}) {
1112
1167
  hasPendingRequests: () => {
1113
1168
  if (!started)
1114
1169
  return false;
1115
- poll();
1170
+ pollOnce();
1116
1171
  return pending.size > 0;
1117
1172
  },
1118
1173
  start: () => {
@@ -1176,6 +1231,7 @@ export function createNativeSupervisorChannel(pi, state, deps = {}) {
1176
1231
  claimedAsks.clear();
1177
1232
  settleNotices.clear();
1178
1233
  requestCorrelations.clear();
1234
+ endedRequests.clear();
1179
1235
  seenFiles.clear();
1180
1236
  },
1181
1237
  pending,
@@ -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";
@@ -8,7 +5,7 @@ import { type ClaudeCodeOverride } from "../shared/claude-code-adapter.ts";
8
5
  import { type ChainStep } from "../../shared/settings.ts";
9
6
  import { type RunnerStep } from "../shared/parallel-utils.ts";
10
7
  import type { ContextMode } from "../shared/context-mode.ts";
11
- import { type AvailableModelInfo, type ModelOrigin, type ParentModel } from "../shared/model-resolution.ts";
8
+ import { type AvailableModelInfo, type KnownProviders, type ModelOrigin, type ParentModel } from "../shared/model-resolution.ts";
12
9
  import { type ModelScopeConfig } from "../shared/model-scope.ts";
13
10
  import { type ThinkingLevel } from "../../shared/thinking-ceiling.ts";
14
11
  import { buildWorkflowGraphSnapshot } from "../shared/workflow-graph.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";
@@ -34,6 +32,7 @@ interface AsyncExecutionContext {
34
32
  currentModelProvider?: string;
35
33
  currentModel?: ParentModel;
36
34
  scopedModelIds?: string[];
35
+ knownProviders?: KnownProviders;
37
36
  /** Optional model-scope enforcement resolved from subagent settings. */
38
37
  modelScope?: ModelScopeConfig;
39
38
  /** Parent-authoritative trust state for profile-aware project config merging. */
@@ -139,6 +138,10 @@ interface AsyncSingleParams {
139
138
  machine?: string;
140
139
  /** Launch cwd as typed when a machine is set: a path on that machine, never resolved locally. */
141
140
  machineCwd?: string;
141
+ /** The launcher and agent definition digest the call requires; checked here, on what this launch spawns. */
142
+ requireLauncher?: RequiredRunnerLauncher;
143
+ /** A revived run's inherited requirement: recorded for its own resumes, not checked here (resume already checked it). */
144
+ carriedRequiredLauncher?: RequiredRunnerLauncher;
142
145
  maxOutput?: MaxOutputConfig;
143
146
  artifactsDir?: string;
144
147
  artifactConfig: ArtifactConfig;
@@ -294,13 +297,7 @@ export declare function resolveClaudeCodeThinking(source: string | false | undef
294
297
  * owns the remote model registry, so the combination fails instead of losing both flags. */
295
298
  export declare function assertClaudeCodeOverrideIsLocal(agent: string, machine: string | undefined, override: ClaudeCodeOverride | undefined): void;
296
299
  export declare function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildParams): AsyncRunnerStepBuildResult;
297
- /**
298
- * Execute a chain asynchronously
299
- */
300
300
  export declare function executeAsyncChain(id: string, params: AsyncChainParams): AsyncExecutionResult | Promise<AsyncExecutionResult>;
301
- /**
302
- * Execute a single agent asynchronously
303
- */
304
301
  export declare function workflowAwaitedAsyncResultPath(asyncDir: string): string;
305
302
  export declare function executeAsyncSingle(id: string, params: AsyncSingleParams): AsyncExecutionResult | Promise<AsyncExecutionResult>;
306
303
  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, omitInheritedProfileEnv } 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 = (() => {
@@ -159,11 +158,11 @@ export const DEFAULT_ASYNC_TIMEOUT_MS = 30 * 60 * 1000;
159
158
  export function formatAsyncStartedMessage(headline, interactive) {
160
159
  const guidance = interactive
161
160
  ? [
162
- "Detached. Return control now: native completion wakes you, so do not sleep, poll, or call bg_wait for it.",
161
+ `Detached. Return control now: native completion wakes you, so do not sleep, poll, or call ${waitToolName()} for it.`,
163
162
  "One-shot check: subagent({ action: \"status\", id: \"...\" }).",
164
163
  ]
165
164
  : [
166
- "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.",
165
+ `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.`,
167
166
  ];
168
167
  return [headline, "", ...guidance].join("\n");
169
168
  }
@@ -192,9 +191,6 @@ function closeFd(fd) {
192
191
  // Best-effort cleanup; child process already owns its duplicated stdio fd.
193
192
  }
194
193
  }
195
- /**
196
- * Spawn the async runner process
197
- */
198
194
  const RUNNER_STARTUP_TIMEOUT_MS = 10_000;
199
195
  function waitForStartupInterval(delayMs = 20) {
200
196
  return new Promise((resolve) => setTimeout(resolve, delayMs));
@@ -296,6 +292,33 @@ function terminateRunnerBeforeProceed(pid) {
296
292
  }
297
293
  return !runnerIsAlive(pid);
298
294
  }
295
+ function parentPid(pid) {
296
+ let ppid;
297
+ if (process.platform === "linux") {
298
+ try {
299
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf-8");
300
+ ppid = Number(stat.slice(stat.lastIndexOf(")") + 1).trim().split(/\s+/)[1]);
301
+ }
302
+ catch {
303
+ return undefined;
304
+ }
305
+ }
306
+ else {
307
+ const result = spawnSync("ps", ["-o", "ppid=", "-p", String(pid)], { encoding: "utf-8" });
308
+ if (result.error || result.status !== 0)
309
+ return undefined;
310
+ ppid = Number(result.stdout.trim());
311
+ }
312
+ return Number.isSafeInteger(ppid) && ppid > 0 ? ppid : undefined;
313
+ }
314
+ /** The runner reports its own pid, so behind a launcher only a pid inside the spawned launcher's tree may be signalled. */
315
+ function isInProcessTree(pid, rootPid) {
316
+ for (let current = pid; current !== undefined && current > 1; current = parentPid(current)) {
317
+ if (current === rootPid)
318
+ return true;
319
+ }
320
+ return false;
321
+ }
299
322
  async function terminateRunnerBeforeProceedAsyncDefault(proc, processClosed) {
300
323
  for (const signal of ["SIGTERM", "SIGKILL"]) {
301
324
  if (proc.pid === undefined || !runnerIsAlive(proc.pid))
@@ -458,7 +481,7 @@ function spawnRunner(cfg, suffix, cwd, initialStatus, initialStatusPath, launchP
458
481
  // its own identity before it is allowed to proceed.
459
482
  const launcher = cfg.launcher;
460
483
  const bootId = launcher ? undefined : currentBootId();
461
- const launchConfig = { ...cfg, runnerProcessInstanceId, ...(launchBarrierToken ? { launchBarrierToken } : {}), ...(bootId ? { bootId } : {}) };
484
+ const launchConfig = { ...cfg, runnerProcessInstanceId, ...(launchBarrierToken ? { launchBarrierToken } : {}), ...(bootId ? { bootId } : {}), ...(waitToolName() !== DEFAULT_WAIT_TOOL_NAME ? { waitToolName: waitToolName() } : {}) };
462
485
  writePrivateAtomicJson(cfgPath, launchConfig);
463
486
  const command = binaryHost ?? nodeExecutable;
464
487
  const launchForStartup = launchConfig;
@@ -486,10 +509,12 @@ function spawnRunner(cfg, suffix, cwd, initialStatus, initialStatusPath, launchP
486
509
  if (identityPath)
487
510
  fs.rmSync(identityPath, { force: true });
488
511
  let runnerIdentity;
489
- // Wrapper exit is not runner exit, so only a reported runner in this namespace may be signalled.
512
+ // Wrapper exit is not runner exit, so only a reported runner in this namespace may be signalled, and only
513
+ // inside the spawned launcher's process tree. Otherwise the runner exits when proceed never arrives.
490
514
  const terminateBeforeProceed = (pid) => !launcher
491
515
  ? terminateRunnerBeforeProceed(pid)
492
- : runnerIdentity !== undefined && runnerIdentity.pidNamespaceScope === currentPidNamespaceScope() && terminateRunnerBeforeProceed(runnerIdentity.pid);
516
+ : runnerIdentity !== undefined && runnerIdentity.pidNamespaceScope === currentPidNamespaceScope()
517
+ && isInProcessTree(runnerIdentity.pid, pid) && terminateRunnerBeforeProceed(runnerIdentity.pid);
493
518
  const adoptRunnerIdentity = (pid, pidNamespaceScope) => {
494
519
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid < 1)
495
520
  return `Async runner reported an invalid process identity in '${launchAsyncDir}'.`;
@@ -955,11 +980,11 @@ export function buildAsyncRunnerSteps(id, params) {
955
980
  taskTemplate = taskTemplate.replace(/\{chain_dir\}/g, behaviorCwd ?? runnerCwd);
956
981
  const taskText = `${readInstructions.prefix}${taskTemplate}${progressInstructions.suffix}`;
957
982
  // A namespaced parallel output path is added to each child's task by the runner.
958
- const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a);
983
+ const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a, machine);
959
984
  const modelScopes = resolveModelScopesForAgent(ctx.modelScope, a.name, ctx.currentModel, ctx.scopedModelIds);
960
985
  const modelOrigin = resolveModelOrigin({ explicitModel: s.model, agentModel: a.model, parentModel: ctx.currentModel });
961
986
  const primaryModelFromParent = modelOrigin === "inherited";
962
- const primaryModel = externalRunner ? undefined : resolveEffectiveSubagentModel(s.model, a.model, ctx.currentModel, availableModels, a.modelProvider ?? ctx.currentModelProvider, { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" });
987
+ const primaryModel = externalRunner ? undefined : resolveEffectiveSubagentModel(s.model, a.model, ctx.currentModel, availableModels, a.modelProvider ?? ctx.currentModelProvider, { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited", knownProviders: ctx.knownProviders });
963
988
  const thinkingOverride = flatIndex === undefined ? undefined : thinkingOverridesByFlatIndex?.[flatIndex];
964
989
  let claudeCodeOverride;
965
990
  if (claudeCodeAdapter) {
@@ -1001,6 +1026,7 @@ export function buildAsyncRunnerSteps(id, params) {
1001
1026
  scope: modelScopes,
1002
1027
  primaryModelFromParent,
1003
1028
  origin: modelOrigin,
1029
+ knownProviders: ctx.knownProviders,
1004
1030
  });
1005
1031
  requestedModel = modelEvidence.requestedModel;
1006
1032
  selectedModel = applyThinkingSuffix(modelEvidence.model, effectiveThinking, thinkingOverride !== undefined);
@@ -1014,7 +1040,8 @@ export function buildAsyncRunnerSteps(id, params) {
1014
1040
  if (launchRuleError)
1015
1041
  throw new AsyncStartValidationError(launchRuleError);
1016
1042
  const fast = s.fast ?? params.fast ?? a.fast;
1017
- const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
1043
+ // Admission already refused mandatory entries for a placed child, which skips the rest.
1044
+ const requiredExtensions = externalRunner || machine ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
1018
1045
  const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
1019
1046
  const toolPlan = resolvePiLaunchToolPlan({
1020
1047
  tools: a.tools,
@@ -1265,9 +1292,6 @@ export function buildAsyncRunnerSteps(id, params) {
1265
1292
  throw error;
1266
1293
  }
1267
1294
  }
1268
- /**
1269
- * Execute a chain asynchronously
1270
- */
1271
1295
  export function executeAsyncChain(id, params) {
1272
1296
  const { chain, agents, ctx, cwd, maxOutput, artifactsDir, artifactConfig, shareEnabled, sessionRoot, sessionFilesByFlatIndex, thinkingOverridesByFlatIndex, maxSubagentDepth, worktreeSetupHook, worktreeSetupHookTimeoutMs, worktreeBaseDir, baseRef, worktreeProvider, worktreeBranchPrefix, controlConfig, controlIntercomTarget, childIntercomTarget, nestedRoute, } = params;
1273
1297
  const resultMode = params.resultMode ?? "chain";
@@ -1592,14 +1616,12 @@ export function executeAsyncChain(id, params) {
1592
1616
  };
1593
1617
  return spawnResultOrPromise instanceof Promise ? spawnResultOrPromise.then(finishSpawnResult) : finishSpawnResult(spawnResultOrPromise);
1594
1618
  }
1595
- /**
1596
- * Execute a single agent asynchronously
1597
- */
1598
1619
  export function workflowAwaitedAsyncResultPath(asyncDir) {
1599
1620
  return path.join(asyncDir, "workflow-result.json");
1600
1621
  }
1601
1622
  export function executeAsyncSingle(id, params) {
1602
- const { agent, agentConfig, ctx, cwd, maxOutput, artifactsDir, artifactConfig, shareEnabled, sessionRoot, sessionFile, maxSubagentDepth, worktreeSetupHook, worktreeSetupHookTimeoutMs, worktreeBaseDir, baseRef, worktreeProvider, worktreeBranchPrefix, controlConfig, controlIntercomTarget, childIntercomTarget, nestedRoute, } = params;
1623
+ const { agent, ctx, cwd, maxOutput, artifactsDir, artifactConfig, shareEnabled, sessionRoot, sessionFile, maxSubagentDepth, worktreeSetupHook, worktreeSetupHookTimeoutMs, worktreeBaseDir, baseRef, worktreeProvider, worktreeBranchPrefix, controlConfig, controlIntercomTarget, childIntercomTarget, nestedRoute, } = params;
1624
+ let agentConfig = params.agentConfig;
1603
1625
  let lane;
1604
1626
  try {
1605
1627
  lane = normalizeWorkflowLaneMetadata(params.lane, "lane");
@@ -1672,6 +1694,13 @@ export function executeAsyncSingle(id, params) {
1672
1694
  if (resolvedLauncher.error)
1673
1695
  return formatAsyncStartError("single", resolvedLauncher.error);
1674
1696
  const launcher = resolvedLauncher.launcher;
1697
+ if (params.requireLauncher) {
1698
+ const required = checkRequiredRunnerLauncher(agentConfig, launcher?.name, params.requireLauncher);
1699
+ if (required.error !== undefined)
1700
+ return formatAsyncStartError("single", required.error);
1701
+ // The launch records the digest it checked, not a second hash of an agent file that may have changed since.
1702
+ agentConfig = { ...agentConfig, definitionDigest: required.definitionDigest };
1703
+ }
1675
1704
  const registeredExtensions = resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? undefined);
1676
1705
  try {
1677
1706
  assertRequiredChildExtensionsAdmitted([params.requiredExtensions, ctx.childRuntime?.requiredExtensions, registeredExtensions], { agent: agentConfig.name, runnerType: agentConfig.runner?.type, machine: requestedMachine });
@@ -1741,7 +1770,7 @@ export function executeAsyncSingle(id, params) {
1741
1770
  const validationError = validateFileOnlyOutputMode(outputMode, outputPath, `Async single run (${agent})`);
1742
1771
  if (validationError)
1743
1772
  return formatAsyncStartError("single", validationError);
1744
- const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, agentConfig);
1773
+ const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, agentConfig, machine);
1745
1774
  // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
1746
1775
  // absolute paths pass through; relative paths resolve against the child cwd.
1747
1776
  const reads = params.reads !== undefined ? params.reads : agentConfig.defaultReads ?? false;
@@ -1770,7 +1799,7 @@ export function executeAsyncSingle(id, params) {
1770
1799
  try {
1771
1800
  primaryModel = externalRunner ? undefined : modelOrigin === "inherited"
1772
1801
  ? params.modelOverride ?? (ctx.currentModel ? `${ctx.currentModel.provider}/${ctx.currentModel.id}` : undefined)
1773
- : resolveSubagentModelOverride(params.modelOverride ?? agentConfig.model, ctx.currentModel, availableModels, ctx.currentModelProvider, { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" });
1802
+ : resolveSubagentModelOverride(params.modelOverride ?? agentConfig.model, ctx.currentModel, availableModels, ctx.currentModelProvider, { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited", knownProviders: ctx.knownProviders });
1774
1803
  }
1775
1804
  catch (error) {
1776
1805
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
@@ -1837,6 +1866,7 @@ export function executeAsyncSingle(id, params) {
1837
1866
  scope: modelScopes,
1838
1867
  primaryModelFromParent: modelOrigin === "inherited",
1839
1868
  origin: modelOrigin,
1869
+ knownProviders: ctx.knownProviders,
1840
1870
  });
1841
1871
  requestedModel = modelEvidence.requestedModel;
1842
1872
  selectedModel = applyThinkingSuffix(modelEvidence.model, effectiveThinking, params.thinkingOverride !== undefined);
@@ -1846,7 +1876,8 @@ export function executeAsyncSingle(id, params) {
1846
1876
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
1847
1877
  }
1848
1878
  }
1849
- const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
1879
+ // Admission already refused mandatory entries for a placed child, which skips the rest.
1880
+ const requiredExtensions = externalRunner || machine ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
1850
1881
  const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
1851
1882
  const toolPlan = resolvePiLaunchToolPlan({
1852
1883
  tools: agentConfig.tools,
@@ -1903,6 +1934,7 @@ export function executeAsyncSingle(id, params) {
1903
1934
  agentContract: params.agentContract,
1904
1935
  });
1905
1936
  const recoveryAgentConfig = params.recoveryAgentConfig ?? agentConfig;
1937
+ const requiredLauncher = params.requireLauncher ?? params.carriedRequiredLauncher;
1906
1938
  const recoveryDescriptor = {
1907
1939
  ...(ctx.modelResponseAliases ? { modelResponseAliases: ctx.modelResponseAliases } : {}),
1908
1940
  version: 1,
@@ -1912,6 +1944,10 @@ export function executeAsyncSingle(id, params) {
1912
1944
  ...(requiredExtensions.length > 0 ? { requiredExtensions } : {}),
1913
1945
  runFanoutBudget,
1914
1946
  sourceRunId: id,
1947
+ ...(ctx.currentSessionId ? { sessionId: ctx.currentSessionId } : {}),
1948
+ // The worktree the runner will create, fixed here from launch inputs (the runner's own naming call).
1949
+ ...(managedWorktreeProvider === "native" ? { managedWorktree: { provider: "native", cwd: instructionCwd } } : {}),
1950
+ ...(managedWorktreeProvider === "worktrunk" ? { managedWorktree: { provider: "worktrunk", branch: buildWorktreeNaming({ runId: `${id}-s0`, index: 0, agent, label: lane?.key ?? params.workflowKey, task: taskText, branchPrefix: worktreeBranchPrefix }).requestedBranch } } : {}),
1915
1951
  ...(params.agentContract ? { agentContract: params.agentContract } : {}),
1916
1952
  agent,
1917
1953
  ...(sandbox ? { sandbox } : {}),
@@ -1950,7 +1986,8 @@ export function executeAsyncSingle(id, params) {
1950
1986
  ...(params.context ? { context: params.context } : {}),
1951
1987
  ...(params.intercomBridge !== undefined ? { intercomBridge: params.intercomBridge } : {}),
1952
1988
  ...(params.baseRef !== undefined ? { baseRef: params.baseRef } : {}),
1953
- ...(launcher ? { launcher: launcher.name } : {}),
1989
+ launcher: launcher ? launcher.name : null,
1990
+ ...(requiredLauncher ? { requiredLauncher } : {}),
1954
1991
  ...(deadlineAt !== undefined ? { absoluteDeadlineAt: deadlineAt } : {}),
1955
1992
  ...(resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {}),
1956
1993
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, recoveryAgentConfig.maxSubagentDepth),
@@ -1963,7 +2000,7 @@ export function executeAsyncSingle(id, params) {
1963
2000
  };
1964
2001
  if (!externalRunner) {
1965
2002
  try {
1966
- writePrivateAtomicJson(path.join(asyncDir, "recovery-descriptor.json"), recoveryDescriptor);
2003
+ writePrivateAtomicJson(recoveryDescriptorPath(path.dirname(asyncDir), id), recoveryDescriptor);
1967
2004
  }
1968
2005
  catch (error) {
1969
2006
  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;
@@ -750,7 +751,18 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
750
751
  if (now >= nextLivenessAt) {
751
752
  nextLivenessAt = now + livenessIntervalMs;
752
753
  let widgetChanged = false;
754
+ // A session reopened in this process takes its runs back from the session that replaced it.
755
+ const owners = state.currentSessionId ? ownerSessionIds(state.currentSessionId) : undefined;
753
756
  for (const job of state.asyncJobs.values()) {
757
+ if (owners && job.sessionId !== undefined && !owners.has(job.sessionId)) {
758
+ cancelCleanup(job.asyncId);
759
+ closeJobWatcher(job.asyncId);
760
+ state.asyncJobs.delete(job.asyncId);
761
+ state.fleetJobs?.delete(job.asyncId);
762
+ options.onJobCleanup?.(job.asyncId);
763
+ widgetChanged = true;
764
+ continue;
765
+ }
754
766
  watchJob(job);
755
767
  if (refreshJob(job))
756
768
  widgetChanged = true;
@@ -53,8 +53,9 @@ export declare function findAsyncRunPrefixMatches(prefix: string, asyncDirRoot:
53
53
  location: AsyncRunLocation;
54
54
  }>;
55
55
  export declare function resolveAsyncRunLocation(params: AsyncResumeParams, asyncDirRoot: string, resultsDir: string): AsyncRunLocation;
56
+ /** A workflow-mode target has a ceiling only when its parent-owned launch record exists (resolveAsyncResumeTarget). */
56
57
  export declare function asyncReviveRequiresRecoveryDescriptor(target: Pick<AsyncResumeTarget, "recoveryDescriptor" | "mode" | "sessionFile" | "capabilityCeiling">): boolean;
57
- export declare function readAsyncRecoveryDescriptor(asyncDir: string | undefined): SteeringRecoveryDescriptor | undefined;
58
+ export declare function readAsyncRecoveryDescriptor(runsRoot: string, runId: string): SteeringRecoveryDescriptor | undefined;
58
59
  export declare function resolveAsyncResumeTarget(params: AsyncResumeParams, deps?: AsyncResumeDeps, options?: AsyncResumeOptions): AsyncResumeTarget;
59
60
  export declare function applySteeringRecoveryAgentConfig(agentConfig: AgentConfig, descriptor: SteeringRecoveryDescriptor): AgentConfig;
60
61
  export declare function buildRevivedAsyncTask(target: AsyncResumeTarget, message: string): string;