-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathproxy.mjs
More file actions
1897 lines (1730 loc) · 69.4 KB
/
Copy pathproxy.mjs
File metadata and controls
1897 lines (1730 loc) · 69.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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
/**
* Command Code → OpenAI 兼容代理
* 基于真实 CLI 流量抓包数据构建
*/
import http from 'http';
import crypto from 'crypto';
import { randomUUID } from 'crypto';
import { readFileSync, existsSync, appendFileSync } from 'fs';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
// ── 配置加载 ──────────────────────────────────────
const __dirname = dirname(fileURLToPath(import.meta.url));
function loadConfig() {
const defaults = {
port: 3000,
host: '0.0.0.0',
apiBase: 'https://api.commandcode.ai',
projectSlug: 'cc-proxy',
logFile: '',
logLevel: 'info',
useProviderModels: true,
modelRefreshIntervalMs: 5 * 60 * 1000, // 5 minutes
};
const configPath = resolve(__dirname, 'config.json');
if (existsSync(configPath)) {
try {
const user = JSON.parse(readFileSync(configPath, 'utf-8'));
Object.assign(defaults, user);
} catch (e) {
console.error('[config] Failed to parse config.json:', e.message);
}
}
// 环境变量覆写
if (process.env.PORT) defaults.port = parseInt(process.env.PORT);
if (process.env.HOST) defaults.host = process.env.HOST;
if (process.env.CC_API_BASE) defaults.apiBase = process.env.CC_API_BASE;
if (process.env.PROJECT_SLUG) defaults.projectSlug = process.env.PROJECT_SLUG;
if (process.env.LOG_FILE) defaults.logFile = process.env.LOG_FILE;
if (process.env.CC_USE_PROVIDER_MODELS) defaults.useProviderModels = process.env.CC_USE_PROVIDER_MODELS !== 'false';
return defaults;
}
const CFG = loadConfig();
// ── 指纹生成(首次运行自动生成,写回 config.json) ──────
// CPU 型号与核心数对应表(仅 Windows x64)
const FINGERPRINT_CPUS = [
{ model: '12th Gen Intel(R) Core(TM) i7-12650H', cores: 10 },
{ model: '12th Gen Intel(R) Core(TM) i5-12400F', cores: 6 },
{ model: '12th Gen Intel(R) Core(TM) i9-12900K', cores: 16 },
{ model: '13th Gen Intel(R) Core(TM) i7-13700K', cores: 16 },
{ model: '13th Gen Intel(R) Core(TM) i5-13600K', cores: 14 },
{ model: '13th Gen Intel(R) Core(TM) i9-13900K', cores: 24 },
{ model: 'Intel(R) Core(TM) Ultra 7 155H', cores: 16 },
{ model: 'Intel(R) Core(TM) Ultra 9 285H', cores: 16 },
{ model: 'Intel(R) Core(TM) i9-14900K', cores: 24 },
{ model: 'Intel(R) Core(TM) i7-14700K', cores: 20 },
{ model: 'AMD Ryzen 7 7800X3D', cores: 8 },
{ model: 'AMD Ryzen 9 7950X', cores: 16 },
{ model: 'AMD Ryzen 5 7600', cores: 6 },
{ model: 'AMD Ryzen 9 7900X', cores: 12 },
{ model: 'AMD Ryzen 7 5800X3D', cores: 8 },
];
const FINGERPRINT_MEMS = [8, 16, 24, 32, 48, 64];
const FINGERPRINT_TZS = [
'America/New_York', 'America/Chicago', 'America/Los_Angeles', 'America/Toronto',
'Europe/London', 'Europe/Berlin', 'Europe/Paris', 'Europe/Moscow',
'Asia/Shanghai', 'Asia/Tokyo', 'Asia/Singapore', 'Asia/Seoul', 'Asia/Hong_Kong',
'Australia/Sydney', 'Pacific/Auckland',
];
const FINGERPRINT_MAC_COUNT_RANGE = [2, 3, 4, 5]; // 随机 2~5 个 MAC
function generateFingerprint() {
const cpuEntry = FINGERPRINT_CPUS[Math.floor(Math.random() * FINGERPRINT_CPUS.length)];
const memGiB = FINGERPRINT_MEMS[Math.floor(Math.random() * FINGERPRINT_MEMS.length)];
const tz = FINGERPRINT_TZS[Math.floor(Math.random() * FINGERPRINT_TZS.length)];
const macCount = FINGERPRINT_MAC_COUNT_RANGE[Math.floor(Math.random() * FINGERPRINT_MAC_COUNT_RANGE.length)];
function sha256(s) { return crypto.createHash('sha256').update(s).digest('hex'); }
function randHex(n) { return crypto.randomBytes(n).toString('hex'); }
const macHashes = [];
for (let i = 0; i < macCount; i++) macHashes.push(sha256(randHex(32)));
const machineIdHash = sha256(randHex(32));
const osUserHash = sha256(randHex(16));
const hostnameHash = sha256(randHex(16));
const gitEmailHash = sha256(randHex(16));
// thumbmark = 所有组件的联合哈希
const thumbData = [machineIdHash, ...macHashes, osUserHash, hostnameHash, gitEmailHash, 'win32', '10.0.22631', cpuEntry.model, String(cpuEntry.cores), String(memGiB)].join('|');
const thumbmark = sha256(thumbData);
return {
thumbmark,
components: {
machineIdHash,
macHashes,
osUserHash,
hostnameHash,
gitEmailHash,
platform: 'win32',
arch: 'x64',
osRelease: '10.0.22631',
cpuModel: cpuEntry.model,
cpuCount: cpuEntry.cores,
memGiB,
isContainer: false,
timezone: tz,
runtime: 'cli',
collectorVersion: 1,
},
};
}
let CC_VERSION = '0.32.3';
const CC_VERSION_FALLBACK = '0.32.3';
const CC_VERSION_REFRESH_MS = 24 * 60 * 60 * 1000; // 24h — npm registry 刷新间隔
// ── 动态 CC 版本号(从 npm registry 拉取) ─────────────
async function refreshCCVersion() {
try {
const url = 'https://registry.npmjs.org/command-code/latest';
const res = await fetch(url, { signal: AbortSignal.timeout(10000) });
if (!res.ok) throw new Error(`npm responded with ${res.status}`);
const pkg = await res.json();
if (pkg.version && typeof pkg.version === 'string') {
CC_VERSION = pkg.version;
log('info', 'CC Version refreshed from npm', { version: CC_VERSION });
}
} catch (e) {
log('warn', 'CC Version fetch failed, using current', { version: CC_VERSION, error: e.message });
}
}
refreshCCVersion(); // 启动时立即拉取
setInterval(refreshCCVersion, CC_VERSION_REFRESH_MS);
const MAX_BODY_SIZE = 10 * 1024 * 1024; // 10MB — 请求体大小上限
const STREAM_IDLE_TIMEOUT_MS = 30000; // 30s — 流式无新数据中断
const NONSTREAM_IDLE_TIMEOUT_MS = 90000; // 90s — 非流式超时更宽容
// 连续超时计数:连续 3 次超时才提醒压缩上下文,任意成功请求后重置
let consecutiveTimeouts = 0;
const TIMEOUT_REDUCE_CONTEXT_THRESHOLD = 3;
// ── 日志 ─────────────────────────────────────────────
function log(level, msg, data) {
const line = `[${new Date().toISOString()}] [${level}] ${msg}${data ? ' ' + JSON.stringify(data) : ''}`;
console.log(line);
if (CFG.logFile) {
try { appendFileSync(CFG.logFile, line + '\n', 'utf-8'); } catch {}
}
}
// ── 会话管理 ───────────────────────────────────────
// 每个 API Key 独立一个 session,12h 过期 + 1h 随机抖动
// 同一 Key 在同一周期内复用,到期自动换新
const SESSION_DURATION_MS = 12 * 60 * 60 * 1000; // 12h
const SESSION_JITTER_MS = 60 * 60 * 1000; // 1h 抖动范围
const sessionStore = new Map(); // apiKey → { sessionId, expiresAt }
function ensureSession(apiKey) {
const now = Date.now();
const entry = sessionStore.get(apiKey);
if (entry && now < entry.expiresAt) {
return entry.sessionId;
}
// 过期或第一次:生成新 session
const jitter = Math.floor(Math.random() * SESSION_JITTER_MS);
const sessionId = randomUUID();
sessionStore.set(apiKey, { sessionId, expiresAt: now + SESSION_DURATION_MS + jitter });
log('info', 'Session created', { sessionId: sessionId.slice(0, 8), storeSize: sessionStore.size });
return sessionId;
}
// 定期清理过期 session 和 key 状态,防止 Map 无限增长
setInterval(() => {
const now = Date.now();
let cleaned = 0;
for (const [key, entry] of sessionStore) {
if (now >= entry.expiresAt) {
sessionStore.delete(key);
keyStateStore.delete(key); // 同时清理该 key 的指纹状态
cleaned++;
}
}
if (cleaned > 0) log('info', 'Session cleanup', { cleaned, remaining: sessionStore.size });
}, 60 * 60 * 1000); // 每小时
function getSessionId(incomingHeaders, apiKey) {
// 优先从客户端传来的 session 类 header 获取
const candidates = [
incomingHeaders['x-session-id'],
incomingHeaders['x-claude-code-session-id'],
];
for (const id of candidates) {
if (id && typeof id === 'string' && id.length >= 8) return id;
}
// 按 API Key 分 session
return ensureSession(apiKey);
}
// 每个请求独立 thread ID
function newThreadId() { return randomUUID(); }
// ── 每 Key 独立状态(fingerprint + 初始化节流) ──
// 每个 API Key 拥有自己的设备指纹和初始化定时器
const keyStateStore = new Map(); // apiKey → { fingerprint, nextInitAt }
function getOrCreateKeyState(apiKey) {
let state = keyStateStore.get(apiKey);
if (!state) {
state = {
fingerprint: generateFingerprint(),
nextInitAt: 0,
};
keyStateStore.set(apiKey, state);
log('info', 'Fingerprint generated for key', { keyPrefix: apiKey.slice(0, 8) });
}
return state;
}
// ── 初始化预请求(fingerprint + lifecycle,首次 + 每 8h+2h 抖动) ────
const INIT_REFRESH_MS = 8 * 60 * 60 * 1000; // 8h
const INIT_JITTER_MS = 2 * 60 * 60 * 1000; // 2h 抖动
async function ensureInitialized(apiKey, signal) {
const state = getOrCreateKeyState(apiKey);
const now = Date.now();
if (now < state.nextInitAt) return;
try {
// 并行发两个预请求
const headers = {
'Content-Type': 'application/json',
'x-cli-environment': 'production',
'Authorization': `Bearer ${apiKey}`,
'x-command-code-version': CC_VERSION,
};
const fingerprint = state.fingerprint || {};
await Promise.all([
fetch(`${CFG.apiBase}/alpha/fingerprint/record`, {
method: 'POST', headers, signal,
body: JSON.stringify(fingerprint),
}).then(r => {
if (!r.ok) log('warn', 'Fingerprint record failed', { status: r.status });
else log('info', 'Fingerprint recorded');
}).catch(e => {
if (e.name !== 'AbortError') log('warn', 'Fingerprint record error', { error: e.message });
}),
fetch(`${CFG.apiBase}/alpha/lifecycle-events`, {
method: 'POST', headers, signal,
body: JSON.stringify({
eventType: 'cli_session_exists',
metadata: {
sessionId: `sess_${crypto.randomBytes(8).toString('hex')}`,
cliVersion: CC_VERSION,
mode: 'interactive',
os: `${fingerprint.components.platform}-${fingerprint.components.arch}`,
},
}),
}).then(r => {
if (!r.ok) log('warn', 'Lifecycle event failed', { status: r.status });
else log('info', 'Lifecycle event sent');
}).catch(e => {
if (e.name !== 'AbortError') log('warn', 'Lifecycle event error', { error: e.message });
}),
]);
// 成功:8h + 2h 随机抖动
const jitter = Math.floor(Math.random() * INIT_JITTER_MS);
state.nextInitAt = Date.now() + INIT_REFRESH_MS + jitter;
log('info', 'Fingerprint/lifecycle next refresh', { nextIn: `${(INIT_REFRESH_MS + jitter) / 3600000}h` });
} catch (e) {
if (e.name !== 'AbortError') log('warn', 'Fingerprint/lifecycle refresh error, will retry next request', { error: e.message });
}
}
// ── 模型列表 ───────────────────────────────────────
const MODELS = [
// Anthropic
{ id: 'claude-sonnet-4-6', name: 'Claude Sonnet 4.6' },
{ id: 'claude-opus-4-8', name: 'Claude Opus 4.8' },
{ id: 'claude-opus-4-7', name: 'Claude Opus 4.7' },
{ id: 'claude-haiku-4-5-20251001', name: 'Claude Haiku 4.5' },
// OpenAI
{ id: 'gpt-5.5', name: 'GPT-5.5' },
{ id: 'gpt-5.4', name: 'GPT-5.4' },
{ id: 'gpt-5.4-mini', name: 'GPT-5.4 Mini' },
{ id: 'gpt-5.3-codex', name: 'GPT-5.3 Codex' },
// DeepSeek
{ id: 'deepseek/deepseek-v4-pro', name: 'DeepSeek V4 Pro' },
{ id: 'deepseek/deepseek-v4-flash', name: 'DeepSeek V4 Flash' },
// Kimi
{ id: 'moonshotai/Kimi-K2.6', name: 'Kimi K2.6' },
{ id: 'moonshotai/Kimi-K2.5', name: 'Kimi K2.5' },
// GLM
{ id: 'zai-org/GLM-5.1', name: 'GLM 5.1' },
{ id: 'zai-org/GLM-5', name: 'GLM 5' },
// MiniMax
{ id: 'MiniMaxAI/MiniMax-M3', name: 'MiniMax M3' },
{ id: 'MiniMaxAI/MiniMax-M2.7', name: 'MiniMax M2.7' },
{ id: 'MiniMaxAI/MiniMax-M2.5', name: 'MiniMax M2.5' },
// Qwen
{ id: 'Qwen/Qwen3.6-Max-Preview', name: 'Qwen 3.6 Max Preview' },
{ id: 'Qwen/Qwen3.6-Plus', name: 'Qwen 3.6 Plus' },
{ id: 'Qwen/Qwen3.7-Max', name: 'Qwen 3.7 Max' },
// Step
{ id: 'stepfun/Step-3.7-Flash', name: 'Step 3.7 Flash' },
{ id: 'stepfun/Step-3.5-Flash', name: 'Step 3.5 Flash' },
// Xiaomi
{ id: 'xiaomi/mimo-v2.5-pro', name: 'MiMo V2.5 Pro' },
{ id: 'xiaomi/mimo-v2.5', name: 'MiMo V2.5' },
// Gemini
{ id: 'google/gemini-3.5-flash', name: 'Gemini 3.5 Flash' },
{ id: 'google/gemini-3.1-flash-lite', name: 'Gemini 3.1 Flash Lite' },
];
// ── 工具函数 ───────────────────────────────────────
// 从 sessionId 构造一个假的工作目录路径,再按真实 CLI 规则生成 slug
// 结果形如 "d-users-dev-projects-web-app-a3f2" (和真实 CLI 的 slug 格式一致)
function fakeProjectSlug(sessionId) {
const names = ['app', 'api', 'backend', 'bot', 'cli', 'core', 'data', 'frontend',
'lib', 'plugin', 'proxy', 'server', 'service', 'tool', 'web', 'worker'];
const name = names[parseInt(sessionId.slice(0, 4), 16) % names.length];
const suffix = sessionId.slice(0, 4);
// 模拟一个类似 C:\Users\dev\projects\{name}-{suffix} 的路径
const path = `C:\\Users\\dev\\projects\\${name}-${suffix}`;
return path
.toLowerCase()
.replace(/^[a-z]:/i, '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
}
function generateTraceparent() {
const traceId = crypto.randomBytes(16).toString('hex');
const parentId = crypto.randomBytes(8).toString('hex');
return `00-${traceId}-${parentId}-01`;
}
function nowUnix() {
return Math.floor(Date.now() / 1000);
}
function getDateStr() {
return new Date().toISOString().slice(0, 10);
}
function getEnvironment() {
return `${process.platform}-${process.arch}, Node.js ${process.version.slice(1)}`;
}
// ── CC 请求体构建 ─────────────────────────────────
function buildCcRequest(openaiReq) {
const { model, messages, max_tokens, temperature, tools, stream, reasoning_effort, tool_choice, parallel_tool_calls } = openaiReq;
// 从 messages 中提取 system prompt
const systemMsgs = messages.filter(m => m.role === 'system');
const systemPrompt = systemMsgs.map(m => m.content).join('\n');
const chatMessages = messages.filter(m => m.role !== 'system');
// Build tool_call_id → tool_name reverse lookup
const toolNameMap = {};
for (const msg of chatMessages) {
if (msg.role === 'assistant' && msg.tool_calls) {
for (const tc of msg.tool_calls) {
if (tc.id) {
toolNameMap[tc.id] = tc.function?.name || '';
}
}
}
}
// 转换 messages 为 CC 格式
const ccMessages = chatMessages.map(msg => {
if (msg.role === 'user') {
if (typeof msg.content === 'string') {
return { role: 'user', content: [{ type: 'text', text: msg.content }] };
}
// 多模态:数组 content 原样透传(text + image_url → CC image 格式)
if (Array.isArray(msg.content)) {
const parts = msg.content.map(part => {
if (part.type === 'image_url') {
const url = part.image_url?.url || '';
// CC CLI 真实格式: { type: "image", image: "data:image/jpeg;base64,..." }
return { type: 'image', image: url };
}
return part;
}).filter(Boolean);
return { role: 'user', content: parts };
}
return { role: 'user', content: [{ type: 'text', text: String(msg.content) }] };
}
if (msg.role === 'assistant') {
const parts = [];
if (msg.content && typeof msg.content === 'string') {
parts.push({ type: 'text', text: msg.content });
} else if (msg.content && Array.isArray(msg.content)) {
for (const part of msg.content) {
if (part.type === 'text') parts.push(part);
}
}
if (msg.tool_calls) {
for (const tc of msg.tool_calls) {
parts.push({
type: 'tool-call',
toolCallId: tc.id,
toolName: tc.function?.name || '',
input: (typeof tc.function?.arguments === 'string' ? tryParseJSON(tc.function.arguments) : (tc.function?.arguments || {})),
});
}
}
return { role: 'assistant', content: parts };
}
if (msg.role === 'tool') {
return {
role: 'tool',
content: [{
type: 'tool-result',
toolCallId: msg.tool_call_id,
toolName: toolNameMap[msg.tool_call_id] || msg.name || '',
output: { type: 'text', value: typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content) },
}],
};
}
return msg;
});
const threadId = newThreadId();
const body = {
config: {
workingDir: process.cwd(),
date: getDateStr(),
environment: getEnvironment(),
structure: [],
isGitRepo: false,
currentBranch: '',
mainBranch: '',
gitStatus: '',
recentCommits: [],
},
memory: null,
taste: null,
skills: '',
permissionMode: 'standard',
params: {
model: model || 'deepseek/deepseek-v4-flash',
messages: ccMessages,
max_tokens: Math.min(max_tokens || 64000, 200000),
stream: true, // CC API 总是 stream
},
};
// 条件字段
if (systemPrompt) {
body.params.system = systemPrompt;
}
if (temperature !== undefined) {
body.params.temperature = temperature;
}
if (reasoning_effort !== undefined) {
body.params.reasoning_effort = reasoning_effort;
}
if (tools && tools.length > 0) {
body.params.tools = tools.map(t => ({
type: t.type || 'function',
name: t.function?.name || t.name || '',
description: t.function?.description || t.description || '',
input_schema: t.function?.parameters || t.input_schema || { type: 'object', properties: {} },
}));
}
if (tool_choice !== undefined) {
// OpenAI 格式 → CC (Anthropic 风格) 格式
if (typeof tool_choice === 'string') {
const map = { 'auto': 'auto', 'none': 'none', 'required': 'any' };
body.params.tool_choice = { type: map[tool_choice] || 'auto' };
} else if (tool_choice.type === 'function') {
// OpenAI object → Anthropic object
body.params.tool_choice = { type: 'tool', name: tool_choice.function?.name };
} else {
body.params.tool_choice = tool_choice;
}
}
if (parallel_tool_calls !== undefined) {
body.params.parallel_tool_calls = parallel_tool_calls;
}
return body;
}
function tryParseJSON(str) {
try { return JSON.parse(str); } catch { return {}; }
}
// ── CC NDJSON → OpenAI SSE 转换 ────────────────────
function createSseTranslator(model, completionId, created) {
let chunkIndex = 0;
let sentRole = false;
let finishReason = null;
let usage = null;
let toolCallIndex = 0;
return {
lastCcEvent: '',
inputTokens: 0,
outputTokens: 0,
cachedInputTokens: 0,
/** 解析一行 NDJSON,返回 OpenAI chunk 数组 */
parseLine(line) {
const trimmed = line.trim();
if (!trimmed || trimmed === '[DONE]' || trimmed.startsWith(':')) return null;
let event;
try { event = JSON.parse(trimmed); } catch { return null; }
if (!event.type) return null;
this.lastCcEvent = event.type;
const out = [];
switch (event.type) {
case 'text-start':
case 'reasoning-start':
case 'start':
case 'start-step':
// 忽略,无用户可见内容
break;
case 'text-delta': {
const text = event.text || event.delta || '';
if (!text) break;
const delta = chunkIndex === 0 ? { role: 'assistant', content: text } : { content: text };
chunkIndex++;
sentRole = true;
out.push(makeChunk(completionId, created, model, delta, null, null));
break;
}
case 'reasoning-delta': {
const text = event.text || '';
if (!text) break;
const delta = chunkIndex === 0
? { role: 'assistant', reasoning_content: text }
: { reasoning_content: text };
chunkIndex++;
out.push(makeChunk(completionId, created, model, delta, null, null));
break;
}
case 'tool-call': {
const id = event.toolCallId || `call_${Date.now()}_${toolCallIndex}`;
const name = event.toolName || '';
const args = typeof event.input === 'string' ? event.input : JSON.stringify(event.input || {});
const tcEntry = { index: toolCallIndex, id, type: 'function', function: { name, arguments: args } };
const delta = chunkIndex === 0
? { role: 'assistant', content: null, tool_calls: [tcEntry] }
: { tool_calls: [tcEntry] };
chunkIndex++;
toolCallIndex++;
out.push(makeChunk(completionId, created, model, delta, null, null));
break;
}
case 'finish-step': {
if (event.finishReason) finishReason = mapFinishReason(event.finishReason);
if (event.usage) {
usage = event.usage;
this.inputTokens = event.usage.inputTokens ?? 0;
this.outputTokens = event.usage.outputTokens ?? 0;
this.cachedInputTokens = event.usage.cachedInputTokens ?? 0;
}
break;
}
case 'finish': {
const fr = finishReason || mapFinishReason(event.finishReason || 'stop');
const u = event.totalUsage || usage || {};
normalizeUsage(u);
this.inputTokens = u.inputTokens ?? 0;
this.outputTokens = u.outputTokens ?? 0;
this.cachedInputTokens = u.cachedInputTokens ?? 0;
const openaiUsage = u ? {
prompt_tokens: u.inputTokens ?? 0,
completion_tokens: u.outputTokens ?? 0,
total_tokens: (u.inputTokens ?? 0) + (u.outputTokens ?? 0),
prompt_tokens_details: { cached_tokens: u.cachedInputTokens ?? 0 },
} : undefined;
out.push(makeChunk(completionId, created, model, {}, fr, openaiUsage));
break;
}
case 'error': {
const msg = event.error?.message || event.message || 'Unknown error';
log('warn', 'CC stream error', { message: msg });
// Don't emit a finish_reason chunk — let the natural stream termination
// handle it. Otherwise a subsequent finish(tool_calls) would be ignored
// by downstream agent loops that stop at the first finish_reason.
break;
}
case 'reasoning-end': case 'provider-metadata': case 'tool-input-start': case 'tool-input-delta': case 'tool-input-end': case 'tool-error': case 'text-end':
// Silent - no user-visible content
break;
default:
log('warn', 'Unknown CC event type', { type: event.type });
break;
}
return out.length > 0 ? out : null;
},
/** 获取 SSE 结束标记 */
getDoneEvent() {
return 'data: [DONE]\n\n';
},
};
}
function makeChunk(id, created, model, delta, finishReason, usage) {
const chunk = {
id,
object: 'chat.completion.chunk',
created,
model,
choices: [{ index: 0, delta, finish_reason: finishReason || null }],
};
if (usage) chunk.usage = usage;
return `data: ${JSON.stringify(chunk)}\n\n`;
}
// normalize CC usage stats:
// - outputTokens=0 → zero everything (anti false billing)
function normalizeUsage(u) {
if (!u) return;
const ot = Number(u.outputTokens);
if (!ot) { // 0, null, undefined, NaN → zero input + cached (anti false billing)
u.inputTokens = 0;
u.cachedInputTokens = 0;
}
}
function mapFinishReason(reason) {
switch (reason) {
case 'tool-calls': return 'tool_calls';
case 'length': return 'length';
case 'stop': return 'stop';
default: return reason || 'stop';
}
}
// ── 错误映射 ───────────────────────────────────────
const CC_STATUS_MAP = {
400: { status: 400, type: 'invalid_request_error' },
401: { status: 401, type: 'authentication_error' },
402: { status: 429, type: 'rate_limit_error' }, // payment required → rate limit
403: { status: 401, type: 'authentication_error' },
404: { status: 404, type: 'not_found' },
422: { status: 400, type: 'invalid_request_error' },
429: { status: 429, type: 'rate_limit_error' },
500: { status: 502, type: 'upstream_error' },
502: { status: 502, type: 'upstream_error' },
503: { status: 503, type: 'temporarily_unavailable' },
};
function mapCcError(ccStatus, ccBody) {
const mapped = CC_STATUS_MAP[ccStatus] || { status: 502, type: 'upstream_error' };
let message = `CC API error (${ccStatus})`;
if (ccBody) {
try {
const parsed = JSON.parse(ccBody);
message = parsed.error?.message || parsed.message || message;
} catch {
message = ccBody.slice(0, 200) || message;
}
}
// CC 429 响应可能带 retry-after
if (ccStatus === 429) {
return {
status: 429,
body: {
error: { message, type: 'rate_limit_error' },
retry_after: 30,
},
};
}
return { status: mapped.status, body: { error: { message, type: mapped.type } } };
}
// ── HTTP 请求处理 ──────────────────────────────────
function readBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
let totalSize = 0;
req.on('data', c => {
totalSize += c.length;
if (totalSize > MAX_BODY_SIZE) {
req.destroy(new Error('Request body too large'));
reject(new Error('Request body exceeds 10MB limit'));
}
chunks.push(c);
});
req.on('end', () => {
try { resolve(JSON.parse(Buffer.concat(chunks).toString())); }
catch { reject(new Error('Invalid JSON')); }
});
req.on('error', reject);
});
}
function sendJSON(res, status, data) {
const headers = { 'Content-Type': 'application/json' };
if (data && data.retry_after !== undefined) {
headers['Retry-After'] = String(data.retry_after);
}
res.writeHead(status, headers);
res.end(JSON.stringify(data));
}
function getApiKey(headers) {
// Try Authorization: Bearer header (OpenAI SDK style)
const auth = headers['authorization'] || headers['Authorization'] || '';
if (auth.startsWith('Bearer ')) {
const match = auth.slice(7).match(/user_[a-zA-Z0-9_-]+/);
if (match) return match[0];
}
// Fall back to x-api-key header (Anthropic SDK style)
const xKey = headers['x-api-key'] || headers['X-Api-Key'] || '';
if (xKey) {
const match = xKey.match(/user_[a-zA-Z0-9_-]+/);
if (match) return match[0];
}
return null;
}
// ── 流式转发 ────────────────────────────────────────
async function forwardToCC(body, apiKey, incomingHeaders = {}, signal) {
const url = `${CFG.apiBase}/alpha/generate`;
const traceparent = generateTraceparent();
const sessionId = getSessionId(incomingHeaders, apiKey);
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
'x-cli-environment': 'production',
'x-command-code-version': CC_VERSION,
'x-session-id': sessionId,
'x-co-flag': 'false',
'x-taste-learning': 'false',
'x-project-slug': fakeProjectSlug(sessionId),
'traceparent': traceparent,
},
body: JSON.stringify(body),
signal,
});
return response;
}
// ── 路由 ────────────────────────────────────────────
async function handleChatCompletions(req, res) {
let openaiReq;
try {
openaiReq = await readBody(req);
} catch {
sendJSON(res, 400, { error: { message: 'Invalid JSON body', type: 'invalid_request_error' } });
return;
}
const apiKey = getApiKey(req.headers);
if (!apiKey) {
sendJSON(res, 401, { error: { message: 'Missing API key. Send in Authorization: Bearer <key> or x-api-key header', type: 'auth_error' } });
return;
}
const stream = openaiReq.stream === true;
const model = openaiReq.model || 'deepseek/deepseek-v4-flash';
const completionId = `chatcmpl-${randomUUID().slice(0, 12)}`;
const created = nowUnix();
// 构建 CC 请求体
const ccBody = buildCcRequest(openaiReq);
// AbortController 用于客户端断连时真正打断 CC 上游(pi-commandcode-provider 模式)
const abortController = new AbortController();
let aborted = false;
// 提前初始化,断连回调/超时 catch 安全引用(避免块级作用域 ReferenceError)
const startTime = Date.now();
let bytesReceived = 0; let lastCcEvent = ''; let keepaliveCount = 0; let fullText = '';
let reader = null;
let translator = null;
try {
// 首次初始化(fingerprint + lifecycle)
await ensureInitialized(apiKey, abortController.signal);
// 转发到 CC API(传入客户端 headers,用于提取 session ID)
const ccResponse = await forwardToCC(ccBody, apiKey, req.headers, abortController.signal);
if (!ccResponse.ok) {
const errorText = await ccResponse.text().catch(() => '');
log('error', 'CC API error', { status: ccResponse.status });
const mapped = mapCcError(ccResponse.status, errorText);
sendJSON(res, mapped.status, mapped.body);
return;
}
// 下游断连检测:打断 CC 上游 + 记录日志
res.on('close', () => {
if (res.writableEnded) return; // Normal completion, not a disconnect
aborted = true;
const reason = lastCcEvent?.startsWith('tool-input') ? 'tool-input-silent-timeout'
: lastCcEvent?.includes('delta') ? 'streaming-active-disconnect'
: 'client-hangup';
abortController.signal.aborted || log('warn', 'Client disconnected', {
path: '/v1/chat/completions',
model, completionId, reason,
streaming: stream,
elapsedMs: Date.now() - startTime,
bytesSent: bytesReceived,
lastCcEvent: lastCcEvent || '(none)',
keepaliveCount,
inputTokens: translator?.inputTokens ?? 0,
outputTokens: translator?.outputTokens ?? 0,
cachedInputTokens: translator?.cachedInputTokens ?? 0,
});
if (!abortController.signal.aborted) {
// 断连前抢发 usage=0 终止 chunk,避免下游自行估算 token
try {
res.write(`data: ${JSON.stringify({
id: completionId,
object: 'chat.completion.chunk',
created,
model,
choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0, prompt_tokens_details: { cached_tokens: 0 } },
})}\n\n`);
res.write('data: [DONE]\n\n');
} catch {}
try { abortController.abort(); } catch {}
}
});
if (stream) {
// ── 流式响应 ──
translator = createSseTranslator(model, completionId, created);
let buffer = '';
let started = false; // 延迟写 200 header,超时/output=0 时返回 JSON 429/502 让 SDK 自动重试
const decoder = new TextDecoder();
reader = ccResponse.body.getReader();
try {
while (true) {
const result = await Promise.race([
reader.read(),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('STREAM_IDLE_TIMEOUT')), STREAM_IDLE_TIMEOUT_MS)
),
]);
const { done, value } = result;
if (done) break;
if (aborted) break;
bytesReceived += value.length;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
let hadOutput = false;
for (const line of lines) {
const events = translator.parseLine(line);
if (events) {
if (!started) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'X-Accel-Buffering': 'no',
});
started = true;
}
for (const evt of events) res.write(evt);
hadOutput = true;
}
if (translator.lastCcEvent) lastCcEvent = translator.lastCcEvent;
}
// silent events 期间发 keepalive,防止客户端超时断开
if (started && !hadOutput) { try { res.write(': keepalive\n\n'); keepaliveCount++; } catch {} }
}
if (!aborted) {
// 成功完成一次请求,重置连续超时计数
consecutiveTimeouts = 0;
// 处理剩余 buffer
if (buffer.trim()) {
const events = translator.parseLine(buffer);
if (events) {
if (!started) started = true;
for (const evt of events) res.write(evt);
}
}
// 输出 token 为 0 时记为错误,避免下游异常计费
if (translator.outputTokens === 0) {
try { if (!abortController.signal.aborted) abortController.abort(); } catch {}
if (!started) {
sendJSON(res, 429, { error: { message: 'Empty response from upstream (zero output tokens)', type: 'rate_limit_error' }, retry_after: 10 });
return;
}
try { res.write(`data: ${JSON.stringify({ error: { message: 'Empty response from upstream (zero output tokens)', type: 'rate_limit_error' }, retry_after: 10 })}\n\n`); } catch {}
} else {
if (!started) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'X-Accel-Buffering': 'no',
});
started = true;
}
res.write(translator.getDoneEvent());
}
}
} catch (e) {
if (aborted) {
// 客户端已断连,只清理(close handler 已调用 abortController.abort())
try { reader.cancel(); } catch {}
} else if (e.message === 'STREAM_IDLE_TIMEOUT') {
log('warn', 'Stream idle timeout', {
path: '/v1/chat/completions',
model,
streaming: true,
timeoutMs: STREAM_IDLE_TIMEOUT_MS,
elapsedMs: Date.now() - startTime,
id: completionId,
bytesReceived,
lastCcEvent: lastCcEvent || '(none)',
inputTokens: translator.inputTokens,
outputTokens: translator.outputTokens,
cachedInputTokens: translator.cachedInputTokens,
});
try { reader.cancel(); } catch {}
try { abortController.abort(); } catch {} // 打断 CC 上游,避免浪费 token
consecutiveTimeouts++;
const timeoutMsg = consecutiveTimeouts >= TIMEOUT_REDUCE_CONTEXT_THRESHOLD
? 'Response timeout - try reducing context length (summarize earlier messages)'
: 'Response timeout - request timed out';
if (!started) {
sendJSON(res, 429, { error: { message: timeoutMsg, type: 'rate_limit_error', input_tokens: 0 }, retry_after: 5 });
return;
}
if (!res.writableEnded) {
try { res.write(`data: ${JSON.stringify({ error: { message: timeoutMsg, type: 'rate_limit_error' }, retry_after: 5 })}\n\n`); } catch {}
try { res.destroy(); } catch {}
}
} else {
log('error', 'Stream error', { message: e.message });
try { abortController.abort(); } catch {} // 打断 CC 上游
if (!started) {
sendJSON(res, 502, { error: { message: `Upstream error: ${e.message}`, type: 'proxy_error', input_tokens: 0 }, retry_after: 10 });
return;
}
if (!res.writableEnded) {
try { res.write(`data: ${JSON.stringify({ error: { message: e.message, type: 'proxy_error' } })}\n\n`); } catch {}
}
}
}
if (!res.writableEnded) res.end();
} else {
// ── 非流式响应(缓冲完整 NDJSON)──
let reasoningContent = '';
let finishReason = 'stop';
let usage = null;
let toolCalls = null;
reader = ccResponse.body.getReader();
const decoder = new TextDecoder();
let buf = '';
const processLines = () => {