omp-opencode-bridge 0.0.0-stage → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/anthropic.ts ADDED
@@ -0,0 +1,698 @@
1
+ "use strict";
2
+
3
+ // Type-only import: erased at load, no runtime require.
4
+ import type { IncomingMessage, ServerResponse } from "http";
5
+
6
+ const NEWLINE = String.fromCharCode(10);
7
+ const INTERNAL_HOST = process.env.HOST && process.env.HOST !== "0.0.0.0" ? process.env.HOST : "127.0.0.1";
8
+ const INTERNAL_PORT = parseInt(process.env.PORT || "20129", 10);
9
+
10
+ // Headers a client may hand us that the bridge's own chat route understands.
11
+ // `user-agent` is deliberately included: server.ts re-derives a gate-safe UA
12
+ // when the forwarded one is not a valid v2 client string, so passing it through
13
+ // preserves a real CLI's identity and never leaks a bad one upstream.
14
+ const FORWARDED_HEADERS = [
15
+ "x-opencode-session",
16
+ "x-opencode-session-id",
17
+ "x-session-id",
18
+ "session-id",
19
+ "x-conversation-id",
20
+ "x-9r-session-id",
21
+ "x-session-affinity",
22
+ "x-opencode-client",
23
+ "x-opencode-project",
24
+ "user-agent",
25
+ ];
26
+
27
+ /** One Anthropic content block, as far as this adapter reads it. */
28
+ interface AnthropicBlock {
29
+ type?: unknown;
30
+ text?: unknown;
31
+ id?: unknown;
32
+ name?: unknown;
33
+ input?: unknown;
34
+ content?: unknown;
35
+ tool_use_id?: unknown;
36
+ }
37
+
38
+ /** An Anthropic request message. */
39
+ interface AnthropicRequestMessage {
40
+ role?: unknown;
41
+ content?: unknown;
42
+ }
43
+
44
+ /** An Anthropic tool definition. */
45
+ interface AnthropicTool {
46
+ name?: unknown;
47
+ description?: unknown;
48
+ input_schema?: unknown;
49
+ }
50
+
51
+ /** The Anthropic Messages request body, as far as this adapter reads it. */
52
+ interface AnthropicRequestBody {
53
+ model?: unknown;
54
+ messages?: unknown;
55
+ system?: unknown;
56
+ max_tokens?: unknown;
57
+ stream?: unknown;
58
+ temperature?: unknown;
59
+ top_p?: unknown;
60
+ tools?: unknown;
61
+ tool_choice?: { type?: unknown; name?: unknown } | null;
62
+ stop_sequences?: unknown;
63
+ thinking?: unknown;
64
+ top_k?: unknown;
65
+ metadata?: unknown;
66
+ container?: unknown;
67
+ [key: string]: unknown;
68
+ }
69
+
70
+ /** The OpenAI-shaped chat completion this adapter consumes. */
71
+ interface OpenAICompletion {
72
+ model?: unknown;
73
+ choices?: Array<{
74
+ finish_reason?: unknown;
75
+ message?: {
76
+ content?: unknown;
77
+ tool_calls?: Array<{ id?: unknown; function?: { name?: unknown; arguments?: unknown } }>;
78
+ };
79
+ }>;
80
+ usage?: { prompt_tokens?: unknown; completion_tokens?: unknown };
81
+ }
82
+
83
+ interface OpenAIToolCall {
84
+ id: string;
85
+ type: "function";
86
+ function: { name: string; arguments: string };
87
+ }
88
+
89
+ interface OpenAIMessage {
90
+ role: string;
91
+ content: string;
92
+ tool_calls?: OpenAIToolCall[];
93
+ }
94
+
95
+ interface OpenAITool {
96
+ type: "function";
97
+ function: { name: string; description: string; parameters: unknown };
98
+ }
99
+
100
+ /** The Anthropic Messages response this adapter produces. */
101
+ interface AnthropicResponse {
102
+ id: string;
103
+ type: "message";
104
+ role: "assistant";
105
+ model: string;
106
+ content: Array<{
107
+ type: "text" | "tool_use";
108
+ text?: unknown;
109
+ id?: string;
110
+ name?: string;
111
+ input?: unknown;
112
+ }>;
113
+ stop_reason: string;
114
+ stop_sequence: null;
115
+ usage: { input_tokens: number; output_tokens: number };
116
+ }
117
+
118
+ function readBody(req: IncomingMessage, limit?: number): Promise<Buffer> {
119
+ const max = limit || 10 * 1024 * 1024;
120
+ return new Promise((resolve, reject) => {
121
+ let size = 0;
122
+ const chunks = [];
123
+ req.on("data", (c) => {
124
+ size += c.length;
125
+ if (size > max) {
126
+ reject(new Error("payload too large"));
127
+ req.destroy();
128
+ return;
129
+ }
130
+ chunks.push(c);
131
+ });
132
+ req.on("end", () => resolve(Buffer.concat(chunks)));
133
+ req.on("error", reject);
134
+ });
135
+ }
136
+
137
+ function systemToString(system: unknown): string | undefined {
138
+ if (typeof system === "string") return system;
139
+ if (!Array.isArray(system)) return undefined;
140
+ const text = system
141
+ .map((block) => (block && block.type === "text" ? String(block.text || "") : ""))
142
+ .join(NEWLINE);
143
+ return text || undefined;
144
+ }
145
+
146
+ /**
147
+ * Anthropic `thinking` parameters have no OpenAI equivalent, so they are
148
+ * reported rather than silently dropped: a caller that asked for a thinking
149
+ * budget and received none should be able to see why in the logs.
150
+ */
151
+ function warnUnsupported(body: AnthropicRequestBody): void {
152
+ const notes = [];
153
+ if (body && body.thinking) notes.push("thinking");
154
+ if (body && body.top_k !== undefined) notes.push("top_k");
155
+ if (body && body.metadata) notes.push("metadata");
156
+ if (body && body.container) notes.push("container");
157
+ if (notes.length > 0) {
158
+ console.warn(
159
+ `[opencode-free-bridge] /v1/messages: ignoring Anthropic-only parameter(s): ${notes.join(", ")}`
160
+ );
161
+ }
162
+ }
163
+
164
+ function toolsToOpenAI(tools: unknown): OpenAITool[] {
165
+ return (Array.isArray(tools) ? tools : [])
166
+ .map((tool) => ({
167
+ type: "function",
168
+ function: {
169
+ name: String(tool && tool.name ? tool.name : ""),
170
+ description: String(tool && tool.description ? tool.description : ""),
171
+ parameters: (tool && tool.input_schema) || { type: "object", properties: {} },
172
+ },
173
+ }))
174
+ .filter((tool) => tool.function.name);
175
+ }
176
+
177
+ function messagesToOpenAI(messages: unknown): OpenAIMessage[] {
178
+ const out: OpenAIMessage[] = [];
179
+ for (const message of Array.isArray(messages) ? messages : []) {
180
+ const role = message && message.role === "assistant" ? "assistant" : "user";
181
+ const blocks = Array.isArray(message && message.content)
182
+ ? message.content
183
+ : [{ type: "text", text: (message && message.content) || "" }];
184
+ if (role === "assistant") {
185
+ const text = blocks
186
+ .filter((b) => b && b.type === "text")
187
+ .map((b) => b.text || "")
188
+ .join("");
189
+ const toolCalls = blocks
190
+ .filter((b) => b && b.type === "tool_use")
191
+ .map((b) => ({
192
+ id: String(b.id || ""),
193
+ type: "function",
194
+ function: {
195
+ name: String(b.name || ""),
196
+ arguments: JSON.stringify(b.input || {}),
197
+ },
198
+ }));
199
+ const item: OpenAIMessage = { role: role, content: text };
200
+ if (toolCalls.length) item.tool_calls = toolCalls;
201
+ out.push(item);
202
+ } else {
203
+ const text = blocks
204
+ .filter((b) => b && b.type === "text")
205
+ .map((b) => b.text || "")
206
+ .join("");
207
+ const toolResults = blocks
208
+ .filter((b) => b && b.type === "tool_result")
209
+ .map((b) => {
210
+ let content = "";
211
+ if (typeof b.content === "string") content = b.content;
212
+ else if (Array.isArray(b.content)) {
213
+ content = b.content
214
+ .map((part) => (part && part.type === "text" ? part.text || "" : JSON.stringify(part)))
215
+ .join(NEWLINE);
216
+ } else if (b.content != null) content = JSON.stringify(b.content);
217
+ return {
218
+ role: "tool",
219
+ tool_call_id: String(b.tool_use_id || ""),
220
+ content: content,
221
+ };
222
+ });
223
+ out.push(...toolResults);
224
+ if (text) out.push({ role: role, content: text });
225
+ }
226
+ }
227
+ return out;
228
+ }
229
+
230
+ function toOpenAI(
231
+ body: AnthropicRequestBody,
232
+ { stream = false }: { stream?: boolean } = {}
233
+ ): Record<string, unknown> {
234
+ const system = systemToString(body.system);
235
+ const messages = messagesToOpenAI(body.messages);
236
+ if (system) messages.unshift({ role: "system", content: system });
237
+ const out: Record<string, unknown> = {
238
+ model: body.model,
239
+ messages: messages,
240
+ max_tokens: body.max_tokens,
241
+ stream: Boolean(stream),
242
+ };
243
+ // `stream_options.include_usage` is what makes the gateway emit a final
244
+ // chunk carrying real token counts; without it a streamed reply has no usage.
245
+ if (stream) out.stream_options = { include_usage: true };
246
+ if (typeof body.temperature === "number") out.temperature = body.temperature;
247
+ if (typeof body.top_p === "number") out.top_p = body.top_p;
248
+ if (Array.isArray(body.tools) && body.tools.length) out.tools = toolsToOpenAI(body.tools);
249
+ if (body.tool_choice) {
250
+ if (body.tool_choice.type === "auto") out.tool_choice = "auto";
251
+ else if (body.tool_choice.type === "any") out.tool_choice = "required";
252
+ else if (body.tool_choice.type === "tool" && body.tool_choice.name) {
253
+ out.tool_choice = { type: "function", function: { name: body.tool_choice.name } };
254
+ }
255
+ }
256
+ if (Array.isArray(body.stop_sequences) && body.stop_sequences.length) {
257
+ out.stop = body.stop_sequences;
258
+ }
259
+ return out;
260
+ }
261
+
262
+ function openAIToAnthropic(completion: OpenAICompletion, requestedModel?: string): AnthropicResponse {
263
+ const choice = (completion && completion.choices && completion.choices[0]) || {};
264
+ const message = choice.message || {};
265
+ const usage = (completion && completion.usage) || {};
266
+ const content: AnthropicResponse["content"] = [];
267
+ if (typeof message.content === "string" && message.content) {
268
+ content.push({ type: "text", text: message.content });
269
+ }
270
+ for (const call of Array.isArray(message.tool_calls) ? message.tool_calls : []) {
271
+ let input = {};
272
+ try {
273
+ input = JSON.parse((call.function && call.function.arguments) || "{}");
274
+ } catch (e) {
275
+ input = {};
276
+ }
277
+ content.push({
278
+ type: "tool_use",
279
+ id: String(call.id || ""),
280
+ name: String((call.function && call.function.name) || ""),
281
+ input: input,
282
+ });
283
+ }
284
+ if (!content.length) content.push({ type: "text", text: "" });
285
+ const stopReason =
286
+ choice.finish_reason === "length"
287
+ ? "max_tokens"
288
+ : content.some((block) => block.type === "tool_use")
289
+ ? "tool_use"
290
+ : "end_turn";
291
+ return {
292
+ id: "msg_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 8),
293
+ type: "message",
294
+ role: "assistant",
295
+ model: requestedModel || (completion && completion.model) || "unknown",
296
+ content: content,
297
+ stop_reason: stopReason,
298
+ stop_sequence: null,
299
+ usage: {
300
+ input_tokens: Number(usage.prompt_tokens || 0),
301
+ output_tokens: Number(usage.completion_tokens || 0),
302
+ },
303
+ };
304
+ }
305
+
306
+ /** Anthropic's documented mapping for a stop reason, from OpenAI's. */
307
+ function stopReasonOf(finishReason: unknown, sawToolUse: boolean): string {
308
+ if (sawToolUse) return "tool_use";
309
+ if (finishReason === "length") return "max_tokens";
310
+ if (finishReason === "content_filter") return "refusal";
311
+ return "end_turn";
312
+ }
313
+
314
+ function sseWrite(res: ServerResponse, event: string, payload: unknown): void {
315
+ res.write(`event: ${event}${NEWLINE}data: ${JSON.stringify(payload)}${NEWLINE}${NEWLINE}`);
316
+ }
317
+
318
+ /**
319
+ * Relay the bridge's OpenAI SSE stream as Anthropic SSE.
320
+ *
321
+ * The previous version buffered the whole completion and replayed it as SSE,
322
+ * which produced a byte-valid but non-streaming response: every event landed in
323
+ * the same millisecond and the client saw one delta. Claude Code and anything
324
+ * built on the Anthropic SDK stream by default, and a buffered reply makes a
325
+ * long generation look frozen, so the relay has to forward each delta as it
326
+ * arrives rather than after the last one.
327
+ */
328
+ async function relayStream(
329
+ res: ServerResponse,
330
+ upstreamBody: ReadableStream<Uint8Array> | null,
331
+ requestedModel: string
332
+ ): Promise<void> {
333
+ const reader = upstreamBody!.getReader();
334
+ const decoder = new TextDecoder();
335
+ let buffer = "";
336
+ let messageStarted = false;
337
+ let index = 0;
338
+ let openText = false;
339
+ let openTool = false;
340
+ let sawToolUse = false;
341
+ let finishReason = null;
342
+ let usage = { input_tokens: 0, output_tokens: 0 };
343
+ let closed = false;
344
+
345
+ const messageId = "msg_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
346
+
347
+ const startMessage = () => {
348
+ if (messageStarted) return;
349
+ messageStarted = true;
350
+ sseWrite(res, "message_start", {
351
+ type: "message_start",
352
+ message: {
353
+ id: messageId,
354
+ type: "message",
355
+ role: "assistant",
356
+ model: requestedModel,
357
+ content: [],
358
+ stop_reason: null,
359
+ stop_sequence: null,
360
+ usage: { input_tokens: usage.input_tokens, output_tokens: 0 },
361
+ },
362
+ });
363
+ };
364
+
365
+ const closeText = () => {
366
+ if (!openText) return;
367
+ sseWrite(res, "content_block_stop", { type: "content_block_stop", index });
368
+ openText = false;
369
+ index += 1;
370
+ };
371
+ const closeTool = () => {
372
+ if (!openTool) return;
373
+ sseWrite(res, "content_block_stop", { type: "content_block_stop", index });
374
+ openTool = false;
375
+ index += 1;
376
+ };
377
+
378
+ const handleChunk = (chunk) => {
379
+ if (closed) return;
380
+ const choice = (chunk && chunk.choices && chunk.choices[0]) || null;
381
+ if (chunk && chunk.usage) {
382
+ usage = {
383
+ input_tokens: Number(chunk.usage.prompt_tokens || usage.input_tokens || 0),
384
+ output_tokens: Number(chunk.usage.completion_tokens || usage.output_tokens || 0),
385
+ };
386
+ }
387
+ if (!choice) return;
388
+ if (choice.finish_reason) finishReason = choice.finish_reason;
389
+ const delta = choice.delta || {};
390
+ const text = typeof delta.content === "string" ? delta.content : "";
391
+ // A reasoning model emits `reasoning_content`; Anthropic clients expect it
392
+ // under `thinking`, which this adapter does not claim to support, so it is
393
+ // dropped rather than mixed into visible text.
394
+ if (text) {
395
+ startMessage();
396
+ closeTool();
397
+ if (!openText) {
398
+ sseWrite(res, "content_block_start", {
399
+ type: "content_block_start",
400
+ index,
401
+ content_block: { type: "text", text: "" },
402
+ });
403
+ openText = true;
404
+ }
405
+ sseWrite(res, "content_block_delta", {
406
+ type: "content_block_delta",
407
+ index,
408
+ delta: { type: "text_delta", text },
409
+ });
410
+ }
411
+ for (const call of Array.isArray(delta.tool_calls) ? delta.tool_calls : []) {
412
+ startMessage();
413
+ closeText();
414
+ sawToolUse = true;
415
+ const callIndex = Number.isFinite(call.index) ? call.index : 0;
416
+ if (!openTool) {
417
+ sseWrite(res, "content_block_start", {
418
+ type: "content_block_start",
419
+ index,
420
+ content_block: {
421
+ type: "tool_use",
422
+ id: String(call.id || `toolu_${callIndex}`),
423
+ name: String((call.function && call.function.name) || ""),
424
+ input: {},
425
+ },
426
+ });
427
+ openTool = true;
428
+ }
429
+ const args = call.function && call.function.arguments;
430
+ if (typeof args === "string" && args) {
431
+ sseWrite(res, "content_block_delta", {
432
+ type: "content_block_delta",
433
+ index,
434
+ delta: { type: "input_json_delta", partial_json: args },
435
+ });
436
+ }
437
+ }
438
+ };
439
+
440
+ const handleEvent = (payload) => {
441
+ if (payload === "[DONE]") {
442
+ closed = true;
443
+ return;
444
+ }
445
+ try {
446
+ handleChunk(JSON.parse(payload));
447
+ } catch {
448
+ // A non-JSON keepalive line is not a failure.
449
+ }
450
+ };
451
+
452
+ try {
453
+ while (true) {
454
+ const { done, value } = await reader.read();
455
+ if (done) break;
456
+ buffer += decoder.decode(value, { stream: true });
457
+ let nl;
458
+ while ((nl = buffer.indexOf(NEWLINE)) !== -1) {
459
+ const line = buffer.slice(0, nl).replace(/\r$/, "");
460
+ buffer = buffer.slice(nl + 1);
461
+ if (!line.startsWith("data:")) continue;
462
+ handleEvent(line.slice(5).trim());
463
+ }
464
+ }
465
+ // Flush a trailing line that arrived without its newline.
466
+ const tail = buffer.trim();
467
+ if (tail.startsWith("data:")) handleEvent(tail.slice(5).trim());
468
+ } finally {
469
+ startMessage();
470
+ closeText();
471
+ closeTool();
472
+ if (!messageStarted) startMessage();
473
+ sseWrite(res, "message_delta", {
474
+ type: "message_delta",
475
+ delta: { stop_reason: stopReasonOf(finishReason, sawToolUse), stop_sequence: null },
476
+ usage: { output_tokens: usage.output_tokens },
477
+ });
478
+ sseWrite(res, "message_stop", { type: "message_stop" });
479
+ if (!res.writableEnded) res.end();
480
+ }
481
+ }
482
+
483
+ function sendSse(res: ServerResponse, message: AnthropicResponse): void {
484
+ res.writeHead(200, {
485
+ "Content-Type": "text/event-stream; charset=utf-8",
486
+ "Cache-Control": "no-cache, no-transform",
487
+ Connection: "keep-alive",
488
+ "Access-Control-Allow-Origin": "*",
489
+ "X-Accel-Buffering": "no",
490
+ });
491
+ sseWrite(res, "message_start", {
492
+ type: "message_start",
493
+ message: Object.assign({}, message, { content: [] }),
494
+ });
495
+ message.content.forEach((block, index) => {
496
+ const blockStart =
497
+ block.type === "tool_use"
498
+ ? { type: "tool_use", id: block.id, name: block.name, input: {} }
499
+ : { type: "text", text: "" };
500
+ sseWrite(res, "content_block_start", { type: "content_block_start", index, content_block: blockStart });
501
+ const delta =
502
+ block.type === "tool_use"
503
+ ? { type: "input_json_delta", partial_json: JSON.stringify(block.input || {}) }
504
+ : { type: "text_delta", text: block.text || "" };
505
+ sseWrite(res, "content_block_delta", { type: "content_block_delta", index, delta });
506
+ sseWrite(res, "content_block_stop", { type: "content_block_stop", index });
507
+ });
508
+ sseWrite(res, "message_delta", {
509
+ type: "message_delta",
510
+ delta: { stop_reason: message.stop_reason, stop_sequence: null },
511
+ usage: { output_tokens: (message.usage && message.usage.output_tokens) || 0 },
512
+ });
513
+ sseWrite(res, "message_stop", { type: "message_stop" });
514
+ res.end();
515
+ }
516
+
517
+ function errorType(status: number): string {
518
+ if (status === 400) return "invalid_request_error";
519
+ if (status === 401 || status === 403) return "authentication_error";
520
+ if (status === 404) return "not_found_error";
521
+ if (status === 413) return "request_too_large";
522
+ if (status === 429) return "rate_limit_error";
523
+ if (status >= 500) return "overloaded_error";
524
+ return "api_error";
525
+ }
526
+
527
+ function sendError(res: ServerResponse, status: number, type: string, message: string): void {
528
+ res.writeHead(status, { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" });
529
+ res.end(JSON.stringify({ type: "error", error: { type: type, message: message } }));
530
+ }
531
+
532
+ function internalHeaders(req: IncomingMessage, extra?: Record<string, string>): Record<string, string> {
533
+ const headers = Object.assign({ "Content-Type": "application/json" }, extra || {});
534
+ for (const name of FORWARDED_HEADERS) {
535
+ const value = req.headers[name];
536
+ if (typeof value === "string" && value) headers[name] = value;
537
+ }
538
+ return headers;
539
+ }
540
+
541
+ /**
542
+ * Anthropic counts tokens with its own tokenizer. The bridge has no such
543
+ * tokenizer and inventing an exact number would be a lie, so this reports a
544
+ * deliberate over-estimate: four characters per token plus per-message framing,
545
+ * which is the heuristic the Anthropic SDK itself documents as a fallback. A
546
+ * caller using it for budgeting gets a conservative number rather than a 404.
547
+ */
548
+ function estimateInputTokens(body: AnthropicRequestBody): number {
549
+ let chars = 0;
550
+ const system = systemToString(body.system);
551
+ if (system) chars += system.length;
552
+ for (const message of Array.isArray(body.messages) ? body.messages : []) {
553
+ const blocks = Array.isArray(message && message.content)
554
+ ? message.content
555
+ : [{ type: "text", text: (message && message.content) || "" }];
556
+ for (const block of blocks) {
557
+ if (!block) continue;
558
+ if (typeof block.text === "string") chars += block.text.length;
559
+ if (typeof block.content === "string") chars += block.content.length;
560
+ else if (Array.isArray(block.content)) {
561
+ for (const part of block.content) {
562
+ if (part && typeof part.text === "string") chars += part.text.length;
563
+ }
564
+ }
565
+ if (block.input) chars += JSON.stringify(block.input).length;
566
+ if (block.name) chars += String(block.name).length;
567
+ }
568
+ }
569
+ for (const tool of Array.isArray(body.tools) ? body.tools : []) {
570
+ if (!tool) continue;
571
+ if (tool.name) chars += String(tool.name).length;
572
+ if (tool.description) chars += String(tool.description).length;
573
+ if (tool.input_schema) chars += JSON.stringify(tool.input_schema).length;
574
+ }
575
+ return Math.max(1, Math.ceil(chars / 4));
576
+ }
577
+
578
+ async function handleCountTokens(req: IncomingMessage, res: ServerResponse): Promise<void> {
579
+ let raw: Buffer;
580
+ try {
581
+ raw = await readBody(req);
582
+ } catch (e) {
583
+ return sendError(res, 413, "request_too_large", "Payload too large");
584
+ }
585
+ let body: AnthropicRequestBody;
586
+ try {
587
+ body = JSON.parse(raw.toString("utf8") || "{}");
588
+ } catch (e) {
589
+ return sendError(res, 400, "invalid_request_error", "Invalid JSON body: " + e.message);
590
+ }
591
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
592
+ return sendError(res, 400, "invalid_request_error", "Request body must be a JSON object");
593
+ }
594
+ res.writeHead(200, { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" });
595
+ res.end(JSON.stringify({ input_tokens: estimateInputTokens(body) }));
596
+ }
597
+
598
+ async function handleAnthropicMessages(req: IncomingMessage, res: ServerResponse): Promise<void> {
599
+ let raw: Buffer;
600
+ try {
601
+ raw = await readBody(req);
602
+ } catch (e) {
603
+ return sendError(res, 413, "request_too_large", "Payload too large");
604
+ }
605
+ let body: AnthropicRequestBody;
606
+ try {
607
+ body = JSON.parse(raw.toString("utf8") || "{}");
608
+ } catch (e) {
609
+ return sendError(res, 400, "invalid_request_error", "Invalid JSON body: " + e.message);
610
+ }
611
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
612
+ return sendError(res, 400, "invalid_request_error", "Request body must be a JSON object");
613
+ }
614
+ if (typeof body.model !== "string" || !body.model) {
615
+ return sendError(res, 400, "invalid_request_error", "Missing or empty required parameter: 'model'");
616
+ }
617
+ if (!Array.isArray(body.messages)) {
618
+ return sendError(res, 400, "invalid_request_error", "Missing or invalid required parameter: 'messages' must be an array");
619
+ }
620
+ warnUnsupported(body);
621
+
622
+ const wantsStream = body.stream === true;
623
+ const openaiBody = toOpenAI(body, { stream: wantsStream });
624
+ const url = `http://${INTERNAL_HOST}:${INTERNAL_PORT}/v1/chat/completions`;
625
+
626
+ let internalRes;
627
+ try {
628
+ internalRes = await fetch(url, {
629
+ method: "POST",
630
+ headers: internalHeaders(req, wantsStream ? { Accept: "text/event-stream" } : {}),
631
+ body: JSON.stringify(openaiBody),
632
+ });
633
+ } catch (e) {
634
+ return sendError(res, 502, "api_error", "Failed to reach the bridge chat route: " + e.message);
635
+ }
636
+
637
+ if (!internalRes.ok) {
638
+ let errJson = null;
639
+ try {
640
+ errJson = await internalRes.json();
641
+ } catch (e) {}
642
+ const message =
643
+ (errJson && errJson.error && errJson.error.message) ||
644
+ (errJson && errJson.message) ||
645
+ "Upstream error " + internalRes.status;
646
+ return sendError(res, internalRes.status, errorType(internalRes.status), message);
647
+ }
648
+
649
+ if (wantsStream) {
650
+ res.writeHead(200, {
651
+ "Content-Type": "text/event-stream; charset=utf-8",
652
+ "Cache-Control": "no-cache, no-transform",
653
+ Connection: "keep-alive",
654
+ "Access-Control-Allow-Origin": "*",
655
+ "X-Accel-Buffering": "no",
656
+ });
657
+ // A client that walks away must not leave the upstream stream dangling.
658
+ req.on("close", () => {
659
+ if (internalRes.body && typeof internalRes.body.cancel === "function") {
660
+ internalRes.body.cancel().catch(() => {});
661
+ }
662
+ });
663
+ try {
664
+ await relayStream(res, internalRes.body, body.model);
665
+ } catch (e) {
666
+ if (!res.writableEnded) {
667
+ try {
668
+ sseWrite(res, "error", { type: "error", error: { type: "api_error", message: e.message } });
669
+ } catch {}
670
+ res.end();
671
+ }
672
+ }
673
+ return;
674
+ }
675
+
676
+ let completion = null;
677
+ try {
678
+ completion = await internalRes.json();
679
+ } catch (e) {
680
+ return sendError(res, 502, "api_error", "Invalid response from the bridge chat route: " + e.message);
681
+ }
682
+ const message = openAIToAnthropic(completion, body.model);
683
+ res.writeHead(200, { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" });
684
+ return res.end(JSON.stringify(message));
685
+ }
686
+
687
+ module.exports = {
688
+ handleAnthropicMessages,
689
+ handleCountTokens,
690
+ toOpenAI,
691
+ openAIToAnthropic,
692
+ systemToString,
693
+ toolsToOpenAI,
694
+ messagesToOpenAI,
695
+ stopReasonOf,
696
+ estimateInputTokens,
697
+ sendSse,
698
+ };