cvc-catalog-sync-plugin 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,582 @@
1
+ /**
2
+ * Клиентская половина cvc-catalog-sync-plugin: страница настроек.
3
+ *
4
+ * Регистрирует секцию `settings.section` (и её иконку) в панели настроек DSH.
5
+ * Значения читаются и пишутся через HTTP-маршрут хост-половины
6
+ * `/cvc-catalog-sync`: браузер не получает ключ и не пишет патч сам.
7
+ *
8
+ * @module cvc-catalog-sync-plugin/client
9
+ */
10
+ window.__ModuleLoader__.load({
11
+ id: 'cvc-catalog-sync-plugin',
12
+ factory(require) {
13
+ const React = require('react')
14
+ const h = React.createElement
15
+ const { useCallback, useEffect, useMemo, useState } = React
16
+
17
+ /** Пространство имён локали и id секции настроек. */
18
+ const NS = 'cvc-catalog-sync'
19
+ /** Префикс маршрута хост-половины. */
20
+ const API = '/cvc-catalog-sync'
21
+ /** Позиция секции в навигации настроек. */
22
+ const ORDER = 25
23
+ /** Имя пакета бандла: ключ блока на странице плагина в разделе «Плагины». */
24
+ const BUNDLE_NAME = 'cvc-catalog-sync-plugin'
25
+
26
+ const EN = {
27
+ nav: 'CVC catalog',
28
+ title: 'CVC catalog sync',
29
+ summary: 'Model catalog sync for the CheapVibeCode route.',
30
+ desc: 'Keeps the CheapVibeCode model list in the profile patch in sync with /v1/models and with the reasoning levels published by the official installer.',
31
+ groupMain: 'Connection',
32
+ groupSync: 'Synchronization',
33
+ groupAdvanced: 'Advanced',
34
+ provider: 'Provider route',
35
+ providerHint: 'Route key inside llm-pi-ai.providers.',
36
+ baseURL: 'API base URL',
37
+ baseURLHint: 'The models request goes to {baseURL}/models.',
38
+ apiKeyEnv: 'Credential name',
39
+ apiKeyEnvHint: 'Name of the variable; the key itself never enters this page.',
40
+ autoSync: 'Automatic sync',
41
+ autoSyncHint: 'Fetch at startup and on the interval; writes only on a real difference.',
42
+ intervalHours: 'Interval, hours',
43
+ intervalHoursHint: '0 turns the timer off; anything below a minute is raised to a minute.',
44
+ startupDelayMs: 'Startup delay, ms',
45
+ startupDelayMsHint: 'Pause after activation before the first run.',
46
+ syncAllowlist: 'Sync subagent list',
47
+ syncAllowlistHint: 'Keep subagent-model-selection-settings.allowedModels aligned with this route.',
48
+ minModelRatio: 'Catalog shrink guard',
49
+ minModelRatioHint: 'Refuse a catalog smaller than this share of the current model count (0 to 1).',
50
+ entryId: 'Profile row',
51
+ entryIdHint: 'Patch row that owns the provider routes.',
52
+ allowlistEntryId: 'Allowlist row',
53
+ allowlistEntryIdHint: 'Patch row that stores allowedModels.',
54
+ installerUrls: 'Installer URLs',
55
+ installerUrlsHint: 'One URL per line; the first reachable one provides reasoning levels.',
56
+ keepModels: 'Keep model ids',
57
+ keepModelsHint: 'One id per line; kept even when the catalog drops it.',
58
+ levelsCacheMinutes: 'Levels cache, minutes',
59
+ levelsCacheMinutesHint: 'How long the reasoning-level map is reused.',
60
+ timeoutMs: 'Request timeout, ms',
61
+ timeoutMsHint: 'Timeout for one catalog or installer request.',
62
+ save: 'Save',
63
+ saving: 'Saving…',
64
+ saved: 'Settings saved.',
65
+ check: 'Check catalog',
66
+ checking: 'Checking…',
67
+ checked: 'Catalog checked; nothing was written.',
68
+ apply: 'Apply catalog',
69
+ applying: 'Applying…',
70
+ confirmApply: 'Write the catalog into the profile patch now?',
71
+ confirmYes: 'Yes, apply',
72
+ confirmNo: 'Cancel',
73
+ reset: 'Reset to defaults',
74
+ resetDone: 'Defaults restored in the form; press Save to remove the override.',
75
+ statusTitle: 'Last run',
76
+ never: 'No run in this process yet.',
77
+ catalog: 'Catalog',
78
+ current: 'Current',
79
+ next: 'Next',
80
+ levels: 'Levels',
81
+ noDiff: 'No differences',
82
+ added: 'Added',
83
+ removed: 'Removed',
84
+ changed: 'Changed',
85
+ allowlistAdded: 'Allowlist added',
86
+ allowlistPruned: 'Allowlist pruned',
87
+ warnings: 'Warnings',
88
+ runError: 'Error',
89
+ patch: 'Patch',
90
+ inactive: 'The plugin row is not active; saving is disabled until the bundle is enabled.',
91
+ dirty: 'Unsaved changes',
92
+ checkUsesSaved: 'Check and apply use the saved settings.',
93
+ errLoad: 'Could not read settings',
94
+ errSave: 'Could not save settings',
95
+ errRun: 'Run failed',
96
+ loading: 'Loading…',
97
+ switchOn: 'On',
98
+ switchOff: 'Off',
99
+ }
100
+
101
+ const RU = {
102
+ nav: 'Каталог CVC',
103
+ title: 'Синхронизация каталога CVC',
104
+ summary: 'Синхронизация каталога моделей маршрута CheapVibeCode.',
105
+ desc: 'Держит список моделей CheapVibeCode в профильном патче в соответствии с /v1/models и с уровнями мышления из официального установщика.',
106
+ groupMain: 'Подключение',
107
+ groupSync: 'Синхронизация',
108
+ groupAdvanced: 'Дополнительно',
109
+ provider: 'Маршрут провайдера',
110
+ providerHint: 'Ключ маршрута в llm-pi-ai.providers.',
111
+ baseURL: 'Базовый адрес API',
112
+ baseURLHint: 'Запрос моделей идёт на {baseURL}/models.',
113
+ apiKeyEnv: 'Имя ключа',
114
+ apiKeyEnvHint: 'Имя переменной; сам ключ на страницу не попадает.',
115
+ autoSync: 'Автоматическая синхронизация',
116
+ autoSyncHint: 'Забирать каталог при старте и по интервалу; писать только при реальной разнице.',
117
+ intervalHours: 'Интервал, часов',
118
+ intervalHoursHint: '0 выключает таймер; значения меньше минуты поднимаются до минуты.',
119
+ startupDelayMs: 'Задержка старта, мс',
120
+ startupDelayMsHint: 'Пауза после активации перед первым прогоном.',
121
+ syncAllowlist: 'Синхронизировать список сабагентов',
122
+ syncAllowlistHint: 'Держать subagent-model-selection-settings.allowedModels в соответствии с маршрутом.',
123
+ minModelRatio: 'Защита от усыхания каталога',
124
+ minModelRatioHint: 'Не принимать каталог меньше этой доли от текущего числа моделей (0…1).',
125
+ entryId: 'Строка профиля',
126
+ entryIdHint: 'Строка патча, которой принадлежат маршруты провайдеров.',
127
+ allowlistEntryId: 'Строка списка',
128
+ allowlistEntryIdHint: 'Строка патча, где лежит allowedModels.',
129
+ installerUrls: 'Адреса установщиков',
130
+ installerUrlsHint: 'По одному на строку; уровни берутся из первого доступного.',
131
+ keepModels: 'Сохранять модели',
132
+ keepModelsHint: 'По одному id на строку; сохраняются, даже если каталог их убрал.',
133
+ levelsCacheMinutes: 'Кэш уровней, минут',
134
+ levelsCacheMinutesHint: 'Сколько времени переиспользуется карта уровней.',
135
+ timeoutMs: 'Таймаут запроса, мс',
136
+ timeoutMsHint: 'Таймаут одного запроса каталога или установщика.',
137
+ save: 'Сохранить',
138
+ saving: 'Сохраняю…',
139
+ saved: 'Настройки сохранены.',
140
+ check: 'Проверить каталог',
141
+ checking: 'Проверяю…',
142
+ checked: 'Каталог проверен, ничего не записано.',
143
+ apply: 'Применить каталог',
144
+ applying: 'Применяю…',
145
+ confirmApply: 'Записать каталог в профильный патч сейчас?',
146
+ confirmYes: 'Да, применить',
147
+ confirmNo: 'Отмена',
148
+ reset: 'Сбросить к умолчаниям',
149
+ resetDone: 'Умолчания подставлены в форму; нажмите «Сохранить», чтобы убрать переопределение.',
150
+ statusTitle: 'Последний прогон',
151
+ never: 'В этом процессе прогонов ещё не было.',
152
+ catalog: 'Каталог',
153
+ current: 'Сейчас',
154
+ next: 'Будет',
155
+ levels: 'Уровни',
156
+ noDiff: 'Различий нет',
157
+ added: 'Добавлено',
158
+ removed: 'Удалено',
159
+ changed: 'Изменено',
160
+ allowlistAdded: 'В список добавлено',
161
+ allowlistPruned: 'Из списка убрано',
162
+ warnings: 'Предупреждения',
163
+ runError: 'Ошибка',
164
+ patch: 'Патч',
165
+ inactive: 'Строка плагина не активна; сохранение недоступно, пока бандл не включён.',
166
+ dirty: 'Есть несохранённые изменения',
167
+ checkUsesSaved: 'Проверка и применение используют сохранённые настройки.',
168
+ errLoad: 'Не удалось прочитать настройки',
169
+ errSave: 'Не удалось сохранить настройки',
170
+ errRun: 'Прогон не удался',
171
+ loading: 'Загружаю…',
172
+ switchOn: 'Вкл',
173
+ switchOff: 'Выкл',
174
+ }
175
+
176
+ const CSS = `
177
+ .cvc-sync { display: flex; flex-direction: column; gap: 14px; max-width: 780px; padding: 4px 2px 28px; color: var(--dsw-alias-label-primary); font-size: 13px; line-height: 1.45; }
178
+ .cvc-sync h2 { margin: 0; font-size: 16px; font-weight: 600; }
179
+ .cvc-sync .cvc-sync-embedded-title { margin: 0; font-size: 14px; font-weight: 600; }
180
+ @media (max-width: 560px) { .cvc-sync .cvc-sync-field { grid-template-columns: 1fr; } }
181
+ .cvc-sync .cvc-sync-desc { margin: 0; color: var(--dsw-alias-label-secondary); }
182
+ .cvc-sync .cvc-sync-group { border: 1px solid var(--dsw-alias-border-l1); border-radius: 10px; background: var(--dsw-alias-bg-layer-1); padding: 4px 16px 8px; }
183
+ .cvc-sync .cvc-sync-group > h3 { margin: 10px 0 2px; font-size: 12px; font-weight: 600; letter-spacing: .02em; text-transform: uppercase; color: var(--dsw-alias-label-secondary); }
184
+ .cvc-sync .cvc-sync-field { display: grid; grid-template-columns: minmax(170px, 220px) minmax(0, 1fr); gap: 6px 16px; padding: 10px 0; border-top: 1px dashed var(--dsw-alias-border-l1); align-items: start; }
185
+ .cvc-sync .cvc-sync-group > .cvc-sync-field:first-of-type { border-top: 0; }
186
+ .cvc-sync .cvc-sync-label { font-weight: 500; }
187
+ .cvc-sync .cvc-sync-hint { margin-top: 2px; color: var(--dsw-alias-label-secondary); font-size: 12px; }
188
+ .cvc-sync .cvc-sync-control { min-width: 0; }
189
+ .cvc-sync input[type="text"], .cvc-sync input[type="number"], .cvc-sync textarea, .cvc-sync select {
190
+ box-sizing: border-box; width: 100%; padding: 7px 9px; border-radius: 8px;
191
+ border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-2);
192
+ color: var(--dsw-alias-label-primary); font: inherit;
193
+ }
194
+ .cvc-sync input:focus-visible, .cvc-sync textarea:focus-visible, .cvc-sync select:focus-visible, .cvc-sync button:focus-visible {
195
+ outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px;
196
+ }
197
+ .cvc-sync textarea { min-height: 64px; resize: vertical; font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font-size: 12px; }
198
+ .cvc-sync .cvc-sync-row { display: flex; align-items: center; gap: 10px; }
199
+ .cvc-sync .cvc-sync-switch { position: relative; width: 38px; height: 22px; flex: none; border-radius: 999px; border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-2); cursor: pointer; padding: 0; transition: background .12s ease, border-color .12s ease; }
200
+ .cvc-sync .cvc-sync-switch[data-on="true"] { background: var(--dsw-alias-brand-primary); border-color: var(--dsw-alias-brand-primary); }
201
+ .cvc-sync .cvc-sync-switch::after { content: ""; position: absolute; top: 2px; left: 2px; width: 16px; height: 16px; border-radius: 50%; background: var(--dsw-alias-bg-base); transition: transform .12s ease; }
202
+ .cvc-sync .cvc-sync-switch[data-on="true"]::after { transform: translateX(16px); }
203
+ .cvc-sync .cvc-sync-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
204
+ .cvc-sync .cvc-sync-btn { border-radius: 8px; border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-2); color: var(--dsw-alias-label-primary); font: inherit; font-weight: 500; padding: 7px 14px; cursor: pointer; }
205
+ .cvc-sync .cvc-sync-btn:hover:not(:disabled) { border-color: var(--dsw-alias-border-l2); }
206
+ .cvc-sync .cvc-sync-btn:disabled { opacity: .5; cursor: default; }
207
+ .cvc-sync .cvc-sync-btn[data-primary="true"] { background: var(--dsw-alias-brand-primary); border-color: var(--dsw-alias-brand-primary); color: var(--dsw-alias-bg-base); }
208
+ .cvc-sync .cvc-sync-note { flex: 1 1 220px; min-width: 0; font-size: 12px; }
209
+ .cvc-sync .cvc-sync-note[data-kind="ok"] { color: var(--dsw-alias-state-success-primary); }
210
+ .cvc-sync .cvc-sync-note[data-kind="warn"] { color: var(--dsw-alias-state-warn-primary); }
211
+ .cvc-sync .cvc-sync-note[data-kind="error"] { color: var(--dsw-alias-state-error-primary); }
212
+ .cvc-sync .cvc-sync-status { border: 1px solid var(--dsw-alias-border-l1); border-radius: 10px; background: var(--dsw-alias-bg-layer-2); padding: 10px 14px; font-size: 12px; }
213
+ .cvc-sync .cvc-sync-status h3 { margin: 0 0 6px; font-size: 12px; font-weight: 600; color: var(--dsw-alias-label-secondary); text-transform: uppercase; letter-spacing: .02em; }
214
+ .cvc-sync .cvc-sync-line { display: flex; flex-wrap: wrap; gap: 4px 10px; }
215
+ .cvc-sync .cvc-sync-line b { font-weight: 600; }
216
+ .cvc-sync .cvc-sync-mono { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; }
217
+ .cvc-sync .cvc-sync-warn { color: var(--dsw-alias-state-warn-primary); }
218
+ .cvc-sync .cvc-sync-error { color: var(--dsw-alias-state-error-primary); }
219
+ .cvc-sync .cvc-sync-ok { color: var(--dsw-alias-state-success-primary); }
220
+ .cvc-sync .cvc-sync-muted { color: var(--dsw-alias-label-secondary); }
221
+ `
222
+
223
+ /** REST-вызов к хост-половине. */
224
+ async function api(method, path, body) {
225
+ const init = { method, headers: { accept: 'application/json' } }
226
+ if (body !== undefined) {
227
+ init.headers['content-type'] = 'application/json'
228
+ init.body = JSON.stringify(body)
229
+ }
230
+ const response = await fetch(API + path, init)
231
+ let payload = null
232
+ try {
233
+ payload = await response.json()
234
+ } catch {
235
+ payload = null
236
+ }
237
+ if (!response.ok) {
238
+ const detail = payload?.fields?.length
239
+ ? `${payload.error ?? 'invalid'}: ${payload.fields.join('; ')}`
240
+ : payload?.error ?? `HTTP ${response.status}`
241
+ throw new Error(detail)
242
+ }
243
+ return payload
244
+ }
245
+
246
+ /** Показать список как строку, без пустых значений. */
247
+ function joinList(list) {
248
+ return Array.isArray(list) && list.length > 0 ? list.join(', ') : ''
249
+ }
250
+
251
+ /** Поле формы: подпись, подсказка и контрол. */
252
+ function Field({ label, hint, children }) {
253
+ return h('div', { className: 'cvc-sync-field' },
254
+ h('div', null,
255
+ h('div', { className: 'cvc-sync-label' }, label),
256
+ hint ? h('div', { className: 'cvc-sync-hint' }, hint) : null,
257
+ ),
258
+ h('div', { className: 'cvc-sync-control' }, children),
259
+ )
260
+ }
261
+
262
+ /** Текстовая строка. */
263
+ function TextInput({ value, onChange, list, placeholder }) {
264
+ return h('input', {
265
+ type: 'text',
266
+ value: value ?? '',
267
+ list,
268
+ placeholder,
269
+ spellCheck: false,
270
+ autoComplete: 'off',
271
+ onChange: (event) => onChange(event.target.value),
272
+ })
273
+ }
274
+
275
+ /** Числовое поле: пустое значение не ломает форму. */
276
+ function NumberInput({ value, onChange, min, max, step }) {
277
+ return h('input', {
278
+ type: 'number',
279
+ value: Number.isFinite(value) ? String(value) : '',
280
+ min, max, step,
281
+ onChange: (event) => {
282
+ const raw = event.target.value
283
+ onChange(raw === '' ? NaN : Number(raw))
284
+ },
285
+ })
286
+ }
287
+
288
+ /** Переключатель с ролью switch. */
289
+ function Switch({ checked, onChange, label }) {
290
+ return h('div', { className: 'cvc-sync-row' },
291
+ h('button', {
292
+ type: 'button',
293
+ role: 'switch',
294
+ 'aria-checked': checked === true,
295
+ 'aria-label': label,
296
+ className: 'cvc-sync-switch',
297
+ 'data-on': checked === true,
298
+ onClick: () => onChange(checked !== true),
299
+ }),
300
+ h('span', { className: 'cvc-sync-muted' }, checked === true ? label : ' '),
301
+ )
302
+ }
303
+
304
+ /** Блок состояния последнего прогона. */
305
+ function StatusBlock({ t, value }) {
306
+ if (value === null || value === undefined) return null
307
+ const lines = []
308
+ lines.push(h('div', { className: 'cvc-sync-line', key: 'counts' },
309
+ h('span', null, h('b', null, t('catalog')), ` ${value.catalogModels}`),
310
+ h('span', null, h('b', null, t('current')), ` ${value.currentModels}`),
311
+ h('span', null, h('b', null, t('next')), ` ${value.nextModels}`),
312
+ h('span', null, h('b', null, t('levels')), ' ', h('span', { className: 'cvc-sync-mono' }, value.levelsSource || '—')),
313
+ ))
314
+ const empty = value.added.length === 0 && value.removed.length === 0 && value.changed.length === 0
315
+ lines.push(h('div', { className: empty ? 'cvc-sync-ok' : '', key: 'diff' },
316
+ empty ? t('noDiff') : [
317
+ value.added.length ? `${t('added')}: ${joinList(value.added)}` : '',
318
+ value.removed.length ? `${t('removed')}: ${joinList(value.removed)}` : '',
319
+ value.changed.length ? `${t('changed')}: ${value.changed.map((row) => `${row.id} (${joinList(row.fields)})`).join(', ')}` : '',
320
+ ].filter(Boolean).join(' · '),
321
+ ))
322
+ if (value.allowlist.added.length) {
323
+ lines.push(h('div', { key: 'al-add' }, `${t('allowlistAdded')}: ${joinList(value.allowlist.added)}`))
324
+ }
325
+ if (value.allowlist.pruned.length) {
326
+ lines.push(h('div', { key: 'al-prune' }, `${t('allowlistPruned')}: ${joinList(value.allowlist.pruned)}`))
327
+ }
328
+ for (const [index, warning] of value.warnings.entries()) {
329
+ lines.push(h('div', { className: 'cvc-sync-warn', key: `warn-${index}` }, warning))
330
+ }
331
+ if (value.error) lines.push(h('div', { className: 'cvc-sync-error', key: 'error' }, `${t('runError')}: ${value.error}`))
332
+ if (value.at) lines.push(h('div', { className: 'cvc-sync-muted', key: 'at' }, value.at))
333
+ if (value.applied) lines.push(h('div', { className: 'cvc-sync-ok', key: 'applied' }, '✓'))
334
+ return h('div', { className: 'cvc-sync-status' }, h('h3', null, t('statusTitle')), ...lines)
335
+ }
336
+
337
+ /** Страница настроек. */
338
+ function SettingsPage({ t, embedded = false }) {
339
+ const [state, setState] = useState(null)
340
+ const [draft, setDraft] = useState(null)
341
+ const [busy, setBusy] = useState('')
342
+ const [note, setNote] = useState(null)
343
+ const [run, setRun] = useState(null)
344
+ const [confirming, setConfirming] = useState(false)
345
+
346
+ const load = useCallback(async () => {
347
+ const body = await api('GET', '/state')
348
+ setState(body)
349
+ setDraft(body.config)
350
+ return body
351
+ }, [])
352
+
353
+ useEffect(() => {
354
+ let alive = true
355
+ load().catch((error) => {
356
+ if (alive) setNote({ kind: 'error', text: `${t('errLoad')}: ${error.message}` })
357
+ })
358
+ return () => {
359
+ alive = false
360
+ }
361
+ }, [load, t])
362
+
363
+ const set = useCallback((key, value) => {
364
+ setDraft((current) => (current === null ? current : { ...current, [key]: value }))
365
+ }, [])
366
+
367
+ const dirty = useMemo(() => {
368
+ if (state === null || draft === null) return false
369
+ return JSON.stringify(state.config) !== JSON.stringify(draft)
370
+ }, [state, draft])
371
+
372
+ /** Привести форму к значениям, которые принимает хост. */
373
+ const payload = useCallback(() => ({
374
+ ...draft,
375
+ installerUrls: Array.isArray(draft.installerUrls) ? draft.installerUrls : [],
376
+ keepModels: Array.isArray(draft.keepModels) ? draft.keepModels : [],
377
+ }), [draft])
378
+
379
+ const save = useCallback(async () => {
380
+ setBusy('save')
381
+ setNote(null)
382
+ try {
383
+ const body = await api('PUT', '/config', { config: payload() })
384
+ await load()
385
+ setNote({ kind: 'ok', text: t('saved') })
386
+ if (body?.config) setDraft(body.config)
387
+ } catch (error) {
388
+ setNote({ kind: 'error', text: `${t('errSave')}: ${error.message}` })
389
+ } finally {
390
+ setBusy('')
391
+ }
392
+ }, [load, payload, t])
393
+
394
+ const runAction = useCallback(async (action) => {
395
+ setBusy(action)
396
+ setNote(null)
397
+ setConfirming(false)
398
+ try {
399
+ const value = await api('POST', '/run', { action })
400
+ setRun(value)
401
+ setNote({ kind: value.ok === true ? 'ok' : 'error', text: action === 'apply' ? '' : t('checked') })
402
+ await load()
403
+ } catch (error) {
404
+ setNote({ kind: 'error', text: `${t('errRun')}: ${error.message}` })
405
+ } finally {
406
+ setBusy('')
407
+ }
408
+ }, [load, t])
409
+
410
+ const reset = useCallback(() => {
411
+ if (state === null) return
412
+ setDraft(state.defaults)
413
+ setNote({ kind: 'warn', text: t('resetDone') })
414
+ }, [state, t])
415
+
416
+ if (state === null || draft === null) {
417
+ return h('div', { className: 'cvc-sync' },
418
+ h('h2', null, t('title')),
419
+ h('p', { className: 'cvc-sync-desc' }, note?.text ?? t('loading')),
420
+ )
421
+ }
422
+
423
+ const status = run ?? state.status
424
+ const disabled = busy !== '' || state.active === false
425
+
426
+ const textRows = (key, hint) => h(TextInput, {
427
+ value: draft[key],
428
+ onChange: (value) => set(key, value),
429
+ })
430
+
431
+ return h('div', { className: 'cvc-sync' },
432
+ h(embedded ? 'h3' : 'h2', { className: embedded ? 'cvc-sync-embedded-title' : undefined }, t('title')),
433
+ embedded ? null : h('p', { className: 'cvc-sync-desc' }, t('desc')),
434
+ state.active === false ? h('p', { className: 'cvc-sync-error' }, t('inactive')) : null,
435
+
436
+ h('div', { className: 'cvc-sync-group' },
437
+ h('h3', null, t('groupMain')),
438
+ h(Field, { label: t('provider'), hint: t('providerHint') },
439
+ h(React.Fragment, null,
440
+ h(TextInput, { value: draft.provider, onChange: (value) => set('provider', value), list: 'cvc-sync-providers' }),
441
+ h('datalist', { id: 'cvc-sync-providers' },
442
+ state.providers.map((id) => h('option', { key: id, value: id }))),
443
+ )),
444
+ h(Field, { label: t('baseURL'), hint: t('baseURLHint') }, textRows('baseURL')),
445
+ h(Field, { label: t('apiKeyEnv'), hint: t('apiKeyEnvHint') }, textRows('apiKeyEnv')),
446
+ ),
447
+
448
+ h('div', { className: 'cvc-sync-group' },
449
+ h('h3', null, t('groupSync')),
450
+ h(Field, { label: t('autoSync'), hint: t('autoSyncHint') },
451
+ h(Switch, { checked: draft.autoSync, onChange: (value) => set('autoSync', value), label: draft.autoSync ? t('switchOn') : t('switchOff') })),
452
+ h(Field, { label: t('intervalHours'), hint: t('intervalHoursHint') },
453
+ h(NumberInput, { value: draft.intervalHours, min: 0, step: 1, onChange: (value) => set('intervalHours', value) })),
454
+ h(Field, { label: t('startupDelayMs'), hint: t('startupDelayMsHint') },
455
+ h(NumberInput, { value: draft.startupDelayMs, min: 0, step: 500, onChange: (value) => set('startupDelayMs', value) })),
456
+ h(Field, { label: t('minModelRatio'), hint: t('minModelRatioHint') },
457
+ h(NumberInput, { value: draft.minModelRatio, min: 0.05, max: 1, step: 0.05, onChange: (value) => set('minModelRatio', value) })),
458
+ h(Field, { label: t('syncAllowlist'), hint: t('syncAllowlistHint') },
459
+ h(Switch, { checked: draft.syncAllowlist, onChange: (value) => set('syncAllowlist', value), label: draft.syncAllowlist ? t('switchOn') : t('switchOff') })),
460
+ ),
461
+
462
+ h('div', { className: 'cvc-sync-group' },
463
+ h('h3', null, t('groupAdvanced')),
464
+ h(Field, { label: t('entryId'), hint: t('entryIdHint') }, textRows('entryId')),
465
+ h(Field, { label: t('allowlistEntryId'), hint: t('allowlistEntryIdHint') }, textRows('allowlistEntryId')),
466
+ h(Field, { label: t('installerUrls'), hint: t('installerUrlsHint') },
467
+ h('textarea', {
468
+ value: Array.isArray(draft.installerUrls) ? draft.installerUrls.join('\n') : '',
469
+ spellCheck: false,
470
+ onChange: (event) => set('installerUrls', event.target.value.split('\n').map((line) => line.trim()).filter(Boolean)),
471
+ })),
472
+ h(Field, { label: t('keepModels'), hint: t('keepModelsHint') },
473
+ h('textarea', {
474
+ value: Array.isArray(draft.keepModels) ? draft.keepModels.join('\n') : '',
475
+ spellCheck: false,
476
+ onChange: (event) => set('keepModels', event.target.value.split(/[\n,]+/).map((line) => line.trim()).filter(Boolean)),
477
+ })),
478
+ h(Field, { label: t('levelsCacheMinutes'), hint: t('levelsCacheMinutesHint') },
479
+ h(NumberInput, { value: draft.levelsCacheMinutes, min: 0, step: 10, onChange: (value) => set('levelsCacheMinutes', value) })),
480
+ h(Field, { label: t('timeoutMs'), hint: t('timeoutMsHint') },
481
+ h(NumberInput, { value: draft.timeoutMs, min: 1, step: 1000, onChange: (value) => set('timeoutMs', value) })),
482
+ ),
483
+
484
+ h(StatusBlock, { t, value: status }),
485
+
486
+ h('div', { className: 'cvc-sync-actions' },
487
+ h('button', {
488
+ type: 'button',
489
+ className: 'cvc-sync-btn',
490
+ 'data-primary': true,
491
+ disabled: disabled || !dirty,
492
+ onClick: save,
493
+ }, busy === 'save' ? t('saving') : t('save')),
494
+ h('button', {
495
+ type: 'button',
496
+ className: 'cvc-sync-btn',
497
+ disabled,
498
+ onClick: () => runAction('plan'),
499
+ }, busy === 'plan' ? t('checking') : t('check')),
500
+ h('button', {
501
+ type: 'button',
502
+ className: 'cvc-sync-btn',
503
+ disabled,
504
+ onClick: () => setConfirming(true),
505
+ }, busy === 'apply' ? t('applying') : t('apply')),
506
+ h('button', {
507
+ type: 'button',
508
+ className: 'cvc-sync-btn',
509
+ disabled: disabled,
510
+ onClick: reset,
511
+ }, t('reset')),
512
+ h('span', { className: 'cvc-sync-note', 'data-kind': note?.kind ?? '' }, note?.text ?? ''),
513
+ ),
514
+
515
+ confirming ? h('div', { className: 'cvc-sync-status' },
516
+ h('div', null, t('confirmApply')),
517
+ h('div', { className: 'cvc-sync-actions', style: { marginTop: '8px' } },
518
+ h('button', { type: 'button', className: 'cvc-sync-btn', 'data-primary': true, onClick: () => runAction('apply') }, t('confirmYes')),
519
+ h('button', { type: 'button', className: 'cvc-sync-btn', onClick: () => setConfirming(false) }, t('confirmNo')),
520
+ ),
521
+ ) : null,
522
+
523
+ h('p', { className: 'cvc-sync-hint' },
524
+ `${t('checkUsesSaved')} ${dirty ? `· ${t('dirty')}` : ''}`),
525
+ h('p', { className: 'cvc-sync-hint cvc-sync-mono' }, `${t('patch')}: ${state.patchPath}`),
526
+ )
527
+ }
528
+
529
+ /** Значок секции в навигации настроек. */
530
+ function NavIcon({ size = 16 }) {
531
+ return h('svg', {
532
+ width: size, height: size, viewBox: '0 0 64 64', 'aria-hidden': true,
533
+ style: { display: 'block' },
534
+ },
535
+ h('path', { d: 'M20 25a12 12 0 0 1 20-6l4 4', fill: 'none', stroke: 'currentColor', strokeWidth: 6, strokeLinecap: 'round' }),
536
+ h('path', { d: 'M44 19v8h-8', fill: 'none', stroke: 'currentColor', strokeWidth: 6, strokeLinecap: 'round', strokeLinejoin: 'round' }),
537
+ h('path', { d: 'M44 39a12 12 0 0 1-20 6l-4-4', fill: 'none', stroke: 'currentColor', strokeWidth: 6, strokeLinecap: 'round' }),
538
+ h('path', { d: 'M20 45v-8h8', fill: 'none', stroke: 'currentColor', strokeWidth: 6, strokeLinecap: 'round', strokeLinejoin: 'round' }),
539
+ )
540
+ }
541
+
542
+ /** Точка входа клиентской половины. */
543
+ function apply(ctx) {
544
+ ctx.effect(() => ctx.locale.register(NS, { en: EN, ru: RU }), 'cvc-catalog-sync: dictionaries')
545
+ const t = ctx.locale.bind(NS)
546
+ ctx.effect(() => {
547
+ const style = document.createElement('style')
548
+ style.dataset.plugin = 'cvc-catalog-sync-plugin'
549
+ style.textContent = CSS
550
+ document.head.appendChild(style)
551
+ return () => style.remove()
552
+ }, 'cvc-catalog-sync: styles')
553
+
554
+ ctx.slots.inject('settings.section.icon', () => ctx.slots.register({
555
+ name: 'settings.section.icon',
556
+ id: NS,
557
+ }, (owner = {}) => h(NavIcon, { size: owner.size ?? 16 })))
558
+
559
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
560
+ name: 'settings.section',
561
+ id: NS,
562
+ order: ORDER,
563
+ label: () => t('nav'),
564
+ locale: NS,
565
+ inject: () => ({ t }),
566
+ }, (owner = {}) => h(SettingsPage, { ...owner, t })))
567
+
568
+ // Второе место — страница плагина в разделе «Плагины»: блок между
569
+ // описанием и списком компонентов, как у dshmarket и dsh-free-search.
570
+ ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
571
+ name: 'plugins.bundle.config',
572
+ key: BUNDLE_NAME,
573
+ locale: NS,
574
+ inject: () => ({ t }),
575
+ }, (owner = {}) => (owner.view === 'summary'
576
+ ? h('span', { className: 'cvc-sync-muted' }, t('summary'))
577
+ : h(SettingsPage, { ...owner, t, embedded: true }))))
578
+ }
579
+
580
+ return { inject: ['slots', 'locale'], apply }
581
+ },
582
+ })
@@ -0,0 +1,14 @@
1
+ # Хост-половина синхронизации каталога CheapVibeCode.
2
+ #
3
+ # Плагин ничего не показывает в интерфейсе: он забирает GET /v1/models,
4
+ # вытаскивает карту уровней мышления из установщика /idhw и точечно пишет
5
+ # models в строку llm-pi-ai профильного патча. Ручной запуск — инструмент
6
+ # cvc_catalog. Своей строкой конфига настраивается поведение (см. README).
7
+
8
+ - insert:
9
+ - id: cvc-catalog-sync
10
+ name: 'cvc-catalog-sync-plugin'
11
+ config:
12
+ provider: cheapvibecode
13
+ autoSync: true
14
+ intervalHours: 24
package/icon.svg ADDED
@@ -0,0 +1,8 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" role="img" aria-label="Catalog sync">
2
+ <rect x="2" y="2" width="60" height="60" rx="14" fill="#1f2937"/>
3
+ <path d="M20 25a12 12 0 0 1 20-6l4 4" fill="none" stroke="#60a5fa" stroke-width="4" stroke-linecap="round"/>
4
+ <path d="M44 19v8h-8" fill="none" stroke="#60a5fa" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
5
+ <path d="M44 39a12 12 0 0 1-20 6l-4-4" fill="none" stroke="#34d399" stroke-width="4" stroke-linecap="round"/>
6
+ <path d="M20 45v-8h8" fill="none" stroke="#34d399" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
7
+ <circle cx="32" cy="32" r="3.5" fill="#f9fafb"/>
8
+ </svg>