cvc-catalog-sync-plugin 1.0.0 → 2.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/CHANGELOG.md +182 -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/lib/providers.js
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Маршруты провайдеров CheapVibeCode в профильном патче.
|
|
3
|
+
*
|
|
4
|
+
* Провайдер узнаётся по `baseURL` из строки `llm-pi-ai`, а не по имени:
|
|
5
|
+
* пользователь вправе назвать маршрут как угодно. Хосты сравниваются с
|
|
6
|
+
* hostname URL, а не подстрокой: `cheapvibecode.ru.evil.com` и
|
|
7
|
+
* `notcheapvibecode.ru` не должны получать ключ и запросы.
|
|
8
|
+
*
|
|
9
|
+
* @module cvc-catalog-sync-plugin/lib/providers
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** Пакет, чья строка патча держит маршруты провайдеров. */
|
|
13
|
+
export const LLM_ENTRY_NAME = '@deepseek-ai/dsh-llm-pi-ai'
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Имя хоста `https`-адреса в нижнем регистре.
|
|
17
|
+
*
|
|
18
|
+
* Только `https`: по этому адресу уходит ключ, и `http` не должен совпадать с
|
|
19
|
+
* шаблоном даже при опечатке в конфигурации.
|
|
20
|
+
* @param {unknown} baseURL
|
|
21
|
+
* @returns {string} имя хоста или пустая строка.
|
|
22
|
+
*/
|
|
23
|
+
export function hostOf(baseURL) {
|
|
24
|
+
if (typeof baseURL !== 'string' || baseURL.trim().length === 0) return ''
|
|
25
|
+
try {
|
|
26
|
+
const url = new URL(baseURL.trim())
|
|
27
|
+
if (url.protocol !== 'https:') return ''
|
|
28
|
+
return url.hostname.toLowerCase()
|
|
29
|
+
} catch {
|
|
30
|
+
return ''
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Совпадает ли hostname с шаблоном хоста.
|
|
36
|
+
*
|
|
37
|
+
* Шаблон `cheapvibecode.ru` покрывает сам хост и его поддомены
|
|
38
|
+
* (`ru.cheapvibecode.ru`), но не строки, где он лишь часть другого хоста.
|
|
39
|
+
* @param {string} host — hostname в нижнем регистре.
|
|
40
|
+
* @param {string} pattern — шаблон хоста из `providers.match`.
|
|
41
|
+
* @returns {boolean}
|
|
42
|
+
*/
|
|
43
|
+
export function hostMatches(host, pattern) {
|
|
44
|
+
if (typeof host !== 'string' || host.length === 0) return false
|
|
45
|
+
if (typeof pattern !== 'string') return false
|
|
46
|
+
const actual = host.trim().toLowerCase()
|
|
47
|
+
const wanted = pattern.trim().toLowerCase().replace(/^\.+/, '')
|
|
48
|
+
if (actual.length === 0 || wanted.length === 0) return false
|
|
49
|
+
return actual === wanted || actual.endsWith(`.${wanted}`)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Принадлежит ли `baseURL` одному из разрешённых хостов.
|
|
54
|
+
* @param {unknown} baseURL
|
|
55
|
+
* @param {readonly string[]} patterns
|
|
56
|
+
* @returns {boolean}
|
|
57
|
+
*/
|
|
58
|
+
export function matchesProvider(baseURL, patterns) {
|
|
59
|
+
if (!Array.isArray(patterns) || patterns.length === 0) return false
|
|
60
|
+
const host = hostOf(baseURL)
|
|
61
|
+
return host.length > 0 && patterns.some((pattern) => hostMatches(host, pattern))
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Совпадает ли id строки с ожидаемым, в том числе с group-префиксом.
|
|
66
|
+
*
|
|
67
|
+
* Строка внутри include-группы получает id вида `include:llm-pi-ai`, поэтому
|
|
68
|
+
* точное сравнение недостаточно.
|
|
69
|
+
* @param {unknown} candidate
|
|
70
|
+
* @param {string} wanted
|
|
71
|
+
* @returns {boolean}
|
|
72
|
+
*/
|
|
73
|
+
export function rowIdMatches(candidate, wanted) {
|
|
74
|
+
return candidate === wanted || (typeof candidate === 'string' && candidate.endsWith(`:${wanted}`))
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Объект провайдеров из строки патча.
|
|
79
|
+
* @param {{ options?: { config?: unknown } } | undefined} entry
|
|
80
|
+
* @returns {Record<string, any>}
|
|
81
|
+
*/
|
|
82
|
+
function providersOf(entry) {
|
|
83
|
+
const config = entry?.options?.config
|
|
84
|
+
if (config === null || typeof config !== 'object') return {}
|
|
85
|
+
const providers = /** @type {{ providers?: unknown }} */ (config).providers
|
|
86
|
+
return providers !== null && typeof providers === 'object' && !Array.isArray(providers)
|
|
87
|
+
? /** @type {Record<string, any>} */ (providers)
|
|
88
|
+
: {}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Найти строку, которая объявляет маршруты провайдеров.
|
|
93
|
+
*
|
|
94
|
+
* Три попытки, как в прежних плагинах: id строки, имя пакета адаптера и id с
|
|
95
|
+
* group-префиксом. Кандидат принимается, только когда реально несёт
|
|
96
|
+
* `providers`: строка-дубль с `config: {}` не должна заканчивать поиск.
|
|
97
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
98
|
+
* @param {string} entryId
|
|
99
|
+
* @returns {{ entry?: any, notes: string[] }}
|
|
100
|
+
*/
|
|
101
|
+
export function findProviderEntry(ctx, entryId) {
|
|
102
|
+
const notes = []
|
|
103
|
+
const editor = ctx.get?.('configEditor') ?? ctx.configEditor
|
|
104
|
+
if (editor === null || typeof editor !== 'object' || typeof editor.entries !== 'function') {
|
|
105
|
+
return { notes: ['configEditor service is unavailable: provider routes cannot be discovered'] }
|
|
106
|
+
}
|
|
107
|
+
let entries
|
|
108
|
+
try {
|
|
109
|
+
entries = editor.entries() ?? []
|
|
110
|
+
} catch (error) {
|
|
111
|
+
return { notes: [`configEditor entries are unreadable: ${messageOf(error)}`] }
|
|
112
|
+
}
|
|
113
|
+
const wanted = typeof entryId === 'string' && entryId.trim().length > 0 ? entryId.trim() : 'llm-pi-ai'
|
|
114
|
+
// Все кандидаты, а не первый попавшийся: строка-дубль с `config: {}` может
|
|
115
|
+
// стоять в патче раньше настоящей, и `find` по id закончил бы поиск на ней.
|
|
116
|
+
const candidates = [
|
|
117
|
+
...entries.filter((entry) => entry?.options?.id === wanted),
|
|
118
|
+
...entries.filter((entry) => entry?.options?.name === LLM_ENTRY_NAME),
|
|
119
|
+
...entries.filter((entry) => rowIdMatches(entry?.options?.id, wanted)),
|
|
120
|
+
]
|
|
121
|
+
for (const candidate of candidates) {
|
|
122
|
+
if (Object.keys(providersOf(candidate)).length > 0) return { entry: candidate, notes }
|
|
123
|
+
}
|
|
124
|
+
notes.push(`profile entry "${wanted}" has no provider routes`)
|
|
125
|
+
return { notes }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Сообщение ошибки без предположения о её типе.
|
|
130
|
+
* @param {unknown} error
|
|
131
|
+
* @returns {string}
|
|
132
|
+
*/
|
|
133
|
+
function messageOf(error) {
|
|
134
|
+
return error instanceof Error ? error.message : String(error)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Все маршруты CheapVibeCode из строки патча.
|
|
139
|
+
*
|
|
140
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
141
|
+
* @param {{ providers: { match: string[], entryId: string } }} config — нормализованный конфиг.
|
|
142
|
+
* @returns {Array<{provider: string, displayName: string, baseURL: string, apiKeyEnv: string, api: string, models: unknown[], entryId: string}>}
|
|
143
|
+
*/
|
|
144
|
+
export function resolveRoutes(ctx, config) {
|
|
145
|
+
const wanted = config?.providers?.entryId ?? 'llm-pi-ai'
|
|
146
|
+
const patterns = Array.isArray(config?.providers?.match) ? config.providers.match : []
|
|
147
|
+
const { entry } = findProviderEntry(ctx, wanted)
|
|
148
|
+
if (entry === undefined) return []
|
|
149
|
+
const providers = providersOf(entry)
|
|
150
|
+
const routes = []
|
|
151
|
+
for (const [provider, raw] of Object.entries(providers)) {
|
|
152
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) continue
|
|
153
|
+
const profile = /** @type {Record<string, any>} */ (raw)
|
|
154
|
+
if (!matchesProvider(profile.baseURL, patterns)) continue
|
|
155
|
+
routes.push({
|
|
156
|
+
provider,
|
|
157
|
+
displayName: typeof profile.displayName === 'string' && profile.displayName.trim().length > 0
|
|
158
|
+
? profile.displayName.trim()
|
|
159
|
+
: provider,
|
|
160
|
+
baseURL: String(profile.baseURL).trim(),
|
|
161
|
+
apiKeyEnv: typeof profile.apiKeyEnv === 'string' ? profile.apiKeyEnv.trim() : '',
|
|
162
|
+
api: typeof profile.api === 'string' ? profile.api : '',
|
|
163
|
+
models: Array.isArray(profile.models) ? profile.models : [],
|
|
164
|
+
entryId: typeof entry.options?.id === 'string' ? entry.options.id : wanted,
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
return routes
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Имя переменной/записи ключа для маршрута: своё имя важнее общего.
|
|
172
|
+
* @param {{ apiKeyEnv?: string } | undefined} route
|
|
173
|
+
* @param {{ providers: { apiKeyEnv: string } }} config
|
|
174
|
+
* @returns {string}
|
|
175
|
+
*/
|
|
176
|
+
export function apiKeyFor(route, config) {
|
|
177
|
+
const own = typeof route?.apiKeyEnv === 'string' ? route.apiKeyEnv.trim() : ''
|
|
178
|
+
return own.length > 0 ? own : config.providers.apiKeyEnv
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Разрешить ссылку на ключ через сервис credentials.
|
|
183
|
+
*
|
|
184
|
+
* Значение остаётся на хосте: наружу уходит только факт «ключ есть/нет».
|
|
185
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
186
|
+
* @param {string} ref
|
|
187
|
+
* @returns {Promise<string>} ключ или пустая строка, если он не настроен.
|
|
188
|
+
*/
|
|
189
|
+
export async function resolveKey(ctx, ref) {
|
|
190
|
+
if (typeof ref !== 'string' || ref.trim().length === 0) return ''
|
|
191
|
+
const credentials = ctx.get?.('credentials') ?? ctx.credentials
|
|
192
|
+
if (credentials === null || typeof credentials !== 'object' || typeof credentials.resolve !== 'function') return ''
|
|
193
|
+
try {
|
|
194
|
+
const hit = await credentials.resolve(ref.trim())
|
|
195
|
+
return typeof hit?.value === 'string' ? hit.value : ''
|
|
196
|
+
} catch {
|
|
197
|
+
return ''
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Маршрут по ключу провайдера; если ключа нет — первый найденный.
|
|
203
|
+
* @param {Array<{ provider: string }>} routes
|
|
204
|
+
* @param {string} provider
|
|
205
|
+
* @returns {{ provider: string } | undefined}
|
|
206
|
+
*/
|
|
207
|
+
export function pickRoute(routes, provider) {
|
|
208
|
+
const wanted = typeof provider === 'string' ? provider.trim() : ''
|
|
209
|
+
return routes.find((route) => route.provider === wanted) ?? routes[0]
|
|
210
|
+
}
|
package/lib/state.js
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Состояние плагина и запись конфигурации через `configEditor`.
|
|
3
|
+
*
|
|
4
|
+
* `GET /cvc/state` — единственная точка, из которой страница настроек узнаёт
|
|
5
|
+
* действующий конфиг, форму записанного патча, состояние последнего прогона и
|
|
6
|
+
* путь к файлу. `PUT /cvc/config` пишет через `configEditor.edit()`: он
|
|
7
|
+
* сохраняет комментарии и чужие строки, валидирует значение и сериализует
|
|
8
|
+
* запись с другими правками профиля. Сброс к умолчаниям удаляет
|
|
9
|
+
* переопределение, а не записывает копию умолчаний.
|
|
10
|
+
*
|
|
11
|
+
* @module cvc-catalog-sync-plugin/lib/state
|
|
12
|
+
*/
|
|
13
|
+
import { configShapeOf, normalizeConfig, sameConfig, validateConfigInput } from './config.js'
|
|
14
|
+
import { HttpError, methodNotAllowed, readJsonBody, sendJson } from './http.js'
|
|
15
|
+
import { rowIdMatches } from './providers.js'
|
|
16
|
+
|
|
17
|
+
/** Префикс маршрутов состояния. */
|
|
18
|
+
export const STATE_PATH = 'state'
|
|
19
|
+
|
|
20
|
+
/** Префикс записи конфига. */
|
|
21
|
+
export const CONFIG_PATH = 'config'
|
|
22
|
+
|
|
23
|
+
/** Обычный объект, не массив и не null. */
|
|
24
|
+
function isPlainObject(value) {
|
|
25
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Совпадает ли id строки с ожидаемым, включая group-префикс.
|
|
30
|
+
* @param {unknown} candidate
|
|
31
|
+
* @param {string} rowId
|
|
32
|
+
* @returns {boolean}
|
|
33
|
+
*/
|
|
34
|
+
export function rowMatches(candidate, rowId) {
|
|
35
|
+
return rowIdMatches(candidate, rowId)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Слои конфигурации строки плагина: то, что записано в патче, и то, что лежит
|
|
40
|
+
* под ним (бандл и умолчания схемы).
|
|
41
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
42
|
+
* @param {string} rowId
|
|
43
|
+
* @returns {{ entry: any, inherited: Record<string, any>, override: Record<string, any>, active: boolean, documentPath: string }}
|
|
44
|
+
*/
|
|
45
|
+
export function readLayers(ctx, rowId) {
|
|
46
|
+
const editor = ctx.get?.('configEditor') ?? ctx.configEditor
|
|
47
|
+
const empty = { entry: undefined, inherited: {}, override: {}, active: false, documentPath: '' }
|
|
48
|
+
if (editor === null || typeof editor !== 'object') return empty
|
|
49
|
+
let configuration = []
|
|
50
|
+
if (typeof editor.configuration === 'function') {
|
|
51
|
+
try {
|
|
52
|
+
configuration = editor.configuration() ?? []
|
|
53
|
+
} catch {
|
|
54
|
+
return empty
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const row = configuration.find((candidate) => rowMatches(candidate?.entry?.options?.id, rowId))
|
|
58
|
+
if (row === undefined) return { ...empty, documentPath: String(editor.documentPath ?? '') }
|
|
59
|
+
return {
|
|
60
|
+
entry: row.entry,
|
|
61
|
+
inherited: isPlainObject(row.inherited) ? row.inherited : {},
|
|
62
|
+
override: isPlainObject(row.override) ? row.override : {},
|
|
63
|
+
active: true,
|
|
64
|
+
documentPath: String(editor.documentPath ?? ''),
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Найти активную строку плагина для записи.
|
|
70
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
71
|
+
* @param {string} rowId
|
|
72
|
+
* @returns {any}
|
|
73
|
+
*/
|
|
74
|
+
export function findEditableEntry(ctx, rowId) {
|
|
75
|
+
const editor = ctx.get?.('configEditor') ?? ctx.configEditor
|
|
76
|
+
if (editor === null || typeof editor !== 'object' || typeof editor.entries !== 'function') return undefined
|
|
77
|
+
let entries = []
|
|
78
|
+
try {
|
|
79
|
+
entries = editor.entries() ?? []
|
|
80
|
+
} catch {
|
|
81
|
+
return undefined
|
|
82
|
+
}
|
|
83
|
+
return entries.find((entry) => rowMatches(entry?.options?.id, rowId))
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Маленький реестр последнего прогона и статуса для `/cvc/state`.
|
|
88
|
+
* @param {{ now?: () => string }} [options]
|
|
89
|
+
*/
|
|
90
|
+
export function createStateStore(options = {}) {
|
|
91
|
+
const now = typeof options.now === 'function' ? options.now : () => new Date().toISOString()
|
|
92
|
+
/** @type {unknown} */
|
|
93
|
+
let lastRun = null
|
|
94
|
+
let running = false
|
|
95
|
+
let error = ''
|
|
96
|
+
return {
|
|
97
|
+
get lastRun() {
|
|
98
|
+
return lastRun
|
|
99
|
+
},
|
|
100
|
+
/** Запомнить итог прогона каталога. */
|
|
101
|
+
setLastRun(value) {
|
|
102
|
+
lastRun = value
|
|
103
|
+
error = ''
|
|
104
|
+
},
|
|
105
|
+
/** Отметить, что прогон идёт. */
|
|
106
|
+
setRunning(value) {
|
|
107
|
+
running = value === true
|
|
108
|
+
},
|
|
109
|
+
/** Запомнить последнюю ошибку хоста. */
|
|
110
|
+
setError(message) {
|
|
111
|
+
error = typeof message === 'string' ? message : ''
|
|
112
|
+
running = false
|
|
113
|
+
},
|
|
114
|
+
/** Сводка для ответа маршрута. */
|
|
115
|
+
snapshot() {
|
|
116
|
+
return { ok: error.length === 0, at: now(), running, error }
|
|
117
|
+
},
|
|
118
|
+
/** Сбросить всё (для тестов и повторной инициализации). */
|
|
119
|
+
reset() {
|
|
120
|
+
lastRun = null
|
|
121
|
+
running = false
|
|
122
|
+
error = ''
|
|
123
|
+
},
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Собрать ответ `GET /cvc/state`.
|
|
129
|
+
* @param {{ version: string, rowId: string, config: ReturnType<typeof normalizeConfig>, store: ReturnType<typeof createStateStore>, layers: ReturnType<typeof readLayers> }} input
|
|
130
|
+
* @returns {Record<string, unknown>}
|
|
131
|
+
*/
|
|
132
|
+
export function buildState(input) {
|
|
133
|
+
const { version, rowId, config, store, layers } = input
|
|
134
|
+
const effectiveRaw = { ...layers.inherited, ...layers.override }
|
|
135
|
+
return {
|
|
136
|
+
version,
|
|
137
|
+
features: config.features,
|
|
138
|
+
config,
|
|
139
|
+
configShape: configShapeOf(effectiveRaw),
|
|
140
|
+
status: store.snapshot(),
|
|
141
|
+
lastRun: store.lastRun,
|
|
142
|
+
patchPath: layers.documentPath,
|
|
143
|
+
rowId,
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Записать конфиг в строку плагина.
|
|
149
|
+
*
|
|
150
|
+
* Если нормализованное значение равно умолчаниям — вернуть слой ниже
|
|
151
|
+
* (`inherited`): `configEditor.edit` в этом случае удаляет переопределение.
|
|
152
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
153
|
+
* @param {string} rowId
|
|
154
|
+
* @param {ReturnType<typeof normalizeConfig>} next
|
|
155
|
+
* @returns {Promise<void>}
|
|
156
|
+
*/
|
|
157
|
+
export async function writeConfig(ctx, rowId, next) {
|
|
158
|
+
const editor = ctx.get?.('configEditor') ?? ctx.configEditor
|
|
159
|
+
if (editor === null || typeof editor !== 'object' || typeof editor.edit !== 'function') {
|
|
160
|
+
throw new HttpError(409, 'configuration cannot be saved in this profile: configEditor is unavailable')
|
|
161
|
+
}
|
|
162
|
+
const entry = findEditableEntry(ctx, rowId)
|
|
163
|
+
if (entry === undefined) {
|
|
164
|
+
throw new HttpError(409, `row "${rowId}" is not active; enable the bundle first`)
|
|
165
|
+
}
|
|
166
|
+
const resetToDefaults = sameConfig(next, normalizeConfig({}))
|
|
167
|
+
await editor.edit(entry, (_current, inherited) => (resetToDefaults ? inherited : next))
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Зарегистрировать маршруты состояния.
|
|
172
|
+
*
|
|
173
|
+
* @param {ReturnType<import('./http.js').createRouter>} router
|
|
174
|
+
* @param {{
|
|
175
|
+
* ctx: import('@deepseek-ai/cordis').Context,
|
|
176
|
+
* rowId: string,
|
|
177
|
+
* version: string,
|
|
178
|
+
* readConfig: () => ReturnType<typeof normalizeConfig>,
|
|
179
|
+
* store: ReturnType<typeof createStateStore>,
|
|
180
|
+
* onAfterWrite?: (config: ReturnType<typeof normalizeConfig>) => void,
|
|
181
|
+
* }} deps
|
|
182
|
+
* @returns {() => void}
|
|
183
|
+
*/
|
|
184
|
+
export function installStateRoutes(router, deps) {
|
|
185
|
+
const disposers = []
|
|
186
|
+
|
|
187
|
+
disposers.push(router.register(STATE_PATH, (req, res) => {
|
|
188
|
+
if (String(req.method ?? 'GET').toUpperCase() !== 'GET') {
|
|
189
|
+
methodNotAllowed(res, ['GET'])
|
|
190
|
+
return
|
|
191
|
+
}
|
|
192
|
+
sendJson(res, 200, buildState({
|
|
193
|
+
version: deps.version,
|
|
194
|
+
rowId: deps.rowId,
|
|
195
|
+
config: deps.readConfig(),
|
|
196
|
+
store: deps.store,
|
|
197
|
+
layers: readLayers(deps.ctx, deps.rowId),
|
|
198
|
+
}))
|
|
199
|
+
}))
|
|
200
|
+
|
|
201
|
+
disposers.push(router.register(CONFIG_PATH, async (req, res) => {
|
|
202
|
+
if (String(req.method ?? 'GET').toUpperCase() !== 'PUT') {
|
|
203
|
+
methodNotAllowed(res, ['PUT'])
|
|
204
|
+
return
|
|
205
|
+
}
|
|
206
|
+
let body
|
|
207
|
+
try {
|
|
208
|
+
body = await readJsonBody(req)
|
|
209
|
+
} catch (error) {
|
|
210
|
+
if (error instanceof HttpError) {
|
|
211
|
+
sendJson(res, error.status, { error: error.message })
|
|
212
|
+
return
|
|
213
|
+
}
|
|
214
|
+
throw error
|
|
215
|
+
}
|
|
216
|
+
const raw = isPlainObject(body) && isPlainObject(body.config) ? body.config : body
|
|
217
|
+
const errors = validateConfigInput(raw)
|
|
218
|
+
if (errors.length > 0) {
|
|
219
|
+
sendJson(res, 400, { error: 'invalid config', fields: errors })
|
|
220
|
+
return
|
|
221
|
+
}
|
|
222
|
+
const next = normalizeConfig(raw)
|
|
223
|
+
await writeConfig(deps.ctx, deps.rowId, next)
|
|
224
|
+
deps.onAfterWrite?.(next)
|
|
225
|
+
sendJson(res, 200, { ok: true, config: next, features: next.features })
|
|
226
|
+
}))
|
|
227
|
+
|
|
228
|
+
return () => {
|
|
229
|
+
for (const dispose of disposers.reverse()) {
|
|
230
|
+
if (typeof dispose === 'function') dispose()
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
package/locale/en.json
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
|
-
"title": "CVC catalog
|
|
4
|
-
"description": "
|
|
3
|
+
"title": "CVC catalog, coefficients and balance",
|
|
4
|
+
"description": "Three switchable features for a CheapVibeCode route: keeps the model catalog and reasoning levels in the profile patch in sync with /v1/models, shows the price multiplier beside each model in the picker, and puts the remaining balance in a sidebar panel.\n\nThe settings page lives in Settings -> CVC and on the bundle page in Plugins -> CVC catalog sync. It has one switch per feature, a field group for its parameters, and Check catalog / Apply catalog buttons that show the diff and then write it; the first run needs the route's API key, which the host resolves by name and never sends to the browser. Everything the plugin reads goes to the CheapVibeCode hosts from the route's own baseURL and installer URLs: no telemetry, no other destination. A switched-off feature registers no route, timer, tool or UI element.",
|
|
5
|
+
"detail": "docs/DETAIL.md"
|
|
5
6
|
}
|
|
6
|
-
}
|
|
7
|
+
}
|
package/locale/ru.json
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
|
-
"title": "
|
|
4
|
-
"description": "
|
|
3
|
+
"title": "Каталог, коэффициенты и баланс CVC",
|
|
4
|
+
"description": "Три отключаемые функции для маршрута CheapVibeCode: держит каталог моделей и уровни мышления в профильном патче в соответствии с /v1/models, показывает коэффициент цены рядом с каждой моделью в выборе модели и выводит остаток баланса в панели сайдбара.\n\nСтраница настроек открывается в «Настройки → CVC» и на странице бандла в «Плагины → CVC catalog sync». На ней свой переключатель у каждой функции, группа полей для её параметров и кнопки «Проверить каталог» / «Применить каталог»: первая показывает разницу, вторая её записывает. Первому запуску нужен ключ маршрута — хост разрешает его по имени и в браузер не отдаёт. Всё, что плагин читает, уходит на хосты CheapVibeCode из baseURL маршрута и адресов установщиков: телеметрии и других получателей нет. Выключенная функция не регистрирует ни маршрута, ни таймера, ни инструмента, ни элемента интерфейса.",
|
|
5
|
+
"detail": "docs/DETAIL.md"
|
|
5
6
|
}
|
|
6
|
-
}
|
|
7
|
+
}
|
package/package.json
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cvc-catalog-sync-plugin",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "DSH plugin: keeps the
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "DSH plugin for CheapVibeCode with three switchable features: keeps the model catalog and reasoning levels in the profile patch in sync with /v1/models, shows model coefficients next to the model picker and the account balance in the sidebar",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"dsh",
|
|
8
|
-
"deepseek-harness",
|
|
9
|
-
"cordis",
|
|
10
8
|
"dsh-plugin",
|
|
11
9
|
"cheapvibecode",
|
|
12
10
|
"model-catalog",
|
|
13
|
-
"reasoning-levels"
|
|
11
|
+
"reasoning-levels",
|
|
12
|
+
"balance",
|
|
13
|
+
"model-coefficients"
|
|
14
14
|
],
|
|
15
15
|
"author": "mikel38487",
|
|
16
16
|
"license": "MIT",
|
|
@@ -26,23 +26,42 @@
|
|
|
26
26
|
"node": ">=20"
|
|
27
27
|
},
|
|
28
28
|
"scripts": {
|
|
29
|
-
"test": "node --test test
|
|
29
|
+
"test": "node --test test/*.mjs",
|
|
30
|
+
"build": "node tools/build-client.mjs"
|
|
30
31
|
},
|
|
31
32
|
"exports": {
|
|
32
33
|
".": "./index.js",
|
|
33
34
|
"./client": "./client.js",
|
|
34
35
|
"./locale/*.json": "./locale/*.json",
|
|
35
|
-
"./icon": "./icon.svg"
|
|
36
|
+
"./icon": "./icon.svg",
|
|
37
|
+
"./package.json": "./package.json"
|
|
36
38
|
},
|
|
37
39
|
"files": [
|
|
38
40
|
"index.js",
|
|
39
41
|
"client.js",
|
|
42
|
+
"lib/",
|
|
40
43
|
"cordis.patch.yml",
|
|
41
44
|
"locale/*.json",
|
|
45
|
+
"docs",
|
|
42
46
|
"icon.svg",
|
|
43
47
|
"README.md",
|
|
44
|
-
"
|
|
48
|
+
"README.ru.md",
|
|
49
|
+
"SECURITY.md",
|
|
50
|
+
"CHANGELOG.md"
|
|
45
51
|
],
|
|
52
|
+
"peerDependencies": {
|
|
53
|
+
"@deepseek-ai/schemastery": ">=3.18.4 <4"
|
|
54
|
+
},
|
|
55
|
+
"peerDependenciesMeta": {
|
|
56
|
+
"@deepseek-ai/schemastery": {
|
|
57
|
+
"optional": true
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
"devDependencies": {
|
|
61
|
+
"@deepseek-ai/schemastery": ">=3.18.4 <4",
|
|
62
|
+
"tsdown": "^0.23.0",
|
|
63
|
+
"typescript": "^5.7.2"
|
|
64
|
+
},
|
|
46
65
|
"publishConfig": {
|
|
47
66
|
"access": "public"
|
|
48
67
|
},
|
|
@@ -53,8 +72,11 @@
|
|
|
53
72
|
"client": {
|
|
54
73
|
"platform": "web",
|
|
55
74
|
"inject": [
|
|
56
|
-
"@deepseek-ai/dsh-client-ui-
|
|
57
|
-
|
|
75
|
+
"@deepseek-ai/dsh-client-ui-model-selection",
|
|
76
|
+
"@deepseek-ai/dsh-client-ui-settings",
|
|
77
|
+
"@deepseek-ai/dsh-client-ui-sidebar"
|
|
78
|
+
],
|
|
79
|
+
"external": []
|
|
58
80
|
},
|
|
59
81
|
"engines": {
|
|
60
82
|
"dsh": ">=0.2.2-rc.3 <0.4.0"
|