-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.mjs
More file actions
executable file
·1125 lines (996 loc) · 33.7 KB
/
proxy.mjs
File metadata and controls
executable file
·1125 lines (996 loc) · 33.7 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
#!/usr/bin/env node
/**
* copilot-proxy
*
* A zero-dependency localhost proxy that translates the Anthropic Messages API
* into OpenAI Chat Completions format for the GitHub Copilot API.
*
* This enables Claude Code (claude-cli) to use a GitHub Copilot subscription
* as its model backend instead of a direct Anthropic API key.
*
* Usage:
* ANTHROPIC_BASE_URL=http://localhost:4141 \
* ANTHROPIC_API_KEY=sk-ant-copilot-proxy-not-a-real-key \
* claude
*
* @license MIT
*/
import http from "node:http";
import https from "node:https";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { execSync } from "node:child_process";
const PORT = parseInt(process.env.COPILOT_PROXY_PORT || "4141");
const COPILOT_API = "api.business.githubcopilot.com";
const INTEGRATION_ID = "copilot-developer-cli";
const VERBOSE = process.argv.includes("--verbose") || process.argv.includes("-v");
// GitHub OAuth Device Flow config (same app as copilot-cli)
const GITHUB_CLIENT_ID = "Iv1.b507a08c87ecfe98";
// ─── Token Management ───────────────────────────────────────────────────────
let cachedToken = null;
// Track ratio of actual prompt_tokens to estimated tokens for calibration
let tokenCalibrationRatio = 1.0;
let tokenCalibrationSamples = 0;
function loadToken() {
// 1. Environment variable override
if (process.env.COPILOT_GITHUB_TOKEN) {
log("Using token from COPILOT_GITHUB_TOKEN env var");
return process.env.COPILOT_GITHUB_TOKEN;
}
// 2. OpenCode auth.json
const opencodePaths = [
path.join(os.homedir(), ".local/share/opencode/auth.json"),
path.join(
process.env.XDG_DATA_HOME || path.join(os.homedir(), ".local/share"),
"opencode/auth.json"
),
];
for (const p of opencodePaths) {
try {
const auth = JSON.parse(fs.readFileSync(p, "utf8"));
if (auth["github-copilot"]?.access) {
log(`Using token from ${p}`);
return auth["github-copilot"].access;
}
} catch {}
}
// 3. Copilot CLI keychain (macOS)
if (process.platform === "darwin") {
try {
const token = execSync(
'security find-generic-password -s "copilot-cli" -w 2>/dev/null',
{ encoding: "utf8", timeout: 5000 }
).trim();
if (token) {
log("Using token from macOS keychain (copilot-cli)");
return token;
}
} catch {}
}
// 4. GitHub CLI token (may not have copilot scope)
try {
const ghToken = execSync("gh auth token 2>/dev/null", {
encoding: "utf8",
timeout: 5000,
}).trim();
if (ghToken) {
log("Using token from gh CLI (may not have copilot access)");
return ghToken;
}
} catch {}
// 5. Legacy copilot extension config
const legacyPath = path.join(
os.homedir(),
".config/github-copilot/apps.json"
);
try {
const apps = JSON.parse(fs.readFileSync(legacyPath, "utf8"));
const first = Object.values(apps)[0];
if (first?.oauth_token) {
log(`Using token from ${legacyPath}`);
return first.oauth_token;
}
} catch {}
return null;
}
async function getToken() {
if (cachedToken) return cachedToken;
cachedToken = loadToken();
if (!cachedToken) {
console.log("\n⚠️ No GitHub Copilot token found.");
console.log("Starting GitHub Device Flow authentication...\n");
cachedToken = await githubDeviceFlow();
if (cachedToken) {
saveToken(cachedToken);
}
}
return cachedToken;
}
function saveToken(token) {
const authDir = path.join(os.homedir(), ".local/share/opencode");
const authFile = path.join(authDir, "auth.json");
try {
fs.mkdirSync(authDir, { recursive: true });
let existing = {};
try {
existing = JSON.parse(fs.readFileSync(authFile, "utf8"));
} catch {}
existing["github-copilot"] = {
type: "oauth",
refresh: token,
access: token,
expires: 0,
};
fs.writeFileSync(authFile, JSON.stringify(existing, null, 2));
log(`Token saved to ${authFile}`);
} catch (e) {
console.error("Warning: Could not save token:", e.message);
}
}
// ─── GitHub Device Flow ─────────────────────────────────────────────────────
function httpsPost(hostname, path, body) {
return new Promise((resolve, reject) => {
const data = typeof body === "string" ? body : JSON.stringify(body);
const req = https.request(
{
hostname,
port: 443,
path,
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Content-Length": Buffer.byteLength(data),
},
},
(res) => {
let chunks = [];
res.on("data", (c) => chunks.push(c));
res.on("end", () => {
try {
resolve(JSON.parse(Buffer.concat(chunks).toString()));
} catch {
resolve({ error: Buffer.concat(chunks).toString() });
}
});
}
);
req.on("error", reject);
req.write(data);
req.end();
});
}
async function githubDeviceFlow() {
const codeResp = await httpsPost("github.com", "/login/device/code", {
client_id: GITHUB_CLIENT_ID,
scope: "copilot",
});
if (!codeResp.device_code) {
console.error("Failed to start device flow:", codeResp);
return null;
}
console.log(`🔗 Open this URL: ${codeResp.verification_uri}`);
console.log(`📋 Enter code: ${codeResp.user_code}\n`);
console.log("Waiting for authorization...");
const interval = (codeResp.interval || 5) * 1000;
const expires = Date.now() + codeResp.expires_in * 1000;
while (Date.now() < expires) {
await new Promise((r) => setTimeout(r, interval));
const tokenResp = await httpsPost(
"github.com",
"/login/oauth/access_token",
{
client_id: GITHUB_CLIENT_ID,
device_code: codeResp.device_code,
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
}
);
if (tokenResp.access_token) {
console.log("✅ Authenticated successfully!\n");
return tokenResp.access_token;
}
if (
tokenResp.error === "authorization_pending" ||
tokenResp.error === "slow_down"
) {
continue;
}
console.error("Auth error:", tokenResp.error_description || tokenResp);
return null;
}
console.error("Authentication timed out.");
return null;
}
// ─── API Translation: Anthropic → OpenAI ────────────────────────────────────
// Claude-cli sends dashes (claude-opus-4-6), copilot wants dots (claude-opus-4.6)
// Supported direct mappings: opus 4.5/4.6, sonnet 4.5/4.6, haiku 4.5
const COPILOT_MODELS = new Set([
"claude-opus-4.5",
"claude-opus-4.6",
"claude-sonnet-4.5",
"claude-sonnet-4.6",
"claude-haiku-4.5",
]);
function mapModel(model) {
if (!model) return "claude-sonnet-4.6";
// Strip common prefixes
let clean = model.replace(/^anthropic\./, "");
// Already a valid copilot model ID
if (COPILOT_MODELS.has(clean)) return clean;
// Strip date suffixes: claude-opus-4-6-v1, claude-sonnet-4-5-20250929-v1, etc.
clean = clean.replace(/-\d{8}(-v\d+)?$/, "").replace(/-v\d+$/, "");
// Convert dashes to dots in version: claude-opus-4-6 → claude-opus-4.6
const match = clean.match(/^(claude-(?:opus|sonnet|haiku))-(\d+)-(\d+)$/);
if (match) {
const mapped = `${match[1]}-${match[2]}.${match[3]}`;
if (COPILOT_MODELS.has(mapped)) return mapped;
}
// Pass through for non-Claude models (gpt-5.2, gemini, etc.)
return clean;
}
function anthropicToOpenAI(body) {
const messages = [];
// System prompt
if (body.system) {
if (typeof body.system === "string") {
messages.push({ role: "system", content: body.system });
} else if (Array.isArray(body.system)) {
const text = body.system
.filter((b) => b.type === "text")
.map((b) => b.text)
.join("\n");
if (text) messages.push({ role: "system", content: text });
}
}
// Messages — handle compaction blocks (drop everything before them)
const rawMessages = body.messages || [];
let startIdx = 0;
let compactionSummary = null;
// Scan for the last compaction block — everything before it gets dropped
for (let i = rawMessages.length - 1; i >= 0; i--) {
const msg = rawMessages[i];
if (!Array.isArray(msg.content)) continue;
for (const block of msg.content) {
if (block.type === "compaction") {
startIdx = i;
compactionSummary = block.content;
break;
}
}
if (compactionSummary) break;
}
// If a compaction block was found, inject the summary as a user context message
if (compactionSummary) {
messages.push({
role: "user",
content: `<context>\nThe following is a summary of our conversation so far:\n\n${compactionSummary}\n</context>`,
});
}
for (const msg of rawMessages.slice(startIdx)) {
const role = msg.role === "assistant" ? "assistant" : "user";
if (typeof msg.content === "string") {
messages.push({ role, content: msg.content });
continue;
}
if (!Array.isArray(msg.content)) {
messages.push({ role, content: JSON.stringify(msg.content) });
continue;
}
// Process content blocks
const parts = [];
const toolCalls = [];
for (const block of msg.content) {
switch (block.type) {
case "text":
parts.push(block.text);
break;
case "image":
parts.push({
type: "image_url",
image_url: {
url: `data:${block.source.media_type};base64,${block.source.data}`,
},
});
break;
case "tool_use":
toolCalls.push({
id: block.id,
type: "function",
function: {
name: block.name,
arguments: JSON.stringify(block.input),
},
});
break;
case "tool_result":
// Tool results become separate messages in OpenAI format
messages.push({
role: "tool",
tool_call_id: block.tool_use_id,
content:
typeof block.content === "string"
? block.content
: JSON.stringify(block.content),
});
break;
case "thinking":
// Pass thinking as a system-like annotation
parts.push(`<thinking>${block.thinking}</thinking>`);
break;
case "compaction":
// Already handled above — skip
break;
}
}
if (parts.length > 0 || toolCalls.length > 0) {
const m = { role };
if (parts.length === 1 && typeof parts[0] === "string") {
m.content = parts[0];
} else if (parts.length > 0) {
// If we have image parts, use the array format
const hasImages = parts.some((p) => typeof p !== "string");
if (hasImages) {
m.content = parts.map((p) =>
typeof p === "string" ? { type: "text", text: p } : p
);
} else {
m.content = parts.join("\n");
}
}
if (toolCalls.length > 0) {
m.tool_calls = toolCalls;
if (!m.content) m.content = null;
}
messages.push(m);
}
}
// Build OpenAI request
const req = {
model: mapModel(body.model),
messages,
stream: body.stream || false,
};
if (body.max_tokens) req.max_tokens = body.max_tokens;
if (body.temperature != null) req.temperature = body.temperature;
if (body.top_p != null) req.top_p = body.top_p;
if (body.stop_sequences) req.stop = body.stop_sequences;
// Tools
if (body.tools?.length) {
req.tools = body.tools.map((t) => ({
type: "function",
function: {
name: t.name,
description: t.description || "",
parameters: t.input_schema || {},
},
}));
}
// Extended thinking → reasoning_effort
if (body.thinking?.type === "enabled") {
// Copilot doesn't directly support thinking, pass as parameter
req.reasoning_effort = "high";
}
return req;
}
function openAIToAnthropic(oaiResp, requestModel) {
const choice = oaiResp.choices?.[0];
if (!choice) {
return {
id: oaiResp.id || `msg_${Date.now()}`,
type: "message",
role: "assistant",
content: [{ type: "text", text: "" }],
model: requestModel,
stop_reason: "end_turn",
usage: { input_tokens: 0, output_tokens: 0 },
};
}
const content = [];
const msg = choice.message;
if (msg.content) {
content.push({ type: "text", text: msg.content });
}
if (msg.tool_calls) {
for (const tc of msg.tool_calls) {
content.push({
type: "tool_use",
id: tc.id,
name: tc.function.name,
input: safeJsonParse(tc.function.arguments),
});
}
}
if (content.length === 0) {
content.push({ type: "text", text: "" });
}
const stopMap = {
stop: "end_turn",
length: "max_tokens",
tool_calls: "tool_use",
function_call: "tool_use",
};
return {
id: `msg_${oaiResp.id || Date.now()}`,
type: "message",
role: "assistant",
content,
model: requestModel,
stop_reason: stopMap[choice.finish_reason] || "end_turn",
stop_sequence: null,
usage: {
input_tokens: oaiResp.usage?.prompt_tokens || 0,
output_tokens: oaiResp.usage?.completion_tokens || 0,
cache_creation_input_tokens: 0,
cache_read_input_tokens:
oaiResp.usage?.prompt_tokens_details?.cached_tokens || 0,
},
};
}
// ─── Streaming Translation ──────────────────────────────────────────────────
function streamOpenAIToAnthropic(res, requestModel, requestId) {
// Send Anthropic SSE stream events
const msgId = `msg_${requestId}`;
sendSSE(res, "message_start", {
type: "message_start",
message: {
id: msgId,
type: "message",
role: "assistant",
content: [],
model: requestModel,
stop_reason: null,
stop_sequence: null,
usage: { input_tokens: 0, output_tokens: 0 },
},
});
sendSSE(res, "content_block_start", {
type: "content_block_start",
index: 0,
content_block: { type: "text", text: "" },
});
let contentIndex = 0;
let pendingToolCalls = {};
let usage = { input_tokens: 0, output_tokens: 0 };
let buffer = "";
return {
processChunk(chunk) {
buffer += chunk;
const lines = buffer.split("\n");
buffer = lines.pop() || "";
for (const line of lines) {
if (!line.startsWith("data: ")) continue;
const data = line.slice(6).trim();
if (data === "[DONE]") {
this.finish(res);
return;
}
let parsed;
try {
parsed = JSON.parse(data);
} catch {
continue;
}
const delta = parsed.choices?.[0]?.delta;
const finishReason = parsed.choices?.[0]?.finish_reason;
if (parsed.usage) {
usage.input_tokens = parsed.usage.prompt_tokens || 0;
usage.output_tokens = parsed.usage.completion_tokens || 0;
}
if (delta?.content) {
sendSSE(res, "content_block_delta", {
type: "content_block_delta",
index: contentIndex,
delta: { type: "text_delta", text: delta.content },
});
}
if (delta?.tool_calls) {
for (const tc of delta.tool_calls) {
const idx = tc.index ?? 0;
if (!pendingToolCalls[idx]) {
// Close text block, start tool block
sendSSE(res, "content_block_stop", {
type: "content_block_stop",
index: contentIndex,
});
contentIndex++;
pendingToolCalls[idx] = {
id: tc.id || `toolu_${Date.now()}_${idx}`,
name: tc.function?.name || "",
args: "",
};
sendSSE(res, "content_block_start", {
type: "content_block_start",
index: contentIndex,
content_block: {
type: "tool_use",
id: pendingToolCalls[idx].id,
name: pendingToolCalls[idx].name,
input: {},
},
});
}
if (tc.function?.arguments) {
pendingToolCalls[idx].args += tc.function.arguments;
sendSSE(res, "content_block_delta", {
type: "content_block_delta",
index: contentIndex,
delta: {
type: "input_json_delta",
partial_json: tc.function.arguments,
},
});
}
}
}
if (finishReason) {
const stopMap = {
stop: "end_turn",
length: "max_tokens",
tool_calls: "tool_use",
};
this.stopReason = stopMap[finishReason] || "end_turn";
}
}
},
finish(res) {
sendSSE(res, "content_block_stop", {
type: "content_block_stop",
index: contentIndex,
});
sendSSE(res, "message_delta", {
type: "message_delta",
delta: {
stop_reason: this.stopReason || "end_turn",
stop_sequence: null,
},
usage: { output_tokens: usage.output_tokens },
});
sendSSE(res, "message_stop", { type: "message_stop" });
res.end();
},
stopReason: "end_turn",
get usage() { return usage; },
};
}
function sendSSE(res, event, data) {
res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
}
// ─── HTTP Proxy Server ──────────────────────────────────────────────────────
function proxyRequest(method, reqPath, headers, body) {
return new Promise((resolve, reject) => {
const req = https.request(
{
hostname: COPILOT_API,
port: 443,
path: reqPath,
method,
headers: {
...headers,
Host: COPILOT_API,
},
},
(res) => resolve(res)
);
req.on("error", reject);
if (body) req.write(body);
req.end();
});
}
async function handleMessages(req, res) {
const token = await getToken();
if (!token) {
res.writeHead(401, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "No GitHub Copilot token available" }));
return;
}
let rawBody = "";
for await (const chunk of req) rawBody += chunk;
let anthropicReq;
try {
anthropicReq = JSON.parse(rawBody);
} catch {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "Invalid JSON" }));
return;
}
const requestModel = anthropicReq.model || "claude-sonnet-4.6";
// Debug: log request structure to diagnose compaction
if (VERBOSE) {
const reqKeys = Object.keys(anthropicReq).join(", ");
log(`Request keys: [${reqKeys}]`);
if (anthropicReq.context_management) {
log(`context_management: ${JSON.stringify(anthropicReq.context_management)}`);
} else {
log("No context_management in request");
}
// Log beta headers
const betaHeader = req.headers["anthropic-beta"] || req.headers["x-anthropic-beta"];
if (betaHeader) log(`anthropic-beta header: ${betaHeader}`);
// Log message count and estimated size
const msgCount = anthropicReq.messages?.length || 0;
const rawSize = rawBody.length;
log(`Messages: ${msgCount}, raw body size: ${rawSize} bytes (~${Math.ceil(rawSize/4)} est tokens)`);
}
// Extract compaction config from request, or use proxy defaults
let compactionConfig = extractCompactionConfig(anthropicReq);
if (compactionConfig) {
delete anthropicReq.context_management;
log(`Compaction config from client: trigger=${compactionConfig.triggerTokens}, pause=${compactionConfig.pauseAfter}`);
} else {
// Claude Code doesn't send compact_20260112 through this proxy —
// inject proxy-side compaction with per-model thresholds (~65-70% of context)
const mappedModel = mapModel(requestModel);
const trigger = MODEL_COMPACTION_TRIGGERS[mappedModel] || DEFAULT_COMPACTION_TRIGGER;
compactionConfig = {
triggerTokens: trigger,
pauseAfter: true,
instructions: DEFAULT_COMPACTION_INSTRUCTIONS,
};
if (VERBOSE) log(`Using proxy-side compaction: model=${mappedModel}, trigger=${trigger}`);
}
// Strip context_management regardless (Copilot doesn't understand it)
delete anthropicReq.context_management;
const openaiReq = anthropicToOpenAI(anthropicReq);
const openaiBody = JSON.stringify(openaiReq);
if (VERBOSE) {
log(
`→ ${requestModel} → ${openaiReq.model} | ${openaiReq.messages.length} msgs | stream=${openaiReq.stream}`
);
}
try {
// Check if compaction should trigger
if (compactionConfig) {
const estimatedTokens = estimateTokens(openaiBody);
log(`Token estimate: ~${estimatedTokens} (threshold: ${compactionConfig.triggerTokens})`);
if (estimatedTokens >= compactionConfig.triggerTokens) {
log("Compaction threshold exceeded — triggering summarization");
const compactionResult = await performCompaction(
openaiReq.messages,
requestModel,
compactionConfig.instructions,
token
);
if (compactionResult) {
return sendCompactionResponse(
res,
requestModel,
compactionResult,
compactionConfig,
openaiReq.stream,
openaiReq.messages
);
}
log("Compaction failed, proceeding with normal request");
}
}
const upstream = await proxyRequest(
"POST",
"/chat/completions",
{
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
"Copilot-Integration-Id": INTEGRATION_ID,
"Editor-Version": "copilot-proxy/1.0.0",
"Content-Length": Buffer.byteLength(openaiBody),
},
openaiBody
);
if (upstream.statusCode === 401 || upstream.statusCode === 403) {
// Token expired, clear cache and retry once
log("Token rejected, clearing cache");
cachedToken = null;
const newToken = await getToken();
if (!newToken) {
res.writeHead(401, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "Authentication failed" }));
return;
}
return handleMessages(req, res);
}
if (upstream.statusCode !== 200) {
let errBody = "";
for await (const chunk of upstream) errBody += chunk;
log(`Upstream error ${upstream.statusCode}: ${errBody}`);
res.writeHead(upstream.statusCode, {
"Content-Type": "application/json",
});
res.end(errBody);
return;
}
if (openaiReq.stream) {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
});
const translator = streamOpenAIToAnthropic(
res,
requestModel,
Date.now().toString(36)
);
upstream.on("data", (chunk) =>
translator.processChunk(chunk.toString())
);
upstream.on("end", () => {
if (!res.writableEnded) translator.finish(res);
// Calibrate from streaming usage
const estimatedTokens = estimateTokens(openaiBody);
calibrateTokenEstimate(estimatedTokens, translator.usage?.input_tokens);
});
upstream.on("error", (e) => {
log(`Stream error: ${e.message}`);
if (!res.writableEnded) res.end();
});
} else {
let respBody = "";
for await (const chunk of upstream) respBody += chunk;
const openaiResp = JSON.parse(respBody);
const anthropicResp = openAIToAnthropic(openaiResp, requestModel);
// Calibrate token estimates with actual usage
const estimatedTokens = estimateTokens(openaiBody);
calibrateTokenEstimate(estimatedTokens, openaiResp.usage?.prompt_tokens);
if (VERBOSE) {
log(
`← ${anthropicResp.stop_reason} | ${anthropicResp.usage.input_tokens}in/${anthropicResp.usage.output_tokens}out`
);
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(anthropicResp));
}
} catch (e) {
log(`Proxy error: ${e.message}`);
res.writeHead(502, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
type: "error",
error: { type: "api_error", message: e.message },
})
);
}
}
function handleModels(req, res) {
// Return a fake models list so claude-cli doesn't complain
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
data: [
{ id: "claude-opus-4-6", display_name: "Claude Opus 4.6 (Copilot)" },
{
id: "claude-sonnet-4-6",
display_name: "Claude Sonnet 4.6 (Copilot)",
},
{
id: "claude-haiku-4-5",
display_name: "Claude Haiku 4.5 (Copilot)",
},
],
})
);
}
const server = http.createServer(async (req, res) => {
// CORS
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "*");
if (req.method === "OPTIONS") {
res.writeHead(204);
res.end();
return;
}
const url = new URL(req.url, `http://localhost:${PORT}`);
log(`${req.method} ${url.pathname}`);
if (url.pathname === "/v1/messages" && req.method === "POST") {
return handleMessages(req, res);
}
if (url.pathname === "/v1/models" && req.method === "GET") {
return handleModels(req, res);
}
// Health check
if (url.pathname === "/" || url.pathname === "/health") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ status: "ok", proxy: "copilot-proxy" }));
return;
}
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "Not found" }));
});
server.listen(PORT, "127.0.0.1", async () => {
const token = await getToken();
console.log(`
┌─────────────────────────────────────────────────┐
│ 🚀 Copilot Proxy running on port ${PORT} │
│ │
│ Token: ${token ? "✅ loaded" : "❌ not found"} │
│ │
│ Usage with claude-cli: │
│ ANTHROPIC_BASE_URL=http://localhost:${PORT} │
│ ANTHROPIC_API_KEY=copilot │
│ claude │
└─────────────────────────────────────────────────┘
`);
});
// ─── Compaction ─────────────────────────────────────────────────────────────
// Compaction triggers at ~65-70% of each model's context window
// Values are in estimated tokens (chars/4 heuristic)
const MODEL_COMPACTION_TRIGGERS = {
"claude-opus-4.6": 130_000, // 200K context → ~65%
"claude-opus-4.5": 130_000, // 200K context → ~65%
"claude-sonnet-4.6": 130_000, // 200K context → ~65%
"claude-sonnet-4.5": 130_000, // 200K context → ~65%
"claude-haiku-4.5": 130_000, // 200K context → ~65%
};
const DEFAULT_COMPACTION_TRIGGER = 100_000;
const MIN_COMPACTION_TRIGGER = 50_000;
const DEFAULT_COMPACTION_INSTRUCTIONS = `Please provide a detailed summary of the conversation so far. Focus on:
1. Key decisions made and their rationale
2. Current state of any tasks in progress
3. Important code changes, file paths, and technical details
4. Any unresolved questions or next steps
Preserve specific details like file paths, function names, error messages, and configuration values that would be needed to continue the work.`;
function extractCompactionConfig(body) {
const edits = body.context_management?.edits;
if (!Array.isArray(edits)) return null;
const compact = edits.find((e) => e.type === "compact_20260112");
if (!compact) return null;
const triggerTokens = Math.max(
compact.trigger?.value || DEFAULT_COMPACTION_TRIGGER,
MIN_COMPACTION_TRIGGER
);
return {
triggerTokens,
pauseAfter: compact.pause_after_compaction ?? true,
instructions: compact.instructions || DEFAULT_COMPACTION_INSTRUCTIONS,
};
}
function estimateTokens(serialized) {
const str = typeof serialized === "string" ? serialized : JSON.stringify(serialized);
const raw = Math.ceil(str.length / 4);
return Math.ceil(raw * tokenCalibrationRatio);
}
function calibrateTokenEstimate(estimatedTokens, actualPromptTokens) {
if (!actualPromptTokens || actualPromptTokens <= 0) return;
const ratio = actualPromptTokens / (estimatedTokens / tokenCalibrationRatio);
// Exponential moving average
tokenCalibrationSamples++;
const alpha = Math.min(0.3, 1 / tokenCalibrationSamples);
tokenCalibrationRatio = tokenCalibrationRatio * (1 - alpha) + ratio * alpha;
if (VERBOSE) {
log(`Token calibration: est=${estimatedTokens} actual=${actualPromptTokens} ratio=${tokenCalibrationRatio.toFixed(3)}`);
}
}
function sendCompactionResponse(res, requestModel, compactionResult, config, isStreaming, originalMessages) {
const msgId = `msg_${Date.now().toString(36)}`;
const compactionUsage = compactionResult.usage;
if (isStreaming) {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
});
// message_start
sendSSE(res, "message_start", {
type: "message_start",
message: {
id: msgId,
type: "message",
role: "assistant",
content: [],
model: requestModel,
stop_reason: null,
stop_sequence: null,
usage: { input_tokens: compactionUsage.input_tokens, output_tokens: 0 },
},
});
// compaction content block
sendSSE(res, "content_block_start", {
type: "content_block_start",
index: 0,