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.
@@ -0,0 +1,260 @@
1
+ # Compatibility
2
+
3
+ This document lists what the plugin expects from DSH, what happens when one of
4
+ those expectations stops holding, and what to change in the code. It is the
5
+ maintainer's checklist for a DSH update; the user-facing requirements are in
6
+ [README.md](../README.md).
7
+
8
+ ## Version range
9
+
10
+ | What | Range |
11
+ | --- | --- |
12
+ | DSH | `>=0.2.2-rc.3 <0.4.0` |
13
+ | Node.js, plugin runtime | `>=20` |
14
+ | Node.js, building `client.js` | `>=22.18` (`tsdown`) |
15
+
16
+ The development line used for the merge and for the live checks was DSH
17
+ `0.2.2-rc.5`: `@deepseek-ai/schemastery` 3.19.0 resolves from the installation
18
+ directory, and a volatile field edit arrives as `loader/volatile-update` without a
19
+ second `apply`. That covers the mechanics this plugin depends on. Every other slot
20
+ and service listed in this document was exercised by the test suites against
21
+ fakes of the shapes named here, not against a second DSH release.
22
+
23
+ The DSH range is declared in `dsh.engines.dsh` of `package.json`. That is the
24
+ field the plugin market reads and shows on the plugin card. The plugin has no
25
+ `peerDependencies` entry on a `@deepseek-ai/dsh-*` package, so the host-side
26
+ install check — which only reads such peers — does not constrain the version. If
27
+ you want the install to be refused on an unsupported DSH, add a peer on
28
+ `@deepseek-ai/dsh-llm` with the same range; that is what the two old private
29
+ plugins did.
30
+
31
+ Node 22.18 is needed only to rebuild the browser half. The published package
32
+ contains the compiled `client.js`, so users on Node 20 never run the build, and
33
+ installing from npm or from git starts no build script at all.
34
+
35
+ ## Client modules declared in the manifest
36
+
37
+ `package.json` declares `dsh.client.inject`:
38
+
39
+ | Module | Needed for | If it is missing |
40
+ | --- | --- | --- |
41
+ | `@deepseek-ai/dsh-client-ui-settings` | the settings page and its navigation icon | no settings page and no bundle block; catalog sync, coefficients and balance still run on the host, but cannot be switched from the UI |
42
+ | `@deepseek-ai/dsh-client-ui-sidebar` | the balance button and panel | no button and no panel; catalog sync and coefficients are unaffected |
43
+ | `@deepseek-ai/dsh-client-ui-model-selection` | the coefficient badges | no badges; catalog sync and balance are unaffected |
44
+
45
+ The client half also exports `inject = ['slots', 'locale']` itself. That export is
46
+ what makes `ctx.slots` and `ctx.locale` connected properties of the Cordis
47
+ context. A client half that exports only `apply` gets `ctx.slots === undefined`
48
+ and its registrations silently disappear — this is a Cordis contract, not a DSH
49
+ choice, and it is the reason the `inject` export must not be removed.
50
+
51
+ ## UI surfaces the plugin leans on
52
+
53
+ These are host-side slots and DOM attributes, not a stable public API. Each row
54
+ names the surface, what the plugin does with it, and the symptom when it changes.
55
+
56
+ | Surface | Used for | Symptom if it changes |
57
+ | --- | --- | --- |
58
+ | `settings.section` | the **Settings → CVC** page (id `cvc`, order 25) | the section disappears from settings navigation; everything else keeps working, and the plugin can still be configured by editing the profile patch |
59
+ | `settings.section.icon` | the icon of that section | the section shows without the plugin icon, or the icon slot rejects the registration |
60
+ | `plugins.bundle.config` | the configuration block on the bundle page in **Plugins** (key = package name, `view: 'summary'` for the one-line form) | the block is not drawn on the plugin page; the settings section is still there |
61
+ | `sidebar.footer.action` | the **CVC balance** button and its panel (id `cvc-balance`, order 5) | no balance button; the balance route still answers `GET /cvc/balance`, and the `cvc_balance` tool still works |
62
+ | `data-model-id` on a model row | the key the badge looks up in the coefficient map | no badges, because the badge does not know which model the row belongs to |
63
+ | `data-provider-id` on the same row | the check that the row belongs to a CVC provider | no badges; the plugin never decorates a model of another provider |
64
+ | `conversation.input.model.label` | **not used** — deliberately left to its owner | nothing: the plugin does not register there, so a change to that slot cannot break it |
65
+ | `shell.overlay` | **not used** — DSH, in the supported range, exposes no public overlay slot; the balance panel is positioned inside `sidebar.footer.action` with `position: fixed` | nothing today. If a real overlay slot appears, moving the panel there would be the cleaner option, and the panel code is the only part to change |
66
+ | `--dsw-alias-*` CSS variables | all colours of the page, badges and panel | styling loses contrast but stays readable; the variables are also what keeps the light theme working |
67
+
68
+ ## Host services the plugin uses
69
+
70
+ | Service | Used by | What it provides | If it changes |
71
+ | --- | --- | --- | --- |
72
+ | `ctx.webServer.register` | `lib/http.js` | route registration under `/cvc` | no HTTP routes: the settings page cannot load or save, badges and balance stay empty |
73
+ | `ctx.configEditor` (`entries`, `configuration`, `edit`, `documentPath`) | `lib/state.js`, `lib/catalog-sync.js` | reading the patch layers and writing the plugin row, `llm-pi-ai.models`, `allowedModels` | saves and catalog applies fail; nothing is written |
74
+ | `ctx.credentials.resolve` | `lib/providers.js` | resolving a key by name | catalog, balance and installer runs fail with a "credential is not configured" error; no key is ever read another way |
75
+ | `ctx.settings.configure({ auto: false })` | `index.js` | keeping the plugin row out of the automatic settings form | the row may be rendered twice |
76
+ | `loader/volatile-update` | `index.js` | applying a changed row without a restart | switches stop taking effect live; the plugin would need a restart after each change |
77
+ | `ctx.slots.inject` / `ctx.slots.register` | `src/client/index.js` | registering the page, the bundle block and the balance button | the affected surface is not registered; the rest keeps working |
78
+ | `ctx.locale.register` / `ctx.locale.bind` | `src/client/index.js` | the en/ru dictionaries, including the section label | the interface falls back to dictionary keys or loses the section title |
79
+ | `window.__ModuleLoader__.load` | `tools/build-client.mjs` | the wrapper the DSH client loader expects | the browser half does not load; `client.js` is not registered |
80
+
81
+ ## What to do when DSH changes
82
+
83
+ 1. Start with the console of the DSH web UI. Each surface fails independently, so
84
+ the first error names the slot or service that moved.
85
+ 2. Check `dsh.client.inject` in `package.json` against the client modules the
86
+ current DSH ships. A module that was merged or renamed must be updated there,
87
+ and the corresponding import in `src/client/**` must follow.
88
+ 3. Check the slot names against the DSH client packages of that version
89
+ (`dsh-client-ui-settings`, `dsh-client-ui-sidebar`,
90
+ `dsh-client-ui-model-selection`). A renamed slot is a one-line change in
91
+ `src/client/index.js`; nothing in the host half depends on it.
92
+ 4. If `ctx.configEditor` changes, `lib/state.js` and `lib/catalog-sync.js` are the
93
+ only files to touch. Keep the rule that the current value is read inside the
94
+ edit callback: it is what makes the write safe next to a concurrent edit.
95
+ 5. If the model selector stops writing `data-model-id` or `data-provider-id`, the
96
+ badges need another way to identify a row. Do not guess by visible text: the
97
+ same model id can belong to another provider.
98
+ 6. If the theme tokens are renamed, `src/client/css.js` is the only file with
99
+ colours. Keep using tokens; hard-coded colours would break the light theme.
100
+ 7. Run the tests after the change. `test/client-render.test.mjs` mounts the page
101
+ on a fake React and fails when a registration shape changes;
102
+ `test/gating.test.mjs` fails when the volatile path stops mounting or
103
+ unmounting a function.
104
+
105
+ ## Deliberate non-dependencies
106
+
107
+ - **No Remote namespaces.** The browser-side Remote table is built into DSH from
108
+ its own packages, so a third-party plugin cannot add an entry. The plugin owns
109
+ HTTP routes instead and uses `fetch`, the same way `dshmarket` does.
110
+ - **No `ctx.shell`.** The catalog and the balance are read with the host
111
+ process's ordinary `fetch`. The plugin does not spawn a process.
112
+ - **No build on install.** `client.js` is committed. `prepare` is not used, so
113
+ pnpm does not ask for `allowBuilds` and the profile does not need a build
114
+ permission for this package.
115
+ - **No `modelOverrides` support.** DSH does not accept `modelOverrides` beside a
116
+ `models` list; a route configured that way is refused with an explicit error
117
+ instead of being silently rewritten.
118
+
119
+ ## Compatibility history
120
+
121
+ | Plugin version | DSH range | Notes |
122
+ | --- | --- | --- |
123
+ | 2.0.0 | `>=0.2.2-rc.3 <0.4.0` | three functions, routes under `/cvc`, grouped config |
124
+ | 1.0.0 | `>=0.2.2-rc.3 <0.4.0` | catalog sync only, flat config, routes under `/cvc-catalog-sync` |
125
+
126
+ The private `cvc-model-coeff-plugin` 1.0.0 and `cvc-balance-plugin` 1.1.0 were
127
+ built for the 0.1.x line; their functions are ported here and the repositories are
128
+ archived.
129
+
130
+ ---
131
+
132
+ # Совместимость
133
+
134
+ Этот документ перечисляет, что плагин ожидает от DSH, что происходит, когда
135
+ ожидание перестаёт выполняться, и что менять в коде. Это памятка сопровождающего
136
+ к обновлению DSH; требования для пользователя — в [README.ru.md](../README.ru.md).
137
+
138
+ ## Диапазон версий
139
+
140
+ | Что | Диапазон |
141
+ | --- | --- |
142
+ | DSH | `>=0.2.2-rc.3 <0.4.0` |
143
+ | Node.js, работа плагина | `>=20` |
144
+ | Node.js, сборка `client.js` | `>=22.18` (`tsdown`) |
145
+
146
+ Линия разработки, на которой шло слияние и живые проверки, — DSH `0.2.2-rc.5`:
147
+ `@deepseek-ai/schemastery` 3.19.0 разрешается из каталога установки, а правка
148
+ volatile-поля приходит событием `loader/volatile-update` без повторного `apply`.
149
+ Это покрывает механику, от которой плагин зависит. Все остальные слоты и
150
+ сервисы из этого документа проверены наборами тестов на подделках с описанными
151
+ здесь формами, а не на втором релизе DSH.
152
+
153
+ Диапазон DSH объявлен в `dsh.engines.dsh` файла `package.json`. Именно это поле
154
+ читает маркет плагинов и показывает на карточке. Peer-зависимости на пакет
155
+ `@deepseek-ai/dsh-*` у плагина нет, поэтому хостовая проверка установки — а она
156
+ читает только такие peer-и — версию не ограничивает. Если нужно, чтобы установка
157
+ на неподдерживаемом DSH отклонялась, добавьте peer на `@deepseek-ai/dsh-llm` с
158
+ тем же диапазоном: так делали оба старых приватных плагина.
159
+
160
+ Node 22.18 нужен только для пересборки браузерной половины. Опубликованный
161
+ пакет содержит собранный `client.js`, поэтому пользователь на Node 20 сборку не
162
+ запускает, а установка из npm и из git вообще не запускает скриптов сборки.
163
+
164
+ ## Клиентские модули, объявленные в манифесте
165
+
166
+ `package.json` объявляет `dsh.client.inject`:
167
+
168
+ | Модуль | Зачем нужен | Если его нет |
169
+ | --- | --- | --- |
170
+ | `@deepseek-ai/dsh-client-ui-settings` | страница настроек и её значок в навигации | нет страницы настроек и блока бандла; синхронизация каталога, коэффициенты и баланс на хосте работают, но переключить их из интерфейса нечем |
171
+ | `@deepseek-ai/dsh-client-ui-sidebar` | кнопка и панель баланса | нет кнопки и панели; синхронизация каталога и коэффициенты не затронуты |
172
+ | `@deepseek-ai/dsh-client-ui-model-selection` | бейджи коэффициентов | нет бейджей; синхронизация каталога и баланс не затронуты |
173
+
174
+ Сама клиентская половина ещё экспортирует `inject = ['slots', 'locale']`. Этот
175
+ экспорт и делает `ctx.slots` и `ctx.locale` подключёнными свойствами контекста
176
+ Cordis. Половина, экспортирующая только `apply`, получает `ctx.slots ===
177
+ undefined`, и её регистрации молча исчезают — это контракт Cordis, а не выбор
178
+ DSH, и поэтому экспорт `inject` нельзя убирать.
179
+
180
+ ## Поверхности интерфейса, на которые опирается плагин
181
+
182
+ Это слоты хоста и атрибуты DOM, а не стабильный публичный API. В каждой строке —
183
+ поверхность, что с ней делает плагин и что будет видно, если она изменится.
184
+
185
+ | Поверхность | Для чего | Симптом при изменении |
186
+ | --- | --- | --- |
187
+ | `settings.section` | страница **Настройки → CVC** (id `cvc`, order 25) | раздел исчезает из навигации настроек; всё остальное работает, а настроить плагин можно правкой профильного патча |
188
+ | `settings.section.icon` | значок этого раздела | раздел показывается без значка плагина либо слот отклоняет регистрацию |
189
+ | `plugins.bundle.config` | блок конфигурации на странице бандла в **«Плагинах»** (ключ — имя пакета, `view: 'summary'` для однострочного вида) | блок не рисуется на странице плагина; раздел настроек остаётся |
190
+ | `sidebar.footer.action` | кнопка **CVC баланс** и её панель (id `cvc-balance`, order 5) | нет кнопки баланса; маршрут `GET /cvc/balance` по-прежнему отвечает, инструмент `cvc_balance` работает |
191
+ | `data-model-id` на строке модели | ключ, по которому бейдж ищет модель в карте коэффициентов | нет бейджей: бейдж не знает, какой модели принадлежит строка |
192
+ | `data-provider-id` на той же строке | проверка, что строка принадлежит провайдеру CVC | нет бейджей; модель чужого провайдера плагин не украшает никогда |
193
+ | `conversation.input.model.label` | **не используется** — намеренно оставлен владельцу | ничего: плагин туда не регистрируется, и изменение слота его не ломает |
194
+ | `shell.overlay` | **не используется** — в поддерживаемом диапазоне DSH нет публичного слота оверлея; панель баланса позиционируется внутри `sidebar.footer.action` через `position: fixed` | сегодня — ничего. Если настоящий слот оверлея появится, перенести панель туда будет чище, и менять придётся только код панели |
195
+ | CSS-переменные `--dsw-alias-*` | все цвета страницы, бейджей и панели | оформление теряет контраст, но остаётся читаемым; эти же переменные обеспечивают работу светлой темы |
196
+
197
+ ## Сервисы хоста, которые использует плагин
198
+
199
+ | Сервис | Кем используется | Что даёт | Если изменится |
200
+ | --- | --- | --- | --- |
201
+ | `ctx.webServer.register` | `lib/http.js` | регистрацию маршрутов под `/cvc` | нет HTTP-маршрутов: страница настроек не загрузится и не сохранит, бейджи и баланс останутся пустыми |
202
+ | `ctx.configEditor` (`entries`, `configuration`, `edit`, `documentPath`) | `lib/state.js`, `lib/catalog-sync.js` | чтение слоёв патча и запись строки плагина, `llm-pi-ai.models`, `allowedModels` | сохранение и применение каталога падают; ничего не записывается |
203
+ | `ctx.credentials.resolve` | `lib/providers.js` | разрешение ключа по имени | прогоны каталога, баланса и установщика падают с ошибкой «credential is not configured»; другим способом ключ не читается никогда |
204
+ | `ctx.settings.configure({ auto: false })` | `index.js` | не показывать строку плагина в автоматической форме настроек | строка может отрисоваться дважды |
205
+ | `loader/volatile-update` | `index.js` | применение изменённой строки без перезапуска | переключатели перестают действовать на лету; после каждого изменения нужен перезапуск |
206
+ | `ctx.slots.inject` / `ctx.slots.register` | `src/client/index.js` | регистрацию страницы, блока бандла и кнопки баланса | соответствующая поверхность не регистрируется; остальное работает |
207
+ | `ctx.locale.register` / `ctx.locale.bind` | `src/client/index.js` | словари en/ru, включая подпись раздела | интерфейс покажет ключи словаря или потеряет заголовок раздела |
208
+ | `window.__ModuleLoader__.load` | `tools/build-client.mjs` | обёртку, которую ждёт загрузчик клиента DSH | браузерная половина не загрузится; `client.js` не зарегистрируется |
209
+
210
+ ## Что делать при обновлении DSH
211
+
212
+ 1. Начните с консоли веб-интерфейса DSH. Каждая поверхность отказывает
213
+ независимо, поэтому первая ошибка называет слот или сервис, который переехал.
214
+ 2. Сверьте `dsh.client.inject` в `package.json` с клиентскими модулями, которые
215
+ поставляет текущий DSH. Объединённый или переименованный модуль надо поправить
216
+ там же, а за ним — соответствующий импорт в `src/client/**`.
217
+ 3. Сверьте имена слотов с клиентскими пакетами DSH этой версии
218
+ (`dsh-client-ui-settings`, `dsh-client-ui-sidebar`,
219
+ `dsh-client-ui-model-selection`). Переименованный слот — правка в одну строку в
220
+ `src/client/index.js`; хост-половина от него не зависит.
221
+ 4. Если изменится `ctx.configEditor`, трогать нужно только `lib/state.js` и
222
+ `lib/catalog-sync.js`. Сохраняйте правило «текущее значение читается внутри
223
+ колбэка правки»: именно оно делает запись безопасной рядом с параллельной
224
+ правкой.
225
+ 5. Если селектор моделей перестанет писать `data-model-id` или
226
+ `data-provider-id`, бейджам нужен другой способ опознать строку. Не угадывайте
227
+ по видимому тексту: тот же id модели может принадлежать другому провайдеру.
228
+ 6. Если переименуют токены темы, `src/client/css.js` — единственный файл с
229
+ цветами. Продолжайте использовать токены; жёстко заданные цвета сломают
230
+ светлую тему.
231
+ 7. Прогоните тесты после правки. `test/client-render.test.mjs` монтирует
232
+ страницу на поддельном React и падает, когда меняется форма регистрации;
233
+ `test/gating.test.mjs` падает, когда volatile-путь перестаёт монтировать и
234
+ снимать функцию.
235
+
236
+ ## Намеренные не-зависимости
237
+
238
+ - **Никаких Remote-неймспейсов.** Браузерная таблица Remote собирается внутри
239
+ DSH из его собственных пакетов, поэтому сторонний плагин не может добавить туда
240
+ запись. Вместо этого плагин владеет HTTP-маршрутами и использует `fetch` — так
241
+ же, как `dshmarket`.
242
+ - **Никакого `ctx.shell`.** Каталог и баланс читаются обычным `fetch` процесса
243
+ хоста. Плагин не запускает дочерний процесс.
244
+ - **Никакой сборки при установке.** `client.js` коммитится. `prepare` не
245
+ используется, поэтому pnpm не просит `allowBuilds` и профилю не нужно
246
+ разрешение на сборку этого пакета.
247
+ - **Никакой поддержки `modelOverrides`.** DSH не принимает `modelOverrides`
248
+ рядом с `models`; маршрут, настроенный так, отклоняется с понятной ошибкой, а
249
+ не переписывается молча.
250
+
251
+ ## История совместимости
252
+
253
+ | Версия плагина | Диапазон DSH | Примечания |
254
+ | --- | --- | --- |
255
+ | 2.0.0 | `>=0.2.2-rc.3 <0.4.0` | три функции, маршруты под `/cvc`, группированный конфиг |
256
+ | 1.0.0 | `>=0.2.2-rc.3 <0.4.0` | только синхронизация каталога, плоский конфиг, маршруты под `/cvc-catalog-sync` |
257
+
258
+ Приватные `cvc-model-coeff-plugin` 1.0.0 и `cvc-balance-plugin` 1.1.0 были
259
+ собраны под линию 0.1.x; их функции перенесены сюда, а репозитории
260
+ заархивированы.
package/docs/DETAIL.md ADDED
@@ -0,0 +1,3 @@
1
+ # CVC catalog, coefficients and balance
2
+
3
+ ![Settings page with three feature switches, coefficient badges in the model picker and the balance panel](preview.svg)
@@ -0,0 +1,357 @@
1
+ # Upgrading to 2.0.0
2
+
3
+ Version 2.0.0 turns one function (catalog sync) into three switchable functions
4
+ (catalog sync, price coefficients, balance) and absorbs two plugins that used to
5
+ be installed separately. The package name, the row id and the locale namespace do
6
+ not change, so an existing profile keeps working; what changes is the shape of the
7
+ row configuration and the set of HTTP routes.
8
+
9
+ There are two upgrade paths:
10
+
11
+ - [from cvc-catalog-sync-plugin 1.0.0](#from-cvc-catalog-sync-plugin-100);
12
+ - [from the two private plugins](#from-the-two-private-plugins).
13
+
14
+ Both end with a check list. Do not skip the check list: a switched-off function
15
+ is silent by design, and the check list is how you see that all three are alive.
16
+
17
+ ## Before you start
18
+
19
+ 1. Copy the profile patch. It is the only state the plugin writes, and the
20
+ profile is not a git repository:
21
+
22
+ ```powershell
23
+ Copy-Item ~\.dsh\profiles\<profile>\cordis.patch.yml ~\.dsh\profiles\<profile>\cordis.patch.yml.bak-before-2.0.0
24
+ ```
25
+
26
+ 2. Note the running DSH version (`Settings → About`, or the version in the
27
+ window title). 2.0.0 supports `>=0.2.2-rc.3 <0.4.0`.
28
+ Installing from npm and running the plugin need Node 20 or newer; rebuilding
29
+ `client.js` from `src/client/**` needs Node `^22.18` or `>=24.11`, and the
30
+ published package already contains the compiled file, so an ordinary upgrade
31
+ never runs the build.
32
+
33
+ ## From cvc-catalog-sync-plugin 1.0.0
34
+
35
+ 1. Update the package to `2.0.0`:
36
+
37
+ ```text
38
+ update the npm bundle cvc-catalog-sync-plugin
39
+ ```
40
+
41
+ or, by hand, change the dependency in
42
+ `~/.dsh/profiles/<profile>/package.json` from `^1.0.0` to `^2.0.0` and let the
43
+ profile install it.
44
+
45
+ 2. Leave the row id alone. The row is `cvc-catalog-sync`, provided by the bundle
46
+ patch; 2.0.0 inserts the same id with the three switches turned on. Nothing in
47
+ the profile has to be renamed.
48
+
49
+ 3. Start DSH, then open **Settings → CVC**. The page reads both configuration
50
+ shapes. A 1.0.0 row shows the hint that the stored configuration is in the 1.x
51
+ shape (`GET /cvc/state` reports `configShape: 'legacy'`).
52
+
53
+ 4. Press **Save** once. This is the migration: the page builds the grouped config
54
+ from the flat keys and writes it back through `PUT /cvc/config`. The flat keys
55
+ (`entryId`, `provider`, `baseURL`, `apiKeyEnv`, `installerUrls`, `autoSync`,
56
+ `intervalHours`, `startupDelayMs`, `minModelRatio`, `keepModels`,
57
+ `syncAllowlist`, `allowlistEntryId`, `levelsCacheMinutes`, `timeoutMs`) are
58
+ accepted by the host as deprecated fields, so nothing is lost if you keep them
59
+ in the file — but after the save they are no longer needed, and the page
60
+ removes them on the next write.
61
+
62
+ 5. Check the switches. Catalog sync, model coefficients and balance are on by
63
+ default. Coefficients and balance need the same `cheapvibecode.ru` route the
64
+ catalog sync already used; there is nothing else to configure.
65
+
66
+ 6. Old HTTP routes are gone. `/cvc-catalog-sync/*` is not served in 2.0.0; the
67
+ page and any script of yours must use `/cvc/*`. A browser tab left open from
68
+ 1.0.0 will show an empty settings page until the tab is reloaded.
69
+
70
+ 7. If you had extra keys in the row from 1.0.0 that the new schema does not know
71
+ (for example `timeoutMs` is now inside `providers`), they are preserved by the
72
+ page on save: the form writes only the fields it owns and keeps the rest of the
73
+ row. The host's schema still normalises the row, so an unknown key is visible
74
+ in `GET /cvc/state` but does not break the load.
75
+
76
+ ## From the two private plugins
77
+
78
+ This path is for a profile that has `cvc-balance-plugin` (1.1.0) and/or
79
+ `cvc-model-coeff-plugin` (1.0.0). Both are archived; their functions live in this
80
+ package now.
81
+
82
+ 1. Install `cvc-catalog-sync-plugin@2.0.0` as usual. If `cvc-catalog-sync-plugin`
83
+ was not installed, this is a fresh install: add the package to
84
+ `~/.dsh/profiles/<profile>/package.json` and to `dsh.profile.bundles`, or ask
85
+ the DSH agent to install the npm bundle.
86
+ 2. Remove the two old packages from the profile:
87
+
88
+ ```sh
89
+ dsh plugin --profile <profile> remove cvc-balance-plugin
90
+ dsh plugin --profile <profile> remove cvc-model-coeff-plugin
91
+ ```
92
+
93
+ This removes the dependency and the row of each plugin from the bundle list.
94
+ If a row was written by hand into `cordis.patch.yml`, delete it there as well:
95
+ look for `id: cvc-balance` and `id: cvc-model-coeff`.
96
+ 3. Remove the `allowBuilds` entries of those two packages from
97
+ `pnpm-workspace.yaml` of the profile. They were needed because the private
98
+ packages built `lib/` through `prepare`; this package ships its compiled
99
+ client half and runs no build script on install, so it never asks for that
100
+ permission. Leaving an unused entry is harmless, removing it is cleaner.
101
+ 4. Restart DSH once, then hard-reload the tab (`Ctrl+Shift+R`). The old browser
102
+ halves are unmounted with their packages; the new button and badges are mounted
103
+ by this package.
104
+ 5. Check that nothing is duplicated. If two balance buttons or two badges appear,
105
+ a row of the old plugin is still in the profile patch: `grep` the patch for
106
+ `cvc-balance` / `cvc-model-coeff` and remove those rows, then restart.
107
+ 6. `cvc-model-coeff-plugin` had no settings page; its only parameter is now
108
+ **Coefficients → Badge refresh, minutes** (`coefficients.refreshMinutes`,
109
+ default 10) and **Show fast mode** (`coefficients.showFast`).
110
+ `cvc-balance-plugin` had no settings page either; its behaviour is now
111
+ **Balance → Balance refresh, seconds** (`balance.refreshSeconds`, default 0 —
112
+ only on demand) and **Show spend since the last reading**
113
+ (`balance.showDelta`).
114
+
115
+ ## Migration table
116
+
117
+ | 1.x key | 2.0.0 location | Note |
118
+ | --- | --- | --- |
119
+ | `entryId` | `providers.entryId` | patch row that owns the provider routes |
120
+ | `provider` | `catalog.provider` | route key whose `models` are written |
121
+ | `baseURL` | `providers.baseURL` | also the base of the balance request |
122
+ | `apiKeyEnv` | `providers.apiKeyEnv` | fallback name when the route has none of its own |
123
+ | `timeoutMs` | `providers.timeoutMs` | default changed from 30000 to 20000 |
124
+ | `autoSync` | `catalog.autoSync` | |
125
+ | `intervalHours` | `catalog.intervalHours` | 0 turns the timer off |
126
+ | `startupDelayMs` | `catalog.startupDelayMs` | |
127
+ | `minModelRatio` | `catalog.minModelRatio` | |
128
+ | `keepModels` | `catalog.keepModels` | |
129
+ | `installerUrls` | `catalog.installerUrls` | |
130
+ | `syncAllowlist` | `catalog.syncAllowlist` | |
131
+ | `allowlistEntryId` | `catalog.allowlistEntryId` | |
132
+ | `levelsCacheMinutes` | `catalog.levelsCacheMinutes` | |
133
+ | — | `features.catalogSync` | new, default `true` |
134
+ | — | `features.coefficients` | new, default `true` |
135
+ | — | `features.balance` | new, default `true` |
136
+ | — | `providers.match` | new, default `['cheapvibecode.ru']` |
137
+ | — | `coefficients.refreshMinutes` | new, default 10 |
138
+ | — | `coefficients.showFast` | new, default `true` |
139
+ | — | `balance.refreshSeconds` | new, default 0 (on demand only) |
140
+ | — | `balance.showDelta` | new, default `true` |
141
+
142
+ The defaults are listed in [ARCHITECTURE.md](ARCHITECTURE.md) under
143
+ "Configuration" and in the README. A value equal to the default is not written
144
+ into the patch by the settings page, so the patch stays short.
145
+
146
+ ## Check list
147
+
148
+ 1. `GET /cvc/health` answers `{"ok":true,"version":"2.0.0"}`.
149
+ 2. `GET /cvc/state` answers with `features` all `true` and `configShape: 'v2'`.
150
+ 3. **Settings → CVC** opens, shows three switches and no unsaved-changes marker.
151
+ 4. The model picker shows `×N` badges on CheapVibeCode rows and none on other
152
+ providers' rows.
153
+ 5. The sidebar footer has a **CVC balance** button; the dot is green when the
154
+ provider answers, and the panel shows the balance after **Refresh**.
155
+ 6. **Check catalog** in the settings page returns a diff with a non-zero catalog
156
+ count and the level source (`installer` or `cache`), and writes nothing.
157
+ 7. Only one row per function exists in `cordis.patch.yml`: `cvc-catalog-sync`,
158
+ and no `cvc-balance` / `cvc-model-coeff`.
159
+
160
+ ## Rollback
161
+
162
+ 1. Stop DSH.
163
+ 2. Restore the patch copy taken before the upgrade:
164
+
165
+ ```powershell
166
+ Copy-Item ~\.dsh\profiles\<profile>\cordis.patch.yml.bak-before-2.0.0 ~\.dsh\profiles\<profile>\cordis.patch.yml -Force
167
+ ```
168
+
169
+ 3. Set the dependency back to `^1.0.0` and, if needed, reinstall the two private
170
+ packages.
171
+ 4. Start DSH.
172
+
173
+ The models the plugin wrote stay in the patch until the old version or the next
174
+ run rewrites them; they are ordinary `llm-pi-ai` model entries and DSH accepts
175
+ them either way.
176
+
177
+ ---
178
+
179
+ # Обновление до 2.0.0
180
+
181
+ Версия 2.0.0 превращает одну функцию (синхронизацию каталога) в три отключаемые
182
+ функции (синхронизация каталога, коэффициенты цен, баланс) и вбирает в себя два
183
+ плагина, которые раньше ставились отдельно. Имя пакета, id строки и пространство
184
+ имён локали не меняются, поэтому существующий профиль продолжает работать;
185
+ меняются форма конфигурации строки и набор HTTP-маршрутов.
186
+
187
+ Путей обновления два:
188
+
189
+ - [с cvc-catalog-sync-plugin 1.0.0](#с-cvc-catalog-sync-plugin-100);
190
+ - [с двух приватных плагинов](#с-двух-приватных-плагинов).
191
+
192
+ Оба заканчиваются списком проверки. Не пропускайте его: выключенная функция
193
+ молчит по своему устройству, и именно список проверки показывает, что все три
194
+ живы.
195
+
196
+ ## Перед началом
197
+
198
+ 1. Скопируйте профильный патч. Это единственное состояние, которое пишет
199
+ плагин, а профиль не под git:
200
+
201
+ ```powershell
202
+ Copy-Item ~\.dsh\profiles\<профиль>\cordis.patch.yml ~\.dsh\profiles\<профиль>\cordis.patch.yml.bak-before-2.0.0
203
+ ```
204
+
205
+ 2. Запомните работающую версию DSH (**Настройки → О программе** или версия в
206
+ заголовке окна). 2.0.0 поддерживает `>=0.2.2-rc.3 <0.4.0`.
207
+ Установка из npm и работа плагина требуют Node 20 или новее; пересборка
208
+ `client.js` из `src/client/**` — Node `^22.18` или `>=24.11`, но собранный
209
+ файл уже лежит в опубликованном пакете, поэтому обычное обновление сборку не
210
+ запускает.
211
+
212
+ ## С cvc-catalog-sync-plugin 1.0.0
213
+
214
+ 1. Обновите пакет до `2.0.0`:
215
+
216
+ ```text
217
+ update the npm bundle cvc-catalog-sync-plugin
218
+ ```
219
+
220
+ или вручную: поменяйте зависимость в
221
+ `~/.dsh/profiles/<профиль>/package.json` с `^1.0.0` на `^2.0.0` и дайте
222
+ профилю установить её.
223
+
224
+ 2. Id строки не трогайте. Строка — `cvc-catalog-sync`, её предоставляет патч
225
+ бандла; 2.0.0 вставляет тот же id с тремя включёнными переключателями. В
226
+ профиле ничего переименовывать не нужно.
227
+
228
+ 3. Запустите DSH и откройте **Настройки → CVC**. Страница читает обе формы
229
+ конфигурации. Строка от 1.0.0 показывает подсказку, что сохранённый конфиг в
230
+ форме 1.x (`GET /cvc/state` сообщает `configShape: 'legacy'`).
231
+
232
+ 4. Нажмите **Сохранить** один раз. Это и есть миграция: страница собирает
233
+ группированный конфиг из плоских ключей и записывает его обратно через
234
+ `PUT /cvc/config`. Плоские ключи (`entryId`, `provider`, `baseURL`,
235
+ `apiKeyEnv`, `installerUrls`, `autoSync`, `intervalHours`, `startupDelayMs`,
236
+ `minModelRatio`, `keepModels`, `syncAllowlist`, `allowlistEntryId`,
237
+ `levelsCacheMinutes`, `timeoutMs`) хост принимает как устаревшие поля,
238
+ поэтому ничего не теряется, если оставить их в файле, — но после сохранения
239
+ они больше не нужны, и страница убирает их при следующей записи.
240
+
241
+ 5. Проверьте переключатели. Синхронизация каталога, коэффициенты моделей и
242
+ баланс включены по умолчанию. Коэффициентам и балансу нужен тот же маршрут
243
+ `cheapvibecode.ru`, которым уже пользовалась синхронизация; больше настраивать
244
+ нечего.
245
+
246
+ 6. Старые HTTP-маршруты удалены. `/cvc-catalog-sync/*` в 2.0.0 не обслуживается;
247
+ страница и ваши скрипты должны обращаться к `/cvc/*`. Вкладка браузера,
248
+ оставшаяся от 1.0.0, покажет пустую страницу настроек, пока её не перезагрузить.
249
+
250
+ 7. Если в строке от 1.0.0 остались лишние ключи, которых новая схема не знает
251
+ (например, `timeoutMs` теперь внутри `providers`), страница сохранит их: форма
252
+ пишет только свои поля и оставляет остальное содержимое строки. Схема хоста
253
+ строку всё равно нормализует, поэтому незнакомый ключ виден в
254
+ `GET /cvc/state`, но загрузку не ломает.
255
+
256
+ ## С двух приватных плагинов
257
+
258
+ Этот путь — для профиля, где стоят `cvc-balance-plugin` (1.1.0) и/или
259
+ `cvc-model-coeff-plugin` (1.0.0). Оба заархивированы; их функции теперь в этом
260
+ пакете.
261
+
262
+ 1. Поставьте `cvc-catalog-sync-plugin@2.0.0` обычным способом. Если
263
+ `cvc-catalog-sync-plugin` не был установлен, это чистая установка: добавьте
264
+ пакет в `~/.dsh/profiles/<профиль>/package.json` и в `dsh.profile.bundles` либо
265
+ попросите агента DSH поставить npm-бандл.
266
+ 2. Удалите два старых пакета из профиля:
267
+
268
+ ```sh
269
+ dsh plugin --profile <профиль> remove cvc-balance-plugin
270
+ dsh plugin --profile <профиль> remove cvc-model-coeff-plugin
271
+ ```
272
+
273
+ Команда убирает зависимость и строку плагина из списка бандлов. Если строка
274
+ была вписана в `cordis.patch.yml` руками, удалите её и там: ищите
275
+ `id: cvc-balance` и `id: cvc-model-coeff`.
276
+ 3. Уберите записи `allowBuilds` этих двух пакетов из `pnpm-workspace.yaml`
277
+ профиля. Они были нужны, потому что приватные пакеты собирали `lib/` через
278
+ `prepare`; этот пакет поставляет собранную браузерную половину и никакого
279
+ скрипта сборки при установке не запускает, поэтому такого разрешения не
280
+ просит. Оставленная без дела запись безвредна, удалённая — чище.
281
+ 4. Перезапустите DSH один раз, затем сделайте жёсткую перезагрузку вкладки
282
+ (`Ctrl+Shift+R`). Старые браузерные половины снимаются вместе со своими
283
+ пакетами; новую кнопку и бейджи монтирует этот пакет.
284
+ 5. Проверьте, что ничего не задвоилось. Если видите две кнопки баланса или два
285
+ бейджа, в профильном патче осталась строка старого плагина: найдите в патче
286
+ `cvc-balance` / `cvc-model-coeff`, удалите эти строки и перезапустите DSH.
287
+ 6. У `cvc-model-coeff-plugin` страницы настроек не было; его единственный
288
+ параметр теперь — **Коэффициенты → Обновление бейджей, минут**
289
+ (`coefficients.refreshMinutes`, по умолчанию 10) и **Показывать быстрый
290
+ режим** (`coefficients.showFast`). У `cvc-balance-plugin` страницы настроек
291
+ тоже не было; его поведение теперь — **Баланс → Обновление баланса, секунд**
292
+ (`balance.refreshSeconds`, по умолчанию 0 — только по запросу) и
293
+ **Показывать расход с прошлого замера** (`balance.showDelta`).
294
+
295
+ ## Таблица переноса
296
+
297
+ | Ключ 1.x | Место в 2.0.0 | Примечание |
298
+ | --- | --- | --- |
299
+ | `entryId` | `providers.entryId` | строка патча, которой принадлежат маршруты провайдеров |
300
+ | `provider` | `catalog.provider` | ключ маршрута, чьи `models` записываются |
301
+ | `baseURL` | `providers.baseURL` | он же база запроса баланса |
302
+ | `apiKeyEnv` | `providers.apiKeyEnv` | запасное имя, если у маршрута нет своего ключа |
303
+ | `timeoutMs` | `providers.timeoutMs` | умолчание изменилось с 30000 на 20000 |
304
+ | `autoSync` | `catalog.autoSync` | |
305
+ | `intervalHours` | `catalog.intervalHours` | 0 выключает таймер |
306
+ | `startupDelayMs` | `catalog.startupDelayMs` | |
307
+ | `minModelRatio` | `catalog.minModelRatio` | |
308
+ | `keepModels` | `catalog.keepModels` | |
309
+ | `installerUrls` | `catalog.installerUrls` | |
310
+ | `syncAllowlist` | `catalog.syncAllowlist` | |
311
+ | `allowlistEntryId` | `catalog.allowlistEntryId` | |
312
+ | `levelsCacheMinutes` | `catalog.levelsCacheMinutes` | |
313
+ | — | `features.catalogSync` | новое, по умолчанию `true` |
314
+ | — | `features.coefficients` | новое, по умолчанию `true` |
315
+ | — | `features.balance` | новое, по умолчанию `true` |
316
+ | — | `providers.match` | новое, по умолчанию `['cheapvibecode.ru']` |
317
+ | — | `coefficients.refreshMinutes` | новое, по умолчанию 10 |
318
+ | — | `coefficients.showFast` | новое, по умолчанию `true` |
319
+ | — | `balance.refreshSeconds` | новое, по умолчанию 0 (только по запросу) |
320
+ | — | `balance.showDelta` | новое, по умолчанию `true` |
321
+
322
+ Умолчания перечислены в [ARCHITECTURE.md](ARCHITECTURE.md), раздел
323
+ «Конфигурация», и в README. Значение, равное умолчанию, страница настроек в патч
324
+ не пишет, поэтому патч остаётся коротким.
325
+
326
+ ## Список проверки
327
+
328
+ 1. `GET /cvc/health` отвечает `{"ok":true,"version":"2.0.0"}`.
329
+ 2. `GET /cvc/state` отвечает с `features` все `true` и `configShape: 'v2'`.
330
+ 3. **Настройки → CVC** открывается, показывает три переключателя и не показывает
331
+ несохранённых изменений.
332
+ 4. В выборе модели у строк CheapVibeCode есть бейджи `×N`, у строк других
333
+ провайдеров их нет.
334
+ 5. В футере сайдбара есть кнопка **CVC баланс**; точка зелёная, когда провайдер
335
+ отвечает, а панель после **Обновить** показывает остаток.
336
+ 6. **Проверить каталог** на странице настроек возвращает разницу с ненулевым
337
+ числом моделей и источником уровней (`installer` или `cache`) и ничего не
338
+ записывает.
339
+ 7. В `cordis.patch.yml` на каждую функцию приходится по одной строке:
340
+ `cvc-catalog-sync`, и нет `cvc-balance` / `cvc-model-coeff`.
341
+
342
+ ## Откат
343
+
344
+ 1. Остановите DSH.
345
+ 2. Восстановите копию патча, снятую до обновления:
346
+
347
+ ```powershell
348
+ Copy-Item ~\.dsh\profiles\<профиль>\cordis.patch.yml.bak-before-2.0.0 ~\.dsh\profiles\<профиль>\cordis.patch.yml -Force
349
+ ```
350
+
351
+ 3. Верните зависимость на `^1.0.0` и, если нужно, переустановите два приватных
352
+ пакета.
353
+ 4. Запустите DSH.
354
+
355
+ Записанные плагином модели остаются в патче, пока старая версия или следующий
356
+ прогон их не перепишут; это обычные записи моделей `llm-pi-ai`, и DSH принимает
357
+ их в любом случае.