-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
2258 lines (2099 loc) · 102 KB
/
Copy pathworker.js
File metadata and controls
2258 lines (2099 loc) · 102 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
const CODEBUFF_API = "https://www.codebuff.com";
const DEFAULT_MODEL = "deepseek/deepseek-v4-flash";
const DEFAULT_API_KEY = "freebuff-default-key";
const VERSION = "1.9.0";
const CONTEXT_PRUNER_AGENT = "context-pruner";
// 仅在官方动态源不可用或旧快照没有暂停字段时使用。成功解析官方源后,
// 该名单会被完整替换,避免把已经恢复的历史模型继续误判为暂停。
const FALLBACK_PAUSED_MODEL_IDS = new Set([
"minimax/minimax-m3",
]);
// 动态模型注册表:从官方 freebuff 镜像拉取模型清单
// 真源: https://github.com/CodebuffAI/freebuff (freebuff-private 的 public 镜像)
// 与 Freebuff Desktop 0.0.51 orchestrator.js 的 FREEBUFF_ROOT_AGENT_ID_BY_MODEL 同源
// (镜像常量 = 桌面版同源源码,安装包只是编译产物)
// 需要 3 个源(常量分散定义):
// 1. free-agents.ts → FREEBUFF_ROOT_AGENT_ID_BY_MODEL(模型→agent 映射)
// 2. freebuff-models.ts → 大部分模型 ID 常量 + 池定义(PREMIUM/GLM)
// 3. freebuff-model-ids.ts→ deepseek/m3 等 ID 常量(被 models.ts re-export)
// 每源都有 raw 主源 + jsDelivr 备用
const DYNAMIC_MODELS_SOURCES = [
"https://raw.githubusercontent.com/CodebuffAI/freebuff/main/common/src/constants/free-agents.ts",
"https://cdn.jsdelivr.net/gh/CodebuffAI/freebuff@main/common/src/constants/free-agents.ts",
];
const DYNAMIC_MODELS_MODEL_IDS_SOURCES = [
"https://raw.githubusercontent.com/CodebuffAI/freebuff/main/common/src/constants/freebuff-models.ts",
"https://cdn.jsdelivr.net/gh/CodebuffAI/freebuff@main/common/src/constants/freebuff-models.ts",
];
const DYNAMIC_MODELS_STABLE_IDS_SOURCES = [
"https://raw.githubusercontent.com/CodebuffAI/freebuff/main/common/src/constants/freebuff-model-ids.ts",
"https://cdn.jsdelivr.net/gh/CodebuffAI/freebuff@main/common/src/constants/freebuff-model-ids.ts",
];
// Releases 兜底源:GitHub Actions 每天生成的解析好的 JSON(无需解析,直接可用)
// 当官方 3 个源全部失败/解析失败时使用。固定 models-cache tag,避免版本 Release
// 改变 releases/latest 指向后导致模型快照 404。
const DYNAMIC_MODELS_RELEASE_SOURCES = [
"https://github.com/wintopic/FreeBuff2API/releases/download/models-cache/freebuff-models.json",
];
// 刷新间隔:与 Quorinex 对齐,6 小时。失败时回退到硬编码 MODELS。
const DYNAMIC_MODELS_REFRESH_MS = 6 * 60 * 60 * 1000;
const DYNAMIC_MODELS_FETCH_TIMEOUT_MS = 10000;
// 运行时动态模型缓存(内存,无 KV)
let dynamicModelsCache = {
fetchedAt: 0,
models: null, // 动态模型表(含分类)
pool: null, // { premium: Set, standard: Set, glm: Set }
paused: new Set(), // 官方 FREEBUFF_PAUSED_FREE_MODEL_IDS
pausedKnown: false, // true 表示已读取官方暂停列表(包括明确为空)
};
// 解析 freebuff-models.ts 的模型 ID 常量
// 形如:
// export const FREEBUFF_MIMO_V25_MODEL_ID = mimoModels.mimoV25
// export const FREEBUFF_MINIMAX_M3_MODEL_ID = 'minimax/minimax-m3'
// 兼容: 'string' | 标识符.成员(取成员名查 knownDefaults)| 标识符
function parseModelIdConstants(source) {
const table = {};
const knownDefaults = {
mimoV25: "mimo/mimo-v2.5",
};
// 匹配 export const NAME = 'value' 或 export const NAME = expr
const re = /export\s+const\s+([A-Z0-9_]+)\s*=\s*(?:'([^']*)'|"([^"]*)"|([A-Za-z0-9_.]+))/g;
let m;
while ((m = re.exec(source)) !== null) {
const name = m[1];
const lit = m[2] ?? m[3] ?? "";
const expr = m[4] ?? "";
if (lit) table[name] = lit;
else if (expr) {
// 标识符.成员 → 取成员名(mimoModels.mimoV25 → mimoV25)
const member = expr.includes(".") ? expr.split(".").pop() : expr;
if (knownDefaults[member]) table[name] = knownDefaults[member];
else if (/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.:/-]+$/.test(expr)) table[name] = expr;
}
}
return table;
}
// 解析 free-agents.ts 中按用途分开的 agent 映射。
// 不把 base2 root、base3 root、reviewer 混为一张表:它们属于不同运行路径。
function parseAgentMappings(source, modelIdConstants) {
const blockNames = {
root: "FREEBUFF_ROOT_AGENT_ID_BY_MODEL",
base3: "FREEBUFF_WEB_BASE3_AGENT_ID_BY_MODEL",
reviewer: "FREEBUFF_REVIEWER_AGENT_ID_BY_MODEL",
};
const result = { root: {}, base3: {}, reviewer: {} };
const lineRe = /\[\s*([A-Z0-9_]+)\s*\]\s*:\s*'([^']+)'/g;
for (const [kind, blockName] of Object.entries(blockNames)) {
const blockRe = new RegExp(`${blockName}[^=]*=\\s*\\{([^}]*)\\}`);
const blockMatch = blockRe.exec(source);
if (!blockMatch) continue;
let m;
lineRe.lastIndex = 0;
while ((m = lineRe.exec(blockMatch[1])) !== null) {
const modelId = modelIdConstants[m[1]];
if (modelId) result[kind][modelId] = m[2];
}
}
return result;
}
// 兼容旧调用方:默认返回普通 base2 root 映射。
function parseAgentMapping(source, modelIdConstants) {
return parseAgentMappings(source, modelIdConstants).root;
}
// 解析 freebuff-models.ts 的池定义(PREMIUM / GLM;STANDARD 由 non-premium 推导)
// FREEBUFF_WEB_PREMIUM_MODEL_IDS 含 spread(...FREEBUFF_PREMIUM_MODEL_IDS)
function parseModelPools(source, modelIdConstants) {
const premium = new Set();
const glm = new Set();
const used = new Set();
// 展开 spread: ...FOO → FOO 里的条目(常量名 → 值)
const constValues = new Map();
const constListRe = /export\s+const\s+([A-Z0-9_]+)\s*=\s*\[([^\]]*)\]\s*as\s*const/g;
let cm;
while ((cm = constListRe.exec(source)) !== null) {
const name = cm[1];
const items = [];
const itemRe = /\.\.\.([A-Z0-9_]+)|'([^']*)'|"([^"]*)"|([A-Za-z0-9_]+)/g;
let im;
while ((im = itemRe.exec(cm[2])) !== null) {
const spread = im[1];
const lit = im[2] ?? im[3];
const expr = im[4];
if (spread) items.push(["spread", spread]);
else if (lit) items.push(["lit", lit]);
else if (expr && modelIdConstants[expr]) items.push(["lit", modelIdConstants[expr]]);
}
constValues.set(name, items);
}
// 解析池
const poolRe = /export\s+const\s+(FREEBUFF_WEB_PREMIUM_MODEL_IDS|FREEBUFF_GLM_V52_MODEL_IDS|FREEBUFF_PREMIUM_MODEL_IDS)\s*=\s*\[([^\]]*)\]/g;
let pm;
while ((pm = poolRe.exec(source)) !== null) {
const poolName = pm[1];
const items = [];
const itemRe = /\.\.\.([A-Z0-9_]+)|'([^']*)'|"([^"]*)"|([A-Za-z0-9_]+)/g;
let im;
while ((im = itemRe.exec(pm[2])) !== null) {
const spread = im[1];
const lit = im[2] ?? im[3];
const expr = im[4];
if (spread) {
// 递归展开 spread 常量
const expand = (n) => {
const entries = constValues.get(n) || [];
for (const [kind, val] of entries) {
if (kind === "spread") expand(val);
else items.push(val);
}
};
expand(spread);
} else if (lit) items.push(lit);
else if (expr && modelIdConstants[expr]) items.push(modelIdConstants[expr]);
}
if (poolName === "FREEBUFF_GLM_V52_MODEL_IDS") {
for (const id of items) glm.add(id);
} else {
for (const id of items) premium.add(id);
}
}
// FREEBUFF_PREMIUM_MODEL_IDS 与 FREEBUFF_WEB_PREMIUM_MODEL_IDS 都算 premium
return { premium: [...premium], glm: [...glm] };
}
// 解析官方 FREEBUFF_PAUSED_FREE_MODEL_IDS。found 用来区分“官方明确列表为空”
// 和“旧快照/解析器没有这个常量”,后者只能使用保守兜底名单。
function parsePausedModels(source, modelIdConstants) {
const listRe = /export\s+const\s+FREEBUFF_PAUSED_FREE_MODEL_IDS\b[^=]*=\s*\[([^\]]*)\]/;
const listMatch = listRe.exec(source || "");
if (!listMatch) return { found: false, ids: new Set() };
const ids = new Set();
const listBody = listMatch[1]
.replace(/\/\*[\s\S]*?\*\//g, "")
.replace(/\/\/.*$/gm, "");
const itemRe = /'([^']*)'|"([^"]*)"|([A-Za-z0-9_]+)/g;
let item;
while ((item = itemRe.exec(listBody)) !== null) {
const literal = item[1] ?? item[2];
const expression = item[3];
if (literal) ids.add(literal);
else if (expression && modelIdConstants[expression]) ids.add(modelIdConstants[expression]);
}
return { found: true, ids };
}
// 动态模型表:分别记录普通 root、base3 root、reviewer。
function buildDynamicModelTable(agentMappings) {
// 兼容旧调用:传入单张 root mapping 时仍可正常构建。
const mappings = agentMappings && agentMappings.root
? agentMappings
: { root: agentMappings || {}, base3: {}, reviewer: {} };
return Object.entries(mappings.root).map(([modelId, rootAgent]) => ({
id: modelId,
session: modelId,
// 旧字段保留为普通 root,普通 chat 永远使用它。
agent: rootAgent,
root_agent: rootAgent,
base3_agent: mappings.base3[modelId] || null,
reviewer_agent: mappings.reviewer[modelId] || null,
upstream: modelId,
}));
}
// 合并硬编码与动态表:硬编码优先(不覆盖),动态新增追加
function mergeModelTables(hardcoded, dynamic) {
const seen = new Set(hardcoded.map((m) => m.id));
const merged = [...hardcoded];
for (const m of dynamic) {
if (!seen.has(m.id)) {
merged.push(m);
seen.add(m.id);
}
}
return merged;
}
// 拉取并刷新动态模型缓存(失败静默回退)
async function fetchSourceList(urls) {
for (const url of urls) {
let timer = null;
try {
const ctrl = new AbortController();
timer = setTimeout(() => ctrl.abort(), DYNAMIC_MODELS_FETCH_TIMEOUT_MS);
const resp = await fetch(url, { signal: ctrl.signal });
if (resp.ok) {
const text = await resp.text();
// 阈值放宽:freebuff-model-ids.ts 只有 ~491B(3 个常量),
// 500 阈值会误杀。只过滤真正的空文件(<100B)。
if (text && text.length > 100) return text;
}
} catch {
} finally {
if (timer !== null) clearTimeout(timer);
}
}
return null;
}
async function refreshDynamicModelsIfStale() {
const now = Date.now();
if (dynamicModelsCache.models && now - dynamicModelsCache.fetchedAt < DYNAMIC_MODELS_REFRESH_MS) {
return dynamicModelsCache;
}
// 并行拉 3 个源(每源主 raw + 备 jsDelivr)
const [agentsSrc, modelsSrc, stableIdsSrc] = await Promise.all([
fetchSourceList(DYNAMIC_MODELS_SOURCES),
fetchSourceList(DYNAMIC_MODELS_MODEL_IDS_SOURCES),
fetchSourceList(DYNAMIC_MODELS_STABLE_IDS_SOURCES),
]);
if (!agentsSrc || !modelsSrc) {
// 官方源拉取失败:尝试 Releases JSON 兜底
const release = await tryReleaseFallback();
if (release) {
dynamicModelsCache = release;
return dynamicModelsCache;
}
// Releases 也失败:保留旧缓存(若有),否则维持现状
return dynamicModelsCache;
}
try {
// 合并常量表:models.ts 优先(完整),stableIds.ts 补充 deepseek/m3
const modelIdConstants = { ...parseModelIdConstants(stableIdsSrc || ""), ...parseModelIdConstants(modelsSrc) };
const agentMappings = parseAgentMappings(agentsSrc, modelIdConstants);
if (Object.keys(agentMappings.root).length === 0) {
// 解析失败:尝试 Releases 兜底
const release = await tryReleaseFallback();
if (release) {
dynamicModelsCache = release;
return dynamicModelsCache;
}
return dynamicModelsCache;
}
const pools = parseModelPools(modelsSrc, modelIdConstants);
const pausedInfo = parsePausedModels(modelsSrc, modelIdConstants);
dynamicModelsCache = {
fetchedAt: Date.now(),
models: buildDynamicModelTable(agentMappings),
pool: {
premium: new Set(pools.premium),
standard: null,
glm: new Set(pools.glm),
},
paused: pausedInfo.found ? pausedInfo.ids : new Set(FALLBACK_PAUSED_MODEL_IDS),
pausedKnown: pausedInfo.found,
};
} catch {
// 解析崩溃:尝试 Releases 兜底
const release = await tryReleaseFallback();
if (release) {
dynamicModelsCache = release;
return dynamicModelsCache;
}
// 保留旧缓存
}
return dynamicModelsCache;
}
// Releases JSON 兜底:直接拉预生成的 models.json,零解析成本
async function tryReleaseFallback() {
for (const url of DYNAMIC_MODELS_RELEASE_SOURCES) {
let timer = null;
try {
const ctrl = new AbortController();
timer = setTimeout(() => ctrl.abort(), DYNAMIC_MODELS_FETCH_TIMEOUT_MS);
const resp = await fetch(url, { signal: ctrl.signal });
if (resp.ok) {
const json = await resp.json();
if (json && Array.isArray(json.models) && json.models.length > 0) {
const pausedList = Array.isArray(json.paused)
? json.paused
: Array.isArray(json.pausedModels) ? json.pausedModels : null;
const hasPaused = Array.isArray(pausedList);
const paused = new Set(hasPaused ? pausedList : FALLBACK_PAUSED_MODEL_IDS);
const premium = new Set(json.pools?.premium ?? []);
const glm = new Set(json.pools?.glm ?? []);
for (const id of paused) {
premium.delete(id);
glm.delete(id);
}
return {
fetchedAt: Date.now(),
models: json.models,
pool: {
premium,
standard: null,
glm,
},
paused,
pausedKnown: hasPaused,
};
}
}
} catch {
} finally {
if (timer !== null) clearTimeout(timer);
}
}
return null;
}
// 动态 STANDARD = 动态表里不在 premium/glm 池的模型
function dynamicStandardModels() {
const cache = dynamicModelsCache;
if (!cache || !cache.models || !cache.pool) return new Set();
const premium = cache.pool.premium;
const glm = cache.pool.glm;
return new Set(cache.models.map((m) => m.id).filter((id) => !premium.has(id) && !glm.has(id)));
}
// 模型池分类查询:动态池优先,硬编码兜底
// 返回 "premium" | "standard" | "glm" | null
function modelPoolCategory(modelId) {
if (isPausedModel(modelId)) return null;
const dyn = dynamicModelsCache;
if (dyn && dyn.pool) {
if (dyn.pool.premium.has(modelId)) return "premium";
if (dyn.pool.glm.has(modelId)) return "glm";
if (dynamicStandardModels().has(modelId)) return "standard";
}
// 硬编码兜底
if (PREMIUM_QUOTA_MODELS.has(modelId)) return "premium";
if (STANDARD_MODELS.has(modelId)) return "standard";
return null;
}
// 模型 → session 用模型名 / 上游 agentId / 上游 chat 模型名
// 只保留稳定 fallback 的硬编码兜底。其余模型(包括当前默认 Flash)全部
// 由动态拉取提供,避免官方撤回或恢复模型时被旧硬编码表覆盖。
// 来源顺序:官方源 → GitHub Release 快照 → 这个 fallback。
const MODELS = [
{ id: "mimo/mimo-v2.5", session: "mimo/mimo-v2.5", agent: "base2-free-mimo", upstream: "mimo/mimo-v2.5" },
];
// ---------------------------------------------------------------------------
// 额度池说明(逆向自官方源码 freebuff-models.ts,2026-08-23 快照)
//
// 官方额度池(都是 session/admission 次数,非 token 数):
// 1. PREMIUM 池:当前共享上限为 4/天;Flash、Pro、Luna 等共同消耗。
// Luna 另有每模型 2/天 cap,Pro 当前无单独 cap。
// 2. STANDARD 池:MiMo 等非 premium 模型;“unlimited”只表示官方分类,
// 不构成任何账号、地区或时段的绝对无限量承诺。
// 3. GLM 5.2 池:独立,referral 解锁(不计入以上)
//
// 桌面版并发桶(FREEBUFF_DESKTOP_SESSION_LIMITS,仅限并发非额度):
// premium: 1 ← Premium 模型每用户同时 1 个活跃 session
// unlimited: 3 ← Flash/MiMo 每用户最多 3 个并发 tab
// limited 访问层(无 Premium 的号):所有模型都占 1 个 slot
// (occupiesFreebuffDesktopSlot / getFreebuffDesktopSessionBucket)
//
// 实际可用性仍以每个账号上游返回的 rateLimitsByModel/status 为准;额度池
// 只用于选号和耗尽判断,绝不改变调用方请求的模型。
// ---------------------------------------------------------------------------
const PREMIUM_QUOTA_MODELS = new Set([
"deepseek/deepseek-v4-flash",
"deepseek/deepseek-v4-pro",
"openai/gpt-5.6-luna",
"openai/gpt-5.6-luna-es",
"crof/kimi-k3-eco",
"meta/muse-spark-1.2-contributor",
]);
const STANDARD_MODELS = new Set([
"mimo/mimo-v2.5",
"anthropic/claude-fable-5",
"stealth/ox-alpha",
]);
// 官方暂停/不可用模型状态来自动态源;此函数只在动态源尚未成功读取时
// 使用保守兜底。暂停模型不静默替换,避免客户端以为调用了原模型。
function isPausedModel(modelId) {
const cache = dynamicModelsCache;
if (cache && cache.pausedKnown) return cache.paused.has(modelId);
return (cache?.paused && cache.paused.size > 0)
? cache.paused.has(modelId)
: FALLBACK_PAUSED_MODEL_IDS.has(modelId);
}
// ---------------------------------------------------------------------------
// 桌面版协议常量(逆向自 Freebuff Desktop orchestrator.js)
// 桌面版 = multi-session 模式(每 tab 一个实例),与 CLI 单会话区分。
// ⚠️ 实测(2026-08-10):multi-session 创建的实例 chat 报 428 waiting_room_required
// (服务端 chat gate 不识别多会话实例),因此 POST 实际用单会话但保留
// 预生成 instance-id 的桌面版签名。include-unused-rate-limits 是浏览器/
// 模型选择器用的额度快照头,GET 探测时带它没问题。
// ---------------------------------------------------------------------------
const DESKTOP_INCLUDE_RATE_LIMITS = { "x-freebuff-include-unused-rate-limits": "1" };
export default {
async fetch(request, env) {
const url = new URL(request.url);
if (request.method === "OPTIONS") return new Response(null, { status: 204, headers: corsHeaders() });
// healthz 不鉴权:健康检查/监控探针不应依赖 API key
if (request.method === "GET" && url.pathname === "/healthz") {
// 健康检查只读 Worker 最近一次真实请求形成的本地快照。
// 不因为公开探针访问就向上游 fan-out GET /session 和 /me;这类请求
// 会产生额外行为,也可能干扰同一账号正在进行的会话。
return jsonResponse({
status: "ok",
version: VERSION,
...summarizeAccountHealth(parseAccounts(env), acctHealth),
health_source: "worker_cache",
time: new Date().toISOString(),
}, 200);
}
const key = getApiKey(request, env);
if (!key) {
if (url.pathname === "/v1/messages" || url.pathname === "/messages" || url.pathname === "/v1/messages/count_tokens" || url.pathname === "/messages/count_tokens") {
return anthropicError("Invalid API key", "authentication_error", 401);
}
return jsonResponse({ error: { message: "Invalid API key", type: "auth_error" } }, 401);
}
cleanCache();
if (request.method === "GET" && (url.pathname === "/v1/models" || url.pathname === "/models")) {
return await handleModels();
}
if (request.method === "POST" && (url.pathname === "/v1/chat/completions" || url.pathname === "/chat/completions")) {
return handleChat(request, env);
}
if (request.method === "POST" && (url.pathname === "/v1/responses" || url.pathname === "/responses")) {
return handleResponses(request, env);
}
if (request.method === "POST" && (url.pathname === "/v1/messages/count_tokens" || url.pathname === "/messages/count_tokens")) {
return handleAnthropicCountTokens(request, env);
}
if (request.method === "POST" && (url.pathname === "/v1/messages" || url.pathname === "/messages")) {
return handleAnthropicMessages(request, env);
}
return jsonResponse({ error: { message: "Not found", type: "not_found" } }, 404);
},
};
// ---------------------------------------------------------------------------
// 账号池
// ---------------------------------------------------------------------------
let accountIdx = 0;
const cooldowns = new Map(); // token -> 冷却到期 ms
const sessCache = new Map(); // `${token}:${sessionModel}` -> { instanceId, model, remainingMs, expiresAt }(必须带 token,多账号防串号)
function parseAccounts(env) {
// 支持一行一个(换行)或逗号分隔;每项可为纯 token 或 "token:uid"(冒号配对 user_id)
// 例:"t1\nt2:u2\nt3,u4:u4" → [{token:t1,uid:null},{token:t2,uid:u2},...]
return (env.FREEBUFF_TOKEN || "").split(/[\n,]/)
.map((s) => s.trim())
.filter((s) => s.length > 8)
.map((s) => {
const idx = s.indexOf(":");
if (idx > 0) return { token: s.slice(0, idx).trim(), uid: s.slice(idx + 1).trim() || null };
return { token: s, uid: null };
})
.filter((a) => a.token.length > 8);
}
// ---------------------------------------------------------------------------
// 账号健康探测(v1.6.0):GET /api/v1/me 不消耗 session/额度,探测 token 有效性并自动发现 uid
// ---------------------------------------------------------------------------
const acctHealth = new Map(); // token -> { alive, state, uid, quota, checkedAt }
const HEALTH_OBSERVATION_TTL_MS = 10 * 60 * 1000;
// 只记录真实业务请求已经观察到的上游结果。不要在 healthz 中主动探测,
// 也不要把网络错误/未知响应误记成账号失效。
function recordAccountObservation(token, status, dataOrText, extra = {}) {
if (!token) return;
let data = dataOrText;
if (typeof dataOrText === "string") {
try { data = JSON.parse(dataOrText); } catch { data = null; }
}
const upstreamState = data && typeof data === "object" ? data.status || data.state : null;
let state = null;
if (status === 404) state = "ok";
else if (["banned", "country_blocked", "rate_limited", "model_locked", "ip_capped"].includes(upstreamState)) state = upstreamState;
else if (status >= 200 && status < 300) state = "ok";
else if (status === 401) state = "token_invalid";
else if (status === 403) {
state = upstreamState === "banned"
? "banned"
: upstreamState === "country_blocked" ? "country_blocked" : "blocked";
} else if (status === 429) state = "rate_limited";
if (!state) return;
const previous = acctHealth.get(token) || {};
acctHealth.set(token, {
...previous,
...extra,
alive: state === "ok",
state,
uid: extra.uid || previous.uid || null,
quota: extra.quota || previous.quota || null,
retryAfterMs: typeof extra.retryAfterMs === "number" ? extra.retryAfterMs : previous.retryAfterMs || null,
checkedAt: Date.now(),
});
}
function summarizeAccountHealth(pool, health) {
const account_details = pool.map((acct) => {
const info = health.get(acct.token);
return {
token: acct.token.slice(0, 8) + "...",
alive: info ? info.alive : null,
state: info?.state || "unknown",
uid: info?.uid ? info.uid.slice(0, 8) + "..." : null,
};
});
const account_states = {};
for (const detail of account_details) {
account_states[detail.state] = (account_states[detail.state] || 0) + 1;
}
const alive_accounts = account_details.filter((p) => p.alive === true).length;
const unknown_accounts = account_details.filter((p) => p.alive === null).length;
const unhealthy_accounts = account_details.filter((p) => p.alive === false).length;
const status = pool.length === 0
? "critical"
: alive_accounts === 0 && (unhealthy_accounts > 0 || unknown_accounts > 0)
? "critical"
: unhealthy_accounts > 0 || unknown_accounts > 0
? "degraded"
: "ok";
return {
status,
accounts: pool.length,
alive_accounts,
unknown_accounts,
account_states,
account_details,
};
}
function pickToken(env, sessionModel) {
const pool = parseAccounts(env);
if (pool.length === 0) return null;
// v1.6.0:跳过已探测为失效的号(alive=false);未探测/探测失败的不跳过(避免误杀)
const alivePool = pool.filter((acct) => {
const h = acctHealth.get(acct.token);
return !(h && h.alive === false);
});
const usePool = alivePool.length > 0 ? alivePool : pool; // 全失效时回退全池,让请求继续(由 429 冷却接管)
// v1.8.5.1:账号选择恢复为稳定轮询。
// rateLimitsByModel 仅作为观测数据,不参与轮询顺序;真实 session/chat
// 返回明确限流后,再通过 cooldown 跳过该账号。这样不会因为旧快照
// 抢占轮询,也不会把账号顺序重排成“剩余额度最多优先”。
const finalPool = usePool;
// 优先复用已有活跃 session 缓存的号:一个 session 约 1 小时有效,创建 session 才扣
// 免费额度(Premium 共享池当前默认上限为 4 次/天,实际以上游快照为准)。
// 纯轮询会让每个请求都切号、各建一个 session,
// 浪费创建额度。只要当前模型的 session 缓存还活跃就钉在同一个号上,用满再换。
if (sessionModel) {
for (const acct of finalPool) {
const t = acct.token;
if (cooldowns.has(t) && cooldowns.get(t) > Date.now()) continue;
const cached = sessCache.get(t + ":" + sessionModel);
if (isUsableSession(cached)) {
return acct;
}
}
}
// 没有活跃缓存才轮询(跳过冷却中的号)
for (let k = 0; k < finalPool.length; k++) {
const acct = finalPool[accountIdx % finalPool.length];
accountIdx = (accountIdx + 1) % finalPool.length;
const t = acct.token;
if (!cooldowns.has(t) || cooldowns.get(t) <= Date.now()) return acct;
}
const oldest = [...cooldowns.entries()].sort((a, b) => a[1] - b[1])[0];
if (oldest) cooldowns.delete(oldest[0]);
return finalPool[0];
}
function normalizeSession(data, requestedModel, now = Date.now()) {
const expiryMs = Date.parse(data?.expiresAt || "");
const remaining = Number(data?.remainingMs);
const effectiveExpiry = Number.isFinite(expiryMs)
? expiryMs
: (Number.isFinite(remaining) ? now + Math.max(0, remaining) : NaN);
return {
model: data?.model || requestedModel,
instanceId: data?.instanceId || null,
remainingMs: Number.isFinite(effectiveExpiry) ? Math.max(0, effectiveExpiry - now) : null,
expiresAt: Number.isFinite(effectiveExpiry) ? new Date(effectiveExpiry).toISOString() : null,
};
}
function isUsableSession(session, now = Date.now()) {
const expiryMs = Date.parse(session?.expiresAt || "");
return Boolean(session?.instanceId) && Number.isFinite(expiryMs) && expiryMs > now + 60000;
}
function accountSlot(pool, token) {
const index = pool.findIndex((acct) => acct.token === token);
return index >= 0 ? `${index + 1}/${pool.length}` : `?/${pool.length}`;
}
function logAccountRoute(enabled, pool, token, model, attempt, reason) {
if (!enabled) return;
try {
console.log(JSON.stringify({ event: "account_route", model, account_slot: accountSlot(pool, token), attempt, reason }));
} catch {}
}
function cooldown(token, ms) {
if (ms > 0) cooldowns.set(token, Date.now() + ms);
}
// Official Freebuff session-gate recovery requires matching both the HTTP
// status and the relayed error code. Do not treat session_limit_reached or
// waiting_room_queued as stale sessions: those states must not delete a live
// session or burn another session slot.
const SESSION_GATE_RECOVERY = {
waiting_room_required: 428,
session_expired: 410,
session_superseded: 409,
session_model_mismatch: 409,
};
function hasExactErrorCode(value, expected) {
if (value === expected) return true;
if (!value || typeof value !== "object") return false;
return Object.values(value).some((entry) => hasExactErrorCode(entry, expected));
}
function upstreamErrorMessage(data, text = "") {
if (typeof data === "string") return data.slice(0, 200);
if (data && typeof data === "object") {
const direct = data.message || data.error_description || data.error;
if (typeof direct === "string") return direct.slice(0, 200);
if (direct && typeof direct === "object") {
const nested = direct.message || direct.code || direct.error;
if (typeof nested === "string") return nested.slice(0, 200);
}
}
return String(text || "").slice(0, 200);
}
function isModelUnavailableResponse(status, data, text = "", allowBare410 = false) {
return hasExactErrorCode(data, "model_unavailable")
|| (typeof text === "string" && /\bmodel_unavailable\b/.test(text))
|| (allowBare410 && status === 410);
}
function isStaleSessionGate(status, body) {
let parsed = null;
try { parsed = JSON.parse(body); } catch {}
return Object.entries(SESSION_GATE_RECOVERY).some(([code, expectedStatus]) =>
status === expectedStatus && hasExactErrorCode(parsed, code));
}
// 仅供流式无首数据时确认 Premium 额度是否耗尽;不参与账号轮询排序。
function remainingQuota(token, sessionModel) {
const poolCategory = modelPoolCategory(sessionModel);
if (poolCategory === "standard" || poolCategory === null) return null;
const h = acctHealth.get(token);
if (!h || !h.quota) return null;
// Current upstream payloads can contain several Premium pools (for example
// Luna's per-model cap alongside the shared pool). Never borrow another
// model's row: a missing exact row means “unknown”, not “same quota”.
const entry = h.quota[sessionModel];
if (!entry || typeof entry.recentCount !== "number" || typeof entry.limit !== "number") return null;
return entry.limit - entry.recentCount;
}
// 长流不应因为固定秒数被误杀:只有上游额度探测明确表示不可用时,
// 才允许当前请求中止并切换账号。探测失败/额度未知一律不判定耗尽。
function isQuotaExhausted(info, sessionModel) {
if (!info) return false;
if (["rate_limited", "banned", "country_blocked", "token_invalid", "blocked", "model_locked", "ip_capped"].includes(info.state)) return true;
// STANDARD 没有可靠的剩余次数查询;只处理明确的账号/上游状态,
// 不根据 rateLimitsByModel 的 STANDARD 数字判断耗尽。
const poolCategory = modelPoolCategory(sessionModel);
if (poolCategory === "standard" || poolCategory === null) return false;
if (!info.quota) return false;
// Do not infer a model's remaining quota from another model's row. The
// official API now exposes independent pools/caps in rateLimitsByModel.
const entry = info.quota[sessionModel];
if (!entry || typeof entry.recentCount !== "number" || typeof entry.limit !== "number") return false;
return entry.limit - entry.recentCount <= 0;
}
function parseCooldown(text, status) {
// 优先解析 JSON 里的 retryAfterMs(luna 等模型 429 返回 {"retryAfterMs": 15506639})
const jm = (text || "").match(/"retryAfterMs"\s*:\s*(\d+)/);
if (jm) {
const ms = parseInt(jm[1], 10);
if (ms > 0) return Math.min(ms, 6 * 3600 * 1000);
}
const m = (text || "").match(/try again in (?:(\d+)\s*h)?\s*(?:(\d+)\s*m)?\s*(?:(\d+)\s*s)?/i);
if (m) {
const ms = (parseInt(m[1]||0,10)*3600 + parseInt(m[2]||0,10)*60 + parseInt(m[3]||0,10)) * 1000;
if (ms > 0) return Math.min(ms, 6*3600*1000);
}
return status === 429 ? 5*60*1000 : 60*1000;
}
class QuotaExhaustedError extends Error {
constructor(info) {
super("upstream account quota exhausted");
this.name = "QuotaExhaustedError";
this.retryAfterMs = info && typeof info.retryAfterMs === "number" ? info.retryAfterMs : null;
}
}
// 上游 410/model_unavailable 表示模型是全局暂停/下线状态,而不是当前账号
// 的额度问题。此错误不能触发账号轮换,否则会对所有账号重复发送必败请求。
class ModelUnavailableError extends Error {
constructor(modelId, upstreamMessage = "") {
super("model unavailable upstream: " + modelId + (upstreamMessage ? " — " + upstreamMessage : ""));
this.name = "ModelUnavailableError";
this.modelId = modelId;
}
}
class EmptyUpstreamStreamError extends Error {
constructor() {
super("upstream returned an empty stream");
this.name = "EmptyUpstreamStreamError";
}
}
function invalidateSessionCache(token) {
const prefix = token + ":";
for (const key of sessCache.keys()) {
if (key.startsWith(prefix)) sessCache.delete(key);
}
}
async function deleteUpstreamSession(token, instanceId) {
invalidateSessionCache(token);
if (!instanceId) return;
try {
await enqueueUp("DELETE", "/api/v1/freebuff/session", token, undefined,
{ "x-freebuff-instance-id": instanceId }, SESSION_TIMEOUT_MS);
} catch {}
}
// ---------------------------------------------------------------------------
// 上游请求(串行队列,免费通道并发超过 1 就出问题)
// ---------------------------------------------------------------------------
let chainTail = Promise.resolve();
const CHAIN_GAP_MS = 300; // 上游免费通道并发 >1 会出问题,串行+小间隔;300ms 足够防抖且链路总耗时可控
function sleep(ms) { return new Promise((r) => setTimeout(r, ms)); }
function enqueue(fn) {
const run = chainTail.then(() => sleep(CHAIN_GAP_MS)).then(fn);
chainTail = run.catch(() => {});
return run;
}
const UPSTREAM_TIMEOUT_MS = 20000; // 上游单请求超时,避免客户端干等
const NONSTREAM_TIMEOUT_MS = 45000; // 非流式要聚合完整上游流(含推理),给更充裕时间
const SESSION_TIMEOUT_MS = 10000; // session/run 等短交互更快失败
// 这不是流式请求的失败时间,只是首个数据迟迟未到时启动一次额度探测的观察窗口。
// 额度仍在时不 abort、不切号,继续等待上游。
const STREAM_NO_DATA_PROBE_DELAY_MS = 20000;
async function up(method, path, token, body, extraHeaders = {}, timeoutMs = UPSTREAM_TIMEOUT_MS) {
const headers = {};
// 桌面版协议:不手动设置 User-Agent(fetch 默认),只带必要的业务头
if (token) headers.Authorization = `Bearer ${token}`;
if (body !== undefined) headers["Content-Type"] = "application/json";
Object.assign(headers, extraHeaders);
const resp = await fetch(CODEBUFF_API + path, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(timeoutMs),
});
const text = await resp.text();
let data = null;
try { data = text ? JSON.parse(text) : null; } catch { data = text; }
return { status: resp.status, data, text };
}
function enqueueUp(method, path, token, body, extraHeaders, timeoutMs) {
return enqueue(() => up(method, path, token, body, extraHeaders, timeoutMs));
}
// 流式无首数据时的额度检查:只读本地缓存,绝不打上游。
// ⚠️ 不能在这里 GET /api/v1/freebuff/session 强制刷新:
// 该接口会占用账号 session,而 freebuff 一个号同一时间只能一个客户端在线,
// 探测会顶掉正在推理的会话(428 waiting_room_required)。luna effort=high
// 等长推理模型首 token 可能 >20s,此时探测必然误伤。
// 缓存缺失/过期/额度未知 → 一律不判定耗尽,继续等待上游。
async function freshQuotaProbe(token, sessionModel) {
const cached = acctHealth.get(token);
if (!cached) return;
if (Date.now() - cached.checkedAt > HEALTH_OBSERVATION_TTL_MS) return;
if (isQuotaExhausted(cached, sessionModel)) throw new QuotaExhaustedError(cached);
}
// 流式 chat 不设置总时长 abort。只有在首个数据迟迟未到时,
// 才强制刷新账号额度;额度未知或仍有额度时,原请求继续等待。
async function fetchStreamWithQuotaGuard(url, init, token, sessionModel) {
const controller = new AbortController();
const request = fetch(url, { ...init, signal: controller.signal });
let probeTimer = null;
const armProbe = () => new Promise((_, reject) => {
probeTimer = setTimeout(() => {
freshQuotaProbe(token, sessionModel).catch((error) => {
if (error instanceof QuotaExhaustedError) {
try { controller.abort(error); } catch { controller.abort(); }
reject(error);
}
});
}, STREAM_NO_DATA_PROBE_DELAY_MS);
});
const clearProbe = () => {
if (probeTimer !== null) clearTimeout(probeTimer);
probeTimer = null;
};
try {
// 首个字节前不再使用 AbortSignal.timeout(20s)。
const response = await Promise.race([request, armProbe()]);
clearProbe();
if (!response.body) throw new EmptyUpstreamStreamError();
const reader = response.body.getReader();
const first = await Promise.race([reader.read(), armProbe()]);
clearProbe();
if (first.done) {
try { reader.releaseLock(); } catch {}
throw new EmptyUpstreamStreamError();
}
// 首个 chunk 已到达,交还给正常 SSE 转发逻辑;不再设置固定总时长。
const body = new ReadableStream({
start(streamController) {
streamController.enqueue(first.value);
(async () => {
try {
while (true) {
const next = await reader.read();
if (next.done) break;
streamController.enqueue(next.value);
}
streamController.close();
} catch (error) {
streamController.error(error);
} finally {
try { reader.releaseLock(); } catch {}
}
})();
},
cancel(reason) { return reader.cancel(reason); },
});
return new Response(body, { status: response.status, headers: response.headers });
} catch (error) {
clearProbe();
try { controller.abort(error); } catch { controller.abort(); }
throw error;
}
}
// ---------------------------------------------------------------------------
// session 生命周期
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// 正常客户端行为层(v1.8.8.1,源码依据:官方 cli/src/hooks/use-gravity-ad.ts、
// cli/src/utils/fingerprint.ts、sdk/src/impl/llm.ts)
// - 稳定指纹:每个 Worker(账号)一个永不变化的 fingerprintId(enhanced- 前缀,
// 官方用硬件序列号/MAC/机器ID 哈希;CF 无硬件,用 token 派生稳定哈希即可,
// 关键是"同一账号永远同一指纹")
// - 广告链:官方免费推理靠广告(源码注释原话),每次会话前 POST /ads 拉取 +
// POST /ads/impression 上报曝光,失败静默
// - usage 触碰:官方客户端启动会查 /api/v1/usage,补上让调用面更完整
// ---------------------------------------------------------------------------
const BEHAVIOR_CACHE_TTL_MS = 30 * 60 * 1000; // 30 分钟
const behaviorCache = new Map(); // key -> ts
function behaviorDue(key) {
const ts = behaviorCache.get(key) || 0;
if (Date.now() - ts > BEHAVIOR_CACHE_TTL_MS) {
behaviorCache.set(key, Date.now());
return true;
}
return false;
}
// 稳定指纹:token 派生,同一账号永远一致(官方 enhanced- 前缀 + 哈希)
// CF Workers 无同步 WebCrypto,用轻量确定性哈希(FNV-1a 双种子 + hex)
function stableFingerprint(token) {
let h1 = 0x811c9dc5, h2 = 0x01000193;
const s = "freebuff-fp-v2:" + token;
for (let i = 0; i < s.length; i++) {
const c = s.charCodeAt(i);
h1 = Math.imul(h1 ^ c, 0x01000193) >>> 0;
h2 = Math.imul(h2 ^ c, 0x85ebca6b) >>> 0;
}
return "enhanced-" + h1.toString(16).padStart(8, "0") + h2.toString(16).padStart(8, "0");
}
// 广告链:POST /ads 拉取 → 若有 impUrl 则 POST /ads/impression 上报曝光。
// 官方实现:getCliAdRequestUserAgent 发 Freebuff-CLI/<version> UA;
// body {provider:"gravity", surface, sessionId, device, userAgent};曝光 {impUrl, mode}
async function runNormalClientBehavior(token, clientFingerprint) {
const failures = [];
// 1) 广告拉取 + 曝光(每 30 分钟一次,避免每个请求都打广告接口)
if (behaviorDue("ads:" + token)) {
try {
const ad = await enqueueUp("POST", "/api/v1/ads", token, {
provider: "gravity",
sessionId: crypto.randomUUID(),
surface: "waiting_room",
device: { os: "macos", timezone: "Asia/Shanghai", locale: "zh-CN" },
userAgent: "Freebuff-CLI/0.0.138",
}, { "User-Agent": "Freebuff-CLI/0.0.138", "Content-Type": "application/json" }, 6000);
const impUrl = ad.data && Array.isArray(ad.data.ads) && ad.data.ads[0] && ad.data.ads[0].impUrl;
if (ad.status === 200 && impUrl) {
await enqueueUp("POST", "/api/v1/ads/impression", token,
{ impUrl, mode: "free" },
{ "User-Agent": "Freebuff-CLI/0.0.138", "Content-Type": "application/json" }, 6000);
}
} catch (e) { failures.push("ads:" + String(e && e.message || e).slice(0, 80)); }
}
// 2) usage 触碰(30 分钟一次)
if (behaviorDue("usage:" + token)) {
try {
await enqueueUp("POST", "/api/v1/usage", token,
{ fingerprintId: clientFingerprint },
{ "Content-Type": "application/json" }, 6000);
} catch (e) { failures.push("usage:" + String(e && e.message || e).slice(0, 80)); }
}
return failures;
}
async function createSession(token, sessionModel, forceCreate = false) {
// 0) 正常客户端行为:广告链 + usage 触碰(30 分钟节流,失败静默)
try { await runNormalClientBehavior(token, stableFingerprint(token)); } catch {}
// 1) 缓存命中且未过期(剩 >60s)直接复用,避免每次请求都打上游 session 接口
if (!forceCreate) {
const cached = sessCache.get(token + ":" + sessionModel);
if (isUsableSession(cached)) {
return cached;
}
if (cached) sessCache.delete(token + ":" + sessionModel);
}
// 1) 查上游当前 session,同模型直接复用(forceCreate 时跳过:僵尸 active session 会被 GET 反复复用,
// 导致 chat 一直 428;强制 POST 拿全新实例)
// 桌面版签名:GET 带 include-unused-rate-limits(模型选择器额度快照头)
if (!forceCreate) {
const cur = await enqueueUp("GET", "/api/v1/freebuff/session", token, undefined,
DESKTOP_INCLUDE_RATE_LIMITS, SESSION_TIMEOUT_MS);
recordAccountObservation(token, cur.status, cur.data, {