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,423 @@
1
+ import { canonicalResponseToEvents } from '../ir/stream.js';
2
+ import { UpstreamError } from '../resilience/error-classifier.js';
3
+ import { proxiedFetch, resolveProxyUrl } from '../utils/proxy.js';
4
+ import { redactUpstreamBody } from '../observability/upstream-body-redaction.js';
5
+ import { emitUpstreamRequestOnce, emitUpstreamResponseOnce, emitUpstreamFailureOnce, withUpstreamFailureGuard, } from '../observability/upstream-events.js';
6
+ /** Raw-wire capture is bounded independently of the semantic event stream. */
7
+ export const STREAM_CAPTURE_CAP = 256 * 1024;
8
+ /** A single unterminated SSE frame must not bypass the accumulator's memory bound. */
9
+ export const STREAM_SSE_FRAME_MAX_CHARS = 32 * 1024 * 1024;
10
+ /** Incremental WHATWG SSE parser: CRLF, comments and multi-line data included. */
11
+ export class SseParser {
12
+ buffer = '';
13
+ data = [];
14
+ dataChars = 0;
15
+ push(text) {
16
+ this.buffer += text;
17
+ const frames = [];
18
+ // Linear scan: walk newlines by index instead of repeatedly slicing the
19
+ // remaining buffer (that was O(N²) copies for a chunk with N short frames).
20
+ let start = 0;
21
+ while (true) {
22
+ const newline = this.buffer.indexOf('\n', start);
23
+ if (newline < 0)
24
+ break;
25
+ let line = this.buffer.slice(start, newline);
26
+ start = newline + 1;
27
+ if (line.endsWith('\r'))
28
+ line = line.slice(0, -1);
29
+ const frame = this.line(line);
30
+ if (frame)
31
+ frames.push(frame);
32
+ }
33
+ this.buffer = start > 0 ? this.buffer.slice(start) : this.buffer;
34
+ // Bound one unterminated line, not the aggregate size of a network chunk
35
+ // that may already contain thousands of complete, small frames.
36
+ if (this.buffer.length > STREAM_SSE_FRAME_MAX_CHARS) {
37
+ throw new Error(`Upstream SSE frame exceeded ${STREAM_SSE_FRAME_MAX_CHARS} characters.`);
38
+ }
39
+ return frames;
40
+ }
41
+ finish() {
42
+ const frames = [];
43
+ if (this.buffer) {
44
+ const line = this.buffer.endsWith('\r') ? this.buffer.slice(0, -1) : this.buffer;
45
+ this.buffer = '';
46
+ const frame = this.line(line);
47
+ if (frame)
48
+ frames.push(frame);
49
+ }
50
+ const frame = this.dispatch();
51
+ if (frame)
52
+ frames.push(frame);
53
+ return frames;
54
+ }
55
+ line(line) {
56
+ if (!line)
57
+ return this.dispatch();
58
+ if (line.startsWith(':'))
59
+ return undefined;
60
+ const colon = line.indexOf(':');
61
+ const field = colon < 0 ? line : line.slice(0, colon);
62
+ let value = colon < 0 ? '' : line.slice(colon + 1);
63
+ if (value.startsWith(' '))
64
+ value = value.slice(1);
65
+ if (field === 'data') {
66
+ this.dataChars += value.length + 1;
67
+ if (this.dataChars > STREAM_SSE_FRAME_MAX_CHARS) {
68
+ throw new Error(`Upstream SSE frame exceeded ${STREAM_SSE_FRAME_MAX_CHARS} characters.`);
69
+ }
70
+ this.data.push(value);
71
+ }
72
+ return undefined;
73
+ }
74
+ dispatch() {
75
+ if (!this.data.length)
76
+ return undefined;
77
+ const data = this.data.join('\n');
78
+ this.data = [];
79
+ this.dataChars = 0;
80
+ return { data };
81
+ }
82
+ }
83
+ function parseRetryAfter(value) {
84
+ if (!value)
85
+ return undefined;
86
+ const seconds = Number.parseInt(value, 10);
87
+ return Number.isNaN(seconds) ? undefined : seconds;
88
+ }
89
+ /**
90
+ * Read up to `maxBytes` of a response body as UTF-8 text, cancelling the
91
+ * stream once the cap is reached so a runaway error response cannot exhaust
92
+ * memory. When `race` is supplied, every chunk read is bounded by it.
93
+ */
94
+ export async function readBoundedBodyText(res, maxBytes, race) {
95
+ if (!res.body)
96
+ return '';
97
+ const reader = res.body.getReader();
98
+ const chunks = [];
99
+ let total = 0;
100
+ let truncated = false;
101
+ try {
102
+ while (true) {
103
+ const readPromise = reader.read();
104
+ const { done, value } = race ? await race(readPromise) : await readPromise;
105
+ if (done)
106
+ break;
107
+ if (!value || value.byteLength === 0)
108
+ continue;
109
+ if (total + value.byteLength > maxBytes) {
110
+ const room = maxBytes - total;
111
+ if (room > 0)
112
+ chunks.push(value.subarray(0, room));
113
+ total = maxBytes;
114
+ truncated = true;
115
+ break;
116
+ }
117
+ chunks.push(value);
118
+ total += value.byteLength;
119
+ }
120
+ }
121
+ finally {
122
+ if (truncated) {
123
+ try {
124
+ await reader.cancel();
125
+ }
126
+ catch { /* The peer may already be gone. */ }
127
+ }
128
+ try {
129
+ reader.releaseLock();
130
+ }
131
+ catch { /* Still settling. */ }
132
+ }
133
+ const merged = new Uint8Array(total);
134
+ let offset = 0;
135
+ for (const c of chunks) {
136
+ merged.set(c, offset);
137
+ offset += c.byteLength;
138
+ }
139
+ return new TextDecoder('utf-8').decode(merged);
140
+ }
141
+ /**
142
+ * One streamed HTTP exchange with shared capture, timeout, SSE and fallback
143
+ * semantics. Provider modules own only request shaping and protocol decoding.
144
+ */
145
+ export async function postProviderStream(options) {
146
+ const { url, headers, payload, model, provider, label, upstreamEventContext, } = options;
147
+ const body = JSON.stringify(payload);
148
+ const exchangeId = emitUpstreamRequestOnce(upstreamEventContext, {
149
+ url,
150
+ method: 'POST',
151
+ requestHeaders: headers,
152
+ requestBody: body,
153
+ model: model.upstreamModel,
154
+ proxy: resolveProxyUrl(url, { provider, model: model.id }),
155
+ });
156
+ const controller = new AbortController();
157
+ let totalTripped = false;
158
+ let idleTripped = false;
159
+ let consumed = false;
160
+ let res;
161
+ const totalTimer = setTimeout(() => {
162
+ totalTripped = true;
163
+ controller.abort();
164
+ if (!consumed) {
165
+ try {
166
+ void res?.body?.cancel().catch(() => { });
167
+ }
168
+ catch { /* ignore */ }
169
+ }
170
+ }, options.timeoutMs);
171
+ const idleMessage = () => `Upstream ${provider} stream idle for ${options.idleTimeoutMs}ms — aborted`;
172
+ /**
173
+ * One I/O wait, bounded by the idle budget. The deadline is a RACE, not just
174
+ * an `abort()`: abort settles a pending body read (verified on the Bun
175
+ * runtime) but it interrupts I/O, not a suspended caller — and it cannot be
176
+ * armed before the response head exists. Racing gives the provider leg one
177
+ * mechanism for "no bytes for an idle budget", covering the head wait (which
178
+ * otherwise had no deadline until the total timeout), the SSE body loop and
179
+ * the buffered-body loop.
180
+ */
181
+ const raceIdle = async (pending) => {
182
+ let timer;
183
+ const deadline = new Promise((_, reject) => {
184
+ timer = setTimeout(() => {
185
+ idleTripped = true;
186
+ controller.abort();
187
+ reject(new Error(idleMessage()));
188
+ }, options.idleTimeoutMs);
189
+ // Ref'd on purpose: under Bun an unref'd deadline with no other ref handle
190
+ // never fires, leaving the head wait / SSE body loop parked forever.
191
+ // `finally { clearTimeout(timer) }` below keeps its lifetime bounded.
192
+ });
193
+ try {
194
+ return await Promise.race([pending, deadline]);
195
+ }
196
+ finally {
197
+ clearTimeout(timer);
198
+ }
199
+ };
200
+ try {
201
+ res = await withUpstreamFailureGuard(upstreamEventContext, exchangeId, url, 'POST', () => raceIdle(proxiedFetch(url, {
202
+ method: 'POST', headers, body, signal: controller.signal,
203
+ }, { provider, model: model.id })), model.upstreamModel);
204
+ if (!res.ok || !res.body) {
205
+ let errorText;
206
+ try {
207
+ errorText = await readBoundedBodyText(res, STREAM_CAPTURE_CAP, raceIdle);
208
+ }
209
+ catch (err) {
210
+ emitUpstreamFailureOnce(upstreamEventContext, {
211
+ model: model.upstreamModel, exchangeId, url, method: 'POST',
212
+ status: res.status, statusText: res.statusText,
213
+ error: `Streaming error body read failed: ${err?.message ?? err}`,
214
+ });
215
+ throw err;
216
+ }
217
+ const safe = redactUpstreamBody(errorText, headers);
218
+ emitUpstreamFailureOnce(upstreamEventContext, {
219
+ model: model.upstreamModel, exchangeId, url, method: 'POST',
220
+ status: res.status, statusText: res.statusText,
221
+ responseHeaders: res.headers, responseBody: safe,
222
+ error: `Upstream ${res.status}`,
223
+ });
224
+ throw new UpstreamError({
225
+ message: `Upstream ${provider} [${label}] returned status ${res.status}: ${safe}`,
226
+ status: res.status,
227
+ errorBody: safe,
228
+ provider,
229
+ modelId: model.id,
230
+ retryAfterSeconds: parseRetryAfter(res.headers.get('retry-after')),
231
+ });
232
+ }
233
+ }
234
+ catch (err) {
235
+ clearTimeout(totalTimer);
236
+ throw err;
237
+ }
238
+ const response = res;
239
+ const responseBody = response.body;
240
+ return {
241
+ async *[Symbol.asyncIterator]() {
242
+ consumed = true;
243
+ const reader = responseBody.getReader();
244
+ // One body read under the idle deadline; `armIdle` used to re-arm a timer
245
+ // that only aborted — this both arms it and guarantees the wait itself ends.
246
+ const readIdle = () => raceIdle(reader.read());
247
+ const bytes = new TextDecoder('utf-8');
248
+ const parser = new SseParser();
249
+ const decoder = options.createDecoder();
250
+ const rawParts = [];
251
+ let rawBytes = 0;
252
+ let rawCapped = false;
253
+ let captured = false;
254
+ let firstByteTs;
255
+ let finished = false;
256
+ let reachedEof = false;
257
+ const appendRaw = (piece) => {
258
+ if (piece.length && firstByteTs === undefined)
259
+ firstByteTs = Date.now();
260
+ if (!piece || rawCapped)
261
+ return;
262
+ const pieceBytes = Buffer.byteLength(piece, 'utf8');
263
+ if (rawBytes + pieceBytes > STREAM_CAPTURE_CAP) {
264
+ const combined = rawParts.join('') + piece;
265
+ rawParts.length = 0;
266
+ rawParts.push(`${Buffer.from(combined, 'utf8').subarray(0, STREAM_CAPTURE_CAP).toString('utf8')}...[TRUNCATED]`);
267
+ rawBytes = STREAM_CAPTURE_CAP;
268
+ rawCapped = true;
269
+ return;
270
+ }
271
+ rawParts.push(piece);
272
+ rawBytes += pieceBytes;
273
+ };
274
+ const capture = (error) => {
275
+ if (captured || !exchangeId)
276
+ return;
277
+ captured = true;
278
+ const event = {
279
+ exchangeId, url, method: 'POST', status: response.status, statusText: response.statusText,
280
+ responseHeaders: response.headers, responseBody: rawParts.join(''), firstByteTs, model: model.upstreamModel,
281
+ };
282
+ if (error)
283
+ emitUpstreamFailureOnce(upstreamEventContext, { ...event, error: redactUpstreamBody(error, headers) });
284
+ else
285
+ emitUpstreamResponseOnce(upstreamEventContext, event);
286
+ };
287
+ const sanitizeStreamEvent = (ev) => {
288
+ if (ev.type === 'error') {
289
+ return { ...ev, message: redactUpstreamBody(ev.message, headers) };
290
+ }
291
+ if (ev.type === 'response.failed') {
292
+ return {
293
+ ...ev,
294
+ ...(ev.reason ? { reason: redactUpstreamBody(ev.reason, headers) } : {}),
295
+ ...(ev.error ? { error: { ...ev.error, message: redactUpstreamBody(ev.error.message, headers) } } : {}),
296
+ };
297
+ }
298
+ return ev;
299
+ };
300
+ const decodeFrame = function* (data) {
301
+ if (data.trim() === '[DONE]') {
302
+ for (const ev of decoder.finish())
303
+ yield sanitizeStreamEvent(ev);
304
+ finished = true;
305
+ return true;
306
+ }
307
+ if (!data.trim())
308
+ return false;
309
+ let payload;
310
+ try {
311
+ payload = JSON.parse(data);
312
+ }
313
+ catch {
314
+ throw new Error(`Upstream ${provider} sent malformed JSON in an SSE data frame.`);
315
+ }
316
+ for (const ev of decoder.push(payload))
317
+ yield sanitizeStreamEvent(ev);
318
+ return false;
319
+ };
320
+ try {
321
+ if (!(response.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream')) {
322
+ let json = '';
323
+ const appendJson = (chunk) => {
324
+ json += chunk;
325
+ if (json.length > STREAM_SSE_FRAME_MAX_CHARS) {
326
+ throw new Error(`Upstream non-SSE body exceeded ${STREAM_SSE_FRAME_MAX_CHARS} characters.`);
327
+ }
328
+ };
329
+ while (true) {
330
+ const { done, value } = await readIdle();
331
+ if (done) {
332
+ reachedEof = true;
333
+ break;
334
+ }
335
+ const decoded = bytes.decode(value, { stream: true });
336
+ appendRaw(decoded);
337
+ appendJson(decoded);
338
+ }
339
+ const tail = bytes.decode();
340
+ appendRaw(tail);
341
+ appendJson(tail);
342
+ let completion;
343
+ try {
344
+ completion = JSON.parse(json);
345
+ }
346
+ catch {
347
+ throw new Error(`Upstream ${provider} answered a non-SSE body that is not valid JSON.`);
348
+ }
349
+ yield* canonicalResponseToEvents(options.parseBuffered(completion));
350
+ finished = true;
351
+ return;
352
+ }
353
+ let sawDone = false;
354
+ reachedEof = false;
355
+ while (!sawDone) {
356
+ const { done, value } = await readIdle();
357
+ if (done) {
358
+ reachedEof = true;
359
+ break;
360
+ }
361
+ const decoded = bytes.decode(value, { stream: true });
362
+ appendRaw(decoded);
363
+ for (const frame of parser.push(decoded)) {
364
+ // A native terminal need not be the last byte: usage/message_stop
365
+ // can follow it, so only EOF or [DONE] ends the IO loop.
366
+ yield* decodeFrame(frame.data);
367
+ if (frame.data.trim() === '[DONE]') {
368
+ sawDone = true;
369
+ break;
370
+ }
371
+ }
372
+ }
373
+ if (!sawDone) {
374
+ appendRaw(bytes.decode());
375
+ for (const frame of parser.finish()) {
376
+ const stop = yield* decodeFrame(frame.data);
377
+ if (stop)
378
+ sawDone = true;
379
+ }
380
+ }
381
+ if (!sawDone && !decoder.terminated) {
382
+ throw new Error(`Upstream ${provider} stream ended before completion.`);
383
+ }
384
+ if (!finished)
385
+ yield* decoder.finish();
386
+ finished = true;
387
+ }
388
+ catch (err) {
389
+ if (idleTripped) {
390
+ const message = idleMessage();
391
+ capture(message);
392
+ throw new Error(message, { cause: err });
393
+ }
394
+ if (totalTripped) {
395
+ const message = `Upstream ${provider} stream exceeded the total timeout of ${options.timeoutMs}ms — aborted`;
396
+ capture(message);
397
+ throw new Error(message, { cause: err });
398
+ }
399
+ capture(`Stream aborted: ${err?.message ?? err}`);
400
+ throw err;
401
+ }
402
+ finally {
403
+ clearTimeout(totalTimer);
404
+ if (!finished) {
405
+ controller.abort();
406
+ }
407
+ if (!finished || !reachedEof) {
408
+ try {
409
+ await reader.cancel();
410
+ }
411
+ catch { /* The peer may already be gone. */ }
412
+ }
413
+ // A deadline that won the race leaves its read request in flight until
414
+ // the abort above settles it; releasing a still-locked reader throws.
415
+ try {
416
+ reader.releaseLock();
417
+ }
418
+ catch { /* Still settling — the abort owns it. */ }
419
+ capture();
420
+ }
421
+ },
422
+ };
423
+ }
@@ -11,7 +11,7 @@ import type { ComboConfig, TiersConfig, TierMemberRule } from '../config/types.j
11
11
  * need a single tier value (pinned-model force_tier, tier-keyed reporting,
12
12
  * model-access tier expansion) `claimModel` derives the home tier: the first
13
13
  * claim in tier order lite → plus → pro → ultra. Nothing matched →
14
- * `'unclassified'` (fourth state, no pool).
14
+ * `'unclassified'` (fourth state, no pool, no home tier).
15
15
  *
16
16
  * `combo:<id>` rules are the one sanctioned indirection: declared references
17
17
  * that expand IN PLACE into the combo's registered members at every commit /
@@ -19,10 +19,9 @@ import type { ComboConfig, TiersConfig, TierMemberRule } from '../config/types.j
19
19
  * path never resolves refs, and later combo edits follow into the tier at the
20
20
  * next commit. A combo may be referenced by any number of tiers.
21
21
  *
22
- * The classifier (tier-match.ts) stays alive as the SUGGESTION engine —
23
- * it feeds catalog-page recommendations, the /tiers ephemeral preview and
24
- * save-time checks, but NEVER routing and NEVER seeding (DEFAULT_CONFIG.tiers
25
- * ships four EMPTY pools — no member defaults exist to seed from).
22
+ * These lists are the ONE membership source: nothing classifies a model by
23
+ * price band, name glob or capability flag any more, and nothing seeds the
24
+ * pools (DEFAULT_CONFIG.tiers ships four EMPTY pools).
26
25
  */
27
26
  export declare const MEMBER_TIER_ORDER: TierLevel[];
28
27
  /** Descending tier order (highest first) — the cross-tier effort-search fallback. */
@@ -11,7 +11,7 @@ import { EFFORT_LADDER } from '../types/router.js';
11
11
  * need a single tier value (pinned-model force_tier, tier-keyed reporting,
12
12
  * model-access tier expansion) `claimModel` derives the home tier: the first
13
13
  * claim in tier order lite → plus → pro → ultra. Nothing matched →
14
- * `'unclassified'` (fourth state, no pool).
14
+ * `'unclassified'` (fourth state, no pool, no home tier).
15
15
  *
16
16
  * `combo:<id>` rules are the one sanctioned indirection: declared references
17
17
  * that expand IN PLACE into the combo's registered members at every commit /
@@ -19,10 +19,9 @@ import { EFFORT_LADDER } from '../types/router.js';
19
19
  * path never resolves refs, and later combo edits follow into the tier at the
20
20
  * next commit. A combo may be referenced by any number of tiers.
21
21
  *
22
- * The classifier (tier-match.ts) stays alive as the SUGGESTION engine —
23
- * it feeds catalog-page recommendations, the /tiers ephemeral preview and
24
- * save-time checks, but NEVER routing and NEVER seeding (DEFAULT_CONFIG.tiers
25
- * ships four EMPTY pools — no member defaults exist to seed from).
22
+ * These lists are the ONE membership source: nothing classifies a model by
23
+ * price band, name glob or capability flag any more, and nothing seeds the
24
+ * pools (DEFAULT_CONFIG.tiers ships four EMPTY pools).
26
25
  */
27
26
  export const MEMBER_TIER_ORDER = ['lite', 'plus', 'pro', 'ultra'];
28
27
  /** Descending tier order (highest first) — the cross-tier effort-search fallback. */
@@ -0,0 +1,13 @@
1
+ import { LLMProvider, type UpstreamEventContext, type CallCredential } from './base.js';
2
+ import type { ModelRegistration, ProviderConfig } from '../config/types.js';
3
+ import type { CanonicalRequest, CanonicalResponse, StreamEvent } from '../ir/types.js';
4
+ export declare class OpenAIChatProvider implements LLMProvider {
5
+ name: string;
6
+ private config;
7
+ constructor(config: ProviderConfig);
8
+ private headers;
9
+ /** One explicit, adapter-owned whitelist feeds both buffered and streaming calls. */
10
+ private payload;
11
+ createCompletion(request: CanonicalRequest, model: ModelRegistration, upstreamEventContext?: UpstreamEventContext, credential?: CallCredential): Promise<CanonicalResponse>;
12
+ createStream(request: CanonicalRequest, model: ModelRegistration, upstreamEventContext?: UpstreamEventContext, credential?: CallCredential): Promise<AsyncIterable<StreamEvent>>;
13
+ }
@@ -0,0 +1,99 @@
1
+ import { chatResponseToIR, irToChatRequest } from '../ir/adapters/openai-chat.js';
2
+ import { ChatStreamDecoder } from '../ir/adapters/openai-chat-stream.js';
3
+ import { postProviderJson, setDefaultHeaderCaseInsensitive, setHeaderCaseInsensitive } from './http-json.js';
4
+ import { postProviderStream } from './http-stream.js';
5
+ import { DEFAULT_PROVIDER_TIMEOUT_MS, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_STREAM_TIMEOUT_MS, } from '../config/defaults.js';
6
+ /**
7
+ * The long tail of OpenAI-compatible servers accepts system but not developer.
8
+ * Defense in depth only: `irToChatRequest` already folds every system/developer
9
+ * block into ONE system message, so this rewrite is normally a no-op and the
10
+ * `supportsDeveloperRole` opt-out is inert. It still guards a future adapter
11
+ * that emits a developer message without going through the folding path.
12
+ */
13
+ function normalizeDeveloperRole(request) {
14
+ if (request.messages.some((message) => message.role === 'developer')) {
15
+ return {
16
+ ...request,
17
+ messages: request.messages.map((message) => message.role === 'developer'
18
+ ? { ...message, role: 'system' }
19
+ : message),
20
+ };
21
+ }
22
+ return request;
23
+ }
24
+ export class OpenAIChatProvider {
25
+ name;
26
+ config;
27
+ constructor(config) {
28
+ this.name = config.name;
29
+ this.config = config;
30
+ }
31
+ headers(credential) {
32
+ const headers = {
33
+ ...this.config.headers,
34
+ };
35
+ setDefaultHeaderCaseInsensitive(headers, 'Content-Type', 'application/json');
36
+ setHeaderCaseInsensitive(headers, 'Authorization', `Bearer ${credential?.key ?? this.config.apiKey}`);
37
+ if (this.config.organization)
38
+ setHeaderCaseInsensitive(headers, 'OpenAI-Organization', this.config.organization);
39
+ return headers;
40
+ }
41
+ /** One explicit, adapter-owned whitelist feeds both buffered and streaming calls. */
42
+ payload(request, model, stream) {
43
+ let chat = irToChatRequest(request, model.upstreamModel, { carrierExtensions: false });
44
+ if (model.supportsDeveloperRole !== true)
45
+ chat = normalizeDeveloperRole(chat);
46
+ if (model.temperature === false)
47
+ delete chat.temperature;
48
+ if (!stream)
49
+ delete chat.stream_options;
50
+ return {
51
+ ...chat,
52
+ model: model.upstreamModel,
53
+ stream,
54
+ ...(stream ? { stream_options: { include_usage: true } } : {}),
55
+ };
56
+ }
57
+ async createCompletion(request, model, upstreamEventContext, credential) {
58
+ const payload = this.payload(request, model, false);
59
+ const data = await postProviderJson({
60
+ url: `${this.config.baseUrl.replace(/\/+$/, '')}/chat/completions`,
61
+ headers: this.headers(credential),
62
+ payload,
63
+ model,
64
+ provider: this.name,
65
+ label: 'chat',
66
+ timeoutMs: this.config.timeoutMs || DEFAULT_PROVIDER_TIMEOUT_MS,
67
+ upstreamEventContext,
68
+ });
69
+ return chatResponseToIR(data);
70
+ }
71
+ async createStream(request, model, upstreamEventContext, credential) {
72
+ return postProviderStream({
73
+ url: `${this.config.baseUrl.replace(/\/+$/, '')}/chat/completions`,
74
+ headers: this.headers(credential),
75
+ payload: this.payload(request, model, true),
76
+ model,
77
+ provider: this.name,
78
+ label: 'chat',
79
+ timeoutMs: this.config.streamTimeoutMs || DEFAULT_STREAM_TIMEOUT_MS,
80
+ idleTimeoutMs: this.config.streamIdleTimeoutMs || DEFAULT_STREAM_IDLE_TIMEOUT_MS,
81
+ upstreamEventContext,
82
+ createDecoder: () => {
83
+ const decoder = new ChatStreamDecoder();
84
+ let terminated = false;
85
+ return {
86
+ get terminated() { return terminated; },
87
+ push(payload) {
88
+ const chunk = payload;
89
+ if (chunk.choices?.some((choice) => choice.finish_reason))
90
+ terminated = true;
91
+ return decoder.push(chunk);
92
+ },
93
+ finish: () => decoder.finish(),
94
+ };
95
+ },
96
+ parseBuffered: (body) => chatResponseToIR(body),
97
+ });
98
+ }
99
+ }
@@ -1,10 +1,13 @@
1
1
  import { LLMProvider, type UpstreamEventContext, type CallCredential } from './base.js';
2
- import { ModelRegistration, ProviderConfig } from '../config/types.js';
3
- import { ChatCompletionChunk, ChatCompletionRequest, ChatCompletionResponse } from '../types/openai.js';
2
+ import type { ModelRegistration, ProviderConfig } from '../config/types.js';
3
+ import type { CanonicalRequest, CanonicalResponse, StreamEvent } from '../ir/types.js';
4
4
  export declare class OpenAICompatibleProvider implements LLMProvider {
5
5
  name: string;
6
6
  private config;
7
7
  constructor(config: ProviderConfig);
8
- createCompletion(request: ChatCompletionRequest, model: ModelRegistration, upstreamEventContext?: UpstreamEventContext, credential?: CallCredential): Promise<ChatCompletionResponse>;
9
- createStream(request: ChatCompletionRequest, model: ModelRegistration, upstreamEventContext?: UpstreamEventContext, credential?: CallCredential): Promise<AsyncIterable<ChatCompletionChunk>>;
8
+ private headers;
9
+ /** One explicit, adapter-owned whitelist feeds both buffered and streaming calls. */
10
+ private payload;
11
+ createCompletion(request: CanonicalRequest, model: ModelRegistration, upstreamEventContext?: UpstreamEventContext, credential?: CallCredential): Promise<CanonicalResponse>;
12
+ createStream(request: CanonicalRequest, model: ModelRegistration, upstreamEventContext?: UpstreamEventContext, credential?: CallCredential): Promise<AsyncIterable<StreamEvent>>;
10
13
  }