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
@@ -10,10 +10,10 @@ import {
10
10
  setInlineWorkflowCoverage,
11
11
  setMainThinkingLevelSource,
12
12
  widgetRenderKey
13
- } from "./chunk-ZVOAMTUQ.js";
13
+ } from "./chunk-L2ENOFVZ.js";
14
14
  import {
15
15
  package_default
16
- } from "./chunk-MABL3FUM.js";
16
+ } from "./chunk-HFTBF7SG.js";
17
17
  import {
18
18
  EXTERNAL_JOB_BRIDGE_REQUEST_DIR,
19
19
  REVIVAL_ORIGIN_FILE,
@@ -51,6 +51,7 @@ import {
51
51
  registerInspectorEventListener,
52
52
  registerMainWatchdog,
53
53
  registerPiWebSessionLiveness,
54
+ registerSubagentLaunchTool,
54
55
  registerSubagentNotify,
55
56
  releaseWorkflowResumeClaim,
56
57
  resolveSubagentResultStatus,
@@ -61,23 +62,16 @@ import {
61
62
  snapshotProviderDiagnostics,
62
63
  workflowResumeClaimState,
63
64
  workflowResumeRefusal
64
- } from "./chunk-F5DBXJ2G.js";
65
+ } from "./chunk-WOVMHDES.js";
65
66
  import {
66
- CONTACT_SUPERVISOR_TOOL_NAME,
67
- NATIVE_SUPERVISOR_TOOL_NAME,
68
67
  SUBAGENT_CHILD_ENV,
69
68
  SUBAGENT_PARENT_SESSION_ENV,
70
- SUPERVISOR_REPLY_ENTRY_TYPE,
71
- SUPERVISOR_REQUEST_MESSAGE_TYPE,
72
69
  SubagentFlatParams,
73
70
  completionReplayPath,
74
- createNativeSupervisorChannel,
75
71
  createSubagentParamsSchema,
76
72
  drainOutstandingWork,
77
73
  finalizeToolResult,
78
74
  normalizeWatchdogWarningDetails,
79
- parseSupervisorReplyData,
80
- parseSupervisorRequestDetails,
81
75
  readCompletionArchive,
82
76
  readCompletionReplay,
83
77
  recordWaitCompletion,
@@ -87,38 +81,55 @@ import {
87
81
  resolveCurrentSessionId,
88
82
  resolvePiSessionId,
89
83
  resolveWaitToolConfig,
90
- setDeclarationPinning,
91
- topLevelSupervisorTool
92
- } from "./chunk-UFL7IYCW.js";
84
+ setDeclarationPinning
85
+ } from "./chunk-IQIWF2VX.js";
93
86
  import {
94
87
  deliverAsyncRunStop,
95
88
  ownerConfirmedDead,
96
89
  readSessionMessagesTail,
97
90
  resolveSubagentRunId,
98
91
  restoreForegroundRunHistory
99
- } from "./chunk-VLFZIN6D.js";
92
+ } from "./chunk-KZ34KQQH.js";
100
93
  import {
101
94
  ASYNC_STATUS_SNAPSHOT_KIND,
102
95
  ASYNC_STATUS_SNAPSHOT_VERSION,
103
- MODEL_ONLY_TOOL,
104
- canRenderComponents,
105
96
  decodeUtf8Tail,
106
97
  formatAsyncRunProgressLabel,
107
98
  formatWorkflowPreflightSummary,
108
- inheritedSessionIds,
109
- isStaleExtensionContextError,
110
99
  isStoppableAsyncStatusStep,
111
100
  listAsyncRuns,
112
101
  normalizeWorkflowPreflight,
113
- ownerSessionIds,
114
- ownsRun,
115
102
  parseWorkflowChildSummary,
116
- recordSessionReplacement,
103
+ recoveryDescriptorPath,
117
104
  resolveAsyncRunLocation,
118
105
  resolveAsyncStatusChild,
119
- stopStoppableAsyncStatusChildren,
106
+ runLaunchDir,
107
+ stopStoppableAsyncStatusChildren
108
+ } from "./chunk-LTPH2DXH.js";
109
+ import {
110
+ CONTACT_SUPERVISOR_TOOL_NAME,
111
+ NATIVE_SUPERVISOR_TOOL_NAME,
112
+ SUPERVISOR_REPLY_ENTRY_TYPE,
113
+ SUPERVISOR_REQUEST_MESSAGE_TYPE,
114
+ createNativeSupervisorChannel,
115
+ parseSupervisorReplyData,
116
+ parseSupervisorRequestDetails,
117
+ topLevelSupervisorTool
118
+ } from "./chunk-T5V5BRCL.js";
119
+ import {
120
+ MODEL_ONLY_TOOL,
121
+ canRenderComponents,
122
+ inheritedSessionIds,
123
+ isStaleExtensionContextError,
124
+ keepSessionWork,
125
+ ownerSessionIds,
126
+ ownsRun,
127
+ recordSessionReplacement,
128
+ recordSessionStart,
129
+ releaseSessionWork,
130
+ reportSessionWarning,
120
131
  withCachedUiContext
121
- } from "./chunk-UYK5MZWE.js";
132
+ } from "./chunk-HXRB42AF.js";
122
133
  import "./chunk-NF7IEKBH.js";
123
134
  import {
124
135
  disabledFeatureUseError,
@@ -129,7 +140,7 @@ import {
129
140
  resolveDisabledFeatureSurface,
130
141
  resolveMaxActiveAsyncRunsPerSession,
131
142
  resolveScheduledStoreRoot
132
- } from "./chunk-QP5ZWNIS.js";
143
+ } from "./chunk-RV5OGHLO.js";
133
144
  import {
134
145
  ACTIVE_RUN_INDEX_DIR,
135
146
  MissionNotFoundError,
@@ -138,10 +149,12 @@ import {
138
149
  acknowledgeMissionObserverSnapshot,
139
150
  checkRecordedPidLiveness,
140
151
  cleanupResultIndexes,
152
+ collectNestedRuns,
141
153
  currentCompletionOwnerId,
142
154
  encodeIndexSegment,
143
155
  findNestedRouteForRootId,
144
156
  hasLiveNestedDescendants,
157
+ isActiveAsyncState,
145
158
  isRecordedPid,
146
159
  isReusableWorkflowStopCause,
147
160
  listMissions,
@@ -178,28 +191,28 @@ import {
178
191
  withWorkflowChildRunModel,
179
192
  writeAsyncResultFile,
180
193
  writeResultIndexForData
181
- } from "./chunk-RNIZLSEA.js";
182
- import "./chunk-F4ASL6OV.js";
194
+ } from "./chunk-LGMILZNE.js";
195
+ import "./chunk-7MAE3DJV.js";
183
196
  import {
184
197
  shouldUseNativeFsWatch
185
198
  } from "./chunk-NIXWDZZV.js";
186
199
  import {
187
200
  validateIntercomBridgeConfig
188
- } from "./chunk-C5P5CHYK.js";
201
+ } from "./chunk-KDMFBYFM.js";
189
202
  import "./chunk-7F6RKT6W.js";
190
- import "./chunk-V2BZYLEP.js";
203
+ import "./chunk-KEY3UQMQ.js";
191
204
  import "./chunk-CTPAE36Y.js";
192
205
  import {
193
206
  listHerdrProjectPaneRoots,
194
207
  restoreHerdrProjectPaneSnapshots
195
- } from "./chunk-2DHZTCOL.js";
208
+ } from "./chunk-PVIVCDG2.js";
196
209
  import "./chunk-7J4ZXMY7.js";
197
210
  import {
198
211
  cleanupAllArtifactDirs,
199
212
  cleanupOldArtifacts,
200
213
  getArtifactPaths,
201
214
  getArtifactsDir
202
- } from "./chunk-D3JAFGMO.js";
215
+ } from "./chunk-PHZP3KHB.js";
203
216
  import {
204
217
  listBackgroundWorkProviders
205
218
  } from "./chunk-XA3DY6UG.js";
@@ -207,14 +220,15 @@ import "./chunk-YYREO77V.js";
207
220
  import "./chunk-UKG4V45O.js";
208
221
  import {
209
222
  registerRuntimeAgentEventListener
210
- } from "./chunk-2S4K53MV.js";
223
+ } from "./chunk-H2NLFTC5.js";
211
224
  import {
212
225
  clearRuntimeAgentsForPi,
213
226
  listRuntimeAgentConfigs,
214
227
  mergeRuntimeAgents
215
- } from "./chunk-G2Z6ZH26.js";
228
+ } from "./chunk-GCSLVFCX.js";
216
229
  import {
217
230
  DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS,
231
+ DEFAULT_WAIT_TOOL_NAME,
218
232
  EXTRA_AGENT_DIRS_ENV,
219
233
  FileLeaseBusyError,
220
234
  SUBAGENT_WATCHDOG_WARNING_TYPE,
@@ -243,6 +257,7 @@ import {
243
257
  resolveWatchPath,
244
258
  runFileSystemOperationWithRetry,
245
259
  serializeAgent,
260
+ setWaitToolName,
246
261
  shortenPath,
247
262
  splitKnownThinkingSuffix,
248
263
  toModelInfo,
@@ -250,9 +265,10 @@ import {
250
265
  validateOptionalMachine,
251
266
  validateToolBudgetConfig,
252
267
  waitForFileSystemRetry,
268
+ waitToolName,
253
269
  withSettingsFileLease,
254
270
  writeAtomicJson
255
- } from "./chunk-LNRJCP2Y.js";
271
+ } from "./chunk-UX4SCV5N.js";
256
272
  import {
257
273
  DEFAULT_ARTIFACT_CONFIG,
258
274
  DIRS,
@@ -307,6 +323,8 @@ import { exec, execFile } from "node:child_process";
307
323
  import { promises as fs } from "node:fs";
308
324
  import path from "node:path";
309
325
  async function resolveGlobalNpmRoot(options = {}) {
326
+ const signal = options.signal;
327
+ if (signal?.aborted) return null;
310
328
  const env = options.env ?? process.env;
311
329
  const offline = env.PI_OFFLINE?.toLowerCase();
312
330
  if (offline === "1" || offline === "true" || offline === "yes") return null;
@@ -317,6 +335,7 @@ async function resolveGlobalNpmRoot(options = {}) {
317
335
  } catch {
318
336
  }
319
337
  }
338
+ if (signal?.aborted) return null;
320
339
  const timeoutMs = options.timeoutMs ?? 5e3;
321
340
  const output = await new Promise((resolve6) => {
322
341
  let settled = false;
@@ -324,6 +343,7 @@ async function resolveGlobalNpmRoot(options = {}) {
324
343
  if (settled) return;
325
344
  settled = true;
326
345
  clearTimeout(timer);
346
+ signal?.removeEventListener("abort", cancel);
327
347
  resolve6(value);
328
348
  };
329
349
  const commandOptions = {
@@ -335,10 +355,12 @@ async function resolveGlobalNpmRoot(options = {}) {
335
355
  };
336
356
  const callback = (error, stdout) => finish(error ? null : stdout.trim());
337
357
  const child = (options.platform ?? process.platform) === "win32" ? exec("npm root -g", commandOptions, callback) : execFile("npm", ["root", "-g"], commandOptions, callback);
338
- const timer = setTimeout(() => {
358
+ const cancel = () => {
339
359
  child.kill();
340
360
  finish(null);
341
- }, timeoutMs);
361
+ };
362
+ const timer = setTimeout(cancel, timeoutMs);
363
+ signal?.addEventListener("abort", cancel, { once: true });
342
364
  });
343
365
  if (!output) return null;
344
366
  try {
@@ -433,6 +455,113 @@ function ensureAccessibleDir(dirPath, options = {}) {
433
455
  }
434
456
  }
435
457
 
458
+ // src/extension/session-switch.ts
459
+ var STAY = "Stay here";
460
+ var TAKE = "Switch and take the work";
461
+ var LEAVE = "Switch and leave the work here";
462
+ var RPC_PROMPT_TIMEOUT_MS = 6e4;
463
+ function createSessionSwitchGuard(deps) {
464
+ let leave;
465
+ let checking = false;
466
+ const lifetime = new AbortController();
467
+ const activeRunCount = (sessionId) => {
468
+ const runs = new Set(listAsyncRuns(deps.asyncDirRoot, {
469
+ sessionId,
470
+ states: ["queued", "running"],
471
+ resultsDir: deps.resultsDir,
472
+ includeNested: false
473
+ }).map((run) => run.id));
474
+ for (const job of deps.state.asyncJobs.values()) {
475
+ if (runs.has(job.asyncId) || !ownsRun(sessionId, job.sessionId) || !isActiveAsyncState(job.status)) continue;
476
+ let active = true;
477
+ try {
478
+ const status = readStatus(job.asyncDir);
479
+ active = !status || isActiveAsyncState(status.state);
480
+ } catch {
481
+ }
482
+ if (active) runs.add(job.asyncId);
483
+ }
484
+ for (const id of deps.state.workflowControllers?.keys() ?? []) runs.add(id);
485
+ return runs.size;
486
+ };
487
+ const hasNestedWork = (sessionId) => {
488
+ const routes = /* @__PURE__ */ new Map();
489
+ for (const job of deps.state.asyncJobs.values()) {
490
+ if (!ownsRun(sessionId, job.sessionId)) continue;
491
+ if (job.nestedRoute) routes.set(job.nestedRoute.rootRunId, job.nestedRoute);
492
+ else if (collectNestedRuns(job.nestedChildren).some((run) => isActiveAsyncState(run.state))) return true;
493
+ }
494
+ for (const control of deps.state.foregroundControls.values()) {
495
+ if (control.sessionId && !ownsRun(sessionId, control.sessionId)) continue;
496
+ if (control.nestedRoute) routes.set(control.nestedRoute.rootRunId, control.nestedRoute);
497
+ }
498
+ for (const route of deps.state.retainedForegroundNestedRoutes?.values() ?? []) routes.set(route.rootRunId, route);
499
+ if (deps.state.retainedNestedLookupRoutes?.sessionId === sessionId) {
500
+ for (const route of deps.state.retainedNestedLookupRoutes.routes.values()) routes.set(route.rootRunId, route);
501
+ }
502
+ return [...routes.values()].some((route) => {
503
+ reconcileNestedAsyncDescendants(route, { resultsDir: deps.resultsDir });
504
+ return collectNestedRuns(projectNestedEvents(route).children).some((run) => isActiveAsyncState(run.state));
505
+ });
506
+ };
507
+ return {
508
+ async beforeSwitch(reason, ctx) {
509
+ if (lifetime.signal.aborted || checking) return { cancel: true };
510
+ leave = void 0;
511
+ if (!ctx.hasUI) return;
512
+ checking = true;
513
+ try {
514
+ const sessionId = deps.state.currentSessionId;
515
+ if (!sessionId) throw new Error("The current session identity is unavailable.");
516
+ const runs = activeRunCount(sessionId);
517
+ const nested = hasNestedWork(sessionId);
518
+ const results = deps.hasPendingResults();
519
+ const questions = deps.hasPendingSupervisorRequest();
520
+ if (runs === 0 && !nested && !results && !questions) return;
521
+ const title = [
522
+ "pi-subagents: switch sessions?",
523
+ "",
524
+ "Background subagent work in this session:",
525
+ ...runs > 0 ? [` ${runs} run${runs === 1 ? "" : "s"} queued or running`] : [],
526
+ ...nested ? [" Nested subagents still running"] : [],
527
+ ...results ? [" Undelivered results"] : [],
528
+ ...questions ? [" Questions awaiting a reply"] : []
529
+ ].join("\n");
530
+ const choice = await ctx.ui.select(title, [STAY, TAKE, LEAVE], { signal: lifetime.signal, timeout: ctx.mode === "rpc" ? RPC_PROMPT_TIMEOUT_MS : void 0 });
531
+ if (lifetime.signal.aborted || deps.state.currentSessionId !== sessionId) return { cancel: true };
532
+ if (choice === TAKE) return;
533
+ if (choice === LEAVE) {
534
+ leave = { sessionId, reason };
535
+ return;
536
+ }
537
+ return { cancel: true };
538
+ } catch (error) {
539
+ const message2 = error instanceof Error ? error.message : String(error);
540
+ try {
541
+ if (!lifetime.signal.aborted) ctx.ui.notify(`Session switch cancelled: ${message2}`, "warning");
542
+ } catch {
543
+ }
544
+ return { cancel: true };
545
+ } finally {
546
+ checking = false;
547
+ }
548
+ },
549
+ // Recorded only once the switch commits, so a switch another extension cancels keeps the default handoff.
550
+ sessionShutdown(event) {
551
+ const left = leave;
552
+ leave = void 0;
553
+ const sessionId = deps.state.currentSessionId;
554
+ if (!sessionId) return;
555
+ if (left && left.sessionId === sessionId && left.reason === event.reason) keepSessionWork(sessionId);
556
+ else releaseSessionWork(sessionId);
557
+ },
558
+ dispose() {
559
+ leave = void 0;
560
+ lifetime.abort();
561
+ }
562
+ };
563
+ }
564
+
436
565
  // src/runs/background/async-job-tracker.ts
437
566
  import * as fs3 from "node:fs";
438
567
  import * as path2 from "node:path";
@@ -1054,7 +1183,17 @@ function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
1054
1183
  if (now >= nextLivenessAt) {
1055
1184
  nextLivenessAt = now + livenessIntervalMs;
1056
1185
  let widgetChanged = false;
1186
+ const owners = state.currentSessionId ? ownerSessionIds(state.currentSessionId) : void 0;
1057
1187
  for (const job of state.asyncJobs.values()) {
1188
+ if (owners && job.sessionId !== void 0 && !owners.has(job.sessionId)) {
1189
+ cancelCleanup(job.asyncId);
1190
+ closeJobWatcher(job.asyncId);
1191
+ state.asyncJobs.delete(job.asyncId);
1192
+ state.fleetJobs?.delete(job.asyncId);
1193
+ options.onJobCleanup?.(job.asyncId);
1194
+ widgetChanged = true;
1195
+ continue;
1196
+ }
1058
1197
  watchJob(job);
1059
1198
  if (refreshJob(job)) widgetChanged = true;
1060
1199
  }
@@ -1215,7 +1354,9 @@ var ASYNC_RETENTION_DAYS = 30;
1215
1354
  var ASYNC_RETENTION_BATCH_SIZE = 100;
1216
1355
  var ASYNC_RETENTION_DELAY_MS = 6e4;
1217
1356
  var ASYNC_RETENTION_TOMBSTONE_GRACE_MS = 24 * 60 * 60 * 1e3;
1357
+ var RESUMABLE_RETENTION_DAYS = 90;
1218
1358
  var RETENTION_MS = ASYNC_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
1359
+ var RESUMABLE_RETENTION_MS = RESUMABLE_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
1219
1360
  var LOCK_NAME = ".async-retention.lock";
1220
1361
  var CURSOR_NAME = ".async-retention-cursor.json";
1221
1362
  var LOG_NAME = "async-retention-maintenance.jsonl";
@@ -1285,7 +1426,7 @@ function hasNestedReferences(status) {
1285
1426
  function hasResumableContract(runDir, status) {
1286
1427
  const statusSessionFiles = [status.sessionFile, ...(status.steps ?? []).map((step) => step.sessionFile)];
1287
1428
  if (statusSessionFiles.some(existingRegularFile)) return true;
1288
- const descriptorPath = path3.join(runDir, "recovery-descriptor.json");
1429
+ const descriptorPath = recoveryDescriptorPath(path3.dirname(runDir), status.runId);
1289
1430
  if (!fs4.existsSync(descriptorPath)) return false;
1290
1431
  const descriptor = readJson(descriptorPath);
1291
1432
  if (!descriptor) return true;
@@ -1389,8 +1530,8 @@ function runSkipReason(input) {
1389
1530
  if (hasNestedReferences(status)) return "nested-reference";
1390
1531
  if (missionReferenceBlocksReclaim(runDir, input.resultsDir, status.runId)) return "mission-reference";
1391
1532
  if (hasUnresolvedRunHandoff(runDir, status)) return "handoff-reference";
1392
- if (hasResumableContract(runDir, status)) return "resumable";
1393
1533
  const timestamp = statusTimestamp(status, runDir);
1534
+ if (hasResumableContract(runDir, status) && (timestamp === void 0 || timestamp > input.resumableCutoff)) return "resumable";
1394
1535
  if (timestamp === void 0) return "unknown-age";
1395
1536
  if (timestamp > input.cutoff) return "recent";
1396
1537
  return void 0;
@@ -1558,10 +1699,10 @@ function resultSkipReason(input) {
1558
1699
  if (missionObserverIndexExists(input.resultsDir, runId)) return "mission-reference";
1559
1700
  if (input.data.mode === "workflow" || completionMode(input.data) === "workflow" || typeof input.data.parentWorkflowRunId === "string" || typeof input.data.workflowKey === "string") return "workflow-reference";
1560
1701
  if (hasUnresolvedResultHandoff(input.data)) return "handoff-reference";
1561
- if (resultHasResumableSession(input.data)) return "resumable";
1702
+ const timestamp = resultTimestamp(input.data, input.candidate.path);
1703
+ if (resultHasResumableSession(input.data) && (timestamp === void 0 || timestamp > input.resumableCutoff)) return "resumable";
1562
1704
  if (input.candidate.kind === "archive" && fs4.existsSync(path3.join(input.resultsDir, "completion-replay", `${encodeURIComponent(runId)}.json`))) return "replay-reference";
1563
1705
  if (!terminalResult(input.data) && input.candidate.kind !== "replay" && input.candidate.kind !== "archive" && input.candidate.kind !== "tombstone") return "non-terminal-result";
1564
- const timestamp = resultTimestamp(input.data, input.candidate.path);
1565
1706
  if (timestamp === void 0) return "unknown-age";
1566
1707
  if (timestamp > input.cutoff) return "recent";
1567
1708
  return void 0;
@@ -1747,6 +1888,7 @@ async function cleanupAsyncRetention(options) {
1747
1888
  if (markCancelled()) return finish();
1748
1889
  const protectedRunIds = new Set(options.protectedRunIds ?? []);
1749
1890
  const cutoff = currentTime - retentionMs;
1891
+ const resumableCutoff = currentTime - RESUMABLE_RETENTION_MS;
1750
1892
  const cursor = readCursor(maintenanceRoot);
1751
1893
  const runBudget = Math.ceil(batchSize / 2);
1752
1894
  const resultBudget = batchSize - runBudget;
@@ -1811,7 +1953,7 @@ async function cleanupAsyncRetention(options) {
1811
1953
  status = reconciliation.status ?? void 0;
1812
1954
  if (reconciliation.repaired) result.repairedRuns += 1;
1813
1955
  }
1814
- const initialReason = runSkipReason({ runDir, status, asyncDirRoot: options.asyncDirRoot, resultsDir: options.resultsDir, cutoff, protectedRunIds, waitRunIds: waitReferences.runIds });
1956
+ const initialReason = runSkipReason({ runDir, status, asyncDirRoot: options.asyncDirRoot, resultsDir: options.resultsDir, cutoff, resumableCutoff, protectedRunIds, waitRunIds: waitReferences.runIds });
1815
1957
  if (initialReason) {
1816
1958
  increment(result.skipped, initialReason);
1817
1959
  continue;
@@ -1826,13 +1968,14 @@ async function cleanupAsyncRetention(options) {
1826
1968
  continue;
1827
1969
  }
1828
1970
  const freshWaitReferences2 = parseWaitRunIds(waitSubscriptionsDir);
1829
- const finalReason = freshWaitReferences2.safe ? runSkipReason({ runDir, status, asyncDirRoot: options.asyncDirRoot, resultsDir: options.resultsDir, cutoff, protectedRunIds, waitRunIds: freshWaitReferences2.runIds }) : "wait-references-unknown";
1971
+ const finalReason = freshWaitReferences2.safe ? runSkipReason({ runDir, status, asyncDirRoot: options.asyncDirRoot, resultsDir: options.resultsDir, cutoff, resumableCutoff, protectedRunIds, waitRunIds: freshWaitReferences2.runIds }) : "wait-references-unknown";
1830
1972
  if (finalReason) {
1831
1973
  increment(result.skipped, `recheck-${finalReason}`);
1832
1974
  continue;
1833
1975
  }
1834
1976
  mutationStateChanged = true;
1835
1977
  fs4.rmSync(runDir, { recursive: true });
1978
+ fs4.rmSync(runLaunchDir(options.asyncDirRoot, status.runId), { recursive: true, force: true });
1836
1979
  removeRunTombstoneMarker(maintenanceRoot, status.runId);
1837
1980
  result.reapedTombstones += 1;
1838
1981
  deletedIds.push(`run-tombstone:${status.runId}`);
@@ -1850,7 +1993,7 @@ async function cleanupAsyncRetention(options) {
1850
1993
  }
1851
1994
  const recheckStatus = readStatus2(tombstone);
1852
1995
  const freshWaitReferences = parseWaitRunIds(waitSubscriptionsDir);
1853
- const recheckReason = freshWaitReferences.safe ? runSkipReason({ runDir: tombstone, status: recheckStatus, asyncDirRoot: options.asyncDirRoot, resultsDir: options.resultsDir, cutoff, protectedRunIds, waitRunIds: freshWaitReferences.runIds }) : "wait-references-unknown";
1996
+ const recheckReason = freshWaitReferences.safe ? runSkipReason({ runDir: tombstone, status: recheckStatus, asyncDirRoot: options.asyncDirRoot, resultsDir: options.resultsDir, cutoff, resumableCutoff, protectedRunIds, waitRunIds: freshWaitReferences.runIds }) : "wait-references-unknown";
1854
1997
  if (recheckReason) {
1855
1998
  if (!fs4.existsSync(runDir)) {
1856
1999
  fs4.renameSync(tombstone, runDir);
@@ -1862,6 +2005,7 @@ async function cleanupAsyncRetention(options) {
1862
2005
  continue;
1863
2006
  }
1864
2007
  fs4.rmSync(tombstone, { recursive: true });
2008
+ fs4.rmSync(runLaunchDir(options.asyncDirRoot, status.runId), { recursive: true, force: true });
1865
2009
  removeRunTombstoneMarker(maintenanceRoot, status.runId);
1866
2010
  result.deletedRuns += 1;
1867
2011
  deletedIds.push(`run:${status.runId}`);
@@ -1882,7 +2026,7 @@ async function cleanupAsyncRetention(options) {
1882
2026
  continue;
1883
2027
  }
1884
2028
  const data = readJson(candidate.path);
1885
- const reason = resultSkipReason({ candidate, data, asyncDirRoot: options.asyncDirRoot, resultsDir: options.resultsDir, maintenanceRoot, cutoff, protectedRunIds, waitRunIds: waitReferences.runIds });
2029
+ const reason = resultSkipReason({ candidate, data, asyncDirRoot: options.asyncDirRoot, resultsDir: options.resultsDir, maintenanceRoot, cutoff, resumableCutoff, protectedRunIds, waitRunIds: waitReferences.runIds });
1886
2030
  if (reason) {
1887
2031
  increment(result.skipped, reason);
1888
2032
  continue;
@@ -1893,7 +2037,7 @@ async function cleanupAsyncRetention(options) {
1893
2037
  continue;
1894
2038
  }
1895
2039
  const freshWaitReferences2 = parseWaitRunIds(waitSubscriptionsDir);
1896
- const finalReason = freshWaitReferences2.safe ? resultSkipReason({ candidate, data, asyncDirRoot: options.asyncDirRoot, resultsDir: options.resultsDir, maintenanceRoot, cutoff, protectedRunIds, waitRunIds: freshWaitReferences2.runIds }) : "wait-references-unknown";
2040
+ const finalReason = freshWaitReferences2.safe ? resultSkipReason({ candidate, data, asyncDirRoot: options.asyncDirRoot, resultsDir: options.resultsDir, maintenanceRoot, cutoff, resumableCutoff, protectedRunIds, waitRunIds: freshWaitReferences2.runIds }) : "wait-references-unknown";
1897
2041
  if (finalReason) {
1898
2042
  increment(result.skipped, `recheck-${finalReason}`);
1899
2043
  continue;
@@ -1910,7 +2054,7 @@ async function cleanupAsyncRetention(options) {
1910
2054
  const tombstoneCandidate = { ...candidate, path: tombstone, kind: "tombstone" };
1911
2055
  const recheckData = readJson(tombstone);
1912
2056
  const freshWaitReferences = parseWaitRunIds(waitSubscriptionsDir);
1913
- const recheckReason = freshWaitReferences.safe ? resultSkipReason({ candidate: tombstoneCandidate, data: recheckData, asyncDirRoot: options.asyncDirRoot, resultsDir: options.resultsDir, maintenanceRoot, cutoff, protectedRunIds, waitRunIds: freshWaitReferences.runIds }) : "wait-references-unknown";
2057
+ const recheckReason = freshWaitReferences.safe ? resultSkipReason({ candidate: tombstoneCandidate, data: recheckData, asyncDirRoot: options.asyncDirRoot, resultsDir: options.resultsDir, maintenanceRoot, cutoff, resumableCutoff, protectedRunIds, waitRunIds: freshWaitReferences.runIds }) : "wait-references-unknown";
1914
2058
  if (recheckReason) {
1915
2059
  if (!fs4.existsSync(candidate.path)) {
1916
2060
  fs4.renameSync(tombstone, candidate.path);
@@ -2017,15 +2161,19 @@ function resultFileIdentity(raw, file) {
2017
2161
  runId: file.replace(/\.json$/i, "")
2018
2162
  };
2019
2163
  }
2020
- function sanitizeNestedResultChildren(value, resultPath, label) {
2164
+ function reportResultWatcherWarning(state, message2, error, key = message2) {
2165
+ const detail = error === void 0 ? "" : `: ${error instanceof Error ? error.message : String(error)}`;
2166
+ reportSessionWarning(state, `${message2}${detail}`, key);
2167
+ }
2168
+ function sanitizeNestedResultChildren(state, value, resultPath, label) {
2021
2169
  if (value === void 0) return void 0;
2022
2170
  if (!Array.isArray(value)) {
2023
- console.error(`Ignoring invalid nested children in subagent result file '${resultPath}' at ${label}: expected an array.`);
2171
+ reportResultWatcherWarning(state, `Ignoring invalid nested children in subagent result file '${resultPath}' at ${label}: expected an array.`);
2024
2172
  return void 0;
2025
2173
  }
2026
2174
  const children = value.map((child) => sanitizeSummary(child)).filter((child) => Boolean(child));
2027
2175
  if (children.length !== value.length) {
2028
- console.error(`Ignoring ${value.length - children.length} invalid nested child record(s) in subagent result file '${resultPath}' at ${label}.`);
2176
+ reportResultWatcherWarning(state, `Ignoring ${value.length - children.length} invalid nested child record(s) in subagent result file '${resultPath}' at ${label}.`, void 0, `result-nested-records-invalid:${resultPath}:${label}`);
2029
2177
  }
2030
2178
  return children.length ? children : void 0;
2031
2179
  }
@@ -2071,6 +2219,7 @@ function createResultWatcher(pi, state, resultsDir, completionTtlMs, deps = {})
2071
2219
  let deliveringPending = 0;
2072
2220
  const identityCache = /* @__PURE__ */ new Map();
2073
2221
  const reportedMissionSyncFailures = /* @__PURE__ */ new Map();
2222
+ let missionSyncReports = 0;
2074
2223
  let deliveryActive = true;
2075
2224
  let deliveryEpoch = 0;
2076
2225
  let resultScanTimer = null;
@@ -2093,7 +2242,7 @@ function createResultWatcher(pi, state, resultsDir, completionTtlMs, deps = {})
2093
2242
  try {
2094
2243
  return fsApi.statSync(publicResultPath(file)).isFile();
2095
2244
  } catch (error) {
2096
- if (!isAbsentResultCandidate(error)) console.error(`Failed to inspect subagent result file '${publicResultPath(file)}':`, error);
2245
+ if (!isAbsentResultCandidate(error)) reportResultWatcherWarning(state, `Failed to inspect subagent result file '${publicResultPath(file)}'`, error);
2097
2246
  return false;
2098
2247
  }
2099
2248
  };
@@ -2126,7 +2275,7 @@ function createResultWatcher(pi, state, resultsDir, completionTtlMs, deps = {})
2126
2275
  } catch (error) {
2127
2276
  identityCache.delete(file);
2128
2277
  if (isAccessDenied(error)) throw error;
2129
- if (!isAbsentResultCandidate(error)) console.error(`Failed to inspect subagent result file '${resultPath}':`, error);
2278
+ if (!isAbsentResultCandidate(error)) reportResultWatcherWarning(state, `Failed to inspect subagent result file '${resultPath}'`, error);
2130
2279
  return void 0;
2131
2280
  }
2132
2281
  };
@@ -2144,7 +2293,7 @@ function createResultWatcher(pi, state, resultsDir, completionTtlMs, deps = {})
2144
2293
  } catch (error) {
2145
2294
  identityCache.delete(file);
2146
2295
  if (isAccessDenied(error)) throw error;
2147
- if (!isAbsentResultCandidate(error)) console.error(`Failed to inspect subagent result file '${resultPath}':`, error);
2296
+ if (!isAbsentResultCandidate(error)) reportResultWatcherWarning(state, `Failed to inspect subagent result file '${resultPath}'`, error);
2148
2297
  return void 0;
2149
2298
  }
2150
2299
  };
@@ -2152,7 +2301,7 @@ function createResultWatcher(pi, state, resultsDir, completionTtlMs, deps = {})
2152
2301
  try {
2153
2302
  return new Set(deps.observedCompletionRunIds?.() ?? []);
2154
2303
  } catch (error) {
2155
- console.error("Failed to inspect observed subagent completion ids:", error);
2304
+ reportResultWatcherWarning(state, "Failed to inspect observed subagent completion ids", error);
2156
2305
  return /* @__PURE__ */ new Set();
2157
2306
  }
2158
2307
  };
@@ -2172,7 +2321,7 @@ function createResultWatcher(pi, state, resultsDir, completionTtlMs, deps = {})
2172
2321
  if (retireResultSnapshot(publicResultPath(file), read, void 0, CLEANUP_LEASE_WAIT_MS) === "replaced") scheduleResult(file, triggerTurn);
2173
2322
  } catch (error) {
2174
2323
  if (isAbsentResultCandidate(error)) return;
2175
- if (!(error instanceof FileLeaseBusyError)) console.error(`Failed to remove delivered subagent result '${publicResultPath(file)}'; will retry:`, error);
2324
+ if (!(error instanceof FileLeaseBusyError)) reportResultWatcherWarning(state, `Failed to remove delivered subagent result '${publicResultPath(file)}'; will retry`, error);
2176
2325
  scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
2177
2326
  }
2178
2327
  };
@@ -2187,7 +2336,7 @@ function createResultWatcher(pi, state, resultsDir, completionTtlMs, deps = {})
2187
2336
  }
2188
2337
  } catch (error) {
2189
2338
  if (!isAccessDenied(error)) throw error;
2190
- console.error(`Failed to inspect subagent result file '${publicResultPath(file)}'; will retry:`, error);
2339
+ reportResultWatcherWarning(state, `Failed to inspect subagent result file '${publicResultPath(file)}'; will retry`, error);
2191
2340
  scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
2192
2341
  return;
2193
2342
  }
@@ -2235,7 +2384,7 @@ function createResultWatcher(pi, state, resultsDir, completionTtlMs, deps = {})
2235
2384
  if (!resultSnapshotReplaced(publicResultPath(file), read)) return false;
2236
2385
  } catch (error) {
2237
2386
  if (isAccessDenied(error)) throw error;
2238
- console.error(`Failed to re-read subagent result file '${publicResultPath(file)}':`, error);
2387
+ reportResultWatcherWarning(state, `Failed to re-read subagent result file '${publicResultPath(file)}'`, error);
2239
2388
  }
2240
2389
  identityCache.delete(file);
2241
2390
  rereadReplacedPayload = true;
@@ -2250,21 +2399,21 @@ function createResultWatcher(pi, state, resultsDir, completionTtlMs, deps = {})
2250
2399
  const message2 = error instanceof Error ? error.message : String(error);
2251
2400
  if (reportedMissionSyncFailures.get(file) !== message2) {
2252
2401
  reportedMissionSyncFailures.set(file, message2);
2253
- console.error(`Mission completion sync failed for '${resultPath}':`, error);
2402
+ reportResultWatcherWarning(state, `Mission completion sync failed for '${resultPath}'`, error, `result-mission-sync-failed:${++missionSyncReports}`);
2254
2403
  }
2255
2404
  }
2256
2405
  try {
2257
2406
  deps.observeCompletion?.({ ...data, runId });
2258
2407
  } catch (error) {
2259
2408
  observerSucceeded = false;
2260
- console.error(`Completion observer failed for '${resultPath}':`, error);
2409
+ reportResultWatcherWarning(state, `Completion observer failed for '${resultPath}'`, error);
2261
2410
  }
2262
2411
  if (observerSucceeded) {
2263
2412
  try {
2264
2413
  if (acknowledgeMissionObserverSnapshot(publicResultPath(file), read, CLEANUP_LEASE_WAIT_MS) === "replaced") rereadReplacedPayload = true;
2265
2414
  } catch (error) {
2266
2415
  observerSucceeded = false;
2267
- if (!(error instanceof FileLeaseBusyError)) console.error(`Failed to acknowledge the mission observer for '${resultPath}'; will retry:`, error);
2416
+ if (!(error instanceof FileLeaseBusyError)) reportResultWatcherWarning(state, `Failed to acknowledge the mission observer for '${resultPath}'; will retry`, error);
2268
2417
  }
2269
2418
  }
2270
2419
  const epoch = deliveryEpoch;
@@ -2274,12 +2423,12 @@ function createResultWatcher(pi, state, resultsDir, completionTtlMs, deps = {})
2274
2423
  sessionId
2275
2424
  });
2276
2425
  const hasExplicitNestedChildren = data.nestedChildren !== void 0;
2277
- let nestedChildren = compactNestedResultChildren(sanitizeNestedResultChildren(data.nestedChildren, resultPath, "nestedChildren"));
2426
+ let nestedChildren = compactNestedResultChildren(sanitizeNestedResultChildren(state, data.nestedChildren, resultPath, "nestedChildren"));
2278
2427
  if (!nestedChildren?.length && !hasExplicitNestedChildren) {
2279
2428
  try {
2280
2429
  nestedChildren = compactNestedResultChildren(projectNestedRegistryForRoot(runId)?.children);
2281
2430
  } catch (error) {
2282
- console.error(`Failed to enrich subagent result file '${resultPath}' with nested registry children; will retry later:`, error);
2431
+ reportResultWatcherWarning(state, `Failed to enrich subagent result file '${resultPath}' with nested registry children; will retry later`, error);
2283
2432
  scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
2284
2433
  return;
2285
2434
  }
@@ -2317,7 +2466,7 @@ ${structuredPreview}` : "(no output)";
2317
2466
  Output:
2318
2467
  ${baseOutput}` : ""}` : output;
2319
2468
  const sessionPath = result.sessionFile ?? (resultChildren.length === 1 ? data.sessionFile : void 0);
2320
- const childNestedChildren = sanitizeNestedResultChildren(result.children, resultPath, `results[${index}].children`);
2469
+ const childNestedChildren = sanitizeNestedResultChildren(state, result.children, resultPath, `results[${index}].children`);
2321
2470
  const childState = result.state === "running" || result.state === "queued" || result.state === "paused" || result.state === "stopped" ? result.state : result.stopped === true ? "stopped" : data.state === "paused" || !hasResultChildren && (data.state === "stopped" || typeof result.success !== "boolean") ? data.state : void 0;
2322
2471
  return {
2323
2472
  agent: result.agent ?? data.agent ?? `step-${index + 1}`,
@@ -2372,7 +2521,7 @@ ${baseOutput}` : ""}` : output;
2372
2521
  ...data.parallelHandoff ? { parallelHandoff: data.parallelHandoff } : {}
2373
2522
  }));
2374
2523
  if (!ownsCompletion(sessionId, completionOwnerId, epoch)) return;
2375
- if (!intercomDelivered) console.error(`Subagent async grouped result intercom delivery was not acknowledged for '${resultPath}'.`);
2524
+ if (!intercomDelivered) reportResultWatcherWarning(state, `Subagent async grouped result intercom delivery was not acknowledged for '${resultPath}'.`);
2376
2525
  }
2377
2526
  const delivery = notifier.deliver({
2378
2527
  ...data,
@@ -2413,7 +2562,7 @@ ${baseOutput}` : ""}` : output;
2413
2562
  }
2414
2563
  ({ data, read } = marked);
2415
2564
  } catch (error) {
2416
- console.error(`Failed to mark subagent result notification delivered for '${resultPath}'; will retry:`, error);
2565
+ reportResultWatcherWarning(state, `Failed to mark subagent result notification delivered for '${resultPath}'; will retry`, error);
2417
2566
  scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
2418
2567
  return;
2419
2568
  }
@@ -2439,7 +2588,7 @@ ${baseOutput}` : ""}` : output;
2439
2588
  } : {}
2440
2589
  });
2441
2590
  } catch (error) {
2442
- console.error(`Completion observer failed for '${resultPath}':`, error);
2591
+ reportResultWatcherWarning(state, `Completion observer failed for '${resultPath}'`, error);
2443
2592
  }
2444
2593
  if (!observerSucceeded) {
2445
2594
  scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
@@ -2453,9 +2602,9 @@ ${baseOutput}` : ""}` : output;
2453
2602
  removeDeliveredResult(file, triggerTurn, read);
2454
2603
  } catch (error) {
2455
2604
  if (isAccessDenied(error)) {
2456
- console.error(`Failed to process subagent result file '${resultPath}'; will retry:`, error);
2605
+ reportResultWatcherWarning(state, `Failed to process subagent result file '${resultPath}'; will retry`, error);
2457
2606
  scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
2458
- } else if (!isNotFound2(error)) console.error(`Failed to process subagent result file '${resultPath}':`, error);
2607
+ } else if (!isNotFound2(error)) reportResultWatcherWarning(state, `Failed to process subagent result file '${resultPath}'`, error);
2459
2608
  } finally {
2460
2609
  processing.delete(file);
2461
2610
  if (rereadReplacedPayload) scheduleResult(file, triggerTurn);
@@ -2475,7 +2624,7 @@ ${baseOutput}` : ""}` : output;
2475
2624
  const resultScanLogging = deps.resultScanLogging ?? "activity";
2476
2625
  if (resultScanLogging === "off") return;
2477
2626
  if (resultScanLogging === "activity" && stats.files === 0 && stats.scheduled === 0) return;
2478
- console.error(`Subagent result scan inspected ${stats.files} indexed result file(s), scheduled ${stats.scheduled} in ${elapsed}ms (${resultsDir}).`);
2627
+ reportSessionWarning(state, `Subagent result scan inspected ${stats.files} indexed result file(s), scheduled ${stats.scheduled} in ${elapsed}ms (${resultsDir}).`, "slow-result-scan");
2479
2628
  };
2480
2629
  const indexedResultCandidates = (observed) => {
2481
2630
  const files = /* @__PURE__ */ new Set();
@@ -2503,10 +2652,27 @@ ${baseOutput}` : ""}` : output;
2503
2652
  }
2504
2653
  logScanStats(stats);
2505
2654
  } catch (error) {
2506
- if (!isNotFound2(error)) console.error(`Failed to scan subagent result index in '${resultsDir}':`, error);
2655
+ if (!isNotFound2(error)) reportResultWatcherWarning(state, `Failed to scan subagent result index in '${resultsDir}'`, error);
2507
2656
  }
2508
2657
  return files;
2509
2658
  };
2659
+ const hasPendingResults = () => eligibleResultFiles().some((file) => {
2660
+ const payloadPath = resultPayloadPath(file);
2661
+ if (!payloadPath) return false;
2662
+ let raw;
2663
+ try {
2664
+ raw = fsApi.readFileSync(payloadPath, "utf-8");
2665
+ } catch (error) {
2666
+ return !isNotFound2(error);
2667
+ }
2668
+ const identity = resultFileIdentity(raw, file);
2669
+ if (!identity.sessionId || !ownsResult(identity.sessionId, deliveryOwnerId(identity.sessionId, identity.completionOwnerId, identity.completionOwnerProcess, identity.parentWorkflowRunId))) return false;
2670
+ try {
2671
+ return !hasDeliveredNotification(parseResult(raw));
2672
+ } catch {
2673
+ return true;
2674
+ }
2675
+ });
2510
2676
  const primeExistingResults = (options = {}) => {
2511
2677
  const triggerTurn = options.triggerTurn !== false;
2512
2678
  for (const file of eligibleResultFiles()) scheduleResult(file, triggerTurn);
@@ -2534,7 +2700,7 @@ ${baseOutput}` : ""}` : output;
2534
2700
  try {
2535
2701
  return deps.hasDeliveryDemand?.() === true;
2536
2702
  } catch (error) {
2537
- console.error("Failed to inspect subagent result delivery demand:", error);
2703
+ reportResultWatcherWarning(state, "Failed to inspect subagent result delivery demand", error);
2538
2704
  return false;
2539
2705
  }
2540
2706
  };
@@ -2558,7 +2724,7 @@ ${baseOutput}` : ""}` : output;
2558
2724
  state.watcher = null;
2559
2725
  clearResultScan();
2560
2726
  if (state.watcherRestartTimer) return;
2561
- console.error(`Subagent result watcher for '${resultsDir}' fell back to polling because native fs.watch is unavailable (${errorCode(reason) ?? "unknown error"}).`);
2727
+ reportResultWatcherWarning(state, `Subagent result watcher for '${resultsDir}' fell back to polling because native fs.watch is unavailable (${errorCode(reason) ?? "unknown error"}).`, void 0, `result-poll-fallback:${resultsDir}`);
2562
2728
  primeExistingResults();
2563
2729
  state.watcherRestartTimer = timers.setInterval(primeExistingResults, POLL_INTERVAL_MS);
2564
2730
  state.watcherRestartTimer.unref?.();
@@ -2573,7 +2739,7 @@ ${baseOutput}` : ""}` : output;
2573
2739
  startResultWatcher();
2574
2740
  } catch (error) {
2575
2741
  if (shouldPoll(error)) return startPolling(error);
2576
- console.error(`Failed to restart subagent result watcher for '${resultsDir}':`, error);
2742
+ reportResultWatcherWarning(state, `Failed to restart subagent result watcher for '${resultsDir}'`, error);
2577
2743
  scheduleRestart();
2578
2744
  }
2579
2745
  }, WATCHER_RESTART_DELAY_MS);
@@ -2612,7 +2778,7 @@ ${baseOutput}` : ""}` : output;
2612
2778
  });
2613
2779
  state.watcher.on("error", (error) => {
2614
2780
  if (shouldPoll(error)) return startPolling(error);
2615
- console.error(`Subagent result watcher failed for '${resultsDir}':`, error);
2781
+ reportResultWatcherWarning(state, `Subagent result watcher failed for '${resultsDir}'`, error);
2616
2782
  state.watcher?.close();
2617
2783
  state.watcher = null;
2618
2784
  scheduleRestart();
@@ -2622,7 +2788,7 @@ ${baseOutput}` : ""}` : output;
2622
2788
  resultScanTimer.unref?.();
2623
2789
  } catch (error) {
2624
2790
  if (shouldPoll(error)) return startPolling(error);
2625
- console.error(`Failed to start subagent result watcher for '${resultsDir}':`, error);
2791
+ reportResultWatcherWarning(state, `Failed to start subagent result watcher for '${resultsDir}'`, error);
2626
2792
  state.watcher = null;
2627
2793
  scheduleRestart();
2628
2794
  }
@@ -2646,7 +2812,7 @@ ${baseOutput}` : ""}` : output;
2646
2812
  processing.clear();
2647
2813
  identityCache.clear();
2648
2814
  };
2649
- return { startResultWatcher, transitionResultDelivery, primeExistingResults, deliverPendingResults, stopResultWatcher, refreshResultDelivery: () => {
2815
+ return { startResultWatcher, transitionResultDelivery, primeExistingResults, deliverPendingResults, hasPendingResults, stopResultWatcher, refreshResultDelivery: () => {
2650
2816
  primeExistingResults();
2651
2817
  startDemandPolling();
2652
2818
  } };
@@ -4057,9 +4223,20 @@ function detailsFromSessionEntry(entry) {
4057
4223
  }
4058
4224
  if (record.type !== "message" || !record.message || typeof record.message !== "object") return void 0;
4059
4225
  const message2 = record.message;
4060
- if (message2.role !== "toolResult" || message2.toolName !== "subagent" && message2.toolName !== "bg_wait") return void 0;
4226
+ if (message2.role !== "toolResult" || message2.toolName !== "subagent" && message2.toolName !== waitToolName() && message2.toolName !== DEFAULT_WAIT_TOOL_NAME) return void 0;
4061
4227
  return isSubagentDetails(message2.details) ? message2.details : void 0;
4062
4228
  }
4229
+ function notifiedAsyncRuns(entry) {
4230
+ if (!entry || typeof entry !== "object") return [];
4231
+ const record = entry;
4232
+ if (record.type !== "custom_message" || record.customType !== "subagent-notify") return [];
4233
+ const runs = record.details?.runs;
4234
+ if (!Array.isArray(runs)) return [];
4235
+ return runs.flatMap((run) => (
4236
+ // A detached foreground task keeps no async status directory to read usage from.
4237
+ run && typeof run.runId === "string" && run.source !== "foreground" ? [{ runId: run.runId, workflow: run.workflowRunId === run.runId }] : []
4238
+ ));
4239
+ }
4063
4240
  function metadataUsage(artifactsDirs, input, indexes = [0, void 0]) {
4064
4241
  if (!/^[A-Za-z0-9._-]+$/.test(input.runId)) return void 0;
4065
4242
  for (const artifactsDir of artifactsDirs) {
@@ -4108,6 +4285,7 @@ function collectSubagentCost(ctx, state) {
4108
4285
  const message2 = entry.type === "message" ? entry.message : void 0;
4109
4286
  const parentUsage = assistantUsageFromMessage(message2) ?? compactionUsageFromEntry(entry);
4110
4287
  if (parentUsage) addUsage(parent, parentUsage);
4288
+ for (const run of notifiedAsyncRuns(entry)) (run.workflow ? workflowRunIds : asyncRunIds).add(run.runId);
4111
4289
  const details = detailsFromSessionEntry(entry);
4112
4290
  if (!details) continue;
4113
4291
  if (details.mode === "workflow" && details.runId && details.asyncId) workflowRunIds.add(details.runId);
@@ -5182,7 +5360,7 @@ function registerSlashCommands(pi, state, options = {}) {
5182
5360
  }
5183
5361
  fleetOpen = true;
5184
5362
  try {
5185
- const { openSubagentFleet } = await import("./chunk-IPGZMQXV.js");
5363
+ const { openSubagentFleet } = await import("./chunk-O7CPL6H4.js");
5186
5364
  await openSubagentFleet(ctx, state, { asyncDirRoot: DIRS.async, inspectorPlugins: () => getInspectorPlugins(pi), resultsDir: DIRS.results, fleetKeybindings: options.fleetKeybindings });
5187
5365
  } finally {
5188
5366
  fleetOpen = false;
@@ -5309,7 +5487,7 @@ ${finalTask}`;
5309
5487
  ctx.ui.notify(`Foreground run ${control.runId} is not currently detachable.`, "info");
5310
5488
  return;
5311
5489
  }
5312
- sendSlashText(pi, `Detached foreground run ${control.runId} without terminating its child. Use subagent({ action: "status", id: ${JSON.stringify(control.runId)} }) or bg_wait({ id: ${JSON.stringify(control.runId)} }) to recover the eventual result. This does not daemonize the process or guarantee survival across Pi reload/restart.`);
5490
+ sendSlashText(pi, `Detached foreground run ${control.runId} without terminating its child. Use subagent({ action: "status", id: ${JSON.stringify(control.runId)} }) or ${waitToolName()}({ id: ${JSON.stringify(control.runId)} }) to recover the eventual result. This does not daemonize the process or guarantee survival across Pi reload/restart.`);
5313
5491
  };
5314
5492
  pi.registerCommand("subagents-detach", {
5315
5493
  description: "Detach the active foreground single-subagent run without terminating it",
@@ -6764,8 +6942,8 @@ function supervisorReminderHeadline(details, status) {
6764
6942
  return [`${ids.length} supervisor ${ids.length === 1 ? "request" : "requests"} `, { status }];
6765
6943
  }
6766
6944
  function waitSubscriptionHeadline(details) {
6767
- if (!isRecord3(details) || typeof details.runId !== "string" || typeof details.outcome !== "string") return ["bg_wait fired"];
6768
- return [`bg_wait: run ${details.runId} `, { status: details.outcome }];
6945
+ if (!isRecord3(details) || typeof details.runId !== "string" || typeof details.outcome !== "string") return [`${waitToolName()} fired`];
6946
+ return [`${waitToolName()}: run ${details.runId} `, { status: details.outcome }];
6769
6947
  }
6770
6948
  function workflowChildHeadline(message2) {
6771
6949
  const { details } = message2;
@@ -7777,16 +7955,19 @@ function registerSubagentRpcBridge(options) {
7777
7955
  import { Type } from "typebox";
7778
7956
  var LOADER_NAME = "subagents_enable";
7779
7957
  var SUBAGENT_NAME = "subagent";
7780
- var WAIT_NAME = "bg_wait";
7781
- var UNLOAD_SENTINELS = /* @__PURE__ */ new Set([LOADER_NAME, SUBAGENT_NAME, WAIT_NAME]);
7958
+ var isUnloadSentinel = (name) => name === LOADER_NAME || name === SUBAGENT_NAME || name === waitToolName();
7959
+ function isOwnWaitDefinition(tool) {
7960
+ const properties = tool.parameters?.properties;
7961
+ return typeof properties === "object" && properties !== null && Object.hasOwn(properties, "nonBlocking") && Object.hasOwn(properties, "stopOnAttention");
7962
+ }
7782
7963
  function hasNativeToolSelection(messages) {
7783
7964
  return messages.some((message2) => message2.role === "system" && (Object.hasOwn(message2, "toolsAdded") || Object.hasOwn(message2, "toolsRemoved")));
7784
7965
  }
7785
7966
  function setSelection(pi, includeSubagent, includeLoader, includeWait, restore = [], keepParentSupervisor = false) {
7786
- const next = [...pi.getActiveTools(), ...restore].filter((name) => (includeSubagent || name !== SUBAGENT_NAME && name !== CONTACT_SUPERVISOR_TOOL_NAME && (keepParentSupervisor || name !== NATIVE_SUPERVISOR_TOOL_NAME)) && (includeLoader || name !== LOADER_NAME) && (includeWait || name !== WAIT_NAME));
7967
+ const next = [...pi.getActiveTools(), ...restore].filter((name) => (includeSubagent || name !== SUBAGENT_NAME && name !== CONTACT_SUPERVISOR_TOOL_NAME && (keepParentSupervisor || name !== NATIVE_SUPERVISOR_TOOL_NAME)) && (includeLoader || name !== LOADER_NAME) && (includeWait || name !== waitToolName()));
7787
7968
  if (includeSubagent) next.push(SUBAGENT_NAME, CONTACT_SUPERVISOR_TOOL_NAME, NATIVE_SUPERVISOR_TOOL_NAME);
7788
7969
  if (includeLoader) next.push(LOADER_NAME);
7789
- if (includeWait) next.push(WAIT_NAME);
7970
+ if (includeWait) next.push(waitToolName());
7790
7971
  pi.setActiveTools([...new Set(next)]);
7791
7972
  }
7792
7973
  function addsToolsWithoutCheckpoint(model) {
@@ -7816,12 +7997,13 @@ function applyRecordedSelection(pi, ctx, mode, replyOwed) {
7816
7997
  const unloadedNames = /* @__PURE__ */ new Set();
7817
7998
  const declaredSentinels = /* @__PURE__ */ new Set();
7818
7999
  const evidenced = /* @__PURE__ */ new Set();
8000
+ let legacyWaitIsOwn = false;
7819
8001
  for (const message2 of messages) {
7820
8002
  if (message2.role !== "system") continue;
7821
- const removedSentinels = (message2.toolsRemoved ?? []).filter((tool) => UNLOAD_SENTINELS.has(tool.name));
8003
+ const removedSentinels = (message2.toolsRemoved ?? []).filter((tool) => isUnloadSentinel(tool.name));
7822
8004
  const allDeclared = removedSentinels.every((tool) => declaredSentinels.has(tool.name));
7823
8005
  for (const tool of message2.toolsRemoved ?? []) declaredSentinels.delete(tool.name);
7824
- for (const tool of message2.toolsAdded ?? []) if (UNLOAD_SENTINELS.has(tool.name)) declaredSentinels.add(tool.name);
8006
+ for (const tool of message2.toolsAdded ?? []) if (isUnloadSentinel(tool.name)) declaredSentinels.add(tool.name);
7825
8007
  const unloaded = removedSentinels.length > 0 && allDeclared && declaredSentinels.size === 0;
7826
8008
  for (const tool of message2.toolsRemoved ?? []) {
7827
8009
  if (unloaded) unloadedNames.add(tool.name);
@@ -7833,19 +8015,21 @@ function applyRecordedSelection(pi, ctx, mode, replyOwed) {
7833
8015
  for (const tool of message2.toolsAdded ?? []) {
7834
8016
  recorded.add(tool.name);
7835
8017
  evidenced.add(tool.name);
8018
+ if (tool.name === DEFAULT_WAIT_TOOL_NAME) legacyWaitIsOwn = isOwnWaitDefinition(tool);
7836
8019
  }
7837
8020
  }
7838
8021
  const fresh = lost && !evidenced.has(LOADER_NAME) && !evidenced.has(SUBAGENT_NAME);
7839
8022
  const startsEager = fresh && mode === "auto" && !addsToolsWithoutCheckpoint(ctx.model);
7840
8023
  const loaderSelected = mode === "dynamic" || recorded.has(LOADER_NAME) || fresh && !startsEager;
8024
+ const waitRecord = waitToolName() !== DEFAULT_WAIT_TOOL_NAME && !evidenced.has(waitToolName()) && legacyWaitIsOwn ? DEFAULT_WAIT_TOOL_NAME : waitToolName();
7841
8025
  const source = unloadedNames.size > 0 ? available.find((tool) => tool.name === LOADER_NAME)?.sourceInfo.path : void 0;
7842
8026
  const restore = source === void 0 ? [] : available.filter((tool) => unloadedNames.has(tool.name) && recorded.has(tool.name) && tool.sourceInfo.path === source).map((tool) => tool.name);
7843
- setSelection(pi, recorded.has(SUBAGENT_NAME) || startsEager, loaderSelected, recorded.has(WAIT_NAME) || !evidenced.has(WAIT_NAME) && startsEager, replyOwed ? [...restore, NATIVE_SUPERVISOR_TOOL_NAME] : restore, replyOwed || recorded.has(NATIVE_SUPERVISOR_TOOL_NAME));
8027
+ setSelection(pi, recorded.has(SUBAGENT_NAME) || startsEager, loaderSelected, recorded.has(waitRecord) || !evidenced.has(waitRecord) && startsEager, replyOwed ? [...restore, NATIVE_SUPERVISOR_TOOL_NAME] : restore, replyOwed || recorded.has(NATIVE_SUPERVISOR_TOOL_NAME));
7844
8028
  return loaderSelected;
7845
8029
  }
7846
8030
  const eager = mode === "auto" && messages.length === 0 && !addsToolsWithoutCheckpoint(ctx.model);
7847
8031
  const kept = (name) => eager || messages.length > 0 && pi.getActiveTools().includes(name);
7848
- setSelection(pi, kept(SUBAGENT_NAME), !eager, kept(WAIT_NAME), replyOwed ? [NATIVE_SUPERVISOR_TOOL_NAME] : [], replyOwed || messages.length > 0);
8032
+ setSelection(pi, kept(SUBAGENT_NAME), !eager, kept(waitToolName()), replyOwed ? [NATIVE_SUPERVISOR_TOOL_NAME] : [], replyOwed || messages.length > 0);
7849
8033
  return !eager;
7850
8034
  }
7851
8035
  function registerSubagentToolActivation(pi, options) {
@@ -7900,8 +8084,8 @@ ${advertised}` : ""}` }],
7900
8084
  pi.on("before_agent_start", (event) => {
7901
8085
  const available = pi.getAllTools();
7902
8086
  if (!Array.isArray(available) || !available.some((tool) => tool.name === LOADER_NAME)) return;
7903
- const providedWait = available.some((tool) => tool.name === WAIT_NAME) && listBackgroundWorkProviders().length > 0;
7904
- const names = [...loaderSelected ? [LOADER_NAME] : [], ...providedWait ? [WAIT_NAME] : []];
8087
+ const providedWait = available.some((tool) => tool.name === waitToolName()) && listBackgroundWorkProviders().length > 0;
8088
+ const names = [...loaderSelected ? [LOADER_NAME] : [], ...providedWait ? [waitToolName()] : []];
7905
8089
  if (names.length === 0) return;
7906
8090
  const selectedTools = event.systemPromptOptions.selectedTools ??= [...pi.getActiveTools()];
7907
8091
  for (const name of names) if (!selectedTools.includes(name)) selectedTools.push(name);
@@ -8071,6 +8255,11 @@ function withMandatorySafetyGuidance(description) {
8071
8255
  ${SUBAGENT_SAFETY_GUIDANCE}` : SUBAGENT_SAFETY_GUIDANCE;
8072
8256
  }
8073
8257
  function buildSubagentToolDescription(config = {}, options) {
8258
+ const description = describeSubagentTool(config, options);
8259
+ const name = waitToolName();
8260
+ return name === DEFAULT_WAIT_TOOL_NAME ? description : description.replace(/\bbg_wait\b/g, name);
8261
+ }
8262
+ function describeSubagentTool(config, options) {
8074
8263
  const on = options?.disabledFeatures ? featureText(options.disabledFeatures) : allEnabled;
8075
8264
  if (config.toolDescriptionMode === void 0) return essentials(on);
8076
8265
  const mode = resolveToolDescriptionMode(config, options);
@@ -8394,9 +8583,9 @@ function getRuntimeRegistry() {
8394
8583
  globalStore[RUNTIME_REGISTRY_STORE_KEY] = registry;
8395
8584
  return registry;
8396
8585
  }
8397
- function logSlowPhase(label, startedAt) {
8586
+ function logSlowPhase(state, label, startedAt) {
8398
8587
  const elapsed = Date.now() - startedAt;
8399
- if (elapsed >= SLOW_RELOAD_PHASE_MS) console.error(`Subagent reload phase '${label}' took ${elapsed}ms.`);
8588
+ if (elapsed >= SLOW_RELOAD_PHASE_MS) reportSessionWarning(state, `Subagent reload phase '${label}' took ${elapsed}ms.`, `slow-reload-phase:${label}`);
8400
8589
  }
8401
8590
  function formatWorkflowPreflightCall(input) {
8402
8591
  if (input === void 0) return "";
@@ -8493,6 +8682,7 @@ function registerSubagentExtension(pi) {
8493
8682
  const config = loadConfig();
8494
8683
  setDeclarationPinning(pi, config.pinToolDeclarations !== false);
8495
8684
  const waitToolConfig = resolveWaitToolConfig(config.waitTool);
8685
+ setWaitToolName(waitToolConfig.name ?? DEFAULT_WAIT_TOOL_NAME);
8496
8686
  const asyncByDefault = resolveAsyncByDefault(config);
8497
8687
  const fleetViewEnabled = config.fleetView !== false;
8498
8688
  const slashCommandsEnabled = config.enableSlashCommands !== false;
@@ -8571,7 +8761,7 @@ function registerSubagentExtension(pi) {
8571
8761
  const ctx = withLastUiContext((current) => current);
8572
8762
  if (!ctx) return;
8573
8763
  try {
8574
- const { openSubagentFleet } = await import("./chunk-IPGZMQXV.js");
8764
+ const { openSubagentFleet } = await import("./chunk-O7CPL6H4.js");
8575
8765
  await openSubagentFleet(ctx, state, { initialKey: itemKey, asyncDirRoot: DIRS.async, resultsDir: DIRS.results, fleetKeybindings: config.fleetKeybindings, inspectorPlugins: () => getInspectorPlugins(pi) });
8576
8766
  } catch (error) {
8577
8767
  if (isStaleExtensionContextError(error)) {
@@ -8592,13 +8782,15 @@ function registerSubagentExtension(pi) {
8592
8782
  await waitForAdvertisement();
8593
8783
  return (await getExecutor()).executeScheduled(randomUUID3(), params, signal, ctx);
8594
8784
  },
8595
- resolveCapabilityCeiling: (sessionId) => resolveCurrentSubagentCapabilityCeiling(sessionId)
8785
+ resolveCapabilityCeiling: (sessionId) => resolveCurrentSubagentCapabilityCeiling(sessionId),
8786
+ reportWarning: (message2, key) => reportSessionWarning(state, message2, key)
8596
8787
  });
8597
8788
  let refreshResultDelivery = () => {
8598
8789
  };
8599
8790
  let advertisedAgents = [];
8600
8791
  let advertisedContext;
8601
8792
  let advertisementGeneration = 0;
8793
+ let advertisementLookup;
8602
8794
  let globalRoot = null;
8603
8795
  let advertisementReady = Promise.resolve();
8604
8796
  let notifySessionChange = () => {
@@ -8620,6 +8812,8 @@ function registerSubagentExtension(pi) {
8620
8812
  };
8621
8813
  const beginAdvertisement = (ctx) => {
8622
8814
  const generation = ++advertisementGeneration;
8815
+ advertisementLookup?.abort();
8816
+ advertisementLookup = new AbortController();
8623
8817
  notifySessionChange();
8624
8818
  sessionChanged = new Promise((resolve6) => {
8625
8819
  notifySessionChange = resolve6;
@@ -8627,7 +8821,7 @@ function registerSubagentExtension(pi) {
8627
8821
  advertisedAgents = [];
8628
8822
  advertisedContext = { cwd: ctx.cwd, model: ctx.model, projectTrusted: typeof ctx.isProjectTrusted === "function" ? ctx.isProjectTrusted() : void 0 };
8629
8823
  globalRoot = null;
8630
- advertisementReady = resolveGlobalNpmRoot().then((root) => {
8824
+ advertisementReady = resolveGlobalNpmRoot({ signal: advertisementLookup.signal }).then((root) => {
8631
8825
  if (generation !== advertisementGeneration) return;
8632
8826
  globalRoot = root;
8633
8827
  refreshAdvertisedAgents();
@@ -8702,6 +8896,15 @@ function registerSubagentExtension(pi) {
8702
8896
  }
8703
8897
  );
8704
8898
  const { startResultWatcher, transitionResultDelivery, primeExistingResults, stopResultWatcher } = resultWatcher;
8899
+ const sessionSwitchGuard = createSessionSwitchGuard({
8900
+ state,
8901
+ asyncDirRoot: DIRS.async,
8902
+ resultsDir: DIRS.results,
8903
+ hasPendingResults: () => owedResultRunIds.size > 0 || completionNotifier.hasPendingDelivery() || resultWatcher.hasPendingResults(),
8904
+ hasPendingSupervisorRequest: supervisorChannel.hasPendingRequests
8905
+ });
8906
+ pi.on("session_before_switch", (event, ctx) => sessionSwitchGuard.beforeSwitch(event.reason, ctx));
8907
+ pi.on("session_before_fork", (_event, ctx) => sessionSwitchGuard.beforeSwitch("fork", ctx));
8705
8908
  refreshResultDelivery = resultWatcher.refreshResultDelivery;
8706
8909
  const asyncRetentionAbort = new AbortController();
8707
8910
  let asyncRetentionTimer;
@@ -8767,7 +8970,7 @@ function registerSubagentExtension(pi) {
8767
8970
  let executor;
8768
8971
  let executorPromise;
8769
8972
  let executorModulePromise;
8770
- const loadExecutorModule = () => executorModulePromise ??= import("./chunk-UUP372DR.js");
8973
+ const loadExecutorModule = () => executorModulePromise ??= import("./chunk-JWYG26RE.js");
8771
8974
  const getExecutor = () => {
8772
8975
  executorPromise ??= loadExecutorModule().then(({ createSubagentExecutor }) => {
8773
8976
  executor = createSubagentExecutor(executorDeps);
@@ -8781,7 +8984,7 @@ function registerSubagentExtension(pi) {
8781
8984
  modulePreloadTimer = setTimeout(() => {
8782
8985
  loadExecutorModule().catch(() => {
8783
8986
  });
8784
- if (fleetViewEnabled) import("./chunk-IPGZMQXV.js").catch(() => {
8987
+ if (fleetViewEnabled) import("./chunk-O7CPL6H4.js").catch(() => {
8785
8988
  });
8786
8989
  }, MODULE_PRELOAD_DELAY_MS);
8787
8990
  modulePreloadTimer.unref?.();
@@ -8941,6 +9144,7 @@ ${close}` }]
8941
9144
  };
8942
9145
  registerPinnedTool(pi, tool);
8943
9146
  registerPinnedTool(pi, topLevelSupervisorTool());
9147
+ registerSubagentLaunchTool(pi);
8944
9148
  pi.on("before_agent_start", async (event, ctx) => {
8945
9149
  await waitForAdvertisement();
8946
9150
  const sessionId = state.currentSessionId ?? resolveCurrentSessionId(ctx.sessionManager);
@@ -9082,11 +9286,12 @@ ${close}` }]
9082
9286
  { liveWorkflowRunIds: new Set(state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(config.capacity?.abandonedSlotReleaseAfterMs) }
9083
9287
  );
9084
9288
  };
9085
- const resetSessionState = (ctx, recovering, previousSessionFile) => {
9289
+ const resetSessionState = (ctx, recovering, startup, previousSessionFile) => {
9086
9290
  state.widgetsSuspended = false;
9087
9291
  state.baseCwd = ctx.cwd;
9088
9292
  goalTurnId = 0;
9089
9293
  state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
9294
+ recordSessionStart(state.currentSessionId, startup);
9090
9295
  if (previousSessionFile) recordSessionReplacement(state.currentSessionId, previousSessionFile);
9091
9296
  state.supervisorOwnerSessionId = ctx.sessionManager.getSessionId() || null;
9092
9297
  transitionResultDelivery();
@@ -9113,10 +9318,10 @@ ${close}` }]
9113
9318
  state.lastUiContext = ctx;
9114
9319
  let phaseStartedAt = Date.now();
9115
9320
  refreshActiveAsyncCapacity();
9116
- logSlowPhase("active-capacity", phaseStartedAt);
9321
+ logSlowPhase(state, "active-capacity", phaseStartedAt);
9117
9322
  phaseStartedAt = Date.now();
9118
9323
  cleanupSessionArtifacts(ctx);
9119
- logSlowPhase("session-artifact-cleanup", phaseStartedAt);
9324
+ logSlowPhase(state, "session-artifact-cleanup", phaseStartedAt);
9120
9325
  state.foregroundControls.clear();
9121
9326
  retainedNestedRouteTracker?.clear();
9122
9327
  retainedNestedRouteTracker = void 0;
@@ -9124,17 +9329,17 @@ ${close}` }]
9124
9329
  state.lastForegroundControlId = null;
9125
9330
  phaseStartedAt = Date.now();
9126
9331
  resetJobs(ctx);
9127
- logSlowPhase("reset-jobs", phaseStartedAt);
9332
+ logSlowPhase(state, "reset-jobs", phaseStartedAt);
9128
9333
  phaseStartedAt = Date.now();
9129
9334
  const interruptedElsewhere = ctx.hasUI ? createInterruptedElsewhereCollector({ currentSessionId: state.currentSessionId, cwd: ctx.cwd, now: Date.now() }) : void 0;
9130
9335
  restoreForegroundRunHistory(state, { resultsDir: DIRS.results, observeForeign: interruptedElsewhere?.observeForegroundRun });
9131
- logSlowPhase("foreground-history", phaseStartedAt);
9336
+ logSlowPhase(state, "foreground-history", phaseStartedAt);
9132
9337
  phaseStartedAt = Date.now();
9133
9338
  restoreActiveJobs(ctx, interruptedElsewhere?.observeStatus);
9134
- logSlowPhase("active-job-restore", phaseStartedAt);
9339
+ logSlowPhase(state, "active-job-restore", phaseStartedAt);
9135
9340
  phaseStartedAt = Date.now();
9136
9341
  if (interruptedElsewhere) for (const line of interruptedElsewhere.lines()) ctx.ui.notify(line, "info");
9137
- logSlowPhase("cross-session-notice", phaseStartedAt);
9342
+ logSlowPhase(state, "cross-session-notice", phaseStartedAt);
9138
9343
  phaseStartedAt = Date.now();
9139
9344
  cancelPendingWorkflowAutoResumes((entry) => entry.owner === autoResumeOwner);
9140
9345
  if (recovering && ctx.hasUI && config.autoResume !== false) {
@@ -9142,22 +9347,22 @@ ${close}` }]
9142
9347
  void launchWorkflowAutoResume(entry, ctx);
9143
9348
  }
9144
9349
  }
9145
- logSlowPhase("workflow-auto-resume", phaseStartedAt);
9350
+ logSlowPhase(state, "workflow-auto-resume", phaseStartedAt);
9146
9351
  phaseStartedAt = Date.now();
9147
9352
  scheduledRunManager.bindSession(ctx);
9148
- logSlowPhase("scheduled-runs", phaseStartedAt);
9353
+ logSlowPhase(state, "scheduled-runs", phaseStartedAt);
9149
9354
  phaseStartedAt = Date.now();
9150
9355
  restoreSlashFinalSnapshots(ctx.sessionManager.getEntries());
9151
- logSlowPhase("slash-snapshots", phaseStartedAt);
9356
+ logSlowPhase(state, "slash-snapshots", phaseStartedAt);
9152
9357
  phaseStartedAt = Date.now();
9153
9358
  waitSubscriptionManager.restore();
9154
- logSlowPhase("wait-subscriptions", phaseStartedAt);
9359
+ logSlowPhase(state, "wait-subscriptions", phaseStartedAt);
9155
9360
  phaseStartedAt = Date.now();
9156
9361
  startResultWatcher();
9157
- logSlowPhase("result-watcher-start", phaseStartedAt);
9362
+ logSlowPhase(state, "result-watcher-start", phaseStartedAt);
9158
9363
  phaseStartedAt = Date.now();
9159
9364
  primeExistingResults({ triggerTurn: !recovering });
9160
- logSlowPhase("result-prime", phaseStartedAt);
9365
+ logSlowPhase(state, "result-prime", phaseStartedAt);
9161
9366
  fleetStatus?.setContext(ctx);
9162
9367
  };
9163
9368
  let runtimeCleaned = false;
@@ -9167,6 +9372,12 @@ ${close}` }]
9167
9372
  cleanup(shutdownReason) {
9168
9373
  if (runtimeCleaned) return;
9169
9374
  runtimeCleaned = true;
9375
+ sessionSwitchGuard.dispose();
9376
+ ++advertisementGeneration;
9377
+ advertisementLookup?.abort();
9378
+ advertisedAgents = [];
9379
+ advertisedContext = void 0;
9380
+ notifySessionChange();
9170
9381
  cancelPendingWorkflowAutoResumes((entry) => entry.owner === autoResumeOwner);
9171
9382
  programStatus.dispose(shutdownReason);
9172
9383
  releaseHostSessionLiveness();
@@ -9317,7 +9528,7 @@ ${close}` }]
9317
9528
  startSessionMaintenance();
9318
9529
  scheduleModulePreload();
9319
9530
  const recovering = event.reason === "startup" || event.reason === "reload" || event.reason === "resume";
9320
- resetSessionState(ctx, recovering, event.previousSessionFile);
9531
+ resetSessionState(ctx, recovering, event.reason === "startup", event.previousSessionFile);
9321
9532
  releaseHostSessionLiveness();
9322
9533
  const sessionId = ctx.sessionManager.getSessionId();
9323
9534
  const sessionFile = ctx.sessionManager.getSessionFile();
@@ -9342,6 +9553,7 @@ ${close}` }]
9342
9553
  supervisorChannel.activateTransport();
9343
9554
  });
9344
9555
  pi.on("session_shutdown", async (event) => {
9556
+ sessionSwitchGuard.sessionShutdown(event);
9345
9557
  cancelCompactionResume();
9346
9558
  completionNotifier.sessionShutdown(event?.reason);
9347
9559
  parentWake.sessionShutdown(event?.reason);