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(server): per-provider timeouts via PROVIDER_TIMEOUT_<PLATFORM>, stream stall watchdog via PROVIDER_STREAM_STALL_TIMEOUT_MS
Tash1aaf10a86861
diff --git a/.env.example b/.env.exampleindex c576c562..d6a5028b 100644--- a/.env.example+++ b/.env.example@@ -38,6 +38,23 @@ PORT=3001# set to 0 to disable the cap. Example — cap OpenRouter at 50 requests/day:# PROVIDER_DAILY_REQUEST_CAP_OPENROUTER=50+# Per-provider chat HTTP timeout in milliseconds, named+# PROVIDER_TIMEOUT_<PLATFORM> (platform name upper-cased). Overrides the+# built-in default for that provider (60s for most OpenAI-compatible platforms,+# 90s NVIDIA, 120s Ollama Cloud / AI Horde / custom providers, 60s Google as+# registered). Set to 0 to disable the timeout entirely. Read at startup.+# Example — give NVIDIA NIM's slow reasoning models 5 minutes:+# PROVIDER_TIMEOUT_NVIDIA=300000++# Mid-stream inactivity timeout for streaming responses, in milliseconds+# (default: 90000). If an SSE stream goes this long without a single byte, the+# gateway gives up on it (before any output reached the client this fails over+# to the next candidate; after output was sent the stream ends with an error+# frame). Providers that queue heavily on their free tiers can pause longer+# than 90s mid-stream — raise this if streamed responses stop early. Set to 0+# to disable the stall watchdog entirely.+# PROVIDER_STREAM_STALL_TIMEOUT_MS=90000+# Wall-clock budget for provider failover, in milliseconds (default: 45000).# A request that keeps failing over stops STARTING new attempts once this much# time has passed and returns the exhaustion error instead (the first attemptdiff --git a/server/src/__tests__/lib/provider-timeout.test.ts b/server/src/__tests__/lib/provider-timeout.test.tsnew file mode 100644index 00000000..58ec6aa1--- /dev/null+++ b/server/src/__tests__/lib/provider-timeout.test.ts@@ -0,0 +1,72 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ DEFAULT_STREAM_STALL_TIMEOUT_MS,+ providerTimeoutEnvName,+ providerTimeoutMs,+ resetTimeoutWarnings,+ streamStallTimeoutMs,+} from '../../lib/provider-timeout.js';++// Per-provider timeout overrides (issue #547, reworked from PR #509).++afterEach(() => {+ delete process.env.PROVIDER_TIMEOUT_NVIDIA;+ delete process.env.PROVIDER_TIMEOUT_GROQ;+ delete process.env.PROVIDER_STREAM_STALL_TIMEOUT_MS;+ resetTimeoutWarnings();+ vi.restoreAllMocks();+});++describe('providerTimeoutEnvName', () => {+ it('upper-cases the platform', () => {+ expect(providerTimeoutEnvName('nvidia')).toBe('PROVIDER_TIMEOUT_NVIDIA');+ expect(providerTimeoutEnvName('aihorde')).toBe('PROVIDER_TIMEOUT_AIHORDE');+ });+});++describe('providerTimeoutMs', () => {+ it('returns the built-in default when the env var is unset', () => {+ expect(providerTimeoutMs('nvidia', 90_000)).toBe(90_000);+ });++ it('lets the env override win over the default', () => {+ process.env.PROVIDER_TIMEOUT_NVIDIA = '300000';+ expect(providerTimeoutMs('nvidia', 90_000)).toBe(300_000);+ });++ it('accepts 0 as "no timeout"', () => {+ process.env.PROVIDER_TIMEOUT_NVIDIA = '0';+ expect(providerTimeoutMs('nvidia', 90_000)).toBe(0);+ });++ it('ignores negative, fractional, and non-numeric values (warns once, keeps default)', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ for (const bad of ['-1', '1.5', 'ninety', '']) {+ process.env.PROVIDER_TIMEOUT_NVIDIA = bad;+ expect(providerTimeoutMs('nvidia', 90_000)).toBe(90_000);+ }+ // '' is treated as unset (no warning); the three malformed values share one+ // env name, so the warn-once gate fires exactly once.+ expect(warn).toHaveBeenCalledTimes(1);+ });++ it('warns on sub-second values that would abort nearly every request, but honors them', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ process.env.PROVIDER_TIMEOUT_GROQ = '500';+ expect(providerTimeoutMs('groq', 60_000)).toBe(500);+ expect(warn).toHaveBeenCalledTimes(1);+ });+});++describe('streamStallTimeoutMs', () => {+ it('defaults to 90s', () => {+ expect(streamStallTimeoutMs()).toBe(DEFAULT_STREAM_STALL_TIMEOUT_MS);+ });++ it('honors PROVIDER_STREAM_STALL_TIMEOUT_MS, including 0 to disable the watchdog', () => {+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_MS = '240000';+ expect(streamStallTimeoutMs()).toBe(240_000);+ process.env.PROVIDER_STREAM_STALL_TIMEOUT_MS = '0';+ expect(streamStallTimeoutMs()).toBe(0);+ });+});diff --git a/server/src/lib/env-drift.ts b/server/src/lib/env-drift.tsindex 3ffc573a..a86a931b 100644--- a/server/src/lib/env-drift.ts+++ b/server/src/lib/env-drift.ts@@ -22,6 +22,7 @@ const KNOWN_UNDOCUMENTED_ENV = new Set([const KNOWN_UNDOCUMENTED_PATTERNS = [/^PROVIDER_DAILY_REQUEST_CAP_[A-Z0-9_]+$/,+ /^PROVIDER_TIMEOUT_[A-Z0-9_]+$/,];export interface EnvDriftReport {diff --git a/server/src/lib/provider-timeout.ts b/server/src/lib/provider-timeout.tsnew file mode 100644index 00000000..11ec2430--- /dev/null+++ b/server/src/lib/provider-timeout.ts@@ -0,0 +1,59 @@+// Per-provider HTTP timeout overrides (issue #547, reworked from PR #509).+//+// PROVIDER_TIMEOUT_<PLATFORM>=<milliseconds> overrides the platform's built-in+// chat timeout (e.g. PROVIDER_TIMEOUT_NVIDIA=300000). 0 disables the timeout+// entirely. Values are read when the provider is constructed — for the built-in+// platforms that means process start, so a change requires a restart.+//+// PROVIDER_STREAM_STALL_TIMEOUT_MS is the streaming counterpart for the+// mid-stream inactivity watchdog (issue #553): how long an SSE stream may go+// without a single byte before the gateway gives up on it. It is global, not+// per-platform: a stall looks the same everywhere, and the per-platform knob+// above already covers the slow-first-byte case.++const warned = new Set<string>();++function warnOnce(name: string, message: string): void {+ if (warned.has(name)) return;+ warned.add(name);+ console.warn(message);+}++function parseTimeoutEnv(name: string, defaultMs: number): number {+ const raw = process.env[name];+ if (raw === undefined || raw.trim() === '') return defaultMs;+ const parsed = Number(raw.trim());+ if (!Number.isInteger(parsed) || parsed < 0) {+ warnOnce(name, `[config] Ignoring ${name}="${raw}": expected a non-negative integer of milliseconds (0 disables the timeout). Using the default ${defaultMs}ms.`);+ return defaultMs;+ }+ if (parsed > 0 && parsed < 1000) {+ warnOnce(name, `[config] ${name}=${parsed}ms is under a second; nearly every request to this provider will abort. Was this meant to be seconds?`);+ }+ return parsed;+}++export function providerTimeoutEnvName(platform: string): string {+ return `PROVIDER_TIMEOUT_${platform.toUpperCase().replace(/[^A-Z0-9]/g, '_')}`;+}++/** Effective chat timeout for a platform: the PROVIDER_TIMEOUT_<PLATFORM> env+ * override when set and valid, else the built-in default. Returns 0 to mean+ * "no timeout" — callers must skip their abort timer for 0, never schedule+ * setTimeout(0). */+export function providerTimeoutMs(platform: string, defaultMs: number): number {+ return parseTimeoutEnv(providerTimeoutEnvName(platform), defaultMs);+}++export const DEFAULT_STREAM_STALL_TIMEOUT_MS = 90_000;++/** Effective mid-stream inactivity timeout (PROVIDER_STREAM_STALL_TIMEOUT_MS,+ * default 90s, 0 disables). Resolved per call so tests can vary the env. */+export function streamStallTimeoutMs(): number {+ return parseTimeoutEnv('PROVIDER_STREAM_STALL_TIMEOUT_MS', DEFAULT_STREAM_STALL_TIMEOUT_MS);+}++/** Test hook: forget which malformed values have already been warned about. */+export function resetTimeoutWarnings(): void {+ warned.clear();+}diff --git a/server/src/providers/aihorde.ts b/server/src/providers/aihorde.tsindex 8b22aff7..986c637d 100644--- a/server/src/providers/aihorde.ts+++ b/server/src/providers/aihorde.ts@@ -7,6 +7,7 @@ import type {} from '@freellmapi/shared/types.js';import { BaseProvider, providerHttpError, type CompletionOptions } from './base.js';import { recordQuotaObservationsFromResponse, type QuotaObservationContext } from '../services/provider-quota.js';+import { providerTimeoutMs } from '../lib/provider-timeout.js';/*** AI Horde — free, community-powered inference served by volunteer workers and@@ -41,7 +42,8 @@ import { recordQuotaObservationsFromResponse, type QuotaObservationContext } froconst ANON_KEY = '0000000000';const MIN_MAX_TOKENS = 16;const DEFAULT_MAX_TOKENS = 512;-const HORDE_TIMEOUT_MS = 120000;+// PROVIDER_TIMEOUT_AIHORDE overrides (#547).+const HORDE_TIMEOUT_MS = providerTimeoutMs('aihorde', 120000);/** Rough token estimate (~4 chars/token) used only to fill usage when the proxy* returns kudos instead of token counts. Good enough for analytics, neverdiff --git a/server/src/providers/base.ts b/server/src/providers/base.tsindex 85f19ffd..8635a760 100644--- a/server/src/providers/base.ts+++ b/server/src/providers/base.ts@@ -9,6 +9,7 @@ import type {import type { QuotaObservationContext } from '../services/provider-quota.js';import type { ExtendedSamplingOptions } from '../lib/sampling-params.js';import { proxyFetch } from '../lib/proxy.js';+import { providerTimeoutMs, streamStallTimeoutMs } from '../lib/provider-timeout.js';/** A provider HTTP error carrying the upstream status and, when the response* included a Retry-After header, the parsed delay so the router can bench the@@ -88,8 +89,15 @@ export abstract class BaseProvider {protected async fetchWithTimeout(url: string,init: RequestInit,- timeoutMs = 15000,+ // Adapters that don't pass a timeout inherit the platform's env override+ // (PROVIDER_TIMEOUT_<PLATFORM>, issue #547) over the historical 15s.+ timeoutMs = providerTimeoutMs(this.platform, 15000),): Promise<Response> {+ // timeoutMs <= 0 means "no timeout" (PROVIDER_TIMEOUT_<PLATFORM>=0).+ // setTimeout(abort, 0) would abort every request on the next macrotask.+ if (timeoutMs <= 0) {+ return proxyFetch(url, init, this.platform, 'chat', timeoutMs);+ }const controller = new AbortController();const timeout = setTimeout(() => controller.abort(), timeoutMs);try {@@ -123,7 +131,12 @@ export abstract class BaseProvider {*/protected async *readSseStream(res: Response,- inactivityTimeoutMs = 90000,+ // The 90s default was hardcoded and silently truncated slow streams — the+ // gateway ended them with an error frame plus a clean [DONE] that OpenAI+ // SDK clients swallow, so responses "just stopped" (issue #553). Operators+ // proxying slow free tiers can now raise it (or 0 to disable) via+ // PROVIDER_STREAM_STALL_TIMEOUT_MS.+ inactivityTimeoutMs = streamStallTimeoutMs(),): AsyncGenerator<ChatCompletionChunk> {const reader = res.body?.getReader();if (!reader) throw new Error('No response body');@@ -135,15 +148,17 @@ export abstract class BaseProvider {try {while (true) {let timer: ReturnType<typeof setTimeout> | undefined;- const result = await Promise.race([- reader.read(),- new Promise<never>((_, reject) => {- timer = setTimeout(- () => reject(new Error(`${this.name} stream stalled: no data for ${inactivityTimeoutMs}ms (timeout)`)),- inactivityTimeoutMs,- );- }),- ]).finally(() => clearTimeout(timer));+ const result = inactivityTimeoutMs <= 0+ ? await reader.read()+ : await Promise.race([+ reader.read(),+ new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error(`${this.name} stream stalled: no data for ${inactivityTimeoutMs}ms (timeout)`)),+ inactivityTimeoutMs,+ );+ }),+ ]).finally(() => clearTimeout(timer));const { done, value } = result;if (done) break;diff --git a/server/src/providers/cloudflare.ts b/server/src/providers/cloudflare.tsindex e5515df3..f1c59895 100644--- a/server/src/providers/cloudflare.ts+++ b/server/src/providers/cloudflare.ts@@ -7,6 +7,7 @@ import { BaseProvider, providerHttpError, type CompletionOptions } from './base.import { extendedBodyParams } from '../lib/sampling-params.js';import { contentToString } from '../lib/content.js';import { recordQuotaObservationsFromResponse, type QuotaObservationContext } from '../services/provider-quota.js';+import { providerTimeoutMs } from '../lib/provider-timeout.js';/*** Cloudflare Workers AI provider.@@ -17,7 +18,8 @@ import { recordQuotaObservationsFromResponse, type QuotaObservationContext } fro// Workers AI hosts reasoning models (@cf/zai-org/glm-4.7-flash) that spend// well over the 15s fetch default before the first byte (live sweep// 2026-07-11: repeated 15s aborts). Matches zhipu/agnes/ollama bumps.-const CHAT_TIMEOUT_MS = 60_000;+// PROVIDER_TIMEOUT_CLOUDFLARE overrides (#547).+const CHAT_TIMEOUT_MS = providerTimeoutMs('cloudflare', 60_000);export class CloudflareProvider extends BaseProvider {readonly platform = 'cloudflare' as const;diff --git a/server/src/providers/google.ts b/server/src/providers/google.tsindex 3f79d40f..87300e14 100644--- a/server/src/providers/google.ts+++ b/server/src/providers/google.ts@@ -11,6 +11,7 @@ import { BaseProvider, providerHttpError, type CompletionOptions } from './base.import { contentToString } from '../lib/content.js';import { proxyFetch } from '../lib/proxy.js';import { recordQuotaObservationsFromResponse, type QuotaObservationContext } from '../services/provider-quota.js';+import { providerTimeoutMs } from '../lib/provider-timeout.js';const API_BASE = 'https://generativelanguage.googleapis.com/v1beta';@@ -535,7 +536,8 @@ export class GoogleProvider extends BaseProvider {constructor(opts: GoogleProviderOptions = {}) {super();- this.timeoutMs = opts.timeoutMs ?? 15000;+ // PROVIDER_TIMEOUT_GOOGLE wins over the registration default (#547).+ this.timeoutMs = providerTimeoutMs('google', opts.timeoutMs ?? 15000);}async chatCompletion(diff --git a/server/src/providers/openai-compat.ts b/server/src/providers/openai-compat.tsindex 7c6dddf8..64e1401f 100644--- a/server/src/providers/openai-compat.ts+++ b/server/src/providers/openai-compat.ts@@ -10,6 +10,7 @@ import { extendedBodyParams } from '../lib/sampling-params.js';import { rescueInlineToolCalls } from '../lib/tool-call-rescue.js';import { repairToolArguments, toolSchemaMap } from '../lib/tool-args.js';import { recordQuotaObservationsFromResponse, type QuotaObservationContext } from '../services/provider-quota.js';+import { providerTimeoutMs } from '../lib/provider-timeout.js';/*** Generic provider for platforms that use an OpenAI-compatible API.@@ -47,7 +48,8 @@ export class OpenAICompatProvider extends BaseProvider {this.baseUrl = opts.baseUrl;this.extraHeaders = opts.extraHeaders ?? {};this.validateUrl = opts.validateUrl;- this.timeoutMs = opts.timeoutMs ?? 60_000;+ // PROVIDER_TIMEOUT_<PLATFORM> wins over the registration default (#547).+ this.timeoutMs = providerTimeoutMs(opts.platform, opts.timeoutMs ?? 60_000);this.keyless = opts.keyless ?? false;this.forceSingleToolCall = opts.forceSingleToolCall ?? false;}@@ -86,6 +88,19 @@ export class OpenAICompatProvider extends BaseProvider {}));}+ /** Extract the useful text from an upstream error body. Most providers put it+ * at error.message, but NVIDIA NIM answers RFC7807-style ({"title": ...,+ * "detail": "Function id '...': DEGRADED function cannot be invoked"}) — the+ * old error.message-only read collapsed that to "Bad Request", so neither the+ * logs nor the error classifier could ever see the DEGRADED marker (#522). */+ private upstreamErrorText(errBody: unknown, res: Response): string {+ const e = errBody as { error?: { message?: unknown }; detail?: unknown; title?: unknown };+ if (typeof e?.error?.message === 'string' && e.error.message) return e.error.message;+ if (typeof e?.detail === 'string' && e.detail) return e.detail;+ if (typeof e?.title === 'string' && e.title) return e.title;+ return res.statusText;+ }+/** Keyless providers (Kilo's anonymous free tier) must send NO Authorization* header — a stored sentinel like `Bearer no-key` could be treated as an* invalid key. Everyone else sends the bearer as usual. */@@ -187,7 +202,7 @@ export class OpenAICompatProvider extends BaseProvider {out._routed_via = { platform: this.platform, model: modelId };return out;}- throw providerHttpError(res, `${this.name} API error ${res.status}: ${(err as any).error?.message ?? res.statusText}`);+ throw providerHttpError(res, `${this.name} API error ${res.status}: ${this.upstreamErrorText(err, res)}`);}let data: ChatCompletionResponse;@@ -295,7 +310,7 @@ export class OpenAICompatProvider extends BaseProvider {yield { ...base, choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }] };return;}- throw providerHttpError(res, `${this.name} API error ${res.status}: ${(err as any).error?.message ?? res.statusText}`);+ throw providerHttpError(res, `${this.name} API error ${res.status}: ${this.upstreamErrorText(err, res)}`);}yield* this.readSseStream(res);