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,391 @@
1
+ /**
2
+ * Чистая сборка моделей `llm-pi-ai` из каталога CheapVibeCode и карты уровней.
3
+ *
4
+ * Модуль ничего не знает о сети, профиле и таймерах: на вход каталог
5
+ * (`GET /v1/models`), карта `reasoningLevels` из официального установщика и
6
+ * текущий список моделей из патча, на выходе — новый список по правилам
7
+ * установщика `modelFromCatalog`. Здесь же живут дифф моделей, защита от
8
+ * усыхания каталога (`minModelRatio`) и планирование списка `allowedModels`
9
+ * сабагентов.
10
+ *
11
+ * Правила переноса уровней повторяют установщик CVC: `none` → ключ `off` со
12
+ * значением `none`, `thinking` → ключ `high` со значением `thinking` (схема
13
+ * llm-pi-ai ограничивает ключи, а значение — произвольное проводное написание),
14
+ * остальные уровни — ключ = значение.
15
+ *
16
+ * @module cvc-catalog-sync-plugin/lib/catalog-build
17
+ */
18
+
19
+ /**
20
+ * Уровни, которые схема llm-pi-ai принимает ключами `reasoningEfforts`
21
+ * (`THINKING_LEVELS`). Значения — проводное написание, поэтому `high: thinking`
22
+ * допустим.
23
+ */
24
+ export const WIRE_LEVELS = Object.freeze(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'])
25
+
26
+ /** Полный ряд уровней для модели с `supports_reasoning`, но без явной карты. */
27
+ export const FULL_ROW = Object.freeze({
28
+ off: 'none',
29
+ minimal: 'minimal',
30
+ low: 'low',
31
+ medium: 'medium',
32
+ high: 'high',
33
+ xhigh: 'xhigh',
34
+ max: 'max',
35
+ })
36
+
37
+ /** Контекст по умолчанию, если каталог и текущая запись молчат. */
38
+ export const DEFAULT_CONTEXT_WINDOW = 128000
39
+
40
+ /** Максимум вывода по умолчанию, если каталог и текущая запись молчат. */
41
+ export const DEFAULT_MAX_TOKENS = 16384
42
+
43
+ /** Доля каталога по умолчанию для защиты от усыхания. */
44
+ export const DEFAULT_MIN_MODEL_RATIO = 0.8
45
+
46
+ /**
47
+ * Проверить, что значение — обычный объект (не массив и не null).
48
+ * @param {unknown} value
49
+ * @returns {value is Record<string, any>}
50
+ */
51
+ function isPlainObject(value) {
52
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
53
+ }
54
+
55
+ /**
56
+ * Положительное целое или null.
57
+ * @param {unknown} value
58
+ * @returns {number | null}
59
+ */
60
+ export function positiveInt(value) {
61
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) return Math.trunc(value)
62
+ if (typeof value === 'string' && value.trim() !== '') {
63
+ const parsed = Number(value)
64
+ if (Number.isFinite(parsed) && parsed > 0) return Math.trunc(parsed)
65
+ }
66
+ return null
67
+ }
68
+
69
+ /**
70
+ * Первое положительное целое по списку полей каталога.
71
+ * @param {Record<string, unknown>} item
72
+ * @param {readonly string[]} keys
73
+ * @returns {number | null}
74
+ */
75
+ function firstPositiveInt(item, keys) {
76
+ for (const key of keys) {
77
+ const value = positiveInt(item[key])
78
+ if (value !== null) return value
79
+ }
80
+ return null
81
+ }
82
+
83
+ /**
84
+ * Имя модели для UI: хвост `display_name` после разделителя ` · `.
85
+ * @param {Record<string, unknown>} item
86
+ * @param {string} id
87
+ * @returns {string}
88
+ */
89
+ export function modelName(item, id) {
90
+ const raw = typeof item.display_name === 'string' && item.display_name.trim().length > 0
91
+ ? item.display_name.trim()
92
+ : typeof item.name === 'string' && item.name.trim().length > 0
93
+ ? item.name.trim()
94
+ : id
95
+ const tail = raw.includes(' · ') ? raw.split(' · ').pop()?.trim() : raw
96
+ return tail && tail.length > 0 ? tail : id
97
+ }
98
+
99
+ /**
100
+ * Построить `reasoningEfforts` для одной модели.
101
+ *
102
+ * Порядок источников:
103
+ * 1. явная карта установщика;
104
+ * 2. текущее значение из патча (карта недоступна — не трогаем то, что уже
105
+ * настроено);
106
+ * 3. `supports_reasoning === true` → полный ряд, иначе `false`.
107
+ *
108
+ * Карта, предлагающая только `off`, не отдаётся: `resolveModelReasoning` в
109
+ * llm-pi-ai отвергает её и роняет всю запись. Такой случай падает в источники
110
+ * ниже с предупреждением.
111
+ *
112
+ * @param {string} id
113
+ * @param {Record<string, unknown>} item — запись каталога.
114
+ * @param {Record<string, any> | undefined} existing — текущая запись патча.
115
+ * @param {Record<string, string[]> | null} levelMap — карта установщика.
116
+ * @param {string[]} warnings — накопитель предупреждений.
117
+ * @returns {Record<string, string> | false}
118
+ */
119
+ export function reasoningEffortsFor(id, item, existing, levelMap, warnings) {
120
+ const levels = levelMap === null ? undefined : levelMap[id]
121
+ if (Array.isArray(levels) && levels.length > 0) {
122
+ /** @type {Record<string, string>} */
123
+ const efforts = {}
124
+ for (const level of levels) {
125
+ if (level === 'none') efforts.off = 'none'
126
+ else if (level === 'thinking') efforts.high = 'thinking'
127
+ else if (WIRE_LEVELS.includes(level)) efforts[level] = level
128
+ else warnings.push(`model ${id}: unknown level "${level}", dropped`)
129
+ }
130
+ const keys = Object.keys(efforts)
131
+ if (keys.length > 1 || (keys.length === 1 && keys[0] !== 'off')) return efforts
132
+ warnings.push(`model ${id}: level list ${JSON.stringify(levels)} offers no level beyond "off", falling back`)
133
+ }
134
+ if (existing !== undefined && existing.reasoningEfforts !== undefined) {
135
+ return /** @type {Record<string, string> | false} */ (existing.reasoningEfforts)
136
+ }
137
+ if (item.supports_reasoning === true) return { ...FULL_ROW }
138
+ return false
139
+ }
140
+
141
+ /**
142
+ * Собрать модели из каталога по правилам установщика `modelFromCatalog`.
143
+ *
144
+ * Модели без текстового вывода и `gpt-image*` пропускаются: адаптер не сможет
145
+ * их обслужить. Значения контекста и вывода при отсутствии в каталоге берутся
146
+ * из текущей записи патча — так ручная правка пользователя не теряется.
147
+ *
148
+ * @param {Array<Record<string, unknown>>} catalog — записи каталога.
149
+ * @param {Record<string, string[]> | null} levelMap — карта уровней установщика.
150
+ * @param {Array<Record<string, unknown>>} existingModels — модели из патча.
151
+ * @param {{ keepModels?: string[] }} [options] — `keepModels` из конфига.
152
+ * @returns {{ models: Array<Record<string, unknown>>, warnings: string[] }}
153
+ */
154
+ export function buildModels(catalog, levelMap, existingModels, options = {}) {
155
+ const keepModels = isPlainObject(options) && Array.isArray(options.keepModels) ? options.keepModels : []
156
+ const rows = Array.isArray(catalog) ? catalog : []
157
+ const previous = Array.isArray(existingModels) ? existingModels : []
158
+
159
+ /** @type {Map<string, Record<string, unknown>>} */
160
+ const existingById = new Map()
161
+ for (const model of previous) {
162
+ if (isPlainObject(model) && typeof model.id === 'string') existingById.set(model.id, model)
163
+ }
164
+ /** @type {Array<Record<string, unknown>>} */
165
+ const models = []
166
+ /** @type {string[]} */
167
+ const warnings = []
168
+ /** @type {Set<string>} */
169
+ const seen = new Set()
170
+
171
+ for (const item of rows) {
172
+ if (!isPlainObject(item)) continue
173
+ const id = typeof item.id === 'string' ? item.id.trim() : ''
174
+ if (id.length === 0) continue
175
+ if (id.toLowerCase().startsWith('gpt-image')) continue
176
+ if (seen.has(id)) continue
177
+
178
+ const outputs = Array.isArray(item.output_modalities)
179
+ ? item.output_modalities.map((value) => String(value).trim().toLowerCase()).filter(Boolean)
180
+ : []
181
+ if (outputs.length > 0 && !outputs.includes('text')) continue
182
+
183
+ const existing = existingById.get(id)
184
+ const contextWindow = firstPositiveInt(item, ['context_window', 'contextWindow', 'context_length', 'max_context_tokens'])
185
+ ?? (existing === undefined ? null : positiveInt(existing.contextWindow))
186
+ ?? DEFAULT_CONTEXT_WINDOW
187
+ const advertisedMax = firstPositiveInt(item, ['max_output_tokens', 'max_tokens'])
188
+ ?? (existing === undefined ? null : positiveInt(existing.maxTokens))
189
+ ?? DEFAULT_MAX_TOKENS
190
+ const maxTokens = Math.min(advertisedMax, contextWindow)
191
+
192
+ // Каталог главнее текущей записи: если он объявил модальности, решение
193
+ // принимается по ним, а `supports_vision: false` означает «картинки нет»,
194
+ // даже когда в патче она когда-то была. Текущая запись отвечает только
195
+ // там, где каталог о зрении молчит вовсе.
196
+ const advertisedInputs = Array.isArray(item.input_modalities)
197
+ ? item.input_modalities.map((value) => String(value).trim().toLowerCase()).filter(Boolean)
198
+ : []
199
+ let input
200
+ if (advertisedInputs.length > 0) {
201
+ input = advertisedInputs.includes('image') || item.supports_vision === true ? ['text', 'image'] : ['text']
202
+ } else if (item.supports_vision === true) {
203
+ input = ['text', 'image']
204
+ } else if (item.supports_vision === false) {
205
+ input = ['text']
206
+ } else if (Array.isArray(existing?.input) && existing.input.length > 0) {
207
+ input = [...existing.input]
208
+ } else {
209
+ input = ['text']
210
+ }
211
+
212
+ /** @type {Record<string, unknown>} */
213
+ const model = {
214
+ id,
215
+ name: modelName(item, id),
216
+ contextWindow,
217
+ maxTokens,
218
+ input,
219
+ reasoningEfforts: reasoningEffortsFor(id, item, existing, levelMap, warnings),
220
+ }
221
+ if (isPlainObject(existing?.compat)) model.compat = existing.compat
222
+ models.push(model)
223
+ seen.add(id)
224
+ }
225
+
226
+ for (const id of keepModels) {
227
+ if (typeof id !== 'string' || id.trim().length === 0) continue
228
+ if (seen.has(id)) continue
229
+ const existing = existingById.get(id)
230
+ if (existing === undefined) {
231
+ warnings.push(`keepModels: "${id}" is neither in the catalog nor in the patch`)
232
+ continue
233
+ }
234
+ models.push(existing)
235
+ seen.add(id)
236
+ warnings.push(`keepModels: "${id}" kept although the catalog no longer lists it`)
237
+ }
238
+
239
+ return { models, warnings }
240
+ }
241
+
242
+ /**
243
+ * Стабильная JSON-строка: ключи сортируются, порядок полей не считается
244
+ * изменением.
245
+ * @param {unknown} value
246
+ * @returns {string}
247
+ */
248
+ export function stableStringify(value) {
249
+ if (Array.isArray(value)) return `[${value.map((entry) => stableStringify(entry)).join(',')}]`
250
+ if (isPlainObject(value)) {
251
+ const keys = Object.keys(value).sort()
252
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`
253
+ }
254
+ return JSON.stringify(value) ?? 'null'
255
+ }
256
+
257
+ /**
258
+ * Сравнить текущий набор моделей с новым.
259
+ * @param {Array<Record<string, unknown>>} current
260
+ * @param {Array<Record<string, unknown>>} next
261
+ * @returns {{ added: string[], removed: string[], changed: Array<{ id: string, fields: string[] }>, changedCount: number }}
262
+ */
263
+ export function diffModels(current, next) {
264
+ /** @type {Map<string, Record<string, unknown>>} */
265
+ const currentById = new Map()
266
+ for (const model of Array.isArray(current) ? current : []) {
267
+ if (isPlainObject(model) && typeof model.id === 'string') currentById.set(model.id, model)
268
+ }
269
+ /** @type {Map<string, Record<string, unknown>>} */
270
+ const nextById = new Map()
271
+ for (const model of Array.isArray(next) ? next : []) {
272
+ if (isPlainObject(model) && typeof model.id === 'string') nextById.set(model.id, model)
273
+ }
274
+ const added = [...nextById.keys()].filter((id) => !currentById.has(id))
275
+ const removed = [...currentById.keys()].filter((id) => !nextById.has(id))
276
+ /** @type {Array<{ id: string, fields: string[] }>} */
277
+ const changed = []
278
+ for (const [id, model] of nextById) {
279
+ const before = currentById.get(id)
280
+ if (before === undefined) continue
281
+ const fields = []
282
+ for (const key of Object.keys(model)) {
283
+ if (stableStringify(model[key]) !== stableStringify(before[key])) fields.push(key)
284
+ }
285
+ for (const key of Object.keys(before)) {
286
+ if (!(key in model)) fields.push(key)
287
+ }
288
+ if (fields.length > 0) changed.push({ id, fields })
289
+ }
290
+ return { added, removed, changed, changedCount: changed.length }
291
+ }
292
+
293
+ /**
294
+ * Пустой ли дифф.
295
+ * @param {{ added: string[], removed: string[], changedCount: number }} diff
296
+ * @returns {boolean}
297
+ */
298
+ export function isDiffEmpty(diff) {
299
+ return diff.added.length === 0 && diff.removed.length === 0 && diff.changedCount === 0
300
+ }
301
+
302
+ /**
303
+ * Доля из конфига: конечное число в (0, 1] или умолчание.
304
+ * @param {unknown} value
305
+ * @returns {number}
306
+ */
307
+ function ratioOr(value) {
308
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > 1) {
309
+ return DEFAULT_MIN_MODEL_RATIO
310
+ }
311
+ return value
312
+ }
313
+
314
+ /**
315
+ * Защита от усыхания каталога: сколько моделей обязано остаться.
316
+ *
317
+ * `minRequired` — максимум из одной модели и `ceil(current * ratio)`: пустой
318
+ * ответ не должен стереть рабочий список, даже когда в патче одна модель.
319
+ *
320
+ * @param {number} currentCount — сколько моделей сейчас в патче.
321
+ * @param {number} nextCount — сколько собралось из нового каталога.
322
+ * @param {number} [minModelRatio] — доля из `catalog.minModelRatio`.
323
+ * @returns {{ minModelRatio: number, currentModels: number, nextModels: number, minRequired: number, ok: boolean }}
324
+ */
325
+ export function modelRatioGuard(currentCount, nextCount, minModelRatio) {
326
+ const ratio = ratioOr(minModelRatio)
327
+ const current = Number.isFinite(currentCount) && currentCount > 0 ? Math.trunc(currentCount) : 0
328
+ const next = Number.isFinite(nextCount) && nextCount > 0 ? Math.trunc(nextCount) : 0
329
+ const minRequired = Math.max(1, Math.ceil(current * ratio))
330
+ return {
331
+ minModelRatio: ratio,
332
+ currentModels: current,
333
+ nextModels: next,
334
+ minRequired,
335
+ ok: next >= minRequired,
336
+ }
337
+ }
338
+
339
+ /**
340
+ * Текст отказа guard для apply (совпадает с формулировкой 1.0.0).
341
+ * @param {{ currentModels: number, nextModels: number, minModelRatio?: number }} input
342
+ * @returns {string}
343
+ */
344
+ export function guardFailureMessage(input) {
345
+ const guard = modelRatioGuard(input.currentModels, input.nextModels, input.minModelRatio)
346
+ return `guard: catalog returned ${guard.nextModels} models, below ${guard.minRequired} `
347
+ + `(${Math.round(guard.minModelRatio * 100)}% of current ${guard.currentModels}); `
348
+ + 'nothing written, use force to override'
349
+ }
350
+
351
+ /**
352
+ * Спланировать список `allowedModels` сабагентов под каталог маршрута.
353
+ *
354
+ * Чужие провайдеры сохраняются как есть и в исходном порядке: плагин владеет
355
+ * только своим маршрутом. Собственные записи всегда переписываются в порядке
356
+ * каталога — это чинит дубли и разъехавшийся порядок, которые DSH отвергает.
357
+ *
358
+ * @param {unknown} allowedModels — текущее значение `allowedModels`.
359
+ * @param {string} provider — ключ своего маршрута.
360
+ * @param {string[]} catalogIds — идентификаторы моделей каталога по порядку.
361
+ * @returns {{
362
+ * allowed: Array<Record<string, unknown>>,
363
+ * others: Array<Record<string, unknown>>,
364
+ * expected: Array<{ provider: string, model: string }>,
365
+ * pruned: string[],
366
+ * added: string[],
367
+ * changed: boolean,
368
+ * }}
369
+ */
370
+ export function planAllowlist(allowedModels, provider, catalogIds) {
371
+ const rows = Array.isArray(allowedModels) ? allowedModels.filter(isPlainObject) : []
372
+ const name = typeof provider === 'string' ? provider : ''
373
+ const ids = Array.isArray(catalogIds)
374
+ ? [...new Set(catalogIds.filter((id) => typeof id === 'string' && id.length > 0))]
375
+ : []
376
+ const catalogSet = new Set(ids)
377
+ const ownRows = rows.filter((row) => row.provider === name)
378
+ const ownIds = new Set(ownRows.map((row) => row.model))
379
+ const others = rows.filter((row) => row.provider !== name)
380
+ const pruned = [...ownIds].filter((id) => !catalogSet.has(id))
381
+ const added = ids.filter((id) => !ownIds.has(id))
382
+ const expected = [...others, ...ids.map((id) => ({ provider: name, model: id }))]
383
+ return {
384
+ allowed: rows,
385
+ others,
386
+ expected,
387
+ pruned,
388
+ added,
389
+ changed: stableStringify(rows) !== stableStringify(expected),
390
+ }
391
+ }