forked from NoeFabris/opencode-antigravity-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsignature-cache.ts
More file actions
473 lines (407 loc) · 12.5 KB
/
Copy pathsignature-cache.ts
File metadata and controls
473 lines (407 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/**
* Signature cache for persisting thinking block signatures to disk.
*
* Features (based on LLM-API-Key-Proxy's ProviderCache):
* - Dual-TTL system: short memory TTL, longer disk TTL
* - Background disk persistence with batched writes
* - Atomic writes with temp file + move pattern
* - Automatic cleanup of expired entries
*
* Cache key format: `${sessionId}:${modelId}`
*/
import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, unlinkSync } from "node:fs";
import { join, dirname } from "node:path";
import { homedir } from "node:os";
import { tmpdir } from "node:os";
import type { SignatureCacheConfig } from "../config";
import { ensureGitignoreSync } from "../storage";
// =============================================================================
// Types
// =============================================================================
interface CacheEntry {
value: string;
timestamp: number;
/** Full thinking text content (optional, for recovery) */
thinkingText?: string;
/** Preview of the thinking text for debugging */
textPreview?: string;
/** Tool call IDs associated with this thinking block */
toolIds?: string[];
}
interface CacheData {
version: "1.0";
memory_ttl_seconds: number;
disk_ttl_seconds: number;
entries: Record<string, CacheEntry>;
statistics: {
memory_hits: number;
disk_hits: number;
misses: number;
writes: number;
last_write: number;
};
}
interface CacheStats {
memoryHits: number;
diskHits: number;
misses: number;
writes: number;
memoryEntries: number;
dirty: boolean;
diskEnabled: boolean;
}
/**
* Full thinking content with signature (for recovery)
*/
export interface ThinkingCacheData {
text: string;
signature: string;
toolIds?: string[];
}
// =============================================================================
// Path Utilities
// =============================================================================
function getConfigDir(): string {
const platform = process.platform;
if (platform === "win32") {
return join(process.env.APPDATA || join(homedir(), "AppData", "Roaming"), "opencode");
}
const xdgConfig = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
return join(xdgConfig, "opencode");
}
function getCacheFilePath(): string {
return join(getConfigDir(), "antigravity-signature-cache.json");
}
// =============================================================================
// Signature Cache Class
// =============================================================================
export class SignatureCache {
// In-memory cache: key -> entry with signature and optional thinking text
private cache: Map<string, CacheEntry> = new Map();
// Configuration
private memoryTtlMs: number;
private diskTtlMs: number;
private writeIntervalMs: number;
private cacheFilePath: string;
private enabled: boolean;
// State
private dirty: boolean = false;
private writeTimer: ReturnType<typeof setInterval> | null = null;
private cleanupTimer: ReturnType<typeof setInterval> | null = null;
// Statistics
private stats = {
memoryHits: 0,
diskHits: 0,
misses: 0,
writes: 0,
};
constructor(config: SignatureCacheConfig) {
this.enabled = config.enabled;
this.memoryTtlMs = config.memory_ttl_seconds * 1000;
this.diskTtlMs = config.disk_ttl_seconds * 1000;
this.writeIntervalMs = config.write_interval_seconds * 1000;
this.cacheFilePath = getCacheFilePath();
if (this.enabled) {
this.loadFromDisk();
this.startBackgroundTasks();
}
}
// ===========================================================================
// Public API
// ===========================================================================
/**
* Generate a cache key from sessionId and modelId.
*/
static makeKey(sessionId: string, modelId: string): string {
return `${sessionId}:${modelId}`;
}
/**
* Store a signature in the cache.
*/
store(key: string, signature: string): void {
if (!this.enabled) return;
this.cache.set(key, {
value: signature,
timestamp: Date.now(),
});
this.dirty = true;
}
/**
* Retrieve a signature from the cache.
* Returns null if not found or expired.
*/
retrieve(key: string): string | null {
if (!this.enabled) return null;
const entry = this.cache.get(key);
if (entry) {
const age = Date.now() - entry.timestamp;
if (age <= this.memoryTtlMs) {
this.stats.memoryHits++;
return entry.value;
}
// Expired from memory, remove it
this.cache.delete(key);
}
this.stats.misses++;
return null;
}
/**
* Check if a key exists in the cache (without updating stats).
*/
has(key: string): boolean {
if (!this.enabled) return false;
const entry = this.cache.get(key);
if (!entry) return false;
const age = Date.now() - entry.timestamp;
return age <= this.memoryTtlMs;
}
// ===========================================================================
// Full Thinking Cache (ported from LLM-API-Key-Proxy)
// ===========================================================================
/**
* Store full thinking content with signature.
* This enables recovery even after thinking text is stripped by compaction.
*
* Port of LLM-API-Key-Proxy's _cache_thinking()
*/
storeThinking(
key: string,
thinkingText: string,
signature: string,
toolIds?: string[],
): void {
if (!this.enabled || !thinkingText || !signature) return;
this.cache.set(key, {
value: signature,
timestamp: Date.now(),
thinkingText,
textPreview: thinkingText.slice(0, 100),
toolIds,
});
this.dirty = true;
}
/**
* Retrieve full thinking content by key.
* Returns null if not found or expired.
*/
retrieveThinking(key: string): ThinkingCacheData | null {
if (!this.enabled) return null;
const entry = this.cache.get(key);
if (!entry || !entry.thinkingText) return null;
const age = Date.now() - entry.timestamp;
if (age > this.memoryTtlMs) {
this.cache.delete(key);
return null;
}
this.stats.memoryHits++;
return {
text: entry.thinkingText,
signature: entry.value,
toolIds: entry.toolIds,
};
}
/**
* Check if full thinking content exists for a key.
*/
hasThinking(key: string): boolean {
if (!this.enabled) return false;
const entry = this.cache.get(key);
if (!entry || !entry.thinkingText) return false;
const age = Date.now() - entry.timestamp;
return age <= this.memoryTtlMs;
}
/**
* Get cache statistics.
*/
getStats(): CacheStats {
return {
...this.stats,
memoryEntries: this.cache.size,
dirty: this.dirty,
diskEnabled: this.enabled,
};
}
/**
* Manually trigger a disk save.
*/
async flush(): Promise<boolean> {
if (!this.enabled) return true;
return this.saveToDisk();
}
/**
* Graceful shutdown: stop timers and flush to disk.
*/
shutdown(): void {
if (this.writeTimer) {
clearInterval(this.writeTimer);
this.writeTimer = null;
}
if (this.cleanupTimer) {
clearInterval(this.cleanupTimer);
this.cleanupTimer = null;
}
if (this.dirty && this.enabled) {
this.saveToDisk();
}
}
// ===========================================================================
// Disk Operations
// ===========================================================================
/**
* Load cache from disk file with TTL validation.
*/
private loadFromDisk(): void {
try {
if (!existsSync(this.cacheFilePath)) {
return;
}
const content = readFileSync(this.cacheFilePath, "utf-8");
const data = JSON.parse(content) as CacheData;
if (data.version !== "1.0") {
// Version mismatch - silently start fresh
return;
}
const now = Date.now();
let loaded = 0;
let expired = 0;
for (const [key, entry] of Object.entries(data.entries)) {
const age = now - entry.timestamp;
if (age <= this.diskTtlMs) {
this.cache.set(key, {
value: entry.value,
timestamp: entry.timestamp,
});
loaded++;
} else {
expired++;
}
}
// Silently load - no console output
} catch {
// Silently start fresh on any error (corruption, file not found, etc.)
}
}
/**
* Save cache to disk with atomic write pattern.
* Merges with existing disk entries that haven't expired.
*/
private saveToDisk(): boolean {
try {
// Ensure directory exists
const dir = dirname(this.cacheFilePath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
ensureGitignoreSync(dir);
const now = Date.now();
// Step 1: Load existing disk entries (if any)
let existingEntries: Record<string, CacheEntry> = {};
if (existsSync(this.cacheFilePath)) {
try {
const content = readFileSync(this.cacheFilePath, "utf-8");
const data = JSON.parse(content) as CacheData;
existingEntries = data.entries || {};
} catch {
// Start fresh if corrupted
}
}
// Step 2: Filter existing disk entries by disk_ttl
const validDiskEntries: Record<string, CacheEntry> = {};
for (const [key, entry] of Object.entries(existingEntries)) {
const age = now - entry.timestamp;
if (age <= this.diskTtlMs) {
validDiskEntries[key] = entry;
}
}
// Step 3: Merge - memory entries take precedence
const mergedEntries: Record<string, CacheEntry> = { ...validDiskEntries };
for (const [key, entry] of this.cache.entries()) {
mergedEntries[key] = {
value: entry.value,
timestamp: entry.timestamp,
};
}
// Step 4: Build cache data
const cacheData: CacheData = {
version: "1.0",
memory_ttl_seconds: this.memoryTtlMs / 1000,
disk_ttl_seconds: this.diskTtlMs / 1000,
entries: mergedEntries,
statistics: {
memory_hits: this.stats.memoryHits,
disk_hits: this.stats.diskHits,
misses: this.stats.misses,
writes: this.stats.writes + 1,
last_write: now,
},
};
// Step 5: Atomic write (temp file + rename)
const tmpPath = join(tmpdir(), `antigravity-cache-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`);
writeFileSync(tmpPath, JSON.stringify(cacheData, null, 2), "utf-8");
try {
renameSync(tmpPath, this.cacheFilePath);
} catch {
// On Windows, rename across volumes may fail
// Fall back to copy + delete
writeFileSync(this.cacheFilePath, readFileSync(tmpPath));
try {
unlinkSync(tmpPath);
} catch {
// Ignore cleanup errors
}
}
this.stats.writes++;
this.dirty = false;
return true;
} catch {
// Silently fail - disk cache is optional
return false;
}
}
// ===========================================================================
// Background Tasks
// ===========================================================================
/**
* Start background write and cleanup timers.
*/
private startBackgroundTasks(): void {
// Periodic disk writes
this.writeTimer = setInterval(() => {
if (this.dirty) {
this.saveToDisk();
}
}, this.writeIntervalMs);
// Periodic memory cleanup (every 30 minutes)
this.cleanupTimer = setInterval(() => {
this.cleanupExpired();
}, 30 * 60 * 1000);
}
/**
* Remove expired entries from memory.
*/
private cleanupExpired(): void {
const now = Date.now();
let cleaned = 0;
for (const [key, entry] of this.cache.entries()) {
const age = now - entry.timestamp;
if (age > this.memoryTtlMs) {
this.cache.delete(key);
cleaned++;
}
}
// Silently clean - no console output
}
}
// =============================================================================
// Factory Function
// =============================================================================
/**
* Create a signature cache with the given configuration.
* Returns null if caching is disabled.
*/
export function createSignatureCache(config: SignatureCacheConfig | undefined): SignatureCache | null {
if (!config || !config.enabled) {
return null;
}
return new SignatureCache(config);
}