omp-antigravity-acp-provider 0.1.19 → 0.1.21

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.
@@ -1,206 +1,201 @@
1
1
  import fs from "node:fs";
2
+ import afs from "node:fs/promises";
2
3
  import path from "node:path";
3
4
  import { createHash, randomUUID } from "node:crypto";
4
- import { lockSync } from "proper-lockfile";
5
+ import { lock } from "proper-lockfile";
5
6
  import { resolveAntigravityAcpDirectory } from "pi-antigravity-acp-provider/src/acp/antigravity.ts";
6
7
  import { isMissingFileError, writeJsonAtomic } from "./fs-atomic.ts";
7
-
8
+ import { AcpSessionStore } from "./session-store.ts";
9
+ import { sourceRoot, sourceId, findSources, type OmpSessionSource } from "./omp-session-source.ts";
8
10
  export type CleanupMode = "off" | "conservative" | "timeout";
9
- export interface CleanupPolicy { mode: CleanupMode; idleDays: number }
11
+ export interface CleanupPolicy { mode: CleanupMode; idleDays: number; maxSessions?: number; maxBytes?: number; orphanGraceDays?: number; batchSize?: number }
10
12
  const DEFAULT: CleanupPolicy = { mode: "conservative", idleDays: 7 };
11
13
  const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
12
- const TOUCH_THROTTLE_MS = 60_000;
13
14
  interface Lease { token: string; pid: number; serverPid: number }
14
- interface SessionRecord { id: string; owned: boolean; lastUsed: number; leases: Lease[]; retiredFor?: string; replaced?: boolean }
15
- interface Registry { version: 1; sessions: SessionRecord[] }
16
-
17
- function validate(policy: unknown): CleanupPolicy {
18
- const candidate = policy as Partial<CleanupPolicy> | null | undefined;
19
- if (!candidate || typeof candidate !== "object" || !["off", "conservative", "timeout"].includes(String(candidate.mode)) ||
20
- typeof candidate.idleDays !== "number" || !Number.isFinite(candidate.idleDays) || candidate.idleDays < 1 / 24 || candidate.idleDays > 3650) {
21
- throw new Error("Cleanup requires mode off|conservative|timeout and idleDays between 1/24 (one hour) and 3650");
22
- }
23
- return { mode: candidate.mode as CleanupMode, idleDays: candidate.idleDays };
24
- }
25
- export function loadCleanupPolicy(file: string): CleanupPolicy {
26
- try { return validate(JSON.parse(fs.readFileSync(file, "utf8"))); }
27
- catch (error: unknown) { if (isMissingFileError(error)) return { ...DEFAULT }; throw error; }
28
- }
29
- export function saveCleanupPolicy(file: string, policy: CleanupPolicy) {
30
- writeJsonAtomic(file, validate(policy), false);
31
- }
32
- function live(pid: number): boolean {
33
- try { process.kill(pid, 0); return true; }
34
- catch (error: unknown) { return !(error && typeof error === "object" && "code" in error && error.code === "ESRCH"); }
15
+ interface Record { id: string; owned: boolean; lastUsed: number; leases: Lease[]; retiredFor?: string; replaced?: boolean; orphanedAt?: number; ompSource?: OmpSessionSource; sourceDeleted?: boolean }
16
+ interface Registry { version: 1; sessions: Record[] }
17
+ const tails = new Map<string, Promise<unknown>>();
18
+ function validate(p: CleanupPolicy): CleanupPolicy {
19
+ if (!p || !["off", "conservative", "timeout"].includes(p.mode) || !Number.isFinite(p.idleDays) || p.idleDays < 1 / 24 || p.idleDays > 3650) throw new Error("Cleanup requires off|conservative|timeout and idleDays between 1/24 and 3650");
20
+ for (const k of ["maxSessions", "maxBytes", "batchSize"] as const) if (p[k] !== undefined && (!Number.isSafeInteger(p[k]) || p[k]! < (k === "batchSize" ? 1 : 0) || (k === "batchSize" && p[k]! > 100))) throw new Error(`Invalid cleanup ${k}`);
21
+ if (p.orphanGraceDays !== undefined && (!Number.isFinite(p.orphanGraceDays) || p.orphanGraceDays < 1 / 24 || p.orphanGraceDays > 3650)) throw new Error("Invalid orphanGraceDays");
22
+ return { mode: p.mode, idleDays: p.idleDays, ...Object.fromEntries(["maxSessions", "maxBytes", "orphanGraceDays", "batchSize"].filter(k => p[k as keyof CleanupPolicy] !== undefined).map(k => [k, p[k as keyof CleanupPolicy]])) };
35
23
  }
36
- function group(key: string) { return createHash("sha256").update(key).digest("hex"); }
24
+ export function loadCleanupPolicy(file: string): CleanupPolicy { try { return validate(JSON.parse(fs.readFileSync(file, "utf8"))); } catch (e) { if (isMissingFileError(e)) return { ...DEFAULT }; throw e; } }
25
+ export function saveCleanupPolicy(file: string, p: CleanupPolicy) { writeJsonAtomic(file, validate(p), false); }
26
+ function live(pid: number) { try { process.kill(pid, 0); return true; } catch (e) { return (e as NodeJS.ErrnoException).code !== "ESRCH"; } }
27
+ const group = (key: string) => createHash("sha256").update(key).digest("hex");
37
28
 
38
- // Only UUIDs registered by this adapter can become deletion candidates. No
39
- // directory-wide adoption of old/unidentified Google sessions is performed.
29
+ // Ownership, mapped sessions and live leases are protected independently of
30
+ // quota. Keep the cross-process lease lock during asynchronous file deletion.
40
31
  export class SessionCleanup {
41
32
  readonly policyPath: string;
42
33
  private readonly registryPath: string;
43
34
  private timer?: NodeJS.Timeout;
44
- private readonly lastTouched = new Map<string, number>();
45
- private readonly pendingTouches = new Map<string, number>();
46
- private cachedPolicy?: { mtimeMs: number; size: number; policy: CleanupPolicy };
47
- constructor(stateDir: string, readonly acpDir = resolveAntigravityAcpDirectory(),
48
- private readonly now = Date.now, private readonly isLive = live) {
35
+ private nextBatch?: NodeJS.Timeout;
36
+ private collecting?: Promise<number>;
37
+ private readonly touched = new Map<string, number>();
38
+ private readonly intents: Array<(r: Registry) => void> = [];
39
+ private report = { owned: 0, active: 0, mapped: 0, unmapped: 0, ownedBytes: 0, overBudget: false, removed: 0, failures: 0, deferred: 0 };
40
+ constructor(private readonly stateDir: string, readonly acpDir = resolveAntigravityAcpDirectory(), private readonly now = Date.now, private readonly isLive = live) {
49
41
  this.policyPath = path.join(stateDir, "cleanup.json");
50
- // Separate registries when the same OMP profile uses different GEMINI_HOME.
51
- const root = createHash("sha256").update(path.resolve(acpDir)).digest("hex").slice(0, 16);
52
- this.registryPath = path.join(stateDir, `cleanup-sessions-${root}.json`);
42
+ this.registryPath = path.join(stateDir, `cleanup-sessions-${createHash("sha256").update(path.resolve(acpDir)).digest("hex").slice(0, 16)}.json`);
53
43
  }
54
- // Stat-based cache: release/collect/status otherwise re-read this file on
55
- // every call. mtime plus size covers test rewrites within the same ms.
56
- private getPolicy(): CleanupPolicy {
57
- try {
58
- const stat = fs.statSync(this.policyPath);
59
- if (this.cachedPolicy && this.cachedPolicy.mtimeMs === stat.mtimeMs && this.cachedPolicy.size === stat.size) {
60
- return this.cachedPolicy.policy;
61
- }
62
- const policy = validate(JSON.parse(fs.readFileSync(this.policyPath, "utf8")));
63
- this.cachedPolicy = { mtimeMs: stat.mtimeMs, size: stat.size, policy };
64
- return policy;
65
- } catch (error: unknown) {
66
- if (isMissingFileError(error)) return { ...DEFAULT };
67
- throw error;
68
- }
69
- }
70
- configure(mode: CleanupMode, idleDays = this.getPolicy().idleDays) {
71
- saveCleanupPolicy(this.policyPath, { mode, idleDays });
72
- this.cachedPolicy = undefined;
73
- }
74
- status() { return { ...this.getPolicy(), file: this.policyPath, scope: "adapter-owned local ACP data" }; }
75
- start() {
76
- if (this.timer) return;
77
- this.collect();
78
- this.timer = setInterval(() => this.collect(), 15 * 60_000);
79
- this.timer.unref();
80
- }
81
- stop() { clearInterval(this.timer); this.timer = undefined; }
82
-
83
- private transaction<T>(action: (registry: Registry) => T): T {
84
- fs.mkdirSync(path.dirname(this.registryPath), { recursive: true, mode: 0o700 });
85
- // No retries/blocking sleeps in the inference path. Busy/malformed stores
86
- // fail closed; callers defer cleanup instead of risking another process.
87
- const release = lockSync(this.registryPath, { realpath: false, stale: 600_000 });
88
- try {
89
- let registry: Registry = { version: 1, sessions: [] };
90
- try { registry = JSON.parse(fs.readFileSync(this.registryPath, "utf8")) as Registry; }
91
- catch (error: unknown) { if (!isMissingFileError(error)) throw error; }
92
- if (registry.version !== 1 || !Array.isArray(registry.sessions) || !registry.sessions.every(r =>
93
- UUID.test(r.id) && typeof r.owned === "boolean" && Number.isFinite(r.lastUsed) && Array.isArray(r.leases) &&
94
- (r.replaced === undefined || typeof r.replaced === "boolean") &&
95
- (r.retiredFor === undefined || /^[a-f0-9]{64}$/.test(r.retiredFor)) &&
96
- r.leases.every(l => typeof l.token === "string" && Number.isSafeInteger(l.pid) && l.pid > 0 && Number.isSafeInteger(l.serverPid) && l.serverPid > 0))) {
97
- throw new Error("Invalid ACP cleanup registry; refusing deletion");
98
- }
99
- if (this.pendingTouches.size > 0) {
100
- for (const r of registry.sessions) {
101
- const touched = this.pendingTouches.get(r.id);
102
- if (touched !== undefined && touched > r.lastUsed) r.lastUsed = touched;
103
- }
104
- this.pendingTouches.clear();
44
+ configure(mode: CleanupMode, idleDays = loadCleanupPolicy(this.policyPath).idleDays) { saveCleanupPolicy(this.policyPath, { ...loadCleanupPolicy(this.policyPath), mode, idleDays }); }
45
+ budget(maxSessions: number, maxBytes: number) { saveCleanupPolicy(this.policyPath, { ...loadCleanupPolicy(this.policyPath), maxSessions, maxBytes }); }
46
+ async trackSource(id: string, file: string) {
47
+ // A managed root independent of cwd also covers OMP named profiles.
48
+ const root = path.resolve(this.stateDir, "..", "sessions");
49
+ const relative = path.relative(root, file);
50
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative) || !file.endsWith(".jsonl")) return;
51
+ const stat = await sourceRoot(root);
52
+ if (await sourceId(file) !== id) return;
53
+ await this.transaction(async registry => {
54
+ const mappings = JSON.parse(await afs.readFile(path.join(this.stateDir, "sessions.json"), "utf8"));
55
+ if (!Array.isArray(mappings)) throw new Error("Invalid mappings");
56
+ for (const record of registry.sessions) if (record.owned && mappings.some(m => m.piSessionId === id && m.acpSessionId === record.id)) {
57
+ record.ompSource = { id, file: path.resolve(file), root, device: stat.dev, inode: stat.ino };
58
+ delete record.sourceDeleted;
105
59
  }
106
- const result = action(registry);
107
- writeJsonAtomic(this.registryPath, registry, false);
108
- return result;
109
- } finally { release(); }
110
- }
111
- acquire(id: string, owned: boolean, serverPid: number): string {
112
- if (!UUID.test(id) || !Number.isSafeInteger(serverPid) || serverPid <= 0) throw new Error("Invalid ACP cleanup lease");
113
- return this.transaction(registry => {
114
- const timestamp = this.now();
115
- let record = registry.sessions.find(r => r.id === id);
116
- if (!record) { record = { id, owned, lastUsed: timestamp, leases: [] }; registry.sessions.push(record); }
117
- // Resuming an old/foreign session never upgrades its ownership.
118
- const token = randomUUID();
119
- record.leases.push({ token, pid: process.pid, serverPid });
120
- record.lastUsed = timestamp;
121
- this.lastTouched.set(id, timestamp);
122
- return token;
123
60
  });
124
61
  }
125
- release(token: string) {
126
- this.transaction(registry => { for (const r of registry.sessions) r.leases = r.leases.filter(l => l.token !== token); });
127
- this.collect();
128
- }
129
- touch(id: string) {
130
- const timestamp = this.now();
131
- const last = this.lastTouched.get(id);
132
- if (last !== undefined && timestamp - last < TOUCH_THROTTLE_MS) {
133
- this.pendingTouches.set(id, timestamp);
134
- return;
135
- }
136
- this.transaction(registry => {
137
- const r = registry.sessions.find(r => r.id === id);
138
- if (r) { r.lastUsed = timestamp; this.lastTouched.set(id, timestamp); }
62
+ status() { return { ...loadCleanupPolicy(this.policyPath), ...this.report, warning: this.report.overBudget ? "Soft budget exceeded; mapped and active sessions remain protected" : undefined, pendingLifecycleUpdates: this.intents.length, file: this.policyPath, scope: "adapter-owned local ACP data" }; }
63
+ start() { if (this.timer) return; void this.collect(); this.timer = setInterval(() => { void this.collect(); }, 15 * 60_000); this.timer.unref(); }
64
+ async stop() { clearInterval(this.timer); clearTimeout(this.nextBatch); this.timer = undefined; this.nextBatch = undefined; await this.collecting; await tails.get(this.registryPath)?.catch(() => {}); }
65
+ private transaction<T>(action: (r: Registry) => T | Promise<T>): Promise<T> {
66
+ const pending = (tails.get(this.registryPath) ?? Promise.resolve()).catch(() => {}).then(async () => {
67
+ await afs.mkdir(path.dirname(this.registryPath), { recursive: true, mode: 0o700 });
68
+ const release = await lock(this.registryPath, { realpath: false, stale: 600_000, retries: 0 });
69
+ try {
70
+ let r: Registry = { version: 1, sessions: [] };
71
+ try { r = JSON.parse(await afs.readFile(this.registryPath, "utf8")); } catch (e) { if (!isMissingFileError(e)) throw e; }
72
+ if (r.version !== 1 || !Array.isArray(r.sessions) || !r.sessions.every(v => UUID.test(v.id) && typeof v.owned === "boolean" && Number.isFinite(v.lastUsed) && Array.isArray(v.leases) &&
73
+ (v.replaced === undefined || typeof v.replaced === "boolean") && (v.orphanedAt === undefined || Number.isFinite(v.orphanedAt)) && (v.retiredFor === undefined || /^[a-f0-9]{64}$/.test(v.retiredFor)) &&
74
+ (v.sourceDeleted === undefined || typeof v.sourceDeleted === "boolean") &&
75
+ (v.ompSource === undefined || (typeof v.ompSource.id === "string" && typeof v.ompSource.file === "string" && typeof v.ompSource.root === "string" && Number.isFinite(v.ompSource.device) && Number.isFinite(v.ompSource.inode) && (v.ompSource.missingSince === undefined || Number.isFinite(v.ompSource.missingSince)))) &&
76
+ v.leases.every(l => typeof l.token === "string" && Number.isSafeInteger(l.pid) && l.pid > 0 && Number.isSafeInteger(l.serverPid) && l.serverPid > 0))) throw new Error("Invalid ACP cleanup registry; refusing deletion");
77
+ const actions = this.intents.slice(); for (const apply of actions) apply(r);
78
+ for (const v of r.sessions) if (this.touched.has(v.id)) v.lastUsed = Math.max(v.lastUsed, this.touched.get(v.id)!);
79
+ const result = await action(r), tmp = this.registryPath + "." + randomUUID() + ".tmp";
80
+ try { await afs.writeFile(tmp, JSON.stringify(r), { mode: 0o600, flag: "wx" }); await afs.rename(tmp, this.registryPath); }
81
+ finally { await afs.rm(tmp, { force: true }); }
82
+ this.intents.splice(0, actions.length); return result;
83
+ } finally { await release(); }
139
84
  });
85
+ tails.set(this.registryPath, pending);
86
+ void pending.finally(() => { if (tails.get(this.registryPath) === pending) tails.delete(this.registryPath); }).catch(() => {});
87
+ return pending;
140
88
  }
141
- retire(key: string, id: string) {
142
- this.transaction(registry => {
143
- const r = registry.sessions.find(r => r.id === id);
144
- if (r?.owned) { r.retiredFor = group(key); r.replaced = false; }
89
+ async acquire(id: string, owned: boolean, serverPid: number) {
90
+ if (!UUID.test(id) || !Number.isSafeInteger(serverPid) || serverPid <= 0) throw new Error("Invalid ACP cleanup lease");
91
+ return this.transaction(r => {
92
+ let v = r.sessions.find(v => v.id === id);
93
+ if (!v) { v = { id, owned, lastUsed: this.now(), leases: [] }; r.sessions.push(v); }
94
+ const token = randomUUID(); v.leases.push({ token, pid: process.pid, serverPid }); v.lastUsed = this.now(); delete v.orphanedAt;
95
+ this.touched.set(id, v.lastUsed); return token;
145
96
  });
146
97
  }
147
- confirm(key: string, replacement: string) {
148
- this.transaction(registry => {
149
- for (const r of registry.sessions) if (r.id !== replacement && r.retiredFor === group(key)) r.replaced = true;
150
- });
151
- this.collect();
98
+ private async intent(action: (r: Registry) => void) {
99
+ if (this.intents.length >= 1024) throw new Error("Lifecycle retry queue full; preserving files");
100
+ this.intents.push(action); try { await this.transaction(() => {}); } catch (e) { this.report.failures++; throw e; }
152
101
  }
153
- collect(): number {
154
- try {
155
- const policy = this.getPolicy();
156
- if (policy.mode === "off") return 0;
157
- return this.transaction(registry => {
158
- let removed = 0;
159
- // Verify the cleanup root once per collect, lazily on the first
160
- // eligible session instead of once per removed session.
161
- let dirs: { conversations: string; brain: string } | undefined;
162
- registry.sessions = registry.sessions.filter(r => {
163
- r.leases = r.leases.filter(l => this.isLive(l.pid) || this.isLive(l.serverPid));
164
- if (!r.owned && r.leases.length === 0) return false;
165
- const eligible = r.owned && r.leases.length === 0 && (r.replaced === true ||
166
- (policy.mode === "timeout" && this.now() - r.lastUsed >= policy.idleDays * 86_400_000));
167
- if (!eligible) return true;
102
+ async release(token: string, background = false) { await this.intent(r => { for (const v of r.sessions) v.leases = v.leases.filter(l => l.token !== token); }); if (background) { void this.collect(); return 0; } return this.collect(); }
103
+ async touch(id: string) { const last = this.touched.get(id); this.touched.set(id, this.now()); if (last !== undefined && this.now() - last < 60_000) return; await this.transaction(() => {}); }
104
+ retire(key: string, id: string) { return this.intent(r => { const v = r.sessions.find(v => v.id === id); if (v?.owned) { v.retiredFor = group(key); v.replaced = false; } }); }
105
+ async confirm(key: string, replacement: string, background = false) { await this.intent(r => { for (const v of r.sessions) if (v.id !== replacement && v.retiredFor === group(key)) v.replaced = true; }); if (background) { void this.collect(); return 0; } return this.collect(); }
106
+ collect(): Promise<number> {
107
+ if (this.collecting) return this.collecting;
108
+ const pending = this.collectOnce().catch(() => { this.report.failures++; return 0; }); this.collecting = pending;
109
+ void pending.finally(() => {
110
+ if (this.collecting === pending) this.collecting = undefined;
111
+ if (this.timer && this.report.deferred > 0 && !this.nextBatch) {
112
+ this.nextBatch = setTimeout(() => { this.nextBatch = undefined; void this.collect(); }, 1000); this.nextBatch.unref();
113
+ }
114
+ }); return pending;
115
+ }
116
+ private async collectOnce() {
117
+ const policy = loadCleanupPolicy(this.policyPath);
118
+ return this.transaction(async registry => {
119
+ let mappings: Array<{ piSessionId: string; acpSessionId: string }> = [];
120
+ try { const p = JSON.parse(await afs.readFile(path.join(this.stateDir, "sessions.json"), "utf8")); if (!Array.isArray(p)) throw new Error("Invalid mappings"); mappings = p; } catch (e) { if (!isMissingFileError(e)) throw e; }
121
+ const mapped = new Set(mappings.map(v => v.acpSessionId));
122
+ const report = { owned: 0, active: 0, mapped: 0, unmapped: 0, ownedBytes: 0, overBudget: false, removed: 0, failures: this.report.failures, deferred: 0 };
123
+ let dirs: { conversations: string; brain: string } | undefined;
124
+ const owned = [];
125
+ const sourceScans = new Map<string, Promise<Map<string, string>>>();
126
+ for (const v of registry.sessions) {
127
+ v.leases = v.leases.filter(l => this.isLive(l.pid) || this.isLive(l.serverPid)); if (!v.owned) continue;
128
+ if (policy.mode !== "off" && v.ompSource && !v.leases.length) {
129
+ // Re-prove eligibility even when the mapping was removed before a
130
+ // crash, or a previous deletion batch left this record pending.
131
+ delete v.sourceDeleted;
168
132
  try {
169
- dirs ??= this.verifyCleanupRoot();
170
- this.removeFiles(r.id, dirs);
171
- this.lastTouched.delete(r.id);
172
- this.pendingTouches.delete(r.id);
173
- removed++;
174
- return false;
175
- }
176
- catch { return true; } // Keep ownership for a later retry; never fail a model answer.
177
- });
178
- return removed;
179
- });
180
- } catch { return 0; }
133
+ const source = v.ompSource, root = path.resolve(this.stateDir, "..", "sessions");
134
+ const relative = path.relative(root, source.file);
135
+ if (source.root !== root || !relative || relative.startsWith("..") || path.isAbsolute(relative)) throw new Error("Invalid source scope");
136
+ const stat = await sourceRoot(root);
137
+ if (stat.dev !== source.device || stat.ino !== source.inode) throw new Error("OMP storage changed; preserving session");
138
+ let missing = false;
139
+ try { await afs.lstat(source.file); } catch (e) { if (!isMissingFileError(e)) throw e; missing = true; }
140
+ if (!missing) { delete source.missingSince; }
141
+ else {
142
+ if (!sourceScans.has(root)) sourceScans.set(root, findSources(root));
143
+ const moved = (await sourceScans.get(root)!).get(source.id);
144
+ if (moved) { source.file = moved; delete source.missingSince; }
145
+ else if (source.missingSince === undefined) source.missingSince = this.now();
146
+ else if (this.now() - source.missingSince >= 60000) {
147
+ const finalRoot = await sourceRoot(root);
148
+ if (finalRoot.dev !== source.device || finalRoot.ino !== source.inode) throw new Error("OMP storage changed during scan");
149
+ let restored = false;
150
+ try { await afs.lstat(source.file); restored = true; delete source.missingSince; }
151
+ catch (e) { if (!isMissingFileError(e)) throw e; }
152
+ if (!restored) {
153
+ // Recheck under the mapping store's own lock. A newer ACP
154
+ // binding must never be removed by an old cleanup snapshot.
155
+ await new AcpSessionStore(path.join(this.stateDir, "sessions.json")).removeIfMatches(source.id, v.id);
156
+ const latest = JSON.parse(await afs.readFile(path.join(this.stateDir, "sessions.json"), "utf8").catch(e => { if (isMissingFileError(e)) return "[]"; throw e; }));
157
+ if (!Array.isArray(latest)) throw new Error("Invalid mappings");
158
+ if (!latest.some(m => m.acpSessionId === v.id)) { mapped.delete(v.id); v.sourceDeleted = true; }
159
+ }
160
+ }
161
+ }
162
+ } catch { report.failures++; }
163
+ }
164
+ report.owned++; if (v.leases.length) report.active++;
165
+ if (mapped.has(v.id)) { report.mapped++; delete v.orphanedAt; } else { report.unmapped++; v.orphanedAt ??= this.now(); }
166
+ let size = 0; try { dirs ??= await this.verifyRoot(); for (const target of this.targets(v.id, dirs)) size += await this.inspect(target); } catch { report.failures++; }
167
+ report.ownedBytes += size; owned.push({ v, size });
168
+ }
169
+ const over = () => Boolean((policy.maxSessions && report.owned > policy.maxSessions) || (policy.maxBytes && report.ownedBytes > policy.maxBytes));
170
+ report.overBudget = over();
171
+ if (policy.mode !== "off") for (const { v, size } of owned.sort((a, b) => a.v.lastUsed - b.v.lastUsed)) {
172
+ if (mapped.has(v.id) || v.leases.length) continue;
173
+ const expired = policy.mode === "timeout" && (this.now() - v.lastUsed >= policy.idleDays * 86_400_000 || (over() && this.now() - v.orphanedAt! >= (policy.orphanGraceDays ?? 1) * 86_400_000));
174
+ if (!v.replaced && !v.sourceDeleted && !expired) continue;
175
+ if (report.removed >= (policy.batchSize ?? 8)) { report.deferred++; continue; }
176
+ try {
177
+ dirs ??= await this.verifyRoot(); const targets = this.targets(v.id, dirs);
178
+ for (const target of targets) await this.inspect(target);
179
+ for (const target of targets) await afs.rm(target, { recursive: true, force: true });
180
+ registry.sessions = registry.sessions.filter(r => r !== v); this.touched.delete(v.id);
181
+ report.removed++; report.owned--; report.unmapped--; report.ownedBytes -= size;
182
+ } catch { report.failures++; }
183
+ }
184
+ registry.sessions = registry.sessions.filter(v => v.owned || v.leases.length);
185
+ report.overBudget = over(); this.report = report; return report.removed;
186
+ });
181
187
  }
182
- private verifyCleanupRoot(): { conversations: string; brain: string } {
183
- const root = path.resolve(this.acpDir);
184
- if (fs.realpathSync(root) !== root) throw new Error("Symlinked ACP root; refusing cleanup");
185
- const conversations = path.join(root, "conversations");
186
- const brain = path.join(root, "brain");
187
- for (const parent of [conversations, brain]) {
188
- try { if (fs.realpathSync(parent) !== parent) throw new Error("Symlinked cleanup directory"); }
189
- catch (error: unknown) { if (!isMissingFileError(error)) throw error; }
190
- }
191
- return { conversations, brain };
188
+ private targets(id: string, d: { conversations: string; brain: string }) { return [".db", ".db-wal", ".db-shm", ".db-journal", ".meta"].map(s => path.join(d.conversations, id + s)).concat(path.join(d.brain, id)); }
189
+ private async verifyRoot() {
190
+ const root = path.resolve(this.acpDir); if (await afs.realpath(root) !== root) throw new Error("Symlinked ACP root");
191
+ const dirs = { conversations: path.join(root, "conversations"), brain: path.join(root, "brain") };
192
+ for (const d of Object.values(dirs)) try { if (await afs.realpath(d) !== d) throw new Error("Symlinked cleanup directory"); } catch (e) { if (!isMissingFileError(e)) throw e; }
193
+ return dirs;
192
194
  }
193
- private removeFiles(id: string, dirs: { conversations: string; brain: string }) {
194
- const targets = [path.join(dirs.conversations, `${id}.db`), path.join(dirs.conversations, `${id}.db-wal`),
195
- path.join(dirs.conversations, `${id}.db-shm`), path.join(dirs.conversations, `${id}.db-journal`),
196
- path.join(dirs.conversations, `${id}.meta`), path.join(dirs.brain, id)];
197
- const inspect = (file: string) => {
198
- let stat: fs.Stats;
199
- try { stat = fs.lstatSync(file); } catch (error: unknown) { if (isMissingFileError(error)) return; throw error; }
200
- if (stat.isSymbolicLink() || (!stat.isDirectory() && !stat.isFile())) throw new Error("Unsafe cleanup target");
201
- if (stat.isDirectory()) for (const child of fs.readdirSync(file)) inspect(path.join(file, child));
202
- };
203
- for (const target of targets) inspect(target);
204
- for (const target of targets) fs.rmSync(target, { recursive: true, force: true });
195
+ private async inspect(file: string): Promise<number> {
196
+ let s: import("node:fs").Stats; try { s = await afs.lstat(file); } catch (e) { if (isMissingFileError(e)) return 0; throw e; }
197
+ if (s.isSymbolicLink() || (!s.isDirectory() && !s.isFile())) throw new Error("Unsafe cleanup target");
198
+ if (!s.isDirectory()) return s.size;
199
+ let size = 0; for (const f of await afs.readdir(file)) size += await this.inspect(path.join(file, f)); return size;
205
200
  }
206
201
  }
@@ -0,0 +1,98 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { setTimeout as delay } from "node:timers/promises";
5
+ import { lock } from "proper-lockfile";
6
+ import { resolvePiAgentDir } from "pi-antigravity-acp-provider/src/config.ts";
7
+
8
+ interface SavedSessionRecord {
9
+ piSessionId: string; acpSessionId: string; acpModelId: string; cwd: string;
10
+ messageCount: number; historyFingerprint: string; lastActive: number;
11
+ expectedAssistantFingerprint?: string;
12
+ ompCancelledCheckpoint?: boolean; ompCancelledHadOutput?: boolean;
13
+ ompCheckpointVersion?: 1; ompInFlight?: boolean; ompExpectedAssistantHasOutput?: boolean;
14
+ }
15
+ const tails = new Map<string, Promise<unknown>>();
16
+
17
+ // Serialize instances in this process, then merge under the same cross-process
18
+ // lock used by older releases. Callers must await writes at checkpoint boundaries.
19
+ export class AcpSessionStore {
20
+ readonly file: string;
21
+ constructor(file = path.join(resolvePiAgentDir(), "antigravity-acp-provider", "sessions.json")) {
22
+ this.file = path.resolve(file);
23
+ }
24
+ private enqueue<T>(work: () => Promise<T>): Promise<T> {
25
+ const result = (tails.get(this.file) ?? Promise.resolve()).catch(() => {}).then(work);
26
+ tails.set(this.file, result);
27
+ void result.finally(() => { if (tails.get(this.file) === result) tails.delete(this.file); }).catch(() => {});
28
+ return result;
29
+ }
30
+ async flush(): Promise<void> { await tails.get(this.file); }
31
+ get(id: string): Promise<SavedSessionRecord | undefined> {
32
+ return this.enqueue(async () => (await this.read()).find(record => record.piSessionId === id &&
33
+ Date.now() - record.lastActive <= 30 * 24 * 60 * 60_000));
34
+ }
35
+ save(record: SavedSessionRecord): Promise<void> {
36
+ const captured = { ...record };
37
+ return this.update(async () => {
38
+ const records = (await this.read()).filter(value => value.piSessionId !== captured.piSessionId);
39
+ records.push(captured);
40
+ records.sort((a, b) => b.lastActive - a.lastActive);
41
+ await this.write(records.slice(0, 256));
42
+ });
43
+ }
44
+ remove(id: string): Promise<void> {
45
+ return this.update(async () => this.write((await this.read()).filter(record => record.piSessionId !== id)));
46
+ }
47
+ removeIfMatches(id: string, acpSessionId: string): Promise<boolean> {
48
+ let removed = false;
49
+ return this.update(async () => {
50
+ const records = await this.read();
51
+ removed = records.some(record => record.piSessionId === id && record.acpSessionId === acpSessionId);
52
+ if (removed) await this.write(records.filter(record => record.piSessionId !== id || record.acpSessionId !== acpSessionId));
53
+ }).then(() => removed);
54
+ }
55
+ clear(): Promise<void> { return this.update(() => fs.rm(this.file, { force: true })); }
56
+ private update(work: () => Promise<void>): Promise<void> {
57
+ return this.enqueue(async () => {
58
+ await fs.mkdir(path.dirname(this.file), { recursive: true, mode: 0o700 });
59
+ const deadline = Date.now() + 5000;
60
+ let compromised: Error | undefined;
61
+ let release: (() => Promise<void>) | undefined;
62
+ for (;;) {
63
+ try {
64
+ release = await lock(this.file, { realpath: false, stale: 30_000, retries: 0,
65
+ onCompromised: (error: Error) => { compromised = error; } });
66
+ break;
67
+ } catch (error) {
68
+ if ((error as NodeJS.ErrnoException).code !== "ELOCKED" || Date.now() >= deadline) throw error;
69
+ await delay(10);
70
+ }
71
+ }
72
+ try { if (compromised) throw compromised; await work(); if (compromised) throw compromised; }
73
+ finally { await release(); }
74
+ });
75
+ }
76
+ private async read(): Promise<SavedSessionRecord[]> {
77
+ let raw: string;
78
+ try { raw = await fs.readFile(this.file, "utf8"); }
79
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
80
+ const parsed: unknown = JSON.parse(raw);
81
+ if (!Array.isArray(parsed)) throw new Error("Invalid ACP session registry; refusing to overwrite it");
82
+ return parsed.filter((record): record is SavedSessionRecord => Boolean(record) && typeof record === "object" &&
83
+ ["piSessionId", "acpSessionId", "acpModelId", "cwd", "historyFingerprint"].every(key => typeof record[key] === "string") &&
84
+ Number.isSafeInteger(record.messageCount) && record.messageCount >= 0 && Number.isFinite(record.lastActive) &&
85
+ (record.expectedAssistantFingerprint === undefined || typeof record.expectedAssistantFingerprint === "string") &&
86
+ (record.ompCheckpointVersion === undefined || record.ompCheckpointVersion === 1) &&
87
+ ["ompInFlight", "ompExpectedAssistantHasOutput", "ompCancelledCheckpoint", "ompCancelledHadOutput"].every(key =>
88
+ record[key] === undefined || typeof record[key] === "boolean"));
89
+ }
90
+ private async write(records: SavedSessionRecord[]): Promise<void> {
91
+ if (!records.length) { await fs.rm(this.file, { force: true }); return; }
92
+ const temporary = `${this.file}.${randomUUID()}.tmp`;
93
+ try {
94
+ await fs.writeFile(temporary, JSON.stringify(records) + "\n", { mode: 0o600, flag: "wx" });
95
+ await fs.rename(temporary, this.file);
96
+ } finally { await fs.rm(temporary, { force: true }); }
97
+ }
98
+ }
@@ -0,0 +1,63 @@
1
+ import { types } from "node:util";
2
+
3
+ const OBJECT = Symbol("object"), NULL_OBJECT = Symbol("null object"), ARRAY = Symbol("array"), FUNCTION = Symbol("function");
4
+ const MAX_NODES = 32768, MAX_TOKENS = 131072, MAX_CHARS = 2 * 1024 * 1024;
5
+ const FUNCTION_PROTOTYPES = new Set([Function.prototype, Object.getPrototypeOf(async () => {}),
6
+ Object.getPrototypeOf(function* () {}), Object.getPrototypeOf(async function* () {})]);
7
+
8
+ // One entry per cache, owned by one runtime. Primitive tokens are independent
9
+ // of host container identity. Never retain executable tool closures.
10
+ export function createStructuredFingerprintMemo() {
11
+ let tokens: unknown[] | undefined, digest: string | undefined;
12
+ function visit(value: any, put: (token: unknown) => void, budget: { nodes: number; chars: number }, seen: Set<object>): void {
13
+ if (++budget.nodes > MAX_NODES) throw new Error("snapshot node budget");
14
+ if (typeof value === "function") {
15
+ if (types.isProxy(value) || !FUNCTION_PROTOTYPES.has(Object.getPrototypeOf(value)) || "toJSON" in value) throw new Error("exotic function");
16
+ put(FUNCTION); return; // Canonical JSON emits null for ordinary functions.
17
+ }
18
+ if (value === null || typeof value !== "object") {
19
+ if (typeof value === "symbol" || typeof value === "bigint") throw new Error("unsupported primitive");
20
+ if (typeof value === "string" && (budget.chars += value.length) > MAX_CHARS) throw new Error("snapshot string budget");
21
+ put(value); return;
22
+ }
23
+ if (types.isProxy(value)) throw new Error("proxy");
24
+ const array = Array.isArray(value), prototype = Object.getPrototypeOf(value);
25
+ if (seen.has(value) || (array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) ||
26
+ Object.getOwnPropertySymbols(value).length) throw new Error("unsupported container");
27
+ seen.add(value);
28
+ // Schema projection examines non-enumerable properties too. Capture both
29
+ // names and enumerable flags, not just JSON-visible object fields.
30
+ const keys = Object.getOwnPropertyNames(value);
31
+ if (keys.length > MAX_NODES) throw new Error("snapshot key budget");
32
+ if (array && (keys.length !== value.length + 1 || keys.at(-1) !== "length")) throw new Error("custom/sparse array");
33
+ put(array ? ARRAY : prototype === null ? NULL_OBJECT : OBJECT); put(keys.length);
34
+ for (let i = 0; i < keys.length; i++) {
35
+ const key = keys[i];
36
+ if (array && i < keys.length - 1 && key !== String(i)) throw new Error("sparse array");
37
+ const descriptor = Object.getOwnPropertyDescriptor(value, key)!;
38
+ if (!("value" in descriptor)) throw new Error("accessor");
39
+ if ((budget.chars += key.length) > MAX_CHARS) throw new Error("snapshot string budget");
40
+ put(key); put(descriptor.enumerable); visit(descriptor.value, put, budget, seen);
41
+ }
42
+ }
43
+ const clear = () => { tokens = undefined; digest = undefined; };
44
+ const memo = (value: unknown, compute: () => string): string => {
45
+ if (tokens) {
46
+ let index = 0;
47
+ try {
48
+ visit(value, token => { if (!Object.is(token, tokens![index++])) throw new Error("changed"); }, { nodes: 0, chars: 0 }, new Set());
49
+ if (index === tokens.length) return digest!;
50
+ } catch { /* Revalidate/recompute every changed or unsupported payload. */ }
51
+ }
52
+ clear();
53
+ let next: unknown[] | undefined = [];
54
+ try {
55
+ visit(value, token => { if (next!.length >= MAX_TOKENS) throw new Error("snapshot token budget"); next!.push(token); },
56
+ { nodes: 0, chars: 0 }, new Set());
57
+ } catch { next = undefined; }
58
+ const result = compute();
59
+ tokens = next; digest = next ? result : undefined;
60
+ return result;
61
+ };
62
+ return Object.assign(memo, { clear });
63
+ }