omnicell-router 0.2.0 → 0.3.1

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 (102) hide show
  1. package/backend/dist/budget/budget-manager.d.ts +25 -0
  2. package/backend/dist/budget/budget-manager.js +54 -0
  3. package/backend/dist/cli/clients/index.js +2 -0
  4. package/backend/dist/cli/clients/omp.d.ts +53 -0
  5. package/backend/dist/cli/clients/omp.js +664 -0
  6. package/backend/dist/cli/clients/pi.js +79 -32
  7. package/backend/dist/cli/index.js +2 -2
  8. package/backend/dist/cli/types.d.ts +1 -1
  9. package/backend/dist/config/governance-limits.d.ts +68 -0
  10. package/backend/dist/config/governance-limits.js +261 -0
  11. package/backend/dist/config/index.js +1 -1
  12. package/backend/dist/config/types.d.ts +15 -5
  13. package/backend/dist/flywheel/collector.d.ts +74 -0
  14. package/backend/dist/flywheel/collector.js +235 -0
  15. package/backend/dist/flywheel/dataset.d.ts +130 -0
  16. package/backend/dist/flywheel/dataset.js +638 -0
  17. package/backend/dist/flywheel/decision-capture.d.ts +68 -0
  18. package/backend/dist/flywheel/decision-capture.js +85 -0
  19. package/backend/dist/flywheel/prune.d.ts +133 -0
  20. package/backend/dist/flywheel/prune.js +495 -0
  21. package/backend/dist/flywheel/schema.d.ts +108 -0
  22. package/backend/dist/flywheel/schema.js +117 -0
  23. package/backend/dist/flywheel/trainer.d.ts +84 -0
  24. package/backend/dist/flywheel/trainer.js +198 -0
  25. package/backend/dist/harness/adapters/amp.js +1 -0
  26. package/backend/dist/harness/adapters/claude.js +1 -0
  27. package/backend/dist/harness/adapters/cline.js +3 -1
  28. package/backend/dist/harness/adapters/codex.js +3 -1
  29. package/backend/dist/harness/adapters/cursor.js +1 -0
  30. package/backend/dist/harness/adapters/declarative.d.ts +3 -1
  31. package/backend/dist/harness/adapters/declarative.js +15 -1
  32. package/backend/dist/harness/adapters/dsh.js +1 -1
  33. package/backend/dist/harness/adapters/gemini-cli.js +1 -0
  34. package/backend/dist/harness/adapters/github-copilot.js +1 -0
  35. package/backend/dist/harness/adapters/index.d.ts +11 -3
  36. package/backend/dist/harness/adapters/index.js +48 -1
  37. package/backend/dist/harness/adapters/omp.d.ts +11 -0
  38. package/backend/dist/harness/adapters/omp.js +22 -0
  39. package/backend/dist/harness/adapters/opencode.js +1 -0
  40. package/backend/dist/harness/adapters/pi.js +2 -1
  41. package/backend/dist/harness/adapters/types.d.ts +19 -4
  42. package/backend/dist/harness/adapters/windsurf.js +1 -0
  43. package/backend/dist/harness/adapters/zed.js +3 -1
  44. package/backend/dist/harness/hosts.js +1 -0
  45. package/backend/dist/harness/translation.js +12 -4
  46. package/backend/dist/harness/types.d.ts +2 -2
  47. package/backend/dist/harness/writers/skill.d.ts +1 -1
  48. package/backend/dist/opencode/agents.d.ts +7 -0
  49. package/backend/dist/opencode/agents.js +22 -3
  50. package/backend/dist/opencode/catalog/custom-store.d.ts +50 -0
  51. package/backend/dist/opencode/catalog/custom-store.js +144 -0
  52. package/backend/dist/opencode/credentials/push.d.ts +38 -0
  53. package/backend/dist/opencode/credentials/push.js +116 -0
  54. package/backend/dist/opencode/credentials/reconcile.d.ts +49 -0
  55. package/backend/dist/opencode/credentials/reconcile.js +216 -0
  56. package/backend/dist/opencode/sync.d.ts +29 -0
  57. package/backend/dist/opencode/sync.js +186 -0
  58. package/backend/dist/pipeline/account-selection.d.ts +101 -0
  59. package/backend/dist/pipeline/account-selection.js +112 -0
  60. package/backend/dist/pipeline/orchestrator.js +34 -3
  61. package/backend/dist/providers/systemone.d.ts +29 -0
  62. package/backend/dist/providers/systemone.js +170 -0
  63. package/backend/dist/ratelimit/duration.d.ts +24 -0
  64. package/backend/dist/ratelimit/duration.js +43 -0
  65. package/backend/dist/ratelimit/governance-runtime.d.ts +121 -0
  66. package/backend/dist/ratelimit/governance-runtime.js +183 -0
  67. package/backend/dist/ratelimit/index.d.ts +4 -0
  68. package/backend/dist/ratelimit/index.js +4 -0
  69. package/backend/dist/ratelimit/limiter.d.ts +157 -0
  70. package/backend/dist/ratelimit/limiter.js +244 -0
  71. package/backend/dist/ratelimit/sliding-window-counter.d.ts +63 -0
  72. package/backend/dist/ratelimit/sliding-window-counter.js +103 -0
  73. package/backend/dist/ratelimit/subject.d.ts +26 -0
  74. package/backend/dist/ratelimit/subject.js +28 -0
  75. package/backend/dist/resilience/account-state.d.ts +84 -0
  76. package/backend/dist/resilience/account-state.js +228 -0
  77. package/backend/dist/router/layer1-classifier.d.ts +111 -0
  78. package/backend/dist/router/layer1-classifier.js +467 -0
  79. package/backend/dist/router/layer2-judge.d.ts +111 -0
  80. package/backend/dist/router/layer2-judge.js +373 -0
  81. package/backend/dist/router/retry-escalation.d.ts +89 -0
  82. package/backend/dist/router/retry-escalation.js +99 -0
  83. package/backend/dist/routes/flywheel.d.ts +3 -0
  84. package/backend/dist/routes/flywheel.js +268 -0
  85. package/backend/dist/routes/harness.js +4 -1
  86. package/backend/dist/routes/systemone.d.ts +3 -0
  87. package/backend/dist/routes/systemone.js +90 -0
  88. package/backend/dist/server.d.ts +0 -15
  89. package/backend/dist/server.js +40 -43
  90. package/backend/dist/session/session-manager.d.ts +15 -0
  91. package/backend/dist/session/session-manager.js +17 -0
  92. package/backend/dist/session/session-row.d.ts +78 -0
  93. package/backend/dist/session/session-row.js +52 -0
  94. package/backend/dist/surfaces/governance-envelope.d.ts +34 -0
  95. package/backend/dist/surfaces/governance-envelope.js +47 -0
  96. package/backend/dist/utils/token-estimator.d.ts +7 -0
  97. package/backend/dist/utils/token-estimator.js +20 -0
  98. package/bin/ocr.js +2 -2
  99. package/frontend/dist/assets/{index-DvXKvNxl.js → index-B7GKsUyU.js} +264 -244
  100. package/frontend/dist/assets/{index-1o7qI-KJ.css → index-DLKLOkQJ.css} +1 -1
  101. package/frontend/dist/index.html +2 -2
  102. package/package.json +1 -1
@@ -42,8 +42,34 @@ const PI_SUBAGENT_TIERS = {
42
42
  reviewer: 'pro',
43
43
  oracle: 'ultra',
44
44
  };
45
- /** Namespace prefix marking a subagent override as router-owned (teardown strips these, only these). */
46
- const SUBAGENT_MODEL_PREFIX = `${PI_PROVIDER_KEY}/`;
45
+ /**
46
+ * Legacy provider keys written by pre-rename OCR releases (OneCastRouter era
47
+ * and earlier experiments). Their `key/<id>` subagent pins and defaultProvider
48
+ * values are router residue, not user choices — treated as router-owned
49
+ * everywhere the current prefix is (stripped on teardown/reset, echoed as the
50
+ * bare id, refreshed by the tier preset) so an old install heals on the next
51
+ * setup instead of posing as a foreign manual pin forever.
52
+ */
53
+ const LEGACY_PROVIDER_KEYS = ['onecast-router', 'opencode-router'];
54
+ /** All provider keys whose `<key>/<id>` model refs count as router-owned. */
55
+ const ROUTER_PROVIDER_KEYS = [PI_PROVIDER_KEY, ...LEGACY_PROVIDER_KEYS];
56
+ /** True when a model ref is qualified with any router provider key. */
57
+ const isRouterModelRef = (v) => typeof v === 'string' && ROUTER_PROVIDER_KEYS.some(k => v.startsWith(`${k}/`));
58
+ /** Bare id of a router-qualified ref, or undefined when foreign. */
59
+ const routerModelBareId = (v) => {
60
+ if (typeof v !== 'string')
61
+ return undefined;
62
+ const k = ROUTER_PROVIDER_KEYS.find(k => v.startsWith(`${k}/`));
63
+ return k ? v.slice(k.length + 1) : undefined;
64
+ };
65
+ /**
66
+ * Startup thinking level written into pi's settings.json alongside
67
+ * defaultProvider/defaultModel. `medium` is pi's own built-in default — safe
68
+ * for every model: the gateway resolves each request's real model and clamps
69
+ * the requested effort to what it can serve (X-OCR-Thinking-* headers), so a
70
+ * permissive client-side preset never over-drives a weaker rung.
71
+ */
72
+ const PI_DEFAULT_THINKING_LEVEL = 'medium';
47
73
  /**
48
74
  * Sidecar next to models.json (`models.json.ocr-meta.json`) holding the
49
75
  * profile-link echo (profile id + role → profile-slot key). The echo must
@@ -206,7 +232,7 @@ export class PiClientAdapter {
206
232
  const pinned = overrides
207
233
  ? Object.keys(overrides).filter(role => {
208
234
  const model = overrides[role]?.model;
209
- return typeof model === 'string' && model.startsWith(SUBAGENT_MODEL_PREFIX);
235
+ return isRouterModelRef(model);
210
236
  }).length
211
237
  : 0;
212
238
  if (pinned > 0)
@@ -222,11 +248,13 @@ export class PiClientAdapter {
222
248
  { key: 'main', value: models[0]?.id ? String(models[0].id) : undefined, default: 'auto' },
223
249
  ];
224
250
  for (const { name: role, description } of this.discoverSubagentRoles(overrides)) {
225
- const pinnedModel = overrides?.[role]?.model;
251
+ // A USER-pinned slot (pi's own agentOverrides), never the gateway's
252
+ // session pin — different word, different mechanism.
253
+ const userPinnedModel = overrides?.[role]?.model;
226
254
  modelSlots.push({
227
255
  key: role,
228
- value: typeof pinnedModel === 'string' && pinnedModel
229
- ? pinnedModel.startsWith(SUBAGENT_MODEL_PREFIX) ? pinnedModel.slice(SUBAGENT_MODEL_PREFIX.length) : pinnedModel
256
+ value: typeof userPinnedModel === 'string' && userPinnedModel
257
+ ? routerModelBareId(userPinnedModel) ?? userPinnedModel
230
258
  : undefined,
231
259
  default: PI_SUBAGENT_TIERS[role] || 'auto',
232
260
  description,
@@ -324,7 +352,7 @@ export class PiClientAdapter {
324
352
  for (const role of Object.keys(meta.profile.bindings)) {
325
353
  const entry = overrides[role];
326
354
  if (entry && typeof entry === 'object' && !Array.isArray(entry) &&
327
- typeof entry.model === 'string' && entry.model.startsWith(SUBAGENT_MODEL_PREFIX)) {
355
+ isRouterModelRef(entry?.model)) {
328
356
  if (Object.keys(entry).length === 1)
329
357
  delete overrides[role];
330
358
  else
@@ -369,16 +397,28 @@ export class PiClientAdapter {
369
397
  const base = entry && typeof entry === 'object' && !Array.isArray(entry) ? entry : {};
370
398
  const current = base.model;
371
399
  if (typeof current === 'string' && current.length > 0) {
372
- if (!current.startsWith(SUBAGENT_MODEL_PREFIX))
400
+ const bare = routerModelBareId(current);
401
+ if (bare === undefined)
373
402
  continue; // foreign pin — never stolen
374
- // Router-owned: refresh only preset-vocabulary auto* aliases (tier
375
- // table updates normalize on re-setup); a router-owned concrete pick
376
- // (omnicell-router/<id>) is an explicit choice and survives.
377
- if (!VIRTUAL_AUTO_IDS.has(current.slice(SUBAGENT_MODEL_PREFIX.length)))
403
+ // Router-owned (incl. legacy-key residue): refresh only
404
+ // preset-vocabulary auto* aliases (tier table updates normalize on
405
+ // re-setup); a router-owned concrete pick is an explicit choice and
406
+ // survives.
407
+ if (!VIRTUAL_AUTO_IDS.has(bare))
378
408
  continue;
379
409
  }
380
410
  overrides[role] = { ...base, model: `${PI_PROVIDER_KEY}/${tier}` };
381
411
  }
412
+ // Startup defaults: route pi's first screen through OCR. Only claimed
413
+ // when unset or already router-owned — a hand-picked foreign provider
414
+ // (user's own default in settings.json) is never stolen; the model list
415
+ // in models.json still exposes the OCR entries via /model.
416
+ if (!settings.defaultProvider || ROUTER_PROVIDER_KEYS.includes(String(settings.defaultProvider))) {
417
+ settings.defaultProvider = PI_PROVIDER_KEY;
418
+ settings.defaultModel = main;
419
+ if (!settings.defaultThinkingLevel)
420
+ settings.defaultThinkingLevel = PI_DEFAULT_THINKING_LEVEL;
421
+ }
382
422
  safeWriteJson(settingsPath, settings);
383
423
  // Profile-link echo: recorded AFTER the writes so the sidecar reflects
384
424
  // what this setup just applied ('' id clears it — the un-link sweep
@@ -446,9 +486,7 @@ export class PiClientAdapter {
446
486
  // not rewrite this file.
447
487
  const changed = Object.entries(desired).some(([role, ref]) => {
448
488
  const current = overrides[role]?.model;
449
- const currentBare = typeof current === 'string' && current.startsWith(SUBAGENT_MODEL_PREFIX)
450
- ? current.slice(SUBAGENT_MODEL_PREFIX.length)
451
- : current;
489
+ const currentBare = routerModelBareId(current) ?? current;
452
490
  return (ref || '') !== (typeof currentBare === 'string' ? currentBare : '');
453
491
  });
454
492
  const meta = readMeta(configPath);
@@ -463,7 +501,7 @@ export class PiClientAdapter {
463
501
  if (ref === null) {
464
502
  const entry = overrides[role];
465
503
  if (entry && typeof entry === 'object' && !Array.isArray(entry) &&
466
- typeof entry.model === 'string' && entry.model.startsWith(SUBAGENT_MODEL_PREFIX)) {
504
+ typeof entry.model === 'string' && isRouterModelRef(entry.model)) {
467
505
  if (Object.keys(entry).length === 1)
468
506
  delete overrides[role];
469
507
  else
@@ -646,11 +684,20 @@ export class PiClientAdapter {
646
684
  }
647
685
  const overrides = data?.subagents?.agentOverrides;
648
686
  let removed = 0;
687
+ // Router-owned startup defaults die with the hook — but only ours: a
688
+ // foreign defaultProvider (user's own pick) is never touched.
689
+ if (data.defaultProvider === PI_PROVIDER_KEY) {
690
+ delete data.defaultProvider;
691
+ delete data.defaultModel;
692
+ if (data.defaultThinkingLevel === PI_DEFAULT_THINKING_LEVEL)
693
+ delete data.defaultThinkingLevel;
694
+ removed++;
695
+ }
649
696
  if (overrides && typeof overrides === 'object' && !Array.isArray(overrides)) {
650
697
  for (const role of Object.keys(overrides)) {
651
698
  const entry = overrides[role];
652
699
  if (entry && typeof entry === 'object' && !Array.isArray(entry) &&
653
- typeof entry.model === 'string' && entry.model.startsWith(SUBAGENT_MODEL_PREFIX)) {
700
+ isRouterModelRef(entry?.model)) {
654
701
  if (Object.keys(entry).length === 1)
655
702
  delete overrides[role];
656
703
  else
@@ -658,24 +705,24 @@ export class PiClientAdapter {
658
705
  removed++;
659
706
  }
660
707
  }
661
- if (removed > 0) {
662
- if (Object.keys(overrides).length === 0)
663
- delete data.subagents.agentOverrides;
664
- if (data.subagents && Object.keys(data.subagents).length === 0)
665
- delete data.subagents;
666
- if (Object.keys(data).length === 0) {
667
- try {
668
- fs.unlinkSync(settingsPath);
669
- }
670
- catch {
671
- safeWriteJson(settingsPath, data); // unlink failed (file lock) — at least drop the residue
672
- }
708
+ }
709
+ if (removed > 0) {
710
+ if (overrides && Object.keys(overrides).length === 0)
711
+ delete data.subagents.agentOverrides;
712
+ if (data.subagents && Object.keys(data.subagents).length === 0)
713
+ delete data.subagents;
714
+ if (Object.keys(data).length === 0) {
715
+ try {
716
+ fs.unlinkSync(settingsPath);
673
717
  }
674
- else {
675
- safeWriteJson(settingsPath, data);
718
+ catch {
719
+ safeWriteJson(settingsPath, data); // unlink failed (file lock) — at least drop the residue
676
720
  }
677
721
  }
722
+ else {
723
+ safeWriteJson(settingsPath, data);
724
+ }
678
725
  }
679
- return removed > 0 ? `; removed ${removed} subagent role override(s) from ${settingsPath}` : '';
726
+ return removed > 0 ? `; removed ${removed} router-owned setting(s) from ${settingsPath}` : '';
680
727
  }
681
728
  }
@@ -275,7 +275,7 @@ async function main() {
275
275
  printBanner();
276
276
  const client = args[1];
277
277
  if (!client) {
278
- console.error(`${C.red}✗ Missing client target.${C.reset} Usage: \`ocr setup <opencode | opencode-proxy | claude | codex | pi | dsh>\``);
278
+ console.error(`${C.red}✗ Missing client target.${C.reset} Usage: \`ocr setup <opencode | opencode-proxy | claude | codex | pi | dsh | omp>\``);
279
279
  process.exit(1);
280
280
  }
281
281
  const res = await setupClient(client, { port });
@@ -292,7 +292,7 @@ async function main() {
292
292
  printBanner();
293
293
  const client = args[1];
294
294
  if (!client) {
295
- console.error(`${C.red}✗ Missing client target.${C.reset} Usage: \`ocr teardown <opencode | opencode-proxy | claude | codex | pi | dsh>\``);
295
+ console.error(`${C.red}✗ Missing client target.${C.reset} Usage: \`ocr teardown <opencode | opencode-proxy | claude | codex | pi | dsh | omp>\``);
296
296
  process.exit(1);
297
297
  }
298
298
  const res = await teardownClient(client);
@@ -1,5 +1,5 @@
1
1
  export type CliAction = 'start' | 'stop' | 'restart' | 'status' | 'web' | 'ui' | 'desktop' | 'setup' | 'teardown' | 'install-shims' | 'env' | 'version' | 'help';
2
- export type SupportedClient = 'opencode' | 'opencode-proxy' | 'claude' | 'codex' | 'pi' | 'dsh';
2
+ export type SupportedClient = 'opencode' | 'opencode-proxy' | 'claude' | 'codex' | 'pi' | 'dsh' | 'omp';
3
3
  export interface CliOptions {
4
4
  action: CliAction;
5
5
  client?: SupportedClient;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Governance-overlay validator + typed accessors (P2b, design §2 / §3a-4 / §5).
3
+ *
4
+ * Trust boundary: every junk shape gets a LOUD boot error naming the offending
5
+ * entry (provider + index + keyHashPrefix, or apiKey id + index) — never a
6
+ * silent drop, never a silent repair. The Limiter (P1) stays config-ignorant;
7
+ * this module never builds a Limiter instance — it only validates the raw tree
8
+ * and hands thin `LimitEntryConfig[]` slices to the P3/P4 wiring.
9
+ *
10
+ * Rules enforced here (binding design lines):
11
+ * - window: parseWindow must accept (30s / 5m / 1h / 1d — lowercase integer
12
+ * duration strings; "5", "1x", "", "1M", "0s", numbers rejected).
13
+ * - window span upper bound: parsed length <= 31 days — governance windows
14
+ * are shaping windows, not accounting periods (longer horizons hide a
15
+ * stale budget behind a counter nobody prunes back).
16
+ * - keyHashPrefix: lowercase hex only (/^[0-9a-f]+$/) — the anchor is a
17
+ * one-way hash prefix of the credential, never a name or a mixed-case
18
+ * digest; all-hex digits stay a STRING at the YAML boundary (the emitter
19
+ * quotes number-lookalikes; round-trip pinned in tests).
20
+ * - EXACTLY ONE countable per entry (zero or ≥2 → error naming them).
21
+ * - countable value: positive finite number (zero/negative/NaN/non-number → error).
22
+ * - costUsd is inbound-only (error on `accounts:` entries; allowed on apiKeys).
23
+ * - per-subject uniqueness of (window, countable) within one entry list —
24
+ * equivalence on the PARSED duration (60s and 1m collide), which is what
25
+ * makes limiter rule ids unique addresses (design §5).
26
+ * - duplicate keyHashPrefix within the same provider → error.
27
+ * - shape guards: non-array list, non-object entry, unknown keys → error.
28
+ * - provider ids are NOT checked against the live registry here — unknown
29
+ * provider + stale-prefix anchors are P3 boot/pool-rebuild checks against
30
+ * resolveKeyChain.
31
+ *
32
+ * Degeneracy promise: absent `accounts:` / absent per-key `limits` → zero
33
+ * issues, zero state, byte-identical request paths.
34
+ */
35
+ import { type LimitEntryConfig } from '../ratelimit/index.js';
36
+ import type { RouterConfig } from './types.js';
37
+ /** One structured validation failure: where it lives + what is wrong. */
38
+ export type GovernanceValidationIssue = {
39
+ /** Offending entry locator, e.g. accounts.anthropic[0] (keyHashPrefix "ab12…") limits[1] */
40
+ location: string;
41
+ problem: string;
42
+ };
43
+ /** Loud boot error carrying every issue — loadConfig throws it, saveConfig surfaces it. */
44
+ export declare class GovernanceConfigError extends Error {
45
+ readonly issues: GovernanceValidationIssue[];
46
+ constructor(issues: GovernanceValidationIssue[]);
47
+ }
48
+ export declare function formatGovernanceIssues(issues: GovernanceValidationIssue[]): string;
49
+ /**
50
+ * Validate the governance tree + per-apiKey limits. Both arguments are RAW
51
+ * YAML-derived (any shape allowed — every guard below is a trust-boundary
52
+ * guard). Returns [] when nothing is configured: absent `accounts` and absent
53
+ * per-key `limits` never produce issues (degeneracy).
54
+ */
55
+ export declare function validateGovernanceLimits(accounts: unknown, apiKeys: unknown): GovernanceValidationIssue[];
56
+ /**
57
+ * Limits governing one account subject — the thin accessor P3 wiring feeds to
58
+ * `Limiter.setRules(accountSubject(provider, prefix), rules)`. undefined =
59
+ * unconfigured (no cap, no state: never build a Limiter rule from it).
60
+ * Returns the live config array — callers MUST treat it as read-only.
61
+ */
62
+ export declare function limitsForAccountSubject(config: Pick<RouterConfig, 'accounts'>, provider: string, keyHashPrefix: string): LimitEntryConfig[] | undefined;
63
+ /**
64
+ * Limits governing one inbound client key — the P4 auth-middleware counterpart
65
+ * (`Limiter.setRules(apiKeySubject(id), rules)`). undefined = unlimited.
66
+ * Returns the live config array — callers MUST treat it as read-only.
67
+ */
68
+ export declare function limitsForApiKey(config: Pick<RouterConfig, 'apiKeys'>, id: string): LimitEntryConfig[] | undefined;
@@ -0,0 +1,261 @@
1
+ /**
2
+ * Governance-overlay validator + typed accessors (P2b, design §2 / §3a-4 / §5).
3
+ *
4
+ * Trust boundary: every junk shape gets a LOUD boot error naming the offending
5
+ * entry (provider + index + keyHashPrefix, or apiKey id + index) — never a
6
+ * silent drop, never a silent repair. The Limiter (P1) stays config-ignorant;
7
+ * this module never builds a Limiter instance — it only validates the raw tree
8
+ * and hands thin `LimitEntryConfig[]` slices to the P3/P4 wiring.
9
+ *
10
+ * Rules enforced here (binding design lines):
11
+ * - window: parseWindow must accept (30s / 5m / 1h / 1d — lowercase integer
12
+ * duration strings; "5", "1x", "", "1M", "0s", numbers rejected).
13
+ * - window span upper bound: parsed length <= 31 days — governance windows
14
+ * are shaping windows, not accounting periods (longer horizons hide a
15
+ * stale budget behind a counter nobody prunes back).
16
+ * - keyHashPrefix: lowercase hex only (/^[0-9a-f]+$/) — the anchor is a
17
+ * one-way hash prefix of the credential, never a name or a mixed-case
18
+ * digest; all-hex digits stay a STRING at the YAML boundary (the emitter
19
+ * quotes number-lookalikes; round-trip pinned in tests).
20
+ * - EXACTLY ONE countable per entry (zero or ≥2 → error naming them).
21
+ * - countable value: positive finite number (zero/negative/NaN/non-number → error).
22
+ * - costUsd is inbound-only (error on `accounts:` entries; allowed on apiKeys).
23
+ * - per-subject uniqueness of (window, countable) within one entry list —
24
+ * equivalence on the PARSED duration (60s and 1m collide), which is what
25
+ * makes limiter rule ids unique addresses (design §5).
26
+ * - duplicate keyHashPrefix within the same provider → error.
27
+ * - shape guards: non-array list, non-object entry, unknown keys → error.
28
+ * - provider ids are NOT checked against the live registry here — unknown
29
+ * provider + stale-prefix anchors are P3 boot/pool-rebuild checks against
30
+ * resolveKeyChain.
31
+ *
32
+ * Degeneracy promise: absent `accounts:` / absent per-key `limits` → zero
33
+ * issues, zero state, byte-identical request paths.
34
+ */
35
+ import { DAY_WINDOW_MS, parseWindow } from '../ratelimit/index.js';
36
+ /** Loud boot error carrying every issue — loadConfig throws it, saveConfig surfaces it. */
37
+ export class GovernanceConfigError extends Error {
38
+ issues;
39
+ constructor(issues) {
40
+ super(formatGovernanceIssues(issues));
41
+ this.name = 'GovernanceConfigError';
42
+ this.issues = issues;
43
+ }
44
+ }
45
+ export function formatGovernanceIssues(issues) {
46
+ const lines = issues.map((i) => ` - ${i.location}: ${i.problem}`);
47
+ return (`[Config] account governance limits validation failed (${issues.length} issue(s)) — ` +
48
+ `fix config.yaml, refusing to silently drop or apply:\n${lines.join('\n')}`);
49
+ }
50
+ const COUNTABLES = ['requests', 'tokens', 'costUsd'];
51
+ const LIMIT_ENTRY_KEYS = new Set(['window', ...COUNTABLES]);
52
+ const GOVERNANCE_ENTRY_KEYS = new Set(['keyHashPrefix', 'limits']);
53
+ /** Upper bound any accepted window may span (31 days — validator-side only; the engine stays syntax-only). */
54
+ const MAX_WINDOW_MS = 31 * DAY_WINDOW_MS;
55
+ /** The account anchor alphabet: lowercase hex (a sha256-prefix digest — anything else is a name, alias, or typo). */
56
+ const KEY_HASH_PREFIX_RE = /^[0-9a-f]+$/;
57
+ const isPlainObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
58
+ /** Short human rendering of an offending value for error messages. */
59
+ function describeValue(v) {
60
+ if (v === undefined)
61
+ return 'undefined';
62
+ if (v === null)
63
+ return 'null';
64
+ if (Array.isArray(v))
65
+ return `array(len ${v.length})`;
66
+ if (typeof v === 'string')
67
+ return JSON.stringify(v);
68
+ if (typeof v === 'number' && Number.isNaN(v))
69
+ return 'NaN';
70
+ if (typeof v === 'object')
71
+ return 'object';
72
+ return String(v);
73
+ }
74
+ const quoteList = (items) => items.map((s) => `"${s}"`).join(', ');
75
+ /** Validate one limits array (shared shape, direction decides the costUsd gate). */
76
+ function validateLimitsList(limits, listLoc, direction, issues) {
77
+ if (!Array.isArray(limits)) {
78
+ issues.push({
79
+ location: listLoc,
80
+ problem: `must be an array of { window, <one countable> } entries, got ${describeValue(limits)}`,
81
+ });
82
+ return;
83
+ }
84
+ // parsed-windowMs + countable -> first entry carrying it (equivalence on the
85
+ // parsed duration, not the spelling: 60s/requests collides with 1m/requests).
86
+ const seen = new Map();
87
+ limits.forEach((raw, j) => {
88
+ const loc = `${listLoc}[${j}]`;
89
+ if (!isPlainObject(raw)) {
90
+ issues.push({
91
+ location: loc,
92
+ problem: `limit entry must be an object { window, one countable }, got ${describeValue(raw)}`,
93
+ });
94
+ return;
95
+ }
96
+ const unknownKeys = Object.keys(raw).filter((k) => !LIMIT_ENTRY_KEYS.has(k));
97
+ if (unknownKeys.length > 0) {
98
+ issues.push({
99
+ location: loc,
100
+ problem: `unknown key(s) ${quoteList(unknownKeys)} — allowed: window plus exactly one countable ` +
101
+ `(${COUNTABLES.join(' / ')})`,
102
+ });
103
+ }
104
+ const window = raw.window;
105
+ const windowMs = typeof window === 'string' ? parseWindow(window) : null;
106
+ if (windowMs === null) {
107
+ issues.push({
108
+ location: `${loc} window`,
109
+ problem: typeof window === 'string'
110
+ ? `invalid window ${JSON.stringify(window)} — expected an integer duration string like 30s / 5m / 1h / 1d (unsigned, uppercase, zero and fractional are rejected)`
111
+ : `window must be a duration string like 30s / 5m / 1h / 1d, got ${describeValue(window)}`,
112
+ });
113
+ }
114
+ else if (windowMs > MAX_WINDOW_MS) {
115
+ issues.push({
116
+ location: `${loc} window`,
117
+ problem: `window ${JSON.stringify(window)} exceeds the 31-day upper bound (${MAX_WINDOW_MS / DAY_WINDOW_MS}d) — ` +
118
+ 'governance windows are sliding shaping windows, not accounting periods; a longer horizon reads as a budget nobody prunes back',
119
+ });
120
+ }
121
+ const present = COUNTABLES.filter((c) => raw[c] !== undefined);
122
+ if (present.length !== 1) {
123
+ issues.push({
124
+ location: loc,
125
+ problem: present.length === 0
126
+ ? `must carry exactly one countable (${COUNTABLES.join(' / ')}), got none`
127
+ : `co-located countables ${quoteList(present)} — one entry = one window = one countable; split them into separate entries (design §3a item 4)`,
128
+ });
129
+ return; // value/uniqueness checks below assume the single-countable shape
130
+ }
131
+ const countable = present[0];
132
+ const value = raw[countable];
133
+ const valueLoc = `${loc} ${countable}`;
134
+ if (direction === 'accounts' && countable === 'costUsd') {
135
+ issues.push({
136
+ location: valueLoc,
137
+ problem: 'costUsd is inbound-only (apiKeys limits) — a budget is a contract with the caller, ' +
138
+ 'never a cap on the provider\'s own key (design §2)',
139
+ });
140
+ }
141
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
142
+ issues.push({ location: valueLoc, problem: `must be a positive finite number, got ${describeValue(value)}` });
143
+ }
144
+ if (windowMs === null)
145
+ return; // no valid window — nothing to address uniquely
146
+ const key = `${windowMs}|${countable}`;
147
+ const first = seen.get(key);
148
+ if (first !== undefined) {
149
+ issues.push({
150
+ location: loc,
151
+ problem: `duplicate rule "${window}/${countable}" — the same window+countable is already at [${first.at}] ` +
152
+ `("${first.window}/${countable}"); (window, countable) must be unique per subject so one verdict ` +
153
+ 'names exactly one YAML line (design §5)',
154
+ });
155
+ }
156
+ else {
157
+ seen.set(key, { at: j, window: window });
158
+ }
159
+ });
160
+ }
161
+ /**
162
+ * Validate the governance tree + per-apiKey limits. Both arguments are RAW
163
+ * YAML-derived (any shape allowed — every guard below is a trust-boundary
164
+ * guard). Returns [] when nothing is configured: absent `accounts` and absent
165
+ * per-key `limits` never produce issues (degeneracy).
166
+ */
167
+ export function validateGovernanceLimits(accounts, apiKeys) {
168
+ const issues = [];
169
+ if (accounts !== undefined && accounts !== null) {
170
+ if (!isPlainObject(accounts)) {
171
+ issues.push({
172
+ location: 'accounts',
173
+ problem: `must be a mapping providerId -> governance entry list, got ${describeValue(accounts)}`,
174
+ });
175
+ }
176
+ else {
177
+ for (const [provider, list] of Object.entries(accounts)) {
178
+ const loc = `accounts.${provider}`;
179
+ if (!Array.isArray(list)) {
180
+ issues.push({ location: loc, problem: `must be an array of { keyHashPrefix, limits } entries, got ${describeValue(list)}` });
181
+ continue;
182
+ }
183
+ const firstByPrefix = new Map();
184
+ list.forEach((raw, i) => {
185
+ if (!isPlainObject(raw)) {
186
+ issues.push({
187
+ location: `${loc}[${i}]`,
188
+ problem: `governance entry must be an object { keyHashPrefix, limits }, got ${describeValue(raw)}`,
189
+ });
190
+ return;
191
+ }
192
+ const unknownKeys = Object.keys(raw).filter((k) => !GOVERNANCE_ENTRY_KEYS.has(k));
193
+ if (unknownKeys.length > 0) {
194
+ issues.push({
195
+ location: `${loc}[${i}]`,
196
+ problem: `unknown key(s) ${quoteList(unknownKeys)} — allowed: keyHashPrefix, limits ` +
197
+ '(the account alias lives in account-state.json meta, not in config)',
198
+ });
199
+ }
200
+ const prefix = raw.keyHashPrefix;
201
+ let entryLoc = `${loc}[${i}]`;
202
+ if (typeof prefix !== 'string' || prefix.trim() === '') {
203
+ issues.push({
204
+ location: `${entryLoc} keyHashPrefix`,
205
+ problem: `must be a non-empty string anchor, got ${describeValue(prefix)}`,
206
+ });
207
+ }
208
+ else {
209
+ if (!KEY_HASH_PREFIX_RE.test(prefix)) {
210
+ issues.push({
211
+ location: `${loc}[${i}] keyHashPrefix`,
212
+ problem: `keyHashPrefix ${JSON.stringify(prefix)} must match /^[0-9a-f]+$/ — the anchor is a lowercase ` +
213
+ 'hex prefix of the credential hash, never a name, alias, or mixed-case digest',
214
+ });
215
+ }
216
+ const first = firstByPrefix.get(prefix);
217
+ if (first !== undefined) {
218
+ issues.push({
219
+ location: `${entryLoc} keyHashPrefix`,
220
+ problem: `duplicate keyHashPrefix "${prefix}" within provider "${provider}" (first entry at [${first}]) — one governance entry per account anchor`,
221
+ });
222
+ }
223
+ else {
224
+ firstByPrefix.set(prefix, i);
225
+ }
226
+ entryLoc = `${loc}[${i}] (keyHashPrefix "${prefix}")`;
227
+ }
228
+ validateLimitsList(raw.limits, `${entryLoc} limits`, 'accounts', issues);
229
+ });
230
+ }
231
+ }
232
+ }
233
+ if (Array.isArray(apiKeys)) {
234
+ apiKeys.forEach((raw, i) => {
235
+ if (!isPlainObject(raw) || raw.limits === undefined)
236
+ return; // absent = unlimited (degeneracy)
237
+ const id = typeof raw.id === 'string' && raw.id !== '' ? raw.id : `#${i}`;
238
+ validateLimitsList(raw.limits, `apiKeys[${i}] (id "${id}") limits`, 'apiKeys', issues);
239
+ });
240
+ }
241
+ return issues;
242
+ }
243
+ /**
244
+ * Limits governing one account subject — the thin accessor P3 wiring feeds to
245
+ * `Limiter.setRules(accountSubject(provider, prefix), rules)`. undefined =
246
+ * unconfigured (no cap, no state: never build a Limiter rule from it).
247
+ * Returns the live config array — callers MUST treat it as read-only.
248
+ */
249
+ export function limitsForAccountSubject(config, provider, keyHashPrefix) {
250
+ const entry = config.accounts?.[provider]?.find((e) => e.keyHashPrefix === keyHashPrefix);
251
+ return entry && entry.limits.length > 0 ? entry.limits : undefined;
252
+ }
253
+ /**
254
+ * Limits governing one inbound client key — the P4 auth-middleware counterpart
255
+ * (`Limiter.setRules(apiKeySubject(id), rules)`). undefined = unlimited.
256
+ * Returns the live config array — callers MUST treat it as read-only.
257
+ */
258
+ export function limitsForApiKey(config, id) {
259
+ const key = config.apiKeys?.find((k) => k.id === id);
260
+ return key?.limits && key.limits.length > 0 ? key.limits : undefined;
261
+ }
@@ -896,7 +896,7 @@ const YAML_FIELD_COMMENTS = {
896
896
  'modelProfiles.*.name': '方案显示名',
897
897
  'modelProfiles.*.slots': '槽位表:槽位名 → modelRef(注册模型 id / 组合 id / auto / lite / plus / pro / ultra)',
898
898
  'modelProfiles.*.note': '备注:仅控制台展示的自由文本,不参与路由',
899
- clientProfileMemory: '控制台表单记忆(按环境保存):各客户端挂接表单上次选择的模型方案、槽位映射与模型列表模式(none=不设置(默认)/ custom=自定义 / follow=跟随所选 API Key 的权限),以及上次写入的 API Key id(apiKeyId;挂接总是写入所选 Key,不存明文),仅用于页面回填,不参与路由、也不影响实际接管配置',
899
+ clientProfileMemory: '控制台表单记忆(按环境保存):点击“接入”时才写入——记录该次挂接实际应用的完整表单状态:模型方案、槽位映射与模型列表模式(none=不设置(默认)/ custom=自定义 / follow=跟随所选 API Key 的权限)、自定义模型列表(extraModels)、写入的 API Key id(apiKeyId;挂接总是写入所选 Key,不存明文),以及槽位/角色模型引用快照(models/agentModels)供“还原上次提交”按钮回填,仅用于页面回填,不参与路由、也不影响实际接管配置',
900
900
  defaultModels: '默认模型(网关自身内部调用花费的模型,不参与客户端路由)',
901
901
  'defaultModels.translation': '控制台内部翻译(技能描述/README)使用的模型:填写网关可见的 modelRef(档位别名 lite/plus/pro/ultra 或已注册模型 id)。未设置 = lite;配置的模型失败降级到 lite,lite 也失败则如实报错——链条绝不自行升级到 auto(内部非关键调用不允许无上限花费;显式写 auto 视为运营者自担成本,照常生效)。可解析性在请求时校验(模型在启动时才注册);更换该值不使已缓存翻译失效(缓存按原文+语言键控,为派生数据)',
902
902
  session: '会话粘性(棘轮:会话内模型不漂移)',
@@ -645,15 +645,25 @@ export interface SystemoneSurfaceConfig {
645
645
  defaultModel?: string;
646
646
  }
647
647
  /**
648
- * Console-only memory (per environment): the last profile id + agent→slot
649
- * mapping picked on the client-hook form. Never consulted by routing or by
650
- * the hook itself — restoring the UI selection across page reloads, gateway
651
- * restarts and teardown is its single job. Keyed by client name (reserved
652
- * for future clients' forms).
648
+ * Console-only memory (per environment): a write-through mirror of the
649
+ * client-hook form's selections — the last profile id + agent→slot mapping,
650
+ * the picked model refs, and the model-list draft. Never consulted by
651
+ * routing or by the hook itself — restoring the UI selection across page
652
+ * reloads, gateway restarts and teardown is its single job. Keyed by client
653
+ * name (reserved for future clients' forms).
653
654
  */
654
655
  export interface ClientProfileMemoryEntry {
655
656
  profile: string;
656
657
  bindings: Record<string, string>;
658
+ /** Write-through mirror of the form drafts (the console saves on every
659
+ * pick, see ClientsPage rememberDraft): models = slot → model-ref draft
660
+ * (pi/omp main pick, plain slot clients); agentModels = role/agent → raw
661
+ * draft ref (opencode agents, pi/omp role rows, native pins included).
662
+ * Absent = restore falls back to slot defaults. */
663
+ models?: Record<string, string>;
664
+ agentModels?: Record<string, string>;
665
+ /** Custom model-list draft (the manual extra models picked on the form). */
666
+ extraModels?: string[];
657
667
  /** Model-list source on the opencode form: 'none' (default) exposes no
658
668
  * concrete models, 'follow' derives the extra-model set from the selected
659
669
  * API key's effective access, 'custom' keeps the manual picker. UI-only —