Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
9974 lines (9365 loc) · 420 KB
/
Copy pathserver.js
File metadata and controls
9974 lines (9365 loc) · 420 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 crypto = require("crypto");
/**
* OpenCode Go Multi-Subscription Smart Router & Load Balancer
* Ultra-low overhead, zero external dependencies (Node.js native).
*
* Features:
* - Full Graphical Configuration UI (/balancer/ui)
* - Safe atomic configuration update & hot-reload without restart
* - One-click account connectivity test with latency check
* - Seamless round-robin / session-affinity load balancing (KV Cache optimized)
* - Zero-downtime 429 / 503 failover with dynamic Retry-After cooldown calculation
* - Full SSE streaming passthrough (text/event-stream)
* - Preserves x-opencode-session header
* - Environment variable fallback (OPENCODE_GO_KEY_1, OPENCODE_GO_KEY_2)
* - Integrated Doctor & Auto-Repair diagnostic engine (/balancer/api/doctor & /balancer/api/repair)
* - Dynamic cooldown reset API (/balancer/api/reset-cooldown)
* - Health check endpoint (/health & /balancer/health)
* - Global CORS preflight (OPTIONS) support
*/
const http = require('node:http');
const https = require('node:https');
const net = require('node:net');
const tls = require('node:tls');
const url = require('node:url');
const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const { execSync, exec, spawn } = require('node:child_process');
const codexAdapter = require('./codex-adapter');
const contextCompactor = require('./context-compactor');
const powershellOptimizer = require('./powershell-optimizer');
let ComfyUIAdapter;
try {
ComfyUIAdapter = require('./comfyui-adapter').ComfyUIAdapter;
} catch (e) {
ComfyUIAdapter = class DummyComfyUIAdapter {
constructor() { this.enabled = false; }
isComfyUIRequest() { return false; }
handleComfyUIRequest() { return false; }
};
}
process.on('uncaughtException', (err) => {
console.error('[Uncaught Exception]', err && err.stack ? err.stack : err);
});
process.on('unhandledRejection', (reason) => {
console.error('[Unhandled Rejection]', reason);
});
const CONFIG_FILE = process.env.OPENCODE_ROUTER_CONFIG || path.join(__dirname, 'config.json');
let CURRENT_ROUTER_VERSION = '3.14.4';
try {
const pkgData = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
if (pkgData && pkgData.version) CURRENT_ROUTER_VERSION = pkgData.version;
} catch (_) {}
function writeFileSyncAtomic(filePath, data, encoding = 'utf8') {
const dir = path.dirname(filePath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
const tmpPath = path.join(dir, `.tmp-${path.basename(filePath)}-${Date.now()}-${Math.random().toString(36).slice(2)}`);
fs.writeFileSync(tmpPath, data, encoding);
try {
fs.renameSync(tmpPath, filePath);
} catch (err) {
try {
fs.copyFileSync(tmpPath, filePath);
fs.unlinkSync(tmpPath);
} catch (_) {
try {
fs.writeFileSync(filePath, data, encoding);
if (fs.existsSync(tmpPath)) fs.unlinkSync(tmpPath);
} catch (finalErr) {
try { if (fs.existsSync(tmpPath)) fs.unlinkSync(tmpPath); } catch (_) {}
throw finalErr;
}
}
}
}
const DEFAULT_CONFIG = {
port: 4010,
host: '127.0.0.1',
upstream: 'https://opencode.ai/zen/go/v1',
defaultCooldownMs: 60000,
maxFailoverRetries: 2,
sessionAffinityEnabled: true,
ttftTimeoutMs: 25000,
chunkIdleTimeoutMs: 60000,
circuitBreaker: {
enabled: true,
failureThreshold: 3,
baseCooldownMs: 5000,
maxCooldownMs: 120000,
halfOpenMaxProbes: 1
},
uiPassword: '',
allowModelAutoUpgrade: false,
allowRegionFallback: false,
modelSourcePolicy: 'hybrid',
defaultModel: 'deepseek-v4.1-flash',
favoriteModels: ['deepseek-v4.1-flash', 'kimi-k3'],
proxy: {
enabled: false,
url: '',
scope: 'all',
models: ['gpt-5.6-luna', 'gpt-6-luna', 'claude-haiku-5-5']
},
accounts: [
{
id: 'account-1',
name: 'OpenCode Go 主账号',
apiKey: '',
enabled: true
},
{
id: 'account-2',
name: 'OpenCode Go 备用账号',
apiKey: '',
enabled: true
}
],
compression: contextCompactor.DEFAULT_COMPRESSION_CONFIG,
comfyui: {
enabled: true,
host: 'http://127.0.0.1:8284',
workflowsDir: '',
localDir: '',
repoUrl: 'https://github.com/deancyl/comfyui-agent-workflows',
timeoutSec: 180
}
};
const DEFAULT_OMO_CONFIG = {
"$schema": "https://raw.githubusercontent.com/code-yeongyu/oh-my-openagent/dev/assets/omo.schema.json",
"[opencode]": {
"agents": {
"sisyphus": { "model": "opencode-go/kimi-k3" },
"oracle": { "model": "opencode-go/glm-5.3" },
"librarian": { "model": "opencode-go/qwen3.7-plus", "fallback_models": [{ "model": "opencode-go/minimax-m3" }] },
"explore": { "model": "opencode-go/qwen3.7-plus", "fallback_models": [{ "model": "opencode-go/minimax-m3" }] },
"multimodal-looker": { "model": "opencode-go/kimi-k3" },
"prometheus": { "model": "opencode-go/kimi-k3", "variant": "high" },
"metis": { "model": "opencode-go/kimi-k3", "variant": "high" },
"momus": { "model": "opencode-go/glm-5.3" },
"atlas": { "model": "opencode-go/kimi-k3", "fallback_models": [{ "model": "opencode-go/minimax-m3" }] },
"sisyphus-junior": { "model": "opencode-go/kimi-k3", "fallback_models": [{ "model": "opencode-go/minimax-m3" }] }
},
"categories": {
"visual-engineering": { "model": "opencode-go/kimi-k3", "variant": "high" },
"ultrabrain": { "model": "opencode-go/deepseek-v4.1-flash" },
"deep-low": { "model": "opencode-go/deepseek-v4.1-flash" },
"deep-high": { "model": "opencode-go/deepseek-v4-pro" },
"artistry": { "model": "opencode-go/kimi-k3", "variant": "high" },
"quick": { "model": "opencode-go/minimax-m3", "variant": "high" },
"unspecified-low": { "model": "opencode-go/deepseek-v4.1-flash" },
"unspecified-high": { "model": "opencode-go/deepseek-v4-pro" }
}
}
};
const proxyAgentCache = new Map();
const MAX_PROXY_AGENT_CACHE = 50; // N3 Fix: Bounded LRU cap to prevent unbounded memory growth
function clearProxyAgentCache() {
for (const [key, agent] of proxyAgentCache.entries()) {
try { agent.destroy(); } catch (_) {}
}
proxyAgentCache.clear();
}
// Load or initialize config
let config = { ...DEFAULT_CONFIG };
function loadConfig() {
if (fs.existsSync(CONFIG_FILE)) {
try {
const raw = fs.readFileSync(CONFIG_FILE, 'utf8').replace(/^\uFEFF/, '');
config = Object.assign({}, DEFAULT_CONFIG, JSON.parse(raw));
config.compression = contextCompactor.normalizeCompressionOptions(config.compression || DEFAULT_CONFIG.compression);
config.allowModelAutoUpgrade = Boolean(config.allowModelAutoUpgrade);
config.allowRegionFallback = Boolean(config.allowRegionFallback);
config.modelSourcePolicy = ['official_docs', 'api_probed', 'hybrid'].includes(config.modelSourcePolicy) ? config.modelSourcePolicy : 'hybrid';
config.defaultModel = config.defaultModel || 'deepseek-v4.1-flash';
config.favoriteModels = Array.isArray(config.favoriteModels) ? config.favoriteModels : ['deepseek-v4.1-flash', 'kimi-k3'];
if (typeof config.proxy === 'string') {
config.proxy = { enabled: Boolean(config.proxy.trim()), url: config.proxy.trim(), scope: 'all', models: [] };
} else if (config.proxy && typeof config.proxy === 'object') {
config.proxy = {
enabled: config.proxy.enabled !== false,
url: (config.proxy.url || '').trim(),
scope: config.proxy.scope || 'all',
models: Array.isArray(config.proxy.models) ? config.proxy.models : ['gpt-5.6-luna', 'gpt-6-luna', 'claude-haiku-5-5']
};
} else {
config.proxy = { ...DEFAULT_CONFIG.proxy };
}
if (!config.plugins || typeof config.plugins !== 'object') {
config.plugins = {};
}
clearProxyAgentCache();
codexAdapter.configureAdapter(config);
} catch (err) {
console.error('[Config] Failed to load config.json, using defaults:', err.message);
}
} else {
try {
writeFileSyncAtomic(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf8');
} catch (err) {
console.error('[Config] Failed to create default config.json:', err.message);
}
}
// Allow PORT environment variable override
if (process.env.PORT) {
const p = parseInt(process.env.PORT, 10);
if (!isNaN(p) && p > 0) config.port = p;
}
// Allow HOST / OPENCODE_ROUTER_HOST override
if (process.env.OPENCODE_ROUTER_HOST || process.env.HOST) {
config.host = (process.env.OPENCODE_ROUTER_HOST || process.env.HOST).trim();
}
// Allow OPENCODE_ROUTER_PASSWORD override
if (process.env.OPENCODE_ROUTER_PASSWORD) {
config.uiPassword = process.env.OPENCODE_ROUTER_PASSWORD.trim();
}
// Fallback to environment variables if apiKey is empty
if (Array.isArray(config.accounts)) {
if (config.accounts[0] && (!config.accounts[0].apiKey || !config.accounts[0].apiKey.trim())) {
const envKey1 = process.env.OPENCODE_GO_KEY_1 || process.env.OPENCODE_GO_API_KEY;
if (envKey1 && envKey1.trim()) {
config.accounts[0].apiKey = envKey1.trim();
}
}
if (config.accounts[1] && (!config.accounts[1].apiKey || !config.accounts[1].apiKey.trim())) {
const envKey2 = process.env.OPENCODE_GO_KEY_2;
if (envKey2 && envKey2.trim()) {
config.accounts[1].apiKey = envKey2.trim();
}
}
}
}
loadConfig();
const comfyuiAdapter = new ComfyUIAdapter({ rootDir: __dirname, config });
if (typeof codexAdapter !== 'undefined' && codexAdapter && typeof codexAdapter.setComfyUIAdapter === 'function') {
codexAdapter.setComfyUIAdapter(comfyuiAdapter);
}
let pluginManager = null;
try {
const { PluginManager } = require('./plugin-manager');
pluginManager = new PluginManager({ rootDir: __dirname, configPath: CONFIG_FILE, routerPort: config.port || 4010 });
pluginManager.scanPlugins();
const pluginsCfg = pluginManager.getPluginsConfig();
for (const [id, manifest] of pluginManager.discoveredPlugins.entries()) {
if (pluginManager.isPluginEnabled(id, manifest, pluginsCfg)) {
pluginManager.enablePlugin(id, { persist: false }).catch(e => {
console.warn(`[PluginManager] 启动加载插件 "${id}" 失败:`, e.message);
});
}
}
config.plugins = pluginsCfg;
if (typeof codexAdapter !== 'undefined' && codexAdapter && typeof codexAdapter.setPluginManager === 'function') {
codexAdapter.setPluginManager(pluginManager);
}
} catch (e) {
console.warn('[PluginManager] 初始化异常:', e.message);
}
/**
* Zero-dependency native HTTP CONNECT tunnel forward proxy agent for Node.js 18+
* Allows routing upstream requests through HTTP/HTTPS proxies (e.g. http://127.0.0.1:7890)
* to bypass geographic IP restrictions (403 unsupported_country_region_territory) for Luna models.
*/
class HttpsTunnelAgent extends https.Agent {
constructor(proxyUrlOrOpts, options = {}) {
let proxyUrlStr = proxyUrlOrOpts;
let agentOpts = options;
if (proxyUrlOrOpts && typeof proxyUrlOrOpts === 'object') {
proxyUrlStr = proxyUrlOrOpts.proxyUrl || proxyUrlOrOpts.url;
agentOpts = { ...proxyUrlOrOpts, ...options };
}
super({ keepAlive: true, keepAliveMsecs: 10000, maxSockets: 50, ...agentOpts });
let norm = String(proxyUrlStr || '').trim();
if (norm && !/^https?:\/\//i.test(norm)) {
norm = 'http://' + norm;
}
this.proxyUrl = new URL(norm || 'http://127.0.0.1:80');
this.agentOpts = agentOpts;
}
createConnection(options, callback) {
const isProxyHttps = this.proxyUrl.protocol === 'https:';
const proxyModule = isProxyHttps ? https : http;
const proxyPort = parseInt(this.proxyUrl.port, 10) || (isProxyHttps ? 443 : 80);
const targetHost = options.host || options.hostname;
const targetPort = options.port || 443;
const connectHeaders = {
'Host': `${targetHost}:${targetPort}`,
'Proxy-Connection': 'Keep-Alive',
'User-Agent': 'OpenCode-Router-ProxyTunnel/1.0'
};
if (this.proxyUrl.username || this.proxyUrl.password) {
const auth = `${decodeURIComponent(this.proxyUrl.username)}:${decodeURIComponent(this.proxyUrl.password)}`;
connectHeaders['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
} else if (this.agentOpts?.auth) {
connectHeaders['Proxy-Authorization'] = `Basic ${Buffer.from(String(this.agentOpts.auth)).toString('base64')}`;
}
const connectReq = proxyModule.request({
host: this.proxyUrl.hostname,
port: proxyPort,
method: 'CONNECT',
path: `${targetHost}:${targetPort}`,
headers: connectHeaders,
timeout: 15000
});
let settled = false;
const onError = (err) => {
if (settled) return;
settled = true;
try { connectReq.destroy(); } catch (_) {}
callback(err);
};
connectReq.on('timeout', () => {
onError(new Error(`Proxy CONNECT timeout after 15s (${this.proxyUrl.host})`));
});
connectReq.on('error', onError);
connectReq.on('connect', (res, socket, head) => {
if (settled) {
try { socket.destroy(); } catch (_) {}
return;
}
if (res.statusCode !== 200) {
settled = true;
try { socket.destroy(); } catch (_) {}
return callback(new Error(`Proxy CONNECT rejected with HTTP ${res.statusCode}: ${res.statusMessage || ''}`));
}
if (head && head.length > 0) {
socket.unshift(head);
}
socket.on('error', (err) => {
if (!settled) {
settled = true;
callback(err);
}
});
const rejectUnauthorized = options.rejectUnauthorized !== undefined
? options.rejectUnauthorized
: (this.agentOpts?.rejectUnauthorized !== undefined ? this.agentOpts.rejectUnauthorized : true);
const tlsSocket = tls.connect({
socket: socket,
servername: options.servername || targetHost,
rejectUnauthorized
}, () => {
if (settled) return;
settled = true;
callback(null, tlsSocket);
});
tlsSocket.on('error', (err) => {
if (!settled) {
settled = true;
callback(err);
}
});
});
connectReq.end();
}
}
class HttpTunnelAgent extends http.Agent {
constructor(proxyUrlOrOpts, options = {}) {
let proxyUrlStr = proxyUrlOrOpts;
let agentOpts = options;
if (proxyUrlOrOpts && typeof proxyUrlOrOpts === 'object') {
proxyUrlStr = proxyUrlOrOpts.proxyUrl || proxyUrlOrOpts.url;
agentOpts = { ...proxyUrlOrOpts, ...options };
}
super({ keepAlive: true, keepAliveMsecs: 10000, maxSockets: 50, ...agentOpts });
let norm = String(proxyUrlStr || '').trim();
if (norm && !/^https?:\/\//i.test(norm)) {
norm = 'http://' + norm;
}
this.proxyUrl = new URL(norm || 'http://127.0.0.1:80');
this.agentOpts = agentOpts;
}
createConnection(options, callback) {
const isProxyHttps = this.proxyUrl.protocol === 'https:';
const proxyModule = isProxyHttps ? https : http;
const proxyPort = parseInt(this.proxyUrl.port, 10) || (isProxyHttps ? 443 : 80);
const targetHost = options.host || options.hostname;
const targetPort = options.port || 80;
const connectHeaders = {
'Host': `${targetHost}:${targetPort}`,
'Proxy-Connection': 'Keep-Alive',
'User-Agent': 'OpenCode-Router-ProxyTunnel/1.0'
};
if (this.proxyUrl.username || this.proxyUrl.password) {
const auth = `${decodeURIComponent(this.proxyUrl.username)}:${decodeURIComponent(this.proxyUrl.password)}`;
connectHeaders['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
} else if (this.agentOpts?.auth) {
connectHeaders['Proxy-Authorization'] = `Basic ${Buffer.from(String(this.agentOpts.auth)).toString('base64')}`;
}
const connectReq = proxyModule.request({
host: this.proxyUrl.hostname,
port: proxyPort,
method: 'CONNECT',
path: `${targetHost}:${targetPort}`,
headers: connectHeaders,
timeout: 15000
});
let settled = false;
const onError = (err) => {
if (settled) return;
settled = true;
try { connectReq.destroy(); } catch (_) {}
callback(err);
};
connectReq.on('timeout', () => {
onError(new Error(`Proxy CONNECT timeout after 15s (${this.proxyUrl.host})`));
});
connectReq.on('error', onError);
connectReq.on('connect', (res, socket, head) => {
if (settled) {
try { socket.destroy(); } catch (_) {}
return;
}
if (res.statusCode !== 200) {
settled = true;
try { socket.destroy(); } catch (_) {}
return callback(new Error(`Proxy CONNECT rejected with HTTP ${res.statusCode}: ${res.statusMessage || ''}`));
}
if (head && head.length > 0) {
socket.unshift(head);
}
socket.on('error', (err) => {
if (!settled) {
settled = true;
callback(err);
}
});
settled = true;
callback(null, socket);
});
connectReq.end();
}
}
function getProxyAgent(proxyUrlInput, isHttps = true) {
if (!proxyUrlInput) return null;
const proxyUrlStr = typeof proxyUrlInput === 'string'
? proxyUrlInput.trim()
: (proxyUrlInput.proxyUrl || proxyUrlInput.url || '').toString().trim();
if (!proxyUrlStr) return null;
const key = `${isHttps ? 'https' : 'http'}://${proxyUrlStr}`;
if (proxyAgentCache.has(key)) {
// LRU refresh: delete and re-insert to move to end
const cached = proxyAgentCache.get(key);
proxyAgentCache.delete(key);
proxyAgentCache.set(key, cached);
return cached;
}
try {
// N3 Fix: Evict oldest entry when cache exceeds bounded cap
if (proxyAgentCache.size >= MAX_PROXY_AGENT_CACHE) {
const oldestKey = proxyAgentCache.keys().next().value;
const oldAgent = proxyAgentCache.get(oldestKey);
proxyAgentCache.delete(oldestKey);
try { oldAgent.destroy(); } catch (_) {}
}
const agent = isHttps ? new HttpsTunnelAgent(proxyUrlStr) : new HttpTunnelAgent(proxyUrlStr);
proxyAgentCache.set(key, agent);
return agent;
} catch (err) {
console.error(`[Proxy Agent Error] Failed to initialize proxy agent for "${proxyUrlStr}":`, err.message);
return null;
}
}
const OVERSEAS_RESTRICTED_MODELS = new Set([
'gpt-5.6-luna',
'gpt-6-luna',
'claude-haiku-5-5'
]);
function getEffectiveProxyForRequest(modelName = null) {
let proxyConf = config.proxy;
// 1. If explicit config.proxy exists
if (proxyConf !== undefined && proxyConf !== null) {
if (typeof proxyConf === 'string' && proxyConf.trim()) {
return { url: proxyConf.trim(), scope: 'all' };
}
if (typeof proxyConf === 'object') {
if (proxyConf.enabled === false) {
return null;
}
const url = (proxyConf.url || '').trim();
if (!url) {
return null;
}
const scope = proxyConf.scope || 'all';
if (scope === 'all') {
return { url, scope: 'all' };
}
const cleanModel = (modelName || '').toLowerCase().trim();
const models = Array.isArray(proxyConf.models) ? proxyConf.models : [];
if (scope === 'restricted') {
const isRestricted = OVERSEAS_RESTRICTED_MODELS.has(cleanModel) ||
cleanModel.includes('luna') ||
models.some(m => (m || '').toLowerCase().trim() === cleanModel);
if (isRestricted) {
return { url, scope: 'restricted' };
}
return null;
}
if (scope === 'custom') {
const isCustom = models.some(m => (m || '').toLowerCase().trim() === cleanModel);
if (isCustom) {
return { url, scope: 'custom' };
}
return null;
}
return null;
}
}
// 2. Fallback to standard environment variables when no explicit config.proxy
const envProxy = process.env.HTTPS_PROXY || process.env.https_proxy ||
process.env.HTTP_PROXY || process.env.http_proxy ||
process.env.ALL_PROXY || process.env.all_proxy;
if (envProxy && envProxy.trim()) {
return { url: envProxy.trim(), scope: 'env' };
}
return null;
}
/**
* Resolves effective compression options with target platform detection from client headers.
* Ensures Linux NAS services adapt PowerShell optimization and denoising for Windows clients.
*/
function getEffectiveCompressionOptions(baseCompressionConfig, clientReq = null) {
if (!baseCompressionConfig) return baseCompressionConfig;
const comp = { ...baseCompressionConfig };
try {
const psOpt = require('./powershell-optimizer');
const platInfo = psOpt.detectPlatform(comp, clientReq);
if (platInfo && platInfo.platform) {
comp.targetPlatform = platInfo.platform;
}
} catch (_) {}
return comp;
}
// Runtime account state tracking & Circuit Breaker state machine
const CIRCUIT_STATE = {
CLOSED: 'CLOSED', // 正常:放行所有常规请求
HALF_OPEN: 'HALF_OPEN', // 半开:单飞探测中 (Single-Flight Probe)
OPEN: 'OPEN' // 熔断:完全阻断流量,执行退避冷却
};
const DEFAULT_CIRCUIT_CONFIG = {
enabled: true,
failureThreshold: 3,
baseCooldownMs: 5000,
maxCooldownMs: 120000,
halfOpenMaxProbes: 1
};
const accountStats = new Map();
const GUEST_STATE_FILE = path.join(__dirname, 'guest-runtime-state.json');
function getAccountKeyHash(apiKey) {
const clean = typeof apiKey === 'string' ? apiKey.trim() : '';
if (!clean) return '';
return crypto.createHash('sha256').update(clean).digest('hex').slice(0, 12);
}
function loadGuestRuntimeState() {
if (process.env.OPENCODE_TEST_MODE === '1') return { endedAccounts: {} };
try {
if (!fs.existsSync(GUEST_STATE_FILE)) return { endedAccounts: {} };
const parsed = JSON.parse(fs.readFileSync(GUEST_STATE_FILE, 'utf8'));
if (parsed && typeof parsed === 'object' && parsed.endedAccounts && typeof parsed.endedAccounts === 'object') {
return parsed;
}
} catch (_) {}
return { endedAccounts: {} };
}
function saveGuestRuntimeState(stateObj) {
if (process.env.OPENCODE_TEST_MODE === '1') return;
try {
writeFileSyncAtomic(GUEST_STATE_FILE, JSON.stringify(stateObj || { endedAccounts: {} }, null, 2), 'utf8');
} catch (_) {}
}
function persistAccountEndedFlag(accountId, isEnded) {
if (!accountId || accountId === '__guest_protocol__') return;
const state = loadGuestRuntimeState();
const acc = Array.isArray(config.accounts) ? config.accounts.find(a => a && a.id === accountId) : null;
if (isEnded) {
state.endedAccounts[accountId] = {
keyHash: acc ? getAccountKeyHash(acc.apiKey) : '',
endedAt: Date.now()
};
} else {
delete state.endedAccounts[accountId];
}
saveGuestRuntimeState(state);
}
function syncAccountStats() {
const persistedGuestState = loadGuestRuntimeState();
for (const acc of config.accounts) {
const keyHash = getAccountKeyHash(acc.apiKey);
const persisted = persistedGuestState.endedAccounts && persistedGuestState.endedAccounts[acc.id];
const isPersistedEnded = Boolean(persisted && persisted.keyHash && persisted.keyHash === keyHash);
if (!accountStats.has(acc.id)) {
accountStats.set(acc.id, {
id: acc.id,
name: acc.name,
activeRequests: 0,
totalRequests: 0,
rateLimitCount: 0,
failoverCount: 0,
cooldownUntil: 0,
lastUsedAt: null,
lastError: isPersistedEnded ? '官方订阅失效: 支付方式需重新授权' : null,
lastStatus: isPersistedEnded ? 403 : null,
isSubscriptionEnded: isPersistedEnded,
isQuotaExhausted: isPersistedEnded,
// Circuit Breaker State Machine
circuitState: CIRCUIT_STATE.CLOSED,
consecutiveFailures: 0,
consecutiveSuccesses: 0,
halfOpenInFlight: false,
halfOpenProbeStartTime: 0,
openCount: 0,
// Latency & TTFT Sliding Window
lastTtftMs: null,
avgTtftMs: null,
ttftSamples: []
});
} else {
const stat = accountStats.get(acc.id);
stat.name = acc.name;
if (persisted && persisted.keyHash && persisted.keyHash !== keyHash) {
// Key changed by user: immediately clear stale subscription-ended state
stat.isSubscriptionEnded = false;
stat.isQuotaExhausted = false;
if (stat.lastStatus === 403) stat.lastStatus = null;
persistAccountEndedFlag(acc.id, false);
}
}
}
// Remove deleted accounts from stats
const currentIds = new Set(config.accounts.map(a => a.id));
for (const id of accountStats.keys()) {
if (id !== '__guest_protocol__' && !currentIds.has(id)) {
accountStats.delete(id);
}
}
}
syncAccountStats();
function getCircuitState(accountId, now = Date.now()) {
const stat = accountStats.get(accountId);
if (!stat) return CIRCUIT_STATE.CLOSED;
if (!stat.circuitState) stat.circuitState = CIRCUIT_STATE.CLOSED;
if (stat.circuitState === CIRCUIT_STATE.OPEN) {
if (now >= (stat.cooldownUntil || 0)) {
stat.circuitState = CIRCUIT_STATE.HALF_OPEN;
stat.halfOpenInFlight = false;
console.log(`[Circuit Breaker] Account "${stat.name}" cooldown expired. Transitioned to HALF_OPEN (Awaiting Single-Flight Probe).`);
}
} else if (stat.circuitState === CIRCUIT_STATE.HALF_OPEN) {
// Deadlock defense: if probe hung for > 45s without completion or error, release probe lock
if (stat.halfOpenInFlight && now - (stat.halfOpenProbeStartTime || 0) > 45000) {
console.warn(`[Circuit Breaker Deadlock Defense] Account "${stat.name}" probe hung for >45s. Releasing probe lock.`);
stat.halfOpenInFlight = false;
}
}
return stat.circuitState;
}
function calculateJitteredBackoff(baseMs, failureCount, maxMs = 120000) {
const exponent = Math.max(0, Math.min(failureCount, 8));
const rawBackoff = Math.min(maxMs, baseMs * Math.pow(2, exponent));
// Full jitter: 70% ~ 130%
const jitterFactor = 0.7 + Math.random() * 0.6;
return Math.round(rawBackoff * jitterFactor);
}
function recordAccountSuccess(accountId, ttftMs = null) {
const stat = accountStats.get(accountId);
if (!stat) return;
if (typeof ttftMs === 'number' && ttftMs >= 0) {
stat.lastTtftMs = ttftMs;
if (!Array.isArray(stat.ttftSamples)) stat.ttftSamples = [];
stat.ttftSamples.push(ttftMs);
if (stat.ttftSamples.length > 10) stat.ttftSamples.shift();
stat.avgTtftMs = Math.round(stat.ttftSamples.reduce((a, b) => a + b, 0) / stat.ttftSamples.length);
}
const wasEnded = Boolean(stat.isSubscriptionEnded);
stat.consecutiveFailures = 0;
stat.consecutiveSuccesses = (stat.consecutiveSuccesses || 0) + 1;
stat.isSubscriptionEnded = false;
stat.isQuotaExhausted = false;
stat.lastStatus = 200;
stat.lastError = null;
if (wasEnded) {
persistAccountEndedFlag(accountId, false);
_guestSyncedCycleSignature = null;
try {
const boundClients = getBoundClientsForAutoSync();
if (boundClients.length > 0) {
const clientAdapter = require("./client-adapter-manager");
clientAdapter.syncAllClients({
policy: config.modelSourcePolicy || "hybrid",
routerPort: config.port,
clients: boundClients,
preserveChoice: true
});
}
} catch (_) {}
}
if (stat.circuitState === CIRCUIT_STATE.HALF_OPEN || stat.circuitState === CIRCUIT_STATE.OPEN || (stat.cooldownUntil && stat.cooldownUntil > 0)) {
stat.circuitState = CIRCUIT_STATE.CLOSED;
stat.halfOpenInFlight = false;
stat.cooldownUntil = 0;
stat.lastError = null;
console.log(`[Circuit Breaker] Account "${stat.name}" probe SUCCEEDED. Circuit CLOSED (Fully Recovered).`);
} else if (stat.circuitState === CIRCUIT_STATE.CLOSED) {
stat.halfOpenInFlight = false;
}
}
function recordAccountFailure(accountId, reason, statusCode = null, isRateLimit = false, explicitCooldownMs = null) {
const stat = accountStats.get(accountId);
if (!stat) return;
const errDesc = `${statusCode ? 'HTTP ' + statusCode + ': ' : ''}${reason || 'Unknown error'}`;
stat.lastError = errDesc;
if (statusCode) stat.lastStatus = statusCode;
stat.consecutiveSuccesses = 0;
const circuitConf = { ...DEFAULT_CIRCUIT_CONFIG, ...(config.circuitBreaker || {}) };
if (stat.circuitState === CIRCUIT_STATE.HALF_OPEN) {
// Single-flight probe failed! Escalate cooldown and reopen circuit
stat.halfOpenInFlight = false;
stat.consecutiveFailures = (stat.consecutiveFailures || 0) + 1;
stat.circuitState = CIRCUIT_STATE.OPEN;
stat.openCount = (stat.openCount || 0) + 1;
const jitteredCooldown = calculateJitteredBackoff(circuitConf.baseCooldownMs, stat.consecutiveFailures, circuitConf.maxCooldownMs);
const explicitDur = Number(explicitCooldownMs);
const cooldown = (Number.isFinite(explicitDur) && explicitDur > 0) ? Math.max(jitteredCooldown, explicitDur) : jitteredCooldown;
stat.cooldownUntil = Math.max(stat.cooldownUntil || 0, Date.now() + cooldown);
console.warn(`[Circuit Breaker] Account "${stat.name}" probe FAILED (${errDesc}). Circuit re-opened until ${new Date(stat.cooldownUntil).toLocaleTimeString()} (+${Math.round(cooldown / 1000)}s)`);
return;
}
if (isRateLimit) {
stat.rateLimitCount = (stat.rateLimitCount || 0) + 1;
stat.consecutiveFailures = (stat.consecutiveFailures || 0) + 1;
stat.circuitState = CIRCUIT_STATE.OPEN;
stat.openCount = (stat.openCount || 0) + 1;
let dur = Number(explicitCooldownMs);
if (isNaN(dur) || dur <= 0 || !isFinite(dur)) {
dur = config.defaultCooldownMs || 60000;
}
const jitteredDur = Math.round(dur * (0.95 + Math.random() * 0.1));
const targetCooldown = Date.now() + jitteredDur;
stat.cooldownUntil = Math.max(stat.cooldownUntil || 0, targetCooldown);
console.warn(`[Circuit Breaker RateLimit] Account "${stat.name}" tripped OPEN until ${new Date(stat.cooldownUntil).toLocaleTimeString()} (${errDesc})`);
return;
}
// Standard 5xx or TTFT Timeout or Network failure
stat.consecutiveFailures = (stat.consecutiveFailures || 0) + 1;
const threshold = circuitConf.failureThreshold || 3;
if (stat.consecutiveFailures >= threshold) {
stat.circuitState = CIRCUIT_STATE.OPEN;
stat.openCount = (stat.openCount || 0) + 1;
const cooldown = calculateJitteredBackoff(circuitConf.baseCooldownMs, stat.consecutiveFailures - threshold, circuitConf.maxCooldownMs);
stat.cooldownUntil = Date.now() + cooldown;
console.warn(`[Circuit Breaker Tripped] Account "${stat.name}" reached ${stat.consecutiveFailures} consecutive failures. Circuit OPEN until ${new Date(stat.cooldownUntil).toLocaleTimeString()} (${errDesc})`);
}
}
// Session affinity map: sessionId -> accountId
const sessionMap = new Map();
const sessionLastSeen = new Map();
// Pre-emptive fallback cache: `${sessionId}:${model}` -> fallbackModel (for heterogeneous nodes)
const sessionModelFallbackCache = new Map();
// Secondary reverse index: sessionId -> Set of `${sessionId}:${model}` cacheKeys (O(1) session invalidation)
const sessionFallbackKeyMap = new Map();
const sessionToFallbackKeys = sessionFallbackKeyMap;
// CacheKey to SessionId reverse mapping for delimiter-safe O(1) invalidation
const cacheKeyToSessionMap = new Map();
const MAX_ROUTER_SESSIONS = 5000;
function touchSession(sessionId, now = Date.now()) {
if (!sessionId) return;
sessionLastSeen.delete(sessionId);
sessionLastSeen.set(sessionId, now);
// Bounded LRU eviction to prevent memory leak under session flooding
if (sessionLastSeen.size > MAX_ROUTER_SESSIONS) {
const oldestSession = sessionLastSeen.keys().next().value;
if (oldestSession) {
deleteSessionRecord(oldestSession);
}
}
}
function getSessionModelFallback(sessionId, model) {
if (!sessionId || !model) return null;
const cleanReq = model.replace(/^opencode-go\//, '');
const effectiveSessionId = typeof sessionId === 'string' ? sessionId.replace(/(?:-r\d+)+$/, '') : sessionId;
const cacheKey = `${effectiveSessionId}:${cleanReq}`;
return sessionModelFallbackCache.get(cacheKey) || (sessionId !== effectiveSessionId ? sessionModelFallbackCache.get(`${sessionId}:${cleanReq}`) : null) || null;
}
function deleteSessionRecord(sess) {
sessionMap.delete(sess);
sessionLastSeen.delete(sess);
contextCompactor.clearSessionMemo(sess);
const fbSet = sessionFallbackKeyMap.get(sess);
if (fbSet) {
for (const k of fbSet) {
sessionModelFallbackCache.delete(k);
cacheKeyToSessionMap.delete(k);
}
sessionFallbackKeyMap.delete(sess);
}
}
function setSessionModelFallback(sessionId, model, fallbackModel) {
if (!sessionId || !model || !fallbackModel) return;
const cleanReq = model.replace(/^opencode-go\//, '');
const effectiveSessionId = typeof sessionId === 'string' ? sessionId.replace(/(?:-r\d+)+$/, '') : sessionId;
const cacheKey = `${effectiveSessionId}:${cleanReq}`;
if (!sessionModelFallbackCache.has(cacheKey) && sessionModelFallbackCache.size >= 5000) {
let pruneCount = Math.floor(sessionModelFallbackCache.size * 0.2) || 1;
for (const key of sessionModelFallbackCache.keys()) {
sessionModelFallbackCache.delete(key);
const sId = cacheKeyToSessionMap.get(key);
cacheKeyToSessionMap.delete(key);
if (sId) {
const fbSet = sessionFallbackKeyMap.get(sId);
if (fbSet) {
fbSet.delete(key);
if (fbSet.size === 0) sessionFallbackKeyMap.delete(sId);
}
}
if (--pruneCount <= 0) break;
}
}
// Refresh insertion order if key already exists
sessionModelFallbackCache.delete(cacheKey);
sessionModelFallbackCache.set(cacheKey, fallbackModel);
cacheKeyToSessionMap.set(cacheKey, effectiveSessionId);
let fbSet = sessionFallbackKeyMap.get(effectiveSessionId);
if (!fbSet) {
fbSet = new Set();
sessionFallbackKeyMap.set(effectiveSessionId, fbSet);
}
fbSet.add(cacheKey);
// Also store exact sessionId if different
if (sessionId && sessionId !== effectiveSessionId) {
const rawCacheKey = `${sessionId}:${cleanReq}`;
sessionModelFallbackCache.set(rawCacheKey, fallbackModel);
cacheKeyToSessionMap.set(rawCacheKey, sessionId);
let rawFbSet = sessionFallbackKeyMap.get(sessionId);
if (!rawFbSet) {
rawFbSet = new Set();
sessionFallbackKeyMap.set(sessionId, rawFbSet);
}
rawFbSet.add(rawCacheKey);
}
}
// Clean up stale sessions periodically (every 10 minutes)
setInterval(() => {
const now = Date.now();
for (const [sess, time] of sessionLastSeen.entries()) {
if (now - time > 3600000) { // 1 hour inactivity
deleteSessionRecord(sess);
} else {
// Insertion-order LRU property: all subsequent entries are even newer
break;
}
}
// Defensive alignment: clean any stray orphaned sessions in sessionMap
if (sessionMap.size > sessionLastSeen.size) {
for (const sess of sessionMap.keys()) {
if (!sessionLastSeen.has(sess)) {
sessionMap.delete(sess);
contextCompactor.clearSessionMemo(sess);
}
}
}
}, 600000).unref();
let rrIndex = 0;
function isAccountAvailable(acc, now = Date.now()) {
if (!acc.enabled || !acc.apiKey || acc.apiKey.trim() === '') return false;
const stat = accountStats.get(acc.id);
if (!stat) return false;
if (stat.isSubscriptionEnded || stat.isQuotaExhausted) return false;
const state = getCircuitState(acc.id, now);
if (state === CIRCUIT_STATE.CLOSED) return true;
if (state === CIRCUIT_STATE.OPEN) return false;
if (state === CIRCUIT_STATE.HALF_OPEN) {
// Single-Flight Probe Guard: if a probe is already running, block concurrent requests
if (stat.halfOpenInFlight) return false;
return true;
}
return false;
}
let _zenGuestCounter = 0;
const _zenGuestSessionMap = new Map();
const _ZEN_BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const ZEN_BORINGSSL_CIPHERS = [
"TLS_AES_128_GCM_SHA256",
"TLS_AES_256_GCM_SHA384",
"TLS_CHACHA20_POLY1305_SHA256",
"ECDHE-ECDSA-AES128-GCM-SHA256",
"ECDHE-RSA-AES128-GCM-SHA256",
"ECDHE-ECDSA-AES256-GCM-SHA384",
"ECDHE-RSA-AES256-GCM-SHA384",
"ECDHE-ECDSA-CHACHA20-POLY1305",
"ECDHE-RSA-CHACHA20-POLY1305",
"ECDHE-RSA-AES128-SHA",
"ECDHE-RSA-AES256-SHA",
"AES128-GCM-SHA256",
"AES256-GCM-SHA384",
"AES128-SHA",
"AES256-SHA"
].join(":");
const ZEN_GUEST_ENV_BLOCK = [
"Here is some useful information about the environment you are running in:",
"<env>",
" Working directory: /workspace",
" Workspace root folder: /workspace",
" Is directory a git repo: yes",
` Platform: ${process.platform === "win32" ? "win32" : (process.platform === "darwin" ? "darwin" : "linux")}`,
"</env>"
].join("\n");
function mintOpencodeZenSessionId() {
_zenGuestCounter = (_zenGuestCounter + 1) & 0x3f; // 0..63 ensures inverted low 12 bits land in [0xfc0, 0xfff]
const raw = BigInt(Date.now()) * 4096n + BigInt(_zenGuestCounter);
const head = (~raw & 0xffffffffffffn).toString(16).padStart(12, "0");
let tail = "";
for (let i = 0; i < 14; i++) {
tail += _ZEN_BASE62[Math.floor(Math.random() * 62)];
}
return `ses_${head}${tail}`;
}
function getOrMintGuestSessionId(rawSessionId) {
if (typeof rawSessionId === "string" && /^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$/.test(rawSessionId)) {
const low12 = parseInt(rawSessionId.slice(13, 16), 16);
if (low12 >= 0xfc0 && low12 <= 0xfff) return rawSessionId;
}
const key = rawSessionId || "default";
if (_zenGuestSessionMap.has(key)) return _zenGuestSessionMap.get(key);