omnicell-router 0.8.1 → 0.8.4

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.
Files changed (89) hide show
  1. package/backend/dist/auth/api-keys.js +11 -0
  2. package/backend/dist/auth/key-models.d.ts +36 -0
  3. package/backend/dist/auth/key-models.js +99 -0
  4. package/backend/dist/cli/clients/activity.d.ts +35 -0
  5. package/backend/dist/cli/clients/activity.js +69 -0
  6. package/backend/dist/cli/clients/codex.d.ts +70 -0
  7. package/backend/dist/cli/clients/codex.js +470 -57
  8. package/backend/dist/cli/clients/follow-catalog-sync.d.ts +62 -0
  9. package/backend/dist/cli/clients/follow-catalog-sync.js +435 -0
  10. package/backend/dist/cli/clients/index.js +7 -1
  11. package/backend/dist/cli/clients/opencode.js +3 -2
  12. package/backend/dist/cli/clients/reserved.js +2 -0
  13. package/backend/dist/cli/types.d.ts +18 -0
  14. package/backend/dist/config/comments-en.js +5 -1
  15. package/backend/dist/config/comments-zh.js +5 -1
  16. package/backend/dist/config/defaults.d.ts +98 -1
  17. package/backend/dist/config/defaults.js +98 -1
  18. package/backend/dist/config/index.d.ts +15 -1
  19. package/backend/dist/config/index.js +35 -1
  20. package/backend/dist/config/migrations/v4-to-v5.d.ts +36 -0
  21. package/backend/dist/config/migrations/v4-to-v5.js +42 -0
  22. package/backend/dist/config/migrations/v5-to-v6.d.ts +27 -0
  23. package/backend/dist/config/migrations/v5-to-v6.js +29 -0
  24. package/backend/dist/config/schema.d.ts +3 -3
  25. package/backend/dist/config/schema.js +8 -4
  26. package/backend/dist/config/types.d.ts +54 -3
  27. package/backend/dist/forward-proxy/egress.js +13 -0
  28. package/backend/dist/forward-proxy/h2-forward.js +6 -5
  29. package/backend/dist/forward-proxy/index.js +5 -0
  30. package/backend/dist/forward-proxy/server.d.ts +12 -0
  31. package/backend/dist/forward-proxy/server.js +113 -15
  32. package/backend/dist/index.js +6 -1
  33. package/backend/dist/ir/adapters/openai-chat.js +5 -3
  34. package/backend/dist/ir/adapters/openai-responses-output.js +2 -2
  35. package/backend/dist/ir/adapters/openai-responses.d.ts +33 -0
  36. package/backend/dist/ir/adapters/openai-responses.js +44 -2
  37. package/backend/dist/ir/capabilities.js +4 -0
  38. package/backend/dist/ir/validate.d.ts +24 -0
  39. package/backend/dist/ir/validate.js +113 -63
  40. package/backend/dist/opencode/catalog/auto-pull.js +8 -7
  41. package/backend/dist/opencode/catalog/ocr-store.d.ts +7 -6
  42. package/backend/dist/opencode/catalog/ocr-store.js +2 -2
  43. package/backend/dist/opencode/catalog/overrides-store.d.ts +5 -3
  44. package/backend/dist/opencode/catalog/overrides-store.js +22 -19
  45. package/backend/dist/opencode/catalog/repository.js +3 -3
  46. package/backend/dist/opencode/catalog/sources/models-dev.d.ts +3 -3
  47. package/backend/dist/opencode/catalog/sources/models-dev.js +29 -11
  48. package/backend/dist/opencode/catalog/types.d.ts +7 -9
  49. package/backend/dist/opencode/credentials/def-materialize.js +27 -21
  50. package/backend/dist/opencode/migrate/engine.d.ts +20 -0
  51. package/backend/dist/opencode/migrate/engine.js +71 -0
  52. package/backend/dist/opencode/migrate/migrator.d.ts +11 -0
  53. package/backend/dist/opencode/migrate/migrator.js +6 -0
  54. package/backend/dist/opencode/migrate/steps/overrides-v1-to-v2.d.ts +6 -0
  55. package/backend/dist/opencode/migrate/steps/overrides-v1-to-v2.js +31 -0
  56. package/backend/dist/opencode/migrate/steps/providers-v1-to-v2.d.ts +6 -0
  57. package/backend/dist/opencode/migrate/steps/providers-v1-to-v2.js +62 -0
  58. package/backend/dist/opencode/provider-def-adapters.d.ts +12 -11
  59. package/backend/dist/opencode/provider-def-adapters.js +43 -27
  60. package/backend/dist/opencode/provider-defs.d.ts +10 -16
  61. package/backend/dist/opencode/provider-defs.js +45 -45
  62. package/backend/dist/opencode/user-config.d.ts +23 -26
  63. package/backend/dist/opencode/user-config.js +95 -77
  64. package/backend/dist/pipeline/orchestrator.js +17 -7
  65. package/backend/dist/plugins/builtin/model-gateway.js +38 -12
  66. package/backend/dist/plugins/host.d.ts +2 -2
  67. package/backend/dist/plugins/host.js +15 -12
  68. package/backend/dist/providers/boot-direct.js +32 -8
  69. package/backend/dist/providers/dial-wire.d.ts +17 -0
  70. package/backend/dist/providers/dial-wire.js +49 -0
  71. package/backend/dist/providers/protocols-field.d.ts +24 -0
  72. package/backend/dist/providers/protocols-field.js +66 -0
  73. package/backend/dist/providers/registry.d.ts +3 -1
  74. package/backend/dist/providers/registry.js +23 -7
  75. package/backend/dist/quota/cli-login.js +3 -1
  76. package/backend/dist/routes/console.js +120 -95
  77. package/backend/dist/server.js +99 -2
  78. package/backend/dist/surfaces/anthropic.js +4 -1
  79. package/backend/dist/surfaces/body-admission.d.ts +279 -0
  80. package/backend/dist/surfaces/body-admission.js +613 -0
  81. package/backend/dist/surfaces/transport-node-http.d.ts +44 -5
  82. package/backend/dist/surfaces/transport-node-http.js +86 -13
  83. package/backend/dist/utils/server-liveness.d.ts +27 -0
  84. package/backend/dist/utils/server-liveness.js +31 -0
  85. package/frontend/dist/assets/{index-Cn3QMOQx.js → index-Dk76uc7e.js} +398 -363
  86. package/frontend/dist/assets/{index-DxZ9MHKB.css → index-KI1OW5x6.css} +1 -1
  87. package/frontend/dist/assets/workbuddy.color-DOMpQkxJ.svg +29 -0
  88. package/frontend/dist/index.html +2 -2
  89. package/package.json +1 -1
@@ -0,0 +1,435 @@
1
+ /**
2
+ * Follow-catalog auto-resync — event-driven rewrite of follow-mode snapshots.
3
+ *
4
+ * Triggers (callers): API key `modelAccess` edits (`reason: 'key'`) and live
5
+ * model-pool rebuilds (`reason: 'pool'`). enabled / expiry / delete do not fire
6
+ * — they only affect auth. Debounced, not polled. Targets:
7
+ * - config hooks with clientProfileMemory.modelMode === 'follow' + hooked
8
+ * - gateway plugins with modelListMode === 'follow' + bound key
9
+ *
10
+ * Auto path never sets acknowledgeRunning — running clients land in `pending`.
11
+ * No background retry loop: debounce coalesces bursts; open issues wait for a
12
+ * manual POST .../retry (may acknowledgeRunning) or the next key/pool event.
13
+ * Auto-polling ide_running would write behind the operator's back; hard fails
14
+ * (api_key_unusable, adapter errors) do not heal by waiting.
15
+ * Not a profile write-through (ADR-0031): N targeted setups / plugin config writes.
16
+ */
17
+ import { DEFAULT_AUTO_RESYNC_FOLLOW_CATALOGS, FOLLOW_CATALOG_KEY_DEBOUNCE_MS, FOLLOW_CATALOG_POOL_DEBOUNCE_MS, } from '../../config/defaults.js';
18
+ import { loadConfig, saveConfig } from '../../config/index.js';
19
+ import { isApiKeyUsable, listApiKeys } from '../../auth/api-keys.js';
20
+ import { allowedFollowLists, buildKeyModelsView } from '../../auth/key-models.js';
21
+ import { getClientAdapter, getAllClientAdapters, setupClient } from './index.js';
22
+ let registryRef;
23
+ const fingerprints = new Map();
24
+ /** In-process until success — drives card/banner hints (cleared on restart). */
25
+ const issues = new Map();
26
+ let lastRun;
27
+ let keyTimer;
28
+ let poolTimer;
29
+ /** Coalesce concurrent key edits — a single keyId would drop earlier keys. */
30
+ const pendingKeyIds = new Set();
31
+ let inFlight;
32
+ export function setFollowCatalogSyncRegistry(registry) {
33
+ registryRef = registry;
34
+ }
35
+ /** Resolve the kill switch: explicit false disables; absent → default ON. */
36
+ export function isFollowCatalogAutoResyncEnabled() {
37
+ const v = loadConfig().autoResyncFollowCatalogs;
38
+ if (v === false)
39
+ return false;
40
+ if (v === true)
41
+ return true;
42
+ return DEFAULT_AUTO_RESYNC_FOLLOW_CATALOGS;
43
+ }
44
+ function fingerprintOf(ids) {
45
+ return [...ids].sort().join('\n');
46
+ }
47
+ function issueKey(kind, id) {
48
+ return `${kind}:${id}`;
49
+ }
50
+ function noteIssue(kind, id, status, reason, apiKeyId) {
51
+ issues.set(issueKey(kind, id), {
52
+ id,
53
+ kind,
54
+ status,
55
+ reason,
56
+ ...(apiKeyId ? { apiKeyId } : {}),
57
+ at: Date.now(),
58
+ });
59
+ }
60
+ function clearIssue(kind, id) {
61
+ issues.delete(issueKey(kind, id));
62
+ }
63
+ export function getFollowCatalogSyncState() {
64
+ const all = [...issues.values()];
65
+ return {
66
+ enabled: isFollowCatalogAutoResyncEnabled(),
67
+ pending: all.filter((i) => i.status === 'pending').map((i) => i.id),
68
+ failed: all.filter((i) => i.status === 'failed').map((i) => i.id),
69
+ issues: all,
70
+ ...(lastRun ? { lastRun } : {}),
71
+ };
72
+ }
73
+ export function isFollowCatalogPending(clientOrPluginId) {
74
+ const c = issues.get(issueKey('client', clientOrPluginId));
75
+ const g = issues.get(issueKey('gateway', clientOrPluginId));
76
+ return c?.status === 'pending' || g?.status === 'pending';
77
+ }
78
+ /** Issue for a client name or its catalogPlugin id (card hint). */
79
+ export function getFollowCatalogIssue(clientOrPluginId) {
80
+ return (issues.get(issueKey('client', clientOrPluginId)) ||
81
+ issues.get(issueKey('gateway', clientOrPluginId)));
82
+ }
83
+ /**
84
+ * Schedule a sync pass. Key edits coalesce into a Set (multi-key → one pool
85
+ * pass so no earlier keyId is dropped); pool rebuilds share one 2s timer.
86
+ */
87
+ export function requestFollowCatalogSync(req) {
88
+ if (!isFollowCatalogAutoResyncEnabled())
89
+ return;
90
+ if (req.reason === 'key') {
91
+ if (req.keyId)
92
+ pendingKeyIds.add(req.keyId);
93
+ if (keyTimer)
94
+ clearTimeout(keyTimer);
95
+ keyTimer = setTimeout(() => {
96
+ keyTimer = undefined;
97
+ const ids = [...pendingKeyIds];
98
+ pendingKeyIds.clear();
99
+ if (ids.length === 0) {
100
+ void runFollowCatalogSync({ reason: 'pool' });
101
+ }
102
+ else if (ids.length === 1) {
103
+ void runFollowCatalogSync({ reason: 'key', keyId: ids[0] });
104
+ }
105
+ else {
106
+ // Several keys changed inside the debounce window — one pool pass
107
+ // covers every follow target instead of dropping all but the last id.
108
+ void runFollowCatalogSync({ reason: 'pool' });
109
+ }
110
+ }, FOLLOW_CATALOG_KEY_DEBOUNCE_MS);
111
+ return;
112
+ }
113
+ if (poolTimer)
114
+ clearTimeout(poolTimer);
115
+ poolTimer = setTimeout(() => {
116
+ poolTimer = undefined;
117
+ void runFollowCatalogSync({ reason: 'pool' });
118
+ }, FOLLOW_CATALOG_POOL_DEBOUNCE_MS);
119
+ }
120
+ /** Retry every open issue (pending + failed). May pass acknowledgeRunning. */
121
+ export async function retryFollowCatalogPending(opts) {
122
+ const snapshot = [...issues.values()]
123
+ .filter((i) => !!i.apiKeyId)
124
+ .map((i) => ({ kind: i.kind, id: i.id, apiKeyId: i.apiKeyId }));
125
+ // Nothing open: an empty retry must NOT fall through to a full pool pass —
126
+ // that would re-setup every follow client and fabricate pending issues for
127
+ // running apps the operator never asked to touch. Answer an empty run.
128
+ if (issues.size === 0) {
129
+ return {
130
+ at: Date.now(),
131
+ reason: 'pool',
132
+ synced: 0,
133
+ skipped: 0,
134
+ failed: 0,
135
+ errors: [],
136
+ };
137
+ }
138
+ // Issues without apiKeyId (rare) still need a rematch from memory/plugin —
139
+ // fall through to a full pool pass when the snapshot is empty but issues remain.
140
+ if (snapshot.length === 0) {
141
+ return runFollowCatalogSync({
142
+ reason: 'pool',
143
+ acknowledgeRunning: opts?.acknowledgeRunning === true,
144
+ });
145
+ }
146
+ return runFollowCatalogSync({
147
+ reason: 'pool',
148
+ onlyPending: snapshot,
149
+ acknowledgeRunning: opts?.acknowledgeRunning === true,
150
+ });
151
+ }
152
+ async function runFollowCatalogSync(opts) {
153
+ // Serialize runs so a key edit mid-pool-pass does not interleave writes.
154
+ const wait = inFlight ?? Promise.resolve();
155
+ let resolve;
156
+ inFlight = new Promise((r) => {
157
+ resolve = r;
158
+ });
159
+ await wait;
160
+ try {
161
+ return await runFollowCatalogSyncInner(opts);
162
+ }
163
+ finally {
164
+ resolve();
165
+ }
166
+ }
167
+ async function runFollowCatalogSyncInner(opts) {
168
+ const run = {
169
+ at: Date.now(),
170
+ reason: opts.reason,
171
+ ...(opts.keyId ? { keyId: opts.keyId } : {}),
172
+ synced: 0,
173
+ skipped: 0,
174
+ failed: 0,
175
+ errors: [],
176
+ };
177
+ if (!isFollowCatalogAutoResyncEnabled() && !opts.onlyPending) {
178
+ lastRun = run;
179
+ return run;
180
+ }
181
+ const registry = registryRef;
182
+ if (!registry) {
183
+ run.failed += 1;
184
+ run.errors.push({ target: '*', reason: 'registry_unavailable' });
185
+ lastRun = run;
186
+ return run;
187
+ }
188
+ if (opts.onlyPending && opts.onlyPending.length > 0) {
189
+ for (const entry of opts.onlyPending) {
190
+ if (entry.kind === 'client') {
191
+ await syncConfigClient(entry.id, entry.apiKeyId, registry, run, opts.acknowledgeRunning === true);
192
+ }
193
+ else {
194
+ await syncGatewayPlugin(entry.id, entry.apiKeyId, registry, run);
195
+ }
196
+ }
197
+ lastRun = run;
198
+ return run;
199
+ }
200
+ const mem = loadConfig().clientProfileMemory || {};
201
+ for (const [name, entry] of Object.entries(mem)) {
202
+ if (entry?.modelMode !== 'follow' || !entry.apiKeyId)
203
+ continue;
204
+ if (opts.reason === 'key' && opts.keyId && entry.apiKeyId !== opts.keyId)
205
+ continue;
206
+ await syncConfigClient(name, entry.apiKeyId, registry, run, false);
207
+ }
208
+ await syncAllGatewayFollow(opts, registry, run);
209
+ lastRun = run;
210
+ return run;
211
+ }
212
+ async function syncConfigClient(name, apiKeyId, registry, run, acknowledgeRunning) {
213
+ // Checked here, not only in the caller's loop: a manual retry arrives from the
214
+ // issue map, which a leave-follow edit that bypassed the stamp never visited.
215
+ const memEntry = (loadConfig().clientProfileMemory || {})[name];
216
+ if (memEntry?.modelMode !== 'follow') {
217
+ clearIssue('client', name);
218
+ fingerprints.delete(issueKey('client', name));
219
+ run.skipped += 1;
220
+ return;
221
+ }
222
+ const adapter = getClientAdapter(name);
223
+ if (!adapter) {
224
+ run.skipped += 1;
225
+ return;
226
+ }
227
+ let status;
228
+ try {
229
+ status = await adapter.getStatus();
230
+ }
231
+ catch (err) {
232
+ const reason = err instanceof Error ? err.message : String(err);
233
+ run.failed += 1;
234
+ run.errors.push({ target: name, reason });
235
+ noteIssue('client', name, 'failed', reason, apiKeyId);
236
+ return;
237
+ }
238
+ if (!status.hooked) {
239
+ clearIssue('client', name);
240
+ run.skipped += 1;
241
+ return;
242
+ }
243
+ const keys = listApiKeys(false);
244
+ const key = keys.find((k) => k.id === apiKeyId);
245
+ if (!key || !isApiKeyUsable(key)) {
246
+ run.failed += 1;
247
+ run.errors.push({ target: name, reason: 'api_key_unusable' });
248
+ noteIssue('client', name, 'failed', 'api_key_unusable', apiKeyId);
249
+ return;
250
+ }
251
+ const view = buildKeyModelsView(apiKeyId, registry);
252
+ if (view.status === 'error') {
253
+ run.failed += 1;
254
+ run.errors.push({ target: name, reason: view.message });
255
+ noteIssue('client', name, 'failed', view.message, apiKeyId);
256
+ return;
257
+ }
258
+ const { extraModels, virtualModels, allAllowedIds } = allowedFollowLists(view);
259
+ const fp = fingerprintOf(allAllowedIds);
260
+ if (fingerprints.get(issueKey('client', name)) === fp) {
261
+ clearIssue('client', name);
262
+ run.skipped += 1;
263
+ return;
264
+ }
265
+ // Cold process: adapters usually echo concrete extras only — never stamp the
266
+ // full (extras+virtuals) fingerprint from an extras-only match, or virtual
267
+ // drift would be skipped forever after the first post-restart pass.
268
+ const result = await setupClient(name, {
269
+ apiKey: key.key,
270
+ extraModels,
271
+ virtualModels,
272
+ ...(memEntry.models ? { models: memEntry.models } : {}),
273
+ ...(memEntry.agentModels ? { agentModels: memEntry.agentModels } : {}),
274
+ ...(typeof memEntry.contextWindow === 'number' && memEntry.contextWindow > 0
275
+ ? { contextWindow: memEntry.contextWindow }
276
+ : {}),
277
+ ...(acknowledgeRunning ? { acknowledgeRunning: true } : {}),
278
+ });
279
+ if (!result.success) {
280
+ if (result.reasonCode === 'ide_running') {
281
+ noteIssue('client', name, 'pending', 'ide_running', apiKeyId);
282
+ run.skipped += 1;
283
+ run.errors.push({ target: name, reason: 'ide_running' });
284
+ return;
285
+ }
286
+ const reason = result.reasonCode || result.message;
287
+ run.failed += 1;
288
+ run.errors.push({ target: name, reason });
289
+ noteIssue('client', name, 'failed', reason, apiKeyId);
290
+ return;
291
+ }
292
+ fingerprints.set(issueKey('client', name), fp);
293
+ clearIssue('client', name);
294
+ run.synced += 1;
295
+ }
296
+ async function syncAllGatewayFollow(opts, registry, run) {
297
+ const host = await import('../../plugins/host.js');
298
+ const installed = host.listInstalledPlugins();
299
+ const installedById = new Map(installed.map((v) => [v.id, v]));
300
+ for (const view of installed) {
301
+ if (view.disabled)
302
+ continue;
303
+ const cfg = host.getPluginConfig(view.id);
304
+ if (!cfg)
305
+ continue;
306
+ const mode = cfg.values.modelListMode;
307
+ if (mode !== 'follow')
308
+ continue;
309
+ const keyField = cfg.schema.find((f) => f.control === 'apiKey')?.key;
310
+ if (!keyField)
311
+ continue;
312
+ const bound = cfg.values[keyField];
313
+ if (typeof bound !== 'string' || !bound.trim())
314
+ continue;
315
+ if (opts.reason === 'key' && opts.keyId && bound !== opts.keyId)
316
+ continue;
317
+ await syncGatewayPlugin(view.id, bound, registry, run);
318
+ }
319
+ // Leave-follow / uninstall / disable: drop stale card issues. Do NOT use the
320
+ // key-scoped visit set — a key-only pass legitimately skips other gateways.
321
+ for (const issue of [...issues.values()]) {
322
+ if (issue.kind !== 'gateway')
323
+ continue;
324
+ const row = installedById.get(issue.id);
325
+ const cfg = host.getPluginConfig(issue.id);
326
+ const stillFollow = !!row && !row.disabled && !!cfg && cfg.values.modelListMode === 'follow';
327
+ if (!stillFollow) {
328
+ clearIssue('gateway', issue.id);
329
+ fingerprints.delete(issueKey('gateway', issue.id));
330
+ }
331
+ }
332
+ }
333
+ async function syncGatewayPlugin(pluginId, apiKeyId, registry, run) {
334
+ const host = await import('../../plugins/host.js');
335
+ const cfg = host.getPluginConfig(pluginId);
336
+ if (!cfg) {
337
+ run.skipped += 1;
338
+ return;
339
+ }
340
+ if (cfg.values.modelListMode !== 'follow') {
341
+ clearIssue('gateway', pluginId);
342
+ run.skipped += 1;
343
+ return;
344
+ }
345
+ const keys = listApiKeys(false);
346
+ const key = keys.find((k) => k.id === apiKeyId);
347
+ if (!key || !isApiKeyUsable(key)) {
348
+ run.failed += 1;
349
+ run.errors.push({ target: pluginId, reason: 'api_key_unusable' });
350
+ noteIssue('gateway', pluginId, 'failed', 'api_key_unusable', apiKeyId);
351
+ return;
352
+ }
353
+ const view = buildKeyModelsView(apiKeyId, registry);
354
+ if (view.status === 'error') {
355
+ run.failed += 1;
356
+ run.errors.push({ target: pluginId, reason: view.message });
357
+ noteIssue('gateway', pluginId, 'failed', view.message, apiKeyId);
358
+ return;
359
+ }
360
+ const models = view.models.filter((m) => m.allowed).map((m) => m.id);
361
+ const fp = fingerprintOf(models);
362
+ const current = Array.isArray(cfg.values.models)
363
+ ? cfg.values.models.map((id) => String(id).replace(/^ocr\//, ''))
364
+ : [];
365
+ if (fingerprints.get(issueKey('gateway', pluginId)) === fp || fingerprintOf(current) === fp) {
366
+ fingerprints.set(issueKey('gateway', pluginId), fp);
367
+ clearIssue('gateway', pluginId);
368
+ run.skipped += 1;
369
+ return;
370
+ }
371
+ try {
372
+ await host.applyPluginConfig(pluginId, { ...cfg.values, models });
373
+ for (const adapter of getAllClientAdapters()) {
374
+ if (adapter.catalogPlugin !== pluginId || !adapter.refreshModelSurface)
375
+ continue;
376
+ try {
377
+ await adapter.refreshModelSurface();
378
+ }
379
+ catch (err) {
380
+ console.warn(`[follow-catalog] refreshModelSurface ${adapter.name}:`, err instanceof Error ? err.message : err);
381
+ }
382
+ }
383
+ fingerprints.set(issueKey('gateway', pluginId), fp);
384
+ clearIssue('gateway', pluginId);
385
+ run.synced += 1;
386
+ }
387
+ catch (err) {
388
+ const reason = err instanceof Error ? err.message : String(err);
389
+ run.failed += 1;
390
+ run.errors.push({ target: pluginId, reason });
391
+ noteIssue('gateway', pluginId, 'failed', reason, apiKeyId);
392
+ }
393
+ }
394
+ /** Persist modelMode / apiKeyId after a successful console setup (authoritative index). */
395
+ export function stampClientProfileMemory(clientName, patch) {
396
+ const cfg = loadConfig();
397
+ const mem = { ...(cfg.clientProfileMemory || {}) };
398
+ const prev = mem[clientName] || {};
399
+ mem[clientName] = { ...prev, ...patch };
400
+ saveConfig({ clientProfileMemory: mem });
401
+ // Leave-follow: drop card issue + fingerprint so a prior pending/fail does not linger.
402
+ if (patch.modelMode !== undefined && patch.modelMode !== 'follow') {
403
+ clearIssue('client', clientName);
404
+ fingerprints.delete(issueKey('client', clientName));
405
+ }
406
+ else if (patch.modelMode === 'follow') {
407
+ // Fresh follow setup succeeded — clear any stale auto-sync residue.
408
+ clearIssue('client', clientName);
409
+ }
410
+ }
411
+ /** Drop follow index on teardown so unloaded clients are not auto-synced. */
412
+ export function clearClientProfileMemory(clientName) {
413
+ const cfg = loadConfig();
414
+ const mem = { ...(cfg.clientProfileMemory || {}) };
415
+ if (!(clientName in mem))
416
+ return;
417
+ delete mem[clientName];
418
+ saveConfig({ clientProfileMemory: mem });
419
+ clearIssue('client', clientName);
420
+ fingerprints.delete(issueKey('client', clientName));
421
+ }
422
+ /** Test helpers — reset in-process state between cases. */
423
+ export function _resetFollowCatalogSyncForTests() {
424
+ if (keyTimer)
425
+ clearTimeout(keyTimer);
426
+ if (poolTimer)
427
+ clearTimeout(poolTimer);
428
+ keyTimer = undefined;
429
+ poolTimer = undefined;
430
+ pendingKeyIds.clear();
431
+ fingerprints.clear();
432
+ issues.clear();
433
+ lastRun = undefined;
434
+ inFlight = undefined;
435
+ }
@@ -4,6 +4,7 @@ import { retiredClientHint } from './reserved.js';
4
4
  import { popularityRank } from '../../utils/popularity.js';
5
5
  import { compareVersions } from '../../utils/semver.js';
6
6
  import { getPluginClientAdapter, listPluginClientAdapters, pluginClientRank, pluginIdForClient } from './plugin-adapters.js';
7
+ import { noteClientSetup } from './activity.js';
7
8
  /** The hooks this build ships (`core-adapters.ts`) — the authoritative answer
8
9
  * for "what is always available", even before the plugin host has run. */
9
10
  const adapters = CORE_ADAPTERS;
@@ -202,8 +203,13 @@ export async function setupClient(name, options) {
202
203
  }
203
204
  const result = await adapter.setup(options);
204
205
  // A hook flip invalidates the roster snapshot: the next read rebuilds.
205
- if (result.success)
206
+ // The success moment is also the client's "接入" timestamp — the activity
207
+ // ledger's fallback sort key, so a freshly hooked client floats up before
208
+ // it has sent any traffic.
209
+ if (result.success) {
206
210
  rosterCache.at = 0;
211
+ noteClientSetup(name);
212
+ }
207
213
  return siblingNote && result.success ? { ...result, message: result.message + siblingNote } : result;
208
214
  }
209
215
  export async function teardownClient(name, options) {
@@ -6,7 +6,6 @@ import { readProviderDefsFile, writeProviderDefs } from '../../opencode/provider
6
6
  import { materializeDefs } from '../../opencode/credentials/def-materialize.js';
7
7
  import { reloadOpencodeService } from '../../opencode/credentials/opencode-v2-store.js';
8
8
  import { resolveDefaultPaths } from '../../opencode/credentials/paths.js';
9
- import { opencodePackageFor } from '../../opencode/provider-package.js';
10
9
  /**
11
10
  * OpenCode client adapter.
12
11
  *
@@ -95,7 +94,9 @@ function buildRouterProviderNode(port, model, extraModels, apiKey, virtualModels
95
94
  }
96
95
  return {
97
96
  name: 'OmniCellRouter',
98
- package: opencodePackageFor('openai-chat'),
97
+ // OCR defs truth is protocols[] (ADR-0010); materialize emits the
98
+ // client `package` spelling for opencode.jsonc.
99
+ protocols: ['openai-chat'],
99
100
  settings: {
100
101
  baseURL: targetUrl,
101
102
  // Gateway-issued key when the user picks one; the placeholder works
@@ -43,6 +43,8 @@ export function isCoreClientId(name) {
43
43
  export const RETIRED_CLIENT_IDS = {
44
44
  // ADR-0028: the ingress half merged into its gateway package.
45
45
  'opencode-proxy': 'opencode-gateway',
46
+ // ChatGPT Desktop shares ~/.codex with the Codex card (one unified hook).
47
+ chatgpt: 'codex',
46
48
  };
47
49
  /** Human-readable hint for a retired id, or undefined when the id is not one. */
48
50
  export function retiredClientHint(name) {
@@ -96,6 +96,24 @@ export interface ClientHookStatus {
96
96
  * each with its own takeover state. Absent for single-product adapters —
97
97
  * the console then renders the card row exactly as before. */
98
98
  products?: ClientProductStatus[];
99
+ /** Last time an inference request was fingerprinted to this client's UA
100
+ * (ms epoch; the auth gate's in-memory activity ledger). Absent = no
101
+ * observed traffic since boot. Display-only sort key — never routing
102
+ * state; the CLI roster table ignores it. */
103
+ lastActiveAt?: number;
104
+ /** Last time `setupClient()` hooked this client successfully (ms epoch).
105
+ * The sort fallback while a client has sent no traffic yet; absent = not
106
+ * hooked this boot. */
107
+ lastSetupAt?: number;
108
+ /** Follow-catalog auto-resync queued this client (or its catalogPlugin)
109
+ * because the last rewrite hit ide_running. Console-only; stamped by the
110
+ * roster route, never by adapters. */
111
+ followCatalogPending?: boolean;
112
+ /** Open follow-catalog issue for this card (pending or failed). */
113
+ followCatalogIssue?: {
114
+ status: 'pending' | 'failed';
115
+ reason: string;
116
+ };
99
117
  }
100
118
  /**
101
119
  * One product instance inside a FAMILY adapter — one installed JetBrains IDE,
@@ -16,7 +16,7 @@
16
16
  export const YAML_FILE_HEADER_EN = [
17
17
  'OmniCellRouter gateway configuration (config.yaml) — schemaVersion 1 (grouped format; evolution rules in docs/adr/0016-config-schema-evolution.md)',
18
18
  'Configuration layers (six groups, exactly one home per section):',
19
- ' client Client entry surface: port / host / adminKey / webAuth / apiKeys / rateLimit / forwardProxy — how requests enter',
19
+ ' client Client entry surface: port / host / adminKey / webAuth / apiKeys / rateLimit / bodyLimits / autoResyncFollowCatalogs / forwardProxy — how requests enter',
20
20
  ' protocol Protocol surface: systemone / responses — which wire the gateway speaks',
21
21
  ' routing Traffic-orchestration surface: strategy / tiers / classifier / session / directives / routeEntries / combos / profileMemory — which model serves',
22
22
  ' resilience Failure-recovery surface: circuitBreaker / retry (inplace / failover / escalation) — what happens when a call fails',
@@ -134,6 +134,10 @@ export const YAML_FIELD_COMMENTS_EN = {
134
134
  'retry.failover.maxAttempts': 'Failover attempt count',
135
135
  'retry.failover.tierCrossPolicy': 'Cross-tier policy: allow_escalate may climb a tier',
136
136
  rateLimit: 'Rate-limit policy switches (the windows themselves live in client.apiKeys[].limits and the upstream.credentials overlay)',
137
+ bodyLimits: 'Request-body admission caps (ADR-0008), one per HTTP plane, counted on the DECOMPRESSED body: `maxBytes` for the inference surfaces (chat / responses / anthropic on the native listener AND the same paths through the forward-proxy MITM leg), `adminMaxBytes` for the console plane. RESTART REQUIRED — Fastify reads a route bodyLimit when the route is registered, so a change lands on the next controlled restart (ADR-0007). Out-of-range values are clamped, junk falls back to the shipped default. Not the capture knob: `ops.requestCapture.maxBodyBytes` only decides how much of a body is ARCHIVED and never rejects a request. Neither cap applies to the two upload routes (book import, plugin package), which declare their own.',
138
+ autoResyncFollowCatalogs: 'When true (default), changing an API key\'s modelAccess OR rebuilding the live model pool event-drives a rewrite of every hooked follow-mode client catalog and every gateway plugin with modelListMode=follow. enabled / expiry / delete only affect auth and do not rewrite catalogs. Running clients are queued as pending (no silent acknowledgeRunning). Hot — no restart. Turn off to keep follow snapshots frozen until a manual re-hook. Not a profile write-through (ADR-0031).',
139
+ 'bodyLimits.maxBytes': 'Inference-plane cap in bytes (default 33554432 = 32 MiB; clamped to 65536…536870912 = 64 KiB…512 MiB). A body over it is refused with 413 naming this number; a body declaring a compression format the gateway cannot decode (gzip / x-gzip / deflate / br) is refused with 415 + `Accept-Encoding` before it is read, and inflates past this cap mid-stream is a 413. Raise it only knowing one request holds that many bytes in memory per in-flight client.',
140
+ 'bodyLimits.adminMaxBytes': 'Console-plane cap in bytes (default 8388608 = 8 MiB; same bounds). Covers every /api/admin/* route that does not declare its own, the largest real payload being the raw-YAML config save (the whole config.yaml in one string). A route that needs more declares its own bodyLimit at registration and is exempt from this cap.',
137
141
  'rateLimit.persist': 'Persistence of the triggered-rate-limit-event ledger: written to traces.db (its own handle in the trace/FinOps database) so the /rate-limit page still shows pre-restart history; observability writes fail open and never block the request path',
138
142
  'rateLimit.persist.enabled': 'Ledger persistence switch (default on): triggered events write to traces.db (the /rate-limit page survives restarts), with a 30s sliding-window checkpoint plus a flush on graceful shutdown and replay at boot (1d-class long-window budgets survive restarts; a hard kill loses at most one checkpoint period); off = memory only (cleared on restart)',
139
143
  'rateLimit.inboundGraceMs': 'Grace wait (ms, default 1000, cap 2000, 0 = off): when a client-key window is full but reopens within this budget, the gateway waits exactly once and re-checks (no loop); still full or over budget → 429 + Retry-After. Absorbs sub-second bursts so a short rate limit never becomes a user-visible error; long windows keep fast-failing: the limit contract is unchanged, the wait belongs to the client\'s own backoff',
@@ -1,7 +1,7 @@
1
1
  export const YAML_FILE_HEADER_ZH = [
2
2
  'OmniCellRouter 网关配置(config.yaml)— schemaVersion 1(分组格式,演进规则见 docs/adr/0016-config-schema-evolution.md)',
3
3
  '配置层次(六组,每段唯一归属):',
4
- ' client 客户端接入面:port / host / adminKey / webAuth / apiKeys / rateLimit / forwardProxy —— 请求怎么进来',
4
+ ' client 客户端接入面:port / host / adminKey / webAuth / apiKeys / rateLimit / bodyLimits / autoResyncFollowCatalogs / forwardProxy —— 请求怎么进来',
5
5
  ' protocol 协议面:systemone / responses —— 网关对外说哪种协议',
6
6
  ' routing 流量编排面:strategy / tiers / classifier / session / directives / routeEntries / combos / profileMemory —— 请求路由到哪个模型',
7
7
  ' upstream 上游连接面:proxy / credentials / streaming / compression —— 怎么打到上游',
@@ -119,6 +119,10 @@ export const YAML_FIELD_COMMENTS_ZH = {
119
119
  'retry.failover.maxAttempts': '故障转移尝试次数',
120
120
  'retry.failover.tierCrossPolicy': '跨梯队策略:allow_escalate 允许向上升级',
121
121
  rateLimit: '限流策略开关(窗口本身在 apiKeys[].limits 与 credentials: 叠加层)',
122
+ bodyLimits: '请求体准入上限(ADR-0008),按 HTTP 面各一个,计的是解压后的体积:`maxBytes` 管推理面(chat / responses / anthropic 两条腿——原生监听与智能体 CLI 经前向代理 MITM 的那条,共用同一天花板),`adminMaxBytes` 管控制台面。重启网关生效——Fastify 在注册路由时读取 bodyLimit,改动随下一次受控重启落地(ADR-0007)。越界值夹到边界,非法值回退出厂默认。与捕捉旋钮不是一回事:`ops.requestCapture.maxBodyBytes` 只决定归档留存多少,从不拒请求。两个上传路由(账本导入、插件包上传)自带更大上限,不受本段约束。',
123
+ autoResyncFollowCatalogs: '为 true(默认)时:API Key 的 modelAccess 变更,或直播模型池重建,会事件驱动地重写所有已挂接的 follow 模式客户端目录,以及 modelListMode=follow 的网关插件配置。启用 / 过期 / 删除只影响鉴权,不重写目录。正在运行的客户端进入 pending(自动路径不带 acknowledgeRunning)。热读——无需重启。关掉则 follow 快照保持冻结直到手动重新挂接。不是方案表 write-through(ADR-0031)。',
124
+ 'bodyLimits.maxBytes': '推理面上限(字节,默认 33554432 = 32 MiB;夹到 65536…536870912 = 64 KiB…512 MiB)。超过即以 413 拒收并在消息里写明该数字;声明了网关无法解码的压缩格式(gzip / x-gzip / deflate / br)在读取请求体之前即 415 + `Accept-Encoding`;边解边膨胀触顶则 413。抬高前请知悉:每个在途请求都会按此规模占用内存。',
125
+ 'bodyLimits.adminMaxBytes': '控制台面上限(字节,默认 8388608 = 8 MiB;边界同上)。覆盖所有未自报上限的 /api/admin/* 路由,其中最大的真实载荷是配置文件原始 YAML 保存(整个 config.yaml 塞进一个字符串)。需要更大的路由在注册时自报 bodyLimit,不受本上限约束。',
122
126
  'rateLimit.persist': '已触发限流事件账本的持久化:写入 traces.db(与 trace/FinOps 共库独立句柄),重启后 /rate-limit 页仍可回看上一次的触发历史;观测性写入 fail-open,永不阻塞请求路径',
123
127
  'rateLimit.persist.enabled': '限流持久化开关(默认开):触发限流事件账本写入 traces.db(重启后 /rate-limit 页仍可回看上一次的触发历史),且滑动窗口每 30s checkpoint 一次并在优雅停机时冲刷、启动时重放(1d 类长窗口预算跨重启连续,硬杀最多丢最近一个 checkpoint 周期);关闭=全部仅内存(重启清零)',
124
128
  'rateLimit.inboundGraceMs': '宽限等待(毫秒,默认 1000,上限 2000,0=关闭):客户端密钥窗口满、但重开等待不超过该值时,网关原地等待窗口重开后复查一次(不循环),复查仍满或等待超限才回 429 + Retry-After——吸收亚秒级突发,避免短限流变成用户可见错误;长窗口维持快速失败:限流契约不变,等待归属客户端自己的退避',