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,157 @@
1
+ /**
2
+ * Limiter — the shared verdict engine (design §3). One mechanism answering
3
+ * questions about a subject's window budgets; the *policy* half (what to do
4
+ * with a denial: exclude from spread, force through, 429, 402) lives in the
5
+ * call sites, never here. The engine never returns actions, never knows HTTP
6
+ * status codes, never touches config files.
7
+ *
8
+ * Combination semantics (§3a, binding):
9
+ * - Deny = ANY rule full (AND constraint set, OR denial gate).
10
+ * - limitedBy = the BINDING rule: among full rules, the one whose budget
11
+ * reopens LATEST — the true bottleneck, not the first match.
12
+ * - retryAfterMs = MAX over full rules of (nextOpenAt - now): the subject
13
+ * recovers only when every constraint is simultaneously slack.
14
+ *
15
+ * Degeneracy promise (§5): a subject with no rules allocates no state and
16
+ * every method short-circuits (peek/tryDispatch allowed, counters zero).
17
+ */
18
+ import { type Subject } from './subject.js';
19
+ /** Reason codes echo the config field names verbatim — operator maps a log reason straight back to the YAML key. */
20
+ export type Countable = 'requests' | 'tokens' | 'costUsd';
21
+ export type Verdict = {
22
+ allowed: true;
23
+ } | {
24
+ allowed: false;
25
+ limitedBy: Countable;
26
+ rule: string;
27
+ retryAfterMs: number;
28
+ };
29
+ /** One parsed limits entry = one window = one countable = one addressable constraint (§3a item 4). */
30
+ export type LimitEntryConfig = {
31
+ window: string;
32
+ requests?: number;
33
+ tokens?: number;
34
+ costUsd?: number;
35
+ };
36
+ /**
37
+ * Boot-time ledger totals (design §4: day windows rebuild from the existing
38
+ * trace/finops ledger — no fourth truth source). P3 fills `accounts` from the
39
+ * trace ledger keyed by `servedAccountPrefix`; P4 fills `apiKeys` from the
40
+ * keyId capture path (cost via finops). Day-granular totals only — shorter
41
+ * windows must not be seeded (they start empty at boot by policy). The read
42
+ * window is TRAILING 24h — rolling, never calendar-aligned (design §2: every
43
+ * window in this engine is a sliding window).
44
+ */
45
+ export type DayLedgerReadback = {
46
+ accounts: {
47
+ provider: string;
48
+ keyHashPrefix: string;
49
+ tokens?: number;
50
+ }[];
51
+ apiKeys: {
52
+ id: string;
53
+ tokens?: number;
54
+ costUsd?: number;
55
+ }[];
56
+ };
57
+ /** One rule's live usage line — the read-only observability shape (P5 overlay source). */
58
+ export type RuleStatus = {
59
+ /** "<window>/<countable>" config spelling, e.g. "6h/requests" — the addressable rule id. */
60
+ rule: string;
61
+ countable: Countable;
62
+ limit: number;
63
+ windowMs: number;
64
+ /** Count inside the sliding window at the snapshot instant. */
65
+ used: number;
66
+ /** Structural time `used` can drop below `limit` (assuming no further traffic). ABSENT while the rule has slack. */
67
+ nextOpenAtMs?: number;
68
+ };
69
+ export declare class Limiter {
70
+ private readonly nowMs;
71
+ /** Subjects without an entry have NO state at all — the degeneracy representation. */
72
+ private readonly states;
73
+ constructor(cfg?: {
74
+ nowMs?: () => number;
75
+ });
76
+ /**
77
+ * Register the rule set for a subject, replacing any prior set atomically
78
+ * (fresh counters — hot-reload keeps no history of the old shape). Empty
79
+ * list deletes the subject's state entirely: no entry -> no cap, no state.
80
+ */
81
+ setRules(subject: Subject, rules: LimitEntryConfig[]): void;
82
+ /** Non-consuming filter (spread evaluation). Bumps nothing, mutates nothing. */
83
+ peek(subject: Subject): Verdict;
84
+ /**
85
+ * Atomic check-and-count for a dispatch attempt: when allowed, EVERY
86
+ * requests-rule gains +1 within this synchronous step (no check-then-act
87
+ * gap — single-threaded engine; cascade windows all consume). Denials
88
+ * consume nothing.
89
+ */
90
+ tryDispatch(subject: Subject): Verdict;
91
+ /**
92
+ * Terminal/usage events (design §4 terminality discipline): additive to the
93
+ * token/cost windows, fired exactly once per terminal path by callers.
94
+ * No-op for subjects without rules (degeneracy).
95
+ *
96
+ * NEVER throws (§4 discipline outranks fail-fast HERE): this runs inside
97
+ * request teardown, and a throw would escape into the terminal path and lose
98
+ * the turn's real recorded usage. Junk amounts (non-finite / negative) are
99
+ * silently skipped — the engine stays log-free by design §3, so the skip is
100
+ * quiet by contract. The config plane (setRules + the P2 validator) keeps
101
+ * rejecting loudly; nothing on this path is repairable input anyway.
102
+ */
103
+ recordUsage(subject: Subject, u: {
104
+ tokens?: number;
105
+ costUsd?: number;
106
+ }): void;
107
+ /**
108
+ * Boot-time seeding from the day ledger (design §4). Only day-class
109
+ * windows (>= 1d, see isDayWindow) are seeded; minute/hour windows always
110
+ * start empty. ADDITIVE by contract — call once, after setRules, on empty
111
+ * day windows; re-calling stacks (documented boot-only misuse).
112
+ * Unknown subjects (no rules configured) are silently skipped: the ledger
113
+ * may know spend the policy chose not to cap.
114
+ *
115
+ * ROLLING-day ruling (binding): windows are SLIDING (design §2 — the
116
+ * SlidingWindowCounter is the sole counter primitive; no calendar semantics
117
+ * anywhere in the engine). The seed is the TRAILING-24h ledger total, so a
118
+ * rule whose window is LONGER than a day (e.g. 7d) receives exactly one day
119
+ * of seed. The post-boot under-count of the older tail is known and
120
+ * accepted: outbound caps are the shaping layer (the breaker is the
121
+ * backstop), and inbound budgets re-accurate within the window as live
122
+ * usage rebuilds the tail.
123
+ *
124
+ * NEVER throws on junk ledger rows (terminal/boot path — same discipline as
125
+ * recordUsage): non-finite or negative totals are skipped, not seeded.
126
+ */
127
+ rehydrate(readback: DayLedgerReadback): void;
128
+ /** Per-subject observability counters (policy bookkeeping stays in callers; counting lives here). */
129
+ counters(subject: Subject): {
130
+ admitted: number;
131
+ skippedAtCap: number;
132
+ forcedThrough: number;
133
+ };
134
+ /**
135
+ * Read-only per-rule usage snapshot for observability surfaces (design §5 —
136
+ * the P5 console overlay). Consumes no budget, bumps no counter. The clock is
137
+ * read EXACTLY ONCE (evaluate docblock discipline): `check`/`openAt` take the
138
+ * captured `now`, so a ticking clock can neither let one snapshot disagree
139
+ * with itself (rule N evaluated at a later instant than rule 1) nor fabricate
140
+ * `nextOpenAtMs` on a slack rule. Unknown/no-rules subject -> the shared
141
+ * frozen empty array: ZERO allocation, ZERO clock reads (degeneracy §5).
142
+ */
143
+ ruleStatus(subject: Subject): RuleStatus[];
144
+ /** Caller invoked this because a peek denial excluded the candidate at cap. */
145
+ recordSkippedAtCap(subject: Subject): void;
146
+ /** Caller invoked this for a bound-session/at-cap force-through (Decision 7 iron law path). */
147
+ recordForcedThrough(subject: Subject): void;
148
+ /**
149
+ * §3a reduction: any full rule denies; the fullest-latest rule names the bottleneck.
150
+ * The clock is read EXACTLY ONCE here and handed to every counter: a second
151
+ * read inside openAt() could return `now+ε > now` for an under-limit rule on
152
+ * a ticking clock and fabricate a denial (and a bogus retryAfterMs floor).
153
+ */
154
+ private evaluate;
155
+ private buildRule;
156
+ private seedSubject;
157
+ }
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Limiter — the shared verdict engine (design §3). One mechanism answering
3
+ * questions about a subject's window budgets; the *policy* half (what to do
4
+ * with a denial: exclude from spread, force through, 429, 402) lives in the
5
+ * call sites, never here. The engine never returns actions, never knows HTTP
6
+ * status codes, never touches config files.
7
+ *
8
+ * Combination semantics (§3a, binding):
9
+ * - Deny = ANY rule full (AND constraint set, OR denial gate).
10
+ * - limitedBy = the BINDING rule: among full rules, the one whose budget
11
+ * reopens LATEST — the true bottleneck, not the first match.
12
+ * - retryAfterMs = MAX over full rules of (nextOpenAt - now): the subject
13
+ * recovers only when every constraint is simultaneously slack.
14
+ *
15
+ * Degeneracy promise (§5): a subject with no rules allocates no state and
16
+ * every method short-circuits (peek/tryDispatch allowed, counters zero).
17
+ */
18
+ import { accountSubject, apiKeySubject } from './subject.js';
19
+ import { isDayWindow, parseWindow } from './duration.js';
20
+ import { SlidingWindowCounter } from './sliding-window-counter.js';
21
+ // Shared empty sentinel: zero-allocation degeneracy for unknown subjects; frozen
22
+ // so a misbehaving caller corrupts nothing and fails loud in strict mode. The
23
+ // double assertion keeps the frozen instance behind the pinned mutable-array
24
+ // signature — callers only ever READ the empty result (the type is the contract).
25
+ const NO_RULE_STATUS = Object.freeze([]);
26
+ const COUNTABLES = ['requests', 'tokens', 'costUsd'];
27
+ export class Limiter {
28
+ nowMs;
29
+ /** Subjects without an entry have NO state at all — the degeneracy representation. */
30
+ states = new Map();
31
+ constructor(cfg) {
32
+ this.nowMs = cfg?.nowMs ?? Date.now;
33
+ }
34
+ /**
35
+ * Register the rule set for a subject, replacing any prior set atomically
36
+ * (fresh counters — hot-reload keeps no history of the old shape). Empty
37
+ * list deletes the subject's state entirely: no entry -> no cap, no state.
38
+ */
39
+ setRules(subject, rules) {
40
+ if (rules.length === 0) {
41
+ this.states.delete(subject);
42
+ return;
43
+ }
44
+ const built = rules.map((entry) => this.buildRule(entry));
45
+ this.states.set(subject, { rules: built, admitted: 0, skippedAtCap: 0, forcedThrough: 0 });
46
+ }
47
+ /** Non-consuming filter (spread evaluation). Bumps nothing, mutates nothing. */
48
+ peek(subject) {
49
+ const denial = this.evaluate(subject);
50
+ return denial ? { allowed: false, ...denial } : { allowed: true };
51
+ }
52
+ /**
53
+ * Atomic check-and-count for a dispatch attempt: when allowed, EVERY
54
+ * requests-rule gains +1 within this synchronous step (no check-then-act
55
+ * gap — single-threaded engine; cascade windows all consume). Denials
56
+ * consume nothing.
57
+ */
58
+ tryDispatch(subject) {
59
+ const denial = this.evaluate(subject);
60
+ if (denial)
61
+ return { allowed: false, ...denial };
62
+ const state = this.states.get(subject);
63
+ if (state) {
64
+ for (const rule of state.rules) {
65
+ if (rule.countable === 'requests')
66
+ rule.counter.increment(1);
67
+ }
68
+ state.admitted += 1;
69
+ }
70
+ return { allowed: true };
71
+ }
72
+ /**
73
+ * Terminal/usage events (design §4 terminality discipline): additive to the
74
+ * token/cost windows, fired exactly once per terminal path by callers.
75
+ * No-op for subjects without rules (degeneracy).
76
+ *
77
+ * NEVER throws (§4 discipline outranks fail-fast HERE): this runs inside
78
+ * request teardown, and a throw would escape into the terminal path and lose
79
+ * the turn's real recorded usage. Junk amounts (non-finite / negative) are
80
+ * silently skipped — the engine stays log-free by design §3, so the skip is
81
+ * quiet by contract. The config plane (setRules + the P2 validator) keeps
82
+ * rejecting loudly; nothing on this path is repairable input anyway.
83
+ */
84
+ recordUsage(subject, u) {
85
+ const state = this.states.get(subject);
86
+ if (!state)
87
+ return;
88
+ const amounts = {
89
+ tokens: u.tokens,
90
+ costUsd: u.costUsd,
91
+ };
92
+ for (const key of ['tokens', 'costUsd']) {
93
+ const amount = amounts[key];
94
+ if (amount === undefined || amount === 0)
95
+ continue;
96
+ if (!Number.isFinite(amount) || amount < 0)
97
+ continue; // terminality skip — see docblock
98
+ for (const rule of state.rules) {
99
+ if (rule.countable === key)
100
+ rule.counter.increment(amount);
101
+ }
102
+ }
103
+ }
104
+ /**
105
+ * Boot-time seeding from the day ledger (design §4). Only day-class
106
+ * windows (>= 1d, see isDayWindow) are seeded; minute/hour windows always
107
+ * start empty. ADDITIVE by contract — call once, after setRules, on empty
108
+ * day windows; re-calling stacks (documented boot-only misuse).
109
+ * Unknown subjects (no rules configured) are silently skipped: the ledger
110
+ * may know spend the policy chose not to cap.
111
+ *
112
+ * ROLLING-day ruling (binding): windows are SLIDING (design §2 — the
113
+ * SlidingWindowCounter is the sole counter primitive; no calendar semantics
114
+ * anywhere in the engine). The seed is the TRAILING-24h ledger total, so a
115
+ * rule whose window is LONGER than a day (e.g. 7d) receives exactly one day
116
+ * of seed. The post-boot under-count of the older tail is known and
117
+ * accepted: outbound caps are the shaping layer (the breaker is the
118
+ * backstop), and inbound budgets re-accurate within the window as live
119
+ * usage rebuilds the tail.
120
+ *
121
+ * NEVER throws on junk ledger rows (terminal/boot path — same discipline as
122
+ * recordUsage): non-finite or negative totals are skipped, not seeded.
123
+ */
124
+ rehydrate(readback) {
125
+ for (const row of readback.accounts) {
126
+ this.seedSubject(accountSubject(row.provider, row.keyHashPrefix), { tokens: row.tokens });
127
+ }
128
+ for (const row of readback.apiKeys) {
129
+ this.seedSubject(apiKeySubject(row.id), { tokens: row.tokens, costUsd: row.costUsd });
130
+ }
131
+ }
132
+ /** Per-subject observability counters (policy bookkeeping stays in callers; counting lives here). */
133
+ counters(subject) {
134
+ const state = this.states.get(subject);
135
+ if (!state)
136
+ return { admitted: 0, skippedAtCap: 0, forcedThrough: 0 };
137
+ return { admitted: state.admitted, skippedAtCap: state.skippedAtCap, forcedThrough: state.forcedThrough };
138
+ }
139
+ /**
140
+ * Read-only per-rule usage snapshot for observability surfaces (design §5 —
141
+ * the P5 console overlay). Consumes no budget, bumps no counter. The clock is
142
+ * read EXACTLY ONCE (evaluate docblock discipline): `check`/`openAt` take the
143
+ * captured `now`, so a ticking clock can neither let one snapshot disagree
144
+ * with itself (rule N evaluated at a later instant than rule 1) nor fabricate
145
+ * `nextOpenAtMs` on a slack rule. Unknown/no-rules subject -> the shared
146
+ * frozen empty array: ZERO allocation, ZERO clock reads (degeneracy §5).
147
+ */
148
+ ruleStatus(subject) {
149
+ const state = this.states.get(subject);
150
+ if (!state)
151
+ return NO_RULE_STATUS;
152
+ const now = this.nowMs();
153
+ return state.rules.map((rule) => {
154
+ const opensAt = rule.counter.openAt(rule.limit, now);
155
+ return {
156
+ rule: rule.id,
157
+ countable: rule.countable,
158
+ limit: rule.limit,
159
+ windowMs: rule.windowMs,
160
+ used: rule.counter.check(now).count,
161
+ ...(opensAt > now ? { nextOpenAtMs: opensAt } : {}),
162
+ };
163
+ });
164
+ }
165
+ /** Caller invoked this because a peek denial excluded the candidate at cap. */
166
+ recordSkippedAtCap(subject) {
167
+ const state = this.states.get(subject);
168
+ if (state)
169
+ state.skippedAtCap += 1;
170
+ }
171
+ /** Caller invoked this for a bound-session/at-cap force-through (Decision 7 iron law path). */
172
+ recordForcedThrough(subject) {
173
+ const state = this.states.get(subject);
174
+ if (state)
175
+ state.forcedThrough += 1;
176
+ }
177
+ /**
178
+ * §3a reduction: any full rule denies; the fullest-latest rule names the bottleneck.
179
+ * The clock is read EXACTLY ONCE here and handed to every counter: a second
180
+ * read inside openAt() could return `now+ε > now` for an under-limit rule on
181
+ * a ticking clock and fabricate a denial (and a bogus retryAfterMs floor).
182
+ */
183
+ evaluate(subject) {
184
+ const state = this.states.get(subject);
185
+ if (!state)
186
+ return null;
187
+ const now = this.nowMs();
188
+ let binding = null;
189
+ for (const rule of state.rules) {
190
+ const opensAt = rule.counter.openAt(rule.limit, now); // === now when the rule has slack
191
+ if (opensAt > now && (!binding || opensAt > binding.opensAt)) {
192
+ binding = { rule, opensAt };
193
+ }
194
+ }
195
+ if (!binding)
196
+ return null;
197
+ return {
198
+ limitedBy: binding.rule.countable,
199
+ rule: binding.rule.id,
200
+ retryAfterMs: Math.max(1, Math.ceil(binding.opensAt - now)),
201
+ };
202
+ }
203
+ buildRule(entry) {
204
+ const windowMs = parseWindow(entry.window);
205
+ if (windowMs === null) {
206
+ throw new Error(`Limiter.setRules: invalid window "${entry.window}" (expect e.g. 30s / 5m / 1h / 1d)`);
207
+ }
208
+ const present = COUNTABLES.filter((c) => entry[c] !== undefined);
209
+ if (present.length !== 1) {
210
+ // §3a item 4: co-located multi-countables are two constraints wearing one entry — a validation error shape.
211
+ throw new Error(`Limiter.setRules: window "${entry.window}" must carry exactly one countable (${COUNTABLES.join('/')}); got ${present.length}`);
212
+ }
213
+ const countable = present[0];
214
+ const limit = entry[countable];
215
+ if (!Number.isFinite(limit) || limit <= 0) {
216
+ throw new Error(`Limiter.setRules: ${countable} limit for window "${entry.window}" must be a positive finite number, got ${limit}`);
217
+ }
218
+ return {
219
+ id: `${entry.window}/${countable}`,
220
+ windowMs,
221
+ countable,
222
+ limit,
223
+ counter: new SlidingWindowCounter(windowMs, { nowMs: this.nowMs }),
224
+ };
225
+ }
226
+ seedSubject(subject, amounts) {
227
+ const state = this.states.get(subject);
228
+ if (!state)
229
+ return;
230
+ for (const rule of state.rules) {
231
+ if (!isDayWindow(rule.windowMs))
232
+ continue; // minute/hour windows always start empty (§4 state policy)
233
+ const amount = rule.countable === 'tokens' ? amounts.tokens : rule.countable === 'costUsd' ? amounts.costUsd : undefined;
234
+ if (amount === undefined || amount === 0)
235
+ continue;
236
+ // Boot-terminal skip (see rehydrate docblock): a junk ledger row must not
237
+ // brick the seeding pass; nothing is seeded for it and the window simply
238
+ // rebuilds from live usage.
239
+ if (!Number.isFinite(amount) || amount < 0)
240
+ continue;
241
+ rule.counter.increment(amount);
242
+ }
243
+ }
244
+ }
@@ -0,0 +1,63 @@
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
+ export type CounterCheck = {
23
+ /** Live count in the sliding window right now. */
24
+ count: number;
25
+ /** Structural time the oldest live count ages out; Infinity when count === 0. */
26
+ nextOpenAt: number;
27
+ };
28
+ export declare class SlidingWindowCounter {
29
+ private readonly windowMs;
30
+ private readonly bucketCount;
31
+ private readonly bucketWidthMs;
32
+ private readonly nowMs;
33
+ /** absolute slot index -> count accumulated in that slot */
34
+ private readonly buckets;
35
+ constructor(windowMs: number, opts?: {
36
+ bucketCount?: number;
37
+ nowMs?: () => number;
38
+ });
39
+ /** Add `n` events to the current slot. Atomic within one JS turn (single-threaded engine). */
40
+ increment(n?: number): void;
41
+ /**
42
+ * Count so far plus when the oldest live count ages out (see CounterCheck).
43
+ * `now` is caller-captured (Limiter.evaluate reads the clock exactly ONCE
44
+ * per verdict): reading it here too would let a mid-evaluation tick make a
45
+ * rule report `openAt > evaluate's now` and fabricate a denial. Only the
46
+ * write side (increment) reads the injected clock.
47
+ */
48
+ check(now: number): CounterCheck;
49
+ /**
50
+ * Earliest structural time the count can drop strictly below `limit`,
51
+ * assuming no further increments. Returns the caller's `now` when already
52
+ * below — never a fresh clock read, so the under-limit arm cannot invent
53
+ * `openAt > now` under a ticking clock. This is the per-rule `nextOpenAt`
54
+ * the verdict layer reduces over (design §3a: binding rule = latest,
55
+ * retryAfterMs = max).
56
+ */
57
+ openAt(limit: number, now: number): number;
58
+ private slot;
59
+ /** Structural time slot `b` ages out. Always > now for any retained slot (oldest >= newest-B+1). */
60
+ private expiry;
61
+ /** Prunes stale buckets as a side effect — every read entry point goes through here, with the caller's captured clock. */
62
+ private live;
63
+ }
@@ -0,0 +1,103 @@
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
+ }
@@ -0,0 +1,26 @@
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 {};
@@ -0,0 +1,28 @@
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
+ }