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75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
/**
 * openai-handler.ts - OpenAI Chat Completions API 兼容处理器
 *
 * 将 OpenAI 格式请求转换为内部 Anthropic 格式,复用现有 Cursor 交互管道
 * 支持流式和非流式响应、工具调用、Cursor IDE Agent 模式
 */

import type { Request, Response } from 'express';
import { v4 as uuidv4 } from 'uuid';
import type {
    OpenAIChatRequest,
    OpenAIMessage,
    OpenAIChatCompletion,
    OpenAIChatCompletionChunk,
    OpenAIToolCall,
    OpenAIContentPart,
    OpenAITool,
} from './openai-types.js';
import type {
    AnthropicRequest,
    AnthropicMessage,
    AnthropicContentBlock,
    AnthropicTool,
    CursorChatRequest,
    CursorSSEEvent,
} from './types.js';
import { convertToCursorRequest, parseToolCalls, hasToolCalls } from './converter.js';
import { sendCursorRequest, sendCursorRequestFull } from './cursor-client.js';
import { getConfig } from './config.js';
import { createRequestLogger, type RequestLogger } from './logger.js';
import { createIncrementalTextStreamer, hasLeadingThinking, splitLeadingThinkingBlocks, stripThinkingTags } from './streaming-text.js';
import {
    autoContinueCursorToolResponseFull,
    autoContinueCursorToolResponseStream,
    isRefusal,
    sanitizeResponse,
    isIdentityProbe,
    isToolCapabilityQuestion,
    buildRetryRequest,
    extractThinking,
    CLAUDE_IDENTITY_RESPONSE,
    CLAUDE_TOOLS_RESPONSE,
    MAX_REFUSAL_RETRIES,
    estimateInputTokens,
} from './handler.js';

function chatId(): string {
    return 'chatcmpl-' + uuidv4().replace(/-/g, '').substring(0, 24);
}

function toolCallId(): string {
    return 'call_' + uuidv4().replace(/-/g, '').substring(0, 24);
}

class OpenAIRequestError extends Error {
    status: number;
    type: string;
    code: string;

    constructor(message: string, status = 400, type = 'invalid_request_error', code = 'invalid_request') {
        super(message);
        this.name = 'OpenAIRequestError';
        this.status = status;
        this.type = type;
        this.code = code;
    }
}

function stringifyUnknownContent(value: unknown): string {
    if (value === null || value === undefined) return '';
    if (typeof value === 'string') return value;
    if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
        return String(value);
    }
    try {
        return JSON.stringify(value);
    } catch {
        return String(value);
    }
}

function unsupportedImageFileError(fileId?: string): OpenAIRequestError {
    const suffix = fileId ? ` (file_id: ${fileId})` : '';
    return new OpenAIRequestError(
        `Unsupported content part: image_file${suffix}. This proxy does not support OpenAI Files API image references. Please send the image as image_url, input_image, data URI, or a local file path instead.`,
        400,
        'invalid_request_error',
        'unsupported_content_part'
    );
}

// ==================== 请求转换:OpenAI → Anthropic ====================

/**
 * 将 OpenAI Chat Completions 请求转换为内部 Anthropic 格式
 * 这样可以完全复用现有的 convertToCursorRequest 管道
 */
function convertToAnthropicRequest(body: OpenAIChatRequest): AnthropicRequest {
    const rawMessages: AnthropicMessage[] = [];
    let systemPrompt: string | undefined;

    // ★ response_format 处理:构建温和的 JSON 格式提示(稍后追加到最后一条用户消息)
    let jsonFormatSuffix = '';
    if (body.response_format && body.response_format.type !== 'text') {
        jsonFormatSuffix = '\n\nRespond in plain JSON format without markdown wrapping.';
        if (body.response_format.type === 'json_schema' && body.response_format.json_schema?.schema) {
            jsonFormatSuffix += ` Schema: ${JSON.stringify(body.response_format.json_schema.schema)}`;
        }
    }

    for (const msg of body.messages) {
        switch (msg.role) {
            case 'system':
                systemPrompt = (systemPrompt ? systemPrompt + '\n\n' : '') + extractOpenAIContent(msg);
                break;

            case 'user': {
                // 检查 content 数组中是否有 tool_result 类型的块(Anthropic 风格)
                const contentBlocks = extractOpenAIContentBlocks(msg);
                if (Array.isArray(contentBlocks)) {
                    rawMessages.push({ role: 'user', content: contentBlocks });
                } else {
                    rawMessages.push({ role: 'user', content: contentBlocks || '' });
                }
                break;
            }

            case 'assistant': {
                const blocks: AnthropicContentBlock[] = [];
                const contentBlocks = extractOpenAIContentBlocks(msg);
                if (typeof contentBlocks === 'string' && contentBlocks) {
                    blocks.push({ type: 'text', text: contentBlocks });
                } else if (Array.isArray(contentBlocks)) {
                    blocks.push(...contentBlocks);
                }

                if (msg.tool_calls && msg.tool_calls.length > 0) {
                    for (const tc of msg.tool_calls) {
                        let args: Record<string, unknown> = {};
                        try {
                            args = JSON.parse(tc.function.arguments);
                        } catch {
                            args = { input: tc.function.arguments };
                        }
                        blocks.push({
                            type: 'tool_use',
                            id: tc.id,
                            name: tc.function.name,
                            input: args,
                        });
                    }
                }

                rawMessages.push({
                    role: 'assistant',
                    content: blocks.length > 0 ? blocks : (typeof contentBlocks === 'string' ? contentBlocks : ''),
                });
                break;
            }

            case 'tool': {
                rawMessages.push({
                    role: 'user',
                    content: [{
                        type: 'tool_result',
                        tool_use_id: msg.tool_call_id,
                        content: extractOpenAIContent(msg),
                    }] as AnthropicContentBlock[],
                });
                break;
            }
        }
    }

    // 合并连续同角色消息(Anthropic API 要求 user/assistant 严格交替)
    const messages = mergeConsecutiveRoles(rawMessages);

    // ★ response_format: 追加 JSON 格式提示到最后一条 user 消息
    if (jsonFormatSuffix) {
        for (let i = messages.length - 1; i >= 0; i--) {
            if (messages[i].role === 'user') {
                const content = messages[i].content;
                if (typeof content === 'string') {
                    messages[i].content = content + jsonFormatSuffix;
                } else if (Array.isArray(content)) {
                    const lastTextBlock = [...content].reverse().find(b => b.type === 'text');
                    if (lastTextBlock && lastTextBlock.text) {
                        lastTextBlock.text += jsonFormatSuffix;
                    } else {
                        content.push({ type: 'text', text: jsonFormatSuffix.trim() });
                    }
                }
                break;
            }
        }
    }

    // 转换工具定义:支持 OpenAI 标准格式和 Cursor 扁平格式
    const tools: AnthropicTool[] | undefined = body.tools?.map((t: OpenAITool | Record<string, unknown>) => {
        // Cursor IDE 可能发送扁平格式:{ name, description, input_schema }
        if ('function' in t && t.function) {
            const fn = (t as OpenAITool).function;
            return {
                name: fn.name,
                description: fn.description,
                input_schema: fn.parameters || { type: 'object', properties: {} },
            };
        }
        // Cursor 扁平格式
        const flat = t as Record<string, unknown>;
        return {
            name: (flat.name as string) || '',
            description: flat.description as string | undefined,
            input_schema: (flat.input_schema as Record<string, unknown>) || { type: 'object', properties: {} },
        };
    });

    return {
        model: body.model,
        messages,
        max_tokens: Math.max(body.max_tokens || body.max_completion_tokens || 8192, 8192),
        stream: body.stream,
        system: systemPrompt,
        tools,
        temperature: body.temperature,
        top_p: body.top_p,
        stop_sequences: body.stop
            ? (Array.isArray(body.stop) ? body.stop : [body.stop])
            : undefined,
        // ★ Thinking 开关:config.yaml 优先级最高
        // enabled=true: 强制注入 thinking(即使客户端没请求)
        // enabled=false: 强制关闭 thinking
        // 未配置: 跟随客户端(模型名含 'thinking' 或传了 reasoning_effort 才注入)
        ...(() => {
            const tc = getConfig().thinking;
            if (tc && tc.enabled) return { thinking: { type: 'enabled' as const } };
            if (tc && !tc.enabled) return {};
            // 未配置 → 跟随客户端信号
            const modelHint = body.model?.toLowerCase().includes('thinking');
            const effortHint = !!(body as unknown as Record<string, unknown>).reasoning_effort;
            return (modelHint || effortHint) ? { thinking: { type: 'enabled' as const } } : {};
        })(),
    };
}

/**
 * 合并连续同角色的消息(Anthropic API 要求角色严格交替)
 */
function mergeConsecutiveRoles(messages: AnthropicMessage[]): AnthropicMessage[] {
    if (messages.length <= 1) return messages;

    const merged: AnthropicMessage[] = [];
    for (const msg of messages) {
        const last = merged[merged.length - 1];
        if (last && last.role === msg.role) {
            // 合并 content
            const lastBlocks = toBlocks(last.content);
            const newBlocks = toBlocks(msg.content);
            last.content = [...lastBlocks, ...newBlocks];
        } else {
            merged.push({ ...msg });
        }
    }
    return merged;
}

/**
 * 将 content 统一转为 AnthropicContentBlock 数组
 */
function toBlocks(content: string | AnthropicContentBlock[]): AnthropicContentBlock[] {
    if (typeof content === 'string') {
        return content ? [{ type: 'text', text: content }] : [];
    }
    return content || [];
}

/**
 * 从 OpenAI 消息中提取文本或多模态内容块
 * 处理多种客户端格式:
 *   - 文本块: { type: 'text'|'input_text', text: '...' }
 *   - OpenAI 标准: { type: 'image_url', image_url: { url: '...' } }
 *   - Anthropic 透传: { type: 'image', source: { type: 'url', url: '...' } }
 *   - 部分客户端: { type: 'input_image', image_url: { url: '...' } }
 */
function extractOpenAIContentBlocks(msg: OpenAIMessage): string | AnthropicContentBlock[] {
    if (msg.content === null || msg.content === undefined) return '';
    if (typeof msg.content === 'string') return msg.content;
    if (Array.isArray(msg.content)) {
        const blocks: AnthropicContentBlock[] = [];
        for (const p of msg.content as (OpenAIContentPart | Record<string, unknown>)[]) {
            if ((p.type === 'text' || p.type === 'input_text') && (p as OpenAIContentPart).text) {
                blocks.push({ type: 'text', text: (p as OpenAIContentPart).text! });
            } else if (p.type === 'image_url' && (p as OpenAIContentPart).image_url?.url) {
                const url = (p as OpenAIContentPart).image_url!.url;
                if (url.startsWith('data:')) {
                    const match = url.match(/^data:([^;]+);base64,(.+)$/);
                    if (match) {
                        blocks.push({
                            type: 'image',
                            source: { type: 'base64', media_type: match[1], data: match[2] }
                        });
                    }
                } else {
                    // HTTP(S)/local URL — 统一存储到 source.data,由 preprocessImages() 下载/读取
                    blocks.push({
                        type: 'image',
                        source: { type: 'url', media_type: 'image/jpeg', data: url }
                    });
                }
            } else if (p.type === 'image' && (p as any).source) {
                // ★ Anthropic 格式透传:某些客户端混合发送 OpenAI 和 Anthropic 格式
                const source = (p as any).source;
                const imageUrl = source.url || source.data;
                if (source.type === 'base64' && source.data) {
                    blocks.push({
                        type: 'image',
                        source: { type: 'base64', media_type: source.media_type || 'image/jpeg', data: source.data }
                    });
                } else if (imageUrl) {
                    if (imageUrl.startsWith('data:')) {
                        const match = imageUrl.match(/^data:([^;]+);base64,(.+)$/);
                        if (match) {
                            blocks.push({
                                type: 'image',
                                source: { type: 'base64', media_type: match[1], data: match[2] }
                            });
                        }
                    } else {
                        blocks.push({
                            type: 'image',
                            source: { type: 'url', media_type: source.media_type || 'image/jpeg', data: imageUrl }
                        });
                    }
                }
            } else if (p.type === 'input_image' && (p as any).image_url?.url) {
                // ★ input_image 类型:部分新版 API 客户端使用
                const url = (p as any).image_url.url;
                if (url.startsWith('data:')) {
                    const match = url.match(/^data:([^;]+);base64,(.+)$/);
                    if (match) {
                        blocks.push({
                            type: 'image',
                            source: { type: 'base64', media_type: match[1], data: match[2] }
                        });
                    }
                } else {
                    blocks.push({
                        type: 'image',
                        source: { type: 'url', media_type: 'image/jpeg', data: url }
                    });
                }
            } else if (p.type === 'image_file' && (p as any).image_file) {
                const fileId = (p as any).image_file.file_id as string | undefined;
                console.log(`[OpenAI] ⚠️ 收到不支持的 image_file 格式 (file_id: ${fileId || 'unknown'})`);
                throw unsupportedImageFileError(fileId);
            } else if ((p.type === 'image_url' || p.type === 'input_image') && (p as any).url) {
                // ★ 扁平 URL 格式:某些客户端将 url 直接放在顶层而非 image_url.url
                const url = (p as any).url as string;
                if (url.startsWith('data:')) {
                    const match = url.match(/^data:([^;]+);base64,(.+)$/);
                    if (match) {
                        blocks.push({
                            type: 'image',
                            source: { type: 'base64', media_type: match[1], data: match[2] }
                        });
                    }
                } else {
                    blocks.push({
                        type: 'image',
                        source: { type: 'url', media_type: 'image/jpeg', data: url }
                    });
                }
            } else if (p.type === 'tool_use') {
                // Anthropic 风格 tool_use 块直接透传
                blocks.push(p as unknown as AnthropicContentBlock);
            } else if (p.type === 'tool_result') {
                // Anthropic 风格 tool_result 块直接透传
                blocks.push(p as unknown as AnthropicContentBlock);
            } else {
                // ★ 通用兜底:检查未知类型的块是否包含可识别的图片数据
                const anyP = p as Record<string, unknown>;
                const possibleUrl = (anyP.url || anyP.file_path || anyP.path ||
                    (anyP.image_url as any)?.url || anyP.data) as string | undefined;
                if (possibleUrl && typeof possibleUrl === 'string') {
                    const looksLikeImage = /\.(jpg|jpeg|png|gif|webp|bmp|svg)/i.test(possibleUrl) ||
                        possibleUrl.startsWith('data:image/');
                    if (looksLikeImage) {
                        console.log(`[OpenAI] 🔄 未知内容类型 "${p.type}" 中检测到图片引用 → 转为 image block`);
                        if (possibleUrl.startsWith('data:')) {
                            const match = possibleUrl.match(/^data:([^;]+);base64,(.+)$/);
                            if (match) {
                                blocks.push({
                                    type: 'image',
                                    source: { type: 'base64', media_type: match[1], data: match[2] }
                                });
                            }
                        } else {
                            blocks.push({
                                type: 'image',
                                source: { type: 'url', media_type: 'image/jpeg', data: possibleUrl }
                            });
                        }
                    }
                }
            }
        }
        return blocks.length > 0 ? blocks : '';
    }
    return stringifyUnknownContent(msg.content);
}

/**
 * 仅提取纯文本(用于系统提示词和旧行为)
 */
function extractOpenAIContent(msg: OpenAIMessage): string {
    const blocks = extractOpenAIContentBlocks(msg);
    if (typeof blocks === 'string') return blocks;
    return blocks.filter(b => b.type === 'text').map(b => b.text).join('\n');
}

// ==================== 主处理入口 ====================

export async function handleOpenAIChatCompletions(req: Request, res: Response): Promise<void> {
    const body = req.body as OpenAIChatRequest;

    const log = createRequestLogger({
        method: req.method,
        path: req.path,
        model: body.model,
        stream: !!body.stream,
        hasTools: (body.tools?.length ?? 0) > 0,
        toolCount: body.tools?.length ?? 0,
        messageCount: body.messages?.length ?? 0,
        apiFormat: 'openai',
    });

    log.startPhase('receive', '接收请求');
    log.recordOriginalRequest(body);
    log.info('OpenAI', 'receive', `收到 OpenAI Chat 请求`, {
        model: body.model,
        messageCount: body.messages?.length,
        stream: body.stream,
        toolCount: body.tools?.length ?? 0,
    });

    // ★ 图片诊断日志:记录每条消息中的 content 格式,帮助定位客户端发送格式
    if (body.messages) {
        for (let i = 0; i < body.messages.length; i++) {
            const msg = body.messages[i];
            if (typeof msg.content === 'string') {
                // 检查字符串中是否包含图片路径特征
                if (/\.(jpg|jpeg|png|gif|webp|bmp|svg)/i.test(msg.content)) {
                    console.log(`[OpenAI] 📋 消息[${i}] role=${msg.role} content=字符串(${msg.content.length}chars) ⚠️ 包含图片后缀: ${msg.content.substring(0, 200)}`);
                }
            } else if (Array.isArray(msg.content)) {
                const types = (msg.content as any[]).map(p => {
                    if (p.type === 'image_url') return `image_url(${(p.image_url?.url || p.url || '?').substring(0, 60)})`;
                    if (p.type === 'image') return `image(${p.source?.type || '?'})`;
                    if (p.type === 'input_image') return `input_image`;
                    if (p.type === 'image_file') return `image_file`;
                    return p.type;
                });
                if (types.some(t => t !== 'text')) {
                    console.log(`[OpenAI] 📋 消息[${i}] role=${msg.role} blocks: [${types.join(', ')}]`);
                }
            }
        }
    }

    try {
        // Step 1: OpenAI → Anthropic 格式
        log.startPhase('convert', '格式转换 (OpenAI→Anthropic)');
        const anthropicReq = convertToAnthropicRequest(body);
        log.endPhase();

        // 注意:图片预处理已移入 convertToCursorRequest → preprocessImages() 统一处理

        // Step 1.6: 身份探针拦截(复用 Anthropic handler 的逻辑)
        if (isIdentityProbe(anthropicReq)) {
            log.intercepted('身份探针拦截 (OpenAI)');
            const mockText = "I am Claude, an advanced AI programming assistant created by Anthropic. I am ready to help you write code, debug, and answer your technical questions. Please let me know what we should work on!";
            if (body.stream) {
                return handleOpenAIMockStream(res, body, mockText);
            } else {
                return handleOpenAIMockNonStream(res, body, mockText);
            }
        }

        // Step 2: Anthropic → Cursor 格式(复用现有管道)
        const cursorReq = await convertToCursorRequest(anthropicReq);
        log.recordCursorRequest(cursorReq);

        if (body.stream) {
            await handleOpenAIStream(res, cursorReq, body, anthropicReq, log);
        } else {
            await handleOpenAINonStream(res, cursorReq, body, anthropicReq, log);
        }
    } catch (err: unknown) {
        const message = err instanceof Error ? err.message : String(err);
        log.fail(message);
        const status = err instanceof OpenAIRequestError ? err.status : 500;
        const type = err instanceof OpenAIRequestError ? err.type : 'server_error';
        const code = err instanceof OpenAIRequestError ? err.code : 'internal_error';
        res.status(status).json({
            error: {
                message,
                type,
                code,
            },
        });
    }
}

// ==================== 身份探针模拟响应 ====================

function handleOpenAIMockStream(res: Response, body: OpenAIChatRequest, mockText: string): void {
    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'X-Accel-Buffering': 'no',
    });
    const id = chatId();
    const created = Math.floor(Date.now() / 1000);
    writeOpenAISSE(res, {
        id, object: 'chat.completion.chunk', created, model: body.model,
        choices: [{ index: 0, delta: { role: 'assistant', content: mockText }, finish_reason: null }],
    });
    writeOpenAISSE(res, {
        id, object: 'chat.completion.chunk', created, model: body.model,
        choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
    });
    res.write('data: [DONE]\n\n');
    res.end();
}

function handleOpenAIMockNonStream(res: Response, body: OpenAIChatRequest, mockText: string): void {
    res.json({
        id: chatId(),
        object: 'chat.completion',
        created: Math.floor(Date.now() / 1000),
        model: body.model,
        choices: [{
            index: 0,
            message: { role: 'assistant', content: mockText },
            finish_reason: 'stop',
        }],
        usage: { prompt_tokens: 15, completion_tokens: 35, total_tokens: 50 },
    });
}

function writeOpenAITextDelta(
    res: Response,
    id: string,
    created: number,
    model: string,
    text: string,
): void {
    if (!text) return;
    writeOpenAISSE(res, {
        id,
        object: 'chat.completion.chunk',
        created,
        model,
        choices: [{
            index: 0,
            delta: { content: text },
            finish_reason: null,
        }],
    });
}

function buildOpenAIUsage(
    anthropicReq: AnthropicRequest,
    outputText: string,
): { prompt_tokens: number; completion_tokens: number; total_tokens: number } {
    const promptTokens = estimateInputTokens(anthropicReq);
    const completionTokens = Math.ceil(outputText.length / 3);
    return {
        prompt_tokens: promptTokens,
        completion_tokens: completionTokens,
        total_tokens: promptTokens + completionTokens,
    };
}

function writeOpenAIReasoningDelta(
    res: Response,
    id: string,
    created: number,
    model: string,
    reasoningContent: string,
): void {
    if (!reasoningContent) return;
    writeOpenAISSE(res, {
        id,
        object: 'chat.completion.chunk',
        created,
        model,
        choices: [{
            index: 0,
            delta: { reasoning_content: reasoningContent } as Record<string, unknown>,
            finish_reason: null,
        }],
    });
}

async function handleOpenAIIncrementalTextStream(
    res: Response,
    cursorReq: CursorChatRequest,
    body: OpenAIChatRequest,
    anthropicReq: AnthropicRequest,
    streamMeta: { id: string; created: number; model: string },
    log: RequestLogger,
): Promise<void> {
    let activeCursorReq = cursorReq;
    let retryCount = 0;
    const thinkingEnabled = anthropicReq.thinking?.type === 'enabled';
    let finalRawResponse = '';
    let finalVisibleText = '';
    let finalReasoningContent = '';
    let streamer = createIncrementalTextStreamer({
        transform: sanitizeResponse,
        isBlockedPrefix: (text) => isRefusal(text.substring(0, 300)),
    });
    let reasoningSent = false;

    const executeAttempt = async (): Promise<{
        rawResponse: string;
        visibleText: string;
        reasoningContent: string;
        streamer: ReturnType<typeof createIncrementalTextStreamer>;
    }> => {
        let rawResponse = '';
        let visibleText = '';
        let leadingBuffer = '';
        let leadingResolved = false;
        let reasoningContent = '';
        const attemptStreamer = createIncrementalTextStreamer({
            transform: sanitizeResponse,
            isBlockedPrefix: (text) => isRefusal(text.substring(0, 300)),
        });

        const flushVisible = (chunk: string): void => {
            if (!chunk) return;
            visibleText += chunk;
            const delta = attemptStreamer.push(chunk);
            if (!delta) return;

            if (thinkingEnabled && reasoningContent && !reasoningSent) {
                writeOpenAIReasoningDelta(res, streamMeta.id, streamMeta.created, streamMeta.model, reasoningContent);
                reasoningSent = true;
            }
            writeOpenAITextDelta(res, streamMeta.id, streamMeta.created, streamMeta.model, delta);
        };

        await sendCursorRequest(activeCursorReq, (event: CursorSSEEvent) => {
            if (event.type !== 'text-delta' || !event.delta) return;

            rawResponse += event.delta;

            if (!leadingResolved) {
                leadingBuffer += event.delta;
                const split = splitLeadingThinkingBlocks(leadingBuffer);

                if (split.startedWithThinking) {
                    if (!split.complete) return;
                    reasoningContent = split.thinkingContent;
                    leadingResolved = true;
                    leadingBuffer = '';
                    flushVisible(split.remainder);
                    return;
                }

                leadingResolved = true;
                const buffered = leadingBuffer;
                leadingBuffer = '';
                flushVisible(buffered);
                return;
            }

            flushVisible(event.delta);
        });

        return {
            rawResponse,
            visibleText,
            reasoningContent,
            streamer: attemptStreamer,
        };
    };

    while (true) {
        const attempt = await executeAttempt();
        finalRawResponse = attempt.rawResponse;
        finalVisibleText = attempt.visibleText;
        finalReasoningContent = attempt.reasoningContent;
        streamer = attempt.streamer;

        const textForRefusalCheck = finalVisibleText;

        if (!streamer.hasSentText() && isRefusal(textForRefusalCheck) && retryCount < MAX_REFUSAL_RETRIES) {
            retryCount++;
            const retryBody = buildRetryRequest(anthropicReq, retryCount - 1);
            activeCursorReq = await convertToCursorRequest(retryBody);
            reasoningSent = false;
            continue;
        }

        break;
    }

    const refusalText = finalVisibleText;
    const usedFallback = !streamer.hasSentText() && isRefusal(refusalText);

    let finalTextToSend: string;
    if (usedFallback) {
        finalTextToSend = isToolCapabilityQuestion(anthropicReq)
            ? CLAUDE_TOOLS_RESPONSE
            : CLAUDE_IDENTITY_RESPONSE;
    } else {
        finalTextToSend = streamer.finish();
    }

    if (!usedFallback && thinkingEnabled && finalReasoningContent && !reasoningSent) {
        writeOpenAIReasoningDelta(res, streamMeta.id, streamMeta.created, streamMeta.model, finalReasoningContent);
        reasoningSent = true;
    }

    writeOpenAITextDelta(res, streamMeta.id, streamMeta.created, streamMeta.model, finalTextToSend);

    writeOpenAISSE(res, {
        id: streamMeta.id,
        object: 'chat.completion.chunk',
        created: streamMeta.created,
        model: streamMeta.model,
        choices: [{
            index: 0,
            delta: {},
            finish_reason: 'stop',
        }],
        usage: buildOpenAIUsage(anthropicReq, streamer.hasSentText() ? (finalVisibleText || finalRawResponse) : finalTextToSend),
    });

    log.recordRawResponse(finalRawResponse);
    if (finalReasoningContent) {
        log.recordThinking(finalReasoningContent);
    }
    const finalRecordedResponse = streamer.hasSentText()
        ? sanitizeResponse(finalVisibleText || finalRawResponse)
        : finalTextToSend;
    log.recordFinalResponse(finalRecordedResponse);
    log.complete(finalRecordedResponse.length, 'stop');

    res.write('data: [DONE]\n\n');
    res.end();
}

// ==================== 流式处理(OpenAI SSE 格式) ====================

async function handleOpenAIStream(
    res: Response,
    cursorReq: CursorChatRequest,
    body: OpenAIChatRequest,
    anthropicReq: AnthropicRequest,
    log: RequestLogger,
): Promise<void> {
    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'X-Accel-Buffering': 'no',
    });

    const id = chatId();
    const created = Math.floor(Date.now() / 1000);
    const model = body.model;
    const hasTools = (body.tools?.length ?? 0) > 0;

    // 发送 role delta
    writeOpenAISSE(res, {
        id, object: 'chat.completion.chunk', created, model,
        choices: [{
            index: 0,
            delta: { role: 'assistant', content: '' },
            finish_reason: null,
        }],
    });

    let fullResponse = '';
    let sentText = '';
    let activeCursorReq = cursorReq;
    let retryCount = 0;

    // 统一缓冲模式:先缓冲全部响应,再检测拒绝和处理
    const executeStream = async (onTextDelta?: (delta: string) => void) => {
        fullResponse = '';
        await sendCursorRequest(activeCursorReq, (event: CursorSSEEvent) => {
            if (event.type !== 'text-delta' || !event.delta) return;
            fullResponse += event.delta;
            onTextDelta?.(event.delta);
        });
    };

    try {
        if (!hasTools && (!body.response_format || body.response_format.type === 'text')) {
            await handleOpenAIIncrementalTextStream(res, cursorReq, body, anthropicReq, { id, created, model }, log);
            return;
        }

        // ★ 混合流式:文本增量 + 工具缓冲(与 Anthropic handler 同一设计)
        const thinkingEnabled = anthropicReq.thinking?.type === 'enabled';
        const hybridStreamer = createIncrementalTextStreamer({
            warmupChars: 300,   // ★ 与拒绝检测窗口对齐
            transform: sanitizeResponse,
            isBlockedPrefix: (text) => isRefusal(text.substring(0, 300)),
        });
        let toolMarkerDetected = false;
        let pendingText = '';
        let hybridThinkingContent = '';
        let hybridLeadingBuffer = '';
        let hybridLeadingResolved = false;
        const TOOL_MARKER = '```json action';
        const MARKER_LOOKBACK = TOOL_MARKER.length + 2;
        let hybridTextSent = false;
        let hybridReasoningSent = false;

        const pushToStreamer = (text: string): void => {
            if (!text || toolMarkerDetected) return;
            pendingText += text;
            const idx = pendingText.indexOf(TOOL_MARKER);
            if (idx >= 0) {
                const before = pendingText.substring(0, idx);
                if (before) {
                    const d = hybridStreamer.push(before);
                    if (d) {
                        if (thinkingEnabled && hybridThinkingContent && !hybridReasoningSent) {
                            writeOpenAIReasoningDelta(res, id, created, model, hybridThinkingContent);
                            hybridReasoningSent = true;
                        }
                        writeOpenAITextDelta(res, id, created, model, d);
                        hybridTextSent = true;
                    }
                }
                toolMarkerDetected = true;
                pendingText = '';
                return;
            }
            const safeEnd = pendingText.length - MARKER_LOOKBACK;
            if (safeEnd > 0) {
                const safe = pendingText.substring(0, safeEnd);
                pendingText = pendingText.substring(safeEnd);
                const d = hybridStreamer.push(safe);
                if (d) {
                    if (thinkingEnabled && hybridThinkingContent && !hybridReasoningSent) {
                        writeOpenAIReasoningDelta(res, id, created, model, hybridThinkingContent);
                        hybridReasoningSent = true;
                    }
                    writeOpenAITextDelta(res, id, created, model, d);
                    hybridTextSent = true;
                }
            }
        };

        const processHybridDelta = (delta: string): void => {
            if (!hybridLeadingResolved) {
                hybridLeadingBuffer += delta;
                const split = splitLeadingThinkingBlocks(hybridLeadingBuffer);
                if (split.startedWithThinking) {
                    if (!split.complete) return;
                    hybridThinkingContent = split.thinkingContent;
                    hybridLeadingResolved = true;
                    hybridLeadingBuffer = '';
                    pushToStreamer(split.remainder);
                    return;
                }
                if (hybridLeadingBuffer.trimStart().length < 10) return;
                hybridLeadingResolved = true;
                const buffered = hybridLeadingBuffer;
                hybridLeadingBuffer = '';
                pushToStreamer(buffered);
                return;
            }
            pushToStreamer(delta);
        };

        await executeStream(processHybridDelta);

        // flush 残留缓冲
        if (!hybridLeadingResolved && hybridLeadingBuffer) {
            hybridLeadingResolved = true;
            const split = splitLeadingThinkingBlocks(hybridLeadingBuffer);
            if (split.startedWithThinking && split.complete) {
                hybridThinkingContent = split.thinkingContent;
                pushToStreamer(split.remainder);
            } else {
                pushToStreamer(hybridLeadingBuffer);
            }
        }
        if (pendingText && !toolMarkerDetected) {
            const d = hybridStreamer.push(pendingText);
            if (d) {
                if (thinkingEnabled && hybridThinkingContent && !hybridReasoningSent) {
                    writeOpenAIReasoningDelta(res, id, created, model, hybridThinkingContent);
                    hybridReasoningSent = true;
                }
                writeOpenAITextDelta(res, id, created, model, d);
                hybridTextSent = true;
            }
            pendingText = '';
        }
        const hybridRemaining = hybridStreamer.finish();
        if (hybridRemaining) {
            if (thinkingEnabled && hybridThinkingContent && !hybridReasoningSent) {
                writeOpenAIReasoningDelta(res, id, created, model, hybridThinkingContent);
                hybridReasoningSent = true;
            }
            writeOpenAITextDelta(res, id, created, model, hybridRemaining);
            hybridTextSent = true;
        }

        // ★ Thinking 提取(在拒绝检测之前)
        let reasoningContent: string | undefined = hybridThinkingContent || undefined;
        if (hasLeadingThinking(fullResponse)) {
            const { thinkingContent: extracted, strippedText } = extractThinking(fullResponse);
            if (extracted) {
                if (thinkingEnabled && !reasoningContent) {
                    reasoningContent = extracted;
                }
                fullResponse = strippedText;
            }
        }

        // 拒绝检测 + 自动重试
        const shouldRetryRefusal = () => {
            if (hybridTextSent) return false;  // 已发文字,不可重试
            if (!isRefusal(fullResponse)) return false;
            if (hasTools && hasToolCalls(fullResponse)) return false;
            return true;
        };

        while (shouldRetryRefusal() && retryCount < MAX_REFUSAL_RETRIES) {
            retryCount++;
            const retryBody = buildRetryRequest(anthropicReq, retryCount - 1);
            activeCursorReq = await convertToCursorRequest(retryBody);
            await executeStream();  // 重试不传回调
        }
        if (shouldRetryRefusal()) {
            if (!hasTools) {
                if (isToolCapabilityQuestion(anthropicReq)) {
                    fullResponse = CLAUDE_TOOLS_RESPONSE;
                } else {
                    fullResponse = CLAUDE_IDENTITY_RESPONSE;
                }
            } else {
                fullResponse = 'I understand the request. Let me analyze the information and proceed with the appropriate action.';
            }
        }

        // 极短响应重试
        if (hasTools && fullResponse.trim().length < 10 && retryCount < MAX_REFUSAL_RETRIES) {
            retryCount++;
            activeCursorReq = await convertToCursorRequest(anthropicReq);
            await executeStream();
        }

        if (hasTools) {
            fullResponse = await autoContinueCursorToolResponseStream(activeCursorReq, fullResponse, hasTools);
        }

        let finishReason: 'stop' | 'tool_calls' = 'stop';

        // ★ 发送 reasoning_content(仅在混合流式未发送时)
        if (reasoningContent && !hybridReasoningSent) {
            writeOpenAISSE(res, {
                id, object: 'chat.completion.chunk', created, model,
                choices: [{
                    index: 0,
                    delta: { reasoning_content: reasoningContent } as Record<string, unknown>,
                    finish_reason: null,
                }],
            });
        }

        if (hasTools && hasToolCalls(fullResponse)) {
            const { toolCalls, cleanText } = parseToolCalls(fullResponse);

            if (toolCalls.length > 0) {
                finishReason = 'tool_calls';
                log.recordToolCalls(toolCalls);
                log.updateSummary({ toolCallsDetected: toolCalls.length });

                // 发送工具调用前的残余文本 — 如果混合流式已发送则跳过
                if (!hybridTextSent) {
                    let cleanOutput = isRefusal(cleanText) ? '' : cleanText;
                    cleanOutput = sanitizeResponse(cleanOutput);
                    if (cleanOutput) {
                        writeOpenAISSE(res, {
                            id, object: 'chat.completion.chunk', created, model,
                            choices: [{
                                index: 0,
                                delta: { content: cleanOutput },
                                finish_reason: null,
                            }],
                        });
                    }
                }

                // 增量流式发送工具调用:先发 name+id,再分块发 arguments
                for (let i = 0; i < toolCalls.length; i++) {
                    const tc = toolCalls[i];
                    const tcId = toolCallId();
                    const argsStr = JSON.stringify(tc.arguments);

                    // 第一帧:发送 name + id, arguments 为空
                    writeOpenAISSE(res, {
                        id, object: 'chat.completion.chunk', created, model,
                        choices: [{
                            index: 0,
                            delta: {
                                ...(i === 0 ? { content: null } : {}),
                                tool_calls: [{
                                    index: i,
                                    id: tcId,
                                    type: 'function',
                                    function: { name: tc.name, arguments: '' },
                                }],
                            },
                            finish_reason: null,
                        }],
                    });

                    // 后续帧:分块发送 arguments (128 字节/帧)
                    const CHUNK_SIZE = 128;
                    for (let j = 0; j < argsStr.length; j += CHUNK_SIZE) {
                        writeOpenAISSE(res, {
                            id, object: 'chat.completion.chunk', created, model,
                            choices: [{
                                index: 0,
                                delta: {
                                    tool_calls: [{
                                        index: i,
                                        function: { arguments: argsStr.slice(j, j + CHUNK_SIZE) },
                                    }],
                                },
                                finish_reason: null,
                            }],
                        });
                    }
                }
            } else {
                // 误报:发送清洗后的文本(如果混合流式未发送)
                if (!hybridTextSent) {
                    let textToSend = fullResponse;
                    if (isRefusal(fullResponse)) {
                        textToSend = 'I understand the request. Let me proceed with the appropriate action. Could you clarify what specific task you would like me to perform?';
                    } else {
                        textToSend = sanitizeResponse(fullResponse);
                    }
                    writeOpenAISSE(res, {
                        id, object: 'chat.completion.chunk', created, model,
                        choices: [{
                            index: 0,
                            delta: { content: textToSend },
                            finish_reason: null,
                        }],
                    });
                }
            }
        } else {
            // 无工具模式或无工具调用 — 如果混合流式未发送则统一清洗后发送
            if (!hybridTextSent) {
                let sanitized = sanitizeResponse(fullResponse);
                // ★ response_format 后处理:剥离 markdown 代码块包裹
                if (body.response_format && body.response_format.type !== 'text') {
                    sanitized = stripMarkdownJsonWrapper(sanitized);
                }
                if (sanitized) {
                    writeOpenAISSE(res, {
                        id, object: 'chat.completion.chunk', created, model,
                        choices: [{
                            index: 0,
                            delta: { content: sanitized },
                            finish_reason: null,
                        }],
                    });
                }
            }
        }

        // 发送完成 chunk(带 usage,兼容依赖最终 usage 帧的 OpenAI 客户端/代理)
        writeOpenAISSE(res, {
            id, object: 'chat.completion.chunk', created, model,
            choices: [{
                index: 0,
                delta: {},
                finish_reason: finishReason,
            }],
            usage: buildOpenAIUsage(anthropicReq, fullResponse),
        });

        log.recordRawResponse(fullResponse);
        if (reasoningContent) {
            log.recordThinking(reasoningContent);
        }
        log.recordFinalResponse(fullResponse);
        log.complete(fullResponse.length, finishReason);

        res.write('data: [DONE]\n\n');

    } catch (err: unknown) {
        const message = err instanceof Error ? err.message : String(err);
        log.fail(message);
        writeOpenAISSE(res, {
            id, object: 'chat.completion.chunk', created, model,
            choices: [{
                index: 0,
                delta: { content: `\n\n[Error: ${message}]` },
                finish_reason: 'stop',
            }],
        });
        res.write('data: [DONE]\n\n');
    }

    res.end();
}

// ==================== 非流式处理 ====================

async function handleOpenAINonStream(
    res: Response,
    cursorReq: CursorChatRequest,
    body: OpenAIChatRequest,
    anthropicReq: AnthropicRequest,
    log: RequestLogger,
): Promise<void> {
    let activeCursorReq = cursorReq;
    let fullText = await sendCursorRequestFull(activeCursorReq);
    const hasTools = (body.tools?.length ?? 0) > 0;

    // 日志记录在详细日志中

    // ★ Thinking 提取必须在拒绝检测之前 — 否则 thinking 内容中的关键词会触发 isRefusal 误判
    const thinkingEnabled = anthropicReq.thinking?.type === 'enabled';
    let reasoningContent: string | undefined;
    if (hasLeadingThinking(fullText)) {
        const { thinkingContent: extracted, strippedText } = extractThinking(fullText);
        if (extracted) {
            if (thinkingEnabled) {
                reasoningContent = extracted;
            }
            // thinking 剥离记录
            fullText = strippedText;
        }
    }

    // 拒绝检测 + 自动重试(在 thinking 提取之后,只检测实际输出内容)
    const shouldRetry = () => isRefusal(fullText) && !(hasTools && hasToolCalls(fullText));

    if (shouldRetry()) {
        for (let attempt = 0; attempt < MAX_REFUSAL_RETRIES; attempt++) {
            // 重试记录
            const retryBody = buildRetryRequest(anthropicReq, attempt);
            const retryCursorReq = await convertToCursorRequest(retryBody);
            activeCursorReq = retryCursorReq;
            fullText = await sendCursorRequestFull(activeCursorReq);
            // 重试响应也需要先剥离 thinking
            if (hasLeadingThinking(fullText)) {
                fullText = extractThinking(fullText).strippedText;
            }
            if (!shouldRetry()) break;
        }
        if (shouldRetry()) {
            if (hasTools) {
                // 记录在详细日志
                fullText = 'I understand the request. Let me analyze the information and proceed with the appropriate action.';
            } else if (isToolCapabilityQuestion(anthropicReq)) {
                // 记录在详细日志
                fullText = CLAUDE_TOOLS_RESPONSE;
            } else {
                // 记录在详细日志
                fullText = CLAUDE_IDENTITY_RESPONSE;
            }
        }
    }

    if (hasTools) {
        fullText = await autoContinueCursorToolResponseFull(activeCursorReq, fullText, hasTools);
    }

    let content: string | null = fullText;
    let toolCalls: OpenAIToolCall[] | undefined;
    let finishReason: 'stop' | 'tool_calls' = 'stop';

    if (hasTools) {
        const parsed = parseToolCalls(fullText);

        if (parsed.toolCalls.length > 0) {
            finishReason = 'tool_calls';
            log.recordToolCalls(parsed.toolCalls);
            log.updateSummary({ toolCallsDetected: parsed.toolCalls.length });
            // 清洗拒绝文本
            let cleanText = parsed.cleanText;
            if (isRefusal(cleanText)) {
                // 记录在详细日志
                cleanText = '';
            }
            content = sanitizeResponse(cleanText) || null;

            toolCalls = parsed.toolCalls.map(tc => ({
                id: toolCallId(),
                type: 'function' as const,
                function: {
                    name: tc.name,
                    arguments: JSON.stringify(tc.arguments),
                },
            }));
        } else {
            // 无工具调用,检查拒绝
            if (isRefusal(fullText)) {
                content = 'I understand the request. Let me proceed with the appropriate action. Could you clarify what specific task you would like me to perform?';
            } else {
                content = sanitizeResponse(fullText);
            }
        }
    } else {
        // 无工具模式:清洗响应
        content = sanitizeResponse(fullText);
        // ★ response_format 后处理:剥离 markdown 代码块包裹
        if (body.response_format && body.response_format.type !== 'text' && content) {
            content = stripMarkdownJsonWrapper(content);
        }
    }

    const response: OpenAIChatCompletion = {
        id: chatId(),
        object: 'chat.completion',
        created: Math.floor(Date.now() / 1000),
        model: body.model,
        choices: [{
            index: 0,
            message: {
                role: 'assistant',
                content,
                ...(toolCalls ? { tool_calls: toolCalls } : {}),
                ...(reasoningContent ? { reasoning_content: reasoningContent } as Record<string, unknown> : {}),
            },
            finish_reason: finishReason,
        }],
        usage: buildOpenAIUsage(anthropicReq, fullText),
    };

    res.json(response);

    log.recordRawResponse(fullText);
    if (reasoningContent) {
        log.recordThinking(reasoningContent);
    }
    log.recordFinalResponse(fullText);
    log.complete(fullText.length, finishReason);
}

// ==================== 工具函数 ====================

/**
 * 剥离 Markdown 代码块包裹,返回裸 JSON 字符串
 * 处理 ```json\n...\n``` 和 ```\n...\n``` 两种格式
 */
function stripMarkdownJsonWrapper(text: string): string {
    if (!text) return text;
    const trimmed = text.trim();
    const match = trimmed.match(/^```(?:json)?\s*\n([\s\S]*?)\n\s*```$/);
    if (match) {
        return match[1].trim();
    }
    return text;
}

function writeOpenAISSE(res: Response, data: OpenAIChatCompletionChunk): void {
    res.write(`data: ${JSON.stringify(data)}\n\n`);
    if (typeof (res as unknown as { flush: () => void }).flush === 'function') {
        (res as unknown as { flush: () => void }).flush();
    }
}

// ==================== /v1/responses 支持 ====================

/**
 * 写入 Responses API SSE 事件
 * 格式:event: {eventType}\ndata: {json}\n\n
 * 注意:与 Chat Completions 的 "data: {json}\n\n" 不同,Responses API 需要 event: 前缀
 */
function writeResponsesSSE(res: Response, eventType: string, data: Record<string, unknown>): void {
    res.write(`event: ${eventType}\ndata: ${JSON.stringify(data)}\n\n`);
    if (typeof (res as unknown as { flush: () => void }).flush === 'function') {
        (res as unknown as { flush: () => void }).flush();
    }
}

function responsesId(): string {
    return 'resp_' + uuidv4().replace(/-/g, '').substring(0, 24);
}

function responsesItemId(): string {
    return 'item_' + uuidv4().replace(/-/g, '').substring(0, 24);
}

/**
 * 构建 Responses API 的 response 对象骨架
 */
function buildResponseObject(
    id: string,
    model: string,
    status: 'in_progress' | 'completed',
    output: Record<string, unknown>[],
    usage?: { input_tokens: number; output_tokens: number; total_tokens: number },
): Record<string, unknown> {
    return {
        id,
        object: 'response',
        created_at: Math.floor(Date.now() / 1000),
        status,
        model,
        output,
        ...(usage ? { usage } : {}),
    };
}

/**
 * 处理 OpenAI Codex / Responses API 的 /v1/responses 请求
 *
 * ★ 关键差异:Responses API 的流式格式与 Chat Completions 完全不同
 * Codex 期望接收 event: response.created / response.output_text.delta / response.completed 等事件
 * 而非 data: {"object":"chat.completion.chunk",...} 格式
 */
export async function handleOpenAIResponses(req: Request, res: Response): Promise<void> {
    const body = req.body as Record<string, unknown>;
    const isStream = (body.stream as boolean) ?? true;
    const chatBody = responsesToChatCompletions(body);
    const log = createRequestLogger({
        method: req.method,
        path: req.path,
        model: chatBody.model,
        stream: isStream,
        hasTools: (chatBody.tools?.length ?? 0) > 0,
        toolCount: chatBody.tools?.length ?? 0,
        messageCount: chatBody.messages?.length ?? 0,
        apiFormat: 'responses',
    });
    log.startPhase('receive', '接收请求');
    log.recordOriginalRequest(body);
    log.info('OpenAI', 'receive', '收到 OpenAI Responses 请求', {
        model: chatBody.model,
        stream: isStream,
        toolCount: chatBody.tools?.length ?? 0,
        messageCount: chatBody.messages?.length ?? 0,
    });

    try {
        // Step 1: 转换请求格式 Responses → Chat Completions → Anthropic → Cursor
        log.startPhase('convert', '格式转换 (Responses→Chat→Anthropic)');
        const anthropicReq = convertToAnthropicRequest(chatBody);
        const cursorReq = await convertToCursorRequest(anthropicReq);
        log.endPhase();
        log.recordCursorRequest(cursorReq);

        // 身份探针拦截
        if (isIdentityProbe(anthropicReq)) {
            log.intercepted('身份探针拦截 (Responses)');
            const mockText = "I am Claude, an advanced AI programming assistant created by Anthropic. I am ready to help you write code, debug, and answer your technical questions.";
            if (isStream) {
                return handleResponsesStreamMock(res, body, mockText);
            } else {
                return handleResponsesNonStreamMock(res, body, mockText);
            }
        }

        if (isStream) {
            await handleResponsesStream(res, cursorReq, body, anthropicReq, log);
        } else {
            await handleResponsesNonStream(res, cursorReq, body, anthropicReq, log);
        }
    } catch (err: unknown) {
        const message = err instanceof Error ? err.message : String(err);
        log.fail(message);
        console.error(`[OpenAI] /v1/responses 处理失败:`, message);
        const status = err instanceof OpenAIRequestError ? err.status : 500;
        const type = err instanceof OpenAIRequestError ? err.type : 'server_error';
        const code = err instanceof OpenAIRequestError ? err.code : 'internal_error';
        res.status(status).json({
            error: { message, type, code },
        });
    }
}

/**
 * 模拟身份响应 — 流式 (Responses API SSE 格式)
 */
function handleResponsesStreamMock(res: Response, body: Record<string, unknown>, mockText: string): void {
    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'X-Accel-Buffering': 'no',
    });

    const respId = responsesId();
    const itemId = responsesItemId();
    const model = (body.model as string) || 'gpt-4';

    emitResponsesTextStream(res, respId, itemId, model, mockText, 0, { input_tokens: 15, output_tokens: 35, total_tokens: 50 });
    res.end();
}

/**
 * 模拟身份响应 — 非流式 (Responses API JSON 格式)
 */
function handleResponsesNonStreamMock(res: Response, body: Record<string, unknown>, mockText: string): void {
    const respId = responsesId();
    const itemId = responsesItemId();
    const model = (body.model as string) || 'gpt-4';

    res.json(buildResponseObject(respId, model, 'completed', [{
        id: itemId,
        type: 'message',
        role: 'assistant',
        status: 'completed',
        content: [{ type: 'output_text', text: mockText, annotations: [] }],
    }], { input_tokens: 15, output_tokens: 35, total_tokens: 50 }));
}

/**
 * 发射完整的 Responses API 文本流事件序列
 * 包含从 response.created 到 response.completed 的完整生命周期
 */
function emitResponsesTextStream(
    res: Response,
    respId: string,
    itemId: string,
    model: string,
    fullText: string,
    outputIndex: number,
    usage: { input_tokens: number; output_tokens: number; total_tokens: number },
    toolCallItems?: Record<string, unknown>[],
): void {
    // 所有输出项(文本 + 工具调用)
    const messageItem: Record<string, unknown> = {
        id: itemId,
        type: 'message',
        role: 'assistant',
        status: 'completed',
        content: [{ type: 'output_text', text: fullText, annotations: [] }],
    };
    const allOutputItems = toolCallItems ? [...toolCallItems, messageItem] : [messageItem];

    // 1. response.created
    writeResponsesSSE(res, 'response.created', buildResponseObject(respId, model, 'in_progress', []));

    // 2. response.in_progress
    writeResponsesSSE(res, 'response.in_progress', buildResponseObject(respId, model, 'in_progress', []));

    // 3. 文本 output item
    writeResponsesSSE(res, 'response.output_item.added', {
        output_index: outputIndex,
        item: {
            id: itemId,
            type: 'message',
            role: 'assistant',
            status: 'in_progress',
            content: [],
        },
    });

    // 4. content part
    writeResponsesSSE(res, 'response.content_part.added', {
        output_index: outputIndex,
        content_index: 0,
        part: { type: 'output_text', text: '', annotations: [] },
    });

    // 5. 文本增量
    if (fullText) {
        // 分块发送,模拟流式体验 (每块约 100 字符)
        const CHUNK_SIZE = 100;
        for (let i = 0; i < fullText.length; i += CHUNK_SIZE) {
            writeResponsesSSE(res, 'response.output_text.delta', {
                output_index: outputIndex,
                content_index: 0,
                delta: fullText.slice(i, i + CHUNK_SIZE),
            });
        }
    }

    // 6. response.output_text.done
    writeResponsesSSE(res, 'response.output_text.done', {
        output_index: outputIndex,
        content_index: 0,
        text: fullText,
    });

    // 7. response.content_part.done
    writeResponsesSSE(res, 'response.content_part.done', {
        output_index: outputIndex,
        content_index: 0,
        part: { type: 'output_text', text: fullText, annotations: [] },
    });

    // 8. response.output_item.done (message)
    writeResponsesSSE(res, 'response.output_item.done', {
        output_index: outputIndex,
        item: messageItem,
    });

    // 9. response.completed — ★ 这是 Codex 等待的关键事件
    writeResponsesSSE(res, 'response.completed', buildResponseObject(respId, model, 'completed', allOutputItems, usage));
}

/**
 * Responses API 流式处理
 *
 * ★ 与 Chat Completions 流式的核心区别:
 * 1. 使用 event: 前缀的 SSE 事件(不是 data-only)
 * 2. 必须发送 response.completed 事件,否则 Codex 报 "stream closed before response.completed"
 * 3. 工具调用用 function_call 类型的 output item 表示
 */
async function handleResponsesStream(
    res: Response,
    cursorReq: CursorChatRequest,
    body: Record<string, unknown>,
    anthropicReq: AnthropicRequest,
    log: RequestLogger,
): Promise<void> {
    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'X-Accel-Buffering': 'no',
    });

    const respId = responsesId();
    const model = (body.model as string) || 'gpt-4';
    const hasTools = (anthropicReq.tools?.length ?? 0) > 0;
    let toolCallsDetected = 0;

    // 缓冲完整响应再处理(复用 Chat Completions 的逻辑)
    let fullResponse = '';
    let activeCursorReq = cursorReq;
    let retryCount = 0;

    // ★ 流式保活:防止网关 504
    const keepaliveInterval = setInterval(() => {
        try {
            res.write(': keepalive\n\n');
            if (typeof (res as unknown as { flush: () => void }).flush === 'function') {
                (res as unknown as { flush: () => void }).flush();
            }
        } catch { /* connection already closed */ }
    }, 15000);

    try {
        const executeStream = async () => {
            fullResponse = '';
            await sendCursorRequest(activeCursorReq, (event: CursorSSEEvent) => {
                if (event.type !== 'text-delta' || !event.delta) return;
                fullResponse += event.delta;
            });
        };

        await executeStream();

        // Thinking 提取
        if (hasLeadingThinking(fullResponse)) {
            const { strippedText } = extractThinking(fullResponse);
            fullResponse = strippedText;
        }

        // 拒绝检测 + 自动重试
        const shouldRetryRefusal = () => {
            if (!isRefusal(fullResponse)) return false;
            if (hasTools && hasToolCalls(fullResponse)) return false;
            return true;
        };

        while (shouldRetryRefusal() && retryCount < MAX_REFUSAL_RETRIES) {
            retryCount++;
            const retryBody = buildRetryRequest(anthropicReq, retryCount - 1);
            activeCursorReq = await convertToCursorRequest(retryBody);
            await executeStream();
            if (hasLeadingThinking(fullResponse)) {
                fullResponse = extractThinking(fullResponse).strippedText;
            }
        }

        if (shouldRetryRefusal()) {
            if (isToolCapabilityQuestion(anthropicReq)) {
                fullResponse = CLAUDE_TOOLS_RESPONSE;
            } else {
                fullResponse = CLAUDE_IDENTITY_RESPONSE;
            }
        }

        if (hasTools) {
            fullResponse = await autoContinueCursorToolResponseStream(activeCursorReq, fullResponse, hasTools);
        }

        // 清洗响应
        fullResponse = sanitizeResponse(fullResponse);

        // 计算 usage
        const inputTokens = estimateInputTokens(anthropicReq);
        const outputTokens = Math.ceil(fullResponse.length / 3);
        const usage = { input_tokens: inputTokens, output_tokens: outputTokens, total_tokens: inputTokens + outputTokens };

        // ★ 工具调用解析 + Responses API 格式输出
        if (hasTools && hasToolCalls(fullResponse)) {
            const { toolCalls, cleanText } = parseToolCalls(fullResponse);

            if (toolCalls.length > 0) {
                toolCallsDetected = toolCalls.length;
                log.recordToolCalls(toolCalls);
                log.updateSummary({ toolCallsDetected: toolCalls.length });
                // 1. response.created + response.in_progress
                writeResponsesSSE(res, 'response.created', buildResponseObject(respId, model, 'in_progress', []));
                writeResponsesSSE(res, 'response.in_progress', buildResponseObject(respId, model, 'in_progress', []));

                const allOutputItems: Record<string, unknown>[] = [];
                let outputIndex = 0;

                // 2. 每个工具调用 → function_call output item
                for (const tc of toolCalls) {
                    const callId = toolCallId();
                    const fcItemId = responsesItemId();
                    const argsStr = JSON.stringify(tc.arguments);

                    // output_item.added (function_call)
                    writeResponsesSSE(res, 'response.output_item.added', {
                        output_index: outputIndex,
                        item: {
                            id: fcItemId,
                            type: 'function_call',
                            name: tc.name,
                            call_id: callId,
                            arguments: '',
                            status: 'in_progress',
                        },
                    });

                    // function_call_arguments.delta — 分块发送
                    const CHUNK_SIZE = 128;
                    for (let j = 0; j < argsStr.length; j += CHUNK_SIZE) {
                        writeResponsesSSE(res, 'response.function_call_arguments.delta', {
                            output_index: outputIndex,
                            delta: argsStr.slice(j, j + CHUNK_SIZE),
                        });
                    }

                    // function_call_arguments.done
                    writeResponsesSSE(res, 'response.function_call_arguments.done', {
                        output_index: outputIndex,
                        arguments: argsStr,
                    });

                    // output_item.done (function_call)
                    const completedFcItem = {
                        id: fcItemId,
                        type: 'function_call',
                        name: tc.name,
                        call_id: callId,
                        arguments: argsStr,
                        status: 'completed',
                    };
                    writeResponsesSSE(res, 'response.output_item.done', {
                        output_index: outputIndex,
                        item: completedFcItem,
                    });

                    allOutputItems.push(completedFcItem);
                    outputIndex++;
                }

                // 3. 如果有纯文本部分,也发送 message output item
                let textContent = sanitizeResponse(isRefusal(cleanText) ? '' : cleanText);
                if (textContent) {
                    const msgItemId = responsesItemId();
                    writeResponsesSSE(res, 'response.output_item.added', {
                        output_index: outputIndex,
                        item: { id: msgItemId, type: 'message', role: 'assistant', status: 'in_progress', content: [] },
                    });
                    writeResponsesSSE(res, 'response.content_part.added', {
                        output_index: outputIndex, content_index: 0,
                        part: { type: 'output_text', text: '', annotations: [] },
                    });
                    writeResponsesSSE(res, 'response.output_text.delta', {
                        output_index: outputIndex, content_index: 0, delta: textContent,
                    });
                    writeResponsesSSE(res, 'response.output_text.done', {
                        output_index: outputIndex, content_index: 0, text: textContent,
                    });
                    writeResponsesSSE(res, 'response.content_part.done', {
                        output_index: outputIndex, content_index: 0,
                        part: { type: 'output_text', text: textContent, annotations: [] },
                    });
                    const msgItem = {
                        id: msgItemId, type: 'message', role: 'assistant', status: 'completed',
                        content: [{ type: 'output_text', text: textContent, annotations: [] }],
                    };
                    writeResponsesSSE(res, 'response.output_item.done', { output_index: outputIndex, item: msgItem });
                    allOutputItems.push(msgItem);
                }

                // 4. response.completed — ★ Codex 等待的关键事件
                writeResponsesSSE(res, 'response.completed', buildResponseObject(respId, model, 'completed', allOutputItems, usage));
            } else {
                // 工具调用解析失败(误报)→ 作为纯文本发送
                const msgItemId = responsesItemId();
                emitResponsesTextStream(res, respId, msgItemId, model, fullResponse, 0, usage);
            }
        } else {
            // 纯文本响应
            const msgItemId = responsesItemId();
            emitResponsesTextStream(res, respId, msgItemId, model, fullResponse, 0, usage);
        }
        log.recordRawResponse(fullResponse);
        log.recordFinalResponse(fullResponse);
        log.complete(fullResponse.length, toolCallsDetected > 0 ? 'tool_calls' : 'stop');
    } catch (err: unknown) {
        const message = err instanceof Error ? err.message : String(err);
        log.fail(message);
        // 尝试发送错误后的 response.completed,确保 Codex 不会等待超时
        try {
            const errorText = `[Error: ${message}]`;
            const errorItemId = responsesItemId();
            writeResponsesSSE(res, 'response.created', buildResponseObject(respId, model, 'in_progress', []));
            writeResponsesSSE(res, 'response.output_item.added', {
                output_index: 0,
                item: { id: errorItemId, type: 'message', role: 'assistant', status: 'in_progress', content: [] },
            });
            writeResponsesSSE(res, 'response.content_part.added', {
                output_index: 0, content_index: 0,
                part: { type: 'output_text', text: '', annotations: [] },
            });
            writeResponsesSSE(res, 'response.output_text.delta', {
                output_index: 0, content_index: 0, delta: errorText,
            });
            writeResponsesSSE(res, 'response.output_text.done', {
                output_index: 0, content_index: 0, text: errorText,
            });
            writeResponsesSSE(res, 'response.content_part.done', {
                output_index: 0, content_index: 0,
                part: { type: 'output_text', text: errorText, annotations: [] },
            });
            writeResponsesSSE(res, 'response.output_item.done', {
                output_index: 0,
                item: { id: errorItemId, type: 'message', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: errorText, annotations: [] }] },
            });
            writeResponsesSSE(res, 'response.completed', buildResponseObject(respId, model, 'completed', [{
                id: errorItemId, type: 'message', role: 'assistant', status: 'completed',
                content: [{ type: 'output_text', text: errorText, annotations: [] }],
            }], { input_tokens: 0, output_tokens: 10, total_tokens: 10 }));
        } catch { /* ignore double error */ }
    } finally {
        clearInterval(keepaliveInterval);
    }

    res.end();
}

/**
 * Responses API 非流式处理
 */
async function handleResponsesNonStream(
    res: Response,
    cursorReq: CursorChatRequest,
    body: Record<string, unknown>,
    anthropicReq: AnthropicRequest,
    log: RequestLogger,
): Promise<void> {
    let activeCursorReq = cursorReq;
    let fullText = await sendCursorRequestFull(activeCursorReq);
    const hasTools = (anthropicReq.tools?.length ?? 0) > 0;

    // Thinking 提取
    if (hasLeadingThinking(fullText)) {
        fullText = extractThinking(fullText).strippedText;
    }

    // 拒绝检测 + 重试
    const shouldRetry = () => isRefusal(fullText) && !(hasTools && hasToolCalls(fullText));
    if (shouldRetry()) {
        for (let attempt = 0; attempt < MAX_REFUSAL_RETRIES; attempt++) {
            const retryBody = buildRetryRequest(anthropicReq, attempt);
            const retryCursorReq = await convertToCursorRequest(retryBody);
            activeCursorReq = retryCursorReq;
            fullText = await sendCursorRequestFull(activeCursorReq);
            if (hasLeadingThinking(fullText)) {
                fullText = extractThinking(fullText).strippedText;
            }
            if (!shouldRetry()) break;
        }
        if (shouldRetry()) {
            if (isToolCapabilityQuestion(anthropicReq)) {
                fullText = CLAUDE_TOOLS_RESPONSE;
            } else {
                fullText = CLAUDE_IDENTITY_RESPONSE;
            }
        }
    }

    if (hasTools) {
        fullText = await autoContinueCursorToolResponseFull(activeCursorReq, fullText, hasTools);
    }

    fullText = sanitizeResponse(fullText);

    const respId = responsesId();
    const model = (body.model as string) || 'gpt-4';
    const inputTokens = estimateInputTokens(anthropicReq);
    const outputTokens = Math.ceil(fullText.length / 3);
    const usage = { input_tokens: inputTokens, output_tokens: outputTokens, total_tokens: inputTokens + outputTokens };

    const output: Record<string, unknown>[] = [];
    let toolCallsDetected = 0;

    if (hasTools && hasToolCalls(fullText)) {
        const { toolCalls, cleanText } = parseToolCalls(fullText);
        toolCallsDetected = toolCalls.length;
        log.recordToolCalls(toolCalls);
        log.updateSummary({ toolCallsDetected: toolCalls.length });
        for (const tc of toolCalls) {
            output.push({
                id: responsesItemId(),
                type: 'function_call',
                name: tc.name,
                call_id: toolCallId(),
                arguments: JSON.stringify(tc.arguments),
                status: 'completed',
            });
        }
        const textContent = sanitizeResponse(isRefusal(cleanText) ? '' : cleanText);
        if (textContent) {
            output.push({
                id: responsesItemId(),
                type: 'message',
                role: 'assistant',
                status: 'completed',
                content: [{ type: 'output_text', text: textContent, annotations: [] }],
            });
        }
    } else {
        output.push({
            id: responsesItemId(),
            type: 'message',
            role: 'assistant',
            status: 'completed',
            content: [{ type: 'output_text', text: fullText, annotations: [] }],
        });
    }

    res.json(buildResponseObject(respId, model, 'completed', output, usage));

    log.recordRawResponse(fullText);
    log.recordFinalResponse(fullText);
    log.complete(fullText.length, toolCallsDetected > 0 ? 'tool_calls' : 'stop');
}

/**
 * 将 OpenAI Responses API 格式转换为 Chat Completions 格式
 *
 * Responses API 使用 `input` 而非 `messages`,格式与 Chat Completions 不同
 */
export function responsesToChatCompletions(body: Record<string, unknown>): OpenAIChatRequest {
    const messages: OpenAIMessage[] = [];

    // 系统指令
    if (body.instructions && typeof body.instructions === 'string') {
        messages.push({ role: 'system', content: body.instructions });
    }

    // 转换 input
    const input = body.input;
    if (typeof input === 'string') {
        messages.push({ role: 'user', content: input });
    } else if (Array.isArray(input)) {
        for (const item of input as Record<string, unknown>[]) {
            // function_call_output 没有 role 字段,必须先检查 type
            if (item.type === 'function_call_output') {
                messages.push({
                    role: 'tool',
                    content: stringifyUnknownContent(item.output),
                    tool_call_id: (item.call_id as string) || '',
                });
                continue;
            }
            const role = (item.role as string) || 'user';
            if (role === 'system' || role === 'developer') {
                const text = extractOpenAIContent({
                    role: 'system',
                    content: (item.content as string | OpenAIContentPart[] | null) ?? null,
                } as OpenAIMessage);
                messages.push({ role: 'system', content: text });
            } else if (role === 'user') {
                const rawContent = (item.content as string | OpenAIContentPart[] | null) ?? null;
                const normalizedContent = typeof rawContent === 'string'
                    ? rawContent
                    : Array.isArray(rawContent) && rawContent.every(b => b.type === 'input_text')
                        ? rawContent.map(b => b.text || '').join('\n')
                        : rawContent;
                messages.push({
                    role: 'user',
                    content: normalizedContent || '',
                });
            } else if (role === 'assistant') {
                const blocks = Array.isArray(item.content) ? item.content as Array<Record<string, unknown>> : [];
                const text = blocks.filter(b => b.type === 'output_text').map(b => b.text as string).join('\n');
                // 检查是否有工具调用
                const toolCallBlocks = blocks.filter(b => b.type === 'function_call');
                const toolCalls: OpenAIToolCall[] = toolCallBlocks.map(b => ({
                    id: (b.call_id as string) || toolCallId(),
                    type: 'function' as const,
                    function: {
                        name: (b.name as string) || '',
                        arguments: (b.arguments as string) || '{}',
                    },
                }));
                messages.push({
                    role: 'assistant',
                    content: text || null,
                    ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
                });
            }
        }
    }

    // 转换工具定义
    const tools: OpenAITool[] | undefined = Array.isArray(body.tools)
        ? (body.tools as Array<Record<string, unknown>>).map(t => {
            if (t.type === 'function') {
                return {
                    type: 'function' as const,
                    function: {
                        name: (t.name as string) || '',
                        description: t.description as string | undefined,
                        parameters: t.parameters as Record<string, unknown> | undefined,
                    },
                };
            }
            return {
                type: 'function' as const,
                function: {
                    name: (t.name as string) || '',
                    description: t.description as string | undefined,
                    parameters: t.parameters as Record<string, unknown> | undefined,
                },
            };
        })
        : undefined;

    return {
        model: (body.model as string) || 'gpt-4',
        messages,
        stream: (body.stream as boolean) ?? true,
        temperature: body.temperature as number | undefined,
        max_tokens: (body.max_output_tokens as number) || 8192,
        tools,
    };
}