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,214 +1,9 @@
1
- import crypto from 'node:crypto';
2
- import { UpstreamError } from '../resilience/error-classifier.js';
3
- import { proxiedFetch, resolveProxyUrl } from '../utils/proxy.js';
4
- import { DEFAULT_PROVIDER_TIMEOUT_MS } from '../config/defaults.js';
5
- import { DATA_URL_RE } from './wire.js';
6
- import { emitUpstreamRequestOnce, emitUpstreamResponseOnce, emitUpstreamFailureOnce, withUpstreamFailureGuard, } from '../observability/upstream-events.js';
7
- /**
8
- * Google Generative Language wire (`@ai-sdk/google`) —
9
- * POST {base}/models/{model}:generateContent with x-goog-api-key.
10
- *
11
- * Tools are fully mapped both directions (2026-10): request.tools →
12
- * functionDeclarations, assistant tool_calls in history → functionCall parts,
13
- * tool role messages → functionResponse parts (call_id resolved to function
14
- * name via a first-pass scan), and upstream functionCall parts → chat
15
- * tool_calls. Without this, tool-driving clients routed to Gemini upstreams
16
- * silently lose tools.
17
- */
18
- /** Parse tool arguments into an object; never throws (tool loops must survive). */
19
- function parseArgs(raw) {
20
- if (raw && typeof raw === 'object')
21
- return raw;
22
- if (typeof raw !== 'string' || !raw.trim())
23
- return {};
24
- try {
25
- const v = JSON.parse(raw);
26
- return v && typeof v === 'object' ? v : { result: v };
27
- }
28
- catch {
29
- return { result: raw };
30
- }
31
- }
32
- function wrapResponse(v) {
33
- // Gemini functionResponse.response must be a structured object.
34
- return Object.keys(v).length ? v : { result: 'ok' };
35
- }
36
- /** Pure payload builder: chat-completions request → Gemini generateContent payload. */
37
- export function buildGooglePayload(request, model) {
38
- // Gemini's functionResponse parts require the FUNCTION NAME (not call_id);
39
- // resolve call ids by scanning assistant tool_calls first.
40
- const nameByCall = new Map();
41
- for (const m of request.messages) {
42
- for (const tc of m.tool_calls || [])
43
- nameByCall.set(tc.id, tc.function.name);
44
- }
45
- const systemText = request.messages
46
- .filter((m) => m.role === 'system' || m.role === 'developer')
47
- .map((m) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content)))
48
- .join('\n\n');
49
- const contents = request.messages
50
- .filter((m) => m.role !== 'system' && m.role !== 'developer')
51
- .map((m) => {
52
- if (m.role === 'tool') {
53
- return {
54
- role: 'user',
55
- parts: [
56
- {
57
- functionResponse: {
58
- name: nameByCall.get(m.tool_call_id || '') || 'unknown_function',
59
- response: wrapResponse(parseArgs(m.content)),
60
- },
61
- },
62
- ],
63
- };
64
- }
65
- if (m.role === 'assistant' && Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {
66
- const parts = [];
67
- const text = typeof m.content === 'string' ? m.content : '';
68
- if (text)
69
- parts.push({ text });
70
- for (const tc of m.tool_calls) {
71
- parts.push({ functionCall: { name: tc.function.name, args: parseArgs(tc.function.arguments) } });
72
- }
73
- return { role: 'model', parts };
74
- }
75
- return {
76
- role: m.role === 'assistant' ? 'model' : 'user',
77
- parts: typeof m.content === 'string'
78
- ? [{ text: m.content }]
79
- : m.content
80
- .map((p) => {
81
- if (p.type === 'text')
82
- return { text: p.text || '' };
83
- // Gemini inlineData requires base64; parse the data-URL so the
84
- // real MIME type rides along. HTTP(S) URLs would need a
85
- // Files-API upload — documented known loss (rare path).
86
- const m2 = DATA_URL_RE.exec(String(p.image_url?.url || ''));
87
- if (m2)
88
- return { inlineData: { mimeType: m2[1], data: m2[2] } };
89
- return { text: `[unsupported image reference]` };
90
- })
91
- .filter(Boolean),
92
- };
93
- });
94
- const generationConfig = {};
95
- if (request.max_tokens != null)
96
- generationConfig.maxOutputTokens = request.max_tokens;
97
- else if (request.max_completion_tokens != null)
98
- generationConfig.maxOutputTokens = request.max_completion_tokens;
99
- if (request.temperature != null && model.temperature !== false)
100
- generationConfig.temperature = request.temperature;
101
- if (request.top_p != null)
102
- generationConfig.topP = request.top_p;
103
- if (request.stop?.length)
104
- generationConfig.stopSequences = request.stop;
105
- // effort level → thinkingConfig.thinkingBudget. The full 6-level
106
- // table; `none` maps to 0 as a defensive value even though the guard
107
- // below skips the thinking block for it. Numbers for the other 5 are
108
- // engineering estimates; operators with strict cost caps should pass
109
- // an explicit `max_thinking_tokens` instead.
110
- const EFFORT_TO_BUDGET = {
111
- none: 0,
112
- low: 1024,
113
- medium: 4096,
114
- high: 16384,
115
- xhigh: 32768,
116
- max: 65536,
117
- };
118
- const effort = request.reasoning_effort;
119
- if (request.max_thinking_tokens != null && request.max_thinking_tokens >= 0) {
120
- generationConfig.thinkingConfig = {
121
- thinkingBudget: request.max_thinking_tokens,
122
- includeThoughts: true,
123
- };
124
- }
125
- else if (effort && effort !== 'none') {
126
- generationConfig.thinkingConfig = {
127
- thinkingBudget: EFFORT_TO_BUDGET[effort],
128
- includeThoughts: true,
129
- };
130
- }
131
- const payload = { contents, ...(systemText ? { systemInstruction: { parts: [{ text: systemText }] } } : {}) };
132
- if (Object.keys(generationConfig).length)
133
- payload.generationConfig = generationConfig;
134
- if (request.tools?.length) {
135
- payload.tools = [
136
- {
137
- functionDeclarations: request.tools.map((t) => ({
138
- name: t.function.name,
139
- description: t.function.description,
140
- parameters: t.function.parameters,
141
- })),
142
- },
143
- ];
144
- }
145
- if (request.tool_choice === 'none') {
146
- payload.toolConfig = { functionCallingConfig: { mode: 'NONE' } };
147
- }
148
- else if (request.tool_choice === 'required') {
149
- payload.toolConfig = { functionCallingConfig: { mode: 'ANY' } };
150
- }
151
- else if (request.tool_choice === 'auto') {
152
- payload.toolConfig = { functionCallingConfig: { mode: 'AUTO' } };
153
- }
154
- return payload;
155
- }
156
- /** Pure response mapper: Gemini generateContent payload → chat-completions response. */
157
- export function googleToChatCompletion(data, model) {
158
- const parts = data.candidates?.[0]?.content?.parts || [];
159
- let text = '';
160
- const toolCalls = [];
161
- for (const p of parts) {
162
- if (p.text)
163
- text += p.text;
164
- if (p.functionCall) {
165
- toolCalls.push({
166
- id: `call_${crypto.randomBytes(8).toString('hex')}`,
167
- type: 'function',
168
- function: { name: p.functionCall.name, arguments: JSON.stringify(p.functionCall.args ?? {}) },
169
- });
170
- }
171
- }
172
- const finishRaw = data.candidates?.[0]?.finishReason;
173
- return {
174
- id: `google-${Date.now()}`,
175
- object: 'chat.completion',
176
- created: Math.floor(Date.now() / 1000),
177
- model: model.id,
178
- choices: [
179
- {
180
- index: 0,
181
- message: {
182
- role: 'assistant',
183
- content: text,
184
- ...(toolCalls.length ? { tool_calls: toolCalls } : {}),
185
- },
186
- finish_reason: toolCalls.length
187
- ? 'tool_calls'
188
- : finishRaw === 'MAX_TOKENS'
189
- ? 'length'
190
- : finishRaw === 'SAFETY'
191
- ? 'content_filter'
192
- : 'stop',
193
- },
194
- ],
195
- usage: {
196
- prompt_tokens: data.usageMetadata?.promptTokenCount ?? 0,
197
- completion_tokens: data.usageMetadata?.candidatesTokenCount ?? 0,
198
- total_tokens: data.usageMetadata?.totalTokenCount ?? 0,
199
- // Gemini surfaces thinking tokens as `thoughtsTokenCount` (separate from
200
- // `candidatesTokenCount` which counts only the visible answer). Surface
201
- // them as OpenAI's `completion_tokens_details.reasoning_tokens`.
202
- ...(data.usageMetadata?.thoughtsTokenCount
203
- ? {
204
- completion_tokens_details: {
205
- reasoning_tokens: data.usageMetadata.thoughtsTokenCount,
206
- },
207
- }
208
- : {}),
209
- },
210
- };
211
- }
1
+ import { canonicalToGooglePayload, googleResponseToIR } from '../ir/adapters/google.js';
2
+ import { GoogleStreamDecoder } from '../ir/adapters/google-stream.js';
3
+ import { DEFAULT_PROVIDER_TIMEOUT_MS, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_STREAM_TIMEOUT_MS, } from '../config/defaults.js';
4
+ import { postProviderJson } from './http-json.js';
5
+ import { postProviderStream } from './http-stream.js';
6
+ /** Google Generative Language upstream. The provider speaks Canonical IR only. */
212
7
  export class GoogleProvider {
213
8
  name;
214
9
  config;
@@ -216,107 +11,39 @@ export class GoogleProvider {
216
11
  this.name = config.name;
217
12
  this.config = config;
218
13
  }
219
- async createCompletion(request, model, upstreamEventContext, credential) {
220
- const url = `${this.config.baseUrl.replace(/\/+$/, '')}/models/${encodeURIComponent(model.upstreamModel)}:generateContent`;
221
- const payload = buildGooglePayload(request, model);
222
- const outboundHeaders = {
14
+ headers(credential) {
15
+ return {
223
16
  'Content-Type': 'application/json',
224
- // Per-call credential outranks the boot-baked key.
225
17
  'x-goog-api-key': credential?.key ?? this.config.apiKey,
226
18
  ...this.config.headers,
227
19
  };
228
- // Event-stream emit BEFORE the fetch fires. Independent of the response.
229
- const exchangeId = emitUpstreamRequestOnce(upstreamEventContext, {
230
- url,
231
- method: 'POST',
232
- requestHeaders: outboundHeaders,
233
- requestBody: JSON.stringify(payload),
234
- model: model.upstreamModel,
235
- proxy: resolveProxyUrl(url, { provider: this.config.name, model: model.id }),
20
+ }
21
+ async createCompletion(request, model, upstreamEventContext, credential) {
22
+ const data = await postProviderJson({
23
+ url: `${this.config.baseUrl.replace(/\/+$/, '')}/models/${encodeURIComponent(model.upstreamModel)}:generateContent`,
24
+ headers: this.headers(credential),
25
+ payload: canonicalToGooglePayload(request, model),
26
+ model,
27
+ provider: this.name,
28
+ label: 'google',
29
+ timeoutMs: this.config.timeoutMs || DEFAULT_PROVIDER_TIMEOUT_MS,
30
+ upstreamEventContext,
31
+ });
32
+ return googleResponseToIR(data);
33
+ }
34
+ async createStream(request, model, upstreamEventContext, credential) {
35
+ return postProviderStream({
36
+ url: `${this.config.baseUrl.replace(/\/+$/, '')}/models/${encodeURIComponent(model.upstreamModel)}:streamGenerateContent?alt=sse`,
37
+ headers: this.headers(credential),
38
+ payload: canonicalToGooglePayload(request, model),
39
+ model,
40
+ provider: this.name,
41
+ label: 'google',
42
+ timeoutMs: this.config.streamTimeoutMs || DEFAULT_STREAM_TIMEOUT_MS,
43
+ idleTimeoutMs: this.config.streamIdleTimeoutMs || DEFAULT_STREAM_IDLE_TIMEOUT_MS,
44
+ upstreamEventContext,
45
+ createDecoder: () => new GoogleStreamDecoder(),
46
+ parseBuffered: (body) => googleResponseToIR(body),
236
47
  });
237
- const controller = new AbortController();
238
- // Wall-clock cap on the non-streaming upstream execution — see the
239
- // openai-compatible provider: agent coding traffic legitimately runs past
240
- // a minute, so the default is 300 s.
241
- const timeout = setTimeout(() => controller.abort(), this.config.timeoutMs || DEFAULT_PROVIDER_TIMEOUT_MS);
242
- try {
243
- const res = await withUpstreamFailureGuard(upstreamEventContext, exchangeId, url, 'POST', () => proxiedFetch(url, {
244
- method: 'POST',
245
- headers: outboundHeaders,
246
- body: JSON.stringify(payload),
247
- signal: controller.signal,
248
- }, { provider: this.config.name, model: model.id }), model.upstreamModel);
249
- if (!res.ok) {
250
- // Body read can fail mid-stream (connection reset) — pair the request
251
- // event with a failure response before rethrowing.
252
- let errorText;
253
- try {
254
- errorText = await res.text();
255
- }
256
- catch (err) {
257
- emitUpstreamFailureOnce(upstreamEventContext, {
258
- model: model.upstreamModel,
259
- exchangeId,
260
- url,
261
- method: 'POST',
262
- status: res.status,
263
- statusText: res.statusText,
264
- error: `Response body read failed: ${err?.message ?? err}`,
265
- });
266
- throw err;
267
- }
268
- emitUpstreamFailureOnce(upstreamEventContext, {
269
- model: model.upstreamModel,
270
- exchangeId,
271
- url,
272
- method: 'POST',
273
- status: res.status,
274
- statusText: res.statusText,
275
- responseHeaders: res.headers,
276
- responseBody: errorText,
277
- error: `Google error [${res.status}]`,
278
- });
279
- throw new UpstreamError({
280
- message: `Upstream ${this.name} [google] returned status ${res.status}: ${errorText}`,
281
- status: res.status,
282
- errorBody: errorText,
283
- provider: this.config.name,
284
- modelId: model.id,
285
- });
286
- }
287
- // Emit the response event the moment the body BYTES arrive — before
288
- // JSON.parse (see anthropic.ts for the rationale).
289
- let rawBody;
290
- try {
291
- rawBody = await res.text();
292
- }
293
- catch (err) {
294
- emitUpstreamFailureOnce(upstreamEventContext, {
295
- model: model.upstreamModel,
296
- exchangeId,
297
- url,
298
- method: 'POST',
299
- status: res.status,
300
- statusText: res.statusText,
301
- error: `Response body read failed: ${err?.message ?? err}`,
302
- });
303
- throw err;
304
- }
305
- emitUpstreamResponseOnce(upstreamEventContext, {
306
- model: model.upstreamModel,
307
- exchangeId,
308
- url,
309
- method: 'POST',
310
- status: res.status,
311
- statusText: res.statusText,
312
- responseHeaders: res.headers,
313
- responseBody: rawBody,
314
- });
315
- const data = JSON.parse(rawBody);
316
- return googleToChatCompletion(data, model);
317
- }
318
- finally {
319
- clearTimeout(timeout);
320
- }
321
48
  }
322
49
  }
@@ -0,0 +1,19 @@
1
+ import type { ModelRegistration } from '../config/types.js';
2
+ /** Set a header while stripping any case-variant duplicate from custom config headers. */
3
+ export declare function setHeaderCaseInsensitive(headers: Record<string, string>, name: string, value: string): void;
4
+ /** Set a default header only if no case-variant key is already present. */
5
+ export declare function setDefaultHeaderCaseInsensitive(headers: Record<string, string>, name: string, value: string): void;
6
+ /** Merge a required comma-separated token (e.g. anthropic-beta) with any custom value. */
7
+ export declare function mergeCommaHeader(headers: Record<string, string>, name: string, requiredToken: string): void;
8
+ import { type UpstreamEventContext } from '../observability/upstream-events.js';
9
+ /** One buffered JSON exchange with the shared capture/error contract. */
10
+ export declare function postProviderJson(options: {
11
+ url: string;
12
+ headers: Record<string, string>;
13
+ payload: Record<string, unknown>;
14
+ model: ModelRegistration;
15
+ provider: string;
16
+ label: string;
17
+ timeoutMs: number;
18
+ upstreamEventContext?: UpstreamEventContext;
19
+ }): Promise<unknown>;
@@ -0,0 +1,104 @@
1
+ import { UpstreamError } from '../resilience/error-classifier.js';
2
+ import { proxiedFetch, resolveProxyUrl } from '../utils/proxy.js';
3
+ import { redactUpstreamBody } from '../observability/upstream-body-redaction.js';
4
+ import { readBoundedBodyText, STREAM_CAPTURE_CAP } from './http-stream.js';
5
+ /** Set a header while stripping any case-variant duplicate from custom config headers. */
6
+ export function setHeaderCaseInsensitive(headers, name, value) {
7
+ const lower = name.toLowerCase();
8
+ for (const key of Object.keys(headers)) {
9
+ if (key.toLowerCase() === lower)
10
+ delete headers[key];
11
+ }
12
+ headers[name] = value;
13
+ }
14
+ /** Set a default header only if no case-variant key is already present. */
15
+ export function setDefaultHeaderCaseInsensitive(headers, name, value) {
16
+ const lower = name.toLowerCase();
17
+ for (const key of Object.keys(headers)) {
18
+ if (key.toLowerCase() === lower)
19
+ return;
20
+ }
21
+ headers[name] = value;
22
+ }
23
+ /** Merge a required comma-separated token (e.g. anthropic-beta) with any custom value. */
24
+ export function mergeCommaHeader(headers, name, requiredToken) {
25
+ const lower = name.toLowerCase();
26
+ const tokens = [requiredToken];
27
+ for (const key of Object.keys(headers)) {
28
+ if (key.toLowerCase() !== lower)
29
+ continue;
30
+ const raw = headers[key];
31
+ delete headers[key];
32
+ if (typeof raw !== 'string')
33
+ continue;
34
+ for (const part of raw.split(',')) {
35
+ const trimmed = part.trim();
36
+ if (trimmed && !tokens.includes(trimmed))
37
+ tokens.push(trimmed);
38
+ }
39
+ }
40
+ headers[name] = tokens.join(',');
41
+ }
42
+ import { emitUpstreamRequestOnce, emitUpstreamResponseOnce, emitUpstreamFailureOnce, withUpstreamFailureGuard, } from '../observability/upstream-events.js';
43
+ /** One buffered JSON exchange with the shared capture/error contract. */
44
+ export async function postProviderJson(options) {
45
+ const { url, headers, payload, model, provider, label, upstreamEventContext } = options;
46
+ const body = JSON.stringify(payload);
47
+ const exchangeId = emitUpstreamRequestOnce(upstreamEventContext, {
48
+ url,
49
+ method: 'POST',
50
+ requestHeaders: headers,
51
+ requestBody: body,
52
+ model: model.upstreamModel,
53
+ proxy: resolveProxyUrl(url, { provider, model: model.id }),
54
+ });
55
+ const controller = new AbortController();
56
+ const timeout = setTimeout(() => controller.abort(), options.timeoutMs);
57
+ try {
58
+ const res = await withUpstreamFailureGuard(upstreamEventContext, exchangeId, url, 'POST', () => proxiedFetch(url, {
59
+ method: 'POST', headers, body, signal: controller.signal,
60
+ }, { provider, model: model.id }), model.upstreamModel);
61
+ let rawBody;
62
+ try {
63
+ rawBody = res.ok ? await res.text() : await readBoundedBodyText(res, STREAM_CAPTURE_CAP);
64
+ }
65
+ catch (err) {
66
+ emitUpstreamFailureOnce(upstreamEventContext, {
67
+ model: model.upstreamModel, exchangeId, url, method: 'POST',
68
+ status: res.status, statusText: res.statusText,
69
+ error: `Response body read failed: ${err?.message ?? err}`,
70
+ });
71
+ throw err;
72
+ }
73
+ if (!res.ok) {
74
+ const retryAfterHeader = res.headers.get('retry-after');
75
+ const parsedRetryAfter = retryAfterHeader ? Number.parseInt(retryAfterHeader, 10) : Number.NaN;
76
+ // Security: upstreams echo Authorization / api keys in 4xx bodies —
77
+ // never forward the raw body to clients, logs, capture or the ledger.
78
+ const safe = redactUpstreamBody(rawBody, headers);
79
+ emitUpstreamFailureOnce(upstreamEventContext, {
80
+ model: model.upstreamModel, exchangeId, url, method: 'POST',
81
+ status: res.status, statusText: res.statusText,
82
+ responseHeaders: res.headers, responseBody: safe,
83
+ error: `${label} error [${res.status}]`,
84
+ });
85
+ throw new UpstreamError({
86
+ message: `Upstream ${provider} [${label}] returned status ${res.status}: ${safe}`,
87
+ status: res.status,
88
+ errorBody: safe,
89
+ provider,
90
+ modelId: model.id,
91
+ retryAfterSeconds: Number.isNaN(parsedRetryAfter) ? undefined : parsedRetryAfter,
92
+ });
93
+ }
94
+ emitUpstreamResponseOnce(upstreamEventContext, {
95
+ model: model.upstreamModel, exchangeId, url, method: 'POST',
96
+ status: res.status, statusText: res.statusText,
97
+ responseHeaders: res.headers, responseBody: rawBody,
98
+ });
99
+ return JSON.parse(rawBody);
100
+ }
101
+ finally {
102
+ clearTimeout(timeout);
103
+ }
104
+ }
@@ -0,0 +1,52 @@
1
+ import type { ModelRegistration } from '../config/types.js';
2
+ import type { CanonicalResponse, StreamEvent } from '../ir/types.js';
3
+ import { type UpstreamEventContext } from '../observability/upstream-events.js';
4
+ /** Raw-wire capture is bounded independently of the semantic event stream. */
5
+ export declare const STREAM_CAPTURE_CAP: number;
6
+ /** A single unterminated SSE frame must not bypass the accumulator's memory bound. */
7
+ export declare const STREAM_SSE_FRAME_MAX_CHARS: number;
8
+ export interface ProviderStreamDecoder {
9
+ /** Decode one complete SSE JSON data frame. */
10
+ push(payload: unknown): StreamEvent[];
11
+ /** Close item lifecycles and emit the single canonical terminal event. */
12
+ finish(): StreamEvent[];
13
+ /** Whether the native wire carried a semantic terminator (not just TCP EOF). */
14
+ readonly terminated: boolean;
15
+ }
16
+ interface SseFrame {
17
+ data: string;
18
+ }
19
+ /** Incremental WHATWG SSE parser: CRLF, comments and multi-line data included. */
20
+ export declare class SseParser {
21
+ private buffer;
22
+ private data;
23
+ private dataChars;
24
+ push(text: string): SseFrame[];
25
+ finish(): SseFrame[];
26
+ private line;
27
+ private dispatch;
28
+ }
29
+ /**
30
+ * Read up to `maxBytes` of a response body as UTF-8 text, cancelling the
31
+ * stream once the cap is reached so a runaway error response cannot exhaust
32
+ * memory. When `race` is supplied, every chunk read is bounded by it.
33
+ */
34
+ export declare function readBoundedBodyText(res: Response, maxBytes: number, race?: <T>(pending: Promise<T>) => Promise<T>): Promise<string>;
35
+ /**
36
+ * One streamed HTTP exchange with shared capture, timeout, SSE and fallback
37
+ * semantics. Provider modules own only request shaping and protocol decoding.
38
+ */
39
+ export declare function postProviderStream(options: {
40
+ url: string;
41
+ headers: Record<string, string>;
42
+ payload: Record<string, unknown>;
43
+ model: ModelRegistration;
44
+ provider: string;
45
+ label: string;
46
+ timeoutMs: number;
47
+ idleTimeoutMs: number;
48
+ upstreamEventContext?: UpstreamEventContext;
49
+ createDecoder: () => ProviderStreamDecoder;
50
+ parseBuffered: (body: unknown) => CanonicalResponse;
51
+ }): Promise<AsyncIterable<StreamEvent>>;
52
+ export {};