pi-subagents 0.83.1 → 0.85.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-5YIITCPD.js → chunk-3UZ5FVVJ.js} +322 -110
  5. package/bundle/{chunk-F4ASL6OV.js → chunk-7MAE3DJV.js} +1 -1
  6. package/bundle/{chunk-YXFJVCOL.js → chunk-CS4O36CZ.js} +11 -156
  7. package/bundle/{chunk-AHIFYGR3.js → chunk-DV2NCNPR.js} +22 -11
  8. package/bundle/{chunk-G2Z6ZH26.js → chunk-GCSLVFCX.js} +1 -1
  9. package/bundle/{chunk-2S4K53MV.js → chunk-H2NLFTC5.js} +1 -1
  10. package/bundle/{chunk-MABL3FUM.js → chunk-HFTBF7SG.js} +2 -1
  11. package/bundle/chunk-HXRB42AF.js +108 -0
  12. package/bundle/{chunk-UFL7IYCW.js → chunk-IQIWF2VX.js} +190 -1177
  13. package/bundle/{chunk-NPIYWVOD.js → chunk-JNXT3MPI.js} +15 -6
  14. package/bundle/{chunk-C7JMPU5F.js → chunk-JO67XSKD.js} +59 -27
  15. package/bundle/{chunk-UUP372DR.js → chunk-JWYG26RE.js} +223 -93
  16. package/bundle/{chunk-C5P5CHYK.js → chunk-KDMFBYFM.js} +1 -1
  17. package/bundle/{chunk-V2BZYLEP.js → chunk-KEY3UQMQ.js} +7 -2
  18. package/bundle/{chunk-VLFZIN6D.js → chunk-KZ34KQQH.js} +9 -6
  19. package/bundle/{chunk-ZVOAMTUQ.js → chunk-L2ENOFVZ.js} +76 -58
  20. package/bundle/{chunk-RNIZLSEA.js → chunk-LGMILZNE.js} +323 -18
  21. package/bundle/{chunk-UYK5MZWE.js → chunk-LTPH2DXH.js} +247 -153
  22. package/bundle/{chunk-2D52JFLF.js → chunk-N7B2KD74.js} +41 -117
  23. package/bundle/{chunk-IPGZMQXV.js → chunk-O7CPL6H4.js} +183 -28
  24. package/bundle/{chunk-D3JAFGMO.js → chunk-PHZP3KHB.js} +1 -1
  25. package/bundle/{chunk-2DHZTCOL.js → chunk-PVIVCDG2.js} +2 -2
  26. package/bundle/{chunk-LFDBD4PW.js → chunk-QO75KJBT.js} +2 -2
  27. package/bundle/{chunk-SSG7IEP5.js → chunk-RQAUNAWG.js} +2 -2
  28. package/bundle/{chunk-QP5ZWNIS.js → chunk-RV5OGHLO.js} +6 -3
  29. package/bundle/chunk-T5V5BRCL.js +1067 -0
  30. package/bundle/{chunk-LNRJCP2Y.js → chunk-UX4SCV5N.js} +337 -207
  31. package/bundle/{chunk-F5DBXJ2G.js → chunk-WOVMHDES.js} +234 -182
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +8 -8
  36. package/bundle/project-panes.js +3 -3
  37. package/docs/agents.md +17 -2
  38. package/docs/configuration.md +2 -2
  39. package/docs/extension-api.md +16 -1
  40. package/docs/workflows.md +30 -2
  41. package/package.json +1 -1
  42. package/src/agents/agent-management.js +27 -11
  43. package/src/agents/agent-memory.d.ts +1 -4
  44. package/src/agents/agent-memory.js +1 -4
  45. package/src/agents/agents.d.ts +1 -3
  46. package/src/agents/agents.js +7 -6
  47. package/src/agents/frontmatter.js +1 -8
  48. package/src/agents/global-npm-root.d.ts +1 -0
  49. package/src/agents/global-npm-root.js +11 -3
  50. package/src/agents/skills.d.ts +0 -3
  51. package/src/agents/skills.js +0 -3
  52. package/src/extension/config.js +7 -1
  53. package/src/extension/herdr-pi-bridge.js +10 -2
  54. package/src/extension/index.d.ts +0 -13
  55. package/src/extension/index.js +43 -32
  56. package/src/extension/public-execution.d.ts +1 -0
  57. package/src/extension/public-execution.js +4 -0
  58. package/src/extension/reply-workflow-script.js +24 -4
  59. package/src/extension/schemas.d.ts +8 -3
  60. package/src/extension/schemas.js +5 -3
  61. package/src/extension/session-switch.d.ts +25 -0
  62. package/src/extension/session-switch.js +138 -0
  63. package/src/extension/subagent-guide.d.ts +1 -1
  64. package/src/extension/subagent-guide.js +1 -1
  65. package/src/extension/subagent-launch-tool.d.ts +25 -0
  66. package/src/extension/subagent-launch-tool.js +48 -0
  67. package/src/extension/tool-activation.js +25 -11
  68. package/src/extension/tool-description.js +6 -0
  69. package/src/inspectors/herdr/actions.d.ts +0 -1
  70. package/src/inspectors/herdr/actions.js +0 -1
  71. package/src/inspectors/session-roots-codec.d.ts +0 -1
  72. package/src/inspectors/session-roots-codec.js +0 -1
  73. package/src/inspectors/tmux/actions.d.ts +0 -1
  74. package/src/inspectors/tmux/actions.js +0 -1
  75. package/src/integrations/herdr-status.js +3 -8
  76. package/src/intercom/native-supervisor-channel.js +65 -9
  77. package/src/runs/background/async-execution.d.ts +8 -9
  78. package/src/runs/background/async-execution.js +77 -27
  79. package/src/runs/background/async-job-tracker.js +12 -0
  80. package/src/runs/background/async-resume.d.ts +2 -1
  81. package/src/runs/background/async-resume.js +112 -39
  82. package/src/runs/background/async-retention.d.ts +1 -0
  83. package/src/runs/background/async-retention.js +22 -11
  84. package/src/runs/background/auto-drain.js +2 -1
  85. package/src/runs/background/boot-id.d.ts +1 -3
  86. package/src/runs/background/boot-id.js +1 -3
  87. package/src/runs/background/completion-batcher.d.ts +3 -4
  88. package/src/runs/background/completion-batcher.js +2 -3
  89. package/src/runs/background/control-channel.d.ts +0 -6
  90. package/src/runs/background/control-channel.js +0 -6
  91. package/src/runs/background/fleet-view.js +2 -3
  92. package/src/runs/background/notify.d.ts +0 -2
  93. package/src/runs/background/notify.js +0 -2
  94. package/src/runs/background/result-watcher.d.ts +1 -0
  95. package/src/runs/background/result-watcher.js +59 -29
  96. package/src/runs/background/resume-guidance.js +4 -2
  97. package/src/runs/background/retained-children.js +2 -1
  98. package/src/runs/background/run-child-session.d.ts +2 -1
  99. package/src/runs/background/run-child-session.js +10 -2
  100. package/src/runs/background/run-status.js +4 -3
  101. package/src/runs/background/scheduled-runs.d.ts +3 -1
  102. package/src/runs/background/scheduled-runs.js +13 -16
  103. package/src/runs/background/subagent-runner.d.ts +2 -4
  104. package/src/runs/background/subagent-runner.js +10 -6
  105. package/src/runs/background/subagent-wait.js +12 -15
  106. package/src/runs/background/wait-config.d.ts +2 -0
  107. package/src/runs/background/wait-config.js +17 -3
  108. package/src/runs/background/wait-tool.js +4 -2
  109. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  110. package/src/runs/background/workflow-terminal-proof.js +0 -1
  111. package/src/runs/foreground/execution.d.ts +0 -3
  112. package/src/runs/foreground/execution.js +17 -9
  113. package/src/runs/foreground/subagent-executor.d.ts +3 -2
  114. package/src/runs/foreground/subagent-executor.js +112 -26
  115. package/src/runs/shared/child-commands.js +15 -2
  116. package/src/runs/shared/child-hooks.d.ts +1 -7
  117. package/src/runs/shared/child-hooks.js +13 -5
  118. package/src/runs/shared/child-launch.js +6 -2
  119. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  120. package/src/runs/shared/child-session.d.ts +3 -1
  121. package/src/runs/shared/child-session.js +22 -2
  122. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  123. package/src/runs/shared/child-tool-plan.js +0 -1
  124. package/src/runs/shared/claude-code-adapter.js +11 -0
  125. package/src/runs/shared/external-cli-runner.js +26 -6
  126. package/src/runs/shared/herdr-connection.js +2 -1
  127. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  128. package/src/runs/shared/herdr-pane-host.js +17 -1
  129. package/src/runs/shared/herdr-placed-run.js +48 -22
  130. package/src/runs/shared/lane-metadata.d.ts +0 -1
  131. package/src/runs/shared/lane-metadata.js +0 -1
  132. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  133. package/src/runs/shared/model-resolution-diagnostic.d.ts +11 -1
  134. package/src/runs/shared/model-resolution-diagnostic.js +25 -0
  135. package/src/runs/shared/model-resolution.d.ts +2 -2
  136. package/src/runs/shared/model-resolution.js +7 -1
  137. package/src/runs/shared/model-scope.d.ts +1 -5
  138. package/src/runs/shared/model-scope.js +1 -5
  139. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  140. package/src/runs/shared/mutation-evidence.js +52 -7
  141. package/src/runs/shared/nested-events.d.ts +1 -0
  142. package/src/runs/shared/nested-events.js +1 -1
  143. package/src/runs/shared/parallel-utils.d.ts +2 -1
  144. package/src/runs/shared/permissions.js +5 -3
  145. package/src/runs/shared/placement-host.d.ts +5 -1
  146. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  147. package/src/runs/shared/rex-pane-host.js +0 -2
  148. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  149. package/src/runs/shared/run-launch-folder.js +21 -0
  150. package/src/runs/shared/runner-launcher.d.ts +12 -1
  151. package/src/runs/shared/runner-launcher.js +16 -0
  152. package/src/runs/shared/single-output.d.ts +3 -3
  153. package/src/runs/shared/single-output.js +5 -3
  154. package/src/runs/shared/structured-output.d.ts +8 -0
  155. package/src/runs/shared/structured-output.js +30 -2
  156. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  157. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  158. package/src/runs/shared/tool-timeout.js +2 -1
  159. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  160. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  161. package/src/runs/shared/worktree.d.ts +3 -0
  162. package/src/runs/shared/worktree.js +20 -0
  163. package/src/shared/capacity-resilient-json.d.ts +1 -1
  164. package/src/shared/child-cache-retention.d.ts +1 -2
  165. package/src/shared/child-cache-retention.js +1 -2
  166. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  167. package/src/shared/fleet-transcript-reader.js +333 -0
  168. package/src/shared/formatters.d.ts +0 -18
  169. package/src/shared/formatters.js +0 -18
  170. package/src/shared/session-succession.d.ts +16 -1
  171. package/src/shared/session-succession.js +41 -2
  172. package/src/shared/session-warnings.d.ts +7 -0
  173. package/src/shared/session-warnings.js +26 -0
  174. package/src/shared/settings.d.ts +0 -23
  175. package/src/shared/settings.js +3 -35
  176. package/src/shared/types.d.ts +28 -11
  177. package/src/shared/types.js +0 -12
  178. package/src/shared/utils.d.ts +0 -14
  179. package/src/shared/utils.js +0 -22
  180. package/src/shared/wait-tool-name.d.ts +8 -0
  181. package/src/shared/wait-tool-name.js +13 -0
  182. package/src/slash/slash-commands.js +2 -1
  183. package/src/slash/subagent-cost.d.ts +3 -2
  184. package/src/slash/subagent-cost.js +22 -3
  185. package/src/slash/subagents-admin.js +0 -1
  186. package/src/tui/fleet-status.d.ts +0 -5
  187. package/src/tui/fleet-status.js +4 -24
  188. package/src/tui/fleet-transcript.d.ts +1 -44
  189. package/src/tui/fleet-transcript.js +1 -327
  190. package/src/tui/fleet.js +6 -4
  191. package/src/tui/render.d.ts +0 -9
  192. package/src/tui/render.js +81 -47
  193. package/src/tui/subagent-messages.js +3 -2
  194. package/src/watchdog/register-child.d.ts +2 -3
  195. package/src/watchdog/register-child.js +2 -3
  196. package/src/watchdog/turn-delta.js +2 -1
  197. package/src/workflows/scripted-workflow.js +243 -20
  198. package/src/workflows/workflow-launch-record.d.ts +15 -6
  199. package/src/workflows/workflow-launch-record.js +30 -12
  200. package/src/workflows/workflow-resume-claim.js +2 -2
  201. package/src/workflows/workflow-resume.d.ts +1 -1
  202. package/src/workflows/workflow-resume.js +11 -8
  203. package/src/workflows/workflow-script-worker.d.ts +13 -0
  204. package/src/workflows/workflow-script-worker.js +79 -0
  205. package/workflow-script-process.cjs +36 -0
  206. package/workflow-script-worker.cjs +453 -176
@@ -11,24 +11,28 @@ import {
11
11
  startWatchdogDiffBaselineCapture,
12
12
  writeUserWatchdogEnabled,
13
13
  writeWatchdogModelSettings
14
- } from "./chunk-UFL7IYCW.js";
14
+ } from "./chunk-IQIWF2VX.js";
15
15
  import {
16
16
  resolveGitRepositoryIdentity
17
- } from "./chunk-VLFZIN6D.js";
17
+ } from "./chunk-KZ34KQQH.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-UYK5MZWE.js";
25
+ } from "./chunk-LTPH2DXH.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-RNIZLSEA.js";
57
+ } from "./chunk-LGMILZNE.js";
54
58
  import {
55
59
  requestAsyncCommand,
56
60
  watchAsyncControlInbox
57
- } from "./chunk-F4ASL6OV.js";
61
+ } from "./chunk-7MAE3DJV.js";
58
62
  import {
59
63
  supervisorChannelDir
60
- } from "./chunk-V2BZYLEP.js";
64
+ } from "./chunk-KEY3UQMQ.js";
61
65
  import {
62
66
  createHerdrClient,
63
67
  detectHerdr
64
- } from "./chunk-2DHZTCOL.js";
68
+ } from "./chunk-PVIVCDG2.js";
65
69
  import {
66
70
  getProjectSubagentsDir
67
- } from "./chunk-D3JAFGMO.js";
71
+ } from "./chunk-PHZP3KHB.js";
68
72
  import {
69
73
  ExternalJobProviderError,
70
74
  getExternalJobProvider,
@@ -74,7 +78,7 @@ import {
74
78
  } from "./chunk-YYREO77V.js";
75
79
  import {
76
80
  mergeRuntimeAgents
77
- } from "./chunk-G2Z6ZH26.js";
81
+ } from "./chunk-GCSLVFCX.js";
78
82
  import {
79
83
  CODE_OWNED_EXTERNAL_CLI_ADAPTER_LABEL,
80
84
  PI_CODING_AGENT_PACKAGE,
@@ -100,6 +104,7 @@ import {
100
104
  getProjectConfigDir,
101
105
  getSupportedThinkingLevels,
102
106
  isCodeOwnedExternalCliAdapterId,
107
+ isUnavailableSubagentModel,
103
108
  mergeAgentsForScope,
104
109
  mergeBuiltinAgentOverride,
105
110
  normalizeModelSegment,
@@ -126,10 +131,11 @@ import {
126
131
  validateCodeOwnedProfileRunner,
127
132
  validateExecutionAcceptance,
128
133
  validateToolBudgetConfig,
134
+ waitToolName,
129
135
  withFileLease,
130
136
  writeAtomicJson,
131
137
  writePrivateAtomicJson
132
- } from "./chunk-LNRJCP2Y.js";
138
+ } from "./chunk-UX4SCV5N.js";
133
139
  import {
134
140
  DIRS,
135
141
  INTERCOM_DETACH_REQUEST_EVENT,
@@ -678,7 +684,7 @@ var DEFAULT_FAST_TOOL_TIMEOUT_TOOLS = /* @__PURE__ */ new Set([
678
684
  ]);
679
685
  var TOOL_TIMEOUT_EXEMPT_TOOLS = /* @__PURE__ */ new Set(["contact_supervisor", "intercom", "bg_wait"]);
680
686
  function isToolTimeoutExempt(toolName) {
681
- return toolName !== void 0 && TOOL_TIMEOUT_EXEMPT_TOOLS.has(toolName);
687
+ return toolName !== void 0 && (TOOL_TIMEOUT_EXEMPT_TOOLS.has(toolName) || toolName === waitToolName());
682
688
  }
683
689
  function defaultToolTimeoutMs(toolName) {
684
690
  return toolName !== void 0 && DEFAULT_FAST_TOOL_TIMEOUT_TOOLS.has(toolName) ? DEFAULT_FAST_TOOL_TIMEOUT_MS : void 0;
@@ -1497,6 +1503,9 @@ function parseScheduleInterval(every) {
1497
1503
  function timestamp(value) {
1498
1504
  return new Date(value).toISOString();
1499
1505
  }
1506
+ function errorText3(error2) {
1507
+ return error2 instanceof Error ? error2.message : String(error2);
1508
+ }
1500
1509
  function validateScheduleId(id) {
1501
1510
  if (!SCHEDULE_ID.test(id)) throw new Error("Schedule id must be 1-64 characters and contain only letters, numbers, '.', '_', or '-'.");
1502
1511
  return id;
@@ -1667,7 +1676,7 @@ function parseSchedule(value, file) {
1667
1676
  if (record.trigger.kind === "once") {
1668
1677
  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
1678
  } 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.`);
1679
+ 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
1680
  } else if (record.trigger.kind === "calendar") {
1672
1681
  restoreCalendarTrigger(record.trigger);
1673
1682
  } else throw new Error(`Schedule record '${file}' has an unsupported trigger.`);
@@ -1938,7 +1947,7 @@ var ScheduledRunManager = class {
1938
1947
  try {
1939
1948
  ids = store.ids();
1940
1949
  } catch (error2) {
1941
- console.error(`Failed to inspect schedule store '${store.root}' during async completion:`, error2);
1950
+ this.deps.reportWarning?.(`Failed to inspect schedule store '${store.root}': ${errorText3(error2)}`, `schedule-store:${store.root}:${errorText3(error2)}`);
1942
1951
  continue;
1943
1952
  }
1944
1953
  for (const id of ids) {
@@ -1950,7 +1959,7 @@ var ScheduledRunManager = class {
1950
1959
  this.finishRun(store, schedule, run, data.success === true, typeof data.summary === "string" ? data.summary : void 0);
1951
1960
  return;
1952
1961
  } catch (error2) {
1953
- console.error(`Failed to inspect schedule '${id}' in '${store.root}' during async completion:`, error2);
1962
+ this.deps.reportWarning?.(`Failed to inspect schedule '${id}' in '${store.root}': ${errorText3(error2)}`, `schedule-record:${store.root}:${id}`);
1954
1963
  }
1955
1964
  }
1956
1965
  }
@@ -2042,6 +2051,7 @@ Mission: ${schedule.target.missionId}`}`, [schedule]);
2042
2051
  const schedule = this.resolve(params);
2043
2052
  if (schedule.paused === paused) return textResult(`Schedule ${schedule.id} is already ${paused ? "paused" : "active"}.`, [schedule]);
2044
2053
  schedule.paused = paused;
2054
+ if (!paused && schedule.trigger.kind === "interval" && schedule.trigger.nextRunAt === void 0) schedule.trigger.nextRunAt = timestamp(this.now() + schedule.trigger.everyMs);
2045
2055
  schedule.updatedAt = timestamp(this.now());
2046
2056
  this.requireStore().write(schedule);
2047
2057
  this.requireStore().appendEvent(schedule, paused ? "schedule.paused" : "schedule.resumed");
@@ -3540,7 +3550,8 @@ function agentListMetadata(agent, providerNames2, externalCliAvailability) {
3540
3550
  function formatAgentListLine(agent, providerNames2) {
3541
3551
  return `- ${agent.name} (${agentListMetadata(agent, providerNames2)}): ${agent.description}`;
3542
3552
  }
3543
- function formatAgentCapabilitiesLine(agent, providerNames2, externalCliAvailability) {
3553
+ var UNAVAILABLE_MODEL_MARKER = "(unavailable in the active model registry)";
3554
+ function formatAgentCapabilitiesLine(agent, providerNames2, externalCliAvailability, unavailableModels) {
3544
3555
  const declaredTools = [
3545
3556
  ...agent.tools ?? [],
3546
3557
  ...(agent.mcpDirectTools ?? []).map((tool) => `mcp:${tool}`)
@@ -3556,6 +3567,7 @@ function formatAgentCapabilitiesLine(agent, providerNames2, externalCliAvailabil
3556
3567
  if (agent.model !== void 0) {
3557
3568
  model = agent.model;
3558
3569
  if (agent.modelProvider && !agent.model.includes("/")) model = `${agent.modelProvider}/${agent.model}`;
3570
+ if (unavailableModels.has(agent)) model = `${model} ${UNAVAILABLE_MODEL_MARKER}`;
3559
3571
  }
3560
3572
  const thinking = agent.thinking === false ? "off" : agent.thinking ?? "default";
3561
3573
  const machine = agent.machine ? `; Machine: ${agent.machine} (saved Herdr placement)` : "";
@@ -3628,7 +3640,7 @@ function agentCapabilityRow(agent, options) {
3628
3640
  aliases: agent.aliases ? [...agent.aliases] : void 0,
3629
3641
  runner: agentCapabilityRunner(agent, options.providerNames, options.externalCliAvailability),
3630
3642
  tools: agentCapabilityTools(agent),
3631
- model: presentDetails({ value: agent.model, thinking: agent.thinking }),
3643
+ model: presentDetails({ value: agent.model, thinking: agent.thinking, unavailable: options.unavailableModels.has(agent) || void 0 }),
3632
3644
  execution: presentDetails({ defaultAsync: agent.defaultAsync, timeoutMs: agent.defaultTimeoutMs }),
3633
3645
  acceptance: presentDetails({ policy: agent.defaultAcceptance, role: agent.acceptanceRole }),
3634
3646
  output: presentDetails({ path: agent.output, mode: agent.outputMode }),
@@ -3638,8 +3650,8 @@ function agentCapabilityRow(agent, options) {
3638
3650
  function agentCapabilitiesSnapshot(input) {
3639
3651
  return {
3640
3652
  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 }))
3653
+ ...input.agents.map((agent) => agentCapabilityRow(agent, { executable: true, providerNames: input.providerNames, externalCliAvailability: input.externalCliAvailability, unavailableModels: input.unavailableModels })),
3654
+ ...input.restrictedAgents.map((agent) => agentCapabilityRow(agent, { executable: false, providerNames: input.providerNames, externalCliAvailability: input.externalCliAvailability, unavailableModels: input.unavailableModels, restrictionSources: input.restrictedSources }))
3643
3655
  ],
3644
3656
  restrictedCount: input.restrictedAgents.length,
3645
3657
  ...input.restrictedSources?.length ? { capabilityCeilingSources: [...input.restrictedSources] } : {}
@@ -3676,6 +3688,7 @@ function agentCapabilityDetails(input) {
3676
3688
  restrictedAgents: input.restrictedAgents,
3677
3689
  providerNames: input.providerNames,
3678
3690
  externalCliAvailability: input.externalCliAvailability,
3691
+ unavailableModels: input.unavailableModels,
3679
3692
  restrictedSources: input.restrictedSources
3680
3693
  }))
3681
3694
  };
@@ -3771,7 +3784,9 @@ function handleList(params, ctx) {
3771
3784
  const providerNameSet = providerNames(providerStatus);
3772
3785
  const capabilityMode = params.capabilities === true;
3773
3786
  const externalCliAvailability = capabilityMode ? externalCliAvailabilityForAgents([...agents, ...restrictedAgents]) : void 0;
3774
- const formatLine = capabilityMode ? (agent, names) => formatAgentCapabilitiesLine(agent, names, externalCliAvailability) : formatAgentListLine;
3787
+ const availableModels = capabilityMode ? ctx.modelRegistry.getAvailable().map(toModelInfo) : [];
3788
+ const unavailableModels = new Set([...agents, ...restrictedAgents].filter((agent) => (agent.runner?.type ?? "pi") === "pi" && isUnavailableSubagentModel(agent.model, availableModels, agent.modelProvider ?? ctx.model?.provider)));
3789
+ const formatLine = capabilityMode ? (agent, names) => formatAgentCapabilitiesLine(agent, names, externalCliAvailability, unavailableModels) : formatAgentListLine;
3775
3790
  const lines = [
3776
3791
  capabilityMode ? "Executable agents (capabilities):" : "Executable agents:",
3777
3792
  ...formatAgentListSections(agents, providerNameSet, formatLine)
@@ -3786,12 +3801,18 @@ function handleList(params, ctx) {
3786
3801
  restrictedAgents,
3787
3802
  providerNames: providerNameSet,
3788
3803
  externalCliAvailability: externalCliAvailability ?? /* @__PURE__ */ new Map(),
3804
+ unavailableModels,
3789
3805
  restrictedSources
3790
3806
  }));
3791
3807
  }
3808
+ function modelOverrideFile(override) {
3809
+ const scopes = override.fieldScopes?.model;
3810
+ const scope = scopes?.includes("project") ? "project" : scopes?.includes("user") ? "user" : override.scope;
3811
+ return { scope, path: override.paths?.[scope] ?? override.path };
3812
+ }
3792
3813
  function formatModelSource(agent, currentModel) {
3793
3814
  if (agent.override && agent.model !== agent.override.base.model) {
3794
- return `${agent.override.scope} override`;
3815
+ return `${modelOverrideFile(agent.override).scope} override`;
3795
3816
  }
3796
3817
  if (agent.modelSource?.type === "subagents.defaultModel" && agent.model === agent.modelSource.model) {
3797
3818
  return `${agent.modelSource.scope} defaultModel`;
@@ -3836,17 +3857,18 @@ function handleModels(params, ctx) {
3836
3857
  const modelEntries = selectedAgents.flatMap((agent) => requestedAgent ? [{ agent, name: requestedAgent }] : [{ agent, name: agent.name }, ...(agent.aliases ?? []).map((name) => ({ agent, name }))]);
3837
3858
  for (const { agent, name } of modelEntries) {
3838
3859
  const resolvedModel = resolveSubagentModelOverride(agent.model, currentModel, availableModels, agent.modelProvider ?? preferredProvider);
3860
+ const shownModel = resolvedModel === void 0 ? "(unresolved)" : (agent.runner?.type ?? "pi") === "pi" && isUnavailableSubagentModel(agent.model, availableModels, agent.modelProvider ?? preferredProvider) ? `${resolvedModel} ${UNAVAILABLE_MODEL_MARKER}` : resolvedModel;
3839
3861
  const effectiveThinking = resolveEffectiveThinking(resolvedModel, agent.thinking) ?? (agent.thinking === false ? "off" : void 0);
3840
3862
  const source = `${formatModelSource(agent, currentModel)}${agent.disabled ? "; disabled" : ""}${isAgentAllowedByCapabilityCeiling(agent.name, capabilityCeiling) ? "" : "; restricted"}`;
3841
3863
  if (requestedAgent) {
3842
3864
  lines.push(`Agent: ${requestedAgent}`);
3843
3865
  lines.push("Effective model:");
3844
- lines.push(` ${resolvedModel ?? "(unresolved)"}`);
3866
+ lines.push(` ${shownModel}`);
3845
3867
  lines.push(`Source: ${source}`);
3846
3868
  lines.push(`Thinking: ${effectiveThinking ?? "default"}`);
3847
3869
  if (agent.override) {
3848
3870
  lines.push("Override file:");
3849
- lines.push(` ${agent.override.path}`);
3871
+ lines.push(` ${modelOverrideFile(agent.override).path}`);
3850
3872
  }
3851
3873
  if (agent.model && resolvedModel && agent.model !== resolvedModel) {
3852
3874
  lines.push("Requested model setting:");
@@ -3860,12 +3882,12 @@ function handleModels(params, ctx) {
3860
3882
  }
3861
3883
  lines.push(name);
3862
3884
  lines.push(" model:");
3863
- lines.push(` ${resolvedModel ?? "(unresolved)"}`);
3885
+ lines.push(` ${shownModel}`);
3864
3886
  lines.push(` source: ${source}`);
3865
3887
  lines.push(` thinking: ${effectiveThinking ?? "default"}`);
3866
3888
  if (agent.override) {
3867
3889
  lines.push(" override file:");
3868
- lines.push(` ${agent.override.path}`);
3890
+ lines.push(` ${modelOverrideFile(agent.override).path}`);
3869
3891
  }
3870
3892
  if (agent.model && resolvedModel && agent.model !== resolvedModel) {
3871
3893
  lines.push(" requested model setting:");
@@ -4911,6 +4933,9 @@ function normalizePublicSubagentExecution(params, options = {}) {
4911
4933
  return { ok: false, error: "action must be a non-empty management/control action, or omit action and use workflow.", mode: "management" };
4912
4934
  }
4913
4935
  const normalizedAction = typeof action === "string" ? action.trim() : void 0;
4936
+ 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)) {
4937
+ return { ok: false, error: REQUIRE_LAUNCHER_SHAPE_ERROR, mode: normalizedAction !== void 0 ? "management" : "workflow" };
4938
+ }
4914
4939
  if (params.baseRef !== void 0 && normalizedAction !== void 0 && normalizedAction !== "resume" && normalizedAction !== "schedule.create") {
4915
4940
  return { ok: false, error: "baseRef is only supported for child execution, resume, and schedule.create.", mode: "management" };
4916
4941
  }
@@ -5073,49 +5098,10 @@ function createParentWake(pi, now = Date.now) {
5073
5098
  };
5074
5099
  }
5075
5100
 
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
5101
  // src/workflows/workflow-resume-claim.ts
5116
5102
  import { randomUUID as randomUUID3 } from "node:crypto";
5117
- import * as fs10 from "node:fs";
5118
- import * as path9 from "node:path";
5103
+ import * as fs9 from "node:fs";
5104
+ import * as path8 from "node:path";
5119
5105
  var CLAIM_FILE_PATTERN = /^resumed-by\.([1-9][0-9]*)\.json$/;
5120
5106
  var RELEASED_CLAIM_FILE_PATTERN = /^resumed-by\.([1-9][0-9]*)\.json\.released-/;
5121
5107
  var REFUSAL_FILE = "resume-refused.json";
@@ -5124,7 +5110,7 @@ var heldClaimsKey = /* @__PURE__ */ Symbol.for("pi-subagents.workflow-resume-cla
5124
5110
  var heldClaimsGlobal = globalThis;
5125
5111
  var heldClaims = heldClaimsGlobal[heldClaimsKey] ?? (heldClaimsGlobal[heldClaimsKey] = /* @__PURE__ */ new Set());
5126
5112
  function claimFilePath(asyncDir, generation) {
5127
- return path9.join(asyncDir, `resumed-by.${generation}.json`);
5113
+ return path8.join(asyncDir, `resumed-by.${generation}.json`);
5128
5114
  }
5129
5115
  function isClaim(value) {
5130
5116
  if (!isRecordedPid(value) || Array.isArray(value)) return false;
@@ -5135,7 +5121,7 @@ function readTopClaim(asyncDir, retries = 3) {
5135
5121
  let generation = 0;
5136
5122
  let releasedGeneration = 0;
5137
5123
  try {
5138
- for (const name of fs10.readdirSync(asyncDir)) {
5124
+ for (const name of fs9.readdirSync(asyncDir)) {
5139
5125
  const live = CLAIM_FILE_PATTERN.exec(name);
5140
5126
  if (live) generation = Math.max(generation, Number(live[1]));
5141
5127
  const released = RELEASED_CLAIM_FILE_PATTERN.exec(name);
@@ -5148,7 +5134,7 @@ function readTopClaim(asyncDir, retries = 3) {
5148
5134
  const filePath = claimFilePath(asyncDir, generation);
5149
5135
  let text2;
5150
5136
  try {
5151
- text2 = fs10.readFileSync(filePath, "utf-8");
5137
+ text2 = fs9.readFileSync(filePath, "utf-8");
5152
5138
  } catch (error2) {
5153
5139
  if (error2.code === "ENOENT" && retries > 0) return readTopClaim(asyncDir, retries - 1);
5154
5140
  return { kind: "unreadable" };
@@ -5165,7 +5151,7 @@ function readWorkflowResumeClaim(asyncDir) {
5165
5151
  return top.kind === "claim" ? top.claim : void 0;
5166
5152
  }
5167
5153
  function resumedRunStarted(sourceAsyncDir, newRunId) {
5168
- return path9.basename(newRunId) === newRunId && fs10.existsSync(path9.join(path9.dirname(sourceAsyncDir), newRunId, "status.json"));
5154
+ return path8.basename(newRunId) === newRunId && fs9.existsSync(path8.join(path8.dirname(sourceAsyncDir), newRunId, "status.json"));
5169
5155
  }
5170
5156
  function claimantLiveness(filePath, claim, liveness) {
5171
5157
  if (claim.pid === process.pid && claim.bootId === currentBootId() && claim.pidNamespaceScope === currentPidNamespaceScope()) return heldClaims.has(filePath) ? "alive" : "dead";
@@ -5181,14 +5167,14 @@ function workflowResumeClaimState(asyncDir, options = {}) {
5181
5167
  function createClaimFile(filePath, claim) {
5182
5168
  const tempPath = `${filePath}.${process.pid}.${randomUUID3()}.tmp`;
5183
5169
  try {
5184
- fs10.writeFileSync(tempPath, JSON.stringify(claim, null, 2), "utf-8");
5185
- fs10.linkSync(tempPath, filePath);
5170
+ fs9.writeFileSync(tempPath, JSON.stringify(claim, null, 2), "utf-8");
5171
+ fs9.linkSync(tempPath, filePath);
5186
5172
  return true;
5187
5173
  } catch (error2) {
5188
5174
  if (error2.code === "EEXIST") return false;
5189
5175
  throw error2;
5190
5176
  } finally {
5191
- fs10.rmSync(tempPath, { force: true });
5177
+ fs9.rmSync(tempPath, { force: true });
5192
5178
  }
5193
5179
  }
5194
5180
  function claimWorkflowResume(asyncDir, input) {
@@ -5223,18 +5209,18 @@ function releaseWorkflowResumeClaim(asyncDir, newRunId) {
5223
5209
  const top = readTopClaim(asyncDir);
5224
5210
  if (top.kind !== "claim" || top.claim.newRunId !== newRunId || top.claim.pid !== process.pid) return;
5225
5211
  try {
5226
- fs10.renameSync(top.filePath, `${top.filePath}.released-${randomUUID3()}`);
5212
+ fs9.renameSync(top.filePath, `${top.filePath}.released-${randomUUID3()}`);
5227
5213
  } catch (error2) {
5228
5214
  if (error2.code !== "ENOENT") throw error2;
5229
5215
  }
5230
5216
  heldClaims.delete(top.filePath);
5231
5217
  }
5232
5218
  function recordWorkflowResumeRefusal(asyncDir, refusal, now = Date.now()) {
5233
- writeAtomicJson(path9.join(asyncDir, REFUSAL_FILE), { version: 1, ...refusal, refusedAt: now });
5219
+ writeAtomicJson(path8.join(asyncDir, REFUSAL_FILE), { version: 1, ...refusal, refusedAt: now });
5234
5220
  }
5235
5221
  function readWorkflowResumeRefusal(asyncDir) {
5236
5222
  try {
5237
- const value = JSON.parse(fs10.readFileSync(path9.join(asyncDir, REFUSAL_FILE), "utf-8"));
5223
+ const value = JSON.parse(fs9.readFileSync(path8.join(asyncDir, REFUSAL_FILE), "utf-8"));
5238
5224
  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
5225
  } catch {
5240
5226
  return void 0;
@@ -5250,7 +5236,7 @@ function refusalSentence(reason, byHand) {
5250
5236
  return `${reason.replace(/\.$/, "")}.${byHand ? ` ${byHand}` : ""}`;
5251
5237
  }
5252
5238
  function hasWorkflowResumeRefusal(asyncDir) {
5253
- return fs10.existsSync(path9.join(asyncDir, REFUSAL_FILE));
5239
+ return fs9.existsSync(path8.join(asyncDir, REFUSAL_FILE));
5254
5240
  }
5255
5241
  var RESUMED_AS = { auto: "Auto-resumed as", manual: "Resumed as", reuse: "Relaunched as" };
5256
5242
  function describeWorkflowResume(asyncDir, runId) {
@@ -5260,8 +5246,8 @@ function describeWorkflowResume(asyncDir, runId) {
5260
5246
  return `Not auto-resumed: ${refusalSentence(refusal.reason, refusal.byHand)}`;
5261
5247
  }
5262
5248
  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);
5249
+ const launch = readWorkflowLaunchRecord(path8.dirname(asyncDir), runId);
5250
+ return launch.ok && (launch.record.source === "script" || launch.record.source === "resource") ? resumeByHandText(runId) : relaunchByHandText(runId);
5265
5251
  }
5266
5252
 
5267
5253
  // src/runs/background/notify.ts
@@ -6236,7 +6222,6 @@ var DEFAULT_SOURCE = "pi-subagents:herdr";
6236
6222
  var DEFAULT_TTL_MS = 12e4;
6237
6223
  var DEFAULT_REFRESH_MS = 45e3;
6238
6224
  var MAX_TASK_LABEL_CHARS = 80;
6239
- var MAX_TITLE_TASK_CHARS = 42;
6240
6225
  var MAX_WORKFLOW_LABEL_NODES = 128;
6241
6226
  var MAX_WORKFLOW_LABEL_DEPTH = 8;
6242
6227
  var metadataReportSeq = Date.now() * 1e3;
@@ -6247,11 +6232,11 @@ function nextMetadataReportSeq() {
6247
6232
  function isRecord(value) {
6248
6233
  return typeof value === "object" && value !== null && !Array.isArray(value);
6249
6234
  }
6250
- function boundedTaskLabel(value, maxChars = MAX_TASK_LABEL_CHARS) {
6235
+ function boundedTaskLabel(value) {
6251
6236
  if (typeof value !== "string") return void 0;
6252
6237
  const normalized = sanitizeDisplayText(value).trim();
6253
6238
  if (!normalized) return void 0;
6254
- return previewDisplayText(normalized, maxChars);
6239
+ return previewDisplayText(normalized, MAX_TASK_LABEL_CHARS);
6255
6240
  }
6256
6241
  function workflowTaskLabel(data) {
6257
6242
  const explicit = boundedTaskLabel(data.taskLabel);
@@ -6332,11 +6317,7 @@ function registerHerdrStatusBridge(options) {
6332
6317
  };
6333
6318
  const titleSuffix = () => {
6334
6319
  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" : ""}`;
6320
+ return `\u23F3${activeSubagentCount()}${attentionRuns.size > 0 ? "\u26A0" : ""}`;
6340
6321
  };
6341
6322
  const enqueue = (args) => {
6342
6323
  pendingReport = args;
@@ -6592,8 +6573,8 @@ function registerPiWebSessionLiveness(registration) {
6592
6573
  }
6593
6574
 
6594
6575
  // src/runs/background/wait-subscriptions.ts
6595
- import * as fs11 from "node:fs";
6596
- import * as path10 from "node:path";
6576
+ import * as fs10 from "node:fs";
6577
+ import * as path9 from "node:path";
6597
6578
  import { randomUUID as randomUUID4 } from "node:crypto";
6598
6579
  var SUBSCRIPTION_VERSION = 1;
6599
6580
  var STATUS_OUTCOMES = /* @__PURE__ */ new Set(["timed out", "could not be reconciled", "needs attention", "reconciliation failed"]);
@@ -6613,7 +6594,7 @@ function needsAttention(run) {
6613
6594
  return run.activityState === "needs_attention" || run.steps.some((step) => step.activityState === "needs_attention");
6614
6595
  }
6615
6596
  function subscriptionFile(dir, token) {
6616
- return path10.join(dir, `${token}.json`);
6597
+ return path9.join(dir, `${token}.json`);
6617
6598
  }
6618
6599
  function formatWaitSubscriptions(state, now = Date.now()) {
6619
6600
  const subscriptions = [...state.waitSubscriptions?.values() ?? []].sort((left, right) => left.createdAt - right.createdAt);
@@ -6627,7 +6608,7 @@ function formatWaitSubscriptions(state, now = Date.now()) {
6627
6608
  function createWaitSubscriptionManager(pi, state, options = {}) {
6628
6609
  const asyncDirRoot = options.asyncDirRoot ?? DIRS.async;
6629
6610
  const resultsDir = options.resultsDir ?? DIRS.results;
6630
- const subscriptionsDir = options.subscriptionsDir ?? path10.join(path10.dirname(asyncDirRoot), "wait-subscriptions");
6611
+ const subscriptionsDir = options.subscriptionsDir ?? path9.join(path9.dirname(asyncDirRoot), "wait-subscriptions");
6631
6612
  const now = options.now ?? Date.now;
6632
6613
  const subscriptions = state.waitSubscriptions ?? /* @__PURE__ */ new Map();
6633
6614
  state.waitSubscriptions = subscriptions;
@@ -6641,16 +6622,16 @@ function createWaitSubscriptionManager(pi, state, options = {}) {
6641
6622
  lastForeignSweepAt = sweptAt;
6642
6623
  let files;
6643
6624
  try {
6644
- files = fs11.readdirSync(subscriptionsDir).filter((file) => file.endsWith(".json"));
6625
+ files = fs10.readdirSync(subscriptionsDir).filter((file) => file.endsWith(".json"));
6645
6626
  } catch (error2) {
6646
6627
  if (!isNotFound(error2)) console.error(`Failed to scan wait subscriptions in '${subscriptionsDir}':`, error2);
6647
6628
  return;
6648
6629
  }
6649
6630
  for (const file of files) {
6650
- const filePath = path10.join(subscriptionsDir, file);
6631
+ const filePath = path9.join(subscriptionsDir, file);
6651
6632
  let record;
6652
6633
  try {
6653
- record = parseRecord(JSON.parse(fs11.readFileSync(filePath, "utf-8")));
6634
+ record = parseRecord(JSON.parse(fs10.readFileSync(filePath, "utf-8")));
6654
6635
  } catch (error2) {
6655
6636
  console.error(`Ignoring invalid wait subscription '${filePath}':`, error2);
6656
6637
  continue;
@@ -6659,7 +6640,7 @@ function createWaitSubscriptionManager(pi, state, options = {}) {
6659
6640
  if (record.sessionId === state.currentSessionId) continue;
6660
6641
  if (sweptAt < record.expiresAt + FOREIGN_SWEEP_GRACE_MS) continue;
6661
6642
  try {
6662
- fs11.unlinkSync(filePath);
6643
+ fs10.unlinkSync(filePath);
6663
6644
  } catch (error2) {
6664
6645
  if (!isNotFound(error2)) console.error(`Failed to remove expired wait subscription '${filePath}':`, error2);
6665
6646
  }
@@ -6667,7 +6648,7 @@ function createWaitSubscriptionManager(pi, state, options = {}) {
6667
6648
  };
6668
6649
  const remove = (record) => {
6669
6650
  try {
6670
- fs11.unlinkSync(subscriptionFile(subscriptionsDir, record.token));
6651
+ fs10.unlinkSync(subscriptionFile(subscriptionsDir, record.token));
6671
6652
  } catch (error2) {
6672
6653
  if (!isNotFound(error2)) throw error2;
6673
6654
  }
@@ -6796,7 +6777,7 @@ Parent action: ${STATUS_OUTCOMES.has(outcome) ? STATUS_ACTION : COMPLETION_ACTIO
6796
6777
  createdAt,
6797
6778
  expiresAt: createdAt + input.timeoutMs
6798
6779
  };
6799
- fs11.mkdirSync(subscriptionsDir, { recursive: true });
6780
+ fs10.mkdirSync(subscriptionsDir, { recursive: true });
6800
6781
  writeAtomicJson(subscriptionFile(subscriptionsDir, record.token), record);
6801
6782
  subscriptions.set(record.token, record);
6802
6783
  return record;
@@ -6808,21 +6789,21 @@ Parent action: ${STATUS_OUTCOMES.has(outcome) ? STATUS_ACTION : COMPLETION_ACTIO
6808
6789
  if (!state.currentSessionId) return;
6809
6790
  let files;
6810
6791
  try {
6811
- files = fs11.readdirSync(subscriptionsDir).filter((file) => file.endsWith(".json"));
6792
+ files = fs10.readdirSync(subscriptionsDir).filter((file) => file.endsWith(".json"));
6812
6793
  } catch (error2) {
6813
6794
  if (isNotFound(error2)) return;
6814
6795
  throw error2;
6815
6796
  }
6816
6797
  for (const file of files) {
6817
6798
  try {
6818
- const record = parseRecord(JSON.parse(fs11.readFileSync(path10.join(subscriptionsDir, file), "utf-8")));
6799
+ const record = parseRecord(JSON.parse(fs10.readFileSync(path9.join(subscriptionsDir, file), "utf-8")));
6819
6800
  if (!record || file !== `${record.token}.json`) continue;
6820
6801
  if (record.sessionId === state.currentSessionId) {
6821
6802
  subscriptions.set(record.token, record);
6822
6803
  if (record.targetKind === "foreground" && !state.foregroundRuns?.has(record.runId)) unresolvedRestoredForegroundTokens.add(record.token);
6823
6804
  }
6824
6805
  } catch (error2) {
6825
- console.error(`Ignoring invalid wait subscription '${path10.join(subscriptionsDir, file)}':`, error2);
6806
+ console.error(`Ignoring invalid wait subscription '${path9.join(subscriptionsDir, file)}':`, error2);
6826
6807
  }
6827
6808
  }
6828
6809
  reconcile();
@@ -6845,25 +6826,26 @@ Parent action: ${STATUS_OUTCOMES.has(outcome) ? STATUS_ACTION : COMPLETION_ACTIO
6845
6826
  }
6846
6827
 
6847
6828
  // src/runs/shared/child-session.ts
6848
- import * as fs14 from "node:fs";
6849
- import * as path13 from "node:path";
6829
+ import * as fs13 from "node:fs";
6830
+ import * as path12 from "node:path";
6850
6831
  import { pathToFileURL } from "node:url";
6832
+ import { cleanupSessionResources, registerSessionResourceCleanup } from "@earendil-works/pi-ai";
6851
6833
 
6852
6834
  // src/runs/shared/child-commands.ts
6853
6835
  import { randomUUID as randomUUID5 } from "node:crypto";
6854
- import * as fs12 from "node:fs";
6855
- import * as path11 from "node:path";
6836
+ import * as fs11 from "node:fs";
6837
+ import * as path10 from "node:path";
6856
6838
  import { Type } from "typebox";
6857
6839
  var CHILD_COMMAND_TOOL = "subagent_command";
6858
6840
  var writeAtomicJson2 = createAtomicJsonWriter({ mode: 384 });
6859
6841
  var MAX_OUTPUT_BYTES = 8 * 1024;
6860
6842
  var RECENT_COMMANDS = 20;
6861
6843
  function childCommandStatePath(channelDir) {
6862
- return path11.join(channelDir, "commands.json");
6844
+ return path10.join(channelDir, "commands.json");
6863
6845
  }
6864
6846
  function readChildCommandState(channelDir) {
6865
6847
  try {
6866
- return JSON.parse(fs12.readFileSync(childCommandStatePath(channelDir), "utf8"));
6848
+ return JSON.parse(fs11.readFileSync(childCommandStatePath(channelDir), "utf8"));
6867
6849
  } catch (error2) {
6868
6850
  if (error2.code === "ENOENT") return void 0;
6869
6851
  throw error2;
@@ -6971,7 +6953,15 @@ Optional yieldTimeMs returns a command handle without stopping execution. Use su
6971
6953
  persist();
6972
6954
  startInbox();
6973
6955
  let timer;
6974
- if (typeof yieldTimeMs === "number") timer = setTimeout(() => operate("yield", toolCallId), yieldTimeMs);
6956
+ let yieldSaveError;
6957
+ if (typeof yieldTimeMs === "number") timer = setTimeout(() => {
6958
+ if (closed) return;
6959
+ try {
6960
+ operate("yield", toolCallId);
6961
+ } catch (error2) {
6962
+ yieldSaveError = error2;
6963
+ }
6964
+ }, yieldTimeMs);
6975
6965
  const execution = Promise.resolve().then(() => tool.execute(toolCallId, args, commandSignal, (update) => {
6976
6966
  job.snapshot.output = text(update);
6977
6967
  if (job.snapshot.state === "running") onUpdate?.(update);
@@ -6995,7 +6985,9 @@ Optional yieldTimeMs returns a command handle without stopping execution. Use su
6995
6985
  });
6996
6986
  const result5 = await Promise.race([execution.then((value) => ({ value })), yielded.then(() => void 0)]);
6997
6987
  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.
6988
+ const saveWarning = yieldSaveError === void 0 ? "" : `
6989
+ The command's saved state is out of date because it could not be saved: ${yieldSaveError instanceof Error ? yieldSaveError.message : String(yieldSaveError)}`;
6990
+ 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
6991
  ${job.snapshot.output}` }], details: { command: { ...job.snapshot } } };
7000
6992
  }
7001
6993
  };
@@ -7035,7 +7027,7 @@ async function waitForCommand(settled, waitMs, signal) {
7035
7027
  }
7036
7028
  }
7037
7029
  function commandReplyPath(channelDir, id) {
7038
- return path11.join(channelDir, "command-replies", `${id}.json`);
7030
+ return path10.join(channelDir, "command-replies", `${id}.json`);
7039
7031
  }
7040
7032
  async function controlChildCommand(channelDir, operation, toolCallId, signal) {
7041
7033
  const current = readChildCommandState(channelDir);
@@ -7059,7 +7051,7 @@ async function controlChildCommand(channelDir, operation, toolCallId, signal) {
7059
7051
  while (Date.now() < deadlineAt) {
7060
7052
  if (signal?.aborted) throw new Error("Command control wait aborted; delivery may still be pending.");
7061
7053
  try {
7062
- const reply = JSON.parse(fs12.readFileSync(replyPath, "utf8"));
7054
+ const reply = JSON.parse(fs11.readFileSync(replyPath, "utf8"));
7063
7055
  if (reply.error) throw new Error(reply.error);
7064
7056
  if (reply.state) return reply.state;
7065
7057
  } catch (error2) {
@@ -7069,7 +7061,7 @@ async function controlChildCommand(channelDir, operation, toolCallId, signal) {
7069
7061
  }
7070
7062
  throw new Error("Command control acknowledgement timed out. Inspect command status; cancellation is not confirmed.");
7071
7063
  } finally {
7072
- fs12.rmSync(replyPath, { force: true });
7064
+ fs11.rmSync(replyPath, { force: true });
7073
7065
  }
7074
7066
  }
7075
7067
 
@@ -7093,8 +7085,8 @@ function pinChildCacheRetention(agent, env) {
7093
7085
  }
7094
7086
 
7095
7087
  // src/runs/background/runner-aliases.ts
7096
- import * as fs13 from "node:fs";
7097
- import * as path12 from "node:path";
7088
+ import * as fs12 from "node:fs";
7089
+ import * as path11 from "node:path";
7098
7090
  var JITI_ALIAS_ENV = "JITI_ALIAS";
7099
7091
  var HOST_PEER_ALIASES = [
7100
7092
  { specifier: "@earendil-works/pi-coding-agent", pkg: "@earendil-works/pi-coding-agent", subpath: "." },
@@ -7117,7 +7109,7 @@ var CHORD_PEER_ALIASES = [
7117
7109
  ];
7118
7110
  function readManifest(packageDir) {
7119
7111
  try {
7120
- return JSON.parse(fs13.readFileSync(path12.join(packageDir, "package.json"), "utf-8"));
7112
+ return JSON.parse(fs12.readFileSync(path11.join(packageDir, "package.json"), "utf-8"));
7121
7113
  } catch {
7122
7114
  return void 0;
7123
7115
  }
@@ -7154,7 +7146,7 @@ function resolvePackageSubpath(packageDir, subpath) {
7154
7146
  const map = typeof exportsField === "string" || Array.isArray(exportsField) || exportsField && typeof exportsField === "object" && !Object.keys(exportsField).some((key) => key.startsWith(".")) ? { ".": exportsField } : exportsField;
7155
7147
  if (subpath in map) {
7156
7148
  const exact = exportTarget(map[subpath]);
7157
- return typeof exact === "string" ? path12.resolve(packageDir, exact) : void 0;
7149
+ return typeof exact === "string" ? path11.resolve(packageDir, exact) : void 0;
7158
7150
  }
7159
7151
  let best;
7160
7152
  for (const [pattern, entry] of Object.entries(map)) {
@@ -7169,23 +7161,23 @@ function resolvePackageSubpath(packageDir, subpath) {
7169
7161
  const target = exportTarget(best.entry);
7170
7162
  if (typeof target !== "string") return void 0;
7171
7163
  const wildcard = subpath.slice(best.prefix.length, subpath.length - best.suffix.length);
7172
- return path12.resolve(packageDir, target.replaceAll("*", () => wildcard));
7164
+ return path11.resolve(packageDir, target.replaceAll("*", () => wildcard));
7173
7165
  }
7174
7166
  if (subpath !== ".") return void 0;
7175
- return path12.resolve(packageDir, typeof manifest.main === "string" && manifest.main.trim() ? manifest.main : "index.js");
7167
+ return path11.resolve(packageDir, typeof manifest.main === "string" && manifest.main.trim() ? manifest.main : "index.js");
7176
7168
  }
7177
7169
  function findPeerPackageDir(piPackageRoot, pkg, hostName) {
7178
7170
  if (hostName === pkg) return piPackageRoot;
7179
- const candidates = [path12.join(piPackageRoot, "node_modules", pkg)];
7171
+ const candidates = [path11.join(piPackageRoot, "node_modules", pkg)];
7180
7172
  let dir = piPackageRoot;
7181
7173
  for (; ; ) {
7182
- const parent = path12.dirname(dir);
7174
+ const parent = path11.dirname(dir);
7183
7175
  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));
7176
+ if (path11.basename(parent) === "node_modules" || path11.basename(path11.dirname(parent)) === "node_modules") {
7177
+ const modulesRoot = path11.basename(parent) === "node_modules" ? parent : path11.dirname(parent);
7178
+ candidates.push(path11.join(modulesRoot, pkg));
7187
7179
  }
7188
- candidates.push(path12.join(parent, "node_modules", pkg));
7180
+ candidates.push(path11.join(parent, "node_modules", pkg));
7189
7181
  dir = parent;
7190
7182
  }
7191
7183
  return candidates.find((candidate) => readManifest(candidate)?.name === pkg);
@@ -7202,7 +7194,7 @@ function resolveHostPeerAliases(piPackageRoot) {
7202
7194
  const packageDir = findPeerPackageDir(piPackageRoot, pkg, hostManifest?.name);
7203
7195
  const target = packageDir ? resolvePackageSubpath(packageDir, subpath) : void 0;
7204
7196
  if (optional && packageDir && target === void 0) continue;
7205
- if (target && fs13.existsSync(target)) aliases[specifier] = fs13.realpathSync(target);
7197
+ if (target && fs12.existsSync(target)) aliases[specifier] = fs12.realpathSync(target);
7206
7198
  else if (pkg !== CHORD_PACKAGE || chordRequired) missing.push(specifier);
7207
7199
  }
7208
7200
  return { aliases, missing };
@@ -7252,9 +7244,9 @@ var CHILD_PROMPT_RUNTIME_EXTENSION_PATH = "<inline:pi-subagents:prompt-runtime>"
7252
7244
  var CHILD_PROMPT_BOUNDARY_EXTENSION_PATH = "<inline:pi-subagents:prompt-boundary>";
7253
7245
  var PI_UNICODE_SPACES = new RegExp("[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]", "g");
7254
7246
  function childExtensionFileIdentity(extensionPath) {
7255
- if (!path13.isAbsolute(extensionPath)) return void 0;
7247
+ if (!path12.isAbsolute(extensionPath)) return void 0;
7256
7248
  try {
7257
- const stat = fs14.statSync(extensionPath, { bigint: true });
7249
+ const stat = fs13.statSync(extensionPath, { bigint: true });
7258
7250
  return stat.isFile() ? `${stat.dev}:${stat.ino}` : void 0;
7259
7251
  } catch {
7260
7252
  return void 0;
@@ -7303,6 +7295,18 @@ function prioritizeChildCommandRuntime(result5) {
7303
7295
  extensions.unshift(commands);
7304
7296
  return { ...result5, extensions };
7305
7297
  }
7298
+ function disposeChildSession(session) {
7299
+ let released = false;
7300
+ const unregister = registerSessionResourceCleanup((sessionId) => {
7301
+ if (sessionId === session.sessionId) released = true;
7302
+ });
7303
+ try {
7304
+ session.dispose();
7305
+ } finally {
7306
+ unregister();
7307
+ if (!released) cleanupSessionResources(session.sessionId);
7308
+ }
7309
+ }
7306
7310
  var loading = Promise.resolve();
7307
7311
  function resetExtensionCacheOnReload(loader) {
7308
7312
  if (!("loaded" in loader)) return false;
@@ -7433,14 +7437,14 @@ async function loadHostPiCodingAgent() {
7433
7437
  const overrideRoot = process.env[PI_CODING_AGENT_PACKAGE_ROOT_ENV]?.trim() || void 0;
7434
7438
  const root = resolveHostPiPackageRoot();
7435
7439
  if (root) {
7436
- const entry = fs14.realpathSync(resolveHostPackageEntry(root, root === overrideRoot ? overrideRoot : void 0));
7440
+ const entry = fs13.realpathSync(resolveHostPackageEntry(root, root === overrideRoot ? overrideRoot : void 0));
7437
7441
  return import(pathToFileURL(entry).href);
7438
7442
  }
7439
7443
  return import(PI_CODING_AGENT_PACKAGE);
7440
7444
  }
7441
7445
  function resolveHostPackageEntry(root, overrideRoot) {
7442
- const packageJson = path13.join(root, "package.json");
7443
- const source = fs14.readFileSync(packageJson, "utf8");
7446
+ const packageJson = path12.join(root, "package.json");
7447
+ const source = fs13.readFileSync(packageJson, "utf8");
7444
7448
  let parsed;
7445
7449
  try {
7446
7450
  parsed = JSON.parse(source);
@@ -7541,7 +7545,7 @@ function createDefaultChildSessionFactory(options = {}) {
7541
7545
  } catch (error2) {
7542
7546
  launch.onExtensionError?.({ extensionPath: "<session>", event: "session_shutdown", error: error2 });
7543
7547
  } finally {
7544
- session2.dispose();
7548
+ disposeChildSession(session2);
7545
7549
  }
7546
7550
  };
7547
7551
  let inheritedProviders = /* @__PURE__ */ new Set();
@@ -7567,7 +7571,7 @@ function createDefaultChildSessionFactory(options = {}) {
7567
7571
  }
7568
7572
  }
7569
7573
  const newSessionOptions = launch.parentSessionFile ? { parentSession: launch.parentSessionFile } : void 0;
7570
- const newSessionFile = launch.storage.kind === "file" && !fs14.existsSync(launch.storage.sessionFile);
7574
+ const newSessionFile = launch.storage.kind === "file" && !fs13.existsSync(launch.storage.sessionFile);
7571
7575
  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
7576
  const header = newSessionFile && launch.parentSessionFile ? sessionManager.getHeader() : null;
7573
7577
  if (header) header.parentSession = launch.parentSessionFile;
@@ -7598,7 +7602,7 @@ function createDefaultChildSessionFactory(options = {}) {
7598
7602
  }
7599
7603
  });
7600
7604
  } catch (error2) {
7601
- session2.dispose();
7605
+ disposeChildSession(session2);
7602
7606
  throw error2;
7603
7607
  } finally {
7604
7608
  binding = false;
@@ -7683,6 +7687,9 @@ function createDefaultChildSessionFactory(options = {}) {
7683
7687
  get inheritedProvider() {
7684
7688
  return session.model && inheritedProviders.has(session.model.provider) ? session.model.provider : void 0;
7685
7689
  },
7690
+ get claimedProvider() {
7691
+ return session.model && !inheritedProviders.has(session.model.provider) && modelRuntime.getRegisteredProviderIds().includes(session.model.provider) ? session.model.provider : void 0;
7692
+ },
7686
7693
  get virtualModelId() {
7687
7694
  return session.model?.api === "pi-virtual" ? `${session.model.provider}/${session.model.id}` : void 0;
7688
7695
  },
@@ -7718,7 +7725,7 @@ function childSessionFactory() {
7718
7725
  }
7719
7726
  function createLazyPlacementFactory(local) {
7720
7727
  let placed;
7721
- const factory = async () => placed ??= (await import("./chunk-C7JMPU5F.js")).createPlacementAwareChildSessionFactory(local);
7728
+ const factory = async () => placed ??= (await import("./chunk-JO67XSKD.js")).createPlacementAwareChildSessionFactory(local);
7722
7729
  return {
7723
7730
  async create(launch) {
7724
7731
  return launch.machine ? (await factory()).create(launch) : local.create(launch);
@@ -7740,8 +7747,8 @@ async function disposeChildSessions() {
7740
7747
 
7741
7748
  // src/workflows/workflow-reuse.ts
7742
7749
  import { createHash as createHash3 } from "node:crypto";
7743
- import * as fs15 from "node:fs";
7744
- import * as path14 from "node:path";
7750
+ import * as fs14 from "node:fs";
7751
+ import * as path13 from "node:path";
7745
7752
  var WORKFLOW_CHILD_JOURNAL_FILE = "workflow-children.jsonl";
7746
7753
  var WORKFLOW_RUNTIME_REPLACED_STOP_NOTICE = "Async children that were still running keep running, and finished children are kept.";
7747
7754
  function runtimeReplacedAbortReason() {
@@ -7760,9 +7767,9 @@ function workflowChildFingerprint(params) {
7760
7767
  return sha256(workflowRunParamsFingerprint(params));
7761
7768
  }
7762
7769
  function appendWorkflowChildJournal(workflowAsyncDir, record) {
7763
- const journalPath = path14.join(workflowAsyncDir, WORKFLOW_CHILD_JOURNAL_FILE);
7770
+ const journalPath = path13.join(workflowAsyncDir, WORKFLOW_CHILD_JOURNAL_FILE);
7764
7771
  try {
7765
- fs15.appendFileSync(journalPath, `${JSON.stringify(record)}
7772
+ fs14.appendFileSync(journalPath, `${JSON.stringify(record)}
7766
7773
  `, "utf-8");
7767
7774
  } catch (error2) {
7768
7775
  console.error(`Failed to append workflow child journal '${journalPath}':`, error2);
@@ -7772,7 +7779,7 @@ function readWorkflowChildJournal(runId, workflowAsyncDir) {
7772
7779
  const source = { runId, started: /* @__PURE__ */ new Map(), settled: /* @__PURE__ */ new Map() };
7773
7780
  let text2 = "";
7774
7781
  try {
7775
- text2 = fs15.readFileSync(path14.join(workflowAsyncDir, WORKFLOW_CHILD_JOURNAL_FILE), "utf-8");
7782
+ text2 = fs14.readFileSync(path13.join(workflowAsyncDir, WORKFLOW_CHILD_JOURNAL_FILE), "utf-8");
7776
7783
  } catch {
7777
7784
  return source;
7778
7785
  }
@@ -7794,12 +7801,12 @@ function readWorkflowChildJournal(runId, workflowAsyncDir) {
7794
7801
  }
7795
7802
  var WORKFLOW_REUSE_CHAIN_MAX_LINKS = 16;
7796
7803
  function readWorkflowReuseChain(asyncDirRoot, headRunId, headStatus) {
7797
- const source = readWorkflowChildJournal(headRunId, path14.join(asyncDirRoot, headRunId));
7804
+ const source = readWorkflowChildJournal(headRunId, path13.join(asyncDirRoot, headRunId));
7798
7805
  const visited = /* @__PURE__ */ new Set([headRunId]);
7799
7806
  let next = headStatus.workflow?.reusedFrom;
7800
7807
  for (let links = 0; isRunId(next) && links < WORKFLOW_REUSE_CHAIN_MAX_LINKS && !visited.has(next); links++) {
7801
7808
  visited.add(next);
7802
- const asyncDir = path14.join(asyncDirRoot, next);
7809
+ const asyncDir = path13.join(asyncDirRoot, next);
7803
7810
  let status;
7804
7811
  try {
7805
7812
  status = readStatus(asyncDir);
@@ -7838,7 +7845,7 @@ function findWorkflowReuseSource(asyncDirRoot, sessionId, scriptDigest, argsDige
7838
7845
  return void 0;
7839
7846
  }
7840
7847
  for (const runId of runIds) {
7841
- const asyncDir = path14.join(asyncDirRoot, runId);
7848
+ const asyncDir = path13.join(asyncDirRoot, runId);
7842
7849
  let status;
7843
7850
  try {
7844
7851
  status = readStatus(asyncDir);
@@ -7854,14 +7861,14 @@ function findWorkflowReuseSource(asyncDirRoot, sessionId, scriptDigest, argsDige
7854
7861
  }
7855
7862
  function readNamedWorkflowReuseSource(asyncDirRoot, runId, scriptDigest, cwd, claimOwnerRunId) {
7856
7863
  const runName = isRunId(runId);
7857
- if (runName) reconcileAsyncRun(path14.join(asyncDirRoot, runId));
7858
- const status = runName ? readStatus(path14.join(asyncDirRoot, runId)) : null;
7864
+ if (runName) reconcileAsyncRun(path13.join(asyncDirRoot, runId));
7865
+ const status = runName ? readStatus(path13.join(asyncDirRoot, runId)) : null;
7859
7866
  if (!status) throw new Error(`options.reuseFrom: workflow run '${runId}' was not found.`);
7860
7867
  if (status.mode !== "workflow") throw new Error(`options.reuseFrom: run '${runId}' is not a workflow run.`);
7861
7868
  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.`);
7862
7869
  if (status.workflow.scriptDigest !== scriptDigest) throw new Error(`options.reuseFrom: workflow run '${runId}' ran a different workflow script.`);
7863
7870
  if (status.cwd !== cwd) throw new Error(`options.reuseFrom: workflow run '${runId}' ran in '${status.cwd}', not '${cwd}'.`);
7864
- assertWorkflowRunNotClaimed(path14.join(asyncDirRoot, runId), runId, true, claimOwnerRunId);
7871
+ assertWorkflowRunNotClaimed(path13.join(asyncDirRoot, runId), runId, true, claimOwnerRunId);
7865
7872
  return readWorkflowReuseChain(asyncDirRoot, runId, status);
7866
7873
  }
7867
7874
  function matchWorkflowReuse(source, key, fingerprint) {
@@ -7873,10 +7880,10 @@ function matchWorkflowReuse(source, key, fingerprint) {
7873
7880
 
7874
7881
  // src/workflows/workflow-resume.ts
7875
7882
  import { randomUUID as randomUUID6 } from "node:crypto";
7876
- import * as path15 from "node:path";
7883
+ import * as path14 from "node:path";
7877
7884
  var MAX_WORKFLOW_RESUME_ATTEMPTS = 3;
7878
7885
  function workflowResumeRefusal(code, reason, runId) {
7879
- 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) : "";
7886
+ 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) : "";
7880
7887
  return { code, reason, byHand };
7881
7888
  }
7882
7889
  function manualWorkflowResumeRefusalText(runId, refusal) {
@@ -7889,7 +7896,7 @@ function workflowResumeTargetId(asyncDirRoot, params) {
7889
7896
  if (!isRunId(id)) return void 0;
7890
7897
  let status;
7891
7898
  try {
7892
- status = readStatus(path15.join(asyncDirRoot, id));
7899
+ status = readStatus(path14.join(asyncDirRoot, id));
7893
7900
  } catch {
7894
7901
  return void 0;
7895
7902
  }
@@ -7898,18 +7905,18 @@ function workflowResumeTargetId(asyncDirRoot, params) {
7898
7905
  function prepareWorkflowResume(input) {
7899
7906
  const { asyncDirRoot, sourceRunId, trigger } = input;
7900
7907
  const refuse = (code, reason) => ({ ok: false, ...workflowResumeRefusal(code, reason, sourceRunId) });
7901
- const sourceAsyncDir = path15.join(asyncDirRoot, sourceRunId);
7902
- const stored = readStatus(sourceAsyncDir);
7903
- if (stored && !ownsRun(input.currentSessionId, stored.sessionId)) return refuse("not-owned", "it was started in another session; reopen that session to resume it");
7908
+ const sourceAsyncDir = path14.join(asyncDirRoot, sourceRunId);
7909
+ const read = readWorkflowLaunchRecord(asyncDirRoot, sourceRunId);
7910
+ 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}`);
7911
+ const record = read.record;
7912
+ if (!ownsRun(input.currentSessionId, record.sessionId)) return refuse("not-owned", "it was started in another session; reopen that session to resume it");
7904
7913
  if (trigger === "manual") reconcileAsyncRun(sourceAsyncDir);
7905
7914
  const status = readStatus(sourceAsyncDir);
7906
7915
  if (!status || status.mode !== "workflow" || !isReusableWorkflowStopCause(status.workflow?.stopCause)) return refuse("not-interrupted", "not interrupted; pass message to revive one of its children");
7907
7916
  const attempt = (status.workflow?.resumeOrigin?.attempt ?? 0) + (status.workflow?.stopCause === WORKFLOW_STOP_CAUSE_OWNER_EXITED ? 1 : 0);
7908
7917
  if (trigger === "auto" && attempt > MAX_WORKFLOW_RESUME_ATTEMPTS) return refuse("attempts", `${MAX_WORKFLOW_RESUME_ATTEMPTS} resumes already followed Pi exits`);
7909
- const read = readWorkflowLaunchRecord(sourceAsyncDir);
7910
- 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}`);
7911
- const record = read.record;
7912
7918
  if (record.source === "structured") return refuse("structured", "launched from tasks/chain");
7919
+ if (record.source === "internal") return refuse("internal", "launched by a schedule or prompt-template delegation");
7913
7920
  if (record.source === "script" && (typeof record.params.workflowScript !== "string" || workflowScriptDigest(record.params.workflowScript) !== record.scriptDigest)) {
7914
7921
  return refuse("launch-invalid", "launch.json is invalid: its script does not match its scriptDigest");
7915
7922
  }
@@ -7931,7 +7938,7 @@ function prepareWorkflowResume(input) {
7931
7938
  ...record.params,
7932
7939
  async: true,
7933
7940
  reuseFrom: sourceRunId,
7934
- ...status.admissionCapabilityCeiling ? { capabilityCeiling: status.admissionCapabilityCeiling } : {}
7941
+ ...record.admissionCapabilityCeiling ? { capabilityCeiling: record.admissionCapabilityCeiling } : {}
7935
7942
  },
7936
7943
  expectedScriptDigest: record.scriptDigest,
7937
7944
  resumeOrigin: { sourceRunId, attempt }
@@ -7986,7 +7993,8 @@ function flattenSubagentToolOptions(params, disabled) {
7986
7993
  }
7987
7994
 
7988
7995
  // src/runs/background/retained-children.ts
7989
- import * as fs16 from "node:fs";
7996
+ import * as fs15 from "node:fs";
7997
+ import * as path15 from "node:path";
7990
7998
  var MAX_RETAINED_CHILDREN = 10;
7991
7999
  var MAX_RETAINED_CHILD_CANDIDATES = 100;
7992
8000
  var MAX_TASK_SUMMARY_LENGTH = 120;
@@ -8000,7 +8008,7 @@ function retainedSessionFile(sessionFile) {
8000
8008
  if (!sessionFile) return { state: "not-resumable", reason: "no persisted session file" };
8001
8009
  if (!sessionFile.endsWith(".jsonl")) return { state: "not-resumable", reason: "persisted session file is not a .jsonl file" };
8002
8010
  try {
8003
- const stat = fs16.lstatSync(sessionFile);
8011
+ const stat = fs15.lstatSync(sessionFile);
8004
8012
  if (!stat.isFile() || stat.isSymbolicLink()) return { state: "not-resumable", reason: "persisted session file is not a regular file" };
8005
8013
  return { state: "resumable", sessionPath: sessionFile };
8006
8014
  } catch (error2) {
@@ -8017,7 +8025,7 @@ function childResumability(run, step) {
8017
8025
  if (session.state === "not-resumable") return session;
8018
8026
  let recoveryDescriptor;
8019
8027
  try {
8020
- recoveryDescriptor = readAsyncRecoveryDescriptor(run.asyncDir);
8028
+ recoveryDescriptor = readAsyncRecoveryDescriptor(path15.dirname(run.asyncDir), path15.basename(run.asyncDir));
8021
8029
  if (!recoveryDescriptor) return { state: "not-resumable", reason: "missing recovery descriptor" };
8022
8030
  if (recoveryDescriptor.sourceRunId !== run.id) return { state: "not-resumable", reason: `recovery descriptor belongs to run ${recoveryDescriptor.sourceRunId}` };
8023
8031
  if (recoveryDescriptor.agent !== step.agent) return { state: "not-resumable", reason: `recovery descriptor belongs to agent ${recoveryDescriptor.agent}` };
@@ -8027,7 +8035,7 @@ function childResumability(run, step) {
8027
8035
  let requiredCwd;
8028
8036
  try {
8029
8037
  requiredCwd = resolveRetainedWorktreeCwd(parallelHandoffPath(run.asyncDir), run.id, step.index, step.worktreePath) ?? recoveryDescriptor.cwd ?? run.cwd;
8030
- if (!requiredCwd || !fs16.statSync(requiredCwd).isDirectory()) return { state: "not-resumable", reason: `required cwd is missing: ${requiredCwd ?? "unknown"}` };
8038
+ if (!requiredCwd || !fs15.statSync(requiredCwd).isDirectory()) return { state: "not-resumable", reason: `required cwd is missing: ${requiredCwd ?? "unknown"}` };
8031
8039
  } catch (error2) {
8032
8040
  return { state: "not-resumable", reason: `resume dependency unavailable: ${error2 instanceof Error ? error2.message : String(error2)}` };
8033
8041
  }
@@ -8087,9 +8095,52 @@ function formatRetainedChildren(children) {
8087
8095
  ].join("\n");
8088
8096
  }
8089
8097
 
8098
+ // src/extension/subagent-launch-tool.ts
8099
+ import { Type as Type2 } from "typebox";
8100
+ var SUBAGENT_LAUNCH_TOOL = "subagent_launch";
8101
+ var parameters = Type2.Object({
8102
+ workflowRunId: Type2.String(),
8103
+ key: Type2.String(),
8104
+ agent: Type2.Optional(Type2.String()),
8105
+ task: Type2.Optional(Type2.String()),
8106
+ cwd: Type2.Optional(Type2.String()),
8107
+ model: Type2.Optional(Type2.String()),
8108
+ async: Type2.Optional(Type2.Boolean()),
8109
+ worktree: Type2.Optional(Type2.Boolean()),
8110
+ resume: Type2.Optional(Type2.String()),
8111
+ commands: Type2.Optional(Type2.Array(Type2.Object({
8112
+ command: Type2.String(),
8113
+ cwd: Type2.Optional(Type2.String()),
8114
+ env: Type2.Optional(Type2.Record(Type2.String(), Type2.String()))
8115
+ }))),
8116
+ output: Type2.Optional(Type2.String())
8117
+ });
8118
+ function registerSubagentLaunchTool(pi) {
8119
+ pi.registerTool({
8120
+ name: SUBAGENT_LAUNCH_TOOL,
8121
+ label: "Subagent launch",
8122
+ description: "A workflow is about to start this subagent. Blocking this call stops that child from starting.",
8123
+ parameters,
8124
+ exposure: "deferred",
8125
+ async execute() {
8126
+ return { content: [{ type: "text", text: "Records approval for a workflow child launch; it starts nothing itself." }], details: {} };
8127
+ }
8128
+ });
8129
+ }
8130
+ async function approveWorkflowChildLaunch(ctx, describe, signal) {
8131
+ if (!("executeTool" in ctx)) return void 0;
8132
+ const toolCtx = ctx;
8133
+ if (!toolCtx.tools.some((tool) => tool.name === SUBAGENT_LAUNCH_TOOL)) return void 0;
8134
+ const args = describe();
8135
+ const outcome = await toolCtx.executeTool(SUBAGENT_LAUNCH_TOOL, args, { signal });
8136
+ if (!outcome.isError) return void 0;
8137
+ const reason = outcome.result.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n").trim();
8138
+ return `Workflow child '${args.key}' was not started: the ${SUBAGENT_LAUNCH_TOOL} call was refused${reason ? `: ${reason}` : "."}`;
8139
+ }
8140
+
8090
8141
  // src/runs/shared/external-job-bridge.ts
8091
8142
  import { randomUUID as randomUUID7 } from "node:crypto";
8092
- import * as fs17 from "node:fs";
8143
+ import * as fs16 from "node:fs";
8093
8144
  import * as os2 from "node:os";
8094
8145
  import * as path16 from "node:path";
8095
8146
  var EXTERNAL_JOB_BRIDGE_REQUEST_DIR = "external-job-requests";
@@ -8122,18 +8173,18 @@ function dispatchClaimHandlePath(claimDir) {
8122
8173
  return path16.join(claimDir, "handle.json");
8123
8174
  }
8124
8175
  function completedDispatchClaimExists(asyncDir, id) {
8125
- return fs17.existsSync(dispatchClaimCompletedPath(dispatchClaimDir(asyncDir, id)));
8176
+ return fs16.existsSync(dispatchClaimCompletedPath(dispatchClaimDir(asyncDir, id)));
8126
8177
  }
8127
8178
  function responsePath(asyncDir, id) {
8128
8179
  return path16.join(responseDir(asyncDir), `${id}.json`);
8129
8180
  }
8130
8181
  function readJson2(filePath) {
8131
- return JSON.parse(fs17.readFileSync(filePath, "utf-8"));
8182
+ return JSON.parse(fs16.readFileSync(filePath, "utf-8"));
8132
8183
  }
8133
8184
  function processStartIdentity(pid) {
8134
8185
  if (process.platform === "linux") {
8135
8186
  try {
8136
- const stat = fs17.readFileSync(`/proc/${pid}/stat`, "utf-8");
8187
+ const stat = fs16.readFileSync(`/proc/${pid}/stat`, "utf-8");
8137
8188
  const commandEnd = stat.lastIndexOf(")");
8138
8189
  if (commandEnd === -1) return void 0;
8139
8190
  const fields = stat.slice(commandEnd + 1).trim().split(/\s+/);
@@ -8253,16 +8304,16 @@ function claimDispatchRequest(asyncDir, filePath, request) {
8253
8304
  const claimDir = dispatchClaimDir(asyncDir, request.id);
8254
8305
  const tempClaimDir = dispatchClaimTempDir(asyncDir, request.id);
8255
8306
  try {
8256
- fs17.mkdirSync(tempClaimDir);
8307
+ fs16.mkdirSync(tempClaimDir);
8257
8308
  writeAtomicJson(path16.join(tempClaimDir, "owner.json"), owner);
8258
8309
  writeAtomicJson(path16.join(tempClaimDir, "request.json"), claimed);
8259
- fs17.renameSync(tempClaimDir, claimDir);
8310
+ fs16.renameSync(tempClaimDir, claimDir);
8260
8311
  } catch (error2) {
8261
- fs17.rmSync(tempClaimDir, { recursive: true, force: true });
8312
+ fs16.rmSync(tempClaimDir, { recursive: true, force: true });
8262
8313
  if (isClaimConflictError(error2)) return void 0;
8263
8314
  throw error2;
8264
8315
  }
8265
- fs17.rmSync(filePath, { force: true });
8316
+ fs16.rmSync(filePath, { force: true });
8266
8317
  return { request: claimed, filePath: claimDir };
8267
8318
  }
8268
8319
  function parseClaimOwner(value) {
@@ -8344,18 +8395,18 @@ function createChildExternalJobBridgeSweeper() {
8344
8395
  function serviceExternalJobBridgeRequests(asyncDir) {
8345
8396
  let files;
8346
8397
  try {
8347
- 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);
8398
+ 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);
8348
8399
  } catch (error2) {
8349
8400
  if (error2.code === "ENOENT") return;
8350
8401
  throw error2;
8351
8402
  }
8352
- fs17.mkdirSync(responseDir(asyncDir), { recursive: true });
8403
+ fs16.mkdirSync(responseDir(asyncDir), { recursive: true });
8353
8404
  for (const file of files) {
8354
8405
  serviceExternalJobBridgeRequestFile(asyncDir, file);
8355
8406
  }
8356
8407
  }
8357
8408
  function serviceExternalJobBridgeRequestFile(asyncDir, file) {
8358
- fs17.mkdirSync(responseDir(asyncDir), { recursive: true });
8409
+ fs16.mkdirSync(responseDir(asyncDir), { recursive: true });
8359
8410
  if (file.endsWith(".claim")) {
8360
8411
  serviceExternalJobDispatchClaim(asyncDir, file);
8361
8412
  return;
@@ -8376,14 +8427,14 @@ function serviceExternalJobBridgeRequestFile(asyncDir, file) {
8376
8427
  message: error2 instanceof Error ? error2.message : String(error2),
8377
8428
  completedAt: Date.now()
8378
8429
  });
8379
- fs17.rmSync(filePath, { force: true });
8430
+ fs16.rmSync(filePath, { force: true });
8380
8431
  return;
8381
8432
  }
8382
8433
  if (isDispatchOperation(request.operation) && completedDispatchClaimExists(asyncDir, request.id)) {
8383
- fs17.rmSync(filePath, { force: true });
8434
+ fs16.rmSync(filePath, { force: true });
8384
8435
  return;
8385
8436
  }
8386
- if (inFlight.has(request.id) || fs17.existsSync(responsePath(asyncDir, request.id))) return;
8437
+ if (inFlight.has(request.id) || fs16.existsSync(responsePath(asyncDir, request.id))) return;
8387
8438
  if (isDispatchOperation(request.operation) && request.claimedAt !== void 0) return;
8388
8439
  const claimed = isDispatchOperation(request.operation) ? claimDispatchRequest(asyncDir, filePath, request) : { request, filePath };
8389
8440
  if (!claimed) return;
@@ -8394,7 +8445,7 @@ function serviceExternalJobBridgeRequestFile(asyncDir, file) {
8394
8445
  if (isDispatchOperation(claimedRequest.operation)) {
8395
8446
  writeAtomicJson(dispatchClaimCompletedPath(claimed.filePath), { completedAt: Date.now() });
8396
8447
  } else {
8397
- fs17.rmSync(claimed.filePath, { recursive: true, force: true });
8448
+ fs16.rmSync(claimed.filePath, { recursive: true, force: true });
8398
8449
  }
8399
8450
  }).catch((error2) => {
8400
8451
  writeAtomicJson(responsePath(asyncDir, claimedRequest.id), {
@@ -8413,10 +8464,10 @@ function serviceExternalJobBridgeRequestFile(asyncDir, file) {
8413
8464
  }
8414
8465
  function serviceExternalJobDispatchClaim(asyncDir, file) {
8415
8466
  const claimDir = path16.join(requestDir(asyncDir), file);
8416
- if (fs17.existsSync(dispatchClaimCompletedPath(claimDir))) return;
8467
+ if (fs16.existsSync(dispatchClaimCompletedPath(claimDir))) return;
8417
8468
  const owner = readClaimOwner(claimDir);
8418
- if (!owner && fs17.existsSync(requestPath(asyncDir, file.replace(/\.claim$/, ""))) && !fs17.existsSync(responsePath(asyncDir, file.replace(/\.claim$/, "")))) {
8419
- fs17.rmSync(claimDir, { recursive: true, force: true });
8469
+ if (!owner && fs16.existsSync(requestPath(asyncDir, file.replace(/\.claim$/, ""))) && !fs16.existsSync(responsePath(asyncDir, file.replace(/\.claim$/, "")))) {
8470
+ fs16.rmSync(claimDir, { recursive: true, force: true });
8420
8471
  return;
8421
8472
  }
8422
8473
  if (!claimOwnerIsDead(owner)) return;
@@ -8426,7 +8477,7 @@ function serviceExternalJobDispatchClaim(asyncDir, file) {
8426
8477
  } catch {
8427
8478
  return;
8428
8479
  }
8429
- if (!isDispatchOperation(request.operation) || fs17.existsSync(responsePath(asyncDir, request.id))) return;
8480
+ if (!isDispatchOperation(request.operation) || fs16.existsSync(responsePath(asyncDir, request.id))) return;
8430
8481
  const handle = readClaimHandle(request.provider, claimDir);
8431
8482
  if (handle) {
8432
8483
  writeAtomicJson(responsePath(asyncDir, request.id), {
@@ -8438,7 +8489,7 @@ function serviceExternalJobDispatchClaim(asyncDir, file) {
8438
8489
  completedAt: Date.now()
8439
8490
  });
8440
8491
  writeAtomicJson(dispatchClaimCompletedPath(claimDir), { completedAt: Date.now() });
8441
- fs17.rmSync(requestPath(asyncDir, request.id), { force: true });
8492
+ fs16.rmSync(requestPath(asyncDir, request.id), { force: true });
8442
8493
  return;
8443
8494
  }
8444
8495
  writeAtomicJson(responsePath(asyncDir, request.id), {
@@ -8450,8 +8501,8 @@ function serviceExternalJobDispatchClaim(asyncDir, file) {
8450
8501
  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.`,
8451
8502
  completedAt: Date.now()
8452
8503
  });
8453
- fs17.rmSync(claimDir, { recursive: true, force: true });
8454
- fs17.rmSync(requestPath(asyncDir, request.id), { force: true });
8504
+ fs16.rmSync(claimDir, { recursive: true, force: true });
8505
+ fs16.rmSync(requestPath(asyncDir, request.id), { force: true });
8455
8506
  }
8456
8507
 
8457
8508
  // src/shared/provider-diagnostics.ts
@@ -8580,7 +8631,6 @@ export {
8580
8631
  COMPLETION_ACTION,
8581
8632
  STATUS_ACTION,
8582
8633
  createParentWake,
8583
- writeWorkflowLaunchRecord,
8584
8634
  resumedRunStarted,
8585
8635
  workflowResumeClaimState,
8586
8636
  claimWorkflowResume,
@@ -8625,5 +8675,7 @@ export {
8625
8675
  prepareWorkflowResume,
8626
8676
  flattenSubagentToolOptions,
8627
8677
  listRetainedChildren,
8628
- formatRetainedChildren
8678
+ formatRetainedChildren,
8679
+ registerSubagentLaunchTool,
8680
+ approveWorkflowChildLaunch
8629
8681
  };