omnicell-router 0.7.0 → 0.8.2

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 (246) hide show
  1. package/backend/dist/cli/clients/activity.d.ts +35 -0
  2. package/backend/dist/cli/clients/activity.js +67 -0
  3. package/backend/dist/cli/clients/base.d.ts +13 -2
  4. package/backend/dist/cli/clients/claude.d.ts +2 -2
  5. package/backend/dist/cli/clients/codex.d.ts +2 -2
  6. package/backend/dist/cli/clients/core-adapters.d.ts +3 -4
  7. package/backend/dist/cli/clients/core-adapters.js +3 -4
  8. package/backend/dist/cli/clients/cursor-proxy.d.ts +88 -0
  9. package/backend/dist/cli/clients/cursor-proxy.js +421 -0
  10. package/backend/dist/cli/clients/dsh.d.ts +2 -2
  11. package/backend/dist/cli/clients/grok.d.ts +2 -2
  12. package/backend/dist/cli/clients/index.d.ts +8 -1
  13. package/backend/dist/cli/clients/index.js +55 -21
  14. package/backend/dist/cli/clients/kimi.d.ts +2 -2
  15. package/backend/dist/cli/clients/launcher.d.ts +8 -0
  16. package/backend/dist/cli/clients/model-meta.js +1 -1
  17. package/backend/dist/cli/clients/omp.d.ts +2 -2
  18. package/backend/dist/cli/clients/openclaw.d.ts +2 -2
  19. package/backend/dist/cli/clients/opencode-proxy.d.ts +11 -0
  20. package/backend/dist/cli/clients/opencode-proxy.js +351 -0
  21. package/backend/dist/cli/clients/opencode.d.ts +2 -2
  22. package/backend/dist/cli/clients/pi.d.ts +2 -2
  23. package/backend/dist/cli/clients/plugin-adapters.d.ts +3 -1
  24. package/backend/dist/cli/clients/plugin-adapters.js +6 -29
  25. package/backend/dist/cli/clients/qoder-proxy.d.ts +84 -0
  26. package/backend/dist/cli/clients/qoder-proxy.js +497 -0
  27. package/backend/dist/cli/clients/reserved.d.ts +2 -6
  28. package/backend/dist/cli/clients/reserved.js +2 -0
  29. package/backend/dist/cli/clients/workbuddy.d.ts +2 -2
  30. package/backend/dist/cli/index.js +60 -9
  31. package/backend/dist/cli/types.d.ts +29 -8
  32. package/backend/dist/compression/caveman-prompts.d.ts +1 -1
  33. package/backend/dist/config/comments-en.js +6 -12
  34. package/backend/dist/config/comments-zh.js +6 -12
  35. package/backend/dist/config/defaults.d.ts +56 -1
  36. package/backend/dist/config/defaults.js +68 -0
  37. package/backend/dist/config/index.d.ts +9 -2
  38. package/backend/dist/config/index.js +26 -3
  39. package/backend/dist/config/types.d.ts +55 -43
  40. package/backend/dist/forward-proxy/egress.d.ts +10 -2
  41. package/backend/dist/forward-proxy/egress.js +42 -4
  42. package/backend/dist/forward-proxy/ordered-relay.d.ts +29 -0
  43. package/backend/dist/forward-proxy/ordered-relay.js +46 -0
  44. package/backend/dist/forward-proxy/rules.d.ts +66 -19
  45. package/backend/dist/forward-proxy/rules.js +61 -14
  46. package/backend/dist/forward-proxy/server.js +226 -77
  47. package/backend/dist/forward-proxy/system-proxy.d.ts +42 -2
  48. package/backend/dist/forward-proxy/system-proxy.js +199 -22
  49. package/backend/dist/harness/common/market.d.ts +3 -3
  50. package/backend/dist/harness/host/adapters/amp.d.ts +1 -1
  51. package/backend/dist/harness/host/adapters/antigravity.d.ts +1 -1
  52. package/backend/dist/harness/host/adapters/claude.d.ts +1 -1
  53. package/backend/dist/harness/host/adapters/cline.d.ts +1 -1
  54. package/backend/dist/harness/host/adapters/codex.d.ts +1 -1
  55. package/backend/dist/harness/host/adapters/cursor.d.ts +1 -1
  56. package/backend/dist/harness/host/adapters/dsh.d.ts +2 -2
  57. package/backend/dist/harness/host/adapters/factory.d.ts +1 -1
  58. package/backend/dist/harness/host/adapters/gemini-cli.d.ts +1 -1
  59. package/backend/dist/harness/host/adapters/grok.d.ts +1 -1
  60. package/backend/dist/harness/host/adapters/kimi.d.ts +1 -1
  61. package/backend/dist/harness/host/adapters/omp.d.ts +1 -1
  62. package/backend/dist/harness/host/adapters/openclaw.d.ts +1 -1
  63. package/backend/dist/harness/host/adapters/opencode.d.ts +1 -1
  64. package/backend/dist/harness/host/adapters/pi.d.ts +1 -1
  65. package/backend/dist/harness/host/adapters/universal.d.ts +1 -1
  66. package/backend/dist/harness/host/adapters/windsurf.d.ts +1 -1
  67. package/backend/dist/harness/host/adapters/zed.d.ts +1 -1
  68. package/backend/dist/harness/skill/skills-sh.d.ts +1 -1
  69. package/backend/dist/harness/translation.js +64 -21
  70. package/backend/dist/harness/types.d.ts +1 -1
  71. package/backend/dist/harness/types.js +1 -1
  72. package/backend/dist/index.js +31 -18
  73. package/backend/dist/ir/adapters/anthropic-stream.d.ts +18 -0
  74. package/backend/dist/ir/adapters/anthropic-stream.js +247 -0
  75. package/backend/dist/ir/adapters/anthropic.d.ts +29 -0
  76. package/backend/dist/ir/adapters/anthropic.js +788 -0
  77. package/backend/dist/ir/adapters/chat.d.ts +15 -0
  78. package/backend/dist/ir/adapters/chat.js +602 -0
  79. package/backend/dist/ir/adapters/google-stream.d.ts +22 -0
  80. package/backend/dist/ir/adapters/google-stream.js +242 -0
  81. package/backend/dist/ir/adapters/google.d.ts +9 -0
  82. package/backend/dist/ir/adapters/google.js +317 -0
  83. package/backend/dist/ir/adapters/openai-responses-output.js +8 -5
  84. package/backend/dist/ir/adapters/openai-responses.d.ts +15 -0
  85. package/backend/dist/ir/adapters/openai-responses.js +26 -1
  86. package/backend/dist/ir/adapters/responses-output.d.ts +50 -0
  87. package/backend/dist/ir/adapters/responses-output.js +348 -0
  88. package/backend/dist/ir/adapters/responses-stream.d.ts +12 -0
  89. package/backend/dist/ir/adapters/responses-stream.js +178 -0
  90. package/backend/dist/ir/adapters/responses.d.ts +14 -0
  91. package/backend/dist/ir/adapters/responses.js +646 -0
  92. package/backend/dist/ir/errors.d.ts +2 -2
  93. package/backend/dist/ir/types.d.ts +2 -1
  94. package/backend/dist/metrics/request-cost.d.ts +11 -2
  95. package/backend/dist/metrics/request-cost.js +12 -3
  96. package/backend/dist/observability/request-identity.d.ts +1 -1
  97. package/backend/dist/observability/trace-id.d.ts +40 -0
  98. package/backend/dist/observability/trace-id.js +134 -0
  99. package/backend/dist/observability/upstream-events.d.ts +82 -60
  100. package/backend/dist/observability/upstream-events.js +142 -67
  101. package/backend/dist/opencode/catalog/types.d.ts +9 -0
  102. package/backend/dist/opencode/credentials/types.d.ts +2 -2
  103. package/backend/dist/opencode/probe.d.ts +24 -1
  104. package/backend/dist/opencode/probe.js +28 -4
  105. package/backend/dist/opencode/user-config.d.ts +5 -0
  106. package/backend/dist/pipeline/directives.d.ts +6 -2
  107. package/backend/dist/pipeline/directives.js +7 -3
  108. package/backend/dist/pipeline/orchestrator.d.ts +28 -27
  109. package/backend/dist/pipeline/orchestrator.js +220 -194
  110. package/backend/dist/pipeline/unresolved-model.d.ts +33 -0
  111. package/backend/dist/pipeline/unresolved-model.js +43 -0
  112. package/backend/dist/plugins/catalog-def.d.ts +143 -0
  113. package/backend/dist/plugins/catalog-def.js +177 -0
  114. package/backend/dist/plugins/gateways.d.ts +62 -3
  115. package/backend/dist/plugins/gateways.js +139 -2
  116. package/backend/dist/plugins/host.d.ts +42 -5
  117. package/backend/dist/plugins/host.js +454 -38
  118. package/backend/dist/plugins/manifest.d.ts +119 -10
  119. package/backend/dist/plugins/manifest.js +265 -14
  120. package/backend/dist/plugins/pack.js +26 -0
  121. package/backend/dist/plugins/types.d.ts +187 -21
  122. package/backend/dist/protocols/systemone/convert.d.ts +1 -0
  123. package/backend/dist/protocols/systemone/convert.js +6 -1
  124. package/backend/dist/protocols/systemone/decide.js +18 -8
  125. package/backend/dist/providers/anthropic-messages.d.ts +12 -0
  126. package/backend/dist/providers/anthropic-messages.js +53 -0
  127. package/backend/dist/providers/anthropic.d.ts +7 -8
  128. package/backend/dist/providers/anthropic.js +36 -324
  129. package/backend/dist/providers/base.d.ts +14 -2
  130. package/backend/dist/providers/boot-direct.js +68 -38
  131. package/backend/dist/providers/dispatch.d.ts +5 -19
  132. package/backend/dist/providers/dispatch.js +46 -58
  133. package/backend/dist/providers/executors/anthropic-messages.d.ts +1 -0
  134. package/backend/dist/providers/executors/anthropic-messages.js +3 -0
  135. package/backend/dist/providers/executors/dispatch.d.ts +16 -2
  136. package/backend/dist/providers/executors/dispatch.js +39 -9
  137. package/backend/dist/providers/executors/google-gemini.d.ts +1 -0
  138. package/backend/dist/providers/executors/google-gemini.js +3 -0
  139. package/backend/dist/providers/executors/http-stream.js +16 -3
  140. package/backend/dist/providers/executors/openai-chat.d.ts +1 -0
  141. package/backend/dist/providers/executors/openai-chat.js +3 -0
  142. package/backend/dist/providers/executors/openai-responses.d.ts +1 -0
  143. package/backend/dist/providers/executors/openai-responses.js +3 -0
  144. package/backend/dist/providers/executors/plugin-adapter.js +4 -4
  145. package/backend/dist/providers/google-gemini.d.ts +12 -0
  146. package/backend/dist/providers/google-gemini.js +50 -0
  147. package/backend/dist/providers/google.d.ts +7 -8
  148. package/backend/dist/providers/google.js +35 -308
  149. package/backend/dist/providers/http-json.d.ts +19 -0
  150. package/backend/dist/providers/http-json.js +104 -0
  151. package/backend/dist/providers/http-stream.d.ts +52 -0
  152. package/backend/dist/providers/http-stream.js +423 -0
  153. package/backend/dist/providers/member-match.d.ts +4 -5
  154. package/backend/dist/providers/member-match.js +4 -5
  155. package/backend/dist/providers/openai-chat.d.ts +13 -0
  156. package/backend/dist/providers/openai-chat.js +99 -0
  157. package/backend/dist/providers/openai-compatible.d.ts +7 -4
  158. package/backend/dist/providers/openai-compatible.js +71 -368
  159. package/backend/dist/providers/openai-responses.d.ts +12 -0
  160. package/backend/dist/providers/openai-responses.js +68 -0
  161. package/backend/dist/providers/opencode-proxy.d.ts +5 -5
  162. package/backend/dist/providers/opencode-proxy.js +49 -125
  163. package/backend/dist/providers/plugin-adapter.d.ts +9 -0
  164. package/backend/dist/providers/plugin-adapter.js +31 -0
  165. package/backend/dist/providers/registry.d.ts +49 -24
  166. package/backend/dist/providers/registry.js +97 -55
  167. package/backend/dist/providers/responses.d.ts +7 -28
  168. package/backend/dist/providers/responses.js +45 -253
  169. package/backend/dist/providers/tool-markup-leak.d.ts +41 -0
  170. package/backend/dist/providers/tool-markup-leak.js +57 -0
  171. package/backend/dist/providers/tool-markup-recovery.d.ts +27 -0
  172. package/backend/dist/providers/tool-markup-recovery.js +786 -0
  173. package/backend/dist/providers/virtual-meta.d.ts +21 -2
  174. package/backend/dist/providers/virtual-meta.js +49 -9
  175. package/backend/dist/proxy/asset-download.d.ts +54 -0
  176. package/backend/dist/proxy/asset-download.js +420 -0
  177. package/backend/dist/proxy/manual-node-spec.d.ts +16 -16
  178. package/backend/dist/proxy/mihomo-binary.d.ts +17 -2
  179. package/backend/dist/proxy/mihomo-binary.js +62 -51
  180. package/backend/dist/proxy/mihomo-client.js +15 -1
  181. package/backend/dist/proxy/mihomo-config.js +11 -2
  182. package/backend/dist/proxy/mihomo-geo.d.ts +87 -0
  183. package/backend/dist/proxy/mihomo-geo.js +213 -0
  184. package/backend/dist/proxy/mihomo-logs.d.ts +27 -0
  185. package/backend/dist/proxy/mihomo-logs.js +70 -0
  186. package/backend/dist/proxy/mihomo-pac.d.ts +11 -0
  187. package/backend/dist/proxy/mihomo-pac.js +15 -0
  188. package/backend/dist/proxy/mihomo-rules-import.d.ts +1 -1
  189. package/backend/dist/proxy/mihomo-rules-import.js +7 -7
  190. package/backend/dist/proxy/mihomo-sidecar.d.ts +17 -1
  191. package/backend/dist/proxy/mihomo-sidecar.js +148 -26
  192. package/backend/dist/quota/adapters/minimax.js +36 -13
  193. package/backend/dist/quota/cli-login.d.ts +8 -0
  194. package/backend/dist/quota/cli-login.js +18 -0
  195. package/backend/dist/quota/declarations.js +10 -0
  196. package/backend/dist/quota/dsl.js +18 -5
  197. package/backend/dist/quota/engine.d.ts +22 -1
  198. package/backend/dist/quota/engine.js +170 -29
  199. package/backend/dist/quota/prober.d.ts +5 -0
  200. package/backend/dist/quota/prober.js +11 -2
  201. package/backend/dist/quota/types.d.ts +87 -8
  202. package/backend/dist/quota/verdict.d.ts +35 -0
  203. package/backend/dist/quota/verdict.js +135 -0
  204. package/backend/dist/ratelimit/admission.d.ts +131 -0
  205. package/backend/dist/ratelimit/admission.js +233 -0
  206. package/backend/dist/ratelimit/rate-limiter.js +6 -0
  207. package/backend/dist/resilience/types.d.ts +2 -2
  208. package/backend/dist/router/layer2-decision.d.ts +1 -1
  209. package/backend/dist/router/layer2-decision.js +5 -8
  210. package/backend/dist/routes/console.js +248 -52
  211. package/backend/dist/routes/mihomo.d.ts +2 -0
  212. package/backend/dist/routes/mihomo.js +334 -29
  213. package/backend/dist/routes/responses.d.ts +87 -8
  214. package/backend/dist/routes/responses.js +314 -33
  215. package/backend/dist/server.js +34 -6
  216. package/backend/dist/session/session-manager.d.ts +6 -0
  217. package/backend/dist/session/session-manager.js +20 -9
  218. package/backend/dist/surfaces/chat-pipeline.d.ts +2 -2
  219. package/backend/dist/surfaces/chat-pipeline.js +17 -7
  220. package/backend/dist/surfaces/chat.js +15 -0
  221. package/backend/dist/surfaces/decision-pipeline.js +7 -10
  222. package/backend/dist/surfaces/direct-forward.d.ts +3 -0
  223. package/backend/dist/surfaces/direct-forward.js +206 -0
  224. package/backend/dist/surfaces/rate-limit-response.d.ts +17 -0
  225. package/backend/dist/surfaces/rate-limit-response.js +57 -0
  226. package/backend/dist/surfaces/types.d.ts +11 -0
  227. package/backend/dist/trace/tracker.d.ts +32 -1
  228. package/backend/dist/trace/tracker.js +29 -4
  229. package/backend/dist/types/router.d.ts +34 -12
  230. package/backend/dist/types/router.js +35 -6
  231. package/backend/dist/utils/chat-stream.d.ts +21 -8
  232. package/backend/dist/utils/chat-stream.js +46 -9
  233. package/backend/dist/utils/event-ring.d.ts +4 -0
  234. package/backend/dist/utils/event-ring.js +4 -0
  235. package/backend/dist/utils/popularity.js +29 -4
  236. package/backend/dist/utils/proxy.d.ts +7 -0
  237. package/backend/dist/utils/proxy.js +35 -10
  238. package/backend/dist/utils/retry-after.d.ts +21 -0
  239. package/backend/dist/utils/retry-after.js +36 -0
  240. package/bin/ocr.js +2 -2
  241. package/frontend/dist/assets/index-55VVwfFQ.js +1521 -0
  242. package/frontend/dist/assets/{index-CQSLGFTV.css → index-DxZ9MHKB.css} +1 -1
  243. package/frontend/dist/assets/workbuddy.color-DOMpQkxJ.svg +29 -0
  244. package/frontend/dist/index.html +2 -2
  245. package/package.json +1 -1
  246. package/frontend/dist/assets/index-CLvxJjp_.js +0 -1476
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Rate-limit waiting & re-entrant admission primitives (ADR-0023).
3
+ *
4
+ * - `waitForSubjectCapacity` — cumulative budget + 1 s capability probes,
5
+ * pair locked (caller never rebinds while waiting).
6
+ * - Bounded wait queue (`acquireWaitSlot`) — over-cap means delay, not shed.
7
+ * - `RateLimitRejected` — structured 429 carrier (budget exhausted / upstream
8
+ * ladder / pool-min) so surfaces never collapse to a generic 5xx.
9
+ * - `AdmissionState` — per-request cumulative wait + re-entry counter shared
10
+ * across re-entries of the same inbound request.
11
+ */
12
+ import type { Countable, RateLimitVerdict } from './rate-limiter.js';
13
+ /** Exact window/cooldown math vs a probe lower-bound (reservation-only / pool). */
14
+ export type RetryAfterKind = 'exact' | 'estimate';
15
+ export type RateLimitRejectReason = 'budget-exhausted' | 'upstream-retry-after' | 'pool-min';
16
+ /**
17
+ * Structured rate-limit rejection the surface maps to 429 + Retry-After
18
+ * (or an SSE error event with `retry_after_ms` once 200 SSE headers are out).
19
+ */
20
+ export declare class RateLimitRejected extends Error {
21
+ readonly statusCode = 429;
22
+ readonly code = "rate_limit_exceeded";
23
+ readonly retryAfterMs: number;
24
+ readonly retryAfterKind: RetryAfterKind;
25
+ readonly rule: string;
26
+ readonly limitedBy: Countable;
27
+ readonly subject: string;
28
+ readonly limit: number;
29
+ readonly used: number;
30
+ readonly waitedMs: number;
31
+ readonly reason: RateLimitRejectReason;
32
+ constructor(opts: {
33
+ retryAfterMs: number;
34
+ retryAfterKind?: RetryAfterKind;
35
+ rule: string;
36
+ limitedBy: Countable;
37
+ subject: string;
38
+ limit?: number;
39
+ used?: number;
40
+ waitedMs?: number;
41
+ reason: RateLimitRejectReason;
42
+ message?: string;
43
+ });
44
+ }
45
+ /** Alias kept for ADR wording / call-site clarity. */
46
+ export { RateLimitRejected as RateLimitWaitExhausted };
47
+ export declare function isRateLimitRejected(err: unknown): err is RateLimitRejected;
48
+ /**
49
+ * Signal that `admitRequest` should re-enter (no-RA 429 / retriable call
50
+ * failure with `!relay.committed`). Carries the original request identity.
51
+ */
52
+ export declare class AdmissionReentry extends Error {
53
+ constructor(message?: string);
54
+ }
55
+ export declare function isAdmissionReentry(err: unknown): err is AdmissionReentry;
56
+ /** Per-request cumulative wait + re-entry state (ADR-0023 §1). */
57
+ export interface AdmissionState {
58
+ /** Gateway-minted request id (ADR-0021) — carried across re-entries. */
59
+ requestId: string;
60
+ /** Cumulative ms already waited across all attempts of this request. */
61
+ waitedMs: number;
62
+ /** How many times admitRequest has re-entered (max DEFAULT_ADMISSION_MAX_REENTRIES). */
63
+ reentries: number;
64
+ maxReentries: number;
65
+ }
66
+ export declare function createAdmissionState(requestId: string, maxReentries?: number): AdmissionState;
67
+ export declare function canReenter(state: AdmissionState): boolean;
68
+ export declare function noteReentry(state: AdmissionState): void;
69
+ /**
70
+ * Acquire a slot in the bounded wait queue. When at capacity, park until a
71
+ * peer releases (delay, not 429). `budgetMs` bounds how long we may queue.
72
+ */
73
+ export declare function acquireWaitSlot(budgetMs: number, maxSlots?: number): Promise<() => void>;
74
+ /** Test seam: reset the live wait-queue counters. */
75
+ export declare function resetWaitQueueForTests(): void;
76
+ export interface WaitForCapacityOptions {
77
+ /** Non-consuming peek of the locked subject. */
78
+ peek: () => RateLimitVerdict;
79
+ /** Remaining cumulative budget for THIS wait (already-waited subtracted by caller). */
80
+ budgetMs: number;
81
+ /** Probe cadence; also the reservation-only Retry-After lower bound. */
82
+ probeIntervalMs?: number;
83
+ /** Client still connected? */
84
+ isClientAlive?: () => boolean;
85
+ /** SSE comment heartbeat while waiting (stream:true). */
86
+ onHeartbeat?: () => void;
87
+ heartbeatIntervalMs?: number;
88
+ /** Small jitter added to the first sleep when evaluate gives msUntilBelow. */
89
+ jitterMs?: number;
90
+ /** Sleep seam for tests. */
91
+ sleep?: (ms: number) => Promise<void>;
92
+ /** Wall clock for heartbeat cadence. */
93
+ now?: () => number;
94
+ }
95
+ export interface WaitForCapacityResult {
96
+ /** Final peek verdict (allowed, or the denied verdict at budget exhaustion). */
97
+ verdict: RateLimitVerdict;
98
+ /** ms actually slept in this wait. */
99
+ waitedMs: number;
100
+ /** Client disconnected mid-wait. */
101
+ clientGone: boolean;
102
+ /**
103
+ * When denied at exhaustion: whether Retry-After is exact window math or a
104
+ * probe lower-bound (reservation-only).
105
+ */
106
+ retryAfterKind: RetryAfterKind;
107
+ }
108
+ /**
109
+ * Probe until the subject opens or the cumulative budget is spent.
110
+ * Does NOT consume a slot — caller `dispatch`s / `tryDispatch`s on success.
111
+ */
112
+ export declare function waitForSubjectCapacity(opts: WaitForCapacityOptions): Promise<WaitForCapacityResult>;
113
+ /**
114
+ * Map a denied verdict to the Retry-After value + kind for the wire
115
+ * (ADR-0023 §2.1): exact window/cooldown, or probe lower-bound for
116
+ * reservation-only (never echo bare 1).
117
+ */
118
+ export declare function resolveExhaustionRetryAfter(verdict: Extract<RateLimitVerdict, {
119
+ allowed: false;
120
+ }>, probeIntervalMs?: number): {
121
+ retryAfterMs: number;
122
+ kind: RetryAfterKind;
123
+ };
124
+ /**
125
+ * Re-entrant admission wrapper: runs `attempt` up to `1 + maxReentries` times.
126
+ * `AdmissionReentry` (and only that, when !committed) triggers another pass;
127
+ * budgets in `state` accumulate and never reset.
128
+ */
129
+ export declare function admitRequest<T>(state: AdmissionState, attempt: (state: AdmissionState) => Promise<T>, opts?: {
130
+ isCommitted?: () => boolean;
131
+ }): Promise<T>;
@@ -0,0 +1,233 @@
1
+ /**
2
+ * Rate-limit waiting & re-entrant admission primitives (ADR-0023).
3
+ *
4
+ * - `waitForSubjectCapacity` — cumulative budget + 1 s capability probes,
5
+ * pair locked (caller never rebinds while waiting).
6
+ * - Bounded wait queue (`acquireWaitSlot`) — over-cap means delay, not shed.
7
+ * - `RateLimitRejected` — structured 429 carrier (budget exhausted / upstream
8
+ * ladder / pool-min) so surfaces never collapse to a generic 5xx.
9
+ * - `AdmissionState` — per-request cumulative wait + re-entry counter shared
10
+ * across re-entries of the same inbound request.
11
+ */
12
+ import { DEFAULT_ADMISSION_MAX_REENTRIES, DEFAULT_RATE_LIMIT_PROBE_INTERVAL_MS, MAX_GRACE_SLEEPERS, } from '../config/defaults.js';
13
+ import { retryAfterSecFromMs } from '../utils/retry-after.js';
14
+ /**
15
+ * Structured rate-limit rejection the surface maps to 429 + Retry-After
16
+ * (or an SSE error event with `retry_after_ms` once 200 SSE headers are out).
17
+ */
18
+ export class RateLimitRejected extends Error {
19
+ statusCode = 429;
20
+ code = 'rate_limit_exceeded';
21
+ retryAfterMs;
22
+ retryAfterKind;
23
+ rule;
24
+ limitedBy;
25
+ subject;
26
+ limit;
27
+ used;
28
+ waitedMs;
29
+ reason;
30
+ constructor(opts) {
31
+ const sec = retryAfterSecFromMs(opts.retryAfterMs);
32
+ super(opts.message ??
33
+ `Rate limit exceeded (${opts.rule}); retry after ${sec}s` +
34
+ (opts.waitedMs && opts.waitedMs > 0 ? ` (waited ${opts.waitedMs}ms)` : ''));
35
+ this.name = 'RateLimitRejected';
36
+ this.retryAfterMs = Math.max(1, opts.retryAfterMs);
37
+ this.retryAfterKind = opts.retryAfterKind ?? 'exact';
38
+ this.rule = opts.rule;
39
+ this.limitedBy = opts.limitedBy;
40
+ this.subject = opts.subject;
41
+ this.limit = opts.limit ?? 0;
42
+ this.used = opts.used ?? 0;
43
+ this.waitedMs = opts.waitedMs ?? 0;
44
+ this.reason = opts.reason;
45
+ }
46
+ }
47
+ /** Alias kept for ADR wording / call-site clarity. */
48
+ export { RateLimitRejected as RateLimitWaitExhausted };
49
+ export function isRateLimitRejected(err) {
50
+ return err instanceof RateLimitRejected;
51
+ }
52
+ /**
53
+ * Signal that `admitRequest` should re-enter (no-RA 429 / retriable call
54
+ * failure with `!relay.committed`). Carries the original request identity.
55
+ */
56
+ export class AdmissionReentry extends Error {
57
+ constructor(message = 'admission re-entry requested') {
58
+ super(message);
59
+ this.name = 'AdmissionReentry';
60
+ }
61
+ }
62
+ export function isAdmissionReentry(err) {
63
+ return err instanceof AdmissionReentry;
64
+ }
65
+ export function createAdmissionState(requestId, maxReentries = DEFAULT_ADMISSION_MAX_REENTRIES) {
66
+ return { requestId, waitedMs: 0, reentries: 0, maxReentries };
67
+ }
68
+ export function canReenter(state) {
69
+ return state.reentries < state.maxReentries;
70
+ }
71
+ export function noteReentry(state) {
72
+ state.reentries += 1;
73
+ }
74
+ let activeWaitSlots = 0;
75
+ const waitQueue = [];
76
+ function releaseWaitSlot() {
77
+ activeWaitSlots = Math.max(0, activeWaitSlots - 1);
78
+ const next = waitQueue.shift();
79
+ if (!next)
80
+ return;
81
+ activeWaitSlots++;
82
+ let released = false;
83
+ next.resolve(() => {
84
+ if (released)
85
+ return;
86
+ released = true;
87
+ releaseWaitSlot();
88
+ });
89
+ }
90
+ /**
91
+ * Acquire a slot in the bounded wait queue. When at capacity, park until a
92
+ * peer releases (delay, not 429). `budgetMs` bounds how long we may queue.
93
+ */
94
+ export async function acquireWaitSlot(budgetMs, maxSlots = MAX_GRACE_SLEEPERS) {
95
+ if (activeWaitSlots < maxSlots) {
96
+ activeWaitSlots++;
97
+ let released = false;
98
+ return () => {
99
+ if (released)
100
+ return;
101
+ released = true;
102
+ releaseWaitSlot();
103
+ };
104
+ }
105
+ if (budgetMs <= 0) {
106
+ throw new Error('wait queue full and no budget left to queue');
107
+ }
108
+ return await new Promise((resolve, reject) => {
109
+ const waiter = { resolve, reject };
110
+ waitQueue.push(waiter);
111
+ const timer = setTimeout(() => {
112
+ const idx = waitQueue.indexOf(waiter);
113
+ if (idx >= 0)
114
+ waitQueue.splice(idx, 1);
115
+ reject(new Error('wait queue timed out'));
116
+ }, budgetMs);
117
+ const origResolve = waiter.resolve;
118
+ waiter.resolve = (release) => {
119
+ clearTimeout(timer);
120
+ origResolve(release);
121
+ };
122
+ });
123
+ }
124
+ /** Test seam: reset the live wait-queue counters. */
125
+ export function resetWaitQueueForTests() {
126
+ activeWaitSlots = 0;
127
+ while (waitQueue.length) {
128
+ const w = waitQueue.shift();
129
+ w?.reject(new Error('wait queue reset'));
130
+ }
131
+ }
132
+ const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
133
+ /**
134
+ * Probe until the subject opens or the cumulative budget is spent.
135
+ * Does NOT consume a slot — caller `dispatch`s / `tryDispatch`s on success.
136
+ */
137
+ export async function waitForSubjectCapacity(opts) {
138
+ const probeIntervalMs = opts.probeIntervalMs ?? DEFAULT_RATE_LIMIT_PROBE_INTERVAL_MS;
139
+ const sleep = opts.sleep ?? defaultSleep;
140
+ const now = opts.now ?? Date.now;
141
+ const isAlive = opts.isClientAlive ?? (() => true);
142
+ const heartbeatEvery = opts.heartbeatIntervalMs ?? 15_000;
143
+ const jitterFloor = opts.jitterMs ?? 25;
144
+ let waitedMs = 0;
145
+ let lastHeartbeat = now();
146
+ let first = true;
147
+ let lastDenied;
148
+ let lastKind = 'exact';
149
+ while (waitedMs < opts.budgetMs) {
150
+ if (!isAlive()) {
151
+ return {
152
+ verdict: lastDenied ?? opts.peek(),
153
+ waitedMs,
154
+ clientGone: true,
155
+ retryAfterKind: lastKind,
156
+ };
157
+ }
158
+ const verdict = opts.peek();
159
+ if (verdict.allowed) {
160
+ return { verdict, waitedMs, clientGone: false, retryAfterKind: 'exact' };
161
+ }
162
+ lastDenied = verdict;
163
+ lastKind = resolveRetryAfterKind(verdict);
164
+ const remaining = opts.budgetMs - waitedMs;
165
+ if (remaining <= 0)
166
+ break;
167
+ let sleepMs;
168
+ if (first && !verdict.reservationOnly && verdict.retryAfterMs > 0 && verdict.retryAfterMs <= remaining) {
169
+ // First probe may sleep until the known reopen (+ small jitter).
170
+ sleepMs = Math.min(remaining, verdict.retryAfterMs + 5 + Math.floor(Math.random() * jitterFloor));
171
+ }
172
+ else {
173
+ sleepMs = Math.min(remaining, Math.max(1, probeIntervalMs));
174
+ }
175
+ first = false;
176
+ await sleep(sleepMs);
177
+ waitedMs += sleepMs;
178
+ if (opts.onHeartbeat && now() - lastHeartbeat >= heartbeatEvery) {
179
+ opts.onHeartbeat();
180
+ lastHeartbeat = now();
181
+ }
182
+ }
183
+ // Budget exhausted — re-peek for the POST-wait verdict (ADR-0023 §2.1).
184
+ const finalVerdict = opts.peek();
185
+ if (!finalVerdict.allowed) {
186
+ lastDenied = finalVerdict;
187
+ lastKind = resolveRetryAfterKind(finalVerdict);
188
+ }
189
+ return {
190
+ verdict: finalVerdict,
191
+ waitedMs,
192
+ clientGone: !isAlive(),
193
+ retryAfterKind: lastKind,
194
+ };
195
+ }
196
+ /**
197
+ * Map a denied verdict to the Retry-After value + kind for the wire
198
+ * (ADR-0023 §2.1): exact window/cooldown, or probe lower-bound for
199
+ * reservation-only (never echo bare 1).
200
+ */
201
+ export function resolveExhaustionRetryAfter(verdict, probeIntervalMs = DEFAULT_RATE_LIMIT_PROBE_INTERVAL_MS) {
202
+ const kind = resolveRetryAfterKind(verdict);
203
+ if (kind === 'estimate') {
204
+ return { retryAfterMs: Math.max(probeIntervalMs, 1_000), kind };
205
+ }
206
+ return { retryAfterMs: Math.max(1, verdict.retryAfterMs), kind };
207
+ }
208
+ function resolveRetryAfterKind(verdict) {
209
+ if (verdict.reservationOnly)
210
+ return 'estimate';
211
+ return 'exact';
212
+ }
213
+ /**
214
+ * Re-entrant admission wrapper: runs `attempt` up to `1 + maxReentries` times.
215
+ * `AdmissionReentry` (and only that, when !committed) triggers another pass;
216
+ * budgets in `state` accumulate and never reset.
217
+ */
218
+ export async function admitRequest(state, attempt, opts) {
219
+ for (;;) {
220
+ try {
221
+ return await attempt(state);
222
+ }
223
+ catch (err) {
224
+ if (isAdmissionReentry(err) &&
225
+ canReenter(state) &&
226
+ !(opts?.isCommitted?.() ?? false)) {
227
+ noteReentry(state);
228
+ continue;
229
+ }
230
+ throw err;
231
+ }
232
+ }
233
+ }
@@ -412,6 +412,12 @@ export class RateLimiter {
412
412
  for (const c of rules) {
413
413
  if (c.countable === 'requests')
414
414
  continue;
415
+ // An UNPRICED turn passes no `costUsd` (unknown price, not zero), so the
416
+ // guard below skips it instead of adding 0 — a `costUsd` budget rule
417
+ // therefore never fires for an unpriced model, which is the honest
418
+ // outcome: a spend cap cannot be enforced against a number nobody knows.
419
+ // (Adding 0 would be worse: it looks like the rule is working while the
420
+ // window silently ignores every such turn.)
415
421
  const amount = c.countable === 'tokens' ? usage.tokens ?? 0 : usage.costUsd ?? 0;
416
422
  if (amount > 0)
417
423
  this.window(subject, c).add(now, amount, c.windowMs);
@@ -1,6 +1,6 @@
1
1
  import { ReasonParams, TierLevel } from '../types/router.js';
2
2
  export type CircuitBreakerState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
3
- export declare const ERROR_CATEGORIES: readonly ['QUOTA_EXHAUSTED', 'AUTHENTICATION_ERROR', 'RATE_LIMITED', 'SERVICE_UNAVAILABLE', 'CLIENT_ERROR', 'MANUAL', 'UNKNOWN'];
3
+ export declare const ERROR_CATEGORIES: readonly ["QUOTA_EXHAUSTED", "AUTHENTICATION_ERROR", "RATE_LIMITED", "SERVICE_UNAVAILABLE", "CLIENT_ERROR", "MANUAL", "UNKNOWN"];
4
4
  export type ErrorCategory = typeof ERROR_CATEGORIES[number];
5
5
  export type NetworkFailureCause = 'CONNECTION_RESET' | 'NETWORK_TIMEOUT' | 'GATEWAY_ERROR' | 'RATE_LIMIT_BURST' | 'DNS_ERROR' | 'SERVER_INTERNAL_ERROR' | 'HARD_FAILURE' | 'UNKNOWN';
6
6
  /**
@@ -27,7 +27,7 @@ export type TripScope = 'pair' | 'credential' | 'model' | 'provider';
27
27
  * inner template from the same vars. `detail` always carries the verbatim
28
28
  * English for unresolvable codes / free-form operator text.
29
29
  */
30
- export declare const BREAKER_REASON_CODES: readonly ['breaker.quota', 'breaker.auth', 'breaker.rate_limit', 'breaker.network', 'breaker.unknown', 'breaker.canary', 'breaker.consecutive', 'breaker.rate_window', 'breaker.manual'];
30
+ export declare const BREAKER_REASON_CODES: readonly ["breaker.quota", "breaker.auth", "breaker.rate_limit", "breaker.network", "breaker.unknown", "breaker.canary", "breaker.consecutive", "breaker.rate_window", "breaker.manual"];
31
31
  export type BreakerReasonCode = typeof BREAKER_REASON_CODES[number];
32
32
  export interface ErrorDiagnosis {
33
33
  category: ErrorCategory;
@@ -3,7 +3,7 @@ import { ReasoningEffort, TierLevel, ReasonParams } from '../types/router.js';
3
3
  import { Layer2DecisionConfig } from '../config/types.js';
4
4
  import { type RoutingCacheStats } from './decision-cache.js';
5
5
  import { ProviderRegistry } from '../providers/registry.js';
6
- import type { UpstreamEventContext } from '../providers/base.js';
6
+ import { UpstreamEventContext } from '../observability/upstream-events.js';
7
7
  export interface Layer2DecisionResult {
8
8
  targetTier: TierLevel;
9
9
  confidence: number;
@@ -225,15 +225,12 @@ export class Layer2Decision {
225
225
  resolve(null);
226
226
  }, timeoutMs);
227
227
  });
228
- // L2-DECISION-CALL CAPTURE gate (the single requestCapture.enabled master,
229
- // checked HERE via the recorder carried by the outer identity; master off
230
- // means the orchestrator never even passes a ctx).
231
- // ON: reuse the OUTER request's requestId/sessionId so the decision layer's wire call
232
- // joins the routed turn's archive, labeled purpose 'l2-decision' to tell it
233
- // from candidate-execution events. OFF: undefined = silence, the exact
234
- // call shape as today.
228
+ // Archive copy of the outer turn, present only while capture is on.
229
+ // The copied sessionId labels the decision wire's events so they join
230
+ // the routed turn. It is not passed to the executor as a conversation
231
+ // binding: a routing decision is not the user's conversation.
235
232
  const decisionCaptureCtx = decisionCapture && decisionCapture.recorder.isEnabled()
236
- ? { ...decisionCapture, purpose: 'l2-decision' }
233
+ ? decisionCapture.withPurpose('l2-decision')
237
234
  : undefined;
238
235
  const pending = runSystemoneDecision(registry, this.buildRequest(state, model.id, askEffort), model, { signal: controller.signal, upstreamEventContext: decisionCaptureCtx })
239
236
  .then((decision) => {