pi-subagents 0.84.0 → 0.86.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 (210) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-JG4QKI5M.js → chunk-2IYBCYFU.js} +214 -97
  5. package/bundle/{chunk-V2BZYLEP.js → chunk-374MZFF4.js} +7 -2
  6. package/bundle/{chunk-4E7BKDTX.js → chunk-3RKFH2UZ.js} +11 -156
  7. package/bundle/{chunk-F4ASL6OV.js → chunk-5H4BICQZ.js} +1 -1
  8. package/bundle/{chunk-PALJGGYC.js → chunk-6VD7BGIC.js} +6 -3
  9. package/bundle/{chunk-C5P5CHYK.js → chunk-77ASNIEM.js} +1 -1
  10. package/bundle/{chunk-XDQORLZ5.js → chunk-7ADDXUGF.js} +15 -6
  11. package/bundle/{chunk-PV63UFUR.js → chunk-7QA7ZA46.js} +183 -28
  12. package/bundle/{chunk-NKQ6JNAS.js → chunk-7ZUFN6ME.js} +2 -1
  13. package/bundle/{chunk-SSG7IEP5.js → chunk-A637IMAO.js} +2 -2
  14. package/bundle/{chunk-L3WFKBEI.js → chunk-BGXEAYUM.js} +247 -153
  15. package/bundle/{chunk-J5YL7LYR.js → chunk-BU6PFPVX.js} +59 -27
  16. package/bundle/{chunk-DZDETGRJ.js → chunk-BWC2LVII.js} +259 -216
  17. package/bundle/{chunk-CGN2TVE7.js → chunk-GJGTMLPE.js} +322 -18
  18. package/bundle/{chunk-D3JAFGMO.js → chunk-GRJHIXYF.js} +1 -1
  19. package/bundle/chunk-HXRB42AF.js +108 -0
  20. package/bundle/{chunk-LFDBD4PW.js → chunk-LGINOOY5.js} +2 -2
  21. package/bundle/{chunk-G2Z6ZH26.js → chunk-NAFLUJ26.js} +1 -1
  22. package/bundle/{chunk-235AWJUQ.js → chunk-O3YH7XIY.js} +324 -111
  23. package/bundle/{chunk-2DHZTCOL.js → chunk-PYOAIN3V.js} +2 -2
  24. package/bundle/{chunk-LNRJCP2Y.js → chunk-QGO6HXHG.js} +417 -242
  25. package/bundle/{chunk-VQVVHSY6.js → chunk-QM3JGE4W.js} +22 -11
  26. package/bundle/{chunk-2S4K53MV.js → chunk-S2Q75LP3.js} +1 -1
  27. package/bundle/{chunk-NENDSQUY.js → chunk-UR7OW5S7.js} +9 -6
  28. package/bundle/{chunk-AKOIVLA5.js → chunk-WN2E5XHN.js} +135 -77
  29. package/bundle/{chunk-2D52JFLF.js → chunk-YK3QYNLE.js} +41 -117
  30. package/bundle/{chunk-7BWGNDNK.js → chunk-ZJJCPV3L.js} +190 -1177
  31. package/bundle/chunk-ZPY5QZCS.js +1067 -0
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +8 -8
  36. package/bundle/project-panes.js +3 -3
  37. package/docs/agents.md +23 -2
  38. package/docs/configuration.md +4 -4
  39. package/docs/extension-api.md +16 -1
  40. package/docs/tool-reference.md +2 -0
  41. package/docs/workflows.md +30 -2
  42. package/package.json +1 -1
  43. package/src/agents/agent-management.js +27 -11
  44. package/src/agents/agent-memory.d.ts +1 -4
  45. package/src/agents/agent-memory.js +1 -4
  46. package/src/agents/agents.d.ts +1 -3
  47. package/src/agents/agents.js +7 -6
  48. package/src/agents/frontmatter.js +1 -8
  49. package/src/agents/global-npm-root.d.ts +1 -0
  50. package/src/agents/global-npm-root.js +11 -3
  51. package/src/agents/skills.d.ts +0 -3
  52. package/src/agents/skills.js +0 -3
  53. package/src/extension/config.js +7 -1
  54. package/src/extension/herdr-pi-bridge.js +10 -2
  55. package/src/extension/index.d.ts +0 -13
  56. package/src/extension/index.js +43 -32
  57. package/src/extension/public-execution.d.ts +1 -0
  58. package/src/extension/public-execution.js +4 -0
  59. package/src/extension/reply-workflow-script.js +24 -4
  60. package/src/extension/schemas.d.ts +8 -3
  61. package/src/extension/schemas.js +5 -3
  62. package/src/extension/session-switch.d.ts +25 -0
  63. package/src/extension/session-switch.js +138 -0
  64. package/src/extension/subagent-guide.d.ts +1 -1
  65. package/src/extension/subagent-guide.js +1 -1
  66. package/src/extension/subagent-launch-tool.d.ts +25 -0
  67. package/src/extension/subagent-launch-tool.js +48 -0
  68. package/src/extension/tool-activation.js +35 -12
  69. package/src/extension/tool-description.d.ts +1 -1
  70. package/src/extension/tool-description.js +14 -8
  71. package/src/inspectors/herdr/actions.d.ts +0 -1
  72. package/src/inspectors/herdr/actions.js +0 -1
  73. package/src/inspectors/session-roots-codec.d.ts +0 -1
  74. package/src/inspectors/session-roots-codec.js +0 -1
  75. package/src/inspectors/tmux/actions.d.ts +0 -1
  76. package/src/inspectors/tmux/actions.js +0 -1
  77. package/src/integrations/herdr-status.js +3 -8
  78. package/src/intercom/native-supervisor-channel.js +65 -9
  79. package/src/runs/background/async-execution.d.ts +5 -9
  80. package/src/runs/background/async-execution.js +62 -27
  81. package/src/runs/background/async-job-tracker.js +12 -0
  82. package/src/runs/background/async-resume.d.ts +2 -1
  83. package/src/runs/background/async-resume.js +112 -39
  84. package/src/runs/background/async-retention.js +6 -1
  85. package/src/runs/background/auto-drain.js +2 -1
  86. package/src/runs/background/boot-id.d.ts +1 -3
  87. package/src/runs/background/boot-id.js +1 -3
  88. package/src/runs/background/completion-batcher.d.ts +3 -4
  89. package/src/runs/background/completion-batcher.js +2 -3
  90. package/src/runs/background/control-channel.d.ts +0 -6
  91. package/src/runs/background/control-channel.js +0 -6
  92. package/src/runs/background/fleet-view.js +2 -3
  93. package/src/runs/background/notify.d.ts +0 -2
  94. package/src/runs/background/notify.js +0 -2
  95. package/src/runs/background/result-watcher.d.ts +1 -0
  96. package/src/runs/background/result-watcher.js +59 -29
  97. package/src/runs/background/resume-guidance.js +4 -2
  98. package/src/runs/background/retained-children.js +2 -1
  99. package/src/runs/background/run-child-session.d.ts +0 -1
  100. package/src/runs/background/run-child-session.js +1 -1
  101. package/src/runs/background/run-status.js +9 -7
  102. package/src/runs/background/scheduled-runs.d.ts +3 -1
  103. package/src/runs/background/scheduled-runs.js +13 -16
  104. package/src/runs/background/subagent-runner.d.ts +2 -4
  105. package/src/runs/background/subagent-runner.js +15 -12
  106. package/src/runs/background/subagent-wait.js +12 -15
  107. package/src/runs/background/wait-config.d.ts +2 -0
  108. package/src/runs/background/wait-config.js +17 -3
  109. package/src/runs/background/wait-tool.js +4 -2
  110. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  111. package/src/runs/background/workflow-terminal-proof.js +0 -1
  112. package/src/runs/foreground/execution.d.ts +0 -3
  113. package/src/runs/foreground/execution.js +17 -9
  114. package/src/runs/foreground/subagent-executor.d.ts +3 -2
  115. package/src/runs/foreground/subagent-executor.js +107 -26
  116. package/src/runs/shared/acceptance.js +69 -26
  117. package/src/runs/shared/child-commands.js +15 -2
  118. package/src/runs/shared/child-hooks.d.ts +1 -7
  119. package/src/runs/shared/child-hooks.js +13 -5
  120. package/src/runs/shared/child-launch.js +6 -2
  121. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  122. package/src/runs/shared/child-session.d.ts +1 -1
  123. package/src/runs/shared/child-session.js +21 -2
  124. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  125. package/src/runs/shared/child-tool-plan.js +0 -1
  126. package/src/runs/shared/claude-code-adapter.js +11 -0
  127. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  128. package/src/runs/shared/external-cli-contract.js +18 -13
  129. package/src/runs/shared/external-cli-runner.js +26 -6
  130. package/src/runs/shared/herdr-connection.js +2 -1
  131. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  132. package/src/runs/shared/herdr-pane-host.js +17 -1
  133. package/src/runs/shared/herdr-placed-run.js +48 -22
  134. package/src/runs/shared/lane-metadata.d.ts +0 -1
  135. package/src/runs/shared/lane-metadata.js +0 -1
  136. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  137. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  138. package/src/runs/shared/model-resolution.d.ts +2 -2
  139. package/src/runs/shared/model-resolution.js +7 -1
  140. package/src/runs/shared/model-scope.d.ts +1 -5
  141. package/src/runs/shared/model-scope.js +1 -5
  142. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  143. package/src/runs/shared/mutation-evidence.js +52 -7
  144. package/src/runs/shared/nested-events.d.ts +1 -0
  145. package/src/runs/shared/nested-events.js +1 -1
  146. package/src/runs/shared/parallel-utils.d.ts +0 -1
  147. package/src/runs/shared/permissions.js +5 -3
  148. package/src/runs/shared/placement-host.d.ts +5 -1
  149. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  150. package/src/runs/shared/rex-pane-host.js +0 -2
  151. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  152. package/src/runs/shared/run-launch-folder.js +21 -0
  153. package/src/runs/shared/runner-launcher.d.ts +12 -1
  154. package/src/runs/shared/runner-launcher.js +16 -0
  155. package/src/runs/shared/single-output.d.ts +3 -3
  156. package/src/runs/shared/single-output.js +5 -3
  157. package/src/runs/shared/structured-output.d.ts +8 -0
  158. package/src/runs/shared/structured-output.js +40 -5
  159. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  160. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  161. package/src/runs/shared/tool-timeout.js +2 -1
  162. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  163. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  164. package/src/runs/shared/worktree.d.ts +3 -0
  165. package/src/runs/shared/worktree.js +20 -0
  166. package/src/shared/capacity-resilient-json.d.ts +1 -1
  167. package/src/shared/child-cache-retention.d.ts +1 -2
  168. package/src/shared/child-cache-retention.js +1 -2
  169. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  170. package/src/shared/fleet-transcript-reader.js +333 -0
  171. package/src/shared/formatters.d.ts +0 -18
  172. package/src/shared/formatters.js +0 -18
  173. package/src/shared/session-succession.d.ts +16 -1
  174. package/src/shared/session-succession.js +41 -2
  175. package/src/shared/session-warnings.d.ts +7 -0
  176. package/src/shared/session-warnings.js +26 -0
  177. package/src/shared/settings.d.ts +0 -23
  178. package/src/shared/settings.js +3 -35
  179. package/src/shared/types.d.ts +85 -59
  180. package/src/shared/types.js +0 -12
  181. package/src/shared/utils.d.ts +0 -14
  182. package/src/shared/utils.js +0 -22
  183. package/src/shared/wait-tool-name.d.ts +8 -0
  184. package/src/shared/wait-tool-name.js +13 -0
  185. package/src/slash/slash-commands.js +2 -1
  186. package/src/slash/subagent-cost.d.ts +3 -2
  187. package/src/slash/subagent-cost.js +22 -3
  188. package/src/slash/subagents-admin.js +0 -1
  189. package/src/tui/fleet-status.d.ts +0 -5
  190. package/src/tui/fleet-status.js +4 -24
  191. package/src/tui/fleet-transcript.d.ts +1 -44
  192. package/src/tui/fleet-transcript.js +1 -327
  193. package/src/tui/fleet.js +6 -4
  194. package/src/tui/render.d.ts +0 -9
  195. package/src/tui/render.js +161 -66
  196. package/src/tui/subagent-messages.js +3 -2
  197. package/src/watchdog/register-child.d.ts +2 -3
  198. package/src/watchdog/register-child.js +2 -3
  199. package/src/watchdog/turn-delta.js +2 -1
  200. package/src/workflows/scripted-workflow.js +241 -20
  201. package/src/workflows/workflow-launch-record.d.ts +15 -6
  202. package/src/workflows/workflow-launch-record.js +30 -12
  203. package/src/workflows/workflow-receipt.js +36 -53
  204. package/src/workflows/workflow-resume-claim.js +2 -2
  205. package/src/workflows/workflow-resume.d.ts +1 -1
  206. package/src/workflows/workflow-resume.js +11 -8
  207. package/src/workflows/workflow-script-worker.d.ts +13 -0
  208. package/src/workflows/workflow-script-worker.js +79 -0
  209. package/workflow-script-process.cjs +36 -0
  210. package/workflow-script-worker.cjs +4 -1
@@ -11,24 +11,28 @@ import {
11
11
  startWatchdogDiffBaselineCapture,
12
12
  writeUserWatchdogEnabled,
13
13
  writeWatchdogModelSettings
14
- } from "./chunk-7BWGNDNK.js";
14
+ } from "./chunk-ZJJCPV3L.js";
15
15
  import {
16
16
  resolveGitRepositoryIdentity
17
- } from "./chunk-NENDSQUY.js";
17
+ } from "./chunk-UR7OW5S7.js";
18
18
  import {
19
19
  listAsyncRuns,
20
- ownsRun,
21
20
  parallelHandoffPath,
22
21
  parseWorkflowChildSummary,
23
22
  readAsyncRecoveryDescriptor,
23
+ readWorkflowLaunchRecord,
24
24
  resolveRetainedWorktreeCwd
25
- } from "./chunk-L3WFKBEI.js";
25
+ } from "./chunk-BGXEAYUM.js";
26
+ import {
27
+ ownsRun
28
+ } from "./chunk-HXRB42AF.js";
26
29
  import {
27
30
  deepFreezeWorkflowArgs,
28
31
  normalizeWorkflowArgs
29
32
  } from "./chunk-NF7IEKBH.js";
30
33
  import {
31
34
  HOST_STEP_MAX_COUNT,
35
+ REQUIRE_LAUNCHER_SHAPE_ERROR,
32
36
  WORKFLOW_STOP_CAUSE_OWNER_EXITED,
33
37
  WORKFLOW_STOP_CAUSE_RUNTIME_REPLACED,
34
38
  assertUniqueHostStepIds,
@@ -50,21 +54,21 @@ import {
50
54
  resolveMissionStoreLocation,
51
55
  validateMissionId,
52
56
  workflowRunParamsFingerprint
53
- } from "./chunk-CGN2TVE7.js";
57
+ } from "./chunk-GJGTMLPE.js";
54
58
  import {
55
59
  requestAsyncCommand,
56
60
  watchAsyncControlInbox
57
- } from "./chunk-F4ASL6OV.js";
61
+ } from "./chunk-5H4BICQZ.js";
58
62
  import {
59
63
  supervisorChannelDir
60
- } from "./chunk-V2BZYLEP.js";
64
+ } from "./chunk-374MZFF4.js";
61
65
  import {
62
66
  createHerdrClient,
63
67
  detectHerdr
64
- } from "./chunk-2DHZTCOL.js";
68
+ } from "./chunk-PYOAIN3V.js";
65
69
  import {
66
70
  getProjectSubagentsDir
67
- } from "./chunk-D3JAFGMO.js";
71
+ } from "./chunk-GRJHIXYF.js";
68
72
  import {
69
73
  ExternalJobProviderError,
70
74
  getExternalJobProvider,
@@ -74,9 +78,10 @@ import {
74
78
  } from "./chunk-YYREO77V.js";
75
79
  import {
76
80
  mergeRuntimeAgents
77
- } from "./chunk-G2Z6ZH26.js";
81
+ } from "./chunk-NAFLUJ26.js";
78
82
  import {
79
83
  CODE_OWNED_EXTERNAL_CLI_ADAPTER_LABEL,
84
+ EXTERNAL_CLI_ADAPTER_SAFETY,
80
85
  PI_CODING_AGENT_PACKAGE,
81
86
  PI_CODING_AGENT_PACKAGE_ROOT_ENV,
82
87
  PROMPT_REDACTED,
@@ -100,6 +105,7 @@ import {
100
105
  getProjectConfigDir,
101
106
  getSupportedThinkingLevels,
102
107
  isCodeOwnedExternalCliAdapterId,
108
+ isUnavailableSubagentModel,
103
109
  mergeAgentsForScope,
104
110
  mergeBuiltinAgentOverride,
105
111
  normalizeModelSegment,
@@ -126,10 +132,11 @@ import {
126
132
  validateCodeOwnedProfileRunner,
127
133
  validateExecutionAcceptance,
128
134
  validateToolBudgetConfig,
135
+ waitToolName,
129
136
  withFileLease,
130
137
  writeAtomicJson,
131
138
  writePrivateAtomicJson
132
- } from "./chunk-LNRJCP2Y.js";
139
+ } from "./chunk-QGO6HXHG.js";
133
140
  import {
134
141
  DIRS,
135
142
  INTERCOM_DETACH_REQUEST_EVENT,
@@ -678,7 +685,7 @@ var DEFAULT_FAST_TOOL_TIMEOUT_TOOLS = /* @__PURE__ */ new Set([
678
685
  ]);
679
686
  var TOOL_TIMEOUT_EXEMPT_TOOLS = /* @__PURE__ */ new Set(["contact_supervisor", "intercom", "bg_wait"]);
680
687
  function isToolTimeoutExempt(toolName) {
681
- return toolName !== void 0 && TOOL_TIMEOUT_EXEMPT_TOOLS.has(toolName);
688
+ return toolName !== void 0 && (TOOL_TIMEOUT_EXEMPT_TOOLS.has(toolName) || toolName === waitToolName());
682
689
  }
683
690
  function defaultToolTimeoutMs(toolName) {
684
691
  return toolName !== void 0 && DEFAULT_FAST_TOOL_TIMEOUT_TOOLS.has(toolName) ? DEFAULT_FAST_TOOL_TIMEOUT_MS : void 0;
@@ -1497,6 +1504,9 @@ function parseScheduleInterval(every) {
1497
1504
  function timestamp(value) {
1498
1505
  return new Date(value).toISOString();
1499
1506
  }
1507
+ function errorText3(error2) {
1508
+ return error2 instanceof Error ? error2.message : String(error2);
1509
+ }
1500
1510
  function validateScheduleId(id) {
1501
1511
  if (!SCHEDULE_ID.test(id)) throw new Error("Schedule id must be 1-64 characters and contain only letters, numbers, '.', '_', or '-'.");
1502
1512
  return id;
@@ -1667,7 +1677,7 @@ function parseSchedule(value, file) {
1667
1677
  if (record.trigger.kind === "once") {
1668
1678
  if (typeof record.trigger.at !== "string" || record.trigger.nextRunAt !== void 0 && typeof record.trigger.nextRunAt !== "string") throw new Error(`Schedule record '${file}' has an invalid one-shot trigger.`);
1669
1679
  } else if (record.trigger.kind === "interval") {
1670
- if (typeof record.trigger.every !== "string" || typeof record.trigger.everyMs !== "number" || typeof record.trigger.anchorAt !== "string" || typeof record.trigger.nextRunAt !== "string") throw new Error(`Schedule record '${file}' has an invalid interval trigger.`);
1680
+ if (typeof record.trigger.every !== "string" || typeof record.trigger.everyMs !== "number" || typeof record.trigger.anchorAt !== "string" || (!record.paused || record.trigger.nextRunAt !== void 0) && typeof record.trigger.nextRunAt !== "string") throw new Error(`Schedule record '${file}' has an invalid interval trigger.`);
1671
1681
  } else if (record.trigger.kind === "calendar") {
1672
1682
  restoreCalendarTrigger(record.trigger);
1673
1683
  } else throw new Error(`Schedule record '${file}' has an unsupported trigger.`);
@@ -1938,7 +1948,7 @@ var ScheduledRunManager = class {
1938
1948
  try {
1939
1949
  ids = store.ids();
1940
1950
  } catch (error2) {
1941
- console.error(`Failed to inspect schedule store '${store.root}' during async completion:`, error2);
1951
+ this.deps.reportWarning?.(`Failed to inspect schedule store '${store.root}': ${errorText3(error2)}`, `schedule-store:${store.root}:${errorText3(error2)}`);
1942
1952
  continue;
1943
1953
  }
1944
1954
  for (const id of ids) {
@@ -1950,7 +1960,7 @@ var ScheduledRunManager = class {
1950
1960
  this.finishRun(store, schedule, run, data.success === true, typeof data.summary === "string" ? data.summary : void 0);
1951
1961
  return;
1952
1962
  } catch (error2) {
1953
- console.error(`Failed to inspect schedule '${id}' in '${store.root}' during async completion:`, error2);
1963
+ this.deps.reportWarning?.(`Failed to inspect schedule '${id}' in '${store.root}': ${errorText3(error2)}`, `schedule-record:${store.root}:${id}`);
1954
1964
  }
1955
1965
  }
1956
1966
  }
@@ -2042,6 +2052,7 @@ Mission: ${schedule.target.missionId}`}`, [schedule]);
2042
2052
  const schedule = this.resolve(params);
2043
2053
  if (schedule.paused === paused) return textResult(`Schedule ${schedule.id} is already ${paused ? "paused" : "active"}.`, [schedule]);
2044
2054
  schedule.paused = paused;
2055
+ if (!paused && schedule.trigger.kind === "interval" && schedule.trigger.nextRunAt === void 0) schedule.trigger.nextRunAt = timestamp(this.now() + schedule.trigger.everyMs);
2045
2056
  schedule.updatedAt = timestamp(this.now());
2046
2057
  this.requireStore().write(schedule);
2047
2058
  this.requireStore().appendEvent(schedule, paused ? "schedule.paused" : "schedule.resumed");
@@ -2568,12 +2579,29 @@ function parseExternalCliMachine(value, label) {
2568
2579
  const unknownRemoteGit = Object.keys(remoteGit).filter((field) => !["head", "branch", "dirty"].includes(field));
2569
2580
  if (unknownRemoteGit.length > 0 || remoteGit.head !== void 0 && (typeof remoteGit.head !== "string" || !remoteGit.head.trim()) || remoteGit.branch !== void 0 && (typeof remoteGit.branch !== "string" || !remoteGit.branch.trim()) || remoteGit.dirty !== void 0 && typeof remoteGit.dirty !== "boolean") throw new Error(`${label}.machine.remoteGit is invalid.`);
2570
2581
  }
2582
+ function parseCodeOwnedSafety(value, adapter, label) {
2583
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label}.safety is missing.`);
2584
+ const safety = value;
2585
+ const profile = EXTERNAL_CLI_ADAPTER_SAFETY[adapter];
2586
+ const unknownSafety = Object.keys(safety).filter((field) => !Object.hasOwn(profile, field));
2587
+ if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
2588
+ if (Object.entries(profile).some(([field, expected]) => safety[field] !== expected)) throw new Error(`${label}.safety is invalid.`);
2589
+ }
2590
+ function parseExternalCliSafetySource(value, label) {
2591
+ if (value === void 0) return false;
2592
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label}.safetySource must be an object.`);
2593
+ const source = value;
2594
+ const unknownSource = Object.keys(source).filter((field) => !["measured", "command"].includes(field));
2595
+ if (unknownSource.length > 0) throw new Error(`${label}.safetySource has unsupported fields: ${unknownSource.join(", ")}.`);
2596
+ if (source.measured !== false || source.command !== void 0 && (typeof source.command !== "string" || !source.command.trim())) throw new Error(`${label}.safetySource is invalid.`);
2597
+ return true;
2598
+ }
2571
2599
  function parseExternalCliReceiptMetadata(value, key, source) {
2572
2600
  if (value === void 0) return void 0;
2573
2601
  const label = `Invalid workflow receipt '${source}': entry '${key}' externalAdapter`;
2574
2602
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object.`);
2575
2603
  const metadata = value;
2576
- const unknownMetadata = Object.keys(metadata).filter((field) => !["adapter", "capabilities", "machine", "safety", "outputArtifacts", "handoff", "supervisor", "nonResumableReason"].includes(field));
2604
+ const unknownMetadata = Object.keys(metadata).filter((field) => !["adapter", "capabilities", "machine", "safety", "safetySource", "outputArtifacts", "handoff", "supervisor", "nonResumableReason"].includes(field));
2577
2605
  if (unknownMetadata.length > 0) throw new Error(`${label} has unsupported fields: ${unknownMetadata.join(", ")}.`);
2578
2606
  const adapter = metadata.adapter;
2579
2607
  if (!adapter || typeof adapter !== "object" || Array.isArray(adapter)) throw new Error(`${label}.adapter must be an object.`);
@@ -2591,47 +2619,23 @@ function parseExternalCliReceiptMetadata(value, key, source) {
2591
2619
  }
2592
2620
  if (metadata.machine !== void 0) parseExternalCliMachine(metadata.machine, label);
2593
2621
  const safety = metadata.safety;
2594
- if (adapterRecord.id === "codex-exec") {
2595
- if (!safety || typeof safety !== "object" || Array.isArray(safety)) throw new Error(`${label}.safety is missing.`);
2622
+ const hasSafetySource = parseExternalCliSafetySource(metadata.safetySource, label);
2623
+ if (adapterRecord.id === "claude-code" && !hasSafetySource && safety && typeof safety === "object" && !Array.isArray(safety) && safety.authentication === void 0) {
2596
2624
  const safetyRecord = safety;
2597
- const unknownSafety = Object.keys(safetyRecord).filter((field) => !["sandbox", "approvalPolicy", "ephemeral"].includes(field));
2625
+ const unknownSafety = Object.keys(safetyRecord).filter((field) => !["permissionMode", "tools", "mcp", "settingSources", "sessionPersistence"].includes(field));
2598
2626
  if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
2599
- if (safetyRecord.sandbox !== "read-only" || safetyRecord.approvalPolicy !== "never" || safetyRecord.ephemeral !== true) throw new Error(`${label}.safety is invalid.`);
2600
- } else if (adapterRecord.id === "codex-exec-writer") {
2601
- if (!safety || typeof safety !== "object" || Array.isArray(safety)) throw new Error(`${label}.safety is missing.`);
2602
- const safetyRecord = safety;
2603
- const unknownSafety = Object.keys(safetyRecord).filter((field) => !["access", "sandbox", "approvalPolicy", "ephemeral"].includes(field));
2604
- if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
2605
- if (safetyRecord.access !== "workspace-write" || safetyRecord.sandbox !== "workspace-write" || safetyRecord.approvalPolicy !== "never" || safetyRecord.ephemeral !== true) throw new Error(`${label}.safety is invalid.`);
2606
- } else if (adapterRecord.id === "claude-code") {
2607
- if (!safety || typeof safety !== "object" || Array.isArray(safety)) throw new Error(`${label}.safety is missing.`);
2608
- const safetyRecord = safety;
2609
- const legacy = safetyRecord.authentication === void 0;
2610
- const unknownSafety = Object.keys(safetyRecord).filter((field) => !(legacy ? ["permissionMode", "tools", "mcp", "settingSources", "sessionPersistence"] : ["access", "authentication", "permissionMode", "tools", "mcp", "settingSources", "userSettingsTrust", "sessionPersistence"]).includes(field));
2611
- if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
2612
- if (legacy) {
2613
- if (safetyRecord.permissionMode !== "plan" || safetyRecord.tools !== "none" || safetyRecord.mcp !== "empty-strict" || safetyRecord.settingSources !== "none" || safetyRecord.sessionPersistence !== false) throw new Error(`${label}.safety is invalid.`);
2614
- } else if (safetyRecord.access !== "read-only" || safetyRecord.authentication !== "existing-cli-required" || safetyRecord.permissionMode !== "plan" || safetyRecord.tools !== "none" || safetyRecord.mcp !== "empty-strict" || safetyRecord.settingSources !== "user" || safetyRecord.userSettingsTrust !== "required" || safetyRecord.sessionPersistence !== false) throw new Error(`${label}.safety is invalid.`);
2615
- } else if (adapterRecord.id === "claude-code-writer") {
2616
- if (!safety || typeof safety !== "object" || Array.isArray(safety)) throw new Error(`${label}.safety is missing.`);
2617
- const safetyRecord = safety;
2618
- const unknownSafety = Object.keys(safetyRecord).filter((field) => !["access", "authentication", "permissionMode", "tools", "mcp", "settingSources", "userSettingsTrust", "sessionPersistence"].includes(field));
2619
- if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
2620
- if (safetyRecord.access !== "workspace-write" || safetyRecord.authentication !== "existing-cli-required" || safetyRecord.permissionMode !== "acceptEdits" || safetyRecord.tools !== "Read,Write,Edit,Glob,Grep" || safetyRecord.mcp !== "empty-strict" || safetyRecord.settingSources !== "user" || safetyRecord.userSettingsTrust !== "required" || safetyRecord.sessionPersistence !== false) throw new Error(`${label}.safety is invalid.`);
2621
- } else if (adapterRecord.id === "cursor-agent" || adapterRecord.id === "cursor-agent-writer") {
2622
- if (!safety || typeof safety !== "object" || Array.isArray(safety)) throw new Error(`${label}.safety is missing.`);
2623
- const safetyRecord = safety;
2624
- const unknownSafety = Object.keys(safetyRecord).filter((field) => !["access", "authentication", "mode", "sandbox", "workspaceTrust", "sessionReuse"].includes(field));
2625
- if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
2626
- const writer = adapterRecord.id === "cursor-agent-writer";
2627
- if (safetyRecord.access !== (writer ? "workspace-write" : "read-only") || safetyRecord.authentication !== "cursor-api-key-or-existing-login" || safetyRecord.mode !== (writer ? "print" : "ask") || safetyRecord.sandbox !== "enabled" || safetyRecord.workspaceTrust !== "existing-required" || safetyRecord.sessionReuse !== false) throw new Error(`${label}.safety is invalid.`);
2627
+ if (safetyRecord.permissionMode !== "plan" || safetyRecord.tools !== "none" || safetyRecord.mcp !== "empty-strict" || safetyRecord.settingSources !== "none" || safetyRecord.sessionPersistence !== false) throw new Error(`${label}.safety is invalid.`);
2628
+ } else if (isCodeOwnedExternalCliAdapterId(adapterRecord.id)) {
2629
+ parseCodeOwnedSafety(safety, adapterRecord.id, label);
2628
2630
  } else if (adapterRecord.id === "grok-build") {
2631
+ if (hasSafetySource) throw new Error(`${label}.safetySource is invalid for the legacy grok-build adapter.`);
2629
2632
  if (!safety || typeof safety !== "object" || Array.isArray(safety)) throw new Error(`${label}.safety is missing.`);
2630
2633
  const safetyRecord = safety;
2631
2634
  const unknownSafety = Object.keys(safetyRecord).filter((field) => !["access", "authentication", "permissionMode", "tools", "deniedTools", "sandbox", "webSearch", "subagents", "config", "updates", "sessionPersistence"].includes(field));
2632
2635
  if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
2633
2636
  if (safetyRecord.access !== "read-only" || safetyRecord.authentication !== "xai-api-key-required" || safetyRecord.permissionMode !== "plan" || safetyRecord.tools !== "read_file,grep,list_dir" || safetyRecord.deniedTools !== "run_terminal_cmd,search_replace,Agent,Bash,Edit,Write,MCPTool" || safetyRecord.sandbox !== "read-only" || safetyRecord.webSearch !== false || safetyRecord.subagents !== false || safetyRecord.config !== "temporary-home" || safetyRecord.updates !== "disabled" || safetyRecord.sessionPersistence !== false) throw new Error(`${label}.safety is invalid.`);
2634
- } else if (safety !== void 0) throw new Error(`${label}.safety is invalid for the generic adapter.`);
2637
+ } else if (hasSafetySource) throw new Error(`${label}.safetySource is invalid for the generic adapter.`);
2638
+ else if (safety !== void 0) throw new Error(`${label}.safety is invalid for the generic adapter.`);
2635
2639
  const handoff = metadata.handoff;
2636
2640
  if (!handoff || typeof handoff !== "object" || Array.isArray(handoff)) throw new Error(`${label}.handoff must be an object.`);
2637
2641
  const handoffRecord = handoff;
@@ -3540,7 +3544,8 @@ function agentListMetadata(agent, providerNames2, externalCliAvailability) {
3540
3544
  function formatAgentListLine(agent, providerNames2) {
3541
3545
  return `- ${agent.name} (${agentListMetadata(agent, providerNames2)}): ${agent.description}`;
3542
3546
  }
3543
- function formatAgentCapabilitiesLine(agent, providerNames2, externalCliAvailability) {
3547
+ var UNAVAILABLE_MODEL_MARKER = "(unavailable in the active model registry)";
3548
+ function formatAgentCapabilitiesLine(agent, providerNames2, externalCliAvailability, unavailableModels) {
3544
3549
  const declaredTools = [
3545
3550
  ...agent.tools ?? [],
3546
3551
  ...(agent.mcpDirectTools ?? []).map((tool) => `mcp:${tool}`)
@@ -3556,6 +3561,7 @@ function formatAgentCapabilitiesLine(agent, providerNames2, externalCliAvailabil
3556
3561
  if (agent.model !== void 0) {
3557
3562
  model = agent.model;
3558
3563
  if (agent.modelProvider && !agent.model.includes("/")) model = `${agent.modelProvider}/${agent.model}`;
3564
+ if (unavailableModels.has(agent)) model = `${model} ${UNAVAILABLE_MODEL_MARKER}`;
3559
3565
  }
3560
3566
  const thinking = agent.thinking === false ? "off" : agent.thinking ?? "default";
3561
3567
  const machine = agent.machine ? `; Machine: ${agent.machine} (saved Herdr placement)` : "";
@@ -3628,7 +3634,7 @@ function agentCapabilityRow(agent, options) {
3628
3634
  aliases: agent.aliases ? [...agent.aliases] : void 0,
3629
3635
  runner: agentCapabilityRunner(agent, options.providerNames, options.externalCliAvailability),
3630
3636
  tools: agentCapabilityTools(agent),
3631
- model: presentDetails({ value: agent.model, thinking: agent.thinking }),
3637
+ model: presentDetails({ value: agent.model, thinking: agent.thinking, unavailable: options.unavailableModels.has(agent) || void 0 }),
3632
3638
  execution: presentDetails({ defaultAsync: agent.defaultAsync, timeoutMs: agent.defaultTimeoutMs }),
3633
3639
  acceptance: presentDetails({ policy: agent.defaultAcceptance, role: agent.acceptanceRole }),
3634
3640
  output: presentDetails({ path: agent.output, mode: agent.outputMode }),
@@ -3638,8 +3644,8 @@ function agentCapabilityRow(agent, options) {
3638
3644
  function agentCapabilitiesSnapshot(input) {
3639
3645
  return {
3640
3646
  agents: [
3641
- ...input.agents.map((agent) => agentCapabilityRow(agent, { executable: true, providerNames: input.providerNames, externalCliAvailability: input.externalCliAvailability })),
3642
- ...input.restrictedAgents.map((agent) => agentCapabilityRow(agent, { executable: false, providerNames: input.providerNames, externalCliAvailability: input.externalCliAvailability, restrictionSources: input.restrictedSources }))
3647
+ ...input.agents.map((agent) => agentCapabilityRow(agent, { executable: true, providerNames: input.providerNames, externalCliAvailability: input.externalCliAvailability, unavailableModels: input.unavailableModels })),
3648
+ ...input.restrictedAgents.map((agent) => agentCapabilityRow(agent, { executable: false, providerNames: input.providerNames, externalCliAvailability: input.externalCliAvailability, unavailableModels: input.unavailableModels, restrictionSources: input.restrictedSources }))
3643
3649
  ],
3644
3650
  restrictedCount: input.restrictedAgents.length,
3645
3651
  ...input.restrictedSources?.length ? { capabilityCeilingSources: [...input.restrictedSources] } : {}
@@ -3676,6 +3682,7 @@ function agentCapabilityDetails(input) {
3676
3682
  restrictedAgents: input.restrictedAgents,
3677
3683
  providerNames: input.providerNames,
3678
3684
  externalCliAvailability: input.externalCliAvailability,
3685
+ unavailableModels: input.unavailableModels,
3679
3686
  restrictedSources: input.restrictedSources
3680
3687
  }))
3681
3688
  };
@@ -3771,7 +3778,9 @@ function handleList(params, ctx) {
3771
3778
  const providerNameSet = providerNames(providerStatus);
3772
3779
  const capabilityMode = params.capabilities === true;
3773
3780
  const externalCliAvailability = capabilityMode ? externalCliAvailabilityForAgents([...agents, ...restrictedAgents]) : void 0;
3774
- const formatLine = capabilityMode ? (agent, names) => formatAgentCapabilitiesLine(agent, names, externalCliAvailability) : formatAgentListLine;
3781
+ const availableModels = capabilityMode ? ctx.modelRegistry.getAvailable().map(toModelInfo) : [];
3782
+ const unavailableModels = new Set([...agents, ...restrictedAgents].filter((agent) => (agent.runner?.type ?? "pi") === "pi" && isUnavailableSubagentModel(agent.model, availableModels, agent.modelProvider ?? ctx.model?.provider)));
3783
+ const formatLine = capabilityMode ? (agent, names) => formatAgentCapabilitiesLine(agent, names, externalCliAvailability, unavailableModels) : formatAgentListLine;
3775
3784
  const lines = [
3776
3785
  capabilityMode ? "Executable agents (capabilities):" : "Executable agents:",
3777
3786
  ...formatAgentListSections(agents, providerNameSet, formatLine)
@@ -3786,12 +3795,18 @@ function handleList(params, ctx) {
3786
3795
  restrictedAgents,
3787
3796
  providerNames: providerNameSet,
3788
3797
  externalCliAvailability: externalCliAvailability ?? /* @__PURE__ */ new Map(),
3798
+ unavailableModels,
3789
3799
  restrictedSources
3790
3800
  }));
3791
3801
  }
3802
+ function modelOverrideFile(override) {
3803
+ const scopes = override.fieldScopes?.model;
3804
+ const scope = scopes?.includes("project") ? "project" : scopes?.includes("user") ? "user" : override.scope;
3805
+ return { scope, path: override.paths?.[scope] ?? override.path };
3806
+ }
3792
3807
  function formatModelSource(agent, currentModel) {
3793
3808
  if (agent.override && agent.model !== agent.override.base.model) {
3794
- return `${agent.override.scope} override`;
3809
+ return `${modelOverrideFile(agent.override).scope} override`;
3795
3810
  }
3796
3811
  if (agent.modelSource?.type === "subagents.defaultModel" && agent.model === agent.modelSource.model) {
3797
3812
  return `${agent.modelSource.scope} defaultModel`;
@@ -3836,17 +3851,18 @@ function handleModels(params, ctx) {
3836
3851
  const modelEntries = selectedAgents.flatMap((agent) => requestedAgent ? [{ agent, name: requestedAgent }] : [{ agent, name: agent.name }, ...(agent.aliases ?? []).map((name) => ({ agent, name }))]);
3837
3852
  for (const { agent, name } of modelEntries) {
3838
3853
  const resolvedModel = resolveSubagentModelOverride(agent.model, currentModel, availableModels, agent.modelProvider ?? preferredProvider);
3854
+ const shownModel = resolvedModel === void 0 ? "(unresolved)" : (agent.runner?.type ?? "pi") === "pi" && isUnavailableSubagentModel(agent.model, availableModels, agent.modelProvider ?? preferredProvider) ? `${resolvedModel} ${UNAVAILABLE_MODEL_MARKER}` : resolvedModel;
3839
3855
  const effectiveThinking = resolveEffectiveThinking(resolvedModel, agent.thinking) ?? (agent.thinking === false ? "off" : void 0);
3840
3856
  const source = `${formatModelSource(agent, currentModel)}${agent.disabled ? "; disabled" : ""}${isAgentAllowedByCapabilityCeiling(agent.name, capabilityCeiling) ? "" : "; restricted"}`;
3841
3857
  if (requestedAgent) {
3842
3858
  lines.push(`Agent: ${requestedAgent}`);
3843
3859
  lines.push("Effective model:");
3844
- lines.push(` ${resolvedModel ?? "(unresolved)"}`);
3860
+ lines.push(` ${shownModel}`);
3845
3861
  lines.push(`Source: ${source}`);
3846
3862
  lines.push(`Thinking: ${effectiveThinking ?? "default"}`);
3847
3863
  if (agent.override) {
3848
3864
  lines.push("Override file:");
3849
- lines.push(` ${agent.override.path}`);
3865
+ lines.push(` ${modelOverrideFile(agent.override).path}`);
3850
3866
  }
3851
3867
  if (agent.model && resolvedModel && agent.model !== resolvedModel) {
3852
3868
  lines.push("Requested model setting:");
@@ -3860,12 +3876,12 @@ function handleModels(params, ctx) {
3860
3876
  }
3861
3877
  lines.push(name);
3862
3878
  lines.push(" model:");
3863
- lines.push(` ${resolvedModel ?? "(unresolved)"}`);
3879
+ lines.push(` ${shownModel}`);
3864
3880
  lines.push(` source: ${source}`);
3865
3881
  lines.push(` thinking: ${effectiveThinking ?? "default"}`);
3866
3882
  if (agent.override) {
3867
3883
  lines.push(" override file:");
3868
- lines.push(` ${agent.override.path}`);
3884
+ lines.push(` ${modelOverrideFile(agent.override).path}`);
3869
3885
  }
3870
3886
  if (agent.model && resolvedModel && agent.model !== resolvedModel) {
3871
3887
  lines.push(" requested model setting:");
@@ -4911,6 +4927,9 @@ function normalizePublicSubagentExecution(params, options = {}) {
4911
4927
  return { ok: false, error: "action must be a non-empty management/control action, or omit action and use workflow.", mode: "management" };
4912
4928
  }
4913
4929
  const normalizedAction = typeof action === "string" ? action.trim() : void 0;
4930
+ if (params.requireLauncher !== void 0 && (normalizedAction !== void 0 || hasWorkflowInput || params.tasks !== void 0 || params.chain !== void 0 || params.parallel !== void 0 || params.resume !== void 0)) {
4931
+ return { ok: false, error: REQUIRE_LAUNCHER_SHAPE_ERROR, mode: normalizedAction !== void 0 ? "management" : "workflow" };
4932
+ }
4914
4933
  if (params.baseRef !== void 0 && normalizedAction !== void 0 && normalizedAction !== "resume" && normalizedAction !== "schedule.create") {
4915
4934
  return { ok: false, error: "baseRef is only supported for child execution, resume, and schedule.create.", mode: "management" };
4916
4935
  }
@@ -5073,49 +5092,10 @@ function createParentWake(pi, now = Date.now) {
5073
5092
  };
5074
5093
  }
5075
5094
 
5076
- // src/workflows/workflow-launch-record.ts
5077
- import * as fs9 from "node:fs";
5078
- import * as path8 from "node:path";
5079
- var WORKFLOW_LAUNCH_RECORD_FILE = "launch.json";
5080
- function launchRecordPath(asyncDir) {
5081
- return path8.join(asyncDir, WORKFLOW_LAUNCH_RECORD_FILE);
5082
- }
5083
- function writeWorkflowLaunchRecord(asyncDir, record) {
5084
- writeAtomicJson(launchRecordPath(asyncDir), record);
5085
- }
5086
- function isPlainObject(value) {
5087
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
5088
- }
5089
- function invalid(error2) {
5090
- return { ok: false, missing: false, error: error2 };
5091
- }
5092
- function readWorkflowLaunchRecord(asyncDir) {
5093
- let text2;
5094
- try {
5095
- text2 = fs9.readFileSync(launchRecordPath(asyncDir), "utf-8");
5096
- } catch (error2) {
5097
- if (error2.code === "ENOENT") return { ok: false, missing: true, error: "launch.json is missing" };
5098
- return invalid(`could not be read: ${error2 instanceof Error ? error2.message : String(error2)}`);
5099
- }
5100
- let value;
5101
- try {
5102
- value = JSON.parse(text2);
5103
- } catch (error2) {
5104
- return invalid(`not valid JSON: ${error2 instanceof Error ? error2.message : String(error2)}`);
5105
- }
5106
- if (!isPlainObject(value)) return invalid("not a JSON object");
5107
- if (value.version !== 1) return invalid("version must be 1");
5108
- if (typeof value.scriptDigest !== "string" || !value.scriptDigest) return invalid("scriptDigest must be a non-empty string");
5109
- if (value.source === "structured") return { ok: true, record: { version: 1, source: "structured", scriptDigest: value.scriptDigest } };
5110
- if (value.source !== "script" && value.source !== "resource") return invalid('source must be "script", "resource", or "structured"');
5111
- if (!isPlainObject(value.params)) return invalid("params must be an object");
5112
- return { ok: true, record: { version: 1, source: value.source, params: value.params, scriptDigest: value.scriptDigest } };
5113
- }
5114
-
5115
5095
  // src/workflows/workflow-resume-claim.ts
5116
5096
  import { randomUUID as randomUUID3 } from "node:crypto";
5117
- import * as fs10 from "node:fs";
5118
- import * as path9 from "node:path";
5097
+ import * as fs9 from "node:fs";
5098
+ import * as path8 from "node:path";
5119
5099
  var CLAIM_FILE_PATTERN = /^resumed-by\.([1-9][0-9]*)\.json$/;
5120
5100
  var RELEASED_CLAIM_FILE_PATTERN = /^resumed-by\.([1-9][0-9]*)\.json\.released-/;
5121
5101
  var REFUSAL_FILE = "resume-refused.json";
@@ -5124,7 +5104,7 @@ var heldClaimsKey = /* @__PURE__ */ Symbol.for("pi-subagents.workflow-resume-cla
5124
5104
  var heldClaimsGlobal = globalThis;
5125
5105
  var heldClaims = heldClaimsGlobal[heldClaimsKey] ?? (heldClaimsGlobal[heldClaimsKey] = /* @__PURE__ */ new Set());
5126
5106
  function claimFilePath(asyncDir, generation) {
5127
- return path9.join(asyncDir, `resumed-by.${generation}.json`);
5107
+ return path8.join(asyncDir, `resumed-by.${generation}.json`);
5128
5108
  }
5129
5109
  function isClaim(value) {
5130
5110
  if (!isRecordedPid(value) || Array.isArray(value)) return false;
@@ -5135,7 +5115,7 @@ function readTopClaim(asyncDir, retries = 3) {
5135
5115
  let generation = 0;
5136
5116
  let releasedGeneration = 0;
5137
5117
  try {
5138
- for (const name of fs10.readdirSync(asyncDir)) {
5118
+ for (const name of fs9.readdirSync(asyncDir)) {
5139
5119
  const live = CLAIM_FILE_PATTERN.exec(name);
5140
5120
  if (live) generation = Math.max(generation, Number(live[1]));
5141
5121
  const released = RELEASED_CLAIM_FILE_PATTERN.exec(name);
@@ -5148,7 +5128,7 @@ function readTopClaim(asyncDir, retries = 3) {
5148
5128
  const filePath = claimFilePath(asyncDir, generation);
5149
5129
  let text2;
5150
5130
  try {
5151
- text2 = fs10.readFileSync(filePath, "utf-8");
5131
+ text2 = fs9.readFileSync(filePath, "utf-8");
5152
5132
  } catch (error2) {
5153
5133
  if (error2.code === "ENOENT" && retries > 0) return readTopClaim(asyncDir, retries - 1);
5154
5134
  return { kind: "unreadable" };
@@ -5165,7 +5145,7 @@ function readWorkflowResumeClaim(asyncDir) {
5165
5145
  return top.kind === "claim" ? top.claim : void 0;
5166
5146
  }
5167
5147
  function resumedRunStarted(sourceAsyncDir, newRunId) {
5168
- return path9.basename(newRunId) === newRunId && fs10.existsSync(path9.join(path9.dirname(sourceAsyncDir), newRunId, "status.json"));
5148
+ return path8.basename(newRunId) === newRunId && fs9.existsSync(path8.join(path8.dirname(sourceAsyncDir), newRunId, "status.json"));
5169
5149
  }
5170
5150
  function claimantLiveness(filePath, claim, liveness) {
5171
5151
  if (claim.pid === process.pid && claim.bootId === currentBootId() && claim.pidNamespaceScope === currentPidNamespaceScope()) return heldClaims.has(filePath) ? "alive" : "dead";
@@ -5181,14 +5161,14 @@ function workflowResumeClaimState(asyncDir, options = {}) {
5181
5161
  function createClaimFile(filePath, claim) {
5182
5162
  const tempPath = `${filePath}.${process.pid}.${randomUUID3()}.tmp`;
5183
5163
  try {
5184
- fs10.writeFileSync(tempPath, JSON.stringify(claim, null, 2), "utf-8");
5185
- fs10.linkSync(tempPath, filePath);
5164
+ fs9.writeFileSync(tempPath, JSON.stringify(claim, null, 2), "utf-8");
5165
+ fs9.linkSync(tempPath, filePath);
5186
5166
  return true;
5187
5167
  } catch (error2) {
5188
5168
  if (error2.code === "EEXIST") return false;
5189
5169
  throw error2;
5190
5170
  } finally {
5191
- fs10.rmSync(tempPath, { force: true });
5171
+ fs9.rmSync(tempPath, { force: true });
5192
5172
  }
5193
5173
  }
5194
5174
  function claimWorkflowResume(asyncDir, input) {
@@ -5223,18 +5203,18 @@ function releaseWorkflowResumeClaim(asyncDir, newRunId) {
5223
5203
  const top = readTopClaim(asyncDir);
5224
5204
  if (top.kind !== "claim" || top.claim.newRunId !== newRunId || top.claim.pid !== process.pid) return;
5225
5205
  try {
5226
- fs10.renameSync(top.filePath, `${top.filePath}.released-${randomUUID3()}`);
5206
+ fs9.renameSync(top.filePath, `${top.filePath}.released-${randomUUID3()}`);
5227
5207
  } catch (error2) {
5228
5208
  if (error2.code !== "ENOENT") throw error2;
5229
5209
  }
5230
5210
  heldClaims.delete(top.filePath);
5231
5211
  }
5232
5212
  function recordWorkflowResumeRefusal(asyncDir, refusal, now = Date.now()) {
5233
- writeAtomicJson(path9.join(asyncDir, REFUSAL_FILE), { version: 1, ...refusal, refusedAt: now });
5213
+ writeAtomicJson(path8.join(asyncDir, REFUSAL_FILE), { version: 1, ...refusal, refusedAt: now });
5234
5214
  }
5235
5215
  function readWorkflowResumeRefusal(asyncDir) {
5236
5216
  try {
5237
- const value = JSON.parse(fs10.readFileSync(path9.join(asyncDir, REFUSAL_FILE), "utf-8"));
5217
+ const value = JSON.parse(fs9.readFileSync(path8.join(asyncDir, REFUSAL_FILE), "utf-8"));
5238
5218
  return value?.version === 1 && typeof value.reason === "string" && typeof value.byHand === "string" && typeof value.refusedAt === "number" && (value.newRunId === void 0 || typeof value.newRunId === "string") ? value : void 0;
5239
5219
  } catch {
5240
5220
  return void 0;
@@ -5250,7 +5230,7 @@ function refusalSentence(reason, byHand) {
5250
5230
  return `${reason.replace(/\.$/, "")}.${byHand ? ` ${byHand}` : ""}`;
5251
5231
  }
5252
5232
  function hasWorkflowResumeRefusal(asyncDir) {
5253
- return fs10.existsSync(path9.join(asyncDir, REFUSAL_FILE));
5233
+ return fs9.existsSync(path8.join(asyncDir, REFUSAL_FILE));
5254
5234
  }
5255
5235
  var RESUMED_AS = { auto: "Auto-resumed as", manual: "Resumed as", reuse: "Relaunched as" };
5256
5236
  function describeWorkflowResume(asyncDir, runId) {
@@ -5260,8 +5240,8 @@ function describeWorkflowResume(asyncDir, runId) {
5260
5240
  return `Not auto-resumed: ${refusalSentence(refusal.reason, refusal.byHand)}`;
5261
5241
  }
5262
5242
  if (claim) return `${RESUMED_AS[claim.trigger]} ${claim.newRunId}.`;
5263
- const launch = readWorkflowLaunchRecord(asyncDir);
5264
- return launch.ok && launch.record.source !== "structured" ? resumeByHandText(runId) : relaunchByHandText(runId);
5243
+ const launch = readWorkflowLaunchRecord(path8.dirname(asyncDir), runId);
5244
+ return launch.ok && (launch.record.source === "script" || launch.record.source === "resource") ? resumeByHandText(runId) : relaunchByHandText(runId);
5265
5245
  }
5266
5246
 
5267
5247
  // src/runs/background/notify.ts
@@ -6236,7 +6216,6 @@ var DEFAULT_SOURCE = "pi-subagents:herdr";
6236
6216
  var DEFAULT_TTL_MS = 12e4;
6237
6217
  var DEFAULT_REFRESH_MS = 45e3;
6238
6218
  var MAX_TASK_LABEL_CHARS = 80;
6239
- var MAX_TITLE_TASK_CHARS = 42;
6240
6219
  var MAX_WORKFLOW_LABEL_NODES = 128;
6241
6220
  var MAX_WORKFLOW_LABEL_DEPTH = 8;
6242
6221
  var metadataReportSeq = Date.now() * 1e3;
@@ -6247,11 +6226,11 @@ function nextMetadataReportSeq() {
6247
6226
  function isRecord(value) {
6248
6227
  return typeof value === "object" && value !== null && !Array.isArray(value);
6249
6228
  }
6250
- function boundedTaskLabel(value, maxChars = MAX_TASK_LABEL_CHARS) {
6229
+ function boundedTaskLabel(value) {
6251
6230
  if (typeof value !== "string") return void 0;
6252
6231
  const normalized = sanitizeDisplayText(value).trim();
6253
6232
  if (!normalized) return void 0;
6254
- return previewDisplayText(normalized, maxChars);
6233
+ return previewDisplayText(normalized, MAX_TASK_LABEL_CHARS);
6255
6234
  }
6256
6235
  function workflowTaskLabel(data) {
6257
6236
  const explicit = boundedTaskLabel(data.taskLabel);
@@ -6332,11 +6311,7 @@ function registerHerdrStatusBridge(options) {
6332
6311
  };
6333
6312
  const titleSuffix = () => {
6334
6313
  if (runs.size === 0) return void 0;
6335
- const agentNames = activeAgentNames();
6336
- const activeCount = activeSubagentCount();
6337
- const task = boundedTaskLabel(activeTaskLabel(), MAX_TITLE_TASK_CHARS);
6338
- const target = task ?? (activeCount === 1 && agentNames.length === 1 ? agentNames[0] : String(activeCount));
6339
- return `\u23F3${target}${attentionRuns.size > 0 ? "\u26A0" : ""}`;
6314
+ return `\u23F3${activeSubagentCount()}${attentionRuns.size > 0 ? "\u26A0" : ""}`;
6340
6315
  };
6341
6316
  const enqueue = (args) => {
6342
6317
  pendingReport = args;
@@ -6592,8 +6567,8 @@ function registerPiWebSessionLiveness(registration) {
6592
6567
  }
6593
6568
 
6594
6569
  // src/runs/background/wait-subscriptions.ts
6595
- import * as fs11 from "node:fs";
6596
- import * as path10 from "node:path";
6570
+ import * as fs10 from "node:fs";
6571
+ import * as path9 from "node:path";
6597
6572
  import { randomUUID as randomUUID4 } from "node:crypto";
6598
6573
  var SUBSCRIPTION_VERSION = 1;
6599
6574
  var STATUS_OUTCOMES = /* @__PURE__ */ new Set(["timed out", "could not be reconciled", "needs attention", "reconciliation failed"]);
@@ -6613,7 +6588,7 @@ function needsAttention(run) {
6613
6588
  return run.activityState === "needs_attention" || run.steps.some((step) => step.activityState === "needs_attention");
6614
6589
  }
6615
6590
  function subscriptionFile(dir, token) {
6616
- return path10.join(dir, `${token}.json`);
6591
+ return path9.join(dir, `${token}.json`);
6617
6592
  }
6618
6593
  function formatWaitSubscriptions(state, now = Date.now()) {
6619
6594
  const subscriptions = [...state.waitSubscriptions?.values() ?? []].sort((left, right) => left.createdAt - right.createdAt);
@@ -6627,7 +6602,7 @@ function formatWaitSubscriptions(state, now = Date.now()) {
6627
6602
  function createWaitSubscriptionManager(pi, state, options = {}) {
6628
6603
  const asyncDirRoot = options.asyncDirRoot ?? DIRS.async;
6629
6604
  const resultsDir = options.resultsDir ?? DIRS.results;
6630
- const subscriptionsDir = options.subscriptionsDir ?? path10.join(path10.dirname(asyncDirRoot), "wait-subscriptions");
6605
+ const subscriptionsDir = options.subscriptionsDir ?? path9.join(path9.dirname(asyncDirRoot), "wait-subscriptions");
6631
6606
  const now = options.now ?? Date.now;
6632
6607
  const subscriptions = state.waitSubscriptions ?? /* @__PURE__ */ new Map();
6633
6608
  state.waitSubscriptions = subscriptions;
@@ -6641,16 +6616,16 @@ function createWaitSubscriptionManager(pi, state, options = {}) {
6641
6616
  lastForeignSweepAt = sweptAt;
6642
6617
  let files;
6643
6618
  try {
6644
- files = fs11.readdirSync(subscriptionsDir).filter((file) => file.endsWith(".json"));
6619
+ files = fs10.readdirSync(subscriptionsDir).filter((file) => file.endsWith(".json"));
6645
6620
  } catch (error2) {
6646
6621
  if (!isNotFound(error2)) console.error(`Failed to scan wait subscriptions in '${subscriptionsDir}':`, error2);
6647
6622
  return;
6648
6623
  }
6649
6624
  for (const file of files) {
6650
- const filePath = path10.join(subscriptionsDir, file);
6625
+ const filePath = path9.join(subscriptionsDir, file);
6651
6626
  let record;
6652
6627
  try {
6653
- record = parseRecord(JSON.parse(fs11.readFileSync(filePath, "utf-8")));
6628
+ record = parseRecord(JSON.parse(fs10.readFileSync(filePath, "utf-8")));
6654
6629
  } catch (error2) {
6655
6630
  console.error(`Ignoring invalid wait subscription '${filePath}':`, error2);
6656
6631
  continue;
@@ -6659,7 +6634,7 @@ function createWaitSubscriptionManager(pi, state, options = {}) {
6659
6634
  if (record.sessionId === state.currentSessionId) continue;
6660
6635
  if (sweptAt < record.expiresAt + FOREIGN_SWEEP_GRACE_MS) continue;
6661
6636
  try {
6662
- fs11.unlinkSync(filePath);
6637
+ fs10.unlinkSync(filePath);
6663
6638
  } catch (error2) {
6664
6639
  if (!isNotFound(error2)) console.error(`Failed to remove expired wait subscription '${filePath}':`, error2);
6665
6640
  }
@@ -6667,7 +6642,7 @@ function createWaitSubscriptionManager(pi, state, options = {}) {
6667
6642
  };
6668
6643
  const remove = (record) => {
6669
6644
  try {
6670
- fs11.unlinkSync(subscriptionFile(subscriptionsDir, record.token));
6645
+ fs10.unlinkSync(subscriptionFile(subscriptionsDir, record.token));
6671
6646
  } catch (error2) {
6672
6647
  if (!isNotFound(error2)) throw error2;
6673
6648
  }
@@ -6796,7 +6771,7 @@ Parent action: ${STATUS_OUTCOMES.has(outcome) ? STATUS_ACTION : COMPLETION_ACTIO
6796
6771
  createdAt,
6797
6772
  expiresAt: createdAt + input.timeoutMs
6798
6773
  };
6799
- fs11.mkdirSync(subscriptionsDir, { recursive: true });
6774
+ fs10.mkdirSync(subscriptionsDir, { recursive: true });
6800
6775
  writeAtomicJson(subscriptionFile(subscriptionsDir, record.token), record);
6801
6776
  subscriptions.set(record.token, record);
6802
6777
  return record;
@@ -6808,21 +6783,21 @@ Parent action: ${STATUS_OUTCOMES.has(outcome) ? STATUS_ACTION : COMPLETION_ACTIO
6808
6783
  if (!state.currentSessionId) return;
6809
6784
  let files;
6810
6785
  try {
6811
- files = fs11.readdirSync(subscriptionsDir).filter((file) => file.endsWith(".json"));
6786
+ files = fs10.readdirSync(subscriptionsDir).filter((file) => file.endsWith(".json"));
6812
6787
  } catch (error2) {
6813
6788
  if (isNotFound(error2)) return;
6814
6789
  throw error2;
6815
6790
  }
6816
6791
  for (const file of files) {
6817
6792
  try {
6818
- const record = parseRecord(JSON.parse(fs11.readFileSync(path10.join(subscriptionsDir, file), "utf-8")));
6793
+ const record = parseRecord(JSON.parse(fs10.readFileSync(path9.join(subscriptionsDir, file), "utf-8")));
6819
6794
  if (!record || file !== `${record.token}.json`) continue;
6820
6795
  if (record.sessionId === state.currentSessionId) {
6821
6796
  subscriptions.set(record.token, record);
6822
6797
  if (record.targetKind === "foreground" && !state.foregroundRuns?.has(record.runId)) unresolvedRestoredForegroundTokens.add(record.token);
6823
6798
  }
6824
6799
  } catch (error2) {
6825
- console.error(`Ignoring invalid wait subscription '${path10.join(subscriptionsDir, file)}':`, error2);
6800
+ console.error(`Ignoring invalid wait subscription '${path9.join(subscriptionsDir, file)}':`, error2);
6826
6801
  }
6827
6802
  }
6828
6803
  reconcile();
@@ -6845,25 +6820,26 @@ Parent action: ${STATUS_OUTCOMES.has(outcome) ? STATUS_ACTION : COMPLETION_ACTIO
6845
6820
  }
6846
6821
 
6847
6822
  // src/runs/shared/child-session.ts
6848
- import * as fs14 from "node:fs";
6849
- import * as path13 from "node:path";
6823
+ import * as fs13 from "node:fs";
6824
+ import * as path12 from "node:path";
6850
6825
  import { pathToFileURL } from "node:url";
6826
+ import { cleanupSessionResources, registerSessionResourceCleanup } from "@earendil-works/pi-ai";
6851
6827
 
6852
6828
  // src/runs/shared/child-commands.ts
6853
6829
  import { randomUUID as randomUUID5 } from "node:crypto";
6854
- import * as fs12 from "node:fs";
6855
- import * as path11 from "node:path";
6830
+ import * as fs11 from "node:fs";
6831
+ import * as path10 from "node:path";
6856
6832
  import { Type } from "typebox";
6857
6833
  var CHILD_COMMAND_TOOL = "subagent_command";
6858
6834
  var writeAtomicJson2 = createAtomicJsonWriter({ mode: 384 });
6859
6835
  var MAX_OUTPUT_BYTES = 8 * 1024;
6860
6836
  var RECENT_COMMANDS = 20;
6861
6837
  function childCommandStatePath(channelDir) {
6862
- return path11.join(channelDir, "commands.json");
6838
+ return path10.join(channelDir, "commands.json");
6863
6839
  }
6864
6840
  function readChildCommandState(channelDir) {
6865
6841
  try {
6866
- return JSON.parse(fs12.readFileSync(childCommandStatePath(channelDir), "utf8"));
6842
+ return JSON.parse(fs11.readFileSync(childCommandStatePath(channelDir), "utf8"));
6867
6843
  } catch (error2) {
6868
6844
  if (error2.code === "ENOENT") return void 0;
6869
6845
  throw error2;
@@ -6971,7 +6947,15 @@ Optional yieldTimeMs returns a command handle without stopping execution. Use su
6971
6947
  persist();
6972
6948
  startInbox();
6973
6949
  let timer;
6974
- if (typeof yieldTimeMs === "number") timer = setTimeout(() => operate("yield", toolCallId), yieldTimeMs);
6950
+ let yieldSaveError;
6951
+ if (typeof yieldTimeMs === "number") timer = setTimeout(() => {
6952
+ if (closed) return;
6953
+ try {
6954
+ operate("yield", toolCallId);
6955
+ } catch (error2) {
6956
+ yieldSaveError = error2;
6957
+ }
6958
+ }, yieldTimeMs);
6975
6959
  const execution = Promise.resolve().then(() => tool.execute(toolCallId, args, commandSignal, (update) => {
6976
6960
  job.snapshot.output = text(update);
6977
6961
  if (job.snapshot.state === "running") onUpdate?.(update);
@@ -6995,7 +6979,9 @@ Optional yieldTimeMs returns a command handle without stopping execution. Use su
6995
6979
  });
6996
6980
  const result5 = await Promise.race([execution.then((value) => ({ value })), yielded.then(() => void 0)]);
6997
6981
  if (result5) return result5.value;
6998
- 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.
6982
+ const saveWarning = yieldSaveError === void 0 ? "" : `
6983
+ The command's saved state is out of date because it could not be saved: ${yieldSaveError instanceof Error ? yieldSaveError.message : String(yieldSaveError)}`;
6984
+ 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}
6999
6985
  ${job.snapshot.output}` }], details: { command: { ...job.snapshot } } };
7000
6986
  }
7001
6987
  };
@@ -7035,7 +7021,7 @@ async function waitForCommand(settled, waitMs, signal) {
7035
7021
  }
7036
7022
  }
7037
7023
  function commandReplyPath(channelDir, id) {
7038
- return path11.join(channelDir, "command-replies", `${id}.json`);
7024
+ return path10.join(channelDir, "command-replies", `${id}.json`);
7039
7025
  }
7040
7026
  async function controlChildCommand(channelDir, operation, toolCallId, signal) {
7041
7027
  const current = readChildCommandState(channelDir);
@@ -7059,7 +7045,7 @@ async function controlChildCommand(channelDir, operation, toolCallId, signal) {
7059
7045
  while (Date.now() < deadlineAt) {
7060
7046
  if (signal?.aborted) throw new Error("Command control wait aborted; delivery may still be pending.");
7061
7047
  try {
7062
- const reply = JSON.parse(fs12.readFileSync(replyPath, "utf8"));
7048
+ const reply = JSON.parse(fs11.readFileSync(replyPath, "utf8"));
7063
7049
  if (reply.error) throw new Error(reply.error);
7064
7050
  if (reply.state) return reply.state;
7065
7051
  } catch (error2) {
@@ -7069,7 +7055,7 @@ async function controlChildCommand(channelDir, operation, toolCallId, signal) {
7069
7055
  }
7070
7056
  throw new Error("Command control acknowledgement timed out. Inspect command status; cancellation is not confirmed.");
7071
7057
  } finally {
7072
- fs12.rmSync(replyPath, { force: true });
7058
+ fs11.rmSync(replyPath, { force: true });
7073
7059
  }
7074
7060
  }
7075
7061
 
@@ -7093,8 +7079,8 @@ function pinChildCacheRetention(agent, env) {
7093
7079
  }
7094
7080
 
7095
7081
  // src/runs/background/runner-aliases.ts
7096
- import * as fs13 from "node:fs";
7097
- import * as path12 from "node:path";
7082
+ import * as fs12 from "node:fs";
7083
+ import * as path11 from "node:path";
7098
7084
  var JITI_ALIAS_ENV = "JITI_ALIAS";
7099
7085
  var HOST_PEER_ALIASES = [
7100
7086
  { specifier: "@earendil-works/pi-coding-agent", pkg: "@earendil-works/pi-coding-agent", subpath: "." },
@@ -7117,7 +7103,7 @@ var CHORD_PEER_ALIASES = [
7117
7103
  ];
7118
7104
  function readManifest(packageDir) {
7119
7105
  try {
7120
- return JSON.parse(fs13.readFileSync(path12.join(packageDir, "package.json"), "utf-8"));
7106
+ return JSON.parse(fs12.readFileSync(path11.join(packageDir, "package.json"), "utf-8"));
7121
7107
  } catch {
7122
7108
  return void 0;
7123
7109
  }
@@ -7154,7 +7140,7 @@ function resolvePackageSubpath(packageDir, subpath) {
7154
7140
  const map = typeof exportsField === "string" || Array.isArray(exportsField) || exportsField && typeof exportsField === "object" && !Object.keys(exportsField).some((key) => key.startsWith(".")) ? { ".": exportsField } : exportsField;
7155
7141
  if (subpath in map) {
7156
7142
  const exact = exportTarget(map[subpath]);
7157
- return typeof exact === "string" ? path12.resolve(packageDir, exact) : void 0;
7143
+ return typeof exact === "string" ? path11.resolve(packageDir, exact) : void 0;
7158
7144
  }
7159
7145
  let best;
7160
7146
  for (const [pattern, entry] of Object.entries(map)) {
@@ -7169,23 +7155,23 @@ function resolvePackageSubpath(packageDir, subpath) {
7169
7155
  const target = exportTarget(best.entry);
7170
7156
  if (typeof target !== "string") return void 0;
7171
7157
  const wildcard = subpath.slice(best.prefix.length, subpath.length - best.suffix.length);
7172
- return path12.resolve(packageDir, target.replaceAll("*", () => wildcard));
7158
+ return path11.resolve(packageDir, target.replaceAll("*", () => wildcard));
7173
7159
  }
7174
7160
  if (subpath !== ".") return void 0;
7175
- return path12.resolve(packageDir, typeof manifest.main === "string" && manifest.main.trim() ? manifest.main : "index.js");
7161
+ return path11.resolve(packageDir, typeof manifest.main === "string" && manifest.main.trim() ? manifest.main : "index.js");
7176
7162
  }
7177
7163
  function findPeerPackageDir(piPackageRoot, pkg, hostName) {
7178
7164
  if (hostName === pkg) return piPackageRoot;
7179
- const candidates = [path12.join(piPackageRoot, "node_modules", pkg)];
7165
+ const candidates = [path11.join(piPackageRoot, "node_modules", pkg)];
7180
7166
  let dir = piPackageRoot;
7181
7167
  for (; ; ) {
7182
- const parent = path12.dirname(dir);
7168
+ const parent = path11.dirname(dir);
7183
7169
  if (parent === dir) break;
7184
- if (path12.basename(parent) === "node_modules" || path12.basename(path12.dirname(parent)) === "node_modules") {
7185
- const modulesRoot = path12.basename(parent) === "node_modules" ? parent : path12.dirname(parent);
7186
- candidates.push(path12.join(modulesRoot, pkg));
7170
+ if (path11.basename(parent) === "node_modules" || path11.basename(path11.dirname(parent)) === "node_modules") {
7171
+ const modulesRoot = path11.basename(parent) === "node_modules" ? parent : path11.dirname(parent);
7172
+ candidates.push(path11.join(modulesRoot, pkg));
7187
7173
  }
7188
- candidates.push(path12.join(parent, "node_modules", pkg));
7174
+ candidates.push(path11.join(parent, "node_modules", pkg));
7189
7175
  dir = parent;
7190
7176
  }
7191
7177
  return candidates.find((candidate) => readManifest(candidate)?.name === pkg);
@@ -7202,7 +7188,7 @@ function resolveHostPeerAliases(piPackageRoot) {
7202
7188
  const packageDir = findPeerPackageDir(piPackageRoot, pkg, hostManifest?.name);
7203
7189
  const target = packageDir ? resolvePackageSubpath(packageDir, subpath) : void 0;
7204
7190
  if (optional && packageDir && target === void 0) continue;
7205
- if (target && fs13.existsSync(target)) aliases[specifier] = fs13.realpathSync(target);
7191
+ if (target && fs12.existsSync(target)) aliases[specifier] = fs12.realpathSync(target);
7206
7192
  else if (pkg !== CHORD_PACKAGE || chordRequired) missing.push(specifier);
7207
7193
  }
7208
7194
  return { aliases, missing };
@@ -7252,9 +7238,9 @@ var CHILD_PROMPT_RUNTIME_EXTENSION_PATH = "<inline:pi-subagents:prompt-runtime>"
7252
7238
  var CHILD_PROMPT_BOUNDARY_EXTENSION_PATH = "<inline:pi-subagents:prompt-boundary>";
7253
7239
  var PI_UNICODE_SPACES = new RegExp("[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]", "g");
7254
7240
  function childExtensionFileIdentity(extensionPath) {
7255
- if (!path13.isAbsolute(extensionPath)) return void 0;
7241
+ if (!path12.isAbsolute(extensionPath)) return void 0;
7256
7242
  try {
7257
- const stat = fs14.statSync(extensionPath, { bigint: true });
7243
+ const stat = fs13.statSync(extensionPath, { bigint: true });
7258
7244
  return stat.isFile() ? `${stat.dev}:${stat.ino}` : void 0;
7259
7245
  } catch {
7260
7246
  return void 0;
@@ -7303,6 +7289,18 @@ function prioritizeChildCommandRuntime(result5) {
7303
7289
  extensions.unshift(commands);
7304
7290
  return { ...result5, extensions };
7305
7291
  }
7292
+ function disposeChildSession(session) {
7293
+ let released = false;
7294
+ const unregister = registerSessionResourceCleanup((sessionId) => {
7295
+ if (sessionId === session.sessionId) released = true;
7296
+ });
7297
+ try {
7298
+ session.dispose();
7299
+ } finally {
7300
+ unregister();
7301
+ if (!released) cleanupSessionResources(session.sessionId);
7302
+ }
7303
+ }
7306
7304
  var loading = Promise.resolve();
7307
7305
  function resetExtensionCacheOnReload(loader) {
7308
7306
  if (!("loaded" in loader)) return false;
@@ -7433,14 +7431,14 @@ async function loadHostPiCodingAgent() {
7433
7431
  const overrideRoot = process.env[PI_CODING_AGENT_PACKAGE_ROOT_ENV]?.trim() || void 0;
7434
7432
  const root = resolveHostPiPackageRoot();
7435
7433
  if (root) {
7436
- const entry = fs14.realpathSync(resolveHostPackageEntry(root, root === overrideRoot ? overrideRoot : void 0));
7434
+ const entry = fs13.realpathSync(resolveHostPackageEntry(root, root === overrideRoot ? overrideRoot : void 0));
7437
7435
  return import(pathToFileURL(entry).href);
7438
7436
  }
7439
7437
  return import(PI_CODING_AGENT_PACKAGE);
7440
7438
  }
7441
7439
  function resolveHostPackageEntry(root, overrideRoot) {
7442
- const packageJson = path13.join(root, "package.json");
7443
- const source = fs14.readFileSync(packageJson, "utf8");
7440
+ const packageJson = path12.join(root, "package.json");
7441
+ const source = fs13.readFileSync(packageJson, "utf8");
7444
7442
  let parsed;
7445
7443
  try {
7446
7444
  parsed = JSON.parse(source);
@@ -7541,7 +7539,7 @@ function createDefaultChildSessionFactory(options = {}) {
7541
7539
  } catch (error2) {
7542
7540
  launch.onExtensionError?.({ extensionPath: "<session>", event: "session_shutdown", error: error2 });
7543
7541
  } finally {
7544
- session2.dispose();
7542
+ disposeChildSession(session2);
7545
7543
  }
7546
7544
  };
7547
7545
  let inheritedProviders = /* @__PURE__ */ new Set();
@@ -7567,7 +7565,7 @@ function createDefaultChildSessionFactory(options = {}) {
7567
7565
  }
7568
7566
  }
7569
7567
  const newSessionOptions = launch.parentSessionFile ? { parentSession: launch.parentSessionFile } : void 0;
7570
- const newSessionFile = launch.storage.kind === "file" && !fs14.existsSync(launch.storage.sessionFile);
7568
+ const newSessionFile = launch.storage.kind === "file" && !fs13.existsSync(launch.storage.sessionFile);
7571
7569
  const sessionManager = launch.storage.kind === "file" ? pi.SessionManager.open(launch.storage.sessionFile, void 0, launch.cwd) : launch.storage.kind === "dir" ? pi.SessionManager.create(launch.cwd, launch.storage.sessionDir, newSessionOptions) : launch.storage.kind === "memory" ? pi.SessionManager.inMemory(launch.cwd, newSessionOptions) : pi.SessionManager.create(launch.cwd, void 0, newSessionOptions);
7572
7570
  const header = newSessionFile && launch.parentSessionFile ? sessionManager.getHeader() : null;
7573
7571
  if (header) header.parentSession = launch.parentSessionFile;
@@ -7598,7 +7596,7 @@ function createDefaultChildSessionFactory(options = {}) {
7598
7596
  }
7599
7597
  });
7600
7598
  } catch (error2) {
7601
- session2.dispose();
7599
+ disposeChildSession(session2);
7602
7600
  throw error2;
7603
7601
  } finally {
7604
7602
  binding = false;
@@ -7721,7 +7719,7 @@ function childSessionFactory() {
7721
7719
  }
7722
7720
  function createLazyPlacementFactory(local) {
7723
7721
  let placed;
7724
- const factory = async () => placed ??= (await import("./chunk-J5YL7LYR.js")).createPlacementAwareChildSessionFactory(local);
7722
+ const factory = async () => placed ??= (await import("./chunk-BU6PFPVX.js")).createPlacementAwareChildSessionFactory(local);
7725
7723
  return {
7726
7724
  async create(launch) {
7727
7725
  return launch.machine ? (await factory()).create(launch) : local.create(launch);
@@ -7743,8 +7741,8 @@ async function disposeChildSessions() {
7743
7741
 
7744
7742
  // src/workflows/workflow-reuse.ts
7745
7743
  import { createHash as createHash3 } from "node:crypto";
7746
- import * as fs15 from "node:fs";
7747
- import * as path14 from "node:path";
7744
+ import * as fs14 from "node:fs";
7745
+ import * as path13 from "node:path";
7748
7746
  var WORKFLOW_CHILD_JOURNAL_FILE = "workflow-children.jsonl";
7749
7747
  var WORKFLOW_RUNTIME_REPLACED_STOP_NOTICE = "Async children that were still running keep running, and finished children are kept.";
7750
7748
  function runtimeReplacedAbortReason() {
@@ -7763,9 +7761,9 @@ function workflowChildFingerprint(params) {
7763
7761
  return sha256(workflowRunParamsFingerprint(params));
7764
7762
  }
7765
7763
  function appendWorkflowChildJournal(workflowAsyncDir, record) {
7766
- const journalPath = path14.join(workflowAsyncDir, WORKFLOW_CHILD_JOURNAL_FILE);
7764
+ const journalPath = path13.join(workflowAsyncDir, WORKFLOW_CHILD_JOURNAL_FILE);
7767
7765
  try {
7768
- fs15.appendFileSync(journalPath, `${JSON.stringify(record)}
7766
+ fs14.appendFileSync(journalPath, `${JSON.stringify(record)}
7769
7767
  `, "utf-8");
7770
7768
  } catch (error2) {
7771
7769
  console.error(`Failed to append workflow child journal '${journalPath}':`, error2);
@@ -7775,7 +7773,7 @@ function readWorkflowChildJournal(runId, workflowAsyncDir) {
7775
7773
  const source = { runId, started: /* @__PURE__ */ new Map(), settled: /* @__PURE__ */ new Map() };
7776
7774
  let text2 = "";
7777
7775
  try {
7778
- text2 = fs15.readFileSync(path14.join(workflowAsyncDir, WORKFLOW_CHILD_JOURNAL_FILE), "utf-8");
7776
+ text2 = fs14.readFileSync(path13.join(workflowAsyncDir, WORKFLOW_CHILD_JOURNAL_FILE), "utf-8");
7779
7777
  } catch {
7780
7778
  return source;
7781
7779
  }
@@ -7797,12 +7795,12 @@ function readWorkflowChildJournal(runId, workflowAsyncDir) {
7797
7795
  }
7798
7796
  var WORKFLOW_REUSE_CHAIN_MAX_LINKS = 16;
7799
7797
  function readWorkflowReuseChain(asyncDirRoot, headRunId, headStatus) {
7800
- const source = readWorkflowChildJournal(headRunId, path14.join(asyncDirRoot, headRunId));
7798
+ const source = readWorkflowChildJournal(headRunId, path13.join(asyncDirRoot, headRunId));
7801
7799
  const visited = /* @__PURE__ */ new Set([headRunId]);
7802
7800
  let next = headStatus.workflow?.reusedFrom;
7803
7801
  for (let links = 0; isRunId(next) && links < WORKFLOW_REUSE_CHAIN_MAX_LINKS && !visited.has(next); links++) {
7804
7802
  visited.add(next);
7805
- const asyncDir = path14.join(asyncDirRoot, next);
7803
+ const asyncDir = path13.join(asyncDirRoot, next);
7806
7804
  let status;
7807
7805
  try {
7808
7806
  status = readStatus(asyncDir);
@@ -7841,7 +7839,7 @@ function findWorkflowReuseSource(asyncDirRoot, sessionId, scriptDigest, argsDige
7841
7839
  return void 0;
7842
7840
  }
7843
7841
  for (const runId of runIds) {
7844
- const asyncDir = path14.join(asyncDirRoot, runId);
7842
+ const asyncDir = path13.join(asyncDirRoot, runId);
7845
7843
  let status;
7846
7844
  try {
7847
7845
  status = readStatus(asyncDir);
@@ -7857,14 +7855,14 @@ function findWorkflowReuseSource(asyncDirRoot, sessionId, scriptDigest, argsDige
7857
7855
  }
7858
7856
  function readNamedWorkflowReuseSource(asyncDirRoot, runId, scriptDigest, cwd, claimOwnerRunId) {
7859
7857
  const runName = isRunId(runId);
7860
- if (runName) reconcileAsyncRun(path14.join(asyncDirRoot, runId));
7861
- const status = runName ? readStatus(path14.join(asyncDirRoot, runId)) : null;
7858
+ if (runName) reconcileAsyncRun(path13.join(asyncDirRoot, runId));
7859
+ const status = runName ? readStatus(path13.join(asyncDirRoot, runId)) : null;
7862
7860
  if (!status) throw new Error(`options.reuseFrom: workflow run '${runId}' was not found.`);
7863
7861
  if (status.mode !== "workflow") throw new Error(`options.reuseFrom: run '${runId}' is not a workflow run.`);
7864
7862
  if (!isReusableWorkflowStopCause(status.workflow?.stopCause)) throw new Error(`options.reuseFrom: workflow run '${runId}' did not stop because its session was replaced or its Pi process exited, so its children cannot be reused.`);
7865
7863
  if (status.workflow.scriptDigest !== scriptDigest) throw new Error(`options.reuseFrom: workflow run '${runId}' ran a different workflow script.`);
7866
7864
  if (status.cwd !== cwd) throw new Error(`options.reuseFrom: workflow run '${runId}' ran in '${status.cwd}', not '${cwd}'.`);
7867
- assertWorkflowRunNotClaimed(path14.join(asyncDirRoot, runId), runId, true, claimOwnerRunId);
7865
+ assertWorkflowRunNotClaimed(path13.join(asyncDirRoot, runId), runId, true, claimOwnerRunId);
7868
7866
  return readWorkflowReuseChain(asyncDirRoot, runId, status);
7869
7867
  }
7870
7868
  function matchWorkflowReuse(source, key, fingerprint) {
@@ -7876,10 +7874,10 @@ function matchWorkflowReuse(source, key, fingerprint) {
7876
7874
 
7877
7875
  // src/workflows/workflow-resume.ts
7878
7876
  import { randomUUID as randomUUID6 } from "node:crypto";
7879
- import * as path15 from "node:path";
7877
+ import * as path14 from "node:path";
7880
7878
  var MAX_WORKFLOW_RESUME_ATTEMPTS = 3;
7881
7879
  function workflowResumeRefusal(code, reason, runId) {
7882
- const byHand = code === "launch-missing" || code === "launch-invalid" || code === "structured" || code === "digest" || code === "authority" ? relaunchByHandText(runId) : code === "capacity" || code === "attempts" || code === "launch-failed" ? resumeByHandText(runId) : "";
7880
+ const byHand = code === "launch-missing" || code === "launch-invalid" || code === "structured" || code === "internal" || code === "digest" || code === "authority" ? relaunchByHandText(runId) : code === "capacity" || code === "attempts" || code === "launch-failed" ? resumeByHandText(runId) : "";
7883
7881
  return { code, reason, byHand };
7884
7882
  }
7885
7883
  function manualWorkflowResumeRefusalText(runId, refusal) {
@@ -7892,7 +7890,7 @@ function workflowResumeTargetId(asyncDirRoot, params) {
7892
7890
  if (!isRunId(id)) return void 0;
7893
7891
  let status;
7894
7892
  try {
7895
- status = readStatus(path15.join(asyncDirRoot, id));
7893
+ status = readStatus(path14.join(asyncDirRoot, id));
7896
7894
  } catch {
7897
7895
  return void 0;
7898
7896
  }
@@ -7901,18 +7899,18 @@ function workflowResumeTargetId(asyncDirRoot, params) {
7901
7899
  function prepareWorkflowResume(input) {
7902
7900
  const { asyncDirRoot, sourceRunId, trigger } = input;
7903
7901
  const refuse = (code, reason) => ({ ok: false, ...workflowResumeRefusal(code, reason, sourceRunId) });
7904
- const sourceAsyncDir = path15.join(asyncDirRoot, sourceRunId);
7905
- const stored = readStatus(sourceAsyncDir);
7906
- if (stored && !ownsRun(input.currentSessionId, stored.sessionId)) return refuse("not-owned", "it was started in another session; reopen that session to resume it");
7902
+ const sourceAsyncDir = path14.join(asyncDirRoot, sourceRunId);
7903
+ const read = readWorkflowLaunchRecord(asyncDirRoot, sourceRunId);
7904
+ if (!read.ok) return read.missing ? refuse("launch-missing", "launch.json is missing (the run started before launches were saved outside its run directory)") : refuse("launch-invalid", `launch.json is invalid: ${read.error}`);
7905
+ const record = read.record;
7906
+ if (!ownsRun(input.currentSessionId, record.sessionId)) return refuse("not-owned", "it was started in another session; reopen that session to resume it");
7907
7907
  if (trigger === "manual") reconcileAsyncRun(sourceAsyncDir);
7908
7908
  const status = readStatus(sourceAsyncDir);
7909
7909
  if (!status || status.mode !== "workflow" || !isReusableWorkflowStopCause(status.workflow?.stopCause)) return refuse("not-interrupted", "not interrupted; pass message to revive one of its children");
7910
7910
  const attempt = (status.workflow?.resumeOrigin?.attempt ?? 0) + (status.workflow?.stopCause === WORKFLOW_STOP_CAUSE_OWNER_EXITED ? 1 : 0);
7911
7911
  if (trigger === "auto" && attempt > MAX_WORKFLOW_RESUME_ATTEMPTS) return refuse("attempts", `${MAX_WORKFLOW_RESUME_ATTEMPTS} resumes already followed Pi exits`);
7912
- const read = readWorkflowLaunchRecord(sourceAsyncDir);
7913
- if (!read.ok) return read.missing ? refuse("launch-missing", "launch.json is missing (the run started before launches were saved)") : refuse("launch-invalid", `launch.json is invalid: ${read.error}`);
7914
- const record = read.record;
7915
7912
  if (record.source === "structured") return refuse("structured", "launched from tasks/chain");
7913
+ if (record.source === "internal") return refuse("internal", "launched by a schedule or prompt-template delegation");
7916
7914
  if (record.source === "script" && (typeof record.params.workflowScript !== "string" || workflowScriptDigest(record.params.workflowScript) !== record.scriptDigest)) {
7917
7915
  return refuse("launch-invalid", "launch.json is invalid: its script does not match its scriptDigest");
7918
7916
  }
@@ -7934,7 +7932,7 @@ function prepareWorkflowResume(input) {
7934
7932
  ...record.params,
7935
7933
  async: true,
7936
7934
  reuseFrom: sourceRunId,
7937
- ...status.admissionCapabilityCeiling ? { capabilityCeiling: status.admissionCapabilityCeiling } : {}
7935
+ ...record.admissionCapabilityCeiling ? { capabilityCeiling: record.admissionCapabilityCeiling } : {}
7938
7936
  },
7939
7937
  expectedScriptDigest: record.scriptDigest,
7940
7938
  resumeOrigin: { sourceRunId, attempt }
@@ -7989,7 +7987,8 @@ function flattenSubagentToolOptions(params, disabled) {
7989
7987
  }
7990
7988
 
7991
7989
  // src/runs/background/retained-children.ts
7992
- import * as fs16 from "node:fs";
7990
+ import * as fs15 from "node:fs";
7991
+ import * as path15 from "node:path";
7993
7992
  var MAX_RETAINED_CHILDREN = 10;
7994
7993
  var MAX_RETAINED_CHILD_CANDIDATES = 100;
7995
7994
  var MAX_TASK_SUMMARY_LENGTH = 120;
@@ -8003,7 +8002,7 @@ function retainedSessionFile(sessionFile) {
8003
8002
  if (!sessionFile) return { state: "not-resumable", reason: "no persisted session file" };
8004
8003
  if (!sessionFile.endsWith(".jsonl")) return { state: "not-resumable", reason: "persisted session file is not a .jsonl file" };
8005
8004
  try {
8006
- const stat = fs16.lstatSync(sessionFile);
8005
+ const stat = fs15.lstatSync(sessionFile);
8007
8006
  if (!stat.isFile() || stat.isSymbolicLink()) return { state: "not-resumable", reason: "persisted session file is not a regular file" };
8008
8007
  return { state: "resumable", sessionPath: sessionFile };
8009
8008
  } catch (error2) {
@@ -8020,7 +8019,7 @@ function childResumability(run, step) {
8020
8019
  if (session.state === "not-resumable") return session;
8021
8020
  let recoveryDescriptor;
8022
8021
  try {
8023
- recoveryDescriptor = readAsyncRecoveryDescriptor(run.asyncDir);
8022
+ recoveryDescriptor = readAsyncRecoveryDescriptor(path15.dirname(run.asyncDir), path15.basename(run.asyncDir));
8024
8023
  if (!recoveryDescriptor) return { state: "not-resumable", reason: "missing recovery descriptor" };
8025
8024
  if (recoveryDescriptor.sourceRunId !== run.id) return { state: "not-resumable", reason: `recovery descriptor belongs to run ${recoveryDescriptor.sourceRunId}` };
8026
8025
  if (recoveryDescriptor.agent !== step.agent) return { state: "not-resumable", reason: `recovery descriptor belongs to agent ${recoveryDescriptor.agent}` };
@@ -8030,7 +8029,7 @@ function childResumability(run, step) {
8030
8029
  let requiredCwd;
8031
8030
  try {
8032
8031
  requiredCwd = resolveRetainedWorktreeCwd(parallelHandoffPath(run.asyncDir), run.id, step.index, step.worktreePath) ?? recoveryDescriptor.cwd ?? run.cwd;
8033
- if (!requiredCwd || !fs16.statSync(requiredCwd).isDirectory()) return { state: "not-resumable", reason: `required cwd is missing: ${requiredCwd ?? "unknown"}` };
8032
+ if (!requiredCwd || !fs15.statSync(requiredCwd).isDirectory()) return { state: "not-resumable", reason: `required cwd is missing: ${requiredCwd ?? "unknown"}` };
8034
8033
  } catch (error2) {
8035
8034
  return { state: "not-resumable", reason: `resume dependency unavailable: ${error2 instanceof Error ? error2.message : String(error2)}` };
8036
8035
  }
@@ -8090,9 +8089,52 @@ function formatRetainedChildren(children) {
8090
8089
  ].join("\n");
8091
8090
  }
8092
8091
 
8092
+ // src/extension/subagent-launch-tool.ts
8093
+ import { Type as Type2 } from "typebox";
8094
+ var SUBAGENT_LAUNCH_TOOL = "subagent_launch";
8095
+ var parameters = Type2.Object({
8096
+ workflowRunId: Type2.String(),
8097
+ key: Type2.String(),
8098
+ agent: Type2.Optional(Type2.String()),
8099
+ task: Type2.Optional(Type2.String()),
8100
+ cwd: Type2.Optional(Type2.String()),
8101
+ model: Type2.Optional(Type2.String()),
8102
+ async: Type2.Optional(Type2.Boolean()),
8103
+ worktree: Type2.Optional(Type2.Boolean()),
8104
+ resume: Type2.Optional(Type2.String()),
8105
+ commands: Type2.Optional(Type2.Array(Type2.Object({
8106
+ command: Type2.String(),
8107
+ cwd: Type2.Optional(Type2.String()),
8108
+ env: Type2.Optional(Type2.Record(Type2.String(), Type2.String()))
8109
+ }))),
8110
+ output: Type2.Optional(Type2.String())
8111
+ });
8112
+ function registerSubagentLaunchTool(pi) {
8113
+ pi.registerTool({
8114
+ name: SUBAGENT_LAUNCH_TOOL,
8115
+ label: "Subagent launch",
8116
+ description: "A workflow is about to start this subagent. Blocking this call stops that child from starting.",
8117
+ parameters,
8118
+ exposure: "deferred",
8119
+ async execute() {
8120
+ return { content: [{ type: "text", text: "Records approval for a workflow child launch; it starts nothing itself." }], details: {} };
8121
+ }
8122
+ });
8123
+ }
8124
+ async function approveWorkflowChildLaunch(ctx, describe, signal) {
8125
+ if (!("executeTool" in ctx)) return void 0;
8126
+ const toolCtx = ctx;
8127
+ if (!toolCtx.tools.some((tool) => tool.name === SUBAGENT_LAUNCH_TOOL)) return void 0;
8128
+ const args = describe();
8129
+ const outcome = await toolCtx.executeTool(SUBAGENT_LAUNCH_TOOL, args, { signal });
8130
+ if (!outcome.isError) return void 0;
8131
+ const reason = outcome.result.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n").trim();
8132
+ return `Workflow child '${args.key}' was not started: the ${SUBAGENT_LAUNCH_TOOL} call was refused${reason ? `: ${reason}` : "."}`;
8133
+ }
8134
+
8093
8135
  // src/runs/shared/external-job-bridge.ts
8094
8136
  import { randomUUID as randomUUID7 } from "node:crypto";
8095
- import * as fs17 from "node:fs";
8137
+ import * as fs16 from "node:fs";
8096
8138
  import * as os2 from "node:os";
8097
8139
  import * as path16 from "node:path";
8098
8140
  var EXTERNAL_JOB_BRIDGE_REQUEST_DIR = "external-job-requests";
@@ -8125,18 +8167,18 @@ function dispatchClaimHandlePath(claimDir) {
8125
8167
  return path16.join(claimDir, "handle.json");
8126
8168
  }
8127
8169
  function completedDispatchClaimExists(asyncDir, id) {
8128
- return fs17.existsSync(dispatchClaimCompletedPath(dispatchClaimDir(asyncDir, id)));
8170
+ return fs16.existsSync(dispatchClaimCompletedPath(dispatchClaimDir(asyncDir, id)));
8129
8171
  }
8130
8172
  function responsePath(asyncDir, id) {
8131
8173
  return path16.join(responseDir(asyncDir), `${id}.json`);
8132
8174
  }
8133
8175
  function readJson2(filePath) {
8134
- return JSON.parse(fs17.readFileSync(filePath, "utf-8"));
8176
+ return JSON.parse(fs16.readFileSync(filePath, "utf-8"));
8135
8177
  }
8136
8178
  function processStartIdentity(pid) {
8137
8179
  if (process.platform === "linux") {
8138
8180
  try {
8139
- const stat = fs17.readFileSync(`/proc/${pid}/stat`, "utf-8");
8181
+ const stat = fs16.readFileSync(`/proc/${pid}/stat`, "utf-8");
8140
8182
  const commandEnd = stat.lastIndexOf(")");
8141
8183
  if (commandEnd === -1) return void 0;
8142
8184
  const fields = stat.slice(commandEnd + 1).trim().split(/\s+/);
@@ -8256,16 +8298,16 @@ function claimDispatchRequest(asyncDir, filePath, request) {
8256
8298
  const claimDir = dispatchClaimDir(asyncDir, request.id);
8257
8299
  const tempClaimDir = dispatchClaimTempDir(asyncDir, request.id);
8258
8300
  try {
8259
- fs17.mkdirSync(tempClaimDir);
8301
+ fs16.mkdirSync(tempClaimDir);
8260
8302
  writeAtomicJson(path16.join(tempClaimDir, "owner.json"), owner);
8261
8303
  writeAtomicJson(path16.join(tempClaimDir, "request.json"), claimed);
8262
- fs17.renameSync(tempClaimDir, claimDir);
8304
+ fs16.renameSync(tempClaimDir, claimDir);
8263
8305
  } catch (error2) {
8264
- fs17.rmSync(tempClaimDir, { recursive: true, force: true });
8306
+ fs16.rmSync(tempClaimDir, { recursive: true, force: true });
8265
8307
  if (isClaimConflictError(error2)) return void 0;
8266
8308
  throw error2;
8267
8309
  }
8268
- fs17.rmSync(filePath, { force: true });
8310
+ fs16.rmSync(filePath, { force: true });
8269
8311
  return { request: claimed, filePath: claimDir };
8270
8312
  }
8271
8313
  function parseClaimOwner(value) {
@@ -8347,18 +8389,18 @@ function createChildExternalJobBridgeSweeper() {
8347
8389
  function serviceExternalJobBridgeRequests(asyncDir) {
8348
8390
  let files;
8349
8391
  try {
8350
- files = fs17.readdirSync(requestDir(asyncDir), { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json") && !completedDispatchClaimExists(asyncDir, entry.name.replace(/\.json$/, "")) || entry.isDirectory() && entry.name.endsWith(".claim") && !fs17.existsSync(dispatchClaimCompletedPath(path16.join(requestDir(asyncDir), entry.name)))).map((entry) => entry.name).slice(0, MAX_REQUESTS_PER_SWEEP);
8392
+ files = fs16.readdirSync(requestDir(asyncDir), { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json") && !completedDispatchClaimExists(asyncDir, entry.name.replace(/\.json$/, "")) || entry.isDirectory() && entry.name.endsWith(".claim") && !fs16.existsSync(dispatchClaimCompletedPath(path16.join(requestDir(asyncDir), entry.name)))).map((entry) => entry.name).slice(0, MAX_REQUESTS_PER_SWEEP);
8351
8393
  } catch (error2) {
8352
8394
  if (error2.code === "ENOENT") return;
8353
8395
  throw error2;
8354
8396
  }
8355
- fs17.mkdirSync(responseDir(asyncDir), { recursive: true });
8397
+ fs16.mkdirSync(responseDir(asyncDir), { recursive: true });
8356
8398
  for (const file of files) {
8357
8399
  serviceExternalJobBridgeRequestFile(asyncDir, file);
8358
8400
  }
8359
8401
  }
8360
8402
  function serviceExternalJobBridgeRequestFile(asyncDir, file) {
8361
- fs17.mkdirSync(responseDir(asyncDir), { recursive: true });
8403
+ fs16.mkdirSync(responseDir(asyncDir), { recursive: true });
8362
8404
  if (file.endsWith(".claim")) {
8363
8405
  serviceExternalJobDispatchClaim(asyncDir, file);
8364
8406
  return;
@@ -8379,14 +8421,14 @@ function serviceExternalJobBridgeRequestFile(asyncDir, file) {
8379
8421
  message: error2 instanceof Error ? error2.message : String(error2),
8380
8422
  completedAt: Date.now()
8381
8423
  });
8382
- fs17.rmSync(filePath, { force: true });
8424
+ fs16.rmSync(filePath, { force: true });
8383
8425
  return;
8384
8426
  }
8385
8427
  if (isDispatchOperation(request.operation) && completedDispatchClaimExists(asyncDir, request.id)) {
8386
- fs17.rmSync(filePath, { force: true });
8428
+ fs16.rmSync(filePath, { force: true });
8387
8429
  return;
8388
8430
  }
8389
- if (inFlight.has(request.id) || fs17.existsSync(responsePath(asyncDir, request.id))) return;
8431
+ if (inFlight.has(request.id) || fs16.existsSync(responsePath(asyncDir, request.id))) return;
8390
8432
  if (isDispatchOperation(request.operation) && request.claimedAt !== void 0) return;
8391
8433
  const claimed = isDispatchOperation(request.operation) ? claimDispatchRequest(asyncDir, filePath, request) : { request, filePath };
8392
8434
  if (!claimed) return;
@@ -8397,7 +8439,7 @@ function serviceExternalJobBridgeRequestFile(asyncDir, file) {
8397
8439
  if (isDispatchOperation(claimedRequest.operation)) {
8398
8440
  writeAtomicJson(dispatchClaimCompletedPath(claimed.filePath), { completedAt: Date.now() });
8399
8441
  } else {
8400
- fs17.rmSync(claimed.filePath, { recursive: true, force: true });
8442
+ fs16.rmSync(claimed.filePath, { recursive: true, force: true });
8401
8443
  }
8402
8444
  }).catch((error2) => {
8403
8445
  writeAtomicJson(responsePath(asyncDir, claimedRequest.id), {
@@ -8416,10 +8458,10 @@ function serviceExternalJobBridgeRequestFile(asyncDir, file) {
8416
8458
  }
8417
8459
  function serviceExternalJobDispatchClaim(asyncDir, file) {
8418
8460
  const claimDir = path16.join(requestDir(asyncDir), file);
8419
- if (fs17.existsSync(dispatchClaimCompletedPath(claimDir))) return;
8461
+ if (fs16.existsSync(dispatchClaimCompletedPath(claimDir))) return;
8420
8462
  const owner = readClaimOwner(claimDir);
8421
- if (!owner && fs17.existsSync(requestPath(asyncDir, file.replace(/\.claim$/, ""))) && !fs17.existsSync(responsePath(asyncDir, file.replace(/\.claim$/, "")))) {
8422
- fs17.rmSync(claimDir, { recursive: true, force: true });
8463
+ if (!owner && fs16.existsSync(requestPath(asyncDir, file.replace(/\.claim$/, ""))) && !fs16.existsSync(responsePath(asyncDir, file.replace(/\.claim$/, "")))) {
8464
+ fs16.rmSync(claimDir, { recursive: true, force: true });
8423
8465
  return;
8424
8466
  }
8425
8467
  if (!claimOwnerIsDead(owner)) return;
@@ -8429,7 +8471,7 @@ function serviceExternalJobDispatchClaim(asyncDir, file) {
8429
8471
  } catch {
8430
8472
  return;
8431
8473
  }
8432
- if (!isDispatchOperation(request.operation) || fs17.existsSync(responsePath(asyncDir, request.id))) return;
8474
+ if (!isDispatchOperation(request.operation) || fs16.existsSync(responsePath(asyncDir, request.id))) return;
8433
8475
  const handle = readClaimHandle(request.provider, claimDir);
8434
8476
  if (handle) {
8435
8477
  writeAtomicJson(responsePath(asyncDir, request.id), {
@@ -8441,7 +8483,7 @@ function serviceExternalJobDispatchClaim(asyncDir, file) {
8441
8483
  completedAt: Date.now()
8442
8484
  });
8443
8485
  writeAtomicJson(dispatchClaimCompletedPath(claimDir), { completedAt: Date.now() });
8444
- fs17.rmSync(requestPath(asyncDir, request.id), { force: true });
8486
+ fs16.rmSync(requestPath(asyncDir, request.id), { force: true });
8445
8487
  return;
8446
8488
  }
8447
8489
  writeAtomicJson(responsePath(asyncDir, request.id), {
@@ -8453,8 +8495,8 @@ function serviceExternalJobDispatchClaim(asyncDir, file) {
8453
8495
  message: `External-job ${request.operation} for provider '${request.provider}' was claimed by a host process that is no longer alive before a provider job id was committed. Refusing to redispatch the prompt automatically.`,
8454
8496
  completedAt: Date.now()
8455
8497
  });
8456
- fs17.rmSync(claimDir, { recursive: true, force: true });
8457
- fs17.rmSync(requestPath(asyncDir, request.id), { force: true });
8498
+ fs16.rmSync(claimDir, { recursive: true, force: true });
8499
+ fs16.rmSync(requestPath(asyncDir, request.id), { force: true });
8458
8500
  }
8459
8501
 
8460
8502
  // src/shared/provider-diagnostics.ts
@@ -8583,7 +8625,6 @@ export {
8583
8625
  COMPLETION_ACTION,
8584
8626
  STATUS_ACTION,
8585
8627
  createParentWake,
8586
- writeWorkflowLaunchRecord,
8587
8628
  resumedRunStarted,
8588
8629
  workflowResumeClaimState,
8589
8630
  claimWorkflowResume,
@@ -8628,5 +8669,7 @@ export {
8628
8669
  prepareWorkflowResume,
8629
8670
  flattenSubagentToolOptions,
8630
8671
  listRetainedChildren,
8631
- formatRetainedChildren
8672
+ formatRetainedChildren,
8673
+ registerSubagentLaunchTool,
8674
+ approveWorkflowChildLaunch
8632
8675
  };