@xzzpig/pi-subagents 0.1.0 → 0.3.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.
- package/CHANGELOG.md +135 -0
- package/README.md +4 -0
- package/agents/reviewer.md +3 -4
- package/docs/agents.md +343 -0
- package/docs/configuration.md +395 -0
- package/docs/extension-api.md +308 -0
- package/docs/missions.md +121 -0
- package/docs/models.md +192 -0
- package/docs/observability.md +198 -0
- package/docs/tool-reference.md +343 -0
- package/docs/watchdog.md +176 -0
- package/docs/workflows.md +163 -0
- package/package.json +13 -11
- package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
- package/skills/pi-subagents/references/execution-controls.md +7 -7
- package/skills/pi-subagents/references/management-authoring-rpc.md +1 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +1 -1
- package/src/agents/agents.ts +53 -23
- package/src/agents/frontmatter.ts +7 -3
- package/src/agents/skills.ts +2 -9
- package/src/api/preflight.ts +1 -1
- package/src/api/project-panes.ts +30 -0
- package/src/extension/config.ts +54 -1
- package/src/extension/doctor.ts +40 -0
- package/src/extension/fanout-child.ts +5 -4
- package/src/extension/index.ts +114 -38
- package/src/extension/public-execution.ts +35 -4
- package/src/extension/rpc.ts +10 -15
- package/src/extension/schemas.ts +33 -11
- package/src/extension/subagent-guide.ts +39 -0
- package/src/extension/tool-description.ts +38 -18
- package/src/inspectors/herdr/actions.ts +11 -2
- package/src/inspectors/herdr/inspector-runner.ts +16 -3
- package/src/inspectors/herdr/project-panes.ts +459 -63
- package/src/intercom/intercom-bridge.ts +7 -2
- package/src/intercom/native-supervisor-channel.ts +102 -4
- package/src/missions/actions.ts +25 -2
- package/src/missions/lifecycle.ts +25 -9
- package/src/missions/store.ts +89 -7
- package/src/missions/types.ts +33 -0
- package/src/missions/workflow-state.ts +25 -15
- package/src/runs/background/active-async-capacity.ts +431 -0
- package/src/runs/background/active-run-index.ts +46 -0
- package/src/runs/background/async-execution.ts +158 -71
- package/src/runs/background/async-job-tracker.ts +297 -133
- package/src/runs/background/async-resume.ts +37 -5
- package/src/runs/background/async-status.ts +39 -5
- package/src/runs/background/chain-append.ts +33 -15
- package/src/runs/background/completion-replay.ts +267 -0
- package/src/runs/background/control-channel.ts +95 -54
- package/src/runs/background/fleet-view.ts +18 -5
- package/src/runs/background/owned-process-tree.ts +104 -0
- package/src/runs/background/process-terminal.ts +17 -3
- package/src/runs/background/result-watcher.ts +113 -10
- package/src/runs/background/resume-guidance.ts +53 -0
- package/src/runs/background/retained-children.ts +14 -6
- package/src/runs/background/run-status.ts +119 -5
- package/src/runs/background/scheduled-runs.ts +25 -1
- package/src/runs/background/stale-run-reconciler.ts +12 -24
- package/src/runs/background/subagent-runner.ts +127 -41
- package/src/runs/background/subagent-wait.ts +5 -2
- package/src/runs/background/wait-completions.ts +39 -5
- package/src/runs/background/wait-subscriptions.ts +21 -5
- package/src/runs/foreground/async-dismiss-action.ts +85 -0
- package/src/runs/foreground/async-steering-action.ts +7 -8
- package/src/runs/foreground/chain-execution.ts +40 -2
- package/src/runs/foreground/execution.ts +97 -19
- package/src/runs/foreground/foreground-control.ts +12 -0
- package/src/runs/foreground/foreground-history.ts +137 -0
- package/src/runs/foreground/prompt-audit.ts +172 -0
- package/src/runs/foreground/subagent-executor.ts +1274 -243
- package/src/runs/foreground/workflow-foreground-steering.ts +187 -0
- package/src/runs/shared/acceptance.ts +13 -4
- package/src/runs/shared/completion-guard.ts +17 -1
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/llm-intent-arbiter.ts +302 -0
- package/src/runs/shared/model-fallback.ts +8 -4
- package/src/runs/shared/model-scope.ts +12 -2
- package/src/runs/shared/parallel-utils.ts +3 -0
- package/src/runs/shared/pi-args.ts +44 -1
- package/src/runs/shared/run-fanout-budget.ts +280 -0
- package/src/runs/shared/single-output.ts +4 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +94 -9
- package/src/runs/shared/task-intent.ts +19 -3
- package/src/runs/shared/worktree.ts +20 -7
- package/src/shared/agent-stream-options.ts +5 -0
- package/src/shared/artifacts.ts +17 -21
- package/src/shared/display-text.ts +150 -0
- package/src/shared/file-coalescer.ts +9 -0
- package/src/shared/fork-context.ts +13 -0
- package/src/shared/formatters.ts +4 -6
- package/src/shared/node-executable.ts +21 -0
- package/src/shared/prompt-resources.ts +51 -0
- package/src/shared/settings.ts +15 -2
- package/src/shared/types.ts +158 -4
- package/src/shared/utf8.ts +11 -0
- package/src/shared/utils.ts +46 -34
- package/src/slash/prompt-workflows.ts +2 -15
- package/src/slash/slash-commands.ts +22 -2
- package/src/tui/fleet-status.ts +29 -17
- package/src/tui/fleet-transcript.ts +1 -48
- package/src/tui/fleet.ts +362 -37
- package/src/tui/render.ts +235 -71
- package/src/watchdog/change-signature.ts +4 -3
- package/src/watchdog/permission-arbiter.ts +2 -1
- package/src/watchdog/review.ts +4 -3
- package/src/workflows/chat-progress.ts +8 -2
- package/src/workflows/scripted-workflow.ts +273 -20
|
@@ -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
|
|
13
|
-
*
|
|
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
|
-
|
|
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
|
|
622
|
-
*
|
|
623
|
-
*
|
|
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
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
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
|
-
|
|
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
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
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
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
2
|
import * as path from "node:path";
|
|
3
3
|
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
4
|
+
import { safeTerminalText } from "../../shared/display-text.ts";
|
|
4
5
|
import { formatDuration, formatModelThinking, formatTokens, shortenPath } from "../../shared/formatters.ts";
|
|
5
6
|
import { formatActivityLabel } from "../../shared/status-format.ts";
|
|
6
7
|
import {
|
|
@@ -196,7 +197,7 @@ function readSessionTranscriptTail(sessionFile: string, maxLines: number, truste
|
|
|
196
197
|
try {
|
|
197
198
|
const parsed = JSON.parse(line) as unknown;
|
|
198
199
|
const messageLine = sessionMessageLine(parsed);
|
|
199
|
-
if (messageLine) lines.push(messageLine);
|
|
200
|
+
if (messageLine) lines.push(...messageLine.split(/\r?\n/));
|
|
200
201
|
} catch {
|
|
201
202
|
malformed++;
|
|
202
203
|
}
|
|
@@ -410,6 +411,18 @@ function appendKnownArtifacts(lines: string[], input: { outputPaths: string[]; s
|
|
|
410
411
|
for (const artifact of artifacts) lines.push(` ${artifact}`);
|
|
411
412
|
}
|
|
412
413
|
|
|
414
|
+
/**
|
|
415
|
+
* Sanitizes each assembled line independently.
|
|
416
|
+
*
|
|
417
|
+
* Sanitizing the joined response would let a single binary fragment in child
|
|
418
|
+
* output collapse the whole transcript, including run state, artifact paths, and
|
|
419
|
+
* warnings, into the binary placeholder. Per-line sanitization keeps that damage
|
|
420
|
+
* to the offending line.
|
|
421
|
+
*/
|
|
422
|
+
function safeTranscriptLines(lines: string[]): string {
|
|
423
|
+
return lines.map((line) => safeTerminalText(line)).join("\n");
|
|
424
|
+
}
|
|
425
|
+
|
|
413
426
|
function appendTranscriptBody(lines: string[], sourceLabel: string, sourceLines: string[], truncated: boolean): void {
|
|
414
427
|
lines.push(`${sourceLabel}${truncated ? " (tail truncated)" : ""}:`);
|
|
415
428
|
if (sourceLines.length === 0) {
|
|
@@ -470,7 +483,7 @@ export function formatAsyncRunTranscript(status: AsyncStatus, asyncDir: string,
|
|
|
470
483
|
for (const warning of warnings) lines.push(` ${warning}`);
|
|
471
484
|
}
|
|
472
485
|
appendTranscriptBody(lines, transcriptSource, transcriptLines, truncated);
|
|
473
|
-
return lines
|
|
486
|
+
return safeTranscriptLines(lines);
|
|
474
487
|
}
|
|
475
488
|
|
|
476
489
|
export function formatNestedRunTranscript(run: NestedRunSummary, options: TranscriptOptions = {}): string {
|
|
@@ -488,7 +501,7 @@ export function formatNestedRunTranscript(run: NestedRunSummary, options: Transc
|
|
|
488
501
|
appendKnownArtifacts(lines, { outputPaths: [], sessionFile: run.sessionFile });
|
|
489
502
|
if (!run.sessionFile) {
|
|
490
503
|
appendTranscriptBody(lines, "Transcript tail", [], false);
|
|
491
|
-
return lines
|
|
504
|
+
return safeTranscriptLines(lines);
|
|
492
505
|
}
|
|
493
506
|
const sessionTail = readSessionTranscriptTail(run.sessionFile, lineLimit, options.sessionRoots ?? []);
|
|
494
507
|
if (sessionTail.warnings.length) {
|
|
@@ -496,7 +509,7 @@ export function formatNestedRunTranscript(run: NestedRunSummary, options: Transc
|
|
|
496
509
|
for (const warning of sessionTail.warnings) lines.push(` ${warning}`);
|
|
497
510
|
}
|
|
498
511
|
appendTranscriptBody(lines, `Session transcript tail from ${run.sessionFile}`, sessionTail.lines, false);
|
|
499
|
-
return lines
|
|
512
|
+
return safeTranscriptLines(lines);
|
|
500
513
|
}
|
|
501
514
|
|
|
502
515
|
export function formatAsyncResultTranscript(data: {
|
|
@@ -536,5 +549,5 @@ export function formatAsyncResultTranscript(data: {
|
|
|
536
549
|
].filter((line): line is string => Boolean(line));
|
|
537
550
|
appendKnownArtifacts(lines, { outputPaths: [], sessionFile, resultPath });
|
|
538
551
|
appendTranscriptBody(lines, "Result transcript tail", transcriptLines.filter((line) => line.trim()), output.split(/\r?\n/).length > lineLimit);
|
|
539
|
-
return lines
|
|
552
|
+
return safeTranscriptLines(lines);
|
|
540
553
|
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import type { ProcessTreeTerminalV1 } from "../../shared/types.ts";
|
|
3
|
+
|
|
4
|
+
const DEFAULT_TERM_GRACE_MS = 3000;
|
|
5
|
+
const DEFAULT_KILL_VERIFY_MS = 1000;
|
|
6
|
+
const VERIFY_INTERVAL_MS = 25;
|
|
7
|
+
|
|
8
|
+
type SignalResult = "sent" | "absent" | { diagnostic: string };
|
|
9
|
+
|
|
10
|
+
function diagnostic(error: unknown): string {
|
|
11
|
+
return error instanceof Error ? error.message : String(error);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function signalProcess(id: number, signal: NodeJS.Signals): SignalResult {
|
|
15
|
+
try {
|
|
16
|
+
process.kill(id, signal);
|
|
17
|
+
return "sent";
|
|
18
|
+
} catch (error) {
|
|
19
|
+
if ((error as NodeJS.ErrnoException).code === "ESRCH") return "absent";
|
|
20
|
+
return { diagnostic: diagnostic(error) };
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function activeProcessGroupMembers(processGroupId: number): number[] | { diagnostic: string } {
|
|
25
|
+
const result = spawnSync("ps", ["-axo", "pid=,pgid=,stat="], { encoding: "utf-8" });
|
|
26
|
+
if (result.error || result.status !== 0) {
|
|
27
|
+
return { diagnostic: result.error ? diagnostic(result.error) : (result.stderr.trim() || `ps exited with ${result.status}`) };
|
|
28
|
+
}
|
|
29
|
+
const members: number[] = [];
|
|
30
|
+
for (const line of result.stdout.split("\n")) {
|
|
31
|
+
const match = /^\s*(\d+)\s+(\d+)\s+(\S+)/.exec(line);
|
|
32
|
+
if (!match || Number(match[2]) !== processGroupId || match[3]!.startsWith("Z")) continue;
|
|
33
|
+
members.push(Number(match[1]));
|
|
34
|
+
}
|
|
35
|
+
return members;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function waitUntilGroupTerminal(
|
|
39
|
+
processGroupId: number,
|
|
40
|
+
timeoutMs: number,
|
|
41
|
+
): Promise<false | { state: "enumeration-failed" | "still-active"; diagnostic: string }> {
|
|
42
|
+
const deadline = Date.now() + timeoutMs;
|
|
43
|
+
while (true) {
|
|
44
|
+
const members = activeProcessGroupMembers(processGroupId);
|
|
45
|
+
if (Array.isArray(members) && members.length === 0) return false;
|
|
46
|
+
const remaining = deadline - Date.now();
|
|
47
|
+
if (remaining <= 0) {
|
|
48
|
+
if (!Array.isArray(members)) return { state: "enumeration-failed", diagnostic: members.diagnostic };
|
|
49
|
+
return { state: "still-active", diagnostic: `Process group ${processGroupId} still has active members: ${members.join(", ")}.` };
|
|
50
|
+
}
|
|
51
|
+
await new Promise<void>((resolve) => setTimeout(resolve, Math.min(VERIFY_INTERVAL_MS, remaining)));
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function observed(processGroupId: number): ProcessTreeTerminalV1 {
|
|
56
|
+
return { state: "observed", mechanism: "posix-process-group", processGroupId, verifiedAt: Date.now() };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Owns one writer process group and arbitrates its cleanup exactly once. */
|
|
60
|
+
export interface OwnedProcessTreeController {
|
|
61
|
+
terminate(): Promise<ProcessTreeTerminalV1>;
|
|
62
|
+
finishAfterWriterClose(): Promise<ProcessTreeTerminalV1>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function createOwnedProcessTreeController(
|
|
66
|
+
pid: number,
|
|
67
|
+
options: { termGraceMs?: number; killVerifyMs?: number } = {},
|
|
68
|
+
): OwnedProcessTreeController {
|
|
69
|
+
let termination: Promise<ProcessTreeTerminalV1> | undefined;
|
|
70
|
+
const posixGroupOwned = process.platform !== "win32";
|
|
71
|
+
const target = posixGroupOwned ? -pid : pid;
|
|
72
|
+
|
|
73
|
+
const terminate = (): Promise<ProcessTreeTerminalV1> => {
|
|
74
|
+
if (termination) return termination;
|
|
75
|
+
termination = (async () => {
|
|
76
|
+
if (!posixGroupOwned) {
|
|
77
|
+
signalProcess(target, "SIGTERM");
|
|
78
|
+
return { state: "unknown", reason: "unsupported-platform" };
|
|
79
|
+
}
|
|
80
|
+
const term = signalProcess(target, "SIGTERM");
|
|
81
|
+
if (term !== "sent" && term !== "absent") {
|
|
82
|
+
return { state: "unknown", reason: "signal-failed", diagnostic: term.diagnostic };
|
|
83
|
+
}
|
|
84
|
+
const termExit = await waitUntilGroupTerminal(pid, options.termGraceMs ?? DEFAULT_TERM_GRACE_MS);
|
|
85
|
+
if (termExit === false) return observed(pid);
|
|
86
|
+
|
|
87
|
+
const kill = signalProcess(target, "SIGKILL");
|
|
88
|
+
if (kill !== "sent" && kill !== "absent") {
|
|
89
|
+
const members = activeProcessGroupMembers(pid);
|
|
90
|
+
if (!Array.isArray(members) || members.length > 0) {
|
|
91
|
+
return { state: "unknown", reason: "signal-failed", diagnostic: kill.diagnostic };
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const killExit = await waitUntilGroupTerminal(pid, options.killVerifyMs ?? DEFAULT_KILL_VERIFY_MS);
|
|
95
|
+
if (killExit !== false) {
|
|
96
|
+
return { state: "unknown", reason: "verification-failed", diagnostic: killExit.diagnostic };
|
|
97
|
+
}
|
|
98
|
+
return observed(pid);
|
|
99
|
+
})();
|
|
100
|
+
return termination;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
return { terminate, finishAfterWriterClose: terminate };
|
|
104
|
+
}
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
type ProcessTerminalV1,
|
|
11
11
|
} from "../../shared/types.ts";
|
|
12
12
|
import { canonicalSessionId, inspectSessionLease } from "../shared/session-lease.ts";
|
|
13
|
+
import { releaseActiveRunIndex } from "./active-run-index.ts";
|
|
13
14
|
|
|
14
15
|
export interface ProcessTerminalCandidate {
|
|
15
16
|
version: 1;
|
|
@@ -40,9 +41,19 @@ function validProcessInstance(value: unknown, kind?: "runner" | "pi-writer"): va
|
|
|
40
41
|
if (typeof value.closeObservedAt !== "number" || !Number.isFinite(value.closeObservedAt)) return false;
|
|
41
42
|
if (typeof value.exitCode !== "number" && value.exitCode !== null) return false;
|
|
42
43
|
if (typeof value.signal !== "string" && value.signal !== null) return false;
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
44
|
+
if (value.kind === "runner") return value.attempt === undefined;
|
|
45
|
+
if (typeof value.attempt !== "number" || !Number.isInteger(value.attempt) || value.attempt < 0 || !isRecord(value.processTree)) return false;
|
|
46
|
+
if (value.processTree.state === "observed") {
|
|
47
|
+
return value.processTree.mechanism === "posix-process-group"
|
|
48
|
+
&& typeof value.processTree.processGroupId === "number"
|
|
49
|
+
&& Number.isInteger(value.processTree.processGroupId)
|
|
50
|
+
&& value.processTree.processGroupId > 0
|
|
51
|
+
&& typeof value.processTree.verifiedAt === "number"
|
|
52
|
+
&& Number.isFinite(value.processTree.verifiedAt);
|
|
53
|
+
}
|
|
54
|
+
return value.processTree.state === "unknown"
|
|
55
|
+
&& ["unsupported-platform", "signal-failed", "verification-failed"].includes(String(value.processTree.reason))
|
|
56
|
+
&& (value.processTree.diagnostic === undefined || typeof value.processTree.diagnostic === "string");
|
|
46
57
|
}
|
|
47
58
|
|
|
48
59
|
function validInstance(value: unknown): value is ProcessInstanceExitV1 {
|
|
@@ -249,6 +260,8 @@ export function finalizeProcessTerminal(
|
|
|
249
260
|
proof = unknownProof(runId, runnerClose.processInstanceId, "canonical-session-release-unverified");
|
|
250
261
|
} else if (inconsistentWriters || (allWriters.length === 0 && expectedEntries.length === 0)) {
|
|
251
262
|
proof = unknownProof(runId, runnerClose.processInstanceId, "writer-close-unverified");
|
|
263
|
+
} else if (allWriters.some((writer) => writer.kind === "pi-writer" && writer.processTree.state !== "observed")) {
|
|
264
|
+
proof = unknownProof(runId, runnerClose.processInstanceId, "process-tree-unverified");
|
|
252
265
|
} else {
|
|
253
266
|
const runner: ProcessInstanceExitV1 = { kind: "runner", ...runnerClose };
|
|
254
267
|
const canonicalSession = session && sessionProjection(candidate, session);
|
|
@@ -271,6 +284,7 @@ export function finalizeProcessTerminal(
|
|
|
271
284
|
try {
|
|
272
285
|
writeAtomicJson(processTerminalPath(asyncDir), proof);
|
|
273
286
|
durable = true;
|
|
287
|
+
if (proof.state === "observed") releaseActiveRunIndex(asyncDir);
|
|
274
288
|
overlayStatus(asyncDir, proof, candidateForOverlay);
|
|
275
289
|
fs.appendFileSync(path.join(asyncDir, "events.jsonl"), `${JSON.stringify({ type: "subagent.run.process_terminal", lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION, ts: Date.now(), runId, processTerminal: proof })}\n`, "utf-8");
|
|
276
290
|
} catch {
|
|
@@ -21,13 +21,15 @@ import {
|
|
|
21
21
|
import { projectNestedRegistryForRoot, sanitizeSummary } from "../shared/nested-events.ts";
|
|
22
22
|
import { resolveWatchPath } from "../../shared/utils.ts";
|
|
23
23
|
import { recordWaitCompletion } from "./wait-completions.ts";
|
|
24
|
+
import { MISSION_BINDING_FILE, syncMissionFromAsyncCompletion } from "../../missions/lifecycle.ts";
|
|
24
25
|
import type { CompletionNotifier, CompletionNotification } from "./notify.ts";
|
|
25
26
|
|
|
26
27
|
const WATCHER_RESTART_DELAY_MS = 3000;
|
|
27
28
|
const POLL_INTERVAL_MS = 3000;
|
|
29
|
+
const HEALTHY_SCAN_INTERVAL_MS = 60_000;
|
|
28
30
|
const RETRY_DELAY_MS = 100;
|
|
29
31
|
|
|
30
|
-
type ResultWatcherFs = Pick<typeof fs, "existsSync" | "readFileSync" | "unlinkSync" | "readdirSync" | "mkdirSync" | "realpathSync" | "watch">;
|
|
32
|
+
type ResultWatcherFs = Pick<typeof fs, "existsSync" | "readFileSync" | "unlinkSync" | "readdirSync" | "mkdirSync" | "realpathSync" | "statSync" | "watch">;
|
|
31
33
|
|
|
32
34
|
type ResultWatcherTimers = {
|
|
33
35
|
setTimeout: typeof setTimeout;
|
|
@@ -42,6 +44,10 @@ type ResultWatcherDeps = {
|
|
|
42
44
|
notifier?: Pick<CompletionNotifier, "deliver">;
|
|
43
45
|
/** Receives persisted completions before active-session delivery filtering. */
|
|
44
46
|
observeCompletion?: (result: CompletionNotification & { runId: string }) => void;
|
|
47
|
+
/** Returns cross-session run ids that the completion observer currently owns. */
|
|
48
|
+
observedCompletionRunIds?: () => Iterable<string>;
|
|
49
|
+
/** Parses a relevant result payload after its lightweight identity check. */
|
|
50
|
+
parseResult?: (raw: string) => ResultFileData;
|
|
45
51
|
/** External grouped-result transport. Disable when native completion notifications own delivery. */
|
|
46
52
|
deliverIntercomResults?: boolean;
|
|
47
53
|
};
|
|
@@ -75,6 +81,33 @@ type ResultFileData = CompletionNotification & {
|
|
|
75
81
|
parallelHandoff?: ParallelHandoffReference;
|
|
76
82
|
};
|
|
77
83
|
|
|
84
|
+
type ResultFileIdentity = {
|
|
85
|
+
sessionId?: string;
|
|
86
|
+
runId?: string;
|
|
87
|
+
asyncDir?: string;
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
function jsonStringProperty(raw: string, property: string): string | undefined {
|
|
91
|
+
const matches = raw.matchAll(new RegExp(`"${property}"\\s*:\\s*("(?:\\\\.|[^"\\\\])*")`, "g"));
|
|
92
|
+
let encoded: string | undefined;
|
|
93
|
+
for (const match of matches) encoded = match[1];
|
|
94
|
+
if (!encoded) return undefined;
|
|
95
|
+
try {
|
|
96
|
+
const value = JSON.parse(encoded) as unknown;
|
|
97
|
+
return typeof value === "string" && value ? value : undefined;
|
|
98
|
+
} catch {
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function resultFileIdentity(raw: string, file: string): ResultFileIdentity {
|
|
104
|
+
return {
|
|
105
|
+
sessionId: jsonStringProperty(raw, "sessionId"),
|
|
106
|
+
runId: file.replace(/\.json$/i, ""),
|
|
107
|
+
asyncDir: jsonStringProperty(raw, "asyncDir"),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
78
111
|
function sanitizeNestedResultChildren(value: unknown, resultPath: string, label: string): NestedRunSummary[] | undefined {
|
|
79
112
|
if (value === undefined) return undefined;
|
|
80
113
|
if (!Array.isArray(value)) {
|
|
@@ -120,11 +153,14 @@ export function createResultWatcher(
|
|
|
120
153
|
const fsApi = deps.fs ?? fs;
|
|
121
154
|
const timers = deps.timers ?? { setTimeout, clearTimeout, setInterval, clearInterval };
|
|
122
155
|
const notifier = deps.notifier ?? { deliver: async () => true };
|
|
156
|
+
const parseResult = deps.parseResult ?? ((raw: string) => JSON.parse(raw) as ResultFileData);
|
|
123
157
|
const deliverIntercomResults = deps.deliverIntercomResults !== false;
|
|
124
158
|
const pendingTriggerTurn = new Map<string, boolean>();
|
|
125
159
|
const processing = new Set<string>();
|
|
160
|
+
const identityCache = new Map<string, { signature: string; identity: ResultFileIdentity }>();
|
|
126
161
|
let deliveryActive = true;
|
|
127
162
|
let deliveryEpoch = 0;
|
|
163
|
+
let resultScanTimer: ReturnType<typeof setInterval> | null = null;
|
|
128
164
|
// The sole in-memory ownership lease. It is acquired for one active session
|
|
129
165
|
// and revoked before the watcher, queues, or callbacks are torn down.
|
|
130
166
|
let activeSessionId: string | null = null;
|
|
@@ -141,14 +177,58 @@ export function createResultWatcher(
|
|
|
141
177
|
state.resultFileCoalescer.schedule(file, delayMs);
|
|
142
178
|
};
|
|
143
179
|
|
|
180
|
+
const inspectResult = (file: string): ResultFileIdentity | undefined => {
|
|
181
|
+
const resultPath = path.join(resultsDir, file);
|
|
182
|
+
try {
|
|
183
|
+
const stat = fsApi.statSync(resultPath);
|
|
184
|
+
const signature = `${stat.size}:${stat.mtimeMs}`;
|
|
185
|
+
const cached = identityCache.get(file);
|
|
186
|
+
if (cached?.signature === signature) return cached.identity;
|
|
187
|
+
const identity = resultFileIdentity(fsApi.readFileSync(resultPath, "utf-8"), file);
|
|
188
|
+
identityCache.set(file, { signature, identity });
|
|
189
|
+
return identity;
|
|
190
|
+
} catch (error) {
|
|
191
|
+
identityCache.delete(file);
|
|
192
|
+
if (!isNotFound(error)) console.error(`Failed to inspect subagent result file '${resultPath}':`, error);
|
|
193
|
+
return undefined;
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
const observedRunIds = (): ReadonlySet<string> => {
|
|
198
|
+
try {
|
|
199
|
+
return new Set(deps.observedCompletionRunIds?.() ?? []);
|
|
200
|
+
} catch (error) {
|
|
201
|
+
console.error("Failed to inspect observed subagent completion ids:", error);
|
|
202
|
+
return new Set();
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
const shouldProcessResult = (file: string, observed?: ReadonlySet<string>): boolean => {
|
|
207
|
+
const identity = inspectResult(file);
|
|
208
|
+
if (!identity) return false;
|
|
209
|
+
// Missing identity stays on the normal parser path so malformed or legacy
|
|
210
|
+
// files keep their existing diagnostics and compatibility behavior.
|
|
211
|
+
if (!identity.sessionId) return true;
|
|
212
|
+
if (identity.sessionId === state.currentSessionId) return true;
|
|
213
|
+
if (identity.asyncDir && fsApi.existsSync(path.join(identity.asyncDir, MISSION_BINDING_FILE))) return true;
|
|
214
|
+
if (identity.runId && (observed ?? observedRunIds()).has(identity.runId)) return true;
|
|
215
|
+
return Boolean(deps.observeCompletion && !deps.observedCompletionRunIds);
|
|
216
|
+
};
|
|
217
|
+
|
|
144
218
|
const handleResult = async (file: string, triggerTurn: boolean) => {
|
|
145
219
|
const resultPath = path.join(resultsDir, file);
|
|
146
220
|
if (processing.has(file) || !fsApi.existsSync(resultPath)) return;
|
|
221
|
+
if (!shouldProcessResult(file)) return;
|
|
147
222
|
processing.add(file);
|
|
148
223
|
try {
|
|
149
|
-
const data =
|
|
224
|
+
const data = parseResult(fsApi.readFileSync(resultPath, "utf-8"));
|
|
150
225
|
if (typeof data.sessionId !== "string" || !data.sessionId) return;
|
|
151
226
|
const runId = data.runId ?? data.id ?? file.replace(/\.json$/i, "");
|
|
227
|
+
try {
|
|
228
|
+
syncMissionFromAsyncCompletion({ ...data, runId });
|
|
229
|
+
} catch (error) {
|
|
230
|
+
console.error(`Mission completion sync failed for '${resultPath}':`, error);
|
|
231
|
+
}
|
|
152
232
|
try {
|
|
153
233
|
deps.observeCompletion?.({ ...data, runId });
|
|
154
234
|
} catch (error) {
|
|
@@ -156,10 +236,12 @@ export function createResultWatcher(
|
|
|
156
236
|
}
|
|
157
237
|
const epoch = deliveryEpoch;
|
|
158
238
|
if (!ownsSession(data.sessionId, epoch)) return;
|
|
159
|
-
// Recorded before dedupe and before the unlink below
|
|
160
|
-
// the
|
|
161
|
-
|
|
162
|
-
|
|
239
|
+
// Recorded before dedupe and before the unlink below so subagent_wait can
|
|
240
|
+
// use the in-memory record or its bounded durable replay after cleanup.
|
|
241
|
+
recordWaitCompletion(state, runId, data, Date.now(), completionTtlMs, {
|
|
242
|
+
resultsDir,
|
|
243
|
+
sessionId: data.sessionId,
|
|
244
|
+
});
|
|
163
245
|
const hasExplicitNestedChildren = data.nestedChildren !== undefined;
|
|
164
246
|
let nestedChildren = compactNestedResultChildren(sanitizeNestedResultChildren(data.nestedChildren, resultPath, "nestedChildren"));
|
|
165
247
|
if (!nestedChildren?.length && !hasExplicitNestedChildren) {
|
|
@@ -180,6 +262,7 @@ export function createResultWatcher(
|
|
|
180
262
|
if (!ownsSession(data.sessionId, epoch) || !fsApi.existsSync(resultPath)) return;
|
|
181
263
|
try {
|
|
182
264
|
fsApi.unlinkSync(resultPath);
|
|
265
|
+
identityCache.delete(file);
|
|
183
266
|
} catch (error) {
|
|
184
267
|
if (!isNotFound(error)) {
|
|
185
268
|
console.error(`Failed to remove delivered subagent result '${resultPath}'; will retry:`, error);
|
|
@@ -305,6 +388,7 @@ export function createResultWatcher(
|
|
|
305
388
|
if (!ownsSession(data.sessionId, epoch) || !fsApi.existsSync(resultPath)) return;
|
|
306
389
|
try {
|
|
307
390
|
fsApi.unlinkSync(resultPath);
|
|
391
|
+
identityCache.delete(file);
|
|
308
392
|
} catch (error) {
|
|
309
393
|
if (!isNotFound(error)) {
|
|
310
394
|
console.error(`Failed to remove delivered subagent result '${resultPath}'; will retry:`, error);
|
|
@@ -329,15 +413,23 @@ export function createResultWatcher(
|
|
|
329
413
|
const triggerTurn = options.triggerTurn !== false;
|
|
330
414
|
fsApi.readdirSync(resultsDir)
|
|
331
415
|
.filter((f) => f.endsWith(".json"))
|
|
332
|
-
.forEach((file) =>
|
|
416
|
+
.forEach((file) => {
|
|
417
|
+
if (shouldProcessResult(file)) scheduleResult(file, triggerTurn);
|
|
418
|
+
});
|
|
333
419
|
} catch (error) {
|
|
334
420
|
if (!isNotFound(error)) console.error(`Failed to scan subagent result directory '${resultsDir}':`, error);
|
|
335
421
|
}
|
|
336
422
|
};
|
|
337
423
|
|
|
424
|
+
const clearResultScan = () => {
|
|
425
|
+
if (resultScanTimer) timers.clearInterval(resultScanTimer);
|
|
426
|
+
resultScanTimer = null;
|
|
427
|
+
};
|
|
428
|
+
|
|
338
429
|
const startPolling = (reason: unknown) => {
|
|
339
430
|
state.watcher?.close();
|
|
340
431
|
state.watcher = null;
|
|
432
|
+
clearResultScan();
|
|
341
433
|
if (state.watcherRestartTimer) return;
|
|
342
434
|
console.error(`Subagent result watcher for '${resultsDir}' fell back to polling because native fs.watch is unavailable (${errorCode(reason) ?? "unknown error"}).`);
|
|
343
435
|
primeExistingResults();
|
|
@@ -346,6 +438,7 @@ export function createResultWatcher(
|
|
|
346
438
|
};
|
|
347
439
|
|
|
348
440
|
const scheduleRestart = () => {
|
|
441
|
+
clearResultScan();
|
|
349
442
|
if (state.watcherRestartTimer) return;
|
|
350
443
|
state.watcherRestartTimer = timers.setTimeout(() => {
|
|
351
444
|
state.watcherRestartTimer = null;
|
|
@@ -373,10 +466,16 @@ export function createResultWatcher(
|
|
|
373
466
|
}
|
|
374
467
|
try {
|
|
375
468
|
const watchDir = resolveWatchPath(resultsDir, fsApi.realpathSync.native);
|
|
376
|
-
state.watcher = fsApi.watch(watchDir, (
|
|
377
|
-
if (
|
|
469
|
+
state.watcher = fsApi.watch(watchDir, (_event, file) => {
|
|
470
|
+
if (!file) {
|
|
471
|
+
primeExistingResults();
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
378
474
|
const fileName = file.toString();
|
|
379
|
-
if (fileName.endsWith(".json"))
|
|
475
|
+
if (fileName.endsWith(".json")) {
|
|
476
|
+
identityCache.delete(fileName);
|
|
477
|
+
scheduleResult(fileName, true);
|
|
478
|
+
}
|
|
380
479
|
});
|
|
381
480
|
state.watcher.on("error", (error) => {
|
|
382
481
|
if (shouldPoll(error)) return startPolling(error);
|
|
@@ -386,6 +485,8 @@ export function createResultWatcher(
|
|
|
386
485
|
scheduleRestart();
|
|
387
486
|
});
|
|
388
487
|
state.watcher.unref?.();
|
|
488
|
+
resultScanTimer = timers.setInterval(primeExistingResults, HEALTHY_SCAN_INTERVAL_MS);
|
|
489
|
+
resultScanTimer.unref?.();
|
|
389
490
|
} catch (error) {
|
|
390
491
|
if (shouldPoll(error)) return startPolling(error);
|
|
391
492
|
console.error(`Failed to start subagent result watcher for '${resultsDir}':`, error);
|
|
@@ -405,9 +506,11 @@ export function createResultWatcher(
|
|
|
405
506
|
timers.clearInterval(state.watcherRestartTimer);
|
|
406
507
|
}
|
|
407
508
|
state.watcherRestartTimer = null;
|
|
509
|
+
clearResultScan();
|
|
408
510
|
state.resultFileCoalescer.clear();
|
|
409
511
|
pendingTriggerTurn.clear();
|
|
410
512
|
processing.clear();
|
|
513
|
+
identityCache.clear();
|
|
411
514
|
};
|
|
412
515
|
|
|
413
516
|
return { startResultWatcher, primeExistingResults, stopResultWatcher };
|