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,156 +1,22 @@
1
- import crypto from 'node:crypto';
2
- import { emitUpstreamRequestOnce, emitUpstreamResponseOnce, emitUpstreamFailureOnce, withUpstreamFailureGuard, } from '../observability/upstream-events.js';
1
+ import { canonicalToResponsesPayload, responsesResponseToIR } from '../ir/adapters/responses.js';
2
+ import { ResponsesStreamDecoder } from '../ir/adapters/responses-stream.js';
3
3
  import { UpstreamError } from '../resilience/error-classifier.js';
4
- import { proxiedFetch, resolveProxyUrl } from '../utils/proxy.js';
5
- import { DEFAULT_PROVIDER_TIMEOUT_MS } from '../config/defaults.js';
6
- import { chatToolsToResponses } from '../routes/responses.js';
7
- /**
8
- * OpenAI Responses API wire (`@ai-sdk/openai`) — POST {base}/responses.
9
- * Serves providers (or single models, via model-level npm override) that reject
10
- * chat/completions with `ModelProtocolUnsupported` — e.g. Zen's gpt-6-luna.
11
- *
12
- * Tools are fully mapped both directions (2026-10): the pipeline canonicalizes
13
- * tools in the chat-completions (nested) shape; request.tools → payload tools
14
- * re-flattens to the Responses wire (identical flat function shape), assistant
15
- * tool_calls in history →
16
- * function_call items, tool role messages → function_call_output items, and
17
- * upstream function_call output items → chat tool_calls. Without this, a
18
- * /v1/responses tool-loop client routed here would silently lose tool calling.
19
- */
20
- /**
21
- * OpenAI Responses wire shares the same response-header semantics as the
22
- * chat-completions wire (x-ratelimit-*, retry-after, x-request-id) — the
23
- * upstream is the same family. Headers are now sanitized uniformly via
24
- * `sanitizeHeadersForCapture` (full names + credential redaction) so the
25
- * wire-specific extractor is no longer needed.
26
- */
27
- /** Pure payload builder: chat-completions request → OpenAI Responses payload. */
28
- export function buildResponsesPayload(request, model) {
29
- const instructions = [];
30
- const input = [];
31
- for (const msg of request.messages) {
32
- if (msg.role === 'system' || msg.role === 'developer') {
33
- instructions.push(typeof msg.content === 'string' ? msg.content : textOf(msg.content));
34
- continue;
35
- }
36
- if (msg.role === 'tool') {
37
- input.push({
38
- type: 'function_call_output',
39
- call_id: msg.tool_call_id || '',
40
- output: typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content),
41
- });
42
- continue;
43
- }
44
- const role = msg.role === 'assistant' ? 'assistant' : 'user';
45
- if (Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
46
- const text = typeof msg.content === 'string' ? msg.content : textOf(msg.content);
47
- if (text)
48
- input.push({ role, content: text });
49
- for (const tc of msg.tool_calls) {
50
- input.push({ type: 'function_call', call_id: tc.id, name: tc.function.name, arguments: tc.function.arguments });
51
- }
52
- continue;
53
- }
54
- if (typeof msg.content === 'string') {
55
- input.push({ role, content: msg.content });
56
- }
57
- else {
58
- input.push({
59
- role,
60
- content: msg.content.map((p) => p.type === 'text'
61
- ? { type: 'input_text', text: p.text || '' }
62
- : { type: 'input_image', image_url: p.image_url?.url }),
63
- });
64
- }
65
- }
66
- const payload = {
67
- model: model.upstreamModel,
68
- input,
69
- stream: false,
70
- };
71
- const joined = instructions.filter(Boolean).join('\n\n');
72
- if (joined)
73
- payload.instructions = joined;
74
- if (request.max_tokens != null)
75
- payload.max_output_tokens = request.max_tokens;
76
- else if (request.max_completion_tokens != null)
77
- payload.max_output_tokens = request.max_completion_tokens;
78
- if (request.temperature != null && model.temperature !== false)
79
- payload.temperature = request.temperature;
80
- if (request.top_p != null)
81
- payload.top_p = request.top_p;
82
- if (request.tools?.length)
83
- payload.tools = chatToolsToResponses(request.tools);
84
- if (request.reasoning_effort || request.max_thinking_tokens != null) {
85
- const reasoning = {};
86
- // OpenAI Responses accepts the full 5-level vocabulary (none/low/medium/
87
- // high/xhigh). Pass through verbatim — upstream rejects unsupported values
88
- // with a clear 400. Explicit max_thinking_tokens wins over the ladder.
89
- if (request.reasoning_effort)
90
- reasoning.effort = request.reasoning_effort;
91
- if (request.max_thinking_tokens != null)
92
- reasoning.max_tokens = request.max_thinking_tokens;
93
- payload.reasoning = reasoning;
94
- }
95
- return payload;
96
- }
97
- /** Pure response mapper: OpenAI Responses payload → chat-completions response. */
98
- export function responsesToChatCompletion(data, model) {
99
- let text = '';
100
- const toolCalls = [];
101
- for (const o of data.output || []) {
102
- if (o.type === 'message') {
103
- text += (o.content || [])
104
- .filter((c) => c.type === 'output_text')
105
- .map((c) => c.text)
106
- .join('');
107
- }
108
- else if (o.type === 'function_call') {
109
- toolCalls.push({
110
- id: o.call_id || o.id || `call_${crypto.randomBytes(8).toString('hex')}`,
111
- type: 'function',
112
- function: {
113
- name: o.name,
114
- arguments: typeof o.arguments === 'string' ? o.arguments : JSON.stringify(o.arguments ?? {}),
115
- },
116
- });
117
- }
4
+ import { DEFAULT_PROVIDER_TIMEOUT_MS, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_STREAM_TIMEOUT_MS, } from '../config/defaults.js';
5
+ import { postProviderJson } from './http-json.js';
6
+ import { postProviderStream } from './http-stream.js';
7
+ function parseCompletion(data, provider, modelId) {
8
+ if (data.status === 'failed') {
9
+ throw new UpstreamError({
10
+ message: data.error?.message || 'Upstream Responses turn failed.',
11
+ status: 502,
12
+ errorBody: JSON.stringify(data.error ?? {}),
13
+ provider,
14
+ modelId,
15
+ });
118
16
  }
119
- const cached = data.usage?.input_tokens_details?.cached_tokens || 0;
120
- // OpenAI Responses surfaces thinking tokens as `usage.output_tokens_details.reasoning_tokens`;
121
- // mirror them into the chat-completions shape so downstream cost math + clients see them.
122
- const reasoningTokens = data.usage?.output_tokens_details?.reasoning_tokens || 0;
123
- return {
124
- id: data.id || `resp-${Date.now()}`,
125
- object: 'chat.completion',
126
- created: Math.floor(Date.now() / 1000),
127
- model: model.id,
128
- choices: [
129
- {
130
- index: 0,
131
- message: {
132
- role: 'assistant',
133
- content: text,
134
- ...(toolCalls.length ? { tool_calls: toolCalls } : {}),
135
- },
136
- finish_reason: toolCalls.length ? 'tool_calls' : data.status === 'incomplete' ? 'length' : 'stop',
137
- },
138
- ],
139
- usage: {
140
- prompt_tokens: data.usage?.input_tokens ?? 0,
141
- completion_tokens: data.usage?.output_tokens ?? 0,
142
- total_tokens: data.usage?.total_tokens ?? (data.usage?.input_tokens ?? 0) + (data.usage?.output_tokens ?? 0),
143
- prompt_tokens_details: { cached_tokens: cached },
144
- ...(reasoningTokens > 0
145
- ? {
146
- completion_tokens_details: {
147
- reasoning_tokens: reasoningTokens,
148
- },
149
- }
150
- : {}),
151
- },
152
- };
17
+ return responsesResponseToIR(data);
153
18
  }
19
+ /** OpenAI Responses upstream. The provider speaks Canonical IR only. */
154
20
  export class ResponsesProvider {
155
21
  name;
156
22
  config;
@@ -158,113 +24,39 @@ export class ResponsesProvider {
158
24
  this.name = config.name;
159
25
  this.config = config;
160
26
  }
161
- async createCompletion(request, model, upstreamEventContext, credential) {
162
- const url = `${this.config.baseUrl.replace(/\/+$/, '')}/responses`;
163
- const headers = {
27
+ headers(credential) {
28
+ return {
164
29
  'Content-Type': 'application/json',
165
- // Per-call credential outranks the boot-baked key.
166
30
  Authorization: `Bearer ${credential?.key ?? this.config.apiKey}`,
167
31
  ...this.config.headers,
168
32
  };
169
- const payload = buildResponsesPayload(request, model);
170
- // Event-stream emit BEFORE the fetch fires. Independent of the response.
171
- const exchangeId = emitUpstreamRequestOnce(upstreamEventContext, {
172
- url,
173
- method: 'POST',
174
- requestHeaders: headers,
175
- requestBody: JSON.stringify(payload),
176
- model: model.upstreamModel,
177
- proxy: resolveProxyUrl(url, { provider: this.config.name, model: model.id }),
33
+ }
34
+ async createCompletion(request, model, upstreamEventContext, credential) {
35
+ const data = await postProviderJson({
36
+ url: `${this.config.baseUrl.replace(/\/+$/, '')}/responses`,
37
+ headers: this.headers(credential),
38
+ payload: canonicalToResponsesPayload(request, model),
39
+ model,
40
+ provider: this.name,
41
+ label: 'responses',
42
+ timeoutMs: this.config.timeoutMs || DEFAULT_PROVIDER_TIMEOUT_MS,
43
+ upstreamEventContext,
44
+ });
45
+ return parseCompletion(data, this.name, model.id);
46
+ }
47
+ async createStream(request, model, upstreamEventContext, credential) {
48
+ return postProviderStream({
49
+ url: `${this.config.baseUrl.replace(/\/+$/, '')}/responses`,
50
+ headers: this.headers(credential),
51
+ payload: canonicalToResponsesPayload(request, model, true),
52
+ model,
53
+ provider: this.name,
54
+ label: 'responses',
55
+ timeoutMs: this.config.streamTimeoutMs || DEFAULT_STREAM_TIMEOUT_MS,
56
+ idleTimeoutMs: this.config.streamIdleTimeoutMs || DEFAULT_STREAM_IDLE_TIMEOUT_MS,
57
+ upstreamEventContext,
58
+ createDecoder: () => new ResponsesStreamDecoder(),
59
+ parseBuffered: (body) => parseCompletion(body, this.name, model.id),
178
60
  });
179
- const controller = new AbortController();
180
- // Wall-clock cap on the non-streaming upstream execution — see the
181
- // openai-compatible provider: agent coding traffic legitimately runs past
182
- // a minute, so the default is 300 s.
183
- const timeout = setTimeout(() => controller.abort(), this.config.timeoutMs || DEFAULT_PROVIDER_TIMEOUT_MS);
184
- try {
185
- const res = await withUpstreamFailureGuard(upstreamEventContext, exchangeId, url, 'POST', () => proxiedFetch(url, {
186
- method: 'POST',
187
- headers,
188
- body: JSON.stringify(payload),
189
- signal: controller.signal,
190
- }, { provider: this.config.name, model: model.id }), model.upstreamModel);
191
- if (!res.ok) {
192
- // Body read can fail mid-stream (connection reset) — pair the request
193
- // event with a failure response before rethrowing.
194
- let errorText;
195
- try {
196
- errorText = await res.text();
197
- }
198
- catch (err) {
199
- emitUpstreamFailureOnce(upstreamEventContext, {
200
- model: model.upstreamModel,
201
- exchangeId,
202
- url,
203
- method: 'POST',
204
- status: res.status,
205
- statusText: res.statusText,
206
- error: `Response body read failed: ${err?.message ?? err}`,
207
- });
208
- throw err;
209
- }
210
- const retryAfterHeader = res.headers.get('retry-after');
211
- const retryAfterSeconds = retryAfterHeader ? parseInt(retryAfterHeader, 10) : undefined;
212
- emitUpstreamFailureOnce(upstreamEventContext, {
213
- model: model.upstreamModel,
214
- exchangeId,
215
- url,
216
- method: 'POST',
217
- status: res.status,
218
- statusText: res.statusText,
219
- responseHeaders: res.headers,
220
- responseBody: errorText,
221
- error: `Responses error [${res.status}]`,
222
- });
223
- throw new UpstreamError({
224
- message: `Upstream ${this.name} [responses] returned status ${res.status}: ${errorText}`,
225
- status: res.status,
226
- errorBody: errorText,
227
- provider: this.name,
228
- modelId: model.id,
229
- retryAfterSeconds: isNaN(retryAfterSeconds) ? undefined : retryAfterSeconds,
230
- });
231
- }
232
- // Emit the response event the moment the body BYTES arrive — before
233
- // JSON.parse (see anthropic.ts for the rationale).
234
- let rawBody;
235
- try {
236
- rawBody = await res.text();
237
- }
238
- catch (err) {
239
- emitUpstreamFailureOnce(upstreamEventContext, {
240
- model: model.upstreamModel,
241
- exchangeId,
242
- url,
243
- method: 'POST',
244
- status: res.status,
245
- statusText: res.statusText,
246
- error: `Response body read failed: ${err?.message ?? err}`,
247
- });
248
- throw err;
249
- }
250
- emitUpstreamResponseOnce(upstreamEventContext, {
251
- model: model.upstreamModel,
252
- exchangeId,
253
- url,
254
- method: 'POST',
255
- status: res.status,
256
- statusText: res.statusText,
257
- responseHeaders: res.headers,
258
- responseBody: rawBody,
259
- });
260
- const data = JSON.parse(rawBody);
261
- return responsesToChatCompletion(data, model);
262
- }
263
- finally {
264
- clearTimeout(timeout);
265
- }
266
61
  }
267
- }
268
- function textOf(parts) {
269
- return parts.map((p) => p.text || '').join(' ');
270
62
  }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Detection of upstreams that leak their own tool-call MARKUP as text.
3
+ *
4
+ * Some model families have no native tool-call channel on the wire: they write
5
+ * the call into the message body and expect the API in front of the model to
6
+ * convert it. DeepSeek V4 writes `<|tool_calls|>` / `<|invoke name="…">` (with
7
+ * an optional `DSML` marker), and a relay that does not run the converter hands
8
+ * that markup to the client as ordinary content — the client sees tags, and the
9
+ * model, reading its own markup back from history, loops.
10
+ *
11
+ * OBSERVE ONLY within this module: detection never edits a response. The
12
+ * narrowly-scoped, validated recovery in `providers/tool-markup-recovery.ts`
13
+ * runs first; this detector then counts only residual markup (unscoped,
14
+ * malformed, truncated or schema-invalid), preserving a visible signal for the
15
+ * operator (ADR-0034). Detection itself is therefore safe to run on every
16
+ * provider at full stream speed, independently of whether a response is
17
+ * eligible for recovery.
18
+ *
19
+ * Lives beside recovery on the provider execution boundary — not in `ir/`.
20
+ */
21
+ import type { CanonicalResponse } from '../ir/types.js';
22
+ /** How many leaked tool-call blocks one response carried. */
23
+ export interface ToolMarkupLeak {
24
+ calls: number;
25
+ }
26
+ /** Count the leaked calls in one text. */
27
+ export declare function countToolMarkupLeak(text: string): number;
28
+ /**
29
+ * Scan a buffered response. Returns null when nothing leaked, so a caller can
30
+ * stamp the result unconditionally.
31
+ */
32
+ export declare function detectToolMarkupLeak(response: CanonicalResponse): ToolMarkupLeak | null;
33
+ /**
34
+ * Incremental scanner for the streaming leg, where no full response exists at
35
+ * the time the bytes leave. Feed every text delta; ask afterwards. The tail
36
+ * window is what lets a tag split across two deltas still match.
37
+ */
38
+ export declare function createToolMarkupScanner(): {
39
+ push: (text: string) => void;
40
+ leak: () => ToolMarkupLeak | null;
41
+ };
@@ -0,0 +1,57 @@
1
+ /**
2
+ * One opening `invoke` tag in any spelling seen in the wild — the `DSML` marker
3
+ * is OPTIONAL (`<|DSML|invoke name="x">` on some channels, a bare
4
+ * `<|invoke name="x">` on others), and the pipe separators may be full-width,
5
+ * doubled, or absent.
6
+ */
7
+ const INVOKE_OPEN = /<[|\uFF5C\s]*(?:DSML[|\uFF5C\s]*)?invoke\b[^>]*>/gi;
8
+ /** Count the leaked calls in one text. */
9
+ export function countToolMarkupLeak(text) {
10
+ return [...text.matchAll(INVOKE_OPEN)].length;
11
+ }
12
+ /**
13
+ * Scan a buffered response. Returns null when nothing leaked, so a caller can
14
+ * stamp the result unconditionally.
15
+ */
16
+ export function detectToolMarkupLeak(response) {
17
+ // Tolerant of a stub/partial response: this runs on the return path of every
18
+ // provider call, so it must never be the thing that throws.
19
+ if (!response || !Array.isArray(response.output))
20
+ return null;
21
+ let calls = 0;
22
+ for (const item of response.output) {
23
+ if (item.type !== 'message')
24
+ continue;
25
+ for (const part of item.content) {
26
+ if (part.type === 'text')
27
+ calls += countToolMarkupLeak(part.text);
28
+ }
29
+ }
30
+ return calls > 0 ? { calls } : null;
31
+ }
32
+ /**
33
+ * Incremental scanner for the streaming leg, where no full response exists at
34
+ * the time the bytes leave. Feed every text delta; ask afterwards. The tail
35
+ * window is what lets a tag split across two deltas still match.
36
+ */
37
+ export function createToolMarkupScanner() {
38
+ let calls = 0;
39
+ let tail = '';
40
+ return {
41
+ push(text) {
42
+ if (!text)
43
+ return;
44
+ const probe = tail + text;
45
+ for (const match of probe.matchAll(INVOKE_OPEN)) {
46
+ // Only count a match that ENDS past the retained tail, otherwise every
47
+ // push would re-count the previous delta's tag.
48
+ if ((match.index ?? 0) + match[0].length > tail.length)
49
+ calls += 1;
50
+ }
51
+ tail = probe.slice(-200);
52
+ },
53
+ leak() {
54
+ return calls > 0 ? { calls } : null;
55
+ },
56
+ };
57
+ }
@@ -0,0 +1,27 @@
1
+ import type { ModelRegistration, ProviderConfig } from '../config/types.js';
2
+ import type { CanonicalRequest, CanonicalResponse, StreamEvent } from '../ir/types.js';
3
+ /** A narrowly-scoped repair for the one endpoint/model family observed leaking. */
4
+ export type ToolMarkupRecovery = 'dsml';
5
+ export interface RecoveredToolCall {
6
+ name: string;
7
+ arguments: string;
8
+ }
9
+ interface TextRecovery {
10
+ text: string;
11
+ calls: RecoveredToolCall[];
12
+ }
13
+ /** Endpoint + model + request scope; provider ids deliberately play no role. */
14
+ export declare function toolMarkupRecoveryFor(request: CanonicalRequest, model: ModelRegistration, config: ProviderConfig | undefined): ToolMarkupRecovery | null;
15
+ export declare function recoverToolMarkupText(text: string, request: CanonicalRequest): TextRecovery;
16
+ export declare function recoverToolMarkupInResponse(response: CanonicalResponse, request: CanonicalRequest): CanonicalResponse;
17
+ /**
18
+ * Incremental IR-event rewriter. Text passes immediately unless it can still
19
+ * become a fence or tool tag. Tool items are reconciled at EOS so an upstream
20
+ * empty native placeholder and a recovered call can never both execute.
21
+ */
22
+ export declare function createToolMarkupStreamRecovery(request: CanonicalRequest): {
23
+ push(event: StreamEvent): StreamEvent[];
24
+ finish(terminal?: StreamEvent): StreamEvent[];
25
+ finishResponse(response: CanonicalResponse): CanonicalResponse;
26
+ };
27
+ export {};