@ferris1225/pi-subagents 5.0.6 → 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.
- package/CHANGELOG.md +89 -0
- package/README.md +187 -97
- package/index.ts +1 -1
- package/package.json +4 -9
- package/src/configuration/role-migration.ts +2 -2
- package/src/configuration/setup.ts +4 -2
- package/src/configuration/ui.ts +144 -132
- package/src/delegation/agents.ts +15 -22
- package/src/delegation/dispatch.ts +17 -122
- package/src/delegation/prompt.ts +13 -12
- package/src/execution/cli-run.ts +112 -39
- package/src/execution/process-tree.ts +12 -8
- package/src/execution/run-control.ts +11 -3
- package/src/execution/spawn.ts +24 -7
- package/src/isolation/cleanup.ts +31 -12
- package/src/isolation/managed-paths.ts +6 -4
- package/src/isolation/manifest-mutation.ts +89 -0
- package/src/isolation/recovery.ts +33 -29
- package/src/isolation/temp-hygiene.ts +1 -1
- package/src/lifecycle/await-results.ts +114 -0
- package/src/lifecycle/dispatch-core.ts +7 -1
- package/src/lifecycle/durable.ts +83 -39
- package/src/lifecycle/runtime.ts +12 -4
- package/src/lifecycle/stop.ts +2 -2
- package/src/lifecycle/thread-lifecycle.ts +10 -5
- package/src/lifecycle/thread-restore.ts +26 -25
- package/src/lifecycle/thread-shared.ts +15 -3
- package/src/lifecycle/tools.ts +90 -33
- package/src/presentation/announcements.ts +8 -2
- package/src/presentation/monitor.ts +5 -3
- package/src/presentation/widget.ts +157 -113
- package/src/workflow/acceptance.ts +67 -0
- package/src/workflow/durable.ts +34 -14
- package/src/workflow/engine.ts +161 -51
- package/src/workflow/plan.ts +25 -4
- package/src/workflow/state.ts +6 -0
- package/src/workflow/templates.ts +156 -0
- package/src/workflow/tool.ts +65 -109
- package/skills/workflow/SKILL.md +0 -268
- package/src/workflow/files.ts +0 -236
- package/workflows/code-review.md +0 -38
- package/workflows/migration.md +0 -42
- package/workflows/research.md +0 -48
package/src/execution/spawn.ts
CHANGED
|
@@ -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
|
};
|
|
@@ -167,11 +169,21 @@ export function sweepProjectResultArtifacts(
|
|
|
167
169
|
|
|
168
170
|
function resultArtifactProjectKey(cwd?: string): string {
|
|
169
171
|
if (!cwd) return "default";
|
|
170
|
-
let
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
172
|
+
let ancestor = resolve(cwd);
|
|
173
|
+
let canonical = ancestor;
|
|
174
|
+
const missing: string[] = [];
|
|
175
|
+
for (;;) {
|
|
176
|
+
try {
|
|
177
|
+
canonical = join(realpathSync.native(ancestor), ...missing);
|
|
178
|
+
break;
|
|
179
|
+
} catch {
|
|
180
|
+
// Keep aliases in existing parents canonical when the checkout is
|
|
181
|
+
// unavailable (for example macOS /var and Windows short paths).
|
|
182
|
+
const parent = dirname(ancestor);
|
|
183
|
+
if (parent === ancestor) break;
|
|
184
|
+
missing.unshift(basename(ancestor));
|
|
185
|
+
ancestor = parent;
|
|
186
|
+
}
|
|
175
187
|
}
|
|
176
188
|
if (process.platform === "win32") canonical = canonical.toLowerCase();
|
|
177
189
|
const slug = basename(canonical).replace(/[^\w.-]+/g, "_") || "project";
|
|
@@ -244,7 +256,7 @@ export function getResultOutput(result: SingleResult): string {
|
|
|
244
256
|
/** Model handoff preserves useful history, but main or siblings may have edited
|
|
245
257
|
* the workspace since the selected model last read it. */
|
|
246
258
|
const RESUME_CONTINUATION_RULES =
|
|
247
|
-
"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.";
|
|
248
260
|
|
|
249
261
|
/** The objective is a multi-line brief, so it gets its own block instead of
|
|
250
262
|
* being spliced mid-sentence (where a trailing period also doubled up). */
|
|
@@ -369,7 +381,12 @@ export async function runSingleAgentWithMainFallback(
|
|
|
369
381
|
|
|
370
382
|
const sessionId = options.sessionId ?? randomUUID();
|
|
371
383
|
const sessionDir = options.sessionDir ?? (await createSessionDir(options.sessionRoot));
|
|
372
|
-
const baseOptions: RunSingleOptions = {
|
|
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
|
+
};
|
|
373
390
|
if (!options.sessionDir) {
|
|
374
391
|
// Surface the fresh session immediately so the dispatching thread can
|
|
375
392
|
// persist a durable checkpoint before the child settles.
|
package/src/isolation/cleanup.ts
CHANGED
|
@@ -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 {
|
|
@@ -73,7 +73,7 @@ export function measureDurableUsage(root: string): CleanupUsage {
|
|
|
73
73
|
return { root, projects: [], totalBytes: 0 };
|
|
74
74
|
}
|
|
75
75
|
const measured = projects
|
|
76
|
-
.filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())
|
|
76
|
+
.filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && !entry.name.endsWith(".lock"))
|
|
77
77
|
.map((entry) => {
|
|
78
78
|
const path = join(root, entry.name);
|
|
79
79
|
return {
|
|
@@ -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
|
-
//
|
|
107
|
-
//
|
|
108
|
-
|
|
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)
|
|
136
|
-
const claimed = await readReferencedDurablePaths(configPath)
|
|
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,8 +229,15 @@ 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
|
|
235
|
+
// unchanged. Settlement also refreshes the directory timestamp.
|
|
236
|
+
let mtimeMs = statSync(path).mtimeMs;
|
|
237
|
+
for (const file of readdirSync(path, { withFileTypes: true })) {
|
|
238
|
+
if (file.isFile()) mtimeMs = Math.max(mtimeMs, statSync(join(path, file.name)).mtimeMs);
|
|
239
|
+
}
|
|
240
|
+
return [{ path, mtimeMs, bytes: directoryBytes(path) }];
|
|
226
241
|
} catch {
|
|
227
242
|
return [];
|
|
228
243
|
}
|
|
@@ -300,9 +315,13 @@ export async function runAutomaticCleanup(
|
|
|
300
315
|
if (!options.force && now - lastAutomaticCleanupAt < AUTO_CLEANUP_INTERVAL_MS) return { freedBytes: 0, skipped: true };
|
|
301
316
|
lastAutomaticCleanupAt = now;
|
|
302
317
|
const root = getSubagentsRoot(runtime.configPath);
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
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
|
+
}
|
|
306
325
|
const protectedPaths = protectedSessionPaths(runtime, claimed);
|
|
307
326
|
const keep = (path: string) => protectedPaths.some((kept) => path.startsWith(kept) || kept.startsWith(path));
|
|
308
327
|
const before = measureDurableUsage(root).totalBytes;
|
|
@@ -317,7 +336,7 @@ export async function runAutomaticCleanup(
|
|
|
317
336
|
projects = [];
|
|
318
337
|
}
|
|
319
338
|
for (const project of projects) {
|
|
320
|
-
if (!project.isDirectory() || project.isSymbolicLink()) continue;
|
|
339
|
+
if (!project.isDirectory() || project.isSymbolicLink() || project.name.endsWith(".lock")) continue;
|
|
321
340
|
const path = join(root, project.name);
|
|
322
341
|
reclaimSettledSessions(path, protectedPaths, now, options.maxSessionAgeMs ?? SETTLED_SESSION_MAX_AGE_MS);
|
|
323
342
|
enforceProjectBudget(path, protectedPaths, now, options.budgetBytes ?? PROJECT_BUDGET_BYTES);
|
|
@@ -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
|
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/** Cross-process serialization for shared durable manifests. */
|
|
2
|
+
|
|
3
|
+
import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { mkdir, readdir, rename, rmdir, stat, unlink, writeFile } from "node:fs/promises";
|
|
6
|
+
import { uptime } from "node:os";
|
|
7
|
+
import { dirname, join } from "node:path";
|
|
8
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
9
|
+
import { isProcessAlive } from "./temp-hygiene.ts";
|
|
10
|
+
|
|
11
|
+
const LOCK_TIMEOUT_MS = 15_000;
|
|
12
|
+
const EMPTY_LOCK_MAX_AGE_MS = 60_000;
|
|
13
|
+
const BOOT_TOLERANCE_MS = 60_000;
|
|
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
|
+
|
|
31
|
+
function bootId(): number {
|
|
32
|
+
return Math.round(Date.now() - uptime() * 1_000);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function releaseLock(lockDir: string, owner: string): Promise<void> {
|
|
36
|
+
// Only the contender which removed this unique owner file may remove its
|
|
37
|
+
// directory. A second stale-lock reaper cannot unlink a successor's lock.
|
|
38
|
+
await unlink(join(lockDir, owner));
|
|
39
|
+
await rmdir(lockDir).catch(() => undefined);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function reapAbandonedLock(lockDir: string): Promise<void> {
|
|
43
|
+
try {
|
|
44
|
+
const owners = await readdir(lockDir);
|
|
45
|
+
if (owners.length === 0) {
|
|
46
|
+
// A process can die between mkdir and writing its owner marker. Fresh
|
|
47
|
+
// empty locks belong to contenders still acquiring them.
|
|
48
|
+
if (Date.now() - (await stat(lockDir)).mtimeMs >= EMPTY_LOCK_MAX_AGE_MS) await rmdir(lockDir);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
if (owners.length !== 1) return;
|
|
52
|
+
const owner = owners[0]!;
|
|
53
|
+
const match = /^(\d+)-(\d+)-[0-9a-f-]+$/.exec(owner);
|
|
54
|
+
if (!match) return;
|
|
55
|
+
if (Math.abs(Number(match[2]) - bootId()) <= BOOT_TOLERANCE_MS && isProcessAlive(Number(match[1]))) return;
|
|
56
|
+
await releaseLock(lockDir, owner);
|
|
57
|
+
} catch {
|
|
58
|
+
/* Another contender may already have released this abandoned lock. */
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Keep the host's in-process queue and lock the entire read/modify/write across
|
|
63
|
+
* Pi windows too. Dead owners are reclaimable without a heartbeat or an age
|
|
64
|
+
* cutoff that could steal a live writer's lock. */
|
|
65
|
+
export function withManifestMutation<T>(path: string, mutate: () => Promise<T>): Promise<T> {
|
|
66
|
+
return withFileMutationQueue(path, async () => {
|
|
67
|
+
await mkdir(dirname(path), { recursive: true });
|
|
68
|
+
const lockDir = `${path}.lock`;
|
|
69
|
+
const owner = `${process.pid}-${bootId()}-${randomUUID()}`;
|
|
70
|
+
const deadline = Date.now() + LOCK_TIMEOUT_MS;
|
|
71
|
+
while (true) {
|
|
72
|
+
try {
|
|
73
|
+
await mkdir(lockDir);
|
|
74
|
+
break;
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
77
|
+
await reapAbandonedLock(lockDir);
|
|
78
|
+
if (Date.now() >= deadline) throw new Error(`Timed out waiting for manifest lock: ${path}`);
|
|
79
|
+
await delay(25);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
await writeFile(join(lockDir, owner), "", "utf8");
|
|
84
|
+
return await mutate();
|
|
85
|
+
} finally {
|
|
86
|
+
await releaseLock(lockDir, owner).catch(() => undefined);
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/** Durable handoff for worktree integration/cleanup failures across sessions. */
|
|
2
2
|
|
|
3
|
-
import {
|
|
3
|
+
import { replaceManifestFile, withManifestMutation } from "./manifest-mutation.ts";
|
|
4
4
|
import { existsSync } from "node:fs";
|
|
5
|
-
import { mkdir, readFile,
|
|
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";
|
|
@@ -13,6 +13,7 @@ const RECOVERY_MANIFEST_FILE_NAME = "pi-subagents-recovery.json";
|
|
|
13
13
|
const RECOVERY_MANIFEST_VERSION = 1;
|
|
14
14
|
|
|
15
15
|
export interface RecoveryRecord {
|
|
16
|
+
durableId?: string;
|
|
16
17
|
runId: number;
|
|
17
18
|
createdAt: number;
|
|
18
19
|
integrated: boolean;
|
|
@@ -38,6 +39,7 @@ function normalizeRecord(value: unknown): RecoveryRecord | undefined {
|
|
|
38
39
|
if (typeof raw.runId !== "number" || !Number.isInteger(raw.runId) || raw.runId < 1) return undefined;
|
|
39
40
|
if (typeof raw.createdAt !== "number" || !Number.isFinite(raw.createdAt)) return undefined;
|
|
40
41
|
return {
|
|
42
|
+
...(typeof raw.durableId === "string" && raw.durableId ? { durableId: raw.durableId } : {}),
|
|
41
43
|
runId: raw.runId,
|
|
42
44
|
createdAt: raw.createdAt,
|
|
43
45
|
integrated: raw.integrated === true,
|
|
@@ -49,25 +51,25 @@ function normalizeRecord(value: unknown): RecoveryRecord | undefined {
|
|
|
49
51
|
}
|
|
50
52
|
|
|
51
53
|
interface RecoveryManifestRead {
|
|
52
|
-
valid: boolean;
|
|
53
54
|
sourceCount: number;
|
|
54
55
|
records: RecoveryRecord[];
|
|
55
56
|
}
|
|
56
57
|
|
|
57
58
|
async function readManifest(path: string): Promise<RecoveryManifestRead> {
|
|
58
59
|
try {
|
|
59
|
-
const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown };
|
|
60
|
-
if (!Array.isArray(parsed
|
|
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}`);
|
|
61
62
|
return {
|
|
62
|
-
valid: true,
|
|
63
63
|
sourceCount: parsed.records.length,
|
|
64
64
|
records: parsed.records.flatMap((record) => {
|
|
65
65
|
const normalized = normalizeRecord(record);
|
|
66
66
|
return normalized ? [normalized] : [];
|
|
67
67
|
}),
|
|
68
68
|
};
|
|
69
|
-
} catch {
|
|
70
|
-
return {
|
|
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;
|
|
71
73
|
}
|
|
72
74
|
}
|
|
73
75
|
|
|
@@ -86,10 +88,10 @@ export async function referencedRecoveryPaths(
|
|
|
86
88
|
|
|
87
89
|
export async function readRecoveryRecords(configPath: string): Promise<RecoveryRecord[]> {
|
|
88
90
|
const path = getRecoveryManifestPath(configPath);
|
|
89
|
-
return
|
|
91
|
+
return withManifestMutation(path, async () => {
|
|
90
92
|
const manifest = await readManifest(path);
|
|
91
93
|
const records = await validatedRecords(configPath, manifest.records);
|
|
92
|
-
if (
|
|
94
|
+
if (records.length !== manifest.sourceCount) await writeManifest(path, records);
|
|
93
95
|
return records;
|
|
94
96
|
});
|
|
95
97
|
}
|
|
@@ -100,19 +102,15 @@ export async function relocateRecoveryManifest(configPath: string): Promise<void
|
|
|
100
102
|
const legacyPath = join(dirname(configPath), RECOVERY_MANIFEST_FILE_NAME);
|
|
101
103
|
const currentPath = getRecoveryManifestPath(configPath);
|
|
102
104
|
if (legacyPath === currentPath || !existsSync(legacyPath)) return;
|
|
103
|
-
await
|
|
105
|
+
await withManifestMutation(legacyPath, async () => {
|
|
104
106
|
const legacy = await readManifest(legacyPath);
|
|
105
|
-
if (!legacy.valid) {
|
|
106
|
-
await rm(legacyPath, { force: true });
|
|
107
|
-
return;
|
|
108
|
-
}
|
|
109
107
|
await persistRecoveryRecords(configPath, legacy.records);
|
|
110
108
|
await rm(legacyPath, { force: true });
|
|
111
109
|
});
|
|
112
110
|
}
|
|
113
111
|
|
|
114
112
|
function recoveryKey(record: RecoveryRecord): string {
|
|
115
|
-
return `${record.runId}\0${record.worktreePath ?? ""}\0${record.patchPath ?? ""}\0${record.error ?? ""}`;
|
|
113
|
+
return `${record.durableId ?? record.runId}\0${record.worktreePath ?? ""}\0${record.patchPath ?? ""}\0${record.error ?? ""}`;
|
|
116
114
|
}
|
|
117
115
|
|
|
118
116
|
async function writeManifest(path: string, records: readonly RecoveryRecord[]): Promise<void> {
|
|
@@ -128,7 +126,7 @@ async function writeManifest(path: string, records: readonly RecoveryRecord[]):
|
|
|
128
126
|
records: [...records],
|
|
129
127
|
};
|
|
130
128
|
await writeFile(temporaryPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
|
|
131
|
-
await
|
|
129
|
+
await replaceManifestFile(temporaryPath, path);
|
|
132
130
|
} finally {
|
|
133
131
|
await rm(temporaryPath, { force: true }).catch(() => undefined);
|
|
134
132
|
}
|
|
@@ -141,7 +139,7 @@ export async function persistRecoveryRecords(
|
|
|
141
139
|
): Promise<void> {
|
|
142
140
|
if (records.length === 0) return;
|
|
143
141
|
const path = getRecoveryManifestPath(configPath);
|
|
144
|
-
await
|
|
142
|
+
await withManifestMutation(path, async () => {
|
|
145
143
|
const merged = new Map<string, RecoveryRecord>();
|
|
146
144
|
const existing = await readManifest(path);
|
|
147
145
|
for (const record of await validatedRecords(configPath, existing.records)) {
|
|
@@ -158,8 +156,10 @@ export function recoveryRecordFromFinalization(
|
|
|
158
156
|
runId: number,
|
|
159
157
|
finalization: WorktreeFinalization,
|
|
160
158
|
now = Date.now(),
|
|
159
|
+
durableId?: string,
|
|
161
160
|
): RecoveryRecord {
|
|
162
161
|
return {
|
|
162
|
+
...(durableId ? { durableId } : {}),
|
|
163
163
|
runId,
|
|
164
164
|
createdAt: now,
|
|
165
165
|
integrated: finalization.integrated,
|
|
@@ -195,11 +195,11 @@ export async function announceRecoveryRecords(
|
|
|
195
195
|
if (ctx.hasUI === false) return;
|
|
196
196
|
const records = await readRecoveryRecords(configPath);
|
|
197
197
|
if (records.length === 0) return;
|
|
198
|
-
const local = new Set<
|
|
198
|
+
const local = new Set<string>();
|
|
199
199
|
for (const record of records) {
|
|
200
200
|
const groupDir = await managedRecoveryGroup(configPath, record);
|
|
201
201
|
if (!groupDir || !recoveryBelongsToSession(configPath, ctx.cwd, groupDir)) continue;
|
|
202
|
-
local.add(record);
|
|
202
|
+
local.add(recoveryKey(record));
|
|
203
203
|
if (!record.integrated || !record.worktreePath) continue;
|
|
204
204
|
if (!existsSync(record.worktreePath) && !(record.patchPath ? existsSync(record.patchPath) : false)) continue;
|
|
205
205
|
await removeWorktreeGroup({
|
|
@@ -207,16 +207,20 @@ export async function announceRecoveryRecords(
|
|
|
207
207
|
tempDir: groupDir,
|
|
208
208
|
});
|
|
209
209
|
}
|
|
210
|
-
const
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
210
|
+
const path = getRecoveryManifestPath(configPath);
|
|
211
|
+
const live = await withManifestMutation(path, async () => {
|
|
212
|
+
// Cleanup awaits Git/filesystem work outside the queue. Re-read here so
|
|
213
|
+
// failures persisted during those awaits survive this pruning pass.
|
|
214
|
+
const current = await readManifest(path);
|
|
215
|
+
const remaining = (await validatedRecords(configPath, current.records)).filter((record) =>
|
|
216
|
+
(record.worktreePath ? existsSync(record.worktreePath) : false) ||
|
|
217
|
+
(record.patchPath ? existsSync(record.patchPath) : false),
|
|
218
|
+
);
|
|
219
|
+
if (remaining.length !== current.sourceCount) await writeManifest(path, remaining);
|
|
220
|
+
return remaining;
|
|
221
|
+
});
|
|
218
222
|
for (const record of live) {
|
|
219
|
-
if (!local.has(record)) continue;
|
|
223
|
+
if (!local.has(recoveryKey(record))) continue;
|
|
220
224
|
const paths = [
|
|
221
225
|
record.worktreePath ? `worktree ${stripVTControlCharacters(record.worktreePath)}` : undefined,
|
|
222
226
|
record.patchPath ? `patch ${stripVTControlCharacters(record.patchPath)}` : undefined,
|
|
@@ -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;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/** Shared in-turn completion delivery for dispatches and completed-run follow-ups. */
|
|
2
|
+
|
|
3
|
+
import { Type } from "typebox";
|
|
4
|
+
import { isFailedResult, type SingleResult } from "../execution/spawn.ts";
|
|
5
|
+
import { formatCompletionBlock } from "../presentation/format.ts";
|
|
6
|
+
import { monitor, statusLabel } from "../presentation/monitor.ts";
|
|
7
|
+
import type { SubagentRuntime } from "./runtime.ts";
|
|
8
|
+
import { projectResultsRoot } from "./thread-shared.ts";
|
|
9
|
+
|
|
10
|
+
export const WaitSchema = Type.Optional(Type.Boolean({
|
|
11
|
+
description: "Wait for runs started by this call and return their results once, after integration. Defaults to true in one-shot print/JSON sessions, false in TUI/RPC. Use true when the next step depends on the result; false to continue independent work. Cancelling the parent stops unfinished runs without background wake-ups.",
|
|
12
|
+
}));
|
|
13
|
+
|
|
14
|
+
/** In-turn wait for a new run or completed-run follow-up. Registration resolves it without a model-chosen
|
|
15
|
+
* timer; parent abort ends the wait and cancels its owned work. */
|
|
16
|
+
export async function awaitRunResults(
|
|
17
|
+
runtime: SubagentRuntime,
|
|
18
|
+
runIds: number[],
|
|
19
|
+
signal: AbortSignal | undefined,
|
|
20
|
+
maxResultLines: number,
|
|
21
|
+
fallbackCwd: string,
|
|
22
|
+
onProgress?: (text: string) => void,
|
|
23
|
+
): Promise<string> {
|
|
24
|
+
const waitForRun = (runId: number): Promise<{ result?: SingleResult; note?: string }> => {
|
|
25
|
+
const already = runtime.settledRuns.get(runId);
|
|
26
|
+
if (already) return Promise.resolve({ result: already });
|
|
27
|
+
if (monitor.findRun(runId)?.status === "parked") {
|
|
28
|
+
return Promise.resolve({ note: `run #${runId} was interrupted; inspect retained work with subagent_status and finish it in main` });
|
|
29
|
+
}
|
|
30
|
+
return new Promise((resolve) => {
|
|
31
|
+
let done = false;
|
|
32
|
+
let unsub: (() => void) | undefined;
|
|
33
|
+
const cleanup = (): void => {
|
|
34
|
+
if (unsub) unsub();
|
|
35
|
+
signal?.removeEventListener("abort", onAbort);
|
|
36
|
+
const listeners = runtime.settledListeners.get(runId);
|
|
37
|
+
if (listeners) {
|
|
38
|
+
listeners.delete(onSettled);
|
|
39
|
+
if (listeners.size === 0) runtime.settledListeners.delete(runId);
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
const finish = (outcome: { result?: SingleResult; note?: string }): void => {
|
|
43
|
+
if (done) return;
|
|
44
|
+
done = true;
|
|
45
|
+
cleanup();
|
|
46
|
+
resolve(outcome);
|
|
47
|
+
};
|
|
48
|
+
const onSettled = (result: SingleResult): void => finish({ result });
|
|
49
|
+
const onMonitor = (): void => {
|
|
50
|
+
const current = runtime.settledRuns.get(runId);
|
|
51
|
+
if (current) {
|
|
52
|
+
finish({ result: current });
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const live = monitor.findRun(runId);
|
|
56
|
+
if (live?.status === "parked") {
|
|
57
|
+
finish({ note: `run #${runId} was interrupted; inspect retained work with subagent_status and finish it in main` });
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (!live) {
|
|
61
|
+
// Removal is followed synchronously by registerRunResult in the
|
|
62
|
+
// finishing task; re-check on the next tick so the result wins.
|
|
63
|
+
setTimeout(() => {
|
|
64
|
+
const late = runtime.settledRuns.get(runId);
|
|
65
|
+
if (late) finish({ result: late });
|
|
66
|
+
else finish({ note: `run #${runId} was removed before its result was recorded (cancelled or session ended)` });
|
|
67
|
+
}, 0);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
const onAbort = (): void => finish({ note: `Parent wait cancelled for run #${runId}; automatic cancellation stops unfinished child work. No additional subagent_stop is needed.` });
|
|
71
|
+
let listeners = runtime.settledListeners.get(runId);
|
|
72
|
+
if (!listeners) {
|
|
73
|
+
listeners = new Set();
|
|
74
|
+
runtime.settledListeners.set(runId, listeners);
|
|
75
|
+
}
|
|
76
|
+
listeners.add(onSettled);
|
|
77
|
+
unsub = monitor.subscribe(onMonitor);
|
|
78
|
+
if (signal?.aborted) onAbort();
|
|
79
|
+
else signal?.addEventListener("abort", onAbort, { once: true });
|
|
80
|
+
});
|
|
81
|
+
};
|
|
82
|
+
// One shared subscription drives the progress line: each waiter already
|
|
83
|
+
// subscribes for its own settlement, and the tool card wants a single
|
|
84
|
+
// rolled-up line rather than one per run.
|
|
85
|
+
let lastProgress: string | undefined;
|
|
86
|
+
const emitProgress = onProgress
|
|
87
|
+
? (): void => {
|
|
88
|
+
const parts = runIds.map((id) => {
|
|
89
|
+
const settled = runtime.settledRuns.get(id);
|
|
90
|
+
if (settled) return `#${id} ${isFailedResult(settled) ? "failed" : "done"}`;
|
|
91
|
+
const live = monitor.findRun(id);
|
|
92
|
+
return live ? `#${id} ${statusLabel(live.status)}` : `#${id} …`;
|
|
93
|
+
});
|
|
94
|
+
const text = `Waiting in-turn on ${runIds.length} run${runIds.length === 1 ? "" : "s"} · ${parts.join(", ")}`;
|
|
95
|
+
// The monitor notifies on every usage and activity change; this line
|
|
96
|
+
// names only statuses, so most notifications leave it identical.
|
|
97
|
+
if (text === lastProgress) return;
|
|
98
|
+
lastProgress = text;
|
|
99
|
+
onProgress(text);
|
|
100
|
+
}
|
|
101
|
+
: undefined;
|
|
102
|
+
const progressUnsub = emitProgress ? monitor.subscribe(emitProgress) : undefined;
|
|
103
|
+
try {
|
|
104
|
+
emitProgress?.();
|
|
105
|
+
const outcomes = await Promise.all(runIds.map(waitForRun));
|
|
106
|
+
return outcomes.map((outcome) =>
|
|
107
|
+
outcome.result
|
|
108
|
+
? formatCompletionBlock(outcome.result, maxResultLines, { resultRoot: projectResultsRoot(runtime.configPath, outcome.result.projectCwd ?? fallbackCwd) })
|
|
109
|
+
: (outcome.note ?? "(no outcome)"),
|
|
110
|
+
).join("\n\n");
|
|
111
|
+
} finally {
|
|
112
|
+
progressUnsub?.();
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -28,6 +28,10 @@ export interface DispatchCore {
|
|
|
28
28
|
|
|
29
29
|
export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
|
|
30
30
|
const environmentRef: { current: DispatchEnvironment | undefined } = { current: undefined };
|
|
31
|
+
// Sweeps outlive the queue task which starts them. Drain every started pass
|
|
32
|
+
// before shutdown releases this runtime and its filesystem ownership.
|
|
33
|
+
let cleanupPending: Promise<void> = Promise.resolve();
|
|
34
|
+
runtime.shutdownHooks.push(() => cleanupPending);
|
|
31
35
|
|
|
32
36
|
// Terminal rows stay in the monitor until the next beginTurn so the footer
|
|
33
37
|
// can count them beside siblings that are still live. The widget ignores
|
|
@@ -46,7 +50,9 @@ export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
|
|
|
46
50
|
if (endedAt !== undefined) publishedEndedAt.set(runId, endedAt);
|
|
47
51
|
// Settlement is the natural moment to reclaim disk: a burst of runs costs
|
|
48
52
|
// one paced sweep, and every live or parked thread stays protected.
|
|
49
|
-
|
|
53
|
+
if (runtime.sessionActive) {
|
|
54
|
+
cleanupPending = Promise.allSettled([cleanupPending, runAutomaticCleanup(runtime)]).then(() => undefined);
|
|
55
|
+
}
|
|
50
56
|
if (opts?.silent || !runtime.sessionActive) return;
|
|
51
57
|
const icon = status === "done" ? "✓" : "✗";
|
|
52
58
|
const result = runtime.threads.get(runId)?.lastResult;
|