@vicary/pi-subagents 0.84.0-1 → 0.85.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-F4ASL6OV.js → chunk-7MAE3DJV.js} +1 -1
  5. package/bundle/{chunk-4MDR6V46.js → chunk-A7VJ5XXE.js} +190 -1177
  6. package/bundle/{chunk-LGLEH7B6.js → chunk-B3OOJJA6.js} +231 -182
  7. package/bundle/{chunk-4E7BKDTX.js → chunk-CS4O36CZ.js} +11 -156
  8. package/bundle/{chunk-G2Z6ZH26.js → chunk-GCSLVFCX.js} +1 -1
  9. package/bundle/{chunk-2S4K53MV.js → chunk-H2NLFTC5.js} +1 -1
  10. package/bundle/{chunk-T44HVL5U.js → chunk-HFTBF7SG.js} +2 -1
  11. package/bundle/{chunk-F4AMYP5N.js → chunk-HS4WPO6B.js} +15 -6
  12. package/bundle/chunk-HXRB42AF.js +108 -0
  13. package/bundle/{chunk-4NIY3BE6.js → chunk-JHBQ7N2L.js} +2 -2
  14. package/bundle/{chunk-HKJLSMXV.js → chunk-JO67XSKD.js} +59 -27
  15. package/bundle/{chunk-C5P5CHYK.js → chunk-KDMFBYFM.js} +1 -1
  16. package/bundle/{chunk-V2BZYLEP.js → chunk-KEY3UQMQ.js} +7 -2
  17. package/bundle/{chunk-NENDSQUY.js → chunk-KZ34KQQH.js} +9 -6
  18. package/bundle/{chunk-AKOIVLA5.js → chunk-L2ENOFVZ.js} +76 -58
  19. package/bundle/{chunk-CGN2TVE7.js → chunk-LGMILZNE.js} +322 -18
  20. package/bundle/{chunk-L3WFKBEI.js → chunk-LTPH2DXH.js} +247 -153
  21. package/bundle/{chunk-2D52JFLF.js → chunk-N7B2KD74.js} +41 -117
  22. package/bundle/{chunk-PV63UFUR.js → chunk-O7CPL6H4.js} +183 -28
  23. package/bundle/{chunk-D3JAFGMO.js → chunk-PHZP3KHB.js} +1 -1
  24. package/bundle/{chunk-2DHZTCOL.js → chunk-PVIVCDG2.js} +2 -2
  25. package/bundle/{chunk-LFDBD4PW.js → chunk-QO75KJBT.js} +2 -2
  26. package/bundle/{chunk-67ENPDDA.js → chunk-QZL2ZZPM.js} +22 -11
  27. package/bundle/{chunk-PALJGGYC.js → chunk-RV5OGHLO.js} +6 -3
  28. package/bundle/chunk-T5V5BRCL.js +1067 -0
  29. package/bundle/{chunk-LNRJCP2Y.js → chunk-UX4SCV5N.js} +337 -207
  30. package/bundle/{chunk-TE4LHYHN.js → chunk-VEZMZDTW.js} +209 -93
  31. package/bundle/{chunk-X2MXCSA5.js → chunk-YZBCREP5.js} +310 -101
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +8 -8
  36. package/bundle/project-panes.js +3 -3
  37. package/docs/agents.md +17 -2
  38. package/docs/configuration.md +2 -2
  39. package/docs/extension-api.md +16 -1
  40. package/docs/workflows.md +30 -2
  41. package/package.json +2 -2
  42. package/src/agents/agent-management.js +27 -11
  43. package/src/agents/agent-memory.d.ts +1 -4
  44. package/src/agents/agent-memory.js +1 -4
  45. package/src/agents/agents.d.ts +1 -3
  46. package/src/agents/agents.js +7 -6
  47. package/src/agents/frontmatter.js +1 -8
  48. package/src/agents/global-npm-root.d.ts +1 -0
  49. package/src/agents/global-npm-root.js +11 -3
  50. package/src/agents/skills.d.ts +0 -3
  51. package/src/agents/skills.js +0 -3
  52. package/src/extension/config.js +7 -1
  53. package/src/extension/herdr-pi-bridge.js +10 -2
  54. package/src/extension/index.d.ts +0 -13
  55. package/src/extension/index.js +43 -32
  56. package/src/extension/public-execution.d.ts +1 -0
  57. package/src/extension/public-execution.js +4 -0
  58. package/src/extension/reply-workflow-script.js +24 -4
  59. package/src/extension/schemas.d.ts +8 -3
  60. package/src/extension/schemas.js +5 -3
  61. package/src/extension/session-switch.d.ts +25 -0
  62. package/src/extension/session-switch.js +138 -0
  63. package/src/extension/subagent-guide.d.ts +1 -1
  64. package/src/extension/subagent-guide.js +1 -1
  65. package/src/extension/subagent-launch-tool.d.ts +25 -0
  66. package/src/extension/subagent-launch-tool.js +48 -0
  67. package/src/extension/tool-activation.js +25 -11
  68. package/src/extension/tool-description.js +6 -0
  69. package/src/inspectors/herdr/actions.d.ts +0 -1
  70. package/src/inspectors/herdr/actions.js +0 -1
  71. package/src/inspectors/session-roots-codec.d.ts +0 -1
  72. package/src/inspectors/session-roots-codec.js +0 -1
  73. package/src/inspectors/tmux/actions.d.ts +0 -1
  74. package/src/inspectors/tmux/actions.js +0 -1
  75. package/src/integrations/herdr-status.js +3 -8
  76. package/src/intercom/native-supervisor-channel.js +65 -9
  77. package/src/runs/background/async-execution.d.ts +5 -9
  78. package/src/runs/background/async-execution.js +62 -27
  79. package/src/runs/background/async-job-tracker.js +12 -0
  80. package/src/runs/background/async-resume.d.ts +2 -1
  81. package/src/runs/background/async-resume.js +112 -39
  82. package/src/runs/background/async-retention.js +6 -1
  83. package/src/runs/background/auto-drain.js +2 -1
  84. package/src/runs/background/boot-id.d.ts +1 -3
  85. package/src/runs/background/boot-id.js +1 -3
  86. package/src/runs/background/completion-batcher.d.ts +3 -4
  87. package/src/runs/background/completion-batcher.js +2 -3
  88. package/src/runs/background/control-channel.d.ts +0 -6
  89. package/src/runs/background/control-channel.js +0 -6
  90. package/src/runs/background/fleet-view.js +2 -3
  91. package/src/runs/background/notify.d.ts +0 -2
  92. package/src/runs/background/notify.js +0 -2
  93. package/src/runs/background/result-watcher.d.ts +1 -0
  94. package/src/runs/background/result-watcher.js +59 -29
  95. package/src/runs/background/resume-guidance.js +4 -2
  96. package/src/runs/background/retained-children.js +2 -1
  97. package/src/runs/background/run-child-session.d.ts +0 -1
  98. package/src/runs/background/run-child-session.js +1 -1
  99. package/src/runs/background/run-status.js +4 -3
  100. package/src/runs/background/scheduled-runs.d.ts +3 -1
  101. package/src/runs/background/scheduled-runs.js +13 -16
  102. package/src/runs/background/subagent-runner.d.ts +2 -4
  103. package/src/runs/background/subagent-runner.js +9 -6
  104. package/src/runs/background/subagent-wait.js +12 -15
  105. package/src/runs/background/wait-config.d.ts +2 -0
  106. package/src/runs/background/wait-config.js +17 -3
  107. package/src/runs/background/wait-tool.js +4 -2
  108. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  109. package/src/runs/background/workflow-terminal-proof.js +0 -1
  110. package/src/runs/foreground/execution.d.ts +0 -3
  111. package/src/runs/foreground/execution.js +17 -9
  112. package/src/runs/foreground/subagent-executor.d.ts +3 -2
  113. package/src/runs/foreground/subagent-executor.js +107 -26
  114. package/src/runs/shared/child-commands.js +15 -2
  115. package/src/runs/shared/child-hooks.d.ts +1 -7
  116. package/src/runs/shared/child-hooks.js +13 -5
  117. package/src/runs/shared/child-launch.js +6 -2
  118. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  119. package/src/runs/shared/child-session.d.ts +1 -1
  120. package/src/runs/shared/child-session.js +21 -2
  121. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  122. package/src/runs/shared/child-tool-plan.js +0 -1
  123. package/src/runs/shared/claude-code-adapter.js +11 -0
  124. package/src/runs/shared/external-cli-runner.js +26 -6
  125. package/src/runs/shared/herdr-connection.js +2 -1
  126. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  127. package/src/runs/shared/herdr-pane-host.js +17 -1
  128. package/src/runs/shared/herdr-placed-run.js +48 -22
  129. package/src/runs/shared/lane-metadata.d.ts +0 -1
  130. package/src/runs/shared/lane-metadata.js +0 -1
  131. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  132. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  133. package/src/runs/shared/model-resolution.d.ts +2 -2
  134. package/src/runs/shared/model-resolution.js +7 -1
  135. package/src/runs/shared/model-scope.d.ts +1 -5
  136. package/src/runs/shared/model-scope.js +1 -5
  137. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  138. package/src/runs/shared/mutation-evidence.js +52 -7
  139. package/src/runs/shared/nested-events.d.ts +1 -0
  140. package/src/runs/shared/nested-events.js +1 -1
  141. package/src/runs/shared/parallel-utils.d.ts +0 -1
  142. package/src/runs/shared/permissions.js +5 -3
  143. package/src/runs/shared/placement-host.d.ts +5 -1
  144. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  145. package/src/runs/shared/rex-pane-host.js +0 -2
  146. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  147. package/src/runs/shared/run-launch-folder.js +21 -0
  148. package/src/runs/shared/runner-launcher.d.ts +12 -1
  149. package/src/runs/shared/runner-launcher.js +16 -0
  150. package/src/runs/shared/single-output.d.ts +3 -3
  151. package/src/runs/shared/single-output.js +5 -3
  152. package/src/runs/shared/structured-output.d.ts +8 -0
  153. package/src/runs/shared/structured-output.js +30 -2
  154. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  155. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  156. package/src/runs/shared/tool-timeout.js +2 -1
  157. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  158. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  159. package/src/runs/shared/worktree.d.ts +3 -0
  160. package/src/runs/shared/worktree.js +20 -0
  161. package/src/shared/capacity-resilient-json.d.ts +1 -1
  162. package/src/shared/child-cache-retention.d.ts +1 -2
  163. package/src/shared/child-cache-retention.js +1 -2
  164. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  165. package/src/shared/fleet-transcript-reader.js +333 -0
  166. package/src/shared/formatters.d.ts +0 -18
  167. package/src/shared/formatters.js +0 -18
  168. package/src/shared/session-succession.d.ts +16 -1
  169. package/src/shared/session-succession.js +41 -2
  170. package/src/shared/session-warnings.d.ts +7 -0
  171. package/src/shared/session-warnings.js +26 -0
  172. package/src/shared/settings.d.ts +0 -23
  173. package/src/shared/settings.js +3 -35
  174. package/src/shared/types.d.ts +28 -11
  175. package/src/shared/types.js +0 -12
  176. package/src/shared/utils.d.ts +0 -14
  177. package/src/shared/utils.js +0 -22
  178. package/src/shared/wait-tool-name.d.ts +8 -0
  179. package/src/shared/wait-tool-name.js +13 -0
  180. package/src/slash/slash-commands.js +2 -1
  181. package/src/slash/subagent-cost.d.ts +3 -2
  182. package/src/slash/subagent-cost.js +22 -3
  183. package/src/slash/subagents-admin.js +0 -1
  184. package/src/tui/fleet-status.d.ts +0 -5
  185. package/src/tui/fleet-status.js +4 -24
  186. package/src/tui/fleet-transcript.d.ts +1 -44
  187. package/src/tui/fleet-transcript.js +1 -327
  188. package/src/tui/fleet.js +6 -4
  189. package/src/tui/render.d.ts +0 -9
  190. package/src/tui/render.js +81 -47
  191. package/src/tui/subagent-messages.js +3 -2
  192. package/src/watchdog/register-child.d.ts +2 -3
  193. package/src/watchdog/register-child.js +2 -3
  194. package/src/watchdog/turn-delta.js +2 -1
  195. package/src/workflows/scripted-workflow.js +241 -20
  196. package/src/workflows/workflow-launch-record.d.ts +15 -6
  197. package/src/workflows/workflow-launch-record.js +30 -12
  198. package/src/workflows/workflow-resume-claim.js +2 -2
  199. package/src/workflows/workflow-resume.d.ts +1 -1
  200. package/src/workflows/workflow-resume.js +11 -8
  201. package/src/workflows/workflow-script-worker.d.ts +13 -0
  202. package/src/workflows/workflow-script-worker.js +79 -0
  203. package/workflow-script-process.cjs +36 -0
  204. package/workflow-script-worker.cjs +4 -1
@@ -1,17 +1,14 @@
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-L3WFKBEI.js";
11
+ } from "./chunk-LTPH2DXH.js";
15
12
  import {
16
13
  MAX_ARGS_BYTES,
17
14
  MAX_ARGS_DEPTH,
@@ -24,18 +21,16 @@ import {
24
21
  resultFilePath,
25
22
  resultPayloadMatchesSessionRun,
26
23
  resultPayloadPathForSessionRun
27
- } from "./chunk-CGN2TVE7.js";
28
- import {
29
- shouldUseNativeFsWatch
30
- } from "./chunk-NIXWDZZV.js";
24
+ } from "./chunk-LGMILZNE.js";
31
25
  import {
32
26
  PROJECT_SUBAGENTS_RELATIVE_DIR
33
- } from "./chunk-D3JAFGMO.js";
27
+ } from "./chunk-PHZP3KHB.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,1045 +40,145 @@ import {
45
40
  formatDuration,
46
41
  getAgentDir,
47
42
  getProjectConfigDir,
48
- readStatus,
49
43
  resolveEffectiveThinking,
50
44
  resolveModelCandidate,
51
45
  shortenPath,
52
46
  splitKnownThinkingSuffix,
53
47
  toAgentToolUsage,
54
48
  toModelInfo,
49
+ waitToolName,
55
50
  withSettingsFileLease,
56
- writeAtomicJson,
57
51
  writePrivateAtomicJson
58
- } from "./chunk-LNRJCP2Y.js";
52
+ } from "./chunk-UX4SCV5N.js";
59
53
  import {
60
- ASYNC_DIR,
61
54
  DIRS,
62
55
  INTERCOM_DETACH_REQUEST_EVENT,
63
- POLL_INTERVAL_MS,
56
+ RUNNER_LAUNCHER_NAME_PATTERN,
64
57
  SUBAGENT_ASYNC_COMPLETE_EVENT,
65
58
  SUBAGENT_CONTROL_EVENT,
66
59
  SUBAGENT_CONTROL_INTERCOM_EVENT,
67
60
  SUBAGENT_FOREGROUND_COMPLETE_EVENT,
68
- SUBAGENT_RESULT_INTERCOM_EVENT,
69
- TEMP_ROOT_DIR
61
+ SUBAGENT_RESULT_INTERCOM_EVENT
70
62
  } from "./chunk-JEZOSEWG.js";
71
63
 
72
- // src/intercom/native-supervisor-channel.ts
73
- import { randomUUID } from "node:crypto";
64
+ // src/shared/session-identity.ts
74
65
  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
- const parsed = JSON.parse(fs.readFileSync(file, "utf-8"));
215
- if (parsed.type === "subagent.supervisor.reply" && parsed.requestId === requestId && typeof parsed.message === "string") {
216
- if (typeof parsed.error === "string") throw new Error(parsed.error);
217
- return parsed;
218
- }
219
- }
220
- await delay(250, signal);
221
- deadline = extendedDeadline(request, deadline);
222
- }
223
- throw new Error("Timed out waiting for supervisor reply.");
224
- }
225
- async function sendSupervisorRequest(params, metadata, signal, toolCallId) {
226
- if (!params.message?.trim() && params.reason !== "interview_request") {
227
- throw new Error("message is required for supervisor decisions and progress updates.");
228
- }
229
- ensureSupervisorChannelDir(metadata.channelDir);
230
- const requestId = randomUUID();
231
- const expectsReply = params.reason !== "progress_update";
232
- const createdAt = Date.now();
233
- const replyDeadline = createdAt + askTimeoutMs();
234
- const expiresAt = expectsReply ? replyDeadline : void 0;
235
- const message2 = params.message?.trim() ?? "";
236
- const requestToolCallId = typeof toolCallId === "string" && toolCallId.length > 0 ? toolCallId : void 0;
237
- const request = {
238
- type: "subagent.supervisor.request",
239
- id: requestId,
240
- createdAt,
241
- ...expiresAt !== void 0 ? { expiresAt } : {},
242
- reason: params.reason,
243
- message: message2,
244
- expectsReply,
245
- ...metadata.orchestratorTarget ? { orchestratorTarget: metadata.orchestratorTarget } : {},
246
- ...metadata.orchestratorSessionId ? { orchestratorSessionId: metadata.orchestratorSessionId } : {},
247
- runId: metadata.runId,
248
- agent: metadata.agent,
249
- childIndex: metadata.childIndex,
250
- ...requestToolCallId ? { toolCallId: requestToolCallId } : {},
251
- ...metadata.childTarget ? { childTarget: metadata.childTarget } : {},
252
- ...params.interview !== void 0 ? { interview: params.interview } : {}
253
- };
254
- const serialized = JSON.stringify(request, null, " ");
255
- if (Buffer.byteLength(serialized, "utf-8") > MAX_MESSAGE_BYTES) throw new Error("Supervisor request is too large.");
256
- writeAtomicJson(requestPath(metadata.channelDir, requestId), request);
257
- if (!expectsReply) {
258
- return {
259
- content: [{ type: "text", text: "Supervisor progress update queued." }],
260
- details: { delivered: true, requestId, reason: params.reason }
261
- };
262
- }
263
- try {
264
- const reply = await waitForReply(metadata.channelDir, requestId, replyDeadline, signal);
265
- const details = { requestId, reason: params.reason };
266
- if (params.reason === "interview_request") {
267
- const structured = parseStructuredReply(reply.message);
268
- if (structured.error) details.structuredReplyParseError = structured.error;
269
- else details.structuredReply = structured.value;
270
- }
271
- return {
272
- content: [{ type: "text", text: `**Reply from supervisor:**
273
- ${reply.message}` }],
274
- details
275
- };
276
- } catch (error) {
277
- removeRequestFile(requestPath(metadata.channelDir, requestId));
278
- throw error;
279
- }
280
- }
281
- function hasTool(pi, name) {
282
- try {
283
- return pi.getAllTools?.().some((tool) => tool.name === name) === true;
284
- } catch {
285
- return false;
286
- }
287
- }
288
- var CONTACT_SUPERVISOR_TOOL_NAME = "contact_supervisor";
289
- var CONTACT_SUPERVISOR_DECLARATION = {
290
- name: CONTACT_SUPERVISOR_TOOL_NAME,
291
- ...MODEL_ONLY_TOOL,
292
- label: "Contact Supervisor",
293
- description: "Contact the parent/supervisor session for a blocking decision, structured interview, or progress update.",
294
- parameters: ContactSupervisorParamsSchema
295
- };
296
- var TOP_LEVEL_SUPERVISOR_REFUSAL = "contact_supervisor works only inside a subagent; this session has no supervisor.";
297
- function topLevelSupervisorTool() {
298
- return {
299
- ...CONTACT_SUPERVISOR_DECLARATION,
300
- async execute() {
301
- return { isError: true, content: [{ type: "text", text: TOP_LEVEL_SUPERVISOR_REFUSAL }], details: {} };
302
- }
303
- };
304
- }
305
- function registerNativeSupervisorClient(pi, metadata) {
306
- if (!metadata || hasTool(pi, CONTACT_SUPERVISOR_TOOL_NAME)) return;
307
- const tool = {
308
- ...CONTACT_SUPERVISOR_DECLARATION,
309
- execute(id2, params, signal) {
310
- return sendSupervisorRequest(params, metadata, signal, id2);
311
- }
312
- };
313
- pi.registerTool(tool);
66
+ function resolveCurrentSessionId(sessionManager) {
67
+ const sessionId = sessionManager.getSessionFile() ?? sessionManager.getSessionId();
68
+ if (!sessionId) throw new Error("Current session identity is unavailable.");
69
+ return sessionId;
314
70
  }
315
- function parseRequestFile(file, channelDir) {
71
+ function resolvePiSessionId(sessionFile) {
72
+ if (!sessionFile) return void 0;
316
73
  try {
317
- const parsed = JSON.parse(fs.readFileSync(file, "utf-8"));
318
- if (parsed.type !== "subagent.supervisor.request") return void 0;
319
- if (typeof parsed.id !== "string" || !parsed.id) return void 0;
320
- if (parsed.reason !== "need_decision" && parsed.reason !== "interview_request" && parsed.reason !== "progress_update") return void 0;
321
- if (typeof parsed.message !== "string" || !parsed.message.trim() && parsed.reason !== "interview_request") return void 0;
322
- if (typeof parsed.runId !== "string" || typeof parsed.agent !== "string" || typeof parsed.childIndex !== "number") return void 0;
323
- return {
324
- ...parsed,
325
- ...typeof parsed.toolCallId === "string" && parsed.toolCallId.length > 0 ? { toolCallId: parsed.toolCallId } : { toolCallId: void 0 },
326
- channelDir,
327
- requestFile: file
328
- };
329
- } catch {
330
- return void 0;
331
- }
332
- }
333
- function isMissingSupervisorDirectory(error, platform) {
334
- const code = error.code;
335
- return code === "ENOENT" || platform === "win32" && code === "UNKNOWN";
336
- }
337
- function listRequestFiles(channelDirs, platform) {
338
- if (!channelDirs) {
74
+ const fd = fs.openSync(sessionFile, "r");
339
75
  try {
340
- channelDirs = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => path.join(SUPERVISOR_CHANNEL_ROOT, entry.name));
341
- } catch (error) {
342
- if (isMissingSupervisorDirectory(error, platform)) return [];
343
- throw error;
344
- }
345
- }
346
- const files = [];
347
- for (const channelDir of channelDirs) {
348
- const requestsDir = path.join(channelDir, REQUESTS_DIR);
349
- let requestEntries;
350
- try {
351
- requestEntries = fs.readdirSync(requestsDir, { withFileTypes: true });
352
- } catch {
353
- continue;
354
- }
355
- for (const requestEntry of requestEntries) {
356
- if (requestEntry.isFile() && requestEntry.name.endsWith(".json")) files.push({ channelDir, file: path.join(requestsDir, requestEntry.name) });
76
+ const buffer = Buffer.alloc(16 * 1024);
77
+ const bytes = fs.readSync(fd, buffer, 0, buffer.length, 0);
78
+ const line = buffer.toString("utf-8", 0, bytes).split("\n", 1)[0];
79
+ if (!line) return void 0;
80
+ const header = JSON.parse(line);
81
+ if (header.type === "session" && typeof header.id === "string" && /^[A-Za-z0-9-]{8,}$/.test(header.id)) return header.id;
82
+ return void 0;
83
+ } finally {
84
+ fs.closeSync(fd);
357
85
  }
358
- }
359
- return files;
360
- }
361
- function readDirectoryEntries(dir, platform) {
362
- try {
363
- return fs.readdirSync(dir, { withFileTypes: true });
364
- } catch (error) {
365
- if (isMissingSupervisorDirectory(error, platform)) return [];
86
+ } catch {
366
87
  return void 0;
367
88
  }
368
89
  }
369
- function directoryMtimeMs(dir) {
370
- try {
371
- return fs.statSync(dir).mtimeMs;
372
- } catch {
373
- return 0;
374
- }
90
+
91
+ // src/watchdog/diff-tool.ts
92
+ import { execFile, spawnSync } from "node:child_process";
93
+ import * as path from "node:path";
94
+ import { Type } from "typebox";
95
+ var WATCHDOG_DIFF_TOOL_NAME = "watchdog_diff";
96
+ var WATCHDOG_DIFF_MAX_CHARS = 24e3;
97
+ 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.";
98
+ var MAX_UNTRACKED_FILES = 50;
99
+ var WatchdogDiffParams = Type.Object({
100
+ path: Type.Optional(Type.String({ description: "Restrict the diff to one file or directory, relative to the repo root." })),
101
+ stat: Type.Optional(Type.Boolean({ description: "Return per-file change counts instead of the full diff." }))
102
+ }, { additionalProperties: false });
103
+ function runGit(root, args2) {
104
+ const result2 = spawnSync("git", ["-C", root, ...args2], { encoding: "utf-8", maxBuffer: 16 * 1024 * 1024, windowsHide: true });
105
+ return { ok: result2.status === 0, stdout: result2.stdout ?? "", stderr: (result2.stderr ?? "").trim() };
375
106
  }
376
- function removeEmptyDirectory(dir) {
377
- try {
378
- fs.rmdirSync(dir);
379
- return true;
380
- } catch (error) {
381
- const code = error.code;
382
- if (code === "ENOENT") return true;
383
- if (code === "ENOTEMPTY" || code === "EEXIST" || code === "EPERM" || code === "EBUSY") return false;
384
- throw error;
385
- }
107
+ var BASELINE_ARGS = ["rev-parse", "--show-toplevel", "HEAD"];
108
+ function parseBaseline(stdout) {
109
+ const lines = stdout.trim().split(/\r?\n/);
110
+ const ref = lines.pop();
111
+ const root = lines.join("\n");
112
+ return root && ref ? { root, ref } : void 0;
386
113
  }
387
- function removeStaleEmptySupervisorChannel(channelDir, nowMs, platform) {
388
- const requestsDir = path.join(channelDir, REQUESTS_DIR);
389
- const repliesDir = path.join(channelDir, REPLIES_DIR);
390
- const newestKnownMtimeMs = Math.max(
391
- directoryMtimeMs(channelDir),
392
- directoryMtimeMs(requestsDir),
393
- directoryMtimeMs(repliesDir)
394
- );
395
- if (nowMs - newestKnownMtimeMs < STALE_EMPTY_CHANNEL_AGE_MS) return false;
396
- const requestEntries = readDirectoryEntries(requestsDir, platform);
397
- if (!requestEntries || requestEntries.length > 0) return false;
398
- const replyEntries = readDirectoryEntries(repliesDir, platform);
399
- if (!replyEntries || replyEntries.length > 0) return false;
400
- if (!removeEmptyDirectory(requestsDir)) return false;
401
- if (!removeEmptyDirectory(repliesDir)) return false;
402
- if (!removeEmptyDirectory(channelDir)) return false;
403
- return true;
114
+ function captureWatchdogDiffBaseline(cwd2) {
115
+ const result2 = runGit(cwd2, BASELINE_ARGS);
116
+ return result2.ok ? parseBaseline(result2.stdout) : void 0;
404
117
  }
405
- function cleanupStaleEmptySupervisorChannels(nowMs = Date.now(), platform = process.platform) {
406
- let channelEntries;
407
- try {
408
- channelEntries = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true });
409
- } catch (error) {
410
- if (isMissingSupervisorDirectory(error, platform)) return 0;
411
- throw error;
412
- }
413
- let removed = 0;
414
- for (const entry of channelEntries) {
415
- if (!entry.isDirectory()) continue;
118
+ function startWatchdogDiffBaselineCapture(cwd2) {
119
+ return new Promise((resolve5) => {
416
120
  try {
417
- if (removeStaleEmptySupervisorChannel(path.join(SUPERVISOR_CHANNEL_ROOT, entry.name), nowMs, platform)) removed++;
121
+ execFile("git", ["-C", cwd2, ...BASELINE_ARGS], { encoding: "utf-8", windowsHide: true }, (error, stdout) => {
122
+ resolve5(error ? void 0 : parseBaseline(stdout));
123
+ });
418
124
  } catch {
125
+ resolve5(void 0);
419
126
  }
420
- }
421
- return removed;
422
- }
423
- function requestMatchesOwner(request, state) {
424
- const currentSessionId = state.supervisorOwnerSessionId;
425
- if (currentSessionId && request.orchestratorSessionId === currentSessionId) return true;
426
- if (!state.currentSessionId || inheritedSessionIds(state.currentSessionId).length === 0) return false;
427
- if (!request.runId || request.runId.startsWith(".") || path.basename(request.runId) !== request.runId) return false;
428
- try {
429
- return ownsRun(state.currentSessionId, readStatus(path.join(ASYNC_DIR, request.runId))?.sessionId);
430
- } catch {
431
- return false;
432
- }
433
- }
434
- function rememberedForegroundChild(request, state) {
435
- const run = state.foregroundRuns?.get(request.runId);
436
- const child = run?.children.find((candidate) => candidate.index === request.childIndex && candidate.agent === request.agent) ?? run?.children[request.childIndex];
437
- return run && child ? { run, child } : void 0;
438
- }
439
- function markForegroundSupervisorAttention(request, state) {
440
- const remembered = rememberedForegroundChild(request, state);
441
- if (!remembered || remembered.child.status !== "detached") return;
442
- const updatedAt = Date.now();
443
- remembered.run.updatedAt = updatedAt;
444
- remembered.child.activityState = "needs_attention";
445
- remembered.child.lastActivityAt = request.createdAt;
446
- remembered.child.currentTool = "contact_supervisor";
447
- remembered.child.currentToolStartedAt = request.createdAt;
448
- remembered.child.updatedAt = updatedAt;
449
- }
450
- function clearForegroundSupervisorAttention(request, pending, state) {
451
- if ([...pending.values()].some(
452
- (candidate) => candidate.expectsReply && candidate.runId === request.runId && candidate.agent === request.agent && candidate.childIndex === request.childIndex
453
- )) return;
454
- const remembered = rememberedForegroundChild(request, state);
455
- if (!remembered || remembered.child.status !== "detached") return;
456
- const updatedAt = Date.now();
457
- remembered.run.updatedAt = updatedAt;
458
- remembered.child.activityState = void 0;
459
- remembered.child.lastActivityAt = updatedAt;
460
- remembered.child.currentTool = void 0;
461
- remembered.child.currentToolStartedAt = void 0;
462
- remembered.child.updatedAt = updatedAt;
463
- }
464
- function removeRequestFile(file) {
465
- try {
466
- fs.rmSync(file, { force: true });
467
- } catch {
468
- }
469
- }
470
- function requestExpiresAt(request, now) {
471
- const expiresAt = request.expiresAt;
472
- if (typeof expiresAt === "number" && Number.isFinite(expiresAt)) return expiresAt;
473
- return Number.isFinite(request.createdAt) ? request.createdAt + askTimeoutMs() : now;
474
- }
475
- function requestRunInactive(request, state) {
476
- if (state.foregroundControls.has(request.runId)) return false;
477
- const foreground = rememberedForegroundChild(request, state);
478
- if (foreground) return foreground.child.status !== "detached";
479
- const asyncJob = state.asyncJobs.get(request.runId);
480
- if (!asyncJob) return false;
481
- if (asyncJob.status === "complete" || asyncJob.status === "failed" || asyncJob.status === "paused") return true;
482
- const stepStatus = asyncJob.steps?.[request.childIndex]?.status;
483
- return stepStatus === "complete" || stepStatus === "completed" || stepStatus === "failed" || stepStatus === "paused";
484
- }
485
- function requestLifecycle(request, state, now, runState) {
486
- if (!requestMatchesOwner(request, state)) return "wrong-session";
487
- if (!fs.existsSync(request.requestFile)) return "missing";
488
- if (request.expectsReply && fs.existsSync(replyPath(request.channelDir, request.id))) return "resolved";
489
- if (request.expectsReply && now > requestExpiresAt(request, now)) return "expired";
490
- if (request.expectsReply && requestRunInactive(request, runState)) return "inactive";
491
- return "pending";
492
- }
493
- function cleanupRequestLifecycle(request, lifecycle) {
494
- if (lifecycle === "resolved" || lifecycle === "expired" || lifecycle === "inactive") removeRequestFile(request.requestFile);
495
- }
496
- function refreshPendingRequests(pending, state, onLifecycle, runState) {
497
- const now = Date.now();
498
- for (const request of pending.values()) {
499
- const lifecycle = requestLifecycle(request, state, now, runState(request));
500
- if (lifecycle === "pending") continue;
501
- pending.delete(request.id);
502
- onLifecycle(request, lifecycle);
503
- cleanupRequestLifecycle(request, lifecycle);
504
- }
505
- }
506
- function pendingHeader(request) {
507
- return `- ${request.id}: ${request.agent} [${request.runId}#${request.childIndex}] ${request.reason}.`;
508
- }
509
- function formatPendingLine(request) {
510
- const replyHint = request.expectsReply ? ` Reply: ${supervisorReplyHint(request.id)}` : "";
511
- const header = `${pendingHeader(request)}${replyHint}`;
512
- return request.message ? `${header}
513
- ${request.message.replace(/\n/g, "\n ")}` : header;
514
- }
515
- function requestVisibleText(request) {
516
- const lines = [
517
- reasonHeading(request.reason),
518
- `Run: ${request.runId}`,
519
- `Agent: ${request.agent}`,
520
- `Child index: ${request.childIndex}`
521
- ];
522
- lines.push("");
523
- if (request.message) lines.push(request.message);
524
- if (request.reason === "interview_request") {
525
- lines.push(
526
- "",
527
- "Structured response requested. Reply with JSON, optionally fenced in ```json, matching the requested interview shape."
528
- );
529
- if (request.interview !== void 0) lines.push(JSON.stringify(request.interview, null, " "));
530
- }
531
- if (request.expectsReply) lines.push("", `Reply with: ${supervisorReplyHint(request.id)}`);
532
- 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.)" : ""}`);
533
- return lines.join("\n").trimEnd();
534
- }
535
- function writeReply(request, message2) {
536
- if (!message2.trim()) throw new Error("message is required for supervisor replies.");
537
- const reply = {
538
- type: "subagent.supervisor.reply",
539
- requestId: request.id,
540
- createdAt: Date.now(),
541
- message: message2.trim()
542
- };
543
- writeAtomicJson(replyPath(request.channelDir, request.id), reply);
544
- removeRequestFile(request.requestFile);
545
- return reply;
127
+ });
546
128
  }
547
- function appendSupervisorReplyEntry(pi, request, reply) {
548
- const appendEntry = pi.appendEntry;
549
- if (typeof appendEntry !== "function") return;
550
- try {
551
- appendEntry.call(pi, SUPERVISOR_REPLY_ENTRY_TYPE, {
552
- requestId: request.id,
553
- reason: request.reason,
554
- runId: request.runId,
555
- agent: request.agent,
556
- childIndex: request.childIndex,
557
- ...request.childTarget ? { childTarget: request.childTarget } : {},
558
- message: reply.message,
559
- createdAt: reply.createdAt
560
- });
561
- } catch (error) {
562
- console.error("Failed to journal native supervisor reply:", error);
563
- }
129
+ function validatePath(value) {
130
+ const trimmed = value?.trim();
131
+ if (!trimmed) return void 0;
132
+ if (trimmed.startsWith("-")) throw new Error("watchdog_diff path must not start with '-'.");
133
+ if (path.isAbsolute(trimmed)) throw new Error("watchdog_diff path must be relative to the repo root.");
134
+ if (trimmed.split(/[\\/]/).includes("..")) throw new Error("watchdog_diff path must not contain '..'.");
135
+ return trimmed;
564
136
  }
565
- function resolvePendingRequest(pending, params) {
566
- const requests = [...pending.values()].filter((request) => request.expectsReply);
567
- if (params.replyTo) {
568
- const request = pending.get(params.replyTo);
569
- if (!request) {
570
- const current = requests.length ? `Pending now:
571
- ${requests.map(pendingHeader).join("\n")}` : "No pending supervisor requests.";
572
- throw new Error(`No pending supervisor request found for replyTo '${params.replyTo}'. It was answered, expired or withdrawn. ${current}`);
573
- }
574
- return request;
575
- }
576
- if (params.to) {
577
- const normalizedTo = params.to.toLowerCase();
578
- const matches = requests.filter(
579
- (request) => request.id.toLowerCase().startsWith(normalizedTo) || request.agent.toLowerCase() === normalizedTo || request.childTarget?.toLowerCase() === normalizedTo
580
- );
581
- if (matches.length === 1) return matches[0];
582
- if (matches.length > 1) throw new Error(`Multiple pending supervisor requests match '${params.to}'. Use replyTo.`);
583
- throw new Error(`No pending supervisor request matches '${params.to}'. Use replyTo.`);
584
- }
585
- if (requests.length === 1) return requests[0];
586
- if (requests.length === 0) throw new Error("No pending supervisor requests need a reply.");
587
- throw new Error("Multiple pending supervisor requests need replies. Use replyTo.");
588
- }
589
- function publicPendingRequests(pending) {
590
- return [...pending.values()].map((request) => ({
591
- id: request.id,
592
- runId: request.runId,
593
- agent: request.agent,
594
- childIndex: request.childIndex,
595
- reason: request.reason,
596
- expectsReply: request.expectsReply
597
- }));
137
+ function bound(text) {
138
+ if (text.length <= WATCHDOG_DIFF_MAX_CHARS) return text;
139
+ const marker = `
140
+
141
+ [... ${text.length - WATCHDOG_DIFF_MAX_CHARS} characters omitted; call again with a narrower path ...]`;
142
+ return `${text.slice(0, WATCHDOG_DIFF_MAX_CHARS - marker.length)}${marker}`;
598
143
  }
599
- function buildParentSupervisorTool(pi, pending, state, onLifecycle, discover, runState) {
144
+ function createWatchdogDiffTool(baseline, options = {}) {
145
+ const workingTreeAtLaunch = options.workingTreeAtLaunch === true;
600
146
  return {
601
- name: NATIVE_SUPERVISOR_TOOL_NAME,
602
- ...MODEL_ONLY_TOOL,
603
- label: "Subagent Supervisor",
604
- description: "Native pi-subagents supervisor channel. Use reply/pending/status to answer child subagent requests without overriding pi-intercom.",
605
- parameters: IntercomParamsSchema,
606
- async execute(_id, params) {
607
- discover();
608
- refreshPendingRequests(pending, state, onLifecycle, runState);
609
- const input = params;
610
- if (input.action === "status") {
611
- return { content: [{ type: "text", text: `Native supervisor channel active. Pending replies: ${pending.size}.` }], details: { active: true, pending: pending.size, root: SUPERVISOR_CHANNEL_ROOT } };
612
- }
613
- if (input.action === "pending" || input.action === "list") {
614
- const lines = [...pending.values()].filter((request) => request.expectsReply).map(formatPendingLine);
615
- return { content: [{ type: "text", text: lines.length ? lines.join("\n") : "No pending supervisor requests." }], details: { pending: publicPendingRequests(pending) } };
616
- }
617
- if (input.action === "reply") {
618
- const request = resolvePendingRequest(pending, input);
619
- const reply = writeReply(request, input.message ?? "");
620
- appendSupervisorReplyEntry(pi, request, reply);
621
- pending.delete(request.id);
622
- onLifecycle(request, "resolved");
623
- clearForegroundSupervisorAttention(request, pending, state);
624
- return { content: [{ type: "text", text: `Replied to supervisor request ${request.id}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent } };
625
- }
626
- throw new Error(`Unsupported supervisor action: ${input.action}`);
627
- }
628
- };
629
- }
630
- function createNativeSupervisorChannel(pi, state, deps = {}) {
631
- const watch2 = deps.watch ?? fs.watch;
632
- const timers = deps.timers ?? globalThis;
633
- const runState = (request) => {
634
- for (const ownerState of deps.getCurrentOwnerStates?.() ?? []) {
635
- if (ownerState.asyncJobs.has(request.runId)) return ownerState;
636
- }
637
- return state;
638
- };
639
- const pending = /* @__PURE__ */ new Map();
640
- const settleNotices = /* @__PURE__ */ new Map();
641
- let unsubscribeSettle;
642
- const queuedNotices = /* @__PURE__ */ new Set();
643
- let unsubscribeDelivery;
644
- const requestCorrelations = /* @__PURE__ */ new Map();
645
- const correlationKey = (request) => {
646
- if (!request.toolCallId) return void 0;
647
- return JSON.stringify([request.runId, request.agent, request.childIndex, request.toolCallId]);
648
- };
649
- const pruneRequestCorrelations = (now = Date.now()) => {
650
- for (const [key, correlation] of requestCorrelations) {
651
- if (correlation.state === "resolved" && now - correlation.updatedAt > SUPERVISOR_REQUEST_CORRELATION_RETENTION_MS) requestCorrelations.delete(key);
652
- }
653
- while (requestCorrelations.size > MAX_SUPERVISOR_REQUEST_CORRELATIONS) {
654
- const oldest = requestCorrelations.keys().next().value;
655
- if (oldest === void 0) break;
656
- requestCorrelations.delete(oldest);
657
- }
658
- };
659
- const rememberPendingRequest = (request) => {
660
- const key = correlationKey(request);
661
- if (!key || !request.expectsReply) return;
662
- requestCorrelations.set(key, { request, state: "pending", updatedAt: Date.now() });
663
- pruneRequestCorrelations();
664
- };
665
- const rememberResolvedRequest = (request) => {
666
- const key = correlationKey(request);
667
- if (!key || !request.expectsReply) return;
668
- requestCorrelations.set(key, { request, state: "resolved", updatedAt: Date.now() });
669
- pruneRequestCorrelations();
670
- };
671
- const observeRequestLifecycle = (request, lifecycle) => {
672
- settleNotices.delete(request.id);
673
- if (queuedNotices.delete(request.id)) updateDeliverySubscription();
674
- if (lifecycle !== "wrong-session") rememberResolvedRequest(request);
675
- updateSettleSubscription();
676
- };
677
- const getSupervisorRequestState = (event) => {
678
- if (event.currentTool === "intercom" || event.index === void 0) return "unknown";
679
- const toolCallId = typeof event.toolCallId === "string" && event.toolCallId.length > 0 ? event.toolCallId : void 0;
680
- if (!toolCallId) return "unknown";
681
- pruneRequestCorrelations();
682
- const key = correlationKey({ runId: event.runId, agent: event.agent, childIndex: event.index, toolCallId });
683
- if (!key) return "unknown";
684
- const correlation = requestCorrelations.get(key);
685
- if (!correlation) return "unknown";
686
- if (correlation.state === "resolved") return "resolved";
687
- const now = Date.now();
688
- 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))) {
689
- rememberResolvedRequest(correlation.request);
690
- return "resolved";
691
- }
692
- return "pending";
693
- };
694
- const seenFiles = /* @__PURE__ */ new Set();
695
- const requestWatchers = /* @__PURE__ */ new Map();
696
- let rootWatcher;
697
- let poller;
698
- let safetyPoller;
699
- let deferredWatcherRefresh;
700
- let started = false;
701
- let lastStaleCleanupAt = 0;
702
- const platform = deps.platform ?? process.platform;
703
- const useNativeWatcher = () => !deps.getChannelDirs && shouldUseNativeFsWatch("supervisor-channel", platform) && platform !== "win32";
704
- const hasTransportDemand = () => {
705
- if (pending.size > 0) return true;
706
- if (state.foregroundControls.size > 0) return true;
707
- if (deps.getChannelDirs?.().dirs.length) return true;
708
- if ([...state.asyncJobs.values()].some((job) => job.status === "queued" || job.status === "running")) return true;
709
- for (const ownerState of deps.getCurrentOwnerStates?.() ?? []) {
710
- for (const job of ownerState.asyncJobs.values()) {
711
- if (job.status === "queued" || job.status === "running") return true;
712
- }
713
- }
714
- return false;
715
- };
716
- const registerParentTools = () => {
717
- if (!hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME)) pi.registerTool(buildParentSupervisorTool(pi, pending, state, observeRequestLifecycle, () => poll(), runState));
718
- };
719
- const declareParentTool = () => {
720
- if (typeof pi.getActiveTools !== "function" || typeof pi.setActiveTools !== "function") return;
721
- const active = pi.getActiveTools();
722
- if (!Array.isArray(active) || active.includes(NATIVE_SUPERVISOR_TOOL_NAME) || !hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME)) return;
723
- pi.setActiveTools([...active, NATIVE_SUPERVISOR_TOOL_NAME]);
724
- };
725
- const cleanupStaleChannelsIfDue = () => {
726
- if (deps.getChannelDirs) return;
727
- const nowMs = Date.now();
728
- if (nowMs - lastStaleCleanupAt < STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS) return;
729
- lastStaleCleanupAt = nowMs;
730
- try {
731
- cleanupStaleEmptySupervisorChannels(nowMs, platform);
732
- } catch {
733
- }
734
- };
735
- const poll = () => {
736
- cleanupStaleChannelsIfDue();
737
- refreshPendingRequests(pending, state, observeRequestLifecycle, runState);
738
- if (queuedNotices.size) extendQueuedNotices();
739
- const now = Date.now();
740
- const channels = deps.getChannelDirs?.();
741
- for (const { channelDir, file } of listRequestFiles(channels?.dirs, platform)) {
742
- if (seenFiles.has(file)) continue;
743
- const request = parseRequestFile(file, channelDir);
744
- if (!request || !requestMatchesOwner(request, state)) continue;
745
- const lifecycle = requestLifecycle(request, state, now, runState(request));
746
- if (lifecycle !== "pending") {
747
- seenFiles.add(file);
748
- observeRequestLifecycle(request, lifecycle);
749
- cleanupRequestLifecycle(request, lifecycle);
750
- continue;
751
- }
752
- if (request.expectsReply && runState(request).blockingWorkflowChildren?.has(request.runId)) {
753
- try {
754
- writePrivateAtomicJson(replyPath(channelDir, request.id), {
755
- type: "subagent.supervisor.reply",
756
- requestId: request.id,
757
- createdAt: now,
758
- message: "",
759
- 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."
760
- });
761
- } catch (error) {
762
- console.error(`Failed to report unreachable supervisor request ${request.id}; will retry:`, error);
763
- continue;
764
- }
765
- seenFiles.add(file);
766
- observeRequestLifecycle(request, "resolved");
767
- cleanupRequestLifecycle(request, "resolved");
768
- continue;
769
- }
770
- seenFiles.add(file);
771
- if (!request.expectsReply) {
772
- removeRequestFile(request.requestFile);
773
- continue;
147
+ name: WATCHDOG_DIFF_TOOL_NAME,
148
+ label: "Watchdog diff",
149
+ 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.",
150
+ parameters: WatchdogDiffParams,
151
+ executionMode: "sequential",
152
+ async execute(_toolCallId, params) {
153
+ if (!baseline) {
154
+ return { content: [{ type: "text", text: WATCHDOG_DIFF_UNAVAILABLE_BASELINE }], details: { chars: WATCHDOG_DIFF_UNAVAILABLE_BASELINE.length } };
774
155
  }
775
- rememberPendingRequest(request);
776
- pending.set(request.id, request);
777
- declareParentTool();
778
- updateSettleSubscription();
779
- markForegroundSupervisorAttention(request, state);
780
- try {
781
- const appended = (deps.parentWake ?? pi).sendMessage({
782
- customType: SUPERVISOR_REQUEST_MESSAGE_TYPE,
783
- content: requestVisibleText(request),
784
- display: true,
785
- details: {
786
- id: request.id,
787
- requestId: request.id,
788
- reason: request.reason,
789
- expectsReply: request.expectsReply,
790
- runId: request.runId,
791
- agent: request.agent,
792
- childIndex: request.childIndex,
793
- ...request.childTarget ? { childTarget: request.childTarget } : {},
794
- ...request.interview !== void 0 ? { interview: request.interview } : {},
795
- requestBody: request.message,
796
- replyHint: supervisorReplyHint(request.id)
797
- }
798
- }, { triggerTurn: true });
799
- if (appended === false && started && pending.has(request.id)) {
800
- queuedNotices.add(request.id);
801
- updateDeliverySubscription();
156
+ const pathFilter = validatePath(params.path);
157
+ const diff = runGit(baseline.root, ["diff", "--no-color", "--no-ext-diff", ...params.stat === true ? ["--stat"] : [], baseline.ref, "--", ...pathFilter ? [pathFilter] : []]);
158
+ if (!diff.ok) throw new Error(`git diff failed: ${diff.stderr || "unknown error"}`);
159
+ const untrackedResult = runGit(baseline.root, ["ls-files", "--others", "--exclude-standard", "-z", "--", ...pathFilter ? [pathFilter] : []]);
160
+ if (workingTreeAtLaunch) {
161
+ const currentHead = runGit(baseline.root, ["rev-parse", "HEAD"]);
162
+ if (!currentHead.ok || currentHead.stdout.trim() !== baseline.ref) {
163
+ const text2 = "Reviewer-launch HEAD changed or is unavailable. Committed changes are unsupported; relaunch the reviewer or supply a diff artifact.";
164
+ return { content: [{ type: "text", text: text2 }], details: { chars: text2.length } };
802
165
  }
803
- } catch (error) {
804
- console.error(`Failed to surface supervisor request ${request.id} as a user turn:`, error);
805
- }
806
- pi.events?.emit(INTERCOM_DETACH_REQUEST_EVENT, {
807
- requestId: request.id,
808
- runId: request.runId,
809
- agent: request.agent,
810
- childIndex: request.childIndex
811
- });
812
- if (pending.has(request.id)) markForegroundSupervisorAttention(request, state);
813
- }
814
- channels?.retire?.();
815
- updateSettleSubscription();
816
- };
817
- const handleBeforeSettle = (event) => {
818
- if (!started || event.outcome !== "completed")
819
- return;
820
- refreshPendingRequests(pending, state, observeRequestLifecycle, runState);
821
- if (event.continue || event.context.pendingMessages.length)
822
- return;
823
- const messages = event.context.contextMessages;
824
- const requests = [...pending.values()].filter((request) => {
825
- if (!request.expectsReply || settleNotices.get(request.id) === "warned" || settleNotices.get(request.id) === "handled") return false;
826
- const index = messages.findLastIndex((message2) => message2.role === "custom" && message2.customType === SUPERVISOR_REQUEST_MESSAGE_TYPE && message2.details?.requestId === request.id);
827
- 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()));
828
- if (index === -1 || acted) {
829
- settleNotices.set(request.id, "handled");
830
- return false;
831
166
  }
832
- return true;
833
- });
834
- updateSettleSubscription();
835
- if (!requests.length) return;
836
- declareParentTool();
837
- const unanswered = requests.filter((request) => !settleNotices.has(request.id));
838
- if (unanswered.length) {
839
- for (const request of unanswered)
840
- settleNotices.set(request.id, "reminded");
841
- return {
842
- entries: [...event.entries, {
843
- type: "custom_message",
844
- customType: "subagent-supervisor-unanswered",
845
- 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.',
846
- display: true,
847
- details: { requestIds: requests.map((request) => request.id) }
848
- }],
849
- continue: true
850
- };
851
- }
852
- const unflagged = requests.filter((request) => settleNotices.get(request.id) !== "warned");
853
- if (!unflagged.length)
854
- return;
855
- for (const request of unflagged)
856
- settleNotices.set(request.id, "warned");
857
- updateSettleSubscription();
858
- return {
859
- entries: [...event.entries, {
860
- type: "custom_message",
861
- customType: "subagent-supervisor-blocked",
862
- 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" }).',
863
- display: true,
864
- details: { blocked: true, requestIds: unflagged.map((request) => request.id) }
865
- }]
866
- };
867
- };
868
- const updateSettleSubscription = () => {
869
- const needed = started && [...pending.values()].some((request) => request.expectsReply && settleNotices.get(request.id) !== "warned" && settleNotices.get(request.id) !== "handled");
870
- if (needed && !unsubscribeSettle) unsubscribeSettle = pi.on?.("agent_before_settle", handleBeforeSettle);
871
- if (!needed) {
872
- unsubscribeSettle?.();
873
- unsubscribeSettle = void 0;
874
- }
875
- };
876
- const noticeDelivered = (event) => {
877
- const message2 = event.message;
878
- if (message2.role !== "custom" || message2.customType !== SUPERVISOR_REQUEST_MESSAGE_TYPE) return;
879
- const requestId = message2.details?.requestId;
880
- if (typeof requestId === "string" && queuedNotices.delete(requestId)) updateDeliverySubscription();
881
- };
882
- const parentRunSettled = () => {
883
- queuedNotices.clear();
884
- updateDeliverySubscription();
885
- };
886
- const updateDeliverySubscription = () => {
887
- const needed = started && queuedNotices.size > 0;
888
- if (needed && !unsubscribeDelivery) {
889
- unsubscribeDelivery = [pi.on?.("message_start", noticeDelivered), pi.on?.("agent_settled", parentRunSettled)];
890
- }
891
- if (!needed) {
892
- for (const unsubscribe of unsubscribeDelivery ?? []) unsubscribe?.();
893
- unsubscribeDelivery = void 0;
894
- }
895
- };
896
- const extendQueuedNotices = () => {
897
- const now = Date.now();
898
- const timeoutMs = askTimeoutMs();
899
- for (const id2 of queuedNotices) {
900
- const request = pending.get(id2);
901
- if (!request || requestExpiresAt(request, now) - now > timeoutMs / 2 || !fs.existsSync(request.requestFile)) continue;
902
- const { channelDir: _channelDir, requestFile, ...stored } = request;
903
- try {
904
- writePrivateAtomicJson(requestFile, { ...stored, expiresAt: now + timeoutMs });
905
- request.expiresAt = now + timeoutMs;
906
- } catch (error) {
907
- queuedNotices.delete(id2);
908
- updateDeliverySubscription();
909
- console.error(`Failed to extend supervisor request ${id2} while its notice is queued; it keeps its current deadline:`, error);
910
- }
911
- }
912
- };
913
- const startPolling = () => {
914
- if (poller) return;
915
- poller = timers.setInterval(() => {
916
- poll();
917
- if (!useNativeWatcher() && !hasTransportDemand()) {
918
- if (poller) timers.clearInterval(poller);
919
- poller = void 0;
167
+ const untracked = untrackedResult.ok ? untrackedResult.stdout.split("\0").filter(Boolean) : [];
168
+ const sections = [diff.stdout.trimEnd()];
169
+ if (untracked.length) {
170
+ const shown = untracked.slice(0, MAX_UNTRACKED_FILES);
171
+ sections.push(["Untracked files (use read to inspect):", ...shown.map((file) => ` ${file}`)].join("\n"));
172
+ if (untracked.length > shown.length) sections.push(`... ${untracked.length - shown.length} more untracked files`);
920
173
  }
921
- }, CHANNEL_POLL_MS);
922
- poller.unref?.();
923
- };
924
- const startSafetyPolling = () => {
925
- if (safetyPoller) return;
926
- safetyPoller = timers.setInterval(() => {
927
- watchExistingRequestDirs();
928
- poll();
929
- }, CHANNEL_SAFETY_POLL_MS);
930
- safetyPoller.unref?.();
931
- };
932
- const watchRequestDir = (requestsDir) => {
933
- if (requestWatchers.has(requestsDir)) return;
934
- try {
935
- const watcher = watch2(requestsDir, () => poll());
936
- watcher.on("error", () => {
937
- try {
938
- watcher.close();
939
- } catch {
940
- }
941
- requestWatchers.delete(requestsDir);
942
- startPolling();
943
- });
944
- watcher.unref?.();
945
- requestWatchers.set(requestsDir, watcher);
946
- } catch (error) {
947
- if (error.code !== "ENOENT") startPolling();
948
- }
949
- };
950
- const watchExistingRequestDirs = () => {
951
- let channelEntries;
952
- try {
953
- channelEntries = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true });
954
- } catch (error) {
955
- if (isMissingSupervisorDirectory(error, platform)) return;
956
- startPolling();
957
- return;
958
- }
959
- for (const entry of channelEntries) {
960
- if (entry.isDirectory()) watchRequestDir(path.join(SUPERVISOR_CHANNEL_ROOT, entry.name, REQUESTS_DIR));
174
+ 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)}.`);
175
+ return { content: [{ type: "text", text }], details: { chars: text.length } };
961
176
  }
962
177
  };
963
- const scheduleWatcherRefresh = () => {
964
- if (deferredWatcherRefresh) return;
965
- deferredWatcherRefresh = timers.setImmediate(() => {
966
- deferredWatcherRefresh = void 0;
967
- if (!started) return;
968
- watchExistingRequestDirs();
969
- poll();
970
- });
971
- deferredWatcherRefresh.unref?.();
972
- };
973
- return {
974
- registerTools: registerParentTools,
975
- activateTransport: () => {
976
- if (!started) return;
977
- poll();
978
- if (!useNativeWatcher() && hasTransportDemand()) startPolling();
979
- },
980
- findPendingAsks: (target) => {
981
- const channelDir = resolveSupervisorChannelDir(target.runId, target.agent, target.childIndex);
982
- let files;
983
- try {
984
- files = fs.readdirSync(path.join(channelDir, REQUESTS_DIR));
985
- } catch (error) {
986
- if (isMissingSupervisorDirectory(error, platform)) return [];
987
- throw error;
988
- }
989
- const now = Date.now();
990
- return files.filter((file) => file.endsWith(".json")).flatMap((file) => {
991
- const request = parseRequestFile(path.join(channelDir, REQUESTS_DIR, file), channelDir);
992
- return request?.expectsReply && request.runId === target.runId && request.agent === target.agent && request.childIndex === target.childIndex && requestLifecycle(request, state, now, runState(request)) === "pending" ? [request.id] : [];
993
- }).sort();
994
- },
995
- hasPendingRequests: () => {
996
- if (!started) return false;
997
- poll();
998
- return pending.size > 0;
999
- },
1000
- start: () => {
1001
- if (started) return;
1002
- started = true;
1003
- registerParentTools();
1004
- poll();
1005
- if (deps.getChannelDirs) return;
1006
- try {
1007
- fs.mkdirSync(SUPERVISOR_CHANNEL_ROOT, { recursive: true });
1008
- if (!useNativeWatcher()) {
1009
- if (platform === "win32") startPolling();
1010
- return;
1011
- }
1012
- watchExistingRequestDirs();
1013
- rootWatcher = watch2(SUPERVISOR_CHANNEL_ROOT, () => {
1014
- watchExistingRequestDirs();
1015
- poll();
1016
- scheduleWatcherRefresh();
1017
- });
1018
- rootWatcher.on("error", startPolling);
1019
- startSafetyPolling();
1020
- scheduleWatcherRefresh();
1021
- } catch {
1022
- startPolling();
1023
- }
1024
- },
1025
- dispose: () => {
1026
- started = false;
1027
- updateSettleSubscription();
1028
- queuedNotices.clear();
1029
- updateDeliverySubscription();
1030
- try {
1031
- rootWatcher?.close();
1032
- } catch {
1033
- }
1034
- rootWatcher = void 0;
1035
- for (const watcher of requestWatchers.values()) {
1036
- try {
1037
- watcher.close();
1038
- } catch {
1039
- }
1040
- }
1041
- requestWatchers.clear();
1042
- if (poller) timers.clearInterval(poller);
1043
- poller = void 0;
1044
- if (safetyPoller) timers.clearInterval(safetyPoller);
1045
- safetyPoller = void 0;
1046
- if (deferredWatcherRefresh) timers.clearImmediate(deferredWatcherRefresh);
1047
- deferredWatcherRefresh = void 0;
1048
- pending.clear();
1049
- settleNotices.clear();
1050
- requestCorrelations.clear();
1051
- seenFiles.clear();
1052
- },
1053
- pending,
1054
- getSupervisorRequestState
1055
- };
1056
- }
1057
-
1058
- // src/shared/session-identity.ts
1059
- import * as fs2 from "node:fs";
1060
- function resolveCurrentSessionId(sessionManager) {
1061
- const sessionId = sessionManager.getSessionFile() ?? sessionManager.getSessionId();
1062
- if (!sessionId) throw new Error("Current session identity is unavailable.");
1063
- return sessionId;
1064
- }
1065
- function resolvePiSessionId(sessionFile) {
1066
- if (!sessionFile) return void 0;
1067
- try {
1068
- const fd = fs2.openSync(sessionFile, "r");
1069
- try {
1070
- const buffer = Buffer.alloc(16 * 1024);
1071
- const bytes = fs2.readSync(fd, buffer, 0, buffer.length, 0);
1072
- const line = buffer.toString("utf-8", 0, bytes).split("\n", 1)[0];
1073
- if (!line) return void 0;
1074
- const header = JSON.parse(line);
1075
- if (header.type === "session" && typeof header.id === "string" && /^[A-Za-z0-9-]{8,}$/.test(header.id)) return header.id;
1076
- return void 0;
1077
- } finally {
1078
- fs2.closeSync(fd);
1079
- }
1080
- } catch {
1081
- return void 0;
1082
- }
1083
178
  }
1084
179
 
1085
180
  // src/watchdog/settings.ts
1086
- import * as fs3 from "node:fs";
181
+ import * as fs2 from "node:fs";
1087
182
  import * as path2 from "node:path";
1088
183
  var DEFAULT_WATCHDOG_CONFIG = {
1089
184
  enabled: false,
@@ -1333,10 +428,10 @@ function parseSettingsObject(settings, meta) {
1333
428
  return parseWatchdogPatch(subagents.watchdog, "subagents.watchdog", meta);
1334
429
  }
1335
430
  function readSettingsFileStrict(filePath) {
1336
- if (!fs3.existsSync(filePath)) return {};
431
+ if (!fs2.existsSync(filePath)) return {};
1337
432
  let raw;
1338
433
  try {
1339
- raw = fs3.readFileSync(filePath, "utf-8");
434
+ raw = fs2.readFileSync(filePath, "utf-8");
1340
435
  } catch (error) {
1341
436
  const message2 = error instanceof Error ? error.message : String(error);
1342
437
  throw new Error(`Failed to read settings file '${filePath}': ${message2}`, { cause: error });
@@ -1355,7 +450,7 @@ function readSettingsFileStrict(filePath) {
1355
450
  }
1356
451
  function isDirectory(dir) {
1357
452
  try {
1358
- return fs3.statSync(dir).isDirectory();
453
+ return fs2.statSync(dir).isDirectory();
1359
454
  } catch {
1360
455
  return false;
1361
456
  }
@@ -1422,8 +517,8 @@ function targetSettingsObject(watchdog, target, meta) {
1422
517
  return ensureObjectField(overrides, target.agent.trim(), `subagents.watchdog.children.overrides.${target.agent.trim()}`, meta);
1423
518
  }
1424
519
  function writeSettingsFile(settingsPath, settings) {
1425
- fs3.mkdirSync(path2.dirname(settingsPath), { recursive: true });
1426
- fs3.writeFileSync(settingsPath, `${JSON.stringify(settings, null, 2)}
520
+ fs2.mkdirSync(path2.dirname(settingsPath), { recursive: true });
521
+ fs2.writeFileSync(settingsPath, `${JSON.stringify(settings, null, 2)}
1427
522
  `, "utf-8");
1428
523
  return settingsPath;
1429
524
  }
@@ -1462,7 +557,7 @@ function resolveWatchdogConfig(cwd2, options = {}) {
1462
557
  ];
1463
558
  for (const source of sourceSpecs) {
1464
559
  if (!source.path) continue;
1465
- sources.push({ scope: source.scope, path: source.path, exists: fs3.existsSync(source.path) });
560
+ sources.push({ scope: source.scope, path: source.path, exists: fs2.existsSync(source.path) });
1466
561
  try {
1467
562
  patch = deepMerge(patch, parseSourceFile(source.path, source.scope));
1468
563
  } catch (error) {
@@ -1809,6 +904,10 @@ var SubagentParamProperties = {
1809
904
  agentScope: Type2.Optional(Type2.String({ description: "user/project/both (default); project wins collisions." })),
1810
905
  cwd: Type2.Optional(Type2.String({ description: "Execution/project-pane directory." })),
1811
906
  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.' })),
907
+ requireLauncher: Type2.Optional(Type2.Object({
908
+ name: Type2.String({ pattern: RUNNER_LAUNCHER_NAME_PATTERN.source }),
909
+ definitionDigest: Type2.String({ pattern: "^[0-9a-f]{64}$" })
910
+ }, { additionalProperties: false, description: "Top-level single async launch only: refuse unless the agent runs under this launcher with this definition digest (preflight agent.definitionDigest)." })),
1812
911
  artifacts: Type2.Optional(Type2.Boolean({ description: "Debug artifacts; default true." })),
1813
912
  includeProgress: Type2.Optional(Type2.Boolean({ description: "Full result progress; default false." })),
1814
913
  share: Type2.Optional(Type2.Boolean({ description: "Upload session to GitHub Gist; default false." })),
@@ -1897,6 +996,8 @@ var SubagentWaitParams = keepTopLevelParameterDescriptions(SubagentWaitParamsSch
1897
996
  // src/runs/background/wait-config.ts
1898
997
  var WAIT_TOOL_ENABLED_ENV = "PI_SUBAGENT_WAIT_TOOL_ENABLED";
1899
998
  var WAIT_TOOL_DEFAULT_TIMEOUT_MS_ENV = "PI_SUBAGENT_WAIT_TOOL_DEFAULT_TIMEOUT_MS";
999
+ var WAIT_TOOL_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
1000
+ 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"]);
1900
1001
  var TRUE_VALUES = /* @__PURE__ */ new Set(["1", "true", "yes", "on", "enabled"]);
1901
1002
  var FALSE_VALUES = /* @__PURE__ */ new Set(["0", "false", "no", "off", "disabled"]);
1902
1003
  function environmentValue(value) {
@@ -1916,33 +1017,42 @@ function configuredValue(config) {
1916
1017
  if (config === void 0) return {};
1917
1018
  if (typeof config === "boolean") return { enabled: config };
1918
1019
  if (!config || typeof config !== "object" || Array.isArray(config)) {
1919
- throw new Error("config.waitTool must be a boolean or an object with optional enabled and defaultTimeoutMs values.");
1020
+ throw new Error("config.waitTool must be a boolean or an object with optional enabled, defaultTimeoutMs and name values.");
1920
1021
  }
1921
- const { enabled, defaultTimeoutMs } = config;
1022
+ const { enabled, defaultTimeoutMs, name } = config;
1922
1023
  if (enabled !== void 0 && typeof enabled !== "boolean") throw new Error("config.waitTool.enabled must be a boolean.");
1923
1024
  if (defaultTimeoutMs !== void 0 && (!Number.isInteger(defaultTimeoutMs) || defaultTimeoutMs < 1)) {
1924
1025
  throw new Error("config.waitTool.defaultTimeoutMs must be a positive integer.");
1925
1026
  }
1926
- return { enabled, ...defaultTimeoutMs !== void 0 ? { defaultTimeoutMs } : {} };
1027
+ if (name !== void 0 && (typeof name !== "string" || !WAIT_TOOL_NAME_PATTERN.test(name))) {
1028
+ throw new Error("config.waitTool.name must start with a letter and contain only letters, digits and underscores (at most 64 characters).");
1029
+ }
1030
+ if (typeof name === "string" && RESERVED_TOOL_NAMES.has(name)) throw new Error(`config.waitTool.name "${name}" is already a pi-subagents tool.`);
1031
+ return {
1032
+ enabled,
1033
+ ...defaultTimeoutMs !== void 0 ? { defaultTimeoutMs } : {},
1034
+ ...name !== void 0 && name !== DEFAULT_WAIT_TOOL_NAME ? { name } : {}
1035
+ };
1927
1036
  }
1928
1037
  function resolveWaitToolConfig(config, env = process.env) {
1929
1038
  const configured = configuredValue(config);
1930
1039
  const envDefaultTimeoutMs = environmentDefaultTimeoutMs(env[WAIT_TOOL_DEFAULT_TIMEOUT_MS_ENV]);
1931
1040
  return {
1932
1041
  enabled: environmentValue(env[WAIT_TOOL_ENABLED_ENV]) ?? configured.enabled ?? true,
1933
- ...envDefaultTimeoutMs ?? configured.defaultTimeoutMs !== void 0 ? { defaultTimeoutMs: envDefaultTimeoutMs ?? configured.defaultTimeoutMs } : {}
1042
+ ...envDefaultTimeoutMs ?? configured.defaultTimeoutMs !== void 0 ? { defaultTimeoutMs: envDefaultTimeoutMs ?? configured.defaultTimeoutMs } : {},
1043
+ ...configured.name ? { name: configured.name } : {}
1934
1044
  };
1935
1045
  }
1936
1046
 
1937
1047
  // src/runs/background/subagent-wait.ts
1938
- import * as fs7 from "node:fs";
1939
- import * as path4 from "node:path";
1048
+ import * as fs6 from "node:fs";
1049
+ import * as path5 from "node:path";
1940
1050
 
1941
1051
  // src/runs/background/wait-completions.ts
1942
- import * as fs5 from "node:fs";
1052
+ import * as fs4 from "node:fs";
1943
1053
 
1944
1054
  // src/runs/background/completion-replay.ts
1945
- import * as fs4 from "node:fs";
1055
+ import * as fs3 from "node:fs";
1946
1056
  import * as path3 from "node:path";
1947
1057
  var REPLAY_VERSION = 1;
1948
1058
  var ARCHIVE_VERSION = 1;
@@ -1967,7 +1077,7 @@ function existingFile(value) {
1967
1077
  const filePath = nonEmptyString(value);
1968
1078
  if (!filePath) return void 0;
1969
1079
  try {
1970
- return fs4.statSync(filePath).isFile() ? filePath : void 0;
1080
+ return fs3.statSync(filePath).isFile() ? filePath : void 0;
1971
1081
  } catch {
1972
1082
  return void 0;
1973
1083
  }
@@ -2052,7 +1162,7 @@ function runIdFromReplayFile(file) {
2052
1162
  }
2053
1163
  function removeBestEffort(filePath) {
2054
1164
  try {
2055
- fs4.rmSync(filePath, { force: true });
1165
+ fs3.rmSync(filePath, { force: true });
2056
1166
  } catch {
2057
1167
  }
2058
1168
  }
@@ -2095,7 +1205,7 @@ function readCompletionReplay(resultsDir, runId, options = {}) {
2095
1205
  const replayPath = completionReplayPath(resultsDir, runId);
2096
1206
  let parsed;
2097
1207
  try {
2098
- parsed = parseReplay(JSON.parse(fs4.readFileSync(replayPath, "utf-8")));
1208
+ parsed = parseReplay(JSON.parse(fs3.readFileSync(replayPath, "utf-8")));
2099
1209
  } catch (error) {
2100
1210
  if (error.code === "ENOENT") return void 0;
2101
1211
  throw error;
@@ -2117,7 +1227,7 @@ function readCompletionReplay(resultsDir, runId, options = {}) {
2117
1227
  }
2118
1228
  function readCompletionArchive(archivePath) {
2119
1229
  try {
2120
- const archive = parseArchive(JSON.parse(fs4.readFileSync(archivePath, "utf-8")));
1230
+ const archive = parseArchive(JSON.parse(fs3.readFileSync(archivePath, "utf-8")));
2121
1231
  if (!archive) throw new Error("Completion archive is malformed.");
2122
1232
  return archive;
2123
1233
  } catch (error) {
@@ -2135,20 +1245,20 @@ function cleanupCompletionReplayIfDue(resultsDir, now, maxAgeMs, intervalMs = CL
2135
1245
  function cleanupCompletionReplay(resultsDir, now, maxAgeMs) {
2136
1246
  const replayDir = path3.join(resultsDir, REPLAY_DIR_NAME);
2137
1247
  try {
2138
- for (const file of fs4.readdirSync(replayDir)) {
1248
+ for (const file of fs3.readdirSync(replayDir)) {
2139
1249
  const runId = runIdFromReplayFile(file);
2140
1250
  if (!runId) continue;
2141
1251
  const filePath = path3.join(replayDir, file);
2142
1252
  try {
2143
- const record = parseReplay(JSON.parse(fs4.readFileSync(filePath, "utf-8")));
1253
+ const record = parseReplay(JSON.parse(fs3.readFileSync(filePath, "utf-8")));
2144
1254
  const safeRecord = record ? validateReplayRecord(resultsDir, runId, record) : void 0;
2145
1255
  if (record && !safeRecord) {
2146
- fs4.rmSync(filePath, { force: true });
1256
+ fs3.rmSync(filePath, { force: true });
2147
1257
  } else if (safeRecord && safeRecord.expiresAt <= now) {
2148
- fs4.rmSync(filePath, { force: true });
2149
- fs4.rmSync(safeRecord.archivePath, { force: true });
2150
- } else if (!record && now - fs4.statSync(filePath).mtimeMs > maxAgeMs) {
2151
- fs4.rmSync(filePath, { force: true });
1258
+ fs3.rmSync(filePath, { force: true });
1259
+ fs3.rmSync(safeRecord.archivePath, { force: true });
1260
+ } else if (!record && now - fs3.statSync(filePath).mtimeMs > maxAgeMs) {
1261
+ fs3.rmSync(filePath, { force: true });
2152
1262
  }
2153
1263
  } catch {
2154
1264
  }
@@ -2157,10 +1267,10 @@ function cleanupCompletionReplay(resultsDir, now, maxAgeMs) {
2157
1267
  }
2158
1268
  const archiveDir = path3.join(resultsDir, ARCHIVE_DIR_NAME);
2159
1269
  try {
2160
- for (const file of fs4.readdirSync(archiveDir)) {
1270
+ for (const file of fs3.readdirSync(archiveDir)) {
2161
1271
  const filePath = path3.join(archiveDir, file);
2162
1272
  try {
2163
- if (now - fs4.statSync(filePath).mtimeMs > maxAgeMs) fs4.rmSync(filePath, { force: true });
1273
+ if (now - fs3.statSync(filePath).mtimeMs > maxAgeMs) fs3.rmSync(filePath, { force: true });
2164
1274
  } catch {
2165
1275
  }
2166
1276
  }
@@ -2212,7 +1322,7 @@ function waitResultPayloadCandidate(resultsDir, run) {
2212
1322
  }
2213
1323
  function readWaitResultPayload(candidatePath, run) {
2214
1324
  if (!run.sessionId) return void 0;
2215
- const payload = JSON.parse(fs5.readFileSync(candidatePath, "utf-8"));
1325
+ const payload = JSON.parse(fs4.readFileSync(candidatePath, "utf-8"));
2216
1326
  if (!resultPayloadMatchesSessionRun(payload, run.sessionId, run.id)) return void 0;
2217
1327
  return payload;
2218
1328
  }
@@ -2372,21 +1482,22 @@ function collectWaitCompletions(terminal, state, resultsDir, onReference) {
2372
1482
  }
2373
1483
 
2374
1484
  // src/runs/background/resume-guidance.ts
2375
- import * as fs6 from "node:fs";
1485
+ import * as fs5 from "node:fs";
1486
+ import * as path4 from "node:path";
2376
1487
  var INTERCOM_DETACH_ERROR = "detached for intercom coordination";
2377
1488
  function isIntercomDetached(run) {
2378
1489
  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;
2379
1490
  }
2380
1491
  function formatIntercomDetachGuidance(run) {
2381
1492
  if (!isIntercomDetached(run)) return void 0;
2382
- 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.`;
1493
+ 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.`;
2383
1494
  }
2384
1495
  function formatAsyncReviveCommand(run) {
2385
1496
  const step = run.steps.find((candidate) => candidate.status === "failed");
2386
1497
  const sessionFile = step?.sessionFile ?? (run.steps.length === 1 ? run.sessionFile : void 0);
2387
- if (!step || !sessionFile || !fs6.existsSync(sessionFile)) return void 0;
1498
+ if (!step || !sessionFile || !fs5.existsSync(sessionFile)) return void 0;
2388
1499
  try {
2389
- const descriptor = readAsyncRecoveryDescriptor(run.asyncDir);
1500
+ const descriptor = readAsyncRecoveryDescriptor(path4.dirname(run.asyncDir), path4.basename(run.asyncDir));
2390
1501
  if (!descriptor || descriptor.sourceRunId !== run.id || descriptor.agent !== step.agent) return void 0;
2391
1502
  } catch {
2392
1503
  return void 0;
@@ -2515,7 +1626,7 @@ function foregroundChildrenNeedingAttention(run, indices) {
2515
1626
  function formatForegroundAttention(run, children, elapsedMs) {
2516
1627
  const childList = children.map((child) => `${child.agent}${child.index !== void 0 ? `#${child.index}` : ""}`).join(", ");
2517
1628
  return result(
2518
- `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.`
1629
+ `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.`
2519
1630
  );
2520
1631
  }
2521
1632
  function needsAttention(run) {
@@ -2529,7 +1640,7 @@ function backgroundWorkIdentity(item) {
2529
1640
  }
2530
1641
  function backgroundWorkForSession(deps, nowMs) {
2531
1642
  const sessionId = deps.state.currentSessionId;
2532
- if (!sessionId) throw new Error("bg_wait requires an active session identity to scope background work safely.");
1643
+ if (!sessionId) throw new Error(`${waitToolName()} requires an active session identity to scope background work safely.`);
2533
1644
  const piSessionId = deps.state.supervisorOwnerSessionId;
2534
1645
  const sessionIds = piSessionId ? [sessionId, piSessionId] : [sessionId];
2535
1646
  return deps.backgroundWork?.snapshot(sessionIds, nowMs) ?? snapshotBackgroundWork(sessionIds, nowMs);
@@ -2542,7 +1653,7 @@ function waitRunScopes(deps) {
2542
1653
  }
2543
1654
  function collectScopedCompletions(terminal, deps, references) {
2544
1655
  const completions = waitRunScopes(deps).flatMap((scope) => collectWaitCompletions(
2545
- terminal.filter((run) => path4.resolve(path4.dirname(run.asyncDir)) === path4.resolve(scope.asyncDirRoot)),
1656
+ terminal.filter((run) => path5.resolve(path5.dirname(run.asyncDir)) === path5.resolve(scope.asyncDirRoot)),
2546
1657
  deps.state,
2547
1658
  scope.resultsDir,
2548
1659
  (reference) => references.push(reference)
@@ -2711,13 +1822,13 @@ function readTranscriptActivity(transcriptPath) {
2711
1822
  if (!transcriptPath) return void 0;
2712
1823
  let fd;
2713
1824
  try {
2714
- const stat = fs7.statSync(transcriptPath);
1825
+ const stat = fs6.statSync(transcriptPath);
2715
1826
  if (!stat.isFile() || stat.size <= 0) return void 0;
2716
1827
  const start = Math.max(0, stat.size - TRANSCRIPT_TAIL_BYTES);
2717
1828
  const length = stat.size - start;
2718
1829
  const buffer = Buffer.allocUnsafe(length);
2719
- fd = fs7.openSync(transcriptPath, "r");
2720
- const bytesRead = fs7.readSync(fd, buffer, 0, length, start);
1830
+ fd = fs6.openSync(transcriptPath, "r");
1831
+ const bytesRead = fs6.readSync(fd, buffer, 0, length, start);
2721
1832
  let lines = buffer.subarray(0, bytesRead).toString("utf-8").split(/\r?\n/);
2722
1833
  if (start > 0) lines = lines.slice(1);
2723
1834
  let currentTool;
@@ -2762,7 +1873,7 @@ function readTranscriptActivity(transcriptPath) {
2762
1873
  } finally {
2763
1874
  if (fd !== void 0) {
2764
1875
  try {
2765
- fs7.closeSync(fd);
1876
+ fs6.closeSync(fd);
2766
1877
  } catch {
2767
1878
  }
2768
1879
  }
@@ -2813,7 +1924,7 @@ async function waitForDetachedForegroundRun(run, signal, deps, startedAt, now, p
2813
1924
  }
2814
1925
  if (now() - startedAt >= timeoutMs) {
2815
1926
  return windowElapsedResult(
2816
- `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.`,
1927
+ `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.`,
2817
1928
  [run.runId]
2818
1929
  );
2819
1930
  }
@@ -2843,10 +1954,10 @@ async function waitForSessionDetachedForegroundRuns(runs, signal, deps, startedA
2843
1954
  }
2844
1955
  async function waitForSubagents(params, signal, deps) {
2845
1956
  if (deps.enabled === false) {
2846
- 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.');
1957
+ 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.`);
2847
1958
  }
2848
1959
  if (!deps.state.currentSessionId) {
2849
- return result("bg_wait requires an active session identity to scope background work safely.", true);
1960
+ return result(`${waitToolName()} requires an active session identity to scope background work safely.`, true);
2850
1961
  }
2851
1962
  const now = deps.now ?? Date.now;
2852
1963
  const pollIntervalMs = Math.max(MIN_POLL_INTERVAL_MS, deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS);
@@ -2901,7 +2012,7 @@ ${references2.join("\n")}` : ""}`,
2901
2012
  }
2902
2013
  if (selected && params.nonBlocking) {
2903
2014
  if (!deps.subscribe) {
2904
- return result("Non-blocking wait subscriptions require a long-lived interactive subagent runtime; this runtime can only use blocking bg_wait calls.", true);
2015
+ return result(`Non-blocking wait subscriptions require a long-lived interactive subagent runtime; this runtime can only use blocking ${waitToolName()} calls.`, true);
2905
2016
  }
2906
2017
  try {
2907
2018
  const registration = deps.subscribe({ targetKind: selected.kind, runId: selected.id, requestedId: params.id, timeoutMs });
@@ -2970,7 +2081,7 @@ ${references2.join("\n")}` : ""}`,
2970
2081
  }
2971
2082
  if (now() - startedAt >= timeoutMs) {
2972
2083
  return windowElapsedResult(
2973
- `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.`,
2084
+ `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.`,
2974
2085
  activeInitialRuns.map((run) => run.id),
2975
2086
  activeInitialProviderItems
2976
2087
  );
@@ -2983,7 +2094,7 @@ ${references2.join("\n")}` : ""}`,
2983
2094
  providerSnapshot = params.id ? providerSnapshot : backgroundWorkForSession(deps, now());
2984
2095
  for (const provider of initialProviderNames) {
2985
2096
  if (!providerSnapshot.providers.includes(provider)) {
2986
- return result(`Background-work provider '${provider}' disappeared while bg_wait was tracking its active work; completion cannot be confirmed.`, true);
2097
+ return result(`Background-work provider '${provider}' disappeared while ${waitToolName()} was tracking its active work; completion cannot be confirmed.`, true);
2987
2098
  }
2988
2099
  }
2989
2100
  providerActive = providerSnapshot.items;
@@ -3015,7 +2126,7 @@ ${references2.join("\n")}` : ""}`,
3015
2126
  }
3016
2127
  const relevantAttention = attention.filter((run) => initialAsyncIds.has(run.id));
3017
2128
  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.' : "";
3018
- 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." : "";
2129
+ 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.` : "";
3019
2130
  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}` : "";
3020
2131
  const stillRunning = active.filter((run) => initialAsyncIds.has(run.id)).length + providerActive.filter((item) => initialProviderIds.has(backgroundWorkIdentity(item))).length;
3021
2132
  const elapsed = formatDuration(now() - startedAt);
@@ -3039,7 +2150,7 @@ ${foregroundResult.content.map((part) => part.type === "text" ? part.text : "").
3039
2150
  }
3040
2151
  const finishedCount = finishedAsyncCount + providerFinishedCount;
3041
2152
  const subject = initialProviderIds.size === 0 ? "run(s)" : "item(s)";
3042
- 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.";
2153
+ 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.";
3043
2154
  const progress = relevantAttention.length > 0 && finishedCount === 0 ? `${relevantAttention.length} of ${initialCount} ${subject} need attention` : `${finishedCount} of ${initialCount} ${subject} finished`;
3044
2155
  return result(
3045
2156
  `Waited ${elapsed}; ${progress}.${outcome}${recoveryNote}${resumeGuidance}${attentionNote}${remainder} Relevant completion/control events have been observed; inspect status if a notification is not visible yet.`,
@@ -3177,7 +2288,8 @@ function setDeclarationPinning(pi, pinned) {
3177
2288
 
3178
2289
  // src/runs/background/wait-tool.ts
3179
2290
  function registerWaitTool(pi, state, enabled = resolveWaitToolConfig().enabled, subscriptions, defaultTimeoutMs, child, hasPendingSupervisorRequest) {
3180
- 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."}
2291
+ const name = waitToolName();
2292
+ 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.`}
3181
2293
  {} \u2014 first active run or provider item to finish or need attention.
3182
2294
  {all:true} \u2014 all work active at call time.
3183
2295
  {id} \u2014 one run; a finished async run returns its result references.
@@ -3208,7 +2320,7 @@ Timeout or a user message ends the wait without error; work keeps running.${enab
3208
2320
  }
3209
2321
  };
3210
2322
  const primaryTool = {
3211
- name: "bg_wait",
2323
+ name,
3212
2324
  label: "Background Wait",
3213
2325
  description,
3214
2326
  parameters: SubagentWaitParams,
@@ -3273,7 +2385,7 @@ async function drainOutstandingWork(deps, observation) {
3273
2385
  }
3274
2386
  );
3275
2387
  if (waitResult.isError) {
3276
- throw new Error(`Auto-drain failed for session '${sessionId}': ${resultText(waitResult) || "bg_wait returned an error without details"}.`);
2388
+ throw new Error(`Auto-drain failed for session '${sessionId}': ${resultText(waitResult) || `${waitToolName()} returned an error without details`}.`);
3277
2389
  }
3278
2390
  if (waitResult.details.wait?.reason === "supervisor_request") break;
3279
2391
  if (deps.hasPendingSupervisorRequest?.()) break;
@@ -3315,102 +2427,13 @@ function evaluateChildToolDiagnostic(config, availableTools) {
3315
2427
  };
3316
2428
  }
3317
2429
 
3318
- // src/watchdog/diff-tool.ts
3319
- import { execFile, spawnSync } from "node:child_process";
3320
- import * as path5 from "node:path";
3321
- import { Type as Type3 } from "typebox";
3322
- var WATCHDOG_DIFF_TOOL_NAME = "watchdog_diff";
3323
- var WATCHDOG_DIFF_MAX_CHARS = 24e3;
3324
- 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.";
3325
- var MAX_UNTRACKED_FILES = 50;
3326
- var WatchdogDiffParams = Type3.Object({
3327
- path: Type3.Optional(Type3.String({ description: "Restrict the diff to one file or directory, relative to the repo root." })),
3328
- stat: Type3.Optional(Type3.Boolean({ description: "Return per-file change counts instead of the full diff." }))
3329
- }, { additionalProperties: false });
3330
- function runGit(root, args2) {
3331
- const result2 = spawnSync("git", ["-C", root, ...args2], { encoding: "utf-8", maxBuffer: 16 * 1024 * 1024, windowsHide: true });
3332
- return { ok: result2.status === 0, stdout: result2.stdout ?? "", stderr: (result2.stderr ?? "").trim() };
3333
- }
3334
- var BASELINE_ARGS = ["rev-parse", "--show-toplevel", "HEAD"];
3335
- function parseBaseline(stdout) {
3336
- const lines = stdout.trim().split(/\r?\n/);
3337
- const ref = lines.pop();
3338
- const root = lines.join("\n");
3339
- return root && ref ? { root, ref } : void 0;
3340
- }
3341
- function captureWatchdogDiffBaseline(cwd2) {
3342
- const result2 = runGit(cwd2, BASELINE_ARGS);
3343
- return result2.ok ? parseBaseline(result2.stdout) : void 0;
3344
- }
3345
- function startWatchdogDiffBaselineCapture(cwd2) {
3346
- return new Promise((resolve5) => {
3347
- try {
3348
- execFile("git", ["-C", cwd2, ...BASELINE_ARGS], { encoding: "utf-8", windowsHide: true }, (error, stdout) => {
3349
- resolve5(error ? void 0 : parseBaseline(stdout));
3350
- });
3351
- } catch {
3352
- resolve5(void 0);
3353
- }
3354
- });
3355
- }
3356
- function validatePath(value) {
3357
- const trimmed = value?.trim();
3358
- if (!trimmed) return void 0;
3359
- if (trimmed.startsWith("-")) throw new Error("watchdog_diff path must not start with '-'.");
3360
- if (path5.isAbsolute(trimmed)) throw new Error("watchdog_diff path must be relative to the repo root.");
3361
- if (trimmed.split(/[\\/]/).includes("..")) throw new Error("watchdog_diff path must not contain '..'.");
3362
- return trimmed;
3363
- }
3364
- function bound(text) {
3365
- if (text.length <= WATCHDOG_DIFF_MAX_CHARS) return text;
3366
- const marker = `
3367
-
3368
- [... ${text.length - WATCHDOG_DIFF_MAX_CHARS} characters omitted; call again with a narrower path ...]`;
3369
- return `${text.slice(0, WATCHDOG_DIFF_MAX_CHARS - marker.length)}${marker}`;
3370
- }
3371
- function createWatchdogDiffTool(baseline, options = {}) {
3372
- const workingTreeAtLaunch = options.workingTreeAtLaunch === true;
3373
- return {
3374
- name: WATCHDOG_DIFF_TOOL_NAME,
3375
- label: "Watchdog diff",
3376
- 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.",
3377
- parameters: WatchdogDiffParams,
3378
- executionMode: "sequential",
3379
- async execute(_toolCallId, params) {
3380
- if (!baseline) {
3381
- return { content: [{ type: "text", text: WATCHDOG_DIFF_UNAVAILABLE_BASELINE }], details: { chars: WATCHDOG_DIFF_UNAVAILABLE_BASELINE.length } };
3382
- }
3383
- const pathFilter = validatePath(params.path);
3384
- const diff = runGit(baseline.root, ["diff", "--no-color", "--no-ext-diff", ...params.stat === true ? ["--stat"] : [], baseline.ref, "--", ...pathFilter ? [pathFilter] : []]);
3385
- if (!diff.ok) throw new Error(`git diff failed: ${diff.stderr || "unknown error"}`);
3386
- const untrackedResult = runGit(baseline.root, ["ls-files", "--others", "--exclude-standard", "-z", "--", ...pathFilter ? [pathFilter] : []]);
3387
- if (workingTreeAtLaunch) {
3388
- const currentHead = runGit(baseline.root, ["rev-parse", "HEAD"]);
3389
- if (!currentHead.ok || currentHead.stdout.trim() !== baseline.ref) {
3390
- const text2 = "Reviewer-launch HEAD changed or is unavailable. Committed changes are unsupported; relaunch the reviewer or supply a diff artifact.";
3391
- return { content: [{ type: "text", text: text2 }], details: { chars: text2.length } };
3392
- }
3393
- }
3394
- const untracked = untrackedResult.ok ? untrackedResult.stdout.split("\0").filter(Boolean) : [];
3395
- const sections = [diff.stdout.trimEnd()];
3396
- if (untracked.length) {
3397
- const shown = untracked.slice(0, MAX_UNTRACKED_FILES);
3398
- sections.push(["Untracked files (use read to inspect):", ...shown.map((file) => ` ${file}`)].join("\n"));
3399
- if (untracked.length > shown.length) sections.push(`... ${untracked.length - shown.length} more untracked files`);
3400
- }
3401
- 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)}.`);
3402
- return { content: [{ type: "text", text }], details: { chars: text.length } };
3403
- }
3404
- };
3405
- }
3406
-
3407
2430
  // src/watchdog/runtime.ts
3408
2431
  import { createHash as createHash3 } from "node:crypto";
3409
2432
 
3410
2433
  // src/watchdog/change-signature.ts
3411
2434
  import { spawnSync as spawnSync2 } from "node:child_process";
3412
2435
  import { createHash } from "node:crypto";
3413
- import * as fs8 from "node:fs";
2436
+ import * as fs7 from "node:fs";
3414
2437
  import * as os from "node:os";
3415
2438
  import * as path6 from "node:path";
3416
2439
  var IGNORED_CHANGE_PREFIXES = [`${PROJECT_SUBAGENTS_RELATIVE_DIR}/`, "tmp/", "node_modules/"];
@@ -3441,7 +2464,7 @@ function git(cwd2, args2) {
3441
2464
  function comparablePath(value) {
3442
2465
  let resolved = path6.resolve(value);
3443
2466
  try {
3444
- resolved = fs8.realpathSync.native(resolved);
2467
+ resolved = fs7.realpathSync.native(resolved);
3445
2468
  } catch {
3446
2469
  }
3447
2470
  return process.platform === "win32" ? resolved.toLowerCase() : resolved;
@@ -3473,7 +2496,7 @@ function useHashEntryBudget(budget) {
3473
2496
  return true;
3474
2497
  }
3475
2498
  function hashFile(filePath) {
3476
- return createHash("sha256").update(fs8.readFileSync(filePath)).digest("hex");
2499
+ return createHash("sha256").update(fs7.readFileSync(filePath)).digest("hex");
3477
2500
  }
3478
2501
  function largeFileHash(stat) {
3479
2502
  return "large:" + stat.size + ":" + Math.floor(stat.mtimeMs);
@@ -3513,17 +2536,17 @@ function hashPath(root, relPath, budget) {
3513
2536
  const fullPath = path6.join(root, normalized);
3514
2537
  let stat;
3515
2538
  try {
3516
- stat = fs8.lstatSync(fullPath);
2539
+ stat = fs7.lstatSync(fullPath);
3517
2540
  } catch (error) {
3518
2541
  if (error.code === "ENOENT") return { path: normalized, state: "deleted" };
3519
2542
  throw error;
3520
2543
  }
3521
2544
  if (stat.isSymbolicLink()) {
3522
- return { path: normalized, state: "symlink", target: fs8.readlinkSync(fullPath) };
2545
+ return { path: normalized, state: "symlink", target: fs7.readlinkSync(fullPath) };
3523
2546
  }
3524
2547
  if (stat.isDirectory()) {
3525
- if (fs8.existsSync(path6.join(fullPath, ".git"))) return gitWorktreeEntry(normalized, fullPath);
3526
- const entries = fs8.readdirSync(fullPath).map((entry) => normalizeRelPath(path6.posix.join(normalized, entry))).filter((entry) => !ignoredRelPath(entry)).sort();
2548
+ if (fs7.existsSync(path6.join(fullPath, ".git"))) return gitWorktreeEntry(normalized, fullPath);
2549
+ const entries = fs7.readdirSync(fullPath).map((entry) => normalizeRelPath(path6.posix.join(normalized, entry))).filter((entry) => !ignoredRelPath(entry)).sort();
3527
2550
  const remainingEntries = Math.max(0, budget.maxEntries - budget.entries);
3528
2551
  const selectedEntries = entries.slice(0, remainingEntries);
3529
2552
  const childEntries = selectedEntries.map((entry) => hashPath(root, entry, budget));
@@ -3701,7 +2724,7 @@ var WatchdogEmissionGuard = class {
3701
2724
  // src/watchdog/lsp-diagnostics.ts
3702
2725
  import { spawn } from "node:child_process";
3703
2726
  import { createHash as createHash2 } from "node:crypto";
3704
- import * as fs9 from "node:fs";
2727
+ import * as fs8 from "node:fs";
3705
2728
  import * as path7 from "node:path";
3706
2729
  import { pathToFileURL } from "node:url";
3707
2730
  var TS_JS_EXTENSIONS = /* @__PURE__ */ new Map([
@@ -3740,10 +2763,10 @@ function severityFromLsp(value) {
3740
2763
  }
3741
2764
  function pathExecutable(filePath) {
3742
2765
  try {
3743
- const stat = fs9.statSync(filePath);
2766
+ const stat = fs8.statSync(filePath);
3744
2767
  if (!stat.isFile()) return false;
3745
2768
  if (process.platform === "win32") return true;
3746
- fs9.accessSync(filePath, fs9.constants.X_OK);
2769
+ fs8.accessSync(filePath, fs8.constants.X_OK);
3747
2770
  return true;
3748
2771
  } catch {
3749
2772
  return false;
@@ -3780,7 +2803,7 @@ function collectTargetFiles(root, changedPaths, maxFiles) {
3780
2803
  }
3781
2804
  let stat;
3782
2805
  try {
3783
- stat = fs9.statSync(absPath);
2806
+ stat = fs8.statSync(absPath);
3784
2807
  } catch (error) {
3785
2808
  if (error.code === "ENOENT") {
3786
2809
  skippedPaths.push(relPath);
@@ -4074,7 +3097,7 @@ async function collectWithTypeScriptLanguageServer(input) {
4074
3097
  await client.request("initialize", initializeParams(input.root), remaining(), input.signal);
4075
3098
  client.notify("initialized", {});
4076
3099
  for (const target of input.targets) {
4077
- const text = fs9.readFileSync(target.absPath, "utf-8");
3100
+ const text = fs8.readFileSync(target.absPath, "utf-8");
4078
3101
  client.notify("textDocument/didOpen", {
4079
3102
  textDocument: { uri: target.uri, languageId: target.languageId, version: 1, text }
4080
3103
  });
@@ -4328,7 +3351,7 @@ function formatWatchdogOrchestrationActivity(event) {
4328
3351
  if (call?.type !== "toolCall" || typeof call.id !== "string") continue;
4329
3352
  const args2 = call.arguments;
4330
3353
  if (!args2 || typeof args2 !== "object") continue;
4331
- 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));
3354
+ 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));
4332
3355
  if (!eligible) continue;
4333
3356
  const result2 = turn.toolResults.find((value) => {
4334
3357
  const result3 = value;
@@ -5108,15 +4131,15 @@ ${this.activityTail}` : "";
5108
4131
  // src/watchdog/review.ts
5109
4132
  import { Agent } from "@earendil-works/pi-agent-core";
5110
4133
  import { createReadOnlyTools, convertToLlm } from "@earendil-works/pi-coding-agent";
5111
- import { Type as Type4 } from "typebox";
4134
+ import { Type as Type3 } from "typebox";
5112
4135
 
5113
4136
  // src/watchdog/guidance.ts
5114
- import * as fs10 from "node:fs";
4137
+ import * as fs9 from "node:fs";
5115
4138
  import * as path8 from "node:path";
5116
4139
  var WATCHDOG_GUIDANCE_MAX_CHARS = 8e3;
5117
4140
  function readOptional(filePath) {
5118
4141
  try {
5119
- return fs10.readFileSync(filePath, "utf-8").trim();
4142
+ return fs9.readFileSync(filePath, "utf-8").trim();
5120
4143
  } catch {
5121
4144
  return "";
5122
4145
  }
@@ -5129,14 +4152,14 @@ function loadWatchdogGuidance(cwd2, enabled) {
5129
4152
 
5130
4153
  // src/watchdog/review.ts
5131
4154
  var WATCHDOG_ALLOWED_TOOL_NAMES = /* @__PURE__ */ new Set(["read", "grep", "find", "ls", "watchdog_warn", WATCHDOG_DIFF_TOOL_NAME]);
5132
- var WatchdogAskParams = Type4.Object({ question: Type4.String(), evidence: Type4.String() }, { additionalProperties: false });
5133
- var WatchdogWarnParams = Type4.Object({
5134
- severity: Type4.String({ enum: WATCHDOG_WARNING_SEVERITIES, description: "concern for actionable risk, blocker for a likely wrong or unsafe outcome" }),
5135
- importance: Type4.String({ enum: WATCHDOG_WARNING_IMPORTANCES, description: "low or medium for user-only visibility; high when the parent model must receive the finding" }),
5136
- summary: Type4.String({ description: "One concise sentence naming the issue." }),
5137
- evidence: Type4.String({ description: "Specific evidence from the turn delta or inspected files." }),
5138
- recommendedAction: Type4.String({ description: "Specific action the parent should take before accepting or continuing." }),
5139
- category: Type4.Optional(Type4.String({ enum: WATCHDOG_WARNING_CATEGORIES }))
4155
+ var WatchdogAskParams = Type3.Object({ question: Type3.String(), evidence: Type3.String() }, { additionalProperties: false });
4156
+ var WatchdogWarnParams = Type3.Object({
4157
+ severity: Type3.String({ enum: WATCHDOG_WARNING_SEVERITIES, description: "concern for actionable risk, blocker for a likely wrong or unsafe outcome" }),
4158
+ importance: Type3.String({ enum: WATCHDOG_WARNING_IMPORTANCES, description: "low or medium for user-only visibility; high when the parent model must receive the finding" }),
4159
+ summary: Type3.String({ description: "One concise sentence naming the issue." }),
4160
+ evidence: Type3.String({ description: "Specific evidence from the turn delta or inspected files." }),
4161
+ recommendedAction: Type3.String({ description: "Specific action the parent should take before accepting or continuing." }),
4162
+ category: Type3.Optional(Type3.String({ enum: WATCHDOG_WARNING_CATEGORIES }))
5140
4163
  }, { additionalProperties: false });
5141
4164
  function fullModelId(model2) {
5142
4165
  return `${model2.provider}/${model2.id}`;
@@ -5412,16 +4435,6 @@ async function runWatchdogAttempt(ctx, request, options) {
5412
4435
  }
5413
4436
 
5414
4437
  export {
5415
- SUPERVISOR_REQUEST_MESSAGE_TYPE,
5416
- SUPERVISOR_REPLY_ENTRY_TYPE,
5417
- parseSupervisorRequestDetails,
5418
- parseSupervisorReplyData,
5419
- NATIVE_SUPERVISOR_TOOL_NAME,
5420
- resolveSupervisorChannelDir,
5421
- CONTACT_SUPERVISOR_TOOL_NAME,
5422
- topLevelSupervisorTool,
5423
- registerNativeSupervisorClient,
5424
- createNativeSupervisorChannel,
5425
4438
  resolveCurrentSessionId,
5426
4439
  resolvePiSessionId,
5427
4440
  WATCHDOG_DIFF_TOOL_NAME,