@aiwayds/dsh-model-sync 0.1.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/src/index.ts ADDED
@@ -0,0 +1,405 @@
1
+ // Plan C (settings-seam): orchestrator with overlay and settings modes.
2
+
3
+ /**
4
+ * dsh-model-sync — drive the llm adapter's pi.dev catalog refresh and report
5
+ * what changed.
6
+ *
7
+ * Supports two write modes:
8
+ * - 'overlay' (default): uses the patched dsh-llm-pi-ai's piAiCatalog.refresh()
9
+ * to overlay pi.dev entries in memory (existing behavior, requires patch)
10
+ * - 'settings': self-contained fetch → translate → settings.mutate pipeline
11
+ * that writes directly to settings.yaml (zero patch required)
12
+ *
13
+ * @module dsh-model-sync
14
+ */
15
+
16
+ import z from '@deepseek-ai/schemastery'
17
+ import type { Context } from '@deepseek-ai/cordis'
18
+ import { settingsNamespace } from '@deepseek-ai/dsh-settings'
19
+ import { diffModelIds, diffEntries } from './diff.ts'
20
+ import {
21
+ fetchRemoteCatalog,
22
+ loadModelsStore,
23
+ type RemoteCatalogEntry,
24
+ } from './remote-catalog.ts'
25
+ import {
26
+ translateEntries,
27
+ type SettingsModelProfile,
28
+ type TranslateOptions,
29
+ type DropWarning,
30
+ } from './translate.ts'
31
+ import {
32
+ syncToSettings,
33
+ type SettingsService,
34
+ type SettingsDescriptor,
35
+ type Logger,
36
+ } from './writer.ts'
37
+ import { BUILTIN_CATALOG_SNAPSHOT } from './builtin-catalog-snapshot.ts'
38
+
39
+ export const name = 'dsh-model-sync'
40
+
41
+ /** The settings seam this plugin consumes (its own config namespace). */
42
+ export const inject = ['settings']
43
+
44
+ const OWN_NS = settingsNamespace('model-sync')
45
+
46
+ /** The `model-sync` settings namespace: user-editable in settings.yaml. */
47
+ const ModelSyncConfig = z.object({
48
+ /** Write mode: 'overlay' (legacy, requires patch) or 'settings' (Plan C). */
49
+ writeMode: z.union(['overlay', 'settings']).default('overlay'),
50
+ /** Minutes between auto refreshes; 0 = startup-only. */
51
+ intervalMinutes: z.number().step(1).min(0).default(60),
52
+ /** Delay before the first auto refresh, so the llm adapter is ready. */
53
+ startupDelaySeconds: z.number().step(1).min(0).default(5),
54
+ /** Abort budget for one forced refresh's network round. */
55
+ refreshTimeoutMs: z.number().step(1).min(1000).default(120000),
56
+ /** Routes to manage (empty = all pi.dev routes). */
57
+ managedRoutes: z.array(z.string()).default([]),
58
+ /** Keep builtin-only models not in pi.dev (smooth migration). */
59
+ keepBuiltinOnly: z.boolean().default(true),
60
+ /** Drop unserviceable entries (true) or abort the entire route (false). */
61
+ dropUnserviceable: z.boolean().default(true),
62
+ /** Notify on changes (logger + /models-sync report). */
63
+ syncNotify: z.boolean().default(false),
64
+ /**
65
+ * Force all models with a non-empty thinkingFormat to have max reasoning
66
+ * effort. Skips S2 gate's SRE check, ensures reasoningEfforts contains
67
+ * max, and forces compat.supportsReasoningEffort=true (S5 gate, openai-
68
+ * completions only). 400 risk is on the user.
69
+ */
70
+ forceMaxReasoningEffort: z.boolean().default(false),
71
+ })
72
+
73
+ /** Typed view of the resolved `model-sync` namespace value. */
74
+ interface ModelSyncConfigValue {
75
+ writeMode: 'overlay' | 'settings'
76
+ intervalMinutes: number
77
+ startupDelaySeconds: number
78
+ refreshTimeoutMs: number
79
+ managedRoutes: string[]
80
+ keepBuiltinOnly: boolean
81
+ dropUnserviceable: boolean
82
+ syncNotify: boolean
83
+ forceMaxReasoningEffort: boolean
84
+ }
85
+
86
+ /** The llm seam as this plugin needs it (overlay mode). */
87
+ interface LlmSeam {
88
+ listProviders?(): readonly { id: string }[]
89
+ listModels?(provider: string): Promise<readonly { id: string }[]>
90
+ }
91
+
92
+ /** The catalog-refresh seam exposed by the patched dsh-llm-pi-ai adapter. */
93
+ interface CatalogSeam {
94
+ refresh?(options: { force?: boolean; signal?: AbortSignal }): Promise<Map<string, unknown>>
95
+ }
96
+
97
+ /** The `modelSync` service surfaced to UIs: run one refresh round and get the report. */
98
+ export interface ModelSyncService {
99
+ syncNow(): Promise<string>
100
+ }
101
+
102
+ /**
103
+ * Default routes to manage when managedRoutes is empty.
104
+ *
105
+ * NOTE (intentional deviation from design doc §5.5): the design suggests
106
+ * dynamically enumerating routes from the llm adapter's provider list, but
107
+ * that requires pi.dev to have been fetched first — unavailable during
108
+ * bootstrap. A static list is the pragmatic fallback; update manually when
109
+ * new routes appear on pi.dev.
110
+ */
111
+ const DEFAULT_ROUTES = [
112
+ 'opencode-go',
113
+ 'zai-coding-cn',
114
+ 'minimax-cn',
115
+ 'xiaomi-token-plan-cn',
116
+ ]
117
+
118
+ export function apply(ctx: Context): void {
119
+ const scope = ctx.settings.register(OWN_NS, ModelSyncConfig)
120
+
121
+ // -----------------------------------------------------------------------
122
+ // Overlay mode sync (existing behavior)
123
+ // -----------------------------------------------------------------------
124
+ const syncOverlay = async (
125
+ config: ModelSyncConfigValue,
126
+ llm: LlmSeam,
127
+ force: boolean,
128
+ ): Promise<string> => {
129
+ const catalog = ctx.get('piAiCatalog') as CatalogSeam | undefined
130
+ if (catalog?.refresh === undefined) {
131
+ return 'catalog refresh is unavailable — the dsh-llm-pi-ai remote-catalog patch is not applied; the model list is the static catalog only.'
132
+ }
133
+ let providers: readonly { id: string }[]
134
+ try {
135
+ providers = llm.listProviders!()
136
+ } catch {
137
+ return 'llm service is not ready yet; try again shortly.'
138
+ }
139
+ if (providers.length === 0) return 'No providers configured under llm-pi-ai.'
140
+
141
+ const list = async (): Promise<Map<string, string[]>> => {
142
+ const out = new Map<string, string[]>()
143
+ await Promise.all(providers.map(async (provider) => {
144
+ try {
145
+ out.set(provider.id, (await llm.listModels!(provider.id)).map((model) => model.id))
146
+ } catch {
147
+ out.set(provider.id, [])
148
+ }
149
+ }))
150
+ return out
151
+ }
152
+ const before = await list()
153
+ const errors = await catalog.refresh({
154
+ force,
155
+ signal: AbortSignal.timeout(config.refreshTimeoutMs),
156
+ })
157
+ const after = await list()
158
+
159
+ const lines: string[] = []
160
+ for (const provider of providers) {
161
+ const error = errors.get(provider.id)
162
+ if (error !== undefined) {
163
+ lines.push(`${provider.id}: refresh failed (${error instanceof Error ? error.message : String(error)})`)
164
+ continue
165
+ }
166
+ const beforeIds = before.get(provider.id) ?? []
167
+ const afterIds = after.get(provider.id) ?? []
168
+ const { added, removed } = diffModelIds(beforeIds, afterIds)
169
+ if (added.length === 0 && removed.length === 0) {
170
+ lines.push(`${provider.id}: up to date (${afterIds.length} models)`)
171
+ continue
172
+ }
173
+ const parts: string[] = []
174
+ if (added.length > 0) parts.push(`+${added.join(', +')}`)
175
+ if (removed.length > 0) parts.push(`-${removed.join(', -')}`)
176
+ lines.push(`${provider.id}: ${parts.join('; ')} (now ${afterIds.length} models)`)
177
+ }
178
+ return lines.join('\n')
179
+ }
180
+
181
+ // -----------------------------------------------------------------------
182
+ // Settings mode sync (Plan C: fetch → translate → write)
183
+ // -----------------------------------------------------------------------
184
+ const syncSettings = async (
185
+ config: ModelSyncConfigValue,
186
+ force: boolean,
187
+ ): Promise<string> => {
188
+ const settings = ctx.get('settings') as SettingsService | undefined
189
+ const logger = ctx.logger as unknown as Logger
190
+ const store = loadModelsStore()
191
+ const lines: string[] = []
192
+
193
+ // Determine routes to sync
194
+ const routes = config.managedRoutes.length > 0
195
+ ? config.managedRoutes
196
+ : DEFAULT_ROUTES
197
+
198
+ for (const route of routes) {
199
+ // Fetch from pi.dev — pass force to bypass revalidation throttle (I-5)
200
+ const result = await fetchRemoteCatalog(route, config.refreshTimeoutMs, store, { force })
201
+
202
+ if (result.error !== undefined && result.entries.length === 0) {
203
+ lines.push(`${route}: fetch failed (${result.error}); keeping last-good`)
204
+ continue
205
+ }
206
+
207
+ if (result.entries.length === 0) {
208
+ lines.push(`${route}: no models from pi.dev; skipped`)
209
+ continue
210
+ }
211
+
212
+ // Translate
213
+ const translateOpts: TranslateOptions = {
214
+ keepBuiltinOnly: config.keepBuiltinOnly,
215
+ dropUnserviceable: config.dropUnserviceable,
216
+ dropWarnings: [],
217
+ forceMaxReasoningEffort: config.forceMaxReasoningEffort,
218
+ }
219
+
220
+ // For builtin catalog snapshot: we use a mock for now since we can't
221
+ // import pi-ai at runtime. The builtin catalog data is needed for
222
+ // base-matching classification. In a real deployment, this would come
223
+ // from the built-in snapshot file.
224
+ const builtinData = getBuiltinCatalogForRoute(route)
225
+ const builtinIds = new Set(builtinData.map((b) => b.id))
226
+ const builtinOnlyEntries = config.keepBuiltinOnly
227
+ ? getBuiltinOnlyEntries(route, result.entries, builtinIds)
228
+ : undefined
229
+
230
+ const translated = translateEntries(
231
+ result.entries,
232
+ builtinIds,
233
+ builtinData,
234
+ route,
235
+ translateOpts,
236
+ builtinOnlyEntries,
237
+ )
238
+
239
+ // Report drops and warnings
240
+ if (translated.dropped.length > 0) {
241
+ for (const w of translated.dropped) {
242
+ lines.push(`${route}: DROPPED ${w.id} — ${w.reason}`)
243
+ }
244
+ }
245
+ if (translated.warnings.length > 0) {
246
+ for (const w of translated.warnings) {
247
+ lines.push(`${route}: DEGRADED ${w.id} — ${w.reason}`)
248
+ }
249
+ }
250
+
251
+ // B1: abort detected — skip writer, only warn
252
+ if (translated.aborted) {
253
+ lines.push(`${route}: ABORTED — dropUnserviceable=false and ${translated.dropped.length} entries dropped; settings not written`)
254
+ continue
255
+ }
256
+
257
+ // I-6: generate added/removed diff report from current raw models
258
+ if (settings !== undefined) {
259
+ const descs = settings.describe()
260
+ const llmDesc = descs.find((d) => d.ns === 'llm-pi-ai')
261
+ const rawModels = getRawUserModelsFromDesc(llmDesc, route)
262
+ if (rawModels !== undefined) {
263
+ const entryDiff = diffEntries(rawModels, translated.entries)
264
+ if (entryDiff.added.length > 0) lines.push(`${route}: added ${entryDiff.added.join(', ')}`)
265
+ if (entryDiff.removed.length > 0) lines.push(`${route}: removed ${entryDiff.removed.join(', ')}`)
266
+ }
267
+ }
268
+
269
+ // Write to settings (change-only, with conflict retry)
270
+ const syncResult = await syncToSettings(
271
+ settings,
272
+ route,
273
+ translated.entries,
274
+ logger,
275
+ // retranslate callback for conflict retry
276
+ async (newRevision: number) => {
277
+ // Re-translate with same data (the remote data hasn't changed;
278
+ // only the settings revision changed)
279
+ void newRevision // revision is used by the caller
280
+ return translated.entries
281
+ },
282
+ )
283
+
284
+ if (syncResult.wrote) {
285
+ lines.push(`${route}: wrote ${translated.entries.length} models (${syncResult.reason})`)
286
+ } else if (syncResult.reason === 'no-change') {
287
+ lines.push(`${route}: up to date (${translated.entries.length} models)`)
288
+ } else if (syncResult.reason === 'skipped') {
289
+ lines.push(`${route}: skipped — settings service unavailable or llm-pi-ai namespace not registered`)
290
+ } else {
291
+ lines.push(`${route}: ${syncResult.reason} (${translated.entries.length} models)`)
292
+ }
293
+ }
294
+
295
+ return lines.join('\n')
296
+ }
297
+
298
+ // -----------------------------------------------------------------------
299
+ // Unified syncNow
300
+ // -----------------------------------------------------------------------
301
+ const syncNow = async (force: boolean): Promise<string> => {
302
+ const config = scope.get() as unknown as ModelSyncConfigValue
303
+
304
+ if (config.writeMode === 'settings') {
305
+ return syncSettings(config, force)
306
+ }
307
+
308
+ // Overlay mode (existing behavior)
309
+ const llm = ctx.get('llm') as LlmSeam | undefined
310
+ if (llm === undefined || llm.listProviders === undefined || llm.listModels === undefined) {
311
+ return 'llm service is not available yet; try again shortly.'
312
+ }
313
+ return syncOverlay(config, llm, force)
314
+ }
315
+
316
+ /** Auto rounds log the same report the /models-sync command shows. */
317
+ const runAuto = (): void => {
318
+ void syncNow(false).then((report) => {
319
+ for (const line of report.split('\n')) ctx.logger.info('model-sync: %s', line)
320
+ })
321
+ }
322
+
323
+ /** (Re)arm the auto-refresh interval; 0 disarms. */
324
+ const armInterval = (minutes: number): void => {
325
+ if (stopInterval !== undefined) clearInterval(stopInterval)
326
+ stopInterval = undefined
327
+ if (minutes > 0) stopInterval = setInterval(runAuto, minutes * 60_000)
328
+ }
329
+ let stopInterval: ReturnType<typeof setInterval> | undefined
330
+ let startupTimer: ReturnType<typeof setTimeout> | undefined
331
+ // One effect releases whatever timers are live at dispose.
332
+ ctx.effect(() => () => {
333
+ if (stopInterval !== undefined) clearInterval(stopInterval)
334
+ if (startupTimer !== undefined) clearTimeout(startupTimer)
335
+ })
336
+
337
+ const initial = scope.get() as unknown as ModelSyncConfigValue
338
+ startupTimer = setTimeout(runAuto, Math.max(0, initial?.startupDelaySeconds ?? 5) * 1000)
339
+ armInterval(initial?.intervalMinutes ?? 60)
340
+ scope.watch((next) => {
341
+ const value = next as unknown as ModelSyncConfigValue
342
+ armInterval(value?.intervalMinutes ?? 0)
343
+ // Clear any pending startup timer before setting a new one
344
+ if (startupTimer !== undefined) clearTimeout(startupTimer)
345
+ startupTimer = setTimeout(runAuto, 1000)
346
+ })
347
+
348
+ // The /models-sync command (registered by dsh-tui-pi) drives this service.
349
+ ctx.provide('modelSync', { syncNow: () => syncNow(true) } satisfies ModelSyncService)
350
+ }
351
+
352
+ // ---------------------------------------------------------------------------
353
+ // Builtin catalog helpers (uses shared snapshot)
354
+ // ---------------------------------------------------------------------------
355
+
356
+ /**
357
+ * Get builtin catalog data for a route from the shared snapshot module.
358
+ * Design doc §3.6: "构建期把 installed catalog 快照成常量"
359
+ */
360
+ function getBuiltinCatalogForRoute(route: string): Array<{ id: string; api: string; maxTokens?: number }> {
361
+ return BUILTIN_CATALOG_SNAPSHOT[route] ?? []
362
+ }
363
+
364
+ /**
365
+ * Get entries from builtin catalog that are not in pi.dev (for keepBuiltinOnly).
366
+ * Returns minimal RemoteCatalogEntry-shaped objects — translateEntries only
367
+ * reads entry.id from these, emitting {id} profiles (I-3).
368
+ */
369
+ function getBuiltinOnlyEntries(
370
+ route: string,
371
+ piDevEntries: RemoteCatalogEntry[],
372
+ builtinIds: Set<string>,
373
+ ): RemoteCatalogEntry[] {
374
+ const piDevIds = new Set(piDevEntries.map((e) => e.id))
375
+ const builtinData = getBuiltinCatalogForRoute(route)
376
+
377
+ return builtinData
378
+ .filter((b) => !piDevIds.has(b.id) && builtinIds.has(b.id))
379
+ .map((b) => ({
380
+ id: b.id,
381
+ name: b.id,
382
+ api: b.api,
383
+ provider: route,
384
+ baseUrl: '',
385
+ reasoning: false,
386
+ input: ['text'] as string[],
387
+ }))
388
+ }
389
+
390
+ /**
391
+ * Extract raw user-segment models for a route from a settings descriptor (I-6).
392
+ */
393
+ function getRawUserModelsFromDesc(
394
+ desc: SettingsDescriptor | undefined,
395
+ route: string,
396
+ ): SettingsModelProfile[] | undefined {
397
+ if (desc === undefined) return undefined
398
+ const providers = desc.user?.providers as Record<string, unknown> | undefined
399
+ if (providers === undefined) return undefined
400
+ const routeData = providers[route] as Record<string, unknown> | undefined
401
+ if (routeData === undefined) return undefined
402
+ const models = routeData.models
403
+ if (!Array.isArray(models)) return undefined
404
+ return models as SettingsModelProfile[]
405
+ }