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,101 +0,0 @@
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;
@@ -1,112 +0,0 @@
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
- }
@@ -1,29 +0,0 @@
1
- import { ModelRegistration, ProviderConfig } from '../config/types.js';
2
- import { SystemoneRequest, SystemoneResponse } from '../protocols/systemone/types.js';
3
- import type { UpstreamEventContext } from './base.js';
4
- /**
5
- * Native System One upstream client (TypeSafe Jev / Alibaba Bailian
6
- * decision-model-preview). Mirrors the chat provider classes' transport
7
- * discipline — proxy policy, provider timeout, UpstreamError taxonomy,
8
- * http-exchange event emission — but speaks the decision wire instead of
9
- * chat/completions.
10
- *
11
- * NOT part of the LLMProvider pool: native System One upstreams are called
12
- * directly by the decision surface and can never be dispatched by chat
13
- * routing.
14
- */
15
- export declare class SystemoneProvider {
16
- name: string;
17
- private config;
18
- constructor(config: ProviderConfig);
19
- createDecision(request: SystemoneRequest, model: ModelRegistration, signal?: AbortSignal,
20
- /**
21
- * Upstream capture context — passed by the Layer 2 judge plumbing
22
- * (purpose 'l2-judge') AND by the /v1/systemone surface pipeline itself
23
- * (no purpose tag; the surface's own turn makes the leg unambiguous),
24
- * each behind their config gates. Every Once helper no-ops on
25
- * undefined, so a gate-off caller stays byte-identical (its client leg
26
- * is captured separately by the transport terminal finalize).
27
- */
28
- upstreamEventContext?: UpstreamEventContext): Promise<SystemoneResponse>;
29
- }
@@ -1,170 +0,0 @@
1
- import { UpstreamError } from '../resilience/error-classifier.js';
2
- import { proxiedFetch, resolveProxyUrl } from '../utils/proxy.js';
3
- import { emitUpstreamFailureOnce, emitUpstreamRequestOnce, emitUpstreamResponseOnce, withUpstreamFailureGuard, } from '../observability/upstream-events.js';
4
- /**
5
- * Native System One upstream client (TypeSafe Jev / Alibaba Bailian
6
- * decision-model-preview). Mirrors the chat provider classes' transport
7
- * discipline — proxy policy, provider timeout, UpstreamError taxonomy,
8
- * http-exchange event emission — but speaks the decision wire instead of
9
- * chat/completions.
10
- *
11
- * NOT part of the LLMProvider pool: native System One upstreams are called
12
- * directly by the decision surface and can never be dispatched by chat
13
- * routing.
14
- */
15
- export class SystemoneProvider {
16
- name;
17
- config;
18
- constructor(config) {
19
- this.name = config.name;
20
- this.config = config;
21
- }
22
- async createDecision(request, model, signal,
23
- /**
24
- * Upstream capture context — passed by the Layer 2 judge plumbing
25
- * (purpose 'l2-judge') AND by the /v1/systemone surface pipeline itself
26
- * (no purpose tag; the surface's own turn makes the leg unambiguous),
27
- * each behind their config gates. Every Once helper no-ops on
28
- * undefined, so a gate-off caller stays byte-identical (its client leg
29
- * is captured separately by the transport terminal finalize).
30
- */
31
- upstreamEventContext) {
32
- const url = `${this.config.baseUrl.replace(/\/+$/, '')}/systemone`;
33
- const headers = {
34
- 'Content-Type': 'application/json',
35
- ...(this.config.apiKey ? { Authorization: `Bearer ${this.config.apiKey}` } : {}),
36
- ...this.config.headers,
37
- };
38
- // Forward the whole request body (protocol extensions survive) with the
39
- // model field swapped to the upstream model id.
40
- const payload = { ...request, model: model.upstreamModel };
41
- const bodyStr = JSON.stringify(payload);
42
- // Event-stream emit BEFORE the fetch fires — independent of the response.
43
- // Pairs with the upstream-response event below via `spanId`.
44
- const spanId = emitUpstreamRequestOnce(upstreamEventContext, {
45
- url,
46
- method: 'POST',
47
- requestHeaders: headers,
48
- requestBody: bodyStr,
49
- model: model.upstreamModel,
50
- proxy: resolveProxyUrl(url, { provider: this.config.name, model: model.id }),
51
- });
52
- const controller = new AbortController();
53
- const timeout = setTimeout(() => controller.abort(), this.config.timeoutMs || 30000);
54
- // Caller-side cancellation (the Layer 2 judge's own deadline) aborts the
55
- // fetch for real, so an abandoned decision stops costing the upstream.
56
- const onCallerAbort = () => controller.abort();
57
- if (signal) {
58
- if (signal.aborted)
59
- controller.abort();
60
- else
61
- signal.addEventListener('abort', onCallerAbort, { once: true });
62
- }
63
- try {
64
- // The guard emits a paired failure response event on ANY thrown error
65
- // (network / DNS / TLS / abort / timeout) so readers never see a
66
- // dangling request event. A loser-of-the-race judge call still emits
67
- // its request event — the wire call really happened; honest over tidy.
68
- const res = await withUpstreamFailureGuard(upstreamEventContext, spanId, url, 'POST', () => proxiedFetch(url, {
69
- method: 'POST',
70
- headers,
71
- body: bodyStr,
72
- signal: controller.signal,
73
- }, { provider: this.config.name, model: model.id }), model.upstreamModel);
74
- if (!res.ok) {
75
- // Body read can fail mid-stream (connection reset) — pair the request
76
- // event with a failure response before rethrowing.
77
- let errorText;
78
- try {
79
- errorText = await res.text();
80
- }
81
- catch (err) {
82
- emitUpstreamFailureOnce(upstreamEventContext, {
83
- model: model.upstreamModel,
84
- spanId,
85
- url,
86
- method: 'POST',
87
- status: res.status,
88
- statusText: res.statusText,
89
- error: `Response body read failed: ${err?.message ?? err}`,
90
- });
91
- throw err;
92
- }
93
- emitUpstreamFailureOnce(upstreamEventContext, {
94
- model: model.upstreamModel,
95
- spanId,
96
- url,
97
- method: 'POST',
98
- status: res.status,
99
- statusText: res.statusText,
100
- responseHeaders: res.headers,
101
- responseBody: errorText,
102
- error: `Upstream ${res.status}`,
103
- });
104
- throw new UpstreamError({
105
- message: `Upstream ${this.name} returned status ${res.status}: ${errorText}`,
106
- status: res.status,
107
- errorBody: errorText,
108
- provider: this.name,
109
- modelId: model.id,
110
- });
111
- }
112
- // Emit the response event the moment the body BYTES arrive — before
113
- // JSON.parse, mirroring the chat providers (the raw text is the truth).
114
- let rawBody;
115
- try {
116
- rawBody = await res.text();
117
- }
118
- catch (err) {
119
- emitUpstreamFailureOnce(upstreamEventContext, {
120
- model: model.upstreamModel,
121
- spanId,
122
- url,
123
- method: 'POST',
124
- status: res.status,
125
- statusText: res.statusText,
126
- error: `Response body read failed: ${err?.message ?? err}`,
127
- });
128
- throw err;
129
- }
130
- emitUpstreamResponseOnce(upstreamEventContext, {
131
- model: model.upstreamModel,
132
- spanId,
133
- url,
134
- method: 'POST',
135
- status: res.status,
136
- statusText: res.statusText,
137
- responseHeaders: res.headers,
138
- responseBody: rawBody,
139
- });
140
- let json;
141
- try {
142
- json = JSON.parse(rawBody);
143
- }
144
- catch {
145
- throw new UpstreamError({
146
- message: `Upstream ${this.name} returned a non-JSON body`,
147
- status: 502,
148
- errorBody: rawBody,
149
- provider: this.name,
150
- modelId: model.id,
151
- });
152
- }
153
- if (!json || typeof json !== 'object' || !json.answers || typeof json.answers !== 'object') {
154
- throw new UpstreamError({
155
- message: `Upstream ${this.name} returned a non-System-One body (missing "answers")`,
156
- status: 502,
157
- errorBody: rawBody,
158
- provider: this.name,
159
- modelId: model.id,
160
- });
161
- }
162
- return json;
163
- }
164
- finally {
165
- clearTimeout(timeout);
166
- if (signal)
167
- signal.removeEventListener('abort', onCallerAbort);
168
- }
169
- }
170
- }
@@ -1,24 +0,0 @@
1
- /**
2
- * Window duration parser — the Go/Prometheus-style vocabulary mandated by
3
- * design §2 (`30s / 5m / 1h / 1d`). Exported standalone so the P2 config
4
- * validator runs the exact same syntax at the trust boundary.
5
- *
6
- * Grammar (deliberately narrower than full Go ParseDuration):
7
- * ^ digits + one unit in {s, m, h, d} $ — lowercase only, integer magnitude
8
- * Rejected: fractional ("1.5s"), multi-segment ("1h30m"), unsigned ("5"),
9
- * unit-first ("d1"), unknown unit ("1x"), uppercase (Go/Prometheus are
10
- * case-sensitive: "1M" means months there — we refuse rather than reinterpret),
11
- * and zero ("0s" is not a constraint).
12
- */
13
- export declare const DAY_WINDOW_MS = 86400000;
14
- /** Window string → milliseconds, or null when the string is not valid syntax. */
15
- export declare function parseWindow(s: string): number | null;
16
- /**
17
- * Day-class window predicate — the rehydrate split (design §4): >= 1d seeds
18
- * from the ledger, anything shorter starts empty. The day class is a SEEDING
19
- * bucket boundary, not calendar semantics: every window here is SLIDING
20
- * (design §2, SlidingWindowCounter is the only counter). A >1d window (e.g.
21
- * 7d) therefore gets only the trailing-24h seed — the accepted under-count
22
- * ruling is documented at Limiter.rehydrate.
23
- */
24
- export declare function isDayWindow(windowMs: number): boolean;
@@ -1,43 +0,0 @@
1
- /**
2
- * Window duration parser — the Go/Prometheus-style vocabulary mandated by
3
- * design §2 (`30s / 5m / 1h / 1d`). Exported standalone so the P2 config
4
- * validator runs the exact same syntax at the trust boundary.
5
- *
6
- * Grammar (deliberately narrower than full Go ParseDuration):
7
- * ^ digits + one unit in {s, m, h, d} $ — lowercase only, integer magnitude
8
- * Rejected: fractional ("1.5s"), multi-segment ("1h30m"), unsigned ("5"),
9
- * unit-first ("d1"), unknown unit ("1x"), uppercase (Go/Prometheus are
10
- * case-sensitive: "1M" means months there — we refuse rather than reinterpret),
11
- * and zero ("0s" is not a constraint).
12
- */
13
- export const DAY_WINDOW_MS = 86_400_000;
14
- const UNIT_MS = {
15
- s: 1_000,
16
- m: 60_000,
17
- h: 3_600_000,
18
- d: DAY_WINDOW_MS,
19
- };
20
- const WINDOW_RE = /^(\d+)([smhd])$/;
21
- /** Window string → milliseconds, or null when the string is not valid syntax. */
22
- export function parseWindow(s) {
23
- const m = WINDOW_RE.exec(s);
24
- if (!m)
25
- return null;
26
- const magnitude = Number(m[1]);
27
- const unit = m[2];
28
- const ms = magnitude * UNIT_MS[unit];
29
- if (!Number.isFinite(ms) || ms <= 0)
30
- return null; // overflowed or "0s"
31
- return ms;
32
- }
33
- /**
34
- * Day-class window predicate — the rehydrate split (design §4): >= 1d seeds
35
- * from the ledger, anything shorter starts empty. The day class is a SEEDING
36
- * bucket boundary, not calendar semantics: every window here is SLIDING
37
- * (design §2, SlidingWindowCounter is the only counter). A >1d window (e.g.
38
- * 7d) therefore gets only the trailing-24h seed — the accepted under-count
39
- * ruling is documented at Limiter.rehydrate.
40
- */
41
- export function isDayWindow(windowMs) {
42
- return windowMs >= DAY_WINDOW_MS;
43
- }
@@ -1,121 +0,0 @@
1
- /**
2
- * Governance runtime — the Limiter lifecycle owner (design §4/§5, P3b).
3
- *
4
- * Placement: this lives in the engine's own package (`ratelimit/`) because it
5
- * is the Limiter's owner — the armed-subject set, the stale-anchor list, and
6
- * the day-window rehydration all speak the subject/window vocabulary the
7
- * engine defines. `resilience/` stays limiter-free: the breaker is an
8
- * independent reactive layer and must not gain governance imports.
9
- *
10
- * The Limiter ENGINE (limiter.ts) stays config-ignorant and verdict-only;
11
- * this module is the wiring half of the split: it builds the process-singleton
12
- * Limiter, translates config → rule sets (via the P2b accessor helpers),
13
- * validates anchors against the LIVE credential pool, and rehydrates day
14
- * windows from the trace ledger. Policy for verdicts (spread-exclude,
15
- * force-through, skip-to-next) lives at the call sites (account-selection,
16
- * orchestrator dispatch), NOT here.
17
- *
18
- * Lifecycle contract:
19
- * - boot (index.ts): `initGovernanceRuntime` — apply + day-ledger rehydrate.
20
- * Unknown provider ids in `accounts:` THROW (a loud boot error naming the
21
- * offending entry — design §5: config validation is a trust boundary and
22
- * this boot cannot route what the entry anchors). Stale keyHashPrefix
23
- * anchors NEVER throw: they are exposed via `getStaleGovernanceAnchors`
24
- * (P5 console) and logged loudly naming provider + prefix — a rotated key
25
- * is an operational fact, not a broken boot.
26
- * - hot-apply on every config save (console.ts handleSaveConfig /
27
- * handleSaveRawYaml — mirrors commit 4764cea breaker-rules precedent):
28
- * `syncGovernanceRuntime` replaces every rule set (setRules → fresh
29
- * counters by P1 contract), re-validates anchors against the live pool,
30
- * and re-seeds day windows from the ledger. Unknown providers at SAVE
31
- * time are refused + logged loud instead of throwing: a running gateway
32
- * must not crash behind the operator's back; the next boot is the hard
33
- * gate. The save path's own validation (config/index.ts saveConfig →
34
- * validateGovernanceLimits) already rejects malformed trees before disk.
35
- * - day rehydration is a SLIDING 24h seed (`now - DAY_WINDOW_MS`), the same
36
- * readback the console usage view uses; minute/hour windows deliberately
37
- * start empty (design §4: shorter-window loss costs "brief under-shaping",
38
- * the breaker catches the rest).
39
- * - degeneracy (design §5): zero `accounts:` entries and zero per-key
40
- * `limits` → nothing armed, `isGovernanceArmed()` false, and the call
41
- * sites short-circuit to the exact pre-P3b paths.
42
- *
43
- * NOT exported from the ratelimit/index.ts barrel on purpose: the config
44
- * validator (config/governance-limits.ts) imports that barrel, and this module
45
- * imports the validator — a barrel re-export would weld the cycle (the engine
46
- * barrel stays the pure verdict contract).
47
- */
48
- import { Limiter } from './limiter.js';
49
- import { type GovernanceValidationIssue } from '../config/governance-limits.js';
50
- import { type TraceTracker } from '../trace/tracker.js';
51
- import type { RouterConfig } from '../config/types.js';
52
- /**
53
- * Structural view of the live pool — the boot/pool-rebuild truth source the
54
- * stale-anchor check compares against (registry.getCredentialChain is exactly
55
- * what boot-direct built from the store's resolveKeyChain; the registry
56
- * instance satisfies it, tests provide fakes).
57
- */
58
- export interface LiveAccountPool {
59
- /** The provider id exists in this boot's registry at all. */
60
- hasProvider(name: string): boolean;
61
- /** Live keyHashPrefix anchors of the provider's chain (empty = no chain). */
62
- chainKeyHashPrefixes(name: string): string[];
63
- }
64
- /** Adapter so callers hand the registry over without the engine importing it. */
65
- export declare function poolViewOfRegistry(registry: {
66
- hasProvider(name: string): boolean;
67
- getCredentialChain(name: string): readonly {
68
- keyHashPrefix: string;
69
- }[] | undefined;
70
- }): LiveAccountPool;
71
- /** One `accounts:` entry whose keyHashPrefix is not in the live chain (rotated/revoked key). */
72
- export type StaleGovernanceAnchor = {
73
- provider: string;
74
- keyHashPrefix: string;
75
- /** The config.yaml list index — the operator's addressable line. */
76
- entryIndex: number;
77
- };
78
- export type GovernanceSyncResult = {
79
- /** account + apiKey subjects armed with at least one rule. */
80
- armedSubjects: number;
81
- stale: StaleGovernanceAnchor[];
82
- /** §5-style named-line issues for providers this boot cannot route at all. */
83
- unknownProviders: GovernanceValidationIssue[];
84
- };
85
- export declare function getGovernanceLimiter(): Limiter;
86
- /** Call-site short-circuit: false ⇒ selection/dispatch skip every limiter
87
- * interaction and run the exact pre-P3b paths (degeneracy promise). */
88
- export declare function isGovernanceArmed(): boolean;
89
- /** P5 console overlay input — entries marked stale by the latest sync (never applied). */
90
- export declare function getStaleGovernanceAnchors(): readonly StaleGovernanceAnchor[];
91
- /**
92
- * Boot + hot-apply sync: replace rule sets against the live pool, then re-seed
93
- * day windows from the trace ledger (setRules wiped counters — the ledger is
94
- * the truth source for day-class windows, design §4). Await `tracker.whenReady`
95
- * FIRST: the persisted day's traces must be in the ring before readback
96
- * (the P3a boot-pattern docblock in trace/tracker.ts).
97
- */
98
- export declare function syncGovernanceRuntime(opts: {
99
- config: Pick<RouterConfig, 'accounts' | 'apiKeys'>;
100
- pool: LiveAccountPool;
101
- tracker: TraceTracker;
102
- /** Sink for the loud lines (tests capture; production console.warn). */
103
- log?: (line: string) => void;
104
- /** Label appearing in every loud line ('boot' / 'config-save'). */
105
- phase?: string;
106
- }): Promise<GovernanceSyncResult>;
107
- /**
108
- * Boot entry — `syncGovernanceRuntime` plus the loud boot error: unknown
109
- * provider ids in `accounts:` throw a GovernanceConfigError naming every
110
- * offending entry (§5/§8 validation pin). A stale keyHash anchor does NOT
111
- * throw — see module header for why the two refusal classes differ.
112
- */
113
- export declare function initGovernanceRuntime(opts: {
114
- config: RouterConfig;
115
- pool: LiveAccountPool;
116
- tracker: TraceTracker;
117
- /** Loud-line sink (tests capture; production console.warn). */
118
- log?: (line: string) => void;
119
- }): Promise<GovernanceSyncResult>;
120
- /** Test seam (precedent: resetBreakerStateStoreForTests) — fresh singleton per fixture. */
121
- export declare function resetGovernanceLimiterForTests(): void;