@xzzpig/pi-subagents 0.1.0 → 0.2.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 (81) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +2 -0
  3. package/agents/reviewer.md +3 -4
  4. package/docs/agents.md +342 -0
  5. package/docs/configuration.md +328 -0
  6. package/docs/extension-api.md +308 -0
  7. package/docs/missions.md +119 -0
  8. package/docs/models.md +192 -0
  9. package/docs/observability.md +174 -0
  10. package/docs/tool-reference.md +343 -0
  11. package/docs/watchdog.md +176 -0
  12. package/docs/workflows.md +163 -0
  13. package/package.json +13 -11
  14. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  15. package/skills/pi-subagents/references/execution-controls.md +7 -7
  16. package/skills/pi-subagents/references/management-authoring-rpc.md +1 -1
  17. package/skills/pi-subagents/references/prompting-and-roles.md +1 -1
  18. package/src/agents/agents.ts +17 -8
  19. package/src/agents/frontmatter.ts +7 -3
  20. package/src/agents/skills.ts +2 -9
  21. package/src/api/project-panes.ts +30 -0
  22. package/src/extension/config.ts +28 -1
  23. package/src/extension/fanout-child.ts +5 -4
  24. package/src/extension/index.ts +75 -30
  25. package/src/extension/rpc.ts +7 -6
  26. package/src/extension/schemas.ts +29 -8
  27. package/src/extension/subagent-guide.ts +39 -0
  28. package/src/extension/tool-description.ts +30 -12
  29. package/src/inspectors/herdr/project-panes.ts +459 -63
  30. package/src/intercom/native-supervisor-channel.ts +102 -4
  31. package/src/missions/actions.ts +25 -2
  32. package/src/missions/lifecycle.ts +21 -2
  33. package/src/missions/store.ts +79 -2
  34. package/src/missions/types.ts +33 -0
  35. package/src/missions/workflow-state.ts +19 -13
  36. package/src/runs/background/active-run-index.ts +42 -0
  37. package/src/runs/background/async-execution.ts +17 -6
  38. package/src/runs/background/async-job-tracker.ts +293 -133
  39. package/src/runs/background/async-resume.ts +19 -3
  40. package/src/runs/background/async-status.ts +33 -5
  41. package/src/runs/background/completion-replay.ts +267 -0
  42. package/src/runs/background/control-channel.ts +95 -54
  43. package/src/runs/background/result-watcher.ts +113 -10
  44. package/src/runs/background/resume-guidance.ts +33 -0
  45. package/src/runs/background/run-status.ts +18 -0
  46. package/src/runs/background/scheduled-runs.ts +25 -1
  47. package/src/runs/background/stale-run-reconciler.ts +12 -24
  48. package/src/runs/background/subagent-runner.ts +69 -11
  49. package/src/runs/background/subagent-wait.ts +5 -2
  50. package/src/runs/background/wait-completions.ts +39 -5
  51. package/src/runs/background/wait-subscriptions.ts +21 -5
  52. package/src/runs/foreground/async-dismiss-action.ts +85 -0
  53. package/src/runs/foreground/async-steering-action.ts +7 -8
  54. package/src/runs/foreground/chain-execution.ts +3 -0
  55. package/src/runs/foreground/execution.ts +7 -0
  56. package/src/runs/foreground/foreground-history.ts +137 -0
  57. package/src/runs/foreground/subagent-executor.ts +466 -61
  58. package/src/runs/foreground/workflow-foreground-steering.ts +187 -0
  59. package/src/runs/shared/dynamic-fanout.ts +1 -1
  60. package/src/runs/shared/model-fallback.ts +8 -4
  61. package/src/runs/shared/model-scope.ts +12 -2
  62. package/src/runs/shared/parallel-utils.ts +1 -0
  63. package/src/runs/shared/subagent-prompt-runtime.ts +94 -9
  64. package/src/runs/shared/worktree.ts +3 -2
  65. package/src/shared/artifacts.ts +15 -15
  66. package/src/shared/display-text.ts +100 -0
  67. package/src/shared/file-coalescer.ts +9 -0
  68. package/src/shared/fork-context.ts +13 -0
  69. package/src/shared/formatters.ts +4 -6
  70. package/src/shared/prompt-resources.ts +51 -0
  71. package/src/shared/settings.ts +15 -2
  72. package/src/shared/types.ts +45 -2
  73. package/src/shared/utf8.ts +11 -0
  74. package/src/shared/utils.ts +43 -33
  75. package/src/slash/prompt-workflows.ts +2 -15
  76. package/src/slash/slash-commands.ts +22 -2
  77. package/src/tui/fleet-status.ts +22 -12
  78. package/src/tui/fleet.ts +135 -25
  79. package/src/tui/render.ts +150 -33
  80. package/src/watchdog/change-signature.ts +4 -3
  81. package/src/workflows/scripted-workflow.ts +210 -13
@@ -0,0 +1,267 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
4
+ import type { WaitCompletion } from "../../shared/types.ts";
5
+ import { utf8Tail } from "../../shared/utf8.ts";
6
+
7
+ const REPLAY_VERSION = 1;
8
+ const ARCHIVE_VERSION = 1;
9
+ const ARCHIVE_TEXT_LIMIT_BYTES = 64 * 1024;
10
+ const REPLAY_DIR_NAME = "completion-replay";
11
+ const ARCHIVE_DIR_NAME = "output-archives";
12
+
13
+ export interface CompletionArchiveEntry {
14
+ agent?: string;
15
+ source: "output-artifact" | "session" | "result-tail";
16
+ path?: string;
17
+ text?: string;
18
+ truncated?: boolean;
19
+ }
20
+
21
+ export interface CompletionArchive {
22
+ version: 1;
23
+ runId: string;
24
+ createdAt: number;
25
+ entries: CompletionArchiveEntry[];
26
+ }
27
+
28
+ export interface CompletionReplayRecord {
29
+ version: 1;
30
+ runId: string;
31
+ sessionId: string;
32
+ completedAt: number;
33
+ expiresAt: number;
34
+ completion: WaitCompletion;
35
+ archivePath: string;
36
+ }
37
+
38
+ function safeRunFile(runId: string): string {
39
+ return `${encodeURIComponent(runId)}.json`;
40
+ }
41
+
42
+ export function completionReplayPath(resultsDir: string, runId: string): string {
43
+ return path.join(resultsDir, REPLAY_DIR_NAME, safeRunFile(runId));
44
+ }
45
+
46
+ export function completionArchivePath(resultsDir: string, runId: string): string {
47
+ return path.join(resultsDir, ARCHIVE_DIR_NAME, safeRunFile(runId));
48
+ }
49
+
50
+ function nonEmptyString(value: unknown): string | undefined {
51
+ return typeof value === "string" && value.length > 0 ? value : undefined;
52
+ }
53
+
54
+ function existingFile(value: unknown): string | undefined {
55
+ const filePath = nonEmptyString(value);
56
+ if (!filePath) return undefined;
57
+ try {
58
+ return fs.statSync(filePath).isFile() ? filePath : undefined;
59
+ } catch {
60
+ return undefined;
61
+ }
62
+ }
63
+
64
+ function outputArtifactPath(child: Record<string, unknown>): string | undefined {
65
+ if (!child.artifactPaths || typeof child.artifactPaths !== "object" || Array.isArray(child.artifactPaths)) return undefined;
66
+ return existingFile((child.artifactPaths as Record<string, unknown>).outputPath);
67
+ }
68
+
69
+ /** Create a small archive that references saved child artifacts and retains only bounded fallback output text. */
70
+ export function writeCompletionArchive(resultsDir: string, runId: string, data: Record<string, unknown>, createdAt: number): string {
71
+ const entries: CompletionArchiveEntry[] = [];
72
+ const fallback: string[] = [];
73
+ const results = Array.isArray(data.results) ? data.results : [];
74
+ for (const value of results) {
75
+ if (!value || typeof value !== "object" || Array.isArray(value)) continue;
76
+ const child = value as Record<string, unknown>;
77
+ const agent = nonEmptyString(child.agent);
78
+ const artifactPath = outputArtifactPath(child);
79
+ if (artifactPath) {
80
+ entries.push({ ...(agent ? { agent } : {}), source: "output-artifact", path: artifactPath });
81
+ continue;
82
+ }
83
+ const sessionPath = existingFile(child.sessionFile);
84
+ if (sessionPath) {
85
+ entries.push({ ...(agent ? { agent } : {}), source: "session", path: sessionPath });
86
+ continue;
87
+ }
88
+ const output = nonEmptyString(child.output);
89
+ const error = nonEmptyString(child.error);
90
+ if (output || error) {
91
+ fallback.push([agent ? `[${agent}]` : undefined, error ? `Error: ${error}` : undefined, output].filter(Boolean).join("\n"));
92
+ }
93
+ }
94
+ if (results.length === 0) {
95
+ const sessionPath = existingFile(data.sessionFile);
96
+ if (sessionPath) entries.push({ source: "session", path: sessionPath });
97
+ }
98
+ if (entries.length === 0 && fallback.length === 0) {
99
+ const summary = nonEmptyString(data.summary);
100
+ if (summary) fallback.push(summary);
101
+ }
102
+ if (fallback.length > 0) {
103
+ const bounded = utf8Tail(fallback.join("\n\n"), ARCHIVE_TEXT_LIMIT_BYTES);
104
+ entries.push({ source: "result-tail", text: bounded.text, ...(bounded.truncated ? { truncated: true } : {}) });
105
+ }
106
+ const archive: CompletionArchive = { version: ARCHIVE_VERSION, runId, createdAt, entries };
107
+ const archivePath = completionArchivePath(resultsDir, runId);
108
+ writePrivateAtomicJson(archivePath, archive);
109
+ return archivePath;
110
+ }
111
+
112
+ function parseCompletion(value: unknown, runId: string): WaitCompletion | undefined {
113
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
114
+ const completion = value as Partial<WaitCompletion>;
115
+ if (completion.runId !== runId) return undefined;
116
+ return completion as WaitCompletion;
117
+ }
118
+
119
+ function parseReplay(value: unknown): CompletionReplayRecord | undefined {
120
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
121
+ const record = value as Partial<CompletionReplayRecord>;
122
+ if (record.version !== REPLAY_VERSION
123
+ || typeof record.runId !== "string"
124
+ || typeof record.sessionId !== "string"
125
+ || typeof record.completedAt !== "number"
126
+ || typeof record.expiresAt !== "number"
127
+ || typeof record.archivePath !== "string") return undefined;
128
+ const completion = parseCompletion(record.completion, record.runId);
129
+ return completion ? { ...record, completion } as CompletionReplayRecord : undefined;
130
+ }
131
+
132
+ function validateReplayRecord(resultsDir: string, runId: string, record: CompletionReplayRecord): CompletionReplayRecord | undefined {
133
+ if (record.runId !== runId) return undefined;
134
+ const archivePath = completionArchivePath(resultsDir, runId);
135
+ return path.resolve(record.archivePath) === path.resolve(archivePath)
136
+ ? { ...record, archivePath, completion: { ...record.completion, archivePath } }
137
+ : undefined;
138
+ }
139
+
140
+ function runIdFromReplayFile(file: string): string | undefined {
141
+ if (!file.endsWith(".json")) return undefined;
142
+ try {
143
+ const runId = decodeURIComponent(file.slice(0, -".json".length));
144
+ return safeRunFile(runId) === file ? runId : undefined;
145
+ } catch {
146
+ return undefined;
147
+ }
148
+ }
149
+
150
+ function removeBestEffort(filePath: string): void {
151
+ try {
152
+ fs.rmSync(filePath, { force: true });
153
+ } catch { /* cleanup only */ }
154
+ }
155
+
156
+ function parseArchive(value: unknown): CompletionArchive | undefined {
157
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
158
+ const archive = value as Partial<CompletionArchive>;
159
+ if (archive.version !== ARCHIVE_VERSION || typeof archive.runId !== "string" || typeof archive.createdAt !== "number" || !Array.isArray(archive.entries)) return undefined;
160
+ const entries = archive.entries.flatMap((value): CompletionArchiveEntry[] => {
161
+ if (!value || typeof value !== "object" || Array.isArray(value)) return [];
162
+ const entry = value as Partial<CompletionArchiveEntry>;
163
+ if (entry.source !== "output-artifact" && entry.source !== "session" && entry.source !== "result-tail") return [];
164
+ return [{
165
+ ...(typeof entry.agent === "string" ? { agent: entry.agent } : {}),
166
+ source: entry.source,
167
+ ...(typeof entry.path === "string" ? { path: entry.path } : {}),
168
+ ...(typeof entry.text === "string" ? { text: entry.text } : {}),
169
+ ...(entry.truncated === true ? { truncated: true } : {}),
170
+ }];
171
+ });
172
+ return { version: ARCHIVE_VERSION, runId: archive.runId, createdAt: archive.createdAt, entries };
173
+ }
174
+
175
+ /** Persist a terminal completion before its one-shot result file is removed. */
176
+ export function writeCompletionReplay(input: {
177
+ resultsDir: string;
178
+ runId: string;
179
+ sessionId: string;
180
+ completion: WaitCompletion;
181
+ data: Record<string, unknown>;
182
+ now: number;
183
+ ttlMs: number;
184
+ }): CompletionReplayRecord {
185
+ const archivePath = writeCompletionArchive(input.resultsDir, input.runId, input.data, input.now);
186
+ const completion = { ...input.completion, archivePath };
187
+ const record: CompletionReplayRecord = {
188
+ version: REPLAY_VERSION,
189
+ runId: input.runId,
190
+ sessionId: input.sessionId,
191
+ completedAt: input.now,
192
+ expiresAt: input.now + input.ttlMs,
193
+ completion,
194
+ archivePath,
195
+ };
196
+ writePrivateAtomicJson(completionReplayPath(input.resultsDir, input.runId), record);
197
+ cleanupCompletionReplay(input.resultsDir, input.now, input.ttlMs);
198
+ return record;
199
+ }
200
+
201
+ /** Read a current replay record. Unknown fields are ignored and unknown versions are skipped. */
202
+ export function readCompletionReplay(resultsDir: string, runId: string, options: { sessionId?: string; now?: number } = {}): CompletionReplayRecord | undefined {
203
+ const replayPath = completionReplayPath(resultsDir, runId);
204
+ let parsed: CompletionReplayRecord | undefined;
205
+ try {
206
+ parsed = parseReplay(JSON.parse(fs.readFileSync(replayPath, "utf-8")));
207
+ } catch (error) {
208
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
209
+ throw error;
210
+ }
211
+ if (!parsed) return undefined;
212
+ const safeRecord = validateReplayRecord(resultsDir, runId, parsed);
213
+ if (!safeRecord) {
214
+ removeBestEffort(replayPath);
215
+ return undefined;
216
+ }
217
+ parsed = safeRecord;
218
+ if (options.sessionId !== undefined && parsed.sessionId !== options.sessionId) return undefined;
219
+ if (parsed.expiresAt <= (options.now ?? Date.now())) {
220
+ removeBestEffort(replayPath);
221
+ removeBestEffort(parsed.archivePath);
222
+ return undefined;
223
+ }
224
+ return parsed;
225
+ }
226
+
227
+ export function readCompletionArchive(archivePath: string): CompletionArchive | undefined {
228
+ try {
229
+ return parseArchive(JSON.parse(fs.readFileSync(archivePath, "utf-8")));
230
+ } catch (error) {
231
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
232
+ throw error;
233
+ }
234
+ }
235
+
236
+ /** Opportunistically remove expired replay and orphan archive files without affecting delivery. */
237
+ export function cleanupCompletionReplay(resultsDir: string, now: number, maxAgeMs: number): void {
238
+ const replayDir = path.join(resultsDir, REPLAY_DIR_NAME);
239
+ try {
240
+ for (const file of fs.readdirSync(replayDir)) {
241
+ const runId = runIdFromReplayFile(file);
242
+ if (!runId) continue;
243
+ const filePath = path.join(replayDir, file);
244
+ try {
245
+ const record = parseReplay(JSON.parse(fs.readFileSync(filePath, "utf-8")));
246
+ const safeRecord = record ? validateReplayRecord(resultsDir, runId, record) : undefined;
247
+ if (record && !safeRecord) {
248
+ fs.rmSync(filePath, { force: true });
249
+ } else if (safeRecord && safeRecord.expiresAt <= now) {
250
+ fs.rmSync(filePath, { force: true });
251
+ fs.rmSync(safeRecord.archivePath, { force: true });
252
+ } else if (!record && now - fs.statSync(filePath).mtimeMs > maxAgeMs) {
253
+ fs.rmSync(filePath, { force: true });
254
+ }
255
+ } catch { /* one bad entry must not block cleanup */ }
256
+ }
257
+ } catch { /* replay directory may not exist yet */ }
258
+ const archiveDir = path.join(resultsDir, ARCHIVE_DIR_NAME);
259
+ try {
260
+ for (const file of fs.readdirSync(archiveDir)) {
261
+ const filePath = path.join(archiveDir, file);
262
+ try {
263
+ if (now - fs.statSync(filePath).mtimeMs > maxAgeMs) fs.rmSync(filePath, { force: true });
264
+ } catch { /* one bad entry must not block cleanup */ }
265
+ }
266
+ } catch { /* archive directory may not exist yet */ }
267
+ }
@@ -9,9 +9,8 @@
9
9
  * This module adds a portable, file-based control inbox inside the run directory.
10
10
  * The parent drops an interrupt request file; the runner watches the inbox and
11
11
  * routes the request into its existing graceful `interruptRunner()` (pause +
12
- * resumable), identically on every platform. The OS signal is kept only as an
13
- * opportunistic fast-path; its failure is non-fatal because the file inbox is
14
- * authoritative.
12
+ * resumable), identically on every platform. The file inbox is authoritative and
13
+ * avoids signaling a PID that the extension cannot prove belongs to the runner.
15
14
  */
16
15
 
17
16
  import { randomUUID } from "node:crypto";
@@ -21,15 +20,19 @@ import { writeAtomicJson } from "../../shared/atomic-json.ts";
21
20
  import { POLL_INTERVAL_MS } from "../../shared/types.ts";
22
21
  import { resolveWatchPath } from "../../shared/utils.ts";
23
22
 
24
- /**
25
- * Opportunistic fast-path interrupt signal. On Unix `SIGUSR2` is trapped by the
26
- * runner; on Windows `process.kill(pid, "SIGBREAK")` is not deliverable
27
- * cross-process and throws `ENOSYS`, so the file inbox below is the real channel.
28
- */
29
- export const INTERRUPT_SIGNAL: NodeJS.Signals = process.platform === "win32" ? "SIGBREAK" : "SIGUSR2";
30
-
31
23
  export type ControlChannelFs = Pick<typeof fs, "mkdirSync" | "existsSync" | "rmSync" | "watch" | "readdirSync" | "readFileSync" | "realpathSync">;
24
+
25
+ function writeJsonToExistingDir(filePath: string, payload: object): void {
26
+ const tempPath = path.join(path.dirname(filePath), `.${path.basename(filePath)}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`);
27
+ try {
28
+ fs.writeFileSync(tempPath, JSON.stringify(payload, null, 2), { encoding: "utf-8", flag: "wx" });
29
+ fs.renameSync(tempPath, filePath);
30
+ } finally {
31
+ fs.rmSync(tempPath, { force: true });
32
+ }
33
+ }
32
34
  export type ControlChannelTimers = { setInterval: typeof setInterval; clearInterval: typeof clearInterval };
35
+ const CONTROL_SAFETY_POLL_INTERVAL_MS = 5000;
33
36
  type KillFn = (pid: number, signal?: NodeJS.Signals | 0) => unknown;
34
37
 
35
38
  export interface InterruptRequest {
@@ -213,6 +216,13 @@ export function writeSteerRequestToDir(dir: string, request: SteerRequest): stri
213
216
  return requestPath;
214
217
  }
215
218
 
219
+ export function writeSteerRequestToExistingDir(dir: string, request: SteerRequest): string {
220
+ if (!validSteerRequest(request)) throw new Error("steer request is malformed or exceeds transport limits.");
221
+ const requestPath = path.join(dir, steerRequestFileName(request));
222
+ writeJsonToExistingDir(requestPath, request);
223
+ return requestPath;
224
+ }
225
+
216
226
  export function writeSteerCapabilityAt(filePath: string, capability: Omit<SteerCapability, "type" | "protocolVersion">): string {
217
227
  assertChildIndex(capability.index);
218
228
  if (!Number.isInteger(capability.pid) || capability.pid <= 0) throw new Error("steer capability pid must be a positive integer.");
@@ -393,6 +403,25 @@ export function consumeSteerCapabilities(asyncDir: string, fsImpl: Pick<typeof f
393
403
  return capabilities;
394
404
  }
395
405
 
406
+ export function consumeSteerAckFromDir(
407
+ dir: string,
408
+ requestId: string,
409
+ fsImpl: Pick<typeof fs, "existsSync" | "readdirSync" | "readFileSync" | "rmSync"> = fs,
410
+ ): SteerAck | undefined {
411
+ if (!fsImpl.existsSync(dir)) return undefined;
412
+ let entries: string[];
413
+ try { entries = fsImpl.readdirSync(dir).filter((name) => name.endsWith(".json")).sort(); } catch { return undefined; }
414
+ for (const entry of entries) {
415
+ const target = path.join(dir, entry);
416
+ let ack: SteerAck | undefined;
417
+ try { ack = parseSteerAck(JSON.parse(fsImpl.readFileSync(target, "utf-8"))); } catch { ack = undefined; }
418
+ if (ack?.requestId !== requestId) continue;
419
+ try { fsImpl.rmSync(target, { force: true }); } catch { return undefined; }
420
+ return ack;
421
+ }
422
+ return undefined;
423
+ }
424
+
396
425
  export function consumeSteerAcks(asyncDir: string, fsImpl: Pick<typeof fs, "existsSync" | "readdirSync" | "readFileSync" | "rmSync"> = fs): SteerAck[] {
397
426
  const root = path.join(controlInboxDir(asyncDir), STEER_ACKS_DIR);
398
427
  if (!fsImpl.existsSync(root)) return [];
@@ -545,38 +574,13 @@ export function consumeCheckpointDecisionRequest(
545
574
  return undefined;
546
575
  }
547
576
 
548
- /**
549
- * Parent side: portable interrupt = authoritative file request + best-effort OS
550
- * signal. The signal is only a latency optimization on Unix; ENOSYS on Windows
551
- * is swallowed because the file inbox is authoritative there. Other signal
552
- * failures are surfaced because they usually mean the runner is not alive to
553
- * consume the request.
554
- */
577
+ /** Parent side: write the authoritative portable interrupt request. */
555
578
  export function deliverInterruptRequest(input: {
556
579
  asyncDir: string;
557
- pid?: number;
558
- kill?: KillFn;
559
- signal?: NodeJS.Signals;
560
580
  now?: () => number;
561
581
  source?: string;
562
582
  }): void {
563
- const requestPath = requestAsyncInterrupt(input.asyncDir, input.source ? { source: input.source } : {}, { now: input.now });
564
- if (typeof input.pid === "number" && input.pid > 0) {
565
- try {
566
- (input.kill ?? process.kill)(input.pid, input.signal ?? INTERRUPT_SIGNAL);
567
- } catch (error) {
568
- if ((error as NodeJS.ErrnoException | undefined)?.code === "ENOSYS") {
569
- // File inbox is authoritative when custom cross-process signals are unavailable.
570
- return;
571
- }
572
- try {
573
- fs.rmSync(requestPath, { force: true });
574
- } catch {
575
- // Best effort cleanup; the caller still gets the signal failure.
576
- }
577
- throw error;
578
- }
579
- }
583
+ requestAsyncInterrupt(input.asyncDir, input.source ? { source: input.source } : {}, { now: input.now });
580
584
  }
581
585
 
582
586
  export function deliverTimeoutRequest(input: {
@@ -618,9 +622,9 @@ export function deliverCheckpointDecisionRequest(input: {
618
622
 
619
623
  /**
620
624
  * Runner side: watch the control inbox and route interrupt requests into
621
- * `onInterrupt`. Uses `fs.watch` when available plus an interval poll as a
622
- * portable safety net (covers filesystems/platforms where `fs.watch` is
623
- * unreliable). Fires once per distinct request. Returns a disposer.
625
+ * `onInterrupt`. Uses `fs.watch` when available and starts interval polling
626
+ * only when native watching is unavailable or fails. Fires once per distinct
627
+ * request. Returns a disposer.
624
628
  */
625
629
  export function watchAsyncControlInbox(
626
630
  asyncDir: string,
@@ -633,6 +637,7 @@ export function watchAsyncControlInbox(
633
637
  onSteerCapability?: (capability: SteerCapability) => void;
634
638
  onSteerAck?: (ack: SteerAck) => void;
635
639
  pollIntervalMs?: number;
640
+ safetyPollIntervalMs?: number;
636
641
  fs?: ControlChannelFs;
637
642
  timers?: ControlChannelTimers;
638
643
  },
@@ -666,27 +671,63 @@ export function watchAsyncControlInbox(
666
671
  // Handle a request that may have arrived before the watcher started.
667
672
  check();
668
673
 
669
- let watcher: fs.FSWatcher | undefined;
670
- try {
671
- watcher = fsImpl.watch(resolveWatchPath(dir, fsImpl.realpathSync.native), () => check());
672
- watcher.on?.("error", () => {
673
- // fs.watch can emit on transient FS errors; the interval poll keeps us live.
674
+ const watchers: fs.FSWatcher[] = [];
675
+ const watchedDirs = new Set<string>();
676
+ let interval: ReturnType<typeof setInterval> | undefined;
677
+ let safetyInterval: ReturnType<typeof setInterval> | undefined;
678
+ const startPolling = (): void => {
679
+ if (interval || disposed) return;
680
+ interval = timers.setInterval(check, opts.pollIntervalMs ?? POLL_INTERVAL_MS);
681
+ interval.unref?.();
682
+ };
683
+ const startSafetyPolling = (): void => {
684
+ if (safetyInterval || disposed) return;
685
+ safetyInterval = timers.setInterval(check, opts.safetyPollIntervalMs ?? CONTROL_SAFETY_POLL_INTERVAL_MS);
686
+ safetyInterval.unref?.();
687
+ };
688
+ const watchDir = (target: string, create = false): void => {
689
+ if (disposed || watchedDirs.has(target)) return;
690
+ if (create) fsImpl.mkdirSync(target, { recursive: true });
691
+ const watcher = fsImpl.watch(resolveWatchPath(target, fsImpl.realpathSync.native), () => {
692
+ watchExistingSteerAckDirs();
693
+ check();
674
694
  });
695
+ watcher.on?.("error", startPolling);
696
+ watchers.push(watcher);
697
+ watchedDirs.add(target);
698
+ };
699
+ const watchExistingSteerAckDirs = (): void => {
700
+ const ackRoot = path.join(dir, STEER_ACKS_DIR);
701
+ let entries: string[];
702
+ try {
703
+ entries = fsImpl.readdirSync(ackRoot).filter((name) => /^\d+$/.test(name));
704
+ } catch {
705
+ return;
706
+ }
707
+ for (const entry of entries) watchDir(path.join(ackRoot, entry));
708
+ };
709
+ try {
710
+ watchDir(dir);
711
+ watchDir(steerRequestsDir(asyncDir), true);
712
+ watchDir(steerCapabilitiesDir(asyncDir), true);
713
+ watchDir(path.join(dir, STEER_ACKS_DIR), true);
714
+ watchExistingSteerAckDirs();
715
+ startSafetyPolling();
675
716
  } catch {
676
- watcher = undefined;
717
+ startPolling();
677
718
  }
678
719
 
679
- const interval = timers.setInterval(check, opts.pollIntervalMs ?? POLL_INTERVAL_MS);
680
- interval.unref?.();
681
-
682
720
  return () => {
683
721
  if (disposed) return;
684
722
  disposed = true;
685
- try {
686
- watcher?.close();
687
- } catch {
688
- // ignore
723
+ for (const watcher of watchers) {
724
+ try {
725
+ watcher.close();
726
+ } catch {
727
+ // ignore
728
+ }
689
729
  }
690
- timers.clearInterval(interval);
730
+ if (interval) timers.clearInterval(interval);
731
+ if (safetyInterval) timers.clearInterval(safetyInterval);
691
732
  };
692
733
  }