cvc-catalog-sync-plugin 1.0.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/LICENSE +21 -0
- package/README.md +284 -0
- package/SECURITY.md +118 -0
- package/client.js +582 -0
- package/cordis.patch.yml +14 -0
- package/icon.svg +8 -0
- package/index.js +1394 -0
- package/locale/en.json +6 -0
- package/locale/ru.json +6 -0
- package/package.json +63 -0
package/index.js
ADDED
|
@@ -0,0 +1,1394 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Синхронизация каталога моделей CheapVibeCode с профильным патчем DSH.
|
|
3
|
+
*
|
|
4
|
+
* Каталог моделей CVC меняется часто, а уровни мышления лежат не в API, а в
|
|
5
|
+
* литерале `reasoningLevels` официального установщика. Штатного обновления в
|
|
6
|
+
* DSH нет, поэтому плагин делает это сам:
|
|
7
|
+
*
|
|
8
|
+
* 1. забирает `GET {baseURL}/models` ключом провайдера;
|
|
9
|
+
* 2. забирает установщик (`/idhw`, запасной `/idhl`) и вытаскивает карту
|
|
10
|
+
* `reasoningLevels` регуляркой;
|
|
11
|
+
* 3. собирает `models` по правилам установщика (`modelFromCatalog`);
|
|
12
|
+
* 4. точечно пишет результат в строку `llm-pi-ai` профильного патча через
|
|
13
|
+
* `ctx.configEditor.edit()` — единственный sanctioned-путь записи: он
|
|
14
|
+
* сохраняет комментарии и чужие строки, пишет атомарно, а `dsh-hmr`
|
|
15
|
+
* перечитывает патч без перезапуска приложения.
|
|
16
|
+
*
|
|
17
|
+
* Запись выполняется только при реальном изменении каталога, и только если
|
|
18
|
+
* число моделей не провалилось ниже доли от текущего (`minModelRatio`):
|
|
19
|
+
* пустой или обрезанный ответ API не должен стирать рабочий список.
|
|
20
|
+
*
|
|
21
|
+
* Ручной запуск — инструмент `cvc_catalog` (status / plan / apply).
|
|
22
|
+
*
|
|
23
|
+
* @module cvc-catalog-sync-plugin
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Уровни, которые схема llm-pi-ai принимает ключами `reasoningEfforts`
|
|
28
|
+
* (`THINKING_LEVELS`). Значения — проводное написание, произвольная строка,
|
|
29
|
+
* поэтому `high: thinking` допустим.
|
|
30
|
+
*/
|
|
31
|
+
const WIRE_LEVELS = Object.freeze(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'])
|
|
32
|
+
|
|
33
|
+
/** Полный ряд уровней для модели с `supports_reasoning`, но без явной карты. */
|
|
34
|
+
const FULL_ROW = Object.freeze({
|
|
35
|
+
off: 'none',
|
|
36
|
+
minimal: 'minimal',
|
|
37
|
+
low: 'low',
|
|
38
|
+
medium: 'medium',
|
|
39
|
+
high: 'high',
|
|
40
|
+
xhigh: 'xhigh',
|
|
41
|
+
max: 'max',
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
/** Официальные установщики CVC: PowerShell для Windows, bash для Linux/WSL. */
|
|
45
|
+
const DEFAULT_INSTALLER_URLS = Object.freeze([
|
|
46
|
+
'https://ru.cheapvibecode.ru/idhw',
|
|
47
|
+
'https://ru.cheapvibecode.ru/idhl',
|
|
48
|
+
])
|
|
49
|
+
|
|
50
|
+
/** Имя инструмента ручного запуска. */
|
|
51
|
+
const TOOL_NAME = 'cvc_catalog'
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Проверить, что значение — обычный объект (не массив и не null).
|
|
55
|
+
* @param {unknown} value
|
|
56
|
+
* @returns {value is Record<string, unknown>}
|
|
57
|
+
*/
|
|
58
|
+
function isPlainObject(value) {
|
|
59
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Привести значение к строке с умолчанием.
|
|
64
|
+
* @param {unknown} value
|
|
65
|
+
* @param {string} fallback
|
|
66
|
+
* @returns {string}
|
|
67
|
+
*/
|
|
68
|
+
function stringOr(value, fallback) {
|
|
69
|
+
return typeof value === 'string' && value.trim().length > 0 ? value.trim() : fallback
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Положительное целое или null.
|
|
74
|
+
* @param {unknown} value
|
|
75
|
+
* @returns {number | null}
|
|
76
|
+
*/
|
|
77
|
+
function positiveInt(value) {
|
|
78
|
+
if (typeof value === 'number' && Number.isFinite(value) && value > 0) return Math.trunc(value)
|
|
79
|
+
if (typeof value === 'string' && value.trim() !== '') {
|
|
80
|
+
const parsed = Number(value)
|
|
81
|
+
if (Number.isFinite(parsed) && parsed > 0) return Math.trunc(parsed)
|
|
82
|
+
}
|
|
83
|
+
return null
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Первое положительное целое по списку полей каталога.
|
|
88
|
+
* @param {Record<string, unknown>} item
|
|
89
|
+
* @param {readonly string[]} keys
|
|
90
|
+
* @returns {number | null}
|
|
91
|
+
*/
|
|
92
|
+
function firstPositiveInt(item, keys) {
|
|
93
|
+
for (const key of keys) {
|
|
94
|
+
const value = positiveInt(item[key])
|
|
95
|
+
if (value !== null) return value
|
|
96
|
+
}
|
|
97
|
+
return null
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Задержка/таймаут из конфига: конечное число не меньше `min`, но не больше
|
|
102
|
+
* предела `setTimeout`/`AbortSignal.timeout` (2^31-1 мс). Большее значение
|
|
103
|
+
* Node молча исполняет как 1 мс, что хуже явного ограничения.
|
|
104
|
+
* @param {unknown} value
|
|
105
|
+
* @param {number} fallback
|
|
106
|
+
* @param {number} min
|
|
107
|
+
* @returns {number}
|
|
108
|
+
*/
|
|
109
|
+
function delayOr(value, fallback, min) {
|
|
110
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < min) return fallback
|
|
111
|
+
return Math.min(Math.round(value), 2147483647)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Текст ошибки без предположения о её типе. */
|
|
115
|
+
function messageOf(error) {
|
|
116
|
+
return error instanceof Error ? error.message : String(error)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Снять хвостовые слэши без регулярки: значение приходит из конфигурации. */
|
|
120
|
+
function stripTrailingSlashes(value) {
|
|
121
|
+
let end = value.length
|
|
122
|
+
while (end > 0 && value[end - 1] === '/') end -= 1
|
|
123
|
+
return value.slice(0, end)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Снять слэши с обоих концов строки без регулярки. */
|
|
127
|
+
function trimSlashes(value) {
|
|
128
|
+
let start = 0
|
|
129
|
+
let end = value.length
|
|
130
|
+
while (start < end && value[start] === '/') start += 1
|
|
131
|
+
while (end > start && value[end - 1] === '/') end -= 1
|
|
132
|
+
return value.slice(start, end)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Пустой ли дифф. */
|
|
136
|
+
function isDiffEmpty(diff) {
|
|
137
|
+
return diff.added.length === 0 && diff.removed.length === 0 && diff.changedCount === 0
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Нормализовать конфигурацию строки плагина.
|
|
142
|
+
*
|
|
143
|
+
* Битые значения не бросают: плагин должен подниматься и с неполным конфигом,
|
|
144
|
+
* иначе одна опечатка в патче выключает автообновление молча.
|
|
145
|
+
* @param {unknown} raw
|
|
146
|
+
* @returns {Record<string, any>}
|
|
147
|
+
*/
|
|
148
|
+
function normalizeConfig(raw) {
|
|
149
|
+
const source = isPlainObject(raw) ? raw : {}
|
|
150
|
+
const installerUrls = Array.isArray(source.installerUrls)
|
|
151
|
+
? source.installerUrls.filter((url) => typeof url === 'string' && url.trim().length > 0).map((url) => url.trim())
|
|
152
|
+
: []
|
|
153
|
+
const intervalHours = typeof source.intervalHours === 'number' && Number.isFinite(source.intervalHours) && source.intervalHours >= 0
|
|
154
|
+
? source.intervalHours
|
|
155
|
+
: 24
|
|
156
|
+
const ratio = typeof source.minModelRatio === 'number' && Number.isFinite(source.minModelRatio)
|
|
157
|
+
&& source.minModelRatio > 0 && source.minModelRatio <= 1
|
|
158
|
+
? source.minModelRatio
|
|
159
|
+
: 0.8
|
|
160
|
+
return {
|
|
161
|
+
entryId: stringOr(source.entryId, 'llm-pi-ai'),
|
|
162
|
+
provider: stringOr(source.provider, 'cheapvibecode'),
|
|
163
|
+
baseURL: stringOr(source.baseURL, 'https://ru.cheapvibecode.ru/v1'),
|
|
164
|
+
apiKeyEnv: stringOr(source.apiKeyEnv, 'CVC_DEEPSEEK_API_KEY'),
|
|
165
|
+
installerUrls: installerUrls.length > 0 ? installerUrls : [...DEFAULT_INSTALLER_URLS],
|
|
166
|
+
autoSync: source.autoSync !== false,
|
|
167
|
+
startupDelayMs: delayOr(source.startupDelayMs, 5000, 0),
|
|
168
|
+
intervalHours,
|
|
169
|
+
minModelRatio: ratio,
|
|
170
|
+
keepModels: Array.isArray(source.keepModels)
|
|
171
|
+
? source.keepModels.filter((id) => typeof id === 'string' && id.trim().length > 0).map((id) => id.trim())
|
|
172
|
+
: [],
|
|
173
|
+
syncAllowlist: source.syncAllowlist !== false,
|
|
174
|
+
allowlistEntryId: stringOr(source.allowlistEntryId, 'subagent-model-selection-settings'),
|
|
175
|
+
timeoutMs: delayOr(source.timeoutMs, 30000, 1),
|
|
176
|
+
levelsCacheMinutes: typeof source.levelsCacheMinutes === 'number' && Number.isFinite(source.levelsCacheMinutes)
|
|
177
|
+
&& source.levelsCacheMinutes >= 0
|
|
178
|
+
? source.levelsCacheMinutes
|
|
179
|
+
: 360,
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Разобрать ответ `GET /v1/models`.
|
|
185
|
+
*
|
|
186
|
+
* Принимается и OpenAI-форма `{ data: [...] }`, и голый массив. Записи без
|
|
187
|
+
* строкового `id` отбрасываются: без идентификатора модель в конфиг не
|
|
188
|
+
* положить.
|
|
189
|
+
* @param {unknown} body
|
|
190
|
+
* @returns {Array<Record<string, unknown>>}
|
|
191
|
+
*/
|
|
192
|
+
function parseCatalogPayload(body) {
|
|
193
|
+
const rows = Array.isArray(body)
|
|
194
|
+
? body
|
|
195
|
+
: isPlainObject(body) && Array.isArray(body.data)
|
|
196
|
+
? body.data
|
|
197
|
+
: []
|
|
198
|
+
const items = []
|
|
199
|
+
for (const row of rows) {
|
|
200
|
+
if (!isPlainObject(row)) continue
|
|
201
|
+
const id = typeof row.id === 'string' ? row.id.trim() : ''
|
|
202
|
+
if (id.length === 0) continue
|
|
203
|
+
items.push(row)
|
|
204
|
+
}
|
|
205
|
+
return items
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Вытащить карту `reasoningLevels` из текста установщика.
|
|
210
|
+
*
|
|
211
|
+
* В обоих установщиках это литерал `const reasoningLevels = {...};` с
|
|
212
|
+
* JSON-совместимым содержимым: вложенных объектов внутри нет, поэтому
|
|
213
|
+
* нежадный разбор до первой `};` безопасен. Дополнительно проверяется, что
|
|
214
|
+
* каждый уровень — строка: битая карта не должна молча менять конфиг.
|
|
215
|
+
* @param {unknown} text
|
|
216
|
+
* @returns {Record<string, string[]> | null}
|
|
217
|
+
*/
|
|
218
|
+
function parseReasoningLevels(text) {
|
|
219
|
+
if (typeof text !== 'string' || text.length === 0) return null
|
|
220
|
+
// Линейный разбор без регулярки: текст приходит из сети, а нежадный
|
|
221
|
+
// `[\s\S]*?` на большом файле — кандидат на квадратичный откат.
|
|
222
|
+
const start = text.indexOf('const reasoningLevels')
|
|
223
|
+
if (start < 0) return null
|
|
224
|
+
const open = text.indexOf('{', start)
|
|
225
|
+
if (open < 0) return null
|
|
226
|
+
const close = text.indexOf('};', open)
|
|
227
|
+
if (close < 0) return null
|
|
228
|
+
/** @type {unknown} */
|
|
229
|
+
let parsed
|
|
230
|
+
try {
|
|
231
|
+
parsed = JSON.parse(text.slice(open, close + 1))
|
|
232
|
+
} catch {
|
|
233
|
+
return null
|
|
234
|
+
}
|
|
235
|
+
if (!isPlainObject(parsed)) return null
|
|
236
|
+
/** @type {Record<string, string[]>} */
|
|
237
|
+
const map = {}
|
|
238
|
+
for (const [id, levels] of Object.entries(parsed)) {
|
|
239
|
+
if (!Array.isArray(levels)) continue
|
|
240
|
+
const clean = levels
|
|
241
|
+
.filter((level) => typeof level === 'string' && level.trim().length > 0)
|
|
242
|
+
.map((level) => level.trim())
|
|
243
|
+
if (clean.length > 0) map[id] = clean
|
|
244
|
+
}
|
|
245
|
+
return Object.keys(map).length > 0 ? map : null
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Имя модели для UI: хвост `display_name` после разделителя ` · `.
|
|
250
|
+
* @param {Record<string, unknown>} item
|
|
251
|
+
* @param {string} id
|
|
252
|
+
* @returns {string}
|
|
253
|
+
*/
|
|
254
|
+
function modelName(item, id) {
|
|
255
|
+
const raw = typeof item.display_name === 'string' && item.display_name.trim().length > 0
|
|
256
|
+
? item.display_name.trim()
|
|
257
|
+
: typeof item.name === 'string' && item.name.trim().length > 0
|
|
258
|
+
? item.name.trim()
|
|
259
|
+
: id
|
|
260
|
+
const tail = raw.includes(' · ') ? raw.split(' · ').pop()?.trim() : raw
|
|
261
|
+
return tail && tail.length > 0 ? tail : id
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Построить `reasoningEfforts` для одной модели.
|
|
266
|
+
*
|
|
267
|
+
* Правила переноса взяты из `reasoningEffortsFor` установщика:
|
|
268
|
+
* `none` → ключ `off` со значением `none`, `thinking` → ключ `high` со
|
|
269
|
+
* значением `thinking`, остальные уровни — ключ = значение.
|
|
270
|
+
*
|
|
271
|
+
* Схема llm-pi-ai ограничивает **ключи** (`THINKING_LEVELS`), а значения —
|
|
272
|
+
* произвольная строка (это и есть проводное написание, которое шлёт адаптер),
|
|
273
|
+
* поэтому `high: thinking` допустим.
|
|
274
|
+
*
|
|
275
|
+
* Порядок источников:
|
|
276
|
+
* 1. явная карта установщика;
|
|
277
|
+
* 2. текущее значение из патча (карта недоступна — не трогаем то, что уже
|
|
278
|
+
* настроено);
|
|
279
|
+
* 3. `supports_reasoning === true` → полный ряд, иначе `false`.
|
|
280
|
+
* @param {string} id
|
|
281
|
+
* @param {Record<string, unknown>} item
|
|
282
|
+
* @param {Record<string, unknown> | undefined} existing
|
|
283
|
+
* @param {Record<string, string[]> | null} levelMap
|
|
284
|
+
* @param {string[]} warnings
|
|
285
|
+
* @returns {Record<string, string> | false}
|
|
286
|
+
*/
|
|
287
|
+
function reasoningEffortsFor(id, item, existing, levelMap, warnings) {
|
|
288
|
+
const levels = levelMap === null ? undefined : levelMap[id]
|
|
289
|
+
if (Array.isArray(levels) && levels.length > 0) {
|
|
290
|
+
/** @type {Record<string, string>} */
|
|
291
|
+
const efforts = {}
|
|
292
|
+
for (const level of levels) {
|
|
293
|
+
if (level === 'none') efforts.off = 'none'
|
|
294
|
+
else if (level === 'thinking') efforts.high = 'thinking'
|
|
295
|
+
else if (WIRE_LEVELS.includes(level)) efforts[level] = level
|
|
296
|
+
else warnings.push(`model ${id}: unknown level "${level}", dropped`)
|
|
297
|
+
}
|
|
298
|
+
const keys = Object.keys(efforts)
|
|
299
|
+
// `resolveModelReasoning` в llm-pi-ai отвергает карту, не предлагающую
|
|
300
|
+
// уровня кроме `off`, и это роняет всю запись. Такую карту не отдаём:
|
|
301
|
+
// падаем в источники ниже (текущее значение, полный ряд, false).
|
|
302
|
+
if (keys.length > 1 || (keys.length === 1 && keys[0] !== 'off')) return efforts
|
|
303
|
+
warnings.push(`model ${id}: level list ${JSON.stringify(levels)} offers no level beyond "off", falling back`)
|
|
304
|
+
}
|
|
305
|
+
if (existing !== undefined && existing.reasoningEfforts !== undefined) {
|
|
306
|
+
return /** @type {Record<string, string> | false} */ (existing.reasoningEfforts)
|
|
307
|
+
}
|
|
308
|
+
if (item.supports_reasoning === true) return { ...FULL_ROW }
|
|
309
|
+
return false
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Собрать модели из каталога по правилам установщика `modelFromCatalog`.
|
|
314
|
+
*
|
|
315
|
+
* Модели без текстового вывода и `gpt-image*` пропускаются: адаптер не сможет
|
|
316
|
+
* их обслужить. Значения контекста и вывода при отсутствии в каталоге берутся
|
|
317
|
+
* из текущей записи патча — так ручная правка пользователя не теряется.
|
|
318
|
+
* @param {Array<Record<string, unknown>>} catalog
|
|
319
|
+
* @param {Record<string, string[]> | null} levelMap
|
|
320
|
+
* @param {Array<Record<string, unknown>>} existingModels
|
|
321
|
+
* @param {ReturnType<typeof normalizeConfig>} cfg
|
|
322
|
+
* @returns {{ models: Array<Record<string, unknown>>, warnings: string[] }}
|
|
323
|
+
*/
|
|
324
|
+
function buildModels(catalog, levelMap, existingModels, cfg) {
|
|
325
|
+
/** @type {Map<string, Record<string, unknown>>} */
|
|
326
|
+
const existingById = new Map()
|
|
327
|
+
for (const model of existingModels) {
|
|
328
|
+
if (typeof model.id === 'string') existingById.set(model.id, model)
|
|
329
|
+
}
|
|
330
|
+
/** @type {Array<Record<string, unknown>>} */
|
|
331
|
+
const models = []
|
|
332
|
+
/** @type {string[]} */
|
|
333
|
+
const warnings = []
|
|
334
|
+
/** @type {Set<string>} */
|
|
335
|
+
const seen = new Set()
|
|
336
|
+
|
|
337
|
+
for (const item of catalog) {
|
|
338
|
+
const id = typeof item.id === 'string' ? item.id.trim() : ''
|
|
339
|
+
if (id.length === 0) continue
|
|
340
|
+
if (id.toLowerCase().startsWith('gpt-image')) continue
|
|
341
|
+
if (seen.has(id)) continue
|
|
342
|
+
|
|
343
|
+
const outputs = Array.isArray(item.output_modalities)
|
|
344
|
+
? item.output_modalities.map((value) => String(value).trim().toLowerCase()).filter(Boolean)
|
|
345
|
+
: []
|
|
346
|
+
if (outputs.length > 0 && !outputs.includes('text')) continue
|
|
347
|
+
|
|
348
|
+
const existing = existingById.get(id)
|
|
349
|
+
const contextWindow = firstPositiveInt(item, ['context_window', 'contextWindow', 'context_length', 'max_context_tokens'])
|
|
350
|
+
?? (existing === undefined ? null : positiveInt(existing.contextWindow))
|
|
351
|
+
?? 128000
|
|
352
|
+
const advertisedMax = firstPositiveInt(item, ['max_output_tokens', 'max_tokens'])
|
|
353
|
+
?? (existing === undefined ? null : positiveInt(existing.maxTokens))
|
|
354
|
+
?? 16384
|
|
355
|
+
const maxTokens = Math.min(advertisedMax, contextWindow)
|
|
356
|
+
|
|
357
|
+
// Каталог главнее текущей записи: если он объявил модальности, решение
|
|
358
|
+
// принимается по ним, а `supports_vision: false` означает «картинки нет»,
|
|
359
|
+
// даже когда в патче она когда-то была. Текущая запись отвечает только
|
|
360
|
+
// там, где каталог о зрении молчит вовсе.
|
|
361
|
+
const advertisedInputs = Array.isArray(item.input_modalities)
|
|
362
|
+
? item.input_modalities.map((value) => String(value).trim().toLowerCase()).filter(Boolean)
|
|
363
|
+
: []
|
|
364
|
+
let input
|
|
365
|
+
if (advertisedInputs.length > 0) {
|
|
366
|
+
input = advertisedInputs.includes('image') || item.supports_vision === true ? ['text', 'image'] : ['text']
|
|
367
|
+
} else if (item.supports_vision === true) {
|
|
368
|
+
input = ['text', 'image']
|
|
369
|
+
} else if (item.supports_vision === false) {
|
|
370
|
+
input = ['text']
|
|
371
|
+
} else if (Array.isArray(existing?.input) && existing.input.length > 0) {
|
|
372
|
+
input = [...existing.input]
|
|
373
|
+
} else {
|
|
374
|
+
input = ['text']
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
const model = {
|
|
378
|
+
id,
|
|
379
|
+
name: modelName(item, id),
|
|
380
|
+
contextWindow,
|
|
381
|
+
maxTokens,
|
|
382
|
+
input,
|
|
383
|
+
reasoningEfforts: reasoningEffortsFor(id, item, existing, levelMap, warnings),
|
|
384
|
+
}
|
|
385
|
+
if (isPlainObject(existing?.compat)) model.compat = existing.compat
|
|
386
|
+
models.push(model)
|
|
387
|
+
seen.add(id)
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
for (const id of cfg.keepModels) {
|
|
391
|
+
if (seen.has(id)) continue
|
|
392
|
+
const existing = existingById.get(id)
|
|
393
|
+
if (existing === undefined) {
|
|
394
|
+
warnings.push(`keepModels: "${id}" is neither in the catalog nor in the patch`)
|
|
395
|
+
continue
|
|
396
|
+
}
|
|
397
|
+
models.push(existing)
|
|
398
|
+
seen.add(id)
|
|
399
|
+
warnings.push(`keepModels: "${id}" kept although the catalog no longer lists it`)
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
return { models, warnings }
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Стабильная JSON-строка: ключи сортируются, порядок полей не считается
|
|
407
|
+
* изменением.
|
|
408
|
+
* @param {unknown} value
|
|
409
|
+
* @returns {string}
|
|
410
|
+
*/
|
|
411
|
+
function stableStringify(value) {
|
|
412
|
+
if (Array.isArray(value)) return `[${value.map((entry) => stableStringify(entry)).join(',')}]`
|
|
413
|
+
if (isPlainObject(value)) {
|
|
414
|
+
const keys = Object.keys(value).sort()
|
|
415
|
+
return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`
|
|
416
|
+
}
|
|
417
|
+
return JSON.stringify(value) ?? 'null'
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Сравнить текущий набор моделей с новым.
|
|
422
|
+
* @param {Array<Record<string, unknown>>} current
|
|
423
|
+
* @param {Array<Record<string, unknown>>} next
|
|
424
|
+
* @returns {{ added: string[], removed: string[], changed: Array<{ id: string, fields: string[] }>, changedCount: number }}
|
|
425
|
+
*/
|
|
426
|
+
function diffModels(current, next) {
|
|
427
|
+
/** @type {Map<string, Record<string, unknown>>} */
|
|
428
|
+
const currentById = new Map()
|
|
429
|
+
for (const model of current) {
|
|
430
|
+
if (typeof model.id === 'string') currentById.set(model.id, model)
|
|
431
|
+
}
|
|
432
|
+
/** @type {Map<string, Record<string, unknown>>} */
|
|
433
|
+
const nextById = new Map()
|
|
434
|
+
for (const model of next) {
|
|
435
|
+
if (typeof model.id === 'string') nextById.set(model.id, model)
|
|
436
|
+
}
|
|
437
|
+
const added = [...nextById.keys()].filter((id) => !currentById.has(id))
|
|
438
|
+
const removed = [...currentById.keys()].filter((id) => !nextById.has(id))
|
|
439
|
+
/** @type {Array<{ id: string, fields: string[] }>} */
|
|
440
|
+
const changed = []
|
|
441
|
+
for (const [id, model] of nextById) {
|
|
442
|
+
const before = currentById.get(id)
|
|
443
|
+
if (before === undefined) continue
|
|
444
|
+
const fields = []
|
|
445
|
+
for (const key of Object.keys(model)) {
|
|
446
|
+
if (stableStringify(model[key]) !== stableStringify(before[key])) fields.push(key)
|
|
447
|
+
}
|
|
448
|
+
for (const key of Object.keys(before)) {
|
|
449
|
+
if (!(key in model)) fields.push(key)
|
|
450
|
+
}
|
|
451
|
+
if (fields.length > 0) changed.push({ id, fields })
|
|
452
|
+
}
|
|
453
|
+
return { added, removed, changed, changedCount: changed.length }
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* Объединить сигнал вызова инструмента с таймаутом запроса.
|
|
458
|
+
* @param {AbortSignal | undefined} signal
|
|
459
|
+
* @param {number} timeoutMs
|
|
460
|
+
* @returns {AbortSignal}
|
|
461
|
+
*/
|
|
462
|
+
function fetchSignal(signal, timeoutMs) {
|
|
463
|
+
const timeout = AbortSignal.timeout(timeoutMs)
|
|
464
|
+
return signal === undefined ? timeout : AbortSignal.any([signal, timeout])
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** JSON-схема вывода инструмента: только поддерживаемые ключевые слова. */
|
|
468
|
+
const OUTPUT_SCHEMA = {
|
|
469
|
+
type: 'object',
|
|
470
|
+
additionalProperties: false,
|
|
471
|
+
required: [
|
|
472
|
+
'action', 'ok', 'at', 'provider', 'catalogModels', 'currentModels', 'nextModels',
|
|
473
|
+
'levelsSource', 'applied', 'added', 'removed', 'changed', 'warnings', 'allowlist', 'error',
|
|
474
|
+
],
|
|
475
|
+
properties: {
|
|
476
|
+
action: { type: 'string', enum: ['status', 'plan', 'apply'] },
|
|
477
|
+
ok: { type: 'boolean' },
|
|
478
|
+
at: { type: 'string' },
|
|
479
|
+
provider: { type: 'string' },
|
|
480
|
+
catalogModels: { type: 'integer' },
|
|
481
|
+
currentModels: { type: 'integer' },
|
|
482
|
+
nextModels: { type: 'integer' },
|
|
483
|
+
levelsSource: { type: 'string' },
|
|
484
|
+
applied: { type: 'boolean' },
|
|
485
|
+
added: { type: 'array', items: { type: 'string' } },
|
|
486
|
+
removed: { type: 'array', items: { type: 'string' } },
|
|
487
|
+
changed: {
|
|
488
|
+
type: 'array',
|
|
489
|
+
items: {
|
|
490
|
+
type: 'object',
|
|
491
|
+
additionalProperties: false,
|
|
492
|
+
required: ['id', 'fields'],
|
|
493
|
+
properties: {
|
|
494
|
+
id: { type: 'string' },
|
|
495
|
+
fields: { type: 'array', items: { type: 'string' } },
|
|
496
|
+
},
|
|
497
|
+
},
|
|
498
|
+
},
|
|
499
|
+
warnings: { type: 'array', items: { type: 'string' } },
|
|
500
|
+
allowlist: {
|
|
501
|
+
type: 'object',
|
|
502
|
+
additionalProperties: false,
|
|
503
|
+
required: ['pruned', 'added', 'skipped', 'changed'],
|
|
504
|
+
properties: {
|
|
505
|
+
pruned: { type: 'array', items: { type: 'string' } },
|
|
506
|
+
added: { type: 'array', items: { type: 'string' } },
|
|
507
|
+
skipped: { type: 'boolean' },
|
|
508
|
+
changed: { type: 'boolean' },
|
|
509
|
+
},
|
|
510
|
+
},
|
|
511
|
+
error: { type: 'string' },
|
|
512
|
+
},
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Текст результата для модели и пользователя.
|
|
517
|
+
* @param {Record<string, any>} value
|
|
518
|
+
* @returns {string}
|
|
519
|
+
*/
|
|
520
|
+
function renderValue(value) {
|
|
521
|
+
const lines = [
|
|
522
|
+
`${value.action}: ${value.provider} — catalog ${value.catalogModels}, current ${value.currentModels}, next ${value.nextModels}; levels: ${value.levelsSource}${value.applied ? '; applied' : ''}`,
|
|
523
|
+
]
|
|
524
|
+
if (value.added.length > 0) lines.push(`added: ${value.added.join(', ')}`)
|
|
525
|
+
if (value.removed.length > 0) lines.push(`removed: ${value.removed.join(', ')}`)
|
|
526
|
+
if (value.changed.length > 0) {
|
|
527
|
+
lines.push(`changed: ${value.changed.map((entry) => `${entry.id} (${entry.fields.join('/')})`).join(', ')}`)
|
|
528
|
+
}
|
|
529
|
+
if (value.added.length === 0 && value.removed.length === 0 && value.changed.length === 0) lines.push('catalog: no difference')
|
|
530
|
+
if (value.allowlist.pruned.length > 0) lines.push(`allowlist pruned: ${value.allowlist.pruned.join(', ')}`)
|
|
531
|
+
if (value.allowlist.added.length > 0) lines.push(`allowlist added: ${value.allowlist.added.join(', ')}`)
|
|
532
|
+
if (value.allowlist.changed && value.allowlist.pruned.length === 0 && value.allowlist.added.length === 0) {
|
|
533
|
+
lines.push('allowlist: duplicates or order fixed')
|
|
534
|
+
}
|
|
535
|
+
for (const warning of value.warnings) lines.push(`warning: ${warning}`)
|
|
536
|
+
if (value.error.length > 0) lines.push(`error: ${value.error}`)
|
|
537
|
+
return lines.join('\n')
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/** Строка композиции, которой владеет плагин (совпадает с id в cordis.patch.yml). */
|
|
541
|
+
const SELF_ROW_ID = 'cvc-catalog-sync'
|
|
542
|
+
|
|
543
|
+
/** Префикс HTTP-маршрута настроек; совпадает с константой клиентской половины. */
|
|
544
|
+
const SETTINGS_API_PREFIX = '/cvc-catalog-sync'
|
|
545
|
+
|
|
546
|
+
/** Верхняя граница тела запроса настроек: конфиг — это несколько килобайт. */
|
|
547
|
+
const SETTINGS_BODY_LIMIT = 65536
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* Проверить, что строка — http(s)-адрес.
|
|
551
|
+
* @param {unknown} value
|
|
552
|
+
* @returns {boolean}
|
|
553
|
+
*/
|
|
554
|
+
function isHttpUrl(value) {
|
|
555
|
+
if (typeof value !== 'string' || value.trim().length === 0) return false
|
|
556
|
+
try {
|
|
557
|
+
const url = new URL(value)
|
|
558
|
+
return url.protocol === 'https:' || url.protocol === 'http:'
|
|
559
|
+
} catch {
|
|
560
|
+
return false
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* Проверить пользовательский ввод перед записью в патч.
|
|
566
|
+
*
|
|
567
|
+
* Возвращает список понятных ошибок, а не молча подставляет умолчания:
|
|
568
|
+
* опечатка в интерфейсе не должна тихо превращаться в другие настройки.
|
|
569
|
+
* @param {unknown} raw
|
|
570
|
+
* @returns {string[]}
|
|
571
|
+
*/
|
|
572
|
+
function validateConfigInput(raw) {
|
|
573
|
+
if (!isPlainObject(raw)) return ['config: object required']
|
|
574
|
+
const errors = []
|
|
575
|
+
for (const key of ['entryId', 'provider', 'apiKeyEnv', 'baseURL', 'allowlistEntryId']) {
|
|
576
|
+
if (typeof raw[key] !== 'string' || raw[key].trim().length === 0) errors.push(`${key}: non-empty string required`)
|
|
577
|
+
}
|
|
578
|
+
if (typeof raw.baseURL === 'string' && raw.baseURL.trim().length > 0 && !isHttpUrl(raw.baseURL)) {
|
|
579
|
+
errors.push('baseURL: http(s) URL required')
|
|
580
|
+
}
|
|
581
|
+
for (const key of ['installerUrls']) {
|
|
582
|
+
const value = raw[key]
|
|
583
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
584
|
+
errors.push(`${key}: non-empty list of URLs required`)
|
|
585
|
+
continue
|
|
586
|
+
}
|
|
587
|
+
if (value.some((url) => !isHttpUrl(url))) errors.push(`${key}: every item must be an http(s) URL`)
|
|
588
|
+
}
|
|
589
|
+
if (!Array.isArray(raw.keepModels) || raw.keepModels.some((id) => typeof id !== 'string')) {
|
|
590
|
+
errors.push('keepModels: list of strings required')
|
|
591
|
+
}
|
|
592
|
+
for (const key of ['autoSync', 'syncAllowlist']) {
|
|
593
|
+
if (typeof raw[key] !== 'boolean') errors.push(`${key}: boolean required`)
|
|
594
|
+
}
|
|
595
|
+
const numbers = [
|
|
596
|
+
['intervalHours', 0, Infinity],
|
|
597
|
+
['startupDelayMs', 0, Infinity],
|
|
598
|
+
['levelsCacheMinutes', 0, Infinity],
|
|
599
|
+
['timeoutMs', 1, Infinity],
|
|
600
|
+
['minModelRatio', Number.MIN_VALUE, 1],
|
|
601
|
+
]
|
|
602
|
+
for (const [key, min, max] of numbers) {
|
|
603
|
+
const value = raw[key]
|
|
604
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < min || value > max) {
|
|
605
|
+
errors.push(`${key}: number in [${min}, ${max}] required`)
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
return errors
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/**
|
|
612
|
+
* Ответить JSON без кэширования.
|
|
613
|
+
* @param {import('node:http').ServerResponse} res
|
|
614
|
+
* @param {number} status
|
|
615
|
+
* @param {unknown} body
|
|
616
|
+
*/
|
|
617
|
+
function sendJson(res, status, body) {
|
|
618
|
+
res.writeHead(status, {
|
|
619
|
+
'content-type': 'application/json; charset=utf-8',
|
|
620
|
+
'cache-control': 'no-store',
|
|
621
|
+
'x-content-type-options': 'nosniff',
|
|
622
|
+
})
|
|
623
|
+
res.end(JSON.stringify(body))
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* Прочитать JSON-тело запроса с ограничением размера.
|
|
628
|
+
* @param {import('node:http').IncomingMessage} req
|
|
629
|
+
* @param {number} [limit]
|
|
630
|
+
* @returns {Promise<unknown>}
|
|
631
|
+
*/
|
|
632
|
+
function readJsonBody(req, limit = SETTINGS_BODY_LIMIT) {
|
|
633
|
+
return new Promise((resolve, reject) => {
|
|
634
|
+
let size = 0
|
|
635
|
+
const chunks = []
|
|
636
|
+
req.on('data', (chunk) => {
|
|
637
|
+
size += chunk.length
|
|
638
|
+
if (size > limit) {
|
|
639
|
+
reject(new Error('request body is too large'))
|
|
640
|
+
req.destroy()
|
|
641
|
+
return
|
|
642
|
+
}
|
|
643
|
+
chunks.push(chunk)
|
|
644
|
+
})
|
|
645
|
+
req.on('end', () => {
|
|
646
|
+
const text = Buffer.concat(chunks).toString('utf8')
|
|
647
|
+
if (text.trim().length === 0) {
|
|
648
|
+
resolve({})
|
|
649
|
+
return
|
|
650
|
+
}
|
|
651
|
+
try {
|
|
652
|
+
resolve(JSON.parse(text))
|
|
653
|
+
} catch (error) {
|
|
654
|
+
reject(new Error(`invalid JSON: ${messageOf(error)}`))
|
|
655
|
+
}
|
|
656
|
+
})
|
|
657
|
+
req.on('error', reject)
|
|
658
|
+
})
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* Текущее состояние для страницы настроек.
|
|
663
|
+
*
|
|
664
|
+
* `config` — действующие значения (слой профиля поверх слоя бандла),
|
|
665
|
+
* `override` — то, что записано в профильном патче, `defaults` — умолчания.
|
|
666
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
667
|
+
* @param {string} selfRowId
|
|
668
|
+
* @param {Record<string, any>} status
|
|
669
|
+
* @returns {Record<string, any>}
|
|
670
|
+
*/
|
|
671
|
+
function settingsState(ctx, selfRowId, status) {
|
|
672
|
+
const editor = ctx.configEditor
|
|
673
|
+
const layers = editor.configuration().find((row) => row.entry?.options?.id === selfRowId)
|
|
674
|
+
const inherited = isPlainObject(layers?.inherited) ? layers.inherited : {}
|
|
675
|
+
const override = isPlainObject(layers?.override) ? layers.override : {}
|
|
676
|
+
const config = normalizeConfig({ ...inherited, ...override })
|
|
677
|
+
const llmEntry = editor.entries().find((candidate) => candidate.options?.id === config.entryId)
|
|
678
|
+
const providers = isPlainObject(llmEntry?.options?.config?.providers)
|
|
679
|
+
? Object.keys(llmEntry.options.config.providers)
|
|
680
|
+
: []
|
|
681
|
+
return {
|
|
682
|
+
config,
|
|
683
|
+
override,
|
|
684
|
+
defaults: normalizeConfig({}),
|
|
685
|
+
providers,
|
|
686
|
+
patchPath: editor.documentPath,
|
|
687
|
+
rowId: selfRowId,
|
|
688
|
+
active: layers !== undefined,
|
|
689
|
+
status,
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/**
|
|
694
|
+
* Установить маршрут настроек.
|
|
695
|
+
* @param {{ register: (route: any) => () => void }} webServer
|
|
696
|
+
* @param {{ ctx: import('@deepseek-ai/cordis').Context, selfRowId: string, refresh: Function, toValue: Function, status: () => Record<string, any> }} deps
|
|
697
|
+
* @returns {() => void}
|
|
698
|
+
*/
|
|
699
|
+
function installSettingsApi(webServer, deps) {
|
|
700
|
+
const jsonRequest = (req) => String(req.headers['content-type'] ?? '').split(';')[0].trim() === 'application/json'
|
|
701
|
+
return webServer.register({
|
|
702
|
+
kind: 'prefix',
|
|
703
|
+
path: SETTINGS_API_PREFIX,
|
|
704
|
+
handler: async (req, res) => {
|
|
705
|
+
if (String(req.headers['sec-fetch-site'] ?? '') === 'cross-site') {
|
|
706
|
+
sendJson(res, 403, { error: 'forbidden' })
|
|
707
|
+
return
|
|
708
|
+
}
|
|
709
|
+
let route
|
|
710
|
+
try {
|
|
711
|
+
route = trimSlashes(new URL(req.url ?? '/', 'http://localhost').pathname.slice(SETTINGS_API_PREFIX.length))
|
|
712
|
+
} catch {
|
|
713
|
+
sendJson(res, 400, { error: 'malformed url' })
|
|
714
|
+
return
|
|
715
|
+
}
|
|
716
|
+
try {
|
|
717
|
+
if (route === 'health' && req.method === 'GET') {
|
|
718
|
+
sendJson(res, 200, { ok: true, plugin: deps.selfRowId })
|
|
719
|
+
return
|
|
720
|
+
}
|
|
721
|
+
if (route === 'state' && req.method === 'GET') {
|
|
722
|
+
sendJson(res, 200, settingsState(deps.ctx, deps.selfRowId, deps.status()))
|
|
723
|
+
return
|
|
724
|
+
}
|
|
725
|
+
if (route === 'config' && (req.method === 'PUT' || req.method === 'POST')) {
|
|
726
|
+
if (!jsonRequest(req)) {
|
|
727
|
+
sendJson(res, 415, { error: 'content-type: application/json required' })
|
|
728
|
+
return
|
|
729
|
+
}
|
|
730
|
+
const body = await readJsonBody(req)
|
|
731
|
+
const raw = isPlainObject(body) && isPlainObject(body.config) ? body.config : body
|
|
732
|
+
const errors = validateConfigInput(raw)
|
|
733
|
+
if (errors.length > 0) {
|
|
734
|
+
sendJson(res, 400, { error: 'invalid config', fields: errors })
|
|
735
|
+
return
|
|
736
|
+
}
|
|
737
|
+
const editor = deps.ctx.configEditor
|
|
738
|
+
const entry = editor.entries().find((candidate) => candidate.options?.id === deps.selfRowId)
|
|
739
|
+
if (entry === undefined) {
|
|
740
|
+
sendJson(res, 409, { error: `row "${deps.selfRowId}" is not active; enable the bundle first` })
|
|
741
|
+
return
|
|
742
|
+
}
|
|
743
|
+
const next = normalizeConfig(raw)
|
|
744
|
+
// Сброс к умолчаниям должен убрать переопределение, а не записать
|
|
745
|
+
// в патч копию умолчаний: `edit` удаляет строку, когда новое
|
|
746
|
+
// значение совпадает со слоем ниже.
|
|
747
|
+
const resetToDefaults = stableStringify(next) === stableStringify(normalizeConfig({}))
|
|
748
|
+
await editor.edit(entry, (current, inherited) => (resetToDefaults ? inherited : next))
|
|
749
|
+
sendJson(res, 200, { ok: true, config: next })
|
|
750
|
+
return
|
|
751
|
+
}
|
|
752
|
+
if (route === 'run' && req.method === 'POST') {
|
|
753
|
+
if (!jsonRequest(req)) {
|
|
754
|
+
sendJson(res, 415, { error: 'content-type: application/json required' })
|
|
755
|
+
return
|
|
756
|
+
}
|
|
757
|
+
const body = await readJsonBody(req)
|
|
758
|
+
const action = isPlainObject(body) && body.action === 'apply' ? 'apply' : 'plan'
|
|
759
|
+
const force = isPlainObject(body) && body.force === true
|
|
760
|
+
const result = await deps.refresh('tool', { apply: action === 'apply', force })
|
|
761
|
+
sendJson(res, 200, deps.toValue(result, action))
|
|
762
|
+
return
|
|
763
|
+
}
|
|
764
|
+
sendJson(res, 404, { error: 'not found' })
|
|
765
|
+
} catch (error) {
|
|
766
|
+
sendJson(res, 500, { error: messageOf(error) })
|
|
767
|
+
}
|
|
768
|
+
},
|
|
769
|
+
})
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/**
|
|
773
|
+
* Сервисы, без которых плагин не работает: запись профильного патча, реестр
|
|
774
|
+
* инструментов и разрешение ссылки на ключ.
|
|
775
|
+
*
|
|
776
|
+
* Плагин без них не активируется (Loader отложит запуск), а не падает.
|
|
777
|
+
*/
|
|
778
|
+
export const inject = ['configEditor', 'tools', 'credentials']
|
|
779
|
+
|
|
780
|
+
/**
|
|
781
|
+
* Подключить плагин.
|
|
782
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
783
|
+
* @param {unknown} [config]
|
|
784
|
+
*/
|
|
785
|
+
export function apply(ctx, config = {}) {
|
|
786
|
+
const cfg = normalizeConfig(config)
|
|
787
|
+
|
|
788
|
+
/** Последний прогон в этом процессе хоста. */
|
|
789
|
+
let last = null
|
|
790
|
+
/** Идущий прогон: параллельный вызов с тем же режимом ждёт его, а не открывает свой. */
|
|
791
|
+
let inflight = null
|
|
792
|
+
/** Кэш карты уровней: она меняется редко, а прогонов бывает два подряд. */
|
|
793
|
+
let levelsCache = null
|
|
794
|
+
|
|
795
|
+
/**
|
|
796
|
+
* Записать строку в лог хоста, не падая на профиле без логгера.
|
|
797
|
+
* @param {'info' | 'warn' | 'error'} level
|
|
798
|
+
* @param {string} message
|
|
799
|
+
*/
|
|
800
|
+
function log(level, message) {
|
|
801
|
+
const logger = ctx.logger
|
|
802
|
+
if (logger !== undefined && logger !== null && typeof logger[level] === 'function') {
|
|
803
|
+
logger[level](`cvc-catalog-sync: ${message}`)
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
/**
|
|
808
|
+
* Разрешить ключ провайдера через сервис credentials.
|
|
809
|
+
*
|
|
810
|
+
* Порядок источников DSH сохраняется: хранилище плагина, затем переменные
|
|
811
|
+
* окружения и `.env`. Значение остаётся на хосте и в лог не попадает.
|
|
812
|
+
* @param {string} ref
|
|
813
|
+
* @returns {Promise<string>}
|
|
814
|
+
*/
|
|
815
|
+
async function resolveKey(ref) {
|
|
816
|
+
const credentials = ctx.credentials
|
|
817
|
+
if (credentials === undefined || typeof credentials.resolve !== 'function') return ''
|
|
818
|
+
try {
|
|
819
|
+
const hit = await credentials.resolve(ref)
|
|
820
|
+
return typeof hit?.value === 'string' ? hit.value : ''
|
|
821
|
+
} catch {
|
|
822
|
+
return ''
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* Прочитать текущие модели маршрута из профильного патча.
|
|
828
|
+
* @returns {{ entry: import('@deepseek-ai/cordis').Context['loader'] extends never ? any : any, models: Array<Record<string, unknown>> }}
|
|
829
|
+
*/
|
|
830
|
+
function readCurrent() {
|
|
831
|
+
const editor = ctx.configEditor
|
|
832
|
+
const entry = editor.entries().find((candidate) => candidate.options?.id === cfg.entryId)
|
|
833
|
+
if (entry === undefined) throw new Error(`profile entry "${cfg.entryId}" is not available`)
|
|
834
|
+
const current = isPlainObject(entry.options.config) ? entry.options.config : {}
|
|
835
|
+
const providers = isPlainObject(current.providers) ? current.providers : {}
|
|
836
|
+
const profile = providers[cfg.provider]
|
|
837
|
+
if (!isPlainObject(profile)) throw new Error(`provider route "${cfg.provider}" is not configured in "${cfg.entryId}"`)
|
|
838
|
+
// llm-pi-ai отвергает `modelOverrides` рядом с `models`; сказать об этом
|
|
839
|
+
// самим понятнее, чем получить отказ валидации при записи.
|
|
840
|
+
if (isPlainObject(profile.modelOverrides) && Object.keys(profile.modelOverrides).length > 0) {
|
|
841
|
+
throw new Error(
|
|
842
|
+
`provider route "${cfg.provider}" uses modelOverrides; a models list cannot be written beside it — `
|
|
843
|
+
+ 'convert the route to an explicit models list first',
|
|
844
|
+
)
|
|
845
|
+
}
|
|
846
|
+
const models = Array.isArray(profile.models) ? profile.models.filter(isPlainObject) : []
|
|
847
|
+
return { entry, models }
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* Забрать каталог провайдера.
|
|
852
|
+
* @param {string} key
|
|
853
|
+
* @param {AbortSignal | undefined} signal
|
|
854
|
+
* @returns {Promise<Array<Record<string, unknown>>>}
|
|
855
|
+
*/
|
|
856
|
+
async function fetchCatalog(key, signal) {
|
|
857
|
+
const url = `${stripTrailingSlashes(cfg.baseURL)}/models`
|
|
858
|
+
const response = await fetch(url, {
|
|
859
|
+
headers: { authorization: `Bearer ${key}`, accept: 'application/json' },
|
|
860
|
+
signal: fetchSignal(signal, cfg.timeoutMs),
|
|
861
|
+
})
|
|
862
|
+
if (!response.ok) throw new Error(`${url}: HTTP ${response.status}`)
|
|
863
|
+
let body
|
|
864
|
+
try {
|
|
865
|
+
body = await response.json()
|
|
866
|
+
} catch (error) {
|
|
867
|
+
throw new Error(`${url}: invalid JSON (${error instanceof Error ? error.message : String(error)})`)
|
|
868
|
+
}
|
|
869
|
+
const items = parseCatalogPayload(body)
|
|
870
|
+
if (items.length === 0) throw new Error(`${url}: response contains no models`)
|
|
871
|
+
return items
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
/**
|
|
875
|
+
* Забрать карту уровней из установщика (первый успешный URL).
|
|
876
|
+
* @param {AbortSignal | undefined} signal
|
|
877
|
+
* @returns {Promise<{ map: Record<string, string[]> | null, source: string, problems: string[] }>}
|
|
878
|
+
*/
|
|
879
|
+
async function loadLevels(signal) {
|
|
880
|
+
if (levelsCache !== null && levelsCache.map !== null
|
|
881
|
+
&& Date.now() - levelsCache.at < cfg.levelsCacheMinutes * 60000) {
|
|
882
|
+
return levelsCache
|
|
883
|
+
}
|
|
884
|
+
const problems = []
|
|
885
|
+
for (const url of cfg.installerUrls) {
|
|
886
|
+
try {
|
|
887
|
+
const response = await fetch(url, {
|
|
888
|
+
headers: { accept: 'text/plain, */*' },
|
|
889
|
+
signal: fetchSignal(signal, cfg.timeoutMs),
|
|
890
|
+
})
|
|
891
|
+
if (!response.ok) {
|
|
892
|
+
problems.push(`${url}: HTTP ${response.status}`)
|
|
893
|
+
continue
|
|
894
|
+
}
|
|
895
|
+
const text = await response.text()
|
|
896
|
+
const map = parseReasoningLevels(text)
|
|
897
|
+
if (map === null) {
|
|
898
|
+
problems.push(`${url}: reasoningLevels literal not found`)
|
|
899
|
+
continue
|
|
900
|
+
}
|
|
901
|
+
levelsCache = { map, source: url, at: Date.now(), problems: [] }
|
|
902
|
+
return levelsCache
|
|
903
|
+
} catch (error) {
|
|
904
|
+
problems.push(`${url}: ${error instanceof Error ? error.message : String(error)}`)
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
for (const problem of problems) log('warn', problem)
|
|
908
|
+
levelsCache = { map: null, source: 'none', at: 0, problems }
|
|
909
|
+
return levelsCache
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/**
|
|
913
|
+
* Записать каталог в строку llm-pi-ai, пересобрав модели по свежему конфигу.
|
|
914
|
+
*
|
|
915
|
+
* `configEditor.edit` отдаёт конфиг на момент блокировки, поэтому сборка
|
|
916
|
+
* внутри колбэка — единственный способ не потерять правку, сделанную между
|
|
917
|
+
* чтением и записью (ручной `maxTokens`, `compat`). Там же проверяется
|
|
918
|
+
* защита от усыхания каталога: её отказ не пишет файл.
|
|
919
|
+
* @param {any} entry
|
|
920
|
+
* @param {Array<Record<string, unknown>>} catalog
|
|
921
|
+
* @param {Record<string, string[]> | null} levelMap
|
|
922
|
+
* @param {boolean} force
|
|
923
|
+
* @returns {Promise<{ models: Array<Record<string, unknown>>, warnings: string[], diff: ReturnType<typeof diffModels>, unchanged: boolean }>}
|
|
924
|
+
*/
|
|
925
|
+
async function writeModels(entry, catalog, levelMap, force) {
|
|
926
|
+
/** @type {any} */
|
|
927
|
+
let outcome = null
|
|
928
|
+
await ctx.configEditor.edit(entry, (current) => {
|
|
929
|
+
const fresh = modelsFromConfig(current)
|
|
930
|
+
const built = buildModels(catalog, levelMap, fresh, cfg)
|
|
931
|
+
if (!force) {
|
|
932
|
+
const minRequired = Math.max(1, Math.ceil(fresh.length * cfg.minModelRatio))
|
|
933
|
+
if (built.models.length < minRequired) {
|
|
934
|
+
throw new Error(
|
|
935
|
+
`guard: catalog returned ${built.models.length} models, below ${minRequired} `
|
|
936
|
+
+ `(${Math.round(cfg.minModelRatio * 100)}% of current ${fresh.length}); `
|
|
937
|
+
+ 'nothing written, use force to override',
|
|
938
|
+
)
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
const diff = diffModels(fresh, built.models)
|
|
942
|
+
outcome = { models: built.models, warnings: built.warnings, diff, unchanged: isDiffEmpty(diff) }
|
|
943
|
+
return withModels(current, built.models)
|
|
944
|
+
})
|
|
945
|
+
return outcome
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
/**
|
|
949
|
+
* Прочитать модели маршрута из raw-конфига строки.
|
|
950
|
+
* @param {unknown} config
|
|
951
|
+
* @returns {Array<Record<string, unknown>>}
|
|
952
|
+
*/
|
|
953
|
+
function modelsFromConfig(config) {
|
|
954
|
+
const providers = isPlainObject(config) && isPlainObject(config.providers) ? config.providers : {}
|
|
955
|
+
const profile = providers[cfg.provider]
|
|
956
|
+
return isPlainObject(profile) && Array.isArray(profile.models) ? profile.models.filter(isPlainObject) : []
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
/**
|
|
960
|
+
* Собрать следующий raw-конфиг строки с новым списком моделей.
|
|
961
|
+
* @param {unknown} current
|
|
962
|
+
* @param {Array<Record<string, unknown>>} models
|
|
963
|
+
* @returns {Record<string, unknown>}
|
|
964
|
+
*/
|
|
965
|
+
function withModels(current, models) {
|
|
966
|
+
const next = isPlainObject(current) ? { ...current } : {}
|
|
967
|
+
const providers = isPlainObject(next.providers) ? { ...next.providers } : {}
|
|
968
|
+
const profile = isPlainObject(providers[cfg.provider]) ? { ...providers[cfg.provider] } : {}
|
|
969
|
+
profile.models = models
|
|
970
|
+
providers[cfg.provider] = profile
|
|
971
|
+
next.providers = providers
|
|
972
|
+
return next
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
/**
|
|
976
|
+
* Привести список доступных моделей сабагентов к каталогу маршрута.
|
|
977
|
+
*
|
|
978
|
+
* Чужие провайдеры сохраняются как есть: плагин владеет только своим
|
|
979
|
+
* маршрутом. Если строки нет (плагин сабагентов не установлен) — пропуск.
|
|
980
|
+
* @param {Array<Record<string, unknown>>} models
|
|
981
|
+
* @returns {Promise<{ pruned: string[], added: string[], skipped: boolean, changed: boolean }>}
|
|
982
|
+
*/
|
|
983
|
+
async function syncAllowlist(models) {
|
|
984
|
+
const empty = { pruned: [], added: [], skipped: true, changed: false }
|
|
985
|
+
if (!cfg.syncAllowlist) return empty
|
|
986
|
+
const editor = ctx.configEditor
|
|
987
|
+
const entry = editor.entries().find((candidate) => candidate.options?.id === cfg.allowlistEntryId)
|
|
988
|
+
if (entry === undefined) return empty
|
|
989
|
+
const catalogIds = models.map((model) => model.id)
|
|
990
|
+
const catalogSet = new Set(catalogIds)
|
|
991
|
+
const expected = (others) => [...others, ...catalogIds.map((id) => ({ provider: cfg.provider, model: id }))]
|
|
992
|
+
/** Посчитать, что нужно поправить для одного снимка списка. */
|
|
993
|
+
const planFor = (allowedValue) => {
|
|
994
|
+
const allowedRows = Array.isArray(allowedValue) ? allowedValue.filter(isPlainObject) : []
|
|
995
|
+
const ownIds = new Set(allowedRows.filter((row) => row.provider === cfg.provider).map((row) => row.model))
|
|
996
|
+
return {
|
|
997
|
+
allowed: allowedRows,
|
|
998
|
+
others: allowedRows.filter((row) => row.provider !== cfg.provider),
|
|
999
|
+
pruned: [...ownIds].filter((id) => !catalogSet.has(id)),
|
|
1000
|
+
added: catalogIds.filter((id) => !ownIds.has(id)),
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
const snapshot = planFor(isPlainObject(entry.options.config) ? entry.options.config.allowedModels : [])
|
|
1004
|
+
// Сравнивается весь список, а не только pruned/added: дубли и порядок
|
|
1005
|
+
// собственных маршрутов в этих множествах не видны, а DSH их отвергает.
|
|
1006
|
+
if (stableStringify(snapshot.allowed) === stableStringify(expected(snapshot.others))) {
|
|
1007
|
+
return { pruned: [], added: [], skipped: false, changed: false }
|
|
1008
|
+
}
|
|
1009
|
+
/** @type {{ pruned: string[], added: string[], changed: boolean } | null} */
|
|
1010
|
+
let outcome = null
|
|
1011
|
+
await ctx.configEditor.edit(entry, (cur) => {
|
|
1012
|
+
const current = isPlainObject(cur) ? cur : {}
|
|
1013
|
+
// Пересчёт на момент блокировки: чужой список мог измениться, пока шли
|
|
1014
|
+
// запросы к каталогу.
|
|
1015
|
+
const fresh = planFor(current.allowedModels)
|
|
1016
|
+
const nextAllowed = expected(fresh.others)
|
|
1017
|
+
const changed = stableStringify(fresh.allowed) !== stableStringify(nextAllowed)
|
|
1018
|
+
outcome = { pruned: fresh.pruned, added: fresh.added, changed }
|
|
1019
|
+
return changed ? { ...current, allowedModels: nextAllowed } : current
|
|
1020
|
+
})
|
|
1021
|
+
log('info', `allowed models synced: +${outcome?.added.length ?? 0}/-${outcome?.pruned.length ?? 0}`)
|
|
1022
|
+
return {
|
|
1023
|
+
pruned: outcome?.pruned ?? [],
|
|
1024
|
+
added: outcome?.added ?? [],
|
|
1025
|
+
skipped: false,
|
|
1026
|
+
changed: outcome?.changed ?? false,
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
/**
|
|
1031
|
+
* Один прогон: каталог → модели → (при необходимости) запись.
|
|
1032
|
+
* @param {'startup' | 'timer' | 'tool'} reason
|
|
1033
|
+
* @param {{ apply: boolean, force?: boolean, signal?: AbortSignal }} options
|
|
1034
|
+
* @returns {Promise<Record<string, any>>}
|
|
1035
|
+
*/
|
|
1036
|
+
async function collect(reason, options) {
|
|
1037
|
+
/** @type {Record<string, any>} */
|
|
1038
|
+
const result = {
|
|
1039
|
+
ok: false,
|
|
1040
|
+
reason,
|
|
1041
|
+
at: new Date().toISOString(),
|
|
1042
|
+
provider: cfg.provider,
|
|
1043
|
+
catalogModels: 0,
|
|
1044
|
+
currentModels: 0,
|
|
1045
|
+
nextModels: 0,
|
|
1046
|
+
levelsSource: 'none',
|
|
1047
|
+
applied: false,
|
|
1048
|
+
added: [],
|
|
1049
|
+
removed: [],
|
|
1050
|
+
changed: [],
|
|
1051
|
+
warnings: [],
|
|
1052
|
+
allowlist: { pruned: [], added: [], skipped: true, changed: false },
|
|
1053
|
+
error: '',
|
|
1054
|
+
}
|
|
1055
|
+
try {
|
|
1056
|
+
const key = await resolveKey(cfg.apiKeyEnv)
|
|
1057
|
+
if (key.length === 0) {
|
|
1058
|
+
throw new Error(`credential "${cfg.apiKeyEnv}" is not configured (process env, store or .env)`)
|
|
1059
|
+
}
|
|
1060
|
+
const catalog = await fetchCatalog(key, options.signal)
|
|
1061
|
+
result.catalogModels = catalog.length
|
|
1062
|
+
|
|
1063
|
+
const levels = await loadLevels(options.signal)
|
|
1064
|
+
result.levelsSource = levels.source
|
|
1065
|
+
if (levels.map === null) {
|
|
1066
|
+
result.warnings.push('reasoning levels unavailable: existing levels preserved, new models fall back to supports_reasoning')
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
const current = readCurrent()
|
|
1070
|
+
result.currentModels = current.models.length
|
|
1071
|
+
|
|
1072
|
+
const built = buildModels(catalog, levels.map, current.models, cfg)
|
|
1073
|
+
result.nextModels = built.models.length
|
|
1074
|
+
const warningsBeforeBuild = result.warnings.length
|
|
1075
|
+
result.warnings.push(...built.warnings)
|
|
1076
|
+
|
|
1077
|
+
const diff = diffModels(current.models, built.models)
|
|
1078
|
+
result.added = diff.added
|
|
1079
|
+
result.removed = diff.removed
|
|
1080
|
+
result.changed = diff.changed
|
|
1081
|
+
|
|
1082
|
+
const unchanged = isDiffEmpty(diff)
|
|
1083
|
+
|
|
1084
|
+
if (!options.apply) {
|
|
1085
|
+
// plan ничего не пишет, поэтому защита от усыхания сообщается
|
|
1086
|
+
// предупреждением, а не отказом: дифф увидеть нужно.
|
|
1087
|
+
if (!unchanged && options.force !== true) {
|
|
1088
|
+
const minRequired = Math.max(1, Math.ceil(current.models.length * cfg.minModelRatio))
|
|
1089
|
+
if (built.models.length < minRequired) {
|
|
1090
|
+
result.warnings.push(
|
|
1091
|
+
`guard: ${built.models.length} models is below ${minRequired} `
|
|
1092
|
+
+ `(${Math.round(cfg.minModelRatio * 100)}% of current ${current.models.length}); `
|
|
1093
|
+
+ 'apply would refuse without force',
|
|
1094
|
+
)
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
result.ok = true
|
|
1098
|
+
return result
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
if (unchanged) {
|
|
1102
|
+
// Модели совпадают, но список сабагентов мог разъехаться: чиним его.
|
|
1103
|
+
result.ok = true
|
|
1104
|
+
try {
|
|
1105
|
+
result.allowlist = await syncAllowlist(current.models)
|
|
1106
|
+
// Патч всё-таки записан — отчитываемся честно.
|
|
1107
|
+
result.applied = result.allowlist.changed
|
|
1108
|
+
} catch (error) {
|
|
1109
|
+
result.warnings.push(`allowed models not synced: ${messageOf(error)}`)
|
|
1110
|
+
}
|
|
1111
|
+
return result
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
const outcome = await writeModels(current.entry, catalog, levels.map, options.force === true)
|
|
1115
|
+
result.applied = outcome !== null && !outcome.unchanged
|
|
1116
|
+
if (outcome !== null) {
|
|
1117
|
+
result.nextModels = outcome.models.length
|
|
1118
|
+
result.added = outcome.diff.added
|
|
1119
|
+
result.removed = outcome.diff.removed
|
|
1120
|
+
result.changed = outcome.diff.changed
|
|
1121
|
+
// Предупреждения сборки на момент блокировки точнее предварительных.
|
|
1122
|
+
result.warnings.length = warningsBeforeBuild
|
|
1123
|
+
result.warnings.push(...outcome.warnings)
|
|
1124
|
+
}
|
|
1125
|
+
log('info', `applied catalog: ${result.nextModels} models (+${result.added.length}/-${result.removed.length}/~${result.changed.length})`)
|
|
1126
|
+
try {
|
|
1127
|
+
result.allowlist = await syncAllowlist(outcome?.models ?? built.models)
|
|
1128
|
+
} catch (error) {
|
|
1129
|
+
result.warnings.push(`allowed models not synced: ${messageOf(error)}`)
|
|
1130
|
+
}
|
|
1131
|
+
result.ok = true
|
|
1132
|
+
} catch (error) {
|
|
1133
|
+
result.error = error instanceof Error ? error.message : String(error)
|
|
1134
|
+
log('warn', `refresh failed: ${result.error}`)
|
|
1135
|
+
}
|
|
1136
|
+
return result
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
/**
|
|
1140
|
+
* Прогон с дедупликацией: два одновременных вызова не дублируют запросы.
|
|
1141
|
+
* @param {'startup' | 'timer' | 'tool'} reason
|
|
1142
|
+
* @param {{ apply: boolean, force?: boolean, signal?: AbortSignal }} options
|
|
1143
|
+
* @returns {Promise<Record<string, any>>}
|
|
1144
|
+
*/
|
|
1145
|
+
function refresh(reason, options) {
|
|
1146
|
+
const apply = options.apply === true
|
|
1147
|
+
const force = options.force === true
|
|
1148
|
+
// Слияние только внутри одного режима: `plan`, прицепившийся к идущей
|
|
1149
|
+
// записи, не должен отчитываться «applied», а `force: true` не теряется
|
|
1150
|
+
// в обычном прогоне.
|
|
1151
|
+
const key = `${apply}:${force}`
|
|
1152
|
+
if (inflight !== null && inflight.key === key) return inflight.promise
|
|
1153
|
+
const promise = collect(reason, options).then((result) => {
|
|
1154
|
+
last = result
|
|
1155
|
+
return result
|
|
1156
|
+
})
|
|
1157
|
+
const record = { key, promise }
|
|
1158
|
+
inflight = record
|
|
1159
|
+
const clear = () => {
|
|
1160
|
+
if (inflight === record) inflight = null
|
|
1161
|
+
}
|
|
1162
|
+
promise.then(clear, clear)
|
|
1163
|
+
return promise
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
const hmrService = typeof ctx.get === 'function' ? ctx.get('hmr') : undefined
|
|
1167
|
+
const hmrPresent = hmrService !== undefined && hmrService !== null
|
|
1168
|
+
/**
|
|
1169
|
+
* AsyncLocalStorage HMR-транзакции, если сервис его отдаёт.
|
|
1170
|
+
*
|
|
1171
|
+
* `executing` — приватное поле Hmr, но именно им сам DSH выводит наблюдение
|
|
1172
|
+
* за файлами из транзакции.
|
|
1173
|
+
* @type {{ exit?: (factory: () => unknown) => unknown, getStore?: () => unknown } | null}
|
|
1174
|
+
*/
|
|
1175
|
+
let hmrExecuting = null
|
|
1176
|
+
try {
|
|
1177
|
+
const executing = hmrPresent ? hmrService.executing : undefined
|
|
1178
|
+
if (executing !== undefined && typeof executing.exit === 'function') {
|
|
1179
|
+
hmrExecuting = /** @type {any} */ (executing)
|
|
1180
|
+
}
|
|
1181
|
+
} catch {
|
|
1182
|
+
hmrExecuting = null
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
/**
|
|
1186
|
+
* Автоматическая запись включается, только когда таймер гарантированно
|
|
1187
|
+
* оказывается вне HMR-транзакции.
|
|
1188
|
+
*
|
|
1189
|
+
* Без HMR-сервиса транзакций не бывает вообще. Если же сервис есть, а его
|
|
1190
|
+
* AsyncLocalStorage недоступен, выйти из контекста нельзя: таймер унаследует
|
|
1191
|
+
* транзакцию установки и `configEditor.edit()` упадёт. Тогда честнее
|
|
1192
|
+
* выключить авто-запись и сказать об этом, чем падать на каждой смене
|
|
1193
|
+
* каталога; ручной `cvc_catalog apply` работает всегда.
|
|
1194
|
+
*/
|
|
1195
|
+
let autoApply = cfg.autoSync && !(hmrPresent && hmrExecuting === null)
|
|
1196
|
+
if (cfg.autoSync && !autoApply) {
|
|
1197
|
+
log('warn', 'auto-write disabled: the HMR service exposes no usable transaction context in this host; '
|
|
1198
|
+
+ 'timers will only report the diff, use cvc_catalog apply')
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
/** Фоновый прогон по таймеру: ошибки уже внутри результата, промис не должен всплывать. */
|
|
1202
|
+
function backgroundRun(reason) {
|
|
1203
|
+
void refresh(reason, { apply: autoApply }).catch((error) => {
|
|
1204
|
+
log('warn', `background refresh failed: ${messageOf(error)}`)
|
|
1205
|
+
})
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
/**
|
|
1209
|
+
* Создать таймер вне текущей async-зоны.
|
|
1210
|
+
*
|
|
1211
|
+
* Плагин может активироваться внутри HMR-транзакции. Таймер, созданный
|
|
1212
|
+
* внутри неё, наследует AsyncLocalStorage-контекст, и `configEditor.edit()`
|
|
1213
|
+
* при срабатывании получает «HMR transactions cannot be nested».
|
|
1214
|
+
* @template T
|
|
1215
|
+
* @param {() => T} factory
|
|
1216
|
+
* @returns {T}
|
|
1217
|
+
*/
|
|
1218
|
+
function scheduleOutsideHmr(factory) {
|
|
1219
|
+
if (hmrExecuting !== null) {
|
|
1220
|
+
try {
|
|
1221
|
+
return /** @type {T} */ (hmrExecuting.exit(factory))
|
|
1222
|
+
} catch (error) {
|
|
1223
|
+
// `exit` штатно не бросает, но если это случилось — таймер окажется
|
|
1224
|
+
// внутри транзакции, поэтому авто-запись выключаем до перезапуска.
|
|
1225
|
+
if (autoApply) {
|
|
1226
|
+
autoApply = false
|
|
1227
|
+
log('warn', `auto-write disabled: HMR transaction escape failed (${messageOf(error)}); `
|
|
1228
|
+
+ 'timers will only report the diff, use cvc_catalog apply')
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
return factory()
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
// Автоматика: стартовая проверка после того, как Loader устоялся, и таймер.
|
|
1236
|
+
if (cfg.autoSync) {
|
|
1237
|
+
ctx.effect(() => {
|
|
1238
|
+
const startup = scheduleOutsideHmr(() => setTimeout(() => backgroundRun('startup'), cfg.startupDelayMs))
|
|
1239
|
+
startup.unref?.()
|
|
1240
|
+
return () => clearTimeout(startup)
|
|
1241
|
+
}, 'cvc-catalog-sync: startup run')
|
|
1242
|
+
if (cfg.intervalHours > 0) {
|
|
1243
|
+
// setInterval принимает от 1 до 2^31-1 мс. Слишком малое значение
|
|
1244
|
+
// (0.00001 ч) округлилось бы в 0 и дало почти непрерывные прогоны,
|
|
1245
|
+
// поэтому нижняя граница — минута.
|
|
1246
|
+
const requested = cfg.intervalHours * 3600000
|
|
1247
|
+
const periodMs = Math.min(Math.max(Math.round(requested), 60000), 2147483647)
|
|
1248
|
+
if (requested < 60000) {
|
|
1249
|
+
log('warn', `intervalHours ${cfg.intervalHours} is too small, timer raised to 1 minute`)
|
|
1250
|
+
} else if (requested > 2147483647) {
|
|
1251
|
+
log('warn', `intervalHours ${cfg.intervalHours} is too large, timer clamped to 24.8 days`)
|
|
1252
|
+
}
|
|
1253
|
+
ctx.effect(() => {
|
|
1254
|
+
const timer = scheduleOutsideHmr(() => setInterval(() => backgroundRun('timer'), periodMs))
|
|
1255
|
+
timer.unref?.()
|
|
1256
|
+
return () => clearInterval(timer)
|
|
1257
|
+
}, 'cvc-catalog-sync: interval')
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
/** @param {Record<string, any>} result @param {'status' | 'plan' | 'apply'} action */
|
|
1262
|
+
function toValue(result, action) {
|
|
1263
|
+
return {
|
|
1264
|
+
action,
|
|
1265
|
+
ok: result.ok === true,
|
|
1266
|
+
at: typeof result.at === 'string' ? result.at : '',
|
|
1267
|
+
provider: cfg.provider,
|
|
1268
|
+
catalogModels: Number.isInteger(result.catalogModels) ? result.catalogModels : 0,
|
|
1269
|
+
currentModels: Number.isInteger(result.currentModels) ? result.currentModels : 0,
|
|
1270
|
+
nextModels: Number.isInteger(result.nextModels) ? result.nextModels : 0,
|
|
1271
|
+
levelsSource: typeof result.levelsSource === 'string' ? result.levelsSource : 'none',
|
|
1272
|
+
applied: result.applied === true,
|
|
1273
|
+
added: Array.isArray(result.added) ? result.added : [],
|
|
1274
|
+
removed: Array.isArray(result.removed) ? result.removed : [],
|
|
1275
|
+
changed: Array.isArray(result.changed) ? result.changed : [],
|
|
1276
|
+
warnings: Array.isArray(result.warnings) ? result.warnings : [],
|
|
1277
|
+
allowlist: {
|
|
1278
|
+
pruned: Array.isArray(result.allowlist?.pruned) ? result.allowlist.pruned : [],
|
|
1279
|
+
added: Array.isArray(result.allowlist?.added) ? result.allowlist.added : [],
|
|
1280
|
+
skipped: result.allowlist?.skipped !== false,
|
|
1281
|
+
changed: result.allowlist?.changed === true,
|
|
1282
|
+
},
|
|
1283
|
+
error: typeof result.error === 'string' ? result.error : '',
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
/** Текущее число моделей в патче; для status, если прогонов ещё не было. */
|
|
1288
|
+
function currentModelCount() {
|
|
1289
|
+
try {
|
|
1290
|
+
return readCurrent().models.length
|
|
1291
|
+
} catch {
|
|
1292
|
+
return 0
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
ctx.effect(() => ctx.tools.register({
|
|
1297
|
+
name: TOOL_NAME,
|
|
1298
|
+
description: 'Refresh the CheapVibeCode model catalog in the DSH profile patch. '
|
|
1299
|
+
+ 'Reads the provider catalog and the reasoning-level map from the official installer, '
|
|
1300
|
+
+ 'then rewrites only llm-pi-ai.providers.<route>.models and, when enabled, the '
|
|
1301
|
+
+ 'subagent allowed-model list. Actions: status (last run in this process, no network), '
|
|
1302
|
+
+ 'plan (fetch and show the diff without writing), apply (fetch and write). '
|
|
1303
|
+
+ 'A write happens only when the catalog changed, and is refused when the response '
|
|
1304
|
+
+ 'shrinks below the configured share of the current model count unless force is set. '
|
|
1305
|
+
+ 'The change is applied without restarting DSH.',
|
|
1306
|
+
parameters: {
|
|
1307
|
+
type: 'object',
|
|
1308
|
+
additionalProperties: false,
|
|
1309
|
+
properties: {
|
|
1310
|
+
action: {
|
|
1311
|
+
type: 'string',
|
|
1312
|
+
enum: ['status', 'plan', 'apply'],
|
|
1313
|
+
description: 'status: report the last run in this process without network. '
|
|
1314
|
+
+ 'plan: fetch and return the diff without writing. apply: fetch and write the catalog.',
|
|
1315
|
+
},
|
|
1316
|
+
force: {
|
|
1317
|
+
type: 'boolean',
|
|
1318
|
+
description: 'apply only: write even when the response is smaller than the model-count guard allows.',
|
|
1319
|
+
},
|
|
1320
|
+
},
|
|
1321
|
+
},
|
|
1322
|
+
output: {
|
|
1323
|
+
schema: OUTPUT_SCHEMA,
|
|
1324
|
+
render: (_args, value) => [{ type: 'text', text: renderValue(value) }],
|
|
1325
|
+
},
|
|
1326
|
+
timeoutMs: 90000,
|
|
1327
|
+
async execute(args, exec) {
|
|
1328
|
+
const action = isPlainObject(args) && (args.action === 'status' || args.action === 'plan' || args.action === 'apply')
|
|
1329
|
+
? args.action
|
|
1330
|
+
: 'status'
|
|
1331
|
+
if (action === 'status') {
|
|
1332
|
+
return toValue(last ?? {
|
|
1333
|
+
ok: true,
|
|
1334
|
+
at: '',
|
|
1335
|
+
provider: cfg.provider,
|
|
1336
|
+
catalogModels: 0,
|
|
1337
|
+
currentModels: currentModelCount(),
|
|
1338
|
+
nextModels: 0,
|
|
1339
|
+
levelsSource: 'none',
|
|
1340
|
+
warnings: ['no refresh has run in this process yet'],
|
|
1341
|
+
}, 'status')
|
|
1342
|
+
}
|
|
1343
|
+
const result = await refresh('tool', {
|
|
1344
|
+
apply: action === 'apply',
|
|
1345
|
+
force: isPlainObject(args) && args.force === true,
|
|
1346
|
+
signal: exec.signal,
|
|
1347
|
+
})
|
|
1348
|
+
last = result
|
|
1349
|
+
return toValue(result, action)
|
|
1350
|
+
},
|
|
1351
|
+
}), 'cvc-catalog-sync: refresh tool')
|
|
1352
|
+
|
|
1353
|
+
/**
|
|
1354
|
+
* Страница настроек: маршрут есть только там, где есть веб-сервер.
|
|
1355
|
+
* В headless-профилях плагин продолжает работать через инструмент.
|
|
1356
|
+
*/
|
|
1357
|
+
ctx.inject(['webServer'], (web) => {
|
|
1358
|
+
web.effect(() => installSettingsApi(web.webServer, {
|
|
1359
|
+
ctx,
|
|
1360
|
+
selfRowId: SELF_ROW_ID,
|
|
1361
|
+
refresh,
|
|
1362
|
+
toValue,
|
|
1363
|
+
status: () => toValue(last ?? {
|
|
1364
|
+
ok: true,
|
|
1365
|
+
at: '',
|
|
1366
|
+
provider: cfg.provider,
|
|
1367
|
+
catalogModels: 0,
|
|
1368
|
+
currentModels: currentModelCount(),
|
|
1369
|
+
nextModels: 0,
|
|
1370
|
+
levelsSource: 'none',
|
|
1371
|
+
warnings: [],
|
|
1372
|
+
}, 'status'),
|
|
1373
|
+
}), 'cvc-catalog-sync: settings API')
|
|
1374
|
+
})
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
export {
|
|
1378
|
+
DEFAULT_INSTALLER_URLS,
|
|
1379
|
+
FULL_ROW,
|
|
1380
|
+
SELF_ROW_ID,
|
|
1381
|
+
SETTINGS_API_PREFIX,
|
|
1382
|
+
TOOL_NAME,
|
|
1383
|
+
WIRE_LEVELS,
|
|
1384
|
+
buildModels,
|
|
1385
|
+
diffModels,
|
|
1386
|
+
installSettingsApi,
|
|
1387
|
+
normalizeConfig,
|
|
1388
|
+
parseCatalogPayload,
|
|
1389
|
+
parseReasoningLevels,
|
|
1390
|
+
reasoningEffortsFor,
|
|
1391
|
+
settingsState,
|
|
1392
|
+
stableStringify,
|
|
1393
|
+
validateConfigInput,
|
|
1394
|
+
}
|