@timmyjl12/pi-subagents 0.21.2 → 0.21.6
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 +30 -0
- package/dist/agent-manager.js +11 -2
- package/dist/report-store.d.ts +9 -0
- package/dist/report-store.js +41 -4
- package/dist/schedule.d.ts +3 -1
- package/dist/schedule.js +15 -0
- package/dist/ui/cleanup-preview.js +1 -0
- package/dist/ui/conversation-viewer.js +11 -2
- package/dist/workflow/meta.js +20 -3
- package/package.json +4 -4
- package/src/agent-manager.ts +3322 -3312
- package/src/report-store.ts +44 -4
- package/src/schedule-store.ts +244 -244
- package/src/schedule.ts +16 -1
- package/src/ui/cleanup-preview.ts +2 -1
- package/src/ui/conversation-viewer.ts +11 -4
- package/src/workflow/meta.ts +19 -3
package/src/report-store.ts
CHANGED
|
@@ -704,6 +704,26 @@ async function renameWithRetry(
|
|
|
704
704
|
}
|
|
705
705
|
}
|
|
706
706
|
|
|
707
|
+
/**
|
|
708
|
+
* Read a lock file, retrying the transient sharing errors Windows reports
|
|
709
|
+
* while another handle (this process's own unlink, AV, an indexer) still has
|
|
710
|
+
* it open. Failing closed on one of those would be permanent, not cautious:
|
|
711
|
+
* a release that cannot read its own lock keeps the file, and a lock whose
|
|
712
|
+
* PID is this live process then refuses every later spawn and resume here.
|
|
713
|
+
*/
|
|
714
|
+
async function readLockFileWithRetry(path: string): Promise<string> {
|
|
715
|
+
for (let attempt = 0; ; attempt++) {
|
|
716
|
+
try {
|
|
717
|
+
return await readFile(path, "utf8");
|
|
718
|
+
} catch (error) {
|
|
719
|
+
const code = errorCode(error);
|
|
720
|
+
const transient = code === "EPERM" || code === "EBUSY" || code === "EACCES";
|
|
721
|
+
if (!transient || attempt >= RENAME_RETRIES) throw error;
|
|
722
|
+
await new Promise((done) => setTimeout(done, RENAME_RETRY_MS * (attempt + 1)));
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
|
|
707
727
|
async function chmodPrivate(path: string, mode: number): Promise<void> {
|
|
708
728
|
try {
|
|
709
729
|
await chmod(path, mode);
|
|
@@ -1495,6 +1515,23 @@ export class ReportStore {
|
|
|
1495
1515
|
);
|
|
1496
1516
|
}
|
|
1497
1517
|
|
|
1518
|
+
/**
|
|
1519
|
+
* The exemption across an awaited lock read. `before` is this store's
|
|
1520
|
+
* maintenance nonce taken before the read started. If that maintenance
|
|
1521
|
+
* ended while the read was in flight, its row is gone by the time the caller
|
|
1522
|
+
* checks, and the lock it just read (our PID, our nonce) would otherwise look
|
|
1523
|
+
* foreign and refuse a spawn or resume. A lock that outlives a failed
|
|
1524
|
+
* release is still refused by every later check, which starts with no row.
|
|
1525
|
+
*/
|
|
1526
|
+
private maintenanceExemptAcross(
|
|
1527
|
+
rootSessionId: string,
|
|
1528
|
+
lock: { pid: number; nonce: string } | undefined,
|
|
1529
|
+
before: string | undefined,
|
|
1530
|
+
): boolean {
|
|
1531
|
+
if (this.maintenanceExempt(rootSessionId, lock)) return true;
|
|
1532
|
+
return lock !== undefined && before !== undefined && lock.pid === process.pid && lock.nonce === before;
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1498
1535
|
/** Drop this store's in-memory ownership of exactly this handle. */
|
|
1499
1536
|
private forgetLocalOwnership(handle: CleanupLockHandle): void {
|
|
1500
1537
|
const current = this.cleanupLocks.get(handle.rootSessionId);
|
|
@@ -1778,7 +1815,7 @@ export class ReportStore {
|
|
|
1778
1815
|
private async readCleanupLockRead(rootSessionId: string): Promise<CleanupLockRead> {
|
|
1779
1816
|
let raw: string;
|
|
1780
1817
|
try {
|
|
1781
|
-
raw = await
|
|
1818
|
+
raw = await readLockFileWithRetry(this.lockPath(rootSessionId));
|
|
1782
1819
|
} catch (error) {
|
|
1783
1820
|
if (isNotFound(error)) return { status: "absent" };
|
|
1784
1821
|
this.diagnose(`cleanup lock unreadable: ${errorCode(error) ?? "unknown"}`);
|
|
@@ -1814,13 +1851,14 @@ export class ReportStore {
|
|
|
1814
1851
|
* uncertain fails closed with an explicit reason (never silently active).
|
|
1815
1852
|
*/
|
|
1816
1853
|
private async writeBlockReason(rootSessionId: string): Promise<string | undefined> {
|
|
1854
|
+
const maintenanceBefore = this.maintenanceLocks.get(rootSessionId);
|
|
1817
1855
|
const read = await this.readCleanupLockRead(rootSessionId);
|
|
1818
1856
|
if (read.status === "uncertain") {
|
|
1819
1857
|
this.diagnose(`cleanup lock uncertain (${read.reason ?? "unknown"}); refusing writes`);
|
|
1820
1858
|
return "cleanup-lock-unreadable";
|
|
1821
1859
|
}
|
|
1822
1860
|
if (read.status !== "live") return undefined;
|
|
1823
|
-
if (this.
|
|
1861
|
+
if (this.maintenanceExemptAcross(rootSessionId, read.lock, maintenanceBefore)) return undefined;
|
|
1824
1862
|
return "cleanup-lock";
|
|
1825
1863
|
}
|
|
1826
1864
|
|
|
@@ -2360,10 +2398,11 @@ export class ReportStore {
|
|
|
2360
2398
|
this.diagnose(`unsafe root entry name: ${entry.name}`);
|
|
2361
2399
|
return true;
|
|
2362
2400
|
}
|
|
2401
|
+
const maintenanceBefore = this.maintenanceLocks.get(entry.name);
|
|
2363
2402
|
const read = await this.readCleanupLockRead(entry.name);
|
|
2364
2403
|
if (read.status === "uncertain") return true;
|
|
2365
2404
|
if (read.status !== "live" || read.lock === undefined) continue;
|
|
2366
|
-
if (this.
|
|
2405
|
+
if (this.maintenanceExemptAcross(entry.name, read.lock, maintenanceBefore)) continue;
|
|
2367
2406
|
if (this.selectionMatches(read.lock, scope)) return true;
|
|
2368
2407
|
}
|
|
2369
2408
|
// A cleanup lock this store acquired while the scan was awaiting is live
|
|
@@ -2431,6 +2470,7 @@ export class ReportStore {
|
|
|
2431
2470
|
if (!activation) throw new ReportUnavailableError("inactive-activation");
|
|
2432
2471
|
const rootSessionId = this.context?.rootSessionId;
|
|
2433
2472
|
if (!rootSessionId || !activation.persistence) return;
|
|
2473
|
+
const maintenanceBefore = this.maintenanceLocks.get(rootSessionId);
|
|
2434
2474
|
const read = await this.readCleanupLockRead(rootSessionId);
|
|
2435
2475
|
// The read awaited: only the activation that started it may be authorized.
|
|
2436
2476
|
// A close, rebind or lost activation in that window makes this answer stale.
|
|
@@ -2441,7 +2481,7 @@ export class ReportStore {
|
|
|
2441
2481
|
if (read.status === "uncertain") {
|
|
2442
2482
|
throw new ReportUnavailableError("cleanup-lock-unreadable");
|
|
2443
2483
|
}
|
|
2444
|
-
if (read.status === "live" && !this.
|
|
2484
|
+
if (read.status === "live" && !this.maintenanceExemptAcross(rootSessionId, read.lock, maintenanceBefore)) {
|
|
2445
2485
|
throw new ReportUnavailableError("cleanup-lock");
|
|
2446
2486
|
}
|
|
2447
2487
|
}
|
package/src/schedule-store.ts
CHANGED
|
@@ -1,244 +1,244 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* schedule-store.ts — File-backed store for scheduled subagents.
|
|
3
|
-
*
|
|
4
|
-
* Session-scoped: each pi session owns its own schedules at
|
|
5
|
-
* `<cwd>/.pi/subagent-schedules/<sessionId>.json`. `/new` starts a fresh
|
|
6
|
-
* empty store; `/resume` reloads.
|
|
7
|
-
*
|
|
8
|
-
* Concurrency model lifted from pi-chonky-tasks/src/task-store.ts: every
|
|
9
|
-
* mutation acquires a PID-based exclusion lock, re-reads the latest state
|
|
10
|
-
* from disk, applies the change, atomic-writes via temp+rename, releases.
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
import { randomBytes } from "node:crypto";
|
|
14
|
-
import { readFileSync } from "node:fs";
|
|
15
|
-
import { mkdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
16
|
-
import { dirname, join } from "node:path";
|
|
17
|
-
import { setTimeout as sleep } from "node:timers/promises";
|
|
18
|
-
import type { ScheduledSubagent, ScheduleStoreData } from "./types.ts";
|
|
19
|
-
|
|
20
|
-
const LOCK_RETRY_MS = 50;
|
|
21
|
-
/** Total asynchronous wait for the lock. */
|
|
22
|
-
const LOCK_MAX_WAIT_MS = 1000;
|
|
23
|
-
/**
|
|
24
|
-
* A lock older than this is stale whatever its PID says: Windows reuses PIDs
|
|
25
|
-
* aggressively, so "that process is alive" does not mean it holds the lock.
|
|
26
|
-
* A mutation holds the lock for a few milliseconds.
|
|
27
|
-
*/
|
|
28
|
-
export const LOCK_STALE_MS = 30_000;
|
|
29
|
-
const RENAME_RETRIES = 5;
|
|
30
|
-
const RENAME_RETRY_MS = 20;
|
|
31
|
-
|
|
32
|
-
function isProcessRunning(pid: number): boolean {
|
|
33
|
-
try {
|
|
34
|
-
process.kill(pid, 0);
|
|
35
|
-
return true;
|
|
36
|
-
} catch {
|
|
37
|
-
return false;
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
function errorCode(e: unknown): string | undefined {
|
|
42
|
-
const code = (e as { code?: unknown } | null)?.code;
|
|
43
|
-
return typeof code === "string" ? code : undefined;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** True when the existing lock file can be broken: too old, or its owner is gone. */
|
|
47
|
-
async function isLockStale(lockPath: string): Promise<boolean> {
|
|
48
|
-
try {
|
|
49
|
-
if (Date.now() - (await stat(lockPath)).mtimeMs > LOCK_STALE_MS) return true;
|
|
50
|
-
const pid = parseInt(await readFile(lockPath, "utf-8"), 10);
|
|
51
|
-
return Number.isInteger(pid) && pid > 0 && !isProcessRunning(pid);
|
|
52
|
-
} catch (e) {
|
|
53
|
-
// Vanished between our write attempt and this check: retry the write.
|
|
54
|
-
return errorCode(e) === "ENOENT";
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
async function acquireLock(lockPath: string): Promise<void> {
|
|
59
|
-
const deadline = Date.now() + LOCK_MAX_WAIT_MS;
|
|
60
|
-
for (;;) {
|
|
61
|
-
try {
|
|
62
|
-
await writeFile(lockPath, `${process.pid}`, { flag: "wx" });
|
|
63
|
-
return;
|
|
64
|
-
} catch (e) {
|
|
65
|
-
if (errorCode(e) !== "EEXIST") throw e;
|
|
66
|
-
}
|
|
67
|
-
if (await isLockStale(lockPath)) {
|
|
68
|
-
try {
|
|
69
|
-
await unlink(lockPath);
|
|
70
|
-
} catch (e) {
|
|
71
|
-
if (errorCode(e) !== "ENOENT") throw e;
|
|
72
|
-
}
|
|
73
|
-
continue;
|
|
74
|
-
}
|
|
75
|
-
if (Date.now() >= deadline) break;
|
|
76
|
-
await sleep(LOCK_RETRY_MS);
|
|
77
|
-
}
|
|
78
|
-
throw new Error(`Failed to acquire schedule lock: ${lockPath}`);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/** rename with a bounded retry: Windows reports EPERM/EBUSY while AV or an indexer holds the target. */
|
|
82
|
-
async function renameWithRetry(from: string, to: string): Promise<void> {
|
|
83
|
-
for (let attempt = 0; ; attempt++) {
|
|
84
|
-
try {
|
|
85
|
-
await rename(from, to);
|
|
86
|
-
return;
|
|
87
|
-
} catch (e) {
|
|
88
|
-
const code = errorCode(e);
|
|
89
|
-
const transient = code === "EPERM" || code === "EBUSY" || code === "EACCES";
|
|
90
|
-
if (!transient || attempt >= RENAME_RETRIES) {
|
|
91
|
-
// Best effort: the rename error below is the one that matters.
|
|
92
|
-
await unlink(from).catch(() => undefined);
|
|
93
|
-
throw e;
|
|
94
|
-
}
|
|
95
|
-
await sleep(RENAME_RETRY_MS * (attempt + 1));
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
async function releaseLock(lockPath: string): Promise<void> {
|
|
101
|
-
await unlink(lockPath).catch(() => undefined);
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/** Resolve the storage path for a session-scoped store. */
|
|
105
|
-
export function resolveStorePath(cwd: string, sessionId: string): string {
|
|
106
|
-
return join(cwd, ".pi", "subagent-schedules", `${sessionId}.json`);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
function parseStoreData(serialized: string): ScheduleStoreData | undefined {
|
|
110
|
-
try {
|
|
111
|
-
return JSON.parse(serialized) as ScheduleStoreData;
|
|
112
|
-
} catch {
|
|
113
|
-
return undefined;
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
export class ScheduleStore {
|
|
118
|
-
private filePath: string;
|
|
119
|
-
private lockPath: string;
|
|
120
|
-
private jobs = new Map<string, ScheduledSubagent>();
|
|
121
|
-
|
|
122
|
-
constructor(filePath: string) {
|
|
123
|
-
this.filePath = filePath;
|
|
124
|
-
this.lockPath = filePath + ".lock";
|
|
125
|
-
this.loadInitial();
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/** Create the backing directory lazily — only when we're about to persist. */
|
|
129
|
-
private async ensureDir(): Promise<void> {
|
|
130
|
-
await mkdir(dirname(this.filePath), { recursive: true });
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* One cold synchronous read preserves the synchronous constructor and the
|
|
135
|
-
* list/get snapshot API. Every reload on a mutation path uses async I/O.
|
|
136
|
-
*/
|
|
137
|
-
private loadInitial(): void {
|
|
138
|
-
let serialized: string;
|
|
139
|
-
try {
|
|
140
|
-
serialized = readFileSync(this.filePath, "utf-8");
|
|
141
|
-
} catch {
|
|
142
|
-
return;
|
|
143
|
-
}
|
|
144
|
-
const data = parseStoreData(serialized);
|
|
145
|
-
if (data) this.replaceJobs(data);
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/** Reload from disk into the in-memory cache. Silent on parse errors. */
|
|
149
|
-
private async load(): Promise<void> {
|
|
150
|
-
let serialized: string;
|
|
151
|
-
try {
|
|
152
|
-
serialized = await readFile(this.filePath, "utf-8");
|
|
153
|
-
} catch (e) {
|
|
154
|
-
if (errorCode(e) === "ENOENT") return;
|
|
155
|
-
throw e;
|
|
156
|
-
}
|
|
157
|
-
const data = parseStoreData(serialized);
|
|
158
|
-
if (data) this.replaceJobs(data);
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
private replaceJobs(data: ScheduleStoreData): void {
|
|
162
|
-
this.jobs.clear();
|
|
163
|
-
for (const j of data.jobs ?? []) this.jobs.set(j.id, j);
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
/** Atomic write via temp file + rename (POSIX-atomic). */
|
|
167
|
-
private async save(): Promise<void> {
|
|
168
|
-
const data: ScheduleStoreData = { version: 1, jobs: [...this.jobs.values()] };
|
|
169
|
-
// Unique per write, so two writers can never clobber each other's temp file.
|
|
170
|
-
const tmp = `${this.filePath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
171
|
-
await writeFile(tmp, JSON.stringify(data, null, 2));
|
|
172
|
-
await renameWithRetry(tmp, this.filePath);
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
/** Acquire lock → reload → mutate → save → release. */
|
|
176
|
-
private async withLock<T>(fn: () => T): Promise<T> {
|
|
177
|
-
await this.ensureDir();
|
|
178
|
-
await acquireLock(this.lockPath);
|
|
179
|
-
try {
|
|
180
|
-
await this.load();
|
|
181
|
-
const result = fn();
|
|
182
|
-
await this.save();
|
|
183
|
-
return result;
|
|
184
|
-
} finally {
|
|
185
|
-
await releaseLock(this.lockPath);
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/** Read-only — returns a snapshot of the in-memory cache. */
|
|
190
|
-
list(): ScheduledSubagent[] {
|
|
191
|
-
return [...this.jobs.values()];
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
/** Read-only check — uses the cache. */
|
|
195
|
-
hasName(name: string, exceptId?: string): boolean {
|
|
196
|
-
for (const j of this.jobs.values()) {
|
|
197
|
-
if (j.id !== exceptId && j.name === name) return true;
|
|
198
|
-
}
|
|
199
|
-
return false;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
get(id: string): ScheduledSubagent | undefined {
|
|
203
|
-
return this.jobs.get(id);
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
async add(job: ScheduledSubagent): Promise<void> {
|
|
207
|
-
await this.withLock(() => {
|
|
208
|
-
this.jobs.set(job.id, job);
|
|
209
|
-
});
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
/** Atomically re-check the latest committed names and insert only if unique. */
|
|
213
|
-
async addUnlessNameExists(job: ScheduledSubagent): Promise<boolean> {
|
|
214
|
-
return this.withLock(() => {
|
|
215
|
-
if (this.hasName(job.name)) return false;
|
|
216
|
-
this.jobs.set(job.id, job);
|
|
217
|
-
return true;
|
|
218
|
-
});
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
async update(id: string, patch: Partial<ScheduledSubagent>): Promise<ScheduledSubagent | undefined> {
|
|
222
|
-
// No-op fast path — an unknown id changes nothing, so don't lock or touch
|
|
223
|
-
// disk (which would otherwise lazily create the backing directory).
|
|
224
|
-
if (!this.jobs.has(id)) return undefined;
|
|
225
|
-
return this.withLock(() => {
|
|
226
|
-
const existing = this.jobs.get(id);
|
|
227
|
-
if (!existing) return undefined;
|
|
228
|
-
const updated = { ...existing, ...patch };
|
|
229
|
-
this.jobs.set(id, updated);
|
|
230
|
-
return updated;
|
|
231
|
-
});
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
async remove(id: string): Promise<boolean> {
|
|
235
|
-
// No-op fast path — see update().
|
|
236
|
-
if (!this.jobs.has(id)) return false;
|
|
237
|
-
return this.withLock(() => this.jobs.delete(id));
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
/** Delete the backing file (used when no jobs remain, optional cleanup). */
|
|
241
|
-
async deleteFileIfEmpty(): Promise<void> {
|
|
242
|
-
if (this.jobs.size === 0) await unlink(this.filePath).catch(() => undefined);
|
|
243
|
-
}
|
|
244
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* schedule-store.ts — File-backed store for scheduled subagents.
|
|
3
|
+
*
|
|
4
|
+
* Session-scoped: each pi session owns its own schedules at
|
|
5
|
+
* `<cwd>/.pi/subagent-schedules/<sessionId>.json`. `/new` starts a fresh
|
|
6
|
+
* empty store; `/resume` reloads.
|
|
7
|
+
*
|
|
8
|
+
* Concurrency model lifted from pi-chonky-tasks/src/task-store.ts: every
|
|
9
|
+
* mutation acquires a PID-based exclusion lock, re-reads the latest state
|
|
10
|
+
* from disk, applies the change, atomic-writes via temp+rename, releases.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { randomBytes } from "node:crypto";
|
|
14
|
+
import { readFileSync } from "node:fs";
|
|
15
|
+
import { mkdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
16
|
+
import { dirname, join } from "node:path";
|
|
17
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
18
|
+
import type { ScheduledSubagent, ScheduleStoreData } from "./types.ts";
|
|
19
|
+
|
|
20
|
+
const LOCK_RETRY_MS = 50;
|
|
21
|
+
/** Total asynchronous wait for the lock. */
|
|
22
|
+
const LOCK_MAX_WAIT_MS = 1000;
|
|
23
|
+
/**
|
|
24
|
+
* A lock older than this is stale whatever its PID says: Windows reuses PIDs
|
|
25
|
+
* aggressively, so "that process is alive" does not mean it holds the lock.
|
|
26
|
+
* A mutation holds the lock for a few milliseconds.
|
|
27
|
+
*/
|
|
28
|
+
export const LOCK_STALE_MS = 30_000;
|
|
29
|
+
const RENAME_RETRIES = 5;
|
|
30
|
+
const RENAME_RETRY_MS = 20;
|
|
31
|
+
|
|
32
|
+
function isProcessRunning(pid: number): boolean {
|
|
33
|
+
try {
|
|
34
|
+
process.kill(pid, 0);
|
|
35
|
+
return true;
|
|
36
|
+
} catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function errorCode(e: unknown): string | undefined {
|
|
42
|
+
const code = (e as { code?: unknown } | null)?.code;
|
|
43
|
+
return typeof code === "string" ? code : undefined;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** True when the existing lock file can be broken: too old, or its owner is gone. */
|
|
47
|
+
async function isLockStale(lockPath: string): Promise<boolean> {
|
|
48
|
+
try {
|
|
49
|
+
if (Date.now() - (await stat(lockPath)).mtimeMs > LOCK_STALE_MS) return true;
|
|
50
|
+
const pid = parseInt(await readFile(lockPath, "utf-8"), 10);
|
|
51
|
+
return Number.isInteger(pid) && pid > 0 && !isProcessRunning(pid);
|
|
52
|
+
} catch (e) {
|
|
53
|
+
// Vanished between our write attempt and this check: retry the write.
|
|
54
|
+
return errorCode(e) === "ENOENT";
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function acquireLock(lockPath: string): Promise<void> {
|
|
59
|
+
const deadline = Date.now() + LOCK_MAX_WAIT_MS;
|
|
60
|
+
for (;;) {
|
|
61
|
+
try {
|
|
62
|
+
await writeFile(lockPath, `${process.pid}`, { flag: "wx" });
|
|
63
|
+
return;
|
|
64
|
+
} catch (e) {
|
|
65
|
+
if (errorCode(e) !== "EEXIST") throw e;
|
|
66
|
+
}
|
|
67
|
+
if (await isLockStale(lockPath)) {
|
|
68
|
+
try {
|
|
69
|
+
await unlink(lockPath);
|
|
70
|
+
} catch (e) {
|
|
71
|
+
if (errorCode(e) !== "ENOENT") throw e;
|
|
72
|
+
}
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (Date.now() >= deadline) break;
|
|
76
|
+
await sleep(LOCK_RETRY_MS);
|
|
77
|
+
}
|
|
78
|
+
throw new Error(`Failed to acquire schedule lock: ${lockPath}`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** rename with a bounded retry: Windows reports EPERM/EBUSY while AV or an indexer holds the target. */
|
|
82
|
+
async function renameWithRetry(from: string, to: string): Promise<void> {
|
|
83
|
+
for (let attempt = 0; ; attempt++) {
|
|
84
|
+
try {
|
|
85
|
+
await rename(from, to);
|
|
86
|
+
return;
|
|
87
|
+
} catch (e) {
|
|
88
|
+
const code = errorCode(e);
|
|
89
|
+
const transient = code === "EPERM" || code === "EBUSY" || code === "EACCES";
|
|
90
|
+
if (!transient || attempt >= RENAME_RETRIES) {
|
|
91
|
+
// Best effort: the rename error below is the one that matters.
|
|
92
|
+
await unlink(from).catch(() => undefined);
|
|
93
|
+
throw e;
|
|
94
|
+
}
|
|
95
|
+
await sleep(RENAME_RETRY_MS * (attempt + 1));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function releaseLock(lockPath: string): Promise<void> {
|
|
101
|
+
await unlink(lockPath).catch(() => undefined);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Resolve the storage path for a session-scoped store. */
|
|
105
|
+
export function resolveStorePath(cwd: string, sessionId: string): string {
|
|
106
|
+
return join(cwd, ".pi", "subagent-schedules", `${sessionId}.json`);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function parseStoreData(serialized: string): ScheduleStoreData | undefined {
|
|
110
|
+
try {
|
|
111
|
+
return JSON.parse(serialized) as ScheduleStoreData;
|
|
112
|
+
} catch {
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export class ScheduleStore {
|
|
118
|
+
private filePath: string;
|
|
119
|
+
private lockPath: string;
|
|
120
|
+
private jobs = new Map<string, ScheduledSubagent>();
|
|
121
|
+
|
|
122
|
+
constructor(filePath: string) {
|
|
123
|
+
this.filePath = filePath;
|
|
124
|
+
this.lockPath = filePath + ".lock";
|
|
125
|
+
this.loadInitial();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Create the backing directory lazily — only when we're about to persist. */
|
|
129
|
+
private async ensureDir(): Promise<void> {
|
|
130
|
+
await mkdir(dirname(this.filePath), { recursive: true });
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* One cold synchronous read preserves the synchronous constructor and the
|
|
135
|
+
* list/get snapshot API. Every reload on a mutation path uses async I/O.
|
|
136
|
+
*/
|
|
137
|
+
private loadInitial(): void {
|
|
138
|
+
let serialized: string;
|
|
139
|
+
try {
|
|
140
|
+
serialized = readFileSync(this.filePath, "utf-8");
|
|
141
|
+
} catch {
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const data = parseStoreData(serialized);
|
|
145
|
+
if (data) this.replaceJobs(data);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Reload from disk into the in-memory cache. Silent on parse errors. */
|
|
149
|
+
private async load(): Promise<void> {
|
|
150
|
+
let serialized: string;
|
|
151
|
+
try {
|
|
152
|
+
serialized = await readFile(this.filePath, "utf-8");
|
|
153
|
+
} catch (e) {
|
|
154
|
+
if (errorCode(e) === "ENOENT") return;
|
|
155
|
+
throw e;
|
|
156
|
+
}
|
|
157
|
+
const data = parseStoreData(serialized);
|
|
158
|
+
if (data) this.replaceJobs(data);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
private replaceJobs(data: ScheduleStoreData): void {
|
|
162
|
+
this.jobs.clear();
|
|
163
|
+
for (const j of data.jobs ?? []) this.jobs.set(j.id, j);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Atomic write via temp file + rename (POSIX-atomic). */
|
|
167
|
+
private async save(): Promise<void> {
|
|
168
|
+
const data: ScheduleStoreData = { version: 1, jobs: [...this.jobs.values()] };
|
|
169
|
+
// Unique per write, so two writers can never clobber each other's temp file.
|
|
170
|
+
const tmp = `${this.filePath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
171
|
+
await writeFile(tmp, JSON.stringify(data, null, 2));
|
|
172
|
+
await renameWithRetry(tmp, this.filePath);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Acquire lock → reload → mutate → save → release. */
|
|
176
|
+
private async withLock<T>(fn: () => T): Promise<T> {
|
|
177
|
+
await this.ensureDir();
|
|
178
|
+
await acquireLock(this.lockPath);
|
|
179
|
+
try {
|
|
180
|
+
await this.load();
|
|
181
|
+
const result = fn();
|
|
182
|
+
await this.save();
|
|
183
|
+
return result;
|
|
184
|
+
} finally {
|
|
185
|
+
await releaseLock(this.lockPath);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Read-only — returns a snapshot of the in-memory cache. */
|
|
190
|
+
list(): ScheduledSubagent[] {
|
|
191
|
+
return [...this.jobs.values()];
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Read-only check — uses the cache. */
|
|
195
|
+
hasName(name: string, exceptId?: string): boolean {
|
|
196
|
+
for (const j of this.jobs.values()) {
|
|
197
|
+
if (j.id !== exceptId && j.name === name) return true;
|
|
198
|
+
}
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
get(id: string): ScheduledSubagent | undefined {
|
|
203
|
+
return this.jobs.get(id);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async add(job: ScheduledSubagent): Promise<void> {
|
|
207
|
+
await this.withLock(() => {
|
|
208
|
+
this.jobs.set(job.id, job);
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Atomically re-check the latest committed names and insert only if unique. */
|
|
213
|
+
async addUnlessNameExists(job: ScheduledSubagent): Promise<boolean> {
|
|
214
|
+
return this.withLock(() => {
|
|
215
|
+
if (this.hasName(job.name)) return false;
|
|
216
|
+
this.jobs.set(job.id, job);
|
|
217
|
+
return true;
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async update(id: string, patch: Partial<ScheduledSubagent>): Promise<ScheduledSubagent | undefined> {
|
|
222
|
+
// No-op fast path — an unknown id changes nothing, so don't lock or touch
|
|
223
|
+
// disk (which would otherwise lazily create the backing directory).
|
|
224
|
+
if (!this.jobs.has(id)) return undefined;
|
|
225
|
+
return this.withLock(() => {
|
|
226
|
+
const existing = this.jobs.get(id);
|
|
227
|
+
if (!existing) return undefined;
|
|
228
|
+
const updated = { ...existing, ...patch };
|
|
229
|
+
this.jobs.set(id, updated);
|
|
230
|
+
return updated;
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async remove(id: string): Promise<boolean> {
|
|
235
|
+
// No-op fast path — see update().
|
|
236
|
+
if (!this.jobs.has(id)) return false;
|
|
237
|
+
return this.withLock(() => this.jobs.delete(id));
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Delete the backing file (used when no jobs remain, optional cleanup). */
|
|
241
|
+
async deleteFileIfEmpty(): Promise<void> {
|
|
242
|
+
if (this.jobs.size === 0) await unlink(this.filePath).catch(() => undefined);
|
|
243
|
+
}
|
|
244
|
+
}
|
package/src/schedule.ts
CHANGED
|
@@ -41,7 +41,7 @@ export type ScheduleChangeEvent =
|
|
|
41
41
|
| { type: "removed"; jobId: string }
|
|
42
42
|
| { type: "updated"; job: ScheduledSubagent }
|
|
43
43
|
| { type: "fired"; jobId: string; agentId: string; name: string }
|
|
44
|
-
| { type: "skipped"; jobId: string; name: string; reason: "overlap" }
|
|
44
|
+
| { type: "skipped"; jobId: string; name: string; reason: "overlap" | "stopped" }
|
|
45
45
|
| { type: "error"; jobId: string; error: string };
|
|
46
46
|
|
|
47
47
|
/** Params accepted at job creation — ID, timestamps, and state are derived. */
|
|
@@ -62,6 +62,8 @@ export class SubagentScheduler {
|
|
|
62
62
|
private jobs = new Map<string, Cron>();
|
|
63
63
|
private intervals = new Map<string, NodeJS.Timeout>();
|
|
64
64
|
private activeRuns = new Set<string>();
|
|
65
|
+
/** Bumped by start() and stop(); a tick from an older generation never spawns. */
|
|
66
|
+
private generation = 0;
|
|
65
67
|
private store: ScheduleStore | undefined;
|
|
66
68
|
private pi: ExtensionAPI | undefined;
|
|
67
69
|
private ctx: ExtensionContext | undefined;
|
|
@@ -69,6 +71,7 @@ export class SubagentScheduler {
|
|
|
69
71
|
|
|
70
72
|
/** Start the scheduler: bind to a session's store and arm enabled jobs. */
|
|
71
73
|
start(pi: ExtensionAPI, ctx: ExtensionContext, manager: AgentManager, store: ScheduleStore): void {
|
|
74
|
+
this.generation += 1;
|
|
72
75
|
this.pi = pi;
|
|
73
76
|
this.ctx = ctx;
|
|
74
77
|
this.manager = manager;
|
|
@@ -81,6 +84,8 @@ export class SubagentScheduler {
|
|
|
81
84
|
|
|
82
85
|
/** Stop all timers; drop refs. Safe to call repeatedly. */
|
|
83
86
|
stop(): void {
|
|
87
|
+
// A tick suspended in an awaited store write must not spawn after this.
|
|
88
|
+
this.generation += 1;
|
|
84
89
|
for (const cron of this.jobs.values()) cron.stop();
|
|
85
90
|
this.jobs.clear();
|
|
86
91
|
for (const t of this.intervals.values()) clearTimeout(t);
|
|
@@ -250,6 +255,7 @@ export class SubagentScheduler {
|
|
|
250
255
|
const ctx = this.ctx;
|
|
251
256
|
const manager = this.manager;
|
|
252
257
|
if (!store || !pi || !ctx || !manager) return;
|
|
258
|
+
const generation = this.generation;
|
|
253
259
|
const job = store.get(id);
|
|
254
260
|
if (!job?.enabled) return;
|
|
255
261
|
if (this.activeRuns.has(id)) {
|
|
@@ -260,6 +266,15 @@ export class SubagentScheduler {
|
|
|
260
266
|
|
|
261
267
|
try {
|
|
262
268
|
await store.update(id, { lastStatus: "running" });
|
|
269
|
+
// Scheduling was turned off (or restarted) while the write was pending:
|
|
270
|
+
// do not launch, and do not leave the job recorded as running. (Only the
|
|
271
|
+
// scheduler generation is checked: a one-shot job is disabled right after
|
|
272
|
+
// its tick starts, by design, and must still run.)
|
|
273
|
+
if (generation !== this.generation) {
|
|
274
|
+
await store.update(id, { lastStatus: job.lastStatus }).catch(() => undefined);
|
|
275
|
+
this.emit({ type: "skipped", jobId: id, name: job.name, reason: "stopped" });
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
263
278
|
|
|
264
279
|
// Resolve model at fire time — registry contents may have changed since the
|
|
265
280
|
// job was created (auth added/removed). Fall back silently to spawn-default
|
|
@@ -469,7 +469,8 @@ class CleanupPreview implements Component {
|
|
|
469
469
|
return keys && keys.length > 0 ? keyLabel(keys[0]) : fallback;
|
|
470
470
|
}
|
|
471
471
|
|
|
472
|
-
|
|
472
|
+
// Read-only: pi >= 1.6 components return (and may cache) readonly arrays.
|
|
473
|
+
private contentLines(width: number): readonly string[] {
|
|
473
474
|
const styled = this.styledBody();
|
|
474
475
|
if (styled !== this.lastStyledBody) {
|
|
475
476
|
this.text.setText(styled);
|