@omnicross/core 0.1.0

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 (114) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +57 -0
  3. package/README.md +15 -0
  4. package/dist/ApiKeyPoolService-BmMkau07.d.cts +170 -0
  5. package/dist/ApiKeyPoolService-BmMkau07.d.ts +170 -0
  6. package/dist/ProviderProxy-f_8ziIhW.d.cts +120 -0
  7. package/dist/ProviderProxy-vjt8sQQk.d.ts +120 -0
  8. package/dist/SubscriptionAuthSource-Cr4fVEYY.d.cts +264 -0
  9. package/dist/SubscriptionAuthSource-D89zmiSS.d.ts +264 -0
  10. package/dist/auth/GeminiCodeAssistProjectResolver.cjs +218 -0
  11. package/dist/auth/GeminiCodeAssistProjectResolver.d.cts +68 -0
  12. package/dist/auth/GeminiCodeAssistProjectResolver.d.ts +68 -0
  13. package/dist/auth/GeminiCodeAssistProjectResolver.js +189 -0
  14. package/dist/completion/ApiKeyPoolService.cjs +331 -0
  15. package/dist/completion/ApiKeyPoolService.d.cts +2 -0
  16. package/dist/completion/ApiKeyPoolService.d.ts +2 -0
  17. package/dist/completion/ApiKeyPoolService.js +306 -0
  18. package/dist/completion.cjs +4027 -0
  19. package/dist/completion.d.cts +17 -0
  20. package/dist/completion.d.ts +17 -0
  21. package/dist/completion.js +3983 -0
  22. package/dist/index-BTSmc9Sm.d.ts +645 -0
  23. package/dist/index-DXazdTzZ.d.cts +645 -0
  24. package/dist/index.cjs +10428 -0
  25. package/dist/index.d.cts +128 -0
  26. package/dist/index.d.ts +128 -0
  27. package/dist/index.js +10339 -0
  28. package/dist/outbound-api/subscriptionRegistryPort.cjs +38 -0
  29. package/dist/outbound-api/subscriptionRegistryPort.d.cts +73 -0
  30. package/dist/outbound-api/subscriptionRegistryPort.d.ts +73 -0
  31. package/dist/outbound-api/subscriptionRegistryPort.js +12 -0
  32. package/dist/outbound-api.cjs +5264 -0
  33. package/dist/outbound-api.d.cts +320 -0
  34. package/dist/outbound-api.d.ts +320 -0
  35. package/dist/outbound-api.js +5218 -0
  36. package/dist/pipeline/SubscriptionAuthSource.cjs +131 -0
  37. package/dist/pipeline/SubscriptionAuthSource.d.cts +3 -0
  38. package/dist/pipeline/SubscriptionAuthSource.d.ts +3 -0
  39. package/dist/pipeline/SubscriptionAuthSource.js +103 -0
  40. package/dist/pipeline/SubscriptionAuthStrategy.cjs +18 -0
  41. package/dist/pipeline/SubscriptionAuthStrategy.d.cts +61 -0
  42. package/dist/pipeline/SubscriptionAuthStrategy.d.ts +61 -0
  43. package/dist/pipeline/SubscriptionAuthStrategy.js +0 -0
  44. package/dist/ports/gemini-code-assist-resolver.cjs +38 -0
  45. package/dist/ports/gemini-code-assist-resolver.d.cts +26 -0
  46. package/dist/ports/gemini-code-assist-resolver.d.ts +26 -0
  47. package/dist/ports/gemini-code-assist-resolver.js +12 -0
  48. package/dist/ports.cjs +18 -0
  49. package/dist/ports.d.cts +15 -0
  50. package/dist/ports.d.ts +15 -0
  51. package/dist/ports.js +0 -0
  52. package/dist/provider-proxy/ingress/providerProxyShared.cjs +2958 -0
  53. package/dist/provider-proxy/ingress/providerProxyShared.d.cts +77 -0
  54. package/dist/provider-proxy/ingress/providerProxyShared.d.ts +77 -0
  55. package/dist/provider-proxy/ingress/providerProxyShared.js +2925 -0
  56. package/dist/provider-proxy/matchText.cjs +73 -0
  57. package/dist/provider-proxy/matchText.d.cts +47 -0
  58. package/dist/provider-proxy/matchText.d.ts +47 -0
  59. package/dist/provider-proxy/matchText.js +45 -0
  60. package/dist/provider-proxy/types.cjs +18 -0
  61. package/dist/provider-proxy/types.d.cts +12 -0
  62. package/dist/provider-proxy/types.d.ts +12 -0
  63. package/dist/provider-proxy/types.js +0 -0
  64. package/dist/provider-proxy.cjs +4667 -0
  65. package/dist/provider-proxy.d.cts +69 -0
  66. package/dist/provider-proxy.d.ts +69 -0
  67. package/dist/provider-proxy.js +4636 -0
  68. package/dist/serializeError.cjs +82 -0
  69. package/dist/serializeError.d.cts +24 -0
  70. package/dist/serializeError.d.ts +24 -0
  71. package/dist/serializeError.js +57 -0
  72. package/dist/sse-parser.cjs +456 -0
  73. package/dist/sse-parser.d.cts +143 -0
  74. package/dist/sse-parser.d.ts +143 -0
  75. package/dist/sse-parser.js +430 -0
  76. package/dist/transformer/TransformerChainExecutor.cjs +321 -0
  77. package/dist/transformer/TransformerChainExecutor.d.cts +104 -0
  78. package/dist/transformer/TransformerChainExecutor.d.ts +104 -0
  79. package/dist/transformer/TransformerChainExecutor.js +294 -0
  80. package/dist/transformer/TransformerService.cjs +290 -0
  81. package/dist/transformer/TransformerService.d.cts +138 -0
  82. package/dist/transformer/TransformerService.d.ts +138 -0
  83. package/dist/transformer/TransformerService.js +265 -0
  84. package/dist/transformer/transformers/GeminiCodeAssistTransformer.cjs +1115 -0
  85. package/dist/transformer/transformers/GeminiCodeAssistTransformer.d.cts +102 -0
  86. package/dist/transformer/transformers/GeminiCodeAssistTransformer.d.ts +102 -0
  87. package/dist/transformer/transformers/GeminiCodeAssistTransformer.js +1085 -0
  88. package/dist/transformer/transformers/GeminiTransformer.cjs +1013 -0
  89. package/dist/transformer/transformers/GeminiTransformer.d.cts +70 -0
  90. package/dist/transformer/transformers/GeminiTransformer.d.ts +70 -0
  91. package/dist/transformer/transformers/GeminiTransformer.js +986 -0
  92. package/dist/transformer/transformers/OpenAIResponseTransformer.cjs +538 -0
  93. package/dist/transformer/transformers/OpenAIResponseTransformer.d.cts +53 -0
  94. package/dist/transformer/transformers/OpenAIResponseTransformer.d.ts +53 -0
  95. package/dist/transformer/transformers/OpenAIResponseTransformer.js +513 -0
  96. package/dist/transformer/transformers/OpenCodeGoTransformer.cjs +73 -0
  97. package/dist/transformer/transformers/OpenCodeGoTransformer.d.cts +51 -0
  98. package/dist/transformer/transformers/OpenCodeGoTransformer.d.ts +51 -0
  99. package/dist/transformer/transformers/OpenCodeGoTransformer.js +48 -0
  100. package/dist/transformer/types.cjs +18 -0
  101. package/dist/transformer/types.d.cts +405 -0
  102. package/dist/transformer/types.d.ts +405 -0
  103. package/dist/transformer/types.js +0 -0
  104. package/dist/transformer.cjs +3736 -0
  105. package/dist/transformer.d.cts +33 -0
  106. package/dist/transformer.d.ts +33 -0
  107. package/dist/transformer.js +3712 -0
  108. package/dist/types-CGGrKqC_.d.cts +142 -0
  109. package/dist/types-CbCN2NQP.d.ts +142 -0
  110. package/dist/types-DCzHkhJt.d.ts +467 -0
  111. package/dist/types-DZIQbgp0.d.cts +467 -0
  112. package/dist/usage-event-sink-BX7FE1NL.d.cts +59 -0
  113. package/dist/usage-event-sink-BX7FE1NL.d.ts +59 -0
  114. package/package.json +62 -0
@@ -0,0 +1,3712 @@
1
+ // src/transformer/anthropicBetaInject.ts
2
+ import { isExtendedContextCapable } from "@omnicross/contracts/extended-context";
3
+ var EXTENDED_CONTEXT_BETA = "context-1m-2025-08-07";
4
+ var ANTHROPIC_BETA_HEADER = "anthropic-beta";
5
+ function injectExtendedContextBeta(headers, model, useExtendedContext) {
6
+ if (!useExtendedContext) return;
7
+ if (!isExtendedContextCapable(model)) return;
8
+ let existingValue = "";
9
+ for (const key of Object.keys(headers)) {
10
+ if (key.toLowerCase() === ANTHROPIC_BETA_HEADER) {
11
+ const v = headers[key];
12
+ if (typeof v === "string") existingValue = v;
13
+ if (key !== ANTHROPIC_BETA_HEADER) delete headers[key];
14
+ }
15
+ }
16
+ const parts = existingValue.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
17
+ if (!parts.includes(EXTENDED_CONTEXT_BETA)) {
18
+ parts.push(EXTENDED_CONTEXT_BETA);
19
+ }
20
+ headers[ANTHROPIC_BETA_HEADER] = parts.join(",");
21
+ }
22
+
23
+ // src/transformer/TransformerChainExecutor.ts
24
+ var defaultLogger = {
25
+ debug: (msg, ...args) => console.debug(`[ChainExecutor] ${msg}`, ...args),
26
+ info: (msg, ...args) => console.info(`[ChainExecutor] ${msg}`, ...args),
27
+ warn: (msg, ...args) => console.warn(`[ChainExecutor] ${msg}`, ...args),
28
+ error: (msg, ...args) => console.error(`[ChainExecutor] ${msg}`, ...args)
29
+ };
30
+ var TransformerChainExecutor = class {
31
+ logger;
32
+ constructor(logger) {
33
+ this.logger = logger ?? defaultLogger;
34
+ }
35
+ /**
36
+ * Execute the request transformation chain
37
+ *
38
+ * @param request - Original request body
39
+ * @param provider - LLM provider configuration
40
+ * @param chain - Resolved transformer chain
41
+ * @param options - Execution options
42
+ * @returns Transformed request result
43
+ */
44
+ async executeRequestChain(request, provider, chain, options = {}) {
45
+ const { endpointTransformer, headers, extendedContext } = options;
46
+ const context = {
47
+ logger: this.logger,
48
+ providerName: provider.name
49
+ };
50
+ let requestBody = request;
51
+ let config = {};
52
+ let bypass = false;
53
+ bypass = this.shouldBypassTransformers(
54
+ chain,
55
+ endpointTransformer,
56
+ requestBody
57
+ );
58
+ if (bypass) {
59
+ if (headers) {
60
+ const cleanHeaders = this.cleanHeaders(headers);
61
+ config.headers = cleanHeaders;
62
+ }
63
+ this.logger.debug("Bypass mode enabled - skipping transformations");
64
+ }
65
+ if (!bypass && endpointTransformer?.transformRequestOut) {
66
+ this.logger.debug("Executing transformRequestOut");
67
+ try {
68
+ const transformOut = await endpointTransformer.transformRequestOut(requestBody, context);
69
+ if (transformOut && typeof transformOut === "object") {
70
+ if ("body" in transformOut) {
71
+ requestBody = transformOut.body;
72
+ config = transformOut.config ?? {};
73
+ } else {
74
+ requestBody = transformOut;
75
+ }
76
+ }
77
+ } catch (error) {
78
+ this.logger.error(`transformRequestOut error: ${this.getErrorMessage(error)}`);
79
+ throw error;
80
+ }
81
+ }
82
+ if (!bypass && chain.providerTransformers.length > 0) {
83
+ this.logger.debug(`Executing ${chain.providerTransformers.length} provider transformers`);
84
+ for (const transformer of chain.providerTransformers) {
85
+ if (transformer.transformRequestIn) {
86
+ try {
87
+ const transformIn = await transformer.transformRequestIn(
88
+ requestBody,
89
+ provider,
90
+ context
91
+ );
92
+ if (transformIn && typeof transformIn === "object") {
93
+ if ("body" in transformIn) {
94
+ requestBody = transformIn.body;
95
+ config = { ...config, ...transformIn.config };
96
+ } else {
97
+ requestBody = transformIn;
98
+ }
99
+ }
100
+ } catch (error) {
101
+ this.logger.error(
102
+ `Provider transformer ${transformer.name} error: ${this.getErrorMessage(error)}`
103
+ );
104
+ throw error;
105
+ }
106
+ }
107
+ }
108
+ }
109
+ if (!bypass && chain.modelTransformers.length > 0) {
110
+ this.logger.debug(`Executing ${chain.modelTransformers.length} model transformers`);
111
+ for (const transformer of chain.modelTransformers) {
112
+ if (transformer.transformRequestIn) {
113
+ try {
114
+ const result = await transformer.transformRequestIn(
115
+ requestBody,
116
+ provider,
117
+ context
118
+ );
119
+ requestBody = result;
120
+ } catch (error) {
121
+ this.logger.error(
122
+ `Model transformer ${transformer.name} error: ${this.getErrorMessage(error)}`
123
+ );
124
+ throw error;
125
+ }
126
+ }
127
+ }
128
+ }
129
+ if (extendedContext?.enabled) {
130
+ if (!config.headers || typeof config.headers !== "object") {
131
+ config.headers = {};
132
+ }
133
+ injectExtendedContextBeta(
134
+ config.headers,
135
+ extendedContext.model,
136
+ true
137
+ );
138
+ }
139
+ return { requestBody, config, bypass };
140
+ }
141
+ /**
142
+ * Execute the response transformation chain
143
+ *
144
+ * @param request - Original request (for context)
145
+ * @param response - Response from provider
146
+ * @param provider - LLM provider configuration
147
+ * @param chain - Resolved transformer chain
148
+ * @param options - Execution options
149
+ * @returns Transformed response
150
+ */
151
+ async executeResponseChain(request, response, provider, chain, options = {}) {
152
+ const { endpointTransformer } = options;
153
+ const context = {
154
+ logger: this.logger,
155
+ providerName: provider.name
156
+ };
157
+ let finalResponse = response;
158
+ const bypass = this.shouldBypassTransformers(chain, endpointTransformer, request);
159
+ if (bypass) {
160
+ this.logger.debug("Bypass mode - skipping response transformations");
161
+ return finalResponse;
162
+ }
163
+ if (chain.modelTransformers.length > 0) {
164
+ const reversedModelTransformers = [...chain.modelTransformers].reverse();
165
+ this.logger.debug(
166
+ `Executing ${reversedModelTransformers.length} model response transformers (reversed)`
167
+ );
168
+ for (const transformer of reversedModelTransformers) {
169
+ if (transformer.transformResponseOut) {
170
+ try {
171
+ finalResponse = await transformer.transformResponseOut(finalResponse, context);
172
+ } catch (error) {
173
+ this.logger.error(
174
+ `Model transformer ${transformer.name} response error: ${this.getErrorMessage(error)}`
175
+ );
176
+ throw error;
177
+ }
178
+ }
179
+ }
180
+ }
181
+ if (chain.providerTransformers.length > 0) {
182
+ const reversedProviderTransformers = [...chain.providerTransformers].reverse();
183
+ this.logger.debug(
184
+ `Executing ${reversedProviderTransformers.length} provider response transformers (reversed)`
185
+ );
186
+ for (const transformer of reversedProviderTransformers) {
187
+ if (transformer.transformResponseOut) {
188
+ try {
189
+ finalResponse = await transformer.transformResponseOut(finalResponse, context);
190
+ } catch (error) {
191
+ this.logger.error(
192
+ `Provider transformer ${transformer.name} response error: ${this.getErrorMessage(error)}`
193
+ );
194
+ throw error;
195
+ }
196
+ }
197
+ }
198
+ }
199
+ if (endpointTransformer?.transformResponseIn) {
200
+ this.logger.debug("Executing transformResponseIn");
201
+ try {
202
+ finalResponse = await endpointTransformer.transformResponseIn(finalResponse, context);
203
+ } catch (error) {
204
+ this.logger.error(`transformResponseIn error: ${this.getErrorMessage(error)}`);
205
+ throw error;
206
+ }
207
+ }
208
+ return finalResponse;
209
+ }
210
+ /**
211
+ * Execute authentication handler if available
212
+ *
213
+ * @param request - Request body
214
+ * @param provider - LLM provider
215
+ * @param endpointTransformer - Endpoint transformer with auth handler
216
+ * @param context - Transformer context
217
+ * @returns Auth result with potentially modified request and config
218
+ */
219
+ async executeAuth(request, provider, endpointTransformer, context) {
220
+ let requestBody = request;
221
+ let config = {};
222
+ if (endpointTransformer?.auth) {
223
+ this.logger.debug("Executing auth handler");
224
+ try {
225
+ const auth = await endpointTransformer.auth(requestBody, provider, context);
226
+ if (auth && typeof auth === "object") {
227
+ if ("body" in auth) {
228
+ requestBody = auth.body;
229
+ const authConfig = auth.config;
230
+ if (authConfig) {
231
+ const headers = { ...config.headers ?? {}, ...authConfig.headers ?? {} };
232
+ delete headers["host"];
233
+ config = { ...config, ...authConfig, headers };
234
+ }
235
+ } else {
236
+ requestBody = auth;
237
+ }
238
+ }
239
+ } catch (error) {
240
+ this.logger.error(`Auth handler error: ${this.getErrorMessage(error)}`);
241
+ throw error;
242
+ }
243
+ }
244
+ return { requestBody, config };
245
+ }
246
+ /**
247
+ * Check if transformers should be bypassed (optimization)
248
+ *
249
+ * Bypass is enabled when:
250
+ * - Provider has only one transformer that matches the endpoint transformer
251
+ * - Model has no specific transformers or only the same endpoint transformer
252
+ */
253
+ shouldBypassTransformers(chain, endpointTransformer, _request) {
254
+ if (!endpointTransformer?.name) {
255
+ return false;
256
+ }
257
+ const providerHasOnlyEndpoint = chain.providerTransformers.length === 1 && chain.providerTransformers[0]?.name === endpointTransformer.name;
258
+ const modelHasNoTransformers = chain.modelTransformers.length === 0;
259
+ const modelHasOnlyEndpoint = chain.modelTransformers.length === 1 && chain.modelTransformers[0]?.name === endpointTransformer.name;
260
+ return providerHasOnlyEndpoint && (modelHasNoTransformers || modelHasOnlyEndpoint);
261
+ }
262
+ /**
263
+ * Clean headers for pass-through
264
+ */
265
+ cleanHeaders(headers) {
266
+ const result = {};
267
+ if (headers instanceof Headers) {
268
+ headers.forEach((value, key) => {
269
+ if (key.toLowerCase() !== "content-length") {
270
+ result[key] = value;
271
+ }
272
+ });
273
+ } else {
274
+ for (const [key, value] of Object.entries(headers)) {
275
+ if (key.toLowerCase() !== "content-length") {
276
+ result[key] = value;
277
+ }
278
+ }
279
+ }
280
+ return result;
281
+ }
282
+ /**
283
+ * Get error message from unknown error
284
+ */
285
+ getErrorMessage(error) {
286
+ if (error instanceof Error) {
287
+ return error.message;
288
+ }
289
+ return String(error);
290
+ }
291
+ };
292
+
293
+ // src/transformer/TransformerService.ts
294
+ var defaultLogger2 = {
295
+ debug: (msg, ...args) => console.debug(`[TransformerService] ${msg}`, ...args),
296
+ info: (msg, ...args) => console.info(`[TransformerService] ${msg}`, ...args),
297
+ warn: (msg, ...args) => console.warn(`[TransformerService] ${msg}`, ...args),
298
+ error: (msg, ...args) => console.error(`[TransformerService] ${msg}`, ...args)
299
+ };
300
+ var TransformerService = class {
301
+ transformers = /* @__PURE__ */ new Map();
302
+ logger;
303
+ // Performance optimization: Cache instantiated transformers
304
+ instanceCache = /* @__PURE__ */ new Map();
305
+ // Performance optimization: Cache endpoint transformer results
306
+ endpointTransformersCache = null;
307
+ noEndpointTransformersCache = null;
308
+ constructor(logger) {
309
+ this.logger = logger ?? defaultLogger2;
310
+ }
311
+ /**
312
+ * Clear instance caches
313
+ */
314
+ clearInstanceCache() {
315
+ this.instanceCache.clear();
316
+ this.endpointTransformersCache = null;
317
+ this.noEndpointTransformersCache = null;
318
+ }
319
+ /**
320
+ * Get cache statistics for diagnostics
321
+ */
322
+ getCacheStats() {
323
+ return {
324
+ instanceCacheSize: this.instanceCache.size,
325
+ hasEndpointCache: this.endpointTransformersCache !== null
326
+ };
327
+ }
328
+ /**
329
+ * Register a transformer by name
330
+ * @param name - Unique transformer name
331
+ * @param transformer - Transformer instance or constructor
332
+ */
333
+ registerTransformer(name, transformer) {
334
+ this.transformers.set(name, transformer);
335
+ this.clearInstanceCache();
336
+ const endpoint = "endPoint" in transformer ? transformer.endPoint : "prototype" in transformer && transformer.prototype?.endPoint ? transformer.prototype.endPoint : void 0;
337
+ this.logger.info(
338
+ `Registered transformer: ${name}${endpoint ? ` (endpoint: ${endpoint})` : " (no endpoint)"}`
339
+ );
340
+ }
341
+ /**
342
+ * Get a transformer by name
343
+ * @param name - Transformer name
344
+ * @returns Transformer instance/constructor or undefined
345
+ */
346
+ getTransformer(name) {
347
+ return this.transformers.get(name);
348
+ }
349
+ /**
350
+ * Get all registered transformers
351
+ * @returns Map of all transformers
352
+ */
353
+ getAllTransformers() {
354
+ return new Map(this.transformers);
355
+ }
356
+ /**
357
+ * Get transformers that have an endpoint defined
358
+ * Uses cache to avoid redundant traversal
359
+ * @returns Array of transformers with endpoints
360
+ */
361
+ getTransformersWithEndpoint() {
362
+ if (this.endpointTransformersCache) {
363
+ return this.endpointTransformersCache;
364
+ }
365
+ const result = [];
366
+ this.transformers.forEach((transformer, name) => {
367
+ const instance = this.instantiateIfNeeded(transformer);
368
+ if (instance?.endPoint) {
369
+ result.push({ name, transformer: instance });
370
+ }
371
+ });
372
+ this.endpointTransformersCache = result;
373
+ return result;
374
+ }
375
+ /**
376
+ * Get transformers without endpoints
377
+ * Uses cache to avoid redundant traversal
378
+ * @returns Array of transformers without endpoints
379
+ */
380
+ getTransformersWithoutEndpoint() {
381
+ if (this.noEndpointTransformersCache) {
382
+ return this.noEndpointTransformersCache;
383
+ }
384
+ const result = [];
385
+ this.transformers.forEach((transformer, name) => {
386
+ const instance = this.instantiateIfNeeded(transformer);
387
+ if (instance && !instance.endPoint) {
388
+ result.push({ name, transformer: instance });
389
+ }
390
+ });
391
+ this.noEndpointTransformersCache = result;
392
+ return result;
393
+ }
394
+ /**
395
+ * Remove a transformer by name
396
+ * @param name - Transformer name
397
+ * @returns true if removed, false if not found
398
+ */
399
+ removeTransformer(name) {
400
+ const removed = this.transformers.delete(name);
401
+ if (removed) {
402
+ this.clearInstanceCache();
403
+ }
404
+ return removed;
405
+ }
406
+ /**
407
+ * Check if a transformer is registered
408
+ * @param name - Transformer name
409
+ * @returns true if registered
410
+ */
411
+ hasTransformer(name) {
412
+ return this.transformers.has(name);
413
+ }
414
+ /**
415
+ * Initialize the service with default transformers
416
+ * @param defaultTransformers - Map or object of default transformers
417
+ */
418
+ async initialize(defaultTransformers) {
419
+ try {
420
+ if (defaultTransformers) {
421
+ await this.registerDefaultTransformers(defaultTransformers);
422
+ }
423
+ this.logger.info(
424
+ `TransformerService initialized with ${this.transformers.size} transformers`
425
+ );
426
+ } catch (error) {
427
+ const errorMessage = error instanceof Error ? error.message : String(error);
428
+ this.logger.error(`TransformerService init error: ${errorMessage}`);
429
+ throw error;
430
+ }
431
+ }
432
+ /**
433
+ * Register default transformers from a map
434
+ * @param transformers - Map of transformer name to transformer
435
+ */
436
+ async registerDefaultTransformers(transformers) {
437
+ for (const [key, TransformerClass] of Object.entries(transformers)) {
438
+ try {
439
+ if (this.isTransformerConstructor(TransformerClass)) {
440
+ const staticName = TransformerClass.TransformerName ?? key;
441
+ this.registerTransformer(staticName, TransformerClass);
442
+ } else {
443
+ const name = TransformerClass.name ?? key;
444
+ TransformerClass.logger = this.logger;
445
+ this.registerTransformer(name, TransformerClass);
446
+ }
447
+ } catch (error) {
448
+ const errorMessage = error instanceof Error ? error.message : String(error);
449
+ this.logger.error(`Failed to register transformer ${key}: ${errorMessage}`);
450
+ }
451
+ }
452
+ }
453
+ /**
454
+ * Resolve a transformer chain configuration to actual transformer instances
455
+ * @param chainConfig - Transformer chain configuration
456
+ * @param modelName - Model name for model-specific transformers
457
+ * @returns Resolved transformer chain with instances
458
+ */
459
+ resolveTransformerChain(chainConfig, modelName) {
460
+ const result = {
461
+ providerTransformers: [],
462
+ modelTransformers: []
463
+ };
464
+ if (!chainConfig) {
465
+ return result;
466
+ }
467
+ if (chainConfig.use) {
468
+ result.providerTransformers = this.resolveTransformerReferences(chainConfig.use);
469
+ }
470
+ if (modelName && chainConfig[modelName]) {
471
+ const modelConfig = chainConfig[modelName];
472
+ if (Array.isArray(modelConfig)) {
473
+ result.modelTransformers = this.resolveTransformerReferences(modelConfig);
474
+ } else if (modelConfig && typeof modelConfig === "object" && "use" in modelConfig) {
475
+ result.modelTransformers = this.resolveTransformerReferences(modelConfig.use ?? []);
476
+ }
477
+ }
478
+ return result;
479
+ }
480
+ /**
481
+ * Resolve an array of transformer references to instances
482
+ * @param refs - Array of transformer references
483
+ * @returns Array of transformer instances
484
+ */
485
+ resolveTransformerReferences(refs) {
486
+ const instances = [];
487
+ for (const ref of refs) {
488
+ const [name, options] = Array.isArray(ref) ? ref : [ref, void 0];
489
+ const transformer = this.getTransformer(name);
490
+ if (!transformer) {
491
+ this.logger.warn(`Transformer not found: ${name}`);
492
+ continue;
493
+ }
494
+ const instance = this.instantiateIfNeeded(transformer, options);
495
+ if (instance) {
496
+ instance.logger = this.logger;
497
+ instances.push(instance);
498
+ }
499
+ }
500
+ return instances;
501
+ }
502
+ /**
503
+ * Instantiate a transformer if it's a constructor
504
+ * Uses instance cache to avoid redundant instantiation
505
+ *
506
+ * @param transformer - Transformer instance or constructor
507
+ * @param options - Options to pass to constructor
508
+ * @returns Transformer instance
509
+ */
510
+ instantiateIfNeeded(transformer, options) {
511
+ if (!this.isTransformerConstructor(transformer)) {
512
+ return transformer;
513
+ }
514
+ const constructorName = transformer.TransformerName || transformer.name || "anonymous";
515
+ const optionsHash = options ? JSON.stringify(options) : "";
516
+ const cacheKey = `${constructorName}:${optionsHash}`;
517
+ if (this.instanceCache.has(cacheKey)) {
518
+ return this.instanceCache.get(cacheKey);
519
+ }
520
+ try {
521
+ const instance = new transformer(options);
522
+ instance.logger = this.logger;
523
+ this.instanceCache.set(cacheKey, instance);
524
+ return instance;
525
+ } catch (error) {
526
+ const errorMessage = error instanceof Error ? error.message : String(error);
527
+ this.logger.error(`Failed to instantiate transformer: ${errorMessage}`);
528
+ return void 0;
529
+ }
530
+ }
531
+ /**
532
+ * Check if a value is a transformer constructor
533
+ * @param value - Value to check
534
+ * @returns true if it's a constructor
535
+ */
536
+ isTransformerConstructor(value) {
537
+ return typeof value === "function" && value.prototype && (typeof value.prototype.transformRequestIn === "function" || typeof value.prototype.transformRequestOut === "function" || typeof value.prototype.transformResponseIn === "function" || typeof value.prototype.transformResponseOut === "function" || "TransformerName" in value);
538
+ }
539
+ /**
540
+ * Get list of all registered transformer names
541
+ * @returns Array of transformer names
542
+ */
543
+ getTransformerNames() {
544
+ return Array.from(this.transformers.keys());
545
+ }
546
+ /**
547
+ * Clear all registered transformers
548
+ */
549
+ clear() {
550
+ this.transformers.clear();
551
+ this.clearInstanceCache();
552
+ this.logger.info("All transformers cleared");
553
+ }
554
+ };
555
+
556
+ // src/transformer/transformers/AnthropicToolHandling.ts
557
+ function isServerSideTool(tool) {
558
+ const type = String(tool.type || "");
559
+ return type.startsWith("web_search_") || type.startsWith("code_execution_") || type.startsWith("text_editor_") || type.startsWith("memory_") || type.startsWith("web_fetch_") || type.startsWith("search_tool_");
560
+ }
561
+ function convertAnthropicToolsToOpenAI(tools) {
562
+ return tools.filter((tool) => !isServerSideTool(tool)).map((tool) => ({
563
+ type: "function",
564
+ function: {
565
+ name: String(tool.name),
566
+ description: String(tool.description || ""),
567
+ parameters: tool.input_schema
568
+ }
569
+ }));
570
+ }
571
+
572
+ // src/transformer/transformers/AnthropicTypes.ts
573
+ function getThinkLevel(budgetTokens) {
574
+ if (!budgetTokens || budgetTokens <= 0) return "none";
575
+ if (budgetTokens < 4096) return "low";
576
+ if (budgetTokens < 16384) return "medium";
577
+ return "high";
578
+ }
579
+ function formatBase64(data, mediaType) {
580
+ if (data.startsWith("data:")) return data;
581
+ return `data:${mediaType || "image/png"};base64,${data}`;
582
+ }
583
+
584
+ // src/transformer/transformers/AnthropicRequestBuilder.ts
585
+ function buildAnthropicRequestBody(request) {
586
+ let systemContent;
587
+ const anthropicMessages = [];
588
+ for (let i = 0; i < request.messages.length; i++) {
589
+ const msg = request.messages[i];
590
+ if (msg.role === "system") {
591
+ if (typeof msg.content === "string") {
592
+ systemContent = msg.content;
593
+ } else if (Array.isArray(msg.content)) {
594
+ systemContent = msg.content.filter((c) => c.type === "text").map((c) => ({
595
+ type: "text",
596
+ text: c.text,
597
+ ...c.cache_control ? { cache_control: c.cache_control } : {}
598
+ }));
599
+ }
600
+ continue;
601
+ }
602
+ if (msg.role === "assistant") {
603
+ const content = [];
604
+ if (msg.thinking?.content) {
605
+ const block = {
606
+ type: "thinking",
607
+ thinking: msg.thinking.content
608
+ };
609
+ if (msg.thinking.signature) {
610
+ block.signature = msg.thinking.signature;
611
+ }
612
+ content.push(block);
613
+ }
614
+ if (msg.content) {
615
+ const text = typeof msg.content === "string" ? msg.content : msg.content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
616
+ if (text) {
617
+ content.push({ type: "text", text });
618
+ }
619
+ }
620
+ if (msg.tool_calls?.length) {
621
+ for (const tc of msg.tool_calls) {
622
+ let input;
623
+ try {
624
+ input = typeof tc.function.arguments === "string" ? JSON.parse(tc.function.arguments) : tc.function.arguments;
625
+ } catch {
626
+ input = { text: tc.function.arguments || "" };
627
+ }
628
+ content.push({
629
+ type: "tool_use",
630
+ id: tc.id,
631
+ name: tc.function.name,
632
+ input
633
+ });
634
+ }
635
+ }
636
+ anthropicMessages.push({
637
+ role: "assistant",
638
+ content: content.length > 0 ? content : ""
639
+ });
640
+ continue;
641
+ }
642
+ if (msg.role === "tool") {
643
+ const toolResults = [];
644
+ let j = i;
645
+ while (j < request.messages.length && request.messages[j].role === "tool") {
646
+ const t = request.messages[j];
647
+ toolResults.push({
648
+ type: "tool_result",
649
+ tool_use_id: t.tool_call_id || "",
650
+ content: typeof t.content === "string" ? t.content : JSON.stringify(t.content),
651
+ ...t.cache_control ? { cache_control: t.cache_control } : {}
652
+ });
653
+ j++;
654
+ }
655
+ anthropicMessages.push({ role: "user", content: toolResults });
656
+ i = j - 1;
657
+ continue;
658
+ }
659
+ if (typeof msg.content === "string") {
660
+ anthropicMessages.push({ role: "user", content: msg.content });
661
+ } else if (Array.isArray(msg.content)) {
662
+ const content = msg.content.map((part) => {
663
+ if (part.type === "image_url") {
664
+ const url = part.image_url.url;
665
+ if (url.startsWith("data:")) {
666
+ const match = url.match(/^data:([^;]+);base64,(.+)$/);
667
+ if (match) {
668
+ return {
669
+ type: "image",
670
+ source: { type: "base64", media_type: match[1], data: match[2] }
671
+ };
672
+ }
673
+ }
674
+ return {
675
+ type: "image",
676
+ source: { type: "url", url }
677
+ };
678
+ }
679
+ return { type: "text", text: part.text };
680
+ });
681
+ anthropicMessages.push({ role: "user", content });
682
+ }
683
+ }
684
+ const body = {
685
+ model: request.model,
686
+ messages: anthropicMessages,
687
+ max_tokens: request.max_tokens || 4096,
688
+ stream: request.stream ?? false
689
+ };
690
+ if (request.temperature !== void 0) {
691
+ body.temperature = request.temperature;
692
+ }
693
+ if (systemContent !== void 0) {
694
+ body.system = systemContent;
695
+ }
696
+ if (request.tools?.length) {
697
+ body.tools = request.tools.map((tool) => ({
698
+ name: tool.function.name,
699
+ description: tool.function.description || "",
700
+ input_schema: tool.function.parameters
701
+ }));
702
+ }
703
+ const serverSideTools = request._serverSideTools;
704
+ if (serverSideTools?.length) {
705
+ body.tools = [...body.tools || [], ...serverSideTools];
706
+ }
707
+ if (request.tool_choice) {
708
+ if (typeof request.tool_choice === "string") {
709
+ if (request.tool_choice === "required") {
710
+ body.tool_choice = { type: "any" };
711
+ } else if (request.tool_choice !== "none") {
712
+ body.tool_choice = { type: request.tool_choice };
713
+ }
714
+ } else if (typeof request.tool_choice === "object" && "function" in request.tool_choice) {
715
+ body.tool_choice = { type: "tool", name: request.tool_choice.function.name };
716
+ }
717
+ }
718
+ if (request.reasoning?.enabled) {
719
+ const budgetMap = { low: 2048, medium: 8192, high: 32768 };
720
+ const budget = request.reasoning.max_tokens || budgetMap[request.reasoning.effort || "medium"] || 8192;
721
+ body.thinking = { type: "enabled", budget_tokens: budget };
722
+ body.temperature = 1;
723
+ }
724
+ return body;
725
+ }
726
+
727
+ // src/transformer/transformers/AnthropicResponseConversion.ts
728
+ function convertAnthropicResponseToOpenAI(anthropicResponse) {
729
+ const content = anthropicResponse.content || [];
730
+ const textParts = content.filter((c) => c.type === "text").map((c) => c.text);
731
+ const toolUses = content.filter((c) => c.type === "tool_use" || c.type === "server_tool_use");
732
+ const thinkingBlock = content.find((c) => c.type === "thinking");
733
+ const searchResults = content.filter((c) => c.type === "web_search_tool_result");
734
+ for (const sr of searchResults) {
735
+ const searches = sr.content;
736
+ if (searches?.length) {
737
+ const formatted = searches.map((s) => `[${s.title}](${s.url}): ${s.page_content || s.snippet || ""}`).join("\n");
738
+ textParts.push(`
739
+
740
+ **Search Results:**
741
+ ${formatted}`);
742
+ }
743
+ }
744
+ const message = {
745
+ role: "assistant",
746
+ content: textParts.join("") || null
747
+ };
748
+ if (toolUses.length > 0) {
749
+ message.tool_calls = toolUses.map((tc) => ({
750
+ id: tc.id,
751
+ type: "function",
752
+ function: {
753
+ name: tc.name,
754
+ arguments: JSON.stringify(tc.input || {})
755
+ }
756
+ }));
757
+ }
758
+ if (thinkingBlock) {
759
+ message.thinking = {
760
+ content: thinkingBlock.thinking,
761
+ signature: thinkingBlock.signature
762
+ };
763
+ }
764
+ const stopReasonMapping = {
765
+ end_turn: "stop",
766
+ max_tokens: "length",
767
+ tool_use: "tool_calls",
768
+ stop_sequence: "stop"
769
+ };
770
+ const usage = anthropicResponse.usage;
771
+ return {
772
+ id: anthropicResponse.id || `chatcmpl-${Date.now()}`,
773
+ object: "chat.completion",
774
+ created: Math.floor(Date.now() / 1e3),
775
+ model: anthropicResponse.model || "unknown",
776
+ choices: [{
777
+ index: 0,
778
+ message,
779
+ finish_reason: stopReasonMapping[anthropicResponse.stop_reason] || "stop"
780
+ }],
781
+ usage: usage ? {
782
+ prompt_tokens: usage.input_tokens || 0,
783
+ completion_tokens: usage.output_tokens || 0,
784
+ total_tokens: (usage.input_tokens || 0) + (usage.output_tokens || 0)
785
+ } : void 0
786
+ };
787
+ }
788
+ function convertOpenAIResponseToAnthropic(openaiResponse) {
789
+ const choice = openaiResponse.choices?.[0];
790
+ if (!choice) {
791
+ throw new Error("No choices found in OpenAI response");
792
+ }
793
+ const message = choice.message;
794
+ const content = [];
795
+ if (message.content) {
796
+ content.push({
797
+ type: "text",
798
+ text: message.content
799
+ });
800
+ }
801
+ const toolCalls = message.tool_calls;
802
+ if (toolCalls?.length) {
803
+ for (const toolCall of toolCalls) {
804
+ const func = toolCall.function;
805
+ let parsedInput = {};
806
+ try {
807
+ const args = func.arguments;
808
+ parsedInput = typeof args === "string" ? JSON.parse(args) : args;
809
+ } catch {
810
+ parsedInput = { text: func.arguments || "" };
811
+ }
812
+ content.push({
813
+ type: "tool_use",
814
+ id: toolCall.id,
815
+ name: func.name,
816
+ input: parsedInput
817
+ });
818
+ }
819
+ }
820
+ const thinking = message.thinking;
821
+ if (thinking?.content) {
822
+ content.push({
823
+ type: "thinking",
824
+ thinking: thinking.content,
825
+ signature: thinking.signature
826
+ });
827
+ }
828
+ const finishReason = choice.finish_reason;
829
+ const stopReasonMapping = {
830
+ stop: "end_turn",
831
+ length: "max_tokens",
832
+ tool_calls: "tool_use",
833
+ content_filter: "stop_sequence"
834
+ };
835
+ const usage = openaiResponse.usage;
836
+ const usageDetails = usage?.prompt_tokens_details;
837
+ return {
838
+ id: openaiResponse.id,
839
+ type: "message",
840
+ role: "assistant",
841
+ model: openaiResponse.model,
842
+ content,
843
+ stop_reason: stopReasonMapping[finishReason] || "end_turn",
844
+ stop_sequence: null,
845
+ usage: {
846
+ input_tokens: (usage?.prompt_tokens || 0) - (usageDetails?.cached_tokens || 0),
847
+ output_tokens: usage?.completion_tokens || 0,
848
+ cache_read_input_tokens: usageDetails?.cached_tokens || 0
849
+ }
850
+ };
851
+ }
852
+
853
+ // src/transformer/transformers/AnthropicConversion.ts
854
+ function transformAnthropicRequestToUnified(request) {
855
+ const anthropicRequest = request;
856
+ const messages = [];
857
+ if (anthropicRequest.system) {
858
+ if (typeof anthropicRequest.system === "string") {
859
+ messages.push({
860
+ role: "system",
861
+ content: anthropicRequest.system
862
+ });
863
+ } else if (Array.isArray(anthropicRequest.system)) {
864
+ const textParts = anthropicRequest.system.filter((item) => item.type === "text" && item.text).map((item) => ({
865
+ type: "text",
866
+ text: item.text,
867
+ cache_control: item.cache_control
868
+ }));
869
+ if (textParts.length > 0) {
870
+ messages.push({
871
+ role: "system",
872
+ content: textParts
873
+ });
874
+ }
875
+ }
876
+ }
877
+ const requestMessages = JSON.parse(JSON.stringify(anthropicRequest.messages || []));
878
+ for (const msg of requestMessages) {
879
+ if (msg.role !== "user" && msg.role !== "assistant") continue;
880
+ if (typeof msg.content === "string") {
881
+ messages.push({
882
+ role: msg.role,
883
+ content: msg.content
884
+ });
885
+ continue;
886
+ }
887
+ if (Array.isArray(msg.content)) {
888
+ if (msg.role === "user") {
889
+ const toolParts = msg.content.filter(
890
+ (c) => c.type === "tool_result" && c.tool_use_id
891
+ );
892
+ for (const tool of toolParts) {
893
+ messages.push({
894
+ role: "tool",
895
+ content: typeof tool.content === "string" ? tool.content : JSON.stringify(tool.content),
896
+ tool_call_id: tool.tool_use_id,
897
+ cache_control: tool.cache_control
898
+ });
899
+ }
900
+ const textAndMediaParts = msg.content.filter(
901
+ (c) => c.type === "text" && c.text || c.type === "image" && c.source
902
+ );
903
+ if (textAndMediaParts.length > 0) {
904
+ messages.push({
905
+ role: "user",
906
+ content: textAndMediaParts.map((part) => {
907
+ if (part.type === "image") {
908
+ const imagePart = part;
909
+ return {
910
+ type: "image_url",
911
+ image_url: {
912
+ url: imagePart.source.type === "base64" ? formatBase64(imagePart.source.data || "", imagePart.source.media_type) : imagePart.source.url || ""
913
+ },
914
+ media_type: imagePart.source.media_type
915
+ };
916
+ }
917
+ return {
918
+ type: "text",
919
+ text: part.text
920
+ };
921
+ })
922
+ });
923
+ }
924
+ } else if (msg.role === "assistant") {
925
+ const assistantMessage = {
926
+ role: "assistant",
927
+ content: ""
928
+ };
929
+ const textParts = msg.content.filter(
930
+ (c) => c.type === "text" && c.text
931
+ );
932
+ if (textParts.length > 0) {
933
+ assistantMessage.content = textParts.map((t) => t.text).join("\n");
934
+ }
935
+ const toolCallParts = msg.content.filter(
936
+ (c) => c.type === "tool_use" && c.id
937
+ );
938
+ if (toolCallParts.length > 0) {
939
+ assistantMessage.tool_calls = toolCallParts.map((tool) => ({
940
+ id: tool.id,
941
+ type: "function",
942
+ function: {
943
+ name: tool.name,
944
+ arguments: JSON.stringify(tool.input || {})
945
+ }
946
+ }));
947
+ }
948
+ const thinkingPart = msg.content.find(
949
+ (c) => c.type === "thinking"
950
+ );
951
+ if (thinkingPart?.thinking) {
952
+ assistantMessage.thinking = {
953
+ content: thinkingPart.thinking,
954
+ signature: thinkingPart.signature
955
+ };
956
+ }
957
+ messages.push(assistantMessage);
958
+ }
959
+ }
960
+ }
961
+ const rawTools = anthropicRequest.tools || [];
962
+ const serverSideTools = rawTools.filter((t) => isServerSideTool(t));
963
+ const functionTools = rawTools.length > 0 ? convertAnthropicToolsToOpenAI(rawTools) : void 0;
964
+ const result = {
965
+ messages,
966
+ model: anthropicRequest.model,
967
+ max_tokens: anthropicRequest.max_tokens,
968
+ temperature: anthropicRequest.temperature,
969
+ stream: anthropicRequest.stream,
970
+ tools: functionTools?.length ? functionTools : void 0
971
+ };
972
+ if (serverSideTools.length > 0) {
973
+ result._serverSideTools = serverSideTools;
974
+ }
975
+ if (anthropicRequest.thinking) {
976
+ result.reasoning = {
977
+ effort: getThinkLevel(anthropicRequest.thinking.budget_tokens),
978
+ enabled: anthropicRequest.thinking.type === "enabled"
979
+ };
980
+ }
981
+ if (anthropicRequest.tool_choice) {
982
+ if (anthropicRequest.tool_choice.type === "tool" && anthropicRequest.tool_choice.name) {
983
+ result.tool_choice = {
984
+ type: "function",
985
+ function: { name: anthropicRequest.tool_choice.name }
986
+ };
987
+ } else {
988
+ result.tool_choice = anthropicRequest.tool_choice.type;
989
+ }
990
+ }
991
+ return result;
992
+ }
993
+
994
+ // src/transformer/transformers/AnthropicAnthropicToOpenAIStream.ts
995
+ function convertAnthropicStreamToOpenAI(anthropicStream, logger) {
996
+ const decoder = new TextDecoder();
997
+ const encoder = new TextEncoder();
998
+ const activeToolCalls = /* @__PURE__ */ new Map();
999
+ let toolCallCounter = 0;
1000
+ let model = "unknown";
1001
+ let messageId = `chatcmpl-${Date.now()}`;
1002
+ return new ReadableStream({
1003
+ start: async (controller) => {
1004
+ const reader = anthropicStream.getReader();
1005
+ let buffer = "";
1006
+ let isClosed = false;
1007
+ const safeEnqueue = (data) => {
1008
+ if (!isClosed) {
1009
+ try {
1010
+ controller.enqueue(encoder.encode(data));
1011
+ } catch {
1012
+ isClosed = true;
1013
+ }
1014
+ }
1015
+ };
1016
+ try {
1017
+ while (true) {
1018
+ const { done, value } = await reader.read();
1019
+ if (done) break;
1020
+ buffer += decoder.decode(value, { stream: true });
1021
+ const lines = buffer.split("\n");
1022
+ buffer = lines.pop() || "";
1023
+ for (const line of lines) {
1024
+ if (isClosed) break;
1025
+ if (!line.startsWith("data:")) continue;
1026
+ const data = line.slice(5).trim();
1027
+ if (!data || data === "[DONE]") continue;
1028
+ try {
1029
+ const event = JSON.parse(data);
1030
+ if (event.type === "message_start" && event.message) {
1031
+ model = event.message.model || model;
1032
+ messageId = event.message.id || messageId;
1033
+ }
1034
+ if (event.type === "content_block_delta" && event.delta) {
1035
+ const chunk = {
1036
+ id: messageId,
1037
+ object: "chat.completion.chunk",
1038
+ created: Math.floor(Date.now() / 1e3),
1039
+ model,
1040
+ choices: [{ index: 0, delta: {}, finish_reason: null }]
1041
+ };
1042
+ const delta = chunk.choices[0].delta;
1043
+ if (event.delta.type === "text_delta") {
1044
+ delta.content = event.delta.text;
1045
+ } else if (event.delta.type === "input_json_delta") {
1046
+ const toolInfo = activeToolCalls.get(event.index);
1047
+ if (toolInfo) {
1048
+ delta.tool_calls = [{
1049
+ index: toolInfo.index,
1050
+ function: { arguments: event.delta.partial_json }
1051
+ }];
1052
+ }
1053
+ } else if (event.delta.type === "thinking_delta") {
1054
+ delta.thinking = { content: event.delta.thinking };
1055
+ } else if (event.delta.type === "signature_delta") {
1056
+ delta.thinking = { signature: event.delta.signature };
1057
+ } else {
1058
+ continue;
1059
+ }
1060
+ safeEnqueue(`data: ${JSON.stringify(chunk)}
1061
+
1062
+ `);
1063
+ }
1064
+ if (event.type === "content_block_start" && event.content_block) {
1065
+ if (event.content_block.type === "tool_use" || event.content_block.type === "server_tool_use") {
1066
+ const tcIndex = toolCallCounter++;
1067
+ activeToolCalls.set(event.index, {
1068
+ id: event.content_block.id,
1069
+ name: event.content_block.name,
1070
+ index: tcIndex
1071
+ });
1072
+ const chunk = {
1073
+ id: messageId,
1074
+ object: "chat.completion.chunk",
1075
+ created: Math.floor(Date.now() / 1e3),
1076
+ model,
1077
+ choices: [{
1078
+ index: 0,
1079
+ delta: {
1080
+ tool_calls: [{
1081
+ index: tcIndex,
1082
+ id: event.content_block.id,
1083
+ type: "function",
1084
+ function: { name: event.content_block.name, arguments: "" }
1085
+ }]
1086
+ },
1087
+ finish_reason: null
1088
+ }]
1089
+ };
1090
+ safeEnqueue(`data: ${JSON.stringify(chunk)}
1091
+
1092
+ `);
1093
+ } else if (event.content_block.type === "web_search_tool_result") {
1094
+ const searches = event.content_block.content;
1095
+ if (searches?.length) {
1096
+ const formatted = searches.map((s) => `[${s.title}](${s.url}): ${s.page_content || s.snippet || ""}`).join("\n");
1097
+ const chunk = {
1098
+ id: messageId,
1099
+ object: "chat.completion.chunk",
1100
+ created: Math.floor(Date.now() / 1e3),
1101
+ model,
1102
+ choices: [{
1103
+ index: 0,
1104
+ delta: { content: `
1105
+
1106
+ **Search Results:**
1107
+ ${formatted}` },
1108
+ finish_reason: null
1109
+ }]
1110
+ };
1111
+ safeEnqueue(`data: ${JSON.stringify(chunk)}
1112
+
1113
+ `);
1114
+ }
1115
+ }
1116
+ }
1117
+ if (event.type === "message_delta" && event.delta) {
1118
+ const stopReasonMapping = {
1119
+ end_turn: "stop",
1120
+ max_tokens: "length",
1121
+ tool_use: "tool_calls",
1122
+ stop_sequence: "stop"
1123
+ };
1124
+ const chunk = {
1125
+ id: messageId,
1126
+ object: "chat.completion.chunk",
1127
+ created: Math.floor(Date.now() / 1e3),
1128
+ model,
1129
+ choices: [{
1130
+ index: 0,
1131
+ delta: {},
1132
+ finish_reason: stopReasonMapping[event.delta.stop_reason] || "stop"
1133
+ }]
1134
+ };
1135
+ if (event.usage) {
1136
+ chunk.usage = {
1137
+ prompt_tokens: event.usage.input_tokens || 0,
1138
+ completion_tokens: event.usage.output_tokens || 0,
1139
+ total_tokens: (event.usage.input_tokens || 0) + (event.usage.output_tokens || 0)
1140
+ };
1141
+ }
1142
+ safeEnqueue(`data: ${JSON.stringify(chunk)}
1143
+
1144
+ `);
1145
+ }
1146
+ } catch (e) {
1147
+ logger?.error("Error parsing Anthropic stream event:", e);
1148
+ }
1149
+ }
1150
+ }
1151
+ } catch (e) {
1152
+ if (!isClosed) {
1153
+ controller.error(e);
1154
+ }
1155
+ } finally {
1156
+ safeEnqueue("data: [DONE]\n\n");
1157
+ if (!isClosed) {
1158
+ try {
1159
+ controller.close();
1160
+ } catch {
1161
+ }
1162
+ }
1163
+ reader.releaseLock();
1164
+ }
1165
+ }
1166
+ });
1167
+ }
1168
+
1169
+ // src/transformer/transformers/AnthropicOpenAIToAnthropicStream.ts
1170
+ function convertOpenAIStreamToAnthropic(openaiStream, _context, logger) {
1171
+ const decoder = new TextDecoder();
1172
+ const encoder = new TextEncoder();
1173
+ let hasStarted = false;
1174
+ let hasTextContentStarted = false;
1175
+ let isThinkingStarted = false;
1176
+ let contentIndex = 0;
1177
+ let currentContentBlockIndex = -1;
1178
+ const toolCallIndexToContentBlockIndex = /* @__PURE__ */ new Map();
1179
+ return new ReadableStream({
1180
+ start: async (controller) => {
1181
+ const reader = openaiStream.getReader();
1182
+ let buffer = "";
1183
+ const messageId = `msg_${Date.now()}`;
1184
+ let model = "unknown";
1185
+ let isClosed = false;
1186
+ let stopReasonDelta = null;
1187
+ const safeEnqueue = (data) => {
1188
+ if (!isClosed) {
1189
+ try {
1190
+ controller.enqueue(encoder.encode(data));
1191
+ } catch (_e) {
1192
+ isClosed = true;
1193
+ }
1194
+ }
1195
+ };
1196
+ const assignContentBlockIndex = () => {
1197
+ return contentIndex++;
1198
+ };
1199
+ const safeClose = () => {
1200
+ if (isClosed) return;
1201
+ if (currentContentBlockIndex >= 0) {
1202
+ safeEnqueue(`event: content_block_stop
1203
+ data: ${JSON.stringify({
1204
+ type: "content_block_stop",
1205
+ index: currentContentBlockIndex
1206
+ })}
1207
+
1208
+ `);
1209
+ }
1210
+ if (stopReasonDelta) {
1211
+ safeEnqueue(`event: message_delta
1212
+ data: ${JSON.stringify(stopReasonDelta)}
1213
+
1214
+ `);
1215
+ } else {
1216
+ safeEnqueue(`event: message_delta
1217
+ data: ${JSON.stringify({
1218
+ type: "message_delta",
1219
+ delta: { stop_reason: "end_turn", stop_sequence: null },
1220
+ usage: { input_tokens: 0, output_tokens: 0 }
1221
+ })}
1222
+
1223
+ `);
1224
+ }
1225
+ safeEnqueue(`event: message_stop
1226
+ data: ${JSON.stringify({ type: "message_stop" })}
1227
+
1228
+ `);
1229
+ try {
1230
+ controller.close();
1231
+ } catch (_e) {
1232
+ }
1233
+ isClosed = true;
1234
+ };
1235
+ try {
1236
+ while (true) {
1237
+ const { done, value } = await reader.read();
1238
+ if (done) break;
1239
+ buffer += decoder.decode(value, { stream: true });
1240
+ const lines = buffer.split("\n");
1241
+ buffer = lines.pop() || "";
1242
+ for (const line of lines) {
1243
+ if (isClosed) break;
1244
+ if (!line.startsWith("data:")) continue;
1245
+ const data = line.slice(5).trim();
1246
+ if (data === "[DONE]") continue;
1247
+ try {
1248
+ const chunk = JSON.parse(data);
1249
+ if (chunk.error) {
1250
+ safeEnqueue(`event: error
1251
+ data: ${JSON.stringify({
1252
+ type: "error",
1253
+ message: { type: "api_error", message: JSON.stringify(chunk.error) }
1254
+ })}
1255
+
1256
+ `);
1257
+ continue;
1258
+ }
1259
+ model = chunk.model || model;
1260
+ if (!hasStarted) {
1261
+ hasStarted = true;
1262
+ safeEnqueue(`event: message_start
1263
+ data: ${JSON.stringify({
1264
+ type: "message_start",
1265
+ message: {
1266
+ id: messageId,
1267
+ type: "message",
1268
+ role: "assistant",
1269
+ content: [],
1270
+ model,
1271
+ stop_reason: null,
1272
+ stop_sequence: null,
1273
+ usage: { input_tokens: 0, output_tokens: 0 }
1274
+ }
1275
+ })}
1276
+
1277
+ `);
1278
+ }
1279
+ const choice = chunk.choices?.[0];
1280
+ if (!choice) continue;
1281
+ if (chunk.usage) {
1282
+ stopReasonDelta = {
1283
+ type: "message_delta",
1284
+ delta: { stop_reason: "end_turn", stop_sequence: null },
1285
+ usage: {
1286
+ input_tokens: (chunk.usage.prompt_tokens || 0) - (chunk.usage.prompt_tokens_details?.cached_tokens || 0),
1287
+ output_tokens: chunk.usage.completion_tokens || 0,
1288
+ cache_read_input_tokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0
1289
+ }
1290
+ };
1291
+ }
1292
+ if (choice.delta?.thinking) {
1293
+ if (!isThinkingStarted) {
1294
+ const thinkingBlockIndex = assignContentBlockIndex();
1295
+ safeEnqueue(`event: content_block_start
1296
+ data: ${JSON.stringify({
1297
+ type: "content_block_start",
1298
+ index: thinkingBlockIndex,
1299
+ content_block: { type: "thinking", thinking: "" }
1300
+ })}
1301
+
1302
+ `);
1303
+ currentContentBlockIndex = thinkingBlockIndex;
1304
+ isThinkingStarted = true;
1305
+ }
1306
+ if (choice.delta.thinking.signature) {
1307
+ safeEnqueue(`event: content_block_delta
1308
+ data: ${JSON.stringify({
1309
+ type: "content_block_delta",
1310
+ index: currentContentBlockIndex,
1311
+ delta: { type: "signature_delta", signature: choice.delta.thinking.signature }
1312
+ })}
1313
+
1314
+ `);
1315
+ safeEnqueue(`event: content_block_stop
1316
+ data: ${JSON.stringify({
1317
+ type: "content_block_stop",
1318
+ index: currentContentBlockIndex
1319
+ })}
1320
+
1321
+ `);
1322
+ currentContentBlockIndex = -1;
1323
+ } else if (choice.delta.thinking.content) {
1324
+ safeEnqueue(`event: content_block_delta
1325
+ data: ${JSON.stringify({
1326
+ type: "content_block_delta",
1327
+ index: currentContentBlockIndex,
1328
+ delta: { type: "thinking_delta", thinking: choice.delta.thinking.content }
1329
+ })}
1330
+
1331
+ `);
1332
+ }
1333
+ }
1334
+ if (choice.delta?.content) {
1335
+ if (!hasTextContentStarted) {
1336
+ if (currentContentBlockIndex >= 0 && isThinkingStarted) {
1337
+ safeEnqueue(`event: content_block_stop
1338
+ data: ${JSON.stringify({
1339
+ type: "content_block_stop",
1340
+ index: currentContentBlockIndex
1341
+ })}
1342
+
1343
+ `);
1344
+ }
1345
+ hasTextContentStarted = true;
1346
+ const textBlockIndex = assignContentBlockIndex();
1347
+ safeEnqueue(`event: content_block_start
1348
+ data: ${JSON.stringify({
1349
+ type: "content_block_start",
1350
+ index: textBlockIndex,
1351
+ content_block: { type: "text", text: "" }
1352
+ })}
1353
+
1354
+ `);
1355
+ currentContentBlockIndex = textBlockIndex;
1356
+ }
1357
+ safeEnqueue(`event: content_block_delta
1358
+ data: ${JSON.stringify({
1359
+ type: "content_block_delta",
1360
+ index: currentContentBlockIndex,
1361
+ delta: { type: "text_delta", text: choice.delta.content }
1362
+ })}
1363
+
1364
+ `);
1365
+ }
1366
+ if (choice.delta?.tool_calls) {
1367
+ for (const toolCall of choice.delta.tool_calls) {
1368
+ const toolCallIndex = toolCall.index ?? 0;
1369
+ if (!toolCallIndexToContentBlockIndex.has(toolCallIndex)) {
1370
+ if (currentContentBlockIndex >= 0) {
1371
+ safeEnqueue(`event: content_block_stop
1372
+ data: ${JSON.stringify({
1373
+ type: "content_block_stop",
1374
+ index: currentContentBlockIndex
1375
+ })}
1376
+
1377
+ `);
1378
+ hasTextContentStarted = false;
1379
+ }
1380
+ const newBlockIndex = assignContentBlockIndex();
1381
+ toolCallIndexToContentBlockIndex.set(toolCallIndex, newBlockIndex);
1382
+ safeEnqueue(`event: content_block_start
1383
+ data: ${JSON.stringify({
1384
+ type: "content_block_start",
1385
+ index: newBlockIndex,
1386
+ content_block: {
1387
+ type: "tool_use",
1388
+ id: toolCall.id || `call_${Date.now()}_${toolCallIndex}`,
1389
+ name: toolCall.function?.name || `tool_${toolCallIndex}`,
1390
+ input: {}
1391
+ }
1392
+ })}
1393
+
1394
+ `);
1395
+ currentContentBlockIndex = newBlockIndex;
1396
+ }
1397
+ if (toolCall.function?.arguments) {
1398
+ const blockIndex = toolCallIndexToContentBlockIndex.get(toolCallIndex);
1399
+ if (blockIndex !== void 0) {
1400
+ safeEnqueue(`event: content_block_delta
1401
+ data: ${JSON.stringify({
1402
+ type: "content_block_delta",
1403
+ index: blockIndex,
1404
+ delta: { type: "input_json_delta", partial_json: toolCall.function.arguments }
1405
+ })}
1406
+
1407
+ `);
1408
+ }
1409
+ }
1410
+ }
1411
+ }
1412
+ if (choice.finish_reason) {
1413
+ const stopReasonMapping = {
1414
+ stop: "end_turn",
1415
+ length: "max_tokens",
1416
+ tool_calls: "tool_use",
1417
+ content_filter: "stop_sequence"
1418
+ };
1419
+ stopReasonDelta = {
1420
+ type: "message_delta",
1421
+ delta: {
1422
+ stop_reason: stopReasonMapping[choice.finish_reason] || "end_turn",
1423
+ stop_sequence: null
1424
+ },
1425
+ usage: {
1426
+ input_tokens: (chunk.usage?.prompt_tokens || 0) - (chunk.usage?.prompt_tokens_details?.cached_tokens || 0),
1427
+ output_tokens: chunk.usage?.completion_tokens || 0,
1428
+ cache_read_input_tokens: chunk.usage?.prompt_tokens_details?.cached_tokens || 0
1429
+ }
1430
+ };
1431
+ }
1432
+ } catch (e) {
1433
+ logger?.error("Error parsing stream chunk:", e);
1434
+ }
1435
+ }
1436
+ }
1437
+ } catch (e) {
1438
+ if (!isClosed) {
1439
+ controller.error(e);
1440
+ }
1441
+ } finally {
1442
+ safeClose();
1443
+ reader.releaseLock();
1444
+ }
1445
+ }
1446
+ });
1447
+ }
1448
+
1449
+ // src/transformer/transformers/AnthropicTransformer.ts
1450
+ var AnthropicTransformer = class {
1451
+ static TransformerName = "anthropic";
1452
+ name = "anthropic";
1453
+ logger;
1454
+ endPoint = "/v1/messages";
1455
+ useBearer;
1456
+ constructor(options) {
1457
+ this.useBearer = options?.UseBearer ?? false;
1458
+ }
1459
+ /**
1460
+ * Handle authentication - Anthropic uses x-api-key header
1461
+ */
1462
+ async auth(request, provider, _context) {
1463
+ const headers = {};
1464
+ if (this.useBearer) {
1465
+ headers["authorization"] = `Bearer ${provider.apiKey}`;
1466
+ headers["x-api-key"] = void 0;
1467
+ } else {
1468
+ headers["x-api-key"] = provider.apiKey;
1469
+ headers["authorization"] = void 0;
1470
+ }
1471
+ return {
1472
+ body: request,
1473
+ config: { headers }
1474
+ };
1475
+ }
1476
+ /**
1477
+ * Transform Anthropic request to unified format.
1478
+ */
1479
+ async transformRequestOut(request, _context) {
1480
+ return transformAnthropicRequestToUnified(request);
1481
+ }
1482
+ /**
1483
+ * Transform OpenAI/unified response back to Anthropic format
1484
+ * (auto-detects stream vs JSON via Content-Type).
1485
+ */
1486
+ async transformResponseIn(response, context) {
1487
+ const contentType = response.headers.get("Content-Type") ?? "";
1488
+ if (contentType.includes("text/event-stream")) {
1489
+ if (!response.body) {
1490
+ throw new Error("Stream response body is null");
1491
+ }
1492
+ const convertedStream = convertOpenAIStreamToAnthropic(response.body, context, this.logger);
1493
+ return new Response(convertedStream, {
1494
+ headers: {
1495
+ "Content-Type": "text/event-stream",
1496
+ "Cache-Control": "no-cache",
1497
+ Connection: "keep-alive"
1498
+ }
1499
+ });
1500
+ } else {
1501
+ const data = await response.json();
1502
+ const anthropicResponse = convertOpenAIResponseToAnthropic(data);
1503
+ return new Response(JSON.stringify(anthropicResponse), {
1504
+ headers: { "Content-Type": "application/json" }
1505
+ });
1506
+ }
1507
+ }
1508
+ /**
1509
+ * Transform unified request to Anthropic Messages API format.
1510
+ * This is the reverse of transformRequestOut — converts OpenAI/unified format
1511
+ * to Anthropic's expected request body structure.
1512
+ */
1513
+ async transformRequestIn(request, _provider, _context) {
1514
+ return buildAnthropicRequestBody(request);
1515
+ }
1516
+ /**
1517
+ * Transform Anthropic response to OpenAI/unified format
1518
+ * (auto-detects stream vs JSON via Content-Type).
1519
+ */
1520
+ async transformResponseOut(response, _context) {
1521
+ const contentType = response.headers.get("Content-Type") ?? "";
1522
+ if (contentType.includes("text/event-stream")) {
1523
+ if (!response.body) {
1524
+ throw new Error("Stream response body is null");
1525
+ }
1526
+ const convertedStream = convertAnthropicStreamToOpenAI(response.body, this.logger);
1527
+ return new Response(convertedStream, {
1528
+ headers: {
1529
+ "Content-Type": "text/event-stream",
1530
+ "Cache-Control": "no-cache",
1531
+ Connection: "keep-alive"
1532
+ }
1533
+ });
1534
+ } else {
1535
+ const data = await response.json();
1536
+ const openaiResponse = convertAnthropicResponseToOpenAI(data);
1537
+ return new Response(JSON.stringify(openaiResponse), {
1538
+ headers: { "Content-Type": "application/json" }
1539
+ });
1540
+ }
1541
+ }
1542
+ };
1543
+
1544
+ // src/transformer/transformers/DeepseekTransformer.ts
1545
+ var DeepseekTransformer = class {
1546
+ static TransformerName = "deepseek";
1547
+ name = "deepseek";
1548
+ logger;
1549
+ /**
1550
+ * Transform request: limit max_tokens to 8192 for legacy models only
1551
+ * V4 models support up to 384K output tokens
1552
+ */
1553
+ async transformRequestIn(request, _provider, _context) {
1554
+ const isV4 = request.model?.startsWith("deepseek-v4");
1555
+ if (!isV4 && request.max_tokens && request.max_tokens > 8192) {
1556
+ this.logger?.debug("DeepSeek: Limiting max_tokens from %d to 8192", request.max_tokens);
1557
+ request.max_tokens = 8192;
1558
+ }
1559
+ return request;
1560
+ }
1561
+ /**
1562
+ * Transform response: convert reasoning_content to thinking blocks
1563
+ */
1564
+ async transformResponseOut(response, _context) {
1565
+ const contentType = response.headers.get("Content-Type") ?? "";
1566
+ if (contentType.includes("application/json")) {
1567
+ return this.handleJsonResponse(response);
1568
+ } else if (contentType.includes("stream") || contentType.includes("text/event-stream")) {
1569
+ return this.handleStreamResponse(response);
1570
+ }
1571
+ return response;
1572
+ }
1573
+ /**
1574
+ * Handle JSON (non-streaming) response
1575
+ */
1576
+ async handleJsonResponse(response) {
1577
+ const jsonResponse = await response.json();
1578
+ if (jsonResponse.choices?.[0]?.message?.reasoning_content) {
1579
+ jsonResponse.choices[0].message.thinking = {
1580
+ content: jsonResponse.choices[0].message.reasoning_content
1581
+ };
1582
+ delete jsonResponse.choices[0].message.reasoning_content;
1583
+ }
1584
+ return new Response(JSON.stringify(jsonResponse), {
1585
+ status: response.status,
1586
+ statusText: response.statusText,
1587
+ headers: response.headers
1588
+ });
1589
+ }
1590
+ /**
1591
+ * Handle streaming response - convert reasoning_content to thinking blocks
1592
+ */
1593
+ async handleStreamResponse(response) {
1594
+ if (!response.body) {
1595
+ return response;
1596
+ }
1597
+ const decoder = new TextDecoder();
1598
+ const encoder = new TextEncoder();
1599
+ let reasoningContent = "";
1600
+ let isReasoningComplete = false;
1601
+ let buffer = "";
1602
+ const stream = new ReadableStream({
1603
+ start: async (controller) => {
1604
+ const reader = response.body.getReader();
1605
+ const processLine = (line) => {
1606
+ if (line.startsWith("data: ") && line.trim() !== "data: [DONE]") {
1607
+ try {
1608
+ const data = JSON.parse(line.slice(6));
1609
+ if (data.choices?.[0]?.delta?.reasoning_content) {
1610
+ reasoningContent += data.choices[0].delta.reasoning_content;
1611
+ const thinkingChunk = {
1612
+ ...data,
1613
+ choices: [
1614
+ {
1615
+ ...data.choices[0],
1616
+ delta: {
1617
+ ...data.choices[0].delta,
1618
+ thinking: {
1619
+ content: data.choices[0].delta.reasoning_content
1620
+ }
1621
+ }
1622
+ }
1623
+ ]
1624
+ };
1625
+ delete thinkingChunk.choices[0].delta.reasoning_content;
1626
+ const thinkingLine = `data: ${JSON.stringify(thinkingChunk)}
1627
+
1628
+ `;
1629
+ controller.enqueue(encoder.encode(thinkingLine));
1630
+ return;
1631
+ }
1632
+ if (data.choices?.[0]?.delta?.content && reasoningContent && !isReasoningComplete) {
1633
+ isReasoningComplete = true;
1634
+ const signature = Date.now().toString();
1635
+ const thinkingChunk = {
1636
+ ...data,
1637
+ choices: [
1638
+ {
1639
+ ...data.choices[0],
1640
+ delta: {
1641
+ ...data.choices[0].delta,
1642
+ content: null,
1643
+ thinking: {
1644
+ signature
1645
+ }
1646
+ }
1647
+ }
1648
+ ]
1649
+ };
1650
+ const thinkingLine = `data: ${JSON.stringify(thinkingChunk)}
1651
+
1652
+ `;
1653
+ controller.enqueue(encoder.encode(thinkingLine));
1654
+ }
1655
+ if (data.choices?.[0]?.delta?.reasoning_content) {
1656
+ delete data.choices[0].delta.reasoning_content;
1657
+ }
1658
+ if (data.choices?.[0]?.delta && Object.keys(data.choices[0].delta).length > 0) {
1659
+ if (isReasoningComplete) {
1660
+ data.choices[0].index++;
1661
+ }
1662
+ const modifiedLine = `data: ${JSON.stringify(data)}
1663
+
1664
+ `;
1665
+ controller.enqueue(encoder.encode(modifiedLine));
1666
+ }
1667
+ } catch (_e) {
1668
+ controller.enqueue(encoder.encode(line + "\n"));
1669
+ }
1670
+ } else {
1671
+ controller.enqueue(encoder.encode(line + "\n"));
1672
+ }
1673
+ };
1674
+ try {
1675
+ while (true) {
1676
+ const { done, value } = await reader.read();
1677
+ if (done) {
1678
+ if (buffer.trim()) {
1679
+ const lines2 = buffer.split("\n");
1680
+ for (const line of lines2) {
1681
+ if (line.trim()) {
1682
+ controller.enqueue(encoder.encode(line + "\n"));
1683
+ }
1684
+ }
1685
+ }
1686
+ break;
1687
+ }
1688
+ const chunk = decoder.decode(value, { stream: true });
1689
+ buffer += chunk;
1690
+ const lines = buffer.split("\n");
1691
+ buffer = lines.pop() || "";
1692
+ for (const line of lines) {
1693
+ if (!line.trim()) continue;
1694
+ try {
1695
+ processLine(line);
1696
+ } catch (error) {
1697
+ this.logger?.error("Error processing DeepSeek stream line:", error);
1698
+ controller.enqueue(encoder.encode(line + "\n"));
1699
+ }
1700
+ }
1701
+ }
1702
+ } catch (error) {
1703
+ this.logger?.error("DeepSeek stream error:", error);
1704
+ controller.error(error);
1705
+ } finally {
1706
+ try {
1707
+ reader.releaseLock();
1708
+ } catch (e) {
1709
+ this.logger?.error("Error releasing reader lock:", e);
1710
+ }
1711
+ controller.close();
1712
+ }
1713
+ }
1714
+ });
1715
+ return new Response(stream, {
1716
+ status: response.status,
1717
+ statusText: response.statusText,
1718
+ headers: new Headers({
1719
+ "Content-Type": "text/event-stream",
1720
+ "Cache-Control": "no-cache",
1721
+ Connection: "keep-alive"
1722
+ })
1723
+ });
1724
+ }
1725
+ };
1726
+
1727
+ // src/transformer/transformers/utils/gemini.response-in.ts
1728
+ var FINISH_REASON_TO_GEMINI = {
1729
+ stop: "STOP",
1730
+ length: "MAX_TOKENS",
1731
+ tool_calls: "STOP",
1732
+ content_filter: "SAFETY",
1733
+ // Already-lowercased Gemini reasons (pass-through from another transformer)
1734
+ max_tokens: "MAX_TOKENS",
1735
+ safety: "SAFETY"
1736
+ };
1737
+ function toGeminiFinishReason(openaiReason) {
1738
+ if (!openaiReason) return null;
1739
+ return FINISH_REASON_TO_GEMINI[openaiReason] || openaiReason.toUpperCase();
1740
+ }
1741
+ function convertOpenAIResponseToGemini(openaiData) {
1742
+ const choice = openaiData.choices?.[0];
1743
+ const message = choice?.message ?? {};
1744
+ const usage = openaiData.usage;
1745
+ const usagePromptDetails = usage?.prompt_tokens_details;
1746
+ const usageOutputDetails = usage?.output_tokens_details;
1747
+ const parts = [];
1748
+ const thinking = message.thinking;
1749
+ if (thinking?.content) {
1750
+ parts.push({ text: thinking.content, thought: true });
1751
+ }
1752
+ if (thinking?.signature) {
1753
+ parts.push({ thoughtSignature: thinking.signature });
1754
+ }
1755
+ if (message.content) {
1756
+ parts.push({ text: message.content });
1757
+ }
1758
+ const toolCalls = message.tool_calls;
1759
+ if (toolCalls?.length) {
1760
+ for (const tc of toolCalls) {
1761
+ const func = tc.function;
1762
+ let args = {};
1763
+ try {
1764
+ const raw = func.arguments;
1765
+ args = typeof raw === "string" ? JSON.parse(raw) : raw;
1766
+ } catch {
1767
+ args = {};
1768
+ }
1769
+ parts.push({
1770
+ functionCall: {
1771
+ id: tc.id,
1772
+ name: func.name,
1773
+ args
1774
+ }
1775
+ });
1776
+ }
1777
+ }
1778
+ if (parts.length === 0) {
1779
+ parts.push({ text: "" });
1780
+ }
1781
+ return {
1782
+ responseId: openaiData.id || "",
1783
+ modelVersion: openaiData.model || "",
1784
+ candidates: [{
1785
+ content: { parts },
1786
+ finishReason: toGeminiFinishReason(choice?.finish_reason)
1787
+ }],
1788
+ usageMetadata: usage ? {
1789
+ promptTokenCount: usage.prompt_tokens || 0,
1790
+ candidatesTokenCount: usage.completion_tokens || 0,
1791
+ totalTokenCount: usage.total_tokens || 0,
1792
+ cachedContentTokenCount: usagePromptDetails?.cached_tokens || 0,
1793
+ thoughtsTokenCount: usageOutputDetails?.reasoning_tokens || 0
1794
+ } : void 0
1795
+ };
1796
+ }
1797
+ function convertOpenAIStreamToGemini(openaiStream, logger) {
1798
+ const decoder = new TextDecoder();
1799
+ const encoder = new TextEncoder();
1800
+ const pendingToolCalls = /* @__PURE__ */ new Map();
1801
+ let model = "";
1802
+ let responseId = "";
1803
+ return new ReadableStream({
1804
+ start: async (controller) => {
1805
+ const reader = openaiStream.getReader();
1806
+ let buffer = "";
1807
+ let isClosed = false;
1808
+ const emit = (data) => {
1809
+ if (isClosed) return;
1810
+ try {
1811
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}
1812
+
1813
+ `));
1814
+ } catch {
1815
+ isClosed = true;
1816
+ }
1817
+ };
1818
+ const flushToolCalls = () => {
1819
+ if (pendingToolCalls.size === 0) return;
1820
+ const parts = [];
1821
+ for (const tc of pendingToolCalls.values()) {
1822
+ let args = {};
1823
+ try {
1824
+ args = JSON.parse(tc.args || "{}");
1825
+ } catch {
1826
+ }
1827
+ parts.push({
1828
+ functionCall: { id: tc.id, name: tc.name, args }
1829
+ });
1830
+ }
1831
+ pendingToolCalls.clear();
1832
+ emit({
1833
+ responseId,
1834
+ modelVersion: model,
1835
+ candidates: [{ content: { parts }, finishReason: null }]
1836
+ });
1837
+ };
1838
+ try {
1839
+ while (true) {
1840
+ const { done, value } = await reader.read();
1841
+ if (done) break;
1842
+ buffer += decoder.decode(value, { stream: true });
1843
+ const lines = buffer.split("\n");
1844
+ buffer = lines.pop() || "";
1845
+ for (const line of lines) {
1846
+ if (isClosed) break;
1847
+ if (!line.startsWith("data:")) continue;
1848
+ const data = line.slice(5).trim();
1849
+ if (!data || data === "[DONE]") continue;
1850
+ try {
1851
+ const chunk = JSON.parse(data);
1852
+ if (!responseId && chunk.id) responseId = chunk.id;
1853
+ if (!model && chunk.model) model = chunk.model;
1854
+ const choice = chunk.choices?.[0];
1855
+ if (!choice) continue;
1856
+ const delta = choice.delta ?? {};
1857
+ if (delta.thinking) {
1858
+ const parts = [];
1859
+ if (delta.thinking.content) {
1860
+ parts.push({ text: delta.thinking.content, thought: true });
1861
+ }
1862
+ if (delta.thinking.signature) {
1863
+ parts.push({ thoughtSignature: delta.thinking.signature });
1864
+ }
1865
+ if (parts.length > 0) {
1866
+ emit({
1867
+ responseId,
1868
+ modelVersion: model,
1869
+ candidates: [{ content: { parts }, finishReason: null }]
1870
+ });
1871
+ }
1872
+ }
1873
+ if (delta.content) {
1874
+ emit({
1875
+ responseId,
1876
+ modelVersion: model,
1877
+ candidates: [{
1878
+ content: { parts: [{ text: delta.content }] },
1879
+ finishReason: null
1880
+ }]
1881
+ });
1882
+ }
1883
+ if (delta.tool_calls) {
1884
+ for (const tc of delta.tool_calls) {
1885
+ const idx = tc.index ?? 0;
1886
+ const existing = pendingToolCalls.get(idx);
1887
+ const func = tc.function;
1888
+ if (existing) {
1889
+ if (func?.arguments) {
1890
+ existing.args += func.arguments;
1891
+ }
1892
+ } else {
1893
+ pendingToolCalls.set(idx, {
1894
+ id: tc.id || `tool_${Date.now()}_${idx}`,
1895
+ name: func?.name || "",
1896
+ args: func?.arguments || ""
1897
+ });
1898
+ }
1899
+ }
1900
+ }
1901
+ if (choice.finish_reason) {
1902
+ flushToolCalls();
1903
+ const geminiUsage = chunk.usage ? {
1904
+ promptTokenCount: chunk.usage.prompt_tokens || 0,
1905
+ candidatesTokenCount: chunk.usage.completion_tokens || 0,
1906
+ totalTokenCount: chunk.usage.total_tokens || 0,
1907
+ cachedContentTokenCount: chunk.usage.prompt_tokens_details?.cached_tokens || 0,
1908
+ thoughtsTokenCount: chunk.usage.output_tokens_details?.reasoning_tokens || 0
1909
+ } : void 0;
1910
+ emit({
1911
+ responseId,
1912
+ modelVersion: model,
1913
+ candidates: [{
1914
+ content: { parts: [{ text: "" }] },
1915
+ finishReason: toGeminiFinishReason(choice.finish_reason) || "STOP"
1916
+ }],
1917
+ usageMetadata: geminiUsage
1918
+ });
1919
+ }
1920
+ } catch (e) {
1921
+ logger?.error(`Error parsing OpenAI stream chunk for Gemini conversion: ${e}`);
1922
+ }
1923
+ }
1924
+ }
1925
+ flushToolCalls();
1926
+ } catch (e) {
1927
+ if (!isClosed) controller.error(e);
1928
+ } finally {
1929
+ if (!isClosed) {
1930
+ try {
1931
+ controller.close();
1932
+ } catch {
1933
+ }
1934
+ }
1935
+ reader.releaseLock();
1936
+ }
1937
+ }
1938
+ });
1939
+ }
1940
+ async function transformResponseIn(response, logger) {
1941
+ const contentType = response.headers.get("Content-Type") ?? "";
1942
+ if (contentType.includes("text/event-stream")) {
1943
+ if (!response.body) {
1944
+ throw new Error("Stream response body is null");
1945
+ }
1946
+ const geminiStream = convertOpenAIStreamToGemini(response.body, logger);
1947
+ return new Response(geminiStream, {
1948
+ headers: {
1949
+ "Content-Type": "text/event-stream",
1950
+ "Cache-Control": "no-cache",
1951
+ Connection: "keep-alive"
1952
+ }
1953
+ });
1954
+ }
1955
+ const data = await response.json();
1956
+ const geminiResponse = convertOpenAIResponseToGemini(data);
1957
+ return new Response(JSON.stringify(geminiResponse), {
1958
+ status: response.status,
1959
+ statusText: response.statusText,
1960
+ headers: { "Content-Type": "application/json" }
1961
+ });
1962
+ }
1963
+
1964
+ // src/transformer/transformers/utils/gemini.stream.ts
1965
+ async function transformResponseOut(response, providerName, logger) {
1966
+ const contentType = response.headers.get("Content-Type") ?? "";
1967
+ if (contentType.includes("application/json")) {
1968
+ return handleJsonResponse(response, providerName, logger);
1969
+ } else if (contentType.includes("stream") || contentType.includes("text/event-stream")) {
1970
+ return handleStreamResponse(response, providerName, logger);
1971
+ }
1972
+ return response;
1973
+ }
1974
+ async function handleJsonResponse(response, providerName, logger) {
1975
+ const jsonResponse = await response.json();
1976
+ logger?.debug(`${providerName} JSON response received`);
1977
+ const parts = jsonResponse.candidates?.[0]?.content?.parts || [];
1978
+ let thinkingContent = "";
1979
+ let thinkingSignature = "";
1980
+ const nonThinkingParts = [];
1981
+ for (const part of parts) {
1982
+ if (part.text && part.thought === true) {
1983
+ thinkingContent += part.text;
1984
+ } else {
1985
+ nonThinkingParts.push(part);
1986
+ }
1987
+ }
1988
+ thinkingSignature = parts.find((part) => part.thoughtSignature)?.thoughtSignature ?? "";
1989
+ const toolCalls = nonThinkingParts.filter((part) => part.functionCall).map((part) => ({
1990
+ id: part.functionCall?.id || `tool_${Math.random().toString(36).substring(2, 15)}`,
1991
+ type: "function",
1992
+ function: {
1993
+ name: part.functionCall?.name ?? "",
1994
+ arguments: JSON.stringify(part.functionCall?.args || {})
1995
+ }
1996
+ }));
1997
+ const textContent = nonThinkingParts.filter((part) => part.text).map((part) => part.text).join("\n");
1998
+ const openAIResponse = {
1999
+ id: jsonResponse.responseId ?? "",
2000
+ choices: [
2001
+ {
2002
+ finish_reason: (jsonResponse.candidates?.[0]?.finishReason ?? "").toLowerCase() || null,
2003
+ index: 0,
2004
+ message: {
2005
+ content: textContent,
2006
+ role: "assistant",
2007
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
2008
+ ...thinkingSignature && {
2009
+ thinking: {
2010
+ content: thinkingContent || "(no content)",
2011
+ signature: thinkingSignature
2012
+ }
2013
+ }
2014
+ }
2015
+ }
2016
+ ],
2017
+ created: Math.floor(Date.now() / 1e3),
2018
+ model: jsonResponse.modelVersion ?? "",
2019
+ object: "chat.completion",
2020
+ usage: {
2021
+ completion_tokens: jsonResponse.usageMetadata?.candidatesTokenCount || 0,
2022
+ prompt_tokens: jsonResponse.usageMetadata?.promptTokenCount || 0,
2023
+ prompt_tokens_details: {
2024
+ cached_tokens: jsonResponse.usageMetadata?.cachedContentTokenCount || 0
2025
+ },
2026
+ total_tokens: jsonResponse.usageMetadata?.totalTokenCount || 0,
2027
+ output_tokens_details: {
2028
+ reasoning_tokens: jsonResponse.usageMetadata?.thoughtsTokenCount || 0
2029
+ }
2030
+ }
2031
+ };
2032
+ return new Response(JSON.stringify(openAIResponse), {
2033
+ status: response.status,
2034
+ statusText: response.statusText,
2035
+ headers: response.headers
2036
+ });
2037
+ }
2038
+ function handleStreamResponse(response, providerName, logger) {
2039
+ if (!response.body) {
2040
+ return response;
2041
+ }
2042
+ const decoder = new TextDecoder();
2043
+ const encoder = new TextEncoder();
2044
+ let signatureSent = false;
2045
+ let contentSent = false;
2046
+ let hasThinkingContent = false;
2047
+ let pendingContent = "";
2048
+ let contentIndex = 0;
2049
+ let toolCallIndex = -1;
2050
+ const stream = new ReadableStream({
2051
+ async start(controller) {
2052
+ const reader = response.body.getReader();
2053
+ let buffer = "";
2054
+ const processLine = async (line) => {
2055
+ if (!line.startsWith("data: ")) return;
2056
+ const chunkStr = line.slice(6).trim();
2057
+ if (!chunkStr) return;
2058
+ logger?.debug(`${providerName} chunk: ${chunkStr.substring(0, 100)}...`);
2059
+ try {
2060
+ const chunk = JSON.parse(chunkStr);
2061
+ if (!chunk.candidates?.[0]) {
2062
+ logger?.debug("Invalid chunk structure");
2063
+ return;
2064
+ }
2065
+ const candidate = chunk.candidates[0];
2066
+ const parts = candidate.content?.parts || [];
2067
+ parts.filter((part) => part.text && part.thought === true).forEach((part) => {
2068
+ hasThinkingContent = true;
2069
+ const thinkingChunk = createChunk({
2070
+ responseId: chunk.responseId,
2071
+ modelVersion: chunk.modelVersion,
2072
+ contentIndex,
2073
+ delta: {
2074
+ role: "assistant",
2075
+ content: null,
2076
+ thinking: { content: part.text }
2077
+ }
2078
+ });
2079
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(thinkingChunk)}
2080
+
2081
+ `));
2082
+ });
2083
+ const signature = parts.find((part) => part.thoughtSignature)?.thoughtSignature;
2084
+ if (signature && !signatureSent) {
2085
+ if (!hasThinkingContent) {
2086
+ const thinkingChunk = createChunk({
2087
+ responseId: chunk.responseId,
2088
+ modelVersion: chunk.modelVersion,
2089
+ contentIndex,
2090
+ delta: {
2091
+ role: "assistant",
2092
+ content: null,
2093
+ thinking: { content: "" }
2094
+ }
2095
+ });
2096
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(thinkingChunk)}
2097
+
2098
+ `));
2099
+ }
2100
+ const signatureChunk = createChunk({
2101
+ responseId: chunk.responseId,
2102
+ modelVersion: chunk.modelVersion,
2103
+ contentIndex,
2104
+ delta: {
2105
+ role: "assistant",
2106
+ content: null,
2107
+ thinking: { signature }
2108
+ }
2109
+ });
2110
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(signatureChunk)}
2111
+
2112
+ `));
2113
+ signatureSent = true;
2114
+ contentIndex++;
2115
+ if (pendingContent) {
2116
+ const pendingChunk = createChunk({
2117
+ responseId: chunk.responseId,
2118
+ modelVersion: chunk.modelVersion,
2119
+ contentIndex,
2120
+ delta: { role: "assistant", content: pendingContent }
2121
+ });
2122
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(pendingChunk)}
2123
+
2124
+ `));
2125
+ pendingContent = "";
2126
+ contentSent = true;
2127
+ }
2128
+ }
2129
+ const toolCalls = parts.filter((part) => part.functionCall).map((part) => ({
2130
+ id: part.functionCall?.id || `ccr_tool_${Math.random().toString(36).substring(2, 15)}`,
2131
+ type: "function",
2132
+ function: {
2133
+ name: part.functionCall?.name ?? "",
2134
+ arguments: JSON.stringify(part.functionCall?.args || {})
2135
+ }
2136
+ }));
2137
+ const textContent = parts.filter((part) => part.text && part.thought !== true).map((part) => part.text).join("\n");
2138
+ if (!textContent && signatureSent && !contentSent) {
2139
+ contentSent = true;
2140
+ }
2141
+ if (hasThinkingContent && textContent && !signatureSent) {
2142
+ if (chunk.modelVersion?.includes("3")) {
2143
+ pendingContent += textContent;
2144
+ return;
2145
+ } else {
2146
+ const signatureChunk = createChunk({
2147
+ responseId: chunk.responseId,
2148
+ modelVersion: chunk.modelVersion,
2149
+ contentIndex,
2150
+ delta: {
2151
+ role: "assistant",
2152
+ content: null,
2153
+ thinking: { signature: `ccr_${Date.now()}` }
2154
+ }
2155
+ });
2156
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(signatureChunk)}
2157
+
2158
+ `));
2159
+ signatureSent = true;
2160
+ }
2161
+ }
2162
+ if (textContent) {
2163
+ if (!pendingContent) contentIndex++;
2164
+ const contentChunk = createChunk({
2165
+ responseId: chunk.responseId,
2166
+ modelVersion: chunk.modelVersion,
2167
+ contentIndex,
2168
+ delta: { role: "assistant", content: textContent },
2169
+ finishReason: candidate.finishReason,
2170
+ usageMetadata: chunk.usageMetadata,
2171
+ groundingMetadata: candidate.groundingMetadata
2172
+ });
2173
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(contentChunk)}
2174
+
2175
+ `));
2176
+ contentSent = true;
2177
+ }
2178
+ if (toolCalls.length > 0) {
2179
+ for (const tool of toolCalls) {
2180
+ contentIndex++;
2181
+ toolCallIndex++;
2182
+ const toolChunk = createChunk({
2183
+ responseId: chunk.responseId,
2184
+ modelVersion: chunk.modelVersion,
2185
+ contentIndex,
2186
+ delta: {
2187
+ role: "assistant",
2188
+ tool_calls: [{ ...tool, index: toolCallIndex }]
2189
+ },
2190
+ finishReason: candidate.finishReason,
2191
+ usageMetadata: chunk.usageMetadata,
2192
+ groundingMetadata: candidate.groundingMetadata
2193
+ });
2194
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(toolChunk)}
2195
+
2196
+ `));
2197
+ }
2198
+ contentSent = true;
2199
+ }
2200
+ } catch (_error) {
2201
+ logger?.error(`Error parsing ${providerName} stream chunk: ${chunkStr}`);
2202
+ }
2203
+ };
2204
+ try {
2205
+ while (true) {
2206
+ const { done, value } = await reader.read();
2207
+ if (done) {
2208
+ if (buffer) await processLine(buffer);
2209
+ break;
2210
+ }
2211
+ buffer += decoder.decode(value, { stream: true });
2212
+ const lines = buffer.split("\n");
2213
+ buffer = lines.pop() || "";
2214
+ for (const line of lines) {
2215
+ await processLine(line);
2216
+ }
2217
+ }
2218
+ } catch (error) {
2219
+ controller.error(error);
2220
+ } finally {
2221
+ controller.close();
2222
+ }
2223
+ }
2224
+ });
2225
+ return new Response(stream, {
2226
+ status: response.status,
2227
+ statusText: response.statusText,
2228
+ headers: response.headers
2229
+ });
2230
+ }
2231
+ function createChunk(options) {
2232
+ const {
2233
+ responseId,
2234
+ modelVersion,
2235
+ contentIndex,
2236
+ delta,
2237
+ finishReason,
2238
+ usageMetadata,
2239
+ groundingMetadata
2240
+ } = options;
2241
+ const chunk = {
2242
+ choices: [
2243
+ {
2244
+ delta,
2245
+ finish_reason: finishReason?.toLowerCase() || null,
2246
+ index: contentIndex,
2247
+ logprobs: null
2248
+ }
2249
+ ],
2250
+ created: Math.floor(Date.now() / 1e3),
2251
+ id: responseId || "",
2252
+ model: modelVersion || "",
2253
+ object: "chat.completion.chunk",
2254
+ system_fingerprint: "fp_a49d71b8a1"
2255
+ };
2256
+ if (usageMetadata) {
2257
+ chunk.usage = {
2258
+ completion_tokens: usageMetadata.candidatesTokenCount || 0,
2259
+ prompt_tokens: usageMetadata.promptTokenCount || 0,
2260
+ prompt_tokens_details: {
2261
+ cached_tokens: usageMetadata.cachedContentTokenCount || 0
2262
+ },
2263
+ total_tokens: usageMetadata.totalTokenCount || 0,
2264
+ output_tokens_details: {
2265
+ reasoning_tokens: usageMetadata.thoughtsTokenCount || 0
2266
+ }
2267
+ };
2268
+ }
2269
+ if (groundingMetadata?.groundingChunks?.length) {
2270
+ const annotations = groundingMetadata.groundingChunks.map((groundingChunk, index) => {
2271
+ const support = groundingMetadata.groundingSupports?.find(
2272
+ (s) => s.groundingChunkIndices?.includes(index)
2273
+ );
2274
+ return {
2275
+ type: "url_citation",
2276
+ url_citation: {
2277
+ url: groundingChunk.web?.uri || "",
2278
+ title: groundingChunk.web?.title || "",
2279
+ content: support?.segment?.text || "",
2280
+ start_index: support?.segment?.startIndex || 0,
2281
+ end_index: support?.segment?.endIndex || 0
2282
+ }
2283
+ };
2284
+ });
2285
+ chunk.choices[0].delta.annotations = annotations;
2286
+ }
2287
+ return chunk;
2288
+ }
2289
+
2290
+ // src/transformer/transformers/utils/gemini.schema.ts
2291
+ var GeminiType = {
2292
+ TYPE_UNSPECIFIED: "TYPE_UNSPECIFIED",
2293
+ STRING: "STRING",
2294
+ NUMBER: "NUMBER",
2295
+ INTEGER: "INTEGER",
2296
+ BOOLEAN: "BOOLEAN",
2297
+ ARRAY: "ARRAY",
2298
+ OBJECT: "OBJECT",
2299
+ NULL: "NULL"
2300
+ };
2301
+ function flattenTypeArrayToAnyOf(typeList, resultingSchema) {
2302
+ if (typeList.includes("null")) {
2303
+ resultingSchema.nullable = true;
2304
+ }
2305
+ const listWithoutNull = typeList.filter((type) => type !== "null");
2306
+ if (listWithoutNull.length === 1) {
2307
+ const upperCaseType = listWithoutNull[0].toUpperCase();
2308
+ resultingSchema.type = Object.values(GeminiType).includes(upperCaseType) ? upperCaseType : GeminiType.TYPE_UNSPECIFIED;
2309
+ } else {
2310
+ resultingSchema.anyOf = listWithoutNull.map((typeName) => {
2311
+ const upperCaseType = typeName.toUpperCase();
2312
+ return {
2313
+ type: Object.values(GeminiType).includes(upperCaseType) ? upperCaseType : GeminiType.TYPE_UNSPECIFIED
2314
+ };
2315
+ });
2316
+ }
2317
+ }
2318
+ function processJsonSchema(jsonSchema) {
2319
+ const genAISchema = {};
2320
+ const schemaFieldNames = ["items"];
2321
+ const listSchemaFieldNames = ["anyOf"];
2322
+ const dictSchemaFieldNames = ["properties"];
2323
+ let workingSchema = jsonSchema;
2324
+ if (workingSchema.type && workingSchema.anyOf) {
2325
+ throw new Error("type and anyOf cannot be both populated.");
2326
+ }
2327
+ const incomingAnyOf = workingSchema.anyOf;
2328
+ if (incomingAnyOf && Array.isArray(incomingAnyOf) && incomingAnyOf.length === 2) {
2329
+ if (incomingAnyOf[0]?.type === "null") {
2330
+ genAISchema.nullable = true;
2331
+ workingSchema = incomingAnyOf[1];
2332
+ } else if (incomingAnyOf[1]?.type === "null") {
2333
+ genAISchema.nullable = true;
2334
+ workingSchema = incomingAnyOf[0];
2335
+ }
2336
+ }
2337
+ if (workingSchema.type && Array.isArray(workingSchema.type)) {
2338
+ flattenTypeArrayToAnyOf(workingSchema.type, genAISchema);
2339
+ }
2340
+ for (const [fieldName, fieldValue] of Object.entries(workingSchema)) {
2341
+ if (fieldValue == null) {
2342
+ continue;
2343
+ }
2344
+ if (fieldName === "type") {
2345
+ if (fieldValue === "null") {
2346
+ throw new Error("type: null cannot be the only possible type for the field.");
2347
+ }
2348
+ if (Array.isArray(fieldValue)) {
2349
+ continue;
2350
+ }
2351
+ const upperCaseValue = fieldValue.toUpperCase();
2352
+ genAISchema.type = Object.values(GeminiType).includes(upperCaseValue) ? upperCaseValue : GeminiType.TYPE_UNSPECIFIED;
2353
+ } else if (schemaFieldNames.includes(fieldName)) {
2354
+ genAISchema[fieldName] = processJsonSchema(fieldValue);
2355
+ } else if (listSchemaFieldNames.includes(fieldName)) {
2356
+ const listValue = [];
2357
+ for (const item of fieldValue) {
2358
+ if (item.type === "null") {
2359
+ genAISchema.nullable = true;
2360
+ continue;
2361
+ }
2362
+ listValue.push(processJsonSchema(item));
2363
+ }
2364
+ genAISchema[fieldName] = listValue;
2365
+ } else if (dictSchemaFieldNames.includes(fieldName)) {
2366
+ const dictValue = {};
2367
+ for (const [key, value] of Object.entries(fieldValue)) {
2368
+ dictValue[key] = processJsonSchema(value);
2369
+ }
2370
+ genAISchema[fieldName] = dictValue;
2371
+ } else {
2372
+ if (fieldName === "additionalProperties") {
2373
+ continue;
2374
+ }
2375
+ genAISchema[fieldName] = fieldValue;
2376
+ }
2377
+ }
2378
+ return genAISchema;
2379
+ }
2380
+ function transformTool(tool) {
2381
+ const functionDeclarations = tool.functionDeclarations;
2382
+ if (functionDeclarations) {
2383
+ for (const functionDeclaration of functionDeclarations) {
2384
+ if (functionDeclaration.parameters) {
2385
+ const params = functionDeclaration.parameters;
2386
+ if (!Object.keys(params).includes("$schema")) {
2387
+ functionDeclaration.parameters = processJsonSchema(params);
2388
+ } else {
2389
+ if (!functionDeclaration.parametersJsonSchema) {
2390
+ functionDeclaration.parametersJsonSchema = functionDeclaration.parameters;
2391
+ delete functionDeclaration.parameters;
2392
+ }
2393
+ }
2394
+ }
2395
+ if (functionDeclaration.response) {
2396
+ const response = functionDeclaration.response;
2397
+ if (!Object.keys(response).includes("$schema")) {
2398
+ functionDeclaration.response = processJsonSchema(response);
2399
+ } else {
2400
+ if (!functionDeclaration.responseJsonSchema) {
2401
+ functionDeclaration.responseJsonSchema = functionDeclaration.response;
2402
+ delete functionDeclaration.response;
2403
+ }
2404
+ }
2405
+ }
2406
+ }
2407
+ }
2408
+ return tool;
2409
+ }
2410
+
2411
+ // src/transformer/transformers/utils/gemini.util.ts
2412
+ function buildRequestBody(request) {
2413
+ const tools = [];
2414
+ const functionDeclarations = request.tools?.filter((tool) => tool.function.name !== "web_search")?.map((tool) => ({
2415
+ name: tool.function.name,
2416
+ description: tool.function.description,
2417
+ parametersJsonSchema: tool.function.parameters
2418
+ }));
2419
+ if (functionDeclarations?.length) {
2420
+ tools.push(
2421
+ transformTool({
2422
+ functionDeclarations
2423
+ })
2424
+ );
2425
+ }
2426
+ const webSearch = request.tools?.find((tool) => tool.function.name === "web_search");
2427
+ if (webSearch) {
2428
+ tools.push({ googleSearch: {} });
2429
+ }
2430
+ const contents = [];
2431
+ const toolResponses = request.messages.filter((item) => item.role === "tool");
2432
+ request.messages.filter((item) => item.role !== "tool").forEach((message) => {
2433
+ let role;
2434
+ if (message.role === "assistant") {
2435
+ role = "model";
2436
+ } else if (["user", "system"].includes(message.role)) {
2437
+ role = "user";
2438
+ } else {
2439
+ role = "user";
2440
+ }
2441
+ const parts = [];
2442
+ if (typeof message.content === "string") {
2443
+ const part = { text: message.content };
2444
+ if (message.thinking?.signature) {
2445
+ part.thoughtSignature = message.thinking.signature;
2446
+ }
2447
+ parts.push(part);
2448
+ } else if (Array.isArray(message.content)) {
2449
+ for (const content of message.content) {
2450
+ if (content.type === "text") {
2451
+ parts.push({ text: content.text || "" });
2452
+ } else if (content.type === "image_url") {
2453
+ const imageUrl = content.image_url?.url ?? "";
2454
+ if (imageUrl.startsWith("http")) {
2455
+ parts.push({
2456
+ file_data: {
2457
+ mime_type: content.media_type,
2458
+ file_uri: imageUrl
2459
+ }
2460
+ });
2461
+ } else {
2462
+ const data = imageUrl.split(",").pop() || imageUrl;
2463
+ parts.push({
2464
+ inlineData: {
2465
+ mime_type: content.media_type || "image/png",
2466
+ data
2467
+ }
2468
+ });
2469
+ }
2470
+ }
2471
+ }
2472
+ } else if (message.content && typeof message.content === "object") {
2473
+ const contentObj = message.content;
2474
+ if (contentObj.text) {
2475
+ parts.push({ text: contentObj.text });
2476
+ } else {
2477
+ parts.push({ text: JSON.stringify(message.content) });
2478
+ }
2479
+ }
2480
+ if (Array.isArray(message.tool_calls)) {
2481
+ for (let index = 0; index < message.tool_calls.length; index++) {
2482
+ const toolCall = message.tool_calls[index];
2483
+ const functionCallPart = {
2484
+ functionCall: {
2485
+ id: toolCall.id || `tool_${Math.random().toString(36).substring(2, 15)}`,
2486
+ name: toolCall.function.name,
2487
+ args: JSON.parse(toolCall.function.arguments || "{}")
2488
+ }
2489
+ };
2490
+ if (index === 0 && message.thinking?.signature) {
2491
+ functionCallPart.thoughtSignature = message.thinking.signature;
2492
+ }
2493
+ parts.push(functionCallPart);
2494
+ }
2495
+ }
2496
+ if (parts.length === 0) {
2497
+ parts.push({ text: "" });
2498
+ }
2499
+ contents.push({ role, parts });
2500
+ if (role === "model" && message.tool_calls) {
2501
+ const functionResponses = message.tool_calls.map(
2502
+ (tool) => {
2503
+ const response = toolResponses.find((item) => item.tool_call_id === tool.id);
2504
+ return {
2505
+ functionResponse: {
2506
+ name: tool.function?.name ?? "",
2507
+ response: { result: response?.content }
2508
+ }
2509
+ };
2510
+ }
2511
+ );
2512
+ contents.push({
2513
+ role: "user",
2514
+ parts: functionResponses
2515
+ });
2516
+ }
2517
+ });
2518
+ const generationConfig = {};
2519
+ if (request.reasoning?.effort && request.reasoning.effort !== "none") {
2520
+ generationConfig.thinkingConfig = {
2521
+ includeThoughts: true
2522
+ };
2523
+ if (request.model.includes("gemini-3")) {
2524
+ generationConfig.thinkingConfig.thinkingLevel = request.reasoning.effort;
2525
+ } else {
2526
+ const thinkingBudgets = request.model.includes("pro") ? [128, 32768] : [0, 24576];
2527
+ const maxTokens = request.reasoning.max_tokens;
2528
+ if (typeof maxTokens !== "undefined") {
2529
+ let thinkingBudget;
2530
+ if (maxTokens >= thinkingBudgets[0] && maxTokens <= thinkingBudgets[1]) {
2531
+ thinkingBudget = maxTokens;
2532
+ } else if (maxTokens < thinkingBudgets[0]) {
2533
+ thinkingBudget = thinkingBudgets[0];
2534
+ } else {
2535
+ thinkingBudget = thinkingBudgets[1];
2536
+ }
2537
+ generationConfig.thinkingConfig.thinkingBudget = thinkingBudget;
2538
+ }
2539
+ }
2540
+ }
2541
+ const body = {
2542
+ contents,
2543
+ tools: tools.length > 0 ? tools : void 0,
2544
+ generationConfig: Object.keys(generationConfig).length > 0 ? generationConfig : void 0
2545
+ };
2546
+ if (request.tool_choice) {
2547
+ const toolConfig = {
2548
+ functionCallingConfig: {}
2549
+ };
2550
+ if (request.tool_choice === "auto") {
2551
+ toolConfig.functionCallingConfig.mode = "auto";
2552
+ } else if (request.tool_choice === "none") {
2553
+ toolConfig.functionCallingConfig.mode = "none";
2554
+ } else if (request.tool_choice === "required") {
2555
+ toolConfig.functionCallingConfig.mode = "any";
2556
+ } else if (typeof request.tool_choice === "object" && request.tool_choice.function?.name) {
2557
+ toolConfig.functionCallingConfig.mode = "any";
2558
+ toolConfig.functionCallingConfig.allowedFunctionNames = [
2559
+ request.tool_choice.function.name
2560
+ ];
2561
+ }
2562
+ body.toolConfig = toolConfig;
2563
+ }
2564
+ return body;
2565
+ }
2566
+ function transformRequestOut(request) {
2567
+ const contents = request.contents;
2568
+ const tools = request.tools;
2569
+ const model = request.model;
2570
+ const maxTokens = request.max_tokens;
2571
+ const temperature = request.temperature;
2572
+ const stream = request.stream;
2573
+ const toolChoice = request.tool_choice;
2574
+ const unifiedRequest = {
2575
+ messages: [],
2576
+ model,
2577
+ max_tokens: maxTokens,
2578
+ temperature,
2579
+ stream,
2580
+ tool_choice: toolChoice
2581
+ };
2582
+ if (Array.isArray(contents)) {
2583
+ for (const content of contents) {
2584
+ if (typeof content === "string") {
2585
+ unifiedRequest.messages.push({
2586
+ role: "user",
2587
+ content
2588
+ });
2589
+ } else if ("text" in content && typeof content.text === "string") {
2590
+ unifiedRequest.messages.push({
2591
+ role: "user",
2592
+ content: content.text || null
2593
+ });
2594
+ } else if ("role" in content && content.role === "user") {
2595
+ const geminiContent = content;
2596
+ unifiedRequest.messages.push({
2597
+ role: "user",
2598
+ content: geminiContent.parts?.map((part) => ({
2599
+ type: "text",
2600
+ text: part.text || ""
2601
+ })) || []
2602
+ });
2603
+ } else if (content.role === "model") {
2604
+ unifiedRequest.messages.push({
2605
+ role: "assistant",
2606
+ content: content.parts?.map((part) => ({
2607
+ type: "text",
2608
+ text: part.text || ""
2609
+ })) || []
2610
+ });
2611
+ }
2612
+ }
2613
+ }
2614
+ if (Array.isArray(tools)) {
2615
+ unifiedRequest.tools = [];
2616
+ for (const tool of tools) {
2617
+ if (Array.isArray(tool.functionDeclarations)) {
2618
+ for (const funcDecl of tool.functionDeclarations) {
2619
+ unifiedRequest.tools.push({
2620
+ type: "function",
2621
+ function: {
2622
+ name: funcDecl.name,
2623
+ description: funcDecl.description ?? "",
2624
+ parameters: funcDecl.parameters ?? {}
2625
+ }
2626
+ });
2627
+ }
2628
+ }
2629
+ }
2630
+ }
2631
+ return unifiedRequest;
2632
+ }
2633
+
2634
+ // src/transformer/transformers/GeminiCodeAssistTransformer.ts
2635
+ var DEFAULT_CODE_ASSIST_ENDPOINT = "https://cloudcode-pa.googleapis.com";
2636
+ var DEFAULT_CODE_ASSIST_API_VERSION = "v1internal";
2637
+ function resolveCodeAssistEndpoint() {
2638
+ return (process.env.CODE_ASSIST_ENDPOINT || DEFAULT_CODE_ASSIST_ENDPOINT).replace(/\/+$/, "");
2639
+ }
2640
+ function resolveCodeAssistApiVersion() {
2641
+ return process.env.CODE_ASSIST_API_VERSION || DEFAULT_CODE_ASSIST_API_VERSION;
2642
+ }
2643
+ function buildCodeAssistUrl(stream) {
2644
+ const base = resolveCodeAssistEndpoint();
2645
+ const version = resolveCodeAssistApiVersion();
2646
+ const method = stream ? "streamGenerateContent?alt=sse" : "generateContent";
2647
+ return `${base}/${version}:${method}`;
2648
+ }
2649
+ function generateUserPromptId() {
2650
+ const c = globalThis.crypto;
2651
+ if (c?.randomUUID) return c.randomUUID();
2652
+ return `omnicross-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
2653
+ }
2654
+ function peelResponseEnvelope(parsed) {
2655
+ if (parsed && typeof parsed === "object" && "response" in parsed) {
2656
+ return parsed.response;
2657
+ }
2658
+ return parsed;
2659
+ }
2660
+ async function unwrapCodeAssistResponse(response) {
2661
+ const contentType = response.headers.get("Content-Type") ?? "";
2662
+ if (contentType.includes("stream") || contentType.includes("text/event-stream")) {
2663
+ const sourceBody = response.body;
2664
+ if (!sourceBody) return response;
2665
+ const decoder = new TextDecoder();
2666
+ const encoder = new TextEncoder();
2667
+ const peeled = new ReadableStream({
2668
+ async start(controller) {
2669
+ const reader = sourceBody.getReader();
2670
+ let buffer = "";
2671
+ const processLine = (line) => {
2672
+ if (!line.startsWith("data:")) {
2673
+ if (line.length > 0) controller.enqueue(encoder.encode(`${line}
2674
+ `));
2675
+ return;
2676
+ }
2677
+ const payload = line.slice(line.indexOf(":") + 1).trim();
2678
+ if (!payload || payload === "[DONE]") {
2679
+ controller.enqueue(encoder.encode(`${line}
2680
+ `));
2681
+ return;
2682
+ }
2683
+ try {
2684
+ const parsed = JSON.parse(payload);
2685
+ const inner2 = peelResponseEnvelope(parsed);
2686
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(inner2)}
2687
+ `));
2688
+ } catch {
2689
+ controller.enqueue(encoder.encode(`${line}
2690
+ `));
2691
+ }
2692
+ };
2693
+ try {
2694
+ while (true) {
2695
+ const { done, value } = await reader.read();
2696
+ if (done) {
2697
+ if (buffer) processLine(buffer);
2698
+ break;
2699
+ }
2700
+ buffer += decoder.decode(value, { stream: true });
2701
+ const lines = buffer.split("\n");
2702
+ buffer = lines.pop() || "";
2703
+ for (const line of lines) processLine(line);
2704
+ }
2705
+ } catch (err) {
2706
+ controller.error(err);
2707
+ } finally {
2708
+ controller.close();
2709
+ }
2710
+ }
2711
+ });
2712
+ return new Response(peeled, {
2713
+ status: response.status,
2714
+ statusText: response.statusText,
2715
+ headers: response.headers
2716
+ });
2717
+ }
2718
+ const raw = await response.json().catch(() => null);
2719
+ const inner = peelResponseEnvelope(raw);
2720
+ return new Response(JSON.stringify(inner), {
2721
+ status: response.status,
2722
+ statusText: response.statusText,
2723
+ headers: response.headers
2724
+ });
2725
+ }
2726
+ var GeminiCodeAssistTransformer = class {
2727
+ static TransformerName = "gemini-code-assist";
2728
+ name = "gemini-code-assist";
2729
+ logger;
2730
+ /** Code Assist has no fixed `/models/:modelAndAction` endpoint pattern — the
2731
+ * URL is built per-request in `transformRequestIn`. Left undefined so the
2732
+ * TransformerService does NOT treat this as an endpoint (reverse) transformer. */
2733
+ endPoint = void 0;
2734
+ /**
2735
+ * unified → Code Assist envelope.
2736
+ *
2737
+ * Builds the inner public-Gemini body via the shared `buildRequestBody`, then
2738
+ * wraps it as `{ model, project, user_prompt_id, request: <inner> }` and sets
2739
+ * the Code Assist URL + Bearer-only headers.
2740
+ *
2741
+ * The resolved Code Assist `project` is threaded in via `provider.geminiProject`
2742
+ * (stashed by the subscription dispatch seam — see SubscriptionDispatcher /
2743
+ * openaiResponsesIngress). `undefined` is the valid fresh free-tier value.
2744
+ */
2745
+ async transformRequestIn(request, provider, _context) {
2746
+ const inner = buildRequestBody(request);
2747
+ const envelope = {
2748
+ model: request.model,
2749
+ project: provider.geminiProject,
2750
+ user_prompt_id: generateUserPromptId(),
2751
+ request: inner
2752
+ };
2753
+ const url = buildCodeAssistUrl(Boolean(request.stream));
2754
+ const headers = {
2755
+ "x-goog-api-key": void 0,
2756
+ "X-Goog-Api-Key": void 0
2757
+ };
2758
+ return {
2759
+ body: envelope,
2760
+ config: { url, headers }
2761
+ };
2762
+ }
2763
+ /**
2764
+ * Code Assist request → unified (endpoint-decode parity with GeminiTransformer).
2765
+ * Peels the top-level `request` envelope first, then delegates to the shared
2766
+ * gemini request decoder. Not used on the subscription dispatch path (the
2767
+ * endpoint transformer there is Anthropic/OpenAI-Response), but provided for
2768
+ * completeness so this transformer is a drop-in for the gemini one.
2769
+ */
2770
+ async transformRequestOut(request, _context) {
2771
+ const r = request;
2772
+ const inner = r && typeof r === "object" && "request" in r ? r.request : r;
2773
+ if (inner && typeof inner === "object" && !("model" in inner) && "model" in r) {
2774
+ inner.model = r.model;
2775
+ }
2776
+ return transformRequestOut(inner);
2777
+ }
2778
+ /**
2779
+ * Code Assist response → OpenAI-compatible. PEEL the `.response` envelope from
2780
+ * the body / each SSE chunk, then DELEGATE to the existing gemini parser.
2781
+ */
2782
+ async transformResponseOut(response, _context) {
2783
+ const unwrapped = await unwrapCodeAssistResponse(response);
2784
+ return transformResponseOut(unwrapped, this.name, this.logger);
2785
+ }
2786
+ /**
2787
+ * OpenAI-compatible response → Code Assist (endpoint-encode parity). Re-wraps
2788
+ * the standard gemini response under the top-level `response` key after the
2789
+ * shared gemini encoder produces a public-Gemini body. Symmetric with
2790
+ * `transformResponseOut`'s peel.
2791
+ */
2792
+ async transformResponseIn(response, _context) {
2793
+ const geminiResponse = await transformResponseIn(response, this.logger);
2794
+ const contentType = geminiResponse.headers.get("Content-Type") ?? "";
2795
+ if (contentType.includes("text/event-stream")) {
2796
+ return geminiResponse;
2797
+ }
2798
+ const data = await geminiResponse.json().catch(() => null);
2799
+ return new Response(JSON.stringify({ response: data }), {
2800
+ status: geminiResponse.status,
2801
+ statusText: geminiResponse.statusText,
2802
+ headers: { "Content-Type": "application/json" }
2803
+ });
2804
+ }
2805
+ };
2806
+
2807
+ // src/transformer/transformers/GeminiTransformer.ts
2808
+ var GeminiTransformer = class {
2809
+ static TransformerName = "gemini";
2810
+ name = "gemini";
2811
+ logger;
2812
+ /**
2813
+ * API endpoint pattern for Gemini
2814
+ * :modelAndAction will be replaced with actual model and action
2815
+ */
2816
+ endPoint = "/v1beta/models/:modelAndAction";
2817
+ /** Use Bearer token instead of x-goog-api-key (for relay providers) */
2818
+ useBearer;
2819
+ constructor(options) {
2820
+ this.useBearer = options?.UseBearer ?? false;
2821
+ }
2822
+ /**
2823
+ * Handle authentication
2824
+ * - Official Gemini: x-goog-api-key header
2825
+ * - Relay providers: Authorization: Bearer header
2826
+ */
2827
+ async auth(request, provider, _context) {
2828
+ const headers = {};
2829
+ if (this.useBearer) {
2830
+ headers["authorization"] = `Bearer ${provider.apiKey}`;
2831
+ headers["x-goog-api-key"] = void 0;
2832
+ } else {
2833
+ headers["x-goog-api-key"] = provider.apiKey;
2834
+ headers["authorization"] = void 0;
2835
+ }
2836
+ return {
2837
+ body: request,
2838
+ config: { headers }
2839
+ };
2840
+ }
2841
+ /**
2842
+ * Transform request from unified format to Gemini format
2843
+ * Also builds the correct URL for the Gemini API
2844
+ */
2845
+ async transformRequestIn(request, provider, _context) {
2846
+ const body = buildRequestBody(request);
2847
+ const action = request.stream ? "streamGenerateContent?alt=sse" : "generateContent";
2848
+ const url = new URL(`./${request.model}:${action}`, provider.baseUrl);
2849
+ const headers = {};
2850
+ if (this.useBearer) {
2851
+ headers["authorization"] = `Bearer ${provider.apiKey}`;
2852
+ headers["x-goog-api-key"] = void 0;
2853
+ } else {
2854
+ headers["x-goog-api-key"] = provider.apiKey;
2855
+ headers["Authorization"] = void 0;
2856
+ }
2857
+ return {
2858
+ body,
2859
+ config: { url, headers }
2860
+ };
2861
+ }
2862
+ /**
2863
+ * Transform incoming request to unified format
2864
+ * (For requests coming into the Gemini endpoint)
2865
+ */
2866
+ async transformRequestOut(request, _context) {
2867
+ return transformRequestOut(request);
2868
+ }
2869
+ /**
2870
+ * Transform Gemini response to OpenAI-compatible format
2871
+ */
2872
+ async transformResponseOut(response, _context) {
2873
+ return transformResponseOut(response, this.name, this.logger);
2874
+ }
2875
+ /**
2876
+ * Transform OpenAI-compatible response back to Gemini format
2877
+ * (For endpoint mode — returning Gemini-format responses to the client)
2878
+ */
2879
+ async transformResponseIn(response, _context) {
2880
+ return transformResponseIn(response, this.logger);
2881
+ }
2882
+ };
2883
+
2884
+ // src/transformer/transformers/OpenAIResponseTransformer.ts
2885
+ var OpenAIResponseTransformer = class {
2886
+ static TransformerName = "openai-response";
2887
+ name = "openai-response";
2888
+ endPoint = "/v1/responses";
2889
+ logger;
2890
+ /**
2891
+ * Handle authentication - Bearer token
2892
+ */
2893
+ async auth(request, provider, _context) {
2894
+ return {
2895
+ body: request,
2896
+ config: {
2897
+ headers: {
2898
+ Authorization: `Bearer ${provider.apiKey}`,
2899
+ "Content-Type": "application/json"
2900
+ }
2901
+ }
2902
+ };
2903
+ }
2904
+ /**
2905
+ * Transform unified request → Response API format
2906
+ */
2907
+ async transformRequestIn(request, provider, _context) {
2908
+ const input = [];
2909
+ for (const msg of request.messages) {
2910
+ if (msg.role === "system") {
2911
+ input.push({
2912
+ role: "developer",
2913
+ content: typeof msg.content === "string" ? msg.content : flattenContent(msg.content)
2914
+ });
2915
+ } else if (msg.role === "tool") {
2916
+ input.push({
2917
+ type: "function_call_output",
2918
+ call_id: msg.tool_call_id,
2919
+ output: typeof msg.content === "string" ? msg.content : ""
2920
+ });
2921
+ } else {
2922
+ const entry = {
2923
+ role: msg.role,
2924
+ content: typeof msg.content === "string" ? msg.content : flattenContent(msg.content)
2925
+ };
2926
+ if (msg.role === "assistant" && msg.tool_calls?.length) {
2927
+ input.push(entry);
2928
+ for (const tc of msg.tool_calls) {
2929
+ input.push({
2930
+ type: "function_call",
2931
+ id: tc.id,
2932
+ call_id: tc.id,
2933
+ name: tc.function.name,
2934
+ arguments: tc.function.arguments
2935
+ });
2936
+ }
2937
+ continue;
2938
+ }
2939
+ input.push(entry);
2940
+ }
2941
+ }
2942
+ const body = {
2943
+ model: request.model,
2944
+ input,
2945
+ stream: request.stream ?? false,
2946
+ ...request.max_tokens ? { max_output_tokens: request.max_tokens } : {},
2947
+ ...request.temperature !== void 0 ? { temperature: request.temperature } : {}
2948
+ };
2949
+ if (request.reasoning?.effort && request.reasoning.effort !== "none") {
2950
+ body.reasoning = { effort: request.reasoning.effort, summary: "auto" };
2951
+ }
2952
+ if (request.tools?.length) {
2953
+ body.tools = request.tools.map((tool) => ({
2954
+ type: "function",
2955
+ name: tool.function.name,
2956
+ description: tool.function.description,
2957
+ parameters: tool.function.parameters
2958
+ }));
2959
+ }
2960
+ if (request.tool_choice) {
2961
+ if (typeof request.tool_choice === "string") {
2962
+ body.tool_choice = request.tool_choice;
2963
+ } else if (typeof request.tool_choice === "object" && "function" in request.tool_choice) {
2964
+ body.tool_choice = { type: "function", name: request.tool_choice.function.name };
2965
+ }
2966
+ }
2967
+ const url = new URL("/v1/responses", provider.baseUrl);
2968
+ return { body, config: { url } };
2969
+ }
2970
+ /**
2971
+ * Transform Response API request → unified format
2972
+ */
2973
+ async transformRequestOut(request, _context) {
2974
+ const req = request;
2975
+ const messages = [];
2976
+ if (req.input) {
2977
+ for (const item of req.input) {
2978
+ const entry = item;
2979
+ if (entry.type === "function_call_output") {
2980
+ messages.push({
2981
+ role: "tool",
2982
+ content: entry.output || "",
2983
+ tool_call_id: entry.call_id || void 0
2984
+ });
2985
+ continue;
2986
+ }
2987
+ if (entry.type === "function_call") {
2988
+ const toolCall = {
2989
+ id: (entry.call_id ?? entry.id) || "",
2990
+ type: "function",
2991
+ function: {
2992
+ name: entry.name || "",
2993
+ arguments: typeof entry.arguments === "string" ? entry.arguments : ""
2994
+ }
2995
+ };
2996
+ const last = messages[messages.length - 1];
2997
+ if (last && last.role === "assistant") {
2998
+ (last.tool_calls ??= []).push(toolCall);
2999
+ } else {
3000
+ messages.push({ role: "assistant", content: null, tool_calls: [toolCall] });
3001
+ }
3002
+ continue;
3003
+ }
3004
+ const role = entry.role;
3005
+ if (role === "developer") {
3006
+ messages.push({
3007
+ role: "system",
3008
+ content: typeof entry.content === "string" ? entry.content : JSON.stringify(entry.content)
3009
+ });
3010
+ } else if (role === "user" || role === "assistant") {
3011
+ messages.push({
3012
+ role,
3013
+ content: typeof entry.content === "string" ? entry.content : JSON.stringify(entry.content)
3014
+ });
3015
+ }
3016
+ }
3017
+ }
3018
+ const result = {
3019
+ messages,
3020
+ model: req.model,
3021
+ max_tokens: req.max_output_tokens,
3022
+ temperature: req.temperature,
3023
+ stream: req.stream
3024
+ };
3025
+ if (req.reasoning?.effort) {
3026
+ result.reasoning = {
3027
+ effort: req.reasoning.effort,
3028
+ enabled: true
3029
+ };
3030
+ }
3031
+ if (req.tools?.length) {
3032
+ result.tools = req.tools.filter((t) => t.type === "function").map((t) => ({
3033
+ type: "function",
3034
+ function: {
3035
+ name: t.name || "",
3036
+ description: t.description || "",
3037
+ parameters: t.parameters || {}
3038
+ }
3039
+ }));
3040
+ }
3041
+ return result;
3042
+ }
3043
+ /**
3044
+ * Transform Response API response → unified (OpenAI CC) format
3045
+ */
3046
+ async transformResponseOut(response, _context) {
3047
+ const contentType = response.headers.get("Content-Type") ?? "";
3048
+ if (contentType.includes("text/event-stream")) {
3049
+ if (!response.body) {
3050
+ throw new Error("Stream response body is null");
3051
+ }
3052
+ return new Response(convertResponseApiStreamToOpenAI(response.body), {
3053
+ headers: {
3054
+ "Content-Type": "text/event-stream",
3055
+ "Cache-Control": "no-cache",
3056
+ Connection: "keep-alive"
3057
+ }
3058
+ });
3059
+ }
3060
+ const data = await response.json();
3061
+ return new Response(JSON.stringify(convertResponseApiJsonToOpenAI(data)), {
3062
+ headers: { "Content-Type": "application/json" }
3063
+ });
3064
+ }
3065
+ /**
3066
+ * Transform OpenAI CC response → Response API format
3067
+ */
3068
+ async transformResponseIn(response, _context) {
3069
+ const contentType = response.headers.get("Content-Type") ?? "";
3070
+ if (contentType.includes("text/event-stream")) {
3071
+ if (!response.body) {
3072
+ throw new Error("Stream response body is null");
3073
+ }
3074
+ return new Response(convertOpenAIStreamToResponseApi(response.body), {
3075
+ headers: {
3076
+ "Content-Type": "text/event-stream",
3077
+ "Cache-Control": "no-cache",
3078
+ Connection: "keep-alive"
3079
+ }
3080
+ });
3081
+ }
3082
+ const data = await response.json();
3083
+ return new Response(JSON.stringify(convertOpenAIJsonToResponseApi(data)), {
3084
+ headers: { "Content-Type": "application/json" }
3085
+ });
3086
+ }
3087
+ };
3088
+ function flattenContent(content) {
3089
+ if (typeof content === "string") return content;
3090
+ if (!content) return "";
3091
+ if (Array.isArray(content)) {
3092
+ return content.filter((c) => c.type === "text").map((c) => c.text || "").join("\n");
3093
+ }
3094
+ return "";
3095
+ }
3096
+ function convertResponseApiJsonToOpenAI(data) {
3097
+ let textContent = "";
3098
+ const toolCalls = [];
3099
+ const output = data.output;
3100
+ if (output) {
3101
+ for (const item of output) {
3102
+ if (item.type === "message") {
3103
+ const content = item.content;
3104
+ if (content) {
3105
+ for (const part of content) {
3106
+ if (part.type === "output_text" && typeof part.text === "string") {
3107
+ textContent += part.text;
3108
+ }
3109
+ }
3110
+ }
3111
+ } else if (item.type === "function_call") {
3112
+ toolCalls.push({
3113
+ id: item.call_id || item.id || `call_${Date.now()}`,
3114
+ type: "function",
3115
+ function: {
3116
+ name: item.name,
3117
+ arguments: typeof item.arguments === "string" ? item.arguments : JSON.stringify(item.arguments || {})
3118
+ }
3119
+ });
3120
+ }
3121
+ }
3122
+ }
3123
+ const usage = data.usage;
3124
+ const message = {
3125
+ role: "assistant",
3126
+ content: textContent || null
3127
+ };
3128
+ if (toolCalls.length > 0) {
3129
+ message.tool_calls = toolCalls;
3130
+ }
3131
+ return {
3132
+ id: data.id || `chatcmpl-${Date.now()}`,
3133
+ object: "chat.completion",
3134
+ created: Math.floor(Date.now() / 1e3),
3135
+ model: data.model || "unknown",
3136
+ choices: [
3137
+ {
3138
+ index: 0,
3139
+ message,
3140
+ finish_reason: toolCalls.length > 0 ? "tool_calls" : "stop"
3141
+ }
3142
+ ],
3143
+ usage: usage ? {
3144
+ prompt_tokens: usage.input_tokens || 0,
3145
+ completion_tokens: usage.output_tokens || 0,
3146
+ total_tokens: (usage.input_tokens || 0) + (usage.output_tokens || 0)
3147
+ } : void 0
3148
+ };
3149
+ }
3150
+ function convertOpenAIJsonToResponseApi(data) {
3151
+ const choices = data.choices;
3152
+ const message = choices?.[0]?.message;
3153
+ const output = [];
3154
+ if (message) {
3155
+ const contentParts = [];
3156
+ if (message.content) {
3157
+ contentParts.push({ type: "output_text", text: message.content });
3158
+ }
3159
+ if (contentParts.length > 0) {
3160
+ output.push({ type: "message", role: "assistant", content: contentParts });
3161
+ }
3162
+ const toolCalls = message.tool_calls;
3163
+ if (toolCalls?.length) {
3164
+ for (const tc of toolCalls) {
3165
+ const func = tc.function;
3166
+ output.push({
3167
+ type: "function_call",
3168
+ id: tc.id,
3169
+ call_id: tc.id,
3170
+ name: func?.name,
3171
+ arguments: func?.arguments
3172
+ });
3173
+ }
3174
+ }
3175
+ }
3176
+ const usage = data.usage;
3177
+ return {
3178
+ id: data.id || `resp_${Date.now()}`,
3179
+ object: "response",
3180
+ status: "completed",
3181
+ model: data.model || "unknown",
3182
+ output,
3183
+ usage: usage ? {
3184
+ input_tokens: usage.prompt_tokens || 0,
3185
+ output_tokens: usage.completion_tokens || 0,
3186
+ total_tokens: usage.total_tokens || (usage.prompt_tokens || 0) + (usage.completion_tokens || 0)
3187
+ } : void 0
3188
+ };
3189
+ }
3190
+ function convertResponseApiStreamToOpenAI(responseApiStream) {
3191
+ const decoder = new TextDecoder();
3192
+ const encoder = new TextEncoder();
3193
+ return new ReadableStream({
3194
+ start: async (controller) => {
3195
+ const reader = responseApiStream.getReader();
3196
+ let buffer = "";
3197
+ let isClosed = false;
3198
+ const messageId = `chatcmpl-${Date.now()}`;
3199
+ let model = "unknown";
3200
+ let hasEmittedRole = false;
3201
+ const safeEnqueue = (str) => {
3202
+ if (!isClosed) {
3203
+ try {
3204
+ controller.enqueue(encoder.encode(str));
3205
+ } catch {
3206
+ isClosed = true;
3207
+ }
3208
+ }
3209
+ };
3210
+ const emitChunk = (choices, usage) => {
3211
+ const chunk = {
3212
+ id: messageId,
3213
+ object: "chat.completion.chunk",
3214
+ created: Math.floor(Date.now() / 1e3),
3215
+ model,
3216
+ choices
3217
+ };
3218
+ if (usage) chunk.usage = usage;
3219
+ safeEnqueue(`data: ${JSON.stringify(chunk)}
3220
+
3221
+ `);
3222
+ };
3223
+ try {
3224
+ while (true) {
3225
+ const { done, value } = await reader.read();
3226
+ if (done) break;
3227
+ buffer += decoder.decode(value, { stream: true });
3228
+ const lines = buffer.split("\n");
3229
+ buffer = lines.pop() || "";
3230
+ for (const line of lines) {
3231
+ if (isClosed) break;
3232
+ if (!line.startsWith("data:")) continue;
3233
+ const data = line.slice(5).trim();
3234
+ if (data === "[DONE]") continue;
3235
+ try {
3236
+ const event = JSON.parse(data);
3237
+ model = event.model || event.response?.model || model;
3238
+ switch (event.type) {
3239
+ case "response.output_text.delta":
3240
+ if (event.delta) {
3241
+ if (!hasEmittedRole) {
3242
+ emitChunk([{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }]);
3243
+ hasEmittedRole = true;
3244
+ }
3245
+ emitChunk([{ index: 0, delta: { content: event.delta }, finish_reason: null }]);
3246
+ }
3247
+ break;
3248
+ case "response.reasoning_summary_text.delta":
3249
+ if (event.delta) {
3250
+ emitChunk([{
3251
+ index: 0,
3252
+ delta: { thinking: { content: event.delta } },
3253
+ finish_reason: null
3254
+ }]);
3255
+ }
3256
+ break;
3257
+ case "response.completed": {
3258
+ const resp = event.response;
3259
+ const respUsage = resp?.usage;
3260
+ const usage = respUsage ? {
3261
+ prompt_tokens: respUsage.input_tokens || 0,
3262
+ completion_tokens: respUsage.output_tokens || 0,
3263
+ total_tokens: (respUsage.input_tokens || 0) + (respUsage.output_tokens || 0)
3264
+ } : void 0;
3265
+ emitChunk([{ index: 0, delta: {}, finish_reason: "stop" }], usage);
3266
+ safeEnqueue("data: [DONE]\n\n");
3267
+ break;
3268
+ }
3269
+ case "error":
3270
+ emitChunk([{
3271
+ index: 0,
3272
+ delta: { content: `[Error: ${event.error?.message || "Unknown error"}]` },
3273
+ finish_reason: "stop"
3274
+ }]);
3275
+ break;
3276
+ default:
3277
+ break;
3278
+ }
3279
+ } catch {
3280
+ }
3281
+ }
3282
+ }
3283
+ } catch (e) {
3284
+ if (!isClosed) controller.error(e);
3285
+ } finally {
3286
+ if (!isClosed) {
3287
+ try {
3288
+ controller.close();
3289
+ } catch {
3290
+ }
3291
+ }
3292
+ reader.releaseLock();
3293
+ }
3294
+ }
3295
+ });
3296
+ }
3297
+ function convertOpenAIStreamToResponseApi(openaiStream) {
3298
+ const decoder = new TextDecoder();
3299
+ const encoder = new TextEncoder();
3300
+ return new ReadableStream({
3301
+ start: async (controller) => {
3302
+ const reader = openaiStream.getReader();
3303
+ let buffer = "";
3304
+ let isClosed = false;
3305
+ let accumulatedContent = "";
3306
+ let model = "unknown";
3307
+ const responseId = `resp_${Date.now()}`;
3308
+ const safeEnqueue = (str) => {
3309
+ if (!isClosed) {
3310
+ try {
3311
+ controller.enqueue(encoder.encode(str));
3312
+ } catch {
3313
+ isClosed = true;
3314
+ }
3315
+ }
3316
+ };
3317
+ const emitEvent = (event) => {
3318
+ safeEnqueue(`data: ${JSON.stringify(event)}
3319
+
3320
+ `);
3321
+ };
3322
+ emitEvent({
3323
+ type: "response.created",
3324
+ response: { id: responseId, status: "in_progress" }
3325
+ });
3326
+ try {
3327
+ while (true) {
3328
+ const { done, value } = await reader.read();
3329
+ if (done) break;
3330
+ buffer += decoder.decode(value, { stream: true });
3331
+ const lines = buffer.split("\n");
3332
+ buffer = lines.pop() || "";
3333
+ for (const line of lines) {
3334
+ if (isClosed) break;
3335
+ if (!line.startsWith("data:")) continue;
3336
+ const data = line.slice(5).trim();
3337
+ if (data === "[DONE]") continue;
3338
+ try {
3339
+ const chunk = JSON.parse(data);
3340
+ const choice = chunk.choices?.[0];
3341
+ model = chunk.model || model;
3342
+ if (!choice) continue;
3343
+ if (choice.delta?.content) {
3344
+ accumulatedContent += choice.delta.content;
3345
+ emitEvent({ type: "response.output_text.delta", delta: choice.delta.content });
3346
+ }
3347
+ if (choice.delta?.thinking?.content) {
3348
+ emitEvent({
3349
+ type: "response.reasoning_summary_text.delta",
3350
+ delta: choice.delta.thinking.content
3351
+ });
3352
+ }
3353
+ if (choice.finish_reason) {
3354
+ emitEvent({ type: "response.output_text.done", text: accumulatedContent });
3355
+ emitEvent({
3356
+ type: "response.completed",
3357
+ response: {
3358
+ id: responseId,
3359
+ status: "completed",
3360
+ model,
3361
+ output: [
3362
+ {
3363
+ type: "message",
3364
+ role: "assistant",
3365
+ content: [{ type: "output_text", text: accumulatedContent }]
3366
+ }
3367
+ ],
3368
+ usage: chunk.usage ? {
3369
+ input_tokens: chunk.usage.prompt_tokens || 0,
3370
+ output_tokens: chunk.usage.completion_tokens || 0,
3371
+ total_tokens: chunk.usage.total_tokens || 0
3372
+ } : void 0
3373
+ }
3374
+ });
3375
+ }
3376
+ } catch {
3377
+ }
3378
+ }
3379
+ }
3380
+ } catch (e) {
3381
+ if (!isClosed) controller.error(e);
3382
+ } finally {
3383
+ if (!isClosed) {
3384
+ try {
3385
+ controller.close();
3386
+ } catch {
3387
+ }
3388
+ }
3389
+ reader.releaseLock();
3390
+ }
3391
+ }
3392
+ });
3393
+ }
3394
+
3395
+ // src/transformer/transformers/OpenCodeGoTransformer.ts
3396
+ var OpenCodeGoTransformer = class {
3397
+ static TransformerName = "opencodego";
3398
+ name = "opencodego";
3399
+ endPoint = "/v1/chat/completions";
3400
+ logger;
3401
+ async auth(request, _provider, _context) {
3402
+ return { body: request, config: { headers: {} } };
3403
+ }
3404
+ /**
3405
+ * Unified → OpenAI Chat Completions.
3406
+ * Unified IS chat completions shape; this is mostly stripping `meta` and
3407
+ * normalizing string-content single-block messages.
3408
+ */
3409
+ async transformRequestIn(request, _provider, _context) {
3410
+ const messages = request.messages.map((m) => {
3411
+ const content = m.content;
3412
+ if (Array.isArray(content) && content.length === 1 && content[0]?.type === "text") {
3413
+ return { ...m, content: content[0].text };
3414
+ }
3415
+ return m;
3416
+ });
3417
+ const out = {
3418
+ model: request.model,
3419
+ messages,
3420
+ stream: request.stream
3421
+ };
3422
+ if (request.temperature !== void 0) out.temperature = request.temperature;
3423
+ if (request.max_tokens !== void 0) out.max_tokens = request.max_tokens;
3424
+ if (request.tools && request.tools.length > 0) out.tools = request.tools;
3425
+ if (request.tool_choice !== void 0) out.tool_choice = request.tool_choice;
3426
+ if (request.reasoning?.effort && request.reasoning.effort !== "none") {
3427
+ out.reasoning_effort = request.reasoning.effort;
3428
+ }
3429
+ return out;
3430
+ }
3431
+ /**
3432
+ * OpenAI Chat Completions response → Unified.
3433
+ * The upstream's response shape already matches Unified — pass through.
3434
+ * The endpoint AnthropicTransformer re-encodes to Anthropic for the SDK.
3435
+ */
3436
+ async transformResponseOut(response, _context) {
3437
+ return response;
3438
+ }
3439
+ };
3440
+
3441
+ // src/transformer/transformers/ReasoningTransformer.ts
3442
+ import {
3443
+ buildAnthropicThinking,
3444
+ buildQwenThinkingConfig,
3445
+ calculateThinkingBudget,
3446
+ getOpenAIReasoningEffort
3447
+ } from "@omnicross/contracts/thinking-config";
3448
+ var ReasoningTransformer = class {
3449
+ static TransformerName = "reasoning";
3450
+ name = "reasoning";
3451
+ logger;
3452
+ enabled;
3453
+ constructor(options) {
3454
+ this.enabled = options?.enable !== false;
3455
+ }
3456
+ /**
3457
+ * Transform request: convert reasoning config to thinking parameters
3458
+ * Uses model-specific budget calculation based on effort level
3459
+ */
3460
+ async transformRequestIn(request, provider, _context) {
3461
+ const extendedRequest = request;
3462
+ const modelId = request.model;
3463
+ if (!this.enabled) {
3464
+ extendedRequest.thinking = {
3465
+ type: "disabled",
3466
+ budget_tokens: -1
3467
+ };
3468
+ extendedRequest.enable_thinking = false;
3469
+ return extendedRequest;
3470
+ }
3471
+ if (request.reasoning) {
3472
+ const effortLevel = request.reasoning.effort || "none";
3473
+ const userMaxTokens = request.reasoning.max_tokens || request.max_tokens;
3474
+ const calculatedBudget = calculateThinkingBudget(modelId, effortLevel, userMaxTokens);
3475
+ const providerName = provider.name?.toLowerCase() || "";
3476
+ if (providerName === "anthropic" || providerName.includes("claude")) {
3477
+ const thinkingConfig = buildAnthropicThinking(modelId, effortLevel, userMaxTokens);
3478
+ if (thinkingConfig) {
3479
+ extendedRequest.thinking = thinkingConfig;
3480
+ } else {
3481
+ extendedRequest.thinking = {
3482
+ type: "disabled"
3483
+ };
3484
+ }
3485
+ } else if (providerName === "openai" || modelId.match(/^o[134]/i)) {
3486
+ const reasoningEffort = getOpenAIReasoningEffort(effortLevel);
3487
+ if (reasoningEffort) {
3488
+ extendedRequest.reasoning_effort = reasoningEffort;
3489
+ }
3490
+ extendedRequest.thinking = {
3491
+ type: effortLevel === "none" ? "disabled" : "enabled",
3492
+ budget_tokens: calculatedBudget
3493
+ };
3494
+ } else if (providerName === "deepseek" && modelId?.startsWith("deepseek-v4")) {
3495
+ extendedRequest.thinking = {
3496
+ type: effortLevel === "none" ? "disabled" : "enabled",
3497
+ budget_tokens: calculatedBudget
3498
+ };
3499
+ if (effortLevel !== "none") {
3500
+ extendedRequest.reasoning_effort = effortLevel === "high" ? "max" : "high";
3501
+ }
3502
+ } else if (providerName === "deepseek" || providerName === "qwen" || providerName === "alibaba") {
3503
+ const qwenConfig = buildQwenThinkingConfig(effortLevel, userMaxTokens);
3504
+ extendedRequest.enable_thinking = qwenConfig.enable_thinking;
3505
+ if (qwenConfig.thinking_budget) {
3506
+ extendedRequest.thinking_budget = qwenConfig.thinking_budget;
3507
+ }
3508
+ extendedRequest.thinking = {
3509
+ type: qwenConfig.enable_thinking ? "enabled" : "disabled",
3510
+ budget_tokens: calculatedBudget
3511
+ };
3512
+ } else {
3513
+ extendedRequest.thinking = {
3514
+ type: effortLevel === "none" ? "disabled" : "enabled",
3515
+ budget_tokens: calculatedBudget
3516
+ };
3517
+ extendedRequest.enable_thinking = effortLevel !== "none";
3518
+ }
3519
+ this.logger?.debug(`[ReasoningTransformer] Model: ${modelId}, Effort: ${effortLevel}, Budget: ${calculatedBudget}`);
3520
+ }
3521
+ return extendedRequest;
3522
+ }
3523
+ /**
3524
+ * Transform response: convert reasoning_content to thinking blocks
3525
+ */
3526
+ async transformResponseOut(response, _context) {
3527
+ if (!this.enabled) return response;
3528
+ const contentType = response.headers.get("Content-Type") ?? "";
3529
+ if (contentType.includes("application/json")) {
3530
+ return this.handleJsonResponse(response);
3531
+ } else if (contentType.includes("stream") || contentType.includes("text/event-stream")) {
3532
+ return this.handleStreamResponse(response);
3533
+ }
3534
+ return response;
3535
+ }
3536
+ /**
3537
+ * Handle JSON (non-streaming) response
3538
+ */
3539
+ async handleJsonResponse(response) {
3540
+ const jsonResponse = await response.json();
3541
+ if (jsonResponse.choices?.[0]?.message?.reasoning_content) {
3542
+ jsonResponse.thinking = {
3543
+ content: jsonResponse.choices[0].message.reasoning_content
3544
+ };
3545
+ delete jsonResponse.choices[0].message.reasoning_content;
3546
+ }
3547
+ return new Response(JSON.stringify(jsonResponse), {
3548
+ status: response.status,
3549
+ statusText: response.statusText,
3550
+ headers: response.headers
3551
+ });
3552
+ }
3553
+ /**
3554
+ * Handle streaming response - convert reasoning_content to thinking blocks
3555
+ */
3556
+ handleStreamResponse(response) {
3557
+ if (!response.body) {
3558
+ return response;
3559
+ }
3560
+ const decoder = new TextDecoder();
3561
+ const encoder = new TextEncoder();
3562
+ let reasoningContent = "";
3563
+ let isReasoningComplete = false;
3564
+ let buffer = "";
3565
+ const stream = new ReadableStream({
3566
+ start: async (controller) => {
3567
+ const reader = response.body.getReader();
3568
+ const processLine = (line) => {
3569
+ this.logger?.debug("Processing reasoning line:", line);
3570
+ if (line.startsWith("data: ") && line.trim() !== "data: [DONE]") {
3571
+ try {
3572
+ const data = JSON.parse(line.slice(6));
3573
+ if (data.choices?.[0]?.delta?.reasoning_content) {
3574
+ reasoningContent += data.choices[0].delta.reasoning_content;
3575
+ const thinkingChunk = {
3576
+ ...data,
3577
+ choices: [
3578
+ {
3579
+ ...data.choices[0],
3580
+ delta: {
3581
+ ...data.choices[0].delta,
3582
+ thinking: {
3583
+ content: data.choices[0].delta.reasoning_content
3584
+ }
3585
+ }
3586
+ }
3587
+ ]
3588
+ };
3589
+ delete thinkingChunk.choices[0].delta.reasoning_content;
3590
+ const thinkingLine = `data: ${JSON.stringify(thinkingChunk)}
3591
+
3592
+ `;
3593
+ controller.enqueue(encoder.encode(thinkingLine));
3594
+ return;
3595
+ }
3596
+ if ((data.choices?.[0]?.delta?.content || data.choices?.[0]?.delta?.tool_calls) && reasoningContent && !isReasoningComplete) {
3597
+ isReasoningComplete = true;
3598
+ const signature = Date.now().toString();
3599
+ const thinkingChunk = {
3600
+ ...data,
3601
+ choices: [
3602
+ {
3603
+ ...data.choices[0],
3604
+ delta: {
3605
+ ...data.choices[0].delta,
3606
+ content: null,
3607
+ thinking: {
3608
+ signature
3609
+ }
3610
+ }
3611
+ }
3612
+ ]
3613
+ };
3614
+ delete thinkingChunk.choices[0].delta.reasoning_content;
3615
+ const thinkingLine = `data: ${JSON.stringify(thinkingChunk)}
3616
+
3617
+ `;
3618
+ controller.enqueue(encoder.encode(thinkingLine));
3619
+ }
3620
+ if (data.choices?.[0]?.delta?.reasoning_content) {
3621
+ delete data.choices[0].delta.reasoning_content;
3622
+ }
3623
+ if (data.choices?.[0]?.delta && Object.keys(data.choices[0].delta).length > 0) {
3624
+ if (isReasoningComplete) {
3625
+ data.choices[0].index++;
3626
+ }
3627
+ const modifiedLine = `data: ${JSON.stringify(data)}
3628
+
3629
+ `;
3630
+ controller.enqueue(encoder.encode(modifiedLine));
3631
+ }
3632
+ } catch (_e) {
3633
+ controller.enqueue(encoder.encode(line + "\n"));
3634
+ }
3635
+ } else {
3636
+ controller.enqueue(encoder.encode(line + "\n"));
3637
+ }
3638
+ };
3639
+ try {
3640
+ while (true) {
3641
+ const { done, value } = await reader.read();
3642
+ if (done) {
3643
+ if (buffer.trim()) {
3644
+ const lines2 = buffer.split("\n");
3645
+ for (const line of lines2) {
3646
+ if (line.trim()) {
3647
+ controller.enqueue(encoder.encode(line + "\n"));
3648
+ }
3649
+ }
3650
+ }
3651
+ break;
3652
+ }
3653
+ const chunk = decoder.decode(value, { stream: true });
3654
+ buffer += chunk;
3655
+ const lines = buffer.split("\n");
3656
+ buffer = lines.pop() || "";
3657
+ for (const line of lines) {
3658
+ if (!line.trim()) continue;
3659
+ try {
3660
+ processLine(line);
3661
+ } catch (error) {
3662
+ this.logger?.error("Error processing reasoning stream line:", error);
3663
+ controller.enqueue(encoder.encode(line + "\n"));
3664
+ }
3665
+ }
3666
+ }
3667
+ } catch (error) {
3668
+ this.logger?.error("Reasoning stream error:", error);
3669
+ controller.error(error);
3670
+ } finally {
3671
+ try {
3672
+ reader.releaseLock();
3673
+ } catch (e) {
3674
+ this.logger?.error("Error releasing reader lock:", e);
3675
+ }
3676
+ controller.close();
3677
+ }
3678
+ }
3679
+ });
3680
+ return new Response(stream, {
3681
+ status: response.status,
3682
+ statusText: response.statusText,
3683
+ headers: new Headers({
3684
+ "Content-Type": "text/event-stream",
3685
+ "Cache-Control": "no-cache",
3686
+ Connection: "keep-alive"
3687
+ })
3688
+ });
3689
+ }
3690
+ };
3691
+
3692
+ // src/transformer/transformers/index.ts
3693
+ var BuiltinTransformers = {
3694
+ DeepseekTransformer,
3695
+ ReasoningTransformer,
3696
+ GeminiTransformer,
3697
+ GeminiCodeAssistTransformer,
3698
+ AnthropicTransformer,
3699
+ OpenAIResponseTransformer,
3700
+ OpenCodeGoTransformer
3701
+ };
3702
+ function getBuiltinTransformers() {
3703
+ return BuiltinTransformers;
3704
+ }
3705
+ async function registerBuiltinTransformers(service) {
3706
+ await service.initialize(getBuiltinTransformers());
3707
+ }
3708
+ export {
3709
+ TransformerChainExecutor,
3710
+ TransformerService,
3711
+ registerBuiltinTransformers
3712
+ };