@omnicross/core 0.1.1 → 0.1.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 (210) hide show
  1. package/dist/ApiConverter.cjs +3 -778
  2. package/dist/ApiConverter.js +12 -751
  3. package/dist/{CompletionService-DtOF_War.d.cts → CompletionService-D3a47vdU.d.cts} +2 -1
  4. package/dist/{CompletionService-7fCmKAP3.d.ts → CompletionService-DdWaAxq0.d.ts} +2 -1
  5. package/dist/auth/GeminiCodeAssistProjectResolver.cjs +27 -60
  6. package/dist/auth/GeminiCodeAssistProjectResolver.js +5 -9
  7. package/dist/builtin-web-fetch-77JZUZGM.cjs +100 -0
  8. package/dist/builtin-web-fetch-IGLBX2XY.js +100 -0
  9. package/dist/chunk-2DCNB7DF.cjs +514 -0
  10. package/dist/chunk-2FEVTJWG.js +4400 -0
  11. package/dist/chunk-3MEACFK3.js +193 -0
  12. package/dist/chunk-3OPYJG76.cjs +266 -0
  13. package/dist/chunk-46RLHI7D.js +0 -0
  14. package/dist/chunk-46ZIFWYG.cjs +277 -0
  15. package/dist/chunk-4NBS6KPV.cjs +43 -0
  16. package/dist/chunk-4VAVYUZS.cjs +991 -0
  17. package/dist/chunk-5ERIZW3D.js +44 -0
  18. package/dist/chunk-5HTVET6E.js +514 -0
  19. package/dist/chunk-5ZQBEOMD.js +764 -0
  20. package/dist/chunk-6VIXXLMX.cjs +14 -0
  21. package/dist/chunk-745DV5FL.js +147 -0
  22. package/dist/chunk-74TMJA7Z.js +53 -0
  23. package/dist/chunk-7VU7V2E4.js +0 -0
  24. package/dist/chunk-7YN22L2H.cjs +87 -0
  25. package/dist/chunk-A2YMUCBT.cjs +105 -0
  26. package/dist/chunk-AQ5TNQB7.js +13 -0
  27. package/dist/chunk-AVYJ4YBN.js +58 -0
  28. package/dist/chunk-C72S6TTV.cjs +49 -0
  29. package/dist/chunk-C7PSERMH.js +87 -0
  30. package/dist/chunk-CDHS2QDC.js +179 -0
  31. package/dist/chunk-DK4A7DLE.js +266 -0
  32. package/dist/chunk-DRWHTIIZ.js +13 -0
  33. package/dist/chunk-DWKQZ2SK.cjs +254 -0
  34. package/dist/chunk-E3WHL7CO.js +14 -0
  35. package/dist/chunk-EYZYXJTJ.cjs +1 -0
  36. package/dist/chunk-FMOBD2OQ.js +39 -0
  37. package/dist/chunk-FTQ7IQUC.js +991 -0
  38. package/dist/chunk-FZ46M34D.cjs +1 -0
  39. package/dist/chunk-G2FUJNA2.cjs +193 -0
  40. package/dist/chunk-G2UTNSGU.js +277 -0
  41. package/dist/chunk-GBHYAGX3.cjs +26 -0
  42. package/dist/chunk-GMMT7RVN.cjs +39 -0
  43. package/dist/chunk-H5JUT3KV.js +105 -0
  44. package/dist/chunk-HQP3K7PU.cjs +431 -0
  45. package/dist/chunk-JO5NLTLY.js +46 -0
  46. package/dist/chunk-JWC6APFQ.js +23 -0
  47. package/dist/chunk-KUU2RNG6.cjs +46 -0
  48. package/dist/chunk-LKZJEL6E.cjs +124 -0
  49. package/dist/chunk-MNYKI4CI.js +94 -0
  50. package/dist/chunk-MZNPGW5Q.js +26 -0
  51. package/dist/chunk-N3V2J5ZO.cjs +53 -0
  52. package/dist/chunk-NYUNU75A.cjs +44 -0
  53. package/dist/chunk-NZYN7C3P.cjs +179 -0
  54. package/dist/chunk-O466Y272.js +235 -0
  55. package/dist/chunk-PXUJF5HS.js +124 -0
  56. package/dist/chunk-QBZJ7P2T.cjs +13 -0
  57. package/dist/chunk-QOCNX236.js +46 -0
  58. package/dist/chunk-QXD4MV2X.cjs +23 -0
  59. package/dist/chunk-R3HK6R4B.cjs +13 -0
  60. package/dist/chunk-RSJ3TWJQ.cjs +186 -0
  61. package/dist/chunk-S4WBV25P.js +913 -0
  62. package/dist/chunk-SN3YWBX7.cjs +4400 -0
  63. package/dist/chunk-SPVWWUHX.cjs +46 -0
  64. package/dist/chunk-SUEGJ75D.cjs +764 -0
  65. package/dist/chunk-SVNDB62D.cjs +58 -0
  66. package/dist/chunk-UYPEN5XE.cjs +235 -0
  67. package/dist/chunk-V5KPWNYX.cjs +147 -0
  68. package/dist/chunk-VVEHS2LI.js +431 -0
  69. package/dist/chunk-XBSYYZIY.cjs +94 -0
  70. package/dist/chunk-YGXJGRFI.cjs +913 -0
  71. package/dist/chunk-YMFAJFQT.cjs +173 -0
  72. package/dist/chunk-Z7LUNECE.js +49 -0
  73. package/dist/chunk-Z7Y2NPHY.js +186 -0
  74. package/dist/chunk-ZJZAOKI7.js +254 -0
  75. package/dist/chunk-ZLX3KGXX.js +173 -0
  76. package/dist/chunk-ZSVQT3PW.js +43 -0
  77. package/dist/completion/ApiKeyPoolService.cjs +23 -48
  78. package/dist/completion/ApiKeyPoolService.d.cts +150 -2
  79. package/dist/completion/ApiKeyPoolService.d.ts +150 -2
  80. package/dist/completion/BuiltinToolExecutor.cjs +9 -324
  81. package/dist/completion/BuiltinToolExecutor.js +6 -290
  82. package/dist/completion/CompletionService.cjs +38 -3487
  83. package/dist/completion/CompletionService.d.cts +3 -2
  84. package/dist/completion/CompletionService.d.ts +3 -2
  85. package/dist/completion/CompletionService.js +34 -3457
  86. package/dist/completion/NativeSearchInjector.cjs +8 -192
  87. package/dist/completion/NativeSearchInjector.js +7 -162
  88. package/dist/completion/ProviderSearchInjector.cjs +12 -39
  89. package/dist/completion/native-search-types.cjs +13 -66
  90. package/dist/completion/native-search-types.js +7 -31
  91. package/dist/completion/openrouter-headers.cjs +15 -71
  92. package/dist/completion/openrouter-headers.js +8 -34
  93. package/dist/completion/openrouter-models.cjs +10 -67
  94. package/dist/completion/openrouter-models.js +4 -34
  95. package/dist/completion/types.cjs +1 -18
  96. package/dist/completion/url-builder.cjs +24 -138
  97. package/dist/completion/url-builder.js +12 -92
  98. package/dist/completion.cjs +55 -3989
  99. package/dist/completion.d.cts +3 -2
  100. package/dist/completion.d.ts +3 -2
  101. package/dist/completion.js +63 -3953
  102. package/dist/index.cjs +197 -10429
  103. package/dist/index.d.cts +9 -2
  104. package/dist/index.d.ts +9 -2
  105. package/dist/index.js +125 -10268
  106. package/dist/logger-4GvQNzhE.d.cts +22 -0
  107. package/dist/logger-4GvQNzhE.d.ts +22 -0
  108. package/dist/outbound-api/routeResolver.cjs +7 -217
  109. package/dist/outbound-api/routeResolver.d.cts +2 -1
  110. package/dist/outbound-api/routeResolver.d.ts +2 -1
  111. package/dist/outbound-api/routeResolver.js +6 -187
  112. package/dist/outbound-api/subscriptionRegistryPort.cjs +7 -37
  113. package/dist/outbound-api/subscriptionRegistryPort.d.cts +2 -1
  114. package/dist/outbound-api/subscriptionRegistryPort.d.ts +2 -1
  115. package/dist/outbound-api/subscriptionRegistryPort.js +4 -8
  116. package/dist/outbound-api/types.cjs +1 -18
  117. package/dist/outbound-api/types.d.cts +2 -1
  118. package/dist/outbound-api/types.d.ts +2 -1
  119. package/dist/outbound-api.cjs +35 -5221
  120. package/dist/outbound-api.d.cts +2 -1
  121. package/dist/outbound-api.d.ts +2 -1
  122. package/dist/outbound-api.js +54 -5194
  123. package/dist/pipeline/AuthSource.cjs +1 -18
  124. package/dist/pipeline/LlmConfigProviderAuth.cjs +5 -166
  125. package/dist/pipeline/LlmConfigProviderAuth.d.cts +2 -1
  126. package/dist/pipeline/LlmConfigProviderAuth.d.ts +2 -1
  127. package/dist/pipeline/LlmConfigProviderAuth.js +5 -139
  128. package/dist/pipeline/SubscriptionAuthSource.cjs +6 -128
  129. package/dist/pipeline/SubscriptionAuthSource.js +5 -99
  130. package/dist/pipeline/SubscriptionAuthStrategy.cjs +1 -18
  131. package/dist/pipeline/executeProviderCall.cjs +5 -69
  132. package/dist/pipeline/executeProviderCall.js +3 -42
  133. package/dist/pipeline/resolveProviderChain.cjs +5 -46
  134. package/dist/pipeline/resolveProviderChain.js +3 -19
  135. package/dist/pipeline/resolveSubscriptionChain.cjs +5 -67
  136. package/dist/pipeline/resolveSubscriptionChain.js +3 -40
  137. package/dist/ports/gemini-code-assist-resolver.cjs +7 -37
  138. package/dist/ports/gemini-code-assist-resolver.js +4 -8
  139. package/dist/ports/pricing-store.cjs +1 -0
  140. package/dist/ports/pricing-store.d.cts +50 -0
  141. package/dist/ports/pricing-store.d.ts +50 -0
  142. package/dist/ports/pricing-store.js +0 -0
  143. package/dist/ports/provider-config-source.cjs +1 -18
  144. package/dist/ports/usage-event-store.cjs +1 -0
  145. package/dist/ports/usage-event-store.d.cts +29 -0
  146. package/dist/ports/usage-event-store.d.ts +29 -0
  147. package/dist/ports/usage-event-store.js +0 -0
  148. package/dist/ports/web-search-backend.cjs +1 -18
  149. package/dist/ports.cjs +1 -18
  150. package/dist/ports.d.cts +6 -1
  151. package/dist/ports.d.ts +6 -1
  152. package/dist/provider-proxy/ProviderProxy.cjs +40 -4643
  153. package/dist/provider-proxy/ProviderProxy.d.cts +2 -1
  154. package/dist/provider-proxy/ProviderProxy.d.ts +2 -1
  155. package/dist/provider-proxy/ProviderProxy.js +35 -4613
  156. package/dist/provider-proxy/ingress/providerProxyShared.cjs +35 -2941
  157. package/dist/provider-proxy/ingress/providerProxyShared.d.cts +2 -1
  158. package/dist/provider-proxy/ingress/providerProxyShared.d.ts +2 -1
  159. package/dist/provider-proxy/ingress/providerProxyShared.js +41 -2914
  160. package/dist/provider-proxy/matchText.cjs +11 -72
  161. package/dist/provider-proxy/matchText.js +6 -39
  162. package/dist/provider-proxy/types.cjs +1 -18
  163. package/dist/provider-proxy/types.d.cts +2 -1
  164. package/dist/provider-proxy/types.d.ts +2 -1
  165. package/dist/provider-proxy.cjs +35 -4655
  166. package/dist/provider-proxy.d.cts +2 -1
  167. package/dist/provider-proxy.d.ts +2 -1
  168. package/dist/provider-proxy.js +39 -4628
  169. package/dist/serializeError.cjs +5 -81
  170. package/dist/serializeError.js +3 -54
  171. package/dist/sse-parser.cjs +7 -455
  172. package/dist/sse-parser.js +4 -426
  173. package/dist/transformer/TransformerChainExecutor.cjs +4 -318
  174. package/dist/transformer/TransformerChainExecutor.js +4 -291
  175. package/dist/transformer/TransformerService.cjs +5 -289
  176. package/dist/transformer/TransformerService.js +3 -262
  177. package/dist/transformer/anthropicBetaInject.cjs +7 -50
  178. package/dist/transformer/anthropicBetaInject.js +4 -21
  179. package/dist/transformer/transformers/AnthropicTransformer.cjs +3 -1014
  180. package/dist/transformer/transformers/AnthropicTransformer.js +3 -987
  181. package/dist/transformer/transformers/GeminiCodeAssistTransformer.cjs +4 -1106
  182. package/dist/transformer/transformers/GeminiCodeAssistTransformer.js +7 -1079
  183. package/dist/transformer/transformers/GeminiTransformer.cjs +4 -1010
  184. package/dist/transformer/transformers/GeminiTransformer.js +4 -983
  185. package/dist/transformer/transformers/OpenAIResponseTransformer.cjs +3 -535
  186. package/dist/transformer/transformers/OpenAIResponseTransformer.js +3 -510
  187. package/dist/transformer/transformers/OpenCodeGoTransformer.cjs +5 -72
  188. package/dist/transformer/transformers/OpenCodeGoTransformer.js +3 -45
  189. package/dist/transformer/transformers/ReasoningTransformer.cjs +3 -270
  190. package/dist/transformer/transformers/ReasoningTransformer.js +2 -249
  191. package/dist/transformer/transformers.cjs +10 -3177
  192. package/dist/transformer/transformers.js +23 -3158
  193. package/dist/transformer/types.cjs +1 -18
  194. package/dist/transformer.cjs +13 -3726
  195. package/dist/transformer.js +17 -3706
  196. package/dist/usage/pricing-engine.cjs +6 -0
  197. package/dist/usage/pricing-engine.d.cts +83 -0
  198. package/dist/usage/pricing-engine.d.ts +83 -0
  199. package/dist/usage/pricing-engine.js +6 -0
  200. package/dist/usage/usage-recorder.cjs +6 -0
  201. package/dist/usage/usage-recorder.d.cts +73 -0
  202. package/dist/usage/usage-recorder.d.ts +73 -0
  203. package/dist/usage/usage-recorder.js +6 -0
  204. package/dist/usage.cjs +11 -0
  205. package/dist/usage.d.cts +8 -0
  206. package/dist/usage.d.ts +8 -0
  207. package/dist/usage.js +11 -0
  208. package/package.json +1 -1
  209. package/dist/ApiKeyPoolService-BmMkau07.d.cts +0 -170
  210. package/dist/ApiKeyPoolService-BmMkau07.d.ts +0 -170
@@ -0,0 +1,913 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/transformer/transformers/utils/gemini.response-in.ts
2
+ var FINISH_REASON_TO_GEMINI = {
3
+ stop: "STOP",
4
+ length: "MAX_TOKENS",
5
+ tool_calls: "STOP",
6
+ content_filter: "SAFETY",
7
+ // Already-lowercased Gemini reasons (pass-through from another transformer)
8
+ max_tokens: "MAX_TOKENS",
9
+ safety: "SAFETY"
10
+ };
11
+ function toGeminiFinishReason(openaiReason) {
12
+ if (!openaiReason) return null;
13
+ return FINISH_REASON_TO_GEMINI[openaiReason] || openaiReason.toUpperCase();
14
+ }
15
+ function convertOpenAIResponseToGemini(openaiData) {
16
+ const choice = _optionalChain([openaiData, 'access', _ => _.choices, 'optionalAccess', _2 => _2[0]]);
17
+ const message = _nullishCoalesce(_optionalChain([choice, 'optionalAccess', _3 => _3.message]), () => ( {}));
18
+ const usage = openaiData.usage;
19
+ const usagePromptDetails = _optionalChain([usage, 'optionalAccess', _4 => _4.prompt_tokens_details]);
20
+ const usageOutputDetails = _optionalChain([usage, 'optionalAccess', _5 => _5.output_tokens_details]);
21
+ const parts = [];
22
+ const thinking = message.thinking;
23
+ if (_optionalChain([thinking, 'optionalAccess', _6 => _6.content])) {
24
+ parts.push({ text: thinking.content, thought: true });
25
+ }
26
+ if (_optionalChain([thinking, 'optionalAccess', _7 => _7.signature])) {
27
+ parts.push({ thoughtSignature: thinking.signature });
28
+ }
29
+ if (message.content) {
30
+ parts.push({ text: message.content });
31
+ }
32
+ const toolCalls = message.tool_calls;
33
+ if (_optionalChain([toolCalls, 'optionalAccess', _8 => _8.length])) {
34
+ for (const tc of toolCalls) {
35
+ const func = tc.function;
36
+ let args = {};
37
+ try {
38
+ const raw = func.arguments;
39
+ args = typeof raw === "string" ? JSON.parse(raw) : raw;
40
+ } catch (e2) {
41
+ args = {};
42
+ }
43
+ parts.push({
44
+ functionCall: {
45
+ id: tc.id,
46
+ name: func.name,
47
+ args
48
+ }
49
+ });
50
+ }
51
+ }
52
+ if (parts.length === 0) {
53
+ parts.push({ text: "" });
54
+ }
55
+ return {
56
+ responseId: openaiData.id || "",
57
+ modelVersion: openaiData.model || "",
58
+ candidates: [{
59
+ content: { parts },
60
+ finishReason: toGeminiFinishReason(_optionalChain([choice, 'optionalAccess', _9 => _9.finish_reason]))
61
+ }],
62
+ usageMetadata: usage ? {
63
+ promptTokenCount: usage.prompt_tokens || 0,
64
+ candidatesTokenCount: usage.completion_tokens || 0,
65
+ totalTokenCount: usage.total_tokens || 0,
66
+ cachedContentTokenCount: _optionalChain([usagePromptDetails, 'optionalAccess', _10 => _10.cached_tokens]) || 0,
67
+ thoughtsTokenCount: _optionalChain([usageOutputDetails, 'optionalAccess', _11 => _11.reasoning_tokens]) || 0
68
+ } : void 0
69
+ };
70
+ }
71
+ function convertOpenAIStreamToGemini(openaiStream, logger) {
72
+ const decoder = new TextDecoder();
73
+ const encoder = new TextEncoder();
74
+ const pendingToolCalls = /* @__PURE__ */ new Map();
75
+ let model = "";
76
+ let responseId = "";
77
+ return new ReadableStream({
78
+ start: async (controller) => {
79
+ const reader = openaiStream.getReader();
80
+ let buffer = "";
81
+ let isClosed = false;
82
+ const emit = (data) => {
83
+ if (isClosed) return;
84
+ try {
85
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}
86
+
87
+ `));
88
+ } catch (e3) {
89
+ isClosed = true;
90
+ }
91
+ };
92
+ const flushToolCalls = () => {
93
+ if (pendingToolCalls.size === 0) return;
94
+ const parts = [];
95
+ for (const tc of pendingToolCalls.values()) {
96
+ let args = {};
97
+ try {
98
+ args = JSON.parse(tc.args || "{}");
99
+ } catch (e4) {
100
+ }
101
+ parts.push({
102
+ functionCall: { id: tc.id, name: tc.name, args }
103
+ });
104
+ }
105
+ pendingToolCalls.clear();
106
+ emit({
107
+ responseId,
108
+ modelVersion: model,
109
+ candidates: [{ content: { parts }, finishReason: null }]
110
+ });
111
+ };
112
+ try {
113
+ while (true) {
114
+ const { done, value } = await reader.read();
115
+ if (done) break;
116
+ buffer += decoder.decode(value, { stream: true });
117
+ const lines = buffer.split("\n");
118
+ buffer = lines.pop() || "";
119
+ for (const line of lines) {
120
+ if (isClosed) break;
121
+ if (!line.startsWith("data:")) continue;
122
+ const data = line.slice(5).trim();
123
+ if (!data || data === "[DONE]") continue;
124
+ try {
125
+ const chunk = JSON.parse(data);
126
+ if (!responseId && chunk.id) responseId = chunk.id;
127
+ if (!model && chunk.model) model = chunk.model;
128
+ const choice = _optionalChain([chunk, 'access', _12 => _12.choices, 'optionalAccess', _13 => _13[0]]);
129
+ if (!choice) continue;
130
+ const delta = _nullishCoalesce(choice.delta, () => ( {}));
131
+ if (delta.thinking) {
132
+ const parts = [];
133
+ if (delta.thinking.content) {
134
+ parts.push({ text: delta.thinking.content, thought: true });
135
+ }
136
+ if (delta.thinking.signature) {
137
+ parts.push({ thoughtSignature: delta.thinking.signature });
138
+ }
139
+ if (parts.length > 0) {
140
+ emit({
141
+ responseId,
142
+ modelVersion: model,
143
+ candidates: [{ content: { parts }, finishReason: null }]
144
+ });
145
+ }
146
+ }
147
+ if (delta.content) {
148
+ emit({
149
+ responseId,
150
+ modelVersion: model,
151
+ candidates: [{
152
+ content: { parts: [{ text: delta.content }] },
153
+ finishReason: null
154
+ }]
155
+ });
156
+ }
157
+ if (delta.tool_calls) {
158
+ for (const tc of delta.tool_calls) {
159
+ const idx = _nullishCoalesce(tc.index, () => ( 0));
160
+ const existing = pendingToolCalls.get(idx);
161
+ const func = tc.function;
162
+ if (existing) {
163
+ if (_optionalChain([func, 'optionalAccess', _14 => _14.arguments])) {
164
+ existing.args += func.arguments;
165
+ }
166
+ } else {
167
+ pendingToolCalls.set(idx, {
168
+ id: tc.id || `tool_${Date.now()}_${idx}`,
169
+ name: _optionalChain([func, 'optionalAccess', _15 => _15.name]) || "",
170
+ args: _optionalChain([func, 'optionalAccess', _16 => _16.arguments]) || ""
171
+ });
172
+ }
173
+ }
174
+ }
175
+ if (choice.finish_reason) {
176
+ flushToolCalls();
177
+ const geminiUsage = chunk.usage ? {
178
+ promptTokenCount: chunk.usage.prompt_tokens || 0,
179
+ candidatesTokenCount: chunk.usage.completion_tokens || 0,
180
+ totalTokenCount: chunk.usage.total_tokens || 0,
181
+ cachedContentTokenCount: _optionalChain([chunk, 'access', _17 => _17.usage, 'access', _18 => _18.prompt_tokens_details, 'optionalAccess', _19 => _19.cached_tokens]) || 0,
182
+ thoughtsTokenCount: _optionalChain([chunk, 'access', _20 => _20.usage, 'access', _21 => _21.output_tokens_details, 'optionalAccess', _22 => _22.reasoning_tokens]) || 0
183
+ } : void 0;
184
+ emit({
185
+ responseId,
186
+ modelVersion: model,
187
+ candidates: [{
188
+ content: { parts: [{ text: "" }] },
189
+ finishReason: toGeminiFinishReason(choice.finish_reason) || "STOP"
190
+ }],
191
+ usageMetadata: geminiUsage
192
+ });
193
+ }
194
+ } catch (e) {
195
+ _optionalChain([logger, 'optionalAccess', _23 => _23.error, 'call', _24 => _24(`Error parsing OpenAI stream chunk for Gemini conversion: ${e}`)]);
196
+ }
197
+ }
198
+ }
199
+ flushToolCalls();
200
+ } catch (e) {
201
+ if (!isClosed) controller.error(e);
202
+ } finally {
203
+ if (!isClosed) {
204
+ try {
205
+ controller.close();
206
+ } catch (e5) {
207
+ }
208
+ }
209
+ reader.releaseLock();
210
+ }
211
+ }
212
+ });
213
+ }
214
+ async function transformResponseIn(response, logger) {
215
+ const contentType = _nullishCoalesce(response.headers.get("Content-Type"), () => ( ""));
216
+ if (contentType.includes("text/event-stream")) {
217
+ if (!response.body) {
218
+ throw new Error("Stream response body is null");
219
+ }
220
+ const geminiStream = convertOpenAIStreamToGemini(response.body, logger);
221
+ return new Response(geminiStream, {
222
+ headers: {
223
+ "Content-Type": "text/event-stream",
224
+ "Cache-Control": "no-cache",
225
+ Connection: "keep-alive"
226
+ }
227
+ });
228
+ }
229
+ const data = await response.json();
230
+ const geminiResponse = convertOpenAIResponseToGemini(data);
231
+ return new Response(JSON.stringify(geminiResponse), {
232
+ status: response.status,
233
+ statusText: response.statusText,
234
+ headers: { "Content-Type": "application/json" }
235
+ });
236
+ }
237
+
238
+ // src/transformer/transformers/utils/gemini.stream.ts
239
+ async function transformResponseOut(response, providerName, logger) {
240
+ const contentType = _nullishCoalesce(response.headers.get("Content-Type"), () => ( ""));
241
+ if (contentType.includes("application/json")) {
242
+ return handleJsonResponse(response, providerName, logger);
243
+ } else if (contentType.includes("stream") || contentType.includes("text/event-stream")) {
244
+ return handleStreamResponse(response, providerName, logger);
245
+ }
246
+ return response;
247
+ }
248
+ async function handleJsonResponse(response, providerName, logger) {
249
+ const jsonResponse = await response.json();
250
+ _optionalChain([logger, 'optionalAccess', _25 => _25.debug, 'call', _26 => _26(`${providerName} JSON response received`)]);
251
+ const parts = _optionalChain([jsonResponse, 'access', _27 => _27.candidates, 'optionalAccess', _28 => _28[0], 'optionalAccess', _29 => _29.content, 'optionalAccess', _30 => _30.parts]) || [];
252
+ let thinkingContent = "";
253
+ let thinkingSignature = "";
254
+ const nonThinkingParts = [];
255
+ for (const part of parts) {
256
+ if (part.text && part.thought === true) {
257
+ thinkingContent += part.text;
258
+ } else {
259
+ nonThinkingParts.push(part);
260
+ }
261
+ }
262
+ thinkingSignature = _nullishCoalesce(_optionalChain([parts, 'access', _31 => _31.find, 'call', _32 => _32((part) => part.thoughtSignature), 'optionalAccess', _33 => _33.thoughtSignature]), () => ( ""));
263
+ const toolCalls = nonThinkingParts.filter((part) => part.functionCall).map((part) => ({
264
+ id: _optionalChain([part, 'access', _34 => _34.functionCall, 'optionalAccess', _35 => _35.id]) || `tool_${Math.random().toString(36).substring(2, 15)}`,
265
+ type: "function",
266
+ function: {
267
+ name: _nullishCoalesce(_optionalChain([part, 'access', _36 => _36.functionCall, 'optionalAccess', _37 => _37.name]), () => ( "")),
268
+ arguments: JSON.stringify(_optionalChain([part, 'access', _38 => _38.functionCall, 'optionalAccess', _39 => _39.args]) || {})
269
+ }
270
+ }));
271
+ const textContent = nonThinkingParts.filter((part) => part.text).map((part) => part.text).join("\n");
272
+ const openAIResponse = {
273
+ id: _nullishCoalesce(jsonResponse.responseId, () => ( "")),
274
+ choices: [
275
+ {
276
+ finish_reason: (_nullishCoalesce(_optionalChain([jsonResponse, 'access', _40 => _40.candidates, 'optionalAccess', _41 => _41[0], 'optionalAccess', _42 => _42.finishReason]), () => ( ""))).toLowerCase() || null,
277
+ index: 0,
278
+ message: {
279
+ content: textContent,
280
+ role: "assistant",
281
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
282
+ ...thinkingSignature && {
283
+ thinking: {
284
+ content: thinkingContent || "(no content)",
285
+ signature: thinkingSignature
286
+ }
287
+ }
288
+ }
289
+ }
290
+ ],
291
+ created: Math.floor(Date.now() / 1e3),
292
+ model: _nullishCoalesce(jsonResponse.modelVersion, () => ( "")),
293
+ object: "chat.completion",
294
+ usage: {
295
+ completion_tokens: _optionalChain([jsonResponse, 'access', _43 => _43.usageMetadata, 'optionalAccess', _44 => _44.candidatesTokenCount]) || 0,
296
+ prompt_tokens: _optionalChain([jsonResponse, 'access', _45 => _45.usageMetadata, 'optionalAccess', _46 => _46.promptTokenCount]) || 0,
297
+ prompt_tokens_details: {
298
+ cached_tokens: _optionalChain([jsonResponse, 'access', _47 => _47.usageMetadata, 'optionalAccess', _48 => _48.cachedContentTokenCount]) || 0
299
+ },
300
+ total_tokens: _optionalChain([jsonResponse, 'access', _49 => _49.usageMetadata, 'optionalAccess', _50 => _50.totalTokenCount]) || 0,
301
+ output_tokens_details: {
302
+ reasoning_tokens: _optionalChain([jsonResponse, 'access', _51 => _51.usageMetadata, 'optionalAccess', _52 => _52.thoughtsTokenCount]) || 0
303
+ }
304
+ }
305
+ };
306
+ return new Response(JSON.stringify(openAIResponse), {
307
+ status: response.status,
308
+ statusText: response.statusText,
309
+ headers: response.headers
310
+ });
311
+ }
312
+ function handleStreamResponse(response, providerName, logger) {
313
+ if (!response.body) {
314
+ return response;
315
+ }
316
+ const decoder = new TextDecoder();
317
+ const encoder = new TextEncoder();
318
+ let signatureSent = false;
319
+ let contentSent = false;
320
+ let hasThinkingContent = false;
321
+ let pendingContent = "";
322
+ let contentIndex = 0;
323
+ let toolCallIndex = -1;
324
+ const stream = new ReadableStream({
325
+ async start(controller) {
326
+ const reader = response.body.getReader();
327
+ let buffer = "";
328
+ const processLine = async (line) => {
329
+ if (!line.startsWith("data: ")) return;
330
+ const chunkStr = line.slice(6).trim();
331
+ if (!chunkStr) return;
332
+ _optionalChain([logger, 'optionalAccess', _53 => _53.debug, 'call', _54 => _54(`${providerName} chunk: ${chunkStr.substring(0, 100)}...`)]);
333
+ try {
334
+ const chunk = JSON.parse(chunkStr);
335
+ if (!_optionalChain([chunk, 'access', _55 => _55.candidates, 'optionalAccess', _56 => _56[0]])) {
336
+ _optionalChain([logger, 'optionalAccess', _57 => _57.debug, 'call', _58 => _58("Invalid chunk structure")]);
337
+ return;
338
+ }
339
+ const candidate = chunk.candidates[0];
340
+ const parts = _optionalChain([candidate, 'access', _59 => _59.content, 'optionalAccess', _60 => _60.parts]) || [];
341
+ parts.filter((part) => part.text && part.thought === true).forEach((part) => {
342
+ hasThinkingContent = true;
343
+ const thinkingChunk = createChunk({
344
+ responseId: chunk.responseId,
345
+ modelVersion: chunk.modelVersion,
346
+ contentIndex,
347
+ delta: {
348
+ role: "assistant",
349
+ content: null,
350
+ thinking: { content: part.text }
351
+ }
352
+ });
353
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(thinkingChunk)}
354
+
355
+ `));
356
+ });
357
+ const signature = _optionalChain([parts, 'access', _61 => _61.find, 'call', _62 => _62((part) => part.thoughtSignature), 'optionalAccess', _63 => _63.thoughtSignature]);
358
+ if (signature && !signatureSent) {
359
+ if (!hasThinkingContent) {
360
+ const thinkingChunk = createChunk({
361
+ responseId: chunk.responseId,
362
+ modelVersion: chunk.modelVersion,
363
+ contentIndex,
364
+ delta: {
365
+ role: "assistant",
366
+ content: null,
367
+ thinking: { content: "" }
368
+ }
369
+ });
370
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(thinkingChunk)}
371
+
372
+ `));
373
+ }
374
+ const signatureChunk = createChunk({
375
+ responseId: chunk.responseId,
376
+ modelVersion: chunk.modelVersion,
377
+ contentIndex,
378
+ delta: {
379
+ role: "assistant",
380
+ content: null,
381
+ thinking: { signature }
382
+ }
383
+ });
384
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(signatureChunk)}
385
+
386
+ `));
387
+ signatureSent = true;
388
+ contentIndex++;
389
+ if (pendingContent) {
390
+ const pendingChunk = createChunk({
391
+ responseId: chunk.responseId,
392
+ modelVersion: chunk.modelVersion,
393
+ contentIndex,
394
+ delta: { role: "assistant", content: pendingContent }
395
+ });
396
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(pendingChunk)}
397
+
398
+ `));
399
+ pendingContent = "";
400
+ contentSent = true;
401
+ }
402
+ }
403
+ const toolCalls = parts.filter((part) => part.functionCall).map((part) => ({
404
+ id: _optionalChain([part, 'access', _64 => _64.functionCall, 'optionalAccess', _65 => _65.id]) || `ccr_tool_${Math.random().toString(36).substring(2, 15)}`,
405
+ type: "function",
406
+ function: {
407
+ name: _nullishCoalesce(_optionalChain([part, 'access', _66 => _66.functionCall, 'optionalAccess', _67 => _67.name]), () => ( "")),
408
+ arguments: JSON.stringify(_optionalChain([part, 'access', _68 => _68.functionCall, 'optionalAccess', _69 => _69.args]) || {})
409
+ }
410
+ }));
411
+ const textContent = parts.filter((part) => part.text && part.thought !== true).map((part) => part.text).join("\n");
412
+ if (!textContent && signatureSent && !contentSent) {
413
+ contentSent = true;
414
+ }
415
+ if (hasThinkingContent && textContent && !signatureSent) {
416
+ if (_optionalChain([chunk, 'access', _70 => _70.modelVersion, 'optionalAccess', _71 => _71.includes, 'call', _72 => _72("3")])) {
417
+ pendingContent += textContent;
418
+ return;
419
+ } else {
420
+ const signatureChunk = createChunk({
421
+ responseId: chunk.responseId,
422
+ modelVersion: chunk.modelVersion,
423
+ contentIndex,
424
+ delta: {
425
+ role: "assistant",
426
+ content: null,
427
+ thinking: { signature: `ccr_${Date.now()}` }
428
+ }
429
+ });
430
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(signatureChunk)}
431
+
432
+ `));
433
+ signatureSent = true;
434
+ }
435
+ }
436
+ if (textContent) {
437
+ if (!pendingContent) contentIndex++;
438
+ const contentChunk = createChunk({
439
+ responseId: chunk.responseId,
440
+ modelVersion: chunk.modelVersion,
441
+ contentIndex,
442
+ delta: { role: "assistant", content: textContent },
443
+ finishReason: candidate.finishReason,
444
+ usageMetadata: chunk.usageMetadata,
445
+ groundingMetadata: candidate.groundingMetadata
446
+ });
447
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(contentChunk)}
448
+
449
+ `));
450
+ contentSent = true;
451
+ }
452
+ if (toolCalls.length > 0) {
453
+ for (const tool of toolCalls) {
454
+ contentIndex++;
455
+ toolCallIndex++;
456
+ const toolChunk = createChunk({
457
+ responseId: chunk.responseId,
458
+ modelVersion: chunk.modelVersion,
459
+ contentIndex,
460
+ delta: {
461
+ role: "assistant",
462
+ tool_calls: [{ ...tool, index: toolCallIndex }]
463
+ },
464
+ finishReason: candidate.finishReason,
465
+ usageMetadata: chunk.usageMetadata,
466
+ groundingMetadata: candidate.groundingMetadata
467
+ });
468
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(toolChunk)}
469
+
470
+ `));
471
+ }
472
+ contentSent = true;
473
+ }
474
+ } catch (_error) {
475
+ _optionalChain([logger, 'optionalAccess', _73 => _73.error, 'call', _74 => _74(`Error parsing ${providerName} stream chunk: ${chunkStr}`)]);
476
+ }
477
+ };
478
+ try {
479
+ while (true) {
480
+ const { done, value } = await reader.read();
481
+ if (done) {
482
+ if (buffer) await processLine(buffer);
483
+ break;
484
+ }
485
+ buffer += decoder.decode(value, { stream: true });
486
+ const lines = buffer.split("\n");
487
+ buffer = lines.pop() || "";
488
+ for (const line of lines) {
489
+ await processLine(line);
490
+ }
491
+ }
492
+ } catch (error) {
493
+ controller.error(error);
494
+ } finally {
495
+ controller.close();
496
+ }
497
+ }
498
+ });
499
+ return new Response(stream, {
500
+ status: response.status,
501
+ statusText: response.statusText,
502
+ headers: response.headers
503
+ });
504
+ }
505
+ function createChunk(options) {
506
+ const {
507
+ responseId,
508
+ modelVersion,
509
+ contentIndex,
510
+ delta,
511
+ finishReason,
512
+ usageMetadata,
513
+ groundingMetadata
514
+ } = options;
515
+ const chunk = {
516
+ choices: [
517
+ {
518
+ delta,
519
+ finish_reason: _optionalChain([finishReason, 'optionalAccess', _75 => _75.toLowerCase, 'call', _76 => _76()]) || null,
520
+ index: contentIndex,
521
+ logprobs: null
522
+ }
523
+ ],
524
+ created: Math.floor(Date.now() / 1e3),
525
+ id: responseId || "",
526
+ model: modelVersion || "",
527
+ object: "chat.completion.chunk",
528
+ system_fingerprint: "fp_a49d71b8a1"
529
+ };
530
+ if (usageMetadata) {
531
+ chunk.usage = {
532
+ completion_tokens: usageMetadata.candidatesTokenCount || 0,
533
+ prompt_tokens: usageMetadata.promptTokenCount || 0,
534
+ prompt_tokens_details: {
535
+ cached_tokens: usageMetadata.cachedContentTokenCount || 0
536
+ },
537
+ total_tokens: usageMetadata.totalTokenCount || 0,
538
+ output_tokens_details: {
539
+ reasoning_tokens: usageMetadata.thoughtsTokenCount || 0
540
+ }
541
+ };
542
+ }
543
+ if (_optionalChain([groundingMetadata, 'optionalAccess', _77 => _77.groundingChunks, 'optionalAccess', _78 => _78.length])) {
544
+ const annotations = groundingMetadata.groundingChunks.map((groundingChunk, index) => {
545
+ const support = _optionalChain([groundingMetadata, 'access', _79 => _79.groundingSupports, 'optionalAccess', _80 => _80.find, 'call', _81 => _81(
546
+ (s) => _optionalChain([s, 'access', _82 => _82.groundingChunkIndices, 'optionalAccess', _83 => _83.includes, 'call', _84 => _84(index)])
547
+ )]);
548
+ return {
549
+ type: "url_citation",
550
+ url_citation: {
551
+ url: _optionalChain([groundingChunk, 'access', _85 => _85.web, 'optionalAccess', _86 => _86.uri]) || "",
552
+ title: _optionalChain([groundingChunk, 'access', _87 => _87.web, 'optionalAccess', _88 => _88.title]) || "",
553
+ content: _optionalChain([support, 'optionalAccess', _89 => _89.segment, 'optionalAccess', _90 => _90.text]) || "",
554
+ start_index: _optionalChain([support, 'optionalAccess', _91 => _91.segment, 'optionalAccess', _92 => _92.startIndex]) || 0,
555
+ end_index: _optionalChain([support, 'optionalAccess', _93 => _93.segment, 'optionalAccess', _94 => _94.endIndex]) || 0
556
+ }
557
+ };
558
+ });
559
+ chunk.choices[0].delta.annotations = annotations;
560
+ }
561
+ return chunk;
562
+ }
563
+
564
+ // src/transformer/transformers/utils/gemini.schema.ts
565
+ var GeminiType = {
566
+ TYPE_UNSPECIFIED: "TYPE_UNSPECIFIED",
567
+ STRING: "STRING",
568
+ NUMBER: "NUMBER",
569
+ INTEGER: "INTEGER",
570
+ BOOLEAN: "BOOLEAN",
571
+ ARRAY: "ARRAY",
572
+ OBJECT: "OBJECT",
573
+ NULL: "NULL"
574
+ };
575
+ function flattenTypeArrayToAnyOf(typeList, resultingSchema) {
576
+ if (typeList.includes("null")) {
577
+ resultingSchema.nullable = true;
578
+ }
579
+ const listWithoutNull = typeList.filter((type) => type !== "null");
580
+ if (listWithoutNull.length === 1) {
581
+ const upperCaseType = listWithoutNull[0].toUpperCase();
582
+ resultingSchema.type = Object.values(GeminiType).includes(upperCaseType) ? upperCaseType : GeminiType.TYPE_UNSPECIFIED;
583
+ } else {
584
+ resultingSchema.anyOf = listWithoutNull.map((typeName) => {
585
+ const upperCaseType = typeName.toUpperCase();
586
+ return {
587
+ type: Object.values(GeminiType).includes(upperCaseType) ? upperCaseType : GeminiType.TYPE_UNSPECIFIED
588
+ };
589
+ });
590
+ }
591
+ }
592
+ function processJsonSchema(jsonSchema) {
593
+ const genAISchema = {};
594
+ const schemaFieldNames = ["items"];
595
+ const listSchemaFieldNames = ["anyOf"];
596
+ const dictSchemaFieldNames = ["properties"];
597
+ let workingSchema = jsonSchema;
598
+ if (workingSchema.type && workingSchema.anyOf) {
599
+ throw new Error("type and anyOf cannot be both populated.");
600
+ }
601
+ const incomingAnyOf = workingSchema.anyOf;
602
+ if (incomingAnyOf && Array.isArray(incomingAnyOf) && incomingAnyOf.length === 2) {
603
+ if (_optionalChain([incomingAnyOf, 'access', _95 => _95[0], 'optionalAccess', _96 => _96.type]) === "null") {
604
+ genAISchema.nullable = true;
605
+ workingSchema = incomingAnyOf[1];
606
+ } else if (_optionalChain([incomingAnyOf, 'access', _97 => _97[1], 'optionalAccess', _98 => _98.type]) === "null") {
607
+ genAISchema.nullable = true;
608
+ workingSchema = incomingAnyOf[0];
609
+ }
610
+ }
611
+ if (workingSchema.type && Array.isArray(workingSchema.type)) {
612
+ flattenTypeArrayToAnyOf(workingSchema.type, genAISchema);
613
+ }
614
+ for (const [fieldName, fieldValue] of Object.entries(workingSchema)) {
615
+ if (fieldValue == null) {
616
+ continue;
617
+ }
618
+ if (fieldName === "type") {
619
+ if (fieldValue === "null") {
620
+ throw new Error("type: null cannot be the only possible type for the field.");
621
+ }
622
+ if (Array.isArray(fieldValue)) {
623
+ continue;
624
+ }
625
+ const upperCaseValue = fieldValue.toUpperCase();
626
+ genAISchema.type = Object.values(GeminiType).includes(upperCaseValue) ? upperCaseValue : GeminiType.TYPE_UNSPECIFIED;
627
+ } else if (schemaFieldNames.includes(fieldName)) {
628
+ genAISchema[fieldName] = processJsonSchema(fieldValue);
629
+ } else if (listSchemaFieldNames.includes(fieldName)) {
630
+ const listValue = [];
631
+ for (const item of fieldValue) {
632
+ if (item.type === "null") {
633
+ genAISchema.nullable = true;
634
+ continue;
635
+ }
636
+ listValue.push(processJsonSchema(item));
637
+ }
638
+ genAISchema[fieldName] = listValue;
639
+ } else if (dictSchemaFieldNames.includes(fieldName)) {
640
+ const dictValue = {};
641
+ for (const [key, value] of Object.entries(fieldValue)) {
642
+ dictValue[key] = processJsonSchema(value);
643
+ }
644
+ genAISchema[fieldName] = dictValue;
645
+ } else {
646
+ if (fieldName === "additionalProperties") {
647
+ continue;
648
+ }
649
+ genAISchema[fieldName] = fieldValue;
650
+ }
651
+ }
652
+ return genAISchema;
653
+ }
654
+ function transformTool(tool) {
655
+ const functionDeclarations = tool.functionDeclarations;
656
+ if (functionDeclarations) {
657
+ for (const functionDeclaration of functionDeclarations) {
658
+ if (functionDeclaration.parameters) {
659
+ const params = functionDeclaration.parameters;
660
+ if (!Object.keys(params).includes("$schema")) {
661
+ functionDeclaration.parameters = processJsonSchema(params);
662
+ } else {
663
+ if (!functionDeclaration.parametersJsonSchema) {
664
+ functionDeclaration.parametersJsonSchema = functionDeclaration.parameters;
665
+ delete functionDeclaration.parameters;
666
+ }
667
+ }
668
+ }
669
+ if (functionDeclaration.response) {
670
+ const response = functionDeclaration.response;
671
+ if (!Object.keys(response).includes("$schema")) {
672
+ functionDeclaration.response = processJsonSchema(response);
673
+ } else {
674
+ if (!functionDeclaration.responseJsonSchema) {
675
+ functionDeclaration.responseJsonSchema = functionDeclaration.response;
676
+ delete functionDeclaration.response;
677
+ }
678
+ }
679
+ }
680
+ }
681
+ }
682
+ return tool;
683
+ }
684
+
685
+ // src/transformer/transformers/utils/gemini.util.ts
686
+ function buildRequestBody(request) {
687
+ const tools = [];
688
+ const functionDeclarations = _optionalChain([request, 'access', _99 => _99.tools, 'optionalAccess', _100 => _100.filter, 'call', _101 => _101((tool) => tool.function.name !== "web_search"), 'optionalAccess', _102 => _102.map, 'call', _103 => _103((tool) => ({
689
+ name: tool.function.name,
690
+ description: tool.function.description,
691
+ parametersJsonSchema: tool.function.parameters
692
+ }))]);
693
+ if (_optionalChain([functionDeclarations, 'optionalAccess', _104 => _104.length])) {
694
+ tools.push(
695
+ transformTool({
696
+ functionDeclarations
697
+ })
698
+ );
699
+ }
700
+ const webSearch = _optionalChain([request, 'access', _105 => _105.tools, 'optionalAccess', _106 => _106.find, 'call', _107 => _107((tool) => tool.function.name === "web_search")]);
701
+ if (webSearch) {
702
+ tools.push({ googleSearch: {} });
703
+ }
704
+ const contents = [];
705
+ const toolResponses = request.messages.filter((item) => item.role === "tool");
706
+ request.messages.filter((item) => item.role !== "tool").forEach((message) => {
707
+ let role;
708
+ if (message.role === "assistant") {
709
+ role = "model";
710
+ } else if (["user", "system"].includes(message.role)) {
711
+ role = "user";
712
+ } else {
713
+ role = "user";
714
+ }
715
+ const parts = [];
716
+ if (typeof message.content === "string") {
717
+ const part = { text: message.content };
718
+ if (_optionalChain([message, 'access', _108 => _108.thinking, 'optionalAccess', _109 => _109.signature])) {
719
+ part.thoughtSignature = message.thinking.signature;
720
+ }
721
+ parts.push(part);
722
+ } else if (Array.isArray(message.content)) {
723
+ for (const content of message.content) {
724
+ if (content.type === "text") {
725
+ parts.push({ text: content.text || "" });
726
+ } else if (content.type === "image_url") {
727
+ const imageUrl = _nullishCoalesce(_optionalChain([content, 'access', _110 => _110.image_url, 'optionalAccess', _111 => _111.url]), () => ( ""));
728
+ if (imageUrl.startsWith("http")) {
729
+ parts.push({
730
+ file_data: {
731
+ mime_type: content.media_type,
732
+ file_uri: imageUrl
733
+ }
734
+ });
735
+ } else {
736
+ const data = imageUrl.split(",").pop() || imageUrl;
737
+ parts.push({
738
+ inlineData: {
739
+ mime_type: content.media_type || "image/png",
740
+ data
741
+ }
742
+ });
743
+ }
744
+ }
745
+ }
746
+ } else if (message.content && typeof message.content === "object") {
747
+ const contentObj = message.content;
748
+ if (contentObj.text) {
749
+ parts.push({ text: contentObj.text });
750
+ } else {
751
+ parts.push({ text: JSON.stringify(message.content) });
752
+ }
753
+ }
754
+ if (Array.isArray(message.tool_calls)) {
755
+ for (let index = 0; index < message.tool_calls.length; index++) {
756
+ const toolCall = message.tool_calls[index];
757
+ const functionCallPart = {
758
+ functionCall: {
759
+ id: toolCall.id || `tool_${Math.random().toString(36).substring(2, 15)}`,
760
+ name: toolCall.function.name,
761
+ args: JSON.parse(toolCall.function.arguments || "{}")
762
+ }
763
+ };
764
+ if (index === 0 && _optionalChain([message, 'access', _112 => _112.thinking, 'optionalAccess', _113 => _113.signature])) {
765
+ functionCallPart.thoughtSignature = message.thinking.signature;
766
+ }
767
+ parts.push(functionCallPart);
768
+ }
769
+ }
770
+ if (parts.length === 0) {
771
+ parts.push({ text: "" });
772
+ }
773
+ contents.push({ role, parts });
774
+ if (role === "model" && message.tool_calls) {
775
+ const functionResponses = message.tool_calls.map(
776
+ (tool) => {
777
+ const response = toolResponses.find((item) => item.tool_call_id === tool.id);
778
+ return {
779
+ functionResponse: {
780
+ name: _nullishCoalesce(_optionalChain([tool, 'access', _114 => _114.function, 'optionalAccess', _115 => _115.name]), () => ( "")),
781
+ response: { result: _optionalChain([response, 'optionalAccess', _116 => _116.content]) }
782
+ }
783
+ };
784
+ }
785
+ );
786
+ contents.push({
787
+ role: "user",
788
+ parts: functionResponses
789
+ });
790
+ }
791
+ });
792
+ const generationConfig = {};
793
+ if (_optionalChain([request, 'access', _117 => _117.reasoning, 'optionalAccess', _118 => _118.effort]) && request.reasoning.effort !== "none") {
794
+ generationConfig.thinkingConfig = {
795
+ includeThoughts: true
796
+ };
797
+ if (request.model.includes("gemini-3")) {
798
+ generationConfig.thinkingConfig.thinkingLevel = request.reasoning.effort;
799
+ } else {
800
+ const thinkingBudgets = request.model.includes("pro") ? [128, 32768] : [0, 24576];
801
+ const maxTokens = request.reasoning.max_tokens;
802
+ if (typeof maxTokens !== "undefined") {
803
+ let thinkingBudget;
804
+ if (maxTokens >= thinkingBudgets[0] && maxTokens <= thinkingBudgets[1]) {
805
+ thinkingBudget = maxTokens;
806
+ } else if (maxTokens < thinkingBudgets[0]) {
807
+ thinkingBudget = thinkingBudgets[0];
808
+ } else {
809
+ thinkingBudget = thinkingBudgets[1];
810
+ }
811
+ generationConfig.thinkingConfig.thinkingBudget = thinkingBudget;
812
+ }
813
+ }
814
+ }
815
+ const body = {
816
+ contents,
817
+ tools: tools.length > 0 ? tools : void 0,
818
+ generationConfig: Object.keys(generationConfig).length > 0 ? generationConfig : void 0
819
+ };
820
+ if (request.tool_choice) {
821
+ const toolConfig = {
822
+ functionCallingConfig: {}
823
+ };
824
+ if (request.tool_choice === "auto") {
825
+ toolConfig.functionCallingConfig.mode = "auto";
826
+ } else if (request.tool_choice === "none") {
827
+ toolConfig.functionCallingConfig.mode = "none";
828
+ } else if (request.tool_choice === "required") {
829
+ toolConfig.functionCallingConfig.mode = "any";
830
+ } else if (typeof request.tool_choice === "object" && _optionalChain([request, 'access', _119 => _119.tool_choice, 'access', _120 => _120.function, 'optionalAccess', _121 => _121.name])) {
831
+ toolConfig.functionCallingConfig.mode = "any";
832
+ toolConfig.functionCallingConfig.allowedFunctionNames = [
833
+ request.tool_choice.function.name
834
+ ];
835
+ }
836
+ body.toolConfig = toolConfig;
837
+ }
838
+ return body;
839
+ }
840
+ function transformRequestOut(request) {
841
+ const contents = request.contents;
842
+ const tools = request.tools;
843
+ const model = request.model;
844
+ const maxTokens = request.max_tokens;
845
+ const temperature = request.temperature;
846
+ const stream = request.stream;
847
+ const toolChoice = request.tool_choice;
848
+ const unifiedRequest = {
849
+ messages: [],
850
+ model,
851
+ max_tokens: maxTokens,
852
+ temperature,
853
+ stream,
854
+ tool_choice: toolChoice
855
+ };
856
+ if (Array.isArray(contents)) {
857
+ for (const content of contents) {
858
+ if (typeof content === "string") {
859
+ unifiedRequest.messages.push({
860
+ role: "user",
861
+ content
862
+ });
863
+ } else if ("text" in content && typeof content.text === "string") {
864
+ unifiedRequest.messages.push({
865
+ role: "user",
866
+ content: content.text || null
867
+ });
868
+ } else if ("role" in content && content.role === "user") {
869
+ const geminiContent = content;
870
+ unifiedRequest.messages.push({
871
+ role: "user",
872
+ content: _optionalChain([geminiContent, 'access', _122 => _122.parts, 'optionalAccess', _123 => _123.map, 'call', _124 => _124((part) => ({
873
+ type: "text",
874
+ text: part.text || ""
875
+ }))]) || []
876
+ });
877
+ } else if (content.role === "model") {
878
+ unifiedRequest.messages.push({
879
+ role: "assistant",
880
+ content: _optionalChain([content, 'access', _125 => _125.parts, 'optionalAccess', _126 => _126.map, 'call', _127 => _127((part) => ({
881
+ type: "text",
882
+ text: part.text || ""
883
+ }))]) || []
884
+ });
885
+ }
886
+ }
887
+ }
888
+ if (Array.isArray(tools)) {
889
+ unifiedRequest.tools = [];
890
+ for (const tool of tools) {
891
+ if (Array.isArray(tool.functionDeclarations)) {
892
+ for (const funcDecl of tool.functionDeclarations) {
893
+ unifiedRequest.tools.push({
894
+ type: "function",
895
+ function: {
896
+ name: funcDecl.name,
897
+ description: _nullishCoalesce(funcDecl.description, () => ( "")),
898
+ parameters: _nullishCoalesce(funcDecl.parameters, () => ( {}))
899
+ }
900
+ });
901
+ }
902
+ }
903
+ }
904
+ }
905
+ return unifiedRequest;
906
+ }
907
+
908
+
909
+
910
+
911
+
912
+
913
+ exports.transformResponseIn = transformResponseIn; exports.transformResponseOut = transformResponseOut; exports.buildRequestBody = buildRequestBody; exports.transformRequestOut = transformRequestOut;