7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
feat(proxy): outbound SOCKS5/HTTP proxy with per-platform bypass
Slyker991b549335ab
diff --git a/client/src/pages/KeysPage.tsx b/client/src/pages/KeysPage.tsxindex ce5c5a33..0883d69a 100644--- a/client/src/pages/KeysPage.tsx+++ b/client/src/pages/KeysPage.tsx@@ -8,7 +8,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@import { Switch } from '@/components/ui/switch'import { PageHeader } from '@/components/page-header'import type { ApiKey, Platform } from '../../../shared/types'-import { Pencil, ExternalLink } from 'lucide-react'+import { Pencil, ExternalLink, Globe } from 'lucide-react'import { formatSqliteUtcToLocalTime } from '@/lib/utils'// Small "Get API key" external link shown next to a provider (#137).@@ -172,6 +172,102 @@ function UnifiedKeySection() {)}+function ProxySettingsSection() {+ const queryClient = useQueryClient()+ const [proxyUrl, setProxyUrl] = useState('')++ const { data, isError } = useQuery<{ proxyUrl: string; enabled: boolean; bypassPlatforms: string[]; active: boolean }>({+ queryKey: ['proxy-url'],+ queryFn: () => apiFetch('/api/settings/proxy'),+ })++ // Sync from server when the query refetches; keep the user's typed value+ // in between (controlled input).+ useEffect(() => {+ if (data) setProxyUrl(data.proxyUrl)+ }, [data?.proxyUrl])++ const saveProxy = useMutation({+ mutationFn: (body: { proxyUrl?: string; enabled?: boolean; bypassPlatforms?: string[] }) =>+ apiFetch('/api/settings/proxy', { method: 'PUT', body: JSON.stringify(body) }),+ onSuccess: (result: { proxyUrl: string; enabled: boolean; bypassPlatforms: string[]; active: boolean }) => {+ queryClient.invalidateQueries({ queryKey: ['proxy-url'] })+ setProxyUrl(result.proxyUrl)+ },+ })++ const submit = (e: React.FormEvent) => {+ e.preventDefault()+ saveProxy.mutate({ proxyUrl })+ }++ const enabled = data?.enabled ?? true+ const active = data?.active ?? false++ return (+ <section className="rounded-3xl border bg-card p-5">+ <div className="flex items-start justify-between gap-4 mb-3">+ <div>+ <h2 className="text-sm font-medium flex items-center gap-2">+ <Globe className="size-3.5 text-muted-foreground" />+ Outbound proxy+ </h2>+ <p className="text-xs text-muted-foreground mt-0.5">+ Route outbound LLM requests through a proxy. Supports SOCKS5, HTTP, and HTTPS.+ </p>+ </div>+ <div className="flex items-center gap-2">+ <Switch+ checked={enabled}+ onCheckedChange={(checked) => saveProxy.mutate({ enabled: checked })}+ disabled={saveProxy.isPending || !data}+ />+ {active && enabled && (+ <span className="text-[11px] px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 font-medium">+ Active+ </span>+ )}+ </div>+ </div>++ {isError ? (+ <p className="text-xs text-muted-foreground">Could not load proxy settings.</p>+ ) : (+ <form onSubmit={submit} className="flex items-end gap-3">+ <div className="space-y-1.5 flex-1">+ <Label className="text-xs">Proxy URL</Label>+ <Input+ value={proxyUrl}+ onChange={e => setProxyUrl(e.target.value)}+ placeholder="socks5://127.0.0.1:1080"+ className="font-mono text-xs"+ />+ </div>+ <Button type="submit" size="sm" disabled={saveProxy.isPending}>+ {saveProxy.isPending ? 'Saving…' : 'Save'}+ </Button>+ </form>+ )}++ {saveProxy.isError && (+ <p className="text-destructive text-xs mt-2">{(saveProxy.error as Error).message}</p>+ )}++ <div className="mt-3 text-[11px] text-muted-foreground">+ <p>+ Also configurable via the <code className="font-mono">PROXY_URL</code> environment variable+ (takes precedence). Leave blank to disable. Examples:+ </p>+ <ul className="list-disc list-inside mt-1 space-y-0.5">+ <li><code className="font-mono">socks5://127.0.0.1:1080</code></li>+ <li><code className="font-mono">http://proxy.corp.com:8080</code></li>+ <li><code className="font-mono">socks5://user:pass@proxy:1080</code></li>+ </ul>+ </div>+ </section>+ )+}+function CustomProviderSection() {const queryClient = useQueryClient()const [baseUrl, setBaseUrl] = useState('')@@ -378,6 +474,24 @@ export default function KeysPage() {const healthKeyMap = new Map<number, { status: string; lastCheckedAt: string | null }>()for (const k of healthData?.keys ?? []) healthKeyMap.set(k.id, k)+ // Proxy bypass: shared query with ProxySettingsSection (same queryKey).+ const { data: proxyData } = useQuery<{ proxyUrl: string; enabled: boolean; bypassPlatforms: string[]; active: boolean }>({+ queryKey: ['proxy-url'],+ queryFn: () => apiFetch('/api/settings/proxy'),+ })+ const bypassPlatforms = proxyData?.bypassPlatforms ?? []+ const proxyEnabled = proxyData?.enabled ?? true++ const toggleBypass = useMutation({+ mutationFn: (platform: string) => {+ const next = bypassPlatforms.includes(platform)+ ? bypassPlatforms.filter(p => p !== platform)+ : [...bypassPlatforms, platform]+ return apiFetch('/api/settings/proxy', { method: 'PUT', body: JSON.stringify({ bypassPlatforms: next }) })+ },+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ['proxy-url'] }),+ })+const grouped = [...PLATFORMS, CUSTOM_GROUP].map(p => ({...p,keys: keys.filter(k => k.platform === p.value),@@ -400,6 +514,8 @@ export default function KeysPage() {<div className="space-y-8"><UnifiedKeySection />+ <ProxySettingsSection />+<section><h2 className="text-sm font-medium mb-3">Add a provider key</h2><form onSubmit={handleSubmit} className="flex flex-wrap gap-3 rounded-3xl border p-4 bg-card">@@ -493,6 +609,16 @@ export default function KeysPage() {disabled={togglePlatform.isPending}/><h3 className="text-sm font-medium">{group.label}</h3>+ {proxyEnabled && (+ <div className="inline-flex items-center gap-1.5 ml-1">+ <span className="text-[10px] text-muted-foreground">proxy</span>+ <Switch+ checked={!bypassPlatforms.includes(group.value)}+ onCheckedChange={() => toggleBypass.mutate(group.value)}+ disabled={toggleBypass.isPending}+ />+ </div>+ )}<GetKeyLink url={group.url} /></div><span className="text-xs text-muted-foreground tabular-nums">diff --git a/package-lock.json b/package-lock.jsonindex 7f390b1c..df41907e 100644--- a/package-lock.json+++ b/package-lock.json@@ -1238,7 +1238,6 @@"os": ["aix"],- "peer": true,"engines": {"node": ">=18"}@@ -1255,7 +1254,6 @@"os": ["android"],- "peer": true,"engines": {"node": ">=18"}@@ -1272,7 +1270,6 @@"os": ["android"],- "peer": true,"engines": {"node": ">=18"}@@ -1289,7 +1286,6 @@"os": ["android"],- "peer": true,"engines": {"node": ">=18"}@@ -1306,7 +1302,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": ">=18"}@@ -1323,7 +1318,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": ">=18"}@@ -1340,7 +1334,6 @@"os": ["freebsd"],- "peer": true,"engines": {"node": ">=18"}@@ -1357,7 +1350,6 @@"os": ["freebsd"],- "peer": true,"engines": {"node": ">=18"}@@ -1374,7 +1366,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -1391,7 +1382,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -1408,7 +1398,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -1425,7 +1414,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -1442,7 +1430,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -1459,7 +1446,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -1476,7 +1462,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -1493,7 +1478,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -1510,7 +1494,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -1527,7 +1510,6 @@"os": ["netbsd"],- "peer": true,"engines": {"node": ">=18"}@@ -1544,7 +1526,6 @@"os": ["netbsd"],- "peer": true,"engines": {"node": ">=18"}@@ -1561,7 +1542,6 @@"os": ["openbsd"],- "peer": true,"engines": {"node": ">=18"}@@ -1578,7 +1558,6 @@"os": ["openbsd"],- "peer": true,"engines": {"node": ">=18"}@@ -1595,7 +1574,6 @@"os": ["openharmony"],- "peer": true,"engines": {"node": ">=18"}@@ -1612,7 +1590,6 @@"os": ["sunos"],- "peer": true,"engines": {"node": ">=18"}@@ -1629,7 +1606,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">=18"}@@ -1646,7 +1622,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">=18"}@@ -1663,7 +1638,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">=18"}@@ -10619,6 +10593,53 @@"integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==","license": "MIT"},+ "node_modules/smart-buffer": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz",+ "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==",+ "license": "MIT",+ "engines": {+ "node": ">= 6.0.0",+ "npm": ">= 3.0.0"+ }+ },+ "node_modules/socks": {+ "version": "2.8.9",+ "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.9.tgz",+ "integrity": "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw==",+ "license": "MIT",+ "dependencies": {+ "ip-address": "^10.1.1",+ "smart-buffer": "^4.2.0"+ },+ "engines": {+ "node": ">= 10.0.0",+ "npm": ">= 3.0.0"+ }+ },+ "node_modules/socks-proxy-agent": {+ "version": "10.0.0",+ "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-10.0.0.tgz",+ "integrity": "sha512-pyp2YR3mNxAMu0mGLtzs4g7O3uT4/9sQOLAKcViAkaS9fJWkud7nmaf6ZREFqQEi24IPkBcjfHjXhPTUWjo3uA==",+ "license": "MIT",+ "dependencies": {+ "agent-base": "9.0.0",+ "debug": "^4.3.4",+ "socks": "^2.8.3"+ },+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/socks-proxy-agent/node_modules/agent-base": {+ "version": "9.0.0",+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-9.0.0.tgz",+ "integrity": "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA==",+ "license": "MIT",+ "engines": {+ "node": ">= 20"+ }+ },"node_modules/source-map": {"version": "0.6.1","resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",@@ -11249,6 +11270,15 @@"typescript": ">=4.8.4 <6.1.0"}},+ "node_modules/undici": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/undici/-/undici-8.3.0.tgz",+ "integrity": "sha512-TkUDgb6tl7KOGZ+7e8E3d2FYgUQgF6z5YypqjWmixVQSQERFcVrVg0ySADm2LVLRh5ljAaHTCR5Fmz3Q34rB7Q==",+ "license": "MIT",+ "engines": {+ "node": ">=22.19.0"+ }+ },"node_modules/undici-types": {"version": "7.16.0","resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz",@@ -13046,6 +13076,8 @@"drizzle-orm": "^0.44.2","express": "^5.1.0","helmet": "^8.1.0",+ "socks-proxy-agent": "^10.0.0",+ "undici": "^8.3.0","zod": "^3.24.4"},"devDependencies": {diff --git a/server/package.json b/server/package.jsonindex 82459094..050d1f09 100644--- a/server/package.json+++ b/server/package.json@@ -18,6 +18,8 @@"drizzle-orm": "^0.44.2","express": "^5.1.0","helmet": "^8.1.0",+ "socks-proxy-agent": "^10.0.0",+ "undici": "^8.3.0","zod": "^3.24.4"},"devDependencies": {diff --git a/server/src/db/index.ts b/server/src/db/index.tsindex d4fba2d3..887af7cf 100644--- a/server/src/db/index.ts+++ b/server/src/db/index.ts@@ -58,6 +58,8 @@ export function initDb(dbPath?: string): Database.Database {migrateModelsV20KiloFree(db);migrateModelsV21PruneDead(db);migrateModelsV22Tools(db);+ migrateModelsV23OpenCodeFree(db);+ migrateModelsV24ReRank(db);// After all model migrations: add/refresh paid-equivalent pricing// (drives the realistic "Est. savings" analytics stat).applyModelPricing(db);@@ -1438,6 +1440,7 @@ function migrateModelsV17IntelligenceTiers(db: Database.Database) {OR LOWER(model_id) LIKE '%deepseek-v4-flash%'OR LOWER(model_id) LIKE '%glm-5.1%'OR LOWER(model_id) LIKE '%minimax-m2.7%'+ OR LOWER(model_id) LIKE '%minimax-m3%'`).run();// Large (AA 26–44). Demotes Gemini 2.5 Pro (35), Nemotron 3 Super/120B (36),@@ -1725,6 +1728,30 @@ function migrateModelsV22Tools(db: Database.Database) {apply();}+/**+ * V23 (June 2026): Sync new OpenCode Zen free models from the upstream catalog.+ * Live-probed from https://opencode.ai/zen/v1/models — only models with IDs+ * ending in "-free" that are not yet seeded. Idempotent (INSERT OR IGNORE ++ * fallback backfill), safe to re-run on every boot.+ */+function migrateModelsV23OpenCodeFree(db: Database.Database) {+ const insert = db.prepare(`+ INSERT OR IGNORE INTO models (platform, model_id, display_name, intelligence_rank, speed_rank, size_label, rpm_limit, rpd_limit, tpm_limit, tpd_limit, monthly_token_budget, context_window)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ `);+ const additions: Array<[string, string, string, number, number, string, number | null, number | null, number | null, number | null, string, number | null]> = [+ ['opencode', 'qwen3.6-plus-free', 'Qwen3.6 Plus Free (OpenCode Zen)', 4, 4, 'Frontier', 20, 200, null, null, 'promo (trial)', 131072],+ ['opencode', 'minimax-m3-free', 'MiniMax M3 Free (OpenCode Zen)', 6, 4, 'Large', 20, 200, null, null, 'promo (trial)', 200000],+ ['opencode', 'nemotron-3-ultra-free', 'Nemotron 3 Ultra Free (OpenCode Zen)', 9, 4, 'Large', 20, 200, null, null, 'promo (trial)', 131072],+ ];++ const apply = db.transaction(() => {+ for (const a of additions) insert.run(...a);+ backfillFallback(db);+ });+ apply();+}+// Embeddings V1 (2026-06): per-family embedding catalog. A "family" is one// model identity + dimension — vectors from different families live in// incompatible spaces, so /v1/embeddings only ever fails over WITHIN a family@@ -1836,3 +1863,139 @@ export function setSetting(key: string, value: string): void {ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(key, value);}++/**+ * V24 (June 2026): Full intelligence re-rank — the last comprehensive re-rank+ * was V4 (April 2026). Since then 26 models were added across V5-V23 with ad-hoc+ * ranks that don't reflect current benchmarks. This re-ranks every model by its+ * V17-assigned tier using June 2026 Artificial Analysis Intelligence Index v4.0+ * scores + SWE-bench Verified performance (Qwen3-Coder 480B family leads open+ * models; DeepSeek V4 Pro/Flash are the strongest frontier coders; MiniMax M3+ * outranks M2.7). Idempotent UPDATE, safe to re-run.+ *+ * Higher rank = weaker. Ties allowed (same capability family across providers).+ */+function migrateModelsV24ReRank(db: Database.Database) {+ const setRank = db.prepare(`UPDATE models SET intelligence_rank = ? WHERE platform = ? AND model_id = ?`);+ const ranks: Array<[number, string, string]> = [+ // ── Frontier (AA ≥ 45, V17 tier) ──+ [1, 'nvidia', 'qwen/qwen3-coder-480b-a35b-instruct'], // SWE-bench leader among open models+ [2, 'nvidia', 'deepseek-ai/deepseek-v4-pro'], // strongest frontier coder+ [3, 'nvidia', 'deepseek-ai/deepseek-v4-flash'], // fast frontier+ [3, 'huggingface', 'deepseek-ai/DeepSeek-V4-Flash'],+ [3, 'opencode', 'deepseek-v4-flash-free'],+ [4, 'google', 'gemini-3.5-flash'], // AA 55+ [5, 'nvidia', 'moonshotai/kimi-k2.6'], // strong all-rounder+ [5, 'cloudflare', '@cf/moonshotai/kimi-k2.6'],+ [5, 'huggingface', 'moonshotai/Kimi-K2.6'],+ [6, 'nvidia', 'z-ai/glm-5.1'], // strong but slow cold-start+ [7, 'opencode', 'minimax-m3-free'], // M3 > M2.7+ [8, 'nvidia', 'minimaxai/minimax-m2.7'],+ [9, 'google', 'gemini-3-flash-preview'], // AA 46+ [10, 'ollama', 'cogito-2.1:671b'], // reasoning specialist+ [11, 'openrouter', 'openrouter/owl-alpha'], // OR-house agentic+ [12, 'opencode', 'qwen3.6-plus-free'], // seed Frontier, no AA score yet++ // ── Large (AA 26–44, V17 tier) ──+ [1, 'ollama', 'qwen3-coder-next'], // ~80B-A3B coder+ [1, 'huggingface', 'Qwen/Qwen3-Coder-Next'],+ [2, 'cerebras', 'zai-glm-4.7'], // AA 42, re-enabled V21+ [2, 'ollama', 'glm-4.7'],+ [3, 'nvidia', 'nvidia/nemotron-3-super-120b-a12b'], // AA 36+ [3, 'opencode', 'nemotron-3-super-free'],+ [3, 'kilo', 'nvidia/nemotron-3-super-120b-a12b:free'],+ [3, 'cloudflare', '@cf/nvidia/nemotron-3-120b-a12b'],+ [4, 'opencode', 'nemotron-3-ultra-free'], // Ultra > Super, no AA yet+ [5, 'sambanova', 'DeepSeek-V3.2'], // AA 32+ [6, 'sambanova', 'DeepSeek-V3.1'], // AA 28+ [7, 'openrouter', 'nousresearch/hermes-3-llama-3.1-405b:free'], // 405B, tool-use tuned+ [8, 'cloudflare', '@cf/zai-org/glm-4.7-flash'], // GLM-4.7 distill+ [8, 'zhipu', 'glm-4.7-flash'], // same GLM-4.7 family+ [9, 'google', 'gemini-2.5-pro'], // AA 35, DISABLED V5+ [9, 'google', 'gemini-3.1-pro-preview'], // DISABLED V13, AA 60++ [10, 'mistral', 'mistral-medium-latest'], // Mistral Medium 3.5, AA 32+ [10, 'mistral', 'magistral-medium-latest'], // reasoning-focused+ [11, 'google', 'gemma-4-31b-it'], // AA 39+ [11, 'google', 'gemma-4-26b-a4b-it'], // AA 31+ [11, 'nvidia', 'google/gemma-4-31b-it'],+ [11, 'cloudflare', '@cf/google/gemma-4-26b-a4b-it'],+ [11, 'ollama', 'gemma4:31b'],+ [12, 'sambanova', 'gpt-oss-120b'],+ [12, 'groq', 'openai/gpt-oss-120b'],+ [12, 'cloudflare', '@cf/openai/gpt-oss-120b'],+ [12, 'ollama', 'gpt-oss:120b'],+ [12, 'cerebras', 'gpt-oss-120b'],+ [12, 'openrouter', 'openai/gpt-oss-120b:free'], // same gpt-oss-120b family+ [13, 'google', 'gemini-3.1-flash-lite-preview'], // AA 34+ [14, 'github', 'openai/gpt-4.1'], // AA 26-44 range+ [14, 'zhipu', 'glm-4.5-flash'], // seed Large, no AA score+ [15, 'openrouter', 'qwen/qwen3-next-80b-a3b-instruct:free'],+ [16, 'opencode', 'big-pickle'], // stealth model, unknown capability+ [17, 'kilo', 'poolside/laguna-m.1:free'], // Poolside Laguna M.1+ [17, 'openrouter', 'poolside/laguna-m.1:free'], // same Laguna M.1 family+ [18, 'cohere', 'command-a-03-2025'], // RAG/agent focused+ [18, 'cohere', 'command-a-reasoning-08-2025'],+ [19, 'ollama', 'devstral-2:123b'], // Devstral 2+ [20, 'ollama', 'mistral-large-3:675b'], // DISABLED V13+ [21, 'ollama', 'deepseek-v3.2'], // DISABLED V13+ [22, 'ollama', 'kimi-k2-thinking'], // DISABLED V13++ // ── Medium (AA 13–25, V17 tier) ──+ [1, 'openrouter', 'qwen/qwen3-coder:free'], // AA 25 — top of Medium+ [1, 'ollama', 'qwen3-coder:480b'],+ [2, 'cerebras', 'qwen-3-235b-a22b-instruct-2507'], // AA 25, DISABLED V14+ [3, 'cloudflare', '@cf/qwen/qwen3-30b-a3b-fp8'], // Qwen3 30B MoE+ [4, 'mistral', 'mistral-large-latest'], // AA 23+ [4, 'nvidia', 'mistralai/mistral-large-3-675b-instruct-2512'],+ [5, 'nvidia', 'meta/llama-4-maverick-17b-128e-instruct'], // AA 18+ [5, 'sambanova', 'Llama-4-Maverick-17B-128E-Instruct'],+ [6, 'google', 'gemini-2.5-flash'], // AA 21+ [7, 'github', 'gpt-4o'], // AA 17+ [8, 'openrouter', 'z-ai/glm-4.5-air:free'], // AA 23+ [9, 'cloudflare', '@cf/deepseek-ai/deepseek-r1-distill-qwen-32b'], // AA 17+ [11, 'mistral', 'devstral-latest'],+ [12, 'groq', 'meta-llama/llama-4-scout-17b-16e-instruct'], // AA 14+ [12, 'cloudflare', '@cf/meta/llama-4-scout-17b-16e-instruct'],+ [13, 'groq', 'groq/compound'], // agent system, not a model+ [15, 'google', 'gemini-2.5-flash-lite'],+ [16, 'groq', 'llama-3.3-70b-versatile'], // AA 14+ [16, 'sambanova', 'Meta-Llama-3.3-70B-Instruct'],+ [16, 'cloudflare', '@cf/meta/llama-3.3-70b-instruct-fp8-fast'],+ [16, 'nvidia', 'meta/llama-3.3-70b-instruct'],+ [16, 'nvidia', 'meta/llama-3.1-70b-instruct'],+ [16, 'openrouter', 'meta-llama/llama-3.3-70b-instruct:free'],+ [18, 'kilo', 'poolside/laguna-xs.2:free'], // Poolside Laguna XS.2+ [18, 'openrouter', 'poolside/laguna-xs.2:free'], // same Laguna XS.2 family+ [19, 'groq', 'qwen/qwen3-32b'], // Qwen3 32B+ [20, 'openrouter', 'openai/gpt-oss-20b:free'],+ [20, 'groq', 'openai/gpt-oss-20b'],+ [20, 'groq', 'openai/gpt-oss-safeguard-20b'],+ [20, 'ollama', 'gpt-oss:20b'],+ [20, 'pollinations', 'openai-fast'],+ [21, 'groq', 'groq/compound-mini'], // agent system, smaller+ [22, 'mistral', 'mistral-small-latest'], // Mistral Small 4+ [23, 'opencode', 'mimo-v2.5-free'], // MiMo-V2.5+ [24, 'kilo', 'stepfun/step-3.7-flash:free'], // StepFun 3.7 Flash+ [25, 'nvidia', 'nvidia/nemotron-3-nano-30b-a3b'], // weak at tools (V22 incident)+ [25, 'openrouter', 'nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free'],+ [25, 'openrouter', 'nvidia/nemotron-3-nano-30b-a3b:free'], // non-omni variant+ [26, 'openrouter', 'nvidia/nemotron-nano-9b-v2:free'], // even smaller+ [27, 'cohere', 'command-r-plus-08-2024'], // RAG-focused, weak on code+ [27, 'cohere', 'command-r-08-2024'],+ [28, 'llm7', 'codestral-latest'], // LLM7 surviving row++ // ── Small (AA ≤ 12, V17 tier) ──+ [1, 'mistral', 'codestral-latest'], // HumanEval 86.6%, AA 8+ [2, 'sambanova', 'gemma-3-12b-it'], // AA 9+ [3, 'cloudflare', '@cf/ibm-granite/granite-4.0-h-micro'], // Granite 4.0 H Micro+ [4, 'openrouter', 'liquid/lfm-2.5-1.2b-instruct:free'], // Liquid 1.2B+ [4, 'openrouter', 'liquid/lfm-2.5-1.2b-thinking:free'], // Liquid 1.2B Thinking+ [5, 'groq', 'llama-3.1-8b-instant'], // Llama 3.1 8B+ [5, 'cerebras', 'llama3.1-8b'], // DISABLED V14+ [6, 'mistral', 'ministral-8b-latest'], // Ministral 3 8B+ ];+ const apply = db.transaction(() => {+ for (const [r, p, m] of ranks) setRank.run(r, p, m);+ });+ apply();+}diff --git a/server/src/index.ts b/server/src/index.tsindex efb7329e..470d5498 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -1,7 +1,8 @@import './env.js';import { createApp } from './app.js';-import { initDb } from './db/index.js';+import { initDb, getSetting } from './db/index.js';import { startHealthChecker } from './services/health.js';+import { applyProxyUrl, applyProxyEnabled, applyProxyBypass } from './lib/proxy.js';const PORT = process.env.PORT ?? 3001;// Dual-stack ('::') by default so the dashboard is reachable over both IPv4@@ -11,6 +12,13 @@ const HOST = process.env.HOST ?? '::';async function main() {initDb();++ // Load the persisted proxy settings from the DB (env var wins if set).+ // Must happen after initDb so the settings table is ready.+ applyProxyUrl(getSetting('proxy_url') ?? '');+ applyProxyEnabled(getSetting('proxy_enabled') !== '0'); // default: enabled+ applyProxyBypass(getSetting('proxy_bypass') ?? '');+const app = createApp();const onReady = (host: string) => () => {diff --git a/server/src/lib/proxy.ts b/server/src/lib/proxy.tsnew file mode 100644index 00000000..4c4a3a8b--- /dev/null+++ b/server/src/lib/proxy.ts@@ -0,0 +1,238 @@+import { ProxyAgent } from 'undici';+import { SocksProxyAgent } from 'socks-proxy-agent';+import http from 'http';+import https from 'https';++// Module-level proxy URL.+let _proxyUrl = '';+let _proxyEnabled = true;+let _bypassPlatforms = new Set<string>();+let _initialized = false;++// Cache.+let cached: {+ dispatcher: ProxyAgent | SocksProxyAgent | undefined;+ proxyUrl: string;+ isSocks: boolean;+ ts: number;+} | null = null;+const CACHE_TTL_MS = 30_000;++/** Called once at startup (after initDb) and on PUT /api/settings/proxy. */+export function applyProxyUrl(dbValue: string): void {+ const envUrl = process.env.PROXY_URL?.trim();+ if (envUrl) {+ _proxyUrl = envUrl;+ } else {+ _proxyUrl = dbValue.trim();+ }+ cached = null;+ if (_proxyUrl) {+ const masked = _proxyUrl.replace(/\/\/[^@]*@/, '//***@');+ console.log(`[proxy] Configured → ${masked}`);+ } else {+ console.log('[proxy] Not configured — outbound requests go direct.');+ }+ _initialized = true;+}++export function getProxyUrl(): string {+ return _proxyUrl;+}++/** Toggle the proxy on/off without losing the URL. */+export function applyProxyEnabled(enabled: boolean): void {+ _proxyEnabled = enabled;+ if (!enabled) console.log('[proxy] Disabled — requests go direct.');+}++export function isProxyEnabled(): boolean {+ return _proxyEnabled;+}++/** Set which platforms bypass the proxy. Comma-separated string from DB. */+export function applyProxyBypass(platformsCsv: string): void {+ _bypassPlatforms = new Set(+ platformsCsv+ .split(',')+ .map(s => s.trim().toLowerCase())+ .filter(Boolean),+ );+ if (_bypassPlatforms.size > 0) {+ console.log(`[proxy] Bypass for: ${[..._bypassPlatforms].join(', ')}`);+ }+}++export function getProxyBypassPlatforms(): string[] {+ return [..._bypassPlatforms];+}++/**+ * Returns true when a platform should NOT use the proxy.+ * True when: proxy is disabled globally, or the platform is in the bypass list.+ */+function shouldBypassProxy(platform?: string): boolean {+ if (!_proxyEnabled) return true;+ if (platform && _bypassPlatforms.has(platform.toLowerCase())) return true;+ return false;+}++/**+ * Resolve the proxy dispatcher. For SOCKS schemes this returns a+ * SocksProxyAgent; for HTTP/HTTPS it returns an undici ProxyAgent.+ */+function resolveDispatcher(): ProxyAgent | SocksProxyAgent | undefined {+ const now = Date.now();++ if (cached && (now - cached.ts) < CACHE_TTL_MS) {+ return cached.dispatcher;+ }++ if (!_initialized) applyProxyUrl('');++ if (!_proxyUrl) {+ cached = { dispatcher: undefined, proxyUrl: '', isSocks: false, ts: now };+ return undefined;+ }++ try {+ const isSocks = _proxyUrl.startsWith('socks5:') || _proxyUrl.startsWith('socks4:');++ if (isSocks) {+ const dispatcher = new SocksProxyAgent(_proxyUrl);+ cached = { dispatcher, proxyUrl: _proxyUrl, isSocks: true, ts: now };+ return dispatcher;+ }++ const dispatcher = new ProxyAgent({ uri: _proxyUrl });+ cached = { dispatcher, proxyUrl: _proxyUrl, isSocks: false, ts: now };+ return dispatcher;+ } catch (err: any) {+ const masked = _proxyUrl.replace(/\/\/[^@]*@/, '//***@');+ console.error(`[proxy] Failed to create dispatcher for "${masked}": ${err.message}`);+ cached = { dispatcher: undefined, proxyUrl: _proxyUrl, isSocks: false, ts: now };+ return undefined;+ }+}++// ── SOCKS-compatible fetch via http/https modules ──++function socksFetch(urlStr: string, init?: RequestInit, agent?: SocksProxyAgent): Promise<Response> {+ const url = new URL(urlStr);+ const isTls = url.protocol === 'https:';+ const transport = isTls ? https : http;+ const port = url.port || (isTls ? 443 : 80);+ const method = init?.method ?? 'GET';+ const headers: Record<string, string> = {};+ if (init?.headers) {+ for (const [k, v] of Object.entries(init.headers as Record<string, string>)) {+ headers[k.toLowerCase()] = v;+ }+ }++ const signal = init?.signal;++ return new Promise((resolve, reject) => {+ const req = transport.request({+ hostname: url.hostname,+ port,+ path: url.pathname + url.search,+ method,+ headers: { ...headers, host: url.hostname },+ agent,+ servername: isTls ? url.hostname : undefined,+ rejectUnauthorized: true,+ timeout: 120_000,+ }, (res) => {+ if (signal?.aborted) {+ res.destroy();+ reject(new DOMException('The operation was aborted', 'AbortError'));+ return;+ }++ const status = res.statusCode ?? 0;+ const statusText = res.statusMessage ?? '';++ const body = new ReadableStream({+ start(controller) {+ res.on('data', (chunk: Buffer) => controller.enqueue(new Uint8Array(chunk)));+ res.on('end', () => controller.close());+ res.on('error', (err: Error) => controller.error(err));+ },+ cancel() {+ res.destroy();+ },+ });++ const hdrs: Record<string, string> = {};+ for (const [k, v] of Object.entries(res.headers)) {+ hdrs[k] = v as string;+ }++ resolve(new Response(body, { status, statusText, headers: hdrs }));+ });++ req.on('error', (err) => reject(err));+ req.on('timeout', () => {+ req.destroy();+ reject(new Error('timeout'));+ });++ if (signal) {+ if (signal.aborted) {+ req.destroy();+ reject(new DOMException('The operation was aborted', 'AbortError'));+ return;+ }+ signal.addEventListener('abort', () => {+ req.destroy();+ reject(new DOMException('The operation was aborted', 'AbortError'));+ }, { once: true });+ }++ if (init?.body) {+ req.write(init.body as string);+ }+ req.end();+ });+}++/**+ * Drop-in replacement for `fetch(url, init)` that routes through the+ * configured proxy. Pass an optional `platform` string to respect the+ * per-platform bypass list.+ *+ * When no proxy is configured, or proxy is disabled, or the platform is+ * in the bypass list, this is a direct pass-through to `fetch()`.+ */+export async function proxyFetch(url: string, init?: RequestInit, platform?: string): Promise<Response> {+ // Bypass check: disabled globally, or this platform is exempt.+ if (shouldBypassProxy(platform)) {+ return fetch(url, init);+ }++ const d = resolveDispatcher();++ // No dispatcher (no proxy URL configured) → direct+ if (!d) {+ return fetch(url, init);+ }++ // SOCKS proxy → http/https fallback+ if (d instanceof SocksProxyAgent) {+ return socksFetch(url, init, d);+ }++ // HTTP/HTTPS proxy → undici (dispatcher is an undici extension not in TS types)+ return fetch(url, { ...init, dispatcher: d } as unknown as RequestInit);+}++/**+ * Returns true when the proxy is configured AND enabled.+ * Used by the dashboard to show the "Active" badge.+ */+export function isProxyActive(): boolean {+ if (!_proxyEnabled) return false;+ resolveDispatcher();+ return !!cached?.dispatcher;+}diff --git a/server/src/providers/base.ts b/server/src/providers/base.tsindex 32139b10..76f0b82a 100644--- a/server/src/providers/base.ts+++ b/server/src/providers/base.ts@@ -6,6 +6,7 @@ import type {ChatToolChoice,Platform,} from '@freellmapi/shared/types.js';+import { proxyFetch } from '../lib/proxy.js';export interface CompletionOptions {model?: string;@@ -50,7 +51,7 @@ export abstract class BaseProvider {const controller = new AbortController();const timeout = setTimeout(() => controller.abort(), timeoutMs);try {- return await fetch(url, { ...init, signal: controller.signal });+ return await proxyFetch(url, { ...init, signal: controller.signal }, this.platform);} finally {clearTimeout(timeout);}diff --git a/server/src/providers/google.ts b/server/src/providers/google.tsindex 7273787c..65594f29 100644--- a/server/src/providers/google.ts+++ b/server/src/providers/google.ts@@ -9,6 +9,7 @@ import type {} from '@freellmapi/shared/types.js';import { BaseProvider, type CompletionOptions } from './base.js';import { contentToString } from '../lib/content.js';+import { proxyFetch } from '../lib/proxy.js';const API_BASE = 'https://generativelanguage.googleapis.com/v1beta';@@ -171,7 +172,7 @@ async function imageUrlToInlineData(url: string): Promise<{ mimeType: string; da}if (/^https?:\/\//i.test(url)) {try {- const res = await fetch(url);+ const res = await proxyFetch(url, undefined, 'google');if (!res.ok) return null;const buf = Buffer.from(await res.arrayBuffer());if (buf.length === 0 || buf.length > MAX_IMAGE_BYTES) return null;diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.tsindex 3d7fa5cd..ba7d8ed2 100644--- a/server/src/routes/proxy.ts+++ b/server/src/routes/proxy.ts@@ -285,6 +285,7 @@ export function isRetryableError(err: any): boolean {|| msg.includes('quota') || msg.includes('resource_exhausted')|| msg.includes('aborted') || msg.includes('timeout') || msg.includes('etimedout')|| msg.includes('econnrefused') || msg.includes('econnreset')+ || msg.includes('fetch failed') // undici transport error (proxy down, DNS, TLS, etc.)|| msg.includes('503') || msg.includes('unavailable')|| msg.includes('500') || msg.includes('internal server error')// 413: this model's payload limit is too small for the request, but anotherdiff --git a/server/src/routes/settings.ts b/server/src/routes/settings.tsindex ef8eb948..e4bfd9d7 100644--- a/server/src/routes/settings.ts+++ b/server/src/routes/settings.ts@@ -1,6 +1,7 @@import { Router } from 'express';import type { Request, Response } from 'express';-import { getUnifiedApiKey, regenerateUnifiedKey } from '../db/index.js';+import { getUnifiedApiKey, regenerateUnifiedKey, getSetting, setSetting } from '../db/index.js';+import { applyProxyUrl, applyProxyEnabled, applyProxyBypass, isProxyActive, getProxyUrl, isProxyEnabled, getProxyBypassPlatforms } from '../lib/proxy.js';export const settingsRouter = Router();@@ -14,3 +15,67 @@ settingsRouter.post('/api-key/regenerate', (_req: Request, res: Response) => {const newKey = regenerateUnifiedKey();res.json({ apiKey: newKey });});++// Get the proxy settings+settingsRouter.get('/proxy', (_req: Request, res: Response) => {+ res.json({+ proxyUrl: getProxyUrl(),+ enabled: isProxyEnabled(),+ bypassPlatforms: getProxyBypassPlatforms(),+ active: isProxyActive(),+ });+});++// Set the proxy settings. Accepts partial updates: proxyUrl, enabled, bypassPlatforms.+settingsRouter.put('/proxy', (req: Request, res: Response) => {+ const { proxyUrl, enabled, bypassPlatforms } = req.body as {+ proxyUrl?: string;+ enabled?: boolean;+ bypassPlatforms?: string[];+ };++ // --- proxyUrl ---+ if (typeof proxyUrl === 'string') {+ const trimmed = proxyUrl.trim();+ if (trimmed) {+ try {+ const u = new URL(trimmed);+ if (!['http:', 'https:', 'socks5:', 'socks4:'].includes(u.protocol)) {+ res.status(400).json({+ error: { message: 'Proxy URL must use http, https, socks5, or socks4 scheme', type: 'invalid_request_error' },+ });+ return;+ }+ } catch {+ res.status(400).json({+ error: { message: 'Invalid proxy URL — must be a valid URL like socks5://host:port', type: 'invalid_request_error' },+ });+ return;+ }+ setSetting('proxy_url', trimmed);+ } else {+ setSetting('proxy_url', '');+ }+ applyProxyUrl(trimmed);+ }++ // --- enabled ---+ if (typeof enabled === 'boolean') {+ setSetting('proxy_enabled', enabled ? '1' : '0');+ applyProxyEnabled(enabled);+ }++ // --- bypassPlatforms ---+ if (Array.isArray(bypassPlatforms)) {+ const csv = bypassPlatforms.map(s => s.trim()).filter(Boolean).join(',');+ setSetting('proxy_bypass', csv);+ applyProxyBypass(csv);+ }++ res.json({+ proxyUrl: getProxyUrl(),+ enabled: isProxyEnabled(),+ bypassPlatforms: getProxyBypassPlatforms(),+ active: isProxyActive(),+ });+});diff --git a/server/src/services/embeddings.ts b/server/src/services/embeddings.tsindex 8375d323..b1255c78 100644--- a/server/src/services/embeddings.ts+++ b/server/src/services/embeddings.ts@@ -9,6 +9,7 @@// cross-provider redundancy for free.import { getDb, getSetting } from '../db/index.js';import { decrypt } from '../lib/crypto.js';+import { proxyFetch } from '../lib/proxy.js';export interface EmbeddingModelRow {id: number;@@ -91,7 +92,7 @@ async function openAiStyleEmbed(inputs: string[],extra: Record<string, unknown> = {},): Promise<ProviderCallResult> {- const r = await fetch(url, {+ const r = await proxyFetch(url, {method: 'POST',headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },body: JSON.stringify({ model: modelId, input: inputs, ...extra }),@@ -114,15 +115,15 @@ async function openAiStyleEmbed(async function callProvider(row: EmbeddingModelRow, key: string, inputs: string[]): Promise<ProviderCallResult> {switch (row.platform) {case 'google':- return openAiStyleEmbed('https://generativelanguage.googleapis.com/v1beta/openai/embeddings', key, row.model_id, inputs);+ return openAiStyleEmbed('https://generativelanguage.googleapis.com/v1beta/openai/embeddings', key, row.model_id, inputs, {});case 'nvidia':// NeMo Retriever NIMs require input_type; 'query' is the symmetric-safe// choice for a gateway that can't know whether this is index or query time.return openAiStyleEmbed('https://integrate.api.nvidia.com/v1/embeddings', key, row.model_id, inputs, { input_type: 'query' });case 'openrouter':- return openAiStyleEmbed('https://openrouter.ai/api/v1/embeddings', key, row.model_id, inputs);+ return openAiStyleEmbed('https://openrouter.ai/api/v1/embeddings', key, row.model_id, inputs, {});case 'github':- return openAiStyleEmbed('https://models.github.ai/inference/embeddings', key, row.model_id, inputs);+ return openAiStyleEmbed('https://models.github.ai/inference/embeddings', key, row.model_id, inputs, {});case 'cloudflare': {// Key is stored as "account_id:token".const sep = key.indexOf(':');@@ -131,12 +132,12 @@ async function callProvider(row: EmbeddingModelRow, key: string, inputs: string[const token = key.slice(sep + 1);return openAiStyleEmbed(`https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/v1/embeddings`,- token, row.model_id, inputs,+ token, row.model_id, inputs, {},);}case 'huggingface': {// HF serves embeddings as the feature-extraction task, not /v1/embeddings.- const r = await fetch(+ const r = await proxyFetch(`https://router.huggingface.co/hf-inference/models/${row.model_id}/pipeline/feature-extraction`,{method: 'POST',@@ -151,7 +152,7 @@ async function callProvider(row: EmbeddingModelRow, key: string, inputs: string[return { vectors, inputTokens: null };}case 'cohere': {- const r = await fetch('https://api.cohere.com/v2/embed', {+ const r = await proxyFetch('https://api.cohere.com/v2/embed', {method: 'POST',headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },body: JSON.stringify({