pi-tensorix-provider 1.0.21 → 1.0.23
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/AGENTS.md +1 -0
- package/CHANGELOG.md +7 -0
- package/README.md +16 -0
- package/index.ts +34 -12
- package/package.json +17 -12
- package/scripts/test-pi-compat.mjs +2 -2
- package/sync-policy.ts +309 -0
- package/tests/quiet-startup-sync.test.ts +261 -0
- package/tests/sync-policy.test.ts +259 -0
- package/vitest.config.ts +10 -0
- package/bun.lock +0 -316
package/AGENTS.md
CHANGED
|
@@ -19,6 +19,7 @@ When a model needs overrides, new properties, or corrections, edit the appropria
|
|
|
19
19
|
| `patch.json` | Per-model overrides keyed by model ID. Add reasoning flags, compat settings, pricing corrections, thinking level maps, etc. Applied on top of `models.json` at runtime and for README generation. |
|
|
20
20
|
| `custom-models.json` | Models that don't exist in the provider API (hidden models, router endpoints, cross-provider aliases). Merged after patch. Format: array of full model objects (same schema as `models.json` entries). |
|
|
21
21
|
| `index.ts` | Provider extension code. |
|
|
22
|
+
| `sync-policy.ts` | Quiet startup sync policy (TTL, key fingerprint, cross-process lock). Provider-agnostic and shared verbatim across pi-*-provider repos — keep it free of provider specifics. |
|
|
22
23
|
| `scripts/update-models.js` | The sync script itself (edit only if changing how models are fetched/transformed). |
|
|
23
24
|
|
|
24
25
|
## Data Flow
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.0.23
|
|
4
|
+
|
|
5
|
+
- Quiet startup sync: background `/v1/models` revalidation runs only with an API key, only when the disk cache is older than 1 hour (`PI_PROVIDER_SYNC_TTL_MS`, `0` = always), missing, or fetched with a different key, and only in one pi process at a time (lock file next to the cache). Failed refreshes back off for 5 minutes; sessions that skip adopt a cache refreshed by another process.
|
|
6
|
+
- Never store the API key: key changes are detected via a salted sha256 fingerprint in `cache/tensorix-models.sync.json`. The cache file format is unchanged.
|
|
7
|
+
- Write the model cache atomically and swallow API key resolution failures in `session_start`.
|
|
8
|
+
- Add vitest coverage for the sync policy and the session_start integration.
|
|
9
|
+
|
|
3
10
|
## 1.0.20
|
|
4
11
|
|
|
5
12
|
- Validate provider registration and session lifecycle against Pi 1.0.0; update the pinned development SDK.
|
package/README.md
CHANGED
|
@@ -21,6 +21,7 @@ _32 models — DeepSeek, Kimi, GLM, Qwen, MiniMax, Llama — all **free** for [p
|
|
|
21
21
|
- **Tool use** - Function calling support
|
|
22
22
|
- **Streaming** - Real-time token streaming
|
|
23
23
|
- **Free tier** - All models available at no cost during preview
|
|
24
|
+
- **Quiet live model sync** - Models refresh from the Tensorix API in the background, at most hourly and by one pi process at a time ([details](#model-sync))
|
|
24
25
|
|
|
25
26
|
## Available Models
|
|
26
27
|
|
|
@@ -117,6 +118,7 @@ Get your API key from [tensorix.ai](https://tensorix.ai).
|
|
|
117
118
|
| Variable | Required | Description |
|
|
118
119
|
|----------|----------|-------------|
|
|
119
120
|
| `TENSORIX_API_KEY` | No | Your Tensorix API key (fallback if not in auth.json) |
|
|
121
|
+
| `PI_PROVIDER_SYNC_TTL_MS` | No | Model sync freshness window in ms (default `3600000`; `0` = revalidate every session start) |
|
|
120
122
|
|
|
121
123
|
## Configuration
|
|
122
124
|
|
|
@@ -166,6 +168,20 @@ Tensorix provides an OpenAI-compatible API proxy. Key notes:
|
|
|
166
168
|
> context lengths, or reasoning flags. `patch.json` provides these based on
|
|
167
169
|
> known model specifications and E2E testing.
|
|
168
170
|
|
|
171
|
+
## Model sync
|
|
172
|
+
|
|
173
|
+
Startup never waits on the network. pi starts with the cached catalog (`~/.pi/agent/cache/tensorix-models.json`,
|
|
174
|
+
falling back to the bundled `models.json`) and revalidates against `/v1/models` in the background — only when:
|
|
175
|
+
|
|
176
|
+
- a Tensorix API key is configured (no key, no request),
|
|
177
|
+
- the cache is older than 1 hour, missing, or was fetched with a different API key, and
|
|
178
|
+
- no other pi process is already refreshing it (a `tensorix-models.lock` file next to the cache).
|
|
179
|
+
|
|
180
|
+
So `/new`, `/reload`, `pi -p` and fan-out child agents share one cache instead of each calling the API; a
|
|
181
|
+
session that skips the fetch still picks up a cache another process refreshed. A failed refresh is retried after
|
|
182
|
+
5 minutes at the earliest. `PI_PROVIDER_SYNC_TTL_MS` changes the window (`0` revalidates on every session start).
|
|
183
|
+
Only a hash fingerprint of the key is stored (`tensorix-models.sync.json`), never the key itself.
|
|
184
|
+
|
|
169
185
|
## API Documentation
|
|
170
186
|
|
|
171
187
|
- Tensorix Docs: https://docs.tensorix.ai
|
package/index.ts
CHANGED
|
@@ -20,6 +20,9 @@
|
|
|
20
20
|
* Model resolution strategy: Stale-While-Revalidate
|
|
21
21
|
* 1. Serve stale immediately: disk cache → embedded models.json (zero-latency)
|
|
22
22
|
* 2. Revalidate in background: live API /models → merge with embedded → cache → hot-swap
|
|
23
|
+
* Quiet startup sync (sync-policy.ts): only with an API key, only when the
|
|
24
|
+
* disk cache is older than the TTL (1h, PI_PROVIDER_SYNC_TTL_MS) or the key
|
|
25
|
+
* changed, and only one pi process at a time (lock file next to the cache).
|
|
23
26
|
* 3. patch.json + custom-models.json applied on top of whichever source won
|
|
24
27
|
*
|
|
25
28
|
* Merge order: [live|cache|embedded] → apply patch.json → merge custom-models.json
|
|
@@ -48,6 +51,7 @@ import patchData from "./patch.json" with { type: "json" };
|
|
|
48
51
|
import deprecatedData from "./deprecated-models.json" with { type: "json" };
|
|
49
52
|
import fs from "fs";
|
|
50
53
|
import path from "path";
|
|
54
|
+
import { acquireModelSync, cacheChangedSinceLoad, markCacheLoaded, writeFileAtomic } from "./sync-policy";
|
|
51
55
|
|
|
52
56
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
|
53
57
|
|
|
@@ -220,7 +224,8 @@ function loadCachedModels(): JsonModel[] | null {
|
|
|
220
224
|
function cacheModels(models: JsonModel[]): void {
|
|
221
225
|
try {
|
|
222
226
|
fs.mkdirSync(CACHE_DIR, { recursive: true });
|
|
223
|
-
|
|
227
|
+
// Atomic (tmp + rename): other pi processes may be reading the cache right now.
|
|
228
|
+
writeFileAtomic(CACHE_PATH, JSON.stringify(models, null, 2) + "\n");
|
|
224
229
|
} catch {
|
|
225
230
|
// Cache write failure is non-fatal
|
|
226
231
|
}
|
|
@@ -292,6 +297,7 @@ function withDeprecated(models: JsonModel[]): JsonModel[] {
|
|
|
292
297
|
}
|
|
293
298
|
|
|
294
299
|
function loadStaleModels(embeddedModels: JsonModel[]): JsonModel[] {
|
|
300
|
+
markCacheLoaded(CACHE_PATH); // stat before read: lets session_start spot newer caches
|
|
295
301
|
const cached = loadCachedModels();
|
|
296
302
|
if (!cached || cached.length === 0) return embeddedModels;
|
|
297
303
|
|
|
@@ -304,13 +310,26 @@ function loadStaleModels(embeddedModels: JsonModel[]): JsonModel[] {
|
|
|
304
310
|
return cached;
|
|
305
311
|
}
|
|
306
312
|
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
313
|
+
/**
|
|
314
|
+
* Background revalidation, gated by the quiet startup sync policy
|
|
315
|
+
* (sync-policy.ts): no key → no fetch; fresh cache (TTL) → no fetch; another
|
|
316
|
+
* process already fetching → no fetch. When skipped, a cache that another
|
|
317
|
+
* process refreshed since we loaded it is adopted from disk instead.
|
|
318
|
+
* `force` bypasses the TTL (e.g. after /login); it is still single-flight.
|
|
319
|
+
*/
|
|
320
|
+
async function revalidateModels(apiKey: string | undefined, embeddedModels: JsonModel[], signal?: AbortSignal, force = false): Promise<JsonModel[] | null> {
|
|
321
|
+
const lease = acquireModelSync({ cachePath: CACHE_PATH, apiKey, force });
|
|
322
|
+
if (!lease) return cacheChangedSinceLoad(CACHE_PATH) ? loadStaleModels(embeddedModels) : null;
|
|
323
|
+
let merged: JsonModel[] | null = null;
|
|
324
|
+
try {
|
|
325
|
+
const liveModels = apiKey ? await fetchLiveModels(apiKey, signal) : null;
|
|
326
|
+
if (!liveModels || liveModels.length === 0) return null;
|
|
327
|
+
merged = mergeWithEmbedded(liveModels, embeddedModels);
|
|
328
|
+
cacheModels(merged);
|
|
329
|
+
return merged;
|
|
330
|
+
} finally {
|
|
331
|
+
lease.release(merged ? "fetched" : signal?.aborted ? "aborted" : "failed");
|
|
332
|
+
}
|
|
314
333
|
}
|
|
315
334
|
|
|
316
335
|
// ─── API Key Resolution (via ModelRegistry) ────────────────────────────────────
|
|
@@ -339,12 +358,15 @@ export default function (pi: ExtensionAPI) {
|
|
|
339
358
|
models: staleModels,
|
|
340
359
|
});
|
|
341
360
|
|
|
361
|
+
// Fire-and-forget: never await network here — startup must not block on the
|
|
362
|
+
// provider API. Nothing is awaited and every rejection is swallowed.
|
|
342
363
|
pi.on("session_start", async (_event, ctx) => {
|
|
343
364
|
revalidateAbort?.abort();
|
|
344
365
|
revalidateAbort = new AbortController();
|
|
345
366
|
const signal = revalidateAbort.signal;
|
|
346
|
-
resolveApiKey(ctx.modelRegistry)
|
|
347
|
-
revalidateModels(cachedApiKey, embeddedModels, signal)
|
|
367
|
+
void resolveApiKey(ctx.modelRegistry)
|
|
368
|
+
.then(() => revalidateModels(cachedApiKey, embeddedModels, signal))
|
|
369
|
+
.then((freshBase) => {
|
|
348
370
|
if (freshBase && !signal.aborted) {
|
|
349
371
|
pi.registerProvider("tensorix", {
|
|
350
372
|
baseUrl: BASE_URL,
|
|
@@ -353,8 +375,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
353
375
|
models: buildModels(freshBase, customModels, patches),
|
|
354
376
|
});
|
|
355
377
|
}
|
|
356
|
-
})
|
|
357
|
-
|
|
378
|
+
})
|
|
379
|
+
.catch(() => { /* keep serving the stale catalog */ });
|
|
358
380
|
});
|
|
359
381
|
|
|
360
382
|
pi.on("session_shutdown", () => {
|
package/package.json
CHANGED
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-tensorix-provider",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.23",
|
|
4
4
|
"description": "Tensorix provider extension for pi - Access DeepSeek, GLM, Kimi, Qwen, MiniMax, Llama, and more through the Tensorix API",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.ts",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"clean": "echo 'nothing to clean'",
|
|
9
|
+
"build": "echo 'nothing to build'",
|
|
10
|
+
"check": "tsc --noEmit && vitest run && node scripts/test-pi-compat.mjs",
|
|
11
|
+
"test": "vitest run",
|
|
12
|
+
"update-models": "node scripts/update-models.js",
|
|
13
|
+
"test:pi": "node scripts/test-pi-compat.mjs",
|
|
14
|
+
"typecheck": "tsc --noEmit"
|
|
15
|
+
},
|
|
7
16
|
"keywords": [
|
|
8
17
|
"pi",
|
|
9
18
|
"extension",
|
|
@@ -25,20 +34,16 @@
|
|
|
25
34
|
"./index.ts"
|
|
26
35
|
]
|
|
27
36
|
},
|
|
37
|
+
"overrides": {
|
|
38
|
+
"brace-expansion": "5.0.12"
|
|
39
|
+
},
|
|
28
40
|
"devDependencies": {
|
|
29
|
-
"@earendil-works/pi-coding-agent": "1.
|
|
41
|
+
"@earendil-works/pi-coding-agent": "1.1.0",
|
|
30
42
|
"typescript": "6.0.3",
|
|
31
|
-
"@types/node": "^25.9.1"
|
|
43
|
+
"@types/node": "^25.9.1",
|
|
44
|
+
"vitest": "4.1.7"
|
|
32
45
|
},
|
|
33
46
|
"peerDependencies": {
|
|
34
47
|
"@earendil-works/pi-coding-agent": "*"
|
|
35
|
-
},
|
|
36
|
-
"scripts": {
|
|
37
|
-
"clean": "echo 'nothing to clean'",
|
|
38
|
-
"build": "echo 'nothing to build'",
|
|
39
|
-
"check": "tsc --noEmit && node scripts/test-pi-compat.mjs",
|
|
40
|
-
"update-models": "node scripts/update-models.js",
|
|
41
|
-
"test:pi": "node scripts/test-pi-compat.mjs",
|
|
42
|
-
"typecheck": "tsc --noEmit"
|
|
43
48
|
}
|
|
44
|
-
}
|
|
49
|
+
}
|
|
@@ -14,7 +14,7 @@ globalThis.fetch = async () => new Response('', { status: 503 });
|
|
|
14
14
|
let session;
|
|
15
15
|
try {
|
|
16
16
|
const { createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager, VERSION } = await import('@earendil-works/pi-coding-agent');
|
|
17
|
-
assert.equal(VERSION, '1.
|
|
17
|
+
assert.equal(VERSION, '1.1.0', 'run compatibility checks against the pinned host');
|
|
18
18
|
const manifest = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
|
|
19
19
|
const hostPackages = ['@earendil-works/pi-ai', '@earendil-works/pi-agent-core', '@earendil-works/pi-coding-agent', '@earendil-works/pi-tui', 'typebox'];
|
|
20
20
|
for (const name of hostPackages) {
|
|
@@ -65,7 +65,7 @@ try {
|
|
|
65
65
|
modelCount += models.length;
|
|
66
66
|
}
|
|
67
67
|
await session.extensionRunner.emit({ type: 'session_shutdown' });
|
|
68
|
-
assert.deepEqual(errors, [], 'startup and shutdown handlers must work with Pi 1.0 contexts');
|
|
68
|
+
assert.deepEqual(errors, [], 'startup and shutdown handlers must work with Pi 1.1.0 contexts');
|
|
69
69
|
console.log(`${manifest.name}: Pi ${VERSION} loader, manifest, session startup, and ${modelCount} models OK`);
|
|
70
70
|
} finally {
|
|
71
71
|
session?.dispose();
|
package/sync-policy.ts
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Quiet startup sync — shared policy for background model-catalog revalidation.
|
|
3
|
+
*
|
|
4
|
+
* Every pi process (interactive start, /new, /reload, `pi -p`, and every child
|
|
5
|
+
* agent a fan-out tool spawns) fires `session_start`. Revalidating the live
|
|
6
|
+
* `/models` catalog on each of those spams the provider API, so this module
|
|
7
|
+
* decides — without any network I/O and without ever throwing — whether *this*
|
|
8
|
+
* process should fetch at all:
|
|
9
|
+
*
|
|
10
|
+
* 1. No credentials → no fetch (serve disk cache → embedded models.json).
|
|
11
|
+
* 2. Freshness window → skip while the disk cache is younger than the TTL.
|
|
12
|
+
* TTL source: the cache file's mtime. The cache is only (re)written after a
|
|
13
|
+
* successful live fetch, so mtime is "last fetched at" — and caches written
|
|
14
|
+
* by older extension versions carry it too, with no format change.
|
|
15
|
+
* Default 1 hour; override with PI_PROVIDER_SYNC_TTL_MS (0 = always).
|
|
16
|
+
* 3. Forced refresh ignores the TTL: cache missing/corrupt, API key changed
|
|
17
|
+
* since the cache was fetched (compared via a salted sha256 fingerprint —
|
|
18
|
+
* never the key itself), or the caller passes `force` (e.g. after /login).
|
|
19
|
+
* 4. Failure backoff → after a failed fetch with the same key, non-forced
|
|
20
|
+
* attempts wait min(5 min, TTL) so a bad key or outage is not retried by
|
|
21
|
+
* every process that starts.
|
|
22
|
+
* 5. Cross-process single-flight → an atomic lock file (`open(…, "wx")`) next
|
|
23
|
+
* to the cache; whoever creates it fetches, everyone else skips and keeps
|
|
24
|
+
* serving the cache. Locks older than the stale timeout (crashed holder)
|
|
25
|
+
* are reclaimed. Any filesystem error fails open to "skip the fetch".
|
|
26
|
+
*
|
|
27
|
+
* Files (for a cache at `<agentDir>/cache/<provider>-models.json`):
|
|
28
|
+
* <provider>-models.json the cache itself — unchanged plain JSON array
|
|
29
|
+
* <provider>-models.sync.json sidecar: { version, keyFingerprint, fetchedAt, failedAt?, failedKeyFingerprint? }
|
|
30
|
+
* <provider>-models.lock present only while one process is fetching
|
|
31
|
+
*
|
|
32
|
+
* Older extension versions ignore the sidecar/lock and read the cache as
|
|
33
|
+
* before; a cache without a sidecar (written by an older version) is treated
|
|
34
|
+
* as "fetched with an unknown key" and revalidated once (still single-flight).
|
|
35
|
+
*
|
|
36
|
+
* This file is provider-agnostic: it is copied verbatim into every
|
|
37
|
+
* pi-*-provider repo. Keep it free of pi imports and provider specifics.
|
|
38
|
+
*
|
|
39
|
+
* Typical use inside a provider's revalidateModels():
|
|
40
|
+
*
|
|
41
|
+
* const lease = acquireModelSync({ cachePath: CACHE_PATH, apiKey, force });
|
|
42
|
+
* if (!lease) return cacheChangedSinceLoad(CACHE_PATH) ? loadStaleModels(embedded) : null;
|
|
43
|
+
* let merged = null;
|
|
44
|
+
* try { …fetch, merge, cacheModels(merged)…; return merged; }
|
|
45
|
+
* finally { lease.release(merged ? "fetched" : signal?.aborted ? "aborted" : "failed"); }
|
|
46
|
+
*/
|
|
47
|
+
|
|
48
|
+
import crypto from "crypto";
|
|
49
|
+
import fs from "fs";
|
|
50
|
+
import path from "path";
|
|
51
|
+
|
|
52
|
+
/** Env override for the freshness window, shared by all pi-*-provider extensions. */
|
|
53
|
+
export const SYNC_TTL_ENV = "PI_PROVIDER_SYNC_TTL_MS";
|
|
54
|
+
export const DEFAULT_SYNC_TTL_MS = 60 * 60 * 1000;
|
|
55
|
+
/** A lock older than this is assumed abandoned (crashed holder). Must exceed the fetch timeout. */
|
|
56
|
+
export const DEFAULT_LOCK_STALE_MS = 60 * 1000;
|
|
57
|
+
/** Pause after a failed fetch (same key) before non-forced retries; capped at the TTL. */
|
|
58
|
+
export const FAILURE_BACKOFF_MS = 5 * 60 * 1000;
|
|
59
|
+
|
|
60
|
+
/** Why this process was granted the fetch. */
|
|
61
|
+
export type SyncReason = "missing" | "key-changed" | "forced" | "stale";
|
|
62
|
+
/** Why this process must not fetch (serve cache/embedded instead). */
|
|
63
|
+
export type SkipReason = "no-key" | "fresh" | "backoff" | "locked" | "unwritable";
|
|
64
|
+
/** How a granted fetch ended; "aborted" (session replaced/shut down) records no failure. */
|
|
65
|
+
export type SyncOutcome = "fetched" | "failed" | "aborted";
|
|
66
|
+
|
|
67
|
+
export type SyncPlan = { fetch: true; reason: SyncReason } | { fetch: false; reason: SkipReason };
|
|
68
|
+
|
|
69
|
+
export interface ModelSyncOptions {
|
|
70
|
+
/** Absolute path of the provider's disk cache, e.g. `<agentDir>/cache/<provider>-models.json`. */
|
|
71
|
+
cachePath: string;
|
|
72
|
+
/** Resolved credential. Falsy → never fetch. */
|
|
73
|
+
apiKey: string | undefined | null;
|
|
74
|
+
/** Revalidate regardless of TTL/backoff (e.g. right after /login). Still single-flight. */
|
|
75
|
+
force?: boolean;
|
|
76
|
+
/** Freshness window; defaults to $PI_PROVIDER_SYNC_TTL_MS, else 1 hour. */
|
|
77
|
+
ttlMs?: number;
|
|
78
|
+
lockStaleMs?: number;
|
|
79
|
+
/** Cache validity check; defaults to "non-empty JSON array" (the models cache format). */
|
|
80
|
+
isValidCache?: (data: unknown) => boolean;
|
|
81
|
+
/** Clock override for tests. */
|
|
82
|
+
now?: number;
|
|
83
|
+
/** Optional diagnostics hook: called with the reason whenever the fetch is skipped. */
|
|
84
|
+
onSkip?: (reason: SkipReason) => void;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface ModelSyncLease {
|
|
88
|
+
readonly reason: SyncReason;
|
|
89
|
+
/** Always call exactly once (use try/finally). Records the outcome and drops the lock. */
|
|
90
|
+
release(outcome: SyncOutcome): void;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
interface SyncMeta {
|
|
94
|
+
version: 1;
|
|
95
|
+
keyFingerprint?: string;
|
|
96
|
+
fetchedAt?: number;
|
|
97
|
+
failedAt?: number;
|
|
98
|
+
failedKeyFingerprint?: string;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// ─── Small helpers ────────────────────────────────────────────────────────────
|
|
102
|
+
|
|
103
|
+
/** Salted, truncated sha256 of the key: detects key changes, cannot be reversed into the key. */
|
|
104
|
+
export function keyFingerprint(apiKey: string): string {
|
|
105
|
+
return crypto.createHash("sha256").update(`pi-provider-sync\0${apiKey}`).digest("hex").slice(0, 16);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function resolveSyncTtlMs(ttlMs?: number): number {
|
|
109
|
+
if (typeof ttlMs === "number" && Number.isFinite(ttlMs) && ttlMs >= 0) return ttlMs;
|
|
110
|
+
const raw = process.env[SYNC_TTL_ENV];
|
|
111
|
+
const fromEnv = raw === undefined || raw.trim() === "" ? NaN : Number(raw);
|
|
112
|
+
return Number.isFinite(fromEnv) && fromEnv >= 0 ? fromEnv : DEFAULT_SYNC_TTL_MS;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** `foo-models.json` → `foo-models` (sidecar/lock base name). */
|
|
116
|
+
function sidecarBase(cachePath: string): string {
|
|
117
|
+
return cachePath.replace(/\.json$/i, "");
|
|
118
|
+
}
|
|
119
|
+
export const syncMetaPath = (cachePath: string): string => `${sidecarBase(cachePath)}.sync.json`;
|
|
120
|
+
export const syncLockPath = (cachePath: string): string => `${sidecarBase(cachePath)}.lock`;
|
|
121
|
+
|
|
122
|
+
function mtimeMs(file: string): number | null {
|
|
123
|
+
try {
|
|
124
|
+
return fs.statSync(file).mtimeMs;
|
|
125
|
+
} catch {
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function readJson(file: string): unknown {
|
|
131
|
+
try {
|
|
132
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
133
|
+
} catch {
|
|
134
|
+
return undefined;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function readMeta(cachePath: string): SyncMeta | null {
|
|
139
|
+
const data = readJson(syncMetaPath(cachePath));
|
|
140
|
+
return data && typeof data === "object" && !Array.isArray(data) ? (data as SyncMeta) : null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Write via temp file + rename so concurrent readers in other processes never
|
|
145
|
+
* observe a half-written file (a torn cache would otherwise read as "corrupt"
|
|
146
|
+
* and force a refetch). Throws on failure — callers decide whether that is fatal.
|
|
147
|
+
*/
|
|
148
|
+
export function writeFileAtomic(file: string, contents: string): void {
|
|
149
|
+
const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
|
|
150
|
+
try {
|
|
151
|
+
fs.writeFileSync(tmp, contents);
|
|
152
|
+
fs.renameSync(tmp, file);
|
|
153
|
+
} catch (error) {
|
|
154
|
+
try { fs.unlinkSync(tmp); } catch { /* already gone */ }
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function writeMeta(cachePath: string, meta: SyncMeta): void {
|
|
160
|
+
try {
|
|
161
|
+
writeFileAtomic(syncMetaPath(cachePath), JSON.stringify(meta) + "\n");
|
|
162
|
+
} catch {
|
|
163
|
+
// Non-fatal: worst case the next process revalidates once more.
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// ─── In-process view of the shared cache ──────────────────────────────────────
|
|
168
|
+
|
|
169
|
+
// mtime of the cache as this process last loaded/wrote it, per cache path.
|
|
170
|
+
const loadedCacheMtimes = new Map<string, number>();
|
|
171
|
+
|
|
172
|
+
/** Call right before reading the disk cache at startup (stat-before-read keeps races harmless). */
|
|
173
|
+
export function markCacheLoaded(cachePath: string): void {
|
|
174
|
+
loadedCacheMtimes.set(cachePath, mtimeMs(cachePath) ?? 0);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* True when another process rewrote the shared cache since this process last
|
|
179
|
+
* loaded it, so a long-lived session can adopt the newer catalog from disk
|
|
180
|
+
* instead of fetching it again.
|
|
181
|
+
*/
|
|
182
|
+
export function cacheChangedSinceLoad(cachePath: string): boolean {
|
|
183
|
+
const current = mtimeMs(cachePath);
|
|
184
|
+
return current !== null && current !== loadedCacheMtimes.get(cachePath);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// ─── Policy ───────────────────────────────────────────────────────────────────
|
|
188
|
+
|
|
189
|
+
const isNonEmptyArray = (data: unknown): boolean => Array.isArray(data) && data.length > 0;
|
|
190
|
+
|
|
191
|
+
/** Decide whether a fetch is warranted (no lock taken, no I/O beyond local stat/read). */
|
|
192
|
+
export function planModelSync(options: ModelSyncOptions): SyncPlan {
|
|
193
|
+
const { cachePath, apiKey, force = false } = options;
|
|
194
|
+
if (!apiKey) return { fetch: false, reason: "no-key" };
|
|
195
|
+
|
|
196
|
+
const now = options.now ?? Date.now();
|
|
197
|
+
const ttlMs = resolveSyncTtlMs(options.ttlMs);
|
|
198
|
+
const fingerprint = keyFingerprint(apiKey);
|
|
199
|
+
const meta = readMeta(cachePath);
|
|
200
|
+
const cacheMtime = mtimeMs(cachePath);
|
|
201
|
+
const valid = cacheMtime !== null && (options.isValidCache ?? isNonEmptyArray)(readJson(cachePath));
|
|
202
|
+
|
|
203
|
+
let reason: SyncReason;
|
|
204
|
+
if (!valid) reason = "missing";
|
|
205
|
+
// A cache without a sidecar (older extension version) counts as an unknown key.
|
|
206
|
+
else if (meta?.keyFingerprint !== fingerprint) reason = "key-changed";
|
|
207
|
+
else if (force) reason = "forced";
|
|
208
|
+
else if (now - cacheMtime < ttlMs) return { fetch: false, reason: "fresh" };
|
|
209
|
+
else reason = "stale";
|
|
210
|
+
|
|
211
|
+
if (!force && meta?.failedKeyFingerprint === fingerprint && typeof meta.failedAt === "number"
|
|
212
|
+
&& now - meta.failedAt < Math.min(FAILURE_BACKOFF_MS, ttlMs)) {
|
|
213
|
+
return { fetch: false, reason: "backoff" };
|
|
214
|
+
}
|
|
215
|
+
return { fetch: true, reason };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Atomically create the lock file; reclaim it once if its holder looks dead. */
|
|
219
|
+
function tryLock(lockPath: string, token: string, lockStaleMs: number, now: number): "locked" | "held" | "unwritable" {
|
|
220
|
+
try {
|
|
221
|
+
fs.mkdirSync(path.dirname(lockPath), { recursive: true });
|
|
222
|
+
} catch {
|
|
223
|
+
return "unwritable";
|
|
224
|
+
}
|
|
225
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
226
|
+
let fd: number;
|
|
227
|
+
try {
|
|
228
|
+
fd = fs.openSync(lockPath, "wx");
|
|
229
|
+
} catch (error) {
|
|
230
|
+
// EEXIST: someone holds the lock. Anything else (EACCES, ENOTDIR, EROFS…):
|
|
231
|
+
// the cache dir is unusable — fail open to "skip the fetch".
|
|
232
|
+
if ((error as NodeJS.ErrnoException)?.code !== "EEXIST") return "unwritable";
|
|
233
|
+
if (attempt > 0) return "held";
|
|
234
|
+
const lockMtime = mtimeMs(lockPath);
|
|
235
|
+
if (lockMtime === null) continue; // released between open and stat: retry once
|
|
236
|
+
if (now - lockMtime <= lockStaleMs) return "held"; // a live process is fetching
|
|
237
|
+
// Stale: the holder crashed or hung. Reclaim and retry once. (Two processes
|
|
238
|
+
// reclaiming the same stale lock at the same instant may both fetch — a rare,
|
|
239
|
+
// harmless duplicate.)
|
|
240
|
+
try { fs.unlinkSync(lockPath); } catch { /* someone else reclaimed it first */ }
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
// We own the lock. Record a token so release() only deletes our own lock.
|
|
244
|
+
let wrote = false;
|
|
245
|
+
try {
|
|
246
|
+
fs.writeSync(fd, JSON.stringify({ pid: process.pid, token, at: now }));
|
|
247
|
+
wrote = true;
|
|
248
|
+
} catch {
|
|
249
|
+
// e.g. ENOSPC — handled below
|
|
250
|
+
} finally {
|
|
251
|
+
try { fs.closeSync(fd); } catch { /* ignore */ }
|
|
252
|
+
}
|
|
253
|
+
if (wrote) return "locked";
|
|
254
|
+
try { fs.unlinkSync(lockPath); } catch { /* ignore */ }
|
|
255
|
+
return "unwritable";
|
|
256
|
+
}
|
|
257
|
+
return "held";
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Decide and, when this process should fetch, take the cross-process lock.
|
|
262
|
+
* Returns null when the caller must skip the network (serve cache/embedded).
|
|
263
|
+
* Never throws.
|
|
264
|
+
*/
|
|
265
|
+
export function acquireModelSync(options: ModelSyncOptions): ModelSyncLease | null {
|
|
266
|
+
try {
|
|
267
|
+
const plan = planModelSync(options);
|
|
268
|
+
if (!plan.fetch) return skip(options, plan.reason);
|
|
269
|
+
|
|
270
|
+
const { cachePath } = options;
|
|
271
|
+
const now = options.now ?? Date.now();
|
|
272
|
+
const lockPath = syncLockPath(cachePath);
|
|
273
|
+
const token = crypto.randomBytes(8).toString("hex");
|
|
274
|
+
const lock = tryLock(lockPath, token, options.lockStaleMs ?? DEFAULT_LOCK_STALE_MS, now);
|
|
275
|
+
if (lock !== "locked") return skip(options, lock === "held" ? "locked" : "unwritable");
|
|
276
|
+
|
|
277
|
+
const fingerprint = keyFingerprint(options.apiKey as string);
|
|
278
|
+
let released = false;
|
|
279
|
+
return {
|
|
280
|
+
reason: plan.reason,
|
|
281
|
+
release(outcome: SyncOutcome): void {
|
|
282
|
+
if (released) return;
|
|
283
|
+
released = true;
|
|
284
|
+
try {
|
|
285
|
+
const at = Date.now();
|
|
286
|
+
if (outcome === "fetched") {
|
|
287
|
+
writeMeta(cachePath, { version: 1, keyFingerprint: fingerprint, fetchedAt: at });
|
|
288
|
+
markCacheLoaded(cachePath); // our own write is not "another process's" update
|
|
289
|
+
} else if (outcome === "failed") {
|
|
290
|
+
const previous = readMeta(cachePath);
|
|
291
|
+
writeMeta(cachePath, { ...previous, version: 1, failedAt: at, failedKeyFingerprint: fingerprint });
|
|
292
|
+
}
|
|
293
|
+
// Only remove the lock if it is still ours (it may have been reclaimed as stale).
|
|
294
|
+
const held = readJson(lockPath) as { token?: string } | undefined;
|
|
295
|
+
if (held?.token === token) fs.unlinkSync(lockPath);
|
|
296
|
+
} catch {
|
|
297
|
+
// Never throw from cleanup; a leftover lock expires after lockStaleMs.
|
|
298
|
+
}
|
|
299
|
+
},
|
|
300
|
+
};
|
|
301
|
+
} catch {
|
|
302
|
+
return skip(options, "unwritable");
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function skip(options: ModelSyncOptions, reason: SkipReason): null {
|
|
307
|
+
try { options.onSkip?.(reason); } catch { /* diagnostics must never break startup */ }
|
|
308
|
+
return null;
|
|
309
|
+
}
|