@aiwayds/dsh-model-sync 0.5.0 → 0.6.0
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 +13 -10
- package/README.zh-CN.md +14 -9
- package/cordis.patch.yml +5 -4
- package/icon.svg +6 -0
- package/lib/builtin-catalog-snapshot.d.ts +9 -0
- package/lib/builtin-catalog-snapshot.js +2 -2
- package/lib/builtin-catalog-snapshot.js.map +1 -1
- package/lib/index.d.ts +149 -1
- package/lib/index.js +120 -42
- package/lib/index.js.map +1 -1
- package/lib/provider-native.d.ts +124 -0
- package/lib/provider-native.js +202 -0
- package/lib/provider-native.js.map +1 -0
- package/lib/route-credential.d.ts +2 -1
- package/lib/route-credential.js.map +1 -1
- package/lib/translate.d.ts +8 -0
- package/lib/translate.js.map +1 -1
- package/lib/writer.d.ts +2 -1
- package/lib/writer.js.map +1 -1
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +26 -23
- package/src/builtin-catalog-snapshot.ts +11 -2
- package/src/index.ts +165 -54
- package/src/provider-native.ts +293 -0
- package/src/route-credential.ts +2 -1
- package/src/translate.ts +8 -0
- package/src/writer.ts +2 -1
package/src/index.ts
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
*
|
|
7
7
|
* Supports two write modes:
|
|
8
8
|
* - 'settings' (default): self-contained fetch → translate → settings.mutate
|
|
9
|
-
* pipeline that writes
|
|
9
|
+
* pipeline that writes through the host settings service (zero patch
|
|
10
|
+
* required; settings.yaml up to dsh 0.1.6, the profile patch on 0.1.7+)
|
|
10
11
|
* - 'overlay' (legacy): uses the patched dsh-llm-pi-ai's piAiCatalog.refresh()
|
|
11
12
|
* to overlay pi.dev entries in memory (requires patch)
|
|
12
13
|
*
|
|
@@ -35,6 +36,7 @@ import {
|
|
|
35
36
|
type SettingsModelProfile,
|
|
36
37
|
type TranslateOptions,
|
|
37
38
|
type DropWarning,
|
|
39
|
+
type BuiltinModelData,
|
|
38
40
|
} from './translate.ts'
|
|
39
41
|
import {
|
|
40
42
|
syncToSettings,
|
|
@@ -45,60 +47,102 @@ import {
|
|
|
45
47
|
import { BUILTIN_CATALOG_SNAPSHOT } from './builtin-catalog-snapshot.ts'
|
|
46
48
|
import { refreshLiveCatalog, getLiveBuiltinCatalogForRoute } from './live-catalog.ts'
|
|
47
49
|
import { checkRouteCredential, type RouteCredentialContext } from './route-credential.ts'
|
|
50
|
+
import {
|
|
51
|
+
PROVIDER_NATIVE_ENDPOINTS,
|
|
52
|
+
fetchProviderNativeModels,
|
|
53
|
+
mergeProviderNativeEntries,
|
|
54
|
+
resolveRouteCredentialValue,
|
|
55
|
+
type NativeCredentialContext,
|
|
56
|
+
} from './provider-native.ts'
|
|
48
57
|
|
|
49
58
|
export const name = 'dsh-model-sync'
|
|
50
59
|
|
|
51
60
|
/** The settings seam this plugin consumes (its own config namespace). */
|
|
52
61
|
export const inject = ['settings']
|
|
53
62
|
|
|
54
|
-
// dsh-settings 0.1.
|
|
55
|
-
//
|
|
56
|
-
//
|
|
57
|
-
//
|
|
58
|
-
|
|
63
|
+
// dsh-settings 0.1.7 rewrote the seam: the runtime register(ns, schema) call
|
|
64
|
+
// is gone, and a plugin's settings form is projected from its exported
|
|
65
|
+
// `Config` schema — the namespace IS the profile entry id. The bundle patch
|
|
66
|
+
// mounts this plugin under the stable id below, so `dsh-model-sync` is the
|
|
67
|
+
// namespace the settings UI (and the legacy settings.yaml import) address.
|
|
68
|
+
const OWN_ENTRY_ID = 'dsh-model-sync'
|
|
59
69
|
|
|
60
|
-
/**
|
|
61
|
-
|
|
70
|
+
/**
|
|
71
|
+
* The plugin's `Config` schema: the settings form the 0.1.7 host projects from
|
|
72
|
+
* the `dsh-model-sync` entry. Every field is user-adjustable and therefore
|
|
73
|
+
* `.volatile()` — volatile fields are the only ones the settings page can edit
|
|
74
|
+
* (and the only ones the legacy settings.yaml import accepts), and they hot-
|
|
75
|
+
* reload without remounting the plugin. Requires schemastery >= 3.18.4 (the
|
|
76
|
+
* version the dsh 0.1.7 wave ships), which provides `.volatile()`.
|
|
77
|
+
*/
|
|
78
|
+
export const Config = z.object({
|
|
62
79
|
/**
|
|
63
80
|
* Write mode: 'settings' (default, zero-patch settings.mutate pipeline) or
|
|
64
81
|
* 'overlay' (legacy, delegates to the patched adapter's piAiCatalog.refresh
|
|
65
82
|
* and requires the optional patch).
|
|
66
83
|
*/
|
|
67
|
-
writeMode: z.union(['settings', 'overlay']).default('settings'),
|
|
84
|
+
writeMode: z.union(['settings', 'overlay']).default('settings').volatile(),
|
|
68
85
|
/** Minutes between auto refreshes (default 240 = 4 hours); 0 = startup-only. */
|
|
69
|
-
intervalMinutes: z.number().step(1).min(0).default(240),
|
|
86
|
+
intervalMinutes: z.number().step(1).min(0).default(240).volatile(),
|
|
70
87
|
/** Delay before the first auto refresh, so the llm adapter is ready. */
|
|
71
|
-
startupDelaySeconds: z.number().step(1).min(0).default(5),
|
|
88
|
+
startupDelaySeconds: z.number().step(1).min(0).default(5).volatile(),
|
|
72
89
|
/** Abort budget for one forced refresh's network round. */
|
|
73
|
-
refreshTimeoutMs: z.number().step(1).min(1000).default(120000),
|
|
90
|
+
refreshTimeoutMs: z.number().step(1).min(1000).default(120000).volatile(),
|
|
74
91
|
/** Routes to manage (empty = all pi.dev routes). */
|
|
75
|
-
managedRoutes: z.array(z.string()).default([]),
|
|
92
|
+
managedRoutes: z.array(z.string()).default([]).volatile(),
|
|
76
93
|
/** Keep builtin-only models not in pi.dev (smooth migration). */
|
|
77
|
-
keepBuiltinOnly: z.boolean().default(true),
|
|
94
|
+
keepBuiltinOnly: z.boolean().default(true).volatile(),
|
|
78
95
|
/** Drop unserviceable entries (true) or abort the entire route (false). */
|
|
79
|
-
dropUnserviceable: z.boolean().default(true),
|
|
96
|
+
dropUnserviceable: z.boolean().default(true).volatile(),
|
|
97
|
+
/**
|
|
98
|
+
* Union each mapped route's first-party /models listing into the pi.dev
|
|
99
|
+
* result (additions only — see provider-native.ts). Default on: the native
|
|
100
|
+
* listing is the fresher source; pi.dev lags (measured 2026-09-22).
|
|
101
|
+
*/
|
|
102
|
+
providerNativeFetch: z.boolean().default(true).volatile(),
|
|
80
103
|
/** Notify on changes (logger + /model-sync report). */
|
|
81
|
-
syncNotify: z.boolean().default(false),
|
|
104
|
+
syncNotify: z.boolean().default(false).volatile(),
|
|
82
105
|
/**
|
|
83
106
|
* Force all models with a non-empty thinkingFormat to have max reasoning
|
|
84
107
|
* effort. Skips S2 gate's SRE check, ensures reasoningEfforts contains
|
|
85
108
|
* max, and forces compat.supportsReasoningEffort=true (S5 gate, openai-
|
|
86
109
|
* completions only). 400 risk is on the user.
|
|
87
110
|
*/
|
|
88
|
-
forceMaxReasoningEffort: z.boolean().default(false),
|
|
111
|
+
forceMaxReasoningEffort: z.boolean().default(false).volatile(),
|
|
112
|
+
/**
|
|
113
|
+
* keepBuiltinOnly may re-emit builtin ids the official default model list
|
|
114
|
+
* dropped (dsh 0.1.7 removed deepseek-v4-flash / deepseek-v4-flash-vision-
|
|
115
|
+
* exp). Those stay in the snapshot for historical user configurations but
|
|
116
|
+
* are excluded from the synced list unless this flag opts them back in —
|
|
117
|
+
* a re-emitted retired id is a model the 0.1.7 host no longer resolves.
|
|
118
|
+
*/
|
|
119
|
+
keepDeprecatedBuiltin: z.boolean().default(false).volatile(),
|
|
89
120
|
})
|
|
90
121
|
|
|
91
|
-
/**
|
|
122
|
+
/**
|
|
123
|
+
* A stable configuration reference — the protocol the 0.1.7 host hands the
|
|
124
|
+
* plugin for every volatile `Config` field (cosmokit's `Volatile<T>`, declared
|
|
125
|
+
* locally as a structural type so this module stays dependency-free). `get()`
|
|
126
|
+
* returns the current immutable snapshot; the host swaps the value in place on
|
|
127
|
+
* volatile-only edits, so reading per round is always fresh.
|
|
128
|
+
*/
|
|
129
|
+
interface VolatileRef<T> {
|
|
130
|
+
get(): T
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Typed view of the resolved `Config` value as delivered to apply(). */
|
|
92
134
|
interface ModelSyncConfigValue {
|
|
93
|
-
writeMode: '
|
|
94
|
-
intervalMinutes: number
|
|
95
|
-
startupDelaySeconds: number
|
|
96
|
-
refreshTimeoutMs: number
|
|
97
|
-
managedRoutes: string[]
|
|
98
|
-
keepBuiltinOnly: boolean
|
|
99
|
-
dropUnserviceable: boolean
|
|
100
|
-
syncNotify: boolean
|
|
101
|
-
forceMaxReasoningEffort: boolean
|
|
135
|
+
writeMode: VolatileRef<'settings' | 'overlay'>
|
|
136
|
+
intervalMinutes: VolatileRef<number>
|
|
137
|
+
startupDelaySeconds: VolatileRef<number>
|
|
138
|
+
refreshTimeoutMs: VolatileRef<number>
|
|
139
|
+
managedRoutes: VolatileRef<readonly string[]>
|
|
140
|
+
keepBuiltinOnly: VolatileRef<boolean>
|
|
141
|
+
dropUnserviceable: VolatileRef<boolean>
|
|
142
|
+
syncNotify: VolatileRef<boolean>
|
|
143
|
+
forceMaxReasoningEffort: VolatileRef<boolean>
|
|
144
|
+
providerNativeFetch: VolatileRef<boolean>
|
|
145
|
+
keepDeprecatedBuiltin: VolatileRef<boolean>
|
|
102
146
|
}
|
|
103
147
|
|
|
104
148
|
/** The llm seam as this plugin needs it (overlay mode). */
|
|
@@ -138,8 +182,12 @@ const DEFAULT_ROUTES = [
|
|
|
138
182
|
* runtime surface; subject to change without notice. */
|
|
139
183
|
export const DEFAULT_ROUTES_LIST = DEFAULT_ROUTES
|
|
140
184
|
|
|
141
|
-
export function apply(ctx: Context): void {
|
|
142
|
-
|
|
185
|
+
export function apply(ctx: Context, config: ModelSyncConfigValue): void {
|
|
186
|
+
// On dsh 0.1.7 the resolved Config arrives as apply()'s second argument:
|
|
187
|
+
// every volatile field is a stable reference (see VolatileRef), so the
|
|
188
|
+
// reads below are live views — no scope.get() and no scope.watch() (both
|
|
189
|
+
// removed from dsh-settings; the hot-reload notification moved to the
|
|
190
|
+
// settings/document-updated event, subscribed at the bottom of apply()).
|
|
143
191
|
|
|
144
192
|
// -----------------------------------------------------------------------
|
|
145
193
|
// Overlay mode sync (existing behavior)
|
|
@@ -180,7 +228,7 @@ export function apply(ctx: Context): void {
|
|
|
180
228
|
const before = await list()
|
|
181
229
|
const errors = await catalog.refresh({
|
|
182
230
|
force,
|
|
183
|
-
signal: AbortSignal.timeout(config.refreshTimeoutMs),
|
|
231
|
+
signal: AbortSignal.timeout(config.refreshTimeoutMs.get()),
|
|
184
232
|
})
|
|
185
233
|
const after = await list()
|
|
186
234
|
|
|
@@ -219,8 +267,9 @@ export function apply(ctx: Context): void {
|
|
|
219
267
|
const lines: string[] = []
|
|
220
268
|
|
|
221
269
|
// Determine routes to sync
|
|
222
|
-
const
|
|
223
|
-
|
|
270
|
+
const managedRoutes = config.managedRoutes.get()
|
|
271
|
+
const routes = managedRoutes.length > 0
|
|
272
|
+
? [...managedRoutes]
|
|
224
273
|
: DEFAULT_ROUTES
|
|
225
274
|
|
|
226
275
|
const gateDesc = settings?.describe().find((d) => d.ns === 'llm-pi-ai')
|
|
@@ -240,7 +289,7 @@ export function apply(ctx: Context): void {
|
|
|
240
289
|
}
|
|
241
290
|
|
|
242
291
|
// Fetch from pi.dev — pass force to bypass revalidation throttle (I-5)
|
|
243
|
-
const result = await fetchRemoteCatalog(route, config.refreshTimeoutMs, store, { force })
|
|
292
|
+
const result = await fetchRemoteCatalog(route, config.refreshTimeoutMs.get(), store, { force })
|
|
244
293
|
|
|
245
294
|
if (result.error !== undefined && result.entries.length === 0) {
|
|
246
295
|
lines.push(`${route}: fetch failed (${result.error}); keeping last-good`)
|
|
@@ -254,10 +303,10 @@ export function apply(ctx: Context): void {
|
|
|
254
303
|
|
|
255
304
|
// Translate
|
|
256
305
|
const translateOpts: TranslateOptions = {
|
|
257
|
-
keepBuiltinOnly: config.keepBuiltinOnly,
|
|
258
|
-
dropUnserviceable: config.dropUnserviceable,
|
|
306
|
+
keepBuiltinOnly: config.keepBuiltinOnly.get(),
|
|
307
|
+
dropUnserviceable: config.dropUnserviceable.get(),
|
|
259
308
|
dropWarnings: [],
|
|
260
|
-
forceMaxReasoningEffort: config.forceMaxReasoningEffort,
|
|
309
|
+
forceMaxReasoningEffort: config.forceMaxReasoningEffort.get(),
|
|
261
310
|
}
|
|
262
311
|
|
|
263
312
|
// For builtin catalog snapshot: we use a mock for now since we can't
|
|
@@ -265,13 +314,55 @@ export function apply(ctx: Context): void {
|
|
|
265
314
|
// base-matching classification. In a real deployment, this would come
|
|
266
315
|
// from the built-in snapshot file.
|
|
267
316
|
const builtinData = getBuiltinCatalogForRoute(route)
|
|
317
|
+
|
|
318
|
+
// Provider-native union: fold the route's first-party /models listing
|
|
319
|
+
// (the fresher source — pi.dev lags; measured 2026-09-22) into the
|
|
320
|
+
// pi.dev result. Additions only, capacities only where the listing
|
|
321
|
+
// states them; any failure degrades to the pi.dev list unchanged so a
|
|
322
|
+
// native hiccup can never lose models.
|
|
323
|
+
let entries = result.entries
|
|
324
|
+
if (config.providerNativeFetch.get() && PROVIDER_NATIVE_ENDPOINTS[route] !== undefined) {
|
|
325
|
+
const apiKey = await resolveRouteCredentialValue(
|
|
326
|
+
ctx as unknown as NativeCredentialContext,
|
|
327
|
+
gateDesc,
|
|
328
|
+
route,
|
|
329
|
+
)
|
|
330
|
+
if (apiKey === undefined) {
|
|
331
|
+
lines.push(`${route}: provider-native skipped — credential value unavailable`)
|
|
332
|
+
} else {
|
|
333
|
+
const native = await fetchProviderNativeModels(route, apiKey, config.refreshTimeoutMs.get())
|
|
334
|
+
if (native.ok) {
|
|
335
|
+
// Base-less synthesis needs the route's one addressable api;
|
|
336
|
+
// unknown or mixed-protocol routes skip synthesis wholesale.
|
|
337
|
+
const routeApis = [...new Set(builtinData.map((b) => b.api))]
|
|
338
|
+
const merged = mergeProviderNativeEntries(
|
|
339
|
+
entries,
|
|
340
|
+
native,
|
|
341
|
+
route,
|
|
342
|
+
routeApis.length === 1 ? routeApis[0] : undefined,
|
|
343
|
+
)
|
|
344
|
+
entries = merged.entries
|
|
345
|
+
if (merged.addedIds.length > 0) {
|
|
346
|
+
lines.push(
|
|
347
|
+
`${route}: provider-native added ${merged.addedIds.join(', ')} (${native.ids.length} ids from first-party listing)`,
|
|
348
|
+
)
|
|
349
|
+
}
|
|
350
|
+
if (merged.skippedReason !== undefined) {
|
|
351
|
+
lines.push(`${route}: provider-native ${merged.skippedReason}`)
|
|
352
|
+
}
|
|
353
|
+
} else {
|
|
354
|
+
lines.push(`${route}: provider-native ${native.error} — pi.dev list only`)
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
268
359
|
const builtinIds = new Set(builtinData.map((b) => b.id))
|
|
269
|
-
const builtinOnlyEntries =
|
|
270
|
-
? getBuiltinOnlyEntries(route,
|
|
360
|
+
const builtinOnlyEntries = translateOpts.keepBuiltinOnly
|
|
361
|
+
? getBuiltinOnlyEntries(route, entries, builtinData, config.keepDeprecatedBuiltin.get())
|
|
271
362
|
: undefined
|
|
272
363
|
|
|
273
364
|
const translated = translateEntries(
|
|
274
|
-
|
|
365
|
+
entries,
|
|
275
366
|
builtinIds,
|
|
276
367
|
builtinData,
|
|
277
368
|
route,
|
|
@@ -365,16 +456,19 @@ export function apply(ctx: Context): void {
|
|
|
365
456
|
// Unified syncNow
|
|
366
457
|
// -----------------------------------------------------------------------
|
|
367
458
|
const syncNow = async (force: boolean): Promise<string> => {
|
|
368
|
-
|
|
459
|
+
// Read the live refs up front; the volatile snapshots are fresh per call.
|
|
460
|
+
const writeMode = config.writeMode.get()
|
|
461
|
+
const managedRoutes = config.managedRoutes.get()
|
|
462
|
+
const routes = managedRoutes.length > 0 ? [...managedRoutes] : DEFAULT_ROUTES
|
|
369
463
|
|
|
370
464
|
// Prefer the host's live pi-ai catalog for this round; the frozen
|
|
371
465
|
// snapshot is only the no-host fallback. Without this, keepBuiltinOnly
|
|
372
466
|
// re-emits ids the host's catalog has already dropped. Awaiting keeps the
|
|
373
467
|
// `which`/`npm` probes off the host's event loop (they used to block every
|
|
374
468
|
// surface for ~0.2s per round).
|
|
375
|
-
await refreshLiveCatalog(
|
|
469
|
+
await refreshLiveCatalog(routes)
|
|
376
470
|
|
|
377
|
-
if (
|
|
471
|
+
if (writeMode === 'settings') {
|
|
378
472
|
return syncSettings(config, force)
|
|
379
473
|
}
|
|
380
474
|
|
|
@@ -416,16 +510,22 @@ export function apply(ctx: Context): void {
|
|
|
416
510
|
if (startupTimer !== undefined) clearTimeout(startupTimer)
|
|
417
511
|
})
|
|
418
512
|
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
513
|
+
// Volatile fields are stable references, so the initial arms read them once
|
|
514
|
+
// and the interval keeps working; the hot-reload notification arrives as a
|
|
515
|
+
// settings/document-updated event (the 0.1.7 replacement for scope.watch).
|
|
516
|
+
startupTimer = setTimeout(runAuto, Math.max(0, config.startupDelaySeconds.get() ?? 5) * 1000)
|
|
517
|
+
armInterval(config.intervalMinutes.get() ?? 240)
|
|
518
|
+
ctx.effect(() => ctx.on('settings/document-updated', (ns) => {
|
|
519
|
+
// Only this plugin's entry (the bundle-patch id) re-arms the timers; the
|
|
520
|
+
// handler is idempotent — the refs already carry the new values, so the
|
|
521
|
+
// next round reads them fresh. Never throws: an interval re-arm is two
|
|
522
|
+
// timer calls, and a throwing settings listener is a host-side incident.
|
|
523
|
+
if (ns !== OWN_ENTRY_ID) return
|
|
524
|
+
armInterval(config.intervalMinutes.get() ?? 0)
|
|
425
525
|
// Clear any pending startup timer before setting a new one
|
|
426
526
|
if (startupTimer !== undefined) clearTimeout(startupTimer)
|
|
427
527
|
startupTimer = setTimeout(runAuto, 1000)
|
|
428
|
-
})
|
|
528
|
+
}), 'dsh-model-sync: settings/document-updated')
|
|
429
529
|
|
|
430
530
|
// The modelSync service stays exposed for UIs that want direct access. The
|
|
431
531
|
// /model-sync command itself is registered by this plugin (below) through
|
|
@@ -479,7 +579,7 @@ export function apply(ctx: Context): void {
|
|
|
479
579
|
* gets the whole llm-pi-ai namespace rejected by the alpha line's strict
|
|
480
580
|
* registration.
|
|
481
581
|
*/
|
|
482
|
-
function getBuiltinCatalogForRoute(route: string):
|
|
582
|
+
function getBuiltinCatalogForRoute(route: string): BuiltinModelData[] {
|
|
483
583
|
return getLiveBuiltinCatalogForRoute(route) ?? BUILTIN_CATALOG_SNAPSHOT[route] ?? []
|
|
484
584
|
}
|
|
485
585
|
|
|
@@ -487,17 +587,28 @@ function getBuiltinCatalogForRoute(route: string): Array<{ id: string; api: stri
|
|
|
487
587
|
* Get entries from builtin catalog that are not in pi.dev (for keepBuiltinOnly).
|
|
488
588
|
* Returns minimal RemoteCatalogEntry-shaped objects — translateEntries only
|
|
489
589
|
* reads entry.id from these, emitting {id} profiles (I-3).
|
|
590
|
+
*
|
|
591
|
+
* Deprecated snapshot entries (the official default model list dropped them —
|
|
592
|
+
* dsh 0.1.7 removed deepseek-v4-flash / deepseek-v4-flash-vision-exp) are
|
|
593
|
+
* excluded unless `includeDeprecated` opts them back in: a re-emitted retired
|
|
594
|
+
* id is a model the 0.1.7 host no longer resolves. The data itself stays in
|
|
595
|
+
* the snapshot for historical user configurations.
|
|
596
|
+
*
|
|
597
|
+
* Exported for the test suite; not part of the public runtime surface.
|
|
490
598
|
*/
|
|
491
|
-
function getBuiltinOnlyEntries(
|
|
599
|
+
export function getBuiltinOnlyEntries(
|
|
492
600
|
route: string,
|
|
493
601
|
piDevEntries: RemoteCatalogEntry[],
|
|
494
|
-
|
|
602
|
+
builtinData: BuiltinModelData[],
|
|
603
|
+
includeDeprecated = false,
|
|
495
604
|
): RemoteCatalogEntry[] {
|
|
496
605
|
const piDevIds = new Set(piDevEntries.map((e) => e.id))
|
|
497
|
-
const builtinData = getBuiltinCatalogForRoute(route)
|
|
498
606
|
|
|
499
607
|
return builtinData
|
|
500
|
-
.filter((b) =>
|
|
608
|
+
.filter((b) =>
|
|
609
|
+
!piDevIds.has(b.id)
|
|
610
|
+
&& (includeDeprecated || b.deprecated !== true)
|
|
611
|
+
)
|
|
501
612
|
.map((b) => ({
|
|
502
613
|
id: b.id,
|
|
503
614
|
name: b.id,
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
// Provider-native model-list fetch: union the pi.dev catalog with each
|
|
2
|
+
// provider's own /models endpoint — the fresher source.
|
|
3
|
+
//
|
|
4
|
+
// Why this exists: pi.dev (and the pi-ai builtin snapshot behind it) lags
|
|
5
|
+
// behind the providers. Measured 2026-09-22 against the native endpoints:
|
|
6
|
+
// DeepSeek's listing had already renamed deepseek-v4-flash → deepseek-flash
|
|
7
|
+
// while pi-ai still carried the retired id; Zhipu served glm-5.3-flashx that
|
|
8
|
+
// pi-ai did not know; Xiaomi's platform announced the V2.6 series while pi-ai
|
|
9
|
+
// stopped at v2.5. Every provider above exposes an OpenAI-shaped
|
|
10
|
+
// `GET /models` listing that answers "which ids exist" straight from the
|
|
11
|
+
// horse's mouth.
|
|
12
|
+
//
|
|
13
|
+
// Merge policy (user-mandated 2026-09-22): the listing may only ADD ids —
|
|
14
|
+
// never remove. A pi.dev entry keeps its richer metadata untouched; a
|
|
15
|
+
// native-only id is synthesized as a minimal entry. Capacities follow the
|
|
16
|
+
// same "don't guess" rule: contextWindow is written only when the listing
|
|
17
|
+
// itself states one (Moonshot's `context_length`), maxTokens never — omitting
|
|
18
|
+
// both lets dsh-llm-pi-ai fall back to the route's defaultContextWindow /
|
|
19
|
+
// defaultMaxTokens (its resolve chain `entry.x ?? base?.x ?? request.default`
|
|
20
|
+
// is exactly this policy made native).
|
|
21
|
+
//
|
|
22
|
+
// Failure policy: a failed native fetch must never lose models. It degrades
|
|
23
|
+
// to the pi.dev result unchanged and surfaces one report line; the round
|
|
24
|
+
// proceeds either way.
|
|
25
|
+
|
|
26
|
+
import type { RemoteCatalogEntry } from './remote-catalog.ts'
|
|
27
|
+
import { deriveKeyRef, getRawUserApiKeyEnv, type RouteCredentialSettingsDescriptor } from './route-credential.ts'
|
|
28
|
+
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
// Endpoint table
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
/** How the /models request authenticates. */
|
|
34
|
+
export type ProviderNativeAuth = 'bearer' | 'api-key-header'
|
|
35
|
+
|
|
36
|
+
/** One provider route's native model-listing endpoint. */
|
|
37
|
+
export interface ProviderNativeEndpoint {
|
|
38
|
+
/** Full URL of the OpenAI-shaped `GET` listing. */
|
|
39
|
+
url: string
|
|
40
|
+
/** Authentication style (Xiaomi accepts either; its docs lead with the header). */
|
|
41
|
+
auth: ProviderNativeAuth
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Provider routes with a known first-party model-listing API. Routes absent
|
|
46
|
+
* from this table (gateways like `opencode-go`, unverified providers) simply
|
|
47
|
+
* keep the pi.dev-only behavior.
|
|
48
|
+
*
|
|
49
|
+
* All endpoints verified 2026-09-22: DeepSeek/Zhipu with a live key, the rest
|
|
50
|
+
* probe-confirmed (401 vs 404 — the endpoint exists, the key was not ours to
|
|
51
|
+
* spend) plus official docs for Xiaomi (mimo.mi.com list-models) and
|
|
52
|
+
* Moonshot (platform.kimi.com OpenAPI, whose response uniquely adds
|
|
53
|
+
* `context_length` and capability flags we can lift).
|
|
54
|
+
*/
|
|
55
|
+
export const PROVIDER_NATIVE_ENDPOINTS: Readonly<Record<string, ProviderNativeEndpoint>> = {
|
|
56
|
+
deepseek: { url: 'https://api.deepseek.com/models', auth: 'bearer' },
|
|
57
|
+
'moonshotai-cn': { url: 'https://api.moonshot.cn/v1/models', auth: 'bearer' },
|
|
58
|
+
moonshotai: { url: 'https://api.moonshot.ai/v1/models', auth: 'bearer' },
|
|
59
|
+
'kimi-coding': { url: 'https://api.kimi.com/coding/v1/models', auth: 'bearer' },
|
|
60
|
+
zai: { url: 'https://api.z.ai/api/paas/v4/models', auth: 'bearer' },
|
|
61
|
+
'zai-coding-cn': { url: 'https://open.bigmodel.cn/api/coding/paas/v4/models', auth: 'bearer' },
|
|
62
|
+
xiaomi: { url: 'https://api.xiaomimimo.com/v1/models', auth: 'api-key-header' },
|
|
63
|
+
'xiaomi-token-plan-cn': { url: 'https://token-plan-cn.xiaomimimo.com/v1/models', auth: 'api-key-header' },
|
|
64
|
+
'xiaomi-token-plan-ams': { url: 'https://token-plan-ams.xiaomimimo.com/v1/models', auth: 'api-key-header' },
|
|
65
|
+
'xiaomi-token-plan-sgp': { url: 'https://token-plan-sgp.xiaomimimo.com/v1/models', auth: 'api-key-header' },
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// ---------------------------------------------------------------------------
|
|
69
|
+
// Credential value resolution
|
|
70
|
+
// ---------------------------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The credentials seam surface this module needs beyond the gate's
|
|
74
|
+
* `describe`: `resolve` returns the value itself (the gate only asks whether
|
|
75
|
+
* it is configured). Optional peer — callers tolerate its absence via the
|
|
76
|
+
* launch-environment fallback.
|
|
77
|
+
*/
|
|
78
|
+
export interface CredentialsResolveSeam {
|
|
79
|
+
resolve(ref: string): Promise<{ value: string } | undefined>
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The launch-environment snapshot surface (same as route-credential.ts). */
|
|
83
|
+
export interface LaunchEnvironmentSnapshotLike {
|
|
84
|
+
get(name: string): { value: string } | undefined
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The subset of `Context` the credential-value resolver reads. */
|
|
88
|
+
export interface NativeCredentialContext {
|
|
89
|
+
get(name: 'credentials'): CredentialsResolveSeam | undefined
|
|
90
|
+
get(name: 'launchEnvironment'): LaunchEnvironmentSnapshotLike | undefined
|
|
91
|
+
get(name: string): unknown
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Resolve one route's credential reference to its current VALUE — the same
|
|
96
|
+
* two layers `checkRouteCredential` gates on, but reading through instead of
|
|
97
|
+
* asking whether:
|
|
98
|
+
* 1. the credentials seam's `resolve(ref)` (the same per-operation read the
|
|
99
|
+
* harness itself uses before a request);
|
|
100
|
+
* 2. the launch-environment snapshot (process env fallback when the service
|
|
101
|
+
* is absent).
|
|
102
|
+
*
|
|
103
|
+
* Returns undefined when neither layer has a value; callers skip the native
|
|
104
|
+
* fetch (the pi.dev result stands) rather than fail the round.
|
|
105
|
+
*/
|
|
106
|
+
export async function resolveRouteCredentialValue(
|
|
107
|
+
ctx: NativeCredentialContext,
|
|
108
|
+
desc: RouteCredentialSettingsDescriptor | undefined,
|
|
109
|
+
route: string,
|
|
110
|
+
): Promise<string | undefined> {
|
|
111
|
+
const declared = getRawUserApiKeyEnv(desc, route)
|
|
112
|
+
const ref = declared ?? deriveKeyRef(route)
|
|
113
|
+
const REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/
|
|
114
|
+
|
|
115
|
+
if (REF_PATTERN.test(ref)) {
|
|
116
|
+
const credentials = ctx.get('credentials')
|
|
117
|
+
if (credentials !== undefined) {
|
|
118
|
+
try {
|
|
119
|
+
const resolved = await credentials.resolve(ref)
|
|
120
|
+
if (resolved !== undefined && typeof resolved.value === 'string' && resolved.value.length > 0) {
|
|
121
|
+
return resolved.value
|
|
122
|
+
}
|
|
123
|
+
} catch {
|
|
124
|
+
// Same tolerance as the gate: a half-broken seam reads as "no value
|
|
125
|
+
// here" and falls through to the environment.
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const snapshot = ctx.get('launchEnvironment') ?? {
|
|
131
|
+
get(name: string) {
|
|
132
|
+
const value = process.env[name]
|
|
133
|
+
return value !== undefined && value !== '' ? { value, source: 'process' } : undefined
|
|
134
|
+
},
|
|
135
|
+
}
|
|
136
|
+
const entry = snapshot.get(ref)
|
|
137
|
+
if (entry !== undefined && typeof entry.value === 'string' && entry.value.length > 0) {
|
|
138
|
+
return entry.value
|
|
139
|
+
}
|
|
140
|
+
return undefined
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// ---------------------------------------------------------------------------
|
|
144
|
+
// Fetch + parse
|
|
145
|
+
// ---------------------------------------------------------------------------
|
|
146
|
+
|
|
147
|
+
/** One provider's native listing outcome: the fresh truth, or why not. */
|
|
148
|
+
export type ProviderNativeResult =
|
|
149
|
+
| {
|
|
150
|
+
ok: true
|
|
151
|
+
/** Model ids exactly as the provider lists them. */
|
|
152
|
+
ids: string[]
|
|
153
|
+
/** contextWindow values the listing itself states (Moonshot `context_length`). */
|
|
154
|
+
contextById: Map<string, number>
|
|
155
|
+
}
|
|
156
|
+
| { ok: false; error: string }
|
|
157
|
+
|
|
158
|
+
/** A minimal fetch compatible enough for tests to stub. */
|
|
159
|
+
export type FetchLike = (url: string, init: { headers: Record<string, string>; signal: AbortSignal }) => Promise<{
|
|
160
|
+
ok: boolean
|
|
161
|
+
status: number
|
|
162
|
+
json(): Promise<unknown>
|
|
163
|
+
}>
|
|
164
|
+
|
|
165
|
+
function isPositiveInt(value: unknown): value is number {
|
|
166
|
+
return typeof value === 'number' && Number.isInteger(value) && value > 0
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Parse a native listing body. Accepts the OpenAI list shape
|
|
171
|
+
* `{"object":"list","data":[{"id":...}]}` and tolerates the per-provider
|
|
172
|
+
* extras (Moonshot's `context_length`; Zhipu's `created`/`owned_by`) — only
|
|
173
|
+
* string `id`s count, and only a positive-integer `context_length` is kept.
|
|
174
|
+
*/
|
|
175
|
+
export function parseProviderNativeBody(value: unknown): { ids: string[]; contextById: Map<string, number> } {
|
|
176
|
+
const ids: string[] = []
|
|
177
|
+
const contextById = new Map<string, number>()
|
|
178
|
+
if (typeof value !== 'object' || value === null) throw new Error('body is not an object')
|
|
179
|
+
const data = (value as Record<string, unknown>).data
|
|
180
|
+
if (!Array.isArray(data)) throw new Error('body has no data array')
|
|
181
|
+
for (const item of data) {
|
|
182
|
+
if (typeof item !== 'object' || item === null) continue
|
|
183
|
+
const id = (item as Record<string, unknown>).id
|
|
184
|
+
if (typeof id !== 'string' || id.length === 0) continue
|
|
185
|
+
ids.push(id)
|
|
186
|
+
const context = (item as Record<string, unknown>).context_length
|
|
187
|
+
if (isPositiveInt(context)) contextById.set(id, context)
|
|
188
|
+
}
|
|
189
|
+
if (ids.length === 0) throw new Error('data array lists no usable model ids')
|
|
190
|
+
return { ids, contextById }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Fetch one route's native model listing. Any failure (non-200, network,
|
|
195
|
+
* unparseable body) resolves to `{ ok: false, error }` — never throws, so the
|
|
196
|
+
* caller's pi.dev result is untouchable.
|
|
197
|
+
*
|
|
198
|
+
* @param route Provider route id; must have an entry in the endpoint table.
|
|
199
|
+
* @param apiKey The credential value (Bearer token / api-key header value).
|
|
200
|
+
* @param timeoutMs Abort budget.
|
|
201
|
+
* @param fetchImpl Injectable fetch (tests); defaults to the global fetch.
|
|
202
|
+
*/
|
|
203
|
+
export async function fetchProviderNativeModels(
|
|
204
|
+
route: string,
|
|
205
|
+
apiKey: string,
|
|
206
|
+
timeoutMs: number,
|
|
207
|
+
fetchImpl: FetchLike = fetch as unknown as FetchLike,
|
|
208
|
+
): Promise<ProviderNativeResult> {
|
|
209
|
+
const endpoint = PROVIDER_NATIVE_ENDPOINTS[route]
|
|
210
|
+
if (endpoint === undefined) {
|
|
211
|
+
return { ok: false, error: `no native endpoint mapped for route "${route}"` }
|
|
212
|
+
}
|
|
213
|
+
const headers: Record<string, string> = { accept: 'application/json' }
|
|
214
|
+
if (endpoint.auth === 'bearer') headers.authorization = `Bearer ${apiKey}`
|
|
215
|
+
else headers['api-key'] = apiKey
|
|
216
|
+
|
|
217
|
+
const controller = new AbortController()
|
|
218
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
|
219
|
+
try {
|
|
220
|
+
const response = await fetchImpl(endpoint.url, { headers, signal: controller.signal })
|
|
221
|
+
if (!response.ok) {
|
|
222
|
+
return { ok: false, error: `HTTP ${response.status} from ${new URL(endpoint.url).host}` }
|
|
223
|
+
}
|
|
224
|
+
const parsed = parseProviderNativeBody(await response.json())
|
|
225
|
+
return { ok: true, ...parsed }
|
|
226
|
+
} catch (err: unknown) {
|
|
227
|
+
const message = err instanceof Error ? err.message : String(err)
|
|
228
|
+
return { ok: false, error: `native listing fetch failed: ${message}` }
|
|
229
|
+
} finally {
|
|
230
|
+
clearTimeout(timer)
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// ---------------------------------------------------------------------------
|
|
235
|
+
// Union merge
|
|
236
|
+
// ---------------------------------------------------------------------------
|
|
237
|
+
|
|
238
|
+
/** Outcome of merging a native listing into a route's pi.dev entries. */
|
|
239
|
+
export interface MergedNativeResult {
|
|
240
|
+
/** pi.dev entries plus one synthesized entry per native-only id. */
|
|
241
|
+
entries: RemoteCatalogEntry[]
|
|
242
|
+
/** Native ids that were not already present and got synthesized. */
|
|
243
|
+
addedIds: string[]
|
|
244
|
+
/** Why some or all native ids could not be synthesized (routeApi unknown). */
|
|
245
|
+
skippedReason?: string
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Union a native listing into the pi.dev entries — additions only.
|
|
250
|
+
*
|
|
251
|
+
* A native id the pi.dev list already carries is ignored (pi.dev's richer
|
|
252
|
+
* metadata wins). A native-only id becomes a minimal entry: no maxTokens ever
|
|
253
|
+
* (no source states one), contextWindow only when the listing itself did
|
|
254
|
+
* (`contextById`). `routeApi` is the route's single builtin api — required so
|
|
255
|
+
* the entry can survive translate's base-less gate; routes with no resolvable
|
|
256
|
+
* api (unknown route, mixed-protocol gateway) skip synthesis wholesale with a
|
|
257
|
+
* `skippedReason` instead of emitting entries the runtime would reject.
|
|
258
|
+
*/
|
|
259
|
+
export function mergeProviderNativeEntries(
|
|
260
|
+
piDevEntries: readonly RemoteCatalogEntry[],
|
|
261
|
+
native: { ids: readonly string[]; contextById: ReadonlyMap<string, number> },
|
|
262
|
+
route: string,
|
|
263
|
+
routeApi: string | undefined,
|
|
264
|
+
): MergedNativeResult {
|
|
265
|
+
const known = new Set(piDevEntries.map((e) => e.id))
|
|
266
|
+
const addedIds: string[] = []
|
|
267
|
+
const entries: RemoteCatalogEntry[] = [...piDevEntries]
|
|
268
|
+
|
|
269
|
+
for (const id of native.ids) {
|
|
270
|
+
if (known.has(id)) continue
|
|
271
|
+
if (routeApi === undefined) {
|
|
272
|
+
return {
|
|
273
|
+
entries,
|
|
274
|
+
addedIds,
|
|
275
|
+
skippedReason: `cannot place ${native.ids.length - addedIds.length} new id(s) — route has no single builtin api to address them`,
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
const context = native.contextById.get(id)
|
|
279
|
+
entries.push({
|
|
280
|
+
id,
|
|
281
|
+
name: id,
|
|
282
|
+
api: routeApi,
|
|
283
|
+
provider: route,
|
|
284
|
+
baseUrl: '',
|
|
285
|
+
reasoning: false,
|
|
286
|
+
input: ['text'],
|
|
287
|
+
...(context !== undefined ? { contextWindow: context } : {}),
|
|
288
|
+
})
|
|
289
|
+
addedIds.push(id)
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
return { entries, addedIds }
|
|
293
|
+
}
|
package/src/route-credential.ts
CHANGED
|
@@ -62,7 +62,8 @@ export interface RouteCredentialContext {
|
|
|
62
62
|
/**
|
|
63
63
|
* The settings descriptor shape this module needs (matches writer.ts's
|
|
64
64
|
* `SettingsDescriptor`). Only `user.providers.<route>.apiKeyEnv` is read —
|
|
65
|
-
* the value the user explicitly declared in
|
|
65
|
+
* the value the user explicitly declared in the llm-pi-ai provider profile
|
|
66
|
+
* (settings.yaml up to dsh 0.1.6, the profile patch on 0.1.7+).
|
|
66
67
|
*/
|
|
67
68
|
export interface RouteCredentialSettingsDescriptor {
|
|
68
69
|
user?: Record<string, unknown>
|