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
@@ -1408,12 +1408,43 @@ export class PipelineOrchestrator {
1408
1408
  // — see resolveTraceId). One id now joins capture events and the trace
1409
1409
  // record, so a console reader can pull both streams by traceId.
1410
1410
  const sharedTraceId = traceId ?? 'unknown';
1411
- const lastUserMsg = normalizedRequest.messages.filter(m => m.role === 'user').pop();
1412
- const userPromptSummary = typeof lastUserMsg?.content === 'string'
1411
+ // Multimodal content parts: keep the text ones (mirrors the early
1412
+ // lastUserText join at 2C without the `any` cast).
1413
+ const textPartOf = (p) => {
1414
+ if (typeof p !== 'object' || p === null || !('text' in p))
1415
+ return '';
1416
+ const text = p.text;
1417
+ return typeof text === 'string' ? text : '';
1418
+ };
1419
+ // The summary names the user message THAT TRIGGERED this turn. A
1420
+ // tool-result continuation turn carries the whole history, so its last
1421
+ // user message is the PREVIOUS turn's prompt — recording it again makes
1422
+ // every continuation row in the console's request detail read as a
1423
+ // duplicate (an empty summary renders the "no new user message"
1424
+ // fallback glyph). The message is stale when its index already existed
1425
+ // at the session's previous turn: clients append, so a genuinely new
1426
+ // user message always lands at or past the previous messageCount.
1427
+ // Both counts are post-compression snapshots — a heavy compression
1428
+ // shrink may over-mark; that only hides a display aid, never data.
1429
+ const lastUserIdx = (() => {
1430
+ for (let i = normalizedRequest.messages.length - 1; i >= 0; i--) {
1431
+ if (normalizedRequest.messages[i].role === 'user')
1432
+ return i;
1433
+ }
1434
+ return -1;
1435
+ })();
1436
+ const lastUserMsg = lastUserIdx >= 0 ? normalizedRequest.messages[lastUserIdx] : undefined;
1437
+ let userPromptSummary = typeof lastUserMsg?.content === 'string'
1413
1438
  ? lastUserMsg.content.slice(0, 200)
1414
1439
  : Array.isArray(lastUserMsg?.content)
1415
- ? (lastUserMsg.content.map(p => p.text || '').join(' ')).slice(0, 200)
1440
+ ? (lastUserMsg.content.map(textPartOf).join(' ')).slice(0, 200)
1416
1441
  : '';
1442
+ if (userPromptSummary) {
1443
+ const prevTraces = this.traceTracker.getTracesBySession(sessionId);
1444
+ const prevMessageCount = prevTraces[prevTraces.length - 1]?.request.messageCount ?? 0;
1445
+ if (lastUserIdx < prevMessageCount)
1446
+ userPromptSummary = '';
1447
+ }
1417
1448
  this.traceTracker.record({
1418
1449
  traceId: sharedTraceId,
1419
1450
  sessionId,
@@ -0,0 +1,29 @@
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
+ }
@@ -0,0 +1,170 @@
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
+ }
@@ -0,0 +1,24 @@
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;
@@ -0,0 +1,43 @@
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
+ }
@@ -0,0 +1,121 @@
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;
@@ -0,0 +1,183 @@
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 { accountSubject, apiKeySubject } from './subject.js';
49
+ import { DAY_WINDOW_MS } from './duration.js';
50
+ import { Limiter } from './limiter.js';
51
+ import { GovernanceConfigError, limitsForAccountSubject, limitsForApiKey, } from '../config/governance-limits.js';
52
+ import { buildDayLedgerReadback } from '../trace/tracker.js';
53
+ /** Adapter so callers hand the registry over without the engine importing it. */
54
+ export function poolViewOfRegistry(registry) {
55
+ return {
56
+ hasProvider: (name) => registry.hasProvider(name),
57
+ chainKeyHashPrefixes: (name) => (registry.getCredentialChain(name) ?? []).map((c) => c.keyHashPrefix),
58
+ };
59
+ }
60
+ // ─── process singleton ───────────────────────────────────────────────────────
61
+ let singleton;
62
+ let armed = false;
63
+ /** The subjects the LAST sync armed — the clear set: when config drops an
64
+ * entry its rules must die with it (setRules([]) deletes state entirely, design §5). */
65
+ let lastArmedSubjects = new Set();
66
+ let staleAnchors = [];
67
+ export function getGovernanceLimiter() {
68
+ if (!singleton)
69
+ singleton = new Limiter();
70
+ return singleton;
71
+ }
72
+ /** Call-site short-circuit: false ⇒ selection/dispatch skip every limiter
73
+ * interaction and run the exact pre-P3b paths (degeneracy promise). */
74
+ export function isGovernanceArmed() {
75
+ return armed;
76
+ }
77
+ /** P5 console overlay input — entries marked stale by the latest sync (never applied). */
78
+ export function getStaleGovernanceAnchors() {
79
+ return staleAnchors;
80
+ }
81
+ /**
82
+ * Translate config → rule sets against the live pool. Pure state transition
83
+ * (no ledger, no logging, never throws): the wrappers decide how loudly the
84
+ * refusals land. `setRules` replaces each subject atomically with FRESH
85
+ * counters (P1 contract: editing policy is re-baselining policy).
86
+ */
87
+ function applyRuleSets(config, pool) {
88
+ const limiter = getGovernanceLimiter();
89
+ const next = new Map();
90
+ const stale = [];
91
+ const unknownProviders = [];
92
+ for (const [provider, entries] of Object.entries(config.accounts ?? {})) {
93
+ const live = pool.hasProvider(provider);
94
+ // Prefix set ONLY from the live chain — an anchor no key hashes to is a
95
+ // dangling address, never a cap (stale ≠ unknown: the provider routes,
96
+ // this particular key is gone).
97
+ const prefixes = live ? new Set(pool.chainKeyHashPrefixes(provider)) : new Set();
98
+ entries.forEach((entry, i) => {
99
+ if (!live) {
100
+ unknownProviders.push({
101
+ location: `accounts.${provider}[${i}] (keyHashPrefix "${entry.keyHashPrefix}")`,
102
+ problem: `provider "${provider}" is not a live provider of this gateway boot — check the id against ` +
103
+ 'opencode.jsonc / the console provider list (a rotated key anchor is reported as stale instead)',
104
+ });
105
+ return;
106
+ }
107
+ if (!prefixes.has(entry.keyHashPrefix)) {
108
+ stale.push({ provider, keyHashPrefix: entry.keyHashPrefix, entryIndex: i });
109
+ return;
110
+ }
111
+ const limits = limitsForAccountSubject(config, provider, entry.keyHashPrefix);
112
+ if (!limits)
113
+ return; // absent/empty limits → no cap, no state (degeneracy)
114
+ next.set(accountSubject(provider, entry.keyHashPrefix), limits);
115
+ });
116
+ }
117
+ // Inbound key budgets arm on the same singleton; P4 wires the auth-middleware
118
+ // policy. Arming without a consumer is inert by construction (verdict-only engine).
119
+ for (const key of config.apiKeys ?? []) {
120
+ const limits = limitsForApiKey(config, key.id);
121
+ if (limits)
122
+ next.set(apiKeySubject(key.id), limits);
123
+ }
124
+ // Clear what a previous sync armed but this config no longer names.
125
+ for (const subject of lastArmedSubjects) {
126
+ if (!next.has(subject))
127
+ limiter.setRules(subject, []);
128
+ }
129
+ for (const [subject, rules] of next)
130
+ limiter.setRules(subject, rules);
131
+ lastArmedSubjects = new Set(next.keys());
132
+ staleAnchors = stale;
133
+ armed = next.size > 0;
134
+ return { result: { armedSubjects: next.size, stale, unknownProviders } };
135
+ }
136
+ /**
137
+ * Boot + hot-apply sync: replace rule sets against the live pool, then re-seed
138
+ * day windows from the trace ledger (setRules wiped counters — the ledger is
139
+ * the truth source for day-class windows, design §4). Await `tracker.whenReady`
140
+ * FIRST: the persisted day's traces must be in the ring before readback
141
+ * (the P3a boot-pattern docblock in trace/tracker.ts).
142
+ */
143
+ export async function syncGovernanceRuntime(opts) {
144
+ const log = opts.log ?? ((line) => console.warn(`[Governance] ${opts.phase ?? 'sync'}: ${line}`));
145
+ const { result } = applyRuleSets(opts.config, opts.pool);
146
+ for (const s of result.stale) {
147
+ log(`stale anchor: accounts.${s.provider}[${s.entryIndex}] keyHashPrefix "${s.keyHashPrefix}" is not in the live ` +
148
+ 'credential chain — entry NOT applied (rotate the config entry to the current key, or remove it)');
149
+ }
150
+ for (const u of result.unknownProviders) {
151
+ log(`unknown provider: ${u.location}: ${u.problem} — entry NOT applied`);
152
+ }
153
+ if (result.armedSubjects > 0) {
154
+ await opts.tracker.whenReady;
155
+ // Sliding 24h seed: the day-class windows rebuild from the same ledger the
156
+ // console reads (known ceiling — windows LONGER than 1d see a partial seed;
157
+ // upgrade path: per-window lookback). Minute/hour windows stay empty: the
158
+ // engine's rehydrate only seeds day-class rules.
159
+ getGovernanceLimiter().rehydrate(buildDayLedgerReadback(opts.tracker, Date.now() - DAY_WINDOW_MS));
160
+ log(`armed ${result.armedSubjects} governance subject(s); day windows rehydrated from the last-24h ledger`);
161
+ }
162
+ return result;
163
+ }
164
+ /**
165
+ * Boot entry — `syncGovernanceRuntime` plus the loud boot error: unknown
166
+ * provider ids in `accounts:` throw a GovernanceConfigError naming every
167
+ * offending entry (§5/§8 validation pin). A stale keyHash anchor does NOT
168
+ * throw — see module header for why the two refusal classes differ.
169
+ */
170
+ export async function initGovernanceRuntime(opts) {
171
+ const result = await syncGovernanceRuntime({ ...opts, phase: 'boot' });
172
+ if (result.unknownProviders.length > 0) {
173
+ throw new GovernanceConfigError(result.unknownProviders);
174
+ }
175
+ return result;
176
+ }
177
+ /** Test seam (precedent: resetBreakerStateStoreForTests) — fresh singleton per fixture. */
178
+ export function resetGovernanceLimiterForTests() {
179
+ singleton = undefined;
180
+ armed = false;
181
+ lastArmedSubjects = new Set();
182
+ staleAnchors = [];
183
+ }
@@ -0,0 +1,4 @@
1
+ export * from './subject.js';
2
+ export * from './duration.js';
3
+ export * from './sliding-window-counter.js';
4
+ export * from './limiter.js';
@@ -0,0 +1,4 @@
1
+ export * from './subject.js';
2
+ export * from './duration.js';
3
+ export * from './sliding-window-counter.js';
4
+ export * from './limiter.js';