cvc-catalog-sync-plugin 1.0.0 → 2.0.1

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.
@@ -0,0 +1,856 @@
1
+ /**
2
+ * Синхронизация каталога моделей с профильным патчем DSH.
3
+ *
4
+ * Функция делает то же, что плагин 1.0.0, но живёт в общем каркасе 2.0.0:
5
+ *
6
+ * 1. забирает каталог из общего кэша (`deps.cache`) — его наполняет
7
+ * `index.js` запросом `GET {baseURL}/models` ключом провайдера;
8
+ * 2. забирает установщик CVC и вытаскивает карту `reasoningLevels`
9
+ * (`deps.api.fetchLevels`, кэш на `catalog.levelsCacheMinutes`);
10
+ * 3. собирает `models` чистыми функциями `lib/catalog-build.js`;
11
+ * 4. точечно пишет результат в строку `providers.entryId` через
12
+ * `ctx.configEditor.edit()` — единственный sanctioned-путь записи: он
13
+ * сохраняет комментарии и чужие строки, пишет атомарно, а `dsh-hmr`
14
+ * перечитывает патч без перезапуска приложения;
15
+ * 5. синхронизирует `allowedModels` сабагентов (`catalog.syncAllowlist`).
16
+ *
17
+ * Сборка и проверка `minModelRatio` выполняются **внутри** колбэка `edit`: он
18
+ * отдаёт конфиг на момент блокировки, поэтому правка, сделанная между чтением
19
+ * и записью, не теряется.
20
+ *
21
+ * Контракт модуля:
22
+ * register(ctx, deps) -> () => void — маршрут `POST /cvc/run`, таймеры;
23
+ * tool(deps) -> object — инструмент `cvc_catalog`.
24
+ *
25
+ * `register` вызывается только при `features.catalogSync === true`, поэтому
26
+ * выключенная функция не оставляет ни маршрута, ни таймера, ни инструмента.
27
+ *
28
+ * @module cvc-catalog-sync-plugin/lib/catalog-sync
29
+ */
30
+ import {
31
+ buildModels,
32
+ diffModels,
33
+ guardFailureMessage,
34
+ isDiffEmpty,
35
+ modelRatioGuard,
36
+ planAllowlist,
37
+ } from './catalog-build.js'
38
+
39
+ /** Имя инструмента ручного запуска. */
40
+ export const TOOL_NAME = 'cvc_catalog'
41
+
42
+ /** Верхняя граница `setTimeout`/`setInterval` (2^31-1 мс). */
43
+ const MAX_TIMEOUT_MS = 2147483647
44
+
45
+ /** Нижняя граница периода автосинхронизации: чаще — почти непрерывные прогоны. */
46
+ const MIN_INTERVAL_MS = 60000
47
+
48
+ /** JSON-схема вывода инструмента: только поддерживаемые ключевые слова. */
49
+ export const OUTPUT_SCHEMA = {
50
+ type: 'object',
51
+ additionalProperties: false,
52
+ required: [
53
+ 'action', 'ok', 'at', 'provider', 'catalogModels', 'currentModels', 'nextModels',
54
+ 'levelsSource', 'applied', 'added', 'removed', 'changed', 'warnings', 'allowlist', 'error',
55
+ ],
56
+ properties: {
57
+ action: { type: 'string', enum: ['status', 'plan', 'apply'] },
58
+ ok: { type: 'boolean' },
59
+ at: { type: 'string' },
60
+ provider: { type: 'string' },
61
+ catalogModels: { type: 'integer' },
62
+ currentModels: { type: 'integer' },
63
+ nextModels: { type: 'integer' },
64
+ levelsSource: { type: 'string' },
65
+ applied: { type: 'boolean' },
66
+ added: { type: 'array', items: { type: 'string' } },
67
+ removed: { type: 'array', items: { type: 'string' } },
68
+ changed: {
69
+ type: 'array',
70
+ items: {
71
+ type: 'object',
72
+ additionalProperties: false,
73
+ required: ['id', 'fields'],
74
+ properties: {
75
+ id: { type: 'string' },
76
+ fields: { type: 'array', items: { type: 'string' } },
77
+ },
78
+ },
79
+ },
80
+ warnings: { type: 'array', items: { type: 'string' } },
81
+ allowlist: {
82
+ type: 'object',
83
+ additionalProperties: false,
84
+ required: ['pruned', 'added', 'skipped', 'changed'],
85
+ properties: {
86
+ pruned: { type: 'array', items: { type: 'string' } },
87
+ added: { type: 'array', items: { type: 'string' } },
88
+ skipped: { type: 'boolean' },
89
+ changed: { type: 'boolean' },
90
+ },
91
+ },
92
+ error: { type: 'string' },
93
+ },
94
+ }
95
+
96
+ /** Текст ошибки без предположения о её типе. */
97
+ function messageOf(error) {
98
+ return error instanceof Error ? error.message : String(error)
99
+ }
100
+
101
+ /** Обычный объект, не массив и не null. */
102
+ function isPlainObject(value) {
103
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
104
+ }
105
+
106
+ /** Пустой результат синхронизации allowlist. */
107
+ function emptyAllowlist() {
108
+ return { pruned: [], added: [], skipped: true, changed: false }
109
+ }
110
+
111
+ /** Конечное число в границах или умолчание. */
112
+ function numberOr(value, fallback, min) {
113
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < min) return fallback
114
+ return Math.min(Math.round(value), MAX_TIMEOUT_MS)
115
+ }
116
+
117
+ /**
118
+ * Ошибка прогона с HTTP-кодом для маршрута.
119
+ *
120
+ * `guard` и `stale` — это 409 (конфликт состояния, клиент показывает текст),
121
+ * остальные неожиданные ошибки — 500. Инструмент код не использует: он отдаёт
122
+ * `ok: false` и понятный `error`.
123
+ */
124
+ class CatalogRunError extends Error {
125
+ /**
126
+ * @param {number} status
127
+ * @param {string} message
128
+ */
129
+ constructor(status, message) {
130
+ super(message)
131
+ this.name = 'CatalogRunError'
132
+ this.status = status
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Текст результата для модели и пользователя (как в 1.0.0).
138
+ * @param {Record<string, any>} value
139
+ * @returns {string}
140
+ */
141
+ export function renderValue(value) {
142
+ const lines = [
143
+ `${value.action}: ${value.provider} — catalog ${value.catalogModels}, current ${value.currentModels}, next ${value.nextModels}; levels: ${value.levelsSource}${value.applied ? '; applied' : ''}`,
144
+ ]
145
+ if (value.added.length > 0) lines.push(`added: ${value.added.join(', ')}`)
146
+ if (value.removed.length > 0) lines.push(`removed: ${value.removed.join(', ')}`)
147
+ if (value.changed.length > 0) {
148
+ lines.push(`changed: ${value.changed.map((entry) => `${entry.id} (${entry.fields.join('/')})`).join(', ')}`)
149
+ }
150
+ if (value.added.length === 0 && value.removed.length === 0 && value.changed.length === 0) lines.push('catalog: no difference')
151
+ if (value.allowlist.pruned.length > 0) lines.push(`allowlist pruned: ${value.allowlist.pruned.join(', ')}`)
152
+ if (value.allowlist.added.length > 0) lines.push(`allowlist added: ${value.allowlist.added.join(', ')}`)
153
+ if (value.allowlist.changed && value.allowlist.pruned.length === 0 && value.allowlist.added.length === 0) {
154
+ lines.push('allowlist: duplicates or order fixed')
155
+ }
156
+ for (const warning of value.warnings) lines.push(`warning: ${warning}`)
157
+ if (value.error.length > 0) lines.push(`error: ${value.error}`)
158
+ return lines.join('\n')
159
+ }
160
+
161
+ /**
162
+ * Совпадает ли id строки с ожидаемым, включая group-префикс.
163
+ * @param {unknown} candidate
164
+ * @param {string} wanted
165
+ * @returns {boolean}
166
+ */
167
+ function sameRowId(candidate, wanted) {
168
+ return candidate === wanted || (typeof candidate === 'string' && candidate.endsWith(`:${wanted}`))
169
+ }
170
+
171
+ /**
172
+ * Активный движок на объект `deps`: `register` создаёт его один раз, а
173
+ * `tool(deps)` переиспользует, чтобы `status` видел последний прогон и
174
+ * параллельные вызовы схлопывались. Если инструмент спросили без `register`
175
+ * (например, в тесте), создаётся временный движок.
176
+ * @type {WeakMap<object, ReturnType<typeof createEngine>>}
177
+ */
178
+ const engines = new WeakMap()
179
+
180
+ /**
181
+ * Собрать движок прогонов: чтение, сборка, запись, allowlist, дедупликация.
182
+ * @param {import('@deepseek-ai/cordis').Context} ctx
183
+ * @param {object} deps
184
+ */
185
+ function createEngine(ctx, deps) {
186
+ /** Последний прогон в этом движке. */
187
+ let last = null
188
+ /** Идущий прогон: параллельный вызов с тем же режимом ждёт его. */
189
+ let inflight = null
190
+ /** Кэш карты уровней: она меняется редко, а прогонов бывает два подряд. */
191
+ let levelsCache = null
192
+
193
+ /** Сервис записи патча. */
194
+ function editor() {
195
+ return ctx.get?.('configEditor') ?? ctx.configEditor
196
+ }
197
+
198
+ /**
199
+ * Найти строку патча по id, включая `include:`-префикс.
200
+ * @param {string} id
201
+ * @returns {any}
202
+ */
203
+ function entryById(id) {
204
+ const service = editor()
205
+ if (service === null || typeof service !== 'object' || typeof service.entries !== 'function') return undefined
206
+ let entries = []
207
+ try {
208
+ entries = service.entries() ?? []
209
+ } catch {
210
+ return undefined
211
+ }
212
+ return entries.find((entry) => sameRowId(entry?.options?.id, id))
213
+ }
214
+
215
+ /**
216
+ * Модели маршрута из raw-конфига строки.
217
+ * @param {unknown} config
218
+ * @param {ReturnType<typeof deps.config>} cfg
219
+ * @returns {Array<Record<string, any>>}
220
+ */
221
+ function modelsFromConfig(config, cfg) {
222
+ const providers = isPlainObject(config) && isPlainObject(config.providers) ? config.providers : {}
223
+ const profile = providers[cfg.catalog.provider]
224
+ return isPlainObject(profile) && Array.isArray(profile.models) ? profile.models.filter(isPlainObject) : []
225
+ }
226
+
227
+ /**
228
+ * Собрать следующий raw-конфиг строки с новым списком моделей.
229
+ * @param {unknown} current
230
+ * @param {Array<Record<string, unknown>>} models
231
+ * @param {ReturnType<typeof deps.config>} cfg
232
+ * @returns {Record<string, unknown>}
233
+ */
234
+ function withModels(current, models, cfg) {
235
+ const next = isPlainObject(current) ? { ...current } : {}
236
+ const providers = isPlainObject(next.providers) ? { ...next.providers } : {}
237
+ const profile = isPlainObject(providers[cfg.catalog.provider]) ? { ...providers[cfg.catalog.provider] } : {}
238
+ profile.models = models
239
+ providers[cfg.catalog.provider] = profile
240
+ next.providers = providers
241
+ return next
242
+ }
243
+
244
+ /**
245
+ * Прочитать текущие модели маршрута из профильного патча.
246
+ * @param {ReturnType<typeof deps.config>} cfg
247
+ * @returns {{ entry: any, models: Array<Record<string, any>> }}
248
+ */
249
+ function readCurrent(cfg) {
250
+ const entry = entryById(cfg.providers.entryId)
251
+ if (entry === undefined) {
252
+ throw new CatalogRunError(409, `profile entry "${cfg.providers.entryId}" is not available`)
253
+ }
254
+ const current = isPlainObject(entry.options.config) ? entry.options.config : {}
255
+ const providers = isPlainObject(current.providers) ? current.providers : {}
256
+ const profile = providers[cfg.catalog.provider]
257
+ if (!isPlainObject(profile)) {
258
+ throw new CatalogRunError(
259
+ 409,
260
+ `provider route "${cfg.catalog.provider}" is not configured in "${cfg.providers.entryId}"`,
261
+ )
262
+ }
263
+ // llm-pi-ai отвергает `modelOverrides` рядом с `models`; сказать об этом
264
+ // самим понятнее, чем получить отказ валидации при записи.
265
+ if (isPlainObject(profile.modelOverrides) && Object.keys(profile.modelOverrides).length > 0) {
266
+ throw new CatalogRunError(
267
+ 409,
268
+ `provider route "${cfg.catalog.provider}" uses modelOverrides; a models list cannot be written beside it — `
269
+ + 'convert the route to an explicit models list first',
270
+ )
271
+ }
272
+ const models = Array.isArray(profile.models) ? profile.models.filter(isPlainObject) : []
273
+ return { entry, models }
274
+ }
275
+
276
+ /**
277
+ * Забрать карту уровней с первого ответившего установщика (кэш на минуты).
278
+ *
279
+ * Недоступность уровней не роняет прогон: существующие значения патча
280
+ * сохраняются, новые модели падают в `supports_reasoning`.
281
+ * @param {ReturnType<typeof deps.config>} cfg
282
+ * @param {AbortSignal | undefined} signal
283
+ * @returns {Promise<{ map: Record<string, string[]> | null, source: string, problems: string[] }>}
284
+ */
285
+ async function loadLevels(cfg, signal) {
286
+ if (levelsCache !== null && levelsCache.map !== null
287
+ && Date.now() - levelsCache.at < cfg.catalog.levelsCacheMinutes * 60000) {
288
+ return levelsCache
289
+ }
290
+ try {
291
+ const answer = await deps.api.fetchLevels({
292
+ urls: cfg.catalog.installerUrls,
293
+ timeoutMs: cfg.providers.timeoutMs,
294
+ signal,
295
+ })
296
+ levelsCache = { map: answer.levels, source: answer.source, at: Date.now(), problems: [] }
297
+ return levelsCache
298
+ } catch (error) {
299
+ for (const problem of String(messageOf(error)).split('; ')) deps.log('warn', problem)
300
+ levelsCache = { map: null, source: 'none', at: 0, problems: [messageOf(error)] }
301
+ return levelsCache
302
+ }
303
+ }
304
+
305
+ /**
306
+ * Записать каталог в строку маршрута, пересобрав модели по свежему конфигу.
307
+ *
308
+ * `configEditor.edit` отдаёт конфиг на момент блокировки, поэтому сборка
309
+ * внутри колбэка — единственный способ не потерять правку, сделанную между
310
+ * чтением и записью (ручной `maxTokens`, `compat`). Там же проверяется
311
+ * защита от усыхания каталога: её отказ не пишет файл.
312
+ * @param {any} entry
313
+ * @param {Array<Record<string, unknown>>} catalog
314
+ * @param {Record<string, string[]> | null} levelMap
315
+ * @param {boolean} force
316
+ * @param {ReturnType<typeof deps.config>} cfg
317
+ * @returns {Promise<{ models: Array<Record<string, unknown>>, warnings: string[], diff: ReturnType<typeof diffModels>, unchanged: boolean } | null>}
318
+ */
319
+ async function writeModels(entry, catalog, levelMap, force, cfg) {
320
+ /** @type {any} */
321
+ let outcome = null
322
+ await editor().edit(entry, (current) => {
323
+ const fresh = modelsFromConfig(current, cfg)
324
+ const built = buildModels(catalog, levelMap, fresh, { keepModels: cfg.catalog.keepModels })
325
+ const guard = modelRatioGuard(fresh.length, built.models.length, cfg.catalog.minModelRatio)
326
+ if (!force && !guard.ok) {
327
+ throw new CatalogRunError(409, guardFailureMessage({
328
+ currentModels: fresh.length,
329
+ nextModels: built.models.length,
330
+ minModelRatio: cfg.catalog.minModelRatio,
331
+ }))
332
+ }
333
+ if (force && !guard.ok) {
334
+ built.warnings.push(
335
+ `force: model-count guard bypassed (${guard.nextModels} < ${guard.minRequired}, `
336
+ + `${Math.round(guard.minModelRatio * 100)}% of current ${guard.currentModels})`,
337
+ )
338
+ }
339
+ const diff = diffModels(fresh, built.models)
340
+ outcome = { models: built.models, warnings: built.warnings, diff, unchanged: isDiffEmpty(diff) }
341
+ return withModels(current, built.models, cfg)
342
+ })
343
+ return outcome
344
+ }
345
+
346
+ /**
347
+ * Привести список доступных моделей сабагентов к каталогу маршрута.
348
+ *
349
+ * Чужие провайдеры сохраняются как есть: плагин владеет только своим
350
+ * маршрутом. Если строки нет (плагин сабагентов не установлен) — пропуск.
351
+ * @param {Array<Record<string, unknown>>} models
352
+ * @param {ReturnType<typeof deps.config>} cfg
353
+ * @returns {Promise<{ pruned: string[], added: string[], skipped: boolean, changed: boolean }>}
354
+ */
355
+ async function syncAllowlist(models, cfg) {
356
+ const empty = { pruned: [], added: [], skipped: true, changed: false }
357
+ if (!cfg.catalog.syncAllowlist) return empty
358
+ const entry = entryById(cfg.catalog.allowlistEntryId)
359
+ if (entry === undefined) return empty
360
+ const catalogIds = models
361
+ .map((model) => model.id)
362
+ .filter((id) => typeof id === 'string' && id.length > 0)
363
+ const snapshot = planAllowlist(
364
+ isPlainObject(entry.options.config) ? entry.options.config.allowedModels : [],
365
+ cfg.catalog.provider,
366
+ catalogIds,
367
+ )
368
+ if (!snapshot.changed) return { pruned: [], added: [], skipped: false, changed: false }
369
+ /** @type {{ pruned: string[], added: string[], changed: boolean } | null} */
370
+ let outcome = null
371
+ await editor().edit(entry, (cur) => {
372
+ const current = isPlainObject(cur) ? cur : {}
373
+ // Пересчёт на момент блокировки: чужой список мог измениться, пока шли
374
+ // запросы к каталогу.
375
+ const fresh = planAllowlist(current.allowedModels, cfg.catalog.provider, catalogIds)
376
+ outcome = { pruned: fresh.pruned, added: fresh.added, changed: fresh.changed }
377
+ return fresh.changed ? { ...current, allowedModels: fresh.expected } : current
378
+ })
379
+ deps.log('info', `allowed models synced: +${outcome?.added.length ?? 0}/-${outcome?.pruned.length ?? 0}`)
380
+ return {
381
+ pruned: outcome?.pruned ?? [],
382
+ added: outcome?.added ?? [],
383
+ skipped: false,
384
+ changed: outcome?.changed ?? false,
385
+ }
386
+ }
387
+
388
+ /**
389
+ * Один прогон: каталог → модели → (при необходимости) запись.
390
+ * @param {'startup' | 'timer' | 'tool'} reason
391
+ * @param {{ apply: boolean, force?: boolean, signal?: AbortSignal }} options
392
+ * @returns {Promise<Record<string, any>>}
393
+ */
394
+ async function collect(reason, options) {
395
+ const cfg = deps.config()
396
+ /** @type {Record<string, any>} */
397
+ const result = {
398
+ ok: false,
399
+ reason,
400
+ at: new Date().toISOString(),
401
+ provider: cfg.catalog.provider,
402
+ catalogModels: 0,
403
+ currentModels: 0,
404
+ nextModels: 0,
405
+ levelsSource: 'none',
406
+ applied: false,
407
+ added: [],
408
+ removed: [],
409
+ changed: [],
410
+ warnings: [],
411
+ allowlist: emptyAllowlist(),
412
+ error: '',
413
+ errorStatus: 500,
414
+ }
415
+ try {
416
+ const snapshot = await deps.cache.get({ force: true })
417
+ const catalog = Array.isArray(snapshot?.data?.models) ? snapshot.data.models : []
418
+ result.catalogModels = catalog.length
419
+ const staleMessage = typeof snapshot?.error === 'string' && snapshot.error.length > 0
420
+ ? snapshot.error
421
+ : 'upstream is unavailable'
422
+ if (snapshot?.stale === true) {
423
+ if (options.apply === true && options.force !== true) {
424
+ throw new CatalogRunError(
425
+ 409,
426
+ `catalog is stale (${staleMessage}); nothing written, use force to override`,
427
+ )
428
+ }
429
+ result.warnings.push(options.apply === true
430
+ ? `force: stale catalog applied (${staleMessage})`
431
+ : `catalog is stale: ${staleMessage}`)
432
+ }
433
+ if (catalog.length === 0) {
434
+ throw new CatalogRunError(409, 'catalog returned no models; nothing written')
435
+ }
436
+
437
+ const levels = await loadLevels(cfg, options.signal)
438
+ result.levelsSource = levels.source
439
+ if (levels.map === null) {
440
+ result.warnings.push('reasoning levels unavailable: existing levels preserved, new models fall back to supports_reasoning')
441
+ }
442
+
443
+ const current = readCurrent(cfg)
444
+ result.currentModels = current.models.length
445
+
446
+ const built = buildModels(catalog, levels.map, current.models, { keepModels: cfg.catalog.keepModels })
447
+ result.nextModels = built.models.length
448
+ const warningsBeforeBuild = result.warnings.length
449
+ result.warnings.push(...built.warnings)
450
+
451
+ const diff = diffModels(current.models, built.models)
452
+ result.added = diff.added
453
+ result.removed = diff.removed
454
+ result.changed = diff.changed
455
+
456
+ const unchanged = isDiffEmpty(diff)
457
+
458
+ if (options.apply !== true) {
459
+ // plan ничего не пишет, поэтому защита от усыхания сообщается
460
+ // предупреждением, а не отказом: дифф увидеть нужно.
461
+ if (!unchanged && options.force !== true) {
462
+ const guard = modelRatioGuard(current.models.length, built.models.length, cfg.catalog.minModelRatio)
463
+ if (!guard.ok) {
464
+ result.warnings.push(
465
+ `guard: ${guard.nextModels} models is below ${guard.minRequired} `
466
+ + `(${Math.round(guard.minModelRatio * 100)}% of current ${guard.currentModels}); `
467
+ + 'apply would refuse without force',
468
+ )
469
+ }
470
+ }
471
+ result.ok = true
472
+ return result
473
+ }
474
+
475
+ if (unchanged) {
476
+ // Модели совпадают, но список сабагентов мог разъехаться: чиним его.
477
+ result.ok = true
478
+ try {
479
+ result.allowlist = await syncAllowlist(current.models, cfg)
480
+ // Патч всё-таки записан — отчитываемся честно.
481
+ result.applied = result.allowlist.changed
482
+ } catch (error) {
483
+ result.warnings.push(`allowed models not synced: ${messageOf(error)}`)
484
+ }
485
+ return result
486
+ }
487
+
488
+ const outcome = await writeModels(current.entry, catalog, levels.map, options.force === true, cfg)
489
+ result.applied = outcome !== null && !outcome.unchanged
490
+ if (outcome !== null) {
491
+ result.nextModels = outcome.models.length
492
+ result.added = outcome.diff.added
493
+ result.removed = outcome.diff.removed
494
+ result.changed = outcome.diff.changed
495
+ // Предупреждения сборки на момент блокировки точнее предварительных.
496
+ result.warnings.length = warningsBeforeBuild
497
+ result.warnings.push(...outcome.warnings)
498
+ }
499
+ deps.log('info', `applied catalog: ${result.nextModels} models (+${result.added.length}/-${result.removed.length}/~${result.changed.length})`)
500
+ try {
501
+ result.allowlist = await syncAllowlist(outcome?.models ?? built.models, cfg)
502
+ } catch (error) {
503
+ result.warnings.push(`allowed models not synced: ${messageOf(error)}`)
504
+ }
505
+ result.ok = true
506
+ } catch (error) {
507
+ result.error = messageOf(error)
508
+ result.errorStatus = typeof error?.status === 'number' ? error.status : 500
509
+ deps.log('warn', `refresh failed: ${result.error}`)
510
+ }
511
+ return result
512
+ }
513
+
514
+ /**
515
+ * Запомнить итог прогона в общем реестре состояния (`GET /cvc/state`).
516
+ * @param {Record<string, any>} result
517
+ * @param {boolean} apply
518
+ */
519
+ function publish(result, apply) {
520
+ const store = deps.store
521
+ if (store === null || typeof store !== 'object') return
522
+ try {
523
+ if (result.ok !== true && result.error.length > 0) {
524
+ store.setError?.(result.error)
525
+ return
526
+ }
527
+ store.setRunning?.(false)
528
+ store.setLastRun?.(toValue(result, apply ? 'apply' : 'plan'))
529
+ } catch (error) {
530
+ deps.log('warn', `state store write failed: ${messageOf(error)}`)
531
+ }
532
+ }
533
+
534
+ /**
535
+ * Прогон с дедупликацией: два одновременных вызова не дублируют запросы.
536
+ * @param {'startup' | 'timer' | 'tool'} reason
537
+ * @param {{ apply?: boolean, force?: boolean, signal?: AbortSignal }} [options]
538
+ * @returns {Promise<Record<string, any>>}
539
+ */
540
+ function refresh(reason, options = {}) {
541
+ const apply = options.apply === true
542
+ const force = options.force === true
543
+ // Слияние только внутри одного режима: `plan`, прицепившийся к идущей
544
+ // записи, не должен отчитываться «applied», а `force: true` не теряется
545
+ // в обычном прогоне.
546
+ const key = `${apply}:${force}`
547
+ if (inflight !== null && inflight.key === key) return inflight.promise
548
+ try {
549
+ deps.store?.setRunning?.(true)
550
+ } catch {
551
+ // Реестр состояния необязателен: инструмент работает и без него.
552
+ }
553
+ const promise = collect(reason, { ...options, apply, force }).then((result) => {
554
+ last = result
555
+ publish(result, apply)
556
+ return result
557
+ })
558
+ const record = { key, promise }
559
+ inflight = record
560
+ const clear = () => {
561
+ if (inflight === record) inflight = null
562
+ }
563
+ promise.then(clear, clear)
564
+ return promise
565
+ }
566
+
567
+ /**
568
+ * Итог прогона в форме ответа маршрута/инструмента (как в 1.0.0).
569
+ * @param {Record<string, any>} result
570
+ * @param {'status' | 'plan' | 'apply'} action
571
+ * @returns {Record<string, any>}
572
+ */
573
+ function toValue(result, action) {
574
+ const cfg = deps.config()
575
+ return {
576
+ action,
577
+ ok: result.ok === true,
578
+ at: typeof result.at === 'string' ? result.at : '',
579
+ provider: cfg.catalog.provider,
580
+ catalogModels: Number.isInteger(result.catalogModels) ? result.catalogModels : 0,
581
+ currentModels: Number.isInteger(result.currentModels) ? result.currentModels : 0,
582
+ nextModels: Number.isInteger(result.nextModels) ? result.nextModels : 0,
583
+ levelsSource: typeof result.levelsSource === 'string' ? result.levelsSource : 'none',
584
+ applied: result.applied === true,
585
+ added: Array.isArray(result.added) ? result.added : [],
586
+ removed: Array.isArray(result.removed) ? result.removed : [],
587
+ changed: Array.isArray(result.changed) ? result.changed : [],
588
+ warnings: Array.isArray(result.warnings) ? result.warnings : [],
589
+ allowlist: {
590
+ pruned: Array.isArray(result.allowlist?.pruned) ? result.allowlist.pruned : [],
591
+ added: Array.isArray(result.allowlist?.added) ? result.allowlist.added : [],
592
+ skipped: result.allowlist?.skipped !== false,
593
+ changed: result.allowlist?.changed === true,
594
+ },
595
+ error: typeof result.error === 'string' ? result.error : '',
596
+ }
597
+ }
598
+
599
+ /** Текущее число моделей в патче; для status, если прогонов ещё не было. */
600
+ function currentModelCount() {
601
+ try {
602
+ return readCurrent(deps.config()).models.length
603
+ } catch {
604
+ return 0
605
+ }
606
+ }
607
+
608
+ /**
609
+ * Ответ `status`: последний прогон в этом движке или честная заготовка.
610
+ * @returns {Record<string, any>}
611
+ */
612
+ function statusValue() {
613
+ const cfg = deps.config()
614
+ return toValue(last ?? {
615
+ ok: true,
616
+ at: '',
617
+ provider: cfg.catalog.provider,
618
+ catalogModels: 0,
619
+ currentModels: currentModelCount(),
620
+ nextModels: 0,
621
+ levelsSource: 'none',
622
+ warnings: ['no refresh has run in this process yet'],
623
+ }, 'status')
624
+ }
625
+
626
+ return { refresh, toValue, statusValue }
627
+ }
628
+
629
+ /**
630
+ * Подключить функцию синхронизации каталога.
631
+ *
632
+ * Регистрирует `POST /cvc/run` и таймеры автосинхронизации. Таймеры создаются
633
+ * через `hmr.executing.exit`, чтобы не унаследовать HMR-транзакцию: иначе
634
+ * `configEditor.edit()` на срабатывании получит «HMR transactions cannot be
635
+ * nested». Если приватного поля у сервиса нет, авто-запись отключается
636
+ * (таймеры только показывают дифф), а без сервиса HMR она работает как есть.
637
+ *
638
+ * @param {import('@deepseek-ai/cordis').Context} ctx — контекст плагина.
639
+ * @param {object} deps — общие зависимости каркаса (см. `index.js`).
640
+ * @returns {() => void} disposer, снимающий маршрут и таймеры.
641
+ */
642
+ export function register(ctx, deps) {
643
+ /** @type {Array<() => void>} */
644
+ const disposers = []
645
+ const engine = createEngine(ctx, deps)
646
+ engines.set(deps, engine)
647
+
648
+ const disposeRoute = deps.route('run', async (req, res) => {
649
+ const method = String(req.method ?? 'GET').toUpperCase()
650
+ if (method !== 'POST') {
651
+ deps.http.methodNotAllowed(res, ['POST'])
652
+ return
653
+ }
654
+ if (!deps.http.isJsonRequest(req)) {
655
+ deps.http.sendJson(res, 415, { error: 'content-type: application/json required' })
656
+ return
657
+ }
658
+ let body
659
+ try {
660
+ body = await deps.http.readJsonBody(req)
661
+ } catch (error) {
662
+ const status = typeof error?.status === 'number' ? error.status : 400
663
+ deps.http.sendJson(res, status, { error: messageOf(error) })
664
+ return
665
+ }
666
+ const requested = isPlainObject(body) ? body.action : undefined
667
+ if (requested !== undefined && requested !== 'plan' && requested !== 'apply') {
668
+ deps.http.sendJson(res, 400, { error: 'action must be "plan" or "apply"' })
669
+ return
670
+ }
671
+ const action = requested === 'apply' ? 'apply' : 'plan'
672
+ const force = isPlainObject(body) && body.force === true
673
+ const result = await engine.refresh('tool', { apply: action === 'apply', force })
674
+ // 409 — отказ по stale/guard: клиент покажет текст, а не «ошибку сервера».
675
+ // Прочие неудачи (нет строки, нет ключа, сеть) остаются 200 с `ok: false`:
676
+ // тело ответа — диагностика прогона, как у инструмента.
677
+ const status = result.ok === true ? 200 : (result.errorStatus === 409 ? 409 : 200)
678
+ deps.http.sendJson(res, status, engine.toValue(result, action))
679
+ })
680
+ disposers.push(disposeRoute)
681
+
682
+ const hmrService = (() => {
683
+ try {
684
+ return typeof ctx.get === 'function' ? ctx.get('hmr') : undefined
685
+ } catch {
686
+ return undefined
687
+ }
688
+ })()
689
+ const hmrPresent = hmrService !== undefined && hmrService !== null
690
+ /**
691
+ * AsyncLocalStorage HMR-транзакции, если сервис его отдаёт.
692
+ *
693
+ * `executing` — приватное поле Hmr, но именно им сам DSH выводит наблюдение
694
+ * за файлами из транзакции.
695
+ * @type {{ exit?: (factory: () => unknown) => unknown } | null}
696
+ */
697
+ let hmrExecuting = null
698
+ try {
699
+ const executing = hmrPresent ? hmrService.executing : undefined
700
+ if (executing !== undefined && executing !== null && typeof executing.exit === 'function') {
701
+ hmrExecuting = /** @type {any} */ (executing)
702
+ }
703
+ } catch {
704
+ hmrExecuting = null
705
+ }
706
+
707
+ const cfg = deps.config()
708
+ /**
709
+ * Автоматическая запись включается, только когда таймер гарантированно
710
+ * оказывается вне HMR-транзакции. Без HMR-сервиса транзакций не бывает.
711
+ */
712
+ let autoApply = cfg.catalog.autoSync && !(hmrPresent && hmrExecuting === null)
713
+ if (cfg.catalog.autoSync && !autoApply) {
714
+ deps.log('warn', 'auto-write disabled: the HMR service exposes no usable transaction context in this host; '
715
+ + 'timers will only report the diff, use cvc_catalog apply')
716
+ }
717
+
718
+ /** Фоновый прогон по таймеру: ошибки уже внутри результата, промис не должен всплывать. */
719
+ function backgroundRun(reason) {
720
+ void engine.refresh(reason, { apply: autoApply }).catch((error) => {
721
+ deps.log('warn', `background refresh failed: ${messageOf(error)}`)
722
+ })
723
+ }
724
+
725
+ /**
726
+ * Создать таймер вне текущей async-зоны.
727
+ *
728
+ * Плагин может активироваться внутри HMR-транзакции. Таймер, созданный
729
+ * внутри неё, наследует AsyncLocalStorage-контекст, и `configEditor.edit()`
730
+ * при срабатывании получает «HMR transactions cannot be nested».
731
+ * @template T
732
+ * @param {() => T} factory
733
+ * @returns {T}
734
+ */
735
+ function scheduleOutsideHmr(factory) {
736
+ if (hmrExecuting !== null) {
737
+ try {
738
+ return /** @type {T} */ (hmrExecuting.exit(factory))
739
+ } catch (error) {
740
+ // `exit` штатно не бросает, но если это случилось — таймер окажется
741
+ // внутри транзакции, поэтому авто-запись выключаем до перезапуска.
742
+ if (autoApply) {
743
+ autoApply = false
744
+ deps.log('warn', `auto-write disabled: HMR transaction escape failed (${messageOf(error)}); `
745
+ + 'timers will only report the diff, use cvc_catalog apply')
746
+ }
747
+ }
748
+ }
749
+ return factory()
750
+ }
751
+
752
+ // Автоматика: стартовая проверка после того, как Loader устоялся, и таймер.
753
+ if (cfg.catalog.autoSync) {
754
+ const startupDelayMs = numberOr(cfg.catalog.startupDelayMs, 5000, 0)
755
+ const startup = scheduleOutsideHmr(() => setTimeout(() => backgroundRun('startup'), startupDelayMs))
756
+ startup?.unref?.()
757
+ disposers.push(() => clearTimeout(startup))
758
+
759
+ if (cfg.catalog.intervalHours > 0) {
760
+ // setInterval принимает от 1 до 2^31-1 мс. Слишком малое значение
761
+ // округлилось бы в 0 и дало почти непрерывные прогоны, поэтому нижняя
762
+ // граница — минута.
763
+ const requested = cfg.catalog.intervalHours * 3600000
764
+ const periodMs = Math.min(Math.max(Math.round(requested), MIN_INTERVAL_MS), MAX_TIMEOUT_MS)
765
+ if (requested < MIN_INTERVAL_MS) {
766
+ deps.log('warn', `intervalHours ${cfg.catalog.intervalHours} is too small, timer raised to 1 minute`)
767
+ } else if (requested > MAX_TIMEOUT_MS) {
768
+ deps.log('warn', `intervalHours ${cfg.catalog.intervalHours} is too large, timer clamped to 24.8 days`)
769
+ }
770
+ const timer = scheduleOutsideHmr(() => setInterval(() => backgroundRun('timer'), periodMs))
771
+ timer?.unref?.()
772
+ disposers.push(() => clearInterval(timer))
773
+ }
774
+ }
775
+
776
+ return () => {
777
+ for (const dispose of disposers.reverse()) {
778
+ if (typeof dispose === 'function') dispose()
779
+ }
780
+ if (engines.get(deps) === engine) engines.delete(deps)
781
+ }
782
+ }
783
+
784
+ /**
785
+ * Описание инструмента `cvc_catalog` (status / plan / apply, force).
786
+ *
787
+ * `tool(deps)` вызывается каркасом сразу после `register(ctx, deps)` с тем же
788
+ * объектом `deps`, поэтому инструмент переиспользует движок функции: `status`
789
+ * видит последний прогон, а параллельный `apply` схлопывается с ручным
790
+ * маршрутом. При выключенной функции (например, гонка с volatile-правкой)
791
+ * `execute` отвечает понятной ошибкой, а не идёт в сеть.
792
+ *
793
+ * @param {object} deps
794
+ * @returns {object}
795
+ */
796
+ export function tool(deps) {
797
+ const engine = engines.get(deps) ?? createEngine(deps.ctx, deps)
798
+ return {
799
+ name: TOOL_NAME,
800
+ description: 'Refresh the CheapVibeCode model catalog in the DSH profile patch. '
801
+ + 'Reads the provider catalog and the reasoning-level map from the official installer, '
802
+ + 'then rewrites only the configured provider route models and, when enabled, the '
803
+ + 'subagent allowed-model list. Actions: status (last run in this process, no network), '
804
+ + 'plan (fetch and show the diff without writing), apply (fetch and write). '
805
+ + 'A write happens only when the catalog changed, and is refused when the response '
806
+ + 'shrinks below the configured share of the current model count unless force is set. '
807
+ + 'The change is applied without restarting DSH.',
808
+ parameters: {
809
+ type: 'object',
810
+ additionalProperties: false,
811
+ properties: {
812
+ action: {
813
+ type: 'string',
814
+ enum: ['status', 'plan', 'apply'],
815
+ description: 'status: report the last run in this process without network. '
816
+ + 'plan: fetch and return the diff without writing. apply: fetch and write the catalog.',
817
+ },
818
+ force: {
819
+ type: 'boolean',
820
+ description: 'apply only: write even when the response is smaller than the model-count guard allows.',
821
+ },
822
+ },
823
+ },
824
+ output: {
825
+ schema: OUTPUT_SCHEMA,
826
+ render: (_args, value) => [{ type: 'text', text: renderValue(value) }],
827
+ },
828
+ timeoutMs: 90000,
829
+ async execute(args, exec) {
830
+ const action = isPlainObject(args) && (args.action === 'status' || args.action === 'plan' || args.action === 'apply')
831
+ ? args.action
832
+ : 'status'
833
+ const features = typeof deps.features === 'function' ? deps.features() : null
834
+ if (features !== null && features !== undefined && features.catalogSync !== true) {
835
+ return engine.toValue({
836
+ ok: false,
837
+ at: new Date().toISOString(),
838
+ catalogModels: 0,
839
+ currentModels: 0,
840
+ nextModels: 0,
841
+ levelsSource: 'none',
842
+ warnings: [],
843
+ error: 'catalog sync is disabled in settings (features.catalogSync=false); '
844
+ + 'enable it on the plugin settings page to use cvc_catalog',
845
+ }, action)
846
+ }
847
+ if (action === 'status') return engine.statusValue()
848
+ const result = await engine.refresh('tool', {
849
+ apply: action === 'apply',
850
+ force: isPlainObject(args) && args.force === true,
851
+ signal: exec?.signal,
852
+ })
853
+ return engine.toValue(result, action)
854
+ },
855
+ }
856
+ }