@ferris1225/pi-subagents 6.0.0 → 6.0.1

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.
@@ -2,8 +2,8 @@
2
2
 
3
3
  import { spawn } from "node:child_process";
4
4
  import { existsSync, readdirSync } from "node:fs";
5
- import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
6
- import { basename, join } from "node:path";
5
+ import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises";
6
+ import { basename, join, resolve } from "node:path";
7
7
  import { StringDecoder } from "node:string_decoder";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import type { Message, Usage } from "@earendil-works/pi-ai";
@@ -12,7 +12,7 @@ import { SUBAGENT_TOOL_NAMES, type AgentConfig } from "../delegation/agents.ts";
12
12
  import type { ThinkingLevel } from "../configuration/config.ts";
13
13
  import { writeTempOwnerMarker } from "../isolation/temp-hygiene.ts";
14
14
  import { terminateProcessTree } from "./process-tree.ts";
15
- import { asPlainTextPrompt, emptyUsage, type RunControl, type AttemptControl, type RunResult, type SubagentLiveEvent } from "./run-control.ts";
15
+ import { asPlainTextPrompt, emptyUsage, type RunControl, type AttemptControl, type RunResult, type SteeringReceipt, type SubagentLiveEvent } from "./run-control.ts";
16
16
 
17
17
  const DEPTH_ENV_VAR = "PI_SUBAGENT_DEPTH";
18
18
  /** Every tool of an MCP server shares this prefix, whatever its exposure. */
@@ -44,15 +44,36 @@ export function currentSubagentDepth(env: NodeJS.ProcessEnv = process.env): numb
44
44
  return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
45
45
  }
46
46
 
47
- /** Match pi's `<timestamp>Z_<id>.jsonl` session-file convention. */
48
- export function sessionExists(sessionDir: string, sessionId: string): boolean {
47
+ /** Match Pi's `<timestamp>Z_<id>.jsonl` session-file convention. */
48
+ export function findSessionFile(sessionDir: string, sessionId: string): string | undefined {
49
49
  try {
50
- return readdirSync(sessionDir).some((file) => file.endsWith(`_${sessionId}.jsonl`));
50
+ const file = readdirSync(sessionDir, { withFileTypes: true })
51
+ .find((entry) => entry.isFile() && entry.name.endsWith(`_${sessionId}.jsonl`));
52
+ return file ? join(sessionDir, file.name) : undefined;
51
53
  } catch {
52
- return false;
54
+ return undefined;
53
55
  }
54
56
  }
55
57
 
58
+ export function sessionExists(sessionDir: string, sessionId: string): boolean {
59
+ return findSessionFile(sessionDir, sessionId) !== undefined;
60
+ }
61
+
62
+ /** Pi restores cwd from the session header, even when its process starts in a
63
+ * new worktree. Update only this run's private copy, keeping its id and every
64
+ * transcript entry intact; the source run's history remains unchanged. */
65
+ async function prepareSessionCwd(file: string, sessionId: string, cwd: string): Promise<void> {
66
+ const transcript = await readFile(file, "utf8");
67
+ const newline = transcript.indexOf("\n");
68
+ const header = JSON.parse(newline < 0 ? transcript : transcript.slice(0, newline));
69
+ if (header?.type !== "session" || header.id !== sessionId) {
70
+ throw new Error(`Invalid retained session header: ${file}`);
71
+ }
72
+ const currentCwd = resolve(cwd);
73
+ if (header.cwd === currentCwd) return;
74
+ await writeFile(file, JSON.stringify({ ...header, cwd: currentCwd }) + (newline < 0 ? "\n" : transcript.slice(newline)), "utf8");
75
+ }
76
+
56
77
  /** Resolve how to invoke the same pi build as the current process. */
57
78
  function getPiInvocation(args: string[]): { command: string; args: string[] } {
58
79
  const currentScript = process.argv[1];
@@ -121,14 +142,15 @@ export interface ChildLaunchOptions {
121
142
  resumeExistingSession?: boolean;
122
143
  /** Appended system prompt file, when the role carries one. */
123
144
  promptPath?: string;
145
+ /** Activate scout's approved indirect tools after they register. */
146
+ toolActivationPath?: string;
124
147
  }
125
148
 
126
149
  /** Command line for one child attempt.
127
150
  *
128
- * An explicit role list is a strict intersection of the parent's tools, but pi
129
- * keeps MCP tools unless a `--tools` entry names one, so a list that names none
130
- * has to exclude them by pattern. Scout depends on that: its read-only boundary
131
- * must not leak an MCP writer. */
151
+ * The allowlist includes active tools and allowed callable indirect tools. Pi
152
+ * keeps their exposure, so naming a codemode/deferred tool does not declare it.
153
+ * Exclude all MCP names when the parent supplied none to keep the boundary. */
132
154
  export function buildChildLaunchArgs(options: ChildLaunchOptions): string[] {
133
155
  const { agent, thinkingLevel } = options;
134
156
  const excludedTools: string[] = [...SUBAGENT_TOOL_NAMES];
@@ -152,6 +174,7 @@ export function buildChildLaunchArgs(options: ChildLaunchOptions): string[] {
152
174
  args.push("--exclude-tools", excludedTools.join(","));
153
175
  // Compiled Pi runtimes may ignore NODE_OPTIONS; install before tools run too.
154
176
  if (process.platform === "win32") args.push("--extension", HIDDEN_CONSOLE_PATH);
177
+ if (options.toolActivationPath) args.push("--extension", options.toolActivationPath);
155
178
  if (options.promptPath) args.push("--append-system-prompt", options.promptPath);
156
179
  return args;
157
180
  }
@@ -188,17 +211,50 @@ export async function runCliAgentAttempt(options: RunCliAttemptOptions): Promise
188
211
  if (signal?.aborted || control?.isStopRequested()) {
189
212
  return { ...result, exitCode: 1, stopReason: "aborted", errorMessage: control?.getStopMessage() ?? "Subagent was aborted" };
190
213
  }
191
- if (agent.systemPrompt.trim()) promptFile = await writePromptToTempFile(options.scratchRoot, agent.name, agent.systemPrompt);
214
+ const activateScoutTools = agent.name === "scout" && !!agent.tools?.length;
215
+ if (agent.systemPrompt.trim() || activateScoutTools) promptFile = await writePromptToTempFile(options.scratchRoot, agent.name, agent.systemPrompt);
216
+ let toolActivationPath: string | undefined;
217
+ if (activateScoutTools && promptFile) {
218
+ toolActivationPath = join(promptFile.dir, "activate-scout-tools.mjs");
219
+ await writeFile(toolActivationPath, `
220
+ export default function (pi) {
221
+ const approved = new Set(${JSON.stringify(agent.tools)});
222
+ const activate = () => {
223
+ const active = pi.getActiveTools();
224
+ const registered = pi.getAllTools();
225
+ const late = registered.filter(tool => approved.has(tool.name) &&
226
+ (tool.exposure === "codemode" || tool.exposure === "deferred") && !active.includes(tool.name));
227
+ if (late.length) pi.setActiveTools([...active, ...late.map(tool => tool.name)]);
228
+ return [...approved].every(name => registered.some(tool => tool.name === name));
229
+ };
230
+ pi.on("before_agent_start", async () => {
231
+ // Match Pi's bounded first-prompt wait for direct MCP tools. These tools
232
+ // retain indirect exposure, so Pi itself would not wait for them.
233
+ const deadline = Date.now() + 10_000;
234
+ while (!activate() && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 25));
235
+ });
236
+ // Run before Pi snapshots the next turn's tools. Registration may finish
237
+ // while the previous model request or its tool calls are in flight.
238
+ pi.on("turn_end", () => { activate(); });
239
+ }
240
+ `, "utf8");
241
+ }
242
+ // Pi matches session headers against process.cwd(). Both must use the same
243
+ // physical directory, including macOS /var aliases and Windows junctions.
244
+ const executionCwd = await realpath(options.cwd ?? options.defaultCwd);
245
+ const sessionFile = options.sessionDir && options.sessionId
246
+ ? findSessionFile(options.sessionDir, options.sessionId) : undefined;
247
+ if (sessionFile) await prepareSessionCwd(sessionFile, options.sessionId!, executionCwd);
192
248
  const args = buildChildLaunchArgs({
193
249
  agent, thinkingLevel: options.thinkingLevel,
194
250
  sessionDir: options.sessionDir, sessionId: options.sessionId,
195
- resumeExistingSession: Boolean(options.sessionDir && options.sessionId && sessionExists(options.sessionDir, options.sessionId)),
196
- promptPath: promptFile?.filePath,
251
+ resumeExistingSession: sessionFile !== undefined,
252
+ promptPath: promptFile?.filePath, toolActivationPath,
197
253
  });
198
254
  const invocation = getPiInvocation(args);
199
255
  const processGroup = process.platform !== "win32";
200
256
  const proc = spawn(invocation.command, invocation.args, {
201
- cwd: options.cwd ?? options.defaultCwd, shell: false, stdio: ["pipe", "pipe", "pipe"],
257
+ cwd: executionCwd, shell: false, stdio: ["pipe", "pipe", "pipe"],
202
258
  windowsHide: true,
203
259
  env: childEnvironment(options.env),
204
260
  detached: processGroup,
@@ -213,7 +269,7 @@ export async function runCliAgentAttempt(options: RunCliAttemptOptions): Promise
213
269
  let idleTimer: ReturnType<typeof setInterval> | undefined;
214
270
  let startupTimer: ReturnType<typeof setTimeout> | undefined;
215
271
  let nextRequestId = 0;
216
- const pendingSteers = new Map<string, { resolve: () => void; reject: (error: Error) => void }>();
272
+ const pendingSteers = new Map<string, { resolve: (receipt: SteeringReceipt) => void; reject: (error: Error) => void }>();
217
273
  let resolveClosed!: () => void;
218
274
  const processClosed = new Promise<void>((resolve) => { resolveClosed = resolve; });
219
275
  const emit = (event: SubagentLiveEvent): void => {
@@ -228,14 +284,14 @@ export async function runCliAgentAttempt(options: RunCliAttemptOptions): Promise
228
284
  };
229
285
  const attempt: AttemptControl = {
230
286
  steer(message) {
231
- if (closed || settled || stopping || proc.stdin.destroyed) return Promise.reject(new Error("Subagent has stopped accepting messages."));
287
+ if (closed || settled || stopping || !proc.stdin || proc.stdin.destroyed) return Promise.reject(new Error("Subagent has stopped accepting messages."));
232
288
  const id = `steer-${++nextRequestId}`;
233
- return new Promise<void>((resolve, reject) => {
289
+ return new Promise<SteeringReceipt>((resolve, reject) => {
234
290
  const timer = setTimeout(() => {
235
291
  if (pendingSteers.delete(id)) reject(new Error("No acknowledgement; message delivery is unconfirmed."));
236
292
  }, 10_000);
237
293
  timer.unref?.();
238
- pendingSteers.set(id, { resolve: () => { clearTimeout(timer); resolve(); }, reject: (error) => { clearTimeout(timer); reject(error); } });
294
+ pendingSteers.set(id, { resolve: (receipt) => { clearTimeout(timer); resolve(receipt); }, reject: (error) => { clearTimeout(timer); reject(error); } });
239
295
  proc.stdin.write(JSON.stringify({ id, type: "steer", message: asPlainTextPrompt(message) }) + "\n", (error) => {
240
296
  if (error) {
241
297
  const pending = pendingSteers.get(id);
@@ -272,6 +328,15 @@ export async function runCliAgentAttempt(options: RunCliAttemptOptions): Promise
272
328
  const processLine = (line: string): void => {
273
329
  let record: any;
274
330
  try { record = JSON.parse(line); } catch { return; }
331
+ if (record?.type === "extension_ui_request") {
332
+ if (["select", "confirm", "input", "editor"].includes(record.method) && typeof record.id === "string") {
333
+ result.stderr = appendBoundedStderr(result.stderr, `Cancelled child extension ${record.method} dialog: subagents cannot answer interactive requests; approval was not granted.\n`);
334
+ if (!closed && !proc.stdin?.destroyed && !proc.stdin?.writableEnded) {
335
+ proc.stdin?.write(JSON.stringify({ type: "extension_ui_response", id: record.id, cancelled: true }) + "\n");
336
+ }
337
+ }
338
+ return;
339
+ }
275
340
  if (record?.type === "response") {
276
341
  if (record.id === "initial-prompt" && (!record.success || record.data?.disposition === "handled")) {
277
342
  result.dispatchFailed = true;
@@ -281,7 +346,13 @@ export async function runCliAgentAttempt(options: RunCliAttemptOptions): Promise
281
346
  const pending = pendingSteers.get(record.id);
282
347
  if (pending) {
283
348
  pendingSteers.delete(record.id);
284
- if (record.success) pending.resolve();
349
+ if (record.success) {
350
+ const disposition = record.data?.disposition;
351
+ pending.resolve({
352
+ requestId: record.id, acknowledgedAt: Date.now(),
353
+ disposition: disposition === "queued" || disposition === "handled" ? disposition : "accepted",
354
+ });
355
+ }
285
356
  else pending.reject(new Error(record.error || "Steering was rejected."));
286
357
  }
287
358
  return;
@@ -339,23 +410,7 @@ export async function runCliAgentAttempt(options: RunCliAttemptOptions): Promise
339
410
  const stdoutDecoder = new StringDecoder("utf8");
340
411
  const stderrDecoder = new StringDecoder("utf8");
341
412
  let stdoutBuffer = "";
342
- proc.stdout.on("data", (chunk: Buffer) => {
343
- lastActivityAt = Date.now();
344
- stdoutBuffer += stdoutDecoder.write(chunk);
345
- let start = 0;
346
- for (let lf = stdoutBuffer.indexOf("\n"); lf !== -1; lf = stdoutBuffer.indexOf("\n", start)) {
347
- processLine(stdoutBuffer.slice(start, lf));
348
- start = lf + 1;
349
- }
350
- if (start) stdoutBuffer = stdoutBuffer.slice(start);
351
- });
352
- proc.stderr.on("data", (chunk: Buffer) => { result.stderr = appendBoundedStderr(result.stderr, stderrDecoder.write(chunk)); });
353
- proc.stdin.on("error", (error) => {
354
- if (stopping || closed || settled) return;
355
- result.dispatchFailed = true;
356
- result.errorMessage ??= "Subagent stdin failed: " + error.message;
357
- terminate();
358
- });
413
+ const onAbort = (): void => { void attempt.stop("Subagent was aborted"); };
359
414
  proc.once("error", (error) => {
360
415
  result.dispatchFailed = true;
361
416
  result.errorMessage ??= "Failed to start the sub-agent process: " + error.message;
@@ -389,7 +444,25 @@ export async function runCliAgentAttempt(options: RunCliAttemptOptions): Promise
389
444
  result.exitCode = result.dispatchFailed || result.stopReason === "error" || result.stopReason === "aborted" || result.stopReason === "length" ? 1 : 0;
390
445
  resolveClosed();
391
446
  });
392
- const onAbort = (): void => { void attempt.stop("Subagent was aborted"); };
447
+ // EMFILE/ENFILE may return a child without stdio. Register lifecycle
448
+ // handlers first so its queued error and close still settle this attempt.
449
+ proc.stdout?.on("data", (chunk: Buffer) => {
450
+ lastActivityAt = Date.now();
451
+ stdoutBuffer += stdoutDecoder.write(chunk);
452
+ let start = 0;
453
+ for (let lf = stdoutBuffer.indexOf("\n"); lf !== -1; lf = stdoutBuffer.indexOf("\n", start)) {
454
+ processLine(stdoutBuffer.slice(start, lf));
455
+ start = lf + 1;
456
+ }
457
+ if (start) stdoutBuffer = stdoutBuffer.slice(start);
458
+ });
459
+ proc.stderr?.on("data", (chunk: Buffer) => { result.stderr = appendBoundedStderr(result.stderr, stderrDecoder.write(chunk)); });
460
+ proc.stdin?.on("error", (error) => {
461
+ if (stopping || closed || settled) return;
462
+ result.dispatchFailed = true;
463
+ result.errorMessage ??= "Subagent stdin failed: " + error.message;
464
+ terminate();
465
+ });
393
466
  startupTimer = setTimeout(() => {
394
467
  result.dispatchFailed = true;
395
468
  result.errorMessage = "Subagent startup timeout before agent activity.";
@@ -406,7 +479,7 @@ export async function runCliAgentAttempt(options: RunCliAttemptOptions): Promise
406
479
  signal?.addEventListener("abort", onAbort, { once: true });
407
480
  try {
408
481
  if (signal?.aborted || control?.isStopRequested()) await attempt.stop(control?.getStopMessage());
409
- else proc.stdin.write(JSON.stringify({ id: "initial-prompt", type: "prompt", message: asPlainTextPrompt(options.prompt) }) + "\n");
482
+ else proc.stdin?.write(JSON.stringify({ id: "initial-prompt", type: "prompt", message: asPlainTextPrompt(options.prompt) }) + "\n");
410
483
  await processClosed;
411
484
  return result;
412
485
  } finally {
@@ -15,14 +15,18 @@ export function terminateProcessTree(proc: ChildProcess, force: boolean, process
15
15
  /* process may already be gone */
16
16
  }
17
17
  };
18
- const killer = spawn("taskkill", ["/pid", String(proc.pid), "/t", "/f"], {
19
- stdio: "ignore",
20
- windowsHide: true,
21
- });
22
- killer.once("error", fallback);
23
- killer.once("close", (code) => {
24
- if (code !== 0) fallback();
25
- });
18
+ try {
19
+ const killer = spawn("taskkill", ["/pid", String(proc.pid), "/t", "/f"], {
20
+ stdio: "ignore",
21
+ windowsHide: true,
22
+ });
23
+ killer.once("error", fallback);
24
+ killer.once("close", (code) => {
25
+ if (code !== 0) fallback();
26
+ });
27
+ } catch {
28
+ fallback();
29
+ }
26
30
  return;
27
31
  }
28
32
 
@@ -70,9 +70,17 @@ export type RunControlPhase =
70
70
  | "settled"
71
71
  | "stopped";
72
72
 
73
+ /** Receipt of a steering command, not proof that the model consumed it. */
74
+ export interface SteeringReceipt {
75
+ /** Present when the child acknowledged a matching RPC request. */
76
+ requestId?: string;
77
+ disposition: "queued" | "handled" | "accepted";
78
+ acknowledgedAt: number;
79
+ }
80
+
73
81
  export interface AttemptControl {
74
82
  stop(reason?: string): Promise<void>;
75
- steer?(message: string): Promise<void>;
83
+ steer?(message: string): Promise<SteeringReceipt | void>;
76
84
  }
77
85
 
78
86
  /** Prevent CLI prompt expansion when a message starts with a slash command. */
@@ -162,11 +170,11 @@ export class RunControl {
162
170
  this.setPhase(phase);
163
171
  }
164
172
 
165
- async steer(message: string): Promise<void> {
173
+ async steer(message: string): Promise<SteeringReceipt> {
166
174
  if (this.stopRequested || this.phase !== "running" || !this.attempt?.control.steer) {
167
175
  throw new Error("This run is not accepting steering messages.");
168
176
  }
169
- await this.attempt.control.steer(message);
177
+ return (await this.attempt.control.steer(message)) ?? { disposition: "accepted", acknowledgedAt: Date.now() };
170
178
  }
171
179
 
172
180
  async stop(reason = "Subagent was aborted"): Promise<void> {
@@ -24,6 +24,7 @@ import {
24
24
  } from "./run-control.ts";
25
25
  import {
26
26
  currentSubagentDepth,
27
+ findSessionFile,
27
28
  runCliAgentAttempt,
28
29
  sessionExists,
29
30
  } from "./cli-run.ts";
@@ -31,6 +32,7 @@ import { writeTempOwnerMarker } from "../isolation/temp-hygiene.ts";
31
32
 
32
33
  export {
33
34
  currentSubagentDepth,
35
+ findSessionFile,
34
36
  RunControl,
35
37
  sessionExists,
36
38
  };
@@ -254,7 +256,7 @@ export function getResultOutput(result: SingleResult): string {
254
256
  /** Model handoff preserves useful history, but main or siblings may have edited
255
257
  * the workspace since the selected model last read it. */
256
258
  const RESUME_CONTINUATION_RULES =
257
- "Your earlier work — searches, reads, edits, and reasoning — is preserved in this session's history above; review it before acting. Do not redo searches, reads, or edits that already succeeded. The workspace may have changed while this thread was inactive: before editing a file, re-read it unless you read it during this continuation. Finish with the result-only handoff your role requires.";
259
+ "Your earlier work — searches, reads, edits, and reasoning — is preserved in this session's history above; review it before acting. Do not redo searches, reads, or edits that already succeeded. The workspace may have changed while this thread was inactive: before editing a file, re-read it unless you read it during this continuation. The current cwd is authoritative; do not reuse paths to an earlier temporary worktree. Finish with the result-only handoff your role requires.";
258
260
 
259
261
  /** The objective is a multi-line brief, so it gets its own block instead of
260
262
  * being spliced mid-sentence (where a trailing period also doubled up). */
@@ -379,7 +381,12 @@ export async function runSingleAgentWithMainFallback(
379
381
 
380
382
  const sessionId = options.sessionId ?? randomUUID();
381
383
  const sessionDir = options.sessionDir ?? (await createSessionDir(options.sessionRoot));
382
- const baseOptions: RunSingleOptions = { ...options, sessionDir, sessionId };
384
+ const baseOptions: RunSingleOptions = {
385
+ ...options, sessionDir, sessionId,
386
+ ...(options.sessionDir && options.stdinText === undefined
387
+ ? { stdinText: buildResumePrompt(options.task, "a follow-up was requested") }
388
+ : {}),
389
+ };
383
390
  if (!options.sessionDir) {
384
391
  // Surface the fresh session immediately so the dispatching thread can
385
392
  // persist a durable checkpoint before the child settles.
@@ -14,7 +14,7 @@ import { join } from "node:path";
14
14
  import { getSubagentsRoot, sweepProjectResultArtifacts } from "../execution/spawn.ts";
15
15
  import { pruneStaleProjectRoots, readReferencedDurablePaths, readThreadRecords } from "../lifecycle/durable.ts";
16
16
  import type { SubagentRuntime } from "../lifecycle/runtime.ts";
17
- import { isProcessAlive, sweepProjectDurableDirs, sweepProjectTempDirs } from "./temp-hygiene.ts";
17
+ import { isProcessAlive, readTempOwnerMarker, sweepProjectDurableDirs, sweepProjectTempDirs } from "./temp-hygiene.ts";
18
18
 
19
19
  /** Bytes a directory tree occupies, without following symlinks. */
20
20
  export function directoryBytes(path: string): number {
@@ -103,9 +103,10 @@ function removeEmptySessionCopies(path: string, claimed: readonly string[]): voi
103
103
  if (!entry.name.startsWith("pi-subagent-session-")) continue;
104
104
  const dir = join(path, "sessions", entry.name);
105
105
  if (claimed.some((claim) => claim.startsWith(dir))) continue;
106
- // A follow-up copies a session and the child resumes it; once that copy
107
- // holds nothing, it is pure overhead. Owner liveness already guards the
108
- // live case, so an empty unclaimed directory is safe to drop.
106
+ // The earlier orphan sweep kept live owners; this pass must honor the
107
+ // same guard while a fresh child has not written its first prompt yet.
108
+ const owner = readTempOwnerMarker(dir);
109
+ if (owner && isProcessAlive(owner.pid)) continue;
109
110
  let files = 0;
110
111
  try {
111
112
  files = readdirSync(dir).filter((name) => name !== "owner.json").length;
@@ -132,8 +133,8 @@ export interface CleanupResult {
132
133
  export async function runStorageCleanup(configPath: string, options: { now?: number; root?: string } = {}): Promise<CleanupResult> {
133
134
  const root = options.root ?? getSubagentsRoot(configPath);
134
135
  const before = measureDurableUsage(root);
135
- const records = await readThreadRecords(configPath).catch(() => []);
136
- const claimed = await readReferencedDurablePaths(configPath).catch(() => new Set<string>());
136
+ const records = await readThreadRecords(configPath);
137
+ const claimed = await readReferencedDurablePaths(configPath);
137
138
  const keep = (path: string) => [...claimed].some((claim) => path.startsWith(claim) || claim.startsWith(path));
138
139
 
139
140
  sweepProjectTempDirs(root);
@@ -203,6 +204,13 @@ export interface AutomaticCleanupOptions {
203
204
  force?: boolean;
204
205
  }
205
206
 
207
+ /** Another Pi process may still be preparing its checkpoint. Its owner marker
208
+ * protects the session even when this runtime has no thread or manifest for it. */
209
+ function hasForeignLiveOwner(path: string): boolean {
210
+ const owner = readTempOwnerMarker(path);
211
+ return owner !== undefined && owner.pid !== process.pid && isProcessAlive(owner.pid);
212
+ }
213
+
206
214
  interface SettledSession {
207
215
  path: string;
208
216
  mtimeMs: number;
@@ -221,6 +229,7 @@ function settledSessions(projectRoot: string): SettledSession[] {
221
229
  .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && entry.name.startsWith("pi-subagent-session-"))
222
230
  .flatMap((entry) => {
223
231
  const path = join(dir, entry.name);
232
+ if (hasForeignLiveOwner(path)) return [];
224
233
  try {
225
234
  // Pi appends the transcript in place, leaving the parent mtime
226
235
  // unchanged. Settlement also refreshes the directory timestamp.
@@ -306,7 +315,13 @@ export async function runAutomaticCleanup(
306
315
  if (!options.force && now - lastAutomaticCleanupAt < AUTO_CLEANUP_INTERVAL_MS) return { freedBytes: 0, skipped: true };
307
316
  lastAutomaticCleanupAt = now;
308
317
  const root = getSubagentsRoot(runtime.configPath);
309
- const claimed = await readReferencedDurablePaths(runtime.configPath).catch(() => new Set<string>());
318
+ let claimed: Set<string>;
319
+ try {
320
+ claimed = await readReferencedDurablePaths(runtime.configPath);
321
+ } catch {
322
+ // Unknown references cannot authorize deleting any recovery artifacts.
323
+ return { freedBytes: 0, skipped: true };
324
+ }
310
325
  const protectedPaths = protectedSessionPaths(runtime, claimed);
311
326
  const keep = (path: string) => protectedPaths.some((kept) => path.startsWith(kept) || kept.startsWith(path));
312
327
  const before = measureDurableUsage(root).totalBytes;
@@ -26,8 +26,9 @@ async function isPlainPath(path: string, kind: "directory" | "file"): Promise<bo
26
26
  try {
27
27
  const entry = await lstat(path);
28
28
  return !entry.isSymbolicLink() && (kind === "directory" ? entry.isDirectory() : entry.isFile());
29
- } catch {
30
- return false;
29
+ } catch (error) {
30
+ if (["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) return false;
31
+ throw error;
31
32
  }
32
33
  }
33
34
 
@@ -35,8 +36,9 @@ async function isDirectRealChild(root: string, candidate: string): Promise<boole
35
36
  try {
36
37
  const [realRoot, realCandidate] = await Promise.all([realpath(root), realpath(candidate)]);
37
38
  return samePath(dirname(realCandidate), realRoot);
38
- } catch {
39
- return false;
39
+ } catch (error) {
40
+ if (["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) return false;
41
+ throw error;
40
42
  }
41
43
  }
42
44
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
4
4
  import { randomUUID } from "node:crypto";
5
- import { mkdir, readdir, rmdir, stat, unlink, writeFile } from "node:fs/promises";
5
+ import { mkdir, readdir, rename, rmdir, stat, unlink, writeFile } from "node:fs/promises";
6
6
  import { uptime } from "node:os";
7
7
  import { dirname, join } from "node:path";
8
8
  import { setTimeout as delay } from "node:timers/promises";
@@ -12,6 +12,22 @@ const LOCK_TIMEOUT_MS = 15_000;
12
12
  const EMPTY_LOCK_MAX_AGE_MS = 60_000;
13
13
  const BOOT_TOLERANCE_MS = 60_000;
14
14
 
15
+ /** Windows can briefly deny replacement while another process inspects the
16
+ * checkpoint. Retry the same atomic rename under the caller's mutation lock;
17
+ * never unlink the last valid manifest to make a replacement succeed. */
18
+ export async function replaceManifestFile(temporaryPath: string, path: string): Promise<void> {
19
+ for (let attempt = 0; ; attempt++) {
20
+ try {
21
+ await rename(temporaryPath, path);
22
+ return;
23
+ } catch (error) {
24
+ const code = (error as NodeJS.ErrnoException).code;
25
+ if (process.platform !== "win32" || (code !== "EPERM" && code !== "EACCES") || attempt === 5) throw error;
26
+ await delay(25 * 2 ** attempt);
27
+ }
28
+ }
29
+ }
30
+
15
31
  function bootId(): number {
16
32
  return Math.round(Date.now() - uptime() * 1_000);
17
33
  }
@@ -1,8 +1,8 @@
1
1
  /** Durable handoff for worktree integration/cleanup failures across sessions. */
2
2
 
3
- import { withManifestMutation } from "./manifest-mutation.ts";
3
+ import { replaceManifestFile, withManifestMutation } from "./manifest-mutation.ts";
4
4
  import { existsSync } from "node:fs";
5
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
5
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
6
6
  import { dirname, join } from "node:path";
7
7
  import { stripVTControlCharacters } from "node:util";
8
8
  import { getProjectRoot, getSubagentsRoot } from "../execution/spawn.ts";
@@ -51,25 +51,25 @@ function normalizeRecord(value: unknown): RecoveryRecord | undefined {
51
51
  }
52
52
 
53
53
  interface RecoveryManifestRead {
54
- valid: boolean;
55
54
  sourceCount: number;
56
55
  records: RecoveryRecord[];
57
56
  }
58
57
 
59
58
  async function readManifest(path: string): Promise<RecoveryManifestRead> {
60
59
  try {
61
- const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown };
62
- if (!Array.isArray(parsed.records)) return { valid: false, sourceCount: 0, records: [] };
60
+ const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown } | null;
61
+ if (!Array.isArray(parsed?.records)) throw new Error(`Invalid recovery manifest: ${path}`);
63
62
  return {
64
- valid: true,
65
63
  sourceCount: parsed.records.length,
66
64
  records: parsed.records.flatMap((record) => {
67
65
  const normalized = normalizeRecord(record);
68
66
  return normalized ? [normalized] : [];
69
67
  }),
70
68
  };
71
- } catch {
72
- return { valid: false, sourceCount: 0, records: [] };
69
+ } catch (error) {
70
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { sourceCount: 0, records: [] };
71
+ // Keep the original document and its artifacts when references are unknown.
72
+ throw error;
73
73
  }
74
74
  }
75
75
 
@@ -91,7 +91,7 @@ export async function readRecoveryRecords(configPath: string): Promise<RecoveryR
91
91
  return withManifestMutation(path, async () => {
92
92
  const manifest = await readManifest(path);
93
93
  const records = await validatedRecords(configPath, manifest.records);
94
- if (!manifest.valid || records.length !== manifest.sourceCount) await writeManifest(path, records);
94
+ if (records.length !== manifest.sourceCount) await writeManifest(path, records);
95
95
  return records;
96
96
  });
97
97
  }
@@ -104,10 +104,6 @@ export async function relocateRecoveryManifest(configPath: string): Promise<void
104
104
  if (legacyPath === currentPath || !existsSync(legacyPath)) return;
105
105
  await withManifestMutation(legacyPath, async () => {
106
106
  const legacy = await readManifest(legacyPath);
107
- if (!legacy.valid) {
108
- await rm(legacyPath, { force: true });
109
- return;
110
- }
111
107
  await persistRecoveryRecords(configPath, legacy.records);
112
108
  await rm(legacyPath, { force: true });
113
109
  });
@@ -130,7 +126,7 @@ async function writeManifest(path: string, records: readonly RecoveryRecord[]):
130
126
  records: [...records],
131
127
  };
132
128
  await writeFile(temporaryPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
133
- await rename(temporaryPath, path);
129
+ await replaceManifestFile(temporaryPath, path);
134
130
  } finally {
135
131
  await rm(temporaryPath, { force: true }).catch(() => undefined);
136
132
  }
@@ -220,7 +216,7 @@ export async function announceRecoveryRecords(
220
216
  (record.worktreePath ? existsSync(record.worktreePath) : false) ||
221
217
  (record.patchPath ? existsSync(record.patchPath) : false),
222
218
  );
223
- if (!current.valid || remaining.length !== current.sourceCount) await writeManifest(path, remaining);
219
+ if (remaining.length !== current.sourceCount) await writeManifest(path, remaining);
224
220
  return remaining;
225
221
  });
226
222
  for (const record of live) {
@@ -72,7 +72,7 @@ export function writeTempOwnerMarker(dir: string, now = Date.now()): void {
72
72
  }
73
73
  }
74
74
 
75
- function readTempOwnerMarker(dir: string): TempOwner | undefined {
75
+ export function readTempOwnerMarker(dir: string): TempOwner | undefined {
76
76
  try {
77
77
  const parsed = JSON.parse(readFileSync(join(dir, TEMP_OWNER_FILE_NAME), "utf8")) as Partial<TempOwner>;
78
78
  if (typeof parsed.pid !== "number" || !Number.isInteger(parsed.pid) || parsed.pid <= 0) return undefined;