This repository was archived by the owner on Jul 29, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
793 lines (723 loc) · 26.6 KB
/
Copy pathserver.js
File metadata and controls
793 lines (723 loc) · 26.6 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
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const path = require("path");
const crypto = require("crypto");
const connectDB = require("./database/db");
// Connect to database
connectDB();
const app = express();
const PORT = process.env.PORT || 3000;
const GROQ_API_KEY = process.env.GROQ_API_KEY;
const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
const OPENROUTER_API_KEY = process.env.OPENROUTER_API_KEY;
const MISTRAL_API_KEY = process.env.MISTRAL_API_KEY;
const CEREBRAS_API_KEY = process.env.CEREBRAS_API_KEY;
const NIM_API_KEY = process.env.NIM_API_KEY;
if (!GROQ_API_KEY) {
console.error("ERROR: GROQ_API_KEY is not set in .env");
process.exit(1);
}
if (!GEMINI_API_KEY) {
console.error("ERROR: GEMINI_API_KEY is not set in .env");
process.exit(1);
}
if (!OPENROUTER_API_KEY) {
console.error("ERROR: OPENROUTER_API_KEY is not set in .env");
process.exit(1);
}
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, "public")));
// Authentication Routes
app.use("/api/auth", require("./routes/auth"));
// ───── Provider configurations ─────
const PROVIDERS = {
fast: {
name: "Llama Pro",
url: "https://api.groq.com/openai/v1/chat/completions",
model: "llama-3.3-70b-versatile",
getKey: () => GROQ_API_KEY,
},
nerd: {
name: "Qwen Pro",
url: "https://api.groq.com/openai/v1/chat/completions",
model: "qwen/qwen3-32b",
getKey: () => GROQ_API_KEY,
},
ultra: {
name: "GPT Pro",
url: "https://api.groq.com/openai/v1/chat/completions",
model: "openai/gpt-oss-120b",
getKey: () => GROQ_API_KEY,
},
ultra_nim: {
name: "GPT Pro Backup",
url: "https://integrate.api.nvidia.com/v1/chat/completions",
model: "openai/gpt-oss-120b",
getKey: () => NIM_API_KEY,
},
ultra_fallback: {
name: "GPT Pro Emergency",
url: "https://openrouter.ai/api/v1/chat/completions",
model: "openai/gpt-oss-120b",
getKey: () => OPENROUTER_API_KEY,
},
net: {
name: "Gemini Lite",
url: "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
model: "gemini-2.5-flash",
getKey: () => GEMINI_API_KEY,
},
debug: {
name: "Debug Specialist",
url: "https://openrouter.ai/api/v1/chat/completions",
model: "openrouter/elephant-alpha",
getKey: () => OPENROUTER_API_KEY,
},
genius: {
name: "Nemotron Pro",
url: "https://openrouter.ai/api/v1/chat/completions",
model: "nvidia/nemotron-3-super-120b-a12b",
getKey: () => OPENROUTER_API_KEY,
},
expert: {
name: "Qwen Coder Pro",
url: "https://openrouter.ai/api/v1/chat/completions",
model: "qwen/qwen3-coder:free",
getKey: () => OPENROUTER_API_KEY,
},
lightspeed: {
name: "GLM Superlite",
url: "https://openrouter.ai/api/v1/chat/completions",
model: "z-ai/glm-4.5-air:free",
getKey: () => OPENROUTER_API_KEY,
},
mystery: {
name: "Mystery AI",
url: "https://openrouter.ai/api/v1/chat/completions",
model: "openrouter/free",
getKey: () => OPENROUTER_API_KEY,
},
// Layer 1: Ultra-cheap traffic absorbers
tinyllama: {
name: "Llama Superlite",
url: "https://openrouter.ai/api/v1/chat/completions",
model: "tinyllama/tinyllama-1.1b-chat-v1.0",
getKey: () => OPENROUTER_API_KEY,
},
qwen05b: {
name: "Qwen Superlite",
url: "https://openrouter.ai/api/v1/chat/completions",
model: "qwen/qwen-2.5-0.5b-instruct",
getKey: () => OPENROUTER_API_KEY,
},
llama32_1b: {
name: "Llama Lite",
url: "https://openrouter.ai/api/v1/chat/completions",
model: "meta-llama/llama-3.2-1b-instruct",
getKey: () => OPENROUTER_API_KEY,
},
gemma2b: {
name: "Gemma Lite",
url: "https://openrouter.ai/api/v1/chat/completions",
model: "google/gemma-2-2b-it",
getKey: () => OPENROUTER_API_KEY,
},
phi2: {
name: "Phi Lite",
url: "https://openrouter.ai/api/v1/chat/completions",
model: "microsoft/phi-2",
getKey: () => OPENROUTER_API_KEY,
},
// Layer 2: Main workforce
llama31_8b: {
name: "Llama",
url: "https://openrouter.ai/api/v1/chat/completions",
model: "meta-llama/llama-3.1-8b-instruct",
getKey: () => OPENROUTER_API_KEY,
},
mistral7b: {
name: "Mistral",
url: MISTRAL_API_KEY
? "https://api.mistral.ai/v1/chat/completions"
: "https://openrouter.ai/api/v1/chat/completions",
model: MISTRAL_API_KEY ? "mistral-small-latest" : "mistralai/mistral-7b-instruct",
getKey: () => MISTRAL_API_KEY || OPENROUTER_API_KEY,
},
gemma7b: {
name: "Gemma",
url: "https://openrouter.ai/api/v1/chat/completions",
model: "google/gemma-7b-it",
getKey: () => OPENROUTER_API_KEY,
},
qwen7b: {
name: "Qwen",
url: "https://openrouter.ai/api/v1/chat/completions",
model: "qwen/qwen2.5-7b-instruct",
getKey: () => OPENROUTER_API_KEY,
},
deepseek67b: {
name: "DeepSeek",
url: "https://openrouter.ai/api/v1/chat/completions",
model: "deepseek/deepseek-chat",
getKey: () => OPENROUTER_API_KEY,
},
// Layer 3: Heavy / restricted
qwen32b: {
name: "Qwen Pro",
url: "https://api.groq.com/openai/v1/chat/completions",
model: "qwen/qwen3-32b",
getKey: () => GROQ_API_KEY,
},
qwen32b_fallback: {
name: "Qwen Pro Backup",
url: "https://api.cerebras.ai/v1/chat/completions",
model: "qwen-32b",
getKey: () => CEREBRAS_API_KEY,
},
nemotronsuper3: {
name: "Nemotron Super",
url: "https://openrouter.ai/api/v1/chat/completions",
model: "nvidia/nemotron-3-super-120b-a12b",
getKey: () => OPENROUTER_API_KEY,
},
nemotronsuper3_fallback: {
name: "Nemotron Super Backup",
url: "https://integrate.api.nvidia.com/v1/chat/completions",
model: "nvidia/llama-3.1-nemotron-70b-instruct",
getKey: () => NIM_API_KEY,
},
glm51_nim: {
name: "GLM Pro",
url: "https://integrate.api.nvidia.com/v1/chat/completions",
model: "zhipuai/glm-5.1",
getKey: () => NIM_API_KEY,
},
glm47_nim: {
name: "GLM",
url: "https://integrate.api.nvidia.com/v1/chat/completions",
model: "zhipuai/glm-4.7",
getKey: () => NIM_API_KEY,
},
kimi25_nim: {
name: "Kimi Pro",
url: "https://integrate.api.nvidia.com/v1/chat/completions",
model: "moonshotai/kimi-k2.5",
getKey: () => NIM_API_KEY,
},
deepseekv32_nim: {
name: "DeepSeek Pro",
url: "https://integrate.api.nvidia.com/v1/chat/completions",
model: "deepseek/deepseek-v3.2",
getKey: () => NIM_API_KEY,
},
minimaxm25_nim: {
name: "Minimax Pro",
url: "https://integrate.api.nvidia.com/v1/chat/completions",
model: "minimax/minimax-m2.5",
getKey: () => NIM_API_KEY,
},
};
const MAX_CONCURRENT_REQUESTS = 25;
const MAX_QUEUE_LENGTH = 150;
const CACHE_TTL_MS = 120000;
const RATE_WINDOW_MS = 60000;
const MODE_META = {
auto: { category: "fast", modelClass: "small", family: "auto_family", baseWeight: 1.5 },
fast: { category: "fast", modelClass: "small", family: "llama_family", baseWeight: 1.2 },
nerd: { category: "powerful", modelClass: "heavy", family: "qwen_reasoning_family", baseWeight: 0.6 },
ultra: { category: "powerful", modelClass: "heavy", family: "gpt_family", baseWeight: 0.5 },
net: { category: "balanced", modelClass: "medium", family: "gemini_family", baseWeight: 1.0 },
debug: { category: "balanced", modelClass: "medium", family: "debug_family", baseWeight: 0.9 },
genius: { category: "powerful", modelClass: "heavy", family: "nemotron_family", baseWeight: 0.5 },
expert: { category: "balanced", modelClass: "medium", family: "coder_family", baseWeight: 1.0 },
lightspeed: { category: "fast", modelClass: "small", family: "glm_family", baseWeight: 1.3 },
mystery: { category: "balanced", modelClass: "medium", family: "openrouter_family", baseWeight: 0.8 },
tinyllama: { category: "fast", modelClass: "small", family: "tinyllama_family", baseWeight: 1.25 },
qwen05b: { category: "fast", modelClass: "small", family: "qwen_small_family", baseWeight: 1.2 },
llama32_1b: { category: "fast", modelClass: "small", family: "llama_small_family", baseWeight: 1.15 },
gemma2b: { category: "fast", modelClass: "small", family: "gemma_small_family", baseWeight: 1.1 },
phi2: { category: "fast", modelClass: "small", family: "phi_family", baseWeight: 1.05 },
llama31_8b: { category: "balanced", modelClass: "medium", family: "llama8b_family", baseWeight: 1.05 },
mistral7b: { category: "balanced", modelClass: "medium", family: "mistral_family", baseWeight: 1.1 },
gemma7b: { category: "balanced", modelClass: "medium", family: "gemma_family", baseWeight: 1.0 },
qwen7b: { category: "balanced", modelClass: "medium", family: "qwen_family", baseWeight: 1.0 },
deepseek67b: { category: "balanced", modelClass: "medium", family: "deepseek_family", baseWeight: 0.95 },
qwen32b: { category: "powerful", modelClass: "heavy", family: "qwen_heavy_family", baseWeight: 0.55 },
nemotronsuper3: { category: "powerful", modelClass: "heavy", family: "nemotron_family", baseWeight: 0.5 },
ultra_nim: { category: "powerful", modelClass: "heavy", family: "gpt_family", baseWeight: 0.48 },
ultra_fallback: { category: "powerful", modelClass: "heavy", family: "gpt_family", baseWeight: 0.45 },
qwen32b_fallback: { category: "powerful", modelClass: "heavy", family: "qwen_heavy_family", baseWeight: 0.5 },
nemotronsuper3_fallback: { category: "powerful", modelClass: "heavy", family: "nemotron_family", baseWeight: 0.45 },
glm51_nim: { category: "powerful", modelClass: "heavy", family: "glm_family", baseWeight: 0.52 },
glm47_nim: { category: "powerful", modelClass: "heavy", family: "glm_family", baseWeight: 0.5 },
kimi25_nim: { category: "powerful", modelClass: "heavy", family: "kimi_family", baseWeight: 0.5 },
deepseekv32_nim: { category: "powerful", modelClass: "heavy", family: "deepseek_family", baseWeight: 0.5 },
minimaxm25_nim: { category: "powerful", modelClass: "heavy", family: "minimax_family", baseWeight: 0.48 },
};
const AUTO_CANDIDATES = {
simple: [
"tinyllama", "qwen05b", "llama32_1b", "gemma2b", "phi2",
"lightspeed", "fast", "net",
],
normal: [
"mistral7b", "llama31_8b", "gemma7b", "qwen7b", "deepseek67b",
"net", "expert", "fast", "debug",
],
complex: [
"qwen32b", "ultra", "genius", "nemotronsuper3", "glm51_nim", "glm47_nim",
"kimi25_nim", "deepseekv32_nim", "minimaxm25_nim", "nerd", "expert", "mistral7b", "net",
],
};
const FAILOVER_CHAINS = {
fast: ["lightspeed", "net", "expert"],
lightspeed: ["fast", "net", "expert"],
net: ["expert", "fast", "lightspeed"],
expert: ["net", "fast", "debug"],
debug: ["expert", "net", "fast"],
nerd: ["ultra", "genius", "expert", "net"],
ultra: ["ultra_nim", "ultra_fallback", "nerd", "genius", "expert", "net"],
genius: ["nerd", "ultra", "expert", "net"],
mystery: ["expert", "net", "fast"],
tinyllama: ["qwen05b", "llama32_1b", "fast", "lightspeed"],
qwen05b: ["tinyllama", "llama32_1b", "fast", "lightspeed"],
llama32_1b: ["tinyllama", "qwen05b", "fast", "lightspeed"],
gemma2b: ["tinyllama", "qwen05b", "fast", "lightspeed"],
phi2: ["tinyllama", "qwen05b", "fast", "lightspeed"],
llama31_8b: ["mistral7b", "qwen7b", "net", "expert"],
mistral7b: ["llama31_8b", "qwen7b", "net", "expert"],
gemma7b: ["mistral7b", "llama31_8b", "net", "expert"],
qwen7b: ["mistral7b", "llama31_8b", "expert", "net"],
deepseek67b: ["mistral7b", "qwen7b", "expert", "net"],
qwen32b: ["qwen32b_fallback", "ultra", "genius", "nerd", "mistral7b", "net"],
nemotronsuper3: ["nemotronsuper3_fallback", "genius", "ultra", "nerd", "mistral7b", "net"],
glm51_nim: ["glm47_nim", "nemotronsuper3", "genius", "ultra", "nerd", "mistral7b", "net"],
glm47_nim: ["glm51_nim", "nemotronsuper3", "genius", "ultra", "nerd", "mistral7b", "net"],
kimi25_nim: ["deepseekv32_nim", "minimaxm25_nim", "genius", "ultra", "nerd", "mistral7b", "net"],
deepseekv32_nim: ["kimi25_nim", "minimaxm25_nim", "genius", "ultra", "nerd", "mistral7b", "net"],
minimaxm25_nim: ["kimi25_nim", "deepseekv32_nim", "genius", "ultra", "nerd", "mistral7b", "net"],
ultra_nim: ["ultra_fallback", "nerd", "genius", "expert", "net"],
ultra_fallback: ["nerd", "genius", "expert", "net"],
qwen32b_fallback: ["ultra", "genius", "nerd", "mistral7b", "net"],
nemotronsuper3_fallback: ["genius", "ultra", "nerd", "mistral7b", "net"],
};
const PROVIDER_PRIORITY = {
groq: 1,
mistral: 2,
cerebras: 3,
nim: 4,
openrouter: 5,
google: 6,
};
const INTERNAL_ONLY_MODES = new Set(["ultra_nim", "ultra_fallback", "qwen32b_fallback", "nemotronsuper3_fallback"]);
let activeRequests = 0;
const requestQueue = [];
const responseCache = new Map();
const userRateState = new Map();
const providerState = {};
for (const mode of Object.keys(PROVIDERS)) {
providerState[mode] = {
success: 0,
failure: 0,
consecutiveFailures: 0,
cooldownUntil: 0,
circuitUntil: 0,
avgLatencyMs: 2000,
};
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function getCurrentLoad() {
return (activeRequests + requestQueue.length) / MAX_CONCURRENT_REQUESTS;
}
function isModeAvailable(mode) {
const provider = PROVIDERS[mode];
if (!provider) return false;
try {
return Boolean(provider.getKey && provider.getKey());
} catch (err) {
return false;
}
}
function resolveProviderName(mode) {
const provider = PROVIDERS[mode];
if (!provider) return "openrouter";
const url = provider.url || "";
const model = provider.model || "";
if (url.includes("groq.com")) return "groq";
if (url.includes("mistral.ai")) return "mistral";
if (url.includes("cerebras.ai")) return "cerebras";
if (url.includes("integrate.api.nvidia.com")) return "nim";
if (url.includes("generativelanguage.googleapis.com")) return "google";
return "openrouter";
}
function estimateTokenCount(messages) {
const text = messages.map((m) => m.content || "").join(" ");
return Math.ceil(text.length / 4);
}
function getRequesterId(req) {
const auth = req.headers.authorization || "";
const ip = req.ip || req.headers["x-forwarded-for"] || "anon";
return `${ip}|${auth.slice(0, 32)}`;
}
function enforceUserRateLimit(req, messages) {
const id = getRequesterId(req);
const now = Date.now();
const tokens = estimateTokenCount(messages);
const load = getCurrentLoad();
const limits = load >= 0.8
? { rpm: 12, tpm: 6000, concurrent: 1 }
: load >= 0.5
? { rpm: 20, tpm: 10000, concurrent: 2 }
: { rpm: 30, tpm: 15000, concurrent: 3 };
let state = userRateState.get(id);
if (!state || now - state.windowStart >= RATE_WINDOW_MS) {
state = { windowStart: now, requests: 0, tokens: 0, concurrent: 0 };
}
if (state.requests >= limits.rpm) {
throw Object.assign(new Error("Rate limit exceeded: too many requests"), { status: 429 });
}
if (state.tokens + tokens > limits.tpm) {
throw Object.assign(new Error("Rate limit exceeded: token budget reached"), { status: 429 });
}
if (state.concurrent >= limits.concurrent) {
throw Object.assign(new Error("Rate limit exceeded: too many concurrent requests"), { status: 429 });
}
state.requests += 1;
state.tokens += tokens;
state.concurrent += 1;
userRateState.set(id, state);
return () => {
const next = userRateState.get(id);
if (!next) return;
next.concurrent = Math.max(0, next.concurrent - 1);
userRateState.set(id, next);
};
}
function classifyComplexity(messages) {
const userText = (messages || [])
.filter((m) => m.role === "user")
.map((m) => m.content || "")
.join(" ");
const len = userText.length;
const hasCode = /```|function|class|stack trace|error|refactor|architecture|optimi[sz]e/i.test(userText);
if (len < 140 && !hasCode) return "simple";
if (len > 600 || /distributed|scal|multi-provider|concurrency|queue|fallback/i.test(userText)) return "complex";
return hasCode ? "normal" : "simple";
}
function getDynamicCooldownMs(mode, load, now = Date.now()) {
const modelClass = MODE_META[mode]?.modelClass || "medium";
let min = 0;
let max = 0;
if (load < 0.5) {
if (modelClass === "small") [min, max] = [0, 0];
if (modelClass === "medium") [min, max] = [0, 0];
if (modelClass === "heavy") [min, max] = [0, 0];
} else if (load < 0.8) {
if (modelClass === "small") [min, max] = [1000, 2000];
if (modelClass === "medium") [min, max] = [3000, 5000];
if (modelClass === "heavy") [min, max] = [10000, 20000];
} else {
if (modelClass === "small") [min, max] = [2000, 3000];
if (modelClass === "medium") [min, max] = [5000, 8000];
if (modelClass === "heavy") [min, max] = [30000, 60000];
}
const pState = providerState[mode];
const quotaStress = Math.min(1, (activeRequests + requestQueue.length) / (MAX_CONCURRENT_REQUESTS * 1.3));
const errorStress = Math.min(1, pState.consecutiveFailures / 5);
const mid = (min + max) / 2;
const adjusted = Math.round(mid * (1 + 0.8 * quotaStress + 1.2 * errorStress));
const remaining = Math.max(0, (pState.cooldownUntil || 0) - now);
return Math.max(adjusted, remaining);
}
function getModePressure(mode) {
const pState = providerState[mode];
const total = pState.success + pState.failure;
const errorRate = total ? pState.failure / total : 0;
const load = getCurrentLoad();
const cooldownPenalty = getDynamicCooldownMs(mode, load) / 60000;
const healthScore = 1 - Math.min(1, errorRate * 1.8);
const latencyPenalty = Math.min(1, pState.avgLatencyMs / 8000);
const baseWeight = MODE_META[mode]?.baseWeight || 1;
const providerName = resolveProviderName(mode);
const rank = PROVIDER_PRIORITY[providerName] || 99;
const providerPenalty = rank * 0.05;
return baseWeight + healthScore - latencyPenalty - cooldownPenalty - providerPenalty;
}
function pickBestMode(mode, messages) {
if (mode && mode !== "auto" && PROVIDERS[mode]) {
if (INTERNAL_ONLY_MODES.has(mode)) return "auto";
return isModeAvailable(mode) ? mode : "auto";
}
const complexity = classifyComplexity(messages);
const load = getCurrentLoad();
let candidates = [...(AUTO_CANDIDATES[complexity] || AUTO_CANDIDATES.normal)];
// Heavy model policy:
// - Auto allowed only under 50% load
// - Manual only at >=50%
// - Never auto-selected at >=80%
if (load >= 0.5) {
candidates = candidates.filter((m) => MODE_META[m]?.modelClass !== "heavy");
}
candidates = candidates.filter((m) => isModeAvailable(m));
candidates = candidates.filter((m) => !INTERNAL_ONLY_MODES.has(m));
candidates = candidates.filter((m) => Date.now() >= (providerState[m]?.circuitUntil || 0));
if (!candidates.length) return "fast";
candidates.sort((a, b) => getModePressure(b) - getModePressure(a));
return candidates[0];
}
function timeoutForMode(mode) {
const modelClass = MODE_META[mode]?.modelClass || "medium";
const load = getCurrentLoad();
if (modelClass === "small") return load >= 0.8 ? 12000 : 18000;
if (modelClass === "heavy") return load >= 0.8 ? 30000 : 50000;
return load >= 0.8 ? 18000 : 35000;
}
function buildCacheKey(messages, mode) {
const normalized = JSON.stringify(
(messages || []).map((m) => ({
role: m.role,
content: (m.content || "").replace(/\s+/g, " ").trim(),
}))
);
return crypto.createHash("sha256").update(`${mode}|${normalized}`).digest("hex");
}
function getFromCache(cacheKey) {
const hit = responseCache.get(cacheKey);
if (!hit) return null;
if (Date.now() > hit.expiresAt) {
responseCache.delete(cacheKey);
return null;
}
return hit.data;
}
function setCache(cacheKey, data) {
responseCache.set(cacheKey, {
data,
expiresAt: Date.now() + CACHE_TTL_MS,
});
if (responseCache.size > 1000) {
const firstKey = responseCache.keys().next().value;
if (firstKey) responseCache.delete(firstKey);
}
}
async function callProvider(mode, messages) {
const provider = PROVIDERS[mode];
const pState = providerState[mode];
const now = Date.now();
if (pState.circuitUntil > now) {
throw Object.assign(new Error(`${provider.name} is temporarily unavailable`), { status: 503 });
}
const cooldownMs = getDynamicCooldownMs(mode, getCurrentLoad(), now);
if (cooldownMs > 0 && pState.cooldownUntil > now) {
await sleep(Math.min(cooldownMs, 3000));
}
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutForMode(mode));
const start = Date.now();
try {
const apiRes = await fetch(provider.url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${provider.getKey()}`,
"HTTP-Referer": "http://localhost:3000",
"X-Title": "TactCode AI",
},
body: JSON.stringify({ model: provider.model, messages }),
signal: controller.signal,
});
if (!apiRes.ok) {
const errBody = await apiRes.text();
const err = new Error(`${provider.name} API error (${apiRes.status}) ${errBody}`);
err.status = apiRes.status;
throw err;
}
const data = await apiRes.json();
if (data.choices?.[0]?.message?.content) {
data.choices[0].message.content = data.choices[0].message.content
.replace(/<think>[\s\S]*?<\/think>\s*/g, "")
.trim();
}
const latency = Date.now() - start;
pState.success += 1;
pState.consecutiveFailures = 0;
pState.avgLatencyMs = Math.round((pState.avgLatencyMs * 0.8) + (latency * 0.2));
pState.cooldownUntil = Date.now() + getDynamicCooldownMs(mode, getCurrentLoad());
return { data, modeUsed: mode };
} catch (err) {
pState.failure += 1;
pState.consecutiveFailures += 1;
pState.cooldownUntil = Date.now() + getDynamicCooldownMs(mode, getCurrentLoad());
if (pState.consecutiveFailures >= 3) {
pState.circuitUntil = Date.now() + 15000;
}
throw err;
} finally {
clearTimeout(timeout);
}
}
function isRetryableError(err) {
return err?.name === "AbortError" || [429, 500, 502, 503, 504].includes(err?.status);
}
async function executeWithFailover(initialMode, messages) {
const plan = [initialMode, ...(FAILOVER_CHAINS[initialMode] || [])];
const tried = new Set();
const maxAttempts = 3;
let attempts = 0;
let lastError = null;
for (const mode of plan) {
if (attempts >= maxAttempts) break;
if (!PROVIDERS[mode] || tried.has(mode) || !isModeAvailable(mode)) continue;
tried.add(mode);
attempts += 1;
try {
return await callProvider(mode, messages);
} catch (err) {
lastError = err;
if (!isRetryableError(err)) break;
await sleep(200 + Math.floor(Math.random() * 400));
}
}
throw lastError || new Error("All failover paths exhausted");
}
function enqueueRequest(taskFn) {
return new Promise((resolve, reject) => {
if (requestQueue.length >= MAX_QUEUE_LENGTH) {
reject(Object.assign(new Error("Server busy, queue is full"), { status: 503 }));
return;
}
requestQueue.push({ taskFn, resolve, reject });
processQueue();
});
}
function processQueue() {
while (activeRequests < MAX_CONCURRENT_REQUESTS && requestQueue.length > 0) {
const task = requestQueue.shift();
activeRequests += 1;
Promise.resolve()
.then(task.taskFn)
.then(task.resolve)
.catch(task.reject)
.finally(() => {
activeRequests = Math.max(0, activeRequests - 1);
processQueue();
});
}
}
setInterval(() => {
const now = Date.now();
for (const [key, value] of responseCache.entries()) {
if (value.expiresAt <= now) responseCache.delete(key);
}
}, 15000);
// ───── Chat API endpoint ─────
app.post("/api/chat", async (req, res) => {
const { messages, mode } = req.body;
if (!messages || !Array.isArray(messages)) {
return res.status(400).json({ error: "messages array is required" });
}
let releaseUserSlot = null;
try {
releaseUserSlot = enforceUserRateLimit(req, messages);
const selectedMode = pickBestMode(mode, messages);
const cacheKey = buildCacheKey(messages, selectedMode);
const cached = getFromCache(cacheKey);
if (cached) {
return res.json({
...cached,
meta: {
...(cached.meta || {}),
cache: "hit",
queueDepth: requestQueue.length,
activeRequests,
},
});
}
const task = async () => {
const result = await executeWithFailover(selectedMode, messages);
const payload = {
...result.data,
meta: {
modeRequested: mode || "auto",
modeResolved: selectedMode,
modeUsed: result.modeUsed,
category: MODE_META[result.modeUsed]?.category || "balanced",
queueDepth: requestQueue.length,
activeRequests,
cache: "miss",
},
};
setCache(cacheKey, payload);
return payload;
};
const data = await enqueueRequest(task);
return res.json(data);
} catch (err) {
console.error("Server error:", err.message);
return res.status(err.status || 500).json({ error: err.message || "Internal server error", details: err.message });
} finally {
if (releaseUserSlot) releaseUserSlot();
}
});
app.get("/api/modes", (req, res) => {
const load = getCurrentLoad();
const now = Date.now();
const modes = Object.entries(PROVIDERS)
.filter(([mode]) => !INTERNAL_ONLY_MODES.has(mode))
.map(([mode, provider]) => {
const cooldownMs = getDynamicCooldownMs(mode, load, now);
const pState = providerState[mode];
const total = pState.success + pState.failure;
const errorRate = total ? pState.failure / total : 0;
return {
mode,
label: provider.name,
category: MODE_META[mode]?.category || "balanced",
modelClass: MODE_META[mode]?.modelClass || "medium",
cooldownSeconds: Math.ceil(cooldownMs / 1000),
health: {
errorRate: Number(errorRate.toFixed(3)),
avgLatencyMs: pState.avgLatencyMs,
circuitOpen: pState.circuitUntil > now,
},
};
});
res.json({
load: Number(load.toFixed(3)),
activeRequests,
queueLength: requestQueue.length,
capacity: MAX_CONCURRENT_REQUESTS,
modes,
});
});
app.get("/api/models", (req, res) => {
const models = Object.entries(PROVIDERS)
.filter(([mode]) => !INTERNAL_ONLY_MODES.has(mode))
.map(([mode, provider]) => ({
mode,
label: provider.name,
providerUrl: provider.url,
category: MODE_META[mode]?.category || "balanced",
modelClass: MODE_META[mode]?.modelClass || "medium",
available: isModeAvailable(mode),
}));
res.json({
total: models.length,
available: models.filter((m) => m.available).length,
models,
});
});
// Fallback: serve index.html
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
app.listen(PORT, () => {
console.log(`TactCode AI server running at http://localhost:${PORT}`);
console.log("Available modes:");
for (const [key, p] of Object.entries(PROVIDERS)) {
console.log(` ${key.padEnd(6)} → ${p.name}`);
}
});