@xzzpig/pi-subagents 0.24.1 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (263) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/bundle/agent-management.js +4 -4
  3. package/bundle/agents.js +3 -3
  4. package/bundle/child-tool-plan.js +2 -2
  5. package/bundle/chunk-34TUUBRN.js +1107 -0
  6. package/bundle/{chunk-SW2VMNIU.js → chunk-5OD3OWTE.js} +2 -2
  7. package/bundle/{chunk-ZWXU5SPQ.js → chunk-5YEOWNSD.js} +371 -135
  8. package/bundle/{chunk-EUPJB4S7.js → chunk-5Z7JAORM.js} +196 -1219
  9. package/bundle/{chunk-LCDJWBVM.js → chunk-66JNFRFS.js} +1 -1
  10. package/bundle/{chunk-6BJUEES3.js → chunk-6MNRKUHY.js} +23 -12
  11. package/bundle/{chunk-ED55MIC2.js → chunk-CGFF4WA3.js} +42 -19
  12. package/bundle/{chunk-TMHVDPYW.js → chunk-DLVPMML3.js} +263 -154
  13. package/bundle/chunk-HXRB42AF.js +108 -0
  14. package/bundle/{chunk-355ECEP2.js → chunk-IH7LQVEE.js} +29 -14
  15. package/bundle/{chunk-SLNMBXLL.js → chunk-IJWITCC6.js} +411 -249
  16. package/bundle/{chunk-RU522D5W.js → chunk-IKFKH5EL.js} +369 -50
  17. package/bundle/{chunk-Z6TFJ6BR.js → chunk-INWSUNI6.js} +1 -1
  18. package/bundle/{chunk-JEA2ZKUA.js → chunk-IUDEI6FJ.js} +35 -200
  19. package/bundle/{chunk-WW76JRIX.js → chunk-JAXVBXGF.js} +1 -1
  20. package/bundle/{chunk-ICNYIALB.js → chunk-JH5H4CYJ.js} +784 -474
  21. package/bundle/{chunk-35GII5EF.js → chunk-JWFLPSTP.js} +41 -117
  22. package/bundle/{chunk-LMGQAJ3O.js → chunk-KCJFGKVK.js} +350 -123
  23. package/bundle/{chunk-RB4GELQA.js → chunk-LPJEKHOY.js} +1 -1
  24. package/bundle/chunk-LYKG4FKH.js +523 -0
  25. package/bundle/{chunk-X6LOM3Z4.js → chunk-LZ3HBDTR.js} +161 -78
  26. package/bundle/{chunk-FG6SQJAR.js → chunk-OGPOCGWX.js} +24 -6
  27. package/bundle/{chunk-Y6H2G6KX.js → chunk-OSVXFWPG.js} +67 -30
  28. package/bundle/{chunk-FJWI64H7.js → chunk-RMSABUN3.js} +27 -13
  29. package/bundle/{chunk-H36HBZB2.js → chunk-SJPABBZG.js} +2 -2
  30. package/bundle/{chunk-3U633XDZ.js → chunk-U3ZDUUTM.js} +11 -3
  31. package/bundle/{chunk-LVWU2HOO.js → chunk-ULGMXABL.js} +16 -7
  32. package/bundle/{chunk-WPW4V6HM.js → chunk-W7ZA6TYD.js} +2 -2
  33. package/bundle/{chunk-V2KFIGFH.js → chunk-XAC2XNAP.js} +503 -304
  34. package/bundle/{chunk-TGLFTQWJ.js → chunk-YWXILP5N.js} +5 -4
  35. package/bundle/control-channel.js +2 -2
  36. package/bundle/index.js +1 -1
  37. package/bundle/intercom-bridge.js +2 -2
  38. package/bundle/preflight.js +12 -10
  39. package/bundle/project-panes.js +3 -3
  40. package/bundle/workflow-resources.js +1 -1
  41. package/docs/agents.md +27 -6
  42. package/docs/configuration.md +20 -8
  43. package/docs/extension-api.md +18 -1
  44. package/docs/models.md +6 -2
  45. package/docs/observability.md +2 -0
  46. package/docs/tool-reference.md +7 -1
  47. package/docs/workflows.md +30 -2
  48. package/node_modules/@xzzpig/pi-components/CHANGELOG.md +12 -0
  49. package/node_modules/@xzzpig/pi-components/README.md +94 -0
  50. package/node_modules/@xzzpig/pi-components/dist/src/transcript-presenter.d.ts +186 -0
  51. package/node_modules/@xzzpig/pi-components/dist/src/transcript-presenter.js +693 -0
  52. package/node_modules/@xzzpig/pi-components/package.json +5 -1
  53. package/package.json +4 -4
  54. package/skills/pi-subagents/SKILL.md +15 -6
  55. package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
  56. package/src/agents/agent-management.d.ts +1 -0
  57. package/src/agents/agent-management.js +46 -18
  58. package/src/agents/agent-memory.d.ts +1 -4
  59. package/src/agents/agent-memory.js +1 -4
  60. package/src/agents/agent-serializer.d.ts +2 -0
  61. package/src/agents/agent-serializer.js +1 -1
  62. package/src/agents/agents.d.ts +2 -3
  63. package/src/agents/agents.js +46 -20
  64. package/src/agents/frontmatter.js +1 -8
  65. package/src/agents/global-npm-root.d.ts +1 -0
  66. package/src/agents/global-npm-root.js +11 -3
  67. package/src/agents/skills.d.ts +0 -3
  68. package/src/agents/skills.js +0 -3
  69. package/src/api/preflight.d.ts +3 -1
  70. package/src/api/preflight.js +2 -0
  71. package/src/extension/config.d.ts +1 -0
  72. package/src/extension/config.js +13 -1
  73. package/src/extension/herdr-pi-bridge.js +10 -2
  74. package/src/extension/index.d.ts +0 -13
  75. package/src/extension/index.js +51 -37
  76. package/src/extension/public-execution.d.ts +1 -0
  77. package/src/extension/public-execution.js +4 -0
  78. package/src/extension/reply-workflow-script.js +24 -4
  79. package/src/extension/schemas.d.ts +12 -3
  80. package/src/extension/schemas.js +7 -3
  81. package/src/extension/session-switch.d.ts +25 -0
  82. package/src/extension/session-switch.js +138 -0
  83. package/src/extension/subagent-guide.d.ts +1 -1
  84. package/src/extension/subagent-guide.js +1 -1
  85. package/src/extension/subagent-launch-tool.d.ts +25 -0
  86. package/src/extension/subagent-launch-tool.js +48 -0
  87. package/src/extension/tool-activation.js +55 -15
  88. package/src/extension/tool-description.d.ts +1 -1
  89. package/src/extension/tool-description.js +14 -8
  90. package/src/inspectors/herdr/actions.d.ts +0 -1
  91. package/src/inspectors/herdr/actions.js +0 -1
  92. package/src/inspectors/session-roots-codec.d.ts +0 -1
  93. package/src/inspectors/session-roots-codec.js +0 -1
  94. package/src/inspectors/tmux/actions.d.ts +0 -1
  95. package/src/inspectors/tmux/actions.js +0 -1
  96. package/src/integrations/herdr-status.js +3 -8
  97. package/src/intercom/native-supervisor-channel.js +65 -9
  98. package/src/runs/background/async-execution.d.ts +7 -10
  99. package/src/runs/background/async-execution.js +66 -29
  100. package/src/runs/background/async-job-tracker.js +12 -0
  101. package/src/runs/background/async-resume.d.ts +2 -1
  102. package/src/runs/background/async-resume.js +114 -40
  103. package/src/runs/background/async-retention.d.ts +0 -2
  104. package/src/runs/background/async-retention.js +17 -6
  105. package/src/runs/background/async-status.d.ts +2 -0
  106. package/src/runs/background/async-status.js +4 -0
  107. package/src/runs/background/auto-drain.js +2 -1
  108. package/src/runs/background/boot-id.d.ts +1 -3
  109. package/src/runs/background/boot-id.js +1 -3
  110. package/src/runs/background/completion-batcher.d.ts +3 -4
  111. package/src/runs/background/completion-batcher.js +2 -3
  112. package/src/runs/background/control-channel.d.ts +0 -6
  113. package/src/runs/background/control-channel.js +0 -6
  114. package/src/runs/background/fleet-view.js +2 -3
  115. package/src/runs/background/notify.d.ts +0 -2
  116. package/src/runs/background/notify.js +0 -2
  117. package/src/runs/background/result-watcher.d.ts +1 -0
  118. package/src/runs/background/result-watcher.js +59 -29
  119. package/src/runs/background/resume-guidance.js +4 -2
  120. package/src/runs/background/retained-children.js +2 -1
  121. package/src/runs/background/run-child-session.d.ts +2 -3
  122. package/src/runs/background/run-child-session.js +5 -8
  123. package/src/runs/background/run-status.js +9 -7
  124. package/src/runs/background/runner-aliases.js +15 -0
  125. package/src/runs/background/scheduled-runs.d.ts +3 -1
  126. package/src/runs/background/scheduled-runs.js +13 -16
  127. package/src/runs/background/steering.d.ts +2 -11
  128. package/src/runs/background/steering.js +11 -6
  129. package/src/runs/background/subagent-runner.d.ts +2 -6
  130. package/src/runs/background/subagent-runner.js +88 -70
  131. package/src/runs/background/subagent-wait.js +12 -15
  132. package/src/runs/background/wait-config.d.ts +2 -0
  133. package/src/runs/background/wait-config.js +17 -3
  134. package/src/runs/background/wait-subscriptions.js +124 -12
  135. package/src/runs/background/wait-tool.js +4 -2
  136. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  137. package/src/runs/background/workflow-terminal-proof.js +0 -1
  138. package/src/runs/foreground/async-steering-action.js +24 -9
  139. package/src/runs/foreground/async-stop-action.d.ts +1 -1
  140. package/src/runs/foreground/async-stop-action.js +9 -1
  141. package/src/runs/foreground/execution.d.ts +0 -3
  142. package/src/runs/foreground/execution.js +56 -24
  143. package/src/runs/foreground/prompt-audit.js +1 -0
  144. package/src/runs/foreground/subagent-executor.d.ts +5 -10
  145. package/src/runs/foreground/subagent-executor.js +164 -49
  146. package/src/runs/shared/acceptance.js +69 -26
  147. package/src/runs/shared/async-status-projection.d.ts +2 -0
  148. package/src/runs/shared/async-status-projection.js +10 -0
  149. package/src/runs/shared/child-commands.js +15 -2
  150. package/src/runs/shared/child-hooks.d.ts +1 -7
  151. package/src/runs/shared/child-hooks.js +13 -5
  152. package/src/runs/shared/child-launch.js +6 -2
  153. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  154. package/src/runs/shared/child-session.d.ts +6 -5
  155. package/src/runs/shared/child-session.js +85 -38
  156. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  157. package/src/runs/shared/child-tool-plan.js +0 -1
  158. package/src/runs/shared/claude-code-adapter.js +11 -0
  159. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  160. package/src/runs/shared/external-cli-contract.js +18 -13
  161. package/src/runs/shared/external-cli-runner.js +26 -6
  162. package/src/runs/shared/herdr-connection.js +2 -1
  163. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  164. package/src/runs/shared/herdr-pane-host.js +17 -1
  165. package/src/runs/shared/herdr-placed-run.js +51 -24
  166. package/src/runs/shared/lane-metadata.d.ts +0 -1
  167. package/src/runs/shared/lane-metadata.js +0 -1
  168. package/src/runs/shared/mcp-config-sources.d.ts +4 -1
  169. package/src/runs/shared/mcp-config-sources.js +1 -1
  170. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -3
  171. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -17
  172. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  173. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  174. package/src/runs/shared/model-resolution.d.ts +20 -5
  175. package/src/runs/shared/model-resolution.js +55 -50
  176. package/src/runs/shared/model-scope.d.ts +1 -5
  177. package/src/runs/shared/model-scope.js +1 -5
  178. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  179. package/src/runs/shared/mutation-evidence.js +52 -7
  180. package/src/runs/shared/nested-events.d.ts +1 -0
  181. package/src/runs/shared/nested-events.js +1 -1
  182. package/src/runs/shared/parallel-utils.d.ts +0 -1
  183. package/src/runs/shared/permissions.js +5 -3
  184. package/src/runs/shared/placement-host.d.ts +5 -1
  185. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  186. package/src/runs/shared/rex-pane-host.js +0 -2
  187. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  188. package/src/runs/shared/run-launch-folder.js +21 -0
  189. package/src/runs/shared/runner-launcher.d.ts +12 -1
  190. package/src/runs/shared/runner-launcher.js +16 -0
  191. package/src/runs/shared/single-output.d.ts +3 -3
  192. package/src/runs/shared/single-output.js +5 -3
  193. package/src/runs/shared/structured-output.d.ts +8 -0
  194. package/src/runs/shared/structured-output.js +40 -5
  195. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  196. package/src/runs/shared/subagent-prompt-runtime.js +18 -4
  197. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  198. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  199. package/src/runs/shared/tool-timeout.js +2 -1
  200. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  201. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  202. package/src/runs/shared/worktree.d.ts +3 -0
  203. package/src/runs/shared/worktree.js +20 -0
  204. package/src/shared/artifacts.d.ts +1 -0
  205. package/src/shared/artifacts.js +132 -22
  206. package/src/shared/capacity-resilient-json.d.ts +1 -1
  207. package/src/shared/child-cache-retention.d.ts +1 -2
  208. package/src/shared/child-cache-retention.js +1 -2
  209. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  210. package/src/shared/fleet-transcript-reader.js +333 -0
  211. package/src/shared/formatters.d.ts +0 -18
  212. package/src/shared/formatters.js +0 -18
  213. package/src/shared/pruned-fork.js +2 -2
  214. package/src/shared/reported-progress.d.ts +1 -0
  215. package/src/shared/reported-progress.js +12 -0
  216. package/src/shared/session-succession.d.ts +16 -1
  217. package/src/shared/session-succession.js +41 -2
  218. package/src/shared/session-warnings.d.ts +7 -0
  219. package/src/shared/session-warnings.js +26 -0
  220. package/src/shared/settings.d.ts +0 -23
  221. package/src/shared/settings.js +3 -35
  222. package/src/shared/status-format.d.ts +1 -0
  223. package/src/shared/status-format.js +1 -1
  224. package/src/shared/types.d.ts +108 -59
  225. package/src/shared/types.js +0 -12
  226. package/src/shared/utils.d.ts +3 -15
  227. package/src/shared/utils.js +4 -22
  228. package/src/shared/wait-tool-name.d.ts +8 -0
  229. package/src/shared/wait-tool-name.js +13 -0
  230. package/src/slash/slash-commands.js +2 -1
  231. package/src/slash/subagent-cost.d.ts +3 -2
  232. package/src/slash/subagent-cost.js +22 -3
  233. package/src/slash/subagents-admin.js +0 -1
  234. package/src/tui/fleet-status.d.ts +0 -5
  235. package/src/tui/fleet-status.js +4 -24
  236. package/src/tui/fleet.js +6 -4
  237. package/src/tui/render.d.ts +0 -9
  238. package/src/tui/render.js +194 -68
  239. package/src/tui/subagent-messages.js +3 -2
  240. package/src/watchdog/model-selection.js +2 -2
  241. package/src/watchdog/permission-arbiter.js +1 -0
  242. package/src/watchdog/register-child.d.ts +2 -3
  243. package/src/watchdog/register-child.js +2 -3
  244. package/src/watchdog/review.d.ts +0 -5
  245. package/src/watchdog/review.js +4 -3
  246. package/src/watchdog/turn-delta.js +2 -1
  247. package/src/workflows/scripted-workflow.d.ts +2 -0
  248. package/src/workflows/scripted-workflow.js +344 -59
  249. package/src/workflows/structured-workflow-scripts.d.ts +4 -3
  250. package/src/workflows/structured-workflow-scripts.js +32 -11
  251. package/src/workflows/workflow-launch-record.d.ts +15 -6
  252. package/src/workflows/workflow-launch-record.js +30 -12
  253. package/src/workflows/workflow-receipt.js +36 -53
  254. package/src/workflows/workflow-resources.js +4 -4
  255. package/src/workflows/workflow-resume-claim.d.ts +2 -0
  256. package/src/workflows/workflow-resume-claim.js +3 -3
  257. package/src/workflows/workflow-resume.d.ts +1 -1
  258. package/src/workflows/workflow-resume.js +13 -8
  259. package/src/workflows/workflow-script-worker.d.ts +13 -0
  260. package/src/workflows/workflow-script-worker.js +81 -0
  261. package/workflow-script-process.cjs +36 -0
  262. package/workflow-script-worker.cjs +4 -1
  263. package/bundle/chunk-U4ODUYAG.js +0 -235
@@ -1,41 +1,36 @@
1
1
  import {
2
- MODEL_ONLY_TOOL,
3
2
  agentStreamOptions,
4
3
  formatAsyncRunList,
5
4
  formatTimeoutRecoveryLines,
6
- inheritedSessionIds,
7
5
  listAsyncRuns,
8
6
  opencodeSessionHeaders,
9
- ownsRun,
10
7
  parseWorkflowChildSummary,
11
8
  projectTimeoutRecovery,
12
9
  readAsyncRecoveryDescriptor,
13
10
  utf8Tail
14
- } from "./chunk-TMHVDPYW.js";
11
+ } from "./chunk-DLVPMML3.js";
15
12
  import {
16
13
  MAX_ARGS_BYTES,
17
14
  MAX_ARGS_DEPTH,
18
15
  MAX_ARGS_FIELDS,
19
16
  MAX_ARGS_ITEMS
20
- } from "./chunk-FJWI64H7.js";
17
+ } from "./chunk-RMSABUN3.js";
21
18
  import {
22
19
  fallbackResultPayloadPathForSessionRun,
23
20
  nestedRunScope,
24
21
  resultFilePath,
25
22
  resultPayloadMatchesSessionRun,
26
23
  resultPayloadPathForSessionRun
27
- } from "./chunk-ICNYIALB.js";
24
+ } from "./chunk-JH5H4CYJ.js";
28
25
  import {
29
26
  PROJECT_SUBAGENTS_RELATIVE_DIR
30
- } from "./chunk-U4ODUYAG.js";
31
- import {
32
- shouldUseNativeFsWatch
33
- } from "./chunk-NIXWDZZV.js";
27
+ } from "./chunk-LYKG4FKH.js";
34
28
  import {
35
29
  listBackgroundWorkWakeChannels,
36
30
  snapshotBackgroundWork
37
31
  } from "./chunk-XA3DY6UG.js";
38
32
  import {
33
+ DEFAULT_WAIT_TOOL_NAME,
39
34
  SUBAGENT_WATCHDOG_WARNING_TYPE,
40
35
  THINKING_LEVELS,
41
36
  WATCHDOG_WARNING_CATEGORIES,
@@ -45,1085 +40,146 @@ import {
45
40
  formatDuration,
46
41
  getAgentDir,
47
42
  getProjectConfigDir,
48
- readStatus,
43
+ knownModelProviders,
49
44
  resolveEffectiveThinking,
50
45
  resolveModelCandidate,
51
46
  shortenPath,
52
47
  splitKnownThinkingSuffix,
53
48
  toAgentToolUsage,
54
49
  toModelInfo,
50
+ waitToolName,
55
51
  withSettingsFileLease,
56
- writeAtomicJson,
57
52
  writePrivateAtomicJson
58
- } from "./chunk-V2KFIGFH.js";
53
+ } from "./chunk-XAC2XNAP.js";
59
54
  import {
60
- ASYNC_DIR,
61
55
  DIRS,
62
56
  INTERCOM_DETACH_REQUEST_EVENT,
63
- POLL_INTERVAL_MS,
57
+ RUNNER_LAUNCHER_NAME_PATTERN,
64
58
  SUBAGENT_ASYNC_COMPLETE_EVENT,
65
59
  SUBAGENT_CONTROL_EVENT,
66
60
  SUBAGENT_CONTROL_INTERCOM_EVENT,
67
61
  SUBAGENT_FOREGROUND_COMPLETE_EVENT,
68
- SUBAGENT_RESULT_INTERCOM_EVENT,
69
- TEMP_ROOT_DIR
62
+ SUBAGENT_RESULT_INTERCOM_EVENT
70
63
  } from "./chunk-UQDHXMUG.js";
71
64
 
72
- // src/intercom/native-supervisor-channel.ts
73
- import { randomUUID } from "node:crypto";
65
+ // src/shared/session-identity.ts
74
66
  import * as fs from "node:fs";
75
- import * as path from "node:path";
76
- import { Type } from "typebox";
77
-
78
- // src/intercom/supervisor-ui.ts
79
- var SUPERVISOR_REQUEST_MESSAGE_TYPE = "subagent_supervisor_request";
80
- var SUPERVISOR_REPLY_ENTRY_TYPE = "subagent_supervisor_reply";
81
- function supervisorReplyHint(requestId) {
82
- return `subagent_supervisor({ action: "reply", replyTo: "${requestId}", message: "..." })`;
83
- }
84
- function isRecord(value) {
85
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
86
- }
87
- function isSupervisorReason(value) {
88
- return value === "need_decision" || value === "interview_request" || value === "progress_update";
89
- }
90
- function optionalString(value) {
91
- return value === void 0 || typeof value === "string";
92
- }
93
- function parseSupervisorRequestDetails(value) {
94
- if (!isRecord(value)) return void 0;
95
- if (!optionalString(value.id) || !optionalString(value.requestId) || !optionalString(value.replyHint) || !optionalString(value.requestBody) || !optionalString(value.runId) || !optionalString(value.agent) || !optionalString(value.childTarget)) return void 0;
96
- if (value.reason !== void 0 && !isSupervisorReason(value.reason)) return void 0;
97
- if (value.expectsReply !== void 0 && typeof value.expectsReply !== "boolean") return void 0;
98
- if (value.childIndex !== void 0 && (typeof value.childIndex !== "number" || !Number.isFinite(value.childIndex))) return void 0;
99
- return value;
100
- }
101
- function parseSupervisorReplyData(value) {
102
- if (!isRecord(value)) return void 0;
103
- if (typeof value.requestId !== "string" || typeof value.runId !== "string" || typeof value.agent !== "string" || typeof value.message !== "string") return void 0;
104
- if (value.reason !== void 0 && !isSupervisorReason(value.reason)) return void 0;
105
- if (value.childTarget !== void 0 && typeof value.childTarget !== "string") return void 0;
106
- if (typeof value.childIndex !== "number" || !Number.isFinite(value.childIndex) || typeof value.createdAt !== "number" || !Number.isFinite(value.createdAt)) return void 0;
107
- return {
108
- requestId: value.requestId,
109
- ...value.reason === void 0 ? {} : { reason: value.reason },
110
- runId: value.runId,
111
- agent: value.agent,
112
- childIndex: value.childIndex,
113
- ...value.childTarget === void 0 ? {} : { childTarget: value.childTarget },
114
- message: value.message,
115
- createdAt: value.createdAt
116
- };
117
- }
118
-
119
- // src/intercom/native-supervisor-channel.ts
120
- var SUPERVISOR_CHANNEL_ROOT = path.join(TEMP_ROOT_DIR, "supervisor-channels");
121
- var REQUESTS_DIR = "requests";
122
- var REPLIES_DIR = "replies";
123
- var NATIVE_SUPERVISOR_TOOL_NAME = "subagent_supervisor";
124
- var MAX_MESSAGE_BYTES = 64 * 1024;
125
- var DEFAULT_ASK_TIMEOUT_MS = 10 * 60 * 1e3;
126
- var CHANNEL_POLL_MS = Math.min(POLL_INTERVAL_MS, 500);
127
- var CHANNEL_SAFETY_POLL_MS = 5e3;
128
- var STALE_EMPTY_CHANNEL_AGE_MS = 60 * 1e3;
129
- var STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS = 60 * 1e3;
130
- var MAX_SUPERVISOR_REQUEST_CORRELATIONS = 256;
131
- var SUPERVISOR_REQUEST_CORRELATION_RETENTION_MS = 10 * 60 * 1e3;
132
- var ContactSupervisorParamsSchema = Type.Object({
133
- reason: Type.String({ enum: ["need_decision", "interview_request", "progress_update"] }),
134
- message: Type.Optional(Type.String()),
135
- interview: Type.Optional(Type.Unsafe({ type: "object", additionalProperties: true }))
136
- }, { additionalProperties: false });
137
- var IntercomParamsSchema = Type.Object({
138
- action: Type.String({ enum: ["list", "pending", "status", "reply"] }),
139
- to: Type.Optional(Type.String()),
140
- message: Type.Optional(Type.String()),
141
- replyTo: Type.Optional(Type.String())
142
- }, { additionalProperties: false });
143
- function safeSegment(value) {
144
- return value.trim().replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "unknown";
145
- }
146
- function resolveSupervisorChannelDir(runId, agent2, childIndex) {
147
- return path.join(SUPERVISOR_CHANNEL_ROOT, `${safeSegment(runId)}-${safeSegment(agent2)}-${childIndex}`);
148
- }
149
- function ensureSupervisorChannelDir(channelDir) {
150
- fs.mkdirSync(path.join(channelDir, REQUESTS_DIR), { recursive: true, mode: 448 });
151
- fs.mkdirSync(path.join(channelDir, REPLIES_DIR), { recursive: true, mode: 448 });
152
- }
153
- function requestPath(channelDir, requestId) {
154
- return path.join(channelDir, REQUESTS_DIR, `${safeSegment(requestId)}.json`);
155
- }
156
- function replyPath(channelDir, requestId) {
157
- return path.join(channelDir, REPLIES_DIR, `${safeSegment(requestId)}.json`);
158
- }
159
- function reasonHeading(reason) {
160
- if (reason === "interview_request") return "Subagent requests a structured supervisor interview.";
161
- if (reason === "progress_update") return "Subagent progress update.";
162
- return "Subagent needs a supervisor decision.";
163
- }
164
- function parseStructuredReply(message2) {
165
- const trimmed = message2.trim();
166
- const fenced = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i)?.[1]?.trim();
167
- try {
168
- return { value: JSON.parse(fenced ?? trimmed) };
169
- } catch (error) {
170
- return { error: error instanceof Error ? `${error.name}: ${error.message}` : String(error) };
171
- }
172
- }
173
- function askTimeoutMs() {
174
- const parsed = Number(process.env.PI_INTERCOM_ASK_TIMEOUT_MS);
175
- return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_ASK_TIMEOUT_MS;
176
- }
177
- function delay(ms, signal) {
178
- return new Promise((resolve5, reject) => {
179
- if (signal?.aborted) {
180
- reject(new Error("Supervisor request cancelled."));
181
- return;
182
- }
183
- let timer;
184
- const cleanup = () => {
185
- if (timer) clearTimeout(timer);
186
- signal?.removeEventListener("abort", onAbort);
187
- };
188
- const onAbort = () => {
189
- cleanup();
190
- reject(new Error("Supervisor request cancelled."));
191
- };
192
- timer = setTimeout(() => {
193
- cleanup();
194
- resolve5();
195
- }, ms);
196
- signal?.addEventListener("abort", onAbort, { once: true });
197
- });
198
- }
199
- function extendedDeadline(requestFile, deadline) {
200
- try {
201
- const expiresAt = JSON.parse(fs.readFileSync(requestFile, "utf-8")).expiresAt;
202
- return typeof expiresAt === "number" && Number.isFinite(expiresAt) ? Math.max(deadline, expiresAt) : deadline;
203
- } catch {
204
- return deadline;
205
- }
206
- }
207
- async function waitForReply(channelDir, requestId, initialDeadline, signal) {
208
- const file = replyPath(channelDir, requestId);
209
- const request = requestPath(channelDir, requestId);
210
- let deadline = initialDeadline;
211
- while (Date.now() <= deadline) {
212
- if (signal?.aborted) throw new Error("Supervisor request cancelled.");
213
- if (fs.existsSync(file)) {
214
- let parsed;
215
- try {
216
- parsed = JSON.parse(fs.readFileSync(file, "utf-8"));
217
- } catch {
218
- parsed = void 0;
219
- }
220
- if (parsed && parsed.type === "subagent.supervisor.reply" && parsed.requestId === requestId && typeof parsed.message === "string") {
221
- if (typeof parsed.error === "string") throw new Error(parsed.error);
222
- return parsed;
223
- }
224
- }
225
- await delay(250, signal);
226
- deadline = extendedDeadline(request, deadline);
227
- }
228
- throw new Error("Timed out waiting for supervisor reply.");
229
- }
230
- async function sendSupervisorRequest(params, metadata, signal, toolCallId) {
231
- if (!params.message?.trim() && params.reason !== "interview_request") {
232
- throw new Error("message is required for supervisor decisions and progress updates.");
233
- }
234
- ensureSupervisorChannelDir(metadata.channelDir);
235
- const requestId = randomUUID();
236
- const expectsReply = params.reason !== "progress_update";
237
- const createdAt = Date.now();
238
- const replyDeadline = createdAt + askTimeoutMs();
239
- const expiresAt = expectsReply ? replyDeadline : void 0;
240
- const message2 = params.message?.trim() ?? "";
241
- const requestToolCallId = typeof toolCallId === "string" && toolCallId.length > 0 ? toolCallId : void 0;
242
- const request = {
243
- type: "subagent.supervisor.request",
244
- id: requestId,
245
- createdAt,
246
- ...expiresAt !== void 0 ? { expiresAt } : {},
247
- reason: params.reason,
248
- message: message2,
249
- expectsReply,
250
- ...metadata.orchestratorTarget ? { orchestratorTarget: metadata.orchestratorTarget } : {},
251
- ...metadata.orchestratorSessionId ? { orchestratorSessionId: metadata.orchestratorSessionId } : {},
252
- runId: metadata.runId,
253
- agent: metadata.agent,
254
- childIndex: metadata.childIndex,
255
- ...requestToolCallId ? { toolCallId: requestToolCallId } : {},
256
- ...metadata.childTarget ? { childTarget: metadata.childTarget } : {},
257
- ...params.interview !== void 0 ? { interview: params.interview } : {}
258
- };
259
- const serialized = JSON.stringify(request, null, " ");
260
- if (Buffer.byteLength(serialized, "utf-8") > MAX_MESSAGE_BYTES) throw new Error("Supervisor request is too large.");
261
- writeAtomicJson(requestPath(metadata.channelDir, requestId), request);
262
- if (!expectsReply) {
263
- return {
264
- content: [{ type: "text", text: "Supervisor progress update queued." }],
265
- details: { delivered: true, requestId, reason: params.reason }
266
- };
267
- }
268
- try {
269
- const reply = await waitForReply(metadata.channelDir, requestId, replyDeadline, signal);
270
- const details = { requestId, reason: params.reason };
271
- if (params.reason === "interview_request") {
272
- const structured = parseStructuredReply(reply.message);
273
- if (structured.error) details.structuredReplyParseError = structured.error;
274
- else details.structuredReply = structured.value;
275
- }
276
- return {
277
- content: [{ type: "text", text: `**Reply from supervisor:**
278
- ${reply.message}` }],
279
- details
280
- };
281
- } catch (error) {
282
- removeRequestFile(requestPath(metadata.channelDir, requestId));
283
- throw error;
284
- }
285
- }
286
- function hasTool(pi, name) {
287
- try {
288
- return pi.getAllTools?.().some((tool) => tool.name === name) === true;
289
- } catch {
290
- return false;
291
- }
292
- }
293
- var CONTACT_SUPERVISOR_TOOL_NAME = "contact_supervisor";
294
- var CONTACT_SUPERVISOR_DECLARATION = {
295
- name: CONTACT_SUPERVISOR_TOOL_NAME,
296
- ...MODEL_ONLY_TOOL,
297
- label: "Contact Supervisor",
298
- description: "Contact the parent/supervisor session for a blocking decision, structured interview, or progress update.",
299
- parameters: ContactSupervisorParamsSchema
300
- };
301
- var TOP_LEVEL_SUPERVISOR_REFUSAL = "contact_supervisor works only inside a subagent; this session has no supervisor.";
302
- function topLevelSupervisorTool() {
303
- return {
304
- ...CONTACT_SUPERVISOR_DECLARATION,
305
- async execute() {
306
- return { isError: true, content: [{ type: "text", text: TOP_LEVEL_SUPERVISOR_REFUSAL }], details: {} };
307
- }
308
- };
309
- }
310
- function registerNativeSupervisorClient(pi, metadata) {
311
- if (!metadata || hasTool(pi, CONTACT_SUPERVISOR_TOOL_NAME)) return;
312
- const tool = {
313
- ...CONTACT_SUPERVISOR_DECLARATION,
314
- execute(id2, params, signal) {
315
- return sendSupervisorRequest(params, metadata, signal, id2);
316
- }
317
- };
318
- pi.registerTool(tool);
67
+ function resolveCurrentSessionId(sessionManager) {
68
+ const sessionId = sessionManager.getSessionFile() ?? sessionManager.getSessionId();
69
+ if (!sessionId) throw new Error("Current session identity is unavailable.");
70
+ return sessionId;
319
71
  }
320
- function parseRequestFile(file, channelDir) {
72
+ function resolvePiSessionId(sessionFile) {
73
+ if (!sessionFile) return void 0;
321
74
  try {
322
- const parsed = JSON.parse(fs.readFileSync(file, "utf-8"));
323
- if (parsed.type !== "subagent.supervisor.request") return void 0;
324
- if (typeof parsed.id !== "string" || !parsed.id) return void 0;
325
- if (parsed.reason !== "need_decision" && parsed.reason !== "interview_request" && parsed.reason !== "progress_update") return void 0;
326
- if (typeof parsed.message !== "string" || !parsed.message.trim() && parsed.reason !== "interview_request") return void 0;
327
- if (typeof parsed.runId !== "string" || typeof parsed.agent !== "string" || typeof parsed.childIndex !== "number") return void 0;
328
- return {
329
- ...parsed,
330
- ...typeof parsed.toolCallId === "string" && parsed.toolCallId.length > 0 ? { toolCallId: parsed.toolCallId } : { toolCallId: void 0 },
331
- channelDir,
332
- requestFile: file
333
- };
334
- } catch {
335
- return void 0;
336
- }
337
- }
338
- function isMissingSupervisorDirectory(error, platform) {
339
- const code = error.code;
340
- return code === "ENOENT" || platform === "win32" && code === "UNKNOWN";
341
- }
342
- function listRequestFiles(channelDirs, platform) {
343
- if (!channelDirs) {
75
+ const fd = fs.openSync(sessionFile, "r");
344
76
  try {
345
- channelDirs = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => path.join(SUPERVISOR_CHANNEL_ROOT, entry.name));
346
- } catch (error) {
347
- if (isMissingSupervisorDirectory(error, platform)) return [];
348
- throw error;
349
- }
350
- }
351
- const files = [];
352
- for (const channelDir of channelDirs) {
353
- const requestsDir = path.join(channelDir, REQUESTS_DIR);
354
- let requestEntries;
355
- try {
356
- requestEntries = fs.readdirSync(requestsDir, { withFileTypes: true });
357
- } catch {
358
- continue;
359
- }
360
- for (const requestEntry of requestEntries) {
361
- if (requestEntry.isFile() && requestEntry.name.endsWith(".json")) files.push({ channelDir, file: path.join(requestsDir, requestEntry.name) });
77
+ const buffer = Buffer.alloc(16 * 1024);
78
+ const bytes = fs.readSync(fd, buffer, 0, buffer.length, 0);
79
+ const line = buffer.toString("utf-8", 0, bytes).split("\n", 1)[0];
80
+ if (!line) return void 0;
81
+ const header = JSON.parse(line);
82
+ if (header.type === "session" && typeof header.id === "string" && /^[A-Za-z0-9-]{8,}$/.test(header.id)) return header.id;
83
+ return void 0;
84
+ } finally {
85
+ fs.closeSync(fd);
362
86
  }
363
- }
364
- return files;
365
- }
366
- function readDirectoryEntries(dir, platform) {
367
- try {
368
- return fs.readdirSync(dir, { withFileTypes: true });
369
- } catch (error) {
370
- if (isMissingSupervisorDirectory(error, platform)) return [];
87
+ } catch {
371
88
  return void 0;
372
89
  }
373
90
  }
374
- function directoryMtimeMs(dir) {
375
- try {
376
- return fs.statSync(dir).mtimeMs;
377
- } catch {
378
- return 0;
379
- }
91
+
92
+ // src/watchdog/diff-tool.ts
93
+ import { execFile, spawnSync } from "node:child_process";
94
+ import * as path from "node:path";
95
+ import { Type } from "typebox";
96
+ var WATCHDOG_DIFF_TOOL_NAME = "watchdog_diff";
97
+ var WATCHDOG_DIFF_MAX_CHARS = 24e3;
98
+ var WATCHDOG_DIFF_UNAVAILABLE_BASELINE = "watchdog_diff unavailable: this cwd has no valid Git HEAD baseline. No diff can be shown; inspect files with independent read-only tools instead.";
99
+ var MAX_UNTRACKED_FILES = 50;
100
+ var WatchdogDiffParams = Type.Object({
101
+ path: Type.Optional(Type.String({ description: "Restrict the diff to one file or directory, relative to the repo root." })),
102
+ stat: Type.Optional(Type.Boolean({ description: "Return per-file change counts instead of the full diff." }))
103
+ }, { additionalProperties: false });
104
+ function runGit(root, args2) {
105
+ const result2 = spawnSync("git", ["-C", root, ...args2], { encoding: "utf-8", maxBuffer: 16 * 1024 * 1024, windowsHide: true });
106
+ return { ok: result2.status === 0, stdout: result2.stdout ?? "", stderr: (result2.stderr ?? "").trim() };
380
107
  }
381
- function removeEmptyDirectory(dir) {
382
- try {
383
- fs.rmdirSync(dir);
384
- return true;
385
- } catch (error) {
386
- const code = error.code;
387
- if (code === "ENOENT") return true;
388
- if (code === "ENOTEMPTY" || code === "EEXIST" || code === "EPERM" || code === "EBUSY") return false;
389
- throw error;
390
- }
108
+ var BASELINE_ARGS = ["rev-parse", "--show-toplevel", "HEAD"];
109
+ function parseBaseline(stdout) {
110
+ const lines = stdout.trim().split(/\r?\n/);
111
+ const ref = lines.pop();
112
+ const root = lines.join("\n");
113
+ return root && ref ? { root, ref } : void 0;
391
114
  }
392
- function removeStaleEmptySupervisorChannel(channelDir, nowMs, platform) {
393
- const requestsDir = path.join(channelDir, REQUESTS_DIR);
394
- const repliesDir = path.join(channelDir, REPLIES_DIR);
395
- const newestKnownMtimeMs = Math.max(
396
- directoryMtimeMs(channelDir),
397
- directoryMtimeMs(requestsDir),
398
- directoryMtimeMs(repliesDir)
399
- );
400
- if (nowMs - newestKnownMtimeMs < STALE_EMPTY_CHANNEL_AGE_MS) return false;
401
- const requestEntries = readDirectoryEntries(requestsDir, platform);
402
- if (!requestEntries || requestEntries.length > 0) return false;
403
- const replyEntries = readDirectoryEntries(repliesDir, platform);
404
- if (!replyEntries || replyEntries.length > 0) return false;
405
- if (!removeEmptyDirectory(requestsDir)) return false;
406
- if (!removeEmptyDirectory(repliesDir)) return false;
407
- if (!removeEmptyDirectory(channelDir)) return false;
408
- return true;
115
+ function captureWatchdogDiffBaseline(cwd2) {
116
+ const result2 = runGit(cwd2, BASELINE_ARGS);
117
+ return result2.ok ? parseBaseline(result2.stdout) : void 0;
409
118
  }
410
- function cleanupStaleEmptySupervisorChannels(nowMs = Date.now(), platform = process.platform) {
411
- let channelEntries;
412
- try {
413
- channelEntries = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true });
414
- } catch (error) {
415
- if (isMissingSupervisorDirectory(error, platform)) return 0;
416
- throw error;
417
- }
418
- let removed = 0;
419
- for (const entry of channelEntries) {
420
- if (!entry.isDirectory()) continue;
119
+ function startWatchdogDiffBaselineCapture(cwd2) {
120
+ return new Promise((resolve5) => {
421
121
  try {
422
- if (removeStaleEmptySupervisorChannel(path.join(SUPERVISOR_CHANNEL_ROOT, entry.name), nowMs, platform)) removed++;
122
+ execFile("git", ["-C", cwd2, ...BASELINE_ARGS], { encoding: "utf-8", windowsHide: true }, (error, stdout) => {
123
+ resolve5(error ? void 0 : parseBaseline(stdout));
124
+ });
423
125
  } catch {
126
+ resolve5(void 0);
424
127
  }
425
- }
426
- return removed;
427
- }
428
- function requestMatchesOwner(request, state) {
429
- const currentSessionId = state.supervisorOwnerSessionId;
430
- if (currentSessionId && request.orchestratorSessionId === currentSessionId) return true;
431
- if (!state.currentSessionId || inheritedSessionIds(state.currentSessionId).length === 0) return false;
432
- if (!request.runId || request.runId.startsWith(".") || path.basename(request.runId) !== request.runId) return false;
433
- try {
434
- return ownsRun(state.currentSessionId, readStatus(path.join(ASYNC_DIR, request.runId))?.sessionId);
435
- } catch {
436
- return false;
437
- }
438
- }
439
- function rememberedForegroundChild(request, state) {
440
- const run = state.foregroundRuns?.get(request.runId);
441
- const child = run?.children.find((candidate) => candidate.index === request.childIndex && candidate.agent === request.agent) ?? run?.children[request.childIndex];
442
- return run && child ? { run, child } : void 0;
443
- }
444
- function markForegroundSupervisorAttention(request, state) {
445
- const remembered = rememberedForegroundChild(request, state);
446
- if (!remembered || remembered.child.status !== "detached") return;
447
- const updatedAt = Date.now();
448
- remembered.run.updatedAt = updatedAt;
449
- remembered.child.activityState = "needs_attention";
450
- remembered.child.lastActivityAt = request.createdAt;
451
- remembered.child.currentTool = "contact_supervisor";
452
- remembered.child.currentToolStartedAt = request.createdAt;
453
- remembered.child.updatedAt = updatedAt;
454
- }
455
- function clearForegroundSupervisorAttention(request, pending, state) {
456
- if ([...pending.values()].some(
457
- (candidate) => candidate.expectsReply && candidate.runId === request.runId && candidate.agent === request.agent && candidate.childIndex === request.childIndex
458
- )) return;
459
- const remembered = rememberedForegroundChild(request, state);
460
- if (!remembered || remembered.child.status !== "detached") return;
461
- const updatedAt = Date.now();
462
- remembered.run.updatedAt = updatedAt;
463
- remembered.child.activityState = void 0;
464
- remembered.child.lastActivityAt = updatedAt;
465
- remembered.child.currentTool = void 0;
466
- remembered.child.currentToolStartedAt = void 0;
467
- remembered.child.updatedAt = updatedAt;
468
- }
469
- function removeRequestFile(file) {
470
- try {
471
- fs.rmSync(file, { force: true });
472
- } catch {
473
- }
474
- }
475
- function requestExpiresAt(request, now) {
476
- const expiresAt = request.expiresAt;
477
- if (typeof expiresAt === "number" && Number.isFinite(expiresAt)) return expiresAt;
478
- return Number.isFinite(request.createdAt) ? request.createdAt + askTimeoutMs() : now;
479
- }
480
- function requestRunInactive(request, state) {
481
- if (state.foregroundControls.has(request.runId)) return false;
482
- const foreground = rememberedForegroundChild(request, state);
483
- if (foreground) return foreground.child.status !== "detached";
484
- const asyncJob = state.asyncJobs.get(request.runId);
485
- if (!asyncJob) return false;
486
- if (asyncJob.status === "complete" || asyncJob.status === "failed" || asyncJob.status === "paused") return true;
487
- const stepStatus = asyncJob.steps?.[request.childIndex]?.status;
488
- return stepStatus === "complete" || stepStatus === "completed" || stepStatus === "failed" || stepStatus === "paused";
489
- }
490
- function requestLifecycle(request, state, now, runState) {
491
- if (!requestMatchesOwner(request, state)) return "wrong-session";
492
- if (!fs.existsSync(request.requestFile)) return "missing";
493
- if (request.expectsReply && fs.existsSync(replyPath(request.channelDir, request.id))) return "resolved";
494
- if (request.expectsReply && now > requestExpiresAt(request, now)) return "expired";
495
- if (request.expectsReply && requestRunInactive(request, runState)) return "inactive";
496
- return "pending";
497
- }
498
- function cleanupRequestLifecycle(request, lifecycle) {
499
- if (lifecycle === "resolved" || lifecycle === "expired" || lifecycle === "inactive") removeRequestFile(request.requestFile);
500
- }
501
- function refreshPendingRequests(pending, state, onLifecycle, runState) {
502
- const now = Date.now();
503
- for (const request of pending.values()) {
504
- const lifecycle = requestLifecycle(request, state, now, runState(request));
505
- if (lifecycle === "pending") continue;
506
- pending.delete(request.id);
507
- onLifecycle(request, lifecycle);
508
- cleanupRequestLifecycle(request, lifecycle);
509
- }
510
- }
511
- function pendingHeader(request) {
512
- return `- ${request.id}: ${request.agent} [${request.runId}#${request.childIndex}] ${request.reason}.`;
513
- }
514
- function formatPendingLine(request) {
515
- const replyHint = request.expectsReply ? ` Reply: ${supervisorReplyHint(request.id)}` : "";
516
- const header = `${pendingHeader(request)}${replyHint}`;
517
- return request.message ? `${header}
518
- ${request.message.replace(/\n/g, "\n ")}` : header;
519
- }
520
- function requestVisibleText(request) {
521
- const lines = [
522
- reasonHeading(request.reason),
523
- `Run: ${request.runId}`,
524
- `Agent: ${request.agent}`,
525
- `Child index: ${request.childIndex}`
526
- ];
527
- lines.push("");
528
- if (request.message) lines.push(request.message);
529
- if (request.reason === "interview_request") {
530
- lines.push(
531
- "",
532
- "Structured response requested. Reply with JSON, optionally fenced in ```json, matching the requested interview shape."
533
- );
534
- if (request.interview !== void 0) lines.push(JSON.stringify(request.interview, null, " "));
535
- }
536
- if (request.expectsReply) lines.push("", `Reply with: ${supervisorReplyHint(request.id)}`);
537
- lines.push("", `Live guidance: subagent({ action: "steer", id: ${JSON.stringify(request.runId)}, message: "...", options: { index: ${request.childIndex} } })${request.expectsReply ? " (Reply to the pending request first.)" : ""}`);
538
- return lines.join("\n").trimEnd();
539
- }
540
- function writeReply(request, message2) {
541
- if (!message2.trim()) throw new Error("message is required for supervisor replies.");
542
- const reply = {
543
- type: "subagent.supervisor.reply",
544
- requestId: request.id,
545
- createdAt: Date.now(),
546
- message: message2.trim()
547
- };
548
- writeAtomicJson(replyPath(request.channelDir, request.id), reply);
549
- removeRequestFile(request.requestFile);
550
- return reply;
128
+ });
551
129
  }
552
- function appendSupervisorReplyEntry(pi, request, reply) {
553
- const appendEntry = pi.appendEntry;
554
- if (typeof appendEntry !== "function") return;
555
- try {
556
- appendEntry.call(pi, SUPERVISOR_REPLY_ENTRY_TYPE, {
557
- requestId: request.id,
558
- reason: request.reason,
559
- runId: request.runId,
560
- agent: request.agent,
561
- childIndex: request.childIndex,
562
- ...request.childTarget ? { childTarget: request.childTarget } : {},
563
- message: reply.message,
564
- createdAt: reply.createdAt
565
- });
566
- } catch {
567
- console.error("Failed to journal native supervisor reply: error details omitted");
568
- }
130
+ function validatePath(value) {
131
+ const trimmed = value?.trim();
132
+ if (!trimmed) return void 0;
133
+ if (trimmed.startsWith("-")) throw new Error("watchdog_diff path must not start with '-'.");
134
+ if (path.isAbsolute(trimmed)) throw new Error("watchdog_diff path must be relative to the repo root.");
135
+ if (trimmed.split(/[\\/]/).includes("..")) throw new Error("watchdog_diff path must not contain '..'.");
136
+ return trimmed;
569
137
  }
570
- function resolvePendingRequest(pending, params) {
571
- const requests = [...pending.values()].filter((request) => request.expectsReply);
572
- if (params.replyTo) {
573
- const request = pending.get(params.replyTo);
574
- if (!request) {
575
- const current = requests.length ? `Pending now:
576
- ${requests.map(pendingHeader).join("\n")}` : "No pending supervisor requests.";
577
- throw new Error(`No pending supervisor request found for replyTo '${params.replyTo}'. It was answered, expired or withdrawn. ${current}`);
578
- }
579
- return request;
580
- }
581
- if (params.to) {
582
- const normalizedTo = params.to.toLowerCase();
583
- const matches = requests.filter(
584
- (request) => request.id.toLowerCase().startsWith(normalizedTo) || request.agent.toLowerCase() === normalizedTo || request.childTarget?.toLowerCase() === normalizedTo
585
- );
586
- if (matches.length === 1) return matches[0];
587
- if (matches.length > 1) throw new Error(`Multiple pending supervisor requests match '${params.to}'. Use replyTo.`);
588
- throw new Error(`No pending supervisor request matches '${params.to}'. Use replyTo.`);
589
- }
590
- if (requests.length === 1) return requests[0];
591
- if (requests.length === 0) throw new Error("No pending supervisor requests need a reply.");
592
- throw new Error("Multiple pending supervisor requests need replies. Use replyTo.");
593
- }
594
- function publicPendingRequests(pending) {
595
- return [...pending.values()].map((request) => ({
596
- id: request.id,
597
- runId: request.runId,
598
- agent: request.agent,
599
- childIndex: request.childIndex,
600
- reason: request.reason,
601
- expectsReply: request.expectsReply
602
- }));
138
+ function bound(text) {
139
+ if (text.length <= WATCHDOG_DIFF_MAX_CHARS) return text;
140
+ const marker = `
141
+
142
+ [... ${text.length - WATCHDOG_DIFF_MAX_CHARS} characters omitted; call again with a narrower path ...]`;
143
+ return `${text.slice(0, WATCHDOG_DIFF_MAX_CHARS - marker.length)}${marker}`;
603
144
  }
604
- function buildParentSupervisorTool(pi, pending, state, onLifecycle, discover, runState, isClaimed = () => false) {
145
+ function createWatchdogDiffTool(baseline, options = {}) {
146
+ const workingTreeAtLaunch = options.workingTreeAtLaunch === true;
605
147
  return {
606
- name: NATIVE_SUPERVISOR_TOOL_NAME,
607
- ...MODEL_ONLY_TOOL,
608
- label: "Subagent Supervisor",
609
- description: "Native pi-subagents supervisor channel. Use reply/pending/status to answer child subagent requests without overriding pi-intercom.",
610
- parameters: IntercomParamsSchema,
611
- async execute(_id, params) {
612
- discover();
613
- refreshPendingRequests(pending, state, onLifecycle, runState);
614
- const input = params;
615
- if (input.action === "status") {
616
- return { content: [{ type: "text", text: `Native supervisor channel active. Pending replies: ${pending.size}.` }], details: { active: true, pending: pending.size, root: SUPERVISOR_CHANNEL_ROOT } };
617
- }
618
- if (input.action === "pending" || input.action === "list") {
619
- const answerable = [...pending.values()].filter((request) => request.expectsReply && !isClaimed(request.id));
620
- const lines = answerable.map(formatPendingLine);
621
- return { content: [{ type: "text", text: lines.length ? lines.join("\n") : "No pending supervisor requests." }], details: { pending: publicPendingRequests(new Map(answerable.map((request) => [request.id, request]))) } };
622
- }
623
- if (input.action === "reply") {
624
- const request = resolvePendingRequest(pending, input);
625
- if (isClaimed(request.id)) {
626
- throw new Error(`Supervisor request ${request.id} is responder-managed; it can only be answered by its registered responder.`);
627
- }
628
- const reply = writeReply(request, input.message ?? "");
629
- appendSupervisorReplyEntry(pi, request, reply);
630
- pending.delete(request.id);
631
- onLifecycle(request, "resolved");
632
- clearForegroundSupervisorAttention(request, pending, state);
633
- return { content: [{ type: "text", text: `Replied to supervisor request ${request.id}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent } };
634
- }
635
- throw new Error(`Unsupported supervisor action: ${input.action}`);
636
- }
637
- };
638
- }
639
- function createNativeSupervisorChannel(pi, state, deps = {}) {
640
- const watch2 = deps.watch ?? fs.watch;
641
- const timers = deps.timers ?? globalThis;
642
- const runState = (request) => {
643
- for (const ownerState of deps.getCurrentOwnerStates?.() ?? []) {
644
- if (ownerState.asyncJobs.has(request.runId)) return ownerState;
645
- }
646
- return state;
647
- };
648
- const pending = /* @__PURE__ */ new Map();
649
- const claimedAsks = /* @__PURE__ */ new Set();
650
- const settleNotices = /* @__PURE__ */ new Map();
651
- let unsubscribeSettle;
652
- const queuedNotices = /* @__PURE__ */ new Set();
653
- let unsubscribeDelivery;
654
- const requestCorrelations = /* @__PURE__ */ new Map();
655
- const correlationKey = (request) => {
656
- if (!request.toolCallId) return void 0;
657
- return JSON.stringify([request.runId, request.agent, request.childIndex, request.toolCallId]);
658
- };
659
- const pruneRequestCorrelations = (now = Date.now()) => {
660
- for (const [key, correlation] of requestCorrelations) {
661
- if (correlation.state === "resolved" && now - correlation.updatedAt > SUPERVISOR_REQUEST_CORRELATION_RETENTION_MS) requestCorrelations.delete(key);
662
- }
663
- while (requestCorrelations.size > MAX_SUPERVISOR_REQUEST_CORRELATIONS) {
664
- const oldest = requestCorrelations.keys().next().value;
665
- if (oldest === void 0) break;
666
- requestCorrelations.delete(oldest);
667
- }
668
- };
669
- const rememberPendingRequest = (request) => {
670
- const key = correlationKey(request);
671
- if (!key || !request.expectsReply) return;
672
- requestCorrelations.set(key, { request, state: "pending", updatedAt: Date.now() });
673
- pruneRequestCorrelations();
674
- };
675
- const rememberResolvedRequest = (request) => {
676
- const key = correlationKey(request);
677
- if (!key || !request.expectsReply) return;
678
- requestCorrelations.set(key, { request, state: "resolved", updatedAt: Date.now() });
679
- pruneRequestCorrelations();
680
- };
681
- const observeRequestLifecycle = (request, lifecycle) => {
682
- settleNotices.delete(request.id);
683
- if (queuedNotices.delete(request.id)) updateDeliverySubscription();
684
- if (lifecycle !== "wrong-session") rememberResolvedRequest(request);
685
- if (lifecycle !== "pending") deps.supervisorDispatcher?.observe(request.id, lifecycle);
686
- updateSettleSubscription();
687
- };
688
- const getSupervisorRequestState = (event) => {
689
- if (event.currentTool === "intercom" || event.index === void 0) return "unknown";
690
- const toolCallId = typeof event.toolCallId === "string" && event.toolCallId.length > 0 ? event.toolCallId : void 0;
691
- if (!toolCallId) return "unknown";
692
- pruneRequestCorrelations();
693
- const key = correlationKey({ runId: event.runId, agent: event.agent, childIndex: event.index, toolCallId });
694
- if (!key) return "unknown";
695
- const correlation = requestCorrelations.get(key);
696
- if (!correlation) return "unknown";
697
- if (correlation.state === "resolved") return "resolved";
698
- const now = Date.now();
699
- if (!fs.existsSync(correlation.request.requestFile) || fs.existsSync(replyPath(correlation.request.channelDir, correlation.request.id)) || now > requestExpiresAt(correlation.request, now) || requestRunInactive(correlation.request, runState(correlation.request))) {
700
- rememberResolvedRequest(correlation.request);
701
- return "resolved";
702
- }
703
- return "pending";
704
- };
705
- const seenFiles = /* @__PURE__ */ new Set();
706
- const requestWatchers = /* @__PURE__ */ new Map();
707
- let rootWatcher;
708
- let poller;
709
- let safetyPoller;
710
- let deferredWatcherRefresh;
711
- let started = false;
712
- let lastStaleCleanupAt = 0;
713
- const platform = deps.platform ?? process.platform;
714
- const useNativeWatcher = () => !deps.getChannelDirs && shouldUseNativeFsWatch("supervisor-channel", platform) && platform !== "win32";
715
- const hasTransportDemand = () => {
716
- if (pending.size > 0) return true;
717
- if (state.foregroundControls.size > 0) return true;
718
- if (deps.getChannelDirs?.().dirs.length) return true;
719
- if ([...state.asyncJobs.values()].some((job) => job.status === "queued" || job.status === "running")) return true;
720
- for (const ownerState of deps.getCurrentOwnerStates?.() ?? []) {
721
- for (const job of ownerState.asyncJobs.values()) {
722
- if (job.status === "queued" || job.status === "running") return true;
723
- }
724
- }
725
- return false;
726
- };
727
- const registerParentTools = () => {
728
- if (!hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME)) pi.registerTool(buildParentSupervisorTool(pi, pending, state, observeRequestLifecycle, () => poll(), runState, (requestId) => claimedAsks.has(requestId)));
729
- };
730
- const deliverClaimedReply = (request, message2) => {
731
- if (!pending.has(request.id)) throw new Error(`Supervisor ask ${request.id} is no longer pending.`);
732
- if (!requestMatchesOwner(request, state)) throw new Error(`Supervisor ask ${request.id} no longer belongs to the live owner session.`);
733
- if (fs.existsSync(replyPath(request.channelDir, request.id))) throw new Error(`Supervisor ask ${request.id} already has a reply.`);
734
- const now = Date.now();
735
- if (request.expectsReply && now > requestExpiresAt(request, now)) throw new Error(`Supervisor ask ${request.id} has expired.`);
736
- const reply = writeReply(request, message2);
737
- appendSupervisorReplyEntry(pi, request, reply);
738
- pending.delete(request.id);
739
- claimedAsks.delete(request.id);
740
- observeRequestLifecycle(request, "resolved");
741
- clearForegroundSupervisorAttention(request, pending, state);
742
- };
743
- const declareParentTool = () => {
744
- if (typeof pi.getActiveTools !== "function" || typeof pi.setActiveTools !== "function") return;
745
- const active = pi.getActiveTools();
746
- if (!Array.isArray(active) || active.includes(NATIVE_SUPERVISOR_TOOL_NAME) || !hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME)) return;
747
- pi.setActiveTools([...active, NATIVE_SUPERVISOR_TOOL_NAME]);
748
- };
749
- const cleanupStaleChannelsIfDue = () => {
750
- if (deps.getChannelDirs) return;
751
- const nowMs = Date.now();
752
- if (nowMs - lastStaleCleanupAt < STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS) return;
753
- lastStaleCleanupAt = nowMs;
754
- try {
755
- cleanupStaleEmptySupervisorChannels(nowMs, platform);
756
- } catch {
757
- }
758
- };
759
- const poll = () => {
760
- cleanupStaleChannelsIfDue();
761
- refreshPendingRequests(pending, state, observeRequestLifecycle, runState);
762
- if (queuedNotices.size) extendQueuedNotices();
763
- const now = Date.now();
764
- const channels = deps.getChannelDirs?.();
765
- for (const { channelDir, file } of listRequestFiles(channels?.dirs, platform)) {
766
- if (seenFiles.has(file)) continue;
767
- const request = parseRequestFile(file, channelDir);
768
- if (!request || !requestMatchesOwner(request, state)) continue;
769
- const lifecycle = requestLifecycle(request, state, now, runState(request));
770
- if (lifecycle !== "pending") {
771
- seenFiles.add(file);
772
- observeRequestLifecycle(request, lifecycle);
773
- cleanupRequestLifecycle(request, lifecycle);
774
- continue;
775
- }
776
- if (request.expectsReply && runState(request).blockingWorkflowChildren?.has(request.runId)) {
777
- try {
778
- writePrivateAtomicJson(replyPath(channelDir, request.id), {
779
- type: "subagent.supervisor.reply",
780
- requestId: request.id,
781
- createdAt: now,
782
- message: "",
783
- error: "Supervisor unavailable: the parent is blocked in an async:false workflow and cannot answer this request. Report the blocker and any partial results, then stop. Relaunch the workflow with async:true to allow supervisor replies."
784
- });
785
- } catch (error) {
786
- console.error(`Failed to report unreachable supervisor request ${request.id}; will retry:`, error);
787
- continue;
788
- }
789
- seenFiles.add(file);
790
- observeRequestLifecycle(request, "resolved");
791
- cleanupRequestLifecycle(request, "resolved");
792
- continue;
793
- }
794
- seenFiles.add(file);
795
- if (!request.expectsReply) {
796
- removeRequestFile(request.requestFile);
797
- continue;
798
- }
799
- rememberPendingRequest(request);
800
- pending.set(request.id, request);
801
- declareParentTool();
802
- updateSettleSubscription();
803
- markForegroundSupervisorAttention(request, state);
804
- const claimed = deps.supervisorDispatcher?.claim({
805
- askId: request.id,
806
- runId: request.runId,
807
- agent: request.agent,
808
- childIndex: request.childIndex,
809
- reason: request.reason,
810
- message: request.message,
811
- ...request.interview !== void 0 ? { interview: request.interview } : {},
812
- ...request.expiresAt !== void 0 ? { deadlineAt: request.expiresAt } : {}
813
- }, (message2) => deliverClaimedReply(request, message2)) === true;
814
- if (claimed) {
815
- claimedAsks.add(request.id);
816
- continue;
148
+ name: WATCHDOG_DIFF_TOOL_NAME,
149
+ label: "Watchdog diff",
150
+ description: !baseline ? "Report that a Git HEAD diff baseline is unavailable in this cwd. No diff is generated." : workingTreeAtLaunch ? "Show the current staged and unstaged working-tree delta against reviewer-launch HEAD, plus untracked file paths, including edits by other sessions in this checkout. Committed ranges are not included. Optional path narrows it; stat:true returns per-file counts only." : "Show the repository diff since the review baseline, plus untracked file paths, including edits by other sessions in this checkout. Optional path narrows it; stat:true returns per-file counts only.",
151
+ parameters: WatchdogDiffParams,
152
+ executionMode: "sequential",
153
+ async execute(_toolCallId, params) {
154
+ if (!baseline) {
155
+ return { content: [{ type: "text", text: WATCHDOG_DIFF_UNAVAILABLE_BASELINE }], details: { chars: WATCHDOG_DIFF_UNAVAILABLE_BASELINE.length } };
817
156
  }
818
- try {
819
- const appended = (deps.parentWake ?? pi).sendMessage({
820
- customType: SUPERVISOR_REQUEST_MESSAGE_TYPE,
821
- content: requestVisibleText(request),
822
- display: true,
823
- details: {
824
- id: request.id,
825
- requestId: request.id,
826
- reason: request.reason,
827
- expectsReply: request.expectsReply,
828
- runId: request.runId,
829
- agent: request.agent,
830
- childIndex: request.childIndex,
831
- ...request.childTarget ? { childTarget: request.childTarget } : {},
832
- ...request.interview !== void 0 ? { interview: request.interview } : {},
833
- requestBody: request.message,
834
- replyHint: supervisorReplyHint(request.id)
835
- }
836
- }, { triggerTurn: true });
837
- if (appended === false && started && pending.has(request.id)) {
838
- queuedNotices.add(request.id);
839
- updateDeliverySubscription();
157
+ const pathFilter = validatePath(params.path);
158
+ const diff = runGit(baseline.root, ["diff", "--no-color", "--no-ext-diff", ...params.stat === true ? ["--stat"] : [], baseline.ref, "--", ...pathFilter ? [pathFilter] : []]);
159
+ if (!diff.ok) throw new Error(`git diff failed: ${diff.stderr || "unknown error"}`);
160
+ const untrackedResult = runGit(baseline.root, ["ls-files", "--others", "--exclude-standard", "-z", "--", ...pathFilter ? [pathFilter] : []]);
161
+ if (workingTreeAtLaunch) {
162
+ const currentHead = runGit(baseline.root, ["rev-parse", "HEAD"]);
163
+ if (!currentHead.ok || currentHead.stdout.trim() !== baseline.ref) {
164
+ const text2 = "Reviewer-launch HEAD changed or is unavailable. Committed changes are unsupported; relaunch the reviewer or supply a diff artifact.";
165
+ return { content: [{ type: "text", text: text2 }], details: { chars: text2.length } };
840
166
  }
841
- } catch (error) {
842
- console.error(`Failed to surface supervisor request ${request.id} as a user turn:`, error);
843
- }
844
- pi.events?.emit(INTERCOM_DETACH_REQUEST_EVENT, {
845
- requestId: request.id,
846
- runId: request.runId,
847
- agent: request.agent,
848
- childIndex: request.childIndex
849
- });
850
- if (pending.has(request.id)) markForegroundSupervisorAttention(request, state);
851
- }
852
- channels?.retire?.();
853
- updateSettleSubscription();
854
- };
855
- const handleBeforeSettle = (event) => {
856
- if (!started || event.outcome !== "completed")
857
- return;
858
- refreshPendingRequests(pending, state, observeRequestLifecycle, runState);
859
- if (event.continue || event.context.pendingMessages.length)
860
- return;
861
- const messages = event.context.contextMessages;
862
- const requests = [...pending.values()].filter((request) => {
863
- if (claimedAsks.has(request.id)) return false;
864
- if (!request.expectsReply || settleNotices.get(request.id) === "warned" || settleNotices.get(request.id) === "handled") return false;
865
- const index = messages.findLastIndex((message2) => message2.role === "custom" && message2.customType === SUPERVISOR_REQUEST_MESSAGE_TYPE && message2.details?.requestId === request.id);
866
- const acted = index !== -1 && messages.slice(index + 1).some((message2) => message2.role === "assistant" && message2.content.some((part) => part.type === "toolCall" || part.type === "text" && part.text.trim()));
867
- if (index === -1 || acted) {
868
- settleNotices.set(request.id, "handled");
869
- return false;
870
- }
871
- return true;
872
- });
873
- updateSettleSubscription();
874
- if (!requests.length) return;
875
- declareParentTool();
876
- const unanswered = requests.filter((request) => !settleNotices.has(request.id));
877
- if (unanswered.length) {
878
- for (const request of unanswered)
879
- settleNotices.set(request.id, "reminded");
880
- return {
881
- entries: [...event.entries, {
882
- type: "custom_message",
883
- customType: "subagent-supervisor-unanswered",
884
- content: "Silent supervisor wake. Pending request IDs: " + requests.map((request) => request.id).join(", ") + '. Check subagent_supervisor({ action: "pending" }) and reply within existing authority, or explicitly ask the user for approval. Do not auto-approve.',
885
- display: true,
886
- details: { requestIds: requests.map((request) => request.id) }
887
- }],
888
- continue: true
889
- };
890
- }
891
- const unflagged = requests.filter((request) => settleNotices.get(request.id) !== "warned");
892
- if (!unflagged.length)
893
- return;
894
- for (const request of unflagged)
895
- settleNotices.set(request.id, "warned");
896
- updateSettleSubscription();
897
- return {
898
- entries: [...event.entries, {
899
- type: "custom_message",
900
- customType: "subagent-supervisor-blocked",
901
- content: "BLOCKED: unanswered supervisor request IDs: " + unflagged.map((request) => request.id).join(", ") + '. Reminder budget exhausted; no reply or approval sent. Inspect subagent_supervisor({ action: "pending" }).',
902
- display: true,
903
- details: { blocked: true, requestIds: unflagged.map((request) => request.id) }
904
- }]
905
- };
906
- };
907
- const updateSettleSubscription = () => {
908
- const needed = started && [...pending.values()].some((request) => request.expectsReply && settleNotices.get(request.id) !== "warned" && settleNotices.get(request.id) !== "handled");
909
- if (needed && !unsubscribeSettle) unsubscribeSettle = pi.on?.("agent_before_settle", handleBeforeSettle);
910
- if (!needed) {
911
- unsubscribeSettle?.();
912
- unsubscribeSettle = void 0;
913
- }
914
- };
915
- const noticeDelivered = (event) => {
916
- const message2 = event.message;
917
- if (message2.role !== "custom" || message2.customType !== SUPERVISOR_REQUEST_MESSAGE_TYPE) return;
918
- const requestId = message2.details?.requestId;
919
- if (typeof requestId === "string" && queuedNotices.delete(requestId)) updateDeliverySubscription();
920
- };
921
- const parentRunSettled = () => {
922
- queuedNotices.clear();
923
- updateDeliverySubscription();
924
- };
925
- const updateDeliverySubscription = () => {
926
- const needed = started && queuedNotices.size > 0;
927
- if (needed && !unsubscribeDelivery) {
928
- unsubscribeDelivery = [pi.on?.("message_start", noticeDelivered), pi.on?.("agent_settled", parentRunSettled)];
929
- }
930
- if (!needed) {
931
- for (const unsubscribe of unsubscribeDelivery ?? []) unsubscribe?.();
932
- unsubscribeDelivery = void 0;
933
- }
934
- };
935
- const extendQueuedNotices = () => {
936
- const now = Date.now();
937
- const timeoutMs = askTimeoutMs();
938
- for (const id2 of queuedNotices) {
939
- const request = pending.get(id2);
940
- if (!request || requestExpiresAt(request, now) - now > timeoutMs / 2 || !fs.existsSync(request.requestFile)) continue;
941
- const { channelDir: _channelDir, requestFile, ...stored } = request;
942
- try {
943
- writePrivateAtomicJson(requestFile, { ...stored, expiresAt: now + timeoutMs });
944
- request.expiresAt = now + timeoutMs;
945
- } catch (error) {
946
- queuedNotices.delete(id2);
947
- updateDeliverySubscription();
948
- console.error(`Failed to extend supervisor request ${id2} while its notice is queued; it keeps its current deadline:`, error);
949
167
  }
950
- }
951
- };
952
- const startPolling = () => {
953
- if (poller) return;
954
- poller = timers.setInterval(() => {
955
- poll();
956
- if (!useNativeWatcher() && !hasTransportDemand()) {
957
- if (poller) timers.clearInterval(poller);
958
- poller = void 0;
168
+ const untracked = untrackedResult.ok ? untrackedResult.stdout.split("\0").filter(Boolean) : [];
169
+ const sections = [diff.stdout.trimEnd()];
170
+ if (untracked.length) {
171
+ const shown = untracked.slice(0, MAX_UNTRACKED_FILES);
172
+ sections.push(["Untracked files (use read to inspect):", ...shown.map((file) => ` ${file}`)].join("\n"));
173
+ if (untracked.length > shown.length) sections.push(`... ${untracked.length - shown.length} more untracked files`);
959
174
  }
960
- }, CHANNEL_POLL_MS);
961
- poller.unref?.();
962
- };
963
- const startSafetyPolling = () => {
964
- if (safetyPoller) return;
965
- safetyPoller = timers.setInterval(() => {
966
- watchExistingRequestDirs();
967
- poll();
968
- }, CHANNEL_SAFETY_POLL_MS);
969
- safetyPoller.unref?.();
970
- };
971
- const watchRequestDir = (requestsDir) => {
972
- if (requestWatchers.has(requestsDir)) return;
973
- try {
974
- const watcher = watch2(requestsDir, () => poll());
975
- watcher.on("error", () => {
976
- try {
977
- watcher.close();
978
- } catch {
979
- }
980
- requestWatchers.delete(requestsDir);
981
- startPolling();
982
- });
983
- watcher.unref?.();
984
- requestWatchers.set(requestsDir, watcher);
985
- } catch (error) {
986
- if (error.code !== "ENOENT") startPolling();
987
- }
988
- };
989
- const watchExistingRequestDirs = () => {
990
- let channelEntries;
991
- try {
992
- channelEntries = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true });
993
- } catch (error) {
994
- if (isMissingSupervisorDirectory(error, platform)) return;
995
- startPolling();
996
- return;
997
- }
998
- for (const entry of channelEntries) {
999
- if (entry.isDirectory()) watchRequestDir(path.join(SUPERVISOR_CHANNEL_ROOT, entry.name, REQUESTS_DIR));
175
+ const text = bound(sections.filter(Boolean).join("\n\n")) || (workingTreeAtLaunch ? `No working-tree changes against reviewer-launch HEAD ${baseline.ref.slice(0, 12)}. Committed changes are not included.` : `No changes since baseline ${baseline.ref.slice(0, 12)}.`);
176
+ return { content: [{ type: "text", text }], details: { chars: text.length } };
1000
177
  }
1001
178
  };
1002
- const scheduleWatcherRefresh = () => {
1003
- if (deferredWatcherRefresh) return;
1004
- deferredWatcherRefresh = timers.setImmediate(() => {
1005
- deferredWatcherRefresh = void 0;
1006
- if (!started) return;
1007
- watchExistingRequestDirs();
1008
- poll();
1009
- });
1010
- deferredWatcherRefresh.unref?.();
1011
- };
1012
- return {
1013
- registerTools: registerParentTools,
1014
- activateTransport: () => {
1015
- if (!started) return;
1016
- poll();
1017
- if (!useNativeWatcher() && hasTransportDemand()) startPolling();
1018
- },
1019
- findPendingAsks: (target) => {
1020
- const channelDir = resolveSupervisorChannelDir(target.runId, target.agent, target.childIndex);
1021
- let files;
1022
- try {
1023
- files = fs.readdirSync(path.join(channelDir, REQUESTS_DIR));
1024
- } catch (error) {
1025
- if (isMissingSupervisorDirectory(error, platform)) return [];
1026
- throw error;
1027
- }
1028
- const now = Date.now();
1029
- return files.filter((file) => file.endsWith(".json")).flatMap((file) => {
1030
- const request = parseRequestFile(path.join(channelDir, REQUESTS_DIR, file), channelDir);
1031
- return request?.expectsReply && request.runId === target.runId && request.agent === target.agent && request.childIndex === target.childIndex && requestLifecycle(request, state, now, runState(request)) === "pending" ? [request.id] : [];
1032
- }).sort();
1033
- },
1034
- hasPendingRequests: () => {
1035
- if (!started) return false;
1036
- poll();
1037
- return pending.size > 0;
1038
- },
1039
- start: () => {
1040
- if (started) return;
1041
- started = true;
1042
- registerParentTools();
1043
- poll();
1044
- if (deps.getChannelDirs) return;
1045
- try {
1046
- fs.mkdirSync(SUPERVISOR_CHANNEL_ROOT, { recursive: true });
1047
- if (!useNativeWatcher()) {
1048
- if (platform === "win32") startPolling();
1049
- return;
1050
- }
1051
- watchExistingRequestDirs();
1052
- rootWatcher = watch2(SUPERVISOR_CHANNEL_ROOT, () => {
1053
- watchExistingRequestDirs();
1054
- poll();
1055
- scheduleWatcherRefresh();
1056
- });
1057
- rootWatcher.on("error", startPolling);
1058
- startSafetyPolling();
1059
- scheduleWatcherRefresh();
1060
- } catch {
1061
- startPolling();
1062
- }
1063
- },
1064
- dispose: () => {
1065
- started = false;
1066
- updateSettleSubscription();
1067
- queuedNotices.clear();
1068
- updateDeliverySubscription();
1069
- try {
1070
- rootWatcher?.close();
1071
- } catch {
1072
- }
1073
- rootWatcher = void 0;
1074
- for (const watcher of requestWatchers.values()) {
1075
- try {
1076
- watcher.close();
1077
- } catch {
1078
- }
1079
- }
1080
- requestWatchers.clear();
1081
- if (poller) timers.clearInterval(poller);
1082
- poller = void 0;
1083
- if (safetyPoller) timers.clearInterval(safetyPoller);
1084
- safetyPoller = void 0;
1085
- if (deferredWatcherRefresh) timers.clearImmediate(deferredWatcherRefresh);
1086
- deferredWatcherRefresh = void 0;
1087
- pending.clear();
1088
- claimedAsks.clear();
1089
- settleNotices.clear();
1090
- requestCorrelations.clear();
1091
- seenFiles.clear();
1092
- },
1093
- pending,
1094
- getSupervisorRequestState
1095
- };
1096
- }
1097
-
1098
- // src/shared/session-identity.ts
1099
- import * as fs2 from "node:fs";
1100
- function resolveCurrentSessionId(sessionManager) {
1101
- const sessionId = sessionManager.getSessionFile() ?? sessionManager.getSessionId();
1102
- if (!sessionId) throw new Error("Current session identity is unavailable.");
1103
- return sessionId;
1104
- }
1105
- function resolvePiSessionId(sessionFile) {
1106
- if (!sessionFile) return void 0;
1107
- try {
1108
- const fd = fs2.openSync(sessionFile, "r");
1109
- try {
1110
- const buffer = Buffer.alloc(16 * 1024);
1111
- const bytes = fs2.readSync(fd, buffer, 0, buffer.length, 0);
1112
- const line = buffer.toString("utf-8", 0, bytes).split("\n", 1)[0];
1113
- if (!line) return void 0;
1114
- const header = JSON.parse(line);
1115
- if (header.type === "session" && typeof header.id === "string" && /^[A-Za-z0-9-]{8,}$/.test(header.id)) return header.id;
1116
- return void 0;
1117
- } finally {
1118
- fs2.closeSync(fd);
1119
- }
1120
- } catch {
1121
- return void 0;
1122
- }
1123
179
  }
1124
180
 
1125
181
  // src/watchdog/settings.ts
1126
- import * as fs3 from "node:fs";
182
+ import * as fs2 from "node:fs";
1127
183
  import * as path2 from "node:path";
1128
184
  var DEFAULT_WATCHDOG_CONFIG = {
1129
185
  enabled: false,
@@ -1373,10 +429,10 @@ function parseSettingsObject(settings, meta) {
1373
429
  return parseWatchdogPatch(subagents.watchdog, "subagents.watchdog", meta);
1374
430
  }
1375
431
  function readSettingsFileStrict(filePath) {
1376
- if (!fs3.existsSync(filePath)) return {};
432
+ if (!fs2.existsSync(filePath)) return {};
1377
433
  let raw;
1378
434
  try {
1379
- raw = fs3.readFileSync(filePath, "utf-8");
435
+ raw = fs2.readFileSync(filePath, "utf-8");
1380
436
  } catch (error) {
1381
437
  const message2 = error instanceof Error ? error.message : String(error);
1382
438
  throw new Error(`Failed to read settings file '${filePath}': ${message2}`, { cause: error });
@@ -1395,7 +451,7 @@ function readSettingsFileStrict(filePath) {
1395
451
  }
1396
452
  function isDirectory(dir) {
1397
453
  try {
1398
- return fs3.statSync(dir).isDirectory();
454
+ return fs2.statSync(dir).isDirectory();
1399
455
  } catch {
1400
456
  return false;
1401
457
  }
@@ -1462,8 +518,8 @@ function targetSettingsObject(watchdog, target, meta) {
1462
518
  return ensureObjectField(overrides, target.agent.trim(), `subagents.watchdog.children.overrides.${target.agent.trim()}`, meta);
1463
519
  }
1464
520
  function writeSettingsFile(settingsPath, settings) {
1465
- fs3.mkdirSync(path2.dirname(settingsPath), { recursive: true });
1466
- fs3.writeFileSync(settingsPath, `${JSON.stringify(settings, null, 2)}
521
+ fs2.mkdirSync(path2.dirname(settingsPath), { recursive: true });
522
+ fs2.writeFileSync(settingsPath, `${JSON.stringify(settings, null, 2)}
1467
523
  `, "utf-8");
1468
524
  return settingsPath;
1469
525
  }
@@ -1502,7 +558,7 @@ function resolveWatchdogConfig(cwd2, options = {}) {
1502
558
  ];
1503
559
  for (const source of sourceSpecs) {
1504
560
  if (!source.path) continue;
1505
- sources.push({ scope: source.scope, path: source.path, exists: fs3.existsSync(source.path) });
561
+ sources.push({ scope: source.scope, path: source.path, exists: fs2.existsSync(source.path) });
1506
562
  try {
1507
563
  patch = deepMerge(patch, parseSourceFile(source.path, source.scope));
1508
564
  } catch (error) {
@@ -1763,6 +819,7 @@ var SubagentParamProperties = {
1763
819
  description: 'Management/control only; omit for execution. validate accepts workflow: true or a script path. Discover actions with {action:"guide",options:{topic:"tool-reference"}}.'
1764
820
  })),
1765
821
  capabilities: Type2.Optional(Type2.Boolean({ description: "list: compact capability rows/details without system prompts." })),
822
+ search: Type2.Optional(Type2.String({ minLength: 1, description: "list: case-insensitive match on agent name, alias, or description." })),
1766
823
  name: Type2.Optional(Type2.String({ description: "schedule.create name." })),
1767
824
  id: Type2.Optional(Type2.String({
1768
825
  description: "Run id/prefix for status/control."
@@ -1781,6 +838,7 @@ var SubagentParamProperties = {
1781
838
  supersession: Type2.Optional(Type2.Unsafe({ type: "object", additionalProperties: true, description: "lane.recordSupersession evidence; read guide tool-reference." })),
1782
839
  index: Type2.Optional(Type2.Integer({ minimum: 0, description: "Zero-based child/transcript index." })),
1783
840
  childId: Type2.Optional(Type2.String({ minLength: 1, maxLength: 256, description: "Child-scoped stop identity." })),
841
+ drain: Type2.Optional(Type2.Boolean({ description: "stop: a live async workflow starts no new children; started ones finish." })),
1784
842
  toolCallId: Type2.Optional(Type2.String({ description: "Command tool-call id." })),
1785
843
  view: Type2.Optional(Type2.String({
1786
844
  enum: ["fleet", "transcript"],
@@ -1848,6 +906,10 @@ var SubagentParamProperties = {
1848
906
  agentScope: Type2.Optional(Type2.String({ description: "user/project/both (default); project wins collisions." })),
1849
907
  cwd: Type2.Optional(Type2.String({ description: "Execution/project-pane directory." })),
1850
908
  machine: Type2.Optional(Type2.String({ minLength: 1, maxLength: 128, description: 'Herdr saved machine id or label (runs an external CLI agent), a Rex host named in settings (runs a Pi child), or "local" (a Pi child in a Rex pane here). On another machine, cwd is a directory there.' })),
909
+ requireLauncher: Type2.Optional(Type2.Object({
910
+ name: Type2.String({ pattern: RUNNER_LAUNCHER_NAME_PATTERN.source }),
911
+ definitionDigest: Type2.String({ pattern: "^[0-9a-f]{64}$" })
912
+ }, { additionalProperties: false, description: "Top-level single async launch only: refuse unless the agent runs under this launcher with this definition digest (preflight agent.definitionDigest)." })),
1851
913
  artifacts: Type2.Optional(Type2.Boolean({ description: "Debug artifacts; default true." })),
1852
914
  includeProgress: Type2.Optional(Type2.Boolean({ description: "Full result progress; default false." })),
1853
915
  share: Type2.Optional(Type2.Boolean({ description: "Upload session to GitHub Gist; default false." })),
@@ -1936,6 +998,8 @@ var SubagentWaitParams = keepTopLevelParameterDescriptions(SubagentWaitParamsSch
1936
998
  // src/runs/background/wait-config.ts
1937
999
  var WAIT_TOOL_ENABLED_ENV = "PI_SUBAGENT_WAIT_TOOL_ENABLED";
1938
1000
  var WAIT_TOOL_DEFAULT_TIMEOUT_MS_ENV = "PI_SUBAGENT_WAIT_TOOL_DEFAULT_TIMEOUT_MS";
1001
+ var WAIT_TOOL_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
1002
+ var RESERVED_TOOL_NAMES = /* @__PURE__ */ new Set(["subagent", "subagents_enable", "subagent_supervisor", "contact_supervisor", "intercom", "structured_output", "subagent_launch", "subagent_command", "watchdog_diff", "watchdog_ask", "watchdog_warn", "watchdog_permission_decision"]);
1939
1003
  var TRUE_VALUES = /* @__PURE__ */ new Set(["1", "true", "yes", "on", "enabled"]);
1940
1004
  var FALSE_VALUES = /* @__PURE__ */ new Set(["0", "false", "no", "off", "disabled"]);
1941
1005
  function environmentValue(value) {
@@ -1955,33 +1019,42 @@ function configuredValue(config) {
1955
1019
  if (config === void 0) return {};
1956
1020
  if (typeof config === "boolean") return { enabled: config };
1957
1021
  if (!config || typeof config !== "object" || Array.isArray(config)) {
1958
- throw new Error("config.waitTool must be a boolean or an object with optional enabled and defaultTimeoutMs values.");
1022
+ throw new Error("config.waitTool must be a boolean or an object with optional enabled, defaultTimeoutMs and name values.");
1959
1023
  }
1960
- const { enabled, defaultTimeoutMs } = config;
1024
+ const { enabled, defaultTimeoutMs, name } = config;
1961
1025
  if (enabled !== void 0 && typeof enabled !== "boolean") throw new Error("config.waitTool.enabled must be a boolean.");
1962
1026
  if (defaultTimeoutMs !== void 0 && (!Number.isInteger(defaultTimeoutMs) || defaultTimeoutMs < 1)) {
1963
1027
  throw new Error("config.waitTool.defaultTimeoutMs must be a positive integer.");
1964
1028
  }
1965
- return { enabled, ...defaultTimeoutMs !== void 0 ? { defaultTimeoutMs } : {} };
1029
+ if (name !== void 0 && (typeof name !== "string" || !WAIT_TOOL_NAME_PATTERN.test(name))) {
1030
+ throw new Error("config.waitTool.name must start with a letter and contain only letters, digits and underscores (at most 64 characters).");
1031
+ }
1032
+ if (typeof name === "string" && RESERVED_TOOL_NAMES.has(name)) throw new Error(`config.waitTool.name "${name}" is already a pi-subagents tool.`);
1033
+ return {
1034
+ enabled,
1035
+ ...defaultTimeoutMs !== void 0 ? { defaultTimeoutMs } : {},
1036
+ ...name !== void 0 && name !== DEFAULT_WAIT_TOOL_NAME ? { name } : {}
1037
+ };
1966
1038
  }
1967
1039
  function resolveWaitToolConfig(config, env = process.env) {
1968
1040
  const configured = configuredValue(config);
1969
1041
  const envDefaultTimeoutMs = environmentDefaultTimeoutMs(env[WAIT_TOOL_DEFAULT_TIMEOUT_MS_ENV]);
1970
1042
  return {
1971
1043
  enabled: environmentValue(env[WAIT_TOOL_ENABLED_ENV]) ?? configured.enabled ?? true,
1972
- ...envDefaultTimeoutMs ?? configured.defaultTimeoutMs !== void 0 ? { defaultTimeoutMs: envDefaultTimeoutMs ?? configured.defaultTimeoutMs } : {}
1044
+ ...envDefaultTimeoutMs ?? configured.defaultTimeoutMs !== void 0 ? { defaultTimeoutMs: envDefaultTimeoutMs ?? configured.defaultTimeoutMs } : {},
1045
+ ...configured.name ? { name: configured.name } : {}
1973
1046
  };
1974
1047
  }
1975
1048
 
1976
1049
  // src/runs/background/subagent-wait.ts
1977
- import * as fs7 from "node:fs";
1978
- import * as path4 from "node:path";
1050
+ import * as fs6 from "node:fs";
1051
+ import * as path5 from "node:path";
1979
1052
 
1980
1053
  // src/runs/background/wait-completions.ts
1981
- import * as fs5 from "node:fs";
1054
+ import * as fs4 from "node:fs";
1982
1055
 
1983
1056
  // src/runs/background/completion-replay.ts
1984
- import * as fs4 from "node:fs";
1057
+ import * as fs3 from "node:fs";
1985
1058
  import * as path3 from "node:path";
1986
1059
  var REPLAY_VERSION = 1;
1987
1060
  var ARCHIVE_VERSION = 1;
@@ -2006,7 +1079,7 @@ function existingFile(value) {
2006
1079
  const filePath = nonEmptyString(value);
2007
1080
  if (!filePath) return void 0;
2008
1081
  try {
2009
- return fs4.statSync(filePath).isFile() ? filePath : void 0;
1082
+ return fs3.statSync(filePath).isFile() ? filePath : void 0;
2010
1083
  } catch {
2011
1084
  return void 0;
2012
1085
  }
@@ -2091,7 +1164,7 @@ function runIdFromReplayFile(file) {
2091
1164
  }
2092
1165
  function removeBestEffort(filePath) {
2093
1166
  try {
2094
- fs4.rmSync(filePath, { force: true });
1167
+ fs3.rmSync(filePath, { force: true });
2095
1168
  } catch {
2096
1169
  }
2097
1170
  }
@@ -2134,7 +1207,7 @@ function readCompletionReplay(resultsDir, runId, options = {}) {
2134
1207
  const replayPath = completionReplayPath(resultsDir, runId);
2135
1208
  let parsed;
2136
1209
  try {
2137
- parsed = parseReplay(JSON.parse(fs4.readFileSync(replayPath, "utf-8")));
1210
+ parsed = parseReplay(JSON.parse(fs3.readFileSync(replayPath, "utf-8")));
2138
1211
  } catch (error) {
2139
1212
  if (error.code === "ENOENT") return void 0;
2140
1213
  throw error;
@@ -2156,7 +1229,7 @@ function readCompletionReplay(resultsDir, runId, options = {}) {
2156
1229
  }
2157
1230
  function readCompletionArchive(archivePath) {
2158
1231
  try {
2159
- const archive = parseArchive(JSON.parse(fs4.readFileSync(archivePath, "utf-8")));
1232
+ const archive = parseArchive(JSON.parse(fs3.readFileSync(archivePath, "utf-8")));
2160
1233
  if (!archive) throw new Error("Completion archive is malformed.");
2161
1234
  return archive;
2162
1235
  } catch (error) {
@@ -2174,20 +1247,20 @@ function cleanupCompletionReplayIfDue(resultsDir, now, maxAgeMs, intervalMs = CL
2174
1247
  function cleanupCompletionReplay(resultsDir, now, maxAgeMs) {
2175
1248
  const replayDir = path3.join(resultsDir, REPLAY_DIR_NAME);
2176
1249
  try {
2177
- for (const file of fs4.readdirSync(replayDir)) {
1250
+ for (const file of fs3.readdirSync(replayDir)) {
2178
1251
  const runId = runIdFromReplayFile(file);
2179
1252
  if (!runId) continue;
2180
1253
  const filePath = path3.join(replayDir, file);
2181
1254
  try {
2182
- const record = parseReplay(JSON.parse(fs4.readFileSync(filePath, "utf-8")));
1255
+ const record = parseReplay(JSON.parse(fs3.readFileSync(filePath, "utf-8")));
2183
1256
  const safeRecord = record ? validateReplayRecord(resultsDir, runId, record) : void 0;
2184
1257
  if (record && !safeRecord) {
2185
- fs4.rmSync(filePath, { force: true });
1258
+ fs3.rmSync(filePath, { force: true });
2186
1259
  } else if (safeRecord && safeRecord.expiresAt <= now) {
2187
- fs4.rmSync(filePath, { force: true });
2188
- fs4.rmSync(safeRecord.archivePath, { force: true });
2189
- } else if (!record && now - fs4.statSync(filePath).mtimeMs > maxAgeMs) {
2190
- fs4.rmSync(filePath, { force: true });
1260
+ fs3.rmSync(filePath, { force: true });
1261
+ fs3.rmSync(safeRecord.archivePath, { force: true });
1262
+ } else if (!record && now - fs3.statSync(filePath).mtimeMs > maxAgeMs) {
1263
+ fs3.rmSync(filePath, { force: true });
2191
1264
  }
2192
1265
  } catch {
2193
1266
  }
@@ -2196,10 +1269,10 @@ function cleanupCompletionReplay(resultsDir, now, maxAgeMs) {
2196
1269
  }
2197
1270
  const archiveDir = path3.join(resultsDir, ARCHIVE_DIR_NAME);
2198
1271
  try {
2199
- for (const file of fs4.readdirSync(archiveDir)) {
1272
+ for (const file of fs3.readdirSync(archiveDir)) {
2200
1273
  const filePath = path3.join(archiveDir, file);
2201
1274
  try {
2202
- if (now - fs4.statSync(filePath).mtimeMs > maxAgeMs) fs4.rmSync(filePath, { force: true });
1275
+ if (now - fs3.statSync(filePath).mtimeMs > maxAgeMs) fs3.rmSync(filePath, { force: true });
2203
1276
  } catch {
2204
1277
  }
2205
1278
  }
@@ -2251,7 +1324,7 @@ function waitResultPayloadCandidate(resultsDir, run) {
2251
1324
  }
2252
1325
  function readWaitResultPayload(candidatePath, run) {
2253
1326
  if (!run.sessionId) return void 0;
2254
- const payload = JSON.parse(fs5.readFileSync(candidatePath, "utf-8"));
1327
+ const payload = JSON.parse(fs4.readFileSync(candidatePath, "utf-8"));
2255
1328
  if (!resultPayloadMatchesSessionRun(payload, run.sessionId, run.id)) return void 0;
2256
1329
  return payload;
2257
1330
  }
@@ -2411,21 +1484,22 @@ function collectWaitCompletions(terminal, state, resultsDir, onReference) {
2411
1484
  }
2412
1485
 
2413
1486
  // src/runs/background/resume-guidance.ts
2414
- import * as fs6 from "node:fs";
1487
+ import * as fs5 from "node:fs";
1488
+ import * as path4 from "node:path";
2415
1489
  var INTERCOM_DETACH_ERROR = "detached for intercom coordination";
2416
1490
  function isIntercomDetached(run) {
2417
1491
  return run.steps.some((step) => step.execution?.status === "detached" || errorWithoutReplyText(step.error)?.toLowerCase().includes(INTERCOM_DETACH_ERROR) === true) || errorWithoutReplyText(run.error)?.toLowerCase().includes(INTERCOM_DETACH_ERROR) === true;
2418
1492
  }
2419
1493
  function formatIntercomDetachGuidance(run) {
2420
1494
  if (!isIntercomDetached(run)) return void 0;
2421
- return `Run "${run.id}" detached for intercom coordination. Reply to the supervisor request first, then wait with bg_wait({ id: "${run.id}" }). Use subagent({ action: "status", id: "${run.id}" }) to recover the result; do not resume or launch a replacement while it remains detached.`;
1495
+ return `Run "${run.id}" detached for intercom coordination. Reply to the supervisor request first, then wait with ${waitToolName()}({ id: "${run.id}" }). Use subagent({ action: "status", id: "${run.id}" }) to recover the result; do not resume or launch a replacement while it remains detached.`;
2422
1496
  }
2423
1497
  function formatAsyncReviveCommand(run) {
2424
1498
  const step = run.steps.find((candidate) => candidate.status === "failed");
2425
1499
  const sessionFile = step?.sessionFile ?? (run.steps.length === 1 ? run.sessionFile : void 0);
2426
- if (!step || !sessionFile || !fs6.existsSync(sessionFile)) return void 0;
1500
+ if (!step || !sessionFile || !fs5.existsSync(sessionFile)) return void 0;
2427
1501
  try {
2428
- const descriptor = readAsyncRecoveryDescriptor(run.asyncDir);
1502
+ const descriptor = readAsyncRecoveryDescriptor(path4.dirname(run.asyncDir), path4.basename(run.asyncDir));
2429
1503
  if (!descriptor || descriptor.sourceRunId !== run.id || descriptor.agent !== step.agent) return void 0;
2430
1504
  } catch {
2431
1505
  return void 0;
@@ -2554,7 +1628,7 @@ function foregroundChildrenNeedingAttention(run, indices) {
2554
1628
  function formatForegroundAttention(run, children, elapsedMs) {
2555
1629
  const childList = children.map((child) => `${child.agent}${child.index !== void 0 ? `#${child.index}` : ""}`).join(", ");
2556
1630
  return result(
2557
- `Waited ${formatDuration(elapsedMs)} for remembered detached foreground run "${run.runId}"; attention required. ${children.length} child run(s) need attention: ${childList}. Reply to any pending supervisor request, then call bg_wait({ id: "${run.runId}" }) again or inspect status; do not resume or launch a replacement while it remains detached.`
1631
+ `Waited ${formatDuration(elapsedMs)} for remembered detached foreground run "${run.runId}"; attention required. ${children.length} child run(s) need attention: ${childList}. Reply to any pending supervisor request, then call ${waitToolName()}({ id: "${run.runId}" }) again or inspect status; do not resume or launch a replacement while it remains detached.`
2558
1632
  );
2559
1633
  }
2560
1634
  function needsAttention(run) {
@@ -2568,7 +1642,7 @@ function backgroundWorkIdentity(item) {
2568
1642
  }
2569
1643
  function backgroundWorkForSession(deps, nowMs) {
2570
1644
  const sessionId = deps.state.currentSessionId;
2571
- if (!sessionId) throw new Error("bg_wait requires an active session identity to scope background work safely.");
1645
+ if (!sessionId) throw new Error(`${waitToolName()} requires an active session identity to scope background work safely.`);
2572
1646
  const piSessionId = deps.state.supervisorOwnerSessionId;
2573
1647
  const sessionIds = piSessionId ? [sessionId, piSessionId] : [sessionId];
2574
1648
  return deps.backgroundWork?.snapshot(sessionIds, nowMs) ?? snapshotBackgroundWork(sessionIds, nowMs);
@@ -2581,7 +1655,7 @@ function waitRunScopes(deps) {
2581
1655
  }
2582
1656
  function collectScopedCompletions(terminal, deps, references) {
2583
1657
  const completions = waitRunScopes(deps).flatMap((scope) => collectWaitCompletions(
2584
- terminal.filter((run) => path4.resolve(path4.dirname(run.asyncDir)) === path4.resolve(scope.asyncDirRoot)),
1658
+ terminal.filter((run) => path5.resolve(path5.dirname(run.asyncDir)) === path5.resolve(scope.asyncDirRoot)),
2585
1659
  deps.state,
2586
1660
  scope.resultsDir,
2587
1661
  (reference) => references.push(reference)
@@ -2750,13 +1824,13 @@ function readTranscriptActivity(transcriptPath) {
2750
1824
  if (!transcriptPath) return void 0;
2751
1825
  let fd;
2752
1826
  try {
2753
- const stat = fs7.statSync(transcriptPath);
1827
+ const stat = fs6.statSync(transcriptPath);
2754
1828
  if (!stat.isFile() || stat.size <= 0) return void 0;
2755
1829
  const start = Math.max(0, stat.size - TRANSCRIPT_TAIL_BYTES);
2756
1830
  const length = stat.size - start;
2757
1831
  const buffer = Buffer.allocUnsafe(length);
2758
- fd = fs7.openSync(transcriptPath, "r");
2759
- const bytesRead = fs7.readSync(fd, buffer, 0, length, start);
1832
+ fd = fs6.openSync(transcriptPath, "r");
1833
+ const bytesRead = fs6.readSync(fd, buffer, 0, length, start);
2760
1834
  let lines = buffer.subarray(0, bytesRead).toString("utf-8").split(/\r?\n/);
2761
1835
  if (start > 0) lines = lines.slice(1);
2762
1836
  let currentTool;
@@ -2801,7 +1875,7 @@ function readTranscriptActivity(transcriptPath) {
2801
1875
  } finally {
2802
1876
  if (fd !== void 0) {
2803
1877
  try {
2804
- fs7.closeSync(fd);
1878
+ fs6.closeSync(fd);
2805
1879
  } catch {
2806
1880
  }
2807
1881
  }
@@ -2852,7 +1926,7 @@ async function waitForDetachedForegroundRun(run, signal, deps, startedAt, now, p
2852
1926
  }
2853
1927
  if (now() - startedAt >= timeoutMs) {
2854
1928
  return windowElapsedResult(
2855
- `Wait window elapsed after ${formatDuration(timeoutMs)} with remembered foreground run "${run.runId}" still detached. Reply to any pending supervisor request, then call bg_wait({ id: "${run.runId}" }) again or inspect status; do not resume or launch a replacement while it remains detached.`,
1929
+ `Wait window elapsed after ${formatDuration(timeoutMs)} with remembered foreground run "${run.runId}" still detached. Reply to any pending supervisor request, then call ${waitToolName()}({ id: "${run.runId}" }) again or inspect status; do not resume or launch a replacement while it remains detached.`,
2856
1930
  [run.runId]
2857
1931
  );
2858
1932
  }
@@ -2882,10 +1956,10 @@ async function waitForSessionDetachedForegroundRuns(runs, signal, deps, startedA
2882
1956
  }
2883
1957
  async function waitForSubagents(params, signal, deps) {
2884
1958
  if (deps.enabled === false) {
2885
- return result('bg_wait is disabled by config.waitTool or PI_SUBAGENT_WAIT_TOOL_ENABLED; returning immediately without blocking background work. Active work keeps going, and you can inspect subagents with subagent({ action: "status" }) or rely on completion notifications.');
1959
+ return result(`${waitToolName()} is disabled by config.waitTool or PI_SUBAGENT_WAIT_TOOL_ENABLED; returning immediately without blocking background work. Active work keeps going, and you can inspect subagents with subagent({ action: "status" }) or rely on completion notifications.`);
2886
1960
  }
2887
1961
  if (!deps.state.currentSessionId) {
2888
- return result("bg_wait requires an active session identity to scope background work safely.", true);
1962
+ return result(`${waitToolName()} requires an active session identity to scope background work safely.`, true);
2889
1963
  }
2890
1964
  const now = deps.now ?? Date.now;
2891
1965
  const pollIntervalMs = Math.max(MIN_POLL_INTERVAL_MS, deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS);
@@ -2940,7 +2014,7 @@ ${references2.join("\n")}` : ""}`,
2940
2014
  }
2941
2015
  if (selected && params.nonBlocking) {
2942
2016
  if (!deps.subscribe) {
2943
- return result("Non-blocking wait subscriptions require a long-lived interactive subagent runtime; this runtime can only use blocking bg_wait calls.", true);
2017
+ return result(`Non-blocking wait subscriptions require a long-lived interactive subagent runtime; this runtime can only use blocking ${waitToolName()} calls.`, true);
2944
2018
  }
2945
2019
  try {
2946
2020
  const registration = deps.subscribe({ targetKind: selected.kind, runId: selected.id, requestedId: params.id, timeoutMs });
@@ -3009,7 +2083,7 @@ ${references2.join("\n")}` : ""}`,
3009
2083
  }
3010
2084
  if (now() - startedAt >= timeoutMs) {
3011
2085
  return windowElapsedResult(
3012
- `Wait window elapsed after ${formatDuration(timeoutMs)} with ${activeInitialRuns.length} async run(s) and ${activeInitialProviderItems.length} provider item(s) still active: ${stillActive}. The work keeps going; call bg_wait again or inspect subagent status.`,
2086
+ `Wait window elapsed after ${formatDuration(timeoutMs)} with ${activeInitialRuns.length} async run(s) and ${activeInitialProviderItems.length} provider item(s) still active: ${stillActive}. The work keeps going; call ${waitToolName()} again or inspect subagent status.`,
3013
2087
  activeInitialRuns.map((run) => run.id),
3014
2088
  activeInitialProviderItems
3015
2089
  );
@@ -3022,7 +2096,7 @@ ${references2.join("\n")}` : ""}`,
3022
2096
  providerSnapshot = params.id ? providerSnapshot : backgroundWorkForSession(deps, now());
3023
2097
  for (const provider of initialProviderNames) {
3024
2098
  if (!providerSnapshot.providers.includes(provider)) {
3025
- return result(`Background-work provider '${provider}' disappeared while bg_wait was tracking its active work; completion cannot be confirmed.`, true);
2099
+ return result(`Background-work provider '${provider}' disappeared while ${waitToolName()} was tracking its active work; completion cannot be confirmed.`, true);
3026
2100
  }
3027
2101
  }
3028
2102
  providerActive = providerSnapshot.items;
@@ -3054,7 +2128,7 @@ ${references2.join("\n")}` : ""}`,
3054
2128
  }
3055
2129
  const relevantAttention = attention.filter((run) => initialAsyncIds.has(run.id));
3056
2130
  const supervisorAttentionHint = relevantAttention.some(hasSupervisorTool) ? ' Reply to any pending supervisor request. If subagent_supervisor({ action: "pending" }) is empty, check intercom({ action: "pending" }) because an external intercom tool may own the request.' : "";
3057
- const keepWaitingHint = stopOnAttention && supervisorAttentionHint === "" && (waitForAll || finishedAsyncCount + providerFinishedCount === 0) ? " These runs are still running and none is waiting on a supervisor reply. To keep waiting through this kind of attention, call bg_wait again with stopOnAttention: false; supervisor requests still end that wait." : "";
2131
+ const keepWaitingHint = stopOnAttention && supervisorAttentionHint === "" && (waitForAll || finishedAsyncCount + providerFinishedCount === 0) ? ` These runs are still running and none is waiting on a supervisor reply. To keep waiting through this kind of attention, call ${waitToolName()} again with stopOnAttention: false; supervisor requests still end that wait.` : "";
3058
2132
  const attentionNote = relevantAttention.length > 0 ? ` ${relevantAttention.length} run(s) need attention: ${relevantAttention.map((run) => run.id).join(", ")} \u2014${supervisorAttentionHint} inspect with subagent({ action: "status" }) then steer a top-level live async child, resume a paused/completed/failed child, or interrupt explicitly.${keepWaitingHint}` : "";
3059
2133
  const stillRunning = active.filter((run) => initialAsyncIds.has(run.id)).length + providerActive.filter((item) => initialProviderIds.has(backgroundWorkIdentity(item))).length;
3060
2134
  const elapsed = formatDuration(now() - startedAt);
@@ -3078,7 +2152,7 @@ ${foregroundResult.content.map((part) => part.type === "text" ? part.text : "").
3078
2152
  }
3079
2153
  const finishedCount = finishedAsyncCount + providerFinishedCount;
3080
2154
  const subject = initialProviderIds.size === 0 ? "run(s)" : "item(s)";
3081
- const remainder = stillRunning > 0 ? ` ${stillRunning} ${subject} still in flight \u2014 call bg_wait again to catch the next one.` : relevantAttention.length > 0 ? " No other work is waitable until attention is handled." : initialProviderIds.size === 0 ? " No runs remain in flight." : " No work remains in flight.";
2155
+ const remainder = stillRunning > 0 ? ` ${stillRunning} ${subject} still in flight \u2014 call ${waitToolName()} again to catch the next one.` : relevantAttention.length > 0 ? " No other work is waitable until attention is handled." : initialProviderIds.size === 0 ? " No runs remain in flight." : " No work remains in flight.";
3082
2156
  const progress = relevantAttention.length > 0 && finishedCount === 0 ? `${relevantAttention.length} of ${initialCount} ${subject} need attention` : `${finishedCount} of ${initialCount} ${subject} finished`;
3083
2157
  return result(
3084
2158
  `Waited ${elapsed}; ${progress}.${outcome}${recoveryNote}${resumeGuidance}${attentionNote}${remainder} Relevant completion/control events have been observed; inspect status if a notification is not visible yet.`,
@@ -3216,7 +2290,8 @@ function setDeclarationPinning(pi, pinned) {
3216
2290
 
3217
2291
  // src/runs/background/wait-tool.ts
3218
2292
  function registerWaitTool(pi, state, enabled = resolveWaitToolConfig().enabled, subscriptions, defaultTimeoutMs, child, hasPendingSupervisorRequest) {
3219
- const description = `Wait for background work, then return. ${child ? "This child runtime has no native completion notifier: use blocking bg_wait to collect your owned descendants this turn and read their result references; agent_end draining does not synthesize results." : "Ordinary async subagent runs already wake this session natively; use bg_wait only for provider, detached, or other background work without native notification, when a same-turn result is needed."}
2293
+ const name = waitToolName();
2294
+ const description = `Wait for background work, then return. ${child ? `This child runtime has no native completion notifier: use blocking ${name} to collect your owned descendants this turn and read their result references; agent_end draining does not synthesize results.` : `Ordinary async subagent runs already wake this session natively; use ${name} only for provider, detached, or other background work without native notification, when a same-turn result is needed.`}
3220
2295
  {} \u2014 first active run or provider item to finish or need attention.
3221
2296
  {all:true} \u2014 all work active at call time.
3222
2297
  {id} \u2014 one run; a finished async run returns its result references.
@@ -3247,7 +2322,7 @@ Timeout or a user message ends the wait without error; work keeps running.${enab
3247
2322
  }
3248
2323
  };
3249
2324
  const primaryTool = {
3250
- name: "bg_wait",
2325
+ name,
3251
2326
  label: "Background Wait",
3252
2327
  description,
3253
2328
  parameters: SubagentWaitParams,
@@ -3312,7 +2387,7 @@ async function drainOutstandingWork(deps, observation) {
3312
2387
  }
3313
2388
  );
3314
2389
  if (waitResult.isError) {
3315
- throw new Error(`Auto-drain failed for session '${sessionId}': ${resultText(waitResult) || "bg_wait returned an error without details"}.`);
2390
+ throw new Error(`Auto-drain failed for session '${sessionId}': ${resultText(waitResult) || `${waitToolName()} returned an error without details`}.`);
3316
2391
  }
3317
2392
  if (waitResult.details.wait?.reason === "supervisor_request") break;
3318
2393
  if (deps.hasPendingSupervisorRequest?.()) break;
@@ -3354,102 +2429,13 @@ function evaluateChildToolDiagnostic(config, availableTools) {
3354
2429
  };
3355
2430
  }
3356
2431
 
3357
- // src/watchdog/diff-tool.ts
3358
- import { execFile, spawnSync } from "node:child_process";
3359
- import * as path5 from "node:path";
3360
- import { Type as Type3 } from "typebox";
3361
- var WATCHDOG_DIFF_TOOL_NAME = "watchdog_diff";
3362
- var WATCHDOG_DIFF_MAX_CHARS = 24e3;
3363
- var WATCHDOG_DIFF_UNAVAILABLE_BASELINE = "watchdog_diff unavailable: this cwd has no valid Git HEAD baseline. No diff can be shown; inspect files with independent read-only tools instead.";
3364
- var MAX_UNTRACKED_FILES = 50;
3365
- var WatchdogDiffParams = Type3.Object({
3366
- path: Type3.Optional(Type3.String({ description: "Restrict the diff to one file or directory, relative to the repo root." })),
3367
- stat: Type3.Optional(Type3.Boolean({ description: "Return per-file change counts instead of the full diff." }))
3368
- }, { additionalProperties: false });
3369
- function runGit(root, args2) {
3370
- const result2 = spawnSync("git", ["-C", root, ...args2], { encoding: "utf-8", maxBuffer: 16 * 1024 * 1024, windowsHide: true });
3371
- return { ok: result2.status === 0, stdout: result2.stdout ?? "", stderr: (result2.stderr ?? "").trim() };
3372
- }
3373
- var BASELINE_ARGS = ["rev-parse", "--show-toplevel", "HEAD"];
3374
- function parseBaseline(stdout) {
3375
- const lines = stdout.trim().split(/\r?\n/);
3376
- const ref = lines.pop();
3377
- const root = lines.join("\n");
3378
- return root && ref ? { root, ref } : void 0;
3379
- }
3380
- function captureWatchdogDiffBaseline(cwd2) {
3381
- const result2 = runGit(cwd2, BASELINE_ARGS);
3382
- return result2.ok ? parseBaseline(result2.stdout) : void 0;
3383
- }
3384
- function startWatchdogDiffBaselineCapture(cwd2) {
3385
- return new Promise((resolve5) => {
3386
- try {
3387
- execFile("git", ["-C", cwd2, ...BASELINE_ARGS], { encoding: "utf-8", windowsHide: true }, (error, stdout) => {
3388
- resolve5(error ? void 0 : parseBaseline(stdout));
3389
- });
3390
- } catch {
3391
- resolve5(void 0);
3392
- }
3393
- });
3394
- }
3395
- function validatePath(value) {
3396
- const trimmed = value?.trim();
3397
- if (!trimmed) return void 0;
3398
- if (trimmed.startsWith("-")) throw new Error("watchdog_diff path must not start with '-'.");
3399
- if (path5.isAbsolute(trimmed)) throw new Error("watchdog_diff path must be relative to the repo root.");
3400
- if (trimmed.split(/[\\/]/).includes("..")) throw new Error("watchdog_diff path must not contain '..'.");
3401
- return trimmed;
3402
- }
3403
- function bound(text) {
3404
- if (text.length <= WATCHDOG_DIFF_MAX_CHARS) return text;
3405
- const marker = `
3406
-
3407
- [... ${text.length - WATCHDOG_DIFF_MAX_CHARS} characters omitted; call again with a narrower path ...]`;
3408
- return `${text.slice(0, WATCHDOG_DIFF_MAX_CHARS - marker.length)}${marker}`;
3409
- }
3410
- function createWatchdogDiffTool(baseline, options = {}) {
3411
- const workingTreeAtLaunch = options.workingTreeAtLaunch === true;
3412
- return {
3413
- name: WATCHDOG_DIFF_TOOL_NAME,
3414
- label: "Watchdog diff",
3415
- description: !baseline ? "Report that a Git HEAD diff baseline is unavailable in this cwd. No diff is generated." : workingTreeAtLaunch ? "Show the current staged and unstaged working-tree delta against reviewer-launch HEAD, plus untracked file paths, including edits by other sessions in this checkout. Committed ranges are not included. Optional path narrows it; stat:true returns per-file counts only." : "Show the repository diff since the review baseline, plus untracked file paths, including edits by other sessions in this checkout. Optional path narrows it; stat:true returns per-file counts only.",
3416
- parameters: WatchdogDiffParams,
3417
- executionMode: "sequential",
3418
- async execute(_toolCallId, params) {
3419
- if (!baseline) {
3420
- return { content: [{ type: "text", text: WATCHDOG_DIFF_UNAVAILABLE_BASELINE }], details: { chars: WATCHDOG_DIFF_UNAVAILABLE_BASELINE.length } };
3421
- }
3422
- const pathFilter = validatePath(params.path);
3423
- const diff = runGit(baseline.root, ["diff", "--no-color", "--no-ext-diff", ...params.stat === true ? ["--stat"] : [], baseline.ref, "--", ...pathFilter ? [pathFilter] : []]);
3424
- if (!diff.ok) throw new Error(`git diff failed: ${diff.stderr || "unknown error"}`);
3425
- const untrackedResult = runGit(baseline.root, ["ls-files", "--others", "--exclude-standard", "-z", "--", ...pathFilter ? [pathFilter] : []]);
3426
- if (workingTreeAtLaunch) {
3427
- const currentHead = runGit(baseline.root, ["rev-parse", "HEAD"]);
3428
- if (!currentHead.ok || currentHead.stdout.trim() !== baseline.ref) {
3429
- const text2 = "Reviewer-launch HEAD changed or is unavailable. Committed changes are unsupported; relaunch the reviewer or supply a diff artifact.";
3430
- return { content: [{ type: "text", text: text2 }], details: { chars: text2.length } };
3431
- }
3432
- }
3433
- const untracked = untrackedResult.ok ? untrackedResult.stdout.split("\0").filter(Boolean) : [];
3434
- const sections = [diff.stdout.trimEnd()];
3435
- if (untracked.length) {
3436
- const shown = untracked.slice(0, MAX_UNTRACKED_FILES);
3437
- sections.push(["Untracked files (use read to inspect):", ...shown.map((file) => ` ${file}`)].join("\n"));
3438
- if (untracked.length > shown.length) sections.push(`... ${untracked.length - shown.length} more untracked files`);
3439
- }
3440
- const text = bound(sections.filter(Boolean).join("\n\n")) || (workingTreeAtLaunch ? `No working-tree changes against reviewer-launch HEAD ${baseline.ref.slice(0, 12)}. Committed changes are not included.` : `No changes since baseline ${baseline.ref.slice(0, 12)}.`);
3441
- return { content: [{ type: "text", text }], details: { chars: text.length } };
3442
- }
3443
- };
3444
- }
3445
-
3446
2432
  // src/watchdog/runtime.ts
3447
2433
  import { createHash as createHash3 } from "node:crypto";
3448
2434
 
3449
2435
  // src/watchdog/change-signature.ts
3450
2436
  import { spawnSync as spawnSync2 } from "node:child_process";
3451
2437
  import { createHash } from "node:crypto";
3452
- import * as fs8 from "node:fs";
2438
+ import * as fs7 from "node:fs";
3453
2439
  import * as os from "node:os";
3454
2440
  import * as path6 from "node:path";
3455
2441
  var IGNORED_CHANGE_PREFIXES = [`${PROJECT_SUBAGENTS_RELATIVE_DIR}/`, "tmp/", "node_modules/"];
@@ -3480,7 +2466,7 @@ function git(cwd2, args2) {
3480
2466
  function comparablePath(value) {
3481
2467
  let resolved = path6.resolve(value);
3482
2468
  try {
3483
- resolved = fs8.realpathSync.native(resolved);
2469
+ resolved = fs7.realpathSync.native(resolved);
3484
2470
  } catch {
3485
2471
  }
3486
2472
  return process.platform === "win32" ? resolved.toLowerCase() : resolved;
@@ -3512,7 +2498,7 @@ function useHashEntryBudget(budget) {
3512
2498
  return true;
3513
2499
  }
3514
2500
  function hashFile(filePath) {
3515
- return createHash("sha256").update(fs8.readFileSync(filePath)).digest("hex");
2501
+ return createHash("sha256").update(fs7.readFileSync(filePath)).digest("hex");
3516
2502
  }
3517
2503
  function largeFileHash(stat) {
3518
2504
  return "large:" + stat.size + ":" + Math.floor(stat.mtimeMs);
@@ -3552,17 +2538,17 @@ function hashPath(root, relPath, budget) {
3552
2538
  const fullPath = path6.join(root, normalized);
3553
2539
  let stat;
3554
2540
  try {
3555
- stat = fs8.lstatSync(fullPath);
2541
+ stat = fs7.lstatSync(fullPath);
3556
2542
  } catch (error) {
3557
2543
  if (error.code === "ENOENT") return { path: normalized, state: "deleted" };
3558
2544
  throw error;
3559
2545
  }
3560
2546
  if (stat.isSymbolicLink()) {
3561
- return { path: normalized, state: "symlink", target: fs8.readlinkSync(fullPath) };
2547
+ return { path: normalized, state: "symlink", target: fs7.readlinkSync(fullPath) };
3562
2548
  }
3563
2549
  if (stat.isDirectory()) {
3564
- if (fs8.existsSync(path6.join(fullPath, ".git"))) return gitWorktreeEntry(normalized, fullPath);
3565
- const entries = fs8.readdirSync(fullPath).map((entry) => normalizeRelPath(path6.posix.join(normalized, entry))).filter((entry) => !ignoredRelPath(entry)).sort();
2550
+ if (fs7.existsSync(path6.join(fullPath, ".git"))) return gitWorktreeEntry(normalized, fullPath);
2551
+ const entries = fs7.readdirSync(fullPath).map((entry) => normalizeRelPath(path6.posix.join(normalized, entry))).filter((entry) => !ignoredRelPath(entry)).sort();
3566
2552
  const remainingEntries = Math.max(0, budget.maxEntries - budget.entries);
3567
2553
  const selectedEntries = entries.slice(0, remainingEntries);
3568
2554
  const childEntries = selectedEntries.map((entry) => hashPath(root, entry, budget));
@@ -3740,7 +2726,7 @@ var WatchdogEmissionGuard = class {
3740
2726
  // src/watchdog/lsp-diagnostics.ts
3741
2727
  import { spawn } from "node:child_process";
3742
2728
  import { createHash as createHash2 } from "node:crypto";
3743
- import * as fs9 from "node:fs";
2729
+ import * as fs8 from "node:fs";
3744
2730
  import * as path7 from "node:path";
3745
2731
  import { pathToFileURL } from "node:url";
3746
2732
  var TS_JS_EXTENSIONS = /* @__PURE__ */ new Map([
@@ -3779,10 +2765,10 @@ function severityFromLsp(value) {
3779
2765
  }
3780
2766
  function pathExecutable(filePath) {
3781
2767
  try {
3782
- const stat = fs9.statSync(filePath);
2768
+ const stat = fs8.statSync(filePath);
3783
2769
  if (!stat.isFile()) return false;
3784
2770
  if (process.platform === "win32") return true;
3785
- fs9.accessSync(filePath, fs9.constants.X_OK);
2771
+ fs8.accessSync(filePath, fs8.constants.X_OK);
3786
2772
  return true;
3787
2773
  } catch {
3788
2774
  return false;
@@ -3819,7 +2805,7 @@ function collectTargetFiles(root, changedPaths, maxFiles) {
3819
2805
  }
3820
2806
  let stat;
3821
2807
  try {
3822
- stat = fs9.statSync(absPath);
2808
+ stat = fs8.statSync(absPath);
3823
2809
  } catch (error) {
3824
2810
  if (error.code === "ENOENT") {
3825
2811
  skippedPaths.push(relPath);
@@ -4113,7 +3099,7 @@ async function collectWithTypeScriptLanguageServer(input) {
4113
3099
  await client.request("initialize", initializeParams(input.root), remaining(), input.signal);
4114
3100
  client.notify("initialized", {});
4115
3101
  for (const target of input.targets) {
4116
- const text = fs9.readFileSync(target.absPath, "utf-8");
3102
+ const text = fs8.readFileSync(target.absPath, "utf-8");
4117
3103
  client.notify("textDocument/didOpen", {
4118
3104
  textDocument: { uri: target.uri, languageId: target.languageId, version: 1, text }
4119
3105
  });
@@ -4367,7 +3353,7 @@ function formatWatchdogOrchestrationActivity(event) {
4367
3353
  if (call?.type !== "toolCall" || typeof call.id !== "string") continue;
4368
3354
  const args2 = call.arguments;
4369
3355
  if (!args2 || typeof args2 !== "object") continue;
4370
- const eligible = call.name === "bg_wait" || call.name === "subagent_supervisor" && ["pending", "list", "reply"].includes(args2.action) || call.name === "subagent" && (["status", "resume", "interrupt", "steer", "stop"].includes(args2.action) || args2.action === void 0 && (typeof args2.agent === "string" || args2.workflow !== void 0));
3356
+ const eligible = call.name === waitToolName() || call.name === "subagent_supervisor" && ["pending", "list", "reply"].includes(args2.action) || call.name === "subagent" && (["status", "resume", "interrupt", "steer", "stop"].includes(args2.action) || args2.action === void 0 && (typeof args2.agent === "string" || args2.workflow !== void 0));
4371
3357
  if (!eligible) continue;
4372
3358
  const result2 = turn.toolResults.find((value) => {
4373
3359
  const result3 = value;
@@ -5147,15 +4133,15 @@ ${this.activityTail}` : "";
5147
4133
  // src/watchdog/review.ts
5148
4134
  import { Agent } from "@earendil-works/pi-agent-core";
5149
4135
  import { createReadOnlyTools, convertToLlm } from "@earendil-works/pi-coding-agent";
5150
- import { Type as Type4 } from "typebox";
4136
+ import { Type as Type3 } from "typebox";
5151
4137
 
5152
4138
  // src/watchdog/guidance.ts
5153
- import * as fs10 from "node:fs";
4139
+ import * as fs9 from "node:fs";
5154
4140
  import * as path8 from "node:path";
5155
4141
  var WATCHDOG_GUIDANCE_MAX_CHARS = 8e3;
5156
4142
  function readOptional(filePath) {
5157
4143
  try {
5158
- return fs10.readFileSync(filePath, "utf-8").trim();
4144
+ return fs9.readFileSync(filePath, "utf-8").trim();
5159
4145
  } catch {
5160
4146
  return "";
5161
4147
  }
@@ -5168,14 +4154,14 @@ function loadWatchdogGuidance(cwd2, enabled) {
5168
4154
 
5169
4155
  // src/watchdog/review.ts
5170
4156
  var WATCHDOG_ALLOWED_TOOL_NAMES = /* @__PURE__ */ new Set(["read", "grep", "find", "ls", "watchdog_warn", WATCHDOG_DIFF_TOOL_NAME]);
5171
- var WatchdogAskParams = Type4.Object({ question: Type4.String(), evidence: Type4.String() }, { additionalProperties: false });
5172
- var WatchdogWarnParams = Type4.Object({
5173
- severity: Type4.String({ enum: WATCHDOG_WARNING_SEVERITIES, description: "concern for actionable risk, blocker for a likely wrong or unsafe outcome" }),
5174
- importance: Type4.String({ enum: WATCHDOG_WARNING_IMPORTANCES, description: "low or medium for user-only visibility; high when the parent model must receive the finding" }),
5175
- summary: Type4.String({ description: "One concise sentence naming the issue." }),
5176
- evidence: Type4.String({ description: "Specific evidence from the turn delta or inspected files." }),
5177
- recommendedAction: Type4.String({ description: "Specific action the parent should take before accepting or continuing." }),
5178
- category: Type4.Optional(Type4.String({ enum: WATCHDOG_WARNING_CATEGORIES }))
4157
+ var WatchdogAskParams = Type3.Object({ question: Type3.String(), evidence: Type3.String() }, { additionalProperties: false });
4158
+ var WatchdogWarnParams = Type3.Object({
4159
+ severity: Type3.String({ enum: WATCHDOG_WARNING_SEVERITIES, description: "concern for actionable risk, blocker for a likely wrong or unsafe outcome" }),
4160
+ importance: Type3.String({ enum: WATCHDOG_WARNING_IMPORTANCES, description: "low or medium for user-only visibility; high when the parent model must receive the finding" }),
4161
+ summary: Type3.String({ description: "One concise sentence naming the issue." }),
4162
+ evidence: Type3.String({ description: "Specific evidence from the turn delta or inspected files." }),
4163
+ recommendedAction: Type3.String({ description: "Specific action the parent should take before accepting or continuing." }),
4164
+ category: Type3.Optional(Type3.String({ enum: WATCHDOG_WARNING_CATEGORIES }))
5179
4165
  }, { additionalProperties: false });
5180
4166
  function fullModelId(model2) {
5181
4167
  return `${model2.provider}/${model2.id}`;
@@ -5205,7 +4191,7 @@ function resolveReviewThinking(input) {
5205
4191
  function resolveConfiguredModel(ctx, rawModel) {
5206
4192
  const availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo);
5207
4193
  const preferredProvider = typeof ctx.model?.provider === "string" ? ctx.model.provider : void 0;
5208
- const resolved = resolveModelCandidate(rawModel, availableModels, preferredProvider);
4194
+ const resolved = resolveModelCandidate(rawModel, availableModels, preferredProvider, knownModelProviders(ctx.modelRegistry));
5209
4195
  if (!resolved) {
5210
4196
  throw new Error(`Configured watchdog model '${rawModel}' did not match exactly one authenticated available model. Use provider/model or configure credentials for the intended provider.`);
5211
4197
  }
@@ -5415,6 +4401,7 @@ async function runWatchdogAttempt(ctx, request, options) {
5415
4401
  hasDiff: diffBaseline !== void 0
5416
4402
  });
5417
4403
  const agent2 = new Agent({
4404
+ sessionId,
5418
4405
  initialState: {
5419
4406
  systemPrompt,
5420
4407
  model: selection.model,
@@ -5451,16 +4438,6 @@ async function runWatchdogAttempt(ctx, request, options) {
5451
4438
  }
5452
4439
 
5453
4440
  export {
5454
- SUPERVISOR_REQUEST_MESSAGE_TYPE,
5455
- SUPERVISOR_REPLY_ENTRY_TYPE,
5456
- parseSupervisorRequestDetails,
5457
- parseSupervisorReplyData,
5458
- NATIVE_SUPERVISOR_TOOL_NAME,
5459
- resolveSupervisorChannelDir,
5460
- CONTACT_SUPERVISOR_TOOL_NAME,
5461
- topLevelSupervisorTool,
5462
- registerNativeSupervisorClient,
5463
- createNativeSupervisorChannel,
5464
4441
  resolveCurrentSessionId,
5465
4442
  resolvePiSessionId,
5466
4443
  WATCHDOG_DIFF_TOOL_NAME,