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
@@ -1,33 +1,22 @@
1
- import { UpstreamError } from '../resilience/error-classifier.js';
2
- import { proxiedFetch, resolveProxyUrl } from '../utils/proxy.js';
3
- import { DEFAULT_PROVIDER_TIMEOUT_MS } from '../config/defaults.js';
4
- import { emitUpstreamRequestOnce, emitUpstreamResponseOnce, emitUpstreamFailureOnce, withUpstreamFailureGuard, } from '../observability/upstream-events.js';
1
+ import { chatResponseToIR, irToChatRequest } from '../ir/adapters/chat.js';
2
+ import { ChatStreamDecoder } from '../ir/stream.js';
3
+ import { postProviderJson } 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';
5
6
  /**
6
- * Upper bound on the raw SSE bytes kept in memory for one streamed exchange's
7
- * capture event. The recorder truncates every body at `maxBodyBytes` (256 KB by
8
- * default) when writing the JSONL line, so retaining more than a few multiples
9
- * of that budget buys the archive nothing — it is purely a memory guard for
10
- * long agent-loop streams.
7
+ * The long tail of OpenAI-compatible servers accepts system but not developer.
8
+ * Catalogs can opt a model into the native role; the safe default is system.
11
9
  */
12
- const STREAM_CAPTURE_CAP = 256 * 1024;
13
- /**
14
- * Role-compatibility rewrite for this wire. The OpenAI `developer` role
15
- * (introduced with the o1 series) is accepted by OpenAI official endpoints,
16
- * but the long tail of OpenAI-compatible servers (DeepSeek, Qwen, Kimi,
17
- * vLLM, llama.cpp, Gemini-compat, ...) only knows `system` and answers a
18
- * `developer` message with a 400 invalid role. No catalog source publishes
19
- * per-model role support, so the SAFE DEFAULT is to rewrite
20
- * `developer` → `system` — semantically lossless: `developer` IS the renamed
21
- * `system` per the OpenAI model spec (gpt-4o even auto-converts it
22
- * server-side), and every current OpenAI chat model accepts `system`.
23
- * A model opts out via `supportsDeveloperRole: true` (overrides.json) when an
24
- * upstream rejects `system` or must see the role verbatim. Message order and
25
- * content are preserved; only the role tag changes.
26
- */
27
- function normalizeDeveloperRole(messages) {
28
- if (!Array.isArray(messages) || !messages.some((m) => m?.role === 'developer'))
29
- return messages;
30
- return messages.map((m) => (m && m.role === 'developer' ? { ...m, role: 'system' } : m));
10
+ function normalizeDeveloperRole(request) {
11
+ if (request.messages.some((message) => message.role === 'developer')) {
12
+ return {
13
+ ...request,
14
+ messages: request.messages.map((message) => message.role === 'developer'
15
+ ? { ...message, role: 'system' }
16
+ : message),
17
+ };
18
+ }
19
+ return request;
31
20
  }
32
21
  export class OpenAICompatibleProvider {
33
22
  name;
@@ -36,358 +25,72 @@ export class OpenAICompatibleProvider {
36
25
  this.name = config.name;
37
26
  this.config = config;
38
27
  }
39
- async createCompletion(request, model, upstreamEventContext, credential) {
40
- const url = `${this.config.baseUrl.replace(/\/+$/, '')}/chat/completions`;
28
+ headers(credential) {
41
29
  const headers = {
42
30
  'Content-Type': 'application/json',
43
- // Per-call credential outranks the boot-baked key;
44
- // absent = baked key, byte-identical to every pre-P3 request.
45
31
  Authorization: `Bearer ${credential?.key ?? this.config.apiKey}`,
46
32
  ...this.config.headers,
47
33
  };
48
- if (this.config.organization) {
34
+ if (this.config.organization)
49
35
  headers['OpenAI-Organization'] = this.config.organization;
50
- }
51
- const payload = {
52
- ...request,
53
- model: model.upstreamModel,
54
- stream: false,
55
- };
56
- delete payload.router_options;
57
- // A streamed client on THIS wire is served by createStream (frames relayed
58
- // as they arrive). This method is the buffered leg: an inbound surface with
59
- // no chunk encoder, the schema-assertion cascade, mock mode, a client that
60
- // did not ask for a stream, or `streaming.enabled:false`. A client-sent
61
- // stream_options must never leak into this payload — strict upstreams (e.g.
62
- // Alibaba) reject stream_options without stream:true with a 400.
63
- delete payload.stream_options;
64
- // Models the catalog marks temperature:false (next-gen Claude etc.) reject
65
- // sampling params — strip them from the passthrough payload to avoid an
66
- // upstream 400 invalid_request_error.
67
- if (model.temperature === false)
68
- delete payload.temperature;
69
- // Role compatibility: unless the model is declared to accept the OpenAI
70
- // `developer` role, rewrite it to `system` (see normalizeDeveloperRole).
36
+ return headers;
37
+ }
38
+ /** One explicit, adapter-owned whitelist feeds both buffered and streaming calls. */
39
+ payload(request, model, stream) {
40
+ let chat = irToChatRequest(request, model.upstreamModel, { carrierExtensions: false });
71
41
  if (model.supportsDeveloperRole !== true)
72
- payload.messages = normalizeDeveloperRole(payload.messages);
73
- // reasoning_effort is the OpenAI-standard field; forwarded verbatim.
74
- // `max` (Anthropic's top tier) is not a valid OpenAI value — the
75
- // orchestrator's downgrade step collapses it to `xhigh` (or lower)
76
- // before reaching here, so a stray `max` would only survive if the
77
- // operator explicitly declared `max` in the model's
78
- // supportedReasoningEfforts AND routed it to an OpenAI wire, which
79
- // is a config error and surfaces as a clear 400 from the upstream.
80
- // Event-stream emit BEFORE the fetch fires — independent of the response.
81
- // Pairs with the upstream-response event below via `exchangeId`.
82
- const exchangeId = emitUpstreamRequestOnce(upstreamEventContext, {
83
- url,
84
- method: 'POST',
85
- requestHeaders: headers,
86
- requestBody: JSON.stringify(payload),
42
+ chat = normalizeDeveloperRole(chat);
43
+ if (model.temperature === false)
44
+ delete chat.temperature;
45
+ if (!stream)
46
+ delete chat.stream_options;
47
+ return {
48
+ ...chat,
87
49
  model: model.upstreamModel,
88
- proxy: resolveProxyUrl(url, { provider: this.config.name, model: model.id }),
50
+ stream,
51
+ ...(stream ? { stream_options: { include_usage: true } } : {}),
52
+ };
53
+ }
54
+ async createCompletion(request, model, upstreamEventContext, credential) {
55
+ const payload = this.payload(request, model, false);
56
+ const data = await postProviderJson({
57
+ url: `${this.config.baseUrl.replace(/\/+$/, '')}/chat/completions`,
58
+ headers: this.headers(credential),
59
+ payload,
60
+ model,
61
+ provider: this.name,
62
+ label: 'chat',
63
+ timeoutMs: this.config.timeoutMs || DEFAULT_PROVIDER_TIMEOUT_MS,
64
+ upstreamEventContext,
89
65
  });
90
- const controller = new AbortController();
91
- // Wall-clock cap on the buffered upstream execution (the gateway awaits the
92
- // full response, then the surface encodes it). Agent coding traffic carries
93
- // large contexts and long generations, so a legitimate completion can easily
94
- // run past a minute — 60 s used to cut healthy streams mid-flight and pay for
95
- // them again on retry. The streamed leg applies the same cap across the whole
96
- // SSE body (see createStream).
97
- const timeout = setTimeout(() => controller.abort(), this.config.timeoutMs || DEFAULT_PROVIDER_TIMEOUT_MS);
98
- try {
99
- // The guard emits a paired failure response event on ANY thrown error
100
- // (network / DNS / TLS / abort / UpstreamError) so console readers
101
- // never see a dangling request event without a matching response.
102
- const res = await withUpstreamFailureGuard(upstreamEventContext, exchangeId, url, 'POST', () => proxiedFetch(url, {
103
- method: 'POST',
104
- headers,
105
- body: JSON.stringify(payload),
106
- signal: controller.signal,
107
- }, { provider: this.config.name, model: model.id }), model.upstreamModel);
108
- if (!res.ok) {
109
- // Body read can fail mid-stream (connection reset) — pair the request
110
- // event with a failure response before rethrowing.
111
- let errorText;
112
- try {
113
- errorText = await res.text();
114
- }
115
- catch (err) {
116
- emitUpstreamFailureOnce(upstreamEventContext, {
117
- model: model.upstreamModel,
118
- exchangeId,
119
- url,
120
- method: 'POST',
121
- status: res.status,
122
- statusText: res.statusText,
123
- error: `Response body read failed: ${err?.message ?? err}`,
124
- });
125
- throw err;
126
- }
127
- const retryAfterHeader = res.headers.get('retry-after');
128
- const retryAfterSeconds = retryAfterHeader ? parseInt(retryAfterHeader, 10) : undefined;
129
- emitUpstreamFailureOnce(upstreamEventContext, {
130
- model: model.upstreamModel,
131
- exchangeId,
132
- url,
133
- method: 'POST',
134
- status: res.status,
135
- statusText: res.statusText,
136
- responseHeaders: res.headers,
137
- responseBody: errorText,
138
- error: `Upstream ${res.status}`,
139
- });
140
- throw new UpstreamError({
141
- message: `Upstream ${this.name} returned status ${res.status}: ${errorText}`,
142
- status: res.status,
143
- errorBody: errorText,
144
- provider: this.name,
145
- modelId: model.id,
146
- retryAfterSeconds: isNaN(retryAfterSeconds) ? undefined : retryAfterSeconds,
147
- });
148
- }
149
- // Emit the response event the moment the body BYTES arrive — before
150
- // JSON.parse (see anthropic.ts for the rationale). The raw text body
151
- // preserves any whitespace / numeric-precision quirks the upstream
152
- // added.
153
- let rawBody;
154
- try {
155
- rawBody = await res.text();
156
- }
157
- catch (err) {
158
- emitUpstreamFailureOnce(upstreamEventContext, {
159
- model: model.upstreamModel,
160
- exchangeId,
161
- url,
162
- method: 'POST',
163
- status: res.status,
164
- statusText: res.statusText,
165
- error: `Response body read failed: ${err?.message ?? err}`,
166
- });
167
- throw err;
168
- }
169
- emitUpstreamResponseOnce(upstreamEventContext, {
170
- model: model.upstreamModel,
171
- exchangeId,
172
- url,
173
- method: 'POST',
174
- status: res.status,
175
- statusText: res.statusText,
176
- responseHeaders: res.headers,
177
- responseBody: rawBody,
178
- });
179
- const json = JSON.parse(rawBody);
180
- return json;
181
- }
182
- finally {
183
- clearTimeout(timeout);
184
- }
66
+ return chatResponseToIR(data);
185
67
  }
186
68
  async createStream(request, model, upstreamEventContext, credential) {
187
- const url = `${this.config.baseUrl.replace(/\/+$/, '')}/chat/completions`;
188
- const headers = {
189
- 'Content-Type': 'application/json',
190
- // Same per-call credential rule as createCompletion above.
191
- Authorization: `Bearer ${credential?.key ?? this.config.apiKey}`,
192
- ...this.config.headers,
193
- };
194
- const payload = {
195
- ...request,
196
- model: model.upstreamModel,
197
- stream: true,
198
- stream_options: { include_usage: true },
199
- };
200
- delete payload.router_options;
201
- // Models the catalog marks temperature:false — strip the param (same as the non-streaming path).
202
- if (model.temperature === false)
203
- delete payload.temperature;
204
- // Role compatibility: same rewrite as the buffered path (see normalizeDeveloperRole).
205
- if (model.supportsDeveloperRole !== true)
206
- payload.messages = normalizeDeveloperRole(payload.messages);
207
- // reasoning_effort is the OpenAI-standard field; forwarded verbatim.
208
- if (request.reasoning_effort)
209
- payload.reasoning_effort = request.reasoning_effort;
210
- // Event-stream emit BEFORE the fetch fires — same discipline as
211
- // createCompletion above, so a streamed turn is captured as a full
212
- // request/response pair instead of a dangling request line.
213
- const exchangeId = emitUpstreamRequestOnce(upstreamEventContext, {
214
- url,
215
- method: 'POST',
216
- requestHeaders: headers,
217
- requestBody: JSON.stringify(payload),
218
- model: model.upstreamModel,
219
- proxy: resolveProxyUrl(url, { provider: this.config.name, model: model.id }),
220
- });
221
- const controller = new AbortController();
222
- // Wall-clock cap, identical in kind to the non-streaming path. It aborts
223
- // MID-STREAM when generation runs long: by then the relay has committed
224
- // bytes to the client, so the pipeline closes the SSE without `[DONE]`
225
- // rather than failing over (re-issuing upstream would duplicate output).
226
- const timeout = setTimeout(() => controller.abort(), this.config.timeoutMs || DEFAULT_PROVIDER_TIMEOUT_MS);
227
- let res;
228
- try {
229
- res = await withUpstreamFailureGuard(upstreamEventContext, exchangeId, url, 'POST', () => proxiedFetch(url, {
230
- method: 'POST',
231
- headers,
232
- body: JSON.stringify(payload),
233
- signal: controller.signal,
234
- }, { provider: this.config.name, model: model.id }), model.upstreamModel);
235
- if (!res.ok || !res.body) {
236
- let errorText;
237
- try {
238
- errorText = await res.text();
239
- }
240
- catch (err) {
241
- emitUpstreamFailureOnce(upstreamEventContext, {
242
- model: model.upstreamModel,
243
- exchangeId,
244
- url,
245
- method: 'POST',
246
- status: res.status,
247
- statusText: res.statusText,
248
- error: `Streaming error body read failed: ${err?.message ?? err}`,
249
- });
250
- throw err;
251
- }
252
- const retryAfterHeader = res.headers.get('retry-after');
253
- const retryAfterSeconds = retryAfterHeader ? parseInt(retryAfterHeader, 10) : undefined;
254
- emitUpstreamFailureOnce(upstreamEventContext, {
255
- model: model.upstreamModel,
256
- exchangeId,
257
- url,
258
- method: 'POST',
259
- status: res.status,
260
- statusText: res.statusText,
261
- responseHeaders: res.headers,
262
- responseBody: errorText,
263
- error: `Upstream ${res.status}`,
264
- });
265
- // UpstreamError (not a bare Error) keeps the classifier's status /
266
- // retry-after / credential attribution working on the streaming leg too
267
- // — a 429 head must trip the same breaker path as on the buffered leg.
268
- throw new UpstreamError({
269
- message: `Upstream ${this.name} returned status ${res.status}: ${errorText}`,
270
- status: res.status,
271
- errorBody: errorText,
272
- provider: this.name,
273
- modelId: model.id,
274
- retryAfterSeconds: isNaN(retryAfterSeconds) ? undefined : retryAfterSeconds,
275
- });
276
- }
277
- }
278
- catch (err) {
279
- // No readable body ever materialized — release the timer, the generator
280
- // below is the only other owner of it.
281
- clearTimeout(timeout);
282
- throw err;
283
- }
284
- const reader = res.body.getReader();
285
- const decoder = new TextDecoder('utf-8');
286
- // Captured before the object literal below: inside `*[Symbol.asyncIterator]`
287
- // `this` is the iterable, not the provider.
288
- const providerName = this.name;
289
- return {
290
- async *[Symbol.asyncIterator]() {
291
- let buffer = '';
292
- // Raw wire bytes accumulated for the capture event only, capped — the
293
- // recorder truncates at maxBodyBytes anyway, so holding a multi-megabyte
294
- // stream in memory would be pure cost for zero extra evidence.
295
- let raw = '';
296
- let rawCapped = false;
297
- let captured = false;
298
- let sawDone = false;
299
- let sawFinishReason = false;
300
- // First streamed body chunk — the capture plane's TTFT anchor (the
301
- // event ts is response-received, so without this stamp the wait and
302
- // decode phases of a stream are indistinguishable).
303
- let firstByteTs;
304
- const appendRaw = (piece) => {
305
- if (firstByteTs === undefined && piece.length > 0)
306
- firstByteTs = Date.now();
307
- if (rawCapped)
308
- return;
309
- raw += piece;
310
- if (raw.length > STREAM_CAPTURE_CAP) {
311
- raw = raw.slice(0, STREAM_CAPTURE_CAP) + '...[TRUNCATED]';
312
- rawCapped = true;
313
- }
314
- };
315
- /** Exactly one response event per streamed exchange (cp-failfast: paired, never dangling). */
316
- const capture = (error) => {
317
- if (captured || !exchangeId)
318
- return;
319
- captured = true;
320
- const base = {
321
- exchangeId,
322
- url,
323
- method: 'POST',
324
- status: res.status,
325
- statusText: res.statusText,
326
- responseHeaders: res.headers,
327
- responseBody: raw,
328
- firstByteTs,
329
- model: model.upstreamModel,
330
- };
331
- if (error)
332
- emitUpstreamFailureOnce(upstreamEventContext, { ...base, error });
333
- else
334
- emitUpstreamResponseOnce(upstreamEventContext, base);
69
+ return postProviderStream({
70
+ url: `${this.config.baseUrl.replace(/\/+$/, '')}/chat/completions`,
71
+ headers: this.headers(credential),
72
+ payload: this.payload(request, model, true),
73
+ model,
74
+ provider: this.name,
75
+ label: 'chat',
76
+ timeoutMs: this.config.streamTimeoutMs || DEFAULT_STREAM_TIMEOUT_MS,
77
+ idleTimeoutMs: this.config.streamIdleTimeoutMs || DEFAULT_STREAM_IDLE_TIMEOUT_MS,
78
+ upstreamEventContext,
79
+ createDecoder: () => {
80
+ const decoder = new ChatStreamDecoder();
81
+ let terminated = false;
82
+ return {
83
+ get terminated() { return terminated; },
84
+ push(payload) {
85
+ const chunk = payload;
86
+ if (chunk.choices?.some((choice) => choice.finish_reason))
87
+ terminated = true;
88
+ return decoder.push(chunk);
89
+ },
90
+ finish: () => decoder.finish(),
335
91
  };
336
- try {
337
- while (true) {
338
- const { done, value } = await reader.read();
339
- if (done)
340
- break;
341
- const decoded = decoder.decode(value, { stream: true });
342
- appendRaw(decoded);
343
- buffer += decoded;
344
- const lines = buffer.split('\n');
345
- buffer = lines.pop() || '';
346
- for (const line of lines) {
347
- const trimmed = line.trim();
348
- if (!trimmed || trimmed.startsWith(':'))
349
- continue;
350
- if (trimmed === 'data: [DONE]') {
351
- sawDone = true;
352
- return;
353
- }
354
- if (trimmed.startsWith('data: ')) {
355
- try {
356
- const chunk = JSON.parse(trimmed.slice(6));
357
- if (chunk.choices?.some((c) => c.finish_reason))
358
- sawFinishReason = true;
359
- yield chunk;
360
- }
361
- catch {
362
- // Ignore parse errors on partial lines
363
- }
364
- }
365
- }
366
- }
367
- // TRUNCATION GUARD. A body that simply stops is indistinguishable
368
- // from a clean end at the reader level, and silently assembling it
369
- // into `{content: null, finish_reason: 'stop'}` would bill a garbage
370
- // turn as a success. A stream is complete only if it said so — via a
371
- // finish_reason frame or [DONE] (some compatible-mode upstreams close
372
- // right after finish_reason without ever sending [DONE]).
373
- if (!sawDone && !sawFinishReason) {
374
- throw new Error(`Upstream ${providerName} stream ended before completion`);
375
- }
376
- }
377
- catch (err) {
378
- capture(`Stream aborted: ${err?.message ?? err}`);
379
- throw err;
380
- }
381
- finally {
382
- // Whether the upstream ever sent `[DONE]` is visible in the captured
383
- // raw body itself — the exchange event stays a success event, because
384
- // a stream that ends after a finish_reason chunk is a complete answer
385
- // for some compatible-mode upstreams and a failed one must not be
386
- // mislabelled as such here.
387
- capture();
388
- clearTimeout(timeout);
389
- }
390
92
  },
391
- };
93
+ parseBuffered: (body) => chatResponseToIR(body),
94
+ });
392
95
  }
393
96
  }
@@ -0,0 +1,12 @@
1
+ import type { LLMProvider, UpstreamEventContext, CallCredential } from './base.js';
2
+ import type { ModelRegistration, ProviderConfig } from '../config/types.js';
3
+ import type { CanonicalRequest, CanonicalResponse, StreamEvent } from '../ir/types.js';
4
+ /** OpenAI Responses upstream. The provider speaks Canonical IR only. */
5
+ export declare class OpenAIResponsesProvider implements LLMProvider {
6
+ name: string;
7
+ private config;
8
+ constructor(config: ProviderConfig);
9
+ private headers;
10
+ createCompletion(request: CanonicalRequest, model: ModelRegistration, upstreamEventContext?: UpstreamEventContext, credential?: CallCredential): Promise<CanonicalResponse>;
11
+ createStream(request: CanonicalRequest, model: ModelRegistration, upstreamEventContext?: UpstreamEventContext, credential?: CallCredential): Promise<AsyncIterable<StreamEvent>>;
12
+ }
@@ -0,0 +1,68 @@
1
+ import { canonicalToResponsesPayload, responsesResponseToIR } from '../ir/adapters/openai-responses.js';
2
+ import { OpenAIResponsesStreamDecoder } from '../ir/adapters/openai-responses-stream.js';
3
+ import { UpstreamError } from '../resilience/error-classifier.js';
4
+ import { DEFAULT_PROVIDER_TIMEOUT_MS, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_STREAM_TIMEOUT_MS, } from '../config/defaults.js';
5
+ import { postProviderJson, setDefaultHeaderCaseInsensitive, setHeaderCaseInsensitive } from './http-json.js';
6
+ import { postProviderStream } from './http-stream.js';
7
+ import { redactUpstreamBody } from '../observability/upstream-body-redaction.js';
8
+ function parseCompletion(data, provider, modelId, headers) {
9
+ if (data.status === 'failed') {
10
+ const safeMessage = redactUpstreamBody(data.error?.message || 'Upstream Responses turn failed.', headers);
11
+ const safeBody = redactUpstreamBody(JSON.stringify(data.error ?? {}), headers);
12
+ throw new UpstreamError({
13
+ message: safeMessage,
14
+ status: 502,
15
+ errorBody: safeBody,
16
+ provider,
17
+ modelId,
18
+ });
19
+ }
20
+ return responsesResponseToIR(data);
21
+ }
22
+ /** OpenAI Responses upstream. The provider speaks Canonical IR only. */
23
+ export class OpenAIResponsesProvider {
24
+ name;
25
+ config;
26
+ constructor(config) {
27
+ this.name = config.name;
28
+ this.config = config;
29
+ }
30
+ headers(credential) {
31
+ const headers = {
32
+ ...this.config.headers,
33
+ };
34
+ setDefaultHeaderCaseInsensitive(headers, 'Content-Type', 'application/json');
35
+ setHeaderCaseInsensitive(headers, 'Authorization', `Bearer ${credential?.key ?? this.config.apiKey}`);
36
+ return headers;
37
+ }
38
+ async createCompletion(request, model, upstreamEventContext, credential) {
39
+ const headers = this.headers(credential);
40
+ const data = await postProviderJson({
41
+ url: `${this.config.baseUrl.replace(/\/+$/, '')}/responses`,
42
+ headers,
43
+ payload: canonicalToResponsesPayload(request, model),
44
+ model,
45
+ provider: this.name,
46
+ label: 'responses',
47
+ timeoutMs: this.config.timeoutMs || DEFAULT_PROVIDER_TIMEOUT_MS,
48
+ upstreamEventContext,
49
+ });
50
+ return parseCompletion(data, this.name, model.id, headers);
51
+ }
52
+ async createStream(request, model, upstreamEventContext, credential) {
53
+ const headers = this.headers(credential);
54
+ return postProviderStream({
55
+ url: `${this.config.baseUrl.replace(/\/+$/, '')}/responses`,
56
+ headers,
57
+ payload: canonicalToResponsesPayload(request, model, true),
58
+ model,
59
+ provider: this.name,
60
+ label: 'responses',
61
+ timeoutMs: this.config.streamTimeoutMs || DEFAULT_STREAM_TIMEOUT_MS,
62
+ idleTimeoutMs: this.config.streamIdleTimeoutMs || DEFAULT_STREAM_IDLE_TIMEOUT_MS,
63
+ upstreamEventContext,
64
+ createDecoder: () => new OpenAIResponsesStreamDecoder(),
65
+ parseBuffered: (body) => parseCompletion(body, this.name, model.id, headers),
66
+ });
67
+ }
68
+ }
@@ -1,10 +1,10 @@
1
1
  import { LLMProvider, type UpstreamEventContext } from './base.js';
2
- import { ModelRegistration } from '../config/types.js';
3
- import { ChatCompletionRequest, ChatCompletionResponse } from '../types/openai.js';
4
- import { OpenCodeServiceConfig } from '../opencode/connector.js';
2
+ import type { ModelRegistration } from '../config/types.js';
3
+ import type { CanonicalRequest, CanonicalResponse } from '../ir/types.js';
4
+ import type { OpenCodeServiceConfig } from '../opencode/connector.js';
5
5
  export declare class OpenCodeProxyProvider implements LLMProvider {
6
- name: string;
7
6
  private config;
7
+ name: string;
8
8
  constructor(config: OpenCodeServiceConfig);
9
- createCompletion(request: ChatCompletionRequest, model: ModelRegistration, upstreamEventContext?: UpstreamEventContext): Promise<ChatCompletionResponse>;
9
+ createCompletion(request: CanonicalRequest, model: ModelRegistration, upstreamEventContext?: UpstreamEventContext): Promise<CanonicalResponse>;
10
10
  }