@xzzpig/pi-subagents 0.24.2 → 0.25.1

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 +37 -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-EUPJB4S7.js → chunk-5Z7JAORM.js} +196 -1219
  8. package/bundle/{chunk-LCDJWBVM.js → chunk-66JNFRFS.js} +1 -1
  9. package/bundle/{chunk-ED55MIC2.js → chunk-CGFF4WA3.js} +42 -19
  10. package/bundle/{chunk-TMHVDPYW.js → chunk-DLVPMML3.js} +263 -154
  11. package/bundle/{chunk-RU522D5W.js → chunk-FQPV4O6C.js} +183 -28
  12. package/bundle/chunk-HXRB42AF.js +108 -0
  13. package/bundle/{chunk-355ECEP2.js → chunk-IH7LQVEE.js} +29 -14
  14. package/bundle/{chunk-Z6TFJ6BR.js → chunk-INWSUNI6.js} +1 -1
  15. package/bundle/{chunk-CYY5UMJU.js → chunk-IXCEOEJT.js} +411 -249
  16. package/bundle/{chunk-WW76JRIX.js → chunk-JAXVBXGF.js} +1 -1
  17. package/bundle/{chunk-ICNYIALB.js → chunk-JH5H4CYJ.js} +784 -474
  18. package/bundle/{chunk-224WMDIV.js → chunk-JUYNN63E.js} +350 -123
  19. package/bundle/{chunk-35GII5EF.js → chunk-JWFLPSTP.js} +41 -117
  20. package/bundle/{chunk-XWWUDWUW.js → chunk-KRNBJPZ2.js} +670 -400
  21. package/bundle/{chunk-RB4GELQA.js → chunk-LPJEKHOY.js} +1 -1
  22. package/bundle/chunk-LYKG4FKH.js +523 -0
  23. package/bundle/{chunk-X6LOM3Z4.js → chunk-LZ3HBDTR.js} +161 -78
  24. package/bundle/{chunk-JEA2ZKUA.js → chunk-MMJQMPOK.js} +37 -165
  25. package/bundle/{chunk-FG6SQJAR.js → chunk-OGPOCGWX.js} +24 -6
  26. package/bundle/{chunk-FJWI64H7.js → chunk-RMSABUN3.js} +27 -13
  27. package/bundle/{chunk-H36HBZB2.js → chunk-SJPABBZG.js} +2 -2
  28. package/bundle/{chunk-4UH4WS4G.js → chunk-SNDCIJMK.js} +23 -12
  29. package/bundle/{chunk-O4D5PBVI.js → chunk-TM2K53NX.js} +3 -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-BQ2OAB4Q.js → chunk-WWDUNXSE.js} +67 -30
  34. package/bundle/{chunk-V2KFIGFH.js → chunk-XAC2XNAP.js} +503 -304
  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/package.json +2 -2
  49. package/skills/pi-subagents/SKILL.md +15 -6
  50. package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
  51. package/src/agents/agent-management.d.ts +1 -0
  52. package/src/agents/agent-management.js +46 -18
  53. package/src/agents/agent-memory.d.ts +1 -4
  54. package/src/agents/agent-memory.js +1 -4
  55. package/src/agents/agent-serializer.d.ts +2 -0
  56. package/src/agents/agent-serializer.js +1 -1
  57. package/src/agents/agents.d.ts +2 -3
  58. package/src/agents/agents.js +46 -20
  59. package/src/agents/frontmatter.js +1 -8
  60. package/src/agents/global-npm-root.d.ts +1 -0
  61. package/src/agents/global-npm-root.js +11 -3
  62. package/src/agents/skills.d.ts +0 -3
  63. package/src/agents/skills.js +0 -3
  64. package/src/api/preflight.d.ts +3 -1
  65. package/src/api/preflight.js +2 -0
  66. package/src/extension/config.d.ts +1 -0
  67. package/src/extension/config.js +13 -1
  68. package/src/extension/herdr-pi-bridge.js +10 -2
  69. package/src/extension/index.d.ts +0 -13
  70. package/src/extension/index.js +51 -37
  71. package/src/extension/public-execution.d.ts +1 -0
  72. package/src/extension/public-execution.js +4 -0
  73. package/src/extension/reply-workflow-script.js +24 -4
  74. package/src/extension/schemas.d.ts +12 -3
  75. package/src/extension/schemas.js +7 -3
  76. package/src/extension/session-switch.d.ts +25 -0
  77. package/src/extension/session-switch.js +138 -0
  78. package/src/extension/subagent-guide.d.ts +1 -1
  79. package/src/extension/subagent-guide.js +1 -1
  80. package/src/extension/subagent-launch-tool.d.ts +25 -0
  81. package/src/extension/subagent-launch-tool.js +48 -0
  82. package/src/extension/tool-activation.js +55 -15
  83. package/src/extension/tool-description.d.ts +1 -1
  84. package/src/extension/tool-description.js +14 -8
  85. package/src/inspectors/herdr/actions.d.ts +0 -1
  86. package/src/inspectors/herdr/actions.js +0 -1
  87. package/src/inspectors/session-roots-codec.d.ts +0 -1
  88. package/src/inspectors/session-roots-codec.js +0 -1
  89. package/src/inspectors/tmux/actions.d.ts +0 -1
  90. package/src/inspectors/tmux/actions.js +0 -1
  91. package/src/integrations/herdr-status.js +3 -8
  92. package/src/intercom/native-supervisor-channel.js +65 -9
  93. package/src/runs/background/async-execution.d.ts +7 -10
  94. package/src/runs/background/async-execution.js +66 -29
  95. package/src/runs/background/async-job-tracker.js +12 -0
  96. package/src/runs/background/async-resume.d.ts +2 -1
  97. package/src/runs/background/async-resume.js +114 -40
  98. package/src/runs/background/async-retention.d.ts +0 -2
  99. package/src/runs/background/async-retention.js +17 -6
  100. package/src/runs/background/async-status.d.ts +2 -0
  101. package/src/runs/background/async-status.js +4 -0
  102. package/src/runs/background/auto-drain.js +2 -1
  103. package/src/runs/background/boot-id.d.ts +1 -3
  104. package/src/runs/background/boot-id.js +1 -3
  105. package/src/runs/background/completion-batcher.d.ts +3 -4
  106. package/src/runs/background/completion-batcher.js +2 -3
  107. package/src/runs/background/control-channel.d.ts +0 -6
  108. package/src/runs/background/control-channel.js +0 -6
  109. package/src/runs/background/fleet-view.js +2 -3
  110. package/src/runs/background/notify.d.ts +0 -2
  111. package/src/runs/background/notify.js +0 -2
  112. package/src/runs/background/result-watcher.d.ts +1 -0
  113. package/src/runs/background/result-watcher.js +59 -29
  114. package/src/runs/background/resume-guidance.js +4 -2
  115. package/src/runs/background/retained-children.js +2 -1
  116. package/src/runs/background/run-child-session.d.ts +2 -3
  117. package/src/runs/background/run-child-session.js +5 -8
  118. package/src/runs/background/run-status.js +9 -7
  119. package/src/runs/background/runner-aliases.js +15 -0
  120. package/src/runs/background/scheduled-runs.d.ts +3 -1
  121. package/src/runs/background/scheduled-runs.js +13 -16
  122. package/src/runs/background/steering.d.ts +2 -11
  123. package/src/runs/background/steering.js +11 -6
  124. package/src/runs/background/subagent-runner.d.ts +2 -6
  125. package/src/runs/background/subagent-runner.js +88 -70
  126. package/src/runs/background/subagent-wait.js +12 -15
  127. package/src/runs/background/wait-config.d.ts +2 -0
  128. package/src/runs/background/wait-config.js +17 -3
  129. package/src/runs/background/wait-subscriptions.js +124 -12
  130. package/src/runs/background/wait-tool.js +4 -2
  131. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  132. package/src/runs/background/workflow-terminal-proof.js +0 -1
  133. package/src/runs/foreground/async-steering-action.js +24 -9
  134. package/src/runs/foreground/async-stop-action.d.ts +1 -1
  135. package/src/runs/foreground/async-stop-action.js +9 -1
  136. package/src/runs/foreground/execution.d.ts +0 -3
  137. package/src/runs/foreground/execution.js +68 -84
  138. package/src/runs/foreground/fork-tool-result-handler.d.ts +60 -0
  139. package/src/runs/foreground/fork-tool-result-handler.js +83 -0
  140. package/src/runs/foreground/prompt-audit.js +1 -0
  141. package/src/runs/foreground/subagent-executor.d.ts +5 -10
  142. package/src/runs/foreground/subagent-executor.js +164 -49
  143. package/src/runs/shared/acceptance.js +69 -26
  144. package/src/runs/shared/async-status-projection.d.ts +2 -0
  145. package/src/runs/shared/async-status-projection.js +10 -0
  146. package/src/runs/shared/child-commands.js +15 -2
  147. package/src/runs/shared/child-hooks.d.ts +1 -7
  148. package/src/runs/shared/child-hooks.js +13 -5
  149. package/src/runs/shared/child-launch.js +6 -2
  150. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  151. package/src/runs/shared/child-session.d.ts +6 -5
  152. package/src/runs/shared/child-session.js +85 -38
  153. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  154. package/src/runs/shared/child-tool-plan.js +0 -1
  155. package/src/runs/shared/claude-code-adapter.js +11 -0
  156. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  157. package/src/runs/shared/external-cli-contract.js +18 -13
  158. package/src/runs/shared/external-cli-runner.js +26 -6
  159. package/src/runs/shared/herdr-connection.js +2 -1
  160. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  161. package/src/runs/shared/herdr-pane-host.js +17 -1
  162. package/src/runs/shared/herdr-placed-run.js +51 -24
  163. package/src/runs/shared/lane-metadata.d.ts +0 -1
  164. package/src/runs/shared/lane-metadata.js +0 -1
  165. package/src/runs/shared/mcp-config-sources.d.ts +4 -1
  166. package/src/runs/shared/mcp-config-sources.js +1 -1
  167. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -3
  168. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -17
  169. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  170. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  171. package/src/runs/shared/model-resolution.d.ts +20 -5
  172. package/src/runs/shared/model-resolution.js +55 -50
  173. package/src/runs/shared/model-scope.d.ts +1 -5
  174. package/src/runs/shared/model-scope.js +1 -5
  175. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  176. package/src/runs/shared/mutation-evidence.js +52 -7
  177. package/src/runs/shared/nested-events.d.ts +1 -0
  178. package/src/runs/shared/nested-events.js +1 -1
  179. package/src/runs/shared/parallel-utils.d.ts +0 -1
  180. package/src/runs/shared/permissions.js +5 -3
  181. package/src/runs/shared/placement-host.d.ts +5 -1
  182. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  183. package/src/runs/shared/rex-pane-host.js +0 -2
  184. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  185. package/src/runs/shared/run-launch-folder.js +21 -0
  186. package/src/runs/shared/runner-launcher.d.ts +12 -1
  187. package/src/runs/shared/runner-launcher.js +16 -0
  188. package/src/runs/shared/single-output.d.ts +3 -3
  189. package/src/runs/shared/single-output.js +5 -3
  190. package/src/runs/shared/structured-output.d.ts +8 -0
  191. package/src/runs/shared/structured-output.js +40 -5
  192. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  193. package/src/runs/shared/subagent-prompt-runtime.js +18 -4
  194. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  195. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  196. package/src/runs/shared/tool-timeout.js +2 -1
  197. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  198. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  199. package/src/runs/shared/worktree.d.ts +3 -0
  200. package/src/runs/shared/worktree.js +20 -0
  201. package/src/shared/artifacts.d.ts +1 -0
  202. package/src/shared/artifacts.js +132 -22
  203. package/src/shared/capacity-resilient-json.d.ts +1 -1
  204. package/src/shared/child-cache-retention.d.ts +1 -2
  205. package/src/shared/child-cache-retention.js +1 -2
  206. package/src/shared/fleet-transcript-reader.d.ts +64 -0
  207. package/src/shared/fleet-transcript-reader.js +376 -0
  208. package/src/shared/formatters.d.ts +0 -18
  209. package/src/shared/formatters.js +0 -18
  210. package/src/shared/pruned-fork.js +2 -2
  211. package/src/shared/reported-progress.d.ts +1 -0
  212. package/src/shared/reported-progress.js +12 -0
  213. package/src/shared/session-succession.d.ts +16 -1
  214. package/src/shared/session-succession.js +41 -2
  215. package/src/shared/session-warnings.d.ts +7 -0
  216. package/src/shared/session-warnings.js +26 -0
  217. package/src/shared/settings.d.ts +0 -23
  218. package/src/shared/settings.js +3 -35
  219. package/src/shared/status-format.d.ts +1 -0
  220. package/src/shared/status-format.js +1 -1
  221. package/src/shared/types.d.ts +108 -59
  222. package/src/shared/types.js +0 -12
  223. package/src/shared/utils.d.ts +3 -15
  224. package/src/shared/utils.js +4 -22
  225. package/src/shared/wait-tool-name.d.ts +8 -0
  226. package/src/shared/wait-tool-name.js +13 -0
  227. package/src/slash/slash-commands.js +2 -1
  228. package/src/slash/subagent-cost.d.ts +3 -2
  229. package/src/slash/subagent-cost.js +22 -3
  230. package/src/slash/subagents-admin.js +0 -1
  231. package/src/tui/fleet-native-transcript.js +1 -1
  232. package/src/tui/fleet-status.d.ts +0 -5
  233. package/src/tui/fleet-status.js +4 -24
  234. package/src/tui/fleet-transcript.d.ts +1 -57
  235. package/src/tui/fleet-transcript.js +4 -370
  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
@@ -1149,13 +1149,34 @@ function verifyRedactionEnv(env) {
1149
1149
  return value.length >= 4 && SENSITIVE_ENV_KEY_PATTERN.test(key);
1150
1150
  }));
1151
1151
  }
1152
- function redactVerifyEnv(value, env) {
1152
+ function verifySecrets(env) {
1153
+ return [...new Set(Object.values(verifyRedactionEnv(env)).filter(Boolean))].sort((left, right) => right.length - left.length);
1154
+ }
1155
+ function redactSecrets(value, secrets) {
1153
1156
  let redacted = value;
1154
- const secrets = [...new Set(Object.values(verifyRedactionEnv(env)).filter(Boolean))].sort((left, right) => right.length - left.length);
1155
1157
  for (const secret of secrets)
1156
1158
  redacted = redacted.replaceAll(secret, "[REDACTED]");
1157
1159
  return redacted;
1158
1160
  }
1161
+ function redactVerifyEnv(value, env) {
1162
+ return redactSecrets(value, verifySecrets(env));
1163
+ }
1164
+ /** Numbers are matched on their source text: parsing rounds or respells them (12345678901234567890, 1.50), which would hide a secret. */
1165
+ function parseRedactedVerifyValue(text, secrets) {
1166
+ return JSON.parse(text, (_key, value, context) => {
1167
+ if (typeof value === "string")
1168
+ return redactSecrets(value, secrets);
1169
+ if (typeof value === "number" && secrets.length > 0) {
1170
+ // Node 22+ and Bun pass the source text; without it, fail closed.
1171
+ const source = context?.source;
1172
+ return source !== undefined && redactSecrets(source, secrets) === source ? value : "[REDACTED]";
1173
+ }
1174
+ if (value && typeof value === "object" && !Array.isArray(value)) {
1175
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [redactSecrets(key, secrets), item]));
1176
+ }
1177
+ return value;
1178
+ });
1179
+ }
1159
1180
  function uniqueStrings(items) {
1160
1181
  return unique(items.map((item) => item?.trim()).filter((item) => Boolean(item)));
1161
1182
  }
@@ -1223,34 +1244,49 @@ const TYPED_VERIFY_OUTPUT_MAX_BYTES = 12_000;
1223
1244
  * A passing `output: "json"` command must print one JSON document on stdout.
1224
1245
  * The parsed value becomes the run's structured output; anything else turns
1225
1246
  * the passing run into a failed one so acceptance rejects rather than
1226
- * silently dropping the verdict. Stdout is already bounded by trimOutput, so a
1227
- * truncated document is detected by its marker instead of a parse guess.
1247
+ * silently dropping the verdict. The raw stdout is parsed, because the stored
1248
+ * stdout is redacted and redaction can hit JSON syntax (`true` in KDE_FULL_SESSION).
1249
+ * The schema checks the raw value so a redacted string cannot fail a correct
1250
+ * gate. Error messages quote parts of their input (a parse error quotes ~10
1251
+ * chars, schema paths escape `/` and `~`), so each one is built from the
1252
+ * redacted text or value, never the raw one.
1228
1253
  */
1229
- async function applyTypedVerifyOutput(command, run) {
1254
+ async function applyTypedVerifyOutput(command, run, rawStdout) {
1230
1255
  if (run.status !== "passed")
1231
1256
  return;
1232
- const stdout = run.stdout ?? "";
1257
+ const secrets = verifySecrets(command.env);
1258
+ const stdout = rawStdout.trim();
1233
1259
  const fail = (message) => {
1234
1260
  run.status = "failed";
1235
- run.structuredOutputError = message;
1261
+ run.structuredOutputError = redactSecrets(message, secrets);
1236
1262
  };
1237
- if (!stdout.trim())
1263
+ if (!stdout)
1238
1264
  return fail("output: \"json\" command printed nothing on stdout.");
1239
- if (stdout.endsWith("...[truncated]"))
1265
+ if (stdout.length > TYPED_VERIFY_OUTPUT_MAX_BYTES)
1240
1266
  return fail(`output: "json" stdout exceeded ${TYPED_VERIFY_OUTPUT_MAX_BYTES} characters and was truncated.`);
1241
1267
  let value;
1242
1268
  try {
1243
1269
  value = JSON.parse(stdout);
1244
1270
  }
1245
- catch (error) {
1246
- return fail(`output: "json" stdout is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
1271
+ catch {
1272
+ let reason = "parse failed";
1273
+ try {
1274
+ JSON.parse(redactSecrets(stdout, secrets));
1275
+ }
1276
+ catch (error) {
1277
+ reason = error instanceof Error ? error.message : String(error);
1278
+ }
1279
+ return fail(`output: "json" stdout is not valid JSON: ${reason}`);
1247
1280
  }
1281
+ const redactedValue = parseRedactedVerifyValue(stdout, secrets);
1248
1282
  if (command.schema) {
1249
1283
  const validation = await validateStructuredOutputValue(command.schema, value);
1250
- if (validation.status === "invalid")
1251
- return fail(`output: "json" stdout does not match gate.schema: ${validation.message}`);
1284
+ if (validation.status === "invalid") {
1285
+ const redactedValidation = await validateStructuredOutputValue(command.schema, redactedValue);
1286
+ return fail(`output: "json" stdout does not match gate.schema${redactedValidation.status === "invalid" ? `: ${redactedValidation.message}` : "."}`);
1287
+ }
1252
1288
  }
1253
- run.structuredOutput = value;
1289
+ run.structuredOutput = redactedValue;
1254
1290
  }
1255
1291
  /** The first typed verify result on a ledger, if any command produced one. */
1256
1292
  export function typedVerifyOutput(ledger) {
@@ -1258,6 +1294,13 @@ export function typedVerifyOutput(ledger) {
1258
1294
  return run ? { value: run.structuredOutput } : undefined;
1259
1295
  }
1260
1296
  async function runMemoizedVerifyCommand(command, defaultCwd, options = {}) {
1297
+ // Typed gates read inputs (a report file, a log) that can change without
1298
+ // the tracked tree changing, so their verdicts are never reused.
1299
+ if (command.output === "json") {
1300
+ const { run, rawStdout } = await runVerifyCommand(command, defaultCwd, options);
1301
+ await applyTypedVerifyOutput(command, run, rawStdout);
1302
+ return run;
1303
+ }
1261
1304
  const cwd = command.cwd ? path.resolve(defaultCwd, command.cwd) : defaultCwd;
1262
1305
  let workspaceState;
1263
1306
  try {
@@ -1266,10 +1309,8 @@ async function runMemoizedVerifyCommand(command, defaultCwd, options = {}) {
1266
1309
  catch {
1267
1310
  workspaceState = undefined;
1268
1311
  }
1269
- // Typed gates read inputs (a report file, a log) that can change without
1270
- // the tracked tree changing, so their verdicts are never reused.
1271
- if (!workspaceState || !options.artifactsDir || !options.runId || command.output === "json") {
1272
- return runVerifyCommand(command, defaultCwd, options);
1312
+ if (!workspaceState || !options.artifactsDir || !options.runId) {
1313
+ return (await runVerifyCommand(command, defaultCwd, options)).run;
1273
1314
  }
1274
1315
  const envKeys = Object.keys(command.env ?? {}).sort();
1275
1316
  const envHash = hash(JSON.stringify(Object.fromEntries(Object.entries(effectiveVerifyEnv(command.env)).sort(([left], [right]) => left.localeCompare(right)))));
@@ -1295,7 +1336,7 @@ async function runMemoizedVerifyCommand(command, defaultCwd, options = {}) {
1295
1336
  catch {
1296
1337
  // A cache miss or unreadable artifact must not prevent host verification.
1297
1338
  }
1298
- const result = await runVerifyCommand(command, defaultCwd, options);
1339
+ const { run: result } = await runVerifyCommand(command, defaultCwd, options);
1299
1340
  const evidenced = { ...result, artifactPath, cacheKey, memoized: false, envKeys, envHash, workspaceState };
1300
1341
  try {
1301
1342
  fs.mkdirSync(path.dirname(artifactPath), { recursive: true });
@@ -1363,6 +1404,7 @@ export function quoteExecutableForShell(command, platform = process.platform) {
1363
1404
  }
1364
1405
  return command;
1365
1406
  }
1407
+ /** `rawStdout` is unredacted and never stored; only typed output parsing reads it. */
1366
1408
  function runVerifyCommand(command, defaultCwd, options = {}) {
1367
1409
  return new Promise((resolve) => {
1368
1410
  const startedAt = Date.now();
@@ -1388,11 +1430,14 @@ function runVerifyCommand(command, defaultCwd, options = {}) {
1388
1430
  clearTimeout(hardKill);
1389
1431
  options.signal?.removeEventListener("abort", abortVerification);
1390
1432
  resolve({
1391
- id: command.id,
1392
- command: command.command,
1393
- cwd,
1394
- durationMs: Date.now() - startedAt,
1395
- ...result,
1433
+ run: {
1434
+ id: command.id,
1435
+ command: command.command,
1436
+ cwd,
1437
+ durationMs: Date.now() - startedAt,
1438
+ ...result,
1439
+ },
1440
+ rawStdout: stdout,
1396
1441
  });
1397
1442
  };
1398
1443
  const abortVerification = () => {
@@ -1531,8 +1576,6 @@ export async function evaluateAcceptance(input) {
1531
1576
  artifactsDir: input.artifactsDir,
1532
1577
  runId: input.runId,
1533
1578
  });
1534
- if (command.output === "json")
1535
- await applyTypedVerifyOutput(command, run);
1536
1579
  ledger.verifyRuns.push(run);
1537
1580
  if (input.signal?.aborted)
1538
1581
  break;
@@ -33,6 +33,8 @@ export interface AsyncStatusSnapshotNode {
33
33
  updatedAt?: number;
34
34
  endedAt?: number;
35
35
  activity?: AsyncStatusSnapshotActivity;
36
+ progressText?: string;
37
+ progressUpdatedAt?: number;
36
38
  /** Step nodes only: the agent the child runs as, and the model and thinking level it reports. */
37
39
  agent?: string;
38
40
  model?: string;
@@ -137,6 +137,8 @@ function projectStep(step, index, depth, ctx) {
137
137
  const activity = activityFor(step, ctx);
138
138
  const { id, label } = stepIdentity(step, index, ctx);
139
139
  const agent = publicOptionalText(step.agent, ctx.caps.maxStringLength);
140
+ const progressText = publicOptionalText(step.progressText, ctx.caps.maxStringLength);
141
+ const progressUpdatedAt = publicTime(step.progressUpdatedAt);
140
142
  const node = {
141
143
  id,
142
144
  kind: "step",
@@ -146,6 +148,8 @@ function projectStep(step, index, depth, ctx) {
146
148
  ...(updatedAt !== undefined ? { updatedAt } : {}),
147
149
  ...(terminalState(state) && endedAt !== undefined ? { endedAt } : {}),
148
150
  ...(activity ? { activity } : {}),
151
+ ...(progressText ? { progressText } : {}),
152
+ ...(progressUpdatedAt !== undefined ? { progressUpdatedAt } : {}),
149
153
  };
150
154
  if (agent)
151
155
  node.agent = agent;
@@ -302,6 +306,12 @@ function projectMaterializedStep(step, index, child, depth, ctx, childrenByParen
302
306
  const selfActivity = selfStep ? activityFor(selfStep, ctx) : undefined;
303
307
  const activity = laneActivity || selfActivity || live.activity ? { ...laneActivity, ...selfActivity, ...live.activity } : undefined;
304
308
  const node = { ...live, id, kind: "step", label };
309
+ const progressText = publicOptionalText(selfStep?.progressText ?? step.progressText, ctx.caps.maxStringLength);
310
+ const progressUpdatedAt = publicTime(selfStep?.progressUpdatedAt ?? step.progressUpdatedAt);
311
+ if (progressText)
312
+ node.progressText = progressText;
313
+ if (progressUpdatedAt !== undefined)
314
+ node.progressUpdatedAt = progressUpdatedAt;
305
315
  const agent = publicOptionalText(selfStep?.agent || step.agent, ctx.caps.maxStringLength);
306
316
  if (agent)
307
317
  node.agent = agent;
@@ -135,8 +135,20 @@ export function createChildCommandRuntime(channelDir) {
135
135
  persist();
136
136
  startInbox();
137
137
  let timer;
138
+ let yieldSaveError;
139
+ // A throw from this timer would exit Pi. A closed controller is already cancelling the command; a failed
140
+ // save still yields, and the handle says the saved state is stale.
138
141
  if (typeof yieldTimeMs === "number")
139
- timer = setTimeout(() => operate("yield", toolCallId), yieldTimeMs);
142
+ timer = setTimeout(() => {
143
+ if (closed)
144
+ return;
145
+ try {
146
+ operate("yield", toolCallId);
147
+ }
148
+ catch (error) {
149
+ yieldSaveError = error;
150
+ }
151
+ }, yieldTimeMs);
140
152
  const execution = Promise.resolve().then(() => tool.execute(toolCallId, args, commandSignal, (update) => {
141
153
  job.snapshot.output = text(update);
142
154
  if (job.snapshot.state === "running")
@@ -163,7 +175,8 @@ export function createChildCommandRuntime(channelDir) {
163
175
  const result = await Promise.race([execution.then((value) => ({ value })), yielded.then(() => undefined)]);
164
176
  if (result)
165
177
  return result.value;
166
- return { content: [{ type: "text", text: `Command is still running (toolCallId: ${toolCallId}). This is not a successful exit. Use subagent_command({ action: "status", toolCallId: ${JSON.stringify(toolCallId)} }) to inspect or wait, or action: "cancel" to stop it.\n${job.snapshot.output}` }], details: { command: { ...job.snapshot } } };
178
+ const saveWarning = yieldSaveError === undefined ? "" : `\nThe command's saved state is out of date because it could not be saved: ${yieldSaveError instanceof Error ? yieldSaveError.message : String(yieldSaveError)}`;
179
+ return { content: [{ type: "text", text: `Command is still running (toolCallId: ${toolCallId}). This is not a successful exit. Use subagent_command({ action: "status", toolCallId: ${JSON.stringify(toolCallId)} }) to inspect or wait, or action: "cancel" to stop it.${saveWarning}\n${job.snapshot.output}` }], details: { command: { ...job.snapshot } } };
167
180
  },
168
181
  };
169
182
  },
@@ -1,13 +1,7 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
1
  import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
3
2
  import type { ChildToolDiagnostic } from "./tool-availability.ts";
4
- import type { ChildSessionLaunch } from "./child-session.ts";
3
+ import type { ChildHookExtension, ChildSessionLaunch } from "./child-session.ts";
5
4
  import type { ChildTranscriptWriter } from "../../shared/child-transcript.ts";
6
- /** Inline extension shape accepted by pi's resource loader (`extensionFactories`). */
7
- export interface ChildHookExtension {
8
- name: string;
9
- factory: (pi: ExtensionAPI) => void;
10
- }
11
5
  /** The host's mandatory transcript reporting, owned by the existing hook certificate. */
12
6
  export declare function withChildSessionErrorReporting(session: Omit<ChildSessionLaunch, "onExtensionError">, transcriptWriter: ChildTranscriptWriter | undefined): ChildSessionLaunch;
13
7
  export declare function isReadonlyChildSessionReporting(launch: ChildSessionLaunch): boolean;
@@ -3,6 +3,7 @@ import { ReadonlyDrainObservation } from "./readonly-drain-observation.js";
3
3
  import registerFanoutChildSubagentExtension, { createChildSafeState } from "../../extension/fanout-child.js";
4
4
  import registerSubagentFastModeExtension from "./fast-mode-extension.js";
5
5
  import registerSubagentPromptRuntime, { registerSubagentPromptBoundary } from "./subagent-prompt-runtime.js";
6
+ import { structuredOutputValidatorReady } from "./structured-output.js";
6
7
  import { projectRuntimeAcknowledgedExtensions } from "./runtime-acknowledged-extensions.js";
7
8
  const promptProofs = new WeakMap();
8
9
  function ownedProof(hooks) {
@@ -153,11 +154,18 @@ function childHooks(config, capture, holdFinalDrain) {
153
154
  }
154
155
  const hooks = [
155
156
  { name: "pi-subagents:prompt-runtime", factory: function promptRuntime(pi) {
156
- if (!proof?.observeNext)
157
- return registerSubagentPromptRuntime(pi, runtime);
158
- proof.observation = proof.observeNext;
159
- proof.observeNext = undefined;
160
- registerSubagentPromptRuntime(pi, runtime, proof.observation);
157
+ if (!proof?.observeNext) {
158
+ registerSubagentPromptRuntime(pi, runtime);
159
+ }
160
+ else {
161
+ proof.observation = proof.observeNext;
162
+ proof.observeNext = undefined;
163
+ registerSubagentPromptRuntime(pi, runtime, proof.observation);
164
+ }
165
+ // Pi awaits extension factories, so structured_output's synchronous prepareArguments has its
166
+ // validator before the model can call it.
167
+ if (runtime.structuredOutput)
168
+ return structuredOutputValidatorReady();
161
169
  } },
162
170
  ];
163
171
  if (config.fast)
@@ -15,6 +15,7 @@ import { buildProfileLaunchEnv } from "./profile-launch-env.js";
15
15
  import { isSubagentRuntimeExtensionPath, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan, supervisorChannelDir, } from "./child-tool-plan.js";
16
16
  import { createCapturedChildHooks, withChildSessionErrorReporting } from "./child-hooks.js";
17
17
  import { resolveRequiredChildExtensions } from "../../shared/required-child-extensions.js";
18
+ import { DEFAULT_WAIT_TOOL_NAME, waitToolName } from "../../shared/wait-tool-name.js";
18
19
  /** Environment variable pi-mcp-adapter reads for the tools a child may expose. */
19
20
  export const MCP_DIRECT_TOOLS_ENV = "MCP_DIRECT_TOOLS";
20
21
  export function inheritedChildRuntime(config) {
@@ -35,7 +36,6 @@ export function inheritedChildRuntime(config) {
35
36
  export function createReportedChildSessionInput(launch, transcriptWriter) {
36
37
  return withChildSessionErrorReporting(launch.session, transcriptWriter);
37
38
  }
38
- /** Escape XML-significant characters in a string for safe attribute interpolation. */
39
39
  function escapeXmlAttr(value) {
40
40
  return value
41
41
  .replace(/&/g, "&amp;")
@@ -76,7 +76,10 @@ function childStorage(input) {
76
76
  return { kind: "default" };
77
77
  }
78
78
  export function buildInProcessChildLaunch(input) {
79
- const requiredExtensions = input.requiredExtensions ?? input.inherited?.requiredExtensions ?? resolveRequiredChildExtensions(input.parentSessionId);
79
+ const resolvedRequiredExtensions = input.requiredExtensions ?? input.inherited?.requiredExtensions ?? resolveRequiredChildExtensions(input.parentSessionId);
80
+ // A placed child cannot load local extension paths, so it skips non-mandatory entries like an
81
+ // external runner does; a mandatory one stays and refuses the launch when it is serialized.
82
+ const requiredExtensions = input.machine ? resolvedRequiredExtensions.filter((entry) => entry.requireForAllRunners) : resolvedRequiredExtensions;
80
83
  const agentCapabilityCeiling = input.descendantAllowedAgents === undefined
81
84
  ? undefined
82
85
  : { version: 1, allowedAgents: [...input.descendantAllowedAgents], denyExtensions: false, sources: [`agent:${input.childAgentName}`] };
@@ -179,6 +182,7 @@ export function buildInProcessChildLaunch(input) {
179
182
  waitTool: {
180
183
  enabled: input.waitToolEnabled ?? true,
181
184
  ...(input.waitToolDefaultTimeoutMs !== undefined ? { defaultTimeoutMs: input.waitToolDefaultTimeoutMs } : {}),
185
+ ...(waitToolName() !== DEFAULT_WAIT_TOOL_NAME ? { name: waitToolName() } : {}),
182
186
  },
183
187
  ...(input.structuredOutput
184
188
  ? {
@@ -90,7 +90,6 @@ export interface ChildRuntimeConfig {
90
90
  permissions?: ChildPermissions;
91
91
  toolBudget?: ResolvedToolBudget;
92
92
  childWatchdog?: ChildWatchdogConfig;
93
- /** Receives child watchdog status events. */
94
93
  watchdogStatus?: (event: ChildWatchdogStatusEvent) => void;
95
94
  waitTool: ResolvedWaitToolConfig;
96
95
  runtimeState?: SubagentState;
@@ -16,7 +16,7 @@ export interface ChildSessionExtensionError {
16
16
  }
17
17
  export interface ChildHookExtension {
18
18
  name: string;
19
- factory: (pi: ExtensionAPI) => void;
19
+ factory: (pi: ExtensionAPI) => void | Promise<void>;
20
20
  }
21
21
  export type ChildSessionStorage = {
22
22
  kind: "file";
@@ -120,9 +120,9 @@ export interface ChildSession {
120
120
  };
121
121
  /** Event-updated pane-native status; reading it performs no network work. */
122
122
  readonly placementSnapshot?: unknown;
123
- /** Set by the foreground host once the run detached; `factory.dispose()` leaves such children running. */
123
+ /** Set by the foreground host once the run detached; factory disposal leaves such children running. */
124
124
  detached?: boolean;
125
- /** Set by `factory.dispose()` before it aborts the child, so the host can report the stop truthfully. */
125
+ /** Set by factory disposal before it aborts the child, so the host can report the stop truthfully. */
126
126
  shutDown?: boolean;
127
127
  }
128
128
  export declare function childSessionHasQueuedMessages(session: ChildSession | undefined): boolean;
@@ -130,6 +130,8 @@ export interface ChildSessionFactory {
130
130
  create(launch: ChildSessionLaunch): Promise<ChildSession>;
131
131
  /** Abort and dispose every live attached child; detached children keep running and hold the shared runtime. */
132
132
  dispose(): Promise<void>;
133
+ /** `dispose()` for only the children `parentSessionFile`'s session launched (undefined: sessions without a file); pi-web shuts sessions down one at a time. */
134
+ disposeForParent(parentSessionFile: string | undefined): Promise<void>;
133
135
  }
134
136
  export type PiCodingAgentModule = typeof import("@earendil-works/pi-coding-agent");
135
137
  export interface DefaultChildSessionFactoryOptions {
@@ -173,6 +175,5 @@ export declare function setChildSessionFactory(factory: ChildSessionFactory | un
173
175
  */
174
176
  export declare function childSessionFactoryModule(): string | undefined;
175
177
  export declare function setChildSessionFactoryModule(modulePath: string | undefined): void;
176
- /** Abort and dispose every live in-process child and release the shared runtime. */
177
- export declare function disposeChildSessions(): Promise<void>;
178
+ export declare function disposeChildSessionsForParent(parentSessionFile: string | undefined): Promise<void>;
178
179
  export {};
@@ -18,9 +18,11 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
18
18
  import * as fs from "node:fs";
19
19
  import * as path from "node:path";
20
20
  import { pathToFileURL } from "node:url";
21
+ import { cleanupSessionResources, registerSessionResourceCleanup } from "@earendil-works/pi-ai";
21
22
  import { CHILD_COMMAND_TOOL, createChildCommandRuntime } from "./child-commands.js";
22
23
  import { supervisorChannelDir } from "./child-tool-plan.js";
23
24
  import { pinChildCacheRetention } from "../../shared/child-cache-retention.js";
25
+ import { parseAcceptanceReport } from "./acceptance.js";
24
26
  import { getAgentDir, PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.js";
25
27
  import { resolvePackageSubpath } from "../background/runner-aliases.js";
26
28
  import { PI_CODING_AGENT_PACKAGE, resolveHostPiPackageRoot } from "./pi-spawn.js";
@@ -138,6 +140,24 @@ function prioritizeChildCommandRuntime(result) {
138
140
  extensions.unshift(commands);
139
141
  return { ...result, extensions };
140
142
  }
143
+ /**
144
+ * `dispose()` releases session resources only in the SDK's copy of pi-ai. Under Pi's bundled CLI, the host's
145
+ * extensions register theirs in a different copy: the one this module imports. The observer is registered per
146
+ * dispose because Pi reloads extensions without a module cache, so a module-level one would pile up on each reload.
147
+ */
148
+ function disposeChildSession(session) {
149
+ let released = false;
150
+ const unregister = registerSessionResourceCleanup((sessionId) => { if (sessionId === session.sessionId)
151
+ released = true; });
152
+ try {
153
+ session.dispose();
154
+ }
155
+ finally {
156
+ unregister();
157
+ if (!released)
158
+ cleanupSessionResources(session.sessionId);
159
+ }
160
+ }
141
161
  /** One launch at a time from env application through `session_start`, so parallel launches never observe each other's `processEnv` while their extensions load and start. */
142
162
  let loading = Promise.resolve();
143
163
  /**
@@ -381,12 +401,15 @@ export function createDefaultChildSessionFactory(options = {}) {
381
401
  const loadPiCodingAgent = options.loadPiCodingAgent ?? loadHostPiCodingAgent;
382
402
  const shutdownTimeoutMs = options.shutdownTimeoutMs ?? 5_000;
383
403
  let runtime;
384
- const live = new Set();
404
+ const live = new Map();
385
405
  /** Extension shutdowns still running for disposed children; `dispose()` waits for them. */
386
406
  const shutdowns = new Set();
387
407
  /** Launches still waiting for their MCP tools; `dispose()` ends the wait and waits for their shutdown. */
388
408
  const mcpWaits = new Map();
389
- let disposals = 0;
409
+ let globalDisposals = 0;
410
+ /** Per-parent disposal epochs: a child's launch aborts only when its own parent's scope (or the whole process) was disposed while it started. */
411
+ const parentDisposals = new Map();
412
+ const parentDisposalEpoch = (parent) => parentDisposals.get(parent) ?? 0;
390
413
  const sharedRuntime = async (pi) => {
391
414
  runtime ??= pi.ModelRuntime.create().catch((error) => {
392
415
  runtime = undefined;
@@ -394,9 +417,32 @@ export function createDefaultChildSessionFactory(options = {}) {
394
417
  });
395
418
  return runtime;
396
419
  };
420
+ const disposeMatching = async (matches) => {
421
+ for (const [cancel, wait] of mcpWaits)
422
+ if (matches(wait.parent))
423
+ cancel.abort();
424
+ const children = [...live.keys()].filter((child) => !child.detached && matches(live.get(child)));
425
+ for (const child of children)
426
+ child.shutDown = true;
427
+ await Promise.allSettled(children.map((child) => child.abort()));
428
+ for (const child of children) {
429
+ try {
430
+ void child.dispose();
431
+ }
432
+ catch { /* best effort */ }
433
+ }
434
+ await Promise.allSettled([
435
+ ...shutdowns,
436
+ ...[...mcpWaits.values()].filter((wait) => matches(wait.parent)).map((wait) => wait.ready),
437
+ ]);
438
+ if (live.size === 0)
439
+ runtime = undefined;
440
+ };
397
441
  return {
398
442
  async create(launch) {
399
- const disposalsAtStart = disposals;
443
+ const globalDisposalsAtStart = globalDisposals;
444
+ const parentEpochAtStart = parentDisposalEpoch(launch.parentSessionFile);
445
+ const disposedSinceStart = () => globalDisposals !== globalDisposalsAtStart || parentDisposalEpoch(launch.parentSessionFile) !== parentEpochAtStart;
400
446
  const pi = await loadPiCodingAgent();
401
447
  const builtinMcpTools = launch.builtinMcpTools ?? [];
402
448
  let readinessTool;
@@ -485,7 +531,7 @@ export function createDefaultChildSessionFactory(options = {}) {
485
531
  launch.onExtensionError?.({ extensionPath: "<session>", event: "session_shutdown", error });
486
532
  }
487
533
  finally {
488
- session.dispose();
534
+ disposeChildSession(session);
489
535
  }
490
536
  };
491
537
  let inheritedProviders = new Set();
@@ -566,7 +612,7 @@ export function createDefaultChildSessionFactory(options = {}) {
566
612
  });
567
613
  }
568
614
  catch (error) {
569
- session.dispose();
615
+ disposeChildSession(session);
570
616
  throw error;
571
617
  }
572
618
  finally {
@@ -601,12 +647,12 @@ export function createDefaultChildSessionFactory(options = {}) {
601
647
  if (builtinMcp) {
602
648
  const cancel = new AbortController();
603
649
  const signal = launch.signal ? AbortSignal.any([cancel.signal, launch.signal]) : cancel.signal;
604
- if (disposals !== disposalsAtStart)
650
+ if (disposedSinceStart())
605
651
  cancel.abort();
606
652
  const ready = (async () => {
607
653
  try {
608
654
  await builtinMcp.waitForTools(signal, () => loader.getExtensions().errors.find(({ path }) => path === "builtin:mcp")?.error);
609
- if (disposals !== disposalsAtStart)
655
+ if (disposedSinceStart())
610
656
  throw new Error("The child session factory was disposed while the child waited for its MCP tools.");
611
657
  if (signal.aborted)
612
658
  throw new Error("The child launch was cancelled while waiting for its MCP tools.");
@@ -619,7 +665,7 @@ export function createDefaultChildSessionFactory(options = {}) {
619
665
  throw error;
620
666
  }
621
667
  })();
622
- mcpWaits.set(cancel, ready);
668
+ mcpWaits.set(cancel, { ready, parent: launch.parentSessionFile });
623
669
  try {
624
670
  await ready;
625
671
  }
@@ -627,12 +673,29 @@ export function createDefaultChildSessionFactory(options = {}) {
627
673
  mcpWaits.delete(cancel);
628
674
  }
629
675
  }
676
+ let reportCompleted = false;
677
+ const guidanceClosed = "Child completed its acceptance report; resume it for further guidance.";
678
+ const assertAcceptsGuidance = () => { if (reportCompleted)
679
+ throw new Error(guidanceClosed); };
680
+ const rejectQueuedGuidance = () => { session.clearQueue(); throw new Error(guidanceClosed); };
630
681
  const child = {
631
- subscribe: (listener) => session.subscribe((event) => listener(event)),
682
+ subscribe: (listener) => session.subscribe((event) => {
683
+ if (event.type === "message_end" && event.message.role === "assistant" && event.message.stopReason === "stop") {
684
+ const text = event.message.content.filter((part) => part.type === "text").map((part) => part.text).join("\n");
685
+ const report = parseAcceptanceReport(text);
686
+ if (report.report || report.malformed) {
687
+ reportCompleted = true;
688
+ session.clearQueue();
689
+ session.agent.steer = rejectQueuedGuidance;
690
+ session.agent.followUp = rejectQueuedGuidance;
691
+ }
692
+ }
693
+ listener(event);
694
+ }),
632
695
  prompt: (text) => session.prompt(text),
633
696
  ...(commands ? { finishCommands: () => commands.finish() } : {}),
634
- steer: (text) => session.steer(text).then(() => undefined),
635
- followUp: (text) => session.followUp(text).then(() => undefined),
697
+ steer: async (text) => { assertAcceptsGuidance(); await session.steer(text); },
698
+ followUp: async (text) => { assertAcceptsGuidance(); await session.followUp(text); },
636
699
  abort: () => session.abort(),
637
700
  hasQueuedMessages: () => session.agent?.hasQueuedMessages?.() === true,
638
701
  dispose: () => {
@@ -654,26 +717,16 @@ export function createDefaultChildSessionFactory(options = {}) {
654
717
  get virtualModelId() { return session.model?.api === "pi-virtual" ? `${session.model.provider}/${session.model.id}` : undefined; },
655
718
  get contextWindow() { return session.model?.contextWindow; },
656
719
  };
657
- live.add(child);
720
+ live.set(child, launch.parentSessionFile);
658
721
  return child;
659
722
  },
660
723
  async dispose() {
661
- disposals += 1;
662
- for (const cancel of mcpWaits.keys())
663
- cancel.abort();
664
- const children = [...live].filter((child) => !child.detached);
665
- for (const child of children)
666
- child.shutDown = true;
667
- await Promise.allSettled(children.map((child) => child.abort()));
668
- for (const child of children) {
669
- try {
670
- void child.dispose();
671
- }
672
- catch { /* best effort */ }
673
- }
674
- await Promise.allSettled([...shutdowns, ...mcpWaits.values()]);
675
- if (live.size === 0)
676
- runtime = undefined;
724
+ globalDisposals += 1;
725
+ await disposeMatching(() => true);
726
+ },
727
+ async disposeForParent(parentSessionFile) {
728
+ parentDisposals.set(parentSessionFile, parentDisposalEpoch(parentSessionFile) + 1);
729
+ await disposeMatching((parent) => parent === parentSessionFile);
677
730
  },
678
731
  };
679
732
  }
@@ -689,10 +742,8 @@ function createLazyPlacementFactory(local) {
689
742
  const factory = async () => placed ??= (await import("./herdr-placed-run.js")).createPlacementAwareChildSessionFactory(local);
690
743
  return {
691
744
  async create(launch) { return launch.machine ? (await factory()).create(launch) : local.create(launch); },
692
- async dispose() { if (placed)
693
- await placed.dispose();
694
- else
695
- await local.dispose(); },
745
+ async dispose() { await (placed ?? local).dispose(); },
746
+ async disposeForParent(parentSessionFile) { await (placed ?? local).disposeForParent(parentSessionFile); },
696
747
  };
697
748
  }
698
749
  /** Default factory including pane-native placement; detached runners use the same boundary. */
@@ -717,10 +768,6 @@ export function childSessionFactoryModule() {
717
768
  export function setChildSessionFactoryModule(modulePath) {
718
769
  activeFactoryModule = modulePath;
719
770
  }
720
- /** Abort and dispose every live in-process child and release the shared runtime. */
721
- export async function disposeChildSessions() {
722
- const factory = activeFactory;
723
- if (!factory)
724
- return;
725
- await factory.dispose();
771
+ export async function disposeChildSessionsForParent(parentSessionFile) {
772
+ await activeFactory?.disposeForParent(parentSessionFile);
726
773
  }
@@ -91,7 +91,6 @@ export declare function formatRuntimeSnapshotMcpServersError(agentName: string |
91
91
  export declare function assertNoToolModifierEntries(agentName: string | undefined, tools: readonly string[]): void;
92
92
  export declare function projectLaunchResolvedChildExtensions(toolPlan: Pick<PiLaunchToolPlan, "runtimeExtensions" | "configuredExtensions" | "requiredExtensions" | "extensionArgs" | "disableAmbientExtensions">): LaunchResolvedChildExtensions;
93
93
  /**
94
- * Resolve the permission-system extension entry point when installed.
95
94
  * Returns the absolute path to the extension's main module, or undefined
96
95
  * when the package is not installed. Callers can check `autoInject` config
97
96
  * to decide whether to include it in child sessions.
@@ -141,7 +141,6 @@ export function projectLaunchResolvedChildExtensions(toolPlan) {
141
141
  };
142
142
  }
143
143
  /**
144
- * Resolve the permission-system extension entry point when installed.
145
144
  * Returns the absolute path to the extension's main module, or undefined
146
145
  * when the package is not installed. Callers can check `autoInject` config
147
146
  * to decide whether to include it in child sessions.
@@ -201,6 +201,17 @@ export function createClaudeCodeJsonlParser() {
201
201
  }
202
202
  return { phase: terminal ? terminal.state : "streaming", eventCount };
203
203
  },
204
+ /**
205
+ * Reading an image returns it as base64 in a user-role tool result, so that line can be far
206
+ * larger than the parser line limit. Only user lines are absorbed: a terminal `result` is
207
+ * never skipped, because dropping it would discard the answer. The runner bounds the size.
208
+ */
209
+ skipOversizedLine(prefix) {
210
+ if (terminal || !/^\s*\{\s*"type"\s*:\s*"user"\s*,/.test(prefix))
211
+ return undefined;
212
+ eventCount += 1;
213
+ return { phase: "streaming", eventCount };
214
+ },
204
215
  finish() {
205
216
  return terminal;
206
217
  },