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.
- package/CHANGELOG.md +203 -0
- package/README.md +297 -203
- package/README.ru.md +380 -0
- package/SECURITY.md +234 -34
- package/client.js +2428 -553
- package/cordis.patch.yml +13 -8
- package/docs/ARCHITECTURE.md +965 -0
- package/docs/COMPATIBILITY.md +260 -0
- package/docs/DETAIL.md +3 -0
- package/docs/UPGRADING.md +357 -0
- package/docs/preview.svg +99 -0
- package/icon.svg +76 -8
- package/index.js +243 -1312
- package/lib/CONTRACT.js +63 -0
- package/lib/balance.js +412 -0
- package/lib/cache.js +114 -0
- package/lib/catalog-build.js +391 -0
- package/lib/catalog-sync.js +856 -0
- package/lib/coefficients.js +308 -0
- package/lib/config.js +558 -0
- package/lib/cvc-api.js +372 -0
- package/lib/http.js +269 -0
- package/lib/providers.js +210 -0
- package/lib/state.js +233 -0
- package/locale/en.json +4 -3
- package/locale/ru.json +4 -3
- package/package.json +32 -10
package/index.js
CHANGED
|
@@ -1,796 +1,99 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* cvc-catalog-sync-plugin 2.0.0 — три функции CheapVibeCode в одном плагине.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* Синхронизация каталога, коэффициенты моделей и баланс ключа включаются
|
|
5
|
+
* независимо группой `features`. Выключенная функция не регистрирует ничего:
|
|
6
|
+
* её маршрут отвечает 404, таймер не создаётся, инструмент не появляется.
|
|
7
|
+
* Страница настроек существует всегда — это и есть переключатель.
|
|
7
8
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* 3. собирает `models` по правилам установщика (`modelFromCatalog`);
|
|
12
|
-
* 4. точечно пишет результат в строку `llm-pi-ai` профильного патча через
|
|
13
|
-
* `ctx.configEditor.edit()` — единственный sanctioned-путь записи: он
|
|
14
|
-
* сохраняет комментарии и чужие строки, пишет атомарно, а `dsh-hmr`
|
|
15
|
-
* перечитывает патч без перезапуска приложения.
|
|
9
|
+
* Все поля `Config` объявлены `.volatile()`, поэтому правка строки патча
|
|
10
|
+
* приходит событием `loader/volatile-update` и применяется на лету: каркас
|
|
11
|
+
* перемонтирует только затронутые функции, не перезапуская плагин.
|
|
16
12
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
* Ручной запуск — инструмент `cvc_catalog` (status / plan / apply).
|
|
13
|
+
* Контракт функций (lib/catalog-sync.js, lib/coefficients.js, lib/balance.js):
|
|
14
|
+
* register(ctx, deps) -> () => void — вызывается при включении функции;
|
|
15
|
+
* tool(deps) -> object | null — описание инструмента, если он есть.
|
|
22
16
|
*
|
|
23
17
|
* @module cvc-catalog-sync-plugin
|
|
24
18
|
*/
|
|
19
|
+
import { readFileSync } from 'node:fs'
|
|
20
|
+
|
|
21
|
+
import * as balanceModule from './lib/balance.js'
|
|
22
|
+
import * as catalogSyncModule from './lib/catalog-sync.js'
|
|
23
|
+
import * as coefficientsModule from './lib/coefficients.js'
|
|
24
|
+
import { createCatalogCache } from './lib/cache.js'
|
|
25
|
+
import {
|
|
26
|
+
Config,
|
|
27
|
+
FEATURE_KEYS,
|
|
28
|
+
featuresOf,
|
|
29
|
+
normalizeConfig,
|
|
30
|
+
readPluginConfig,
|
|
31
|
+
sameConfig,
|
|
32
|
+
} from './lib/config.js'
|
|
33
|
+
import * as apiModule from './lib/cvc-api.js'
|
|
34
|
+
import { CvcApiError, fetchModels } from './lib/cvc-api.js'
|
|
35
|
+
import * as httpModule from './lib/http.js'
|
|
36
|
+
import { CVC_PREFIX, createRouter, methodNotAllowed, sendJson } from './lib/http.js'
|
|
37
|
+
import * as providersModule from './lib/providers.js'
|
|
38
|
+
import { apiKeyFor, pickRoute, resolveKey, resolveRoutes } from './lib/providers.js'
|
|
39
|
+
import { createStateStore, installStateRoutes } from './lib/state.js'
|
|
40
|
+
|
|
41
|
+
/** Идентификатор строки композиции; совпадает с id в cordis.patch.yml. */
|
|
42
|
+
export const SELF_ROW_ID = 'cvc-catalog-sync'
|
|
43
|
+
|
|
44
|
+
/** Имя плагина в терминах Cordis. */
|
|
45
|
+
export const name = 'cvc-catalog-sync'
|
|
25
46
|
|
|
26
47
|
/**
|
|
27
|
-
*
|
|
28
|
-
*
|
|
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}
|
|
48
|
+
* Сервисы, без которых плагин не работает: запись профильного патча, реестр
|
|
49
|
+
* инструментов и разрешение ссылки на ключ. Loader отложит запуск, а не упадёт.
|
|
67
50
|
*/
|
|
68
|
-
|
|
69
|
-
return typeof value === 'string' && value.trim().length > 0 ? value.trim() : fallback
|
|
70
|
-
}
|
|
51
|
+
export const inject = ['configEditor', 'tools', 'credentials']
|
|
71
52
|
|
|
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
|
-
}
|
|
53
|
+
export { Config }
|
|
85
54
|
|
|
86
|
-
/**
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
for (const key of keys) {
|
|
94
|
-
const value = positiveInt(item[key])
|
|
95
|
-
if (value !== null) return value
|
|
55
|
+
/** Версия из package.json; при нечитаемом манифесте — запасная строка. */
|
|
56
|
+
export const VERSION = (() => {
|
|
57
|
+
try {
|
|
58
|
+
const manifest = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))
|
|
59
|
+
return typeof manifest.version === 'string' && manifest.version.length > 0 ? manifest.version : '0.0.0'
|
|
60
|
+
} catch {
|
|
61
|
+
return '0.0.0'
|
|
96
62
|
}
|
|
97
|
-
|
|
98
|
-
}
|
|
63
|
+
})()
|
|
99
64
|
|
|
100
|
-
/**
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
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
|
-
}
|
|
65
|
+
/** Модули функций по ключам переключателей. */
|
|
66
|
+
const MODULES = Object.freeze({
|
|
67
|
+
catalogSync: catalogSyncModule,
|
|
68
|
+
coefficients: coefficientsModule,
|
|
69
|
+
balance: balanceModule,
|
|
70
|
+
})
|
|
113
71
|
|
|
114
72
|
/** Текст ошибки без предположения о её типе. */
|
|
115
73
|
function messageOf(error) {
|
|
116
74
|
return error instanceof Error ? error.message : String(error)
|
|
117
75
|
}
|
|
118
76
|
|
|
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
77
|
/**
|
|
781
78
|
* Подключить плагин.
|
|
782
79
|
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
783
|
-
* @param {unknown} [config]
|
|
80
|
+
* @param {unknown} [config] — конфиг строки патча (объект со ссылками).
|
|
784
81
|
*/
|
|
785
82
|
export function apply(ctx, config = {}) {
|
|
786
|
-
|
|
83
|
+
/** Действующий нормализованный конфиг; обновляется в applyConfig. */
|
|
84
|
+
let current = readPluginConfig(config)
|
|
787
85
|
|
|
788
|
-
/** Последний прогон
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
86
|
+
/** Последний прогон и статус для `/cvc/state`. */
|
|
87
|
+
const store = createStateStore()
|
|
88
|
+
|
|
89
|
+
/** Один prefix-маршрут на весь плагин: выключенная функция даёт 404. */
|
|
90
|
+
const router = createRouter({
|
|
91
|
+
prefix: CVC_PREFIX,
|
|
92
|
+
log: (message) => log('warn', message),
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
/** @type {Map<string, () => void>} */
|
|
96
|
+
const mounted = new Map()
|
|
794
97
|
|
|
795
98
|
/**
|
|
796
99
|
* Записать строку в лог хоста, не падая на профиле без логгера.
|
|
@@ -798,597 +101,225 @@ export function apply(ctx, config = {}) {
|
|
|
798
101
|
* @param {string} message
|
|
799
102
|
*/
|
|
800
103
|
function log(level, message) {
|
|
104
|
+
const line = `cvc-catalog-sync: ${message}`
|
|
801
105
|
const logger = ctx.logger
|
|
802
|
-
if (logger !==
|
|
803
|
-
logger[level](
|
|
106
|
+
if (logger !== null && logger !== undefined && typeof logger[level] === 'function') {
|
|
107
|
+
logger[level](line)
|
|
108
|
+
return
|
|
804
109
|
}
|
|
110
|
+
if (level === 'error') console.error(line)
|
|
805
111
|
}
|
|
806
112
|
|
|
807
113
|
/**
|
|
808
|
-
*
|
|
114
|
+
* Загрузить общий снимок каталога: выбранный маршрут, ключ, `GET /models`.
|
|
809
115
|
*
|
|
810
|
-
*
|
|
811
|
-
*
|
|
812
|
-
* @
|
|
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>> }}
|
|
116
|
+
* Используется кэшем, который делят каталог и коэффициенты; баланс ходит
|
|
117
|
+
* своим запросом за `token_balance`.
|
|
118
|
+
* @returns {Promise<{ models: Array<Record<string, unknown>>, providers: Array<{ provider: string, displayName: string }>, fetchedAt: string }>}
|
|
829
119
|
*/
|
|
830
|
-
function
|
|
831
|
-
const
|
|
832
|
-
const
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
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',
|
|
120
|
+
async function loadCatalog() {
|
|
121
|
+
const snapshot = current
|
|
122
|
+
const routes = resolveRoutes(ctx, snapshot)
|
|
123
|
+
const route = pickRoute(routes, snapshot.catalog.provider)
|
|
124
|
+
if (route === undefined) {
|
|
125
|
+
throw new CvcApiError(
|
|
126
|
+
'no-route',
|
|
127
|
+
`provider route "${snapshot.catalog.provider}" is not configured in "${snapshot.providers.entryId}"`,
|
|
844
128
|
)
|
|
845
129
|
}
|
|
846
|
-
const
|
|
847
|
-
|
|
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)})`)
|
|
130
|
+
const key = await resolveKey(ctx, apiKeyFor(route, snapshot))
|
|
131
|
+
const models = await fetchModels({ baseURL: route.baseURL, key, timeoutMs: snapshot.providers.timeoutMs })
|
|
132
|
+
return {
|
|
133
|
+
models,
|
|
134
|
+
providers: routes.map((item) => ({ provider: item.provider, displayName: item.displayName })),
|
|
135
|
+
fetchedAt: new Date().toISOString(),
|
|
868
136
|
}
|
|
869
|
-
const items = parseCatalogPayload(body)
|
|
870
|
-
if (items.length === 0) throw new Error(`${url}: response contains no models`)
|
|
871
|
-
return items
|
|
872
137
|
}
|
|
873
138
|
|
|
874
|
-
/**
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
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
|
-
}
|
|
139
|
+
/** Общий кэш каталога; TTL следует за `coefficients.refreshMinutes`. */
|
|
140
|
+
const cache = createCatalogCache({
|
|
141
|
+
client: loadCatalog,
|
|
142
|
+
ttlMs: () => Math.max(1, current.coefficients.refreshMinutes) * 60000,
|
|
143
|
+
})
|
|
911
144
|
|
|
912
145
|
/**
|
|
913
|
-
*
|
|
146
|
+
* Общие зависимости функций.
|
|
914
147
|
*
|
|
915
|
-
*
|
|
916
|
-
*
|
|
917
|
-
*
|
|
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 }>}
|
|
148
|
+
* Модуль получает живой доступ к конфигу (`config()`), общий кэш каталога,
|
|
149
|
+
* реестр состояния и helpers HTTP — но не сам `webServer`: маршруты
|
|
150
|
+
* регистрируются в общей таблице через `route()`.
|
|
151
|
+
* @returns {object}
|
|
924
152
|
*/
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
153
|
+
function createFeatureDeps() {
|
|
154
|
+
return Object.freeze({
|
|
155
|
+
ctx,
|
|
156
|
+
version: VERSION,
|
|
157
|
+
/** Актуальный нормализованный конфиг. */
|
|
158
|
+
config: () => current,
|
|
159
|
+
/** Только переключатели. */
|
|
160
|
+
features: () => featuresOf(current),
|
|
161
|
+
log,
|
|
162
|
+
/** Зарегистрировать подмаршрут `/cvc/<path>`; вернуть disposer. */
|
|
163
|
+
route: (path, handler) => router.register(path, handler),
|
|
164
|
+
http: httpModule,
|
|
165
|
+
api: apiModule,
|
|
166
|
+
providers: providersModule,
|
|
167
|
+
cache,
|
|
168
|
+
store,
|
|
169
|
+
/** Маршруты CheapVibeCode по текущему конфигу. */
|
|
170
|
+
routes: () => resolveRoutes(ctx, current),
|
|
171
|
+
/** Ключ по ссылке (пустая строка, если не настроен). */
|
|
172
|
+
key: (ref) => resolveKey(ctx, ref),
|
|
173
|
+
/** Имя записи ключа для маршрута с учётом общего запасного имени. */
|
|
174
|
+
apiKeyFor: (route) => apiKeyFor(route, current),
|
|
944
175
|
})
|
|
945
|
-
return outcome
|
|
946
176
|
}
|
|
947
177
|
|
|
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
|
-
}
|
|
178
|
+
const featureDeps = createFeatureDeps()
|
|
958
179
|
|
|
959
180
|
/**
|
|
960
|
-
*
|
|
961
|
-
* @param {
|
|
962
|
-
* @param {Array<Record<string, unknown>>} models
|
|
963
|
-
* @returns {Record<string, unknown>}
|
|
181
|
+
* Включить функцию: вызвать `register` и зарегистрировать её инструмент.
|
|
182
|
+
* @param {string} feature
|
|
964
183
|
*/
|
|
965
|
-
function
|
|
966
|
-
|
|
967
|
-
const
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
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,
|
|
184
|
+
function mountFeature(feature) {
|
|
185
|
+
if (mounted.has(feature)) return
|
|
186
|
+
const module = MODULES[feature]
|
|
187
|
+
if (module === undefined || typeof module.register !== 'function') {
|
|
188
|
+
log('warn', `feature "${feature}" has no module`)
|
|
189
|
+
return
|
|
1027
190
|
}
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
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
|
-
}
|
|
191
|
+
const disposers = []
|
|
192
|
+
const disposeModule = module.register(ctx, featureDeps)
|
|
193
|
+
if (typeof disposeModule === 'function') disposers.push(disposeModule)
|
|
194
|
+
|
|
195
|
+
if (typeof module.tool === 'function') {
|
|
196
|
+
const spec = module.tool(featureDeps)
|
|
197
|
+
if (spec !== null && spec !== undefined) {
|
|
198
|
+
const tools = ctx.get?.('tools') ?? ctx.tools
|
|
199
|
+
if (tools !== null && tools !== undefined && typeof tools.register === 'function') {
|
|
200
|
+
disposers.push(tools.register(spec))
|
|
201
|
+
} else {
|
|
202
|
+
log('warn', `feature "${feature}": tools service is unavailable, "${spec.name ?? 'tool'}" is not registered`)
|
|
1096
203
|
}
|
|
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
204
|
}
|
|
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
205
|
}
|
|
1136
|
-
return result
|
|
1137
|
-
}
|
|
1138
206
|
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
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
|
|
207
|
+
mounted.set(feature, () => {
|
|
208
|
+
for (const dispose of disposers.reverse()) {
|
|
209
|
+
if (typeof dispose === 'function') dispose()
|
|
210
|
+
}
|
|
1156
211
|
})
|
|
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
212
|
}
|
|
1165
213
|
|
|
1166
|
-
const hmrService = typeof ctx.get === 'function' ? ctx.get('hmr') : undefined
|
|
1167
|
-
const hmrPresent = hmrService !== undefined && hmrService !== null
|
|
1168
214
|
/**
|
|
1169
|
-
*
|
|
1170
|
-
*
|
|
1171
|
-
* `executing` — приватное поле Hmr, но именно им сам DSH выводит наблюдение
|
|
1172
|
-
* за файлами из транзакции.
|
|
1173
|
-
* @type {{ exit?: (factory: () => unknown) => unknown, getStore?: () => unknown } | null}
|
|
215
|
+
* Выключить функцию: снять маршруты, таймеры и инструмент.
|
|
216
|
+
* @param {string} feature
|
|
1174
217
|
*/
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
218
|
+
function unmountFeature(feature) {
|
|
219
|
+
const dispose = mounted.get(feature)
|
|
220
|
+
if (dispose === undefined) return
|
|
221
|
+
mounted.delete(feature)
|
|
222
|
+
try {
|
|
223
|
+
dispose()
|
|
224
|
+
} catch (error) {
|
|
225
|
+
log('warn', `feature "${feature}" teardown failed: ${messageOf(error)}`)
|
|
1180
226
|
}
|
|
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
227
|
}
|
|
1207
228
|
|
|
1208
229
|
/**
|
|
1209
|
-
*
|
|
230
|
+
* Применить новый конфиг без перезапуска плагина.
|
|
1210
231
|
*
|
|
1211
|
-
*
|
|
1212
|
-
*
|
|
1213
|
-
*
|
|
1214
|
-
*
|
|
1215
|
-
*
|
|
1216
|
-
* @
|
|
232
|
+
* Перемонтируются только функции: их таймеры и маршруты должны увидеть новые
|
|
233
|
+
* значения, а `apply()` повторно не вызывается — ссылки уже обновлены.
|
|
234
|
+
* Если обычные (не переключательные) настройки поменялись у уже включённой
|
|
235
|
+
* функции, она перемонтируется тоже: иначе, например, новый интервал
|
|
236
|
+
* автосинхронизации подхватился бы только после перезапуска DSH.
|
|
237
|
+
* @param {ReturnType<typeof normalizeConfig>} next
|
|
1217
238
|
*/
|
|
1218
|
-
function
|
|
1219
|
-
if (
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
239
|
+
function applyConfig(next) {
|
|
240
|
+
if (sameConfig(next, current)) return
|
|
241
|
+
const previous = current
|
|
242
|
+
current = next
|
|
243
|
+
// Смена самих переключателей снимает все функции — это одна операция; для
|
|
244
|
+
// обычных настроек перемонтируется только затронутая функция.
|
|
245
|
+
const remount = new Set()
|
|
246
|
+
const featuresChanged = !sameConfig(previous.features, next.features)
|
|
247
|
+
if (featuresChanged) {
|
|
248
|
+
for (const feature of FEATURE_KEYS) remount.add(feature)
|
|
249
|
+
} else {
|
|
250
|
+
const providersChanged = !sameConfig(previous.providers, next.providers)
|
|
251
|
+
if (providersChanged
|
|
252
|
+
|| (previous.features.catalogSync === true && !sameConfig(previous.catalog, next.catalog))) remount.add('catalogSync')
|
|
253
|
+
if (providersChanged
|
|
254
|
+
|| (previous.features.coefficients === true && !sameConfig(previous.coefficients, next.coefficients))) remount.add('coefficients')
|
|
255
|
+
if (providersChanged
|
|
256
|
+
|| (previous.features.balance === true && !sameConfig(previous.balance, next.balance))) remount.add('balance')
|
|
1231
257
|
}
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
258
|
+
for (const feature of remount) unmountFeature(feature)
|
|
259
|
+
for (const feature of FEATURE_KEYS) {
|
|
260
|
+
if (current.features[feature] === true) mountFeature(feature)
|
|
261
|
+
}
|
|
262
|
+
if (!sameConfig(previous.providers, current.providers) || !sameConfig(previous.catalog, current.catalog)) {
|
|
263
|
+
cache.clear()
|
|
264
|
+
}
|
|
265
|
+
log('info', 'configuration updated without restart')
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Базовые маршруты: состояние и переключатели есть всегда, даже когда все
|
|
269
|
+
// три функции выключены — страница настроек и есть переключатель.
|
|
270
|
+
ctx.effect(() => {
|
|
271
|
+
const disposers = [
|
|
272
|
+
installStateRoutes(router, {
|
|
273
|
+
ctx,
|
|
274
|
+
rowId: SELF_ROW_ID,
|
|
275
|
+
version: VERSION,
|
|
276
|
+
readConfig: () => current,
|
|
277
|
+
store,
|
|
278
|
+
onAfterWrite: (next) => applyConfig(next),
|
|
279
|
+
}),
|
|
280
|
+
router.register('health', (req, res) => {
|
|
281
|
+
if (String(req.method ?? 'GET').toUpperCase() !== 'GET') {
|
|
282
|
+
methodNotAllowed(res, ['GET'])
|
|
283
|
+
return
|
|
284
|
+
}
|
|
285
|
+
sendJson(res, 200, { ok: true, version: VERSION })
|
|
286
|
+
}),
|
|
287
|
+
]
|
|
288
|
+
return () => {
|
|
289
|
+
for (const dispose of disposers) {
|
|
290
|
+
if (typeof dispose === 'function') dispose()
|
|
1252
291
|
}
|
|
1253
|
-
ctx.effect(() => {
|
|
1254
|
-
const timer = scheduleOutsideHmr(() => setInterval(() => backgroundRun('timer'), periodMs))
|
|
1255
|
-
timer.unref?.()
|
|
1256
|
-
return () => clearInterval(timer)
|
|
1257
|
-
}, 'cvc-catalog-sync: interval')
|
|
1258
292
|
}
|
|
1259
|
-
}
|
|
293
|
+
}, 'cvc-catalog-sync: state routes')
|
|
1260
294
|
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
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
|
-
}
|
|
295
|
+
// Первичное монтирование по текущему конфигу.
|
|
296
|
+
for (const feature of FEATURE_KEYS) {
|
|
297
|
+
if (current.features[feature] === true) mountFeature(feature)
|
|
1285
298
|
}
|
|
1286
299
|
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
}
|
|
1294
|
-
}
|
|
300
|
+
// Правка volatile-полей строки патча: перемонтировать функции по новым
|
|
301
|
+
// значениям. `sameConfig` не даст сделать работу дважды (например, после
|
|
302
|
+
// PUT /cvc/config, который уже применил конфиг сам).
|
|
303
|
+
ctx.effect(() => ctx.on('loader/volatile-update', () => {
|
|
304
|
+
applyConfig(readPluginConfig(config))
|
|
305
|
+
}), 'cvc-catalog-sync: volatile config')
|
|
1295
306
|
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
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')
|
|
307
|
+
// Выключение плагина снимает всё, что зарегистрировали функции.
|
|
308
|
+
ctx.effect(() => () => {
|
|
309
|
+
for (const feature of FEATURE_KEYS) unmountFeature(feature)
|
|
310
|
+
}, 'cvc-catalog-sync: feature teardown')
|
|
1352
311
|
|
|
1353
|
-
|
|
1354
|
-
* Страница настроек: маршрут есть только там, где есть веб-сервер.
|
|
1355
|
-
* В headless-профилях плагин продолжает работать через инструмент.
|
|
1356
|
-
*/
|
|
312
|
+
// Веб-сервер есть не в каждом профиле: без него плагин живёт инструментами.
|
|
1357
313
|
ctx.inject(['webServer'], (web) => {
|
|
1358
|
-
web.effect(() =>
|
|
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')
|
|
314
|
+
web.effect(() => router.attach(web.webServer), 'cvc-catalog-sync: browser API')
|
|
1374
315
|
})
|
|
1375
|
-
}
|
|
1376
316
|
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
installSettingsApi,
|
|
1387
|
-
normalizeConfig,
|
|
1388
|
-
parseCatalogPayload,
|
|
1389
|
-
parseReasoningLevels,
|
|
1390
|
-
reasoningEffortsFor,
|
|
1391
|
-
settingsState,
|
|
1392
|
-
stableStringify,
|
|
1393
|
-
validateConfigInput,
|
|
1394
|
-
}
|
|
317
|
+
// Своя страница настроек: форма строится клиентом, автогенерация не нужна.
|
|
318
|
+
// Регистрация внутри inject — плагин обязан грузиться и без Settings.
|
|
319
|
+
ctx.inject(['settings'], (scoped) => {
|
|
320
|
+
scoped.effect(
|
|
321
|
+
() => scoped.settings.configure({ auto: false }, scoped.fiber),
|
|
322
|
+
'cvc-catalog-sync: settings policy',
|
|
323
|
+
)
|
|
324
|
+
})
|
|
325
|
+
}
|