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
@@ -0,0 +1,216 @@
1
+ import { keyHashPrefix } from './types.js';
2
+ import { credentialStoreStateFile, resolveDefaultPaths } from './paths.js';
3
+ import { getBoundCredentialPaths, readCredentialStoreState, writeCredentialStoreState, } from './factory.js';
4
+ import { authSnapshot } from './auth-snapshot.js';
5
+ /**
6
+ * The one-shot reconcile gate (anti-regression).
7
+ *
8
+ * On the FIRST boot that binds a writable OpencodeV2Store with no completion marker:
9
+ * read the auth.json snapshot (opencode-v1 read path via bridge primitives — read
10
+ * only), diff its api-type entries against the opencode v2 db credentials, and push
11
+ * auth.json-only keys through OpencodeV2Store.connectKey (POST …/connect/key).
12
+ * Dedup is keyed by (provider case-insensitive × keyHash prefix — hash
13
+ * primary, label advisory). oauth/wellknown entries are NEVER pushed
14
+ * (the OAuth boundary — reconcile pushes {type:'key'}/api only).
15
+ *
16
+ * auth.json itself is never modified or deleted (opencode's territory).
17
+ * Completing — even with partial push failures — writes the marker + audit
18
+ * trail into <ocrHome>/credential-store.json and sets authWriteDisabled,
19
+ * which B4 gates console auth.json writes on. The gate is idempotent:
20
+ * marker present => zero work; rerunning with the same inputs => zero pushes.
21
+ *
22
+ * Total function: it never throws — a crash lands as an excluded entry and
23
+ * the bind stands (boot must not die here).
24
+ */
25
+ const LOG_PREFIX = '[reconcile]';
26
+ const PUSH_FAILED_DETAIL = 'push failed, key present locally';
27
+ // Boot runs before the Fastify instance exists; the repo's boot convention
28
+ // is prefixed console lines (index.ts). B4's rebind path can inject req.log.
29
+ const defaultLog = {
30
+ info: (m) => console.log(m),
31
+ warn: (m) => console.warn(m),
32
+ };
33
+ export async function ensureReconciled(store, status, deps = {}) {
34
+ const log = deps.log ?? defaultLog;
35
+ const now = deps.now ?? Date.now;
36
+ const paths = deps.paths ?? getBoundCredentialPaths() ?? resolveDefaultPaths();
37
+ try {
38
+ return await runReconcile(store, status, paths, deps.bridge ?? authSnapshot(paths), log, now);
39
+ }
40
+ catch (e) {
41
+ const msg = e instanceof Error ? e.message : String(e);
42
+ log.warn(`${LOG_PREFIX} crashed — bind stands, boot continues: ${msg}`);
43
+ status.excluded.push({ provider: '*', reasonCode: 'reconcile_push_failed', detail: `reconcile crashed: ${msg}` });
44
+ return { ran: false, entries: [], authWriteDisabled: isAuthJsonWriteDisabled(paths) };
45
+ }
46
+ }
47
+ /**
48
+ * In-process override for the Decision 4 gate (P2-6): marker persistence goes
49
+ * through atomicWriteWithRetry best-effort (writeCredentialStoreState swallows
50
+ * a final failure), so a completed reconcile must still count as done FOR THIS
51
+ * BOOT even when the file write failed. The persisted file stays the
52
+ * cross-boot fallback: if the marker never survived, the next boot re-runs the
53
+ * gate — idempotent by keyHash dedup (pushed keys dedup, failed keys retry) —
54
+ * which is strictly safer than silently re-enabling auth.json writes. Keyed by
55
+ * state-file path so sandboxed machines never share an override.
56
+ */
57
+ const inProcessAuthWriteDisabled = new Set();
58
+ /**
59
+ * Sync read of the Decision 4 gate's B4 seam: true only when the PERSISTED
60
+ * binding is a writable 'opencode-v2' AND the reconcile marker completed (or the
61
+ * marker completed in-process this boot — see override above). Cheap
62
+ * single-file read; no file-state cache — the answer must reflect a
63
+ * just-completed reconcile within the same boot, and it is only consulted on
64
+ * admin credential writes.
65
+ */
66
+ export function isAuthJsonWriteDisabled(paths) {
67
+ const p = paths ?? getBoundCredentialPaths() ?? resolveDefaultPaths();
68
+ if (inProcessAuthWriteDisabled.has(credentialStoreStateFile(p)))
69
+ return true;
70
+ const state = readCredentialStoreState(p);
71
+ return state?.bound === 'opencode-v2' && state?.reconcile?.authWriteDisabled === true;
72
+ }
73
+ /**
74
+ * B4 parallel flag (NOT folded into isAuthJsonWriteDisabled, which stays the
75
+ * opencode-v2 reconcile gate per Decision 4): true when the standalone one-shot import
76
+ * landed this machine on OcrStore with auth.json entries — from then on
77
+ * auth.json is superseded by <ocrHome>/credentials.json as the OCR-side truth
78
+ * and the console must not side-write it (same anti-double-truth reason).
79
+ */
80
+ export function isStandaloneAuthImported(paths) {
81
+ const state = readCredentialStoreState(paths ?? getBoundCredentialPaths() ?? resolveDefaultPaths());
82
+ return state?.bound === 'ocr' && typeof state?.standaloneImport?.doneAt === 'number';
83
+ }
84
+ /**
85
+ * KeyHash dedup index of a store's current credentials (shared dedup
86
+ * rule: keyHash primary, label advisory). Shared by the reconcile gate and
87
+ * the push endpoint — one guard, two converge-toward-opencode
88
+ * flows. An empty index on throw degrades toward pushing (a duplicate push is
89
+ * louder and safer than skipping real keys); push failures land in results,
90
+ * never silence.
91
+ */
92
+ export function indexStoreKeyHashes(store, log = defaultLog) {
93
+ const index = new Map();
94
+ try {
95
+ for (const overview of store.accountsOverview()) {
96
+ for (const meta of store.listAccounts(overview.providerId)) {
97
+ if (!meta.keyHashPrefix)
98
+ continue;
99
+ const bucket = index.get(meta.providerId.toLowerCase());
100
+ if (bucket)
101
+ bucket.add(meta.keyHashPrefix);
102
+ else
103
+ index.set(meta.providerId.toLowerCase(), new Set([meta.keyHashPrefix]));
104
+ }
105
+ }
106
+ }
107
+ catch (e) {
108
+ log.warn(`${LOG_PREFIX} could not index store credentials for dedup: ${e instanceof Error ? e.message : String(e)}`);
109
+ }
110
+ return index;
111
+ }
112
+ async function runReconcile(store, status, paths, bridge, log, now) {
113
+ // Decision 1 (P2-8): branch on CAPABILITIES, never on `kind`. The gate
114
+ // needs a store that can push api keys toward the opencode v2 truth —
115
+ // envVisible (coexists with opencode's surface) AND activate (writable
116
+ // per-account semantics) is exactly the writable-OpencodeV2Store signature.
117
+ // opencode-v2-readonly cannot push (writes refused) — the gate waits for a
118
+ // writable bind; other kinds have nothing to converge toward opencode.
119
+ if (!store.capabilities.envVisible || !store.capabilities.activate) {
120
+ return { ran: false, skipped: 'not-opencode-v2', entries: [], authWriteDisabled: false };
121
+ }
122
+ const state = readCredentialStoreState(paths);
123
+ if (state?.reconcile?.doneAt) {
124
+ // Audit honesty (P2-5): the one-shot ran on an earlier
125
+ // boot — failed entries from the persisted audit trail stay STRANDED
126
+ // keys. Without this re-append they vanish after boot #1 (silent). The
127
+ // reason was redacted by construction (http() redacts before the message
128
+ // is built), so it is management-surface safe.
129
+ for (const entry of state.reconcile.entries) {
130
+ if (entry.action !== 'failed')
131
+ continue;
132
+ const dup = status.excluded.some((e) => e.provider === entry.provider && e.reasonCode === 'reconcile_push_failed');
133
+ if (dup)
134
+ continue;
135
+ status.excluded.push({
136
+ provider: entry.provider,
137
+ reasonCode: 'reconcile_push_failed',
138
+ detail: `persisted reconcile failure: ${entry.reason ?? PUSH_FAILED_DETAIL}`,
139
+ });
140
+ }
141
+ return {
142
+ ran: false,
143
+ skipped: 'already-done',
144
+ entries: state.reconcile.entries,
145
+ authWriteDisabled: state.reconcile.authWriteDisabled === true,
146
+ };
147
+ }
148
+ // --- read the auth.json snapshot (never write it) ------------------------
149
+ let snapshot;
150
+ try {
151
+ snapshot = bridge.read();
152
+ }
153
+ catch (e) {
154
+ const msg = e instanceof Error ? e.message : String(e);
155
+ log.warn(`${LOG_PREFIX} auth.json snapshot unreadable — nothing to reconcile: ${msg}`);
156
+ status.excluded.push({ provider: '*', reasonCode: 'reconcile_push_failed', detail: `auth.json snapshot unreadable — nothing reconciled: ${msg}` });
157
+ snapshot = {};
158
+ }
159
+ // --- index the db credentials for dedup (keyHash primary) ---------------
160
+ const dbIndex = indexStoreKeyHashes(store, log);
161
+ // --- entry-by-entry converge (push-only toward opencode) -----------------
162
+ const entries = [];
163
+ let pushed = 0;
164
+ for (const [providerId, entry] of Object.entries(snapshot)) {
165
+ if (!entry ||
166
+ typeof entry !== 'object' ||
167
+ entry.type !== 'api' || // oauth/wellknown never pushed
168
+ typeof entry.key !== 'string' ||
169
+ !entry.key) {
170
+ continue;
171
+ }
172
+ const prefix = keyHashPrefix(entry.key);
173
+ if (dbIndex.get(providerId.toLowerCase())?.has(prefix)) {
174
+ log.info(`${LOG_PREFIX} ${providerId}: deduped (key ${prefix})`);
175
+ entries.push({ provider: providerId, action: 'deduped' });
176
+ continue;
177
+ }
178
+ try {
179
+ await store.connectKey(providerId, entry.key);
180
+ pushed += 1;
181
+ log.info(`${LOG_PREFIX} ${providerId}: pushed (key ${prefix})`);
182
+ entries.push({ provider: providerId, action: 'pushed' });
183
+ }
184
+ catch (e) {
185
+ const msg = e instanceof Error ? e.message : String(e);
186
+ log.warn(`${LOG_PREFIX} ${providerId}: push failed — ${msg}`);
187
+ entries.push({ provider: providerId, action: 'failed', reason: msg });
188
+ status.excluded.push(excludedPushFailure(providerId));
189
+ // keep going: remaining entries must not be silently dropped
190
+ }
191
+ }
192
+ // Pushed keys must be resolvable THIS boot — drop the cached view.
193
+ if (pushed > 0)
194
+ store.invalidate();
195
+ const reconcile = {
196
+ doneAt: now(),
197
+ authWriteDisabled: true, // even with partial failures: no future auth.json writes on this machine
198
+ entries,
199
+ };
200
+ const base = state ?? {
201
+ bound: store.kind,
202
+ version: null,
203
+ evidence: status.evidence,
204
+ degradedCode: status.degradedCode,
205
+ updatedAt: now(),
206
+ };
207
+ writeCredentialStoreState(paths, { ...base, reconcile });
208
+ // P2-6: the gate completed THIS boot — the override keeps the auth.json
209
+ // write path disabled even if the marker write above failed best-effort.
210
+ inProcessAuthWriteDisabled.add(credentialStoreStateFile(paths));
211
+ log.info(`${LOG_PREFIX} complete: ${pushed} pushed, ${entries.length} entries recorded; auth.json write path disabled`);
212
+ return { ran: true, entries, authWriteDisabled: true };
213
+ }
214
+ function excludedPushFailure(provider) {
215
+ return { provider, reasonCode: 'reconcile_push_failed', detail: PUSH_FAILED_DETAIL };
216
+ }
@@ -0,0 +1,29 @@
1
+ import { ModelRegistration } from '../config/types.js';
2
+ export interface OpenCodeServiceConfig {
3
+ baseUrl: string;
4
+ authHeader: string;
5
+ password?: string;
6
+ }
7
+ export declare class OpenCodeConnector {
8
+ private serviceConfig;
9
+ constructor(customUrl?: string, customPassword?: string);
10
+ /**
11
+ * Auto-discover OpenCode v2 background service from ~/.config/opencode/service.json
12
+ */
13
+ resolveServiceConfig(customUrl?: string, customPassword?: string): OpenCodeServiceConfig | null;
14
+ isAvailable(): boolean;
15
+ getServiceConfig(): OpenCodeServiceConfig | null;
16
+ /**
17
+ * Fetch active providers from OpenCode v2
18
+ */
19
+ getProviders(): Promise<any[]>;
20
+ /**
21
+ * Fetch active models and pricing from OpenCode v2
22
+ */
23
+ getModels(): Promise<any[]>;
24
+ /**
25
+ * Automatically categorize OpenCode models into FinOps lite, plus, pro, and ultra tiers
26
+ * completely dynamically based on pricing and capabilities (Zero Hardcoding!)
27
+ */
28
+ syncToTierModels(): Promise<ModelRegistration[]>;
29
+ }
@@ -0,0 +1,186 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { EFFORT_LADDER } from '../types/router.js';
5
+ import { loadConfig } from '../config/index.js';
6
+ import { resolveTierMatch, classifyTier } from '../providers/tier-match.js';
7
+ import { readOverridesStore } from './catalog/overrides-store.js';
8
+ export class OpenCodeConnector {
9
+ serviceConfig = null;
10
+ constructor(customUrl, customPassword) {
11
+ this.serviceConfig = this.resolveServiceConfig(customUrl, customPassword);
12
+ }
13
+ /**
14
+ * Auto-discover OpenCode v2 background service from ~/.config/opencode/service.json
15
+ */
16
+ resolveServiceConfig(customUrl, customPassword) {
17
+ const baseUrl = customUrl || process.env.OPENCODE_SERVER_URL || 'http://127.0.0.1:49374';
18
+ let password = customPassword || process.env.OPENCODE_SERVER_PASSWORD;
19
+ if (!password) {
20
+ const configPaths = [
21
+ path.join(os.homedir(), '.config', 'opencode', 'service.json'),
22
+ path.join(os.homedir(), '.opencode', 'service.json'),
23
+ ];
24
+ for (const p of configPaths) {
25
+ if (fs.existsSync(p)) {
26
+ try {
27
+ const raw = JSON.parse(fs.readFileSync(p, 'utf8'));
28
+ if (raw.password) {
29
+ password = raw.password;
30
+ break;
31
+ }
32
+ }
33
+ catch {
34
+ // Ignore parse errors
35
+ }
36
+ }
37
+ }
38
+ }
39
+ if (!password) {
40
+ return null;
41
+ }
42
+ const authHeader = 'Basic ' + Buffer.from(`opencode:${password}`).toString('base64');
43
+ return {
44
+ baseUrl,
45
+ authHeader,
46
+ password,
47
+ };
48
+ }
49
+ isAvailable() {
50
+ return this.serviceConfig !== null;
51
+ }
52
+ getServiceConfig() {
53
+ return this.serviceConfig;
54
+ }
55
+ /**
56
+ * Fetch active providers from OpenCode v2
57
+ */
58
+ async getProviders() {
59
+ if (!this.serviceConfig)
60
+ throw new Error('OpenCode v2 service credentials not found');
61
+ const res = await fetch(`${this.serviceConfig.baseUrl}/api/provider`, {
62
+ headers: { Authorization: this.serviceConfig.authHeader },
63
+ });
64
+ if (!res.ok)
65
+ throw new Error(`OpenCode provider fetch failed [${res.status}]`);
66
+ const json = (await res.json());
67
+ return json.data || [];
68
+ }
69
+ /**
70
+ * Fetch active models and pricing from OpenCode v2
71
+ */
72
+ async getModels() {
73
+ if (!this.serviceConfig)
74
+ throw new Error('OpenCode v2 service credentials not found');
75
+ const res = await fetch(`${this.serviceConfig.baseUrl}/api/model`, {
76
+ headers: { Authorization: this.serviceConfig.authHeader },
77
+ });
78
+ if (!res.ok)
79
+ throw new Error(`OpenCode model fetch failed [${res.status}]`);
80
+ const json = (await res.json());
81
+ return json.data || [];
82
+ }
83
+ /**
84
+ * Automatically categorize OpenCode models into FinOps lite, plus, pro, and ultra tiers
85
+ * completely dynamically based on pricing and capabilities (Zero Hardcoding!)
86
+ */
87
+ async syncToTierModels() {
88
+ const rawModels = await this.getModels();
89
+ const registered = [];
90
+ // Shared smart match — same config & precedence as the direct boot pool
91
+ // (providers/tier-match.ts); this path must not drift its own heuristic.
92
+ const tierMatch = resolveTierMatch(loadConfig().tiers);
93
+ for (const m of rawModels) {
94
+ if (m.status !== 'active')
95
+ continue;
96
+ const modelId = `${m.providerID}/${m.id}`;
97
+ // 1. Detect thinking-effort capability dynamically from variants and metadata
98
+ const isReasoning = m.capabilities?.reasoning === true ||
99
+ m.variants?.some((v) => v.settings?.thinking || v.settings?.effort);
100
+ // 1b. Per-level effort override: if an operator has stored a finer
101
+ // truth in the overrides store, use that. Absent = catalog default
102
+ // (all 5 non-default levels, when the model is thinking-capable).
103
+ // Narrow the untyped JSON values to the typed vocabulary; silently drop
104
+ // anything that doesn't match a known level (catastrophic input
105
+ // hygiene, but the catalog store is operator-controlled).
106
+ const rawOverride = readOverridesStore()?.models[`${m.providerID}||${m.id}`]?.reasoningEfforts;
107
+ const allowedEfforts = new Set(EFFORT_LADDER);
108
+ const effortOverride = Array.isArray(rawOverride)
109
+ ? (rawOverride.filter((v) => typeof v === 'string' && allowedEfforts.has(v)))
110
+ : undefined;
111
+ // 2. Extract pricing (OpenCode cost array is per 1M tokens)
112
+ const inputCost = m.cost?.[0]?.input ?? (isReasoning ? 10.0 : 2.0);
113
+ const outputCost = m.cost?.[0]?.output ?? inputCost * 4.0;
114
+ const cachedCost = m.cost?.[0]?.cache?.read ?? inputCost * 0.25;
115
+ // 3. Tiering via the shared classifyTier (patterns > price band >
116
+ // thinking-effort flag) — missing price skips bands, and since ADR-0012 nothing
117
+ // claims the model → it stays UNCLASSIFIED (no residual tier).
118
+ const membership = classifyTier({ modelId: m.id, inputPerM: m.cost?.[0]?.input, reasoningFlag: isReasoning }, tierMatch);
119
+ const unclassified = membership === 'unclassified';
120
+ const tier = unclassified ? 'plus' : membership;
121
+ registered.push({
122
+ id: modelId,
123
+ provider: m.providerID,
124
+ upstreamModel: m.modelID || m.id,
125
+ tier,
126
+ isDefaultInTier: false, // will be dynamically assigned below
127
+ // Per-level effort support: catalog sources today only declare a
128
+ // boolean "thinking-effort" capability, so we treat any thinking-capable
129
+ // model as supporting the full 6-level EFFORT_LADDER by default
130
+ // (`none` included — it is rank 0 and always servable; the provider
131
+ // builders skip the thinking block for it, so listing it costs nothing).
132
+ // Operators who need finer truth (e.g. "gpt-5.1 has no xhigh" or
133
+ // "Claude Sonnet 4.5 has no max") override via the catalog
134
+ // overrides-store `reasoningEfforts` field, read in step 1b above and
135
+ // applied here.
136
+ supportedReasoningEfforts: isReasoning
137
+ ? effortOverride ?? EFFORT_LADDER
138
+ : undefined,
139
+ supportsReasoningEffort: isReasoning || undefined,
140
+ supportsPromptCaching: true,
141
+ tierMatch: { rawInputPerM: m.cost?.[0]?.input, reasoningFlag: isReasoning },
142
+ ...(unclassified ? { unclassified: true } : {}),
143
+ pricing: {
144
+ input: inputCost,
145
+ output: outputCost,
146
+ cacheRead: cachedCost,
147
+ ...(m.cost?.[0]?.cache?.write !== undefined ? { cacheWrite: m.cost[0].cache.write } : {}),
148
+ },
149
+ });
150
+ }
151
+ // -----------------------------------------------------------------
152
+ // 4. Dynamic Default Selection (Zero hardcoded model or provider names)
153
+ // -----------------------------------------------------------------
154
+ // Separate external configured plans from local synthetic fallback if
155
+ // available. ADR-0012: UNCLASSIFIED models join no pool, so they can never
156
+ // be picked as a tier representative either (their `tier` is a placeholder).
157
+ const claimable = (m) => !m.unclassified;
158
+ const externalPlans = registered.filter(m => m.provider !== 'opencode' && claimable(m));
159
+ const pool = externalPlans.length > 0 ? externalPlans : registered.filter(claimable);
160
+ // Lite Tier Default: lowest input cost model in lite tier
161
+ const tLite = pool.filter(m => m.tier === 'lite').sort((a, b) => a.pricing.input - b.pricing.input);
162
+ if (tLite.length > 0) {
163
+ tLite[0].isDefaultInTier = true;
164
+ }
165
+ // Plus Tier Default: plus model from pool (fallback: any non-pro/non-ultra)
166
+ let tPlus = pool.filter(m => m.tier === 'plus').sort((a, b) => a.pricing.input - b.pricing.input);
167
+ if (tPlus.length === 0) {
168
+ tPlus = pool.filter(m => m.tier !== 'pro' && m.tier !== 'ultra');
169
+ }
170
+ if (tPlus.length > 0) {
171
+ tPlus[Math.floor(tPlus.length / 2)].isDefaultInTier = true;
172
+ }
173
+ // Pro Tier Default: top thinking-effort capability model
174
+ const tPro = pool.filter(m => m.tier === 'pro');
175
+ if (tPro.length > 0) {
176
+ const topPro = tPro.find(m => m.supportsReasoningEffort) || tPro[0];
177
+ topPro.isDefaultInTier = true;
178
+ }
179
+ // Ultra Tier Default: top-priced model in ultra tier (frontier)
180
+ const tUltra = pool.filter(m => m.tier === 'ultra').sort((a, b) => b.pricing.input - a.pricing.input);
181
+ if (tUltra.length > 0) {
182
+ tUltra[0].isDefaultInTier = true;
183
+ }
184
+ return registered;
185
+ }
186
+ }
@@ -0,0 +1,101 @@
1
+ import type { CallCredential } from '../providers/base.js';
2
+ import type { CircuitBreakerManager } from '../resilience/circuit-breaker-manager.js';
3
+ import type { ModelRegistration } from '../config/types.js';
4
+ import type { ConversationSession } from '../session/session-manager.js';
5
+ /**
6
+ * Per-request account selection with session affinity.
7
+ *
8
+ * switching is FORCED FAILOVER, never balancing
9
+ *
10
+ * Pure over (session binding, pair breaker state, suspect flags): it decides which
11
+ * credential of a provider chain should serve one (session x model) call and
12
+ * which affinity mutation the caller must PERSIST after a success. Persistence
13
+ * lives with the caller (the orchestrator) precisely so a speculative move is
14
+ * never written when the chosen account then fails.
15
+ *
16
+ * bound present & healthy -> keep (no rebalance, ever)
17
+ * bound present & pair breaker OPEN/suspect -> next healthy in chain order, FORCED rebind
18
+ * bound absent/expired/stale -> deterministic hash(sessionId) spread (new-session rule)
19
+ * chain length <= 1 / no chain -> undefined = legacy no-prefix path (byte-identical)
20
+ * every prefix out -> undefined + 'all-unhealthy' (caller keeps the
21
+ * last-candidate force: today's gate semantics)
22
+ *
23
+ * No switch-back logic exists anywhere: a binding only moves while its breaker is
24
+ * out, and the moved-to value then holds while it is healthy — recovery of the
25
+ * old account cannot pull traffic back (correct by construction).
26
+ */
27
+ /** Anthropic's default prompt-cache TTL (5 min, 2026-03-06) — the affinity window. */
28
+ export declare const DEFAULT_ACCOUNT_AFFINITY_CACHE_TTL_MS = 300000;
29
+ /** Why no credential was selected (never an error — each maps to a caller rule). */
30
+ export type AccountSelectionReason =
31
+ /** Provider has no registered chain (config.yaml/mock boot shape) — baked key path. */
32
+ 'no-chain'
33
+ /**
34
+ * Single-credential chain — today's byte-identical no-prefix path. NOT returned
35
+ * when that one credential is operator-disabled: the no-prefix path would serve
36
+ * the boot-baked key and route traffic the operator took down, so the takedown
37
+ * outranks the degeneracy and 'all-disabled' is returned instead.
38
+ */
39
+ | 'single-credential'
40
+ /** Every prefix is pair-OPEN or account-SUSPECT — caller forces without attribution. */
41
+ | 'all-unhealthy'
42
+ /**
43
+ * Every credential of this chain is operator-DISABLED. Unlike 'all-unhealthy'
44
+ * this is NEVER forced: a takedown is a decision, not a guess about health, so
45
+ * the caller must move on to another candidate even at the last position.
46
+ */
47
+ | 'all-disabled';
48
+ export interface AccountSelection {
49
+ /** Credential to pass to `registry.execute`; undefined = no prefix (legacy path). */
50
+ credential?: CallCredential;
51
+ /** Set only when this turn produced NO credential; explains which degeneracy applies. */
52
+ reason?: AccountSelectionReason;
53
+ /**
54
+ * Affinity mutation to persist AFTER the call succeeds:
55
+ * forced=false -> first-write-wins bind; forced=true -> rebind (the bound
56
+ * account moved, or its stored prefix is stale/expired).
57
+ */
58
+ bind?: {
59
+ keyHashPrefix: string;
60
+ forced: boolean;
61
+ };
62
+ /** True when this selection moved the session off its previously bound account. */
63
+ forcedMove: boolean;
64
+ }
65
+ export interface AccountSelectionCtx {
66
+ /** Session id the deterministic spread hashes over (conversation identity). */
67
+ sessionId: string;
68
+ /** Affinity window; default `DEFAULT_ACCOUNT_AFFINITY_CACHE_TTL_MS`. */
69
+ affinityWindowMs?: number;
70
+ /** Clock seam for tests. */
71
+ now?: () => number;
72
+ /**
73
+ * Rate-limit shaping predicate: true = this credential is currently at a
74
+ * local window cap (`accounts:` overlay). Applied ONLY to the new-session
75
+ * spread and the forced-failover landing — NEVER to a kept binding, which a
76
+ * local cap must not move (iron law: rebinding burns the prompt cache; the
77
+ * provider's own 429, not a local hint, is what a bound session should
78
+ * react to). When EVERY healthy account is capped the filter opens again —
79
+ * shaping never starves a provider that has no slack.
80
+ * PURE READ: call sites peek without consuming; use `onSpreadCapped` (not a
81
+ * side effect in this predicate) to observe a cap that actually shaped a
82
+ * placement — the filter is consulted before the keep branch and must not
83
+ * report a kept binding as steered-around.
84
+ */
85
+ spreadCapped?: (keyHashPrefix: string) => boolean;
86
+ /**
87
+ * Notifier for the shape that LANDED: called once per capped member that the
88
+ * slack filter actually excluded from the spread pool (new-session spread and
89
+ * forced-failover landing only; never when the all-capped filter re-opens,
90
+ * never for a kept binding). Purely observational.
91
+ */
92
+ onSpreadCapped?: (keyHashPrefix: string) => void;
93
+ }
94
+ /**
95
+ * Deterministic new-session spread index: sha256(sessionId) % count. Stable
96
+ * across restarts and across callers; cold prefixes have nothing to lose, so
97
+ * spreading new sessions is free (Decision 7). Exported so tests assert the
98
+ * same function the resolver uses instead of duplicating the hash.
99
+ */
100
+ export declare function accountSpreadIndex(sessionId: string, count: number): number;
101
+ export declare function selectAccount(session: ConversationSession | undefined, model: ModelRegistration, chain: readonly CallCredential[] | undefined, cb: CircuitBreakerManager, ctx: AccountSelectionCtx): AccountSelection;
@@ -0,0 +1,112 @@
1
+ import crypto from 'node:crypto';
2
+ /**
3
+ * Per-request account selection with session affinity.
4
+ *
5
+ * switching is FORCED FAILOVER, never balancing
6
+ *
7
+ * Pure over (session binding, pair breaker state, suspect flags): it decides which
8
+ * credential of a provider chain should serve one (session x model) call and
9
+ * which affinity mutation the caller must PERSIST after a success. Persistence
10
+ * lives with the caller (the orchestrator) precisely so a speculative move is
11
+ * never written when the chosen account then fails.
12
+ *
13
+ * bound present & healthy -> keep (no rebalance, ever)
14
+ * bound present & pair breaker OPEN/suspect -> next healthy in chain order, FORCED rebind
15
+ * bound absent/expired/stale -> deterministic hash(sessionId) spread (new-session rule)
16
+ * chain length <= 1 / no chain -> undefined = legacy no-prefix path (byte-identical)
17
+ * every prefix out -> undefined + 'all-unhealthy' (caller keeps the
18
+ * last-candidate force: today's gate semantics)
19
+ *
20
+ * No switch-back logic exists anywhere: a binding only moves while its breaker is
21
+ * out, and the moved-to value then holds while it is healthy — recovery of the
22
+ * old account cannot pull traffic back (correct by construction).
23
+ */
24
+ /** Anthropic's default prompt-cache TTL (5 min, 2026-03-06) — the affinity window. */
25
+ export const DEFAULT_ACCOUNT_AFFINITY_CACHE_TTL_MS = 300_000;
26
+ /**
27
+ * Deterministic new-session spread index: sha256(sessionId) % count. Stable
28
+ * across restarts and across callers; cold prefixes have nothing to lose, so
29
+ * spreading new sessions is free (Decision 7). Exported so tests assert the
30
+ * same function the resolver uses instead of duplicating the hash.
31
+ */
32
+ export function accountSpreadIndex(sessionId, count) {
33
+ if (count <= 1)
34
+ return 0;
35
+ const hex = crypto.createHash('sha256').update(sessionId).digest('hex').slice(0, 8);
36
+ return parseInt(hex, 16) % count;
37
+ }
38
+ export function selectAccount(session, model, chain, cb, ctx) {
39
+ if (!chain || chain.length === 0)
40
+ return { forcedMove: false, reason: 'no-chain' };
41
+ // A takedown outranks every degeneracy: the no-prefix paths (single-credential,
42
+ // and 'all-unhealthy' below) fall back to the boot-baked head key, which would
43
+ // route through a credential the operator explicitly parked.
44
+ const allDisabled = chain.every((c) => cb.isDisabled(model.id, c.keyHashPrefix));
45
+ if (allDisabled)
46
+ return { forcedMove: false, reason: 'all-disabled' };
47
+ if (chain.length === 1) {
48
+ // Single-credential degeneracy: no prefix is ever passed, so no pair breakers are
49
+ // created and every downstream path is exactly pre-P3 behavior.
50
+ return { forcedMove: false, reason: 'single-credential' };
51
+ }
52
+ const healthy = chain.filter((c) => !cb.isPairOut(model.id, c.keyHashPrefix));
53
+ // Rate-limit shaping: when a predicate exists, NEW placements (spread and
54
+ // the forced-failover landing) prefer accounts with window slack; a kept
55
+ // binding below never consults it (iron law). All-capped chain = filter
56
+ // opens again — local shaping must never starve a provider of its own key.
57
+ const spreadCapped = ctx.spreadCapped;
58
+ const cappedSet = spreadCapped
59
+ ? new Set(healthy.filter((c) => spreadCapped(c.keyHashPrefix)).map((c) => c.keyHashPrefix))
60
+ : undefined;
61
+ const withSlack = cappedSet
62
+ ? healthy.filter((c) => !cappedSet.has(c.keyHashPrefix))
63
+ : healthy;
64
+ const spreadPool = withSlack.length > 0 ? withSlack : healthy;
65
+ // The slack filter only SHAPED the landing when it actually excluded someone
66
+ // (withSlack non-empty); the all-capped re-open is a no-op for the ledger.
67
+ const notifyShaped = () => {
68
+ if (!cappedSet || cappedSet.size === 0 || withSlack.length === 0)
69
+ return;
70
+ for (const c of healthy)
71
+ if (cappedSet.has(c.keyHashPrefix))
72
+ ctx.onSpreadCapped?.(c.keyHashPrefix);
73
+ };
74
+ const bound = session?.boundKeyHashPrefix;
75
+ const now = (ctx.now ?? Date.now)();
76
+ const windowMs = ctx.affinityWindowMs ?? DEFAULT_ACCOUNT_AFFINITY_CACHE_TTL_MS;
77
+ // Lazy TTL expiry: idle past the cache window the prefix is re-billed anyway,
78
+ // so the binding is treated as ABSENT and the session re-spreads like new.
79
+ const boundLive = bound !== undefined && now - (session?.lastActiveAt ?? 0) <= windowMs;
80
+ if (bound !== undefined && boundLive) {
81
+ const kept = healthy.find((c) => c.keyHashPrefix === bound);
82
+ if (kept)
83
+ return { credential: kept, forcedMove: false };
84
+ if (chain.some((c) => c.keyHashPrefix === bound)) {
85
+ // FORCED failover — the bound account is known-bad for this model.
86
+ if (healthy.length === 0)
87
+ return { forcedMove: false, reason: 'all-unhealthy' };
88
+ const next = spreadPool[0]; // chain order = selection priority (active head first)
89
+ notifyShaped();
90
+ return {
91
+ credential: next,
92
+ bind: { keyHashPrefix: next.keyHashPrefix, forced: true },
93
+ forcedMove: true,
94
+ };
95
+ }
96
+ // else: stale binding (keyHash gone from this boot's chain) — fall through
97
+ // to the spread below; registry.execute would throw on the unknown prefix,
98
+ // so recovery happens HERE, at the selection boundary, never as a 500.
99
+ }
100
+ // New-session spread — also the landing for expired and stale bindings.
101
+ if (healthy.length === 0)
102
+ return { forcedMove: false, reason: 'all-unhealthy' };
103
+ const pick = spreadPool[accountSpreadIndex(ctx.sessionId, spreadPool.length)];
104
+ notifyShaped();
105
+ return {
106
+ credential: pick,
107
+ forcedMove: false,
108
+ // forced=true overwrites an expired/stale stored value; a genuinely unset
109
+ // binding uses the first-write-wins path.
110
+ bind: { keyHashPrefix: pick.keyHashPrefix, forced: bound !== undefined },
111
+ };
112
+ }