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
refactor(db): introduce Db/DbStatement/DbFactory interfaces (#397)
LoneRifle4a558d975cca
diff --git a/server/src/__tests__/db/factory-injection.test.ts b/server/src/__tests__/db/factory-injection.test.tsnew file mode 100644index 00000000..da34c7bb--- /dev/null+++ b/server/src/__tests__/db/factory-injection.test.ts@@ -0,0 +1,38 @@+import { describe, it, expect, vi } from 'vitest';+import { connectDb } from '../../db/index.js';+import type { Db, DbFactory } from '../../db/types.js';++// A minimal in-memory stub that satisfies the Db interface.+function makeStubDb(): Db {+ const store = new Map<string, unknown>();+ return {+ prepare: vi.fn().mockReturnValue({+ get: vi.fn(),+ all: vi.fn().mockReturnValue([]),+ run: vi.fn().mockReturnValue({ changes: 0 }),+ }),+ exec: vi.fn(),+ transaction: vi.fn().mockImplementation((fn) => fn),+ pragma: vi.fn(),+ };+}++describe('connectDb — factory injection', () => {+ it('calls the injected factory instead of opening a filesystem path', () => {+ const stub = makeStubDb();+ const factory: DbFactory = vi.fn().mockReturnValue(stub);++ const result = connectDb('/fake/non-existent/path.db', { factory, ensureDir: false });++ expect(factory).toHaveBeenCalledWith('/fake/non-existent/path.db');+ expect(result).toBe(stub);+ });++ it('does not touch the filesystem when an in-memory stub factory is supplied', () => {+ const stub = makeStubDb();+ const factory: DbFactory = () => stub;++ // ensureDir: false skips mkdirSync so the fake path never hits the filesystem.+ expect(() => connectDb('/definitely/does/not/exist/db.sqlite', { factory, ensureDir: false })).not.toThrow();+ });+});diff --git a/server/src/db/index.ts b/server/src/db/index.tsindex bfa7dae9..9bf6e79c 100644--- a/server/src/db/index.ts+++ b/server/src/db/index.ts@@ -1,17 +1,20 @@import crypto from 'crypto';-import Database from 'better-sqlite3';+import BetterSqlite from 'better-sqlite3';import fs from 'fs';import path from 'path';import { fileURLToPath } from 'url';import { runMigrationsSync } from './migrate/runner.js';import { initEncryptionKey, isEncryptionKeyInitialized } from '../lib/crypto.js';+import type { Db, DbFactory } from './types.js';++export type { Db, DbFactory } from './types.js';const __dirname = path.dirname(fileURLToPath(import.meta.url));const DB_PATH = path.resolve(__dirname, '../../data/freeapi.db');-let db: Database.Database;+let db: Db;-export function getDb(): Database.Database {+export function getDb(): Db {if (!db) {throw new Error('Database not initialized. Call initDb() or connectDb() first.');}@@ -22,17 +25,25 @@ export function getDefaultDbPath(): string {return process.env.FREEAPI_DB_PATH?.trim() || DB_PATH;}+/** Default factory: opens a better-sqlite3 connection at the given path. */+function betterSqliteFactory(resolvedPath: string): Db {+ return new BetterSqlite(resolvedPath) as unknown as Db;+}+export function connectDb(dbPath?: string,opts?: {/** Create the parent directory if absent. Default: true. Set false in* environments that do not have a writable local filesystem. */ensureDir?: boolean;+ /** Factory that constructs the raw Db connection. Default: better-sqlite3. */+ factory?: DbFactory;},-): Database.Database {+): Db {const resolvedPath = dbPath ?? getDefaultDbPath();const isMemory = resolvedPath === ':memory:';const ensureDir = opts?.ensureDir ?? true;+ const factory = opts?.factory ?? betterSqliteFactory;if (!isMemory && ensureDir) {const dataDir = path.dirname(resolvedPath);@@ -41,7 +52,7 @@ export function connectDb(}}- db = new Database(resolvedPath);+ db = factory(resolvedPath);if (!isMemory) db.pragma('journal_mode = WAL');db.pragma('foreign_keys = ON');@@ -51,8 +62,8 @@ export function connectDb(export function initDb(dbPath?: string,- opts?: { ensureDir?: boolean },-): Database.Database {+ opts?: { ensureDir?: boolean; factory?: DbFactory },+): Db {const db = connectDb(dbPath, opts);if (process.env.NODE_ENV !== 'development') {diff --git a/server/src/db/migrate/TEMPLATE.ts b/server/src/db/migrate/TEMPLATE.tsindex 09ad8765..6cd7c9eb 100644--- a/server/src/db/migrate/TEMPLATE.ts+++ b/server/src/db/migrate/TEMPLATE.ts@@ -3,15 +3,15 @@//// DOWN: <reversible | irreversible - reason>-import type Database from 'better-sqlite3';+import type { Db } from '../types.js';-export function up(db: Database.Database): void {+export function up(db: Db): void {db.exec(`-- your SQL here`);}-export function down(db: Database.Database): void {+export function down(db: Db): void {// If reversible:db.exec(`-- inverse SQL herediff --git a/server/src/db/migrate/cli.ts b/server/src/db/migrate/cli.tsindex 5e8ced29..8d0af82d 100644--- a/server/src/db/migrate/cli.ts+++ b/server/src/db/migrate/cli.ts@@ -2,7 +2,8 @@ import '../../env.js';import fs from 'fs';import path from 'path';import { fileURLToPath } from 'url';-import type Database from 'better-sqlite3';++import type { Db } from '../types.js';import { connectDb } from '../index.js';import { getMigrationStatuses, runMigrations } from './runner.js';@@ -42,7 +43,7 @@ async function main(): Promise<void> {}}-async function runFresh(db: Database.Database): Promise<void> {+async function runFresh(db: Db): Promise<void> {if (process.env.NODE_ENV === 'production') {console.error('db:migration:fresh is not allowed in production');process.exit(1);@@ -52,7 +53,7 @@ async function runFresh(db: Database.Database): Promise<void> {await runMigrations(db, 'up');}-function printStatus(db: Database.Database): void {+function printStatus(db: Db): void {const statuses = getMigrationStatuses(db);console.table(statuses.map(status => ({filename: status.filename,@@ -182,7 +183,7 @@ function toMigrationBindingName(filename: string): string {return `migration${filename.replace(/\.ts$/, '').replace(/[^a-zA-Z0-9_]/g, '_')}`;}-function dropAllUserTables(db: Database.Database): void {+function dropAllUserTables(db: Db): void {const tables = db.prepare(`SELECT nameFROM sqlite_masterdiff --git a/server/src/db/migrate/defaults.ts b/server/src/db/migrate/defaults.tsindex f3d60059..a15e5196 100644--- a/server/src/db/migrate/defaults.ts+++ b/server/src/db/migrate/defaults.ts@@ -1,4 +1,4 @@-import type Database from 'better-sqlite3';+import type { Db } from '../types.js';import * as legacyBaseline from '../migrations/20260101_000000_legacy_baseline.js';import * as customProviderModalities from '../migrations/20260627_000001_custom_provider_modalities.js';import * as catalogModelState from '../migrations/20260627_000002_catalog_model_state.js';@@ -7,8 +7,8 @@ import * as githubGpt41Context from '../migrations/20260630_000001_github_gpt41_import * as requestClientInfo from '../migrations/20260706_000001_request_client_info.js';export interface MigrationModule {- up(db: Database.Database): void;- down(db: Database.Database): void;+ up(db: Db): void;+ down(db: Db): void;}export interface DefaultMigration {diff --git a/server/src/db/migrate/runner.ts b/server/src/db/migrate/runner.tsindex 5d5f67a9..46314c9e 100644--- a/server/src/db/migrate/runner.ts+++ b/server/src/db/migrate/runner.ts@@ -1,7 +1,8 @@import fs from 'fs';import path from 'path';import { fileURLToPath, pathToFileURL } from 'url';-import type Database from 'better-sqlite3';++import type { Db } from '../types.js';import { DEFAULT_MIGRATIONS, type MigrationModule } from './defaults.js';export type MigrationDirection = 'up' | 'down';@@ -40,7 +41,7 @@ const CREATE_MIGRATIONS_TABLE_SQL = ``;export async function runMigrations(- db: Database.Database,+ db: Db,direction: MigrationDirection = 'up',options: MigrationRunnerOptions = {},): Promise<void> {@@ -61,7 +62,7 @@ export async function runMigrations(}export function runMigrationsSync(- db: Database.Database,+ db: Db,direction: MigrationDirection = 'up',): void {initializeMigrationTracking(db);@@ -81,7 +82,7 @@ export function runMigrationsSync(}export function getMigrationStatuses(- db: Database.Database,+ db: Db,options: MigrationRunnerOptions = {},): MigrationStatus[] {initializeMigrationTracking(db);@@ -94,16 +95,16 @@ export function getMigrationStatuses(}));}-function initializeMigrationTracking(db: Database.Database): void {+function initializeMigrationTracking(db: Db): void {ensureMigrationsTable(db);}-function ensureMigrationsTable(db: Database.Database): void {+function ensureMigrationsTable(db: Db): void {db.exec(CREATE_MIGRATIONS_TABLE_SQL);}async function runPendingMigrations(- db: Database.Database,+ db: Db,records: readonly MigrationRecord[],options: MigrationRunnerOptions,): Promise<void> {@@ -124,7 +125,7 @@ async function runPendingMigrations(}async function runLatestDownMigration(- db: Database.Database,+ db: Db,records: readonly MigrationRecord[],options: MigrationRunnerOptions,): Promise<void> {@@ -150,7 +151,7 @@ async function runLatestDownMigration(}function runPendingMigrationsSync(- db: Database.Database,+ db: Db,records: readonly MigrationRecord[],): void {const applied = getAppliedMigrations(db);@@ -170,7 +171,7 @@ function runPendingMigrationsSync(}function runLatestDownMigrationSync(- db: Database.Database,+ db: Db,records: readonly MigrationRecord[],): void {const row = db.prepare(`@@ -193,7 +194,7 @@ function runLatestDownMigrationSync(revertMigration();}-function getAppliedMigrations(db: Database.Database): Map<string, string> {+function getAppliedMigrations(db: Db): Map<string, string> {const rows = db.prepare(`SELECT filename, applied_atFROM migrationsdiff --git a/server/src/db/migrations/20260101_000000_legacy_baseline.ts b/server/src/db/migrations/20260101_000000_legacy_baseline.tsindex 3ed12619..dbedf324 100644--- a/server/src/db/migrations/20260101_000000_legacy_baseline.ts+++ b/server/src/db/migrations/20260101_000000_legacy_baseline.ts@@ -1,9 +1,10 @@import crypto from 'crypto';-import Database from 'better-sqlite3';+import type { Db } from '../types.js';+import { initEncryptionKey } from '../../lib/crypto.js';import { applyModelPricing } from '../model-pricing.js';-export function up(db: Database.Database): void {+export function up(db: Db): void {createTables(db);initEncryptionKey(db);seedModels(db);@@ -50,11 +51,11 @@ export function up(db: Database.Database): void {migrateProfilesInit(db);}-export function down(_db: Database.Database): void {+export function down(_db: Db): void {throw new Error('Legacy baseline is irreversible - restore from backup');}-function createTables(db: Database.Database) {+function createTables(db: Db) {db.exec(`CREATE TABLE IF NOT EXISTS models (id INTEGER PRIMARY KEY AUTOINCREMENT,@@ -234,7 +235,7 @@ function createTables(db: Database.Database) {// NULL when the request was auto-routed ('auto' or omitted model field).// requested_model = model_id means the pin was honored; a different model_id// means rate limits or failures forced a failover to another model.-function ensureRequestRequestedModelColumn(db: Database.Database) {+function ensureRequestRequestedModelColumn(db: Db) {const columns = db.prepare('PRAGMA table_info(requests)').all() as { name: string }[];if (!columns.some(col => col.name === 'requested_model')) {db.prepare('ALTER TABLE requests ADD COLUMN requested_model TEXT').run();@@ -244,14 +245,14 @@ function ensureRequestRequestedModelColumn(db: Database.Database) {// `ttfb_ms` is the time-to-first-byte for streaming responses (ms from dispatch// to the first chunk). NULL for non-streaming or pre-existing rows. Feeds the// bandit router's latency axis (server/src/services/scoring.ts).-function ensureRequestTtfbColumn(db: Database.Database) {+function ensureRequestTtfbColumn(db: Db) {const columns = db.prepare('PRAGMA table_info(requests)').all() as { name: string }[];if (!columns.some(col => col.name === 'ttfb_ms')) {db.prepare('ALTER TABLE requests ADD COLUMN ttfb_ms INTEGER').run();}}-function ensureRequestKeyIdColumn(db: Database.Database) {+function ensureRequestKeyIdColumn(db: Db) {const columns = db.prepare('PRAGMA table_info(requests)').all() as { name: string }[];if (!columns.some(col => col.name === 'key_id')) {db.prepare('ALTER TABLE requests ADD COLUMN key_id INTEGER').run();@@ -261,7 +262,7 @@ function ensureRequestKeyIdColumn(db: Database.Database) {// `base_url` is the upstream endpoint for the user-configured 'custom' provider// (#117). NULL for every built-in platform — they use their hardcoded base URL.-function ensureApiKeysBaseUrlColumn(db: Database.Database) {+function ensureApiKeysBaseUrlColumn(db: Db) {const columns = db.prepare('PRAGMA table_info(api_keys)').all() as { name: string }[];if (!columns.some(col => col.name === 'base_url')) {db.prepare('ALTER TABLE api_keys ADD COLUMN base_url TEXT').run();@@ -271,7 +272,7 @@ function ensureApiKeysBaseUrlColumn(db: Database.Database) {// `key_id` binds a custom model to the api_keys row that carries ITS endpoint,// so several custom providers can coexist (#212). NULL for built-in platforms// (any key of the platform serves any of its models).-function ensureModelsKeyIdColumn(db: Database.Database) {+function ensureModelsKeyIdColumn(db: Db) {const columns = db.prepare('PRAGMA table_info(models)').all() as { name: string }[];if (!columns.some(col => col.name === 'key_id')) {db.prepare('ALTER TABLE models ADD COLUMN key_id INTEGER').run();@@ -285,7 +286,7 @@ function ensureModelsKeyIdColumn(db: Database.Database) {}}-function seedModels(db: Database.Database) {+function seedModels(db: Db) {const count = db.prepare('SELECT COUNT(*) as cnt FROM models').get() as { cnt: number };if (count.cnt > 0) return;@@ -360,7 +361,7 @@ function seedModels(db: Database.Database) {* corrects stale rate-limits / monthly budgets, adds new smarter models* and three new providers (Zhipu, Moonshot, MiniMax).*/-function migrateModels(db: Database.Database) {+function migrateModels(db: Db) {// 1) Replace outdated models in-place (preserves fallback_config & any references)const renames: Array<[string, string, string, string, number, string, number | null, number | null, number]> = [// platform, oldModelId, newModelId, newDisplayName, intelligenceRank, monthlyBudget, rpdLimit, contextWindow, sizeLabelPriority(unused)@@ -439,7 +440,7 @@ function migrateModels(db: Database.Database) {* the current free tier, and adds real :free OpenRouter models found in the* live catalog (April 2026).*/-function migrateModelsV2(db: Database.Database) {+function migrateModelsV2(db: Db) {// Helper: delete a model and its fallback_config entry (FK is RESTRICT-by-default)const deleteModel = db.prepare(`DELETE FROM models WHERE platform = ? AND model_id = ?`);const deleteFallback = db.prepare(`@@ -515,7 +516,7 @@ function migrateModelsV2(db: Database.Database) {* SWE-bench Verified, Terminal-Bench 2, TAU-Bench, Aider Polyglot.* Higher rank = weaker. Ties are allowed (same weights across providers).*/-function migrateModelsV3Ranks(db: Database.Database) {+function migrateModelsV3Ranks(db: Db) {const setRank = db.prepare(`UPDATE models SET intelligence_rank = ? WHERE platform = ? AND model_id = ?`);const ranks: Array<[number, string, string]> = [// #1-10 frontier coders / agents@@ -570,7 +571,7 @@ function migrateModelsV3Ranks(db: Database.Database) {* (no structured tools), OR/gemma-4 (weak at tools). Renames CF llama-3.1 → 3.3* fp8-fast. Corrects stale limits.*/-function migrateModelsV4(db: Database.Database) {+function migrateModelsV4(db: Db) {// 1) Remove entries that are unavailable or fail agentic tool useconst deleteModel = db.prepare(`DELETE FROM models WHERE platform = ? AND model_id = ?`);const deleteFallback = db.prepare(`@@ -725,7 +726,7 @@ function migrateModelsV4(db: Database.Database) {* free tier but throttled to 10 RPM / 100 RPD due to high demand; context capped* at 8192 on free tier).*/-function migrateModelsV5(db: Database.Database) {+function migrateModelsV5(db: Db) {db.prepare(`UPDATE models SET enabled = 0 WHERE platform = 'google' AND model_id = 'gemini-2.5-pro'`).run();const insert = db.prepare(`@@ -766,7 +767,7 @@ function migrateModelsV5(db: Database.Database) {* against the same 20 RPD pool, confirming free-tier eligibility)* - 2 OpenRouter :free models with no expiration_date*/-function migrateModelsV6(db: Database.Database) {+function migrateModelsV6(db: Db) {// 1) Remove confirmed-dead OR routeconst deleteModel = db.prepare(`DELETE FROM models WHERE platform = ? AND model_id = ?`);const deleteFallback = db.prepare(`@@ -844,7 +845,7 @@ function migrateModelsV6(db: Database.Database) {* api.z.ai and open.bigmodel.cn keys.* HF and NVIDIA left as-is: HF still serves chat with current key; NVIDIA already disabled.*/-function migrateModelsV7(db: Database.Database) {+function migrateModelsV7(db: Db) {const deleteModel = db.prepare(`DELETE FROM models WHERE platform = ? AND model_id = ?`);const deleteFallback = db.prepare(`DELETE FROM fallback_config WHERE model_db_id IN (@@ -903,7 +904,7 @@ function migrateModelsV7(db: Database.Database) {* "Couldn't find valid service tier", so the 200s on these rows confirm free-tier* access. Cloudflare's @cf/* models share the 10K Neurons/day free pool.*/-function migrateModelsV8(db: Database.Database) {+function migrateModelsV8(db: Db) {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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)@@ -940,7 +941,7 @@ function migrateModelsV8(db: Database.Database) {* zai-glm-4.7 due to high demand. Row kept (not deleted) so it can be* re-enabled later without losing fallback_config history.*/-function migrateModelsV9(db: Database.Database) {+function migrateModelsV9(db: Db) {db.prepare("UPDATE models SET enabled = 0 WHERE platform = 'cerebras' AND model_id = 'zai-glm-4.7'").run();@@ -960,7 +961,7 @@ function migrateModelsV9(db: Database.Database) {* Quota shape: GPU-time, not tokens. monthly_token_budget reflects rough* Free-tier "session" capacity rather than a hard token cap.*/-function migrateModelsV10(db: Database.Database) {+function migrateModelsV10(db: Db) {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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)@@ -1017,7 +1018,7 @@ function migrateModelsV10(db: Database.Database) {* please pay with fiat or send tao". The "free" tier requires a paid* balance, which conflicts with the no-card criterion.*/-function migrateModelsV11(db: Database.Database) {+function migrateModelsV11(db: Db) {// 1) Rename cerebras qwen3-235b → qwen-3-235b-a22b-instruct-2507 if the// old id still exists on this DB. Safe to re-run because of the WHERE.db.prepare(`@@ -1129,7 +1130,7 @@ function migrateModelsV11(db: Database.Database) {* - nvidia/nemotron-3-super-120b-a12b:free 262144 → 1000000* - qwen/qwen3-coder:free 262144 → 1048576*/-function migrateModelsV12(db: Database.Database) {+function migrateModelsV12(db: Db) {const deleteModel = db.prepare(`DELETE FROM models WHERE platform = ? AND model_id = ?`);const deleteFallback = db.prepare(`DELETE FROM fallback_config WHERE model_db_id IN (@@ -1263,7 +1264,7 @@ function migrateModelsV12(db: Database.Database) {* - github: gpt-5 family + xai/grok-3 both 400 "unavailable_model" on free* tier — keep gpt-4o (V2 verdict still holds).*/-function migrateModelsV13(db: Database.Database) {+function migrateModelsV13(db: Db) {// 1) Disables (row kept; can be re-enabled without losing fallback history).const disable = db.prepare(`UPDATE models SET enabled = 0 WHERE platform = ? AND model_id = ?`);const disables: Array<[string, string]> = [@@ -1388,7 +1389,7 @@ function migrateModelsV13(db: Database.Database) {* Cerebras `gpt-oss-120b` is NOT in the deprecation list and stays enabled* as the sole free-tier Cerebras route.*/-function migrateModelsV14(db: Database.Database) {+function migrateModelsV14(db: Db) {db.prepare(`UPDATE models SET enabled = 0WHERE platform = 'cerebras'@@ -1408,7 +1409,7 @@ function migrateModelsV14(db: Database.Database) {* as Chutes — so the provider was reverted. This removes any orphaned row from* a DB that already ran the original V15. No-op on DBs that never had it.*/-function migrateModelsV15(db: Database.Database) {+function migrateModelsV15(db: Db) {db.prepare(`DELETE FROM fallback_config WHERE model_db_id IN (SELECT id FROM models WHERE platform = 'siliconflow'@@ -1429,7 +1430,7 @@ function migrateModelsV15(db: Database.Database) {// Conservative on purpose: with hard-fail routing a false negative is just a// clear "no vision model" error, while a false positive routes an image to a// model that chokes. Idempotent — safe on fresh seeds and upgrades alike.-function migrateModelsV16Vision(db: Database.Database) {+function migrateModelsV16Vision(db: Db) {const columns = db.prepare('PRAGMA table_info(models)').all() as { name: string }[];if (!columns.some(col => col.name === 'supports_vision')) {db.prepare('ALTER TABLE models ADD COLUMN supports_vision INTEGER NOT NULL DEFAULT 0').run();@@ -1483,7 +1484,7 @@ function migrateModelsV16Vision(db: Database.Database) {// Baidu CoBuddy, Groq Compound, GLM-4.6V Flash, GLM-4.5 Flash, Mistral Small 4,// Devstral). intelligence_rank (the within-tier tiebreak, low impact) is left// untouched. Idempotent — every statement is an absolute SET, safe to re-run.-function migrateModelsV17IntelligenceTiers(db: Database.Database) {+function migrateModelsV17IntelligenceTiers(db: Db) {const apply = db.transaction(() => {// Frontier (AA ≥ 45): genuine frontier-class. Promotes Gemini 3.5 Flash (55)// and Gemini 3 Flash Preview (46) up from Large.@@ -1587,7 +1588,7 @@ function migrateModelsV17IntelligenceTiers(db: Database.Database) {// models (NVIDIA logs Nemotron traffic). Conservative shared 20 RPM / 200 RPD,// matching the OpenRouter :free pool pattern. Idempotent (INSERT OR IGNORE +// fallback_config backfill), safe to re-run.-function migrateModelsV18OpenCodeZen(db: Database.Database) {+function migrateModelsV18OpenCodeZen(db: Db) {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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)@@ -1624,7 +1625,7 @@ function migrateModelsV18OpenCodeZen(db: Database.Database) {* Dec 2025, so rpd/tpm are conservative. Idempotent (INSERT OR IGNORE + fallback* backfill), safe to re-run.*/-function migrateModelsV19Gemma4(db: Database.Database) {+function migrateModelsV19Gemma4(db: Db) {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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)@@ -1653,7 +1654,7 @@ function migrateModelsV19Gemma4(db: Database.Database) {* 'kilo' api_keys sentinel row, added via the keyless Keys-page flow. Idempotent* (INSERT OR IGNORE + fallback backfill), safe to re-run.*/-function migrateModelsV20KiloFree(db: Database.Database) {+function migrateModelsV20KiloFree(db: Db) {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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)@@ -1690,7 +1691,7 @@ function migrateModelsV20KiloFree(db: Database.Database) {* These ids are re-inserted by their original migrations on each boot, so this* later DELETE is what keeps them out. Idempotent, safe to re-run.*/-function migrateModelsV21PruneDead(db: Database.Database) {+function migrateModelsV21PruneDead(db: Db) {const dead: Array<[string, string]> = [['llm7', 'gpt-oss-20b'],['llm7', 'meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo'],@@ -1745,7 +1746,7 @@ function migrateModelsV21PruneDead(db: Database.Database) {// tail (granite, lfm, stepfun, big-pickle, mimo, owl-alpha, cogito,// pollinations). Idempotent — reset-then-set, safe on fresh seeds and// upgrades alike.-function migrateModelsV22Tools(db: Database.Database) {+function migrateModelsV22Tools(db: Db) {const columns = db.prepare('PRAGMA table_info(models)').all() as { name: string }[];if (!columns.some(col => col.name === 'supports_tools')) {db.prepare('ALTER TABLE models ADD COLUMN supports_tools INTEGER NOT NULL DEFAULT 0').run();@@ -1836,7 +1837,7 @@ function migrateModelsV22Tools(db: Database.Database) {* vision/tools seeds match the V16/V22 rules (which re-assert next boot);* tiers match V17's bands.*/-function migrateModelsV23FreeTierAudit(db: Database.Database) {+function migrateModelsV23FreeTierAudit(db: Db) {const apply = db.transaction(() => {for (const platform of ['sambanova', 'chutes']) {db.prepare(`@@ -1896,7 +1897,7 @@ function migrateModelsV23FreeTierAudit(db: Database.Database) {** Idempotent: INSERT OR IGNORE + always-run UPDATEs, safe to re-run.*/-function migrateModelsV24ZenRefresh(db: Database.Database) {+function migrateModelsV24ZenRefresh(db: Db) {const apply = db.transaction(() => {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, enabled, supports_vision, supports_tools)@@ -1933,7 +1934,7 @@ function migrateModelsV24ZenRefresh(db: Database.Database) {* promo can re-enable). Idempotent: re-asserted each boot like the V13/V24* disables.*/-function migrateModelsV25ZenDeadPromos(db: Database.Database) {+function migrateModelsV25ZenDeadPromos(db: Db) {const disable = db.prepare(`UPDATE models SET enabled = 0 WHERE platform = ? AND model_id = ?`);const disables: Array<[string, string]> = [['opencode', 'nemotron-3-super-free'],@@ -1961,7 +1962,7 @@ function migrateModelsV25ZenDeadPromos(db: Database.Database) {// incompatible spaces, so /v1/embeddings only ever fails over WITHIN a family// (same model served by another provider), never across families.// Every entry was live-verified against the provider on 2026-06-04.-function migrateEmbeddingsV1(db: Database.Database) {+function migrateEmbeddingsV1(db: Db) {db.exec(`CREATE TABLE IF NOT EXISTS embedding_models (id INTEGER PRIMARY KEY AUTOINCREMENT,@@ -2029,7 +2030,7 @@ function migrateEmbeddingsV1(db: Database.Database) {* request_type column (added by migrateEmbeddingsV1) tags media traffic 'image'* / 'audio' so it stays out of the chat budget math.*/-function migrateMediaV1(db: Database.Database) {+function migrateMediaV1(db: Db) {db.exec(`CREATE TABLE IF NOT EXISTS media_models (id INTEGER PRIMARY KEY AUTOINCREMENT,@@ -2071,7 +2072,7 @@ function migrateMediaV1(db: Database.Database) {* reset-then-insert of the curated set, so editing a seeded quirk in code wins* on next boot while operator-added quirks (new slugs) are left untouched.*/-function migrateQuirksV1(db: Database.Database) {+function migrateQuirksV1(db: Db) {db.exec(`CREATE TABLE IF NOT EXISTS quirks (id INTEGER PRIMARY KEY AUTOINCREMENT,@@ -2222,7 +2223,7 @@ function migrateQuirksV1(db: Database.Database) {/** Append any models not yet in the fallback chain, lowest priority, ordered by* intelligence_rank. Shared by the recent model migrations (V18–V20). */-function backfillFallback(db: Database.Database) {+function backfillFallback(db: Db) {const missing = db.prepare(`SELECT m.id FROM models mLEFT JOIN fallback_config f ON m.id = f.model_db_id@@ -2235,7 +2236,7 @@ function backfillFallback(db: Database.Database) {}}-function ensureUnifiedKey(db: Database.Database) {+function ensureUnifiedKey(db: Db) {const existing = db.prepare("SELECT value FROM settings WHERE key = 'unified_api_key'").get() as { value: string } | undefined;if (!existing) {const key = `freellmapi-${crypto.randomBytes(24).toString('hex')}`;@@ -2248,7 +2249,7 @@ function ensureUnifiedKey(db: Database.Database) {* Migration helper to ensure Default profile exists, legacy profiles converted,* and fallback_config synced.*/-function migrateProfilesInit(db: Database.Database) {+function migrateProfilesInit(db: Db) {// 1. Convert any legacy built-in profiles to custom profiles (type = 'custom')db.prepare(`UPDATE profilesdiff --git a/server/src/db/migrations/20260627_000001_custom_provider_modalities.ts b/server/src/db/migrations/20260627_000001_custom_provider_modalities.tsindex 3d035317..8272d100 100644--- a/server/src/db/migrations/20260627_000001_custom_provider_modalities.ts+++ b/server/src/db/migrations/20260627_000001_custom_provider_modalities.ts@@ -1,30 +1,30 @@-import type Database from 'better-sqlite3';+import type { Db } from '../types.js';-function hasColumn(db: Database.Database, table: string, column: string): boolean {+function hasColumn(db: Db, table: string, column: string): boolean {const columns = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];return columns.some(col => col.name === column);}-function addKeyIdColumn(db: Database.Database, table: string): void {+function addKeyIdColumn(db: Db, table: string): void {if (!hasColumn(db, table, 'key_id')) {db.prepare(`ALTER TABLE ${table} ADD COLUMN key_id INTEGER`).run();}}-function dropKeyIdColumn(db: Database.Database, table: string): void {+function dropKeyIdColumn(db: Db, table: string): void {if (hasColumn(db, table, 'key_id')) {db.prepare(`ALTER TABLE ${table} DROP COLUMN key_id`).run();}}-export function up(db: Database.Database): void {+export function up(db: Db): void {addKeyIdColumn(db, 'embedding_models');addKeyIdColumn(db, 'media_models');db.prepare('CREATE INDEX IF NOT EXISTS idx_embedding_models_key_id ON embedding_models(key_id)').run();db.prepare('CREATE INDEX IF NOT EXISTS idx_media_models_key_id ON media_models(key_id)').run();}-export function down(db: Database.Database): void {+export function down(db: Db): void {db.prepare('DROP INDEX IF EXISTS idx_embedding_models_key_id').run();db.prepare('DROP INDEX IF EXISTS idx_media_models_key_id').run();dropKeyIdColumn(db, 'media_models');diff --git a/server/src/db/migrations/20260627_000002_catalog_model_state.ts b/server/src/db/migrations/20260627_000002_catalog_model_state.tsindex 936bd4ad..ddf7c7ad 100644--- a/server/src/db/migrations/20260627_000002_catalog_model_state.ts+++ b/server/src/db/migrations/20260627_000002_catalog_model_state.ts@@ -1,6 +1,6 @@-import type Database from 'better-sqlite3';+import type { Db } from '../types.js';-export function up(db: Database.Database): void {+export function up(db: Db): void {db.exec(`CREATE TABLE IF NOT EXISTS catalog_model_tombstones (kind TEXT NOT NULL DEFAULT 'chat',@@ -23,7 +23,7 @@ export function up(db: Database.Database): void {`);}-export function down(db: Database.Database): void {+export function down(db: Db): void {db.exec(`DROP INDEX IF EXISTS idx_catalog_model_tombstones_platform_model;DROP TABLE IF EXISTS model_overrides;diff --git a/server/src/db/migrations/20260628_120000_request_aggregates.ts b/server/src/db/migrations/20260628_120000_request_aggregates.tsindex dedae2dc..99631972 100644--- a/server/src/db/migrations/20260628_120000_request_aggregates.ts+++ b/server/src/db/migrations/20260628_120000_request_aggregates.ts@@ -1,4 +1,4 @@-import type Database from 'better-sqlite3';+import type { Db } from '../types.js';/*** Roll up request analytics into two durable stores so UI totals stay accurate@@ -15,7 +15,7 @@ import type Database from 'better-sqlite3';* this migration. Lifetime counters start counting from "now" — rows pruned* before this migration are unrecoverable from the aggregate.*/-function tableExists(db: Database.Database, name: string): boolean {+function tableExists(db: Db, name: string): boolean {return !!db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(name);@@ -26,7 +26,7 @@ function hourKey(createdAt: string): string {return createdAt.slice(0, 13) + ':00:00';}-export function up(db: Database.Database): void {+export function up(db: Db): void {// Hourly aggregate table. `hour` is the primary key so the same-hour upsert// is a single-row write. We never update tokens on a partial failure, so// success/error counts and token sums stay consistent.@@ -108,7 +108,7 @@ export function up(db: Database.Database): void {}}-export function down(db: Database.Database): void {+export function down(db: Db): void {db.prepare(`DROP INDEX IF EXISTS idx_request_hourly_hour`).run();db.prepare(`DROP TABLE IF EXISTS request_hourly`).run();db.prepare(`DELETE FROM settings WHERE key IN (diff --git a/server/src/db/migrations/20260630_000001_github_gpt41_context.ts b/server/src/db/migrations/20260630_000001_github_gpt41_context.tsindex 9b79124c..5fd93a29 100644--- a/server/src/db/migrations/20260630_000001_github_gpt41_context.ts+++ b/server/src/db/migrations/20260630_000001_github_gpt41_context.ts@@ -1,11 +1,11 @@-import type Database from 'better-sqlite3';+import type { Db } from '../types.js';/*** GitHub Models' free GPT-4.1 endpoint rejects requests above the low-tier* per-call input cap even though the upstream model can support a larger* context elsewhere. Keep the local catalog aligned with the routable limit.*/-export function up(db: Database.Database): void {+export function up(db: Db): void {db.prepare(`UPDATE modelsSET context_window = 8000@@ -14,7 +14,7 @@ export function up(db: Database.Database): void {`).run();}-export function down(db: Database.Database): void {+export function down(db: Db): void {db.prepare(`UPDATE modelsSET context_window = 128000diff --git a/server/src/db/migrations/20260706_000001_request_client_info.ts b/server/src/db/migrations/20260706_000001_request_client_info.tsindex 27c5b0af..abfcb6c7 100644--- a/server/src/db/migrations/20260706_000001_request_client_info.ts+++ b/server/src/db/migrations/20260706_000001_request_client_info.ts@@ -1,4 +1,4 @@-import type Database from 'better-sqlite3';+import type { Db } from '../types.js';/*** Record WHO made each proxied call. All local clients share the single@@ -9,12 +9,12 @@ import type Database from 'better-sqlite3';* Guarded like the baseline's column adds: catalog-sync re-runs migrations* over a live schema, so ALTERs must be idempotent.*/-function hasColumn(db: Database.Database, table: string, column: string): boolean {+function hasColumn(db: Db, table: string, column: string): boolean {const columns = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];return columns.some(col => col.name === column);}-export function up(db: Database.Database): void {+export function up(db: Db): void {if (!hasColumn(db, 'requests', 'client_ip')) {db.prepare('ALTER TABLE requests ADD COLUMN client_ip TEXT').run();}@@ -23,7 +23,7 @@ export function up(db: Database.Database): void {}}-export function down(db: Database.Database): void {+export function down(db: Db): void {if (hasColumn(db, 'requests', 'client_user_agent')) {db.prepare('ALTER TABLE requests DROP COLUMN client_user_agent').run();}diff --git a/server/src/db/model-pricing.ts b/server/src/db/model-pricing.tsindex 1275520b..d62e2a0d 100644--- a/server/src/db/model-pricing.ts+++ b/server/src/db/model-pricing.ts@@ -1,4 +1,4 @@-import type Database from 'better-sqlite3';+import type { Db } from './types.js';/*** Paid-equivalent pricing per model: what the SAME model (or its nearest@@ -195,7 +195,7 @@ export const FALLBACK_OUTPUT_PER_M = 0.80;* known model. Runs on every boot — it's ~100 UPDATEs in one transaction* and keeps prices current when this map is updated in a release.*/-export function applyModelPricing(db: Database.Database): void {+export function applyModelPricing(db: Db): void {const columns = db.prepare('PRAGMA table_info(models)').all() as { name: string }[];if (!columns.some(c => c.name === 'paid_input_per_m')) {db.prepare('ALTER TABLE models ADD COLUMN paid_input_per_m REAL').run();diff --git a/server/src/db/types.ts b/server/src/db/types.tsnew file mode 100644index 00000000..353f25c8--- /dev/null+++ b/server/src/db/types.ts@@ -0,0 +1,20 @@+export interface DbStatement {+ get(...params: unknown[]): unknown;+ all(...params: unknown[]): unknown[];+ run(...params: unknown[]): { lastInsertRowid?: number | bigint; changes: number };+}++export interface Db {+ prepare(sql: string): DbStatement;+ exec(sql: string): void;+ // Mirrors better-sqlite3's pattern: transaction() wraps fn and returns a+ // callable with the same signature. The F extends constraint covers both+ // zero-arg transactions and the parameterised form used in routes/embeddings.+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ transaction<F extends (...args: any[]) => unknown>(fn: F): F;+ pragma(source: string): unknown;+}++/** Factory that opens (or creates) a database at the given resolved path and+ * returns it as a Db. Pragmas and migrations are applied by the caller. */+export type DbFactory = (resolvedPath: string) => Db;diff --git a/server/src/lib/crypto.ts b/server/src/lib/crypto.tsindex 43b4e508..cd861fd6 100644--- a/server/src/lib/crypto.ts+++ b/server/src/lib/crypto.ts@@ -1,5 +1,5 @@import crypto from 'crypto';-import Database from 'better-sqlite3';+import type { Db } from '../db/types.js';const ALGORITHM = 'aes-256-gcm';@@ -49,7 +49,7 @@ function missingKeyError(): Error {* Initialize encryption key from env or an explicit local-dev fallback.* Must be called after DB is initialized.*/-export function initEncryptionKey(db: Database.Database): void {+export function initEncryptionKey(db: Db): void {// 1. Check env varconst envKey = process.env.ENCRYPTION_KEY;if (envKey && envKey !== PLACEHOLDER_KEY) {diff --git a/server/src/lib/custom-provider-cleanup.ts b/server/src/lib/custom-provider-cleanup.tsindex bc772148..db2c2090 100644--- a/server/src/lib/custom-provider-cleanup.ts+++ b/server/src/lib/custom-provider-cleanup.ts@@ -1,6 +1,6 @@-import type Database from 'better-sqlite3';+import type { Db } from '../db/types.js';-export function deleteUnusedCustomEndpointKey(db: Database.Database, keyId: number | null | undefined) {+export function deleteUnusedCustomEndpointKey(db: Db, keyId: number | null | undefined) {if (keyId == null) return;const chat = db.prepare("SELECT COUNT(*) AS n FROM models WHERE platform = 'custom' AND key_id = ?").get(keyId) as { n: number };const embeddings = db.prepare("SELECT COUNT(*) AS n FROM embedding_models WHERE platform = 'custom' AND key_id = ?").get(keyId) as { n: number };diff --git a/server/src/lib/db-backup.ts b/server/src/lib/db-backup.tsindex f64603d1..b855fa45 100644--- a/server/src/lib/db-backup.ts+++ b/server/src/lib/db-backup.ts@@ -2,7 +2,7 @@ import crypto from 'crypto';import fs from 'fs';import path from 'path';import { gzipSync, gunzipSync } from 'zlib';-import type Database from 'better-sqlite3';+import type { Db } from '../db/types.js';import type { Scheduler } from './scheduler.js';import { getDefaultDbPath } from '../db/index.js';@@ -133,7 +133,7 @@ export async function restoreDbBackupIfNeeded(dbPath = getDefaultDbPath()): Promreturn { ok: true, target, bytes: restored.length, restored: true };}-export async function backupDbNow(db: Database.Database, dbPath = getDefaultDbPath()): Promise<DbBackupResult> {+export async function backupDbNow(db: Db, dbPath = getDefaultDbPath()): Promise<DbBackupResult> {const target = backupTarget();if (!target) return { ok: true, skipped: 'not configured' };if (dbPath === ':memory:') return { ok: true, target, skipped: 'memory database' };@@ -152,7 +152,7 @@ export async function backupDbNow(db: Database.Database, dbPath = getDefaultDbPareturn { ok: true, target, bytes: plain.length };}-export function startDbBackupPump(db: Database.Database, scheduler: Scheduler, dbPath = getDefaultDbPath()): (() => void) | null {+export function startDbBackupPump(db: Db, scheduler: Scheduler, dbPath = getDefaultDbPath()): (() => void) | null {if (!backupTarget()) return null;const run = () => {void backupDbNow(db, dbPath).catch(err => {diff --git a/server/src/services/catalog-sync.ts b/server/src/services/catalog-sync.tsindex 03b2e740..f4139e4d 100644--- a/server/src/services/catalog-sync.ts+++ b/server/src/services/catalog-sync.ts@@ -1,5 +1,5 @@import crypto from 'crypto';-import type DatabaseType from 'better-sqlite3';+import type { Db } from '../db/types.js';import { getDb, getSetting, setSetting } from '../db/index.js';import { hasProvider } from '../providers/index.js';import { MEDIA_PLATFORMS } from './media.js';@@ -165,7 +165,7 @@ function routableContextWindow(platform: string, modelId: string, contextWindow:* - models that vanished from the catalog are deleted, exactly like the* dead-model migrations do (fallback_config row first, FK order).*/-export function applyCatalog(db: DatabaseType.Database, catalog: Catalog): NonNullable<SyncResult['counts']> {+export function applyCatalog(db: Db, catalog: Catalog): NonNullable<SyncResult['counts']> {const counts = { updated: 0, inserted: 0, removed: 0, skippedUnknownPlatform: 0, quirks: 0 };const selectModel = db.prepare('SELECT id, enabled FROM models WHERE platform = ? AND model_id = ?');diff --git a/server/src/services/declarative-config.ts b/server/src/services/declarative-config.tsindex d943c177..3112b021 100644--- a/server/src/services/declarative-config.ts+++ b/server/src/services/declarative-config.ts@@ -1,6 +1,6 @@import fs from 'fs';import { z } from 'zod';-import type Database from 'better-sqlite3';+import type { Db } from '../db/types.js';import { getDb } from '../db/index.js';import { encrypt } from '../lib/crypto.js';import { resolveProvider } from '../providers/index.js';@@ -124,7 +124,7 @@ function encryptedKey(raw: string) {return { encrypted, iv, authTag };}-function upsertApiKey(db: Database.Database, input: z.infer<typeof keySchema>): number {+function upsertApiKey(db: Db, input: z.infer<typeof keySchema>): number {const platform = input.platform.trim();const enabled = input.enabled === false ? 0 : 1;const isCustom = platform === 'custom';@@ -177,7 +177,7 @@ function normalizeModelEntry(entry: z.infer<typeof modelEntrySchema>): Normalizereturn { ...entry, modelId, displayName: entry.displayName?.trim() || modelId };}-function ensureFallbackRow(db: Database.Database, modelDbId: number, enabled = true, updateExisting = true): void {+function ensureFallbackRow(db: Db, modelDbId: number, enabled = true, updateExisting = true): void {const existing = db.prepare('SELECT 1 FROM fallback_config WHERE model_db_id = ?').get(modelDbId);if (existing) {if (updateExisting) {@@ -190,7 +190,7 @@ function ensureFallbackRow(db: Database.Database, modelDbId: number, enabled = t.run(modelDbId, max.m + 1, enabled ? 1 : 0);}-function registerCustomProvider(db: Database.Database, input: z.infer<typeof customProviderSchema>): number {+function registerCustomProvider(db: Db, input: z.infer<typeof customProviderSchema>): number {const keyId = upsertApiKey(db, {platform: 'custom',key: input.apiKey,@@ -250,7 +250,7 @@ function modelPatchFromInput(input: z.infer<typeof modelSchema>): ModelOverridePreturn patch;}-function upsertModel(db: Database.Database, input: z.infer<typeof modelSchema>): void {+function upsertModel(db: Db, input: z.infer<typeof modelSchema>): void {const platform = input.platform.trim();const modelId = input.modelId.trim();clearCatalogModelTombstone(db, 'chat', platform, modelId);@@ -321,7 +321,7 @@ function upsertModel(db: Database.Database, input: z.infer<typeof modelSchema>):ensureFallbackRow(db, existing.id, input.fallbackEnabled ?? input.enabled !== false, input.fallbackEnabled !== undefined);}-function applyFallback(db: Database.Database, entries: z.infer<typeof fallbackEntrySchema>[]): number {+function applyFallback(db: Db, entries: z.infer<typeof fallbackEntrySchema>[]): number {const update = db.prepare('UPDATE fallback_config SET priority = ?, enabled = ? WHERE model_db_id = ?');let changed = 0;entries.forEach((entry, i) => {diff --git a/server/src/services/model-state.ts b/server/src/services/model-state.tsindex 9e42e519..66ac3cfc 100644--- a/server/src/services/model-state.ts+++ b/server/src/services/model-state.ts@@ -1,4 +1,4 @@-import type Database from 'better-sqlite3';+import type { Db } from '../db/types.js';export type CatalogModelKind = 'chat' | 'media';@@ -64,7 +64,7 @@ export function isCatalogManagedModel(row: { platform: string; key_id?: number |}export function isCatalogModelTombstoned(- db: Database.Database,+ db: Db,kind: CatalogModelKind,platform: string,modelId: string,@@ -75,7 +75,7 @@ export function isCatalogModelTombstoned(}export function recordCatalogModelTombstone(- db: Database.Database,+ db: Db,kind: CatalogModelKind,platform: string,modelId: string,@@ -91,7 +91,7 @@ export function recordCatalogModelTombstone(}export function clearCatalogModelTombstone(- db: Database.Database,+ db: Db,kind: CatalogModelKind,platform: string,modelId: string,@@ -101,7 +101,7 @@ export function clearCatalogModelTombstone(}export function upsertModelOverrides(- db: Database.Database,+ db: Db,platform: string,modelId: string,patch: ModelOverridePatch,@@ -122,7 +122,7 @@ export function upsertModelOverrides(}export function getModelOverrides(- db: Database.Database,+ db: Db,platform: string,modelId: string,): StoredOverrides {@@ -133,7 +133,7 @@ export function getModelOverrides(}export function applyModelOverrides(- db: Database.Database,+ db: Db,platform: string,modelId: string,): boolean {@@ -152,7 +152,7 @@ export function applyModelOverrides(return true;}-export function applyAllModelOverrides(db: Database.Database): number {+export function applyAllModelOverrides(db: Db): number {const rows = db.prepare('SELECT platform, model_id FROM model_overrides').all() as { platform: string; model_id: string }[];let applied = 0;for (const row of rows) {@@ -161,7 +161,7 @@ export function applyAllModelOverrides(db: Database.Database): number {return applied;}-export function deleteTombstonedCatalogModels(db: Database.Database): number {+export function deleteTombstonedCatalogModels(db: Db): number {const chatRows = db.prepare(`SELECT m.id, m.platform, m.model_idFROM models mdiff --git a/server/src/services/quirks.ts b/server/src/services/quirks.tsindex 2f4706db..6539425f 100644Binary files a/server/src/services/quirks.ts and b/server/src/services/quirks.ts differdiff --git a/server/src/services/router.ts b/server/src/services/router.tsindex 9191662e..91f5f371 100644--- a/server/src/services/router.ts+++ b/server/src/services/router.ts@@ -11,7 +11,7 @@ import { parseBudget } from '../lib/budget.js';import { isUnifyEnabled, getModelGroups, resolveRequestedIdToMembers } from './model-groups.js';import type { BaseProvider } from '../providers/base.js';import type { Platform } from '@freellmapi/shared/types.js';-import type { Database } from 'better-sqlite3';+import type { Db } from '../db/types.js';class RouteError extends Error {status: number;@@ -300,7 +300,7 @@ function decayWeight(ageDays: number): number {return Math.pow(0.5, Math.max(0, ageDays) / HALF_LIFE_DAYS);}-export function refreshStatsCache(db: Database, force = false): void {+export function refreshStatsCache(db: Db, force = false): void {if (!force && statsCache && Date.now() - statsCacheTime < CACHE_TTL_MS) return;const since = new Date(Date.now() - WINDOW_MS).toISOString();@@ -483,7 +483,7 @@ const GLOBAL_SORT_ALIASES: Record<string, string> = {balanced: 'balanced',};-function getActiveChain(db: Database): ChainRow[] {+function getActiveChain(db: Db): ChainRow[] {const activeProfileSetting = db.prepare("SELECT value FROM settings WHERE key = 'active_profile_id'").get() as { value: string } | undefined;if (activeProfileSetting) {const profileId = parseInt(activeProfileSetting.value, 10);@@ -514,7 +514,7 @@ function getActiveChain(db: Database): ChainRow[] {`).all() as ChainRow[];}-function getChainByProfileName(db: Database, name: string): ChainRow[] | null {+function getChainByProfileName(db: Db, name: string): ChainRow[] | null {const profile = db.prepare("SELECT id FROM profiles WHERE LOWER(name) = ?").get(name.toLowerCase()) as { id: number } | undefined;if (!profile) return null;@@ -531,7 +531,7 @@ function getChainByProfileName(db: Database, name: string): ChainRow[] | null {`).all(profile.id) as ChainRow[];}-function getChainByGlobalSort(db: Database, globalAxis: string): ChainRow[] {+function getChainByGlobalSort(db: Db, globalAxis: string): ChainRow[] {const allEnabled = db.prepare(`SELECT m.id as model_db_id, 0 as priority, 1 as enabled,m.platform, m.model_id, m.display_name, m.intelligence_rank,@@ -699,7 +699,7 @@ function selectKeyForModel(entry: ChainRow, estimatedTokens: number, skipKeys?:/*** Fetch a single enabled model's chain row by its db id.*/-function getModelChainRow(db: Database, modelDbId: number): ChainRow | undefined {+function getModelChainRow(db: Db, modelDbId: number): ChainRow | undefined {return db.prepare(`SELECT m.id as model_db_id, 0 as priority, 1 as enabled,m.platform, m.model_id, m.display_name, m.intelligence_rank,