@omnicross/core 0.1.0 → 0.1.1

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 (139) hide show
  1. package/dist/ApiConverter.cjs +799 -0
  2. package/dist/ApiConverter.d.cts +82 -0
  3. package/dist/ApiConverter.d.ts +82 -0
  4. package/dist/ApiConverter.js +763 -0
  5. package/dist/BuiltinToolExecutor-BluWyeob.d.ts +81 -0
  6. package/dist/BuiltinToolExecutor-CS2WpXhM.d.cts +81 -0
  7. package/dist/CompletionService-7fCmKAP3.d.ts +212 -0
  8. package/dist/CompletionService-DtOF_War.d.cts +212 -0
  9. package/dist/{ProviderProxy-f_8ziIhW.d.cts → ProviderProxy-C-xqrkKi.d.ts} +7 -2
  10. package/dist/{ProviderProxy-vjt8sQQk.d.ts → ProviderProxy-CnMQYN59.d.cts} +7 -2
  11. package/dist/completion/BuiltinToolExecutor.cjs +327 -0
  12. package/dist/completion/BuiltinToolExecutor.d.cts +4 -0
  13. package/dist/completion/BuiltinToolExecutor.d.ts +4 -0
  14. package/dist/completion/BuiltinToolExecutor.js +296 -0
  15. package/dist/completion/CompletionService.cjs +3487 -0
  16. package/dist/completion/CompletionService.d.cts +21 -0
  17. package/dist/completion/CompletionService.d.ts +21 -0
  18. package/dist/completion/CompletionService.js +3461 -0
  19. package/dist/completion/NativeSearchInjector.cjs +196 -0
  20. package/dist/completion/NativeSearchInjector.d.cts +42 -0
  21. package/dist/completion/NativeSearchInjector.d.ts +42 -0
  22. package/dist/completion/NativeSearchInjector.js +167 -0
  23. package/dist/completion/ProviderSearchInjector.cjs +87 -0
  24. package/dist/completion/ProviderSearchInjector.d.cts +47 -0
  25. package/dist/completion/ProviderSearchInjector.d.ts +47 -0
  26. package/dist/completion/ProviderSearchInjector.js +60 -0
  27. package/dist/completion/native-search-types.cjs +67 -0
  28. package/dist/completion/native-search-types.d.cts +3 -0
  29. package/dist/completion/native-search-types.d.ts +3 -0
  30. package/dist/completion/native-search-types.js +38 -0
  31. package/dist/completion/openrouter-headers.cjs +72 -0
  32. package/dist/completion/openrouter-headers.d.cts +44 -0
  33. package/dist/completion/openrouter-headers.d.ts +44 -0
  34. package/dist/completion/openrouter-headers.js +42 -0
  35. package/dist/completion/openrouter-models.cjs +86 -0
  36. package/dist/completion/openrouter-models.d.cts +27 -0
  37. package/dist/completion/openrouter-models.d.ts +27 -0
  38. package/dist/completion/openrouter-models.js +59 -0
  39. package/dist/completion/types.cjs +18 -0
  40. package/dist/completion/types.d.cts +3 -0
  41. package/dist/completion/types.d.ts +3 -0
  42. package/dist/completion/types.js +0 -0
  43. package/dist/completion/url-builder.cjs +138 -0
  44. package/dist/completion/url-builder.d.cts +87 -0
  45. package/dist/completion/url-builder.d.ts +87 -0
  46. package/dist/completion/url-builder.js +104 -0
  47. package/dist/completion.d.cts +148 -7
  48. package/dist/completion.d.ts +148 -7
  49. package/dist/index.cjs +1 -0
  50. package/dist/index.d.cts +27 -90
  51. package/dist/index.d.ts +27 -90
  52. package/dist/index.js +1 -0
  53. package/dist/outbound-api/routeResolver.cjs +221 -0
  54. package/dist/outbound-api/routeResolver.d.cts +18 -0
  55. package/dist/outbound-api/routeResolver.d.ts +18 -0
  56. package/dist/outbound-api/routeResolver.js +192 -0
  57. package/dist/outbound-api/subscriptionRegistryPort.d.cts +5 -2
  58. package/dist/outbound-api/subscriptionRegistryPort.d.ts +5 -2
  59. package/dist/outbound-api/types.cjs +18 -0
  60. package/dist/{types-CbCN2NQP.d.ts → outbound-api/types.d.cts} +17 -3
  61. package/dist/{types-CGGrKqC_.d.cts → outbound-api/types.d.ts} +17 -3
  62. package/dist/outbound-api/types.js +0 -0
  63. package/dist/outbound-api.cjs +1 -0
  64. package/dist/outbound-api.d.cts +14 -87
  65. package/dist/outbound-api.d.ts +14 -87
  66. package/dist/outbound-api.js +1 -0
  67. package/dist/pipeline/AuthSource.cjs +18 -0
  68. package/dist/pipeline/AuthSource.d.cts +101 -0
  69. package/dist/pipeline/AuthSource.d.ts +101 -0
  70. package/dist/pipeline/AuthSource.js +0 -0
  71. package/dist/pipeline/LlmConfigProviderAuth.cjs +169 -0
  72. package/dist/pipeline/LlmConfigProviderAuth.d.cts +86 -0
  73. package/dist/pipeline/LlmConfigProviderAuth.d.ts +86 -0
  74. package/dist/pipeline/LlmConfigProviderAuth.js +142 -0
  75. package/dist/pipeline/SubscriptionAuthSource.d.cts +165 -3
  76. package/dist/pipeline/SubscriptionAuthSource.d.ts +165 -3
  77. package/dist/pipeline/executeProviderCall.cjs +70 -0
  78. package/dist/pipeline/executeProviderCall.d.cts +149 -0
  79. package/dist/pipeline/executeProviderCall.d.ts +149 -0
  80. package/dist/pipeline/executeProviderCall.js +45 -0
  81. package/dist/pipeline/resolveProviderChain.cjs +47 -0
  82. package/dist/pipeline/resolveProviderChain.d.cts +58 -0
  83. package/dist/pipeline/resolveProviderChain.d.ts +58 -0
  84. package/dist/pipeline/resolveProviderChain.js +22 -0
  85. package/dist/pipeline/resolveSubscriptionChain.cjs +68 -0
  86. package/dist/pipeline/resolveSubscriptionChain.d.cts +68 -0
  87. package/dist/pipeline/resolveSubscriptionChain.d.ts +68 -0
  88. package/dist/pipeline/resolveSubscriptionChain.js +43 -0
  89. package/dist/ports/provider-config-source.cjs +18 -0
  90. package/dist/ports/provider-config-source.d.cts +51 -0
  91. package/dist/ports/provider-config-source.d.ts +51 -0
  92. package/dist/ports/provider-config-source.js +0 -0
  93. package/dist/ports/web-search-backend.cjs +18 -0
  94. package/dist/ports/web-search-backend.d.cts +29 -0
  95. package/dist/ports/web-search-backend.d.ts +29 -0
  96. package/dist/ports/web-search-backend.js +0 -0
  97. package/dist/ports.d.cts +10 -7
  98. package/dist/ports.d.ts +10 -7
  99. package/dist/provider-proxy/ProviderProxy.cjs +4643 -0
  100. package/dist/provider-proxy/ProviderProxy.d.cts +16 -0
  101. package/dist/provider-proxy/ProviderProxy.d.ts +16 -0
  102. package/dist/provider-proxy/ProviderProxy.js +4618 -0
  103. package/dist/provider-proxy/ingress/providerProxyShared.d.cts +5 -2
  104. package/dist/provider-proxy/ingress/providerProxyShared.d.ts +5 -2
  105. package/dist/provider-proxy/types.d.cts +406 -8
  106. package/dist/provider-proxy/types.d.ts +406 -8
  107. package/dist/provider-proxy.cjs +1 -0
  108. package/dist/provider-proxy.d.cts +8 -5
  109. package/dist/provider-proxy.d.ts +8 -5
  110. package/dist/provider-proxy.js +1 -0
  111. package/dist/routeResolver-BrbK6ja9.d.cts +88 -0
  112. package/dist/routeResolver-HE-ZO0fO.d.ts +88 -0
  113. package/dist/transformer/anthropicBetaInject.cjs +51 -0
  114. package/dist/transformer/anthropicBetaInject.d.cts +20 -0
  115. package/dist/transformer/anthropicBetaInject.d.ts +20 -0
  116. package/dist/transformer/anthropicBetaInject.js +25 -0
  117. package/dist/transformer/transformers/AnthropicTransformer.cjs +1017 -0
  118. package/dist/transformer/transformers/AnthropicTransformer.d.cts +148 -0
  119. package/dist/transformer/transformers/AnthropicTransformer.d.ts +148 -0
  120. package/dist/transformer/transformers/AnthropicTransformer.js +990 -0
  121. package/dist/transformer/transformers/ReasoningTransformer.cjs +273 -0
  122. package/dist/transformer/transformers/ReasoningTransformer.d.cts +47 -0
  123. package/dist/transformer/transformers/ReasoningTransformer.d.ts +47 -0
  124. package/dist/transformer/transformers/ReasoningTransformer.js +253 -0
  125. package/dist/transformer/transformers.cjs +3206 -0
  126. package/dist/transformer/transformers.d.cts +100 -0
  127. package/dist/transformer/transformers.d.ts +100 -0
  128. package/dist/transformer/transformers.js +3174 -0
  129. package/dist/transformer.d.cts +8 -31
  130. package/dist/transformer.d.ts +8 -31
  131. package/dist/types-BScIHmPr.d.cts +153 -0
  132. package/dist/types-BScIHmPr.d.ts +153 -0
  133. package/package.json +3 -3
  134. package/dist/SubscriptionAuthSource-Cr4fVEYY.d.cts +0 -264
  135. package/dist/SubscriptionAuthSource-D89zmiSS.d.ts +0 -264
  136. package/dist/index-BTSmc9Sm.d.ts +0 -645
  137. package/dist/index-DXazdTzZ.d.cts +0 -645
  138. package/dist/types-DCzHkhJt.d.ts +0 -467
  139. package/dist/types-DZIQbgp0.d.cts +0 -467
@@ -0,0 +1,1017 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/transformer/transformers/AnthropicTransformer.ts
21
+ var AnthropicTransformer_exports = {};
22
+ __export(AnthropicTransformer_exports, {
23
+ AnthropicTransformer: () => AnthropicTransformer
24
+ });
25
+ module.exports = __toCommonJS(AnthropicTransformer_exports);
26
+
27
+ // src/transformer/transformers/AnthropicToolHandling.ts
28
+ function isServerSideTool(tool) {
29
+ const type = String(tool.type || "");
30
+ return type.startsWith("web_search_") || type.startsWith("code_execution_") || type.startsWith("text_editor_") || type.startsWith("memory_") || type.startsWith("web_fetch_") || type.startsWith("search_tool_");
31
+ }
32
+ function convertAnthropicToolsToOpenAI(tools) {
33
+ return tools.filter((tool) => !isServerSideTool(tool)).map((tool) => ({
34
+ type: "function",
35
+ function: {
36
+ name: String(tool.name),
37
+ description: String(tool.description || ""),
38
+ parameters: tool.input_schema
39
+ }
40
+ }));
41
+ }
42
+
43
+ // src/transformer/transformers/AnthropicTypes.ts
44
+ function getThinkLevel(budgetTokens) {
45
+ if (!budgetTokens || budgetTokens <= 0) return "none";
46
+ if (budgetTokens < 4096) return "low";
47
+ if (budgetTokens < 16384) return "medium";
48
+ return "high";
49
+ }
50
+ function formatBase64(data, mediaType) {
51
+ if (data.startsWith("data:")) return data;
52
+ return `data:${mediaType || "image/png"};base64,${data}`;
53
+ }
54
+
55
+ // src/transformer/transformers/AnthropicRequestBuilder.ts
56
+ function buildAnthropicRequestBody(request) {
57
+ let systemContent;
58
+ const anthropicMessages = [];
59
+ for (let i = 0; i < request.messages.length; i++) {
60
+ const msg = request.messages[i];
61
+ if (msg.role === "system") {
62
+ if (typeof msg.content === "string") {
63
+ systemContent = msg.content;
64
+ } else if (Array.isArray(msg.content)) {
65
+ systemContent = msg.content.filter((c) => c.type === "text").map((c) => ({
66
+ type: "text",
67
+ text: c.text,
68
+ ...c.cache_control ? { cache_control: c.cache_control } : {}
69
+ }));
70
+ }
71
+ continue;
72
+ }
73
+ if (msg.role === "assistant") {
74
+ const content = [];
75
+ if (msg.thinking?.content) {
76
+ const block = {
77
+ type: "thinking",
78
+ thinking: msg.thinking.content
79
+ };
80
+ if (msg.thinking.signature) {
81
+ block.signature = msg.thinking.signature;
82
+ }
83
+ content.push(block);
84
+ }
85
+ if (msg.content) {
86
+ const text = typeof msg.content === "string" ? msg.content : msg.content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
87
+ if (text) {
88
+ content.push({ type: "text", text });
89
+ }
90
+ }
91
+ if (msg.tool_calls?.length) {
92
+ for (const tc of msg.tool_calls) {
93
+ let input;
94
+ try {
95
+ input = typeof tc.function.arguments === "string" ? JSON.parse(tc.function.arguments) : tc.function.arguments;
96
+ } catch {
97
+ input = { text: tc.function.arguments || "" };
98
+ }
99
+ content.push({
100
+ type: "tool_use",
101
+ id: tc.id,
102
+ name: tc.function.name,
103
+ input
104
+ });
105
+ }
106
+ }
107
+ anthropicMessages.push({
108
+ role: "assistant",
109
+ content: content.length > 0 ? content : ""
110
+ });
111
+ continue;
112
+ }
113
+ if (msg.role === "tool") {
114
+ const toolResults = [];
115
+ let j = i;
116
+ while (j < request.messages.length && request.messages[j].role === "tool") {
117
+ const t = request.messages[j];
118
+ toolResults.push({
119
+ type: "tool_result",
120
+ tool_use_id: t.tool_call_id || "",
121
+ content: typeof t.content === "string" ? t.content : JSON.stringify(t.content),
122
+ ...t.cache_control ? { cache_control: t.cache_control } : {}
123
+ });
124
+ j++;
125
+ }
126
+ anthropicMessages.push({ role: "user", content: toolResults });
127
+ i = j - 1;
128
+ continue;
129
+ }
130
+ if (typeof msg.content === "string") {
131
+ anthropicMessages.push({ role: "user", content: msg.content });
132
+ } else if (Array.isArray(msg.content)) {
133
+ const content = msg.content.map((part) => {
134
+ if (part.type === "image_url") {
135
+ const url = part.image_url.url;
136
+ if (url.startsWith("data:")) {
137
+ const match = url.match(/^data:([^;]+);base64,(.+)$/);
138
+ if (match) {
139
+ return {
140
+ type: "image",
141
+ source: { type: "base64", media_type: match[1], data: match[2] }
142
+ };
143
+ }
144
+ }
145
+ return {
146
+ type: "image",
147
+ source: { type: "url", url }
148
+ };
149
+ }
150
+ return { type: "text", text: part.text };
151
+ });
152
+ anthropicMessages.push({ role: "user", content });
153
+ }
154
+ }
155
+ const body = {
156
+ model: request.model,
157
+ messages: anthropicMessages,
158
+ max_tokens: request.max_tokens || 4096,
159
+ stream: request.stream ?? false
160
+ };
161
+ if (request.temperature !== void 0) {
162
+ body.temperature = request.temperature;
163
+ }
164
+ if (systemContent !== void 0) {
165
+ body.system = systemContent;
166
+ }
167
+ if (request.tools?.length) {
168
+ body.tools = request.tools.map((tool) => ({
169
+ name: tool.function.name,
170
+ description: tool.function.description || "",
171
+ input_schema: tool.function.parameters
172
+ }));
173
+ }
174
+ const serverSideTools = request._serverSideTools;
175
+ if (serverSideTools?.length) {
176
+ body.tools = [...body.tools || [], ...serverSideTools];
177
+ }
178
+ if (request.tool_choice) {
179
+ if (typeof request.tool_choice === "string") {
180
+ if (request.tool_choice === "required") {
181
+ body.tool_choice = { type: "any" };
182
+ } else if (request.tool_choice !== "none") {
183
+ body.tool_choice = { type: request.tool_choice };
184
+ }
185
+ } else if (typeof request.tool_choice === "object" && "function" in request.tool_choice) {
186
+ body.tool_choice = { type: "tool", name: request.tool_choice.function.name };
187
+ }
188
+ }
189
+ if (request.reasoning?.enabled) {
190
+ const budgetMap = { low: 2048, medium: 8192, high: 32768 };
191
+ const budget = request.reasoning.max_tokens || budgetMap[request.reasoning.effort || "medium"] || 8192;
192
+ body.thinking = { type: "enabled", budget_tokens: budget };
193
+ body.temperature = 1;
194
+ }
195
+ return body;
196
+ }
197
+
198
+ // src/transformer/transformers/AnthropicResponseConversion.ts
199
+ function convertAnthropicResponseToOpenAI(anthropicResponse) {
200
+ const content = anthropicResponse.content || [];
201
+ const textParts = content.filter((c) => c.type === "text").map((c) => c.text);
202
+ const toolUses = content.filter((c) => c.type === "tool_use" || c.type === "server_tool_use");
203
+ const thinkingBlock = content.find((c) => c.type === "thinking");
204
+ const searchResults = content.filter((c) => c.type === "web_search_tool_result");
205
+ for (const sr of searchResults) {
206
+ const searches = sr.content;
207
+ if (searches?.length) {
208
+ const formatted = searches.map((s) => `[${s.title}](${s.url}): ${s.page_content || s.snippet || ""}`).join("\n");
209
+ textParts.push(`
210
+
211
+ **Search Results:**
212
+ ${formatted}`);
213
+ }
214
+ }
215
+ const message = {
216
+ role: "assistant",
217
+ content: textParts.join("") || null
218
+ };
219
+ if (toolUses.length > 0) {
220
+ message.tool_calls = toolUses.map((tc) => ({
221
+ id: tc.id,
222
+ type: "function",
223
+ function: {
224
+ name: tc.name,
225
+ arguments: JSON.stringify(tc.input || {})
226
+ }
227
+ }));
228
+ }
229
+ if (thinkingBlock) {
230
+ message.thinking = {
231
+ content: thinkingBlock.thinking,
232
+ signature: thinkingBlock.signature
233
+ };
234
+ }
235
+ const stopReasonMapping = {
236
+ end_turn: "stop",
237
+ max_tokens: "length",
238
+ tool_use: "tool_calls",
239
+ stop_sequence: "stop"
240
+ };
241
+ const usage = anthropicResponse.usage;
242
+ return {
243
+ id: anthropicResponse.id || `chatcmpl-${Date.now()}`,
244
+ object: "chat.completion",
245
+ created: Math.floor(Date.now() / 1e3),
246
+ model: anthropicResponse.model || "unknown",
247
+ choices: [{
248
+ index: 0,
249
+ message,
250
+ finish_reason: stopReasonMapping[anthropicResponse.stop_reason] || "stop"
251
+ }],
252
+ usage: usage ? {
253
+ prompt_tokens: usage.input_tokens || 0,
254
+ completion_tokens: usage.output_tokens || 0,
255
+ total_tokens: (usage.input_tokens || 0) + (usage.output_tokens || 0)
256
+ } : void 0
257
+ };
258
+ }
259
+ function convertOpenAIResponseToAnthropic(openaiResponse) {
260
+ const choice = openaiResponse.choices?.[0];
261
+ if (!choice) {
262
+ throw new Error("No choices found in OpenAI response");
263
+ }
264
+ const message = choice.message;
265
+ const content = [];
266
+ if (message.content) {
267
+ content.push({
268
+ type: "text",
269
+ text: message.content
270
+ });
271
+ }
272
+ const toolCalls = message.tool_calls;
273
+ if (toolCalls?.length) {
274
+ for (const toolCall of toolCalls) {
275
+ const func = toolCall.function;
276
+ let parsedInput = {};
277
+ try {
278
+ const args = func.arguments;
279
+ parsedInput = typeof args === "string" ? JSON.parse(args) : args;
280
+ } catch {
281
+ parsedInput = { text: func.arguments || "" };
282
+ }
283
+ content.push({
284
+ type: "tool_use",
285
+ id: toolCall.id,
286
+ name: func.name,
287
+ input: parsedInput
288
+ });
289
+ }
290
+ }
291
+ const thinking = message.thinking;
292
+ if (thinking?.content) {
293
+ content.push({
294
+ type: "thinking",
295
+ thinking: thinking.content,
296
+ signature: thinking.signature
297
+ });
298
+ }
299
+ const finishReason = choice.finish_reason;
300
+ const stopReasonMapping = {
301
+ stop: "end_turn",
302
+ length: "max_tokens",
303
+ tool_calls: "tool_use",
304
+ content_filter: "stop_sequence"
305
+ };
306
+ const usage = openaiResponse.usage;
307
+ const usageDetails = usage?.prompt_tokens_details;
308
+ return {
309
+ id: openaiResponse.id,
310
+ type: "message",
311
+ role: "assistant",
312
+ model: openaiResponse.model,
313
+ content,
314
+ stop_reason: stopReasonMapping[finishReason] || "end_turn",
315
+ stop_sequence: null,
316
+ usage: {
317
+ input_tokens: (usage?.prompt_tokens || 0) - (usageDetails?.cached_tokens || 0),
318
+ output_tokens: usage?.completion_tokens || 0,
319
+ cache_read_input_tokens: usageDetails?.cached_tokens || 0
320
+ }
321
+ };
322
+ }
323
+
324
+ // src/transformer/transformers/AnthropicConversion.ts
325
+ function transformAnthropicRequestToUnified(request) {
326
+ const anthropicRequest = request;
327
+ const messages = [];
328
+ if (anthropicRequest.system) {
329
+ if (typeof anthropicRequest.system === "string") {
330
+ messages.push({
331
+ role: "system",
332
+ content: anthropicRequest.system
333
+ });
334
+ } else if (Array.isArray(anthropicRequest.system)) {
335
+ const textParts = anthropicRequest.system.filter((item) => item.type === "text" && item.text).map((item) => ({
336
+ type: "text",
337
+ text: item.text,
338
+ cache_control: item.cache_control
339
+ }));
340
+ if (textParts.length > 0) {
341
+ messages.push({
342
+ role: "system",
343
+ content: textParts
344
+ });
345
+ }
346
+ }
347
+ }
348
+ const requestMessages = JSON.parse(JSON.stringify(anthropicRequest.messages || []));
349
+ for (const msg of requestMessages) {
350
+ if (msg.role !== "user" && msg.role !== "assistant") continue;
351
+ if (typeof msg.content === "string") {
352
+ messages.push({
353
+ role: msg.role,
354
+ content: msg.content
355
+ });
356
+ continue;
357
+ }
358
+ if (Array.isArray(msg.content)) {
359
+ if (msg.role === "user") {
360
+ const toolParts = msg.content.filter(
361
+ (c) => c.type === "tool_result" && c.tool_use_id
362
+ );
363
+ for (const tool of toolParts) {
364
+ messages.push({
365
+ role: "tool",
366
+ content: typeof tool.content === "string" ? tool.content : JSON.stringify(tool.content),
367
+ tool_call_id: tool.tool_use_id,
368
+ cache_control: tool.cache_control
369
+ });
370
+ }
371
+ const textAndMediaParts = msg.content.filter(
372
+ (c) => c.type === "text" && c.text || c.type === "image" && c.source
373
+ );
374
+ if (textAndMediaParts.length > 0) {
375
+ messages.push({
376
+ role: "user",
377
+ content: textAndMediaParts.map((part) => {
378
+ if (part.type === "image") {
379
+ const imagePart = part;
380
+ return {
381
+ type: "image_url",
382
+ image_url: {
383
+ url: imagePart.source.type === "base64" ? formatBase64(imagePart.source.data || "", imagePart.source.media_type) : imagePart.source.url || ""
384
+ },
385
+ media_type: imagePart.source.media_type
386
+ };
387
+ }
388
+ return {
389
+ type: "text",
390
+ text: part.text
391
+ };
392
+ })
393
+ });
394
+ }
395
+ } else if (msg.role === "assistant") {
396
+ const assistantMessage = {
397
+ role: "assistant",
398
+ content: ""
399
+ };
400
+ const textParts = msg.content.filter(
401
+ (c) => c.type === "text" && c.text
402
+ );
403
+ if (textParts.length > 0) {
404
+ assistantMessage.content = textParts.map((t) => t.text).join("\n");
405
+ }
406
+ const toolCallParts = msg.content.filter(
407
+ (c) => c.type === "tool_use" && c.id
408
+ );
409
+ if (toolCallParts.length > 0) {
410
+ assistantMessage.tool_calls = toolCallParts.map((tool) => ({
411
+ id: tool.id,
412
+ type: "function",
413
+ function: {
414
+ name: tool.name,
415
+ arguments: JSON.stringify(tool.input || {})
416
+ }
417
+ }));
418
+ }
419
+ const thinkingPart = msg.content.find(
420
+ (c) => c.type === "thinking"
421
+ );
422
+ if (thinkingPart?.thinking) {
423
+ assistantMessage.thinking = {
424
+ content: thinkingPart.thinking,
425
+ signature: thinkingPart.signature
426
+ };
427
+ }
428
+ messages.push(assistantMessage);
429
+ }
430
+ }
431
+ }
432
+ const rawTools = anthropicRequest.tools || [];
433
+ const serverSideTools = rawTools.filter((t) => isServerSideTool(t));
434
+ const functionTools = rawTools.length > 0 ? convertAnthropicToolsToOpenAI(rawTools) : void 0;
435
+ const result = {
436
+ messages,
437
+ model: anthropicRequest.model,
438
+ max_tokens: anthropicRequest.max_tokens,
439
+ temperature: anthropicRequest.temperature,
440
+ stream: anthropicRequest.stream,
441
+ tools: functionTools?.length ? functionTools : void 0
442
+ };
443
+ if (serverSideTools.length > 0) {
444
+ result._serverSideTools = serverSideTools;
445
+ }
446
+ if (anthropicRequest.thinking) {
447
+ result.reasoning = {
448
+ effort: getThinkLevel(anthropicRequest.thinking.budget_tokens),
449
+ enabled: anthropicRequest.thinking.type === "enabled"
450
+ };
451
+ }
452
+ if (anthropicRequest.tool_choice) {
453
+ if (anthropicRequest.tool_choice.type === "tool" && anthropicRequest.tool_choice.name) {
454
+ result.tool_choice = {
455
+ type: "function",
456
+ function: { name: anthropicRequest.tool_choice.name }
457
+ };
458
+ } else {
459
+ result.tool_choice = anthropicRequest.tool_choice.type;
460
+ }
461
+ }
462
+ return result;
463
+ }
464
+
465
+ // src/transformer/transformers/AnthropicAnthropicToOpenAIStream.ts
466
+ function convertAnthropicStreamToOpenAI(anthropicStream, logger) {
467
+ const decoder = new TextDecoder();
468
+ const encoder = new TextEncoder();
469
+ const activeToolCalls = /* @__PURE__ */ new Map();
470
+ let toolCallCounter = 0;
471
+ let model = "unknown";
472
+ let messageId = `chatcmpl-${Date.now()}`;
473
+ return new ReadableStream({
474
+ start: async (controller) => {
475
+ const reader = anthropicStream.getReader();
476
+ let buffer = "";
477
+ let isClosed = false;
478
+ const safeEnqueue = (data) => {
479
+ if (!isClosed) {
480
+ try {
481
+ controller.enqueue(encoder.encode(data));
482
+ } catch {
483
+ isClosed = true;
484
+ }
485
+ }
486
+ };
487
+ try {
488
+ while (true) {
489
+ const { done, value } = await reader.read();
490
+ if (done) break;
491
+ buffer += decoder.decode(value, { stream: true });
492
+ const lines = buffer.split("\n");
493
+ buffer = lines.pop() || "";
494
+ for (const line of lines) {
495
+ if (isClosed) break;
496
+ if (!line.startsWith("data:")) continue;
497
+ const data = line.slice(5).trim();
498
+ if (!data || data === "[DONE]") continue;
499
+ try {
500
+ const event = JSON.parse(data);
501
+ if (event.type === "message_start" && event.message) {
502
+ model = event.message.model || model;
503
+ messageId = event.message.id || messageId;
504
+ }
505
+ if (event.type === "content_block_delta" && event.delta) {
506
+ const chunk = {
507
+ id: messageId,
508
+ object: "chat.completion.chunk",
509
+ created: Math.floor(Date.now() / 1e3),
510
+ model,
511
+ choices: [{ index: 0, delta: {}, finish_reason: null }]
512
+ };
513
+ const delta = chunk.choices[0].delta;
514
+ if (event.delta.type === "text_delta") {
515
+ delta.content = event.delta.text;
516
+ } else if (event.delta.type === "input_json_delta") {
517
+ const toolInfo = activeToolCalls.get(event.index);
518
+ if (toolInfo) {
519
+ delta.tool_calls = [{
520
+ index: toolInfo.index,
521
+ function: { arguments: event.delta.partial_json }
522
+ }];
523
+ }
524
+ } else if (event.delta.type === "thinking_delta") {
525
+ delta.thinking = { content: event.delta.thinking };
526
+ } else if (event.delta.type === "signature_delta") {
527
+ delta.thinking = { signature: event.delta.signature };
528
+ } else {
529
+ continue;
530
+ }
531
+ safeEnqueue(`data: ${JSON.stringify(chunk)}
532
+
533
+ `);
534
+ }
535
+ if (event.type === "content_block_start" && event.content_block) {
536
+ if (event.content_block.type === "tool_use" || event.content_block.type === "server_tool_use") {
537
+ const tcIndex = toolCallCounter++;
538
+ activeToolCalls.set(event.index, {
539
+ id: event.content_block.id,
540
+ name: event.content_block.name,
541
+ index: tcIndex
542
+ });
543
+ const chunk = {
544
+ id: messageId,
545
+ object: "chat.completion.chunk",
546
+ created: Math.floor(Date.now() / 1e3),
547
+ model,
548
+ choices: [{
549
+ index: 0,
550
+ delta: {
551
+ tool_calls: [{
552
+ index: tcIndex,
553
+ id: event.content_block.id,
554
+ type: "function",
555
+ function: { name: event.content_block.name, arguments: "" }
556
+ }]
557
+ },
558
+ finish_reason: null
559
+ }]
560
+ };
561
+ safeEnqueue(`data: ${JSON.stringify(chunk)}
562
+
563
+ `);
564
+ } else if (event.content_block.type === "web_search_tool_result") {
565
+ const searches = event.content_block.content;
566
+ if (searches?.length) {
567
+ const formatted = searches.map((s) => `[${s.title}](${s.url}): ${s.page_content || s.snippet || ""}`).join("\n");
568
+ const chunk = {
569
+ id: messageId,
570
+ object: "chat.completion.chunk",
571
+ created: Math.floor(Date.now() / 1e3),
572
+ model,
573
+ choices: [{
574
+ index: 0,
575
+ delta: { content: `
576
+
577
+ **Search Results:**
578
+ ${formatted}` },
579
+ finish_reason: null
580
+ }]
581
+ };
582
+ safeEnqueue(`data: ${JSON.stringify(chunk)}
583
+
584
+ `);
585
+ }
586
+ }
587
+ }
588
+ if (event.type === "message_delta" && event.delta) {
589
+ const stopReasonMapping = {
590
+ end_turn: "stop",
591
+ max_tokens: "length",
592
+ tool_use: "tool_calls",
593
+ stop_sequence: "stop"
594
+ };
595
+ const chunk = {
596
+ id: messageId,
597
+ object: "chat.completion.chunk",
598
+ created: Math.floor(Date.now() / 1e3),
599
+ model,
600
+ choices: [{
601
+ index: 0,
602
+ delta: {},
603
+ finish_reason: stopReasonMapping[event.delta.stop_reason] || "stop"
604
+ }]
605
+ };
606
+ if (event.usage) {
607
+ chunk.usage = {
608
+ prompt_tokens: event.usage.input_tokens || 0,
609
+ completion_tokens: event.usage.output_tokens || 0,
610
+ total_tokens: (event.usage.input_tokens || 0) + (event.usage.output_tokens || 0)
611
+ };
612
+ }
613
+ safeEnqueue(`data: ${JSON.stringify(chunk)}
614
+
615
+ `);
616
+ }
617
+ } catch (e) {
618
+ logger?.error("Error parsing Anthropic stream event:", e);
619
+ }
620
+ }
621
+ }
622
+ } catch (e) {
623
+ if (!isClosed) {
624
+ controller.error(e);
625
+ }
626
+ } finally {
627
+ safeEnqueue("data: [DONE]\n\n");
628
+ if (!isClosed) {
629
+ try {
630
+ controller.close();
631
+ } catch {
632
+ }
633
+ }
634
+ reader.releaseLock();
635
+ }
636
+ }
637
+ });
638
+ }
639
+
640
+ // src/transformer/transformers/AnthropicOpenAIToAnthropicStream.ts
641
+ function convertOpenAIStreamToAnthropic(openaiStream, _context, logger) {
642
+ const decoder = new TextDecoder();
643
+ const encoder = new TextEncoder();
644
+ let hasStarted = false;
645
+ let hasTextContentStarted = false;
646
+ let isThinkingStarted = false;
647
+ let contentIndex = 0;
648
+ let currentContentBlockIndex = -1;
649
+ const toolCallIndexToContentBlockIndex = /* @__PURE__ */ new Map();
650
+ return new ReadableStream({
651
+ start: async (controller) => {
652
+ const reader = openaiStream.getReader();
653
+ let buffer = "";
654
+ const messageId = `msg_${Date.now()}`;
655
+ let model = "unknown";
656
+ let isClosed = false;
657
+ let stopReasonDelta = null;
658
+ const safeEnqueue = (data) => {
659
+ if (!isClosed) {
660
+ try {
661
+ controller.enqueue(encoder.encode(data));
662
+ } catch (_e) {
663
+ isClosed = true;
664
+ }
665
+ }
666
+ };
667
+ const assignContentBlockIndex = () => {
668
+ return contentIndex++;
669
+ };
670
+ const safeClose = () => {
671
+ if (isClosed) return;
672
+ if (currentContentBlockIndex >= 0) {
673
+ safeEnqueue(`event: content_block_stop
674
+ data: ${JSON.stringify({
675
+ type: "content_block_stop",
676
+ index: currentContentBlockIndex
677
+ })}
678
+
679
+ `);
680
+ }
681
+ if (stopReasonDelta) {
682
+ safeEnqueue(`event: message_delta
683
+ data: ${JSON.stringify(stopReasonDelta)}
684
+
685
+ `);
686
+ } else {
687
+ safeEnqueue(`event: message_delta
688
+ data: ${JSON.stringify({
689
+ type: "message_delta",
690
+ delta: { stop_reason: "end_turn", stop_sequence: null },
691
+ usage: { input_tokens: 0, output_tokens: 0 }
692
+ })}
693
+
694
+ `);
695
+ }
696
+ safeEnqueue(`event: message_stop
697
+ data: ${JSON.stringify({ type: "message_stop" })}
698
+
699
+ `);
700
+ try {
701
+ controller.close();
702
+ } catch (_e) {
703
+ }
704
+ isClosed = true;
705
+ };
706
+ try {
707
+ while (true) {
708
+ const { done, value } = await reader.read();
709
+ if (done) break;
710
+ buffer += decoder.decode(value, { stream: true });
711
+ const lines = buffer.split("\n");
712
+ buffer = lines.pop() || "";
713
+ for (const line of lines) {
714
+ if (isClosed) break;
715
+ if (!line.startsWith("data:")) continue;
716
+ const data = line.slice(5).trim();
717
+ if (data === "[DONE]") continue;
718
+ try {
719
+ const chunk = JSON.parse(data);
720
+ if (chunk.error) {
721
+ safeEnqueue(`event: error
722
+ data: ${JSON.stringify({
723
+ type: "error",
724
+ message: { type: "api_error", message: JSON.stringify(chunk.error) }
725
+ })}
726
+
727
+ `);
728
+ continue;
729
+ }
730
+ model = chunk.model || model;
731
+ if (!hasStarted) {
732
+ hasStarted = true;
733
+ safeEnqueue(`event: message_start
734
+ data: ${JSON.stringify({
735
+ type: "message_start",
736
+ message: {
737
+ id: messageId,
738
+ type: "message",
739
+ role: "assistant",
740
+ content: [],
741
+ model,
742
+ stop_reason: null,
743
+ stop_sequence: null,
744
+ usage: { input_tokens: 0, output_tokens: 0 }
745
+ }
746
+ })}
747
+
748
+ `);
749
+ }
750
+ const choice = chunk.choices?.[0];
751
+ if (!choice) continue;
752
+ if (chunk.usage) {
753
+ stopReasonDelta = {
754
+ type: "message_delta",
755
+ delta: { stop_reason: "end_turn", stop_sequence: null },
756
+ usage: {
757
+ input_tokens: (chunk.usage.prompt_tokens || 0) - (chunk.usage.prompt_tokens_details?.cached_tokens || 0),
758
+ output_tokens: chunk.usage.completion_tokens || 0,
759
+ cache_read_input_tokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0
760
+ }
761
+ };
762
+ }
763
+ if (choice.delta?.thinking) {
764
+ if (!isThinkingStarted) {
765
+ const thinkingBlockIndex = assignContentBlockIndex();
766
+ safeEnqueue(`event: content_block_start
767
+ data: ${JSON.stringify({
768
+ type: "content_block_start",
769
+ index: thinkingBlockIndex,
770
+ content_block: { type: "thinking", thinking: "" }
771
+ })}
772
+
773
+ `);
774
+ currentContentBlockIndex = thinkingBlockIndex;
775
+ isThinkingStarted = true;
776
+ }
777
+ if (choice.delta.thinking.signature) {
778
+ safeEnqueue(`event: content_block_delta
779
+ data: ${JSON.stringify({
780
+ type: "content_block_delta",
781
+ index: currentContentBlockIndex,
782
+ delta: { type: "signature_delta", signature: choice.delta.thinking.signature }
783
+ })}
784
+
785
+ `);
786
+ safeEnqueue(`event: content_block_stop
787
+ data: ${JSON.stringify({
788
+ type: "content_block_stop",
789
+ index: currentContentBlockIndex
790
+ })}
791
+
792
+ `);
793
+ currentContentBlockIndex = -1;
794
+ } else if (choice.delta.thinking.content) {
795
+ safeEnqueue(`event: content_block_delta
796
+ data: ${JSON.stringify({
797
+ type: "content_block_delta",
798
+ index: currentContentBlockIndex,
799
+ delta: { type: "thinking_delta", thinking: choice.delta.thinking.content }
800
+ })}
801
+
802
+ `);
803
+ }
804
+ }
805
+ if (choice.delta?.content) {
806
+ if (!hasTextContentStarted) {
807
+ if (currentContentBlockIndex >= 0 && isThinkingStarted) {
808
+ safeEnqueue(`event: content_block_stop
809
+ data: ${JSON.stringify({
810
+ type: "content_block_stop",
811
+ index: currentContentBlockIndex
812
+ })}
813
+
814
+ `);
815
+ }
816
+ hasTextContentStarted = true;
817
+ const textBlockIndex = assignContentBlockIndex();
818
+ safeEnqueue(`event: content_block_start
819
+ data: ${JSON.stringify({
820
+ type: "content_block_start",
821
+ index: textBlockIndex,
822
+ content_block: { type: "text", text: "" }
823
+ })}
824
+
825
+ `);
826
+ currentContentBlockIndex = textBlockIndex;
827
+ }
828
+ safeEnqueue(`event: content_block_delta
829
+ data: ${JSON.stringify({
830
+ type: "content_block_delta",
831
+ index: currentContentBlockIndex,
832
+ delta: { type: "text_delta", text: choice.delta.content }
833
+ })}
834
+
835
+ `);
836
+ }
837
+ if (choice.delta?.tool_calls) {
838
+ for (const toolCall of choice.delta.tool_calls) {
839
+ const toolCallIndex = toolCall.index ?? 0;
840
+ if (!toolCallIndexToContentBlockIndex.has(toolCallIndex)) {
841
+ if (currentContentBlockIndex >= 0) {
842
+ safeEnqueue(`event: content_block_stop
843
+ data: ${JSON.stringify({
844
+ type: "content_block_stop",
845
+ index: currentContentBlockIndex
846
+ })}
847
+
848
+ `);
849
+ hasTextContentStarted = false;
850
+ }
851
+ const newBlockIndex = assignContentBlockIndex();
852
+ toolCallIndexToContentBlockIndex.set(toolCallIndex, newBlockIndex);
853
+ safeEnqueue(`event: content_block_start
854
+ data: ${JSON.stringify({
855
+ type: "content_block_start",
856
+ index: newBlockIndex,
857
+ content_block: {
858
+ type: "tool_use",
859
+ id: toolCall.id || `call_${Date.now()}_${toolCallIndex}`,
860
+ name: toolCall.function?.name || `tool_${toolCallIndex}`,
861
+ input: {}
862
+ }
863
+ })}
864
+
865
+ `);
866
+ currentContentBlockIndex = newBlockIndex;
867
+ }
868
+ if (toolCall.function?.arguments) {
869
+ const blockIndex = toolCallIndexToContentBlockIndex.get(toolCallIndex);
870
+ if (blockIndex !== void 0) {
871
+ safeEnqueue(`event: content_block_delta
872
+ data: ${JSON.stringify({
873
+ type: "content_block_delta",
874
+ index: blockIndex,
875
+ delta: { type: "input_json_delta", partial_json: toolCall.function.arguments }
876
+ })}
877
+
878
+ `);
879
+ }
880
+ }
881
+ }
882
+ }
883
+ if (choice.finish_reason) {
884
+ const stopReasonMapping = {
885
+ stop: "end_turn",
886
+ length: "max_tokens",
887
+ tool_calls: "tool_use",
888
+ content_filter: "stop_sequence"
889
+ };
890
+ stopReasonDelta = {
891
+ type: "message_delta",
892
+ delta: {
893
+ stop_reason: stopReasonMapping[choice.finish_reason] || "end_turn",
894
+ stop_sequence: null
895
+ },
896
+ usage: {
897
+ input_tokens: (chunk.usage?.prompt_tokens || 0) - (chunk.usage?.prompt_tokens_details?.cached_tokens || 0),
898
+ output_tokens: chunk.usage?.completion_tokens || 0,
899
+ cache_read_input_tokens: chunk.usage?.prompt_tokens_details?.cached_tokens || 0
900
+ }
901
+ };
902
+ }
903
+ } catch (e) {
904
+ logger?.error("Error parsing stream chunk:", e);
905
+ }
906
+ }
907
+ }
908
+ } catch (e) {
909
+ if (!isClosed) {
910
+ controller.error(e);
911
+ }
912
+ } finally {
913
+ safeClose();
914
+ reader.releaseLock();
915
+ }
916
+ }
917
+ });
918
+ }
919
+
920
+ // src/transformer/transformers/AnthropicTransformer.ts
921
+ var AnthropicTransformer = class {
922
+ static TransformerName = "anthropic";
923
+ name = "anthropic";
924
+ logger;
925
+ endPoint = "/v1/messages";
926
+ useBearer;
927
+ constructor(options) {
928
+ this.useBearer = options?.UseBearer ?? false;
929
+ }
930
+ /**
931
+ * Handle authentication - Anthropic uses x-api-key header
932
+ */
933
+ async auth(request, provider, _context) {
934
+ const headers = {};
935
+ if (this.useBearer) {
936
+ headers["authorization"] = `Bearer ${provider.apiKey}`;
937
+ headers["x-api-key"] = void 0;
938
+ } else {
939
+ headers["x-api-key"] = provider.apiKey;
940
+ headers["authorization"] = void 0;
941
+ }
942
+ return {
943
+ body: request,
944
+ config: { headers }
945
+ };
946
+ }
947
+ /**
948
+ * Transform Anthropic request to unified format.
949
+ */
950
+ async transformRequestOut(request, _context) {
951
+ return transformAnthropicRequestToUnified(request);
952
+ }
953
+ /**
954
+ * Transform OpenAI/unified response back to Anthropic format
955
+ * (auto-detects stream vs JSON via Content-Type).
956
+ */
957
+ async transformResponseIn(response, context) {
958
+ const contentType = response.headers.get("Content-Type") ?? "";
959
+ if (contentType.includes("text/event-stream")) {
960
+ if (!response.body) {
961
+ throw new Error("Stream response body is null");
962
+ }
963
+ const convertedStream = convertOpenAIStreamToAnthropic(response.body, context, this.logger);
964
+ return new Response(convertedStream, {
965
+ headers: {
966
+ "Content-Type": "text/event-stream",
967
+ "Cache-Control": "no-cache",
968
+ Connection: "keep-alive"
969
+ }
970
+ });
971
+ } else {
972
+ const data = await response.json();
973
+ const anthropicResponse = convertOpenAIResponseToAnthropic(data);
974
+ return new Response(JSON.stringify(anthropicResponse), {
975
+ headers: { "Content-Type": "application/json" }
976
+ });
977
+ }
978
+ }
979
+ /**
980
+ * Transform unified request to Anthropic Messages API format.
981
+ * This is the reverse of transformRequestOut — converts OpenAI/unified format
982
+ * to Anthropic's expected request body structure.
983
+ */
984
+ async transformRequestIn(request, _provider, _context) {
985
+ return buildAnthropicRequestBody(request);
986
+ }
987
+ /**
988
+ * Transform Anthropic response to OpenAI/unified format
989
+ * (auto-detects stream vs JSON via Content-Type).
990
+ */
991
+ async transformResponseOut(response, _context) {
992
+ const contentType = response.headers.get("Content-Type") ?? "";
993
+ if (contentType.includes("text/event-stream")) {
994
+ if (!response.body) {
995
+ throw new Error("Stream response body is null");
996
+ }
997
+ const convertedStream = convertAnthropicStreamToOpenAI(response.body, this.logger);
998
+ return new Response(convertedStream, {
999
+ headers: {
1000
+ "Content-Type": "text/event-stream",
1001
+ "Cache-Control": "no-cache",
1002
+ Connection: "keep-alive"
1003
+ }
1004
+ });
1005
+ } else {
1006
+ const data = await response.json();
1007
+ const openaiResponse = convertAnthropicResponseToOpenAI(data);
1008
+ return new Response(JSON.stringify(openaiResponse), {
1009
+ headers: { "Content-Type": "application/json" }
1010
+ });
1011
+ }
1012
+ }
1013
+ };
1014
+ // Annotate the CommonJS export names for ESM import in node:
1015
+ 0 && (module.exports = {
1016
+ AnthropicTransformer
1017
+ });