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): min-context-window pool floor with one-switch presets (#1445)
suantea (asuan_suan)2763f5bd2452
diff --git a/server/src/__tests__/lib/min-context-window.test.ts b/server/src/__tests__/lib/min-context-window.test.tsnew file mode 100644index 00000000..e65968a6--- /dev/null+++ b/server/src/__tests__/lib/min-context-window.test.ts@@ -0,0 +1,77 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import {+ MIN_CONTEXT_WINDOW_SETTING,+ MIN_CONTEXT_WINDOW_PRESETS,+ minContextWindowFloor,+ passesContextWindowFloor,+} from '../../lib/min-context-window.js';+import { initDb, getDb, setSetting, getSetting } from '../../db/index.js';++beforeEach(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+});++afterEach(() => {+ getDb().prepare('DELETE FROM settings WHERE key = ?').run(MIN_CONTEXT_WINDOW_SETTING);+});++describe('minContextWindowFloor', () => {+ it('is disabled by default (off / unset)', () => {+ expect(minContextWindowFloor()).toBeNull();+ setSetting(MIN_CONTEXT_WINDOW_SETTING, 'off');+ expect(minContextWindowFloor()).toBeNull();+ });++ it('resolves the named presets to their token counts', () => {+ for (const [key, tokens] of Object.entries(MIN_CONTEXT_WINDOW_PRESETS)) {+ setSetting(MIN_CONTEXT_WINDOW_SETTING, key);+ expect(minContextWindowFloor()).toBe(tokens);+ }+ });++ it('is case-insensitive', () => {+ setSetting(MIN_CONTEXT_WINDOW_SETTING, '128K');+ expect(minContextWindowFloor()).toBe(131_072);+ });++ it('treats garbage as disabled so a bad value can never empty the pool', () => {+ for (const raw of ['banana', '-1', '1.5', 'NaN', 'Infinity', '{}']) {+ setSetting(MIN_CONTEXT_WINDOW_SETTING, raw);+ expect(minContextWindowFloor()).toBeNull();+ }+ });+});++describe('passesContextWindowFloor', () => {+ it('passes everything while disabled', () => {+ expect(passesContextWindowFloor(8_000)).toBe(true);+ expect(passesContextWindowFloor(null)).toBe(true);+ });++ it('is upward-compatible: 128k keeps 512k and 1M models', () => {+ setSetting(MIN_CONTEXT_WINDOW_SETTING, '128k');+ expect(passesContextWindowFloor(131_072)).toBe(true);+ expect(passesContextWindowFloor(524_288)).toBe(true);+ expect(passesContextWindowFloor(1_048_576)).toBe(true);+ expect(passesContextWindowFloor(32_768)).toBe(false);+ });++ it('never filters an unknown (null) window', () => {+ setSetting(MIN_CONTEXT_WINDOW_SETTING, '1m');+ expect(passesContextWindowFloor(null)).toBe(true);+ expect(passesContextWindowFloor(undefined)).toBe(true);+ });++ it('rejects models strictly below the floor', () => {+ setSetting(MIN_CONTEXT_WINDOW_SETTING, '32k');+ expect(passesContextWindowFloor(16_000)).toBe(false);+ expect(passesContextWindowFloor(32_768)).toBe(true);+ });++ it('reads through the same settings row the PUT endpoint writes', () => {+ setSetting(MIN_CONTEXT_WINDOW_SETTING, '512k');+ expect(getSetting(MIN_CONTEXT_WINDOW_SETTING)).toBe('512k');+ expect(minContextWindowFloor()).toBe(524_288);+ });+});diff --git a/server/src/lib/min-context-window.ts b/server/src/lib/min-context-window.tsnew file mode 100644index 00000000..de264204--- /dev/null+++ b/server/src/lib/min-context-window.ts@@ -0,0 +1,54 @@+import { getSetting } from '../db/index.js';++// Operator-facing context-window floor for the ROUTING POOL (issue #1442):+// a one-switch gate that excludes small-window models entirely, because the+// smallest free tiers (32k and below) fail real agent workloads before any+// rate limit does. Upward-compatible by construction — the floor is a minimum,+// so 128k keeps 512k and 1M models — and distinct from the per-request+// fitsContextWindow check, which only compares THIS request's estimated size.+//+// Stored as a plain settings string ('off' | '32k' | '128k' | '512k' | '1m'),+// parsed on every call: cheap (better-sqlite3 sync read), picks up dashboard+// changes without a restart, and a garbage value disables the gate rather than+// emptying the pool.++export const MIN_CONTEXT_WINDOW_SETTING = 'min_context_window';++// The named presets. '1m' is 1,048,576 (the binary MiB-scale window the+// largest catalog rows actually advertise), not a round 1,000,000 — matching+// the catalog keeps the gate consistent with what /v1/models publishes.+export const MIN_CONTEXT_WINDOW_PRESETS: Record<string, number> = {+ '32k': 32_768,+ '128k': 131_072,+ '512k': 524_288,+ '1m': 1_048_576,+};++/** The configured pool floor in tokens, or null when disabled ('off'/unset).+ * A null context_window on a model means "unknown" and is NEVER filtered —+ * the same convention fitsContextWindow uses, so models the catalog has no+ * window for can't be silently mass-excluded by a typo'd floor. */+export function minContextWindowFloor(): number | null {+ let raw: string | undefined;+ try {+ raw = getSetting(MIN_CONTEXT_WINDOW_SETTING);+ } catch {+ return null; // DB not ready — never throw on the proxy hot path+ }+ if (!raw) return null;+ const value = raw.trim().toLowerCase();+ if (!value || value === 'off' || value === '0') return null;+ const preset = MIN_CONTEXT_WINDOW_PRESETS[value];+ if (preset !== undefined) return preset;+ const n = Number(value);+ return Number.isInteger(n) && n > 0 ? n : null;+}++/** True when a model with this advertised window may serve at all under the+ * configured floor. Unknown windows (null/undefined) always pass. */+export function passesContextWindowFloor(contextWindow: number | null | undefined): boolean {+ const floor = minContextWindowFloor();+ if (floor == null) return true;+ if (contextWindow == null) return true;+ return contextWindow >= floor;+}diff --git a/server/src/routes/settings.ts b/server/src/routes/settings.tsindex 5d99132e..d459a42b 100644--- a/server/src/routes/settings.ts+++ b/server/src/routes/settings.ts@@ -10,6 +10,7 @@ import { isUnifyEnabled, setUnifyEnabled, getUnifyOverrides, setUnifyOverrides,import { getClaudeModelMap, setClaudeModelMap } from '../services/anthropic-map.js';import { getGeminiModelMap, setGeminiModelMap } from '../services/gemini-map.js';import { getOllamaEmulationMode } from './ollama.js';+import { MIN_CONTEXT_WINDOW_SETTING, MIN_CONTEXT_WINDOW_PRESETS } from '../lib/min-context-window.js';import { UPDATE_CHECK_SETTING, isAutoUpdateCheckEnabled } from './update.js';import { listUrlTokens, mintUrlToken, revokeUrlToken } from '../services/url-tokens.js';import {@@ -290,6 +291,38 @@ settingsRouter.put('/output-limit', (req: Request, res: Response) => {res.json(outputLimitState());});+// Get the min-context-window pool floor ('off' = disabled, or a preset key+// like '128k'). See lib/min-context-window.ts minContextWindowFloor().+settingsRouter.get('/min-context-window', (_req: Request, res: Response) => {+ let value = 'off';+ try {+ value = getSetting(MIN_CONTEXT_WINDOW_SETTING) || 'off';+ } catch {+ // DB not ready — report the disabled default rather than failing.+ }+ res.json({ value, presets: MIN_CONTEXT_WINDOW_PRESETS });+});++const minContextWindowPutSchema = z.object({+ value: z.union([+ z.literal('off'),+ z.string().regex(/^(32k|128k|512k|1m)$/i),+ ]),+});++// Update the min-context-window pool floor. Upward-compatible by construction:+// '128k' keeps every model at or above 128k (including 512k and 1M). Takes+// effect on the next routed request — no restart.+settingsRouter.put('/min-context-window', (req: Request, res: Response) => {+ const parsed = minContextWindowPutSchema.safeParse(req.body);+ if (!parsed.success) {+ res.status(400).json({ error: { message: "Invalid min context window: value must be 'off', '32k', '128k', '512k', or '1m'", type: 'invalid_request_error' } });+ return;+ }+ setSetting(MIN_CONTEXT_WINDOW_SETTING, parsed.data.value.toLowerCase());+ res.json({ value: parsed.data.value.toLowerCase(), presets: MIN_CONTEXT_WINDOW_PRESETS });+});+// Get the request guardrails (per-request token budget + failover circuit// breaker). Both default to 0 = disabled; see lib/guardrails.ts.settingsRouter.get('/guardrails', (_req: Request, res: Response) => {diff --git a/server/src/services/router.ts b/server/src/services/router.tsindex c5ab8338..e956b769 100644--- a/server/src/services/router.ts+++ b/server/src/services/router.ts@@ -32,6 +32,7 @@ import { applyModelWeightOverride, getModelWeightOverrides } from './model-weighimport { modelsWithOverriddenField, getCatalogModelTombstone } from './model-state.js';import { parseBudget } from '../lib/budget.js';import { platformDropsResponseFormat } from '../lib/sampling-params.js';+import { passesContextWindowFloor } from '../lib/min-context-window.js';import { isUnifyEnabled, getModelGroups, resolveRequestedIdForDispatch } from './model-groups.js';import { getActiveProfileId } from './profile-models.js';import { customEndpointKeyIds } from './custom-endpoint.js';@@ -1807,8 +1808,11 @@ const TRIM_GUARDED_PLATFORMS = new Set(['github']);/** True when `estimatedTokens` fits the RAW advertised window (null window =* unknown, never filtered — same convention as the auto-router). This is the- * comparison /v1/models publishes and the soft-preference fallback tier. */+ * comparison /v1/models publishes and the soft-preference fallback tier.+ * The operator's min-context-window floor applies here too: the fallback tier+ * must not reintroduce a model the floor excluded from the main chain. */export function fitsContextWindowStrict(contextWindow: number | null | undefined, estimatedTokens: number): boolean {+ if (!passesContextWindowFloor(contextWindow)) return false;return contextWindow == null || estimatedTokens <= contextWindow;}@@ -1816,8 +1820,12 @@ export function fitsContextWindowStrict(contextWindow: number | null | undefined* margin. The chars/4 heuristic portion is scaled by the factor; an explicit* output reserve derived from the client's max_tokens (`routingReserveTokens`)* is already an exact count and is added UNSCALED (#956 review). Trim-guarded- * platforms compare strictly — their guard guarantees the fit. */+ * platforms compare strictly — their guard guarantees the fit. Also enforces+ * the operator's min-context-window floor (lib/min-context-window.ts): a model+ * below the configured preset is excluded from every chain, while an unknown+ * window (null) always passes. */export function fitsContextWindow(platform: string, contextWindow: number | null | undefined, estimatedTokens: number, exactOutputReserve = 0): boolean {+ if (!passesContextWindowFloor(contextWindow)) return false;if (contextWindow == null) return true;// Raw advertised comparison first — the margin can only shrink eligibility.if (estimatedTokens > contextWindow) return false;