@maplezzk/llm-proxy 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 (153) hide show
  1. package/README.md +85 -0
  2. package/bin/llm-proxy.js +17 -0
  3. package/dist/adapter/handlers.d.ts +5 -0
  4. package/dist/adapter/handlers.d.ts.map +1 -0
  5. package/dist/adapter/handlers.js +61 -0
  6. package/dist/adapter/handlers.js.map +1 -0
  7. package/dist/adapter/router.d.ts +12 -0
  8. package/dist/adapter/router.d.ts.map +1 -0
  9. package/dist/adapter/router.js +40 -0
  10. package/dist/adapter/router.js.map +1 -0
  11. package/dist/api/admin/app.d.ts +2 -0
  12. package/dist/api/admin/app.d.ts.map +1 -0
  13. package/dist/api/admin/app.js +35 -0
  14. package/dist/api/admin/app.js.map +1 -0
  15. package/dist/api/admin/components/adapters.d.ts +33 -0
  16. package/dist/api/admin/components/adapters.d.ts.map +1 -0
  17. package/dist/api/admin/components/adapters.js +144 -0
  18. package/dist/api/admin/components/adapters.js.map +1 -0
  19. package/dist/api/admin/components/capture.d.ts +23 -0
  20. package/dist/api/admin/components/capture.d.ts.map +1 -0
  21. package/dist/api/admin/components/capture.js +198 -0
  22. package/dist/api/admin/components/capture.js.map +1 -0
  23. package/dist/api/admin/components/dashboard.d.ts +14 -0
  24. package/dist/api/admin/components/dashboard.d.ts.map +1 -0
  25. package/dist/api/admin/components/dashboard.js +48 -0
  26. package/dist/api/admin/components/dashboard.js.map +1 -0
  27. package/dist/api/admin/components/logs.d.ts +24 -0
  28. package/dist/api/admin/components/logs.d.ts.map +1 -0
  29. package/dist/api/admin/components/logs.js +89 -0
  30. package/dist/api/admin/components/logs.js.map +1 -0
  31. package/dist/api/admin/components/providers.d.ts +33 -0
  32. package/dist/api/admin/components/providers.d.ts.map +1 -0
  33. package/dist/api/admin/components/providers.js +165 -0
  34. package/dist/api/admin/components/providers.js.map +1 -0
  35. package/dist/api/admin/components/proxy-key.d.ts +10 -0
  36. package/dist/api/admin/components/proxy-key.d.ts.map +1 -0
  37. package/dist/api/admin/components/proxy-key.js +34 -0
  38. package/dist/api/admin/components/proxy-key.js.map +1 -0
  39. package/dist/api/admin/components/test-panel.d.ts +14 -0
  40. package/dist/api/admin/components/test-panel.d.ts.map +1 -0
  41. package/dist/api/admin/components/test-panel.js +58 -0
  42. package/dist/api/admin/components/test-panel.js.map +1 -0
  43. package/dist/api/admin/store.d.ts +2 -0
  44. package/dist/api/admin/store.d.ts.map +1 -0
  45. package/dist/api/admin/store.js +86 -0
  46. package/dist/api/admin/store.js.map +1 -0
  47. package/dist/api/admin/types.d.ts +41 -0
  48. package/dist/api/admin/types.d.ts.map +1 -0
  49. package/dist/api/admin/types.js +2 -0
  50. package/dist/api/admin/types.js.map +1 -0
  51. package/dist/api/admin-app.js +5 -0
  52. package/dist/api/admin-ui.html +799 -0
  53. package/dist/api/handlers/adapter-crud.d.ts +7 -0
  54. package/dist/api/handlers/adapter-crud.d.ts.map +1 -0
  55. package/dist/api/handlers/adapter-crud.js +118 -0
  56. package/dist/api/handlers/adapter-crud.js.map +1 -0
  57. package/dist/api/handlers/base.d.ts +15 -0
  58. package/dist/api/handlers/base.d.ts.map +1 -0
  59. package/dist/api/handlers/base.js +103 -0
  60. package/dist/api/handlers/base.js.map +1 -0
  61. package/dist/api/handlers/index.d.ts +7 -0
  62. package/dist/api/handlers/index.d.ts.map +1 -0
  63. package/dist/api/handlers/index.js +9 -0
  64. package/dist/api/handlers/index.js.map +1 -0
  65. package/dist/api/handlers/model-handlers.d.ts +7 -0
  66. package/dist/api/handlers/model-handlers.d.ts.map +1 -0
  67. package/dist/api/handlers/model-handlers.js +239 -0
  68. package/dist/api/handlers/model-handlers.js.map +1 -0
  69. package/dist/api/handlers/provider-crud.d.ts +6 -0
  70. package/dist/api/handlers/provider-crud.d.ts.map +1 -0
  71. package/dist/api/handlers/provider-crud.js +106 -0
  72. package/dist/api/handlers/provider-crud.js.map +1 -0
  73. package/dist/api/handlers.d.ts +16 -0
  74. package/dist/api/handlers.d.ts.map +1 -0
  75. package/dist/api/handlers.js +45 -0
  76. package/dist/api/handlers.js.map +1 -0
  77. package/dist/api/server.d.ts +26 -0
  78. package/dist/api/server.d.ts.map +1 -0
  79. package/dist/api/server.js +114 -0
  80. package/dist/api/server.js.map +1 -0
  81. package/dist/cli/commands.d.ts +15 -0
  82. package/dist/cli/commands.d.ts.map +1 -0
  83. package/dist/cli/commands.js +165 -0
  84. package/dist/cli/commands.js.map +1 -0
  85. package/dist/config/parser.d.ts +4 -0
  86. package/dist/config/parser.d.ts.map +1 -0
  87. package/dist/config/parser.js +75 -0
  88. package/dist/config/parser.js.map +1 -0
  89. package/dist/config/store.d.ts +16 -0
  90. package/dist/config/store.d.ts.map +1 -0
  91. package/dist/config/store.js +59 -0
  92. package/dist/config/store.js.map +1 -0
  93. package/dist/config/types.d.ts +72 -0
  94. package/dist/config/types.d.ts.map +1 -0
  95. package/dist/config/types.js +2 -0
  96. package/dist/config/types.js.map +1 -0
  97. package/dist/config/validator.d.ts +3 -0
  98. package/dist/config/validator.d.ts.map +1 -0
  99. package/dist/config/validator.js +109 -0
  100. package/dist/config/validator.js.map +1 -0
  101. package/dist/index.d.ts +3 -0
  102. package/dist/index.d.ts.map +1 -0
  103. package/dist/index.js +68 -0
  104. package/dist/index.js.map +1 -0
  105. package/dist/lib/http-utils.d.ts +4 -0
  106. package/dist/lib/http-utils.d.ts.map +1 -0
  107. package/dist/lib/http-utils.js +21 -0
  108. package/dist/lib/http-utils.js.map +1 -0
  109. package/dist/log/logger.d.ts +31 -0
  110. package/dist/log/logger.d.ts.map +1 -0
  111. package/dist/log/logger.js +170 -0
  112. package/dist/log/logger.js.map +1 -0
  113. package/dist/proxy/capture.d.ts +28 -0
  114. package/dist/proxy/capture.d.ts.map +1 -0
  115. package/dist/proxy/capture.js +49 -0
  116. package/dist/proxy/capture.js.map +1 -0
  117. package/dist/proxy/handlers.d.ts +6 -0
  118. package/dist/proxy/handlers.d.ts.map +1 -0
  119. package/dist/proxy/handlers.js +30 -0
  120. package/dist/proxy/handlers.js.map +1 -0
  121. package/dist/proxy/pipeline.d.ts +32 -0
  122. package/dist/proxy/pipeline.d.ts.map +1 -0
  123. package/dist/proxy/pipeline.js +120 -0
  124. package/dist/proxy/pipeline.js.map +1 -0
  125. package/dist/proxy/provider.d.ts +21 -0
  126. package/dist/proxy/provider.d.ts.map +1 -0
  127. package/dist/proxy/provider.js +231 -0
  128. package/dist/proxy/provider.js.map +1 -0
  129. package/dist/proxy/router.d.ts +4 -0
  130. package/dist/proxy/router.d.ts.map +1 -0
  131. package/dist/proxy/router.js +20 -0
  132. package/dist/proxy/router.js.map +1 -0
  133. package/dist/proxy/stream-converter.d.ts +16 -0
  134. package/dist/proxy/stream-converter.d.ts.map +1 -0
  135. package/dist/proxy/stream-converter.js +1050 -0
  136. package/dist/proxy/stream-converter.js.map +1 -0
  137. package/dist/proxy/translation.d.ts +23 -0
  138. package/dist/proxy/translation.d.ts.map +1 -0
  139. package/dist/proxy/translation.js +913 -0
  140. package/dist/proxy/translation.js.map +1 -0
  141. package/dist/proxy/types.d.ts +8 -0
  142. package/dist/proxy/types.d.ts.map +1 -0
  143. package/dist/proxy/types.js +2 -0
  144. package/dist/proxy/types.js.map +1 -0
  145. package/dist/status/token-tracker.d.ts +24 -0
  146. package/dist/status/token-tracker.d.ts.map +1 -0
  147. package/dist/status/token-tracker.js +65 -0
  148. package/dist/status/token-tracker.js.map +1 -0
  149. package/dist/status/tracker.d.ts +14 -0
  150. package/dist/status/tracker.d.ts.map +1 -0
  151. package/dist/status/tracker.js +44 -0
  152. package/dist/status/tracker.js.map +1 -0
  153. package/package.json +55 -0
@@ -0,0 +1,913 @@
1
+ // --- Helpers ---
2
+ function truncateBody(obj, maxLen = 500) {
3
+ const json = JSON.stringify(obj);
4
+ if (json.length <= maxLen)
5
+ return obj;
6
+ // Truncate messages array content
7
+ const truncated = { ...obj };
8
+ if (Array.isArray(truncated.messages)) {
9
+ const msgs = truncated.messages;
10
+ if (msgs.length > 0) {
11
+ const last = msgs[msgs.length - 1];
12
+ const pc = typeof last.content === 'string' ? last.content : JSON.stringify(last.content);
13
+ truncated._messagesTruncated = `${msgs.length} messages, last: ${pc.slice(0, 100)}...`;
14
+ truncated.messages = undefined;
15
+ }
16
+ }
17
+ else {
18
+ truncated._truncated = `${json.slice(0, maxLen)}...`;
19
+ }
20
+ return truncated;
21
+ }
22
+ // --- Tool format conversion ---
23
+ function convertToolsToAnthropic(tools) {
24
+ if (!Array.isArray(tools))
25
+ return undefined;
26
+ return tools
27
+ .filter((t) => {
28
+ // Filter out non-function tools (web_search, code_interpreter, etc.) -
29
+ // Anthropic API only supports standard tools
30
+ const item = t;
31
+ return item.type === 'function' || (item.name && item.input_schema);
32
+ })
33
+ .map((t) => {
34
+ const item = t;
35
+ // OpenAI Chat format: { type: "function", function: { name, description, parameters } }
36
+ if (item.type === 'function' && item.function) {
37
+ const fn = item.function;
38
+ return {
39
+ name: fn.name ?? '',
40
+ description: fn.description || undefined,
41
+ input_schema: fn.parameters ?? {},
42
+ };
43
+ }
44
+ // OpenAI Responses flat format: { type: "function", name, description, parameters } (no "function" wrapper)
45
+ if (item.type === 'function' && item.name) {
46
+ return {
47
+ name: item.name ?? '',
48
+ description: item.description || undefined,
49
+ input_schema: item.parameters ?? {},
50
+ };
51
+ }
52
+ // Already Anthropic format or unknown
53
+ return item;
54
+ });
55
+ }
56
+ function convertToolsToOpenAI(tools) {
57
+ if (!Array.isArray(tools))
58
+ return undefined;
59
+ return tools
60
+ .filter((t) => {
61
+ // Filter out non-function tools (web_search, code_interpreter, etc.) -
62
+ // Chat Completions API only supports type: "function"
63
+ const item = t;
64
+ return item.type === 'function' || (item.name && item.input_schema);
65
+ })
66
+ .map((t) => {
67
+ const item = t;
68
+ // Anthropic format: { name, description, input_schema }
69
+ if (item.name && item.input_schema) {
70
+ return {
71
+ type: 'function',
72
+ function: {
73
+ name: item.name,
74
+ description: item.description || undefined,
75
+ parameters: item.input_schema,
76
+ },
77
+ };
78
+ }
79
+ // OpenAI Responses flat format: { type: "function", name, parameters } → wrap in "function" for Chat Completions
80
+ if (item.type === 'function' && item.name && !item.function) {
81
+ return {
82
+ type: 'function',
83
+ function: {
84
+ name: item.name ?? '',
85
+ description: item.description || undefined,
86
+ parameters: item.parameters ?? {},
87
+ },
88
+ };
89
+ }
90
+ return item;
91
+ });
92
+ }
93
+ function convertToolChoiceToAnthropic(toolChoice) {
94
+ if (toolChoice === undefined || toolChoice === null)
95
+ return undefined;
96
+ if (typeof toolChoice === 'string') {
97
+ // OpenAI "required" → Anthropic "any"
98
+ if (toolChoice === 'required')
99
+ return 'any';
100
+ return toolChoice;
101
+ }
102
+ // OpenAI: { type: "function", function: { name } } → Anthropic: { type: "tool", name }
103
+ const tc = toolChoice;
104
+ if (tc.type === 'function') {
105
+ const fn = tc.function;
106
+ return { type: 'tool', name: fn?.name ?? '' };
107
+ }
108
+ return toolChoice;
109
+ }
110
+ function convertToolChoiceToOpenAI(toolChoice) {
111
+ if (toolChoice === undefined || toolChoice === null)
112
+ return undefined;
113
+ if (typeof toolChoice === 'string') {
114
+ // Anthropic "any" → OpenAI "required"
115
+ if (toolChoice === 'any')
116
+ return 'required';
117
+ return toolChoice;
118
+ }
119
+ // Anthropic: { type: "tool", name } → OpenAI: { type: "function", function: { name } }
120
+ const tc = toolChoice;
121
+ if (tc.type === 'tool') {
122
+ return { type: 'function', function: { name: tc.name } };
123
+ }
124
+ return toolChoice;
125
+ }
126
+ // --- Responses input ↔ Chat messages format conversion ---
127
+ /**
128
+ * Convert OpenAI Responses input items to Chat Completions message format.
129
+ * Responses input: {type:"message",role:"user",content:"..."} / {type:"function_call",...} / {type:"function_call_output",...}
130
+ * Chat messages: {role:"user",content:"..."} / {role:"assistant",tool_calls:[...]} / {role:"tool",tool_call_id,content}
131
+ */
132
+ function convertResponsesInputToMessages(input) {
133
+ const messages = [];
134
+ for (const item of input) {
135
+ const it = item;
136
+ if (it.type === 'message') {
137
+ // { type: "message", role: "user"|"assistant"|"system"|"developer", content: string | array }
138
+ const content = it.content;
139
+ let normalizedContent = content;
140
+ // Convert Responses content blocks to Chat/Anthropic-compatible format
141
+ if (Array.isArray(content)) {
142
+ const blocks = content.map((block) => {
143
+ // input_text → text (Anthropic-style content block)
144
+ if (block.type === 'input_text' || block.type === 'output_text') {
145
+ return { type: 'text', text: block.text };
146
+ }
147
+ // reasoning → thinking (Anthropic-style thinking block)
148
+ if (block.type === 'reasoning') {
149
+ // reasoning can have summary (array of summary_text) or reasoning_text (plain string)
150
+ const summary = block.summary;
151
+ const reasoningText = summary
152
+ ? summary.map((s) => s.text ?? '').join('')
153
+ : block.reasoning_text ?? '';
154
+ return { type: 'thinking', thinking: reasoningText, signature: '' };
155
+ }
156
+ // input_image → image (Anthropic-style)
157
+ if (block.type === 'input_image') {
158
+ // Responses input_image uses {type:"input_image", image_url:"..."} or {type:"input_image", detail, file_id}
159
+ // Convert to Anthropic image format
160
+ const imageUrl = block.image_url;
161
+ if (imageUrl) {
162
+ return { type: 'image', source: { type: 'url', url: imageUrl } };
163
+ }
164
+ // If it uses file_id, skip (Anthropic doesn't support file_id directly)
165
+ return { type: 'text', text: '[image]' };
166
+ }
167
+ // input_file → text placeholder (no direct Chat/Anthropic equivalent)
168
+ if (block.type === 'input_file') {
169
+ return { type: 'text', text: '[file]' };
170
+ }
171
+ return block;
172
+ });
173
+ // If all blocks are text blocks, collapse to a single string
174
+ if (blocks.every((b) => b.type === 'text')) {
175
+ normalizedContent = blocks.map((b) => b.text).join('');
176
+ }
177
+ else {
178
+ normalizedContent = blocks;
179
+ }
180
+ }
181
+ messages.push({ role: it.role, content: normalizedContent });
182
+ }
183
+ else if (it.type === 'function_call') {
184
+ // { type: "function_call", call_id, name, arguments }
185
+ messages.push({
186
+ role: 'assistant',
187
+ content: null,
188
+ tool_calls: [{
189
+ id: it.call_id ?? it.id,
190
+ type: 'function',
191
+ function: { name: it.name ?? '', arguments: it.arguments ?? '' },
192
+ }],
193
+ });
194
+ }
195
+ else if (it.type === 'function_call_output') {
196
+ // { type: "function_call_output", call_id, output }
197
+ messages.push({
198
+ role: 'tool',
199
+ tool_call_id: it.call_id,
200
+ content: it.output ?? '',
201
+ });
202
+ }
203
+ else if (it.type === 'item_reference') {
204
+ // Skip item references (they reference previous response items, not applicable to stateless chat)
205
+ }
206
+ else {
207
+ // Unknown item type, pass through as-is
208
+ messages.push(it);
209
+ }
210
+ }
211
+ return messages;
212
+ }
213
+ /**
214
+ * Convert Chat Completions messages to OpenAI Responses input format.
215
+ */
216
+ function convertMessagesToResponsesInput(messages) {
217
+ const input = [];
218
+ for (const msg of messages) {
219
+ const m = msg;
220
+ if (m.role === 'tool') {
221
+ input.push({
222
+ type: 'function_call_output',
223
+ call_id: m.tool_call_id,
224
+ output: typeof m.content === 'string' ? m.content : JSON.stringify(m.content),
225
+ });
226
+ }
227
+ else if (m.role === 'assistant') {
228
+ // Add message item for text content (if any)
229
+ const text = typeof m.content === 'string' ? m.content : '';
230
+ if (text) {
231
+ input.push({ type: 'message', role: 'assistant', content: text });
232
+ }
233
+ // Add function_call items for tool_calls
234
+ const toolCalls = m.tool_calls;
235
+ if (toolCalls) {
236
+ for (const tc of toolCalls) {
237
+ const fn = tc.function;
238
+ input.push({
239
+ type: 'function_call',
240
+ call_id: tc.id,
241
+ name: fn?.name ?? '',
242
+ arguments: fn?.arguments ?? '',
243
+ });
244
+ }
245
+ }
246
+ }
247
+ else if (m.role === 'system') {
248
+ // system is handled via instructions field, but if it appears in messages we include it
249
+ input.push({ type: 'message', role: 'system', content: m.content });
250
+ }
251
+ else {
252
+ // user, developer, etc.
253
+ input.push({ type: 'message', role: m.role ?? 'user', content: m.content });
254
+ }
255
+ }
256
+ return input;
257
+ }
258
+ // --- System message extraction ---
259
+ function extractSystemFromOpenAI(messages) {
260
+ const first = messages[0];
261
+ if (first?.role === 'system') {
262
+ return {
263
+ system: first.content,
264
+ remainingMessages: messages.slice(1),
265
+ };
266
+ }
267
+ return { remainingMessages: messages };
268
+ }
269
+ function extractFullOpenAI(body) {
270
+ const messages = body.messages ?? [];
271
+ const { system, remainingMessages } = extractSystemFromOpenAI(messages);
272
+ return {
273
+ model: body.model,
274
+ messages: remainingMessages,
275
+ system,
276
+ temperature: body.temperature,
277
+ max_tokens: body.max_tokens,
278
+ stream: body.stream,
279
+ top_p: body.top_p,
280
+ stop: body.stop,
281
+ tools: body.tools,
282
+ tool_choice: body.tool_choice,
283
+ };
284
+ }
285
+ function extractFullAnthropic(body) {
286
+ return {
287
+ model: body.model,
288
+ messages: body.messages ?? [],
289
+ system: body.system,
290
+ temperature: body.temperature,
291
+ max_tokens: body.max_tokens,
292
+ stream: body.stream,
293
+ top_p: body.top_p,
294
+ stop: body.stop_sequences,
295
+ tools: body.tools,
296
+ tool_choice: body.tool_choice,
297
+ };
298
+ }
299
+ function convertMessagesToAnthropic(messages) {
300
+ return messages.map((msg) => {
301
+ const m = msg;
302
+ // tool role → Anthropic user message with tool_result content block
303
+ if (m.role === 'tool') {
304
+ return {
305
+ role: 'user',
306
+ content: [{
307
+ type: 'tool_result',
308
+ tool_use_id: m.tool_call_id,
309
+ content: typeof m.content === 'string' ? m.content : JSON.stringify(m.content),
310
+ }],
311
+ };
312
+ }
313
+ // developer role → user (Anthropic doesn't support "developer" role)
314
+ if (m.role === 'developer') {
315
+ return { role: 'user', content: m.content };
316
+ }
317
+ if (m.role !== 'assistant')
318
+ return m;
319
+ const reasoning = m.reasoning_content;
320
+ const text = m.content;
321
+ // If no reasoning, keep as-is (Anthropic accepts string content for assistant)
322
+ if (!reasoning)
323
+ return m;
324
+ // Convert to content block array with thinking + text
325
+ const content = [];
326
+ if (reasoning)
327
+ content.push({ type: 'thinking', thinking: reasoning, signature: m.reasoning_signature ?? '' });
328
+ if (text)
329
+ content.push({ type: 'text', text });
330
+ const converted = { role: 'assistant', content };
331
+ if (m.tool_calls)
332
+ converted.tool_calls = m.tool_calls;
333
+ return converted;
334
+ });
335
+ }
336
+ function buildAnthropicFromOpenAI(params) {
337
+ const body = {
338
+ model: params.model,
339
+ max_tokens: params.max_tokens ?? 4096,
340
+ messages: convertMessagesToAnthropic(params.messages),
341
+ };
342
+ if (params.system)
343
+ body.system = params.system;
344
+ if (params.temperature !== undefined)
345
+ body.temperature = params.temperature;
346
+ if (params.stream)
347
+ body.stream = true;
348
+ if (params.top_p !== undefined)
349
+ body.top_p = params.top_p;
350
+ if (params.stop)
351
+ body.stop_sequences = params.stop;
352
+ if (params.tools)
353
+ body.tools = convertToolsToAnthropic(params.tools);
354
+ if (params.tool_choice !== undefined)
355
+ body.tool_choice = convertToolChoiceToAnthropic(params.tool_choice);
356
+ return body;
357
+ }
358
+ function convertMessagesToOpenAI(messages) {
359
+ const result = [];
360
+ for (const msg of messages) {
361
+ const m = msg;
362
+ if (m.role === 'user') {
363
+ const content = m.content;
364
+ // Check if this is a tool_result message (array with tool_result blocks)
365
+ if (Array.isArray(content)) {
366
+ const toolResults = content.filter((b) => b.type === 'tool_result');
367
+ const otherBlocks = content.filter((b) => b.type !== 'tool_result');
368
+ // Emit tool messages for each tool_result
369
+ for (const tr of toolResults) {
370
+ result.push({
371
+ role: 'tool',
372
+ tool_call_id: tr.tool_use_id,
373
+ content: typeof tr.content === 'string' ? tr.content : JSON.stringify(tr.content),
374
+ });
375
+ }
376
+ // Emit remaining user content if any
377
+ if (otherBlocks.length > 0) {
378
+ const text = otherBlocks.map((b) => b.text ?? '').join('');
379
+ result.push({ role: 'user', content: text });
380
+ }
381
+ continue;
382
+ }
383
+ }
384
+ // developer role → system (older Chat Completions APIs don't support "developer")
385
+ if (m.role === 'developer') {
386
+ result.push({ role: 'system', content: m.content });
387
+ continue;
388
+ }
389
+ // Handle assistant messages with content blocks (thinking + text + tool_use from Anthropic)
390
+ if (m.role === 'assistant' && Array.isArray(m.content)) {
391
+ const blocks = m.content;
392
+ let textContent = '';
393
+ let reasoningContent = '';
394
+ let thinkingSignature = '';
395
+ for (const block of blocks) {
396
+ if (block.type === 'text') {
397
+ textContent += block.text ?? '';
398
+ }
399
+ else if (block.type === 'thinking') {
400
+ reasoningContent += block.thinking ?? '';
401
+ if (block.signature)
402
+ thinkingSignature += block.signature;
403
+ }
404
+ }
405
+ const converted = { role: 'assistant', content: textContent };
406
+ if (reasoningContent) {
407
+ converted.reasoning_content = reasoningContent;
408
+ // Always include signature if reasoning_content is present (some APIs require it paired)
409
+ converted.reasoning_signature = thinkingSignature || '';
410
+ }
411
+ // Convert Anthropic tool_use blocks → OpenAI tool_calls
412
+ const toolUses = blocks.filter((b) => b.type === 'tool_use');
413
+ if (toolUses.length > 0) {
414
+ converted.tool_calls = toolUses.map((tu) => ({
415
+ id: tu.id,
416
+ type: 'function',
417
+ function: {
418
+ name: tu.name ?? '',
419
+ arguments: JSON.stringify(tu.input ?? {}),
420
+ },
421
+ }));
422
+ }
423
+ if (m.tool_calls)
424
+ converted.tool_calls = m.tool_calls;
425
+ result.push(converted);
426
+ continue;
427
+ }
428
+ result.push(m);
429
+ }
430
+ return result;
431
+ }
432
+ function buildOpenAIFromAnthropic(params) {
433
+ const convertedMessages = convertMessagesToOpenAI(params.messages);
434
+ const body = {
435
+ model: params.model,
436
+ messages: convertedMessages,
437
+ };
438
+ if (params.system) {
439
+ body.messages = [{ role: 'system', content: params.system }, ...convertedMessages];
440
+ }
441
+ if (params.max_tokens !== undefined)
442
+ body.max_tokens = params.max_tokens;
443
+ if (params.temperature !== undefined)
444
+ body.temperature = params.temperature;
445
+ if (params.stream)
446
+ body.stream = true;
447
+ if (params.top_p !== undefined)
448
+ body.top_p = params.top_p;
449
+ if (params.stop)
450
+ body.stop = params.stop;
451
+ if (params.tools)
452
+ body.tools = convertToolsToOpenAI(params.tools);
453
+ if (params.tool_choice !== undefined)
454
+ body.tool_choice = convertToolChoiceToOpenAI(params.tool_choice);
455
+ return body;
456
+ }
457
+ // --- OpenAI Responses API extraction ---
458
+ function extractFullOpenAIResponses(body) {
459
+ const rawInput = body.input;
460
+ let messages;
461
+ if (typeof rawInput === 'string') {
462
+ messages = [{ role: 'user', content: rawInput }];
463
+ }
464
+ else if (Array.isArray(rawInput)) {
465
+ messages = convertResponsesInputToMessages(rawInput);
466
+ }
467
+ else {
468
+ messages = [];
469
+ }
470
+ return {
471
+ model: body.model,
472
+ messages,
473
+ system: body.instructions,
474
+ temperature: body.temperature,
475
+ max_tokens: (body.max_output_tokens ?? body.max_tokens),
476
+ stream: body.stream,
477
+ top_p: body.top_p,
478
+ stop: body.stop,
479
+ tools: body.tools,
480
+ tool_choice: body.tool_choice,
481
+ };
482
+ }
483
+ // --- Builders for OpenAI Responses format ---
484
+ function buildAnthropicFromOpenAIResponses(params) {
485
+ const body = {
486
+ model: params.model,
487
+ max_tokens: params.max_tokens ?? 4096,
488
+ messages: convertMessagesToAnthropic(params.messages),
489
+ };
490
+ if (params.system)
491
+ body.system = params.system;
492
+ if (params.temperature !== undefined)
493
+ body.temperature = params.temperature;
494
+ if (params.stream)
495
+ body.stream = true;
496
+ if (params.top_p !== undefined)
497
+ body.top_p = params.top_p;
498
+ if (params.stop)
499
+ body.stop_sequences = params.stop;
500
+ if (params.tools)
501
+ body.tools = convertToolsToAnthropic(params.tools);
502
+ if (params.tool_choice !== undefined)
503
+ body.tool_choice = convertToolChoiceToAnthropic(params.tool_choice);
504
+ return body;
505
+ }
506
+ function buildOpenAIResponsesFromFullParams(params) {
507
+ const body = {
508
+ model: params.model,
509
+ input: convertMessagesToResponsesInput(params.messages),
510
+ };
511
+ if (params.system)
512
+ body.instructions = params.system;
513
+ if (params.temperature !== undefined)
514
+ body.temperature = params.temperature;
515
+ if (params.max_tokens !== undefined)
516
+ body.max_output_tokens = params.max_tokens;
517
+ if (params.stream)
518
+ body.stream = true;
519
+ if (params.top_p !== undefined)
520
+ body.top_p = params.top_p;
521
+ if (params.stop)
522
+ body.stop = params.stop;
523
+ if (params.tools)
524
+ body.tools = convertToolsToOpenAI(params.tools);
525
+ if (params.tool_choice !== undefined)
526
+ body.tool_choice = convertToolChoiceToOpenAI(params.tool_choice);
527
+ return body;
528
+ }
529
+ export async function transformInboundRequest(inboundType, route, body, logger) {
530
+ const sameProtocol = inboundType === route.providerType;
531
+ const upstreamEndpoint = route.providerType === 'anthropic'
532
+ ? 'messages'
533
+ : route.providerType === 'openai-responses'
534
+ ? 'responses'
535
+ : 'chat/completions';
536
+ const url = `${route.apiBase}/v1/${upstreamEndpoint}`;
537
+ const headers = { 'Content-Type': 'application/json' };
538
+ if (route.providerType === 'anthropic') {
539
+ headers['x-api-key'] = route.apiKey;
540
+ headers['anthropic-version'] = '2023-06-01';
541
+ }
542
+ else {
543
+ headers['Authorization'] = `Bearer ${route.apiKey}`;
544
+ }
545
+ if (sameProtocol) {
546
+ return { url, headers, body: { ...body, model: route.modelId }, crossProtocol: false };
547
+ }
548
+ // Cross-protocol: full translation
549
+ const params = inboundType === 'openai-responses'
550
+ ? extractFullOpenAIResponses(body)
551
+ : inboundType === 'openai'
552
+ ? extractFullOpenAI(body)
553
+ : extractFullAnthropic(body);
554
+ params.model = route.modelId;
555
+ let upstreamBody;
556
+ if (route.providerType === 'anthropic') {
557
+ upstreamBody = inboundType === 'openai-responses'
558
+ ? buildAnthropicFromOpenAIResponses(params)
559
+ : buildAnthropicFromOpenAI(params);
560
+ }
561
+ else if (route.providerType === 'openai-responses') {
562
+ upstreamBody = buildOpenAIResponsesFromFullParams(params);
563
+ }
564
+ else {
565
+ upstreamBody = buildOpenAIFromAnthropic(params);
566
+ }
567
+ logger?.log('request', `跨协议转换: ${inboundType} → ${route.providerType}`, {
568
+ originalModel: body.model,
569
+ targetModel: route.modelId,
570
+ originalBody: truncateBody(body),
571
+ convertedBody: truncateBody(upstreamBody),
572
+ }, 'debug');
573
+ return { url, headers, body: upstreamBody, crossProtocol: true };
574
+ }
575
+ // --- OpenAI Responses ↔ Anthropic response conversion ---
576
+ function mapResponsesStopReason(stop, hasToolCalls) {
577
+ if (hasToolCalls)
578
+ return 'tool_use';
579
+ const stopMap = { completed: 'end_turn', incomplete: 'max_tokens', max_output_tokens: 'max_tokens' };
580
+ return stopMap[stop] ?? 'end_turn';
581
+ }
582
+ export function convertOpenAIResponsesToAnthropic(responsesBody) {
583
+ const output = responsesBody.output;
584
+ const usage = responsesBody.usage;
585
+ const content = [];
586
+ let stopReason = 'end_turn';
587
+ if (output) {
588
+ for (const item of output) {
589
+ if (item.type === 'message' && item.role === 'assistant') {
590
+ const msgContent = item.content;
591
+ if (msgContent) {
592
+ for (const block of msgContent) {
593
+ if (block.type === 'output_text') {
594
+ content.push({ type: 'text', text: block.text ?? '' });
595
+ }
596
+ else if (block.type === 'reasoning') {
597
+ content.push({ type: 'thinking', thinking: block.summary ? block.summary.map((s) => s.text ?? '').join('') : (block.reasoning_text ?? ''), signature: '' });
598
+ }
599
+ else if (block.type === 'web_search_call') {
600
+ // web_search is Responses-specific, map to text note or skip
601
+ // For now, skip as Anthropic doesn't have direct equivalent
602
+ }
603
+ }
604
+ }
605
+ if (item.status)
606
+ stopReason = item.status;
607
+ }
608
+ else if (item.type === 'function_call') {
609
+ let input = {};
610
+ try {
611
+ input = typeof item.arguments === 'string' ? JSON.parse(item.arguments) : (item.arguments ?? {});
612
+ }
613
+ catch {
614
+ input = item.arguments;
615
+ }
616
+ content.push({
617
+ type: 'tool_use',
618
+ id: item.call_id ?? item.id,
619
+ name: item.name ?? '',
620
+ input,
621
+ });
622
+ stopReason = 'tool_use';
623
+ }
624
+ }
625
+ }
626
+ const hasToolCalls = content.some((b) => b.type === 'tool_use');
627
+ const anthropicStop = mapResponsesStopReason(stopReason, hasToolCalls);
628
+ return {
629
+ id: `msg_${Date.now()}`,
630
+ type: 'message',
631
+ role: 'assistant',
632
+ content,
633
+ model: responsesBody.model ?? '',
634
+ stop_reason: anthropicStop,
635
+ stop_sequence: null,
636
+ usage: {
637
+ input_tokens: usage?.input_tokens ?? 0,
638
+ output_tokens: usage?.output_tokens ?? 0,
639
+ },
640
+ };
641
+ }
642
+ export function convertAnthropicResponseToOpenAIResponses(anthropicBody) {
643
+ const content = anthropicBody.content;
644
+ const usage = anthropicBody.usage;
645
+ const stopReason = anthropicBody.stop_reason ?? 'end_turn';
646
+ const outputMessageContent = [];
647
+ const output = [];
648
+ if (content) {
649
+ for (const block of content) {
650
+ if (block.type === 'text') {
651
+ outputMessageContent.push({ type: 'output_text', text: block.text ?? '', annotations: [] });
652
+ }
653
+ else if (block.type === 'thinking') {
654
+ // Skip reasoning - Responses client doesn't track it
655
+ }
656
+ else if (block.type === 'tool_use') {
657
+ output.push({
658
+ type: 'function_call',
659
+ id: `fc_${Date.now().toString(36)}_${block.id ?? ''}`,
660
+ call_id: block.id,
661
+ name: block.name ?? '',
662
+ arguments: JSON.stringify(block.input ?? {}),
663
+ });
664
+ }
665
+ }
666
+ }
667
+ // Message output item goes first (before function_call items for correct ordering)
668
+ output.unshift({
669
+ type: 'message',
670
+ id: `msg_${Date.now().toString(36)}`,
671
+ status: stopReason === 'end_turn' ? 'completed' : stopReason === 'max_tokens' ? 'incomplete' : 'completed',
672
+ role: 'assistant',
673
+ content: outputMessageContent,
674
+ });
675
+ return {
676
+ id: `resp_${Date.now().toString(36)}`,
677
+ object: 'response',
678
+ created_at: Math.floor(Date.now() / 1000),
679
+ status: stopReason === 'end_turn' ? 'completed' : 'incomplete',
680
+ model: anthropicBody.model ?? '',
681
+ output,
682
+ usage: {
683
+ input_tokens: usage?.input_tokens ?? 0,
684
+ output_tokens: usage?.output_tokens ?? 0,
685
+ total_tokens: (usage?.input_tokens ?? 0) + (usage?.output_tokens ?? 0),
686
+ },
687
+ };
688
+ }
689
+ // --- Chat Completions ↔ Anthropic response conversion ---
690
+ export function convertOpenAIResponseToAnthropic(openaiBody) {
691
+ const choices = openaiBody.choices;
692
+ const choice = choices?.[0];
693
+ const message = choice?.message;
694
+ const usage = openaiBody.usage;
695
+ const content = [];
696
+ // reasoning_content → thinking block
697
+ const reasoning = message?.reasoning_content;
698
+ if (reasoning)
699
+ content.push({ type: 'thinking', thinking: reasoning, signature: message?.reasoning_signature ?? '' });
700
+ // Collect text content
701
+ const text = message?.content;
702
+ if (text)
703
+ content.push({ type: 'text', text });
704
+ // Collect tool calls
705
+ const toolCalls = message?.tool_calls;
706
+ if (toolCalls) {
707
+ for (const tc of toolCalls) {
708
+ const fn = tc.function;
709
+ let input = {};
710
+ try {
711
+ input = fn?.arguments ? JSON.parse(fn.arguments) : {};
712
+ }
713
+ catch {
714
+ input = {};
715
+ }
716
+ content.push({
717
+ type: 'tool_use',
718
+ id: tc.id,
719
+ name: fn?.name ?? '',
720
+ input,
721
+ });
722
+ }
723
+ }
724
+ const stopMap = { stop: 'end_turn', length: 'max_tokens', tool_calls: 'tool_use' };
725
+ const stopReason = choice?.finish_reason ?? 'end_turn';
726
+ return {
727
+ id: `msg_${Date.now()}`,
728
+ type: 'message',
729
+ role: 'assistant',
730
+ content,
731
+ model: openaiBody.model ?? '',
732
+ stop_reason: stopMap[stopReason] ?? stopReason,
733
+ stop_sequence: null,
734
+ usage: {
735
+ input_tokens: usage?.prompt_tokens ?? 0,
736
+ output_tokens: usage?.completion_tokens ?? 0,
737
+ },
738
+ };
739
+ }
740
+ export function convertAnthropicResponseToOpenAI(anthropicBody) {
741
+ const content = anthropicBody.content;
742
+ const usage = anthropicBody.usage;
743
+ let textContent = '';
744
+ let reasoningContent = '';
745
+ let thinkingSignature = '';
746
+ const toolCalls = [];
747
+ if (content) {
748
+ for (const block of content) {
749
+ if (block.type === 'thinking') {
750
+ reasoningContent += block.thinking ?? '';
751
+ if (block.signature)
752
+ thinkingSignature += block.signature;
753
+ }
754
+ else if (block.type === 'text') {
755
+ textContent += block.text ?? '';
756
+ }
757
+ else if (block.type === 'tool_use') {
758
+ toolCalls.push({
759
+ id: block.id,
760
+ type: 'function',
761
+ function: {
762
+ name: block.name,
763
+ arguments: JSON.stringify(block.input ?? {}),
764
+ },
765
+ });
766
+ }
767
+ }
768
+ }
769
+ const stopMap = { end_turn: 'stop', max_tokens: 'length', tool_use: 'tool_calls' };
770
+ const stopReason = anthropicBody.stop_reason ?? 'stop';
771
+ const message = { role: 'assistant', content: textContent };
772
+ if (reasoningContent) {
773
+ message.reasoning_content = reasoningContent;
774
+ if (thinkingSignature)
775
+ message.reasoning_signature = thinkingSignature;
776
+ }
777
+ if (toolCalls.length > 0)
778
+ message.tool_calls = toolCalls;
779
+ return {
780
+ id: `chatcmpl-${Date.now().toString(36)}`,
781
+ object: 'chat.completion',
782
+ created: Math.floor(Date.now() / 1000),
783
+ model: anthropicBody.model ?? '',
784
+ choices: [{
785
+ index: 0,
786
+ message,
787
+ finish_reason: stopMap[stopReason] ?? stopReason,
788
+ }],
789
+ usage: {
790
+ prompt_tokens: usage?.input_tokens ?? 0,
791
+ completion_tokens: usage?.output_tokens ?? 0,
792
+ total_tokens: (usage?.input_tokens ?? 0) + (usage?.output_tokens ?? 0),
793
+ },
794
+ };
795
+ }
796
+ // --- Chat Completions ↔ OpenAI Responses response conversion ---
797
+ /**
798
+ * Convert OpenAI Chat Completions response to OpenAI Responses format.
799
+ */
800
+ export function convertOpenAIResponseToOpenAIResponses(chatBody) {
801
+ const choices = chatBody.choices;
802
+ const choice = choices?.[0];
803
+ const message = choice?.message;
804
+ const usage = chatBody.usage;
805
+ const finishReason = choice?.finish_reason ?? 'stop';
806
+ const output = [];
807
+ const outputMessageContent = [];
808
+ // reasoning_content → skip (Responses client doesn't track reasoning for passthrough)
809
+ // text content
810
+ const text = message?.content;
811
+ if (text) {
812
+ outputMessageContent.push({ type: 'output_text', text, annotations: [] });
813
+ }
814
+ // Add message output item
815
+ const statusMap = { stop: 'completed', length: 'incomplete', tool_calls: 'completed' };
816
+ output.push({
817
+ type: 'message',
818
+ id: `msg_${Date.now().toString(36)}`,
819
+ status: statusMap[finishReason] ?? 'completed',
820
+ role: 'assistant',
821
+ content: outputMessageContent,
822
+ });
823
+ // tool_calls → function_call output items
824
+ const toolCalls = message?.tool_calls;
825
+ if (toolCalls) {
826
+ for (const tc of toolCalls) {
827
+ output.push({
828
+ type: 'function_call',
829
+ id: `fc_${Date.now().toString(36)}_${tc.id ?? ''}`,
830
+ call_id: tc.id,
831
+ name: tc.function?.name ?? '',
832
+ arguments: tc.function?.arguments ?? '',
833
+ });
834
+ }
835
+ }
836
+ return {
837
+ id: `resp_${Date.now().toString(36)}`,
838
+ object: 'response',
839
+ created_at: Math.floor(Date.now() / 1000),
840
+ status: statusMap[finishReason] ?? 'completed',
841
+ model: chatBody.model ?? '',
842
+ output,
843
+ usage: {
844
+ input_tokens: usage?.prompt_tokens ?? 0,
845
+ output_tokens: usage?.completion_tokens ?? 0,
846
+ total_tokens: (usage?.prompt_tokens ?? 0) + (usage?.completion_tokens ?? 0),
847
+ },
848
+ };
849
+ }
850
+ /**
851
+ * Convert OpenAI Responses response to Chat Completions format.
852
+ */
853
+ export function convertOpenAIResponsesResponseToOpenAI(responsesBody) {
854
+ const output = responsesBody.output;
855
+ const usage = responsesBody.usage;
856
+ const status = responsesBody.status ?? 'completed';
857
+ let textContent = '';
858
+ let reasoningContent = '';
859
+ const toolCalls = [];
860
+ if (output) {
861
+ for (const item of output) {
862
+ if (item.type === 'message' && item.role === 'assistant') {
863
+ const msgContent = item.content;
864
+ if (msgContent) {
865
+ for (const block of msgContent) {
866
+ if (block.type === 'output_text') {
867
+ textContent += block.text ?? '';
868
+ }
869
+ else if (block.type === 'reasoning') {
870
+ reasoningContent += (block.summary
871
+ ? block.summary.map((s) => s.text ?? '').join('')
872
+ : block.reasoning_text ?? '');
873
+ }
874
+ }
875
+ }
876
+ }
877
+ else if (item.type === 'function_call') {
878
+ toolCalls.push({
879
+ id: item.call_id ?? item.id,
880
+ type: 'function',
881
+ function: {
882
+ name: item.name ?? '',
883
+ arguments: item.arguments ?? '',
884
+ },
885
+ });
886
+ }
887
+ }
888
+ }
889
+ const finishMap = { completed: 'stop', incomplete: 'length' };
890
+ const finishReason = finishMap[status] ?? 'stop';
891
+ const message = { role: 'assistant', content: textContent };
892
+ if (reasoningContent)
893
+ message.reasoning_content = reasoningContent;
894
+ if (toolCalls.length > 0)
895
+ message.tool_calls = toolCalls;
896
+ return {
897
+ id: `chatcmpl-${Date.now().toString(36)}`,
898
+ object: 'chat.completion',
899
+ created: Math.floor(Date.now() / 1000),
900
+ model: responsesBody.model ?? '',
901
+ choices: [{
902
+ index: 0,
903
+ message,
904
+ finish_reason: finishReason,
905
+ }],
906
+ usage: {
907
+ prompt_tokens: usage?.input_tokens ?? 0,
908
+ completion_tokens: usage?.output_tokens ?? 0,
909
+ total_tokens: (usage?.input_tokens ?? 0) + (usage?.output_tokens ?? 0),
910
+ },
911
+ };
912
+ }
913
+ //# sourceMappingURL=translation.js.map