@maplezzk/llm-proxy 0.24.0 → 0.26.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 (50) hide show
  1. package/README.md +1 -0
  2. package/dist/adapter/handlers.js +1 -1
  3. package/dist/adapter/handlers.js.map +1 -1
  4. package/dist/adapter/router.d.ts +2 -1
  5. package/dist/adapter/router.d.ts.map +1 -1
  6. package/dist/adapter/router.js +6 -3
  7. package/dist/adapter/router.js.map +1 -1
  8. package/dist/api/admin-ui.html +61 -54
  9. package/dist/api/handlers/base.d.ts.map +1 -1
  10. package/dist/api/handlers/base.js +35 -31
  11. package/dist/api/handlers/base.js.map +1 -1
  12. package/dist/api/handlers/provider-crud.d.ts.map +1 -1
  13. package/dist/api/handlers/provider-crud.js +30 -19
  14. package/dist/api/handlers/provider-crud.js.map +1 -1
  15. package/dist/api/server.d.ts +6 -0
  16. package/dist/api/server.d.ts.map +1 -1
  17. package/dist/api/server.js +84 -2
  18. package/dist/api/server.js.map +1 -1
  19. package/dist/cli/commands.d.ts +1 -0
  20. package/dist/cli/commands.d.ts.map +1 -1
  21. package/dist/cli/commands.js +29 -5
  22. package/dist/cli/commands.js.map +1 -1
  23. package/dist/config/parser.d.ts.map +1 -1
  24. package/dist/config/parser.js +9 -5
  25. package/dist/config/parser.js.map +1 -1
  26. package/dist/config/types.d.ts +3 -0
  27. package/dist/config/types.d.ts.map +1 -1
  28. package/dist/config/validator.js +1 -1
  29. package/dist/config/validator.js.map +1 -1
  30. package/dist/index.js +3 -1
  31. package/dist/index.js.map +1 -1
  32. package/dist/proxy/capture.d.ts +2 -0
  33. package/dist/proxy/capture.d.ts.map +1 -1
  34. package/dist/proxy/capture.js +10 -0
  35. package/dist/proxy/capture.js.map +1 -1
  36. package/dist/proxy/provider.d.ts.map +1 -1
  37. package/dist/proxy/provider.js +3 -1
  38. package/dist/proxy/provider.js.map +1 -1
  39. package/dist/proxy/stream-converter.d.ts +1 -1
  40. package/dist/proxy/stream-converter.d.ts.map +1 -1
  41. package/dist/proxy/stream-converter.js +142 -17
  42. package/dist/proxy/stream-converter.js.map +1 -1
  43. package/dist/proxy/translation.d.ts.map +1 -1
  44. package/dist/proxy/translation.js +378 -126
  45. package/dist/proxy/translation.js.map +1 -1
  46. package/dist/types/i18n.generated.d.ts +1 -1
  47. package/dist/types/i18n.generated.d.ts.map +1 -1
  48. package/locales/en/translation.json +9 -0
  49. package/locales/zh/translation.json +9 -0
  50. package/package.json +1 -1
@@ -12,6 +12,32 @@ const REASONING_EFFORT_TO_BUDGET = {
12
12
  xhigh: 32768,
13
13
  max: 65536,
14
14
  };
15
+ // 反向映射:budget_tokens → reasoning_effort
16
+ // 接受区间:low (<2048), medium (<8192), high (<24576), xhigh (<49152), max (>=49152)
17
+ function budgetToReasoningEffort(budget) {
18
+ if (budget < 2048)
19
+ return 'low';
20
+ if (budget < 8192)
21
+ return 'medium';
22
+ if (budget < 24576)
23
+ return 'high';
24
+ if (budget < 49152)
25
+ return 'xhigh';
26
+ return 'max';
27
+ }
28
+ /**
29
+ * 将 tool_use 的 input 序列化为 Responses/Chat 都接受的 JSON 字符串 arguments。
30
+ * - input 是 string/array 时直接使用(避免双重 stringify 导致上游解析失败)
31
+ * - input 是对象/undefined 时 JSON.stringify 为 '{}' 或对应 JSON 串
32
+ */
33
+ function stringifyArguments(input) {
34
+ if (typeof input === 'string')
35
+ return input;
36
+ if (input === undefined || input === null)
37
+ return '';
38
+ // 数组在 Responses 里不合法,强制以 JSON 字符串传入
39
+ return JSON.stringify(input);
40
+ }
15
41
  /**
16
42
  * Build a lookup table of namespace function tools from the original request tools array.
17
43
  * CCX's BuildCodexToolContext scans tools and records namespace children.
@@ -355,6 +381,9 @@ function convertResponsesInputToMessages(input) {
355
381
  const it = item;
356
382
  if (it.type === 'message') {
357
383
  // { type: "message", role: "user"|"assistant"|"system"|"developer", content: string | array }
384
+ // system role 应被提取到 body.instructions(在 extractFullOpenAIResponses 处理),这里跳过避免重复
385
+ if (it.role === 'system')
386
+ continue;
358
387
  const content = it.content;
359
388
  let normalizedContent = content;
360
389
  // Convert Responses content blocks to Chat/Anthropic-compatible format
@@ -366,11 +395,21 @@ function convertResponsesInputToMessages(input) {
366
395
  }
367
396
  // reasoning → thinking (Anthropic-style thinking block)
368
397
  if (block.type === 'reasoning') {
369
- // reasoning can have summary (array of summary_text) or reasoning_text (plain string)
398
+ // OpenAI Responses 规范的 reasoning item 用 summary 字段(summary_text 数组)。
399
+ // 某些实现用 reasoning_text(字符串 或 字符串数组)作为 fallback。
370
400
  const summary = block.summary;
371
- const reasoningText = summary
372
- ? summary.map((s) => s.text ?? '').join('')
373
- : block.reasoning_text ?? '';
401
+ let reasoningText = '';
402
+ if (summary && summary.length > 0) {
403
+ reasoningText = summary.map((s) => s.text ?? '').join('');
404
+ }
405
+ else if (typeof block.reasoning_text === 'string') {
406
+ reasoningText = block.reasoning_text;
407
+ }
408
+ else if (Array.isArray(block.reasoning_text)) {
409
+ reasoningText = block.reasoning_text
410
+ .map((s) => (typeof s === 'string' ? s : s.text ?? ''))
411
+ .join('');
412
+ }
374
413
  return { type: 'thinking', thinking: reasoningText, signature: '' };
375
414
  }
376
415
  // input_image → image (Anthropic-style)
@@ -515,7 +554,13 @@ function convertResponsesInputToMessages(input) {
515
554
  });
516
555
  }
517
556
  else if (it.type === 'item_reference') {
518
- // Skip item references (they reference previous response items, not applicable to stateless chat)
557
+ // item_reference 引用上一轮 response item(如加密 reasoning);Chat/Anthropic 无原生对应物
558
+ // 为避免上下文断链,转为 user 消息占位(多轮 reasoning 场景仍会因 stateful session 丢一些信息,
559
+ // 但至少上游知道有引用)
560
+ messages.push({
561
+ role: 'user',
562
+ content: `[item_reference:${it.id ?? ''}]`,
563
+ });
519
564
  }
520
565
  else {
521
566
  // Unknown item type, pass through as-is
@@ -557,8 +602,35 @@ function convertOpenAIChatImageUrlToResponsesInputImage(block) {
557
602
  }
558
603
  return block;
559
604
  }
605
+ /**
606
+ * 把一个 Chat 风格 image_url / Anthropic image 块转成 Responses input_image 块。
607
+ * Chat: { type: "image_url", image_url: { url, detail? } | url }
608
+ * Anthropic: { type: "image", source: { type: "url", url } | { type: "base64", media_type, data } }
609
+ * Responses: { type: "input_image", image_url: string, detail? }
610
+ */
611
+ function convertAnyImageBlockToResponsesInputImage(block) {
612
+ if (block.type === 'image' && block.source) {
613
+ const source = block.source;
614
+ if (source.type === 'url' && source.url) {
615
+ return { type: 'input_image', image_url: source.url };
616
+ }
617
+ if (source.type === 'base64' && source.data) {
618
+ const mediaType = source.media_type || 'image/png';
619
+ return { type: 'input_image', image_url: `data:${mediaType};base64,${source.data}` };
620
+ }
621
+ return { type: 'input_text', text: '[image]' };
622
+ }
623
+ return convertOpenAIChatImageUrlToResponsesInputImage(block);
624
+ }
560
625
  /**
561
626
  * Convert Chat Completions messages to OpenAI Responses input format.
627
+ *
628
+ * Responses API 规范:
629
+ * - user/system 消息的 text 块必须使用 `input_text`(不是 `text`)
630
+ * - assistant 消息的 text 块必须使用 `output_text`(不是 `text`)
631
+ * - assistant 消息的 `thinking` 块提升为顶层 reasoning item
632
+ * - assistant 消息的 `tool_use` 块提升为顶层 function_call item
633
+ * - tool role 消息 → function_call_output item
562
634
  */
563
635
  function convertMessagesToResponsesInput(messages) {
564
636
  const input = [];
@@ -570,15 +642,51 @@ function convertMessagesToResponsesInput(messages) {
570
642
  call_id: m.tool_call_id,
571
643
  output: typeof m.content === 'string' ? m.content : JSON.stringify(m.content),
572
644
  });
645
+ continue;
573
646
  }
574
- else if (m.role === 'assistant') {
575
- // Add message item for text content (if any)
576
- const text = typeof m.content === 'string' ? m.content : '';
577
- if (text) {
578
- input.push({ type: 'message', role: 'assistant', content: text });
579
- }
580
- // Add function_call items for tool_calls
647
+ if (m.role === 'assistant') {
648
+ // assistant 消息:字符串 content → message (string content)
649
+ // 数组 content → 多个 item(output_text + reasoning + function_call)
581
650
  const toolCalls = m.tool_calls;
651
+ if (typeof m.content === 'string') {
652
+ if (m.content) {
653
+ input.push({ type: 'message', role: 'assistant', content: m.content });
654
+ }
655
+ }
656
+ else if (Array.isArray(m.content)) {
657
+ // Anthropic assistant content blocks: text → output_text, thinking → reasoning, tool_use → function_call
658
+ for (const block of m.content) {
659
+ if (block.type === 'text') {
660
+ input.push({ type: 'message', role: 'assistant', content: [{ type: 'output_text', text: block.text ?? '' }] });
661
+ }
662
+ else if (block.type === 'thinking') {
663
+ // thinking block → reasoning item(Responses 端要求 reasoning 后必须有 message/function_call 跟随)
664
+ const reasoningText = block.thinking ?? '';
665
+ const signature = block.signature ?? '';
666
+ if (reasoningText || signature) {
667
+ input.push({
668
+ type: 'reasoning',
669
+ summary: [{ type: 'summary_text', text: reasoningText }],
670
+ ...(signature ? { encrypted_content: signature } : {}),
671
+ });
672
+ }
673
+ }
674
+ else if (block.type === 'tool_use') {
675
+ const args = block.input;
676
+ input.push({
677
+ type: 'function_call',
678
+ call_id: block.id,
679
+ name: block.name ?? '',
680
+ arguments: typeof args === 'string' ? args : JSON.stringify(args ?? {}),
681
+ });
682
+ }
683
+ // 忽略其他块类型(image_url / redacted_thinking 等)
684
+ }
685
+ }
686
+ else if (toolCalls && toolCalls.length > 0) {
687
+ // content 是 null/未定义但有 tool_calls:保持现有行为(不推 message,只推 function_call)
688
+ }
689
+ // 推完 content 块后再推 tool_calls(Chat 风格)
582
690
  if (toolCalls) {
583
691
  for (const tc of toolCalls) {
584
692
  const fn = tc.function;
@@ -590,107 +698,121 @@ function convertMessagesToResponsesInput(messages) {
590
698
  });
591
699
  }
592
700
  }
701
+ continue;
593
702
  }
594
- else if (m.role === 'system') {
595
- // system is handled via instructions field, but if it appears in messages we include it
703
+ if (m.role === 'system') {
704
+ // system 在 extractSystemFromOpenAI 里已被提升为 instructions;这里兜底处理(次要 system 消息)
596
705
  input.push({ type: 'message', role: 'system', content: m.content });
706
+ continue;
597
707
  }
598
- else {
599
- // Check for Anthropic tool_result blocks in user message content array
600
- const content = m.content;
601
- if (m.role === 'user' && Array.isArray(content)) {
602
- const blocks = content;
603
- const toolResults = blocks.filter((b) => b.type === 'tool_result');
604
- const otherBlocks = blocks.filter((b) => b.type !== 'tool_result');
605
- // Emit computer_call_output for tool_results with image content
606
- for (const tr of toolResults) {
607
- const trContent = tr.content;
608
- let imageUrl;
609
- let fileId;
610
- if (Array.isArray(trContent)) {
611
- const imgBlock = trContent.find((b) => b.type === 'image');
612
- if (imgBlock) {
613
- const src = imgBlock.source;
614
- if (src?.type === 'url') {
615
- imageUrl = src.url;
616
- }
617
- else {
618
- fileId = imgBlock.file_id;
619
- }
708
+ if (m.role === 'developer') {
709
+ // developer 角色:Responses 没有对应项,转为 system message item
710
+ input.push({ type: 'message', role: 'system', content: m.content });
711
+ continue;
712
+ }
713
+ // user (or other) 消息
714
+ const content = m.content;
715
+ if (m.role === 'user' && Array.isArray(content)) {
716
+ const blocks = content;
717
+ const toolResults = blocks.filter((b) => b.type === 'tool_result');
718
+ const otherBlocks = blocks.filter((b) => b.type !== 'tool_result');
719
+ // tool_results 提升为 function_call_output / computer_call_output
720
+ for (const tr of toolResults) {
721
+ const trContent = tr.content;
722
+ let imageUrl;
723
+ let fileId;
724
+ if (Array.isArray(trContent)) {
725
+ const imgBlock = trContent.find((b) => b.type === 'image');
726
+ if (imgBlock) {
727
+ const src = imgBlock.source;
728
+ if (src?.type === 'url') {
729
+ imageUrl = src.url;
730
+ }
731
+ else {
732
+ fileId = imgBlock.file_id;
620
733
  }
621
- }
622
- if (imageUrl) {
623
- input.push({
624
- type: 'computer_call_output',
625
- call_id: tr.tool_use_id,
626
- output: { type: 'computer_screenshot', image_url: imageUrl },
627
- });
628
- }
629
- else if (fileId) {
630
- input.push({
631
- type: 'computer_call_output',
632
- call_id: tr.tool_use_id,
633
- output: { type: 'computer_screenshot', file_id: fileId },
634
- });
635
- }
636
- else {
637
- // tool_result without image → function_call_output
638
- input.push({
639
- type: 'function_call_output',
640
- call_id: tr.tool_use_id,
641
- output: typeof trContent === 'string' ? trContent : JSON.stringify(trContent),
642
- });
643
734
  }
644
735
  }
645
- // Emit remaining non-tool_result blocks as message items
646
- if (otherBlocks.length > 0) {
647
- // 转换 Anthropic image 块 和 OpenAI Chat image_url 块 → Responses input_image 块
648
- const blocks = otherBlocks.map((b) => {
649
- // Anthropic 风格的 image 块
650
- if (b.type === 'image' && b.source) {
651
- const source = b.source;
652
- if (source.type === 'url' && source.url) {
653
- return { type: 'input_image', image_url: source.url };
654
- }
655
- if (source.type === 'base64' && source.data) {
656
- const mediaType = source.media_type || 'image/png';
657
- return { type: 'input_image', image_url: `data:${mediaType};base64,${source.data}` };
658
- }
659
- return { type: 'input_text', text: '[image]' };
660
- }
661
- // OpenAI Chat 风格的 image_url 块
662
- return convertOpenAIChatImageUrlToResponsesInputImage(b);
736
+ if (imageUrl) {
737
+ input.push({
738
+ type: 'computer_call_output',
739
+ call_id: tr.tool_use_id,
740
+ output: { type: 'computer_screenshot', image_url: imageUrl },
741
+ });
742
+ }
743
+ else if (fileId) {
744
+ input.push({
745
+ type: 'computer_call_output',
746
+ call_id: tr.tool_use_id,
747
+ output: { type: 'computer_screenshot', file_id: fileId },
748
+ });
749
+ }
750
+ else {
751
+ input.push({
752
+ type: 'function_call_output',
753
+ call_id: tr.tool_use_id,
754
+ output: typeof trContent === 'string' ? trContent : JSON.stringify(trContent),
663
755
  });
664
- const textBlocks = blocks.filter((b) => b.type === 'text' || b.type === 'input_text');
665
- const text = textBlocks.map((b) => b.text ?? '').join('');
666
- if (text || blocks.length !== textBlocks.length) {
667
- input.push({
668
- type: 'message',
669
- role: m.role ?? 'user',
670
- content: blocks,
671
- });
672
- }
673
756
  }
674
757
  }
675
- else {
676
- // user, developer, etc. (non-Anthropic format)
677
- // content 数组中可能有 OpenAI Chat 风格的 image_url 块,需转成 Responses 的 input_image
678
- if (Array.isArray(m.content)) {
679
- const blocks = m.content.map(convertOpenAIChatImageUrlToResponsesInputImage);
680
- const textBlocks = blocks.filter((b) => b.type === 'text' || b.type === 'input_text');
681
- const allText = blocks.every((b) => b.type === 'text' || b.type === 'input_text');
682
- if (allText) {
683
- // 全部文本 → 用 Responses 的 input_text 块 (更规范)
684
- input.push({ type: 'message', role: m.role ?? 'user', content: blocks });
758
+ // 剩余块(text/image/image_url/document/tool_use)转为 Responses content 块
759
+ if (otherBlocks.length > 0) {
760
+ const converted = otherBlocks.map((b) => {
761
+ // text 块必须转 input_text(user 角色)
762
+ if (b.type === 'text') {
763
+ return { type: 'input_text', text: b.text ?? '' };
685
764
  }
686
- else if (textBlocks.length > 0 || blocks.length > 0) {
687
- input.push({ type: 'message', role: m.role ?? 'user', content: blocks });
765
+ // Anthropic image 块 / Chat image_url 块 → input_image
766
+ if (b.type === 'image' || b.type === 'image_url') {
767
+ return convertAnyImageBlockToResponsesInputImage(b);
688
768
  }
769
+ // 未知块:保留 input_text 形态或原样透传
770
+ return b;
771
+ });
772
+ // 全部 input_text 时可以压平为字符串(Responses 接受 string content)
773
+ const allInputText = converted.every((b) => b.type === 'input_text');
774
+ if (allInputText) {
775
+ input.push({
776
+ type: 'message',
777
+ role: 'user',
778
+ content: converted.map((b) => b.text ?? '').join(''),
779
+ });
689
780
  }
690
781
  else {
691
- input.push({ type: 'message', role: m.role ?? 'user', content: m.content });
782
+ input.push({
783
+ type: 'message',
784
+ role: 'user',
785
+ content: converted,
786
+ });
692
787
  }
693
788
  }
789
+ continue;
790
+ }
791
+ // 其他情况:user/其他角色的非 Anthropic 形式
792
+ if (Array.isArray(m.content)) {
793
+ const blocks = m.content.map((b) => {
794
+ if (b.type === 'text')
795
+ return { type: 'input_text', text: b.text ?? '' };
796
+ return convertAnyImageBlockToResponsesInputImage(b);
797
+ });
798
+ const allInputText = blocks.every((b) => b.type === 'input_text');
799
+ if (allInputText) {
800
+ input.push({
801
+ type: 'message',
802
+ role: m.role ?? 'user',
803
+ content: blocks.map((b) => b.text ?? '').join(''),
804
+ });
805
+ }
806
+ else {
807
+ input.push({
808
+ type: 'message',
809
+ role: m.role ?? 'user',
810
+ content: blocks,
811
+ });
812
+ }
813
+ }
814
+ else {
815
+ input.push({ type: 'message', role: m.role ?? 'user', content: m.content });
694
816
  }
695
817
  }
696
818
  return input;
@@ -748,6 +870,9 @@ function extractFullOpenAI(body) {
748
870
  stop: body.stop,
749
871
  tools: body.tools,
750
872
  tool_choice: body.tool_choice,
873
+ store: body.store,
874
+ metadata: body.metadata,
875
+ parallel_tool_calls: body.parallel_tool_calls,
751
876
  };
752
877
  }
753
878
  function extractFullAnthropic(body) {
@@ -1169,19 +1294,43 @@ function buildOpenAIFromAnthropic(params) {
1169
1294
  function extractFullOpenAIResponses(body) {
1170
1295
  const rawInput = body.input;
1171
1296
  let messages;
1297
+ let inputSystem;
1172
1298
  if (typeof rawInput === 'string') {
1173
1299
  messages = [{ role: 'user', content: rawInput }];
1174
1300
  }
1175
1301
  else if (Array.isArray(rawInput)) {
1302
+ // 从 input 数组中提取 system message 到 instructions(避免出现在 messages 里)
1303
+ for (const item of rawInput) {
1304
+ const it = item;
1305
+ if (it.type === 'message' && it.role === 'system') {
1306
+ const c = it.content;
1307
+ if (typeof c === 'string')
1308
+ inputSystem = c;
1309
+ else if (Array.isArray(c)) {
1310
+ inputSystem = c
1311
+ .filter((b) => b.type === 'input_text')
1312
+ .map((b) => b.text ?? '')
1313
+ .join('\n\n');
1314
+ }
1315
+ break;
1316
+ }
1317
+ }
1176
1318
  messages = convertResponsesInputToMessages(rawInput);
1319
+ // 空 input 数组:上游 Chat Completions 会拒空 messages,以占位 user message 代替
1320
+ // (仅在跨协议路由到 Chat/Anthropic 时需要;同 Responses 协议透传由 builder 处理)
1321
+ if (messages.length === 0) {
1322
+ messages = [{ role: 'user', content: '' }];
1323
+ }
1177
1324
  }
1178
1325
  else {
1179
- messages = [];
1326
+ messages = [{ role: 'user', content: '' }];
1180
1327
  }
1328
+ // instructions 优先;input 数组里 system 次之
1329
+ const system = body.instructions ?? inputSystem;
1181
1330
  return {
1182
1331
  model: body.model,
1183
1332
  messages,
1184
- system: body.instructions,
1333
+ system,
1185
1334
  reasoning: resolveReasoning(body),
1186
1335
  temperature: body.temperature,
1187
1336
  max_tokens: (body.max_output_tokens ?? body.max_tokens),
@@ -1190,6 +1339,12 @@ function extractFullOpenAIResponses(body) {
1190
1339
  stop: body.stop,
1191
1340
  tools: body.tools,
1192
1341
  tool_choice: body.tool_choice,
1342
+ store: body.store,
1343
+ include: body.include,
1344
+ metadata: body.metadata,
1345
+ parallel_tool_calls: body.parallel_tool_calls,
1346
+ previous_response_id: body.previous_response_id,
1347
+ truncation: body.truncation,
1193
1348
  };
1194
1349
  }
1195
1350
  // --- Builders for OpenAI Responses format ---
@@ -1245,6 +1400,19 @@ function buildOpenAIResponsesFromFullParams(params) {
1245
1400
  body.tools = convertToolsToOpenAIResponses(params.tools);
1246
1401
  if (params.tool_choice !== undefined)
1247
1402
  body.tool_choice = convertToolChoiceToOpenAIResponses(params.tool_choice);
1403
+ // Responses 协议专有字段透传
1404
+ if (params.store !== undefined)
1405
+ body.store = params.store;
1406
+ if (params.include !== undefined)
1407
+ body.include = params.include;
1408
+ if (params.metadata !== undefined)
1409
+ body.metadata = params.metadata;
1410
+ if (params.parallel_tool_calls !== undefined)
1411
+ body.parallel_tool_calls = params.parallel_tool_calls;
1412
+ if (params.previous_response_id !== undefined)
1413
+ body.previous_response_id = params.previous_response_id;
1414
+ if (params.truncation !== undefined)
1415
+ body.truncation = params.truncation;
1248
1416
  return body;
1249
1417
  }
1250
1418
  export async function transformInboundRequest(inboundType, route, body, logger) {
@@ -1338,6 +1506,16 @@ export async function transformInboundRequest(inboundType, route, body, logger)
1338
1506
  }
1339
1507
  // max_tokens 二次兜底,处理 builder 中可能遗留的 0
1340
1508
  sanitizeMaxTokens(upstreamBody, route);
1509
+ // 跨协议:Anthropic 客户端传 thinking.budget_tokens → Responses/OpenAI 的 reasoning.effort
1510
+ // (响应式的 builder 不消费 thinking 字段,需要在这里反向映射)
1511
+ if (!params.reasoning && (route.providerType === 'openai' || route.providerType === 'openai-responses')) {
1512
+ const anthropicThinking = body.thinking;
1513
+ if (anthropicThinking?.type === 'enabled' && typeof anthropicThinking.budget_tokens === 'number') {
1514
+ const effort = budgetToReasoningEffort(anthropicThinking.budget_tokens);
1515
+ if (effort)
1516
+ params.reasoning = { effort };
1517
+ }
1518
+ }
1341
1519
  // 注入 thinking 配置到转换后的请求体(跨协议场景下携带客户端的 reasoning_effort)
1342
1520
  const clientReasoningEffort = extractClientReasoningEffort(params.reasoning);
1343
1521
  injectThinkingConfig(upstreamBody, route, clientReasoningEffort);
@@ -1470,6 +1648,24 @@ function sanitizeMaxTokens(upstreamBody, route) {
1470
1648
  * @param clientReasoningEffort 客户端请求里的 reasoning_effort(跨协议时可用)
1471
1649
  */
1472
1650
  function injectThinkingConfig(upstreamBody, route, clientReasoningEffort) {
1651
+ // 跨协议:Anthropic 客户端传 thinking.budget_tokens → Responses 上游的 reasoning.effort
1652
+ // (Responses 不认识 Anthropic thinking 块格式)
1653
+ if ((route.providerType === 'openai' || route.providerType === 'openai-responses')
1654
+ && !upstreamBody.reasoning && !upstreamBody.reasoning_effort) {
1655
+ // 客户端的 thinking.budget_tokens(Anthropic 风格)
1656
+ const anthropicThinking = upstreamBody.thinking;
1657
+ if (anthropicThinking?.type === 'enabled' && typeof anthropicThinking.budget_tokens === 'number') {
1658
+ const effort = budgetToReasoningEffort(anthropicThinking.budget_tokens);
1659
+ if (effort) {
1660
+ if (route.providerType === 'openai-responses') {
1661
+ upstreamBody.reasoning = { effort };
1662
+ }
1663
+ else {
1664
+ upstreamBody.reasoning_effort = effort;
1665
+ }
1666
+ }
1667
+ }
1668
+ }
1473
1669
  if (route.providerType === 'anthropic') {
1474
1670
  // 解析 budget_tokens 来源:用户配的 budget_tokens > 用户配的 reasoning_effort > 客户端的 reasoning_effort
1475
1671
  let budget;
@@ -1519,6 +1715,17 @@ function injectThinkingConfig(upstreamBody, route, clientReasoningEffort) {
1519
1715
  }
1520
1716
  }
1521
1717
  }
1718
+ else if ((route.providerType === 'openai' || route.providerType === 'openai-responses')
1719
+ && clientReasoningEffort
1720
+ && !upstreamBody.reasoning && !upstreamBody.reasoning_effort) {
1721
+ // 跨协议场景:客户端传了 reasoning(从 Anthropic thinking.budget_tokens 反向映射而来)
1722
+ if (route.providerType === 'openai-responses') {
1723
+ upstreamBody.reasoning = { effort: clientReasoningEffort };
1724
+ }
1725
+ else {
1726
+ upstreamBody.reasoning_effort = clientReasoningEffort;
1727
+ }
1728
+ }
1522
1729
  }
1523
1730
  // --- Action mapping helpers (Computer Use) ---
1524
1731
  /** OpenAI ComputerAction → Anthropic tool_use input */
@@ -1614,24 +1821,36 @@ export function convertActionToOpenAI(input) {
1614
1821
  return result;
1615
1822
  }
1616
1823
  // --- OpenAI Responses ↔ Anthropic response conversion ---
1617
- function mapResponsesStopReason(stop, hasToolCalls) {
1824
+ function mapResponsesStopReason(stop, hasToolCalls, incompleteReason) {
1618
1825
  if (hasToolCalls)
1619
1826
  return 'tool_use';
1827
+ // 优先根据 incomplete_details.reason 推断(如 max_output_tokens → max_tokens)
1828
+ if (stop === 'incomplete') {
1829
+ if (incompleteReason === 'max_output_tokens' || incompleteReason === 'max_tokens')
1830
+ return 'max_tokens';
1831
+ if (incompleteReason === 'content_filter')
1832
+ return 'end_turn';
1833
+ }
1620
1834
  const stopMap = { completed: 'end_turn', incomplete: 'max_tokens', max_output_tokens: 'max_tokens' };
1621
1835
  return stopMap[stop] ?? 'end_turn';
1622
1836
  }
1623
1837
  export function convertOpenAIResponsesToAnthropic(responsesBody) {
1624
1838
  const output = responsesBody.output;
1625
1839
  const usage = responsesBody.usage;
1840
+ const respStatus = responsesBody.status ?? 'completed';
1841
+ const incompleteDetails = responsesBody.incomplete_details;
1842
+ const incompleteReason = incompleteDetails?.reason;
1626
1843
  const content = [];
1627
- let stopReason = 'end_turn';
1844
+ let stopReason = respStatus;
1628
1845
  // 提取顶层 reasoning.summary → Anthropic thinking 块(作为首个 content block)
1846
+ // encrypted_content 作为 signature 透传给下一轮(多轮 reasoning 必依赖)
1629
1847
  const topReasoning = responsesBody.reasoning;
1630
1848
  if (topReasoning?.summary) {
1631
1849
  const summaryItems = topReasoning.summary;
1632
1850
  const summaryText = summaryItems.map((s) => s.text ?? '').join('');
1633
- if (summaryText) {
1634
- content.push({ type: 'thinking', thinking: summaryText, signature: '' });
1851
+ const encrypted = topReasoning.encrypted_content ?? '';
1852
+ if (summaryText || encrypted) {
1853
+ content.push({ type: 'thinking', thinking: summaryText, signature: encrypted });
1635
1854
  }
1636
1855
  }
1637
1856
  if (output) {
@@ -1643,25 +1862,40 @@ export function convertOpenAIResponsesToAnthropic(responsesBody) {
1643
1862
  if (block.type === 'output_text') {
1644
1863
  content.push({ type: 'text', text: block.text ?? '' });
1645
1864
  }
1865
+ else if (block.type === 'refusal') {
1866
+ // refusal → Anthropic 普通 text 块(Anthropic 没有显式 refusal 概念)
1867
+ const refusalText = block.refusal ?? '';
1868
+ if (refusalText) {
1869
+ content.push({ type: 'text', text: refusalText });
1870
+ }
1871
+ }
1646
1872
  else if (block.type === 'reasoning') {
1647
1873
  content.push({ type: 'thinking', thinking: block.summary ? block.summary.map((s) => s.text ?? '').join('') : (block.reasoning_text ?? ''), signature: '' });
1648
1874
  }
1649
1875
  else if (block.type === 'web_search_call') {
1650
- // web_search is Responses-specific, map to text note or skip
1651
- // For now, skip as Anthropic doesn't have direct equivalent
1876
+ // web_search is Responses-specific, skip (Anthropic doesn't have direct equivalent)
1652
1877
  }
1653
1878
  }
1654
1879
  }
1655
- if (item.status)
1656
- stopReason = item.status;
1657
1880
  }
1658
1881
  else if (item.type === 'function_call') {
1659
1882
  let input = {};
1660
- try {
1661
- input = typeof item.arguments === 'string' ? JSON.parse(item.arguments) : (item.arguments ?? {});
1883
+ const rawArgs = item.arguments;
1884
+ if (typeof rawArgs === 'string') {
1885
+ if (rawArgs.trim() === '') {
1886
+ input = {};
1887
+ }
1888
+ else {
1889
+ try {
1890
+ input = JSON.parse(rawArgs);
1891
+ }
1892
+ catch {
1893
+ input = rawArgs;
1894
+ }
1895
+ }
1662
1896
  }
1663
- catch {
1664
- input = item.arguments;
1897
+ else if (rawArgs && typeof rawArgs === 'object') {
1898
+ input = rawArgs;
1665
1899
  }
1666
1900
  content.push({
1667
1901
  type: 'tool_use',
@@ -1687,19 +1921,18 @@ export function convertOpenAIResponsesToAnthropic(responsesBody) {
1687
1921
  continue;
1688
1922
  }
1689
1923
  else if (item.type === 'reasoning') {
1690
- // Standalone reasoning output item → thinking block
1924
+ // Standalone reasoning output item → thinking block(encrypted_content 作为 signature 透传)
1691
1925
  const summary = item.summary;
1692
- if (summary) {
1693
- const reasonText = summary.map((s) => s.text ?? '').join('');
1694
- if (reasonText) {
1695
- content.push({ type: 'thinking', thinking: reasonText, signature: '' });
1696
- }
1926
+ const reasonText = summary ? summary.map((s) => s.text ?? '').join('') : '';
1927
+ const encrypted = item.encrypted_content ?? '';
1928
+ if (reasonText || encrypted) {
1929
+ content.push({ type: 'thinking', thinking: reasonText, signature: encrypted });
1697
1930
  }
1698
1931
  }
1699
1932
  }
1700
1933
  }
1701
1934
  const hasToolCalls = content.some((b) => b.type === 'tool_use');
1702
- const anthropicStop = mapResponsesStopReason(stopReason, hasToolCalls);
1935
+ const anthropicStop = mapResponsesStopReason(stopReason, hasToolCalls, incompleteReason);
1703
1936
  return {
1704
1937
  id: `msg_${Date.now()}`,
1705
1938
  type: 'message',
@@ -1724,6 +1957,7 @@ export function convertAnthropicResponseToOpenAIResponses(anthropicBody) {
1724
1957
  const outputMessageContent = [];
1725
1958
  const output = [];
1726
1959
  let thinkingText = '';
1960
+ let thinkingSignatures = [];
1727
1961
  if (content) {
1728
1962
  for (const block of content) {
1729
1963
  if (block.type === 'text') {
@@ -1732,6 +1966,9 @@ export function convertAnthropicResponseToOpenAIResponses(anthropicBody) {
1732
1966
  else if (block.type === 'thinking') {
1733
1967
  // 收集 thinking 文本,稍后放到顶层的 reasoning.summary
1734
1968
  thinkingText += block.thinking ?? '';
1969
+ // 收集 signature 作为 encrypted_content 透传(多轮 reasoning 依赖)
1970
+ if (block.signature)
1971
+ thinkingSignatures.push(block.signature);
1735
1972
  }
1736
1973
  else if (block.type === 'tool_use') {
1737
1974
  const name = block.name ?? '';
@@ -1755,7 +1992,8 @@ export function convertAnthropicResponseToOpenAIResponses(anthropicBody) {
1755
1992
  id: `fc_${Date.now().toString(36)}_${block.id ?? ''}`,
1756
1993
  call_id: block.id,
1757
1994
  name,
1758
- arguments: JSON.stringify(block.input ?? {}),
1995
+ // arguments 必须是合法 JSON 字符串。input 已是 string/array 时不再 stringify
1996
+ arguments: stringifyArguments(block.input),
1759
1997
  status: 'completed',
1760
1998
  });
1761
1999
  }
@@ -1780,8 +2018,13 @@ export function convertAnthropicResponseToOpenAIResponses(anthropicBody) {
1780
2018
  status: stopReason === 'end_turn' ? 'completed' : 'incomplete',
1781
2019
  model: anthropicBody.model ?? '',
1782
2020
  output,
1783
- // Anthropic thinking → 顶层 reasoning.summary(非完整推理文本)
1784
- ...(thinkingText ? { reasoning: { summary: [{ type: 'summary_text', text: thinkingText, index: 0 }] } } : {}),
2021
+ // Anthropic thinking → 顶层 reasoning.summary(非完整推理文本)+ encrypted_content 透传 signature
2022
+ ...(thinkingText || thinkingSignatures.length > 0
2023
+ ? { reasoning: {
2024
+ summary: [{ type: 'summary_text', text: thinkingText, index: 0 }],
2025
+ ...(thinkingSignatures.length > 0 ? { encrypted_content: thinkingSignatures.join('|') } : {}),
2026
+ } }
2027
+ : {}),
1785
2028
  usage: (() => {
1786
2029
  const ai = usage?.input_tokens ?? 0;
1787
2030
  const cr = usage?.cache_read_input_tokens ?? 0;
@@ -1890,7 +2133,7 @@ export function convertAnthropicResponseToOpenAI(anthropicBody) {
1890
2133
  type: 'function',
1891
2134
  function: {
1892
2135
  name: block.name,
1893
- arguments: JSON.stringify(block.input ?? {}),
2136
+ arguments: stringifyArguments(block.input),
1894
2137
  },
1895
2138
  });
1896
2139
  }
@@ -2023,10 +2266,19 @@ export function convertOpenAIResponsesResponseToOpenAI(responsesBody) {
2023
2266
  }
2024
2267
  else if (block.type === 'reasoning') {
2025
2268
  // 消息内嵌 reasoning(兼容格式),优先级低于顶层 summary
2269
+ // summary 是首选;reasoning_text 接受 string 或 string 数组两种形态
2026
2270
  if (!reasoningContent) {
2027
- reasoningContent += (block.summary
2028
- ? block.summary.map((s) => s.text ?? '').join('')
2029
- : block.reasoning_text ?? '');
2271
+ if (block.summary) {
2272
+ reasoningContent += block.summary.map((s) => s.text ?? '').join('');
2273
+ }
2274
+ else if (typeof block.reasoning_text === 'string') {
2275
+ reasoningContent += block.reasoning_text;
2276
+ }
2277
+ else if (Array.isArray(block.reasoning_text)) {
2278
+ reasoningContent += block.reasoning_text
2279
+ .map((s) => (typeof s === 'string' ? s : s.text ?? ''))
2280
+ .join('');
2281
+ }
2030
2282
  }
2031
2283
  }
2032
2284
  }