-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.ts
More file actions
650 lines (584 loc) · 21.3 KB
/
Copy pathserver.ts
File metadata and controls
650 lines (584 loc) · 21.3 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
import http from "node:http";
import { Readable } from "node:stream";
import { URL } from "node:url";
import type { Config } from "@/config.js";
import { toCCRequest, OpenAIStreamEncoder, buildNonStreamingResponse } from "@/translate/openai.js";
import {
toCCRequest as anToCCRequest,
AnthropicStreamEncoder,
buildAnthropicResponse,
} from "@/translate/anthropic.js";
import { getDefaultModels, fetchModelList } from "@/translate/models.js";
import type { CCEvent } from "@/translate/types.js";
import { formatSSE, formatSSEDone, formatAnthropicSSE } from "@/stream.js";
import { sendToCC, collectEvents, UpstreamError } from "@/upstream.js";
import { logger } from "@/logger.js";
import {
validateOpenAIChatRequest,
validateAnthropicRequest,
ValidationError,
} from "@/translate/validation.js";
import type { AnthropicRequest, AnthropicSSERecord } from "@/translate/anthropic-types.js";
// ──────────────────────────────────────────
// Mutable server state
// ──────────────────────────────────────────
let config: Config;
let modelList: string[] = getDefaultModels();
let corsOrigin = "*";
function updateModelList(models: string[]): void {
if (models.length > 0) modelList = models;
}
// ──────────────────────────────────────────
// Request body parser
// ──────────────────────────────────────────
const MAX_BODY_BYTES = 10 * 1024 * 1024; // 10 MiB
export class BodyParseError extends Error {
constructor(
public readonly status: number,
message: string,
) {
super(message);
this.name = "BodyParseError";
}
}
function parseBody(req: http.IncomingMessage): Promise<unknown> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let size = 0;
let tooLarge = false;
req.on("data", (chunk: Buffer) => {
if (tooLarge) return;
size += chunk.length;
if (size > MAX_BODY_BYTES) {
tooLarge = true;
// Tear down the underlying socket so the client stops uploading the
// rest of an oversized body. Without this the connection lingers
// until the client finishes (or its own timeout fires) — wasting
// bandwidth and a request slot.
req.destroy();
reject(new BodyParseError(413, "Request body too large"));
return;
}
chunks.push(chunk);
});
req.on("end", () => {
if (tooLarge) return;
const raw = Buffer.concat(chunks).toString("utf-8");
if (!raw) return resolve(null);
try {
resolve(JSON.parse(raw));
} catch {
reject(new BodyParseError(400, "Invalid JSON body"));
}
});
req.on("error", (err) => {
if (!tooLarge) reject(err);
});
});
}
// ──────────────────────────────────────────
// Auth
// ──────────────────────────────────────────
function extractApiKey(req: http.IncomingMessage): string | null {
let key: string | null = null;
const auth = req.headers.authorization;
if (auth) {
const m = auth.match(/^Bearer\s+(.+)$/i);
if (m) key = m[1];
}
if (!key) {
const xApiKey = req.headers["x-api-key"] as string | undefined;
if (xApiKey) key = xApiKey;
}
// If the client sent "proxy-managed" or no key, fall back to the proxy's configured key
if (!key || key === "proxy-managed" || key === "placeholder") {
logger.debug(`client key sentinel, using config key (length: ${config.apiKey?.length ?? 0})`);
return config.apiKey;
}
logger.debug(`using client's own key (length: ${key.length})`);
return key;
}
// ──────────────────────────────────────────
// Response helpers
// ──────────────────────────────────────────
function sendJson(res: http.ServerResponse, status: number, data: unknown): void {
// Client may have disconnected mid-request; never write to a dead socket.
if (res.headersSent || res.writableEnded || res.destroyed) return;
res.writeHead(status, {
"Content-Type": "application/json",
...corsHeaders(),
});
res.end(JSON.stringify(data));
}
function sendOpenAIError(res: http.ServerResponse, status: number, message: string): void {
sendJson(res, status, { error: { message, type: "proxy_error" } });
}
const ANTHROPIC_STATUS_ERROR_MAP: Record<number, string> = {
400: "invalid_request_error",
401: "authentication_error",
403: "permission_error",
404: "not_found_error",
429: "rate_limit_error",
500: "api_error",
529: "overloaded_error",
};
function sendAnthropicError(
res: http.ServerResponse,
status: number,
type: string,
message: string,
): void {
if (res.headersSent || res.writableEnded || res.destroyed) return;
res.writeHead(status, { "Content-Type": "application/json", ...corsHeaders() });
res.end(JSON.stringify({ type: "error", error: { type, message } }));
}
function corsHeaders(): Record<string, string> {
const origin = corsOrigin;
const headers: Record<string, string> = {
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization, x-api-key",
};
// Empty CORS_ORIGIN disables the header entirely (browser blocks cross-origin).
if (origin) headers["Access-Control-Allow-Origin"] = origin;
return headers;
}
// ──────────────────────────────────────────
// Helpers
// ──────────────────────────────────────────
function abortOnClientDisconnect(
req: http.IncomingMessage,
res: http.ServerResponse,
): AbortController {
const abort = new AbortController();
req.on("close", () => {
if (!res.writableEnded) abort.abort();
});
return abort;
}
function destroyStreamOnClientDisconnect(
req: http.IncomingMessage,
stream: NodeJS.ReadableStream,
): void {
req.on("close", () => (stream as Readable).destroy());
}
/**
* Write a chunk to `res`, returning a Promise that resolves once the
* underlying socket has drained (when backpressure applies). Returns
* `false` if the response is no longer writable.
*/
function writeSSE(res: http.ServerResponse, chunk: string): Promise<boolean> {
if (res.writableEnded || res.destroyed) return Promise.resolve(false);
if (res.write(chunk)) return Promise.resolve(true);
return new Promise((resolve) => {
res.once("drain", () => resolve(!res.writableEnded && !res.destroyed));
});
}
/**
* Drive the upstream CC stream through `encoder`, writing formatted SSE
* records to `res`. Applies client-side backpressure (pauses the upstream
* when `res` buffers fill), and isolates encoder errors so they terminate
* the stream cleanly instead of crashing the process.
*/
async function pumpStream(
stream: NodeJS.ReadableStream,
res: http.ServerResponse,
encode: (event: CCEvent) => string[],
onEnd: () => string[],
onError: (err: Error) => string[],
): Promise<void> {
const writable = (chunk: string): Promise<boolean> => writeSSE(res, chunk);
try {
for await (const event of stream) {
let chunks: string[];
try {
chunks = encode(event as unknown as CCEvent);
} catch (err) {
// Encoder blew up — turn it into a stream error so the catch below
// handles it uniformly instead of crashing the proxy.
(stream as Readable).destroy(err as Error);
break;
}
for (const chunk of chunks) {
if (!(await writable(chunk))) return;
}
}
for (const chunk of onEnd()) {
if (!(await writable(chunk))) return;
}
} catch (err) {
logger.error("[stream] upstream streaming error:", (err as Error).message);
for (const chunk of onError(err as Error)) {
if (!(await writable(chunk))) return;
}
}
}
// ──────────────────────────────────────────
// Route handlers
// ──────────────────────────────────────────
function handleHealth(_req: http.IncomingMessage, res: http.ServerResponse): void {
sendJson(res, 200, {
status: "ok",
version: process.env.npm_package_version ?? "0.1.0",
});
}
function handleModels(req: http.IncomingMessage, res: http.ServerResponse): void {
const isAnthropic = req.headers["anthropic-version"] !== undefined;
if (isAnthropic) {
const items = modelList;
const data = {
data: items.map((id: string) => ({
id,
type: "model" as const,
display_name: id,
created_at: new Date().toISOString(),
max_input_tokens: null as number | null,
max_tokens: null as number | null,
capabilities: null,
})),
has_more: false,
first_id: items.length > 0 ? items[0] : null,
last_id: items.length > 0 ? items[items.length - 1] : null,
};
sendJson(res, 200, data);
return;
}
const data = {
object: "list",
data: modelList.map((id: string) => ({
id,
object: "model",
created: Math.floor(Date.now() / 1000),
owned_by: "commandcode",
})),
};
sendJson(res, 200, data);
}
async function handleChatCompletions(
req: http.IncomingMessage,
res: http.ServerResponse,
): Promise<void> {
let rawBody: unknown;
try {
rawBody = await parseBody(req);
} catch (err) {
const status = err instanceof BodyParseError ? err.status : 400;
const message = err instanceof BodyParseError ? err.message : "Invalid JSON body";
return sendOpenAIError(res, status, message);
}
let openAIReq;
try {
openAIReq = validateOpenAIChatRequest(rawBody);
} catch (err) {
if (err instanceof ValidationError) {
return sendOpenAIError(res, 400, err.message);
}
return sendOpenAIError(res, 400, "Invalid request body");
}
const apiKey = extractApiKey(req);
if (!apiKey) {
return sendOpenAIError(res, 401, "Unauthorized");
}
const isStream = openAIReq.stream === true;
const model = openAIReq.model ?? "default";
const encoder = new OpenAIStreamEncoder(model);
logger.info(`[Incoming Request] Model: ${model}`);
logger.info(`[Incoming Request] Tools count: ${openAIReq.tools ? openAIReq.tools.length : 0}`);
if (openAIReq.tools && openAIReq.tools.length > 0) {
logger.info(
`[Incoming Request] Tools list: ${openAIReq.tools.map((t) => t.function.name).join(", ")}`,
);
} else {
logger.info(`[Incoming Request] No tools were sent by the client!`);
}
const ccBody = toCCRequest(openAIReq);
const abort = abortOnClientDisconnect(req, res);
try {
const result = await sendToCC(
ccBody,
{
apiBase: config.ccApiBase,
apiKey,
ccVersion: config.ccVersion,
timeoutMs: config.upstreamTimeoutMs,
idleTimeoutMs: config.idleTimeoutMs,
},
abort.signal,
);
const stream = result.stream;
if (isStream) {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
...corsHeaders(),
});
await pumpStream(
stream,
res,
(event) => encoder.emit(event).map((c) => formatSSE(c)),
() =>
encoder.finished
? []
: encoder.finishChunks("stop").map((c) => formatSSE(c)),
// Stream-level error (TCP failure, idle timeout, encoder throw).
// Always emit a uniform content+finish chunk pair via streamErrorChunks
// — mixing a non-chunk `{error:...}` envelope with valid chunks
// confused some clients (treating the envelope as a tool call named
// "error", or failing JSON parse).
(err) => encoder.streamErrorChunks(err).map((c) => formatSSE(c)),
);
// After pump completes, emit the [DONE] sentinel if we still can.
// `writableEnded` only flips when end() is called — `res.destroyed`
// catches the case where the client disconnected mid-stream and the
// socket was torn down underneath us.
if (!res.writableEnded && !res.destroyed) {
res.write(formatSSEDone());
res.end();
}
// No destroyStreamOnClientDisconnect here — by the time pumpStream
// returns the stream has already ended or errored, so the call would
// be a no-op. Mid-stream disconnects are handled by the abort signal
// (see abortOnClientDisconnect + nodeReaderToStream's abortSignal
// listener).
} else {
destroyStreamOnClientDisconnect(req, stream);
const events = await collectEvents(stream);
const response = buildNonStreamingResponse(events, model, encoder.id);
sendJson(res, 200, response);
}
} catch (err) {
handleUpstreamError(res, err, "openai");
}
}
async function handleMessages(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
let rawBody: unknown;
try {
rawBody = await parseBody(req);
} catch (err) {
const status = err instanceof BodyParseError ? err.status : 400;
const message = err instanceof BodyParseError ? err.message : "Invalid JSON body";
return sendAnthropicError(
res,
status,
status === 413 ? "api_error" : "invalid_request_error",
message,
);
}
let anthropicReq: AnthropicRequest;
try {
anthropicReq = validateAnthropicRequest(rawBody);
} catch (err) {
if (err instanceof ValidationError) {
return sendAnthropicError(res, 400, "invalid_request_error", err.message);
}
return sendAnthropicError(res, 400, "invalid_request_error", "Invalid request body");
}
const apiKey = extractApiKey(req);
if (!apiKey) {
return sendAnthropicError(res, 401, "authentication_error", "Missing API key");
}
const isStream = anthropicReq.stream === true;
const model = anthropicReq.model;
const encoder = new AnthropicStreamEncoder(model);
const ccBody = anToCCRequest(anthropicReq);
const abort = abortOnClientDisconnect(req, res);
try {
const result = await sendToCC(
ccBody,
{
apiBase: config.ccApiBase,
apiKey,
ccVersion: config.ccVersion,
timeoutMs: config.upstreamTimeoutMs,
idleTimeoutMs: config.idleTimeoutMs,
},
abort.signal,
);
const stream = result.stream;
if (isStream) {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
...corsHeaders(),
});
await pumpStream(
stream,
res,
(event) => encoder.emit(event).map((r) => formatAnthropicSSE(r.event, r.data)),
() =>
encoder.finished
? []
: encoder
.finishRecords("end_turn")
.map((r) => formatAnthropicSSE(r.event, r.data)),
(err) => {
const records: AnthropicSSERecord[] = [
{
event: "error",
data: { type: "error", error: { type: "api_error", message: err.message } },
},
];
if (!encoder.finished) records.push(...encoder.finishRecords("end_turn"));
return records.map((r) => formatAnthropicSSE(r.event, r.data));
},
);
if (!res.writableEnded && !res.destroyed) res.end();
// No destroyStreamOnClientDisconnect here — see OpenAI streaming path
// for rationale (abort signal already covers mid-stream disconnect).
} else {
destroyStreamOnClientDisconnect(req, stream);
const events = await collectEvents(stream);
const response = buildAnthropicResponse(events, model, encoder.messageId);
res.writeHead(200, { "Content-Type": "application/json", ...corsHeaders() });
res.end(JSON.stringify(response));
}
} catch (err) {
handleUpstreamError(res, err, "anthropic");
}
}
async function handleCountTokens(
req: http.IncomingMessage,
res: http.ServerResponse,
): Promise<void> {
let rawBody: unknown;
try {
rawBody = await parseBody(req);
} catch (err) {
const status = err instanceof BodyParseError ? err.status : 400;
const message = err instanceof BodyParseError ? err.message : "Invalid JSON body";
return sendAnthropicError(
res,
status,
status === 413 ? "api_error" : "invalid_request_error",
message,
);
}
const body = rawBody as Record<string, unknown>;
const parts: string[] = [];
if (typeof body.system === "string") parts.push(body.system);
else if (Array.isArray(body.system)) {
for (const b of body.system as { text?: string }[]) {
if (b.text) parts.push(b.text);
}
}
const msgs = body.messages as { content?: unknown }[] | undefined;
if (msgs) {
for (const msg of msgs) {
parts.push(typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content));
}
}
const tools = body.tools as
| { name?: string; description?: string; input_schema?: unknown }[]
| undefined;
if (tools) {
for (const t of tools) {
parts.push(t.name ?? "", t.description ?? "", JSON.stringify(t.input_schema ?? {}));
}
}
const allText = parts.join("");
let cjk = 0;
let nonCjk = 0;
for (const ch of allText) {
const code = ch.codePointAt(0) ?? 0;
if (
(code >= 0x4e00 && code <= 0x9fff) ||
(code >= 0x3040 && code <= 0x309f) ||
(code >= 0x30a0 && code <= 0x30ff) ||
(code >= 0xac00 && code <= 0xd7af)
) {
cjk++;
} else {
nonCjk++;
}
}
const estimated = Math.ceil(cjk + nonCjk / 4);
sendJson(res, 200, { input_tokens: estimated });
}
// ──────────────────────────────────────────
// Error handling
// ──────────────────────────────────────────
function handleUpstreamError(
res: http.ServerResponse,
err: unknown,
format: "openai" | "anthropic",
): void {
if (format === "anthropic") {
if (err instanceof UpstreamError) {
const status = err.statusCode >= 400 && err.statusCode < 500 ? err.statusCode : 502;
const type = ANTHROPIC_STATUS_ERROR_MAP[status] ?? "api_error";
sendAnthropicError(res, status, type, err.message);
} else {
sendAnthropicError(res, 502, "api_error", (err as Error).message);
}
return;
}
if (err instanceof UpstreamError) {
const status = err.statusCode >= 400 && err.statusCode < 500 ? err.statusCode : 502;
sendOpenAIError(res, status, err.message);
} else {
sendOpenAIError(res, 502, (err as Error).message);
}
}
// ──────────────────────────────────────────
// Server factory
// ──────────────────────────────────────────
interface RouteEntry {
method: string;
path: string;
handler: (req: http.IncomingMessage, res: http.ServerResponse, url: URL) => void | Promise<void>;
}
export function createServer(cfg: Config): http.Server {
config = cfg;
corsOrigin = cfg.corsOrigin;
// Start fetching model list in background (only if we have a key to use).
if (cfg.apiKey) {
fetchModelList(cfg.ccApiBase, cfg.apiKey)
.then((models) => {
if (models.length > 0) updateModelList(models);
})
.catch(() => {
/* keep defaults */
});
}
const routes: RouteEntry[] = [
{ method: "GET", path: "/health", handler: handleHealth },
{ method: "GET", path: "/v1/models", handler: handleModels },
{ method: "POST", path: "/v1/chat/completions", handler: handleChatCompletions },
{ method: "POST", path: "/v1/messages", handler: handleMessages },
{ method: "POST", path: "/v1/messages/count_tokens", handler: handleCountTokens },
];
const server = http.createServer((req, res) => {
if (req.method === "OPTIONS") {
res.writeHead(204, corsHeaders());
return res.end();
}
const parsedUrl = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
const pathname = parsedUrl.pathname;
const route = routes.find((r) => r.method === req.method && r.path === pathname);
if (!route) {
const isAnthropic = req.headers["anthropic-version"] !== undefined;
if (isAnthropic) {
return sendAnthropicError(res, 404, "not_found_error", "Not found");
}
return sendJson(res, 404, { error: "Not found" });
}
try {
const result = route.handler(req, res, parsedUrl);
if (result instanceof Promise) {
result.catch((err) => {
logger.error("[route] handler promise error:", err);
if (!res.headersSent) {
sendJson(res, 500, { error: "Internal server error" });
}
});
}
} catch (err) {
logger.error("[route] handler error:", err);
if (!res.headersSent) {
sendJson(res, 500, { error: "Internal server error" });
}
}
});
return server;
}