@maplezzk/llm-proxy 0.14.1 → 0.15.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.
@@ -1,5 +1,55 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { sanitizeApiBase } from '../lib/http-utils.js';
3
+ /**
4
+ * Build a lookup table of namespace function tools from the original request tools array.
5
+ * CCX's BuildCodexToolContext scans tools and records namespace children.
6
+ */
7
+ export function buildNamespaceToolContext(tools) {
8
+ const ctx = new Map();
9
+ if (!Array.isArray(tools))
10
+ return ctx;
11
+ for (const raw of tools) {
12
+ const t = raw;
13
+ if (t.type === 'namespace') {
14
+ const namespaceName = t.name ?? '';
15
+ const children = t.tools;
16
+ if (!namespaceName || !children)
17
+ continue;
18
+ for (const child of children) {
19
+ const childItem = child;
20
+ if (childItem.type !== 'function')
21
+ continue;
22
+ const childName = childItem.name;
23
+ if (!childName)
24
+ continue;
25
+ // CCX convention: namespace__name (namespace ends with __ → no extra separator)
26
+ const flatName = namespaceName.endsWith('__') ? `${namespaceName}${childName}` : `${namespaceName}__${childName}`;
27
+ ctx.set(flatName, { namespace: namespaceName, name: childName });
28
+ }
29
+ }
30
+ }
31
+ return ctx;
32
+ }
33
+ /**
34
+ * Remap namespace function calls in a response output array.
35
+ * CCX's RemapNamespaceFunctionCallsInResponse uses the context to add namespace field.
36
+ */
37
+ export function remapNamespaceFunctionCalls(output, namespaceCtx) {
38
+ if (!namespaceCtx.size)
39
+ return;
40
+ for (const item of output) {
41
+ if (item.type !== 'function_call')
42
+ continue;
43
+ const name = item.name;
44
+ if (!name)
45
+ continue;
46
+ const spec = namespaceCtx.get(name);
47
+ if (!spec)
48
+ continue;
49
+ item.name = spec.name;
50
+ item.namespace = spec.namespace;
51
+ }
52
+ }
3
53
  // --- Helpers ---
4
54
  /** 从 thinking 内容生成确定性伪签名(与 stream-converter.ts 中的一致) */
5
55
  function makeSignature(thinkingText) {
@@ -29,72 +79,175 @@ function truncateBody(obj, maxLen = 500) {
29
79
  function convertToolsToAnthropic(tools) {
30
80
  if (!Array.isArray(tools))
31
81
  return undefined;
32
- return tools
33
- .filter((t) => {
34
- // Filter out non-function tools (web_search, code_interpreter, etc.) -
35
- // Anthropic API only supports standard tools
36
- const item = t;
37
- return item.type === 'function' || (item.name && item.input_schema);
38
- })
39
- .map((t) => {
82
+ const result = [];
83
+ for (const t of tools) {
40
84
  const item = t;
85
+ const type = String(item.type ?? '');
86
+ // OpenAI Responses built-in: computer_use_preview → Anthropic computer_20251124
87
+ if (type.startsWith('computer_use_preview')) {
88
+ result.push({
89
+ type: 'computer_20251124',
90
+ name: 'computer',
91
+ display_width_px: (item.display_width ?? item.display_width_px),
92
+ display_height_px: (item.display_height ?? item.display_height_px),
93
+ display_number: item.display_number,
94
+ });
95
+ continue;
96
+ }
97
+ // OpenAI built-in tools with no Anthropic equivalent → skip
98
+ if (['web_search_preview', 'web_search', 'code_interpreter', 'file_search'].includes(type)) {
99
+ continue;
100
+ }
101
+ // OpenAI namespace tools → flatten to individual Anthropic tools
102
+ // (same approach as convertToolsToOpenAI, using Anthropic tool format)
103
+ if (type === 'namespace') {
104
+ const nsName = item.name ?? '';
105
+ const children = item.tools;
106
+ if (children) {
107
+ for (const child of children) {
108
+ const childType = child.type ?? '';
109
+ const childName = (child.name ?? child.function?.name) ?? '';
110
+ if (!childName)
111
+ continue;
112
+ // CCX convention: namespace ends with __, so direct concatenation
113
+ const flatName = nsName.endsWith('__') ? `${nsName}${childName}` : `${nsName}__${childName}`;
114
+ if (childType === 'function') {
115
+ const fn = child.function;
116
+ const params = fn?.parameters ?? child.parameters ?? {};
117
+ result.push({
118
+ name: flatName,
119
+ description: (fn?.description ?? child.description ?? '') || undefined,
120
+ input_schema: params,
121
+ });
122
+ }
123
+ else {
124
+ // Non-function child tools: use child data directly
125
+ result.push({
126
+ name: flatName,
127
+ description: child.description || undefined,
128
+ input_schema: (child.input_schema ?? child.parameters ?? {}),
129
+ });
130
+ }
131
+ }
132
+ }
133
+ continue;
134
+ }
41
135
  // OpenAI Chat format: { type: "function", function: { name, description, parameters } }
42
- if (item.type === 'function' && item.function) {
136
+ if (type === 'function' && item.function) {
43
137
  const fn = item.function;
44
- return {
138
+ result.push({
45
139
  name: fn.name ?? '',
46
140
  description: fn.description || undefined,
47
141
  input_schema: fn.parameters ?? {},
48
- };
142
+ });
143
+ continue;
49
144
  }
50
145
  // OpenAI Responses flat format: { type: "function", name, description, parameters } (no "function" wrapper)
51
- if (item.type === 'function' && item.name) {
52
- return {
146
+ if (type === 'function' && item.name) {
147
+ result.push({
53
148
  name: item.name ?? '',
54
149
  description: item.description || undefined,
55
150
  input_schema: item.parameters ?? {},
56
- };
151
+ });
152
+ continue;
57
153
  }
58
- // Already Anthropic format or unknown
59
- return item;
60
- });
154
+ // Already Anthropic format: { name, input_schema }
155
+ if (item.name && item.input_schema) {
156
+ result.push(item);
157
+ continue;
158
+ }
159
+ }
160
+ return result.length > 0 ? result : undefined;
61
161
  }
62
162
  function convertToolsToOpenAI(tools) {
63
163
  if (!Array.isArray(tools))
64
164
  return undefined;
65
- return tools
66
- .filter((t) => {
67
- // Filter out non-function tools (web_search, code_interpreter, etc.) -
68
- // Chat Completions API only supports type: "function"
69
- const item = t;
70
- return item.type === 'function' || (item.name && item.input_schema);
71
- })
72
- .map((t) => {
165
+ const result = [];
166
+ for (const t of tools) {
73
167
  const item = t;
168
+ const type = String(item.type ?? '');
169
+ // Anthropic built-in: computer_2025* (versioned type) → OpenAI computer_use_preview
170
+ // Must be checked BEFORE the strip below (computer_use_preview keywords overlap)
171
+ if (type.startsWith('computer_20')) {
172
+ result.push({
173
+ type: 'computer_use_preview',
174
+ display_width: (item.display_width_px ?? item.display_width),
175
+ display_height: (item.display_height_px ?? item.display_height),
176
+ display_number: item.display_number,
177
+ });
178
+ continue;
179
+ }
180
+ // CCX stripCodexClientOnlyTools: drop non-function tool types (except namespace)
181
+ // Namespace tools are flattened below (CCX's namespaceToolsToOpenAI)
182
+ if (['custom', 'web_search', 'web_search_preview', 'computer_use', 'computer_use_preview',
183
+ 'local_shell', 'code_interpreter', 'file_search'].includes(type)) {
184
+ continue;
185
+ }
186
+ // CCX namespaceToolsToOpenAI: flatten namespace tools to OpenAI function tools
187
+ // e.g. namespace "mcp__computer_use__" with child "get_app_state" → tool "mcp__computer_use__get_app_state"
188
+ if (type === 'namespace') {
189
+ const nsName = item.name ?? '';
190
+ const nsDesc = item.description ?? '';
191
+ const children = item.tools;
192
+ if (nsName && children) {
193
+ for (const child of children) {
194
+ const childItem = child;
195
+ if (childItem.type !== 'function')
196
+ continue;
197
+ const childName = childItem.name;
198
+ if (!childName)
199
+ continue;
200
+ const childFn = childItem.function;
201
+ const childDesc = childFn?.description ?? childItem.description ?? '';
202
+ const childParams = (childFn?.parameters ?? childItem.parameters) ?? {};
203
+ // CCX flattenNamespaceToolName: namespace ends with __ → no extra separator
204
+ const flatName = nsName.endsWith('__') ? `${nsName}${childName}` : `${nsName}__${childName}`;
205
+ // CCX combineNamespaceDescription
206
+ const combinedDesc = nsDesc && childDesc ? `${nsDesc}\n\n${childDesc}` : (nsDesc || childDesc || undefined);
207
+ result.push({
208
+ type: 'function',
209
+ function: {
210
+ name: flatName,
211
+ description: combinedDesc,
212
+ parameters: childParams,
213
+ },
214
+ });
215
+ }
216
+ }
217
+ continue;
218
+ }
74
219
  // Anthropic format: { name, description, input_schema }
75
220
  if (item.name && item.input_schema) {
76
- return {
221
+ result.push({
77
222
  type: 'function',
78
223
  function: {
79
224
  name: item.name,
80
225
  description: item.description || undefined,
81
226
  parameters: item.input_schema,
82
227
  },
83
- };
228
+ });
229
+ continue;
84
230
  }
85
231
  // OpenAI Responses flat format: { type: "function", name, parameters } → wrap in "function" for Chat Completions
86
- if (item.type === 'function' && item.name && !item.function) {
87
- return {
232
+ if (type === 'function' && item.name && !item.function) {
233
+ result.push({
88
234
  type: 'function',
89
235
  function: {
90
236
  name: item.name ?? '',
91
237
  description: item.description || undefined,
92
238
  parameters: item.parameters ?? {},
93
239
  },
94
- };
240
+ });
241
+ continue;
95
242
  }
96
- return item;
97
- });
243
+ // Already valid Chat format (type: "function" with nested "function") → keep
244
+ if (type === 'function' && item.function) {
245
+ result.push(item);
246
+ continue;
247
+ }
248
+ // Unknown tool type → skip (OpenAI Chat only accepts type: "function")
249
+ }
250
+ return result.length > 0 ? result : undefined;
98
251
  }
99
252
  function convertToolChoiceToAnthropic(toolChoice) {
100
253
  if (toolChoice === undefined || toolChoice === null)
@@ -211,17 +364,25 @@ function convertResponsesInputToMessages(input) {
211
364
  messages.push({ role: it.role, content: normalizedContent });
212
365
  }
213
366
  else if (it.type === 'function_call') {
214
- // { type: "function_call", call_id, name, arguments }
367
+ // { type: "function_call", call_id, name, arguments, namespace? }
368
+ // Encode namespace in function name using `__` prefix convention (CCX-compatible)
369
+ let fnName = it.name ?? '';
370
+ const namespace = it.namespace;
371
+ if (namespace) {
372
+ // CCX convention: if namespace ends with __, don't add separator
373
+ fnName = namespace.endsWith('__') ? `${namespace}${fnName}` : `${namespace}__${fnName}`;
374
+ }
215
375
  // 检查上一条消息是否是 assistant 消息,如果是则合并 tool_calls,避免两条连续 assistant 消息
216
376
  const lastMsg = messages.length > 0 ? messages[messages.length - 1] : null;
377
+ const tcEntry = {
378
+ id: it.call_id ?? it.id,
379
+ type: 'function',
380
+ function: { name: fnName, arguments: it.arguments ?? '' },
381
+ };
217
382
  if (lastMsg && lastMsg.role === 'assistant') {
218
383
  if (!lastMsg.tool_calls)
219
384
  lastMsg.tool_calls = [];
220
- lastMsg.tool_calls.push({
221
- id: it.call_id ?? it.id,
222
- type: 'function',
223
- function: { name: it.name ?? '', arguments: it.arguments ?? '' },
224
- });
385
+ lastMsg.tool_calls.push(tcEntry);
225
386
  // 确保 content 不为 undefined(OpenAI 要求 tool_calls 时 content 为 null)
226
387
  if (lastMsg.content === undefined)
227
388
  lastMsg.content = null;
@@ -230,20 +391,56 @@ function convertResponsesInputToMessages(input) {
230
391
  messages.push({
231
392
  role: 'assistant',
232
393
  content: null,
233
- tool_calls: [{
234
- id: it.call_id ?? it.id,
235
- type: 'function',
236
- function: { name: it.name ?? '', arguments: it.arguments ?? '' },
237
- }],
394
+ tool_calls: [tcEntry],
238
395
  });
239
396
  }
240
397
  }
398
+ else if (it.type === 'reasoning') {
399
+ // { type: "reasoning", summary, content } → skip (not a message type in Chat format)
400
+ continue;
401
+ }
241
402
  else if (it.type === 'function_call_output') {
242
- // { type: "function_call_output", call_id, output }
403
+ // { type: "function_call_output", call_id, output: string | array of content blocks }
404
+ let outputContent = it.output ?? '';
405
+ // Normalize Responses content blocks to Anthropic-compatible format
406
+ if (Array.isArray(outputContent)) {
407
+ outputContent = outputContent.map((block) => {
408
+ if (block.type === 'input_text') {
409
+ return { type: 'text', text: block.text };
410
+ }
411
+ if (block.type === 'output_text') {
412
+ return { type: 'text', text: block.text };
413
+ }
414
+ if (block.type === 'input_image') {
415
+ const imageUrl = block.image_url;
416
+ if (imageUrl) {
417
+ return { type: 'image', source: { type: 'url', url: imageUrl } };
418
+ }
419
+ return { type: 'text', text: '[image]' };
420
+ }
421
+ return block;
422
+ });
423
+ }
243
424
  messages.push({
244
425
  role: 'tool',
245
426
  tool_call_id: it.call_id,
246
- content: it.output ?? '',
427
+ content: outputContent,
428
+ });
429
+ }
430
+ else if (it.type === 'computer_call_output') {
431
+ // { type: "computer_call_output", call_id, output: { type: "computer_screenshot", image_url } }
432
+ const output = it.output;
433
+ const imageUrl = output?.image_url;
434
+ const fileId = output?.file_id;
435
+ const content = imageUrl
436
+ ? [{ type: 'image', source: { type: 'url', url: imageUrl } }]
437
+ : fileId
438
+ ? [{ type: 'text', text: '[screenshot from file_id]' }]
439
+ : '';
440
+ messages.push({
441
+ role: 'tool',
442
+ tool_call_id: it.call_id,
443
+ content,
247
444
  });
248
445
  }
249
446
  else if (it.type === 'item_reference') {
@@ -295,8 +492,69 @@ function convertMessagesToResponsesInput(messages) {
295
492
  input.push({ type: 'message', role: 'system', content: m.content });
296
493
  }
297
494
  else {
298
- // user, developer, etc.
299
- input.push({ type: 'message', role: m.role ?? 'user', content: m.content });
495
+ // Check for Anthropic tool_result blocks in user message content array
496
+ const content = m.content;
497
+ if (m.role === 'user' && Array.isArray(content)) {
498
+ const blocks = content;
499
+ const toolResults = blocks.filter((b) => b.type === 'tool_result');
500
+ const otherBlocks = blocks.filter((b) => b.type !== 'tool_result');
501
+ // Emit computer_call_output for tool_results with image content
502
+ for (const tr of toolResults) {
503
+ const trContent = tr.content;
504
+ let imageUrl;
505
+ let fileId;
506
+ if (Array.isArray(trContent)) {
507
+ const imgBlock = trContent.find((b) => b.type === 'image');
508
+ if (imgBlock) {
509
+ const src = imgBlock.source;
510
+ if (src?.type === 'url') {
511
+ imageUrl = src.url;
512
+ }
513
+ else {
514
+ fileId = imgBlock.file_id;
515
+ }
516
+ }
517
+ }
518
+ if (imageUrl) {
519
+ input.push({
520
+ type: 'computer_call_output',
521
+ call_id: tr.tool_use_id,
522
+ output: { type: 'computer_screenshot', image_url: imageUrl },
523
+ });
524
+ }
525
+ else if (fileId) {
526
+ input.push({
527
+ type: 'computer_call_output',
528
+ call_id: tr.tool_use_id,
529
+ output: { type: 'computer_screenshot', file_id: fileId },
530
+ });
531
+ }
532
+ else {
533
+ // tool_result without image → function_call_output
534
+ input.push({
535
+ type: 'function_call_output',
536
+ call_id: tr.tool_use_id,
537
+ output: typeof trContent === 'string' ? trContent : JSON.stringify(trContent),
538
+ });
539
+ }
540
+ }
541
+ // Emit remaining non-tool_result blocks as message items
542
+ if (otherBlocks.length > 0) {
543
+ const textBlocks = otherBlocks.filter((b) => b.type === 'text' || b.type === 'input_text');
544
+ const text = textBlocks.map((b) => b.text ?? '').join('');
545
+ if (text || otherBlocks.length !== textBlocks.length) {
546
+ input.push({
547
+ type: 'message',
548
+ role: m.role ?? 'user',
549
+ content: otherBlocks,
550
+ });
551
+ }
552
+ }
553
+ }
554
+ else {
555
+ // user, developer, etc. (non-Anthropic format)
556
+ input.push({ type: 'message', role: m.role ?? 'user', content: m.content });
557
+ }
300
558
  }
301
559
  }
302
560
  return input;
@@ -378,7 +636,9 @@ function convertMessagesToAnthropic(messages) {
378
636
  toolResults.push({
379
637
  type: 'tool_result',
380
638
  tool_use_id: cur.tool_call_id,
381
- content: typeof cur.content === 'string' ? cur.content : JSON.stringify(cur.content),
639
+ content: typeof cur.content === 'string' || Array.isArray(cur.content)
640
+ ? cur.content
641
+ : JSON.stringify(cur.content),
382
642
  });
383
643
  i++;
384
644
  }
@@ -503,13 +763,52 @@ function convertMessagesToOpenAI(messages) {
503
763
  });
504
764
  }
505
765
  // Emit remaining user content if any
766
+ // Convert Anthropic image blocks → OpenAI image_url format
506
767
  if (otherBlocks.length > 0) {
507
- const text = otherBlocks.map((b) => b.text ?? '').join('');
508
- result.push({ role: 'user', content: text });
768
+ const parts = otherBlocks.map((b) => {
769
+ if (b.type === 'image' && b.source) {
770
+ const source = b.source;
771
+ const url = source.url || source.data;
772
+ return {
773
+ type: 'image_url',
774
+ image_url: { url: url, ...(source.media_type ? {} : {}) },
775
+ };
776
+ }
777
+ if (b.type === 'text')
778
+ return { type: 'text', text: b.text };
779
+ return b;
780
+ });
781
+ // If single text part, collapse to string
782
+ if (parts.length === 1 && parts[0].type === 'text') {
783
+ result.push({ role: 'user', content: parts[0].text });
784
+ }
785
+ else {
786
+ result.push({ role: 'user', content: parts });
787
+ }
509
788
  }
510
789
  continue;
511
790
  }
512
791
  }
792
+ // Handle tool messages with array content (e.g., computer_call_output screenshots)
793
+ // Convert image blocks → text for models that don't support image_url in tool messages
794
+ if (m.role === 'tool' && Array.isArray(m.content)) {
795
+ const blocks = m.content;
796
+ const textParts = [];
797
+ for (const b of blocks) {
798
+ if (b.type === 'text') {
799
+ textParts.push(b.text);
800
+ }
801
+ else if (b.type === 'image') {
802
+ const source = b.source;
803
+ if (source?.url)
804
+ textParts.push(`[image: ${source.url}]`);
805
+ else
806
+ textParts.push('[image]');
807
+ }
808
+ }
809
+ result.push({ role: 'tool', tool_call_id: m.tool_call_id, content: textParts.join('\n') || '[output]' });
810
+ continue;
811
+ }
513
812
  // developer role → system (older Chat Completions APIs don't support "developer")
514
813
  if (m.role === 'developer') {
515
814
  result.push({ role: 'system', content: m.content });
@@ -723,6 +1022,32 @@ export async function transformInboundRequest(inboundType, route, body, logger)
723
1022
  : inboundType === 'openai'
724
1023
  ? extractFullOpenAI(body)
725
1024
  : extractFullAnthropic(body);
1025
+ // Strip Codex-internal MCP probe tools BEFORE any builder sees them.
1026
+ // These tools trigger MCP server calls (resources/list, resources/read, etc.) when
1027
+ // returned as function_calls. They are generated by Codex for Responses API's server-side
1028
+ // MCP handling and don't work with non-Responses upstreams.
1029
+ //
1030
+ // NOTE: namespace tools (mcp__computer_use__ etc.) are NOT stripped here.
1031
+ // They are flattened to function tools in convertToolsToOpenAI (like CCX's namespaceToolsToOpenAI).
1032
+ //
1033
+ // NOTE: exec_command is Codex's built-in bash execution tool and should NOT be stripped.
1034
+ if (params.tools && inboundType === 'openai-responses') {
1035
+ const mcpPrefixes = ['list_mcp_', 'read_mcp_', 'write_mcp_', 'subscribe_mcp_'];
1036
+ params.tools = params.tools.filter((t) => {
1037
+ if (typeof t === 'string')
1038
+ return true;
1039
+ const item = t;
1040
+ // Check by tool name AND nested function name (Chat format)
1041
+ const itemName = String(item.name ?? item.function?.name ?? '');
1042
+ if (mcpPrefixes.some((p) => itemName.startsWith(p)))
1043
+ return false;
1044
+ return true;
1045
+ });
1046
+ // Strip only by name — type-based stripping stays in convertToolsToOpenAI
1047
+ // (computer_use_preview is valid for Anthropic path, dropped only for Chat path)
1048
+ if (params.tools.length === 0)
1049
+ delete params.tools;
1050
+ }
726
1051
  params.model = route.modelId;
727
1052
  // max_tokens: 0 → undefined(不传,让 builder 走默认值), 应用路由级默认值
728
1053
  if (params.max_tokens === 0)
@@ -848,6 +1173,99 @@ function injectThinkingConfig(upstreamBody, route) {
848
1173
  }
849
1174
  }
850
1175
  }
1176
+ // --- Action mapping helpers (Computer Use) ---
1177
+ /** OpenAI ComputerAction → Anthropic tool_use input */
1178
+ export function convertActionToAnthropic(action) {
1179
+ const type = action.type;
1180
+ const result = { action: type };
1181
+ switch (type) {
1182
+ case 'click':
1183
+ case 'double_click':
1184
+ case 'drag':
1185
+ result.coordinate = [action.x, action.y];
1186
+ break;
1187
+ case 'move':
1188
+ result.action = 'mouse_move';
1189
+ result.coordinate = [action.x, action.y];
1190
+ break;
1191
+ case 'keypress':
1192
+ result.action = 'key';
1193
+ const keys = action.keys;
1194
+ result.text = keys ? keys.join('') : '';
1195
+ break;
1196
+ case 'scroll':
1197
+ result.coordinate = [action.x, action.y];
1198
+ result.scroll_x = action.scroll_x;
1199
+ result.scroll_y = action.scroll_y;
1200
+ break;
1201
+ case 'type':
1202
+ result.text = action.text ?? '';
1203
+ break;
1204
+ case 'wait':
1205
+ result.action = 'wait';
1206
+ result.duration = action.ms ?? action.duration ?? 0;
1207
+ break;
1208
+ case 'screenshot':
1209
+ break;
1210
+ default:
1211
+ // Pass through unknown actions as-is
1212
+ Object.assign(result, action);
1213
+ }
1214
+ return result;
1215
+ }
1216
+ /** Anthropic tool_use input → OpenAI ComputerAction */
1217
+ export function convertActionToOpenAI(input) {
1218
+ const action = input.action;
1219
+ const coord = input.coordinate;
1220
+ const result = {};
1221
+ switch (action) {
1222
+ case 'click':
1223
+ case 'double_click':
1224
+ case 'drag':
1225
+ result.type = action;
1226
+ if (coord) {
1227
+ result.x = coord[0];
1228
+ result.y = coord[1];
1229
+ }
1230
+ break;
1231
+ case 'mouse_move':
1232
+ result.type = 'move';
1233
+ if (coord) {
1234
+ result.x = coord[0];
1235
+ result.y = coord[1];
1236
+ }
1237
+ break;
1238
+ case 'key':
1239
+ result.type = 'keypress';
1240
+ result.keys = [input.text ?? ''];
1241
+ break;
1242
+ case 'scroll':
1243
+ result.type = 'scroll';
1244
+ if (coord) {
1245
+ result.x = coord[0];
1246
+ result.y = coord[1];
1247
+ }
1248
+ result.scroll_x = input.scroll_x;
1249
+ result.scroll_y = input.scroll_y;
1250
+ break;
1251
+ case 'type':
1252
+ result.type = 'type';
1253
+ result.text = input.text ?? '';
1254
+ break;
1255
+ case 'wait':
1256
+ result.type = 'wait';
1257
+ result.ms = input.duration ?? 0;
1258
+ break;
1259
+ case 'screenshot':
1260
+ result.type = 'screenshot';
1261
+ break;
1262
+ default:
1263
+ // Pass through unknown actions as-is
1264
+ result.type = action;
1265
+ Object.assign(result, input);
1266
+ }
1267
+ return result;
1268
+ }
851
1269
  // --- OpenAI Responses ↔ Anthropic response conversion ---
852
1270
  function mapResponsesStopReason(stop, hasToolCalls) {
853
1271
  if (hasToolCalls)
@@ -906,6 +1324,31 @@ export function convertOpenAIResponsesToAnthropic(responsesBody) {
906
1324
  });
907
1325
  stopReason = 'tool_use';
908
1326
  }
1327
+ else if (item.type === 'computer_call') {
1328
+ // OpenAI computer_call → Anthropic tool_use with name "computer"
1329
+ const action = item.action;
1330
+ content.push({
1331
+ type: 'tool_use',
1332
+ id: item.call_id ?? item.id,
1333
+ name: 'computer',
1334
+ input: action ? convertActionToAnthropic(action) : {},
1335
+ });
1336
+ stopReason = 'tool_use';
1337
+ }
1338
+ else if (['web_search_call', 'code_interpreter_call', 'file_search_call'].includes(item.type)) {
1339
+ // 忽略无 Anthropic 对应物的内置工具输出
1340
+ continue;
1341
+ }
1342
+ else if (item.type === 'reasoning') {
1343
+ // Standalone reasoning output item → thinking block
1344
+ const summary = item.summary;
1345
+ if (summary) {
1346
+ const reasonText = summary.map((s) => s.text ?? '').join('');
1347
+ if (reasonText) {
1348
+ content.push({ type: 'thinking', thinking: reasonText, signature: '' });
1349
+ }
1350
+ }
1351
+ }
909
1352
  }
910
1353
  }
911
1354
  const hasToolCalls = content.some((b) => b.type === 'tool_use');
@@ -941,24 +1384,45 @@ export function convertAnthropicResponseToOpenAIResponses(anthropicBody) {
941
1384
  thinkingText += block.thinking ?? '';
942
1385
  }
943
1386
  else if (block.type === 'tool_use') {
944
- output.push({
945
- type: 'function_call',
946
- id: `fc_${Date.now().toString(36)}_${block.id ?? ''}`,
947
- call_id: block.id,
948
- name: block.name ?? '',
949
- arguments: JSON.stringify(block.input ?? {}),
950
- });
1387
+ const name = block.name ?? '';
1388
+ if (name === 'computer') {
1389
+ // Computer use tool → computer_call output item
1390
+ const input = block.input ?? {};
1391
+ output.push({
1392
+ type: 'computer_call',
1393
+ id: `cc_${Date.now().toString(36)}_${block.id ?? ''}`,
1394
+ call_id: block.id,
1395
+ action: convertActionToOpenAI(input),
1396
+ pending_safety_checks: [],
1397
+ status: 'completed',
1398
+ });
1399
+ }
1400
+ else {
1401
+ // Regular tool_use → function_call
1402
+ // CCX always sets status: "completed" on function_call items
1403
+ output.push({
1404
+ type: 'function_call',
1405
+ id: `fc_${Date.now().toString(36)}_${block.id ?? ''}`,
1406
+ call_id: block.id,
1407
+ name,
1408
+ arguments: JSON.stringify(block.input ?? {}),
1409
+ status: 'completed',
1410
+ });
1411
+ }
951
1412
  }
952
1413
  }
953
1414
  }
954
- // Message output item goes first (before function_call items for correct ordering)
955
- output.unshift({
956
- type: 'message',
957
- id: `msg_${Date.now().toString(36)}`,
958
- status: stopReason === 'end_turn' ? 'completed' : stopReason === 'max_tokens' ? 'incomplete' : 'completed',
959
- role: 'assistant',
960
- content: outputMessageContent,
961
- });
1415
+ // Message output item goes first (before function_call/computer_call items)
1416
+ // CCX compatibility: only add message item when there's actual content
1417
+ if (outputMessageContent.length > 0) {
1418
+ output.unshift({
1419
+ type: 'message',
1420
+ id: `msg_${Date.now().toString(36)}`,
1421
+ status: stopReason === 'end_turn' ? 'completed' : stopReason === 'max_tokens' ? 'incomplete' : 'completed',
1422
+ role: 'assistant',
1423
+ content: outputMessageContent,
1424
+ });
1425
+ }
962
1426
  return {
963
1427
  id: `resp_${Date.now().toString(36)}`,
964
1428
  object: 'response',
@@ -1137,6 +1601,7 @@ export function convertOpenAIResponseToOpenAIResponses(chatBody) {
1137
1601
  call_id: tc.id,
1138
1602
  name: tc.function?.name ?? '',
1139
1603
  arguments: tc.function?.arguments ?? '',
1604
+ status: 'completed',
1140
1605
  });
1141
1606
  }
1142
1607
  }
@@ -1202,6 +1667,22 @@ export function convertOpenAIResponsesResponseToOpenAI(responsesBody) {
1202
1667
  },
1203
1668
  });
1204
1669
  }
1670
+ else if (item.type === 'computer_call') {
1671
+ // Computer call → Chat tool_calls (lossy conversion: serialize action as arguments)
1672
+ const action = item.action;
1673
+ toolCalls.push({
1674
+ id: item.call_id ?? item.id,
1675
+ type: 'function',
1676
+ function: {
1677
+ name: 'computer',
1678
+ arguments: JSON.stringify(action ?? {}),
1679
+ },
1680
+ });
1681
+ }
1682
+ else if (['web_search_call', 'code_interpreter_call', 'file_search_call'].includes(item.type)) {
1683
+ // 无 Chat 对应物 → 跳过
1684
+ continue;
1685
+ }
1205
1686
  }
1206
1687
  }
1207
1688
  const finishMap = { completed: 'stop', incomplete: 'length' };