omnicell-router 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/RELEASING.md +238 -238
  2. package/RELEASING.zh-CN.md +230 -230
  3. package/backend/dist/capture/recorder.js +2 -1
  4. package/backend/dist/cli/clients/base.js +8 -16
  5. package/backend/dist/cli/clients/dsh.js +8 -16
  6. package/backend/dist/cli/clients/pi.js +16 -9
  7. package/backend/dist/cli/types.d.ts +5 -0
  8. package/backend/dist/config/env.js +2 -1
  9. package/backend/dist/config/index.js +2 -0
  10. package/backend/dist/config/types.d.ts +23 -0
  11. package/backend/dist/harness/adapters/amp.d.ts +2 -0
  12. package/backend/dist/harness/adapters/amp.js +7 -0
  13. package/backend/dist/harness/adapters/claude.d.ts +2 -0
  14. package/backend/dist/harness/adapters/claude.js +7 -0
  15. package/backend/dist/harness/adapters/cline.d.ts +2 -0
  16. package/backend/dist/harness/adapters/cline.js +6 -0
  17. package/backend/dist/harness/adapters/codex.d.ts +2 -0
  18. package/backend/dist/harness/adapters/codex.js +6 -0
  19. package/backend/dist/harness/adapters/cursor.d.ts +5 -0
  20. package/backend/dist/harness/adapters/cursor.js +10 -0
  21. package/backend/dist/harness/adapters/declarative.d.ts +62 -0
  22. package/backend/dist/harness/adapters/declarative.js +202 -0
  23. package/backend/dist/harness/adapters/dsh.d.ts +5 -0
  24. package/backend/dist/harness/adapters/dsh.js +6 -0
  25. package/backend/dist/harness/adapters/gemini-cli.d.ts +2 -0
  26. package/backend/dist/harness/adapters/gemini-cli.js +7 -0
  27. package/backend/dist/harness/adapters/github-copilot.d.ts +5 -0
  28. package/backend/dist/harness/adapters/github-copilot.js +10 -0
  29. package/backend/dist/harness/adapters/index.d.ts +44 -0
  30. package/backend/dist/harness/adapters/index.js +99 -0
  31. package/backend/dist/harness/adapters/opencode.d.ts +2 -0
  32. package/backend/dist/harness/adapters/opencode.js +55 -0
  33. package/backend/dist/harness/adapters/pi.d.ts +1 -0
  34. package/backend/dist/harness/adapters/pi.js +22 -0
  35. package/backend/dist/harness/adapters/skills-paths.d.ts +15 -0
  36. package/backend/dist/harness/adapters/skills-paths.js +17 -0
  37. package/backend/dist/harness/adapters/types.d.ts +174 -0
  38. package/backend/dist/harness/adapters/types.js +12 -0
  39. package/backend/dist/harness/adapters/universal.d.ts +6 -0
  40. package/backend/dist/harness/adapters/universal.js +10 -0
  41. package/backend/dist/harness/adapters/windsurf.d.ts +2 -0
  42. package/backend/dist/harness/adapters/windsurf.js +10 -0
  43. package/backend/dist/harness/adapters/zed.d.ts +2 -0
  44. package/backend/dist/harness/adapters/zed.js +6 -0
  45. package/backend/dist/harness/awesome-opencode.d.ts +40 -0
  46. package/backend/dist/harness/awesome-opencode.js +75 -0
  47. package/backend/dist/harness/browse.d.ts +202 -0
  48. package/backend/dist/harness/browse.js +1214 -0
  49. package/backend/dist/harness/catalog-npm.d.ts +59 -0
  50. package/backend/dist/harness/catalog-npm.js +145 -0
  51. package/backend/dist/harness/clawhub.d.ts +212 -0
  52. package/backend/dist/harness/clawhub.js +426 -0
  53. package/backend/dist/harness/config-file.d.ts +29 -0
  54. package/backend/dist/harness/config-file.js +35 -0
  55. package/backend/dist/harness/detail.d.ts +74 -0
  56. package/backend/dist/harness/detail.js +330 -0
  57. package/backend/dist/harness/discover.d.ts +118 -0
  58. package/backend/dist/harness/discover.js +507 -0
  59. package/backend/dist/harness/drift.d.ts +21 -0
  60. package/backend/dist/harness/drift.js +25 -0
  61. package/backend/dist/harness/hash.d.ts +10 -0
  62. package/backend/dist/harness/hash.js +63 -0
  63. package/backend/dist/harness/hosts.d.ts +18 -0
  64. package/backend/dist/harness/hosts.js +15 -0
  65. package/backend/dist/harness/install.d.ts +88 -0
  66. package/backend/dist/harness/install.js +301 -0
  67. package/backend/dist/harness/inventory.d.ts +10 -0
  68. package/backend/dist/harness/inventory.js +198 -0
  69. package/backend/dist/harness/ledger.d.ts +39 -0
  70. package/backend/dist/harness/ledger.js +83 -0
  71. package/backend/dist/harness/maintenance.d.ts +115 -0
  72. package/backend/dist/harness/maintenance.js +603 -0
  73. package/backend/dist/harness/manifest.d.ts +31 -0
  74. package/backend/dist/harness/manifest.js +234 -0
  75. package/backend/dist/harness/net.d.ts +86 -0
  76. package/backend/dist/harness/net.js +113 -0
  77. package/backend/dist/harness/opencode-cafe.d.ts +40 -0
  78. package/backend/dist/harness/opencode-cafe.js +85 -0
  79. package/backend/dist/harness/opencode-ecosystem.d.ts +34 -0
  80. package/backend/dist/harness/opencode-ecosystem.js +246 -0
  81. package/backend/dist/harness/pi-dev.d.ts +81 -0
  82. package/backend/dist/harness/pi-dev.js +187 -0
  83. package/backend/dist/harness/probe.d.ts +33 -0
  84. package/backend/dist/harness/probe.js +85 -0
  85. package/backend/dist/harness/registry.d.ts +2 -0
  86. package/backend/dist/harness/registry.js +26 -0
  87. package/backend/dist/harness/scopes.d.ts +21 -0
  88. package/backend/dist/harness/scopes.js +22 -0
  89. package/backend/dist/harness/skill-md.d.ts +18 -0
  90. package/backend/dist/harness/skill-md.js +71 -0
  91. package/backend/dist/harness/skills-sh.d.ts +109 -0
  92. package/backend/dist/harness/skills-sh.js +178 -0
  93. package/backend/dist/harness/smithery.d.ts +64 -0
  94. package/backend/dist/harness/smithery.js +146 -0
  95. package/backend/dist/harness/sources/awesome-opencode.d.ts +11 -0
  96. package/backend/dist/harness/sources/awesome-opencode.js +39 -0
  97. package/backend/dist/harness/sources/clawhub.d.ts +2 -0
  98. package/backend/dist/harness/sources/clawhub.js +83 -0
  99. package/backend/dist/harness/sources/github.d.ts +9 -0
  100. package/backend/dist/harness/sources/github.js +202 -0
  101. package/backend/dist/harness/sources/mcp-official.d.ts +2 -0
  102. package/backend/dist/harness/sources/mcp-official.js +110 -0
  103. package/backend/dist/harness/sources/npm.d.ts +2 -0
  104. package/backend/dist/harness/sources/npm.js +152 -0
  105. package/backend/dist/harness/sources/opencode-cafe.d.ts +11 -0
  106. package/backend/dist/harness/sources/opencode-cafe.js +41 -0
  107. package/backend/dist/harness/sources/smithery.d.ts +2 -0
  108. package/backend/dist/harness/sources/smithery.js +81 -0
  109. package/backend/dist/harness/spi.d.ts +98 -0
  110. package/backend/dist/harness/spi.js +8 -0
  111. package/backend/dist/harness/stars.d.ts +70 -0
  112. package/backend/dist/harness/stars.js +202 -0
  113. package/backend/dist/harness/translation.d.ts +142 -0
  114. package/backend/dist/harness/translation.js +567 -0
  115. package/backend/dist/harness/tree.d.ts +13 -0
  116. package/backend/dist/harness/tree.js +19 -0
  117. package/backend/dist/harness/types.d.ts +286 -0
  118. package/backend/dist/harness/types.js +8 -0
  119. package/backend/dist/harness/writers/extension.d.ts +116 -0
  120. package/backend/dist/harness/writers/extension.js +219 -0
  121. package/backend/dist/harness/writers/mcp.d.ts +72 -0
  122. package/backend/dist/harness/writers/mcp.js +195 -0
  123. package/backend/dist/harness/writers/skill.d.ts +60 -0
  124. package/backend/dist/harness/writers/skill.js +146 -0
  125. package/backend/dist/opencode/agents.d.ts +5 -0
  126. package/backend/dist/opencode/agents.js +10 -1
  127. package/backend/dist/opencode/catalog/cache.js +2 -1
  128. package/backend/dist/opencode/catalog/logos.js +2 -1
  129. package/backend/dist/opencode/catalog/ocr-store.js +2 -1
  130. package/backend/dist/opencode/catalog/overrides-store.js +2 -1
  131. package/backend/dist/opencode/credentials/factory.js +10 -27
  132. package/backend/dist/opencode/credentials/ocr-store.js +2 -1
  133. package/backend/dist/opencode/provider-defs.js +2 -1
  134. package/backend/dist/opencode/user-config.js +8 -16
  135. package/backend/dist/providers/registry.d.ts +15 -4
  136. package/backend/dist/providers/registry.js +29 -5
  137. package/backend/dist/providers/virtual-meta.d.ts +13 -0
  138. package/backend/dist/providers/virtual-meta.js +18 -0
  139. package/backend/dist/quota/store.js +2 -1
  140. package/backend/dist/resilience/breaker-state.js +2 -1
  141. package/backend/dist/resilience/credential-state.js +2 -1
  142. package/backend/dist/routes/console.js +137 -15
  143. package/backend/dist/routes/harness.d.ts +2 -0
  144. package/backend/dist/routes/harness.js +622 -0
  145. package/backend/dist/server.js +4 -0
  146. package/backend/dist/session/session-manager.js +2 -1
  147. package/backend/dist/surfaces/systemone-probe.d.ts +25 -0
  148. package/backend/dist/surfaces/systemone-probe.js +74 -0
  149. package/backend/dist/utils/atomic-write.d.ts +12 -0
  150. package/backend/dist/utils/atomic-write.js +29 -0
  151. package/bin/ocr.js +2 -2
  152. package/frontend/dist/assets/{index-DEo2iAT7.css → index-1o7qI-KJ.css} +1 -1
  153. package/frontend/dist/assets/index-DvXKvNxl.js +962 -0
  154. package/frontend/dist/index.html +2 -2
  155. package/package.json +87 -87
  156. package/backend/dist/budget/budget-manager.d.ts +0 -25
  157. package/backend/dist/budget/budget-manager.js +0 -54
  158. package/backend/dist/config/governance-limits.d.ts +0 -68
  159. package/backend/dist/config/governance-limits.js +0 -261
  160. package/backend/dist/flywheel/collector.d.ts +0 -74
  161. package/backend/dist/flywheel/collector.js +0 -235
  162. package/backend/dist/flywheel/dataset.d.ts +0 -130
  163. package/backend/dist/flywheel/dataset.js +0 -638
  164. package/backend/dist/flywheel/decision-capture.d.ts +0 -68
  165. package/backend/dist/flywheel/decision-capture.js +0 -85
  166. package/backend/dist/flywheel/prune.d.ts +0 -133
  167. package/backend/dist/flywheel/prune.js +0 -495
  168. package/backend/dist/flywheel/schema.d.ts +0 -108
  169. package/backend/dist/flywheel/schema.js +0 -117
  170. package/backend/dist/flywheel/trainer.d.ts +0 -84
  171. package/backend/dist/flywheel/trainer.js +0 -198
  172. package/backend/dist/opencode/catalog/custom-store.d.ts +0 -50
  173. package/backend/dist/opencode/catalog/custom-store.js +0 -144
  174. package/backend/dist/opencode/credentials/push.d.ts +0 -38
  175. package/backend/dist/opencode/credentials/push.js +0 -116
  176. package/backend/dist/opencode/credentials/reconcile.d.ts +0 -49
  177. package/backend/dist/opencode/credentials/reconcile.js +0 -216
  178. package/backend/dist/opencode/sync.d.ts +0 -29
  179. package/backend/dist/opencode/sync.js +0 -186
  180. package/backend/dist/pipeline/account-selection.d.ts +0 -101
  181. package/backend/dist/pipeline/account-selection.js +0 -112
  182. package/backend/dist/providers/systemone.d.ts +0 -29
  183. package/backend/dist/providers/systemone.js +0 -170
  184. package/backend/dist/ratelimit/duration.d.ts +0 -24
  185. package/backend/dist/ratelimit/duration.js +0 -43
  186. package/backend/dist/ratelimit/governance-runtime.d.ts +0 -121
  187. package/backend/dist/ratelimit/governance-runtime.js +0 -183
  188. package/backend/dist/ratelimit/index.d.ts +0 -4
  189. package/backend/dist/ratelimit/index.js +0 -4
  190. package/backend/dist/ratelimit/limiter.d.ts +0 -157
  191. package/backend/dist/ratelimit/limiter.js +0 -244
  192. package/backend/dist/ratelimit/sliding-window-counter.d.ts +0 -63
  193. package/backend/dist/ratelimit/sliding-window-counter.js +0 -103
  194. package/backend/dist/ratelimit/subject.d.ts +0 -26
  195. package/backend/dist/ratelimit/subject.js +0 -28
  196. package/backend/dist/resilience/account-state.d.ts +0 -84
  197. package/backend/dist/resilience/account-state.js +0 -228
  198. package/backend/dist/router/layer1-classifier.d.ts +0 -111
  199. package/backend/dist/router/layer1-classifier.js +0 -467
  200. package/backend/dist/router/layer2-judge.d.ts +0 -111
  201. package/backend/dist/router/layer2-judge.js +0 -373
  202. package/backend/dist/router/retry-escalation.d.ts +0 -89
  203. package/backend/dist/router/retry-escalation.js +0 -99
  204. package/backend/dist/routes/flywheel.d.ts +0 -3
  205. package/backend/dist/routes/flywheel.js +0 -268
  206. package/backend/dist/routes/systemone.d.ts +0 -3
  207. package/backend/dist/routes/systemone.js +0 -90
  208. package/backend/dist/surfaces/governance-envelope.d.ts +0 -34
  209. package/backend/dist/surfaces/governance-envelope.js +0 -47
  210. package/backend/dist/utils/token-estimator.d.ts +0 -7
  211. package/backend/dist/utils/token-estimator.js +0 -20
  212. package/frontend/dist/assets/index-nwgWkmU1.js +0 -840
@@ -1,103 +0,0 @@
1
- /**
2
- * SlidingWindowCounter — fixed-to-sliding window counter over ephemeral
3
- * in-memory buckets (design §3 engine primitive, §4 state policy: never
4
- * persisted, minute/hour windows start empty at boot).
5
- *
6
- * Structure: the window is divided into `bucketCount` equal buckets; each
7
- * stored bucket is one absolute time slot whose events count toward the
8
- * sliding total. The last `bucketCount` buckets span exactly windowMs, so a
9
- * bucket ages out at the deterministic structural time
10
- * `bucketStart + windowMs` (= its slot index * width + windowMs).
11
- *
12
- * window: |--- b0 ---|--- b1 ---| ... |--- bB-1 ---| (sum = live count)
13
- * slot b ages out when floor(now / width) >= b + bucketCount
14
- *
15
- * Approximation ceiling (marked per cp-marked): counts are bucket-granular —
16
- * an event ages out no earlier than (itsSlot)*width + windowMs and no later
17
- * than one bucket-width after its true arrival + windowMs. Upgrade path for
18
- * exactness would be per-event timestamps (O(events) memory) — not worth it
19
- * for a shaping layer. Config-scale windows (whole seconds with default
20
- * bucketCount=10) divide exactly, so bucket edges land on integer ms.
21
- */
22
- const DEFAULT_BUCKET_COUNT = 10;
23
- export class SlidingWindowCounter {
24
- windowMs;
25
- bucketCount;
26
- bucketWidthMs;
27
- nowMs;
28
- /** absolute slot index -> count accumulated in that slot */
29
- buckets = new Map();
30
- constructor(windowMs, opts) {
31
- if (!Number.isFinite(windowMs) || windowMs <= 0) {
32
- throw new Error(`SlidingWindowCounter: windowMs must be a positive finite number, got ${windowMs}`);
33
- }
34
- this.windowMs = windowMs;
35
- this.bucketCount = Math.max(1, Math.min(opts?.bucketCount ?? DEFAULT_BUCKET_COUNT, windowMs));
36
- this.bucketWidthMs = windowMs / this.bucketCount;
37
- this.nowMs = opts?.nowMs ?? Date.now; // injected once; hot paths never touch Date.now directly
38
- }
39
- /** Add `n` events to the current slot. Atomic within one JS turn (single-threaded engine). */
40
- increment(n = 1) {
41
- if (!Number.isFinite(n) || n <= 0) {
42
- throw new Error(`SlidingWindowCounter.increment: n must be a positive finite number, got ${n}`);
43
- }
44
- const slot = this.slot(this.nowMs());
45
- this.buckets.set(slot, (this.buckets.get(slot) ?? 0) + n);
46
- }
47
- /**
48
- * Count so far plus when the oldest live count ages out (see CounterCheck).
49
- * `now` is caller-captured (Limiter.evaluate reads the clock exactly ONCE
50
- * per verdict): reading it here too would let a mid-evaluation tick make a
51
- * rule report `openAt > evaluate's now` and fabricate a denial. Only the
52
- * write side (increment) reads the injected clock.
53
- */
54
- check(now) {
55
- const { count, oldestLive } = this.live(now);
56
- return { count, nextOpenAt: count === 0 ? Number.POSITIVE_INFINITY : this.expiry(oldestLive) };
57
- }
58
- /**
59
- * Earliest structural time the count can drop strictly below `limit`,
60
- * assuming no further increments. Returns the caller's `now` when already
61
- * below — never a fresh clock read, so the under-limit arm cannot invent
62
- * `openAt > now` under a ticking clock. This is the per-rule `nextOpenAt`
63
- * the verdict layer reduces over (design §3a: binding rule = latest,
64
- * retryAfterMs = max).
65
- */
66
- openAt(limit, now) {
67
- const { count, oldestLive, newest } = this.live(now);
68
- if (count < limit)
69
- return now;
70
- // Age out oldest -> newest until the remaining count is under the limit.
71
- let dropped = 0;
72
- for (let slot = oldestLive; slot <= newest; slot++) {
73
- dropped += this.buckets.get(slot) ?? 0;
74
- if (dropped > count - limit)
75
- return this.expiry(slot);
76
- }
77
- return this.expiry(newest); // only reachable for limit < 1 (callers validate limits); safety floor
78
- }
79
- slot(t) {
80
- return Math.floor(t / this.bucketWidthMs);
81
- }
82
- /** Structural time slot `b` ages out. Always > now for any retained slot (oldest >= newest-B+1). */
83
- expiry(b) {
84
- return b * this.bucketWidthMs + this.windowMs;
85
- }
86
- /** Prunes stale buckets as a side effect — every read entry point goes through here, with the caller's captured clock. */
87
- live(now) {
88
- const newest = this.slot(now);
89
- const oldestRetained = newest - this.bucketCount + 1;
90
- let count = 0;
91
- let oldestLive = Number.POSITIVE_INFINITY;
92
- for (const [slot, n] of this.buckets) {
93
- if (slot < oldestRetained)
94
- this.buckets.delete(slot); // age out stale buckets
95
- else {
96
- count += n;
97
- if (slot < oldestLive)
98
- oldestLive = slot;
99
- }
100
- }
101
- return { count, oldestLive, newest };
102
- }
103
- }
@@ -1,26 +0,0 @@
1
- /**
2
- * Limiter subject key — internal addressing vocabulary (design §2).
3
- *
4
- * A Subject is an opaque branded string over the wire format:
5
- * `account:<encProvider>:<encKeyHashPrefix>` — outbound governance anchor
6
- * `apikey:<encId>` — inbound contract anchor
7
- *
8
- * Every colon-joined segment is percent-encoded (`%` → `%25`, `:` → `%3A`) so
9
- * the key space is injective: without encoding, provider "a:b" + prefix "c"
10
- * and provider "a" + prefix "b:c" weld into one `account:a:b:c` — two accounts
11
- * silently sharing one budget. Encoding the escape char first keeps crafted
12
- * ids like "a%3Ab" distinct from "a:b" as well.
13
- *
14
- * Never user-facing: subjects are engine-internal (design §2) — these strings
15
- * must not surface in config output, API payloads, or operator logs (the
16
- * keyHashPrefix is display-safe only because it is a one-way prefix — the
17
- * limiter itself does not re-derive any of it).
18
- */
19
- declare const SUBJECT_BRAND: unique symbol;
20
- /** Opaque branded string — construct only via {@link accountSubject} / {@link apiKeySubject}. */
21
- export type Subject = string & {
22
- readonly [SUBJECT_BRAND]: true;
23
- };
24
- export declare function accountSubject(provider: string, keyHashPrefix: string): Subject;
25
- export declare function apiKeySubject(id: string): Subject;
26
- export {};
@@ -1,28 +0,0 @@
1
- /**
2
- * Limiter subject key — internal addressing vocabulary (design §2).
3
- *
4
- * A Subject is an opaque branded string over the wire format:
5
- * `account:<encProvider>:<encKeyHashPrefix>` — outbound governance anchor
6
- * `apikey:<encId>` — inbound contract anchor
7
- *
8
- * Every colon-joined segment is percent-encoded (`%` → `%25`, `:` → `%3A`) so
9
- * the key space is injective: without encoding, provider "a:b" + prefix "c"
10
- * and provider "a" + prefix "b:c" weld into one `account:a:b:c` — two accounts
11
- * silently sharing one budget. Encoding the escape char first keeps crafted
12
- * ids like "a%3Ab" distinct from "a:b" as well.
13
- *
14
- * Never user-facing: subjects are engine-internal (design §2) — these strings
15
- * must not surface in config output, API payloads, or operator logs (the
16
- * keyHashPrefix is display-safe only because it is a one-way prefix — the
17
- * limiter itself does not re-derive any of it).
18
- */
19
- /** Encode one segment: escape char first, then the join char — order is what keeps the map injective. */
20
- function encodeSegment(segment) {
21
- return segment.replace(/%/g, '%25').replace(/:/g, '%3A');
22
- }
23
- export function accountSubject(provider, keyHashPrefix) {
24
- return `account:${encodeSegment(provider)}:${encodeSegment(keyHashPrefix)}`;
25
- }
26
- export function apiKeySubject(id) {
27
- return `apikey:${encodeSegment(id)}`;
28
- }
@@ -1,84 +0,0 @@
1
- import { CredentialPaths } from '../opencode/credentials/paths.js';
2
- /**
3
- * The SUSPECT account flag store.
4
- *
5
- * SUSPECT is ADMINISTRATIVE state, not breaker state: a confirmed-bad
6
- * credential (401 after refresh attempts) is marked suspect and NEVER
7
- * auto-returns. Cooldown expiry un-trips the pair breakers; only an explicit clear
8
- * (console reconnect / Push / admin REST) lifts the flag.
9
- *
10
- * Persistence is the OCR GLOBAL state root (`<OCR_HOME|~/.opencode-router>/
11
- * suspect-accounts.json`), not per-environment — an account is an account
12
- * wherever it is used. Payload is display-safe (provider id + sha256 prefix),
13
- * so nothing sensitive sits in a file that survives restarts.
14
- */
15
- /** Stable composite id: the same key material under two providers is two flags. */
16
- export declare function suspectAccountId(providerId: string, keyHashPrefix: string): string;
17
- export interface SuspectAccount {
18
- providerId: string;
19
- keyHashPrefix: string;
20
- /** Why it was marked (diagnosis reason) — observability only. */
21
- reason: string;
22
- /** Epoch ms of the mark. */
23
- markedAt: number;
24
- }
25
- /** Operator-taken credential: listed, never served, until the operator re-enables it. */
26
- export interface DisabledAccount {
27
- providerId: string;
28
- keyHashPrefix: string;
29
- /** Operator-supplied note (quota, rotation, abuse suspicion…) — display only. */
30
- reason: string;
31
- disabledAt: number;
32
- }
33
- export interface AccountStateStoreDeps {
34
- /** Injection seam for tests — same CredentialPaths the stores use. */
35
- paths?: CredentialPaths;
36
- now?: () => number;
37
- }
38
- export declare class AccountStateStore {
39
- /** Undefined = resolve from the real environment at first touch (boot path). */
40
- private readonly paths;
41
- private readonly nowFn;
42
- private loaded;
43
- private resolvedFile;
44
- private accounts;
45
- private disabled;
46
- private preserveCorrupt;
47
- constructor(deps?: AccountStateStoreDeps);
48
- /** Where the flags live — log/diagnostic surface, never a secret. */
49
- get filePath(): string;
50
- /** Load-once; a missing or malformed file is an empty set (never fatal). */
51
- private ensureLoaded;
52
- /** Atomic write (temp + rename), best-effort 0600 — OcrStore.save precedent. */
53
- private persist;
54
- /**
55
- * Mark an account suspect. Idempotent: re-marking keeps the FIRST markedAt
56
- * (the flag's age is the audit signal) and refreshes the reason.
57
- * @returns true when this call created the flag.
58
- */
59
- mark(providerId: string, keyHashPrefix: string, reason?: string): boolean;
60
- /** Lift the flag (reconnect / Push / admin). @returns true when a flag was cleared. */
61
- clear(providerId: string, keyHashPrefix: string): boolean;
62
- /**
63
- * Take a credential out of routing. Idempotent: re-disabling keeps the FIRST
64
- * `disabledAt` (the takedown's age is the audit signal) and refreshes the note.
65
- * @returns true when this call created the flag.
66
- */
67
- disable(providerId: string, keyHashPrefix: string, reason?: string): boolean;
68
- /** Put it back in routing. Only the operator does this — no automatic path exists. */
69
- enable(providerId: string, keyHashPrefix: string): boolean;
70
- isDisabled(providerId: string, keyHashPrefix: string): boolean;
71
- getDisabled(providerId: string, keyHashPrefix: string): DisabledAccount | undefined;
72
- listDisabled(): DisabledAccount[];
73
- get(providerId: string, keyHashPrefix: string): SuspectAccount | undefined;
74
- isSuspect(providerId: string, keyHashPrefix: string): boolean;
75
- list(): SuspectAccount[];
76
- }
77
- /**
78
- * The process-wide store the boot path uses (paths resolved from the real
79
- * environment at first touch). Anything with an injected `CredentialPaths` —
80
- * every test — constructs its own `AccountStateStore` instead.
81
- */
82
- export declare function defaultAccountStateStore(): AccountStateStore;
83
- /** Test seam: drop the memoized default so the next access re-reads env. */
84
- export declare function resetAccountStateStoreForTests(): void;
@@ -1,228 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { resolveDefaultPaths, suspectAccountsFile, } from '../opencode/credentials/paths.js';
4
- /**
5
- * The SUSPECT account flag store.
6
- *
7
- * SUSPECT is ADMINISTRATIVE state, not breaker state: a confirmed-bad
8
- * credential (401 after refresh attempts) is marked suspect and NEVER
9
- * auto-returns. Cooldown expiry un-trips the pair breakers; only an explicit clear
10
- * (console reconnect / Push / admin REST) lifts the flag.
11
- *
12
- * Persistence is the OCR GLOBAL state root (`<OCR_HOME|~/.opencode-router>/
13
- * suspect-accounts.json`), not per-environment — an account is an account
14
- * wherever it is used. Payload is display-safe (provider id + sha256 prefix),
15
- * so nothing sensitive sits in a file that survives restarts.
16
- */
17
- /** Stable composite id: the same key material under two providers is two flags. */
18
- export function suspectAccountId(providerId, keyHashPrefix) {
19
- return `${providerId}::${keyHashPrefix}`;
20
- }
21
- export class AccountStateStore {
22
- /** Undefined = resolve from the real environment at first touch (boot path). */
23
- paths;
24
- nowFn;
25
- loaded = false;
26
- resolvedFile;
27
- accounts = new Map();
28
- // Operator takedowns — see SuspectFile.disabled: independent lifecycle, so an
29
- // independent map rather than a flag that `clear()` would sweep away.
30
- disabled = new Map();
31
- // A file that existed but could not be parsed is preserved on the first
32
- // write instead of being overwritten (cp-dataloss: the flags are the only
33
- // record of an account an operator may have been working on).
34
- preserveCorrupt = false;
35
- constructor(deps = {}) {
36
- this.paths = deps.paths;
37
- this.nowFn = deps.now ?? Date.now;
38
- }
39
- /** Where the flags live — log/diagnostic surface, never a secret. */
40
- get filePath() {
41
- if (!this.resolvedFile)
42
- this.resolvedFile = suspectAccountsFile(this.paths ?? resolveDefaultPaths());
43
- return this.resolvedFile;
44
- }
45
- /** Load-once; a missing or malformed file is an empty set (never fatal). */
46
- ensureLoaded() {
47
- if (this.loaded)
48
- return;
49
- this.loaded = true;
50
- let raw;
51
- try {
52
- raw = fs.readFileSync(this.filePath, 'utf8');
53
- }
54
- catch {
55
- return; // absent/unreadable -> no suspects
56
- }
57
- let parsed;
58
- try {
59
- parsed = JSON.parse(raw);
60
- }
61
- catch (e) {
62
- // Loud, not silent: a half-written file must not read as "no suspects".
63
- this.preserveCorrupt = true;
64
- console.warn(`[resilience] ${this.filePath} is unparseable, starting empty: ${e instanceof Error ? e.message : String(e)}`);
65
- return;
66
- }
67
- const file = parsed;
68
- if (file.version !== 1 || !file.accounts || typeof file.accounts !== 'object') {
69
- this.preserveCorrupt = true;
70
- console.warn(`[resilience] ${this.filePath} has an unexpected shape, starting empty`);
71
- return;
72
- }
73
- for (const [id, entry] of Object.entries(file.accounts)) {
74
- const a = entry;
75
- if (!a || typeof a.providerId !== 'string' || typeof a.keyHashPrefix !== 'string')
76
- continue;
77
- this.accounts.set(id, {
78
- providerId: a.providerId,
79
- keyHashPrefix: a.keyHashPrefix,
80
- reason: typeof a.reason === 'string' ? a.reason : '',
81
- markedAt: typeof a.markedAt === 'number' ? a.markedAt : 0,
82
- });
83
- }
84
- // Optional in v1 files (both directions): absent = nothing takedown.
85
- if (file.disabled && typeof file.disabled === 'object') {
86
- for (const [id, entry] of Object.entries(file.disabled)) {
87
- const d = entry;
88
- if (!d || typeof d.providerId !== 'string' || typeof d.keyHashPrefix !== 'string')
89
- continue;
90
- this.disabled.set(id, {
91
- providerId: d.providerId,
92
- keyHashPrefix: d.keyHashPrefix,
93
- reason: typeof d.reason === 'string' ? d.reason : '',
94
- disabledAt: typeof d.disabledAt === 'number' ? d.disabledAt : 0,
95
- });
96
- }
97
- }
98
- }
99
- /** Atomic write (temp + rename), best-effort 0600 — OcrStore.save precedent. */
100
- persist() {
101
- if (this.preserveCorrupt) {
102
- this.preserveCorrupt = false;
103
- try {
104
- fs.renameSync(this.filePath, `${this.filePath}.corrupt.${this.nowFn()}`);
105
- }
106
- catch {
107
- // best effort — a rename race must not block the write of live flags
108
- }
109
- }
110
- const accounts = {};
111
- for (const [id, entry] of this.accounts)
112
- accounts[id] = entry;
113
- const disabled = {};
114
- for (const [id, entry] of this.disabled)
115
- disabled[id] = entry;
116
- // Written only when non-empty so a reader from before this feature keeps
117
- // parsing the file exactly as it did.
118
- const content = `${JSON.stringify({ version: 1, accounts, ...(this.disabled.size > 0 ? { disabled } : {}) }, null, 2)}\n`;
119
- fs.mkdirSync(path.dirname(this.filePath), { recursive: true });
120
- const tmpPath = `${this.filePath}.tmp.${process.pid}.${Date.now()}`;
121
- fs.writeFileSync(tmpPath, content, { encoding: 'utf8', mode: 0o600 });
122
- try {
123
- fs.chmodSync(tmpPath, 0o600);
124
- }
125
- catch {
126
- // best effort — Windows chmod semantics differ
127
- }
128
- fs.renameSync(tmpPath, this.filePath);
129
- }
130
- /**
131
- * Mark an account suspect. Idempotent: re-marking keeps the FIRST markedAt
132
- * (the flag's age is the audit signal) and refreshes the reason.
133
- * @returns true when this call created the flag.
134
- */
135
- mark(providerId, keyHashPrefix, reason = '') {
136
- this.ensureLoaded();
137
- const id = suspectAccountId(providerId, keyHashPrefix);
138
- const existing = this.accounts.get(id);
139
- if (existing) {
140
- if (existing.reason === reason)
141
- return false; // exact re-mark: no write churn
142
- existing.reason = reason;
143
- this.persist();
144
- return false;
145
- }
146
- this.accounts.set(id, { providerId, keyHashPrefix, reason, markedAt: this.nowFn() });
147
- this.persist();
148
- return true;
149
- }
150
- /** Lift the flag (reconnect / Push / admin). @returns true when a flag was cleared. */
151
- clear(providerId, keyHashPrefix) {
152
- this.ensureLoaded();
153
- if (!this.accounts.delete(suspectAccountId(providerId, keyHashPrefix)))
154
- return false;
155
- this.persist();
156
- return true;
157
- }
158
- // -- Operator DISABLED credentials (separate lifecycle: reconnect never lifts it) --
159
- /**
160
- * Take a credential out of routing. Idempotent: re-disabling keeps the FIRST
161
- * `disabledAt` (the takedown's age is the audit signal) and refreshes the note.
162
- * @returns true when this call created the flag.
163
- */
164
- disable(providerId, keyHashPrefix, reason = '') {
165
- this.ensureLoaded();
166
- const id = suspectAccountId(providerId, keyHashPrefix);
167
- const existing = this.disabled.get(id);
168
- if (existing) {
169
- if (existing.reason === reason)
170
- return false; // exact re-disable: no write churn
171
- existing.reason = reason;
172
- this.persist();
173
- return false;
174
- }
175
- this.disabled.set(id, { providerId, keyHashPrefix, reason, disabledAt: this.nowFn() });
176
- this.persist();
177
- return true;
178
- }
179
- /** Put it back in routing. Only the operator does this — no automatic path exists. */
180
- enable(providerId, keyHashPrefix) {
181
- this.ensureLoaded();
182
- if (!this.disabled.delete(suspectAccountId(providerId, keyHashPrefix)))
183
- return false;
184
- this.persist();
185
- return true;
186
- }
187
- isDisabled(providerId, keyHashPrefix) {
188
- this.ensureLoaded();
189
- return this.disabled.has(suspectAccountId(providerId, keyHashPrefix));
190
- }
191
- getDisabled(providerId, keyHashPrefix) {
192
- this.ensureLoaded();
193
- return this.disabled.get(suspectAccountId(providerId, keyHashPrefix));
194
- }
195
- listDisabled() {
196
- this.ensureLoaded();
197
- return Array.from(this.disabled.values()).sort((a, b) => a.disabledAt - b.disabledAt);
198
- }
199
- get(providerId, keyHashPrefix) {
200
- this.ensureLoaded();
201
- return this.accounts.get(suspectAccountId(providerId, keyHashPrefix));
202
- }
203
- isSuspect(providerId, keyHashPrefix) {
204
- return this.get(providerId, keyHashPrefix) !== undefined;
205
- }
206
- list() {
207
- this.ensureLoaded();
208
- return Array.from(this.accounts.values()).sort((a, b) => a.markedAt - b.markedAt);
209
- }
210
- }
211
- // ---------------------------------------------------------------------------
212
- // Process-wide default (the boot path uses it; tests inject their own store).
213
- // ---------------------------------------------------------------------------
214
- let defaultStore = null;
215
- /**
216
- * The process-wide store the boot path uses (paths resolved from the real
217
- * environment at first touch). Anything with an injected `CredentialPaths` —
218
- * every test — constructs its own `AccountStateStore` instead.
219
- */
220
- export function defaultAccountStateStore() {
221
- if (!defaultStore)
222
- defaultStore = new AccountStateStore();
223
- return defaultStore;
224
- }
225
- /** Test seam: drop the memoized default so the next access re-reads env. */
226
- export function resetAccountStateStoreForTests() {
227
- defaultStore = null;
228
- }
@@ -1,111 +0,0 @@
1
- import { ChatCompletionRequest } from '../types/openai.js';
2
- import { TierLevel, ReasonParams } from '../types/router.js';
3
- import { Layer1ClassifierConfig } from '../config/types.js';
4
- export interface Layer1Prediction {
5
- isConfident: boolean;
6
- targetTier: TierLevel;
7
- confidence: number;
8
- needsSchemaValidation: boolean;
9
- probabilities: {
10
- lite: number;
11
- plus: number;
12
- pro: number;
13
- ultra: number;
14
- };
15
- reason: string;
16
- reasonCode: string;
17
- reasonParams?: ReasonParams;
18
- isBaseModel?: boolean;
19
- }
20
- export interface Layer1ModelWeights {
21
- version: string;
22
- modelType: 'linear_softmax_classifier' | 'onnx';
23
- description: string;
24
- isBaseModel: boolean;
25
- sampleCount: number;
26
- lastTrainedAt: string | null;
27
- featureDimensions: number;
28
- featureNames: string[];
29
- classes: TierLevel[];
30
- weights: number[][];
31
- biases: number[];
32
- }
33
- export interface ExtractedFeatures {
34
- vector: number[];
35
- featureNames: string[];
36
- metrics: {
37
- tokenCount: number;
38
- turnCount: number;
39
- hasCode: boolean;
40
- symbolEntropy: number;
41
- syntaxDensity: number;
42
- hasToolsOrSchema: boolean;
43
- };
44
- }
45
- /**
46
- * Standard Empty Local Model Base (Untrained Base Scaffold)
47
- * 8 Language-Agnostic Structural & Statistical Features
48
- * Weights initialized to 0.0 -> Uniform probability 0.25 -> Guaranteed low confidence -> Cascades to Layer 2
49
- */
50
- export declare const DEFAULT_BASE_MODEL: Layer1ModelWeights;
51
- /**
52
- * Layer 1: CPU Micro-Tensor Classifier Engine
53
- * 100% Language-Agnostic, Zero Hardcoding, i18n-Compliant.
54
- *
55
- * Auto-initializes an empty base model scaffold if no model file exists on disk.
56
- * When untrained (base model), forward pass confidence is ~0.333 (< threshold 0.85),
57
- * mathematically guaranteeing a smooth and definitive cascade to Layer 2 (Judge / OpenCode).
58
- * Once trained via the Data Flywheel, the same base model achieves high confidence locally on CPU!
59
- */
60
- export declare class Layer1Classifier {
61
- private static loadedModel;
62
- private static modelFilePath;
63
- private static onnxRuntime;
64
- private static onnxSession;
65
- private static initialized;
66
- /**
67
- * Initialize Layer 1 model.
68
- * If model file does NOT exist, automatically scaffolds the base model!
69
- */
70
- static init(config?: Layer1ClassifierConfig): Promise<void>;
71
- static isModelLoaded(): boolean;
72
- static isBaseModel(): boolean;
73
- static resetToBaseModel(): void;
74
- static getModelStatus(): string;
75
- static getLoadedModel(): Layer1ModelWeights;
76
- /**
77
- * Extract 100% language-agnostic numerical & statistical features.
78
- * Completely avoids any language keyword dictionaries, regex word matching, or length biases.
79
- */
80
- static extractFeatures(request: ChatCompletionRequest): ExtractedFeatures;
81
- /**
82
- * Predict tier using Layer 1 model.
83
- * If untrained base model, outputs ~0.33 probability (< threshold), mathematically guaranteeing
84
- * isConfident=false so it cleanly cascades to Layer 2.
85
- */
86
- static predict(request: ChatCompletionRequest, config?: Layer1ClassifierConfig): Layer1Prediction;
87
- /**
88
- * Save current model weights to disk
89
- */
90
- static saveModel(weights: Layer1ModelWeights, targetPath?: string): void;
91
- /**
92
- * Reload model weights from disk
93
- */
94
- static reload(targetPath?: string): void;
95
- /**
96
- * Train the local base model in-place using accumulated dataset.
97
- * Uses Multiclass Logistic Regression (Softmax Cross-Entropy with L2 Regularization).
98
- */
99
- static train(samples: Array<{
100
- features: number[];
101
- targetTier: TierLevel;
102
- }>, options?: {
103
- epochs?: number;
104
- lr?: number;
105
- l2?: number;
106
- }): {
107
- finalLoss: number;
108
- accuracy: number;
109
- trainedSamples: number;
110
- };
111
- }