@darkbear9494/dsh-model-manager 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,955 @@
1
+ /**
2
+ * @darkbear9494/dsh-model-manager — Web client half.
3
+ *
4
+ * Contributes a configuration page for this plugin's own row on the Plugins
5
+ * page. The row gains a configure control that opens a card with one model
6
+ * picker per role (main / planning / execution / vision) fed by the host's live
7
+ * model catalog, plus the distribution mode and a per-role reasoning effort.
8
+ *
9
+ * Design constraints (from the harness's own plugin practices):
10
+ * - No Harness Client package is `require`d as a module. React comes from the
11
+ * browser module table; every other collaborator is a cordis *service*
12
+ * reached through `inject`. Controls are written here and styled only with
13
+ * `--dsw-alias-*` theme tokens, so light/dark and future renames degrade
14
+ * gracefully instead of breaking the entry.
15
+ * - The host owns the values and the write path: the slot passes a `form`
16
+ * with `state` (accepted values, revision, writability) and `mutate`
17
+ * (ordered, revision-fenced path operations). This half never talks to
18
+ * settings storage directly.
19
+ * - A component that throws blanks the slot entry, so every render path is
20
+ * guarded and defaults to a readable notice.
21
+ *
22
+ * Writes are applied immediately on selection — the same pattern the host's own
23
+ * volatile settings cards use. The host half re-reads its config on
24
+ * `loader/volatile-update`, so a change takes effect without a restart.
25
+ *
26
+ * @module @darkbear9494/dsh-model-manager/client
27
+ */
28
+ window.__ModuleLoader__.load({
29
+ id: '@darkbear9494/dsh-model-manager',
30
+ factory(require) {
31
+ const React = require('react');
32
+ const h = React.createElement;
33
+
34
+ /**
35
+ * Locale namespace for this card's copy. Deliberately NOT the package name:
36
+ * the namespace is ours, so it stayed put when the package became scoped,
37
+ * which keeps every existing key (`dsh-model-manager.usageTitle`, …) and
38
+ * every translation stable across the rename. The module-loader `id` above
39
+ * is the one string that must track the package name, because the Host
40
+ * composes this half under it.
41
+ */
42
+ const LOCALE_NS = 'dsh-model-manager';
43
+ /**
44
+ * This plugin's own settings namespace — the Loader row id its host half is
45
+ * mounted as. `configForms`/`settings` are keyed by row id; the shipped
46
+ * Subagent settings card binds `configForms.get("subagent-model-selection-settings")`,
47
+ * i.e. its own row id, which is the convention followed here.
48
+ */
49
+ const ROW_NS = 'model-manager';
50
+ /**
51
+ * Key of the session projection the host half folds from the durable log.
52
+ * Must match USAGE_PROJECTION_KEY in lib/index.js: the client only subscribes,
53
+ * it never folds.
54
+ */
55
+ const USAGE_PROJECTION_KEY = 'modelManagerUsage';
56
+ const ROLES = ['main', 'planning', 'execution', 'vision'];
57
+ const MODES = ['hybrid', 'managed', 'advisory'];
58
+ /**
59
+ * How long to wait for the session-scoped catalog before relying on the
60
+ * global `remote.llm` directory alone. It is a bonus source (it carries
61
+ * reasoning efforts), never a gate.
62
+ */
63
+ const SESSION_CATALOG_TIMEOUT_MS = 4000;
64
+
65
+ const en = {
66
+ title: 'Model manager',
67
+ summaryEmpty: 'No roles configured',
68
+ summary: 'Model roles',
69
+ help: 'Each role names the model used for that kind of work. Changes apply immediately.',
70
+ roleMain: 'Main model',
71
+ roleMainHint: 'Top-level agent outside plan mode. Unset keeps the composer in charge. When set, it takes over only sessions that never had a manual pick — a model you chose in the composer keeps running, unless the mode is managed.',
72
+ rolePlanning: 'Planning and reasoning',
73
+ rolePlanningHint: 'Used in plan mode and for delegations labelled as planning work.',
74
+ roleExecution: 'Execution',
75
+ roleExecutionHint: 'The default tier for delegated implementation work.',
76
+ roleVision: 'Image recognition',
77
+ roleVisionHint: 'Used for image, screenshot and OCR work. Pick a model that accepts images.',
78
+ mode: 'Distribution mode',
79
+ modeHybrid: 'hybrid — take over only when the child inherited the parent route',
80
+ modeManaged: 'managed — always apply the role route',
81
+ modeAdvisory: 'advisory — never rewrite, report only',
82
+ effort: 'Reasoning effort',
83
+ effortDefault: '(model default)',
84
+ loading: 'Loading models…',
85
+ unavailable: 'These settings are not available to this client right now.',
86
+ readOnly: 'This deployment stores settings read-only.',
87
+ saved: 'Saved',
88
+ refused: 'The host refused the change.',
89
+ notInCatalog: 'not advertised',
90
+ providersFailed: 'Some providers could not be listed:',
91
+ noModels: 'No models are advertised yet. Configure a provider route, then reopen this page.',
92
+ noForm: 'This page did not supply configuration values, so the model roles cannot be edited here. Open this plugin\'s own row on the Plugins page to configure it.',
93
+ current: 'Current',
94
+ enable: 'Enable model manager',
95
+ enableHint: 'Off: routes are observed and reported but never rewritten.',
96
+ addModel: 'Add a model…',
97
+ remove: 'Remove',
98
+ moveUp: 'Move up',
99
+ pick: 'Selection',
100
+ pickFirst: 'first — use the top model, fall back down the list',
101
+ pickRoundRobin: 'round-robin — rotate across the list',
102
+ orderHint: 'Order is the fallback order: the top model is tried first.',
103
+ usageTitle: 'Model usage',
104
+ usageModel: 'Provider / model',
105
+ usageUncachedInput: 'Uncached input',
106
+ usageOutput: 'Output',
107
+ usageCacheRead: 'Cached input',
108
+ usageCacheWrite: 'Cache write',
109
+ usageRequests: '{count} requests',
110
+ usageEmpty: 'No usage reported for this session yet.',
111
+ usageHint: 'Folded from the durable session log, so it survives a restart. Only attempts that reported an exact usage sample are counted, which is why a Turn where a model failed shows no line here.',
112
+ };
113
+
114
+ const zh = {
115
+ title: '模型管理器',
116
+ summaryEmpty: '未配置角色',
117
+ summary: '模型角色',
118
+ help: '每个角色指定该类工作使用的模型。更改会立即生效。',
119
+ roleMain: '主模型',
120
+ roleMainHint: '非计划模式下顶层 Agent 使用的模型。留空则完全跟随输入框选择。设置后只接管从未手动选过模型的会话;你在输入框点选过的模型会继续使用,除非分发模式为 managed。',
121
+ rolePlanning: '规划与推理',
122
+ rolePlanningHint: '计划模式下使用,也用于标记为规划类工作的委派。',
123
+ roleExecution: '执行',
124
+ roleExecutionHint: '委派实现的默认档位。',
125
+ roleVision: '图像识别',
126
+ roleVisionHint: '用于图像、截图与 OCR 工作。请选择支持图像输入的模型。',
127
+ mode: '分发模式',
128
+ modeHybrid: 'hybrid — 仅当子 Agent 继承父路由时才接管',
129
+ modeManaged: 'managed — 始终应用角色路由',
130
+ modeAdvisory: 'advisory — 只记录不改写',
131
+ effort: '推理档位',
132
+ effortDefault: '(模型默认)',
133
+ loading: '正在加载模型…',
134
+ unavailable: '当前客户端无法使用这些设置。',
135
+ readOnly: '该部署以只读方式存储设置。',
136
+ saved: '已保存',
137
+ refused: '主机拒绝了此次更改。',
138
+ notInCatalog: '未在目录中',
139
+ providersFailed: '以下供应商无法列出:',
140
+ noModels: '尚无可用模型。请先配置供应商路由,然后重新打开此页。',
141
+ noForm: '此页面未提供配置值,因此无法在此编辑模型角色。请在「插件」页面打开该插件自身的条目进行配置。',
142
+ current: '当前',
143
+ enable: '启用模型管理器',
144
+ enableHint: '关闭时:只观察和记录各会话实际使用的模型,不改写任何路由。',
145
+ addModel: '添加模型…',
146
+ remove: '移除',
147
+ moveUp: '上移',
148
+ pick: '选择方式',
149
+ pickFirst: 'first — 优先用第一个,失败时按顺序向下回退',
150
+ pickRoundRobin: 'round-robin — 在列表内轮流使用',
151
+ orderHint: '列表顺序即回退顺序:排在最前的模型优先使用。',
152
+ usageTitle: '模型用量',
153
+ usageModel: '提供方 / 模型',
154
+ usageUncachedInput: '未缓存输入',
155
+ usageOutput: '输出',
156
+ usageCacheRead: '缓存读取',
157
+ usageCacheWrite: '缓存写入',
158
+ usageRequests: '{count} 次请求',
159
+ usageEmpty: '这个会话还没有上报用量。',
160
+ usageHint: '从持久会话日志折叠而来,重启后依然准确。只计入上报了精确 usage 样本的请求,因此某个 turn 发生模型失败切换时不会出现在这里。',
161
+ };
162
+
163
+ /** Styles reference only theme tokens, so light/dark switch with the host. */
164
+ const S = {
165
+ root: { display: 'flex', flexDirection: 'column', gap: '0.9rem', color: 'var(--dsw-alias-label-primary)' },
166
+ help: { margin: 0, fontSize: '0.82rem', color: 'var(--dsw-alias-label-secondary)' },
167
+ row: { display: 'flex', flexDirection: 'column', gap: '0.3rem' },
168
+ label: { fontSize: '0.85rem', fontWeight: 600, color: 'var(--dsw-alias-label-primary)' },
169
+ hint: { fontSize: '0.76rem', color: 'var(--dsw-alias-label-secondary)' },
170
+ controls: { display: 'flex', gap: '0.5rem', flexWrap: 'wrap' },
171
+ select: {
172
+ flex: '1 1 16rem',
173
+ minWidth: 0,
174
+ padding: '0.35rem 0.5rem',
175
+ borderRadius: 6,
176
+ border: '1px solid var(--dsw-alias-border-l1)',
177
+ background: 'var(--dsw-alias-bg-layer-1)',
178
+ color: 'var(--dsw-alias-label-primary)',
179
+ fontSize: '0.85rem',
180
+ },
181
+ // One grid per role: fixed column tracks make every model control start and
182
+ // end at the same x, whatever row it is in or which optional controls show.
183
+ entryGrid: {
184
+ display: 'grid',
185
+ gridTemplateColumns: 'auto minmax(0, 1fr) auto auto',
186
+ gap: '0.35rem 0.45rem',
187
+ alignItems: 'center',
188
+ },
189
+ cellIndex: {
190
+ justifySelf: 'end',
191
+ minWidth: '1.1rem',
192
+ fontSize: '0.75rem',
193
+ color: 'var(--dsw-alias-label-secondary)',
194
+ fontVariantNumeric: 'tabular-nums',
195
+ },
196
+ cellGap: {},
197
+ actions: { display: 'inline-flex', gap: '0.25rem' },
198
+ // Fixed square glyph buttons: no text, so the column width cannot drift
199
+ // with the active locale or with a row having one action instead of two.
200
+ action: {
201
+ width: '1.7rem',
202
+ height: '1.7rem',
203
+ padding: 0,
204
+ display: 'inline-flex',
205
+ alignItems: 'center',
206
+ justifyContent: 'center',
207
+ borderRadius: 6,
208
+ border: '1px solid var(--dsw-alias-border-l1)',
209
+ background: 'var(--dsw-alias-bg-layer-1)',
210
+ color: 'var(--dsw-alias-label-secondary)',
211
+ fontSize: '0.85rem',
212
+ lineHeight: 1,
213
+ cursor: 'pointer',
214
+ },
215
+ actionOff: { opacity: 0.35, cursor: 'default' },
216
+ selectGrid: {
217
+ minWidth: 0,
218
+ padding: '0.35rem 0.5rem',
219
+ borderRadius: 6,
220
+ border: '1px solid var(--dsw-alias-border-l1)',
221
+ background: 'var(--dsw-alias-bg-layer-1)',
222
+ color: 'var(--dsw-alias-label-primary)',
223
+ fontSize: '0.85rem',
224
+ height: '1.7rem',
225
+ },
226
+ selectEffortGrid: { minWidth: '7rem' },
227
+ // The add affordance must not look like another configured model.
228
+ selectAdd: {
229
+ borderStyle: 'dashed',
230
+ background: 'transparent',
231
+ color: 'var(--dsw-alias-label-secondary)',
232
+ },
233
+ cellSpan: { gridColumn: '2 / -1' },
234
+ pickLabel: { fontSize: '0.76rem', color: 'var(--dsw-alias-label-secondary)' },
235
+ usage: { position: 'relative', display: 'inline-flex' },
236
+ usageButton: {
237
+ display: 'inline-flex',
238
+ alignItems: 'center',
239
+ gap: '0.35rem',
240
+ padding: '0.22rem 0.5rem',
241
+ borderRadius: 6,
242
+ border: '1px solid var(--dsw-alias-border-l1)',
243
+ background: 'var(--dsw-alias-bg-layer-2)',
244
+ color: 'var(--dsw-alias-label-secondary)',
245
+ fontSize: '0.74rem',
246
+ cursor: 'pointer',
247
+ fontVariantNumeric: 'tabular-nums',
248
+ },
249
+ usagePanel: {
250
+ position: 'absolute',
251
+ top: 'calc(100% + 0.3rem)',
252
+ right: 0,
253
+ zIndex: 30,
254
+ minWidth: '17rem',
255
+ padding: '0.6rem 0.7rem',
256
+ borderRadius: 8,
257
+ border: '1px solid var(--dsw-alias-border-l1)',
258
+ background: 'var(--dsw-alias-bg-layer-2)',
259
+ boxShadow: '0 6px 20px rgb(0 0 0 / 18%)',
260
+ display: 'flex',
261
+ flexDirection: 'column',
262
+ gap: '0.35rem',
263
+ },
264
+ usageHead: {
265
+ display: 'flex',
266
+ justifyContent: 'space-between',
267
+ gap: '0.8rem',
268
+ fontSize: '0.78rem',
269
+ fontWeight: 600,
270
+ color: 'var(--dsw-alias-label-primary)',
271
+ },
272
+ usageTable: { display: 'flex', flexDirection: 'column', gap: '0.3rem' },
273
+ usageRow: {
274
+ display: 'grid',
275
+ gridTemplateColumns: 'minmax(0, 1fr) auto',
276
+ gap: '0.7rem',
277
+ alignItems: 'baseline',
278
+ paddingTop: '0.3rem',
279
+ borderTop: '1px solid var(--dsw-alias-border-l1)',
280
+ },
281
+ usageName: {
282
+ overflow: 'hidden',
283
+ textOverflow: 'ellipsis',
284
+ whiteSpace: 'nowrap',
285
+ fontSize: '0.76rem',
286
+ color: 'var(--dsw-alias-label-primary)',
287
+ },
288
+ usageValue: {
289
+ fontSize: '0.76rem',
290
+ color: 'var(--dsw-alias-label-secondary)',
291
+ fontVariantNumeric: 'tabular-nums',
292
+ whiteSpace: 'nowrap',
293
+ },
294
+ usageBuckets: {
295
+ gridColumn: '1 / -1',
296
+ fontSize: '0.7rem',
297
+ color: 'var(--dsw-alias-label-secondary)',
298
+ fontVariantNumeric: 'tabular-nums',
299
+ },
300
+ usageEmpty: { fontSize: '0.76rem', color: 'var(--dsw-alias-label-secondary)' },
301
+ toggleRow: { display: 'flex', gap: '0.5rem', alignItems: 'center' },
302
+ checkbox: { width: '1rem', height: '1rem', accentColor: 'var(--dsw-alias-brand-primary)' },
303
+ notice: { fontSize: '0.76rem', color: 'var(--dsw-alias-label-secondary)' },
304
+ warn: { fontSize: '0.76rem', color: 'var(--dsw-alias-state-warn-primary)' },
305
+ error: { fontSize: '0.76rem', color: 'var(--dsw-alias-state-error-primary)' },
306
+ ok: { fontSize: '0.76rem', color: 'var(--dsw-alias-state-success-primary)' },
307
+ summary: { fontSize: '0.8rem', color: 'var(--dsw-alias-label-secondary)' },
308
+ };
309
+
310
+ const routeKey = (provider, model) => `${provider}\u0000${model}`;
311
+ const parseKey = (raw) => {
312
+ const at = String(raw ?? '').indexOf('\u0000');
313
+ if (at < 0) return undefined;
314
+ const provider = raw.slice(0, at);
315
+ const model = raw.slice(at + 1);
316
+ return provider === '' || model === '' ? undefined : { provider, model };
317
+ };
318
+ const firstRoute = (role) => {
319
+ const models = role && Array.isArray(role.models) ? role.models : [];
320
+ return models.length > 0 ? models[0] : undefined;
321
+ };
322
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
323
+
324
+ function apply(ctx) {
325
+ const safely = (label, fn) => {
326
+ try {
327
+ return fn();
328
+ } catch (error) {
329
+ try {
330
+ console.warn(`[model-manager] ${label}: ${error?.message ?? error}`);
331
+ } catch {
332
+ /* nothing else we can do */
333
+ }
334
+ return undefined;
335
+ }
336
+ };
337
+ /** Register through `ctx.effect` when present, else directly. */
338
+ const use = (fn, label) => (typeof ctx.effect === 'function' ? ctx.effect(fn, label) : fn());
339
+
340
+ safely('locale', () => use(() => ctx.locale.register(LOCALE_NS, { en, zh }), 'model-manager: locale'));
341
+ const t = safely('locale binding', () => ctx.locale.bind(LOCALE_NS)) ?? ((key) => key);
342
+
343
+ // -- model catalog ------------------------------------------------------
344
+ // Shared by every card render; invalidated when adapters change.
345
+ let catalog = { status: 'loading', groups: [], failures: [], error: undefined };
346
+ const listeners = new Set();
347
+ const publish = (next) => {
348
+ catalog = next;
349
+ for (const listener of [...listeners]) {
350
+ try {
351
+ listener();
352
+ } catch {
353
+ /* a broken subscriber must not break the others */
354
+ }
355
+ }
356
+ };
357
+ const subscribe = (listener) => {
358
+ listeners.add(listener);
359
+ return () => listeners.delete(listener);
360
+ };
361
+ const getSnapshot = () => catalog;
362
+
363
+ let generation = 0;
364
+
365
+ /**
366
+ * Session-independent catalog, from the global `remote.llm` directory.
367
+ *
368
+ * `remote.session.modelCatalog()` is served through the session namespace,
369
+ * so it yields nothing when the Settings panel is open with no session —
370
+ * which is why the pickers used to offer only "(unset)" plus the currently
371
+ * configured route. This path lists every configurable provider and then
372
+ * discovers its models, so it works from any page. It carries no reasoning
373
+ * metadata, so the effort picker simply stays hidden in this mode.
374
+ */
375
+ const loadCatalogFromLlm = async () => {
376
+ const listed = await ctx.remote.llm.listConfigurableProviders();
377
+ if (!listed || !listed.ok) throw new Error(String(listed?.error ?? 'listConfigurableProviders refused'));
378
+ const providers = Array.isArray(listed.value) ? listed.value : [];
379
+ const groups = [];
380
+ const failures = [];
381
+ for (const entry of providers) {
382
+ if (entry === null || typeof entry !== 'object' || typeof entry.provider !== 'string') continue;
383
+ const label = typeof entry.displayName === 'string' && entry.displayName !== '' ? entry.displayName : entry.provider;
384
+ if (typeof entry.error === 'string' && entry.error !== '') {
385
+ failures.push({ id: entry.provider, name: label, message: entry.error });
386
+ continue;
387
+ }
388
+ try {
389
+ const answer = await ctx.remote.llm.discoverModels(entry.settingsNs, { provider: entry.provider });
390
+ if (answer && answer.ok && Array.isArray(answer.value)) {
391
+ groups.push({
392
+ id: entry.provider,
393
+ name: label,
394
+ models: answer.value
395
+ .filter((model) => model !== null && typeof model === 'object' && typeof model.id === 'string')
396
+ .map((model) => ({
397
+ id: model.id,
398
+ name: typeof model.name === 'string' && model.name !== '' ? model.name : model.id,
399
+ ...(Array.isArray(model.inputModalities) ? { inputModalities: model.inputModalities } : {}),
400
+ })),
401
+ });
402
+ } else {
403
+ failures.push({ id: entry.provider, name: label, message: String(answer?.error ?? 'discoverModels refused') });
404
+ }
405
+ } catch (error) {
406
+ failures.push({ id: entry.provider, name: label, message: error?.message ?? String(error) });
407
+ }
408
+ }
409
+ return { groups, failures };
410
+ };
411
+
412
+ /**
413
+ * Load the model catalog.
414
+ *
415
+ * Both sources run *concurrently* on purpose. `remote.session.modelCatalog()`
416
+ * is served through the session namespace: it carries each model's reasoning
417
+ * efforts, but with no session open it can reject or never settle, so
418
+ * awaiting it first would gate the whole card — which is exactly how the
419
+ * pickers ended up empty in the Settings panel. The global `remote.llm`
420
+ * directory always answers and is therefore the floor; the session catalog
421
+ * only upgrades the result when it arrives in time.
422
+ */
423
+ const withTimeout = (promise, ms) => Promise.race([
424
+ promise,
425
+ new Promise((resolve) => { setTimeout(() => resolve(undefined), ms); }),
426
+ ]);
427
+
428
+ const fromSessionCatalog = async () => {
429
+ try {
430
+ const response = await withTimeout(ctx.remote.session.modelCatalog(), SESSION_CATALOG_TIMEOUT_MS);
431
+ if (response === undefined) return { timedOut: true };
432
+ if (response.ok) {
433
+ const value = response.value ?? {};
434
+ return {
435
+ groups: Array.isArray(value.groups) ? value.groups : [],
436
+ failures: Array.isArray(value.failures) ? value.failures : [],
437
+ };
438
+ }
439
+ return { error: response.error === undefined ? 'refused without a reason' : String(response.error) };
440
+ } catch (error) {
441
+ return { error: error?.message ?? String(error) };
442
+ }
443
+ };
444
+
445
+ const fromLlmDirectory = async () => {
446
+ try {
447
+ return await loadCatalogFromLlm();
448
+ } catch (error) {
449
+ return { groups: [], failures: [], error: error?.message ?? String(error) };
450
+ }
451
+ };
452
+
453
+ const loadCatalog = async () => {
454
+ const mine = ++generation;
455
+ publish({ status: 'loading', groups: [], failures: [], error: undefined });
456
+
457
+ const sessionPromise = fromSessionCatalog();
458
+ const directoryPromise = fromLlmDirectory();
459
+
460
+ // Publish the global directory the moment it lands, so the pickers are
461
+ // usable even when the session catalog never settles.
462
+ const directory = await directoryPromise;
463
+ if (mine !== generation) return;
464
+ const directoryOk = Array.isArray(directory.groups) && directory.groups.length > 0;
465
+ if (directoryOk) {
466
+ publish({ status: 'ready', groups: directory.groups, failures: directory.failures ?? [], error: undefined });
467
+ }
468
+
469
+ // Then let the session catalog upgrade the result: it is the only source
470
+ // that carries each model's reasoning efforts.
471
+ const session = await sessionPromise;
472
+ if (mine !== generation) return;
473
+ const sessionOk = Array.isArray(session.groups) && session.groups.length > 0;
474
+ if (sessionOk) {
475
+ publish({ status: 'ready', groups: session.groups, failures: session.failures ?? [], error: undefined });
476
+ return;
477
+ }
478
+ if (directoryOk) return; // already published; the session catalog added nothing
479
+
480
+ // Neither source produced models. Report what each one actually did, so
481
+ // an empty picker says why instead of leaving it to guesswork.
482
+ const sessionNote = session.timedOut === true
483
+ ? `timed out after ${SESSION_CATALOG_TIMEOUT_MS}ms (no session open?)`
484
+ : (session.error ?? 'returned no groups');
485
+ const directoryNote = directory.error
486
+ ?? `returned no groups${(directory.failures ?? []).length > 0
487
+ ? ` (${directory.failures.length} provider failure(s))` : ''}`;
488
+ publish({
489
+ status: 'error',
490
+ groups: [],
491
+ failures: [...(session.failures ?? []), ...(directory.failures ?? [])],
492
+ error: `no models from either source — session catalog: ${sessionNote}; llm directory: ${directoryNote}`,
493
+ });
494
+ };
495
+
496
+ // A client half that throws while applying leaves the card unregistered,
497
+ // so every optional collaborator is probed and reported rather than
498
+ // trusted. Mirrors the host half's never-throw discipline.
499
+ void safely('initial catalog load', () => loadCatalog());
500
+ safely('adapter updates', () => use(() => ctx.remote.$on('llm/adapters-updated', () => void loadCatalog()), 'model-manager: adapter updates'));
501
+ safely('settings updates', () => use(() => ctx.remote.$on('settings/document-updated', () => void loadCatalog()), 'model-manager: settings updates'));
502
+
503
+ // -- lookups ------------------------------------------------------------
504
+ const modelIn = (provider, model) => {
505
+ for (const group of catalog.groups) {
506
+ if (group?.id !== provider) continue;
507
+ for (const entry of group.models ?? []) if (entry?.id === model) return entry;
508
+ }
509
+ return undefined;
510
+ };
511
+ const effortsFor = (route) => {
512
+ const entry = route === undefined ? undefined : modelIn(route.provider, route.model);
513
+ const efforts = entry?.reasoning?.efforts;
514
+ return Array.isArray(efforts) ? efforts : [];
515
+ };
516
+ const catalogue = () => catalog.groups.filter((g) => isObject(g) && Array.isArray(g.models));
517
+
518
+ // -- card ---------------------------------------------------------------
519
+ /**
520
+ * Shared per-namespace form, for surfaces that are handed no `form` prop.
521
+ *
522
+ * The Plugins configuration slots pass a `form`; the Settings page slots
523
+ * do not, so that page reads and writes the same namespace through
524
+ * `ctx.configForms`, whose snapshot has the same `{ value, revision,
525
+ * writable, status }` shape and whose `mutate` takes the same operations.
526
+ * Assigned once, inside the `configForms` injection scope below, so the
527
+ * store subscription identities stay stable across renders.
528
+ */
529
+ let settingsForm;
530
+ let settingsSubscribe = () => () => {};
531
+ let settingsGetSnapshot = () => undefined;
532
+
533
+ function Card(props) {
534
+ const state = React.useSyncExternalStore(subscribe, getSnapshot);
535
+ const shared = React.useSyncExternalStore(settingsSubscribe, settingsGetSnapshot);
536
+ const [status, setStatus] = React.useState(null);
537
+ const view = props?.view;
538
+ const form = props?.form ?? settingsForm;
539
+ const snapshot = props?.form?.state ?? shared;
540
+ const value = isObject(snapshot?.value) ? snapshot.value : {};
541
+ const roles = isObject(value.roles) ? value.roles : {};
542
+ const mode = isObject(value.strategy) && typeof value.strategy.mode === 'string' ? value.strategy.mode : 'hybrid';
543
+
544
+ const summary = () => {
545
+ const parts = ROLES
546
+ .map((role) => {
547
+ const route = firstRoute(roles[role]);
548
+ return route ? `${t(roleKeyFor(role))}: ${route.model}` : undefined;
549
+ })
550
+ .filter(Boolean);
551
+ return parts.length > 0 ? parts.join(' · ') : t('summaryEmpty');
552
+ };
553
+
554
+ if (view === 'summary') {
555
+ // The row-list render passes no `form`, so there is nothing to
556
+ // summarise; render nothing and let the row's own description stand
557
+ // rather than claiming no roles are configured.
558
+ if (snapshot === undefined) return null;
559
+ return h('span', { style: S.summary }, summary());
560
+ }
561
+ if (snapshot === undefined) {
562
+ // A page render without a form cannot read or write. Say so instead of
563
+ // sitting on a misleading "loading" state.
564
+ return h('div', { style: S.warn }, t('noForm'));
565
+ }
566
+ if (snapshot.status === 'unavailable') return h('div', { style: S.warn }, t('unavailable'));
567
+
568
+ const ready = snapshot.status === 'ready' && snapshot.writable !== false;
569
+ const write = async (ops) => {
570
+ setStatus(null);
571
+ try {
572
+ const accepted = await form.mutate(ops, snapshot.revision);
573
+ setStatus(accepted ? { kind: 'ok', text: t('saved') } : { kind: 'err', text: t('refused') });
574
+ } catch (error) {
575
+ setStatus({ kind: 'err', text: error?.message ?? String(error) });
576
+ }
577
+ };
578
+
579
+ /** The role's configured routes, normalized and order-preserving. */
580
+ const roleModels = (role) => {
581
+ const holder = roles[role];
582
+ const list = holder !== null && typeof holder === 'object' && Array.isArray(holder.models)
583
+ ? holder.models : [];
584
+ return list.filter((route) => route !== null && typeof route === 'object'
585
+ && typeof route.provider === 'string' && typeof route.model === 'string');
586
+ };
587
+ // Every edit rewrites the whole list in one atomic operation, so order,
588
+ // removals and effort changes cannot interleave into a partial state.
589
+ const saveModels = (role, next) => write([{ op: 'set', path: ['roles', role, 'models'], value: next }]);
590
+
591
+ /** Catalog models as grouped options, minus every key in `exclude`. */
592
+ const modelOptions = (exclude) => {
593
+ const out = [];
594
+ for (const group of catalogue()) {
595
+ const options = (group.models ?? [])
596
+ .filter((entry) => entry !== null && typeof entry === 'object' && typeof entry.id === 'string')
597
+ .filter((entry) => !exclude.has(routeKey(group.id, entry.id)))
598
+ .map((entry) => h('option', {
599
+ key: routeKey(group.id, entry.id),
600
+ value: routeKey(group.id, entry.id),
601
+ }, entry.name && entry.name !== entry.id ? `${entry.name} — ${entry.id}` : entry.id));
602
+ if (options.length > 0) out.push(h('optgroup', { key: group.id, label: group.name ?? group.id }, ...options));
603
+ }
604
+ return out;
605
+ };
606
+
607
+ const row = (role) => {
608
+ const models = roleModels(role);
609
+ const used = new Set(models.map((route) => routeKey(route.provider, route.model)));
610
+
611
+ // Every control of one role's editor is a child of a single grid, so the
612
+ // column tracks — index, model, effort, actions — line up across rows by
613
+ // construction instead of by luck.
614
+ const cells = [];
615
+ models.forEach((route, index) => {
616
+ const key = routeKey(route.provider, route.model);
617
+ const known = catalogue().some((group) => group.id === route.provider
618
+ && (group.models ?? []).some((entry) => entry?.id === route.model));
619
+ const options = modelOptions(new Set());
620
+ // A configured route the catalog no longer advertises must stay
621
+ // selectable, or the control would silently show a different value.
622
+ if (!known) options.push(h('option', { key: 'current', value: key },
623
+ `${route.provider}/${route.model} (${t('notInCatalog')})`));
624
+
625
+ cells.push(h('span', { key: `${key}#i`, style: S.cellIndex }, String(index + 1)));
626
+
627
+ cells.push(h('select', {
628
+ key: `${key}#m`,
629
+ style: S.selectGrid,
630
+ value: key,
631
+ disabled: !ready,
632
+ 'aria-label': `${t(roleKeyFor(role))} ${index + 1}`,
633
+ onChange: (event) => {
634
+ const next = parseKey(event.target.value);
635
+ if (next === undefined) return undefined;
636
+ const copy = models.slice();
637
+ copy[index] = {
638
+ provider: next.provider,
639
+ model: next.model,
640
+ ...(typeof route.reasoningEffort === 'string' ? { reasoningEffort: route.reasoningEffort } : {}),
641
+ };
642
+ return saveModels(role, copy);
643
+ },
644
+ }, ...options));
645
+
646
+ const efforts = effortsFor(route);
647
+ // A row with no effort control still occupies the column, otherwise the
648
+ // action buttons of every row beneath it would sit at a different x.
649
+ cells.push(efforts.length === 0
650
+ ? h('span', { key: `${key}#gap`, 'aria-hidden': true })
651
+ : h('select', {
652
+ key: `${key}#e`,
653
+ style: { ...S.selectGrid, ...S.selectEffortGrid },
654
+ value: typeof route.reasoningEffort === 'string' ? route.reasoningEffort : '',
655
+ disabled: !ready,
656
+ 'aria-label': `${t(roleKeyFor(role))} ${index + 1} — ${t('effort')}`,
657
+ onChange: (event) => {
658
+ const chosen = event.target.value;
659
+ const copy = models.slice();
660
+ copy[index] = { provider: route.provider, model: route.model };
661
+ if (chosen !== '') copy[index].reasoningEffort = chosen;
662
+ return saveModels(role, copy);
663
+ },
664
+ },
665
+ h('option', { key: '', value: '' }, t('effortDefault')),
666
+ ...efforts.map((effort) => h('option', { key: effort.id, value: effort.id },
667
+ effort.name && effort.name !== effort.id ? `${effort.name} — ${effort.id}` : effort.id))));
668
+
669
+ // Both actions always render; the first row's "move up" is disabled
670
+ // rather than absent, so the column width never shifts while reordering
671
+ // and the glyphs keep the row the same width in every locale.
672
+ cells.push(h('span', { key: `${key}#a`, style: S.actions },
673
+ h('button', {
674
+ type: 'button',
675
+ style: index === 0 ? { ...S.action, ...S.actionOff } : S.action,
676
+ disabled: !ready || index === 0,
677
+ 'aria-label': `${t('moveUp')} ${index + 1}`,
678
+ title: t('moveUp'),
679
+ onClick: () => {
680
+ const copy = models.slice();
681
+ const [moved] = copy.splice(index, 1);
682
+ copy.splice(index - 1, 0, moved);
683
+ return saveModels(role, copy);
684
+ },
685
+ }, '↑'),
686
+ h('button', {
687
+ type: 'button',
688
+ style: S.action,
689
+ disabled: !ready,
690
+ 'aria-label': `${t('remove')} ${index + 1}`,
691
+ title: t('remove'),
692
+ onClick: () => saveModels(role, models.filter((_, position) => position !== index)),
693
+ }, '×')));
694
+ });
695
+
696
+ // Add reads as an affordance, not as another configured model: dashed
697
+ // border, no fill, muted text, and it spans the value columns.
698
+ cells.push(h('select', {
699
+ key: 'add',
700
+ style: { ...S.selectGrid, ...S.selectAdd, ...S.cellSpan },
701
+ value: '',
702
+ disabled: !ready,
703
+ 'aria-label': `${t(roleKeyFor(role))} — ${t('addModel')}`,
704
+ onChange: (event) => {
705
+ const next = parseKey(event.target.value);
706
+ if (next === undefined) return undefined;
707
+ return saveModels(role, [...models, { provider: next.provider, model: next.model }]);
708
+ },
709
+ },
710
+ h('option', { key: '', value: '' }, t('addModel')),
711
+ ...modelOptions(used)));
712
+
713
+ if (models.length > 1) {
714
+ const holder = roles[role];
715
+ const pick = holder !== null && typeof holder === 'object' && holder.pick === 'round-robin'
716
+ ? 'round-robin' : 'first';
717
+ cells.push(h('span', {
718
+ key: 'pick',
719
+ style: { ...S.cellSpan, display: 'inline-flex', alignItems: 'center', gap: '0.45rem' },
720
+ },
721
+ h('span', { style: S.pickLabel }, t('pick')),
722
+ h('select', {
723
+ style: { ...S.selectGrid, ...S.selectEffortGrid },
724
+ value: pick,
725
+ disabled: !ready,
726
+ 'aria-label': `${t(roleKeyFor(role))} — ${t('pick')}`,
727
+ onChange: (event) => write([{ op: 'set', path: ['roles', role, 'pick'], value: event.target.value }]),
728
+ },
729
+ h('option', { key: 'first', value: 'first' }, t('pickFirst')),
730
+ h('option', { key: 'rr', value: 'round-robin' }, t('pickRoundRobin')))));
731
+ }
732
+
733
+ return h('div', { key: role, style: S.row },
734
+ h('label', { style: S.label }, t(roleKeyFor(role))),
735
+ h('span', { style: S.hint }, t(hintKeyFor(role))),
736
+ h('div', { style: S.entryGrid }, ...cells),
737
+ models.length > 1 ? h('span', { key: 'oh', style: S.hint }, t('orderHint')) : null);
738
+ };
739
+
740
+ const modeControl = h('div', { style: S.row },
741
+ h('label', { style: S.label }, t('mode')),
742
+ h('div', { style: S.controls },
743
+ h('select', {
744
+ style: S.select,
745
+ value: MODES.includes(mode) ? mode : 'hybrid',
746
+ disabled: !ready,
747
+ 'aria-label': t('mode'),
748
+ onChange: (event) => write([{ op: 'set', path: ['strategy', 'mode'], value: event.target.value }]),
749
+ }, ...MODES.map((name) => h('option', { key: name, value: name }, t(modeKeyFor(name)))))));
750
+
751
+ const notices = [];
752
+ if (!ready && snapshot.status === 'ready') notices.push(h('div', { key: 'ro', style: S.notice }, t('readOnly')));
753
+ if (state.status === 'loading') notices.push(h('div', { key: 'load', style: S.notice }, t('loading')));
754
+ if (state.status === 'error') {
755
+ notices.push(h('div', { key: 'err', style: S.error }, state.error ?? t('unavailable')));
756
+ }
757
+ if (state.status === 'ready' && catalogue().length === 0) {
758
+ notices.push(h('div', { key: 'none', style: S.notice }, t('noModels')));
759
+ }
760
+ if (state.status === 'ready' && state.failures.length > 0) {
761
+ notices.push(h('div', { key: 'fail', style: S.warn },
762
+ `${t('providersFailed')} ${state.failures.map((f) => f?.name ?? f?.id ?? '?').join(', ')}`));
763
+ }
764
+ if (status !== null) {
765
+ notices.push(h('div', {
766
+ key: 'status',
767
+ style: status.kind === 'ok' ? S.ok : S.error,
768
+ }, status.text));
769
+ }
770
+
771
+ // Master switch. Off still records what each session ran on, so the
772
+ // report stays useful; it only stops rewriting routes.
773
+ const enableToggle = h('div', { style: S.row },
774
+ h('label', { style: S.toggleRow },
775
+ h('input', {
776
+ type: 'checkbox',
777
+ style: S.checkbox,
778
+ checked: value.enabled !== false,
779
+ disabled: !ready,
780
+ 'aria-label': t('enable'),
781
+ onChange: (event) => write([{ op: 'set', path: ['enabled'], value: event.target.checked === true }]),
782
+ }),
783
+ h('span', { style: S.label }, t('enable'))),
784
+ h('span', { style: S.hint }, t('enableHint')));
785
+
786
+ return h('div', { style: S.root },
787
+ h('p', { style: S.help }, t('help')),
788
+ enableToggle,
789
+ ...ROLES.map((role) => row(role)),
790
+ modeControl,
791
+ ...notices);
792
+ }
793
+
794
+ // One surface only, as requested: a page in the Settings panel
795
+ // (`sidebar.settings` → `settings.section`). The Plugins page slots
796
+ // (`plugins.item`, `plugins.row.config`) are deliberately not registered.
797
+ //
798
+ // Registered *unconditionally* on purpose. The shipped pattern gates a page
799
+ // behind `configForms.whileServed([ns], …)`, but the Host only serves a
800
+ // namespace when the row has a Config schema with volatile fields — so if
801
+ // this plugin's optional schema dependency ever failed to resolve, that
802
+ // gate would hide the page entirely and a packaging problem would look
803
+ // exactly like a missing feature. The entry is therefore always reachable,
804
+ // and the card itself reports why it cannot show values.
805
+ // -- per-session model usage, rendered in the session header -------------
806
+ // The host half folds `modelManagerUsage` out of the durable session log and
807
+ // ships it as a wired projection, so this half only subscribes to a finished
808
+ // value: no folding here, no polling, and the numbers survive a restart.
809
+ function UsageView(props) {
810
+ const face = props.face ?? null;
811
+ const subscribe = React.useMemo(
812
+ () => (face === null ? () => () => {} : (listener) => face.subscribe(listener)),
813
+ [face],
814
+ );
815
+ const getSnapshot = React.useMemo(
816
+ () => (face === null ? () => undefined : () => face.getSnapshot()),
817
+ [face],
818
+ );
819
+ const value = React.useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
820
+ const [open, setOpen] = React.useState(false);
821
+ const routes = Array.isArray(value?.routes) ? value.routes : [];
822
+ if (routes.length === 0) return null;
823
+ const total = routes.reduce((sum, route) => sum + (Number.isSafeInteger(route.totalTokens) ? route.totalTokens : 0), 0);
824
+ const rows = [...routes].sort((a, b) => (b.totalTokens ?? 0) - (a.totalTokens ?? 0));
825
+ const head = [
826
+ h('div', { key: 'h', style: S.usageHead }, [
827
+ h('span', null, t('usageTitle')),
828
+ h('span', null, formatTokens(total)),
829
+ ]),
830
+ ];
831
+ for (const route of rows) {
832
+ const label = `${route.provider}/${route.model}`;
833
+ head.push(h('div', { key: label, style: S.usageRow }, [
834
+ h('span', { style: S.usageName, title: label }, label),
835
+ h('span', { style: S.usageValue }, formatTokens(route.totalTokens)),
836
+ h('span', { style: S.usageBuckets }, [
837
+ t('usageUncachedInput'), ' ', formatTokens(route.uncachedInputTokens),
838
+ ' · ', t('usageOutput'), ' ', formatTokens(route.outputTokens),
839
+ ...(route.cacheReadTokens > 0 ? [' · ', t('usageCacheRead'), ' ', formatTokens(route.cacheReadTokens)] : []),
840
+ ...(route.cacheWriteTokens > 0 ? [' · ', t('usageCacheWrite'), ' ', formatTokens(route.cacheWriteTokens)] : []),
841
+ ' · ', t('usageRequests', { count: route.requests }),
842
+ ].join('')),
843
+ ]));
844
+ }
845
+ head.push(h('div', { key: 'hint', style: S.usageEmpty }, t('usageHint')));
846
+ return h('span', { style: S.usage }, [
847
+ h('button', {
848
+ type: 'button',
849
+ style: S.usageButton,
850
+ 'aria-haspopup': 'dialog',
851
+ 'aria-expanded': open,
852
+ onClick: () => setOpen((current) => !current),
853
+ }, [ t('usageTitle'), ' ', formatTokens(total), ' · ', String(rows.length)],
854
+ ),
855
+ ...(open ? [h('div', { style: S.usagePanel, role: 'dialog', 'aria-label': t('usageTitle') }, head)] : []),
856
+ ]);
857
+ }
858
+
859
+ safely('session usage surface', () => ctx.inject(['sessions'], (scoped) => {
860
+ const sessions = scoped.sessions;
861
+ if (sessions === undefined || typeof sessions.binding !== 'function') {
862
+ console.warn('[model-manager] no sessions service; per-session model usage is unavailable');
863
+ return undefined;
864
+ }
865
+ return ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register({
866
+ name: 'conversation.session.header.utilities',
867
+ id: 'model-manager-usage',
868
+ order: 60,
869
+ locale: LOCALE_NS,
870
+ inject: (sessionId) => {
871
+ let face;
872
+ try {
873
+ face = sessions.binding(sessionId)?.session?.projections?.faceOf?.(USAGE_PROJECTION_KEY);
874
+ } catch (error) {
875
+ console.warn(`[model-manager] projection face unavailable: ${error?.message ?? error}`);
876
+ face = undefined;
877
+ }
878
+ return { sessionId, face: face ?? null };
879
+ },
880
+ }, UsageView));
881
+ }));
882
+
883
+ safely('settings page', () => use(() => ctx.slots.inject('settings.section', () => {
884
+ const disposer = ctx.slots.register({
885
+ name: 'settings.section',
886
+ id: 'model-manager',
887
+ order: 50,
888
+ label: () => t('title'),
889
+ }, Card);
890
+ // A positive line at the moment the card actually lands. The apply-time
891
+ // summary below cannot know whether this ran: `slots.inject` waits for the
892
+ // owning declaration, so a count taken there would read 0 even on success.
893
+ try {
894
+ console.log('[model-manager] settings card registered');
895
+ } catch {
896
+ /* logging is best-effort */
897
+ }
898
+ return disposer;
899
+ }), 'model-manager: settings page'));
900
+
901
+ // Bind the shared per-namespace form when the Host serves it. This runs at
902
+ // apply time, well before the user can navigate to the page, so the card's
903
+ // first render already sees it.
904
+ safely('settings form', () => ctx.inject(['configForms'], (scoped) => {
905
+ settingsForm = safely('settings form get', () => scoped.configForms.get(ROW_NS));
906
+ if (settingsForm !== undefined) {
907
+ if (typeof settingsForm.subscribe === 'function') settingsSubscribe = settingsForm.subscribe.bind(settingsForm);
908
+ if (typeof settingsForm.getSnapshot === 'function') settingsGetSnapshot = settingsForm.getSnapshot.bind(settingsForm);
909
+ }
910
+ }));
911
+
912
+ // One success line, so the browser console distinguishes "never applied"
913
+ // from "applied but a step failed" (each failed step logs its own
914
+ // `[model-manager] <step>: <error>` warning immediately above this).
915
+ try {
916
+ console.log('[model-manager] client half applied; locale registered, 2 surfaces awaited (settings section, session header utilities)');
917
+ } catch {
918
+ /* logging is best-effort */
919
+ }
920
+ }
921
+
922
+ function formatTokens(value) {
923
+ const n = Number.isSafeInteger(value) && value >= 0 ? value : 0;
924
+ if (n >= 1000000) return `${(n / 1000000).toFixed(n >= 10000000 ? 0 : 1)}M`;
925
+ if (n >= 1000) return `${(n / 1000).toFixed(n >= 10000 ? 0 : 1)}k`;
926
+ return String(n);
927
+ }
928
+
929
+ function roleKeyFor(role) {
930
+ return role === 'main' ? 'roleMain'
931
+ : role === 'planning' ? 'rolePlanning'
932
+ : role === 'execution' ? 'roleExecution'
933
+ : 'roleVision';
934
+ }
935
+ function hintKeyFor(role) {
936
+ return role === 'main' ? 'roleMainHint'
937
+ : role === 'planning' ? 'rolePlanningHint'
938
+ : role === 'execution' ? 'roleExecutionHint'
939
+ : 'roleVisionHint';
940
+ }
941
+ function modeKeyFor(mode) {
942
+ return mode === 'managed' ? 'modeManaged' : mode === 'advisory' ? 'modeAdvisory' : 'modeHybrid';
943
+ }
944
+
945
+ return {
946
+ // Each `remote.<namespace>` is its own cordis service, installed when the
947
+ // package contributing it applies — `remote` itself existing does not mean
948
+ // `remote.llm` or `remote.session` do. Declaring them here parks this half
949
+ // until they are mounted. Without that, `apply` ran first and both were
950
+ // `undefined`, which is exactly what emptied the model pickers.
951
+ inject: ['slots', 'locale', 'remote', 'remote.llm', 'remote.session'],
952
+ apply,
953
+ };
954
+ },
955
+ });