Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : server/next/providers.ts9 * Module : server10 * Repository : https://git.spboucher.ai/vquant11 * Project Website : https://vquant.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier : MIT34 * License : MIT License35 * License File : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Provider registry (contract: docs/next/CONTRACT.md §2.1).47 *48 * Two sources are merged, and nothing else:49 * - a CURATED table of the models this app already ships (ids of routes/validation.ts, labels and tiers of50 * client/src/lib/models.ts, prices and output limits of services/claude/tokenManagement.ts);51 * - what each provider's own listing endpoint returns with the server's key, cached 6 h.52 *53 * No model id, price or context size is written here from memory: a figure that neither the repository nor the54 * provider gives is `null`. A curated id that the provider's listing does not return is `available: false`.55 * Discovery never throws to a route: a failed refresh keeps the previous listing (stale-while-error) and reports56 * `ok: false` with the reason.57 */58import type { Express, Request, Response } from "express";59import { OPENAI_COMPAT_SPECS, knownClaudeSpecs } from "../services/claude/tokenManagement";6061export type ProviderId = "anthropic" | "openai" | "google" | "openrouter" | "local";62export const PROVIDER_IDS: ProviderId[] = ["anthropic", "openai", "google", "openrouter", "local"];63export type ModelTier = "frontier" | "balanced" | "fast";6465export interface ModelPricing {66 inputPerMTok: number;67 outputPerMTok: number;68}6970export interface RegistryModel {71 id: string;72 label: string;73 provider: ProviderId;74 tier: ModelTier;75 contextWindow: number | null;76 maxOutput: number | null;77 pricing: ModelPricing | null;78 capabilities: { tools: boolean; vision: boolean; reasoning: boolean; streaming: boolean };79 available: boolean;80 source: "api" | "curated";81 selectable: boolean;82}8384export interface RegistryProvider {85 id: ProviderId;86 name: string;87 configured: boolean;88 ok: boolean;89 checkedAt: number;90 error: string | null;91 logo: string;92 models: RegistryModel[];93}9495/** One model as a provider's listing describes it (`id` is the provider's own id, without our prefix). */96export interface DiscoveredModel {97 id: string;98 label?: string;99 contextWindow?: number | null;100 maxOutput?: number | null;101 pricing?: ModelPricing | null;102 tools?: boolean | null;103 vision?: boolean | null;104 reasoning?: boolean | null;105}106107export interface ProviderState {108 /** last attempt (0 = never) */109 checkedAt: number;110 /** last success (0 = never) */111 fetchedAt: number;112 ok: boolean;113 error: string | null;114 /** the last listing that succeeded; null until one does */115 models: DiscoveredModel[] | null;116}117118type Env = Record<string, string | undefined>;119type FetchLike = (url: string, init?: { headers?: Record<string, string>; signal?: AbortSignal }) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>;120121export const DEFAULT_MODEL_ID = "claude-fable-5-2";122export const AUTO_MODEL = { id: "auto", label: "Auto" } as const;123const CACHE_MS = 6 * 3_600_000;124/** After a failed refresh, wait this long before asking the provider again. */125const RETRY_MS = 5 * 60_000;126const DISCOVERY_TIMEOUT_MS = 8_000;127128// ─── Curated table ───────────────────────────────────────────────────────────129// Exactly what the repository already knew before discovery existed. `tier` is the `power` column of130// client/src/lib/models.ts (3 → frontier, 2 → balanced, 1 → fast); `oneM` is its "1M" context badge.131// Vision: the chat has always forwarded image attachments to every one of these models.132interface CuratedRow {133 id: string;134 label: string;135 provider: ProviderId;136 tier: ModelTier;137 oneM?: boolean;138}139const CURATED_ROWS: CuratedRow[] = [140 { id: "claude-fable-5-2", label: "Fable 5.2", provider: "anthropic", tier: "frontier", oneM: true },141 { id: "claude-opus-5-5", label: "Opus 5.5", provider: "anthropic", tier: "frontier", oneM: true },142 { id: "claude-sonnet-5-5", label: "Sonnet 5.5", provider: "anthropic", tier: "balanced", oneM: true },143 { id: "claude-haiku-5-5", label: "Haiku 5.5", provider: "anthropic", tier: "fast", oneM: true },144 { id: "claude-opus-4-8", label: "Opus 4.8", provider: "anthropic", tier: "frontier", oneM: true },145 { id: "claude-sonnet-4-6", label: "Sonnet 4.6", provider: "anthropic", tier: "balanced", oneM: true },146147 { id: "gpt-5.6-sol", label: "GPT-5.6 Sol", provider: "openai", tier: "frontier" },148 { id: "gpt-5.6-terra", label: "GPT-5.6 Terra", provider: "openai", tier: "balanced" },149 { id: "gpt-5.6-luna", label: "GPT-5.6 Luna", provider: "openai", tier: "balanced" },150 { id: "gpt-5.5", label: "GPT-5.5", provider: "openai", tier: "frontier" },151 { id: "gpt-5.4", label: "GPT-5.4", provider: "openai", tier: "balanced", oneM: true },152 { id: "gpt-5.2", label: "GPT-5.2", provider: "openai", tier: "balanced" },153 { id: "gpt-5.1", label: "GPT-5.1", provider: "openai", tier: "balanced" },154 { id: "gpt-5", label: "GPT-5", provider: "openai", tier: "balanced" },155 { id: "gpt-5-mini", label: "GPT-5 Mini", provider: "openai", tier: "fast" },156 { id: "gpt-5-nano", label: "GPT-5 Nano", provider: "openai", tier: "fast" },157 { id: "gpt-4.1", label: "GPT-4.1", provider: "openai", tier: "balanced", oneM: true },158 { id: "gpt-4.1-mini", label: "GPT-4.1 Mini", provider: "openai", tier: "fast" },159160 { id: "gemini-3.5-flash", label: "Gemini 3.5 Flash", provider: "google", tier: "balanced" },161 { id: "gemini-3.1-pro-preview", label: "Gemini 3.1 Pro", provider: "google", tier: "frontier" },162 { id: "gemini-3-flash-preview", label: "Gemini 3 Flash", provider: "google", tier: "balanced" },163 { id: "gemini-3.1-flash-lite", label: "Gemini 3.1 Flash Lite", provider: "google", tier: "fast" },164];165166let curatedCache: RegistryModel[] | null = null;167/** The curated models with the prices and limits the model services use. */168export function curatedModels(): RegistryModel[] {169 if (curatedCache) return curatedCache;170 const claude = knownClaudeSpecs();171 curatedCache = CURATED_ROWS.map((row) => {172 const c = claude[row.id];173 const o = OPENAI_COMPAT_SPECS[row.id];174 const pricing = c ? { inputPerMTok: c.input, outputPerMTok: c.output } : o ? { inputPerMTok: o.input, outputPerMTok: o.output } : null;175 return {176 id: row.id,177 label: row.label,178 provider: row.provider,179 tier: row.tier,180 contextWindow: row.oneM ? 1_000_000 : null,181 maxOutput: c?.maxOutput ?? o?.maxOut ?? null,182 pricing,183 capabilities: {184 tools: true,185 vision: true,186 // Claude: adaptive thinking in the spec table; gpt-5.x and gemini-3.x are sent as reasoning models by openaiService.187 reasoning: c ? c.thinking === "adaptive" : /^(gpt-5|gemini-3)/.test(row.id),188 streaming: true,189 },190 available: true,191 source: "curated" as const,192 selectable: true,193 };194 });195 return curatedCache;196}197export const CURATED_MODEL_IDS: readonly string[] = CURATED_ROWS.map((r) => r.id);198199// ─── Providers ───────────────────────────────────────────────────────────────200export function providerName(id: ProviderId, env: Env = process.env): string {201 if (id === "local") return (env.LOCAL_LLM_NAME ?? "").trim() || "Local";202 return { anthropic: "Anthropic", openai: "OpenAI", google: "Google", openrouter: "OpenRouter" }[id];203}204205export function providerConfigured(id: ProviderId, env: Env = process.env): boolean {206 const has = (k: string) => !!(env[k] ?? "").trim();207 return id === "anthropic" ? has("ANTHROPIC_API_KEY") : id === "openai" ? has("OPENAI_API_KEY") : id === "google" ? has("GEMINI_API_KEY") : id === "openrouter" ? has("OPENROUTER_API_KEY") : has("LOCAL_LLM_BASE_URL");208}209210/** Base of the local OpenAI-compatible API, always ending in /v1 (the variable may or may not include it). */211export function localBaseUrl(env: Env = process.env): string | null {212 const raw = (env.LOCAL_LLM_BASE_URL ?? "").trim().replace(/\/+$/, "");213 if (!raw) return null;214 return /\/v\d+$/.test(raw) ? raw : `${raw}/v1`;215}216217/** Which provider serves a model id. Ids without a prefix keep the rule the chat always used. */218export function providerOf(modelId: string): ProviderId {219 if (modelId.startsWith("openrouter:")) return "openrouter";220 if (modelId.startsWith("local:")) return "local";221 if (modelId.startsWith("gemini-")) return "google";222 if (modelId.startsWith("gpt-")) return "openai";223 return curatedModels().find((m) => m.id === modelId)?.provider ?? "anthropic";224}225226/** The id the provider itself knows (our `openrouter:` / `local:` prefix removed). */227export function upstreamModelId(modelId: string): string {228 return modelId.replace(/^(openrouter|local):/, "");229}230231// ─── Discovery ───────────────────────────────────────────────────────────────232const num = (v: unknown): number | null => {233 const n = typeof v === "string" && v.trim() !== "" ? Number(v) : typeof v === "number" ? v : NaN;234 return Number.isFinite(n) ? n : null;235};236const posInt = (v: unknown): number | null => {237 const n = num(v);238 return n !== null && n > 0 ? Math.round(n) : null;239};240241async function getJson(fetchImpl: FetchLike, url: string, headers: Record<string, string>, timeoutMs: number): Promise<any> {242 const res = await fetchImpl(url, { headers, signal: AbortSignal.timeout(timeoutMs) });243 if (!res.ok) throw new Error(`HTTP ${res.status}`);244 return res.json();245}246247/** OpenRouter prices are USD per token, as strings; a negative value marks a price decided at request time. */248export function openRouterPricing(p: any): ModelPricing | null {249 const input = num(p?.prompt);250 const output = num(p?.completion);251 if (input === null || output === null || input < 0 || output < 0) return null;252 return { inputPerMTok: +(input * 1e6).toPrecision(12), outputPerMTok: +(output * 1e6).toPrecision(12) };253}254255/** Asks one provider for its models. Throws on any failure (the caller keeps the previous listing). */256export async function fetchProviderModels(id: ProviderId, opts: { fetchImpl?: FetchLike; env?: Env; timeoutMs?: number } = {}): Promise<DiscoveredModel[]> {257 const env = opts.env ?? process.env;258 const f = opts.fetchImpl ?? (fetch as unknown as FetchLike);259 const t = opts.timeoutMs ?? DISCOVERY_TIMEOUT_MS;260 if (id === "anthropic") {261 const out: DiscoveredModel[] = [];262 let after = "";263 for (let page = 0; page < 5; page++) {264 const body = await getJson(f, `https://api.anthropic.com/v1/models?limit=1000${after ? `&after_id=${encodeURIComponent(after)}` : ""}`, { "x-api-key": env.ANTHROPIC_API_KEY ?? "", "anthropic-version": "2023-06-01" }, t);265 for (const m of Array.isArray(body?.data) ? body.data : []) {266 if (typeof m?.id !== "string") continue;267 out.push({ id: m.id, label: typeof m.display_name === "string" ? m.display_name : undefined, contextWindow: posInt(m.max_input_tokens), maxOutput: posInt(m.max_tokens) });268 }269 if (!body?.has_more || typeof body?.last_id !== "string") break;270 after = body.last_id;271 }272 return out;273 }274 if (id === "openai") {275 const body = await getJson(f, "https://api.openai.com/v1/models", { Authorization: `Bearer ${env.OPENAI_API_KEY ?? ""}` }, t);276 return (Array.isArray(body?.data) ? body.data : []).filter((m: any) => typeof m?.id === "string").map((m: any) => ({ id: m.id }));277 }278 if (id === "google") {279 const out: DiscoveredModel[] = [];280 let token = "";281 for (let page = 0; page < 5; page++) {282 const body = await getJson(f, `https://generativelanguage.googleapis.com/v1beta/models?pageSize=1000${token ? `&pageToken=${encodeURIComponent(token)}` : ""}`, { "x-goog-api-key": env.GEMINI_API_KEY ?? "" }, t);283 for (const m of Array.isArray(body?.models) ? body.models : []) {284 if (typeof m?.name !== "string") continue;285 // Only models that generate content: the listing also carries embedding and other endpoints.286 if (Array.isArray(m.supportedGenerationMethods) && !m.supportedGenerationMethods.includes("generateContent")) continue;287 out.push({ id: m.name.replace(/^models\//, ""), label: typeof m.displayName === "string" ? m.displayName : undefined, contextWindow: posInt(m.inputTokenLimit), maxOutput: posInt(m.outputTokenLimit) });288 }289 if (typeof body?.nextPageToken !== "string" || !body.nextPageToken) break;290 token = body.nextPageToken;291 }292 return out;293 }294 if (id === "openrouter") {295 const body = await getJson(f, "https://openrouter.ai/api/v1/models", { Authorization: `Bearer ${env.OPENROUTER_API_KEY ?? ""}` }, t);296 return (Array.isArray(body?.data) ? body.data : [])297 .filter((m: any) => typeof m?.id === "string")298 .map((m: any): DiscoveredModel => {299 const params: unknown[] = Array.isArray(m.supported_parameters) ? m.supported_parameters : [];300 const inputs: unknown[] = Array.isArray(m.architecture?.input_modalities) ? m.architecture.input_modalities : [];301 return {302 id: m.id,303 label: typeof m.name === "string" ? m.name : undefined,304 contextWindow: posInt(m.context_length),305 maxOutput: posInt(m.top_provider?.max_completion_tokens),306 pricing: openRouterPricing(m.pricing),307 tools: params.includes("tools"),308 vision: inputs.includes("image"),309 reasoning: params.includes("reasoning") || params.includes("include_reasoning"),310 };311 });312 }313 const base = localBaseUrl(env);314 if (!base) throw new Error("LOCAL_LLM_BASE_URL is not set");315 const key = (env.LOCAL_LLM_API_KEY ?? "").trim();316 const body = await getJson(f, `${base}/models`, key ? { Authorization: `Bearer ${key}` } : {}, t);317 return (Array.isArray(body?.data) ? body.data : []).filter((m: any) => typeof m?.id === "string").map((m: any) => ({ id: m.id }));318}319320const emptyState = (): ProviderState => ({ checkedAt: 0, fetchedAt: 0, ok: false, error: null, models: null });321const states = new Map<ProviderId, ProviderState>();322const inflight = new Map<ProviderId, Promise<void>>();323const stateOf = (id: ProviderId): ProviderState => states.get(id) ?? emptyState();324325function needsRefresh(s: ProviderState, now: number): boolean {326 if (s.checkedAt === 0) return true;327 if (!s.ok) return now - s.checkedAt > RETRY_MS;328 return now - s.fetchedAt > CACHE_MS;329}330331/** A provider message may quote the request: never let a key through, keep it short. */332function safeError(e: unknown): string {333 const raw = String((e as Error)?.name === "TimeoutError" ? "timed out" : (e as Error)?.message ?? e);334 return raw.replace(/(sk-|key=|Bearer\s+)[A-Za-z0-9_\-.]{6,}/g, "$1…").slice(0, 160);335}336337async function refreshProvider(id: ProviderId, opts: { fetchImpl?: FetchLike; env?: Env; now?: () => number }): Promise<void> {338 const now = opts.now ?? Date.now;339 const prev = stateOf(id);340 try {341 const models = await fetchProviderModels(id, opts);342 states.set(id, { checkedAt: now(), fetchedAt: now(), ok: true, error: null, models });343 } catch (e) {344 // Stale-while-error: the last good listing stays in use.345 states.set(id, { ...prev, checkedAt: now(), ok: false, error: safeError(e) });346 }347}348349/**350 * Refreshes the listings that are due (never asked, older than 6 h, or failed more than 5 min ago). Never throws.351 * Concurrent callers share the request in flight.352 */353export async function refreshRegistry(opts: { force?: boolean; fetchImpl?: FetchLike; env?: Env; now?: () => number } = {}): Promise<void> {354 const env = opts.env ?? process.env;355 const now = (opts.now ?? Date.now)();356 await Promise.all(357 PROVIDER_IDS.filter((id) => providerConfigured(id, env) && (opts.force || needsRefresh(stateOf(id), now))).map((id) => {358 let p = inflight.get(id);359 if (!p) {360 p = refreshProvider(id, opts).finally(() => inflight.delete(id));361 inflight.set(id, p);362 }363 return p;364 }),365 );366}367368// ─── Merge ───────────────────────────────────────────────────────────────────369/** OpenRouter does not publish a tier: it is read from the output price (documented, deterministic thresholds). */370function tierFromPricing(p: ModelPricing | null | undefined): ModelTier {371 if (!p) return "balanced";372 return p.outputPerMTok >= 15 ? "frontier" : p.outputPerMTok <= 2 ? "fast" : "balanced";373}374375const NATIVE_CHAT_ID: Partial<Record<ProviderId, RegExp>> = { openai: /^(gpt-|o\d|chatgpt-)/, google: /^gemini-/ };376377/** The registry entry of one provider from its curated models and its listing. Pure. */378export function mergeProvider(id: ProviderId, state: ProviderState, env: Env = process.env): RegistryProvider {379 const configured = providerConfigured(id, env);380 const listed = state.models ? new Map(state.models.map((m) => [m.id, m])) : null;381 const models: RegistryModel[] = [];382383 for (const c of curatedModels().filter((m) => m.provider === id)) {384 const live = listed?.get(c.id);385 // Before any listing has succeeded the curated models stay usable: an outage of a listing endpoint at boot386 // must not lock the chat. Once a listing exists, it decides.387 const available = configured && (listed ? !!live : true);388 models.push({ ...c, contextWindow: c.contextWindow ?? live?.contextWindow ?? null, maxOutput: c.maxOutput ?? live?.maxOutput ?? null, available, selectable: available && c.capabilities.tools });389 }390391 const curatedIds = new Set(models.map((m) => m.id));392 for (const d of state.models ?? []) {393 if (curatedIds.has(d.id)) continue;394 if (NATIVE_CHAT_ID[id] && !NATIVE_CHAT_ID[id]!.test(d.id)) continue;395 const prefixed = id === "openrouter" || id === "local";396 // Tool support: OpenRouter declares it per model. A local endpoint is the owner's own choice of model and is397 // offered as declared by them. For the three native providers, a model the app was never run with is listed398 // but not selectable: nothing tells us it accepts this app's tool loop.399 const tools = id === "openrouter" ? d.tools === true : id === "local";400 models.push({401 id: prefixed ? `${id}:${d.id}` : d.id,402 label: d.label || d.id,403 provider: id,404 tier: id === "openrouter" ? tierFromPricing(d.pricing) : "balanced",405 contextWindow: d.contextWindow ?? null,406 maxOutput: d.maxOutput ?? null,407 pricing: d.pricing ?? null,408 capabilities: { tools, vision: d.vision === true, reasoning: d.reasoning === true, streaming: true },409 available: configured,410 source: "api",411 selectable: configured && tools,412 });413 }414415 return { id, name: providerName(id, env), configured, ok: configured && state.ok, checkedAt: state.checkedAt, error: configured ? state.error : null, logo: `/brand/providers/${id}.svg`, models };416}417418/** The registry as known right now (no network). */419export function registrySnapshot(env: Env = process.env): RegistryProvider[] {420 return PROVIDER_IDS.map((id) => mergeProvider(id, stateOf(id), env));421}422423/** The registry after making sure every configured provider has been asked at least once; stale listings refresh in the background. */424export async function getRegistry(): Promise<RegistryProvider[]> {425 const now = Date.now();426 const never = PROVIDER_IDS.some((id) => providerConfigured(id) && stateOf(id).checkedAt === 0);427 if (never) await refreshRegistry();428 else if (PROVIDER_IDS.some((id) => providerConfigured(id) && needsRefresh(stateOf(id), now))) void refreshRegistry();429 return registrySnapshot();430}431432export function allModels(registry: RegistryProvider[] = registrySnapshot()): RegistryModel[] {433 return registry.flatMap((p) => p.models);434}435436export function findModel(id: string): RegistryModel | undefined {437 return allModels().find((m) => m.id === id);438}439440/**441 * Whether the chat may run on this id. Curated ids need no network (they stay selectable until a listing says442 * otherwise); `openrouter:` and `local:` ids exist only once their provider has listed them.443 */444export function isSelectableModel(id: string | undefined | null): boolean {445 if (!id) return false;446 if (id === AUTO_MODEL.id) return true;447 const m = findModel(id);448 if (!m) return false;449 // A curated id is refused only when its provider's listing says it is gone. A missing key is not a reason to450 // swap the model silently: the call then fails with the provider's own message, as it always did.451 if (m.source === "curated") {452 const listed = stateOf(m.provider).models;453 return !listed || listed.some((d) => d.id === id);454 }455 return m.selectable;456}457458/** Price of a model when the repository or its provider gives one; null otherwise (never estimated). */459export function pricingFor(modelId: string): ModelPricing | null {460 return findModel(modelId)?.pricing ?? null;461}462463/** Test hooks: replace or clear the discovery state. */464export function __setProviderState(id: ProviderId, state: Partial<ProviderState> | null): void {465 if (state === null) states.delete(id);466 else states.set(id, { ...emptyState(), ...state });467}468export function __resetRegistry(): void {469 states.clear();470 inflight.clear();471}472473// ─── Routes ──────────────────────────────────────────────────────────────────474export function registerModelRoutes(app: Express): void {475 // Warm the listings at boot so the first chat request does not wait on five providers.476 if (process.env.NODE_ENV !== "test" && !process.env.VITEST) void refreshRegistry();477478 app.get("/api/v2/models", async (_req: Request, res: Response) => {479 const providers = await getRegistry();480 res.set("Cache-Control", "private, no-store").json({ default: DEFAULT_MODEL_ID, auto: AUTO_MODEL, providers });481 });482483 app.get("/api/v2/models/route", async (req: Request, res: Response) => {484 // Imported on demand so that the registry itself (used by request validation and by tests) stays free of the485 // access layer and of the router.486 const [{ previewRoute }, { currentUser }] = await Promise.all([import("./modelRouter"), import("../access")]);487 const mode = String(req.query.mode ?? "standard");488 if (!["fast", "standard", "deep", "ultra", "research"].includes(mode)) return res.status(400).json({ error: "mode must be fast, standard, deep, ultra or research" });489 const vision = ["1", "true", "yes"].includes(String(req.query.vision ?? "").toLowerCase());490 const decision = await previewRoute(currentUser(req).id, { mode: mode as "fast" | "standard" | "deep" | "ultra" | "research", vision, query: String(req.query.q ?? "").slice(0, 10_000) });491 res.set("Cache-Control", "private, no-store").json(decision);492 });493}494