Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

refactor(env): promote hardcoded URLs and circuit-breaker timeouts to environment

diegosouzapw46932961d466
diff --git a/.env.example b/.env.example
index ab1dec0d05..d4c04f22df 100644
--- a/.env.example
+++ b/.env.example
@@ -263,6 +263,13 @@ NEXT_PUBLIC_CLOUD_URL=
#OMNIROUTE_KIE_CALLBACK_URL=
#OMNIROUTE_PUBLIC_URL=
+# Upstream quota endpoints used by the Usage page. Override only for
+# debugging or when routing through a corporate mirror. Used by:
+# open-sse/services/usage.ts.
+#OMNIROUTE_CROF_USAGE_URL=https://crof.ai/usage_api/
+#OMNIROUTE_GEMINI_CLI_USAGE_URL=https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist
+#OMNIROUTE_CODEWHISPERER_BASE_URL=https://codewhisperer.us-east-1.amazonaws.com
+
# ═══════════════════════════════════════════════════════════════════════════════
# 8. OUTBOUND PROXY (Upstream Provider Calls)
@@ -630,6 +637,29 @@ GEMINI_CLI_USER_AGENT="google-api-nodejs-client/10.3.0"
# FETCH_CONNECT_TIMEOUT_MS=30000 # TCP connection establishment (default: 30s)
# FETCH_KEEPALIVE_TIMEOUT_MS=4000 # Keep-alive socket idle timeout (default: 4s)
+# Default timeout (ms) for src/shared/utils/fetchTimeout.ts. Acts as the
+# fallback when FETCH_TIMEOUT_MS is unset. Default: 120000 (2 min).
+# OMNIROUTE_DEFAULT_FETCH_TIMEOUT_MS=120000
+
+# ── ChatGPT TLS sidecar (Firefox-fingerprinted client) ──
+# Used by: open-sse/services/chatgptTlsClient.ts — wire-level timeout for
+# the bogdanfinn/tls-client koffi binding and the JS-side grace window
+# layered on top of it when the native library is wedged.
+# OMNIROUTE_CHATGPT_TLS_TIMEOUT_MS=60000
+# OMNIROUTE_CHATGPT_TLS_GRACE_MS=10000
+
+# ── Circuit breaker thresholds and reset windows ──
+# Used by: open-sse/config/constants.ts → src/lib/resilience/settings.ts.
+# Defaults match historical PROVIDER_PROFILES values (post-scaling for
+# 500+ connections). Lower the threshold to react faster, raise it to
+# tolerate more transient failures before short-circuiting.
+# OMNIROUTE_CIRCUIT_BREAKER_OAUTH_THRESHOLD=8
+# OMNIROUTE_CIRCUIT_BREAKER_OAUTH_RESET_MS=60000
+# OMNIROUTE_CIRCUIT_BREAKER_API_KEY_THRESHOLD=12
+# OMNIROUTE_CIRCUIT_BREAKER_API_KEY_RESET_MS=30000
+# OMNIROUTE_CIRCUIT_BREAKER_LOCAL_THRESHOLD=2
+# OMNIROUTE_CIRCUIT_BREAKER_LOCAL_RESET_MS=15000
+
# ── Stream idle detection ──
# STREAM_IDLE_TIMEOUT_MS=600000 # Max silence between SSE chunks (default: 600000)
# # Extended-thinking models rarely pause >90s.
diff --git a/open-sse/config/constants.ts b/open-sse/config/constants.ts
index b55085526d..21c1adfc80 100644
--- a/open-sse/config/constants.ts
+++ b/open-sse/config/constants.ts
@@ -142,13 +142,23 @@ export const RateLimitReason = {
// ─── Provider Resilience Profiles ───────────────────────────────────────────
// Separate behavior for OAuth (low-limit, session-based) vs API Key (high-limit, metered)
+// Circuit-breaker thresholds and reset windows are overridable via
+// OMNIROUTE_CIRCUIT_BREAKER_* env vars so operators can dampen or harden
+// behavior without recompiling.
+function envInt(name: string, fallback: number): number {
+ const raw = process.env[name];
+ if (raw === undefined || raw === null || raw === "") return fallback;
+ const parsed = Number(raw);
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
+}
+
export const PROVIDER_PROFILES = {
oauth: {
transientCooldown: 5000, // 5s (session tokens — short recovery)
rateLimitCooldown: 60000, // 60s default when no retry-after header
maxBackoffLevel: 8, // Higher ceiling (sessions may stay bad longer)
- circuitBreakerThreshold: 8, // Scaled for 500+ connections (was 3)
- circuitBreakerReset: 60000, // 1min reset
+ circuitBreakerThreshold: envInt("OMNIROUTE_CIRCUIT_BREAKER_OAUTH_THRESHOLD", 8),
+ circuitBreakerReset: envInt("OMNIROUTE_CIRCUIT_BREAKER_OAUTH_RESET_MS", 60000),
// Provider-level circuit breaker (entire provider cooldown after repeated failures)
providerFailureThreshold: 10, // Scaled for 500+ connections (was 3)
providerFailureWindowMs: 900000, // 15min window (was 10min)
@@ -158,8 +168,8 @@ export const PROVIDER_PROFILES = {
transientCooldown: 3000, // 3s (API providers recover faster)
rateLimitCooldown: 0, // 0 = respect retry-after header from provider
maxBackoffLevel: 5, // Lower ceiling (API quotas reset at known intervals)
- circuitBreakerThreshold: 12, // Scaled for 500+ connections (was 5)
- circuitBreakerReset: 30000, // 30s reset
+ circuitBreakerThreshold: envInt("OMNIROUTE_CIRCUIT_BREAKER_API_KEY_THRESHOLD", 12),
+ circuitBreakerReset: envInt("OMNIROUTE_CIRCUIT_BREAKER_API_KEY_RESET_MS", 30000),
// Provider-level circuit breaker (entire provider cooldown after repeated failures)
providerFailureThreshold: 15, // Scaled for 500+ connections (was 5)
providerFailureWindowMs: 1800000, // 30min window (was 20min)
@@ -172,8 +182,8 @@ export const PROVIDER_PROFILES = {
transientCooldown: 2000, // 2s (local — very fast recovery)
rateLimitCooldown: 5000, // 5s (local — no real rate limits)
maxBackoffLevel: 3, // Low ceiling (local either works or doesn't)
- circuitBreakerThreshold: 2, // Opens fast (if local is down, it's down)
- circuitBreakerReset: 15000, // 15s reset (check again quickly)
+ circuitBreakerThreshold: envInt("OMNIROUTE_CIRCUIT_BREAKER_LOCAL_THRESHOLD", 2),
+ circuitBreakerReset: envInt("OMNIROUTE_CIRCUIT_BREAKER_LOCAL_RESET_MS", 15000),
// Provider-level circuit breaker (entire provider cooldown after repeated failures)
providerFailureThreshold: 2, // 2 failures trigger provider cooldown
providerFailureWindowMs: 300000, // 5min window for counting failures
diff --git a/open-sse/services/chatgptTlsClient.ts b/open-sse/services/chatgptTlsClient.ts
index 4e21f18da4..b5c3fdbf66 100644
--- a/open-sse/services/chatgptTlsClient.ts
+++ b/open-sse/services/chatgptTlsClient.ts
@@ -21,14 +21,16 @@ let clientPromise: Promise<unknown> | null = null;
let exitHookInstalled = false;
const CHATGPT_PROFILE = "firefox_148"; // matches the Firefox 148 UA we send
-const DEFAULT_TIMEOUT_MS = 60_000;
+const DEFAULT_TIMEOUT_MS =
+ Number.parseInt(process.env.OMNIROUTE_CHATGPT_TLS_TIMEOUT_MS || "", 10) || 60_000;
// Grace period added to the binding's wire-level timeout before our JS-level
// hard timeout fires. Under healthy operation `tls-client-node` honors
// `timeoutMilliseconds` and rejects on its own; the JS-level race only wins
// when the koffi-loaded native library is wedged (which the binding's own
// timer can't escape). Keep the grace small so users don't wait noticeably
// longer than the configured timeout when the binding is dead.
-const HARD_TIMEOUT_GRACE_MS = 10_000;
+const HARD_TIMEOUT_GRACE_MS =
+ Number.parseInt(process.env.OMNIROUTE_CHATGPT_TLS_GRACE_MS || "", 10) || 10_000;
function installExitHook(): void {
if (exitHookInstalled) return;
diff --git a/open-sse/services/usage.ts b/open-sse/services/usage.ts
index 007f77f341..21d85889f6 100644
--- a/open-sse/services/usage.ts
+++ b/open-sse/services/usage.ts
@@ -3,6 +3,14 @@
*/
import { PROVIDERS } from "../config/constants.ts";
+
+// Quota / usage upstream URLs (overridable for testing or relays).
+const CROF_USAGE_URL = process.env.OMNIROUTE_CROF_USAGE_URL ?? "https://crof.ai/usage_api/";
+const GEMINI_CLI_USAGE_URL =
+ process.env.OMNIROUTE_GEMINI_CLI_USAGE_URL ??
+ "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist";
+const CODEWHISPERER_BASE_URL =
+ process.env.OMNIROUTE_CODEWHISPERER_BASE_URL ?? "https://codewhisperer.us-east-1.amazonaws.com";
import {
getAntigravityFetchAvailableModelsUrls,
ANTIGRAVITY_BASE_URLS,
@@ -482,7 +490,7 @@ async function getCrofUsage(apiKey: string) {
let response: Response;
try {
- response = await fetch("https://crof.ai/usage_api/", {
+ response = await fetch(CROF_USAGE_URL, {
method: "GET",
headers: {
Authorization: `Bearer ${apiKey}`,
@@ -1400,7 +1408,7 @@ async function getGeminiCliSubscriptionInfoCached(accessToken: string): Promise<
*/
async function getGeminiCliSubscriptionInfo(accessToken: string): Promise<unknown | null> {
try {
- const response = await fetch("https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist", {
+ const response = await fetch(GEMINI_CLI_USAGE_URL, {
method: "POST",
headers: {
Authorization: `Bearer ${accessToken}`,
@@ -2212,7 +2220,7 @@ async function getKiroUsage(accessToken?: string, providerSpecificData?: JsonRec
resourceType: "AGENTIC_REQUEST",
};
- const response = await fetch("https://codewhisperer.us-east-1.amazonaws.com", {
+ const response = await fetch(CODEWHISPERER_BASE_URL, {
method: "POST",
headers: {
Authorization: `Bearer ${accessToken}`,
diff --git a/src/shared/utils/fetchTimeout.ts b/src/shared/utils/fetchTimeout.ts
index cfc36205ff..55efe599ac 100644
--- a/src/shared/utils/fetchTimeout.ts
+++ b/src/shared/utils/fetchTimeout.ts
@@ -7,7 +7,8 @@
* @module shared/utils/fetchTimeout
*/
-const DEFAULT_TIMEOUT_MS = 120000; // 2 minutes
+const DEFAULT_TIMEOUT_MS =
+ parseInt(process.env.OMNIROUTE_DEFAULT_FETCH_TIMEOUT_MS || "", 10) || 120000; // 2 minutes
const FETCH_TIMEOUT_MS = parseInt(process.env.FETCH_TIMEOUT_MS || "", 10) || DEFAULT_TIMEOUT_MS;
interface FetchTimeoutOptions extends RequestInit {