-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
964 lines (845 loc) · 33.4 KB
/
server.js
File metadata and controls
964 lines (845 loc) · 33.4 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
import "dotenv/config";
import express from "express";
import crypto from "crypto";
import { readFileSync, existsSync } from "fs";
import { fileURLToPath } from "url";
import { dirname, join } from "path";
const __dirname = dirname(fileURLToPath(import.meta.url));
const app = express();
app.use(express.json({ limit: "50mb" }));
// ============ 配置文件 ============
function loadJson(filename, fallback) {
const filepath = join(__dirname, filename);
if (!existsSync(filepath)) {
console.log(`[config] ${filename} not found, using defaults`);
return fallback;
}
try {
return JSON.parse(readFileSync(filepath, "utf8"));
} catch (e) {
console.error(`[config] Failed to parse ${filename}:`, e.message);
return fallback;
}
}
const config = loadJson("config.json", {
port: 3000,
api: "https://api.zo.computer",
cache_ttl: 300000,
default_system_prompt: "你通过代理服务器运行,所有工具调用都在用户本地系统上执行,而非远程沙箱。请根据工具返回的实际结果来判断环境。",
});
const ZO_API = config.api;
const CACHE_TTL = config.cache_ttl;
const DEFAULT_SYSTEM_PROMPT = config.default_system_prompt;
// ============ Token 管理 ============
const tokenConfigs = loadJson("account.json", []);
const tokenPool = tokenConfigs.map((config, i) => ({
token: config.token,
origin: config.origin || "https://rustydaisy.zo.computer",
index: i,
exhausted: false,
exhaustedAt: null,
failCount: 0,
}));
if (tokenPool.length === 0) {
console.warn("[config] No tokens configured! Please add tokens to account.json");
}
let currentTokenIndex = 0; // 轮询索引
// 获取下一个可用 token(轮询)
function getNextToken() {
const now = Date.now();
const DAY_MS = 24 * 60 * 60 * 1000;
// 重置超过 24 小时的 exhausted token
for (const t of tokenPool) {
if (t.exhausted && t.exhaustedAt && (now - t.exhaustedAt) > DAY_MS) {
console.log(`[token] Resetting exhausted token #${t.index}`);
t.exhausted = false;
t.exhaustedAt = null;
t.failCount = 0;
}
}
// 获取可用 token
const available = tokenPool.filter(t => !t.exhausted);
if (available.length === 0) {
console.error("[token] All tokens exhausted!");
return tokenPool[0]; // 没有可用的,返回第一个
}
// 轮询
const token = available[currentTokenIndex % available.length];
currentTokenIndex = (currentTokenIndex + 1) % available.length;
return token;
}
// 标记 token 额度用完(402 错误)
function markTokenExhausted(tokenObj) {
tokenObj.exhausted = true;
tokenObj.exhaustedAt = Date.now();
const available = tokenPool.filter(t => !t.exhausted).length;
console.log(`[token] Token #${tokenObj.index} exhausted (${available} remaining)`);
}
// 标记 token 失败(非 402 错误,只记录日志,不累计)
function markTokenFailed(tokenObj, err) {
tokenObj.failCount++;
console.log(`[token] Token #${tokenObj.index} failed (${tokenObj.failCount}): ${err?.message || err}`);
// 不再累计失败后自动 exhausted,只有 402 才 exhausted
}
// 重置 token 失败计数
function markTokenSuccess(tokenObj) {
tokenObj.failCount = 0;
}
// 动态模型列表缓存
let cachedModels = null;
let cacheTime = 0;
// 短名 -> zo:vendor/name 映射
let shortNameMap = {};
// zo:vendor/name -> 模型详情
let modelInfoMap = {};
// 并发刷新去重
let refreshPromise = null;
function zoHeaders(tokenObj) {
const origin = tokenObj.origin;
return {
"Content-Type": "application/json",
"Cookie": `access_token=${tokenObj.token}`,
"X-Zo-Streaming-Version": "2",
"X-Zo-Workspace-Origin": origin,
"Idempotency-Key": crypto.randomUUID(),
"Origin": origin,
"Referer": `${origin}/`,
};
}
function uid() {
return crypto.randomUUID();
}
/** 生成短名: zo:anthropic/claude-opus-4-7 -> claude-opus-4-7 */
function toShortName(zoName) {
const parts = zoName.split("/");
return parts[parts.length - 1];
}
/** 解析模型名 */
function resolveModel(name) {
// 先查短名映射
if (shortNameMap[name]) return shortNameMap[name];
// 如果是完整的 zo:xxx/yyy 格式,直接返回
if (name.startsWith("zo:")) return name;
return name;
}
/** 刷新模型列表 */
async function refreshModels() {
const now = Date.now();
if (cachedModels && (now - cacheTime) < CACHE_TTL) return cachedModels;
// 并发去重:多个请求同时触发刷新时,只发一次 API 调用
if (refreshPromise) return refreshPromise;
refreshPromise = (async () => {
try {
const tokenObj = getNextToken();
const origin = tokenObj.origin;
console.log(`[models] Fetching from ${ZO_API}/models/available with origin ${origin}`);
const resp = await fetch(`${ZO_API}/models/available`, {
headers: {
"Cookie": `access_token=${tokenObj.token}`,
"X-Zo-Workspace-Origin": origin,
"Origin": origin,
"Referer": `${origin}/`,
},
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const data = await resp.json();
cachedModels = data.models;
cacheTime = now;
// 重建映射
shortNameMap = {};
modelInfoMap = {};
for (const m of data.models) {
const short = toShortName(m.model_name);
shortNameMap[short] = m.model_name;
modelInfoMap[m.model_name] = m;
}
markTokenSuccess(tokenObj);
console.log(`[models] Loaded ${cachedModels.length} models`);
return cachedModels;
} catch (err) {
console.error("[models] Failed to fetch:", err.message);
return cachedModels || [];
} finally {
refreshPromise = null;
}
})();
return refreshPromise;
}
// ============ SSE 解析 ============
async function* parseZoSse(reader, decoder) {
let buffer = "";
let currentEvent = "";
while (true) {
const { done, value } = await reader.read();
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() || "";
for (const line of lines) {
if (!line || line.startsWith(":")) continue;
if (line.startsWith("event: ")) { currentEvent = line.slice(7).trim(); continue; }
if (line.startsWith("data: ")) {
try { yield { sseEvent: currentEvent, data: JSON.parse(line.slice(6)) }; } catch (_) {}
currentEvent = "";
}
}
if (done) {
if (buffer.trim()) {
let evt = "";
for (const line of buffer.split("\n")) {
if (line.startsWith("event: ")) { evt = line.slice(7).trim(); continue; }
if (line.startsWith("data: ")) {
try { yield { sseEvent: evt, data: JSON.parse(line.slice(6)) }; } catch (_) {}
evt = "";
}
}
}
break;
}
}
}
function buildQuestion(messages) {
return messages.map(m => {
// Handle tool_result messages specially
if (m.role === "tool") {
return `tool_result: ${m.content}`;
}
// Handle tool_use content blocks (Anthropic format)
if (Array.isArray(m.content)) {
const parts = m.content.map(block => {
if (block.type === "tool_result") {
return `tool_result (${block.tool_use_id}): ${block.content || ""}`;
}
if (block.type === "tool_use") {
return `tool_call: ${block.name}(${JSON.stringify(block.input)})`;
}
if (block.type === "text") {
return block.text;
}
return JSON.stringify(block);
}).join("\n");
return `${m.role}: ${parts}`;
}
const c = typeof m.content === "string" ? m.content : JSON.stringify(m.content);
return `${m.role}: ${c}`;
}).join("\n");
}
/** 将 OpenAI/Anthropic 格式的 tools 转换为 ZO 可能接受的格式 */
function convertToolsToZO(tools, format) {
if (!tools || tools.length === 0) return [];
if (format === "openai") {
return tools.map(t => ({
name: t.function?.name || t.name,
description: t.function?.description || t.description || "",
parameters: t.function?.parameters || t.input_schema || {},
}));
}
// Anthropic format
return tools.map(t => ({
name: t.name,
description: t.description || "",
parameters: t.input_schema || {},
}));
}
/** 将工具定义格式化为文本描述,嵌入 q 字段 */
function formatToolsAsText(tools, format) {
if (!tools || tools.length === 0) return "";
const toolList = tools.map(t => {
const name = format === "openai" ? (t.function?.name || t.name) : t.name;
const desc = format === "openai" ? (t.function?.description || t.description || "") : (t.description || "");
const params = format === "openai" ? (t.function?.parameters || t.input_schema || {}) : (t.input_schema || {});
const props = params.properties || {};
const required = params.required || [];
const paramDescs = Object.entries(props).map(([k, v]) => {
const req = required.includes(k) ? " (必填)" : "";
return ` - ${k}: ${v.description || v.type || "any"}${req}`;
}).join("\n");
return `- ${name}: ${desc}\n 参数:\n${paramDescs || " 无参数"}`;
}).join("\n\n");
return `\n\n可用工具:\n${toolList}\n\n请使用上述工具完成任务,参数必须严格按照定义的格式。`;
}
/** 从 ZO 的 FrontendModelResponse 提取 usage,带上 cache */
function extractUsage(zoResp) {
const input = zoResp.input_tokens || 0;
const output = zoResp.output_tokens || 0;
const cacheRead = zoResp.cache_read_tokens || 0;
const cacheWrite = zoResp.cache_write_tokens || 0;
return { input, output, cacheRead, cacheWrite };
}
/** 构建 OpenAI 格式的 usage */
function buildOpenAIUsage(usage) {
return {
prompt_tokens: usage.input,
completion_tokens: usage.output,
total_tokens: usage.input + usage.output,
prompt_cache_hit_tokens: usage.cacheRead,
prompt_cache_write_tokens: usage.cacheWrite,
};
}
/** 构建 Anthropic 格式的 usage */
function buildAnthropicUsage(usage) {
return {
input_tokens: usage.input,
output_tokens: usage.output,
cache_read_input_tokens: usage.cacheRead,
cache_creation_input_tokens: usage.cacheWrite,
};
}
// ============ OpenAI 兼容接口 ============
// GET /v1/models - 动态获取模型
app.get("/v1/models", async (req, res) => {
try {
const models = await refreshModels();
res.json({
object: "list",
data: models.map(m => ({
id: toShortName(m.model_name),
object: "model",
created: Math.floor(cacheTime / 1000),
owned_by: m.vendor.toLowerCase(),
})),
});
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// POST /v1/chat/completions
app.post("/v1/chat/completions", async (req, res) => {
let { model, messages, tools, tool_choice, stream = false } = req.body;
if (!model || !messages) return res.status(400).json({ error: "model and messages are required" });
// 在系统消息末尾追加代理信息
const sysIdx = messages.findIndex(m => m.role === "system");
if (sysIdx >= 0) {
const sysMsg = messages[sysIdx];
const origContent = typeof sysMsg.content === "string" ? sysMsg.content
: (Array.isArray(sysMsg.content) ? sysMsg.content.map(b => b.text || b.content || "").join("\n") : "");
messages[sysIdx] = { ...sysMsg, content: origContent + "\n\n" + DEFAULT_SYSTEM_PROMPT };
} else {
messages = [{ role: "system", content: DEFAULT_SYSTEM_PROMPT }, ...messages];
}
const zoModel = resolveModel(model);
let question = buildQuestion(messages);
// 将工具定义嵌入 q 字段文本,确保模型能看到完整参数定义
if (tools && tools.length > 0) {
question += formatToolsAsText(tools, "openai");
console.log(`[tools] Embedding ${tools.length} tools in question text`);
}
const zoBody = {
q: question,
context_paths: [],
command_paths: [],
model_name: zoModel,
expanded_paths: ["Articles", "Images"],
stream: true, // 强制流式,因为 ZO API 总是返回 SSE
};
// 也传递 tools 字段(ZO 可能会用)
if (tools && tools.length > 0) {
zoBody.tools = convertToolsToZO(tools, "openai");
}
// 获取 token 并发送请求(支持 402 自动切换)
let tokenObj = getNextToken();
const availableTokens = tokenPool.filter(t => !t.exhausted);
if (availableTokens.length === 0) {
return res.status(402).json({ error: "All tokens exhausted" });
}
let resp;
for (let attempt = 0; attempt < availableTokens.length; attempt++) {
try {
console.log(`[request] Using token #${tokenObj.index}, attempt ${attempt + 1}`);
resp = await fetch(`${ZO_API}/ask`, {
method: "POST",
headers: zoHeaders(tokenObj),
body: JSON.stringify(zoBody),
});
// 402 错误:额度用完,尝试下一个 token
if (resp.status === 402) {
markTokenExhausted(tokenObj);
const nextToken = getNextToken();
if (nextToken.index === tokenObj.index || nextToken.exhausted) {
const err = await resp.text();
return res.status(402).json({ error: "All tokens exhausted", detail: err });
}
tokenObj = nextToken;
continue;
}
if (!resp.ok) {
const errText = await resp.text();
markTokenFailed(tokenObj, new Error(`HTTP ${resp.status}: ${errText}`));
return res.status(resp.status).json({ error: errText });
}
markTokenSuccess(tokenObj);
break;
} catch (err) {
markTokenFailed(tokenObj, err);
if (attempt === availableTokens.length - 1) {
console.error("ZO API error:", err);
return res.status(500).json({ error: err.message });
}
tokenObj = getNextToken();
}
}
// 确保 resp 存在
if (!resp) {
return res.status(500).json({ error: "No response from ZO API" });
}
try {
if (stream) {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.flushHeaders();
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let toolCalls = [];
let currentToolCall = null;
for await (const { sseEvent, data } of parseZoSse(reader, decoder)) {
console.log("[sse]", sseEvent, data.part?.part_kind || data.delta?.part_delta_kind || "");
// Handle tool-call PartStartEvent (ZO uses "tool-call" with hyphen)
if (sseEvent === "PartStartEvent" && data.part?.part_kind === "tool-call") {
currentToolCall = {
id: data.part.tool_call_id || "call_" + uid(),
type: "function",
function: { name: data.part.tool_name, arguments: "" },
};
toolCalls.push(currentToolCall);
res.write(`data: ${JSON.stringify({
id: "chatcmpl-" + uid(),
object: "chat.completion.chunk",
created: Math.floor(Date.now() / 1000),
model,
choices: [{ index: 0, delta: { tool_calls: [{ index: toolCalls.length - 1, id: currentToolCall.id, type: "function", function: { name: currentToolCall.function.name, arguments: "" } }] }, finish_reason: null }],
})}\n\n`);
continue;
}
// Handle tool_call PartDeltaEvent (ZO uses "tool_call" with underscore)
if (sseEvent === "PartDeltaEvent" && data.delta?.part_delta_kind === "tool_call" && currentToolCall) {
const argsDelta = data.delta.args_delta || "";
currentToolCall.function.arguments += argsDelta;
res.write(`data: ${JSON.stringify({
id: "chatcmpl-" + uid(),
object: "chat.completion.chunk",
created: Math.floor(Date.now() / 1000),
model,
choices: [{ index: 0, delta: { tool_calls: [{ index: toolCalls.length - 1, function: { arguments: argsDelta } }] }, finish_reason: null }],
})}\n\n`);
continue;
}
// Handle FunctionToolCallEvent (complete tool call with validated args)
if (sseEvent === "FunctionToolCallEvent") {
const tc = data.part;
// Update or add the tool call
const existing = toolCalls.find(t => t.id === tc.tool_call_id);
if (existing) {
existing.function.arguments = tc.args || "{}";
} else {
toolCalls.push({
id: tc.tool_call_id || "call_" + uid(),
type: "function",
function: { name: tc.tool_name, arguments: tc.args || "{}" },
});
}
continue;
}
// Handle text content
let delta = null;
if (sseEvent === "PartDeltaEvent" && data.delta?.part_delta_kind === "text") delta = data.delta.content_delta;
if (sseEvent === "PartStartEvent" && data.part?.part_kind === "text" && data.part.content) delta = data.part.content;
if (delta) {
res.write(`data: ${JSON.stringify({
id: "chatcmpl-" + uid(),
object: "chat.completion.chunk",
created: Math.floor(Date.now() / 1000),
model,
choices: [{ index: 0, delta: { content: delta }, finish_reason: null }],
})}\n\n`);
}
}
const finishReason = toolCalls.length > 0 ? "tool_calls" : "stop";
const finalDelta = toolCalls.length > 0
? { tool_calls: toolCalls.map((tc, i) => ({ index: i, ...tc })) }
: {};
res.write(`data: ${JSON.stringify({
id: "chatcmpl-" + uid(),
object: "chat.completion.chunk",
created: Math.floor(Date.now() / 1000),
model,
choices: [{ index: 0, delta: finalDelta, finish_reason: finishReason }],
})}\n\n`);
res.write("data: [DONE]\n\n");
res.end();
} else {
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let fullText = "";
let zoUsage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
let toolCalls = [];
for await (const { sseEvent, data } of parseZoSse(reader, decoder)) {
console.log("[sse]", sseEvent, data.part?.part_kind || data.delta?.part_delta_kind || "");
if (sseEvent === "FrontendModelResponse") {
zoUsage = extractUsage(data);
const textParts = (data.parts || []).filter(p => p.part_kind === "text");
if (textParts.length > 0) fullText = textParts.map(p => p.content).join("\n");
}
// Handle FunctionToolCallEvent (complete tool call)
if (sseEvent === "FunctionToolCallEvent") {
const tc = data.part;
toolCalls.push({
id: tc.tool_call_id || "call_" + uid(),
type: "function",
function: {
name: tc.tool_name,
arguments: tc.args || "{}",
},
});
}
if (sseEvent === "PartEndEvent" && data.part?.part_kind === "text" && data.part.content) {
fullText = fullText || data.part.content;
}
}
const message = { role: "assistant", content: fullText || null };
if (toolCalls.length > 0) {
message.tool_calls = toolCalls;
}
res.json({
id: "chatcmpl-" + uid(),
object: "chat.completion",
created: Math.floor(Date.now() / 1000),
model,
choices: [{ index: 0, message, finish_reason: toolCalls.length > 0 ? "tool_calls" : "stop" }],
usage: buildOpenAIUsage(zoUsage),
});
}
} catch (err) {
console.error("ZO API error:", err);
res.status(500).json({ error: err.message });
}
});
// ============ Anthropic Messages 兼容接口 ============
app.post("/v1/messages", async (req, res) => {
const { model, messages, system, tools, tool_choice, stream = false } = req.body;
if (!model || !messages) return res.status(400).json({ type: "error", error: { message: "model and messages are required" } });
const zoModel = resolveModel(model);
let question = "";
// 构建系统提示,总是追加代理信息
const sysText = system
? (typeof system === "string" ? system
: (Array.isArray(system) ? system.map(s => s.text || s.content).join("\n") : ""))
: "";
question = `System: ${sysText}\n\n${DEFAULT_SYSTEM_PROMPT}\n\n`;
question += buildQuestion(messages);
// 将工具定义嵌入 q 字段文本,确保模型能看到完整参数定义
if (tools && tools.length > 0) {
question += formatToolsAsText(tools, "anthropic");
console.log(`[tools] Embedding ${tools.length} tools in question text`);
}
const zoBody = {
q: question,
context_paths: [],
command_paths: [],
model_name: zoModel,
expanded_paths: ["Articles", "Images"],
stream: true, // 强制流式,因为 ZO API 总是返回 SSE
};
// 也传递 tools 字段(ZO 可能会用)
if (tools && tools.length > 0) {
zoBody.tools = convertToolsToZO(tools, "anthropic");
}
// 获取 token 并发送请求(支持 402 自动切换)
let tokenObj = getNextToken();
const availableTokens = tokenPool.filter(t => !t.exhausted);
if (availableTokens.length === 0) {
return res.status(402).json({ type: "error", error: { message: "All tokens exhausted" } });
}
let resp;
for (let attempt = 0; attempt < availableTokens.length; attempt++) {
try {
console.log(`[request] Using token #${tokenObj.index}, attempt ${attempt + 1}`);
resp = await fetch(`${ZO_API}/ask`, {
method: "POST",
headers: zoHeaders(tokenObj),
body: JSON.stringify(zoBody),
});
// 402 错误:额度用完,尝试下一个 token
if (resp.status === 402) {
markTokenExhausted(tokenObj);
const nextToken = getNextToken();
if (nextToken.index === tokenObj.index || nextToken.exhausted) {
const err = await resp.text();
return res.status(402).json({ type: "error", error: { message: "All tokens exhausted", detail: err } });
}
tokenObj = nextToken;
continue;
}
if (!resp.ok) {
const errText = await resp.text();
markTokenFailed(tokenObj, new Error(`HTTP ${resp.status}: ${errText}`));
return res.status(resp.status).json({ type: "error", error: { message: errText } });
}
markTokenSuccess(tokenObj);
break;
} catch (err) {
markTokenFailed(tokenObj, err);
if (attempt === availableTokens.length - 1) {
console.error("ZO API error:", err);
return res.status(500).json({ type: "error", error: { message: err.message } });
}
tokenObj = getNextToken();
}
}
// 确保 resp 存在
if (!resp) {
return res.status(500).json({ type: "error", error: { message: "No response from ZO API" } });
}
try {
if (stream) {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.flushHeaders();
const msgId = "msg_" + uid();
res.write(`event: message_start\ndata: ${JSON.stringify({
type: "message_start",
message: { id: msgId, type: "message", role: "assistant", content: [], model, usage: { input_tokens: 0, output_tokens: 0 } },
})}\n\n`);
// keepalive: Anthropic SDK 接受 comment 行做心跳
const keepalive = setInterval(() => res.write(": heartbeat\n\n"), 5000);
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let zoUsage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
let contentBlocks = []; // track all blocks for final stop_reason
let blockIndex = 0; // monotonically increasing index
let currentBlockType = null; // "text" or "tool_use" or null
let currentToolUse = null;
let textStarted = false;
let textClosed = false;
// Helper: close current block if open
function closeCurrentBlock() {
if (currentBlockType === "text" && textStarted && !textClosed) {
res.write(`event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: blockIndex - 1 })}\n\n`);
textClosed = true;
}
if (currentBlockType === "tool_use" && currentToolUse) {
// Parse accumulated input
if (typeof currentToolUse.input === "string") {
try { currentToolUse.input = JSON.parse(currentToolUse.input); } catch { currentToolUse.input = {}; }
}
res.write(`event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: blockIndex - 1 })}\n\n`);
currentToolUse = null;
}
currentBlockType = null;
}
for await (const { sseEvent, data } of parseZoSse(reader, decoder)) {
console.log("[sse]", sseEvent, data.part?.part_kind || data.delta?.part_delta_kind || "");
if (sseEvent === "FrontendModelResponse") {
zoUsage = extractUsage(data);
}
// Handle text PartStartEvent
if (sseEvent === "PartStartEvent" && data.part?.part_kind === "text") {
if (!textStarted) {
closeCurrentBlock();
res.write(`event: content_block_start\ndata: ${JSON.stringify({
type: "content_block_start", index: blockIndex,
content_block: { type: "text", text: "" },
})}\n\n`);
textStarted = true;
textClosed = false;
currentBlockType = "text";
blockIndex++;
}
continue;
}
// Handle text PartDeltaEvent
if (sseEvent === "PartDeltaEvent" && data.delta?.part_delta_kind === "text") {
if (currentBlockType !== "text") {
closeCurrentBlock();
res.write(`event: content_block_start\ndata: ${JSON.stringify({
type: "content_block_start", index: blockIndex,
content_block: { type: "text", text: "" },
})}\n\n`);
textStarted = true;
textClosed = false;
currentBlockType = "text";
blockIndex++;
}
res.write(`event: content_block_delta\ndata: ${JSON.stringify({
type: "content_block_delta", index: blockIndex - 1,
delta: { type: "text_delta", text: data.delta.content_delta || "" },
})}\n\n`);
continue;
}
// Handle text PartEndEvent
if (sseEvent === "PartEndEvent" && data.part?.part_kind === "text") {
if (currentBlockType === "text" && !textClosed) {
res.write(`event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: blockIndex - 1 })}\n\n`);
textClosed = true;
currentBlockType = null;
}
continue;
}
// Handle tool-call PartStartEvent (ZO uses "tool-call" with hyphen)
if (sseEvent === "PartStartEvent" && data.part?.part_kind === "tool-call") {
closeCurrentBlock();
currentToolUse = {
type: "tool_use",
id: data.part.tool_call_id || "toolu_" + uid(),
name: data.part.tool_name,
input: "",
};
contentBlocks.push(currentToolUse);
currentBlockType = "tool_use";
res.write(`event: content_block_start\ndata: ${JSON.stringify({
type: "content_block_start", index: blockIndex,
content_block: { type: "tool_use", id: currentToolUse.id, name: currentToolUse.name, input: {} },
})}\n\n`);
blockIndex++;
continue;
}
// Handle tool_call PartDeltaEvent (ZO uses "tool_call" with underscore)
if (sseEvent === "PartDeltaEvent" && data.delta?.part_delta_kind === "tool_call" && currentToolUse) {
const argsDelta = data.delta.args_delta || "";
currentToolUse.input += argsDelta;
res.write(`event: content_block_delta\ndata: ${JSON.stringify({
type: "content_block_delta", index: blockIndex - 1,
delta: { type: "input_json_delta", partial_json: argsDelta },
})}\n\n`);
continue;
}
// Handle FunctionToolCallEvent (complete tool call with validated args)
if (sseEvent === "FunctionToolCallEvent") {
const tc = data.part;
if (currentToolUse && currentToolUse.id === tc.tool_call_id) {
// Update existing tool call
currentToolUse.input = tc.args || "{}";
} else {
// New tool call not started by PartStartEvent
closeCurrentBlock();
currentToolUse = {
type: "tool_use",
id: tc.tool_call_id || "toolu_" + uid(),
name: tc.tool_name,
input: tc.args || "{}",
};
contentBlocks.push(currentToolUse);
currentBlockType = "tool_use";
res.write(`event: content_block_start\ndata: ${JSON.stringify({
type: "content_block_start", index: blockIndex,
content_block: { type: "tool_use", id: currentToolUse.id, name: currentToolUse.name, input: {} },
})}\n\n`);
blockIndex++;
// Send the full input as delta
res.write(`event: content_block_delta\ndata: ${JSON.stringify({
type: "content_block_delta", index: blockIndex - 1,
delta: { type: "input_json_delta", partial_json: currentToolUse.input },
})}\n\n`);
}
continue;
}
// Handle tool-call PartEndEvent
if (sseEvent === "PartEndEvent" && data.part?.part_kind === "tool-call") {
if (currentBlockType === "tool_use" && currentToolUse) {
// Parse the accumulated input
if (typeof currentToolUse.input === "string") {
try { currentToolUse.input = JSON.parse(currentToolUse.input); } catch { currentToolUse.input = {}; }
}
res.write(`event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index: blockIndex - 1 })}\n\n`);
currentToolUse = null;
currentBlockType = null;
}
continue;
}
}
clearInterval(keepalive);
// Close any remaining open block
closeCurrentBlock();
const stopReason = contentBlocks.length > 0 ? "tool_use" : "end_turn";
res.write(`event: message_delta\ndata: ${JSON.stringify({
type: "message_delta",
delta: { stop_reason: stopReason, stop_sequence: null },
usage: { output_tokens: zoUsage.output },
})}\n\n`);
res.write(`event: message_stop\ndata: ${JSON.stringify({ type: "message_stop" })}\n\n`);
res.end();
} else {
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let fullText = "";
let zoUsage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
let toolUses = [];
for await (const { sseEvent, data } of parseZoSse(reader, decoder)) {
console.log("[sse]", sseEvent, data.part?.part_kind || data.delta?.part_delta_kind || "");
if (sseEvent === "FrontendModelResponse") {
zoUsage = extractUsage(data);
const textParts = (data.parts || []).filter(p => p.part_kind === "text");
if (textParts.length > 0) fullText = textParts.map(p => p.content).join("\n");
}
// Handle FunctionToolCallEvent (complete tool call)
if (sseEvent === "FunctionToolCallEvent") {
const tc = data.part;
toolUses.push({
type: "tool_use",
id: tc.tool_call_id || "toolu_" + uid(),
name: tc.tool_name,
input: typeof tc.args === "string" ? JSON.parse(tc.args) : (tc.args || {}),
});
}
if (sseEvent === "PartEndEvent" && data.part?.part_kind === "text" && data.part.content) {
fullText = fullText || data.part.content;
}
}
const content = [];
if (fullText) content.push({ type: "text", text: fullText });
content.push(...toolUses);
res.json({
id: "msg_" + uid(),
type: "message",
role: "assistant",
content,
model,
stop_reason: toolUses.length > 0 ? "tool_use" : "end_turn",
usage: buildAnthropicUsage(zoUsage),
});
}
} catch (err) {
console.error("ZO API error:", err);
res.status(500).json({ type: "error", error: { message: err.message } });
}
});
// ============ 健康检查 ============
app.get("/health", (req, res) => {
res.json({
status: "ok",
zo_api: ZO_API,
models_cached: !!cachedModels,
model_count: cachedModels?.length || 0,
tokens: {
total: tokenPool.length,
available: tokenPool.filter(t => !t.exhausted).length,
exhausted: tokenPool.filter(t => t.exhausted).length,
},
});
});
// ============ 启动 ============
const PORT = process.env.PORT || config.port || 3000;
app.listen(PORT, async () => {
console.log(`ZO Proxy starting on http://localhost:${PORT}`);
console.log(`Tokens: ${tokenPool.length} loaded, ${tokenPool.filter(t => !t.exhausted).length} available`);
// 重试加载模型(最多 3 次)
for (let i = 0; i < 3; i++) {
try {
await refreshModels();
if (cachedModels && cachedModels.length > 0) break;
} catch (e) {
console.log(`[models] Attempt ${i + 1} failed, retrying...`);
await new Promise(r => setTimeout(r, 1000));
}
}
console.log(`ZO Proxy running on http://localhost:${PORT}`);
console.log(` OpenAI: POST http://localhost:${PORT}/v1/chat/completions`);
console.log(` Anthropic: POST http://localhost:${PORT}/v1/messages`);
console.log(` Models: GET http://localhost:${PORT}/v1/models`);
if (cachedModels && cachedModels.length > 0) {
console.log(`Available: ${Object.keys(shortNameMap).join(", ")}`);
console.log(`Free models: ${cachedModels.filter(m => m.type === "free").map(m => toShortName(m.model_name)).join(", ")}`);
} else {
console.log(`Models: Failed to load (will retry on first request)`);
}
});