@aiwayds/dsh-model-sync 0.2.1 → 0.2.3
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/README.md +2 -2
- package/README.zh-CN.md +2 -2
- package/lib/index.js +25 -3
- package/lib/index.js.map +1 -1
- package/lib/remote-catalog.d.ts +93 -3
- package/lib/remote-catalog.js +172 -23
- package/lib/remote-catalog.js.map +1 -1
- package/lib/writer.d.ts +65 -14
- package/lib/writer.js +178 -21
- package/lib/writer.js.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +23 -2
- package/src/remote-catalog.ts +243 -24
- package/src/writer.ts +265 -27
package/src/remote-catalog.ts
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
|
|
14
14
|
import { homedir } from 'node:os'
|
|
15
15
|
import { dirname, join } from 'node:path'
|
|
16
|
-
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
16
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
|
17
17
|
|
|
18
18
|
// ---------------------------------------------------------------------------
|
|
19
19
|
// Constants (ported from docs-dsh-llm-pi-ai.patch:35-36)
|
|
@@ -65,8 +65,36 @@ export interface ModelsStoreEntry {
|
|
|
65
65
|
checkedAt: number
|
|
66
66
|
lastModified: number
|
|
67
67
|
etag?: string
|
|
68
|
+
/**
|
|
69
|
+
* User `modelOverrides` folded out of settings and unset there (the dsh
|
|
70
|
+
* llm-pi-ai validation refuses a models list beside non-empty
|
|
71
|
+
* modelOverrides). Replayed into the translated target on every later
|
|
72
|
+
* round so the user's values survive. The catalog refresh must NOT carry
|
|
73
|
+
* this field forward from its own snapshot — the queue-internal seed
|
|
74
|
+
* merge keeps whatever overrides the route currently holds, so a
|
|
75
|
+
* concurrent round's stage cannot be clobbered by a fetch write (C1 fix).
|
|
76
|
+
*/
|
|
77
|
+
overrides?: Record<string, Record<string, unknown>>
|
|
68
78
|
}
|
|
69
79
|
|
|
80
|
+
/**
|
|
81
|
+
* Patch surface for `update()`. The fetch side typically only names
|
|
82
|
+
* fetch-owned fields (`models` / `checkedAt` / `lastModified` / `etag`),
|
|
83
|
+
* but `overrides` is part of the type so the same seed formula works for
|
|
84
|
+
* callers that need to patch out-of-band fields too (and so TS doesn't
|
|
85
|
+
* reject `patch.overrides` in the seed). The merge is a field-level seed
|
|
86
|
+
* inside the accessor's write queue: concurrent stages (the writer's
|
|
87
|
+
* `persistOverridesToStore`, a sibling route's fetch, etc.) see a
|
|
88
|
+
* consistent read-modify-write and never overwrite each other's
|
|
89
|
+
* out-of-band fields. The seed also guarantees the entry shape invariant
|
|
90
|
+
* — every persisted entry carries models (default []), checkedAt (default
|
|
91
|
+
* Date.now()), lastModified (default 0), etag, and overrides — so a
|
|
92
|
+
* subsequent read never sees an incomplete shape (B1 fix).
|
|
93
|
+
*/
|
|
94
|
+
export type ModelsStoreEntryPatch = Partial<
|
|
95
|
+
Pick<ModelsStoreEntry, 'models' | 'checkedAt' | 'lastModified' | 'etag' | 'overrides'>
|
|
96
|
+
>
|
|
97
|
+
|
|
70
98
|
/** Top-level shape of ~/.dsh/models-store.json. */
|
|
71
99
|
export interface ModelsStore {
|
|
72
100
|
[route: string]: ModelsStoreEntry
|
|
@@ -124,10 +152,51 @@ export function parseRemoteCatalog(
|
|
|
124
152
|
|
|
125
153
|
let modelsStoreCache: ModelsStoreAccessor | undefined
|
|
126
154
|
|
|
127
|
-
/**
|
|
155
|
+
/**
|
|
156
|
+
* Serialized read/write accessor for ~/.dsh/models-store.json.
|
|
157
|
+
*
|
|
158
|
+
* Every mutation method funnels through the same promise queue so
|
|
159
|
+
* concurrent updates serialize cleanly. `update` / `updateOverrides` use
|
|
160
|
+
* a queue-internal field-level seed (B1 fix) that gives every persisted
|
|
161
|
+
* entry the unconditional shape { models, checkedAt, lastModified, etag,
|
|
162
|
+
* overrides } — patch missing → fall through to current → fall back to a
|
|
163
|
+
* per-field default. The `write` method is the legacy whole-entry
|
|
164
|
+
* replacement path (kept for tests / seeders); production callers prefer
|
|
165
|
+
* the targeted merge so concurrent stages (the writer's
|
|
166
|
+
* `persistOverridesToStore`, a sibling route's fetch, etc.) never
|
|
167
|
+
* overwrite each other's out-of-band fields.
|
|
168
|
+
*/
|
|
128
169
|
export interface ModelsStoreAccessor {
|
|
129
170
|
read(providerId?: string): Promise<ModelsStoreEntry | undefined>
|
|
171
|
+
/**
|
|
172
|
+
* Whole-entry replacement. Still available for tests / seeders; production
|
|
173
|
+
* code paths prefer the targeted `update` / `updateOverrides` so the queue
|
|
174
|
+
* can preserve out-of-band fields.
|
|
175
|
+
*/
|
|
130
176
|
write(providerId: string, entry: ModelsStoreEntry): Promise<void>
|
|
177
|
+
/**
|
|
178
|
+
* Field-level seed merge: the route's current entry is re-read inside
|
|
179
|
+
* the write queue (so it sees every prior queue task's committed
|
|
180
|
+
* state), the patch's fields override the current's where present, and
|
|
181
|
+
* missing fields fall back to per-field defaults (models: [],
|
|
182
|
+
* checkedAt: Date.now(), lastModified: 0, etag: undefined, overrides:
|
|
183
|
+
* undefined). The result is an unconditional entry shape — a
|
|
184
|
+
* subsequent read never sees an incomplete `{overrides}-only` entry.
|
|
185
|
+
* Used by `fetchRemoteCatalog` for every status path.
|
|
186
|
+
*/
|
|
187
|
+
update(providerId: string, patch: ModelsStoreEntryPatch): Promise<void>
|
|
188
|
+
/**
|
|
189
|
+
* Replace the route's `overrides` field only; the same field-level
|
|
190
|
+
* seed as `update` guarantees the rest of the entry (models /
|
|
191
|
+
* checkedAt / lastModified / etag) lands with sensible defaults when
|
|
192
|
+
* the route is new / the doc is corrupt, or is preserved verbatim
|
|
193
|
+
* from the current entry otherwise. Used by `persistOverridesToStore`
|
|
194
|
+
* so its stage survives a concurrent fetch write.
|
|
195
|
+
*/
|
|
196
|
+
updateOverrides(
|
|
197
|
+
providerId: string,
|
|
198
|
+
overrides: Record<string, Record<string, unknown>>,
|
|
199
|
+
): Promise<void>
|
|
131
200
|
delete(providerId: string): Promise<void>
|
|
132
201
|
}
|
|
133
202
|
|
|
@@ -147,14 +216,37 @@ export function loadModelsStore(storePath?: string): ModelsStoreAccessor {
|
|
|
147
216
|
const readDoc = async (): Promise<ModelsStore> => {
|
|
148
217
|
try {
|
|
149
218
|
return JSON.parse(await readFile(effectivePath, 'utf8')) as ModelsStore
|
|
150
|
-
} catch {
|
|
151
|
-
|
|
219
|
+
} catch (err: unknown) {
|
|
220
|
+
// ENOENT is a normal first run — the store has never been written.
|
|
221
|
+
// Anything else (SyntaxError on a corrupted file, EACCES on a
|
|
222
|
+
// permission-denied read, EIO on storage failure) bubbles up so the
|
|
223
|
+
// writer fails closed: treating an unreadable store as empty would
|
|
224
|
+
// let a later replay write the raw pi.dev target into settings and
|
|
225
|
+
// clobber user-folded values (the v0.1.5 data-loss shape). The
|
|
226
|
+
// failure propagates to the writer which skips the round and keeps
|
|
227
|
+
// settings.models — the authoritative, already-landed source —
|
|
228
|
+
// untouched.
|
|
229
|
+
if (err instanceof Error && (err as NodeJS.ErrnoException).code === 'ENOENT') {
|
|
230
|
+
return {}
|
|
231
|
+
}
|
|
232
|
+
throw err
|
|
152
233
|
}
|
|
153
234
|
}
|
|
154
235
|
|
|
155
236
|
const writeDoc = async (doc: ModelsStore): Promise<void> => {
|
|
156
237
|
await mkdir(dirname(effectivePath), { recursive: true })
|
|
157
|
-
|
|
238
|
+
// Atomic write: stage to a sibling temp file then rename(2) into place.
|
|
239
|
+
// rename(2) is atomic on POSIX, so a concurrent reader either sees the
|
|
240
|
+
// pre-rename doc or the post-rename doc — never a half-written file.
|
|
241
|
+
// JSON.stringify without spaces keeps the existing wire format (the
|
|
242
|
+
// reader is strict on the parse side; legacy stores carry no
|
|
243
|
+
// whitespace). A fresh write also *heals* a previously-corrupt store:
|
|
244
|
+
// the first successful write after corruption replaces the bad file
|
|
245
|
+
// atomically with a well-formed doc, so subsequent reads see the
|
|
246
|
+
// expected shape.
|
|
247
|
+
const tmpPath = `${effectivePath}.${process.pid}.tmp`
|
|
248
|
+
await writeFile(tmpPath, JSON.stringify(doc))
|
|
249
|
+
await rename(tmpPath, effectivePath)
|
|
158
250
|
}
|
|
159
251
|
|
|
160
252
|
let queue: Promise<void> = Promise.resolve()
|
|
@@ -171,13 +263,103 @@ export function loadModelsStore(storePath?: string): ModelsStoreAccessor {
|
|
|
171
263
|
},
|
|
172
264
|
write: (providerId: string, entry: ModelsStoreEntry): Promise<void> =>
|
|
173
265
|
enqueue(async () => {
|
|
174
|
-
|
|
266
|
+
// The read-modify-write pattern preserves concurrent routes'
|
|
267
|
+
// entries; if the file is corrupt or unreadable, treat the doc as
|
|
268
|
+
// empty and overwrite — the atomic writeDoc below replaces the
|
|
269
|
+
// bad file with a fresh, well-formed doc carrying this route's
|
|
270
|
+
// entry (and any other routes the caller writes later will
|
|
271
|
+
// re-stamp theirs). The store reads path stays strict (readDoc
|
|
272
|
+
// still throws) so the writer's fail-closed logic can react to
|
|
273
|
+
// the actual error instead of seeing a fake empty doc.
|
|
274
|
+
let doc: ModelsStore
|
|
275
|
+
try {
|
|
276
|
+
doc = await readDoc()
|
|
277
|
+
} catch {
|
|
278
|
+
doc = {}
|
|
279
|
+
}
|
|
175
280
|
doc[providerId] = entry
|
|
176
281
|
await writeDoc(doc)
|
|
177
282
|
}),
|
|
283
|
+
update: (providerId: string, patch: ModelsStoreEntryPatch): Promise<void> =>
|
|
284
|
+
enqueue(async () => {
|
|
285
|
+
// Queue-internal read-modify-write: the read sees every prior
|
|
286
|
+
// queue task's committed state. The merge is field-level seeded —
|
|
287
|
+
// a field is taken from the patch when present, otherwise from
|
|
288
|
+
// the current entry, otherwise from a per-field default. This
|
|
289
|
+
// makes the entry shape unconditional: every persisted entry
|
|
290
|
+
// carries models/checkedAt/lastModified/etag/overrides (the
|
|
291
|
+
// last three may be undefined, but the first two always have
|
|
292
|
+
// values). Field-level seed closes the C1 bug: a stage via
|
|
293
|
+
// `updateOverrides` on an ENOENT/corrupt doc now lands an entry
|
|
294
|
+
// shape the next round's fetch can consume (`stored.models` is
|
|
295
|
+
// `[]`, never undefined) — the previous `{...current, ...patch}`
|
|
296
|
+
// spread left the entry incomplete and crashed `fetchRemoteCatalog`
|
|
297
|
+
// on the stale read.
|
|
298
|
+
//
|
|
299
|
+
// Fields outside the patch (notably `overrides`) survive any
|
|
300
|
+
// concurrent stage of out-of-band data: patch field is undefined
|
|
301
|
+
// → fall through to current → preserved. A stale pre-fetch
|
|
302
|
+
// snapshot can no longer clobber an out-of-band stage because
|
|
303
|
+
// the patch only names fields the call site intends to write.
|
|
304
|
+
//
|
|
305
|
+
// Read failure → treat the doc as empty and let the atomic
|
|
306
|
+
// writeDoc heal the file (same self-heal contract as `write`).
|
|
307
|
+
let doc: ModelsStore
|
|
308
|
+
try {
|
|
309
|
+
doc = await readDoc()
|
|
310
|
+
} catch {
|
|
311
|
+
doc = {}
|
|
312
|
+
}
|
|
313
|
+
const current = doc[providerId] ?? {}
|
|
314
|
+
doc[providerId] = {
|
|
315
|
+
models: patch.models ?? current.models ?? [],
|
|
316
|
+
checkedAt: patch.checkedAt ?? current.checkedAt ?? Date.now(),
|
|
317
|
+
lastModified: patch.lastModified ?? current.lastModified ?? 0,
|
|
318
|
+
etag: patch.etag ?? current.etag,
|
|
319
|
+
overrides: patch.overrides ?? current.overrides,
|
|
320
|
+
}
|
|
321
|
+
await writeDoc(doc)
|
|
322
|
+
}),
|
|
323
|
+
updateOverrides: (
|
|
324
|
+
providerId: string,
|
|
325
|
+
overrides: Record<string, Record<string, unknown>>,
|
|
326
|
+
): Promise<void> =>
|
|
327
|
+
enqueue(async () => {
|
|
328
|
+
// Queue-internal RMW: same field-level seed as `update`. The
|
|
329
|
+
// patch is `{ overrides }`; the seed fills every other field
|
|
330
|
+
// with a sensible default (models: [], checkedAt: Date.now(),
|
|
331
|
+
// lastModified: 0, etag: undefined) when current is missing, and
|
|
332
|
+
// preserves current's value when present. The result: an
|
|
333
|
+
// overrides-only stage on an ENOENT / corrupt doc still produces
|
|
334
|
+
// a well-formed entry the fetch side can consume, and an
|
|
335
|
+
// overrides-only stage on a populated entry keeps the fetch's
|
|
336
|
+
// models / etag / checkedAt intact. This is what the writer's
|
|
337
|
+
// `persistOverridesToStore` calls — its previous read-then-write
|
|
338
|
+
// raced the fetch side because the read ran outside the queue.
|
|
339
|
+
let doc: ModelsStore
|
|
340
|
+
try {
|
|
341
|
+
doc = await readDoc()
|
|
342
|
+
} catch {
|
|
343
|
+
doc = {}
|
|
344
|
+
}
|
|
345
|
+
const current = doc[providerId] ?? {}
|
|
346
|
+
doc[providerId] = {
|
|
347
|
+
models: current.models ?? [],
|
|
348
|
+
checkedAt: current.checkedAt ?? Date.now(),
|
|
349
|
+
lastModified: current.lastModified ?? 0,
|
|
350
|
+
etag: current.etag,
|
|
351
|
+
overrides,
|
|
352
|
+
}
|
|
353
|
+
await writeDoc(doc)
|
|
354
|
+
}),
|
|
178
355
|
delete: (providerId: string): Promise<void> =>
|
|
179
356
|
enqueue(async () => {
|
|
180
|
-
|
|
357
|
+
let doc: ModelsStore
|
|
358
|
+
try {
|
|
359
|
+
doc = await readDoc()
|
|
360
|
+
} catch {
|
|
361
|
+
doc = {}
|
|
362
|
+
}
|
|
181
363
|
delete doc[providerId]
|
|
182
364
|
await writeDoc(doc)
|
|
183
365
|
}),
|
|
@@ -205,11 +387,38 @@ export function resetModelsStoreCache(): void {
|
|
|
205
387
|
* Fetch one route's model list from pi.dev with ETag/304 revalidation.
|
|
206
388
|
*
|
|
207
389
|
* Behavior mirrors the original withRemoteCatalog.refreshModels:
|
|
208
|
-
* - 304 →
|
|
209
|
-
* - 404/501 →
|
|
390
|
+
* - 304 → refresh checkedAt only (everything else falls through to current via the seed)
|
|
391
|
+
* - 404/501 → empty overlay, return empty
|
|
210
392
|
* - transient failure → keep cached entries, return error message
|
|
211
393
|
* - success → parse + store + return entries
|
|
212
394
|
*
|
|
395
|
+
* C1 fix (2026-09-04): the four write paths used to spread the route's
|
|
396
|
+
* pre-fetch snapshot into the written entry — most notably re-attaching
|
|
397
|
+
* `overrides: stored?.overrides` — which clobbered any out-of-band field
|
|
398
|
+
* staged by a concurrent round (e.g. an overlapping auto-refresh whose
|
|
399
|
+
* `persistOverridesToStore` ran between this round's `store.read(route)`
|
|
400
|
+
* and `store.write(...)`). Every status path now calls
|
|
401
|
+
* `effectiveStore.update(route, patch)` with a fetch-owned patch — the
|
|
402
|
+
* queue-internal field-level seed re-reads the route's current entry
|
|
403
|
+
* inside the queue and only overrides the fields the patch names
|
|
404
|
+
* (`models` / `checkedAt` / `lastModified` / `etag`; the 304 path
|
|
405
|
+
* narrows this to just `checkedAt`). Out-of-band fields — notably
|
|
406
|
+
* `overrides`, plus anything a future caller stages — are preserved
|
|
407
|
+
* verbatim because the seed only writes fields the patch actually
|
|
408
|
+
* supplies. The pre-fetch `stored` snapshot stays in scope only for
|
|
409
|
+
* conditional checks (304 ETag match, 4h throttle) and to seed the
|
|
410
|
+
* fall-back models/lastModified/etag values on error paths — it never
|
|
411
|
+
* participates in the write payload.
|
|
412
|
+
*
|
|
413
|
+
* B1 fix: the seed gives every persisted entry an unconditional shape
|
|
414
|
+
* — models / checkedAt / lastModified / etag / overrides (the last
|
|
415
|
+
* three may be undefined, but models is always an array and checkedAt
|
|
416
|
+
* is always a number). A `updateOverrides` stage on an ENOENT / corrupt
|
|
417
|
+
* doc now lands an entry the next round can consume; the previous
|
|
418
|
+
* `{...current, ...patch}` spread left the entry incomplete
|
|
419
|
+
* (`{overrides}-only`) and crashed `fetchRemoteCatalog` on the stale
|
|
420
|
+
* read because `stored.models` was undefined.
|
|
421
|
+
*
|
|
213
422
|
* @param route The provider route id (e.g. 'opencode-go')
|
|
214
423
|
* @param timeout Abort budget in ms (default 30s)
|
|
215
424
|
* @param store Optional override for the models-store accessor (testing)
|
|
@@ -224,8 +433,11 @@ export async function fetchRemoteCatalog(
|
|
|
224
433
|
const effectiveStore = store ?? loadModelsStore(options?.storePath)
|
|
225
434
|
const stored = await effectiveStore.read(route)
|
|
226
435
|
|
|
227
|
-
// I-5: throttle — return cached entries if checkedAt is within revalidation interval
|
|
228
|
-
|
|
436
|
+
// I-5: throttle — return cached entries if checkedAt is within revalidation interval.
|
|
437
|
+
// Optional chaining on `models` is defensive: the field-level seed (B1) always seeds
|
|
438
|
+
// `models: []` at minimum, so a missing field here means a legacy entry written
|
|
439
|
+
// before the seed landed — treat it as "no cached entries" rather than crashing.
|
|
440
|
+
if (!options?.force && stored !== undefined && (stored.models?.length ?? 0) > 0) {
|
|
229
441
|
const elapsed = Date.now() - stored.checkedAt
|
|
230
442
|
if (elapsed >= 0 && elapsed < REMOTE_CATALOG_REFRESH_INTERVAL_MS) {
|
|
231
443
|
return { entries: stored.models, fromCache: true }
|
|
@@ -251,33 +463,41 @@ export async function fetchRemoteCatalog(
|
|
|
251
463
|
|
|
252
464
|
const checkedAt = Date.now()
|
|
253
465
|
|
|
254
|
-
// 304: body unchanged, just refresh checkedAt
|
|
466
|
+
// 304: body unchanged, just refresh checkedAt. The patch is narrowed to
|
|
467
|
+
// { checkedAt }: the seed merge preserves models / lastModified / etag /
|
|
468
|
+
// overrides from the route's current entry, so re-naming them on a 304
|
|
469
|
+
// is unnecessary (and previously risked a clobber if a concurrent round
|
|
470
|
+
// had staged one of those fields between the snapshot read and the
|
|
471
|
+
// write — N1).
|
|
255
472
|
if (response.status === 304 && stored) {
|
|
256
|
-
await effectiveStore.
|
|
473
|
+
await effectiveStore.update(route, { checkedAt })
|
|
257
474
|
return { entries: stored.models, fromCache: true }
|
|
258
475
|
}
|
|
259
476
|
|
|
260
|
-
// 404/501: provider not found on pi.dev; store empty overlay
|
|
477
|
+
// 404/501: provider not found on pi.dev; store empty overlay. The
|
|
478
|
+
// patch omits `etag` (and `overrides`) so the seed preserves both
|
|
479
|
+
// from the route's current entry — the next round's conditional
|
|
480
|
+
// request still uses the cached etag, harmless if the resource is
|
|
481
|
+
// truly gone (server replies 404/501 again) and useful if it comes
|
|
482
|
+
// back (server replies 304). lastModified is zeroed so the catalog
|
|
483
|
+
// metadata reflects "no known server-side last-mod time".
|
|
261
484
|
if (response.status === 404 || response.status === 501) {
|
|
262
|
-
|
|
485
|
+
await effectiveStore.update(route, {
|
|
263
486
|
models: stored?.models ?? [],
|
|
264
487
|
checkedAt,
|
|
265
488
|
lastModified: 0,
|
|
266
|
-
|
|
267
|
-
}
|
|
268
|
-
await effectiveStore.write(route, entry)
|
|
489
|
+
})
|
|
269
490
|
return { entries: [], fromCache: false }
|
|
270
491
|
}
|
|
271
492
|
|
|
272
493
|
// Transient failure: keep cached entries, report error
|
|
273
494
|
if (!response.ok) {
|
|
274
|
-
|
|
495
|
+
await effectiveStore.update(route, {
|
|
275
496
|
models: stored?.models ?? [],
|
|
276
497
|
checkedAt,
|
|
277
498
|
lastModified: stored?.lastModified ?? 0,
|
|
278
499
|
etag: stored?.etag,
|
|
279
|
-
}
|
|
280
|
-
await effectiveStore.write(route, entry)
|
|
500
|
+
})
|
|
281
501
|
return {
|
|
282
502
|
entries: stored?.models ?? [],
|
|
283
503
|
fromCache: false,
|
|
@@ -290,13 +510,12 @@ export async function fetchRemoteCatalog(
|
|
|
290
510
|
const lastModified = Date.parse(response.headers.get('last-modified') ?? '')
|
|
291
511
|
const etag = response.headers.get('etag') ?? undefined
|
|
292
512
|
|
|
293
|
-
|
|
513
|
+
await effectiveStore.update(route, {
|
|
294
514
|
models: refreshed,
|
|
295
515
|
checkedAt,
|
|
296
516
|
lastModified: Number.isNaN(lastModified) ? 0 : lastModified,
|
|
297
517
|
etag,
|
|
298
|
-
}
|
|
299
|
-
await effectiveStore.write(route, storeEntry)
|
|
518
|
+
})
|
|
300
519
|
|
|
301
520
|
return { entries: refreshed, fromCache: false }
|
|
302
521
|
} catch (err: unknown) {
|