-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopencode-gateway.mjs
More file actions
1264 lines (1120 loc) · 36.8 KB
/
opencode-gateway.mjs
File metadata and controls
1264 lines (1120 loc) · 36.8 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
import http from "node:http";
import { randomUUID } from "node:crypto";
import fs from "node:fs";
import path from "node:path";
const HOST = process.env.KIMI_PROXY_HOST ?? "127.0.0.1";
const PORT = Number(process.env.KIMI_PROXY_PORT ?? "4141");
const UPSTREAM_BASE =
process.env.OPENCODE_GO_BASE_URL ?? "https://opencode.ai/zen/go/v1";
const UPSTREAM_MODEL = process.env.OPENCODE_GO_MODEL ?? "kimi-k2.6";
const UPSTREAM_TIMEOUT_MS = Number(process.env.KIMI_PROXY_UPSTREAM_TIMEOUT_MS ?? "120000");
const AUTH_PATH =
process.env.OPENCODE_AUTH_PATH ??
path.join(process.env.HOME ?? "", ".local/share/opencode/auth.json");
const MAX_BODY_SIZE = 10 * 1024 * 1024; // 10 MB
const MAX_REASONING_CACHE = 200;
const toolCallReasoningCache = new Map();
/* ------------------------------------------------------------------ */
/* Model capability map */
/* ------------------------------------------------------------------ */
const DEFAULT_CAPABILITIES = {
tools: false,
reasoning: false,
streaming: true,
vision: false,
json_mode: false,
max_output_tokens: 8192,
context_window: 128000,
supported_params: ["temperature", "top_p", "presence_penalty", "frequency_penalty", "max_tokens", "stop", "seed", "n"],
};
const MODEL_CAPABILITIES = (() => {
const env = process.env.OPENCODE_GO_MODEL_CAPABILITIES;
if (env) {
try {
return JSON.parse(env);
} catch {
console.error("[PROXY] Warning: OPENCODE_GO_MODEL_CAPABILITIES is invalid JSON, using defaults");
}
}
return {
"kimi-k2.6": {
tools: true,
reasoning: true,
streaming: true,
vision: true,
json_mode: true,
max_output_tokens: 65536,
context_window: 262144,
supported_params: ["temperature", "top_p", "presence_penalty", "frequency_penalty", "max_tokens", "stop", "seed", "n", "response_format"],
},
"kimi-k2.5": {
tools: true,
reasoning: true,
streaming: true,
vision: true,
json_mode: true,
max_output_tokens: 16384,
context_window: 256000,
supported_params: ["temperature", "top_p", "presence_penalty", "frequency_penalty", "max_tokens", "stop", "seed", "n", "response_format"],
},
"glm-5.1": {
tools: true,
reasoning: true,
streaming: true,
vision: false,
json_mode: true,
supported_params: ["temperature", "top_p", "presence_penalty", "frequency_penalty", "max_tokens", "stop", "seed", "n", "response_format"],
},
"qwen3.5-plus": {
tools: true,
reasoning: true,
streaming: true,
vision: false,
json_mode: true,
supported_params: ["temperature", "top_p", "presence_penalty", "frequency_penalty", "max_tokens", "stop", "seed", "n", "response_format"],
},
"qwen3.6-plus": {
tools: true,
reasoning: true,
streaming: true,
vision: false,
json_mode: true,
supported_params: ["temperature", "top_p", "presence_penalty", "frequency_penalty", "max_tokens", "stop", "seed", "n", "response_format"],
},
"mimo-v2-pro": {
tools: true,
reasoning: true,
streaming: true,
vision: false,
json_mode: true,
supported_params: ["temperature", "top_p", "presence_penalty", "frequency_penalty", "max_tokens", "stop", "seed", "n", "response_format"],
},
"mimo-v2-omni": {
tools: true,
reasoning: true,
streaming: true,
vision: true,
json_mode: true,
supported_params: ["temperature", "top_p", "presence_penalty", "frequency_penalty", "max_tokens", "stop", "seed", "n", "response_format"],
},
"minimax-m2.5": {
tools: true,
reasoning: false,
streaming: true,
vision: false,
json_mode: true,
supported_params: ["temperature", "top_p", "presence_penalty", "frequency_penalty", "max_tokens", "stop", "seed", "n", "response_format"],
},
"minimax-m2.7": {
tools: true,
reasoning: false,
streaming: true,
vision: false,
json_mode: true,
supported_params: ["temperature", "top_p", "presence_penalty", "frequency_penalty", "max_tokens", "stop", "seed", "n", "response_format"],
},
};
})();
function getCapabilities(model) {
return MODEL_CAPABILITIES[model] ?? DEFAULT_CAPABILITIES;
}
function cacheReasoning(callId, reasoning) {
if (!callId || !reasoning) return;
if (toolCallReasoningCache.size >= MAX_REASONING_CACHE) {
const firstKey = toolCallReasoningCache.keys().next().value;
toolCallReasoningCache.delete(firstKey);
}
toolCallReasoningCache.set(callId, reasoning);
}
function summarizeMessages(msgs) {
return msgs.map((m) => {
if (m.role === "assistant" && m.tool_calls?.length) {
return `assistant[tool_calls:${m.tool_calls.map((t) => t.id).join(",")}]`;
}
if (m.role === "tool") {
return `tool[${m.tool_call_id}]`;
}
return `${m.role}[${String(m.content).slice(0, 40)}]`;
});
}
/* ------------------------------------------------------------------ */
/* In-memory conversation thread storage (LRU) */
/* ------------------------------------------------------------------ */
const MAX_STORED_THREADS = 100;
const responseThreads = new Map();
function storeThread(responseId, { messages, outputItems, usage }) {
if (responseThreads.size >= MAX_STORED_THREADS) {
const firstKey = responseThreads.keys().next().value;
responseThreads.delete(firstKey);
}
responseThreads.set(responseId, {
messages,
outputItems,
usage,
});
}
function loadThread(responseId) {
return responseThreads.get(responseId) ?? null;
}
/* ------------------------------------------------------------------ */
/* Auth / IO helpers */
/* ------------------------------------------------------------------ */
function readJsonFile(filePath) {
return JSON.parse(fs.readFileSync(filePath, "utf8"));
}
function loadOpencodeGoKey() {
if (process.env.OPENCODE_GO_API_KEY) {
return process.env.OPENCODE_GO_API_KEY;
}
const auth = readJsonFile(AUTH_PATH);
const key = auth?.["opencode-go"]?.key;
if (!key) {
throw new Error(
`Missing opencode-go key in ${AUTH_PATH}. Set OPENCODE_GO_API_KEY to override.`,
);
}
return key;
}
function readRequestBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
let totalLength = 0;
req.on("data", (chunk) => {
totalLength += chunk.length;
if (totalLength > MAX_BODY_SIZE) {
req.destroy();
reject(new Error(`Request body exceeds ${MAX_BODY_SIZE} bytes`));
return;
}
chunks.push(chunk);
});
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
req.on("error", reject);
});
}
function sendJson(res, statusCode, body) {
res.statusCode = statusCode;
res.setHeader("content-type", "application/json");
res.end(JSON.stringify(body));
}
function setCorsHeaders(res) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
}
/* ------------------------------------------------------------------ */
/* SSE helpers */
/* ------------------------------------------------------------------ */
function writeSse(res, event) {
res.write(`event: ${event.type}\n`);
res.write(`data: ${JSON.stringify(event)}\n\n`);
}
function writeSseError(res, responseId, message, code = "proxy_error") {
writeSse(res, {
type: "response.failed",
response: {
id: responseId,
error: { code, message },
},
});
}
/* ------------------------------------------------------------------ */
/* Content normalisation */
/* ------------------------------------------------------------------ */
function normalizeContent(content) {
if (typeof content === "string") {
return content;
}
if (!Array.isArray(content)) {
return "";
}
const parts = [];
for (const part of content) {
if (typeof part === "string") {
parts.push({ type: "text", text: part });
continue;
}
if (!part || typeof part !== "object") {
continue;
}
switch (part.type) {
case "input_text":
case "output_text":
case "summary_text":
case "reasoning_text":
parts.push({ type: "text", text: part.text ?? "" });
break;
case "input_image": {
const url = part.image_url;
if (url) {
parts.push({
type: "image_url",
image_url: { url, detail: part.detail ?? "auto" },
});
}
break;
}
default:
parts.push({ type: "text", text: JSON.stringify(part) });
}
}
// Collapse to plain string when there are no images – keeps upstream
// payloads simple and compatible with APIs that prefer strings.
if (parts.every((p) => p.type === "text")) {
return parts.map((p) => p.text).join("\n");
}
return parts;
}
function flattenContent(content) {
if (typeof content === "string") {
return content;
}
if (!Array.isArray(content)) {
return "";
}
return content
.map((part) => {
if (typeof part === "string") return part;
if (!part || typeof part !== "object") return "";
switch (part.type) {
case "input_text":
case "output_text":
case "summary_text":
case "reasoning_text":
return part.text ?? "";
case "input_image":
return part.image_url
? `[image: ${part.image_url}]`
: "[image input omitted]";
default:
return JSON.stringify(part);
}
})
.filter(Boolean)
.join("\n");
}
function normalizeToolOutput(output) {
if (typeof output === "string") {
return output;
}
if (!output || typeof output !== "object") {
return "";
}
if (typeof output.content === "string") {
return output.content;
}
return JSON.stringify(output);
}
function normalizeToolChoice(toolChoice) {
if (!toolChoice || typeof toolChoice === "string") {
return toolChoice ?? "auto";
}
if (toolChoice.type === "function" && toolChoice.name) {
return {
type: "function",
function: { name: toolChoice.name },
};
}
if (toolChoice.type === "function" && toolChoice.function?.name) {
return {
type: "function",
function: { name: toolChoice.function.name },
};
}
return "auto";
}
/* ------------------------------------------------------------------ */
/* Tool normalisation */
/* ------------------------------------------------------------------ */
const UNSUPPORTED_TOOL_TYPES = new Set([
"web_search_preview",
"file_search",
"computer_use_preview",
"web_search",
"computer_use",
]);
function normalizeTools(tools) {
return (tools ?? [])
.filter((tool) => {
if (tool?.type !== "function") return false;
return tool?.name || tool?.function?.name;
})
.map((tool) => ({
type: "function",
function: {
name: tool.name ?? tool.function?.name,
description: tool.description ?? tool.function?.description ?? "",
parameters: tool.parameters ?? tool.function?.parameters ?? { type: "object", properties: {} },
...(tool.strict !== undefined ? { strict: tool.strict } : {}),
},
}));
}
/* ------------------------------------------------------------------ */
/* Message building */
/* ------------------------------------------------------------------ */
function buildChatMessages(request) {
const messages = [];
if (request.instructions) {
messages.push({
role: "system",
content: request.instructions,
});
}
// Restore previous conversation state
if (request.previous_response_id) {
const thread = loadThread(request.previous_response_id);
console.error("[PROXY] previous_response_id:", request.previous_response_id, "thread found:", !!thread, "thread messages:", thread ? summarizeMessages(thread.messages) : []);
if (thread?.messages) {
let skippedFirstSystem = false;
for (const msg of thread.messages) {
// Avoid duplicate system message only the first one
if (msg.role === "system" && request.instructions && !skippedFirstSystem) {
skippedFirstSystem = true;
continue;
}
messages.push(msg);
}
}
} else {
console.error("[PROXY] No previous_response_id");
}
let pendingToolCallMessage = null;
const flushPendingToolCalls = () => {
if (pendingToolCallMessage) {
messages.push(pendingToolCallMessage);
pendingToolCallMessage = null;
}
};
const inputItems = request.input ?? [];
for (const item of inputItems) {
if (!item || typeof item !== "object") continue;
// Skip function_call items when previous_response_id is used;
// the stored thread already contains the assistant message with tool_calls.
if (request.previous_response_id && item.type === "function_call") {
continue;
}
// Reasoning items from previous turns are already captured in the
// assistant message or cache; ignore them here.
if (item.type === "reasoning") {
continue;
}
if (item.type === "function_call") {
if (!pendingToolCallMessage) {
const cachedReasoning = item.call_id
? toolCallReasoningCache.get(item.call_id)
: undefined;
pendingToolCallMessage = {
role: "assistant",
content: "",
...(cachedReasoning
? {
reasoning: cachedReasoning,
reasoning_content: cachedReasoning,
}
: {}),
tool_calls: [],
};
}
pendingToolCallMessage.tool_calls.push({
id: item.call_id ?? `call_${randomUUID()}`,
type: "function",
function: {
name: item.name ?? "unknown_tool",
arguments: item.arguments ?? "{}",
},
});
continue;
}
// function_call_output MUST immediately follow the assistant tool_calls.
// If a developer/system message is interleaved, don't flush yet — emit
// the assistant first when we hit the first tool output.
if (item.type === "function_call_output") {
const fallbackCallId = pendingToolCallMessage?.tool_calls.at(-1)?.id ?? `call_${randomUUID()}`;
flushPendingToolCalls();
messages.push({
role: "tool",
tool_call_id: item.call_id ?? fallbackCallId,
content: normalizeToolOutput(item.output),
});
continue;
}
// For user or assistant messages, flush any buffered tool calls first.
if (item.type === "message") {
const isUserOrAssistant = item.role === "user" || item.role === "assistant";
if (isUserOrAssistant) {
flushPendingToolCalls();
}
const role =
item.role === "developer"
? "system"
: item.role === "assistant"
? "assistant"
: "user";
messages.push({
role,
content: normalizeContent(item.content),
});
continue;
}
}
flushPendingToolCalls();
console.error("[PROXY] Final message summary:", summarizeMessages(messages));
return messages;
}
function buildStoredMessages(requestMessages, outputItems) {
const messages = [...requestMessages];
let assistantContent = "";
let reasoningContent = "";
const toolCalls = [];
for (const item of outputItems) {
if (item.type === "message") {
assistantContent = flattenContent(item.content);
} else if (item.type === "reasoning") {
reasoningContent = flattenContent(item.content);
} else if (item.type === "function_call") {
toolCalls.push({
id: item.call_id,
type: "function",
function: {
name: item.name,
arguments: item.arguments,
},
});
}
}
if (toolCalls.length > 0) {
const msg = {
role: "assistant",
content: assistantContent,
tool_calls: toolCalls,
};
if (reasoningContent) {
msg.reasoning = reasoningContent;
msg.reasoning_content = reasoningContent;
}
messages.push(msg);
} else if (assistantContent || reasoningContent) {
const msg = { role: "assistant", content: assistantContent };
if (reasoningContent) {
msg.reasoning = reasoningContent;
msg.reasoning_content = reasoningContent;
}
messages.push(msg);
}
return messages;
}
/* ------------------------------------------------------------------ */
/* Fetch with timeout */
/* ------------------------------------------------------------------ */
function fetchWithTimeout(url, options) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), UPSTREAM_TIMEOUT_MS);
return fetch(url, { ...options, signal: controller.signal })
.finally(() => clearTimeout(timeout));
}
/* ------------------------------------------------------------------ */
/* Chat request building */
/* ------------------------------------------------------------------ */
function buildChatRequest(request, capabilities) {
const stream = request.stream !== false; // default true per OpenAI spec
const req = {
model: request.model ?? UPSTREAM_MODEL,
messages: buildChatMessages(request),
stream,
};
if (stream) {
req.stream_options = { include_usage: true };
}
// Forward only params the model claims to support
const supported = new Set(capabilities.supported_params ?? []);
const optionalParams = [
"temperature",
"top_p",
"presence_penalty",
"frequency_penalty",
"max_tokens",
"stop",
"seed",
"n",
"response_format",
];
for (const key of optionalParams) {
if (supported.has(key) && request[key] !== undefined) {
req[key] = request[key];
}
}
// OpenAI Responses API uses max_output_tokens; map to upstream max_tokens
if (request.max_output_tokens != null) {
const limit = capabilities.max_output_tokens ?? Infinity;
req.max_tokens = Math.min(request.max_output_tokens, limit);
}
// Tools: only forward if model supports them
if (capabilities.tools) {
const tools = normalizeTools(request.tools);
if (tools.length > 0) {
req.tools = tools;
req.tool_choice = normalizeToolChoice(request.tool_choice);
}
}
return req;
}
/* ------------------------------------------------------------------ */
/* Usage helper */
/* ------------------------------------------------------------------ */
function usageOrZero(usage, reasoningText = "") {
const reasoningTokens = reasoningText
? Math.ceil(reasoningText.length / 4)
: 0;
if (usage && typeof usage === "object") {
const inputDetails =
usage.prompt_tokens_details ?? usage.input_tokens_details ?? {};
const outputDetails =
usage.completion_tokens_details ?? usage.output_tokens_details ?? {};
return {
input_tokens: usage.prompt_tokens ?? usage.input_tokens ?? 0,
input_tokens_details: {
cached_tokens: inputDetails.cached_tokens ?? 0,
},
output_tokens: usage.completion_tokens ?? usage.output_tokens ?? 0,
output_tokens_details: {
reasoning_tokens:
outputDetails.reasoning_tokens ?? reasoningTokens,
},
total_tokens: usage.total_tokens ?? 0,
};
}
return {
input_tokens: 0,
input_tokens_details: { cached_tokens: 0 },
output_tokens: 0,
output_tokens_details: { reasoning_tokens: reasoningTokens },
total_tokens: 0,
};
}
/* ------------------------------------------------------------------ */
/* SSE parsing */
/* ------------------------------------------------------------------ */
function parseSseChunk(buffer) {
const events = [];
let searchIndex = 0;
while (true) {
const endUnix = buffer.indexOf("\n\n", searchIndex);
const endWin = buffer.indexOf("\r\n\r\n", searchIndex);
let end = -1;
if (endUnix !== -1 && endWin !== -1) {
end = Math.min(endUnix, endWin);
} else if (endUnix !== -1) {
end = endUnix;
} else if (endWin !== -1) {
end = endWin;
} else {
break;
}
events.push(buffer.slice(searchIndex, end));
searchIndex = end + (end === endUnix ? 2 : 4);
}
return { events, remainder: buffer.slice(searchIndex) };
}
function parseSseEvent(rawEvent) {
const lines = rawEvent
.split("\n")
.map((line) => line.trimEnd())
.filter(Boolean);
const dataLines = lines
.filter((line) => line.startsWith("data:"))
.map((line) => line.slice(5).trimStart());
return dataLines.join("\n");
}
/* ------------------------------------------------------------------ */
/* Response construction helpers */
/* ------------------------------------------------------------------ */
function buildResponseOutputItems({
reasoningText,
assistantText,
refusalText,
toolCalls,
}) {
const items = [];
if (reasoningText) {
items.push({
type: "reasoning",
id: `rs_${randomUUID()}`,
summary: [],
content: [{ type: "reasoning_text", text: reasoningText }],
});
}
if (refusalText) {
items.push({
type: "refusal",
id: `ref_${randomUUID()}`,
content: [{ type: "refusal", text: refusalText }],
});
} else if (assistantText) {
items.push({
type: "message",
id: `msg_${randomUUID()}`,
role: "assistant",
content: [{ type: "output_text", text: assistantText }],
});
}
const sortedToolCalls = [...toolCalls.entries()]
.sort((a, b) => a[0] - b[0])
.map(([, value]) => value);
for (const tc of sortedToolCalls) {
items.push({
type: "function_call",
call_id: tc.id,
name: tc.name,
arguments: tc.arguments || "{}",
});
}
return { items, sortedToolCalls };
}
/* ------------------------------------------------------------------ */
/* Non-streaming handler */
/* ------------------------------------------------------------------ */
async function handleResponsesNonStream(req, res, apiKey, request, capabilities) {
const responseId = `resp_${randomUUID()}`;
const chatRequest = buildChatRequest(request, capabilities);
console.error("[PROXY] Non-stream messages:", JSON.stringify(summarizeMessages(chatRequest.messages)));
const upstreamResponse = await fetchWithTimeout(
`${UPSTREAM_BASE}/chat/completions`,
{
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify(chatRequest),
},
);
if (!upstreamResponse.ok) {
const errorText = await upstreamResponse.text();
console.error("[PROXY] Upstream error (non-stream):", errorText);
sendJson(res, upstreamResponse.status, {
error: { message: errorText || "Upstream request failed" },
});
return;
}
const data = await upstreamResponse.json();
const choice = data.choices?.[0];
const message = choice?.message ?? {};
const usage = data.usage;
const reasoningText = capabilities.reasoning ? (message.reasoning_content ?? "") : "";
const assistantText = message.content ?? "";
const refusalText = message.refusal ?? "";
const toolCalls = new Map();
if (capabilities.tools && Array.isArray(message.tool_calls)) {
for (let i = 0; i < message.tool_calls.length; i++) {
const tc = message.tool_calls[i];
toolCalls.set(i, {
id: tc.id ?? `call_${randomUUID()}`,
name: tc.function?.name ?? "unknown_tool",
arguments: tc.function?.arguments ?? "{}",
});
}
}
const { items: outputItems, sortedToolCalls: sortedTCs } =
buildResponseOutputItems({ reasoningText, assistantText, refusalText, toolCalls });
const isIncomplete = choice?.finish_reason === "length";
const responseObj = {
id: responseId,
object: "response",
created_at: Math.floor(Date.now() / 1000),
status: isIncomplete ? "incomplete" : "completed",
error: null,
incomplete_details: isIncomplete
? { reason: "max_output_tokens" }
: null,
model: chatRequest.model,
output: outputItems,
usage: usageOrZero(usage, reasoningText),
};
// Cache reasoning for multi-turn tool loops
for (const tc of sortedTCs) {
cacheReasoning(tc.id, reasoningText);
}
storeThread(responseId, {
messages: buildStoredMessages(chatRequest.messages, outputItems),
outputItems,
usage: responseObj.usage,
});
sendJson(res, 200, responseObj);
}
/* ------------------------------------------------------------------ */
/* Streaming handler */
/* ------------------------------------------------------------------ */
async function handleResponsesStream(req, res, apiKey, request, capabilities) {
const responseId = `resp_${randomUUID()}`;
const assistantMessageId = `msg_${randomUUID()}`;
const reasoningItemId = `rs_${randomUUID()}`;
const refusalItemId = `ref_${randomUUID()}`;
const chatRequest = buildChatRequest(request, capabilities);
console.error("[PROXY] Stream messages:", JSON.stringify(summarizeMessages(chatRequest.messages)));
const abortController = new AbortController();
const onClientClose = () => abortController.abort();
req.on("close", onClientClose);
res.on("close", onClientClose);
const upstreamResponse = await fetchWithTimeout(
`${UPSTREAM_BASE}/chat/completions`,
{
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
Accept: "text/event-stream",
},
body: JSON.stringify(chatRequest),
signal: abortController.signal,
},
);
if (!upstreamResponse.ok || !upstreamResponse.body) {
const errorText = await upstreamResponse.text();
console.error("[PROXY] Upstream error (stream):", errorText);
res.statusCode = upstreamResponse.status;
res.setHeader("content-type", "application/json");
res.end(
JSON.stringify({
error: { message: errorText || "Upstream request failed" },
}),
);
req.off("close", onClientClose);
res.off("close", onClientClose);
return;
}
res.statusCode = 200;
res.setHeader("content-type", "text/event-stream");
res.setHeader("cache-control", "no-cache");
res.setHeader("connection", "keep-alive");
res.flushHeaders?.();
writeSse(res, {
type: "response.created",
response: { id: responseId },
});
let buffered = "";
let assistantText = "";
let reasoningText = "";
let refusalText = "";
let usage = null;
let finishReason = null;
const toolCalls = new Map();
let reasoningItemOpened = false;
let assistantItemOpened = false;
let refusalItemOpened = false;
const decoder = new TextDecoder();
try {
for await (const chunk of upstreamResponse.body) {
buffered += decoder.decode(chunk, { stream: true });
const parsed = parseSseChunk(buffered);
buffered = parsed.remainder;
for (const rawEvent of parsed.events) {
const data = parseSseEvent(rawEvent);
if (!data) continue;
if (data === "[DONE]") continue;
let event;
try {
event = JSON.parse(data);
} catch (parseErr) {
console.error("[PROXY] SSE JSON parse error:", parseErr.message, "data:", data.slice(0, 200));
continue;
}
if (event.error?.message) {
writeSseError(res, responseId, event.error.message, event.error.code);
res.end();
return;
}
if (event.usage) {
usage = event.usage;
}
const choice = event.choices?.[0];
const delta = choice?.delta ?? {};
if (choice?.finish_reason) {
finishReason = choice.finish_reason;
}
// Refusal
if (typeof delta.refusal === "string" && delta.refusal.length > 0) {
if (!refusalItemOpened) {
writeSse(res, {
type: "response.output_item.added",
item: {
type: "refusal",
id: refusalItemId,
content: [{ type: "refusal", text: "" }],
},
});
refusalItemOpened = true;
}
refusalText += delta.refusal;
writeSse(res, {
type: "response.output_text.delta",
delta: delta.refusal,
});
continue;
}
// Regular text
if (typeof delta.content === "string" && delta.content.length > 0) {
if (!assistantItemOpened) {
writeSse(res, {
type: "response.output_item.added",
item: {
type: "message",
id: assistantMessageId,
role: "assistant",
content: [{ type: "output_text", text: "" }],
},
});
assistantItemOpened = true;
}
assistantText += delta.content;
writeSse(res, {
type: "response.output_text.delta",
delta: delta.content,
});
}
// Reasoning
if (capabilities.reasoning && typeof delta.reasoning === "string" && delta.reasoning.length > 0) {
if (!reasoningItemOpened) {
writeSse(res, {
type: "response.output_item.added",
item: {
type: "reasoning",
id: reasoningItemId,
summary: [],