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,965 @@
1
+ # Architecture
2
+
3
+ This document describes how `cvc-catalog-sync-plugin` 2.0.0 is put together: what
4
+ runs on the host, what runs in the browser, where a decision is made, and why the
5
+ pieces are split the way they are. It is written for someone who has to change the
6
+ plugin, not for the end user: the user-facing text is in [README.md](../README.md).
7
+
8
+ ## One package, two halves, three functions
9
+
10
+ The plugin is a DSH bundle with a host half and a browser half in one npm package.
11
+
12
+ - The **host half** is plain ESM (`index.js`, `lib/**`). It is loaded by the DSH
13
+ process, registers HTTP routes on the DSH web server, reads the provider
14
+ configuration and the profile patch, and is the only place that ever sees an
15
+ API key.
16
+ - The **browser half** is compiled from `src/client/**` into `client.js`. It
17
+ renders the three surfaces — the settings page, the coefficient badges, the
18
+ balance button and panel — and talks to the host only through the plugin's own
19
+ HTTP routes.
20
+ - The **three functions** on top of that split are catalog sync, coefficients and
21
+ balance. They are independent: each one can be off while the others work, and
22
+ the settings page is the switchboard that stays present with all three off.
23
+
24
+ The bundle patch `cordis.patch.yml` inserts one row, `cvc-catalog-sync`, with the
25
+ three switches on. That row is also the configuration surface: the settings page
26
+ edits the same row through `ctx.configEditor`.
27
+
28
+ ## Module map
29
+
30
+ ```text
31
+ index.js apply(); the Config schema; feature gating;
32
+ handling of loader/volatile-update
33
+ lib/config.js Config (schemastery), normalizeConfig(v1 + v2),
34
+ validateConfigInput
35
+ lib/providers.js resolveRoutes(ctx, cfg) -> CVC routes on the
36
+ llm-pi-ai row; resolveKey(ctx, ref)
37
+ lib/cvc-api.js fetchModels, fetchBalance, fetchLevels; timeouts,
38
+ error mapping, no key in messages
39
+ lib/cache.js createCatalogCache({ client, ttlMs, now });
40
+ get / peek / clear
41
+ lib/catalog-build.js buildModels(catalog, levels, options): pure logic
42
+ ported from 1.0.0
43
+ lib/catalog-sync.js plan and apply: diff, shrink guard, patch write,
44
+ allowlist, the cvc_catalog tool, the timer
45
+ lib/coefficients.js indexCoefficients(catalog), GET /cvc/coefficients
46
+ lib/balance.js snapshot, spend delta, GET /cvc/balance,
47
+ the cvc_balance tool
48
+ lib/http.js JSON helpers, 64 KB body limit, same-origin fence,
49
+ prefix route registration
50
+ lib/state.js GET /cvc/state, PUT /cvc/config, lastRun/status
51
+ lib/CONTRACT.js the frozen contract the three feature modules and
52
+ the client follow (documentation in code)
53
+ client.js compiled browser bundle (never edited by hand)
54
+ src/client/index.js apply() of the browser half: locale, styles,
55
+ feature toggles, slot registrations
56
+ src/client/store.js {features, config, status, lastRun}; initial load
57
+ from GET /cvc/state; subscribe / refresh / save / run
58
+ src/client/settings.js the settings page (React): switches, groups,
59
+ buttons, last-run block
60
+ src/client/config-form.js pure form model: field paths, defaults, drafts,
61
+ v1 -> v2 reading, validation
62
+ src/client/coefficients.js DOM observer and the ×N badges
63
+ src/client/balance.js sidebar button and the draggable panel
64
+ src/client/panel-pos.js pure part of the panel: position clamping and the
65
+ status dot state
66
+ src/client/css.js all styles under the .cvc2- prefix
67
+ src/client/i18n.js en/ru dictionaries of the page and surfaces
68
+ tools/build-client.mjs builds client.js (tsdown + the __ModuleLoader__
69
+ wrapper)
70
+ tools/assert-pack.mjs checks the contents of the npm tarball
71
+ test/*.mjs node --test suites
72
+ ```
73
+
74
+ ## Boot and gating
75
+
76
+ `apply(ctx, config)` in `index.js` does the following:
77
+
78
+ 1. Reads and validates the row configuration through the `Config` schema.
79
+ Every field is declared `.volatile()`, so DSH applies a changed row through
80
+ `loader/volatile-update` instead of restarting the plugin.
81
+ 2. Computes the feature set from `features.*` and mounts exactly the functions
82
+ that are on:
83
+ - catalog sync registers its timer, the `cvc_catalog` tool, `POST /cvc/run`
84
+ and the catalog parts of `GET /cvc/state`;
85
+ - coefficients registers `GET /cvc/coefficients` and the shared cache client;
86
+ - balance registers `GET /cvc/balance` and the `cvc_balance` tool.
87
+ 3. On a volatile update, normalises the new row and remounts the functions so
88
+ their timers and routes see the new values. A function that goes off releases
89
+ its routes, timer, tool and cache subscription in the same tick; its route
90
+ starts answering `404`. When `providers` or `catalog` changed, the shared
91
+ catalog cache is cleared, because the route or the key may be different.
92
+
93
+ The host half declares `inject = ['configEditor', 'tools', 'credentials']`, so
94
+ Loader defers the plugin instead of crashing when one of those services is not
95
+ up yet. The web server is injected separately and optionally: in a profile
96
+ without it the plugin still runs, but only its tools work and the HTTP routes are
97
+ not attached.
98
+
99
+ The settings page is not gated. It is registered on the browser side
100
+ unconditionally, because it is the only place where the switches can be turned
101
+ back on. `GET /cvc/state` and `PUT /cvc/config` therefore exist even when all
102
+ three functions are off; `POST /cvc/run` exists only with catalog sync on.
103
+
104
+ "What a disabled function does not do" is a testable contract, not a convention:
105
+ `test/gating.test.mjs` asserts that a disabled function registers no route, no
106
+ timer and no tool, and that a volatile update mounts and unmounts it.
107
+
108
+ ## Configuration
109
+
110
+ The schema has five groups. Defaults:
111
+
112
+ | Group | Field | Default | Meaning |
113
+ | --- | --- | --- | --- |
114
+ | `features` | `catalogSync` | `true` | catalog sync on |
115
+ | | `coefficients` | `true` | badges on |
116
+ | | `balance` | `true` | balance on |
117
+ | `providers` | `match` | `['cheapvibecode.ru']` | host names that identify a CVC provider |
118
+ | | `entryId` | `'llm-pi-ai'` | patch row that owns the provider routes |
119
+ | | `apiKeyEnv` | `'CVC_DEEPSEEK_API_KEY'` | fallback credential name |
120
+ | | `baseURL` | `'https://ru.cheapvibecode.ru/v1'` | base used when the row has no route of its own |
121
+ | | `timeoutMs` | `20000` | per-request timeout |
122
+ | `catalog` | `provider` | `'cheapvibecode'` | route key whose `models` are written |
123
+ | | `autoSync` | `true` | startup run plus interval runs |
124
+ | | `intervalHours` | `24` | `0` turns the timer off |
125
+ | | `startupDelayMs` | `5000` | pause before the first automatic run |
126
+ | | `minModelRatio` | `0.8` | refuse a catalog below this share of the current count |
127
+ | | `keepModels` | `[]` | ids kept even when the catalog drops them |
128
+ | | `installerUrls` | `/idhw`, `/idhl` | level maps, first reachable wins |
129
+ | | `syncAllowlist` | `true` | keep `allowedModels` aligned |
130
+ | | `allowlistEntryId` | `'subagent-model-selection-settings'` | row that holds `allowedModels` |
131
+ | | `levelsCacheMinutes` | `360` | how long the level map is reused |
132
+ | `coefficients` | `refreshMinutes` | `10` | badge re-read interval |
133
+ | | `showFast` | `true` | include the fast multiplier in the tooltip |
134
+ | `balance` | `refreshSeconds` | `0` | `0` = on demand only; 15 or more = timer while the panel is open |
135
+ | | `showDelta` | `true` | show the spend between two readings |
136
+
137
+ Two behaviours sit in `lib/config.js` rather than in the consumers:
138
+
139
+ - **Legacy normalisation.** The flat 1.x keys (`entryId`, `provider`, `baseURL`,
140
+ `apiKeyEnv`, `installerUrls`, `autoSync`, `intervalHours`, `startupDelayMs`,
141
+ `minModelRatio`, `keepModels`, `syncAllowlist`, `allowlistEntryId`,
142
+ `levelsCacheMinutes`, `timeoutMs`) stay in the schema as optional deprecated
143
+ fields. `normalizeConfig` folds them into the groups, so a profile written for
144
+ 1.0.0 loads without edits. `GET /cvc/state` reports `configShape: 'legacy'`
145
+ when any of them was the source, and the settings page suggests saving once.
146
+ - **Validation.** `validateConfigInput` checks the values the settings page
147
+ sends and returns field names; `PUT /cvc/config` answers `400` with `fields`
148
+ and does not write. The form validates the obvious cases before sending, but
149
+ the host is the authority.
150
+
151
+ ## Provider resolution
152
+
153
+ `lib/providers.js` answers one question: which `cheapvibecode.ru` routes exist on
154
+ the `llm-pi-ai` row, and how is each one's key named?
155
+
156
+ Resolution reads the rows of the profile through `ctx.configEditor.entries()`
157
+ and looks for the row named by `providers.entryId` (default `llm-pi-ai`) in three
158
+ passes: by exact id, by the adapter package name
159
+ (`@deepseek-ai/dsh-llm-pi-ai`), and by id with a group prefix (`include:llm-pi-ai`
160
+ and the like). A candidate is accepted only when it actually carries a
161
+ non-empty `providers` object, so a duplicate row with `config: {}` cannot end the
162
+ search. From the accepted row it keeps the routes whose `baseURL` is `https` and
163
+ whose parsed hostname equals a host from `providers.match` or ends with
164
+ `.host` — `cheapvibecode.ru` covers `ru.cheapvibecode.ru`, while a lookalike such as
165
+ `cheapvibecode.ru.example.com` or a plain-`http` URL never matches. A route added
166
+ later in the DSH settings appears on the next read without a plugin restart,
167
+ because the lookup runs against the live entries.
168
+
169
+ `apiKeyFor(route, cfg)` returns the route's own `apiKeyEnv` when it has one and
170
+ the global `providers.apiKeyEnv` otherwise. `resolveKey(ctx, ref)` resolves that
171
+ name through `ctx.credentials.resolve` and returns the value or an empty string;
172
+ the caller turns an empty string into a `no-key` error, so the plugin reports "API
173
+ key is not configured for this provider" instead of sending an empty `Bearer`.
174
+ Nothing else is accepted: the plugin does not read `.env` or the process
175
+ environment itself, that is the credential service's job.
176
+
177
+ The shared catalog cache targets `catalog.provider`. `pickRoute(routes, key)`
178
+ prefers the route whose key matches and falls back to the first discovered CVC
179
+ route when the key names nothing, so the cache still has a catalog to serve.
180
+ Catalog sync itself addresses `catalog.provider` directly: a row whose
181
+ `provider` names no CVC route fails the run with `no route "<key>" is
182
+ configured`, rather than writing models into a route the user did not name.
183
+
184
+ All three functions use this one module. Before 2.0.0 the catalog plugin, the
185
+ coefficient plugin and the balance plugin each had their own discovery code, and
186
+ a fix in one did not reach the others.
187
+
188
+ ## Shared catalog cache
189
+
190
+ `lib/cache.js` is a small TTL cache around `fetchModels`, with one instance per
191
+ plugin process:
192
+
193
+ - `get({ force })` returns the cached catalog, or fetches it when the entry is
194
+ missing, older than `ttlMs`, or `force` is set;
195
+ - concurrent callers share one in-flight request instead of starting two;
196
+ - a failed fetch does not drop the last good payload: `get` keeps serving it with
197
+ `stale: true` and the error text, while the next caller retries. When there is
198
+ no snapshot yet, the error is thrown;
199
+ - `refresh()` is `get({ force: true })`; `peek()` reads without fetching (used by
200
+ status reporting), and `clear()` drops the entry and bumps a generation counter,
201
+ so an answer that is still in flight cannot write itself back;
202
+ - `ttlMs` is a number or a function of the current configuration, so the cache
203
+ lifetime follows `coefficients.refreshMinutes` without recreating the cache;
204
+ - `now` is injectable, so TTL behaviour is tested without sleeping.
205
+
206
+ Catalog sync and coefficients read the same cache. That is the point of the
207
+ module: one `GET /v1/models` populates both the `models` list written into the
208
+ patch and the multiplier map drawn in the picker. A badge refresh that lands
209
+ while the cache is fresh costs no catalog request at all.
210
+
211
+ ## HTTP layer
212
+
213
+ `lib/http.js` owns the transport rules so that every route answers the same way:
214
+
215
+ | Rule | Answer |
216
+ | --- | --- |
217
+ | path outside the `/cvc` prefix | `404` |
218
+ | route of a disabled function | `404` |
219
+ | `Sec-Fetch-Site: cross-site` | `403` |
220
+ | `PUT` or `POST` without `application/json` | `415` |
221
+ | body over 64 KB | `413` |
222
+ | `POST /cvc/run` refused by the shrink guard or by a stale catalog | `409` with the run result |
223
+ | wrong method on a known path | `405` with an `allow` header |
224
+ | malformed JSON in the body | `400` |
225
+
226
+ The order matters: the fence runs before the path is looked at, so a cross-site
227
+ request never learns whether a route exists, and the content-type check runs
228
+ before dispatch, so a write cannot reach a handler without being declared JSON.
229
+ `409` on `/cvc/run` is a decision, not a failure: the guard refused to write a
230
+ catalog that is smaller than `minModelRatio` of the current count, or the catalog
231
+ is stale. Other run failures (no route, no key, network) answer `200` with
232
+ `ok: false` and the diagnostic body, the same shape the `cvc_catalog` tool
233
+ returns.
234
+
235
+ Routes are registered as one prefix (`/cvc`) on `ctx.webServer.attach`, and the
236
+ plugin keeps an internal table of sub-paths. One prefix registration per plugin is
237
+ deliberate: two `webServer.register` calls for the same prefix conflict, and with a
238
+ private table a disabled function simply removes its own sub-path and answers
239
+ `404` without touching the web server. `index.js` does not create a server. Answers carry `cache-control: no-store` and
240
+ `x-content-type-options: nosniff`. `lib/http.js` also exposes the JSON helper and
241
+ the body reader used by `lib/state.js`.
242
+
243
+ Rules the HTTP layer and `lib/cvc-api.js` keep everywhere:
244
+
245
+ - an unset credential is an error about the name (`credential "…" is not
246
+ configured`), never an empty `Bearer`;
247
+ - a `401` or `403` from the provider is raised as `CvcApiError` with code
248
+ `unauthorized` and the provider's own message, redacted;
249
+ - a network failure, a timeout and a broken JSON body are three different errors
250
+ with three different codes; none of them contains the key.
251
+
252
+ ## Provider API calls
253
+
254
+ `lib/cvc-api.js` is the only module that talks to the provider:
255
+
256
+ | Function | Request | Answer |
257
+ | --- | --- | --- |
258
+ | `fetchModels({ baseURL, key, timeoutMs })` | `GET {baseURL}/models` | the model list, from `{ data: [...] }` or a bare array; rows without a string `id` are dropped |
259
+ | `fetchBalance({ baseURL, key, timeoutMs })` | `GET {apiRoot}/v1/balance` | `{ units }` from `token_balance` |
260
+ | `fetchLevels({ urls, timeoutMs })` | `GET <installerUrl>`, no key, each URL in turn | the `reasoningLevels` map and the URL that answered |
261
+
262
+ The installer is tried in the order of `catalog.installerUrls`, and the first one
263
+ that answers with a parseable map wins. If none does, the error lists, per URL,
264
+ whether it timed out, failed at the network, answered a non-2xx status, returned an
265
+ unreadable body, or carried no `reasoningLevels` literal.
266
+
267
+ `apiRoot(baseURL)` strips a trailing `/v1`, because a route is configured with the
268
+ OpenAI-compatible base (`…/v1`) while the balance endpoint lives one level up.
269
+ `redact(text, secret)` replaces the key with `***` in every message that can carry
270
+ provider text.
271
+
272
+ ## The route contract
273
+
274
+ | Method | Path | Body | Answer |
275
+ | --- | --- | --- | --- |
276
+ | `GET` | `/cvc/state` | — | `{version, features, config, configShape, status, lastRun, patchPath, rowId}` |
277
+ | `PUT` | `/cvc/config` | `{config}` | `{ok, config, features}`, or `400` with `fields` |
278
+ | `POST` | `/cvc/run` | `{action: 'plan' \| 'apply', force?}` | the run result |
279
+ | `GET` | `/cvc/coefficients` | — | `{models: [{id, displayName, multiplier, fastMultiplier, contextWindow}], providers, fetchedAt, stale}` |
280
+ | `GET` | `/cvc/balance` | — | `{providers: [{provider, displayName, baseURL, apiKeyEnv, keySet, balanceUnits, spentSinceLast, balanceError}], fetchedAt}` |
281
+ | `GET` | `/cvc/health` | — | `{ok, version}` |
282
+
283
+ `PUT /cvc/config` and `POST /cvc/run` are writes: the first writes the plugin row,
284
+ the second writes the models and the allowlist. Both go through
285
+ `ctx.configEditor.edit()`, which preserves the rest of the patch file, its
286
+ comments and other plugins' rows. Saving the panel loses nothing it does not own:
287
+ `buildState` reports the effective configuration (the bundle layer with the profile
288
+ override on top) and `PUT` writes the row back only through that editor; a save
289
+ whose value equals the schema defaults removes the override instead of writing a
290
+ copy of the defaults into the patch.
291
+
292
+ ## Where each decision is made
293
+
294
+ | Decision | Module | Why there |
295
+ | --- | --- | --- |
296
+ | is a function on? | `index.js` | the switch is a plugin-level fact, and mounting is a plugin-level effect |
297
+ | which routes are CVC? | `lib/providers.js` | one lookup for three functions; the alternative was three copies |
298
+ | how is a model built? | `lib/catalog-build.js` | pure function, fed by catalog + levels + options; testable without DSH |
299
+ | is the catalog too small? | `lib/catalog-sync.js` | the guard needs the current list, which only the apply path reads |
300
+ | what does a badge say? | `lib/coefficients.js` (host) and `src/client/coefficients.js` (drawing) | the host decides the number, the browser decides the pixel |
301
+ | is a balance reading an expense? | `lib/balance.js` | the previous reading is process state, and only the host holds it |
302
+ | how does the page look? | `src/client/settings.js` + `css.js` + `i18n.js` | the browser half owns the rendering and the wording |
303
+
304
+ ## Catalog sync
305
+
306
+ A run is `plan` or `apply`; both build the same candidate list:
307
+
308
+ 1. `lib/cvc-api.js` fetches `{baseURL}/models` with the route's key and the
309
+ installer page (first reachable of `installerUrls`), then extracts the
310
+ `reasoningLevels` literal linearly — no backtracking regular expression on
311
+ downloaded text.
312
+ 2. `lib/catalog-build.js` turns each catalog row into an `llm-pi-ai` model:
313
+ `name` is the part of `display_name` after ` · `, `contextWindow` is
314
+ `context_window`, `maxTokens` is `min(max_output_tokens, contextWindow)`,
315
+ `input` gains `image` when the model accepts images, the `none` level becomes
316
+ `off: none`, and `gpt-image*` plus models without text output are skipped.
317
+ A field missing from the catalog falls back to the current patch entry, then
318
+ to a default, so a manual edit is not lost.
319
+ 3. `lib/catalog-sync.js` diffs the candidate list against the current models and
320
+ reports added / removed / changed.
321
+ 4. The shrink guard refuses an `apply` when the candidate count is below
322
+ `minModelRatio` of the current count, unless `force: true`.
323
+ 5. `apply` writes the models and, with `syncAllowlist`, the
324
+ `subagent-model-selection-settings.allowedModels` list. Both writes read the
325
+ current value inside the editor callback, so a concurrent edit is not
326
+ overwritten. The write happens only when something actually changed;
327
+ a second apply is a no-op.
328
+ 6. Timer runs are the same code path with `apply` and no `force`.
329
+
330
+ The `cvc_catalog` tool exposes `status`, `plan` and `apply`; `status` answers
331
+ from the in-process last-run record and does not touch the network. The tool is
332
+ registered only while catalog sync is mounted, so with the function off it is not
333
+ in the tool list at all.
334
+
335
+ ## Coefficients
336
+
337
+ `lib/coefficients.js` indexes the catalog into `{id → multiplier, fastMultiplier,
338
+ displayName, contextWindow}` and serves it on `GET /cvc/coefficients`. The answer
339
+ also carries the provider ids that own the cached catalog, because the browser
340
+ must not decorate a model id that belongs to another provider.
341
+
342
+ The browser half (`src/client/coefficients.js`) does not replace the model
343
+ selector. It watches the document for `[data-model-id]` nodes, reads
344
+ `data-provider-id` from the same node, and appends a `<span class="cvc2-badge">`
345
+ only when the provider is in the list and the model has a multiplier. Missing
346
+ multiplier means no badge — the plugin does not guess a price. The badge is
347
+ `pointer-events: none`, so clicks and keyboard selection stay with the selector.
348
+ The observer skips mutations inside its own badges, which is what keeps it from
349
+ looping; a `requestAnimationFrame` coalesces redraws while the user types in the
350
+ model search. Stopping the function disconnects the observer and removes every
351
+ badge it drew.
352
+
353
+ The slot `conversation.input.model.label` stays untouched: it is `single`, it is
354
+ already owned by the built-in badge, and a second registration would displace it.
355
+
356
+ ## Balance
357
+
358
+ `lib/balance.js` reads every CVC route's balance with `GET {apiRoot}/v1/balance`:
359
+
360
+ - `apiRoot` is the route's `baseURL` with a trailing `/v1` removed, so the
361
+ request goes to the host the route already names;
362
+ - `token_balance` becomes `balanceUnits`; `keySet` reports whether the credential
363
+ was found, never the value;
364
+ - one provider's failure is recorded in its own `balanceError` and does not stop
365
+ the other providers from answering;
366
+ - `spentSinceLast` is the drop between the previous and the current reading and
367
+ lives in the memory of the process, so it is lost on restart;
368
+ - the `cvc_balance` tool returns the last snapshot without spending a request. Its
369
+ rows are `{provider, displayName, keySet, balanceUnits}` — `keySet` is the
370
+ boolean, and neither `baseURL` nor `apiKeyEnv` is repeated there, because the
371
+ tool answers the agent rather than rendering a panel.
372
+
373
+ The browser panel draws the cards, the spend line, the status dot and the drag
374
+ handling. It stores its position in `localStorage` under `cvc:panel-pos`, not
375
+ `cvc-balance:panel-pos` — the old key belonged to the 1.1.0 panel, whose
376
+ coordinates can fall outside the viewport.
377
+
378
+ The `cvc_balance` tool is registered only while the balance function is mounted.
379
+ It speaks for the agent side; the panel is the human side. Coefficients register
380
+ no tool: the badges are read-only decoration, and there is nothing for a tool to
381
+ do.
382
+
383
+ ## The browser half
384
+
385
+ `src/client/index.js` registers four surfaces:
386
+
387
+ | Surface | Slot | Always on? |
388
+ | --- | --- | --- |
389
+ | settings page | `settings.section` (id `cvc`, order 25) | yes |
390
+ | settings icon | `settings.section.icon` | yes |
391
+ | bundle block | `plugins.bundle.config` (key = package name) | yes |
392
+ | balance button and panel | `sidebar.footer.action` (id `cvc-balance`, order 5) | only with `features.balance` |
393
+ | coefficient badges | DOM observer, no slot | only with `features.coefficients` |
394
+
395
+ The page is registered in two seats with the same component: the settings section
396
+ and the plugin page block. In the plugin list the block asks for `view: 'summary'`
397
+ and renders one line, because the full form does not fit there. The three feature
398
+ switches are buttons with `role="switch"` and `aria-checked`, so a screen reader
399
+ announces them as on/off controls rather than as buttons.
400
+
401
+ Status reads left to right as follows. The **last run** block under the buttons
402
+ shows the catalog size, the current and next model count, the level source, the
403
+ added / removed / changed models, allowlist changes, warnings and the patch path.
404
+ The balance dot is `warn` while a refresh is running, `err` when the request
405
+ failed and no provider row exists, neutral when no CVC route is configured at all,
406
+ `ok` when every provider returned a number, `warn` when only some did, and `err`
407
+ when none did.
408
+
409
+ `store.js` is the single client-side source of truth. It starts with the schema
410
+ defaults (all three functions on), loads `GET /cvc/state`, publishes changes to
411
+ subscribers, and updates itself from the answer of `PUT /cvc/config` and
412
+ `POST /cvc/run` without a second round trip. A feature change is detected by a
413
+ short key of the three booleans, which is what wakes the toggles that mount and
414
+ unmount the balance button and the badge observer. `refresh()` collapses
415
+ concurrent calls into one request: the page and the balance button may both ask.
416
+ `coefficients()` and `balance()` return `{ok, status, body, error}` instead of
417
+ throwing: a `404` from a function that was switched off a moment ago is an
418
+ expected answer, not an exception.
419
+
420
+ All class names live under `.cvc2-`. The prefix is deliberate: 1.0.0 used
421
+ `.cvc-sync`, the private plugins used `.cvc-coeff` and `.cvc-panel`, and a plugin
422
+ row left over during an upgrade must not inherit the new styles.
423
+
424
+ ## Why not Remote namespaces
425
+
426
+ The browser-side Remote table is generated when DSH is built, from the host
427
+ packages in `@deepseek-ai/dsh-api-remotes`. A third-party plugin cannot add a
428
+ namespace to it, so `ctx.remote.<something>` would be `undefined` in the browser.
429
+ That is why every function here owns plain HTTP routes and the browser calls them
430
+ with `fetch`, the same way `dshmarket` does. The plugin also does not spawn a
431
+ process: a permanently installed plugin runs in the ordinary Node process, where
432
+ `fetch` is available directly.
433
+
434
+ ## Why a peer dependency on schemastery
435
+
436
+ The row configuration is validated by a `Config` schema. `@deepseek-ai/schemastery`
437
+ is the schema library DSH itself uses, so it is already present in every DSH
438
+ installation, and it is declared as an optional peer dependency: the profile takes
439
+ it from the DSH package tree, and a missing peer does not break installation. The
440
+ alternative — bundling a second copy — would validate with a different instance
441
+ than the host and confuse error messages.
442
+
443
+ ## Build
444
+
445
+ `index.js` and `lib/**` are loaded as they are; there is no build step for the
446
+ host half. The browser half is compiled because it is several ESM modules that
447
+ must become one `window.__ModuleLoader__.load({ id, factory })` artifact:
448
+
449
+ - `tools/build-client.mjs` runs `tsdown` over `src/client/index.js`, marks
450
+ `react` and `@deepseek-ai/*` as external, and wraps the result in the loader
451
+ call under the package name;
452
+ - the compiled `client.js` is committed, so npm and git installs work without a
453
+ build on the user's machine and without `allowBuilds`;
454
+ - CI runs `npm run build` and `git diff --exit-code client.js`, so a change in
455
+ `src/client/**` that was not rebuilt fails the pipeline.
456
+
457
+ `tsdown` requires Node 22.18 or newer for building; the plugin itself runs on
458
+ Node 20 or newer, and the published package contains the compiled file.
459
+
460
+ ## Tests
461
+
462
+ `npm test` runs `node --test test/*.mjs`. The suites follow the module map, so a
463
+ failure names the layer that broke:
464
+
465
+ | File | Covers |
466
+ | --- | --- |
467
+ | `config.test.mjs` | schema defaults, v1 -> v2 normalisation, rejected values, defaults matching the schema |
468
+ | `providers.test.mjs` | route lookup by `baseURL`, field precedence, no route found |
469
+ | `cvc-api.test.mjs` | the provider client: addresses, timeouts, 401/403, broken JSON, the key never appearing in an error |
470
+ | `http.test.mjs` | the fence, the body limit, 415, 404 for a disabled function |
471
+ | `state.test.mjs` | patch layers, reset to defaults, `GET /cvc/state` assembly, the last-run registry |
472
+ | `gating.test.mjs` | a disabled function registers nothing; `loader/volatile-update` mounts and unmounts |
473
+ | `api.test.mjs` | the HTTP contract through a live `apply()`: state, config, run |
474
+ | `catalog-build.test.mjs` | model building: names, context, vision, levels, keepModels, image models |
475
+ | `catalog-sync.test.mjs` | plan and apply on a fake `configEditor`, idempotency, the shrink guard, `force`, the allowlist |
476
+ | `catalog-tool.test.mjs` | the `cvc_catalog` tool contract |
477
+ | `coefficients.test.mjs` | catalog indexing, id matching, multiplier formatting, no multiplier means no badge |
478
+ | `balance.test.mjs` | snapshot, the spend delta, a rising balance is not spend, one provider failing |
479
+ | `client-store.test.mjs` | initial load, feature changes, save, run |
480
+ | `client-render.test.mjs` | the settings page on a fake React |
481
+
482
+ Shared fakes (React, DOM, `configEditor`) live in `test/helpers/`.
483
+
484
+ ---
485
+
486
+ # Архитектура
487
+
488
+ Этот документ описывает устройство `cvc-catalog-sync-plugin` 2.0.0: что
489
+ работает на хосте, что в браузере, где принимается каждое решение и почему части
490
+ разделены именно так. Он написан для того, кто будет плагин менять, а не для
491
+ пользователя: пользовательский текст — в [README.ru.md](../README.ru.md).
492
+
493
+ ## Один пакет, две половины, три функции
494
+
495
+ Плагин — это бандл DSH: хост-половина и браузерная половина в одном npm-пакете.
496
+
497
+ - **Хост-половина** — обычный ESM (`index.js`, `lib/**`). Её загружает процесс
498
+ DSH, она регистрирует HTTP-маршруты на веб-сервере DSH, читает конфигурацию
499
+ провайдеров и профильный патч и только она вообще видит ключ API.
500
+ - **Браузерная половина** собирается из `src/client/**` в `client.js`. Она
501
+ рисует три поверхности — страницу настроек, бейджи коэффициентов, кнопку и
502
+ панель баланса — и общается с хостом только через собственные HTTP-маршруты
503
+ плагина.
504
+ - **Три функции** поверх этого разделения — синхронизация каталога,
505
+ коэффициенты и баланс. Они независимы: каждая может быть выключена, пока
506
+ работают остальные, а страница настроек — это коммутатор, который остаётся на
507
+ месте при всех трёх выключенных.
508
+
509
+ Патч бандла `cordis.patch.yml` вставляет одну строку `cvc-catalog-sync` с тремя
510
+ включёнными переключателями. Эта же строка — поверхность конфигурации: страница
511
+ настроек правит её через `ctx.configEditor`.
512
+
513
+ ## Карта модулей
514
+
515
+ ```text
516
+ index.js apply(); схема Config; гейтинг функций; обработка
517
+ loader/volatile-update
518
+ lib/config.js Config (schemastery), normalizeConfig(v1 + v2),
519
+ validateConfigInput
520
+ lib/providers.js resolveRoutes(ctx, cfg) -> маршруты CVC в строке
521
+ llm-pi-ai; resolveKey(ctx, ref)
522
+ lib/cvc-api.js fetchModels, fetchBalance, fetchLevels; таймауты,
523
+ ошибки, ключа в сообщениях нет
524
+ lib/cache.js createCatalogCache({ client, ttlMs, now });
525
+ get / peek / clear
526
+ lib/catalog-build.js buildModels(catalog, levels, options): чистая
527
+ логика, перенесённая из 1.0.0
528
+ lib/catalog-sync.js план и применение: дифф, guard, запись патча,
529
+ allowlist, инструмент cvc_catalog, таймер
530
+ lib/coefficients.js indexCoefficients(catalog), GET /cvc/coefficients
531
+ lib/balance.js снимок, дельта расхода, GET /cvc/balance,
532
+ инструмент cvc_balance
533
+ lib/http.js JSON-помощники, лимит тела 64 КБ, same-origin
534
+ фенс, регистрация prefix-маршрута
535
+ lib/state.js GET /cvc/state, PUT /cvc/config, lastRun/status
536
+ lib/CONTRACT.js замороженный контракт, которому следуют три
537
+ модуля функций и клиент (документация в коде)
538
+ client.js собранный браузерный бандл (руками не правится)
539
+ src/client/index.js apply() браузерной половины: локаль, стили,
540
+ переключатели функций, регистрации слотов
541
+ src/client/store.js {features, config, status, lastRun}; начальная
542
+ загрузка из GET /cvc/state; subscribe / refresh /
543
+ save / run
544
+ src/client/settings.js страница настроек (React): переключатели, группы,
545
+ кнопки, блок последнего прогона
546
+ src/client/config-form.js чистая модель формы: пути полей, умолчания,
547
+ черновики, чтение v1 -> v2, проверка
548
+ src/client/coefficients.js наблюдатель DOM и бейджи ×N
549
+ src/client/balance.js кнопка в сайдбаре и перетаскиваемая панель
550
+ src/client/panel-pos.js чистая часть панели: прижатие позиции и состояние
551
+ точки
552
+ src/client/css.js все стили под префиксом .cvc2-
553
+ src/client/i18n.js словари en/ru страницы и поверхностей
554
+ tools/build-client.mjs сборка client.js (tsdown + обёртка __ModuleLoader__)
555
+ tools/assert-pack.mjs проверка состава npm-тарбола
556
+ test/*.mjs наборы node --test
557
+ ```
558
+
559
+ ## Запуск и гейтинг
560
+
561
+ `apply(ctx, config)` в `index.js` делает следующее:
562
+
563
+ 1. Читает и проверяет конфигурацию строки через схему `Config`. Каждое поле
564
+ объявлено `.volatile()`, поэтому изменённую строку DSH применяет через
565
+ `loader/volatile-update`, а не перезапуском плагина.
566
+ 2. Вычисляет набор функций из `features.*` и монтирует ровно те, что включены:
567
+ - синхронизация каталога регистрирует таймер, инструмент `cvc_catalog`,
568
+ `POST /cvc/run` и относящуюся к каталогу часть `GET /cvc/state`;
569
+ - коэффициенты регистрируют `GET /cvc/coefficients` и клиент общего кэша;
570
+ - баланс регистрирует `GET /cvc/balance` и инструмент `cvc_balance`.
571
+ 3. При volatile-обновлении нормализует новую строку и перемонтирует функции,
572
+ чтобы их таймеры и маршруты увидели новые значения. Выключенная функция
573
+ освобождает свои маршруты, таймер, инструмент и подписку на кэш в том же
574
+ такте; её маршрут начинает отвечать `404`. Если изменились `providers` или
575
+ `catalog`, общий кэш каталога очищается: маршрут или ключ могли стать другими.
576
+
577
+ Хост-половина объявляет `inject = ['configEditor', 'tools', 'credentials']`,
578
+ поэтому Loader откладывает запуск плагина, а не падает, когда одного из этих
579
+ сервисов ещё нет. Веб-сервер подключается отдельно и необязательно: в профиле
580
+ без него плагин работает, но доступны только его инструменты, а HTTP-маршруты не
581
+ регистрируются.
582
+
583
+ Страница настроек не гейтится. Она регистрируется в браузере всегда, потому что
584
+ это единственное место, где переключатели можно включить обратно. Поэтому
585
+ `GET /cvc/state` и `PUT /cvc/config` существуют даже при всех трёх выключенных
586
+ функциях; `POST /cvc/run` существует только при включённой синхронизации.
587
+
588
+ «Чего выключенная функция не делает» — это проверяемый контракт, а не
589
+ соглашение: `test/gating.test.mjs` утверждает, что выключенная функция не
590
+ регистрирует ни маршрута, ни таймера, ни инструмента, и что volatile-обновление
591
+ монтирует и снимает её.
592
+
593
+ ## Конфигурация
594
+
595
+ В схеме пять групп. Умолчания:
596
+
597
+ | Группа | Поле | Умолчание | Смысл |
598
+ | --- | --- | --- | --- |
599
+ | `features` | `catalogSync` | `true` | синхронизация каталога включена |
600
+ | | `coefficients` | `true` | бейджи включены |
601
+ | | `balance` | `true` | баланс включён |
602
+ | `providers` | `match` | `['cheapvibecode.ru']` | хосты, по которым узнаётся провайдер CVC |
603
+ | | `entryId` | `'llm-pi-ai'` | строка патча с маршрутами провайдеров |
604
+ | | `apiKeyEnv` | `'CVC_DEEPSEEK_API_KEY'` | запасное имя ключа |
605
+ | | `baseURL` | `'https://ru.cheapvibecode.ru/v1'` | база, когда у строки нет своего маршрута |
606
+ | | `timeoutMs` | `20000` | таймаут одного запроса |
607
+ | `catalog` | `provider` | `'cheapvibecode'` | ключ маршрута, чьи `models` записываются |
608
+ | | `autoSync` | `true` | прогон при старте и по интервалу |
609
+ | | `intervalHours` | `24` | `0` выключает таймер |
610
+ | | `startupDelayMs` | `5000` | пауза перед первым автоматическим прогоном |
611
+ | | `minModelRatio` | `0.8` | не принимать каталог меньше этой доли от текущего числа |
612
+ | | `keepModels` | `[]` | id, сохраняемые даже при исчезновении из каталога |
613
+ | | `installerUrls` | `/idhw`, `/idhl` | карты уровней, побеждает первый доступный |
614
+ | | `syncAllowlist` | `true` | держать `allowedModels` в соответствии |
615
+ | | `allowlistEntryId` | `'subagent-model-selection-settings'` | строка, где лежит `allowedModels` |
616
+ | | `levelsCacheMinutes` | `360` | сколько времени переиспользуется карта уровней |
617
+ | `coefficients` | `refreshMinutes` | `10` | период повторного чтения бейджей |
618
+ | | `showFast` | `true` | добавлять быстрый множитель в подсказку |
619
+ | `balance` | `refreshSeconds` | `0` | `0` — только по запросу; 15 и больше — таймер, пока панель открыта |
620
+ | | `showDelta` | `true` | показывать расход между двумя замерами |
621
+
622
+ Два поведения живут в `lib/config.js`, а не в потребителях:
623
+
624
+ - **Нормализация старого вида.** Плоские ключи 1.x (`entryId`, `provider`,
625
+ `baseURL`, `apiKeyEnv`, `installerUrls`, `autoSync`, `intervalHours`,
626
+ `startupDelayMs`, `minModelRatio`, `keepModels`, `syncAllowlist`,
627
+ `allowlistEntryId`, `levelsCacheMinutes`, `timeoutMs`) остаются в схеме
628
+ необязательными устаревшими полями. `normalizeConfig` раскладывает их по
629
+ группам, поэтому профиль, написанный для 1.0.0, загружается без правок.
630
+ `GET /cvc/state` сообщает `configShape: 'legacy'`, если источником было хоть
631
+ одно из них, и страница настроек предлагает сохранить один раз.
632
+ - **Проверка.** `validateConfigInput` проверяет значения, которые присылает
633
+ страница настроек, и возвращает имена полей; `PUT /cvc/config` отвечает `400`
634
+ с `fields` и ничего не записывает. Форма проверяет очевидные случаи до
635
+ отправки, но истина — на хосте.
636
+
637
+ ## Поиск провайдеров
638
+
639
+ `lib/providers.js` отвечает на один вопрос: какие маршруты `cheapvibecode.ru`
640
+ есть в строке `llm-pi-ai` и как называется ключ каждого?
641
+
642
+ Поиск читает строки профиля через `ctx.configEditor.entries()` и ищет строку,
643
+ названную `providers.entryId` (по умолчанию `llm-pi-ai`), в три прохода: по
644
+ точному id, по имени пакета адаптера (`@deepseek-ai/dsh-llm-pi-ai`) и по id с
645
+ префиксом группы (`include:llm-pi-ai` и подобные). Кандидат принимается, только
646
+ если он действительно несёт непустой объект `providers`, поэтому строка-дубль с
647
+ `config: {}` не может закончить поиск. Из принятой строки остаются маршруты, чей
648
+ `baseURL` — `https` и чей разобранный hostname равен хосту из `providers.match`
649
+ или оканчивается на `.хост`: `cheapvibecode.ru` покрывает
650
+ `ru.cheapvibecode.ru`, а похожий `cheapvibecode.ru.example.com` и обычный `http`
651
+ не совпадают никогда. Маршрут, добавленный позже в настройках DSH, появляется
652
+ при следующем чтении без перезапуска плагина: поиск идёт по живым строкам.
653
+
654
+ `apiKeyFor(route, cfg)` возвращает собственный `apiKeyEnv` маршрута, если он
655
+ есть, иначе общий `providers.apiKeyEnv`. `resolveKey(ctx, ref)` разрешает это имя
656
+ через `ctx.credentials.resolve` и возвращает значение или пустую строку;
657
+ вызывающий превращает пустую строку в ошибку `no-key`, поэтому плагин сообщает
658
+ «API key is not configured for this provider», а не отправляет пустой `Bearer`.
659
+ Другого не принимается: плагин не читает `.env` и переменные окружения сам — это
660
+ работа сервиса ключей.
661
+
662
+ Общий кэш каталога нацелен на `catalog.provider`. `pickRoute(routes, key)`
663
+ предпочитает маршрут с совпавшим ключом и откатывается к первому найденному
664
+ маршруту CVC, если ключ ни на что не указывает, — чтобы кэшу было что отдать.
665
+ Сама синхронизация каталога адресует `catalog.provider` напрямую: строка, чей
666
+ `provider` не называет ни одного маршрута CVC, валит прогон с `no route "<key>"
667
+ is configured`, а не пишет модели в маршрут, который пользователь не называл.
668
+
669
+ Все три функции используют этот один модуль. До 2.0.0 у плагина каталога, у
670
+ плагина коэффициентов и у плагина баланса был свой код поиска, и исправление в
671
+ одном не доходило до остальных.
672
+
673
+ ## Общий кэш каталога
674
+
675
+ `lib/cache.js` — небольшой TTL-кэш вокруг `fetchModels`, один экземпляр на
676
+ процесс плагина:
677
+
678
+ - `get({ force })` возвращает кэшированный каталог или забирает его, когда
679
+ записи нет, она старше `ttlMs` или передан `force`;
680
+ - параллельные вызовы делят один запрос вместо двух;
681
+ - неудачный запрос не теряет последний удачный ответ: `get` продолжает его
682
+ отдавать с `stale: true` и текстом ошибки, а следующий вызов повторяет
683
+ попытку. Если снимка ещё нет, ошибка пробрасывается;
684
+ - `refresh()` — это `get({ force: true })`; `peek()` читает без запроса (им
685
+ пользуется отчёт о состоянии), а `clear()` выбрасывает запись и увеличивает
686
+ счётчик поколения, поэтому ещё летящий ответ не может записать себя обратно;
687
+ - `ttlMs` — число или функция от текущего конфига, поэтому время жизни кэша
688
+ следует за `coefficients.refreshMinutes` без пересоздания кэша;
689
+ - `now` инъектируется, поэтому поведение TTL проверяется без сна.
690
+
691
+ Синхронизация каталога и коэффициенты читают один и тот же кэш. В этом и смысл
692
+ модуля: один `GET /v1/models` наполняет и список `models`, записываемый в патч, и
693
+ карту множителей, рисуемую в селекторе. Обновление бейджей, попавшее в свежий
694
+ кэш, не стоит ни одного запроса к каталогу.
695
+
696
+ ## HTTP-слой
697
+
698
+ `lib/http.js` держит правила транспорта, чтобы все маршруты отвечали одинаково:
699
+
700
+ | Правило | Ответ |
701
+ | --- | --- |
702
+ | путь вне префикса `/cvc` | `404` |
703
+ | маршрут выключенной функции | `404` |
704
+ | `Sec-Fetch-Site: cross-site` | `403` |
705
+ | `PUT` или `POST` без `application/json` | `415` |
706
+ | тело больше 64 КБ | `413` |
707
+ | `POST /cvc/run` отклонён guard-ом от усыхания или устаревшим каталогом | `409` с результатом прогона |
708
+ | неверный метод на известном пути | `405` с заголовком `allow` |
709
+ | битый JSON в теле | `400` |
710
+
711
+ Порядок важен: фенс срабатывает раньше разбора пути, поэтому межсайтовый запрос
712
+ никогда не узнаёт, существует ли маршрут, а проверка content-type идёт до
713
+ диспетчеризации, поэтому запись не может дойти до обработчика, не объявив себя
714
+ JSON. `409` на `/cvc/run` — это решение, а не сбой: guard отказался записывать
715
+ каталог меньше `minModelRatio` от текущего числа, либо каталог устарел. Прочие
716
+ неудачи прогона (нет маршрута, нет ключа, сеть) отвечают `200` с `ok: false` и
717
+ диагностическим телом — той же формой, что возвращает инструмент `cvc_catalog`.
718
+
719
+ Маршруты регистрируются одним префиксом (`/cvc`) через `ctx.webServer.attach`, и
720
+ плагин держит собственную таблицу подпутей. Одна регистрация префикса на плагин
721
+ намеренна: две регистрации одного префикса на веб-сервере конфликтуют, а с
722
+ собственной таблицей выключенная функция просто убирает свой подпуть и отвечает
723
+ `404`, не трогая веб-сервер. Свой сервер `index.js` не создаёт. Ответы несут `cache-control: no-store` и
724
+ `x-content-type-options: nosniff`. `lib/http.js` также отдаёт JSON-помощник и
725
+ чтение тела, которыми пользуется `lib/state.js`.
726
+
727
+ Правила, которые соблюдают HTTP-слой и `lib/cvc-api.js` везде:
728
+
729
+ - незаданный ключ — это ошибка про имя (`credential "…" is not configured`), а не
730
+ пустой `Bearer`;
731
+ - `401` или `403` провайдера поднимается как `CvcApiError` с кодом
732
+ `unauthorized` и собственным сообщением провайдера, прошедшим redact;
733
+ - сетевая ошибка, таймаут и битое тело JSON — три разные ошибки с тремя разными
734
+ кодами; ни в одной из них нет ключа.
735
+
736
+ ## Запросы к API провайдера
737
+
738
+ `lib/cvc-api.js` — единственный модуль, который общается с провайдером:
739
+
740
+ | Функция | Запрос | Ответ |
741
+ | --- | --- | --- |
742
+ | `fetchModels({ baseURL, key, timeoutMs })` | `GET {baseURL}/models` | список моделей из `{ data: [...] }` или голого массива; строки без строкового `id` отбрасываются |
743
+ | `fetchBalance({ baseURL, key, timeoutMs })` | `GET {apiRoot}/v1/balance` | `{ units }` из `token_balance` |
744
+ | `fetchLevels({ urls, timeoutMs })` | `GET <адрес установщика>`, без ключа, по очереди | карта `reasoningLevels` и ответивший адрес |
745
+
746
+ Установщик пробуется в порядке `catalog.installerUrls`, и побеждает первый, что
747
+ ответил разбираемой картой. Если не ответил ни один, ошибка перечисляет по
748
+ каждому адресу, был ли таймаут, сетевая ошибка, не-2xx статус, нечитаемое тело
749
+ или отсутствие литерала `reasoningLevels`.
750
+
751
+ `apiRoot(baseURL)` снимает хвостовой `/v1`, потому что маршрут настраивается
752
+ OpenAI-совместимой базой (`…/v1`), а эндпоинт баланса живёт на уровень выше.
753
+ `redact(text, secret)` заменяет ключ на `***` во всех сообщениях, куда может
754
+ попасть текст провайдера.
755
+
756
+ ## Контракт маршрутов
757
+
758
+ | Метод | Путь | Тело | Ответ |
759
+ | --- | --- | --- | --- |
760
+ | `GET` | `/cvc/state` | — | `{version, features, config, configShape, status, lastRun, patchPath, rowId}` |
761
+ | `PUT` | `/cvc/config` | `{config}` | `{ok, config, features}` либо `400` с `fields` |
762
+ | `POST` | `/cvc/run` | `{action: 'plan' \| 'apply', force?}` | результат прогона |
763
+ | `GET` | `/cvc/coefficients` | — | `{models: [{id, displayName, multiplier, fastMultiplier, contextWindow}], providers, fetchedAt, stale}` |
764
+ | `GET` | `/cvc/balance` | — | `{providers: [{provider, displayName, baseURL, apiKeyEnv, keySet, balanceUnits, spentSinceLast, balanceError}], fetchedAt}` |
765
+ | `GET` | `/cvc/health` | — | `{ok, version}` |
766
+
767
+ `PUT /cvc/config` и `POST /cvc/run` — записи: первая пишет строку плагина, вторая
768
+ пишет модели и список сабагентов. Обе идут через `ctx.configEditor.edit()`,
769
+ который сохраняет остальной файл патча, комментарии и строки чужих плагинов.
770
+ Сохранение через страницу ничего чужого не теряет: `buildState` отдаёт
771
+ действующий конфиг (слой бандла с наложенным переопределением профиля), а `PUT`
772
+ пишет строку обратно только этим редактором; сохранение со значением, равным
773
+ умолчаниям схемы, удаляет переопределение, а не записывает копию умолчаний в
774
+ патч.
775
+
776
+ ## Где принимается какое решение
777
+
778
+ | Решение | Модуль | Почему там |
779
+ | --- | --- | --- |
780
+ | включена ли функция? | `index.js` | переключатель — факт уровня плагина, а монтирование — эффект уровня плагина |
781
+ | какие маршруты CVC? | `lib/providers.js` | один поиск на три функции; альтернатива — три копии |
782
+ | как строится модель? | `lib/catalog-build.js` | чистая функция от каталога, уровней и настроек; проверяется без DSH |
783
+ | не слишком ли мал каталог? | `lib/catalog-sync.js` | guard нуждается в текущем списке, а его читает только путь применения |
784
+ | что говорит бейдж? | `lib/coefficients.js` (хост) и `src/client/coefficients.js` (рисование) | хост решает, что за число, браузер — как это выглядит |
785
+ | расход ли это? | `lib/balance.js` | прошлый замер — состояние процесса, и держит его только хост |
786
+ | как выглядит страница? | `src/client/settings.js` + `css.js` + `i18n.js` | рендеринг и формулировки принадлежат браузерной половине |
787
+
788
+ ## Синхронизация каталога
789
+
790
+ Прогон бывает `plan` или `apply`; оба собирают один и тот же список-кандидат:
791
+
792
+ 1. `lib/cvc-api.js` забирает `{baseURL}/models` ключом маршрута и страницу
793
+ установщика (первый доступный из `installerUrls`), затем извлекает литерал
794
+ `reasoningLevels` линейно — без возвратной регулярки на скачанном тексте.
795
+ 2. `lib/catalog-build.js` превращает каждую строку каталога в модель
796
+ `llm-pi-ai`: `name` — часть `display_name` после ` · `, `contextWindow` —
797
+ `context_window`, `maxTokens` — `min(max_output_tokens, contextWindow)`,
798
+ `input` получает `image`, когда модель принимает картинки, уровень `none`
799
+ становится `off: none`, а `gpt-image*` и модели без текстового вывода
800
+ пропускаются. Поле, которого нет в каталоге, берётся из текущей записи патча,
801
+ затем из умолчания, поэтому ручная правка не теряется.
802
+ 3. `lib/catalog-sync.js` сравнивает список-кандидат с текущими моделями и
803
+ сообщает добавленные, удалённые и изменённые.
804
+ 4. Guard от усыхания отклоняет `apply`, если число кандидатов ниже
805
+ `minModelRatio` от текущего числа, кроме случая `force: true`.
806
+ 5. `apply` пишет модели и, при `syncAllowlist`, список
807
+ `subagent-model-selection-settings.allowedModels`. Обе записи читают текущее
808
+ значение внутри колбэка редактора, поэтому параллельная правка не
809
+ затирается. Запись выполняется только при реальном изменении; второй `apply`
810
+ ничего не делает.
811
+ 6. Прогоны по таймеру — тот же путь с `apply` и без `force`.
812
+
813
+ Инструмент `cvc_catalog` открывает `status`, `plan` и `apply`; `status` отвечает
814
+ по записи о последнем прогоне в процессе и сети не касается. Инструмент
815
+ регистрируется только пока синхронизация каталога смонтирована: при выключенной
816
+ функции его нет в списке инструментов вовсе.
817
+
818
+ ## Коэффициенты
819
+
820
+ `lib/coefficients.js` индексирует каталог в `{id → multiplier, fastMultiplier,
821
+ displayName, contextWindow}` и отдаёт это на `GET /cvc/coefficients`. Ответ
822
+ несёт ещё и id провайдеров, которым принадлежит кэшированный каталог, потому что
823
+ браузер не должен украшать id модели чужого провайдера.
824
+
825
+ Браузерная половина (`src/client/coefficients.js`) не заменяет селектор модели.
826
+ Она наблюдает документ за узлами `[data-model-id]`, читает `data-provider-id` из
827
+ того же узла и дописывает `<span class="cvc2-badge">`, только когда провайдер
828
+ есть в списке и у модели есть множитель. Нет множителя — нет бейджа: цену
829
+ плагин не угадывает. Бейдж с `pointer-events: none`, поэтому клики и выбор с
830
+ клавиатуры остаются у селектора. Наблюдатель пропускает мутации внутри своих
831
+ бейджей — это и не даёт ему зациклиться; `requestAnimationFrame` схлопывает
832
+ перерисовки, пока пользователь печатает в поиске моделей. Остановка функции
833
+ отключает наблюдателя и снимает все нарисованные бейджи.
834
+
835
+ Слот `conversation.input.model.label` не трогается: он `single`, его уже держит
836
+ штатный бейдж, и вторая регистрация вытеснила бы его.
837
+
838
+ ## Баланс
839
+
840
+ `lib/balance.js` читает баланс каждого маршрута CVC через
841
+ `GET {apiRoot}/v1/balance`:
842
+
843
+ - `apiRoot` — это `baseURL` маршрута без хвостового `/v1`, поэтому запрос идёт
844
+ на тот хост, который маршрут уже называет;
845
+ - `token_balance` становится `balanceUnits`; `keySet` сообщает, найден ли ключ,
846
+ а не его значение;
847
+ - отказ одного провайдера записывается в его собственный `balanceError` и не
848
+ мешает остальным ответить;
849
+ - `spentSinceLast` — падение между прошлым и текущим замером, и живёт он в
850
+ памяти процесса, поэтому теряется при перезапуске;
851
+ - инструмент `cvc_balance` возвращает последний снимок, не тратя запрос. Его
852
+ строки — `{provider, displayName, keySet, balanceUnits}`, где `keySet` — булев
853
+ факт наличия ключа; `baseURL` и `apiKeyEnv` там не повторяются, потому что
854
+ инструмент отвечает агенту, а не рисует панель.
855
+
856
+ Панель в браузере рисует карточки, строку расхода, точку состояния и
857
+ перетаскивание. Позицию она хранит в `localStorage` под ключом `cvc:panel-pos`, а
858
+ не `cvc-balance:panel-pos`: старый ключ принадлежал панели 1.1.0, и её
859
+ координаты могут оказаться за пределами окна.
860
+
861
+ Инструмент `cvc_balance` регистрируется только пока функция баланса
862
+ смонтирована. Он говорит за сторону агента; панель — сторона человека.
863
+ Коэффициенты инструмента не регистрируют: бейджи — только чтение, и делать
864
+ инструменту нечего.
865
+
866
+ ## Браузерная половина
867
+
868
+ `src/client/index.js` регистрирует четыре поверхности:
869
+
870
+ | Поверхность | Слот | Всегда включена? |
871
+ | --- | --- | --- |
872
+ | страница настроек | `settings.section` (id `cvc`, order 25) | да |
873
+ | значок настроек | `settings.section.icon` | да |
874
+ | блок бандла | `plugins.bundle.config` (ключ — имя пакета) | да |
875
+ | кнопка и панель баланса | `sidebar.footer.action` (id `cvc-balance`, order 5) | только при `features.balance` |
876
+ | бейджи коэффициентов | наблюдатель DOM, без слота | только при `features.coefficients` |
877
+
878
+ Страница регистрируется в двух местах одним компонентом: секцией настроек и
879
+ блоком на странице плагина. В списке плагинов блок просит `view: 'summary'` и
880
+ рисует одну строку, потому что полная форма там не помещается. Три переключателя
881
+ функций — кнопки с `role="switch"` и `aria-checked`, поэтому экранный диктор
882
+ объявляет их переключателями вкл/выкл, а не кнопками.
883
+
884
+ Состояние читается слева направо так. Блок **последнего прогона** под кнопками
885
+ показывает размер каталога, текущее и будущее число моделей, источник уровней,
886
+ добавленные, удалённые и изменённые модели, правки списка сабагентов,
887
+ предупреждения и путь патча. Точка баланса: `warn`, пока идёт обновление;
888
+ `err`, когда запрос упал и строк провайдеров нет; нейтральная, когда маршрут CVC
889
+ не настроен вовсе; `ok`, когда все провайдеры вернули число; `warn`, когда только
890
+ часть; `err`, когда ни один.
891
+
892
+ `store.js` — единственный источник истины на клиенте. Он стартует с умолчаний
893
+ схемы (все три функции включены), загружает `GET /cvc/state`, публикует
894
+ изменения подписчикам и обновляется из ответа `PUT /cvc/config` и
895
+ `POST /cvc/run` без второго запроса. Смену набора функций он замечает по
896
+ короткому ключу из трёх булевых значений — это и будит переключатели, которые
897
+ монтируют и снимают кнопку баланса и наблюдатель бейджей. `refresh()`
898
+ схлопывает параллельные вызовы в один запрос: страница и кнопка баланса могут
899
+ спросить одновременно. `coefficients()` и `balance()` возвращают
900
+ `{ok, status, body, error}` вместо выброса: `404` от функции, выключенной
901
+ мгновение назад, — ожидаемый ответ, а не исключение.
902
+
903
+ Все имена классов живут под `.cvc2-`. Префикс намеренный: 1.0.0 использовал
904
+ `.cvc-sync`, приватные плагины — `.cvc-coeff` и `.cvc-panel`, и оставшаяся при
905
+ обновлении строка плагина не должна унаследовать новые стили.
906
+
907
+ ## Почему не Remote-неймспейсы
908
+
909
+ Таблица Remote на стороне браузера генерируется при сборке DSH из хост-пакетов
910
+ в `@deepseek-ai/dsh-api-remotes`. Сторонний плагин не может добавить в неё свой
911
+ неймспейс, поэтому `ctx.remote.<что-то>` в браузере был бы `undefined`. Именно
912
+ поэтому каждая функция здесь владеет обычными HTTP-маршрутами, а браузер
913
+ вызывает их через `fetch` — так же, как `dshmarket`. Плагин не запускает и
914
+ дочерний процесс: постоянно установленный плагин выполняется в обычном
915
+ Node-процессе, где `fetch` доступен напрямую.
916
+
917
+ ## Почему schemastery — peer-зависимость
918
+
919
+ Конфигурацию строки проверяет схема `Config`. `@deepseek-ai/schemastery` — та
920
+ самая библиотека схем, которую использует сам DSH, поэтому она уже есть в любой
921
+ установке DSH, и объявлена она необязательной peer-зависимостью: профиль берёт её
922
+ из дерева пакетов DSH, а отсутствие peer не ломает установку. Альтернатива —
923
+ вложить вторую копию — проверяла бы другой копией, чем хост, и путала бы
924
+ сообщения об ошибках.
925
+
926
+ ## Сборка
927
+
928
+ `index.js` и `lib/**` загружаются как есть; шага сборки у хост-половины нет.
929
+ Браузерная половина собирается, потому что это несколько ESM-модулей, которые
930
+ должны стать одним артефактом `window.__ModuleLoader__.load({ id, factory })`:
931
+
932
+ - `tools/build-client.mjs` прогоняет `tsdown` по `src/client/index.js`, помечает
933
+ `react` и `@deepseek-ai/*` внешними и заворачивает результат в вызов
934
+ загрузчика под именем пакета;
935
+ - собранный `client.js` коммитится, поэтому установка из npm и из git работает
936
+ без сборки на машине пользователя и без `allowBuilds`;
937
+ - CI выполняет `npm run build` и `git diff --exit-code client.js`, поэтому
938
+ изменение в `src/client/**`, которое не пересобрали, валит пайплайн.
939
+
940
+ `tsdown` требует Node 22.18 или новее для сборки; сам плагин работает на Node 20
941
+ или новее, а опубликованный пакет содержит собранный файл.
942
+
943
+ ## Тесты
944
+
945
+ `npm test` запускает `node --test test/*.mjs`. Наборы идут по карте модулей,
946
+ поэтому падение называет слой, который сломался:
947
+
948
+ | Файл | Что покрывает |
949
+ | --- | --- |
950
+ | `config.test.mjs` | умолчания схемы, нормализацию v1 -> v2, отказ невалидных значений, совпадение умолчаний со схемой |
951
+ | `providers.test.mjs` | поиск маршрутов по `baseURL`, приоритет полей, отсутствие маршрута |
952
+ | `cvc-api.test.mjs` | клиент провайдера: адреса, таймауты, 401/403, битый JSON, отсутствие ключа в тексте ошибки |
953
+ | `http.test.mjs` | фенс, лимит тела, 415, 404 при выключенной функции |
954
+ | `state.test.mjs` | слои патча, сброс к умолчаниям, сборку `GET /cvc/state`, реестр последнего прогона |
955
+ | `gating.test.mjs` | выключенная функция не регистрирует ничего; `loader/volatile-update` монтирует и снимает |
956
+ | `api.test.mjs` | HTTP-контракт на живом `apply()`: state, config, run |
957
+ | `catalog-build.test.mjs` | сборку моделей: имена, контекст, зрение, уровни, keepModels, image-модели |
958
+ | `catalog-sync.test.mjs` | план и применение на поддельном `configEditor`, идемпотентность, guard, `force`, allowlist |
959
+ | `catalog-tool.test.mjs` | контракт инструмента `cvc_catalog` |
960
+ | `coefficients.test.mjs` | индексацию каталога, сопоставление id, форматирование множителя, отсутствие множителя — нет бейджа |
961
+ | `balance.test.mjs` | снимок, дельту расхода, рост баланса — не расход, отказ одного провайдера |
962
+ | `client-store.test.mjs` | начальную загрузку, смену функций, сохранение, прогон |
963
+ | `client-render.test.mjs` | страницу настроек на поддельном React |
964
+
965
+ Общие подделки (React, DOM, `configEditor`) лежат в `test/helpers/`.