-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.js
More file actions
804 lines (739 loc) · 27.1 KB
/
Copy pathproxy.js
File metadata and controls
804 lines (739 loc) · 27.1 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
#!/usr/bin/env node
// Windows-compatible Node.js port of cc-proxy.
// Intercepts OpenCode's Anthropic API calls and rewrites them to use
// Claude Code's OAuth token (loaded from ~/.claude/.credentials.json).
'use strict';
const http = require('http');
const https = require('https');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { URL } = require('url');
// ---------- Config ----------
const DEFAULT_LISTEN_HOST = '127.0.0.1';
const DEFAULT_LISTEN_PORT = 34156;
const UPSTREAM_HOST = 'api.anthropic.com';
const UPSTREAM_BASE = `https://${UPSTREAM_HOST}`;
const OAUTH_CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e';
const TOKEN_REFRESH_URL = 'https://platform.claude.com/v1/oauth/token';
const CC_VERSION = '2.1.117';
const ANTHROPIC_VERSION = '2023-06-01';
const REQUIRED_BETAS = [
'claude-code-20250219',
'oauth-2025-04-20',
'interleaved-thinking-2025-05-14',
'context-management-2025-06-27',
'prompt-caching-scope-2026-01-05',
'advisor-tool-2026-03-01',
'effort-2025-11-24',
];
const STRIP_BETAS = [];
// opencode sends lowercase tool names. Claude Code's canonical tool names are
// CapitalCase and Anthropic's classifier treats lowercase as "third-party". Map
// outbound to CapitalCase; reverse in the SSE/JSON response.
const TOOL_NAME_MAP = {
bash: 'Bash',
read: 'Read',
glob: 'Glob',
grep: 'Grep',
edit: 'Edit',
write: 'Write',
task: 'Task',
task_write: 'TodoWrite',
todowrite: 'TodoWrite',
webfetch: 'WebFetch',
websearch: 'WebSearch',
skill: 'Skill',
bg_output: 'BashOutput',
background_output: 'BashOutput',
};
const REVERSE_TOOL_NAME_MAP = Object.fromEntries(
Object.entries(TOOL_NAME_MAP).map(([k, v]) => [v, k])
);
// Only forward tools whose post-mapping name is in Claude Code's canonical set.
const TOOL_ALLOWLIST = new Set([
'Bash', 'Read', 'Glob', 'Grep', 'Edit', 'Write',
'Task', 'TodoWrite', 'WebFetch', 'WebSearch', 'Skill', 'BashOutput',
'NotebookEdit',
]);
// ---------- Logging ----------
const LOG_FILE = path.join(__dirname, 'proxy.log');
const STATE_FILE = path.join(__dirname, 'proxy-state.json');
const LOG_MAX_BYTES = 10 * 1024 * 1024; // 10 MB, rotate once
function rotateLogIfNeeded() {
try {
const st = fs.statSync(LOG_FILE);
if (st.size > LOG_MAX_BYTES) {
fs.renameSync(LOG_FILE, LOG_FILE + '.1');
}
} catch { /* no file yet */ }
}
function log(tag, ...args) {
const ts = new Date().toISOString();
const line = `${ts} [${tag}] ` + args.map((a) =>
typeof a === 'string' ? a : (() => { try { return JSON.stringify(a); } catch { return String(a); } })()
).join(' ');
console.log(line);
try {
rotateLogIfNeeded();
fs.appendFileSync(LOG_FILE, line + '\n');
} catch { /* swallow file IO errors to never crash the proxy */ }
}
function loadProxyState() {
try {
const state = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
if (state && state.billingLine1 && state.billingLine2 && state.sessionId) {
return state;
}
} catch { /* create below */ }
const state = {
billingLine1: `x-anthropic-billing-header: cc_version=${CC_VERSION}.${randHex(3)}; cc_entrypoint=sdk-cli; cch=${randHex(5)};`,
billingLine2: `x-anthropic-billing-header: cc_version=${CC_VERSION}.${randHex(3)}; cc_entrypoint=sdk-cli; cch=${randHex(5)};`,
sessionId: ccSessionId(),
createdAt: new Date().toISOString(),
};
try {
fs.writeFileSync(STATE_FILE, JSON.stringify(state, null, 2) + '\n', { mode: 0o600 });
} catch (e) {
log('state', 'WARNING: could not persist proxy cache identity:', e.message);
}
return state;
}
// ---------- Token Manager ----------
class TokenManager {
constructor() {
this.creds = null;
this.refreshing = null; // Promise lock
}
credsFilePath() {
return path.join(os.homedir(), '.claude', '.credentials.json');
}
parseCredentials(raw) {
let obj;
try {
obj = JSON.parse(raw);
} catch (e) {
throw new Error(`parse credentials: ${e.message}`);
}
if (obj && obj.claudeAiOauth && obj.claudeAiOauth.accessToken) {
return obj.claudeAiOauth;
}
if (obj && obj.accessToken) {
return obj;
}
throw new Error('no access token in credentials');
}
loadFromFile() {
const p = this.credsFilePath();
const raw = fs.readFileSync(p, 'utf8').trim();
return this.parseCredentials(raw);
}
saveToFile() {
const p = this.credsFilePath();
let obj = {};
try {
obj = JSON.parse(fs.readFileSync(p, 'utf8'));
} catch {
obj = {};
}
if (obj && obj.claudeAiOauth && typeof obj.claudeAiOauth === 'object') {
obj.claudeAiOauth = {
...obj.claudeAiOauth,
accessToken: this.creds.accessToken,
refreshToken: this.creds.refreshToken,
expiresAt: this.creds.expiresAt,
};
} else if (obj && obj.accessToken) {
obj = {
...obj,
accessToken: this.creds.accessToken,
refreshToken: this.creds.refreshToken,
expiresAt: this.creds.expiresAt,
};
} else {
obj = { claudeAiOauth: this.creds };
}
const tmp = `${p}.tmp-${process.pid}`;
fs.writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', { mode: 0o600 });
fs.renameSync(tmp, p);
}
localStatus() {
const creds = this.creds || this.loadFromFile();
const refreshAt = creds.expiresAt - 5 * 60 * 1000;
return {
ok: Date.now() < refreshAt,
expiresAt: new Date(creds.expiresAt).toISOString(),
refreshRequired: Date.now() >= refreshAt,
};
}
async getValidToken() {
if (!this.creds) {
this.creds = this.loadFromFile();
log('token', `loaded from file (expires: ${new Date(this.creds.expiresAt).toISOString()})`);
}
// Refresh if within 5 minutes of expiry
if (Date.now() >= this.creds.expiresAt - 5 * 60 * 1000) {
await this.refresh();
}
return this.creds.accessToken;
}
async forceRefresh() {
return this.refresh();
}
async refresh() {
if (this.refreshing) return this.refreshing;
this.refreshing = (async () => {
try {
let refreshToken = this.creds && this.creds.refreshToken;
if (!refreshToken) {
this.creds = this.loadFromFile();
refreshToken = this.creds.refreshToken;
}
log('token', 'refreshing OAuth token...');
const form = new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
client_id: OAUTH_CLIENT_ID,
}).toString();
const result = await new Promise((resolve, reject) => {
const u = new URL(TOKEN_REFRESH_URL);
const req = https.request(
{
method: 'POST',
hostname: u.hostname,
port: u.port || 443,
path: u.pathname + u.search,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(form),
},
timeout: 30000,
},
(res) => {
const chunks = [];
res.on('data', (c) => chunks.push(c));
res.on('end', () => {
const body = Buffer.concat(chunks).toString('utf8');
if (res.statusCode !== 200) {
return reject(new Error(`refresh failed status=${res.statusCode} body=${body}`));
}
try {
resolve(JSON.parse(body));
} catch (e) {
reject(e);
}
});
}
);
req.on('error', reject);
req.on('timeout', () => req.destroy(new Error('refresh timeout')));
req.write(form);
req.end();
});
this.creds = {
accessToken: result.access_token,
refreshToken: result.refresh_token || refreshToken,
expiresAt: Date.now() + result.expires_in * 1000,
};
try {
this.saveToFile();
log('token', 'persisted refreshed OAuth token to credentials file');
} catch (e) {
log('token', 'WARNING: could not persist refreshed OAuth token:', e.message);
}
log('token', `refreshed (expires: ${new Date(this.creds.expiresAt).toISOString()})`);
} finally {
this.refreshing = null;
}
})();
return this.refreshing;
}
}
// ---------- Request transforms ----------
function transformBetaHeader(existing) {
const betas = (existing || '')
.split(',')
.map((s) => s.trim())
.filter(Boolean)
.filter((b) => !STRIP_BETAS.includes(b));
for (const r of REQUIRED_BETAS) if (!betas.includes(r)) betas.push(r);
return betas.join(',');
}
function buildUpstreamHeaders(origHeaders, token) {
// Start fresh — only forward what Claude Code would send, in the canonical shape.
const h = {};
h['accept'] = 'application/json';
h['content-type'] = 'application/json';
h['authorization'] = 'Bearer ' + token;
h['anthropic-version'] = ANTHROPIC_VERSION;
h['anthropic-beta'] = transformBetaHeader(origHeaders['anthropic-beta']);
h['anthropic-dangerous-direct-browser-access'] = 'true';
h['x-app'] = 'cli';
h['x-claude-code-session-id'] = STABLE_CC_SESSION_ID;
h['user-agent'] = `claude-cli/${CC_VERSION} (external, sdk-cli)`;
h['x-stainless-arch'] = 'x64';
h['x-stainless-lang'] = 'js';
h['x-stainless-os'] = 'Windows';
h['x-stainless-package-version'] = '0.81.0';
h['x-stainless-retry-count'] = '0';
h['x-stainless-runtime'] = 'node';
h['x-stainless-runtime-version'] = 'v24.3.0';
h['x-stainless-timeout'] = '600';
h['accept-encoding'] = 'identity';
return h;
}
const RE_AVAILABLE_SKILLS_OPEN = /<available_skills>/g;
const RE_AVAILABLE_SKILLS_CLOSE = /<\/available_skills>/g;
const RE_AGENT_IDENTITY = /<agent-identity>[\s\S]*?<\/agent-identity>/g;
const RE_ENV_OPEN = /<env>/g;
const RE_ENV_CLOSE = /<\/env>/g;
// Real Claude Code's first two system blocks. Anthropic's classifier requires
// these to start the system array for the request to bill against the plan.
const CC_DEVICE_ID = 'e43a5b7dd895c50e3d5ee132ae9fd3e33f35cb0f6a1dd491be15fe4e2a03a33f';
const CC_ACCOUNT_UUID = 'e0ed53bf-9b87-4712-8c33-6a7b9a9a921a';
function randHex(n) {
return require('crypto').randomBytes(Math.ceil(n / 2)).toString('hex').slice(0, n);
}
function ccSessionId() {
const b = require('crypto').randomBytes(16);
b[6] = (b[6] & 0x0f) | 0x40; b[8] = (b[8] & 0x3f) | 0x80;
const h = b.toString('hex');
return `${h.slice(0,8)}-${h.slice(8,12)}-${h.slice(12,16)}-${h.slice(16,20)}-${h.slice(20)}`;
}
// CACHE FIX: keep cache-identity strings stable across requests AND restarts.
// If these prompt-prefix strings change, Anthropic cannot reuse previously
// written cache entries even when the visible conversation is unchanged.
const PROXY_STATE = loadProxyState();
const STABLE_BILLING_LINE_1 = PROXY_STATE.billingLine1;
const STABLE_BILLING_LINE_2 = PROXY_STATE.billingLine2;
const STABLE_CC_SESSION_ID = PROXY_STATE.sessionId;
function transformSystemText(text) {
return text
.replace(RE_AVAILABLE_SKILLS_OPEN, '## Commands Reference')
.replace(RE_AVAILABLE_SKILLS_CLOSE, '')
.replace(RE_AGENT_IDENTITY, '')
.replace(RE_ENV_OPEN, '# Environment')
.replace(RE_ENV_CLOSE, '')
.replace(/\bOpenCode\b/g, 'Claude Code')
.replace(/opencode\.ai/gi, 'claude.com/claude-code')
.replace(/anomalyco\/opencode/gi, 'anthropics/claude-code')
.replace(/Is directory a git repo:/g, 'Is a git repository:'); // v14: trigger 우회
}
function transformSystemPrompt(msg) {
// Scrub opencode identity in whatever the caller sent
if (typeof msg.system === 'string') {
msg.system = [{ type: 'text', text: transformSystemText(msg.system) }];
} else if (Array.isArray(msg.system)) {
for (const block of msg.system) {
if (block && block.type === 'text' && typeof block.text === 'string') {
block.text = transformSystemText(block.text);
}
}
} else {
msg.system = [];
}
// v7+v8/v12: prepend 4 canonical Claude Code system blocks (billing+identity x2).
// CACHE FIX: use STABLE_BILLING_LINE_{1,2} (computed once at startup) so the
// system-prompt prefix is byte-identical across requests in the same proxy run.
const sdkLine = `You are a Claude agent, built on Anthropic's Claude Agent SDK.`;
msg.system = [
{ type: 'text', text: STABLE_BILLING_LINE_1 },
{ type: 'text', text: sdkLine },
{ type: 'text', text: STABLE_BILLING_LINE_2 },
{ type: 'text', text: sdkLine },
...msg.system,
];
}
function transformMessageContent(message) {
const c = message.content;
if (!Array.isArray(c)) return;
for (const block of c) {
if (!block || typeof block !== 'object') continue;
if ((block.type === 'tool_use' || block.type === 'tool_result') && typeof block.name === 'string') {
if (TOOL_NAME_MAP[block.name]) block.name = TOOL_NAME_MAP[block.name];
}
}
}
// CACHE FIX: Anthropic allows up to 4 prompt-cache breakpoints per request.
// Preserve caller markers whenever possible. If a caller sends too many, keep
// both stable prefix anchors (tools/system) and the newest conversation anchors
// instead of blindly deleting all early markers or all late markers.
function capCacheControl(msg, maxKeep = 4) {
const collected = [];
const scan = (blocks, segment) => {
if (!Array.isArray(blocks)) return;
for (const b of blocks) {
if (b && typeof b === 'object' && b.cache_control) collected.push({ block: b, segment });
}
};
if (msg && msg.cache_control) collected.push({ block: msg, segment: 'top-level' });
if (Array.isArray(msg.tools)) scan(msg.tools, 'tools');
scan(msg.system, 'system');
if (Array.isArray(msg.messages)) {
for (const m of msg.messages) {
if (m && Array.isArray(m.content)) scan(m.content, 'messages');
}
}
if (collected.length <= maxKeep) return;
const keep = new Set();
const keepFirst = (segment) => {
const entry = collected.find((item) => item.segment === segment);
if (entry && keep.size < maxKeep) keep.add(entry);
};
keepFirst('tools');
keepFirst('system');
for (let i = collected.length - 1; i >= 0 && keep.size < maxKeep; i--) {
keep.add(collected[i]);
}
for (const entry of collected) {
if (!keep.has(entry)) delete entry.block.cache_control;
}
log('cache', `trimmed cache_control markers ${collected.length}->${maxKeep}; kept=[${[...keep].map((entry) => entry.segment).join(',')}]`);
}
function stableMetadataUserId() {
return JSON.stringify({
device_id: CC_DEVICE_ID,
account_uuid: CC_ACCOUNT_UUID,
session_id: STABLE_CC_SESSION_ID,
});
}
function transformRequestBody(bodyBuf) {
let msg;
try {
msg = JSON.parse(bodyBuf.toString('utf8'));
} catch {
return bodyBuf;
}
if (Array.isArray(msg.tools)) {
// Rename known tools, then drop anything outside the Claude Code allowlist.
for (const tool of msg.tools) {
if (tool && typeof tool.name === 'string' && TOOL_NAME_MAP[tool.name]) {
tool.name = TOOL_NAME_MAP[tool.name];
}
}
// v11: allow MCP tools (mcp__server__tool) alongside the canonical allowlist.
const isKept = (t) => t && (TOOL_ALLOWLIST.has(t.name) || (typeof t.name === 'string' && t.name.startsWith('mcp__')));
const kept = msg.tools.filter(isKept);
if (kept.length !== msg.tools.length) {
const dropped = msg.tools.filter((t) => !isKept(t)).map((t) => t && t.name);
log('transform', `filtered tools: kept ${kept.length}/${msg.tools.length}, dropped=[${dropped.join(',')}]`);
}
msg.tools = kept;
}
if (Array.isArray(msg.messages)) {
for (const m of msg.messages) transformMessageContent(m);
}
transformSystemPrompt(msg);
// Inject Claude Code metadata + thinking/context fields.
// CACHE FIX: force a durable session_id even when the caller already sends a
// changing metadata.user_id value.
if (!msg.metadata) msg.metadata = {};
msg.metadata.user_id = stableMetadataUserId();
// CACHE FIX: keep up to 4 breakpoints (Anthropic's true limit), not 1.
capCacheControl(msg, 4);
return Buffer.from(JSON.stringify(msg), 'utf8');
}
// ---------- Response transforms ----------
function reverseToolNamesInContent(msg) {
if (!msg || !Array.isArray(msg.content)) return;
for (const block of msg.content) {
if (block && block.type === 'tool_use' && typeof block.name === 'string') {
if (REVERSE_TOOL_NAME_MAP[block.name]) block.name = REVERSE_TOOL_NAME_MAP[block.name];
}
}
}
function reverseToolNamesInSSEData(dataStr) {
let ev;
try { ev = JSON.parse(dataStr); } catch { return dataStr; }
switch (ev.type) {
case 'content_block_start':
if (ev.content_block && ev.content_block.type === 'tool_use'
&& typeof ev.content_block.name === 'string'
&& REVERSE_TOOL_NAME_MAP[ev.content_block.name]) {
ev.content_block.name = REVERSE_TOOL_NAME_MAP[ev.content_block.name];
}
break;
case 'message_start':
if (ev.message) reverseToolNamesInContent(ev.message);
break;
case 'message_delta':
if (ev.delta) reverseToolNamesInContent(ev.delta);
break;
}
return JSON.stringify(ev);
}
// CACHE FIX: extract usage from SSE events so proxy.log shows whether cache
// is actually working. Anthropic streams `message_start` with input/cache
// numbers, then `message_delta` with cumulative output_tokens at the end.
function applyUsageSnapshot(acc, u) {
if (!u) return;
if (typeof u.input_tokens === 'number') acc.in = u.input_tokens;
if (typeof u.output_tokens === 'number') acc.out = u.output_tokens;
if (typeof u.cache_read_input_tokens === 'number') acc.cache_read = u.cache_read_input_tokens;
if (typeof u.cache_creation_input_tokens === 'number') acc.cache_create = u.cache_creation_input_tokens;
if (u.cache_creation) {
if (typeof u.cache_creation.ephemeral_5m_input_tokens === 'number') acc.cache_create_5m = u.cache_creation.ephemeral_5m_input_tokens;
if (typeof u.cache_creation.ephemeral_1h_input_tokens === 'number') acc.cache_create_1h = u.cache_creation.ephemeral_1h_input_tokens;
}
}
function usageLine(usage) {
const total = usage.in + usage.cache_read + usage.cache_create;
return `in=${usage.in} total_in=${total} out=${usage.out} cache_read=${usage.cache_read} cache_create=${usage.cache_create} cache_create_5m=${usage.cache_create_5m} cache_create_1h=${usage.cache_create_1h}`;
}
function captureUsageFromSSE(dataStr, acc) {
let ev;
try { ev = JSON.parse(dataStr); } catch { return; }
if (ev.type === 'message_start' && ev.message && ev.message.usage) {
applyUsageSnapshot(acc, ev.message.usage);
} else if (ev.type === 'message_delta' && ev.usage) {
applyUsageSnapshot(acc, ev.usage);
}
}
function streamTransformSSE(upstreamRes, clientRes) {
let buf = '';
const usage = { in: 0, out: 0, cache_read: 0, cache_create: 0, cache_create_5m: 0, cache_create_1h: 0 };
upstreamRes.setEncoding('utf8');
upstreamRes.on('data', (chunk) => {
buf += chunk;
let idx;
while ((idx = buf.indexOf('\n')) !== -1) {
const line = buf.slice(0, idx);
buf = buf.slice(idx + 1);
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data !== '[DONE]') {
captureUsageFromSSE(data, usage);
clientRes.write('data: ' + reverseToolNamesInSSEData(data) + '\n');
continue;
}
}
clientRes.write(line + '\n');
}
});
upstreamRes.on('end', () => {
if (buf.length > 0) clientRes.write(buf);
clientRes.end();
log('usage', usageLine(usage));
});
upstreamRes.on('error', (e) => {
log('response', 'upstream stream error:', e.message);
clientRes.end();
});
}
function readAndTransformJSON(upstreamRes, clientRes) {
const chunks = [];
upstreamRes.on('data', (c) => chunks.push(c));
upstreamRes.on('end', () => {
const body = Buffer.concat(chunks);
let out = body;
try {
const msg = JSON.parse(body.toString('utf8'));
reverseToolNamesInContent(msg);
// CACHE FIX: log usage for non-streaming responses too.
if (msg.usage) {
const usage = { in: 0, out: 0, cache_read: 0, cache_create: 0, cache_create_5m: 0, cache_create_1h: 0 };
applyUsageSnapshot(usage, msg.usage);
log('usage', usageLine(usage));
}
out = Buffer.from(JSON.stringify(msg), 'utf8');
} catch { /* forward as-is */ }
clientRes.end(out);
});
upstreamRes.on('error', (e) => {
log('response', 'upstream read error:', e.message);
clientRes.end();
});
}
// ---------- Proxy ----------
const tokenMgr = new TokenManager();
// Claude Code always calls /v1/messages?beta=true. Add the flag if missing.
function ensureBetaQuery(pathAndQuery) {
if (!pathAndQuery.includes('/messages')) return pathAndQuery;
if (/[?&]beta=/.test(pathAndQuery)) return pathAndQuery;
return pathAndQuery + (pathAndQuery.includes('?') ? '&' : '?') + 'beta=true';
}
function doUpstreamRequest(method, pathAndQuery, headers, bodyBuf) {
pathAndQuery = ensureBetaQuery(pathAndQuery);
return new Promise((resolve, reject) => {
const req = https.request(
{
method,
hostname: UPSTREAM_HOST,
port: 443,
path: pathAndQuery,
headers: {
...headers,
'Content-Length': bodyBuf ? bodyBuf.length : 0,
},
timeout: 120000,
},
(res) => resolve(res)
);
req.on('error', reject);
req.on('timeout', () => req.destroy(new Error('upstream timeout')));
if (bodyBuf && bodyBuf.length > 0) req.write(bodyBuf);
req.end();
});
}
function copyResponseHeaders(upstreamRes, clientRes) {
for (const [k, v] of Object.entries(upstreamRes.headers)) {
const lk = k.toLowerCase();
if (lk === 'connection' || lk === 'transfer-encoding' || lk === 'content-encoding') continue;
clientRes.setHeader(k, v);
}
clientRes.statusCode = upstreamRes.statusCode;
}
async function handleRequest(req, res) {
if (req.url === '/health') {
try {
const status = tokenMgr.localStatus();
if (!status.ok) {
res.statusCode = 503;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ status: 'token_refresh_required', expiresAt: status.expiresAt }));
return;
}
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ status: 'ok', expiresAt: status.expiresAt }));
} catch (e) {
res.statusCode = 503;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ status: 'error: ' + e.message }));
}
return;
}
// Read request body
const chunks = [];
for await (const c of req) chunks.push(c);
let bodyBuf = Buffer.concat(chunks);
if (process.env.CC_PROXY_DEBUG) {
try { fs.writeFileSync('C:/tmp/raw-incoming.json', bodyBuf); } catch {}
}
const isMessages = req.url.includes('/messages');
if (isMessages && bodyBuf.length > 0) {
bodyBuf = transformRequestBody(bodyBuf);
}
let token;
try {
token = await tokenMgr.getValidToken();
} catch (e) {
log('proxy', 'token error:', e.message);
res.statusCode = 503;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'proxy token error: ' + e.message }));
return;
}
const headers = buildUpstreamHeaders(req.headers, token);
log('proxy', `${req.method} ${req.url} -> ${UPSTREAM_BASE}${req.url} (body: ${bodyBuf.length} bytes)`);
if (process.env.CC_PROXY_DEBUG) {
try { fs.writeFileSync('C:/tmp/last-sent.json', bodyBuf); } catch {}
try { fs.writeFileSync('C:/tmp/last-headers.json', JSON.stringify({incoming: req.headers, url: req.url, method: req.method}, null, 2)); } catch {}
}
let upstreamRes;
try {
upstreamRes = await doUpstreamRequest(req.method, req.url, headers, bodyBuf);
} catch (e) {
log('proxy', 'upstream error:', e.message);
res.statusCode = 502;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'upstream request failed: ' + e.message }));
return;
}
log('proxy', `upstream status=${upstreamRes.statusCode}`);
if (upstreamRes.statusCode >= 400 && upstreamRes.statusCode !== 401) {
// Swallow error body, log it, return JSON to client — don't try to stream
const chunks = [];
upstreamRes.on('data', (c) => chunks.push(c));
upstreamRes.on('end', () => {
const body = Buffer.concat(chunks).toString('utf8');
log('proxy', `upstream ${upstreamRes.statusCode} body:`, body.slice(0, 600));
copyResponseHeaders(upstreamRes, res);
res.end(body);
});
return;
}
if (upstreamRes.statusCode === 401) {
upstreamRes.resume();
log('proxy', 'got 401, refreshing token and retrying...');
try {
await tokenMgr.forceRefresh();
token = await tokenMgr.getValidToken();
const retryHeaders = buildUpstreamHeaders(req.headers, token);
upstreamRes = await doUpstreamRequest(req.method, req.url, retryHeaders, bodyBuf);
} catch (e) {
log('proxy', 'retry failed:', e.message);
res.statusCode = 503;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'token refresh failed: ' + e.message }));
return;
}
}
copyResponseHeaders(upstreamRes, res);
const ct = upstreamRes.headers['content-type'] || '';
if (isMessages && ct.includes('text/event-stream')) {
streamTransformSSE(upstreamRes, res);
} else if (isMessages) {
readAndTransformJSON(upstreamRes, res);
} else {
upstreamRes.pipe(res);
}
}
// ---------- Startup ----------
function parseArgs() {
const argv = process.argv.slice(2);
let host = DEFAULT_LISTEN_HOST;
let port = DEFAULT_LISTEN_PORT;
for (let i = 0; i < argv.length; i++) {
if (argv[i] === '-listen' || argv[i] === '--listen') {
const addr = argv[++i];
const m = addr.match(/^(.*):(\d+)$/);
if (m) { host = m[1]; port = parseInt(m[2], 10); }
}
}
return { host, port };
}
async function main() {
const { host, port } = parseArgs();
log('main', `cc-proxy starting on ${host}:${port}`);
log('main', `upstream: ${UPSTREAM_BASE}`);
try {
const status = tokenMgr.localStatus();
if (status.ok) {
log('main', `token available locally (expires: ${status.expiresAt})`);
} else {
log('main', `WARNING: token requires refresh/login before upstream use (expires: ${status.expiresAt})`);
}
} catch (e) {
log('main', 'WARNING: could not inspect local token:', e.message);
log('main', 'will retry on first request');
}
const server = http.createServer((req, res) => {
handleRequest(req, res).catch((e) => {
log('main', 'unhandled:', e && e.stack ? e.stack : e);
try {
res.statusCode = 500;
res.end(JSON.stringify({ error: 'internal proxy error' }));
} catch {}
});
});
server.on('error', (e) => {
log('main', 'server listen/runtime error:', e && e.stack ? e.stack : e);
process.exit(1);
});
server.listen(port, host, () => {
log('main', 'ready. Configure OpenCode with:');
log('main', ` ANTHROPIC_BASE_URL=http://${host}:${port}/v1`);
log('main', ' ANTHROPIC_API_KEY=proxy-placeholder');
});
const shutdown = () => {
log('main', 'shutting down...');
server.close(() => process.exit(0));
setTimeout(() => process.exit(0), 2000).unref();
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
}
main().catch((e) => {
log('main', 'fatal:', e && e.stack ? e.stack : e);
process.exit(1);
});