Files
OmniRoute/src/lib/db/settings.ts
Diego Rodrigues de Sa e Souza fa367dd99e Release v3.8.27 (#3968)
* chore(release): open v3.8.27 development cycle

* fix(security): polynomial ReDoS in comboAgentMiddleware regex (#3982)

* fix(security): eliminate polynomial ReDoS in comboAgentMiddleware <omniModel> regex (CodeQL js/polynomial-redos)

CACHE_TAG_PATTERN wrapped the tag in an unbounded `(?:\\n|\n|\r)*` prefix/suffix.
On an unanchored `.test()`/`.exec()` that is O(n²) on inputs with many newlines
(CodeQL js/polynomial-redos, alerts #612/#613). The surrounding runs are irrelevant
to detecting/capturing the tag, so the detection pattern now matches only the core
`<omniModel>([^<]+)</omniModel>`; the global strip pattern still consumes the
wrapping newlines (combo.ts streaming, #531) but BOUNDED ({0,16}) so it stays linear.

Behavior preserved: detection, model extraction, multi-tag stripping (#454) and
blank-line cleanup all unchanged (107 related tests green). Adds ReDoS-safety
regression tests (50k-newline inputs complete in <1ms).

* docs(changelog): add #3982 ReDoS fix to [3.8.27]

* ci(security): harden workflows — artipacked persist-credentials + cache-poisoning + SC2086 (#3965)

* Refine provider quota card display (#3969)

Integrated into release/v3.8.27

* feat: add sidebar group separator toggles (#3971)

Integrated into release/v3.8.27

* Gate control-plane proxy direct fallback (#3963)

Integrated into release/v3.8.27

* Capture actual upstream provider requests (#3941)

Integrated into release/v3.8.27

* ci(quality): flip require-tighten + osv + Trivy to blocking (v3.8.27 cycle-end) (#3984)

* fix(resilience): respect connection cooldown stored as numeric epoch (#3954) (#3995)

rate_limited_until is a TEXT column, but setConnectionRateLimitUntil (Antigravity full-quota path) persists a raw epoch number that SQLite coerces to a numeric string ("1781696905131.0"). The selection predicate isAccountUnavailable then did new Date("1781696905131.0") -> NaN, so the cooling connection was never skipped and the router kept dispatching to rate-limited accounts. Normalize numeric-epoch strings (and number/Date/ISO) via a shared cooldownUntilMs() helper in isAccountUnavailable / getEarliestRateLimitedUntil / filterAvailableAccounts / parseFutureDateMs. ISO behavior preserved.

* fix(providers): fetch live /models for LLM7 and BytePlus (#3976) (#3996)

llm7 and byteplus carry a real modelsUrl but were not classified by any live-fetch branch of the model-import route, so their hardcoded 4-entry registry catalog was served (source local_catalog) instead of the upstream catalog. Add both to NAMED_OPENAI_STYLE_PROVIDERS so the route probes <baseUrl>/models and serves the live list, falling back to the local catalog only on fetch failure.

* fix(dashboard): logs auto-refresh reads live visibility, not a stale mount ref (#3972) (#3997)

The auto-refresh interval gated each tick on visibleRef, seeded once at mount and updated only by a visibilitychange event. A tab mounted while document.visibilityState is 'hidden' (background load, bfcache, embedded/proxied webviews) with no later visibilitychange left the ref false forever, so the interval ticked but never fetched — only the manual button worked. Read the live document.visibilityState in the tick instead.

* feat(compression): add Indonesian caveman rules and language pack (#3975)

Integrated into release/v3.8.27

(cherry picked from commit c9b5b1a892)

* fix(combo): shuffle strict-random fallback remainder to spread load (#3959) (#3998)

strict-random shuffled only the deck-selected slot 0 and left the fallback remainder in fixed priority order, so after a failing deck pick the chain always fell through to the same top-priority model — a persistently-failing model was retried on essentially every request and fallback load never spread across peers. Shuffle the remainder too (like the random strategy).

* Add provider auth visibility controls (#3953)

Integrated into release/v3.8.27

* fix(claude): forward client tool-search-tool anthropic-beta on the Claude OAuth path (#3974) (#3999)

The client-negotiated anthropic-beta: tool-search-tool-2025-10-19 was dropped on both Claude code paths (default executor rebuilt from static ANTHROPIC_BETA_CLAUDE_OAUTH; selectBetaFlags only read the client beta to gate thinking/effort), so claude.ai rejected deferred-tool requests with 400 'Tool reference not found'. Add an allowlist-merge (mergeClientAnthropicBeta) that unions the client's allowlisted betas into the outbound set on both paths, preserving #3415 (no forced thinking/effort).

* feat(providers): add model search filter to provider dashboard (#3950)

Integrated into release/v3.8.27

* fix(vision-bridge): force bridge for tokenrouter deepseek models (#3946)

Integrated into release/v3.8.27

* fix(executor): strip stream_options on non-streaming requests (#3884) (#4000)

Clients that send stream_options:{include_usage:true} regardless of stream (e.g. the OpenAI Python SDK) had it passed through on non-streaming calls; NVIDIA NIM rejected it with 400 'Stream options can only be defined when stream=True'. DefaultExecutor.transformRequest only injected/cleared stream_options on the streaming branch and never stripped a client-sent value when stream=false. Add a !stream strip branch; the streaming injection path is unchanged. Global to openai-compat providers.

* fix(qwen-web): cookie validation false-positive - check response body for user object (#3958)

Integrated into release/v3.8.27

* fix(db): persist backup retention days (#3970)

Integrated into release/v3.8.27

* 大量UI显示和i18n优化 (#3973)

Integrated into release/v3.8.27

* deps: bump the npm_and_yarn group across 1 directory with 2 updates (#3943)

Integrated into release/v3.8.27

* deps: bump form-data from 4.0.5 to 4.0.6 (#3944)

Integrated into release/v3.8.27

* deps: bump vite from 8.0.5 to 8.0.16 (#3942)

Integrated into release/v3.8.27

* chore(quality): re-baseline validation.ts 4407->4428 (#3958 qwen body-check)

The qwen-web validation body-check merged in #3958 pushed validation.ts past its
frozen size on the integrated release tip. Bump the baseline with justification;
no logic is separately extractable from the existing qwen-web validation branch.

* deps: bump the production group with 13 updates (#3915)

Integrated into release/v3.8.27 — low-risk group (playwright 1.60→1.61 minor + transitive patches; fumadocs-core 16.9→16.10 minor).

* chore(deps): ignore jscpd major bumps (v5 Rust rewrite breaks the duplication gate)

Our duplication ratchet (scripts/check/check-duplication.mjs) is pinned to jscpd@4
and parses jscpd-report.json against a frozen baseline. jscpd v5 is a native Rust
binary with no Node.js API and a different report/bin, so a major bump would break
the gate. Migrate deliberately, not via dependabot. Closes the noise from #3916.

* fix(perplexity-web): parse schematized diff_block stream so answers aren't empty (#4001)

Integrated into release/v3.8.27 — schematized diff_block parsing follow-up to #3938.

* refactor: modularize providerRegistry.ts into 159 individual provider plugins (#3993)

Modularize provider registry (#3594). Integrated into release/v3.8.27 after rebase + behavior-preservation verification (provider-consistency gate 159/232/0, typecheck, registry tests, build 556/556).

Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com>

* fix(registry): restore byteplus + mimocode dropped by #3993 modularization

The provider-registry modularization (#3993) was cut from a base predating the
byteplus (#3877) and mimocode (#3837) registry entries, so merging it silently
dropped both providers (getRegistryEntry returned undefined → validation reported
'not supported'). Re-add them as registry modules in the new structure; registered
count 159→161, provider-consistency 161/232/0.

Also align the pre-existing qwen-web validator test to #3958: since the validator
now requires a real `user` object in the 200 body, the mock must carry one.

* refactor: modularize schemas (non-stacked) (#3988)

Modularize validation schemas (#3594). Integrated into release/v3.8.27 after rebase (reconciled the merged hiddenSidebarGroupLabels #3971 + intelligenceSyncRequestSchema into the new modules) + behavior verification (typecheck, 195 schema/settings/validation tests, build 556/556).

Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com>

* fix(default-executor): honor custom providerSpecificData.baseUrl for OpenAI-format providers (#4002)

Integrated into release/v3.8.27 — honor custom providerSpecificData.baseUrl in DefaultExecutor (openai-format), tested.

* feat(openai): honor custom base URL in model discovery + complete openai/codex pricing (#4005)

Integrated into release/v3.8.27 — openai model-discovery honors custom base URL (SSRF-guarded) + pricing rows for new openai/codex models. Tested + baselines bumped.

* fix(live-ws): bridge sidecar events to dashboard (#4004)

Integrated into release/v3.8.27 — repair LiveWS sidecar (startup, same-origin /live-ws, main→sidecar compression.completed bridge, early-msg queue). Fixed the cookie-parse regex (\s) + added a focused unit test; baseline bumped for the non-blocking chatCore bridge.

* docs(troubleshooting): note MITM proxy cannot intercept Windows-host apps under WSL (#4003)

Integrated into release/v3.8.27 — MITM/WSL troubleshooting note.

* fix(repo): untrack accidentally-committed root node_modules symlink + gitignore it

A worktree node_modules symlink (-> the main checkout's node_modules) was staged by a
`git add -A` during the #3988 merge and committed into 05213ac6a. The symlink points
at the repo's own node_modules path, so checking it out turns the main checkout's
node_modules into a self-referential symlink (breaking tsx/all node ops). Untrack it and
add a root-anchored /node_modules ignore so the symlink form can't be re-committed (the
existing 'node_modules/' only matches directories).

* fix(quality): allowlist socks dep (declared by #4004, never allowlisted)

socks@^2.8.7 was added to package.json in #4004 (LiveWS sidecar, 02302131f)
as a phantom-dep cleanup but never added to dependency-allowlist.json, so
check:deps has been red on the release tip ever since. socks is the standard
SOCKS proxy client (dep of fetch-socks), legitimate and years old.

* feat(sse): real LLMLingua-2 ONNX compression engine (stable) (#4014)

Integrated into release/v3.8.27.

Adjustments before merge:
- Synced with the current release tip (was 11 commits behind).
- Added the 3 LLMLingua-2 ONNX optional-runtime deps to dependency-allowlist.json
  (@atjsh/llmlingua-2, @tensorflow/tfjs, js-tiktoken) — the only gate that was red.
- socks was allowlisted directly on release (separate fix d7db5c73d; it was declared
  by #4004 but never allowlisted, leaving check:deps red release-wide).

Verified locally: check:deps OK, file-size OK, public-creds OK, provider-consistency
161/232/0, typecheck:core clean, 24/24 LLMLingua tests pass. The only remaining Fast-QG
red is the pre-existing #3972 orphan test (request-logger-autorefresh-visibility-3972.test.tsx),
which is release-wide and unrelated to this PR.

* test(dashboard): rehome #3972 logs auto-refresh test so a runner collects it

tests/unit/request-logger-autorefresh-visibility-3972.test.tsx (added by #3972
via #3997) sat at the top level of tests/unit/ as a .tsx vitest test, which NO
runner collects: the node runner only globs *.test.ts, and test:vitest:ui only
runs tests/unit/ui. So the #3972 regression guard never executed in CI and
check:test-discovery was red release-wide. Move it under tests/unit/ui/ (the
collected vitest:ui path) and fix the relative import depth. Verified: the test
now runs and passes (2/2), and check:test-discovery is green.

* feat(compression): capture per-engine analytics (#3960) + Lite schema fix (#3952) (#4018)

Captures the net-new value from #3960 (per-engine breakdown analytics) and #3952 (Lite engine schema fix) onto release/v3.8.27. Fast QG green; 622/622 compression+analytics tests pass.

* fix(sse): guard model-less registry entries in getUnsupportedParams (mimocode) (#4015)

Real bugfix: guard model-less registry entries (mimocode) in getUnsupportedParams so handleChatCore no longer throws 'entry.models is not iterable' / reports 'All models failed' for unrelated requests. Includes a regression test. Fast QG green.

* feat(ci): Quality Gate v2 — Onda 0 + Onda 1 (gate flips, TIA, SAST, DAST-smoke, mutation infra) (#4016)

* docs(ops): add quality-gate assessment + replication playbook (Fase 9 foundation)

* feat(ci): flip oasdiff breaking-change gate to blocking (ratchet)

* docs(ops): deliver main branch-protection ruleset for owner to apply

* fix(ci): run typecheck:core in PR->release fast-gates (close fast-gates hole, part 1)

* perf(mutation): enable Stryker incremental mode + cache (scales the 60/80 rollout)

* feat(ci): commit CodeQL advanced config (security-extended), replacing default-setup

* feat(ci): version semgrep SAST workflow (owasp/secrets), advisory

* feat(quality): TIA test-impact map builder (import-graph; map built at runtime, gitignored)

* feat(quality): TIA impacted-test selector with run-all fail-safe

* fix(ci): run TIA-impacted unit tests in PR->release fast-gates (build map at runtime, fail-safe full)

* feat(ci): DAST-smoke per-PR (schemathesis subset + promptfoo injection-guard, blocking)

* fix(ci): unbreak Fase 9 PR CI (MDX frontmatter, CodeQL conflict, dast-smoke advisory)

- Add MDX frontmatter to docs/ops/{BRANCH_PROTECTION_MAIN,QUALITY_GATE_PLAYBOOK}.md.
  fumadocs rejects frontmatter-less docs -> 'npm run build' failed -> broke dast-smoke's
  build step (the release fast-gates never runs build, so this only surfaced on the PR).
- codeql.yml: workflow_dispatch-only until the owner switches repo CodeQL Default->Advanced
  (advanced configs cannot be processed while default setup is enabled; documented inline).
- dast-smoke.yml: job-level continue-on-error (advisory) so this brand-new gate matures
  before it blocks (repo convention: advisory -> blocking).

* ci(quality): make TIA unit-test step advisory until release test-debt is cleared

release/v3.8.27 carries ~17 pre-existing failing unit tests (budget #3537, apiKey
#3552, several Zod schemas, Puter/Qwen executors, mimocode entry, etc.) unrelated to
this PR — the new 'run tests on PR->release' gate surfaced them. Per the repo's
advisory->blocking convention, this step enters advisory (it still runs + reports)
so pre-existing debt doesn't block the gate program. typecheck:core stays blocking.
Flip to blocking (remove continue-on-error) once the release suite is green.

* fix(sse): preserve Kiro streaming finish_reason tool_calls (#3980) (#4025)

* fix(guardrails): preserve original image when vision-bridge describe fails (#4012) (#4026)

* feat(api): advertise combo capabilities on import surfaces (#3979) (#4027)

* feat(sse): delegated Anthropic Context Editing for Claude (clear_tool_uses) (#4021)

Opt-in Claude-only delegated compression: injects context_management.clear_tool_uses_20250919 at the Claude pre-serialization chokepoint (composes with clear_thinking, thinking first), threaded via ExecuteInput from handleChatCore. Pure edit-builder + 11 tests (7 unit + 4 e2e fetch-capture). Beta context-management-2025-06-27 already advertised; allowlist done. Telemetry/400-fallback/claude-web coverage deferred.

* fix(opencode): map x-session-affinity to x-opencode-session for custom providers (#4022) (#4028)

* fix(dashboard): Playground Compare tab loading + HTTP method guard (#4024)

randomUUID non-HTTPS fallback + static CompareTab import; raw HTTP TRACE->405 method guard wired into dev + standalone servers. Integrated into release/v3.8.27.

* refactor(dashboard): settings UI layout + API Keys naming (#4020)

Presentation/relabel refactor of the Settings dashboard (API Manager -> API Keys), card relocations, Toggle adoption, present-but-disabled engine steps. Auth-file changes are string/comment-only (no behavior change). Integrated into release/v3.8.27.

* fix: restore unit regressions dropped by lossy schema/registry modularizations (#4030)

Restores schema fields (combo reasoningTokenBuffer, budget-0 #3537, openrouter preset, proxy family #3777, resilience degradation/providerCooldown), qwen-web v2 endpoint+catalog, mimocode models key — all dropped by #3988/#3993 — and aligns 3 tests to #3941/#3993. Verified: 8 failing regression tests on release tip -> 131/131 green on this branch. Integrated into release/v3.8.27.

* fix(api): return 400 (not 500) for malformed JSON on /api/auth/login (#4031)

Wrap request.json() so a malformed/non-JSON login body returns a structured 400 instead of falling through to the 500 catch. Fixes the schemathesis high-risk-endpoint DAST finding (verified: schemathesis step now passes). +TDD test. Integrated into release/v3.8.27.

* feat(dashboard): real circuit-breaker state in the Combo Live cascade (U1b) (#4029)

Overlays real provider circuit-breaker state (GET /api/monitoring/health) onto the Combo Live cascade as a 'CB: OPEN · 41s' badge. Pure enrichRunWithBreakers + fail-soft useProviderBreakerHealth poll; graceful when health is absent. +13 tests. Integrated into release/v3.8.27.

* Fix promptfoo security assertion parsing (#4032)

* chore(deps): dependabot security bumps + drop unused gray-matter (#4036)

Integrated into release/v3.8.27 — dependabot security bumps (form-data/js-yaml/protobufjs/dompurify/hono) + drop unused gray-matter. Unblocks the npm audit:deps gate (Lint) branch-wide.

* fix(ci): scope TIA to node:test unit files only (mirror test:unit glob) (#4035)

Integrated into release/v3.8.27 — scopes the advisory TIA step to the test:unit node:test glob, fixing the 99 false failures. +4 TDD.

* Refine compression settings, storage labels, and sidebar grouping (#4033)

Integrated into release/v3.8.27 — relocate Token Saver into Compression Settings (controlled component), reorder Security/Authz tabs, storage labels + i18n relabel. Thanks @rdself!

* [codex] add per-key local usage command (#4034)

Integrated into release/v3.8.27 — per-key local @@om-usage command (cached quota, no upstream routing). Rebased onto modularized schemas/keys.ts + file-size rebaseline. Thanks @Witroch4!

* chore(release): reconcile v3.8.27 CHANGELOG + i18n mirrors

* ci(quality): unblock v3.8.27 release gates (zizmor pin + test-masking allowlist)

- zizmor ratchet (151→139, no regression): SHA-pin every action ref ADDED this
  cycle — codeql/dast-smoke/semgrep (3 new workflows) + trivy-action (docker-publish)
  + actions/cache (nightly-mutation). Pre-existing tag refs keep the repo convention.
- test-masking: add config/quality/test-masking-allowlist.json + allowlist support in
  check-test-masking.mjs (exempts ONLY the net-assert-reduction signal; tautology/skip/
  deletion still fire). Allowlists 2 verified-legitimate reductions:
  appearance-widget-settings-schema (#4033 removed showTokenSaverOnEndpoint field) and
  dashboard-shell-tabs (#3973 tabs→redirect refactor, asserts replaced). +4 gate tests.

* test(quality): reword test-masking self-test comments to avoid literal masking patterns

The added allowlist-test comments contained the literal strings 'assert.ok(true)' and
'.skip' which the masking detector's own regexes match as text — making the gate flag
its own test file (net +1 tautology/skip/extended-tautology vs main). Reworded to plain
prose ('a new tautology', 'a new skip marker'); test logic unchanged (24/24 pass).

* fix(quality): unblock v3.8.27 release — align 3 stale tests + restore modularized settings-schema parity

Release-PR full CI surfaced 3 deterministic test failures (no live product regression),
all stale vs legitimate cycle changes:

- settings-schema parity (#3988): the modularized updateSettingsSchema barrel
  (schemas/settings.ts) had diverged from the canonical settingsSchemas.ts (45 vs 85
  fields — 40 dropped + 6 extra), a lossy-modularization dead-code copy. Re-export from
  the canonical source so the barrel can never diverge again (runtime already uses
  canonical). Parity test now passes.
- api-manager permissions modal: #4034 added a 4th self-service switch (per-key usage
  allowance); a11y invariant (every switch type="button") still holds. Updated the
  static count 3 -> 4.
- pack-artifact policy: dist/http-method-guard.cjs became a required runtime path;
  added it to the test's expected missing-paths list.

Also documents the gate gap for Fase 9 (QUALITY_GATE_PLAYBOOK Parte 6): G1 run the
deterministic unit layer + test-masking on PR->release (not just PR->main), G2 a
modularization-parity gate (would have caught the #3988 drop at its PR), G3 flake
quarantine. Env flakes (LiveWS startup timeout, integration server-startup cascade)
are pre-existing/CI-env, triaged separately.

---------

Co-authored-by: Randi <55005611+rdself@users.noreply.github.com>
Co-authored-by: Veier04 <118300867+Veier04@users.noreply.github.com>
Co-authored-by: Felipe Sartori <felipesartori.ti@gmail.com>
Co-authored-by: WormAlien <164898390+WormAlien@users.noreply.github.com>
Co-authored-by: thezukiru <121331256+thezukiru@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: NOXX - Commiter <artur1992123@mail.ru>
Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com>
Co-authored-by: Demiurge The Single <megamen932@gmail.com>
Co-authored-by: Witroch4 <witalo_rocha@hotmail.com>
2026-06-17 02:43:21 -03:00

1149 lines
38 KiB
TypeScript

/**
* db/settings.js — Settings, pricing, and proxy config.
*/
import { getDbInstance } from "./core";
import { backupDbFile } from "./backup";
import { PROVIDER_ID_TO_ALIAS } from "@omniroute/open-sse/config/providerModels.ts";
import { invalidateDbCache } from "./readCache";
import { getProxyRegistryGeneration, resolveProxyForScopeFromRegistry } from "./proxies";
import { getComboModelProvider as getComboEntryProvider } from "@/lib/combos/steps";
import { requestBodyLimitMbFromEnv } from "@/shared/constants/bodySize";
import { DEFAULT_RESPONSES_PREVIOUS_RESPONSE_ID_MODE } from "@/shared/constants/responsesPreviousResponseId";
type JsonRecord = Record<string, unknown>;
type PricingModels = Record<string, JsonRecord>;
type PricingByProvider = Record<string, PricingModels>;
export type PricingSource = "default" | "litellm" | "modelsDev" | "user";
export type PricingSourceMap = Record<string, Record<string, PricingSource>>;
type ProxyValue = JsonRecord | string | null;
type ProxyResolutionResult = {
proxy: ProxyValue;
level: string;
levelId: string | null;
source?: string;
};
type ProxyResolutionCacheEntry = {
generation: number;
registryGeneration: number;
result: ProxyResolutionResult;
};
const PROXY_RESOLUTION_CACHE_MAX_ENTRIES = 100;
function isTruthyEnvFlag(value: string | undefined): boolean {
return typeof value === "string" && /^(1|true|yes|on)$/i.test(value.trim());
}
let proxyConfigGeneration = 0;
const proxyResolutionCache = new Map<string, ProxyResolutionCacheEntry>();
export function bumpProxyConfigGeneration() {
proxyConfigGeneration++;
proxyResolutionCache.clear();
}
function cacheProxyResolution(
connectionId: string,
generation: number,
registryGeneration: number,
result: ProxyResolutionResult
) {
if (generation !== proxyConfigGeneration) return;
if (registryGeneration !== getProxyRegistryGeneration()) return;
if (proxyResolutionCache.size >= PROXY_RESOLUTION_CACHE_MAX_ENTRIES) {
const oldestKey = proxyResolutionCache.keys().next().value;
if (oldestKey) proxyResolutionCache.delete(oldestKey);
}
proxyResolutionCache.set(connectionId, { generation, registryGeneration, result });
}
type ProxyMap = Record<string, ProxyValue>;
interface ProxyConfig {
global: ProxyValue;
providers: ProxyMap;
combos: ProxyMap;
keys: ProxyMap;
[key: string]: unknown;
}
function toRecord(value: unknown): JsonRecord {
return value && typeof value === "object" ? (value as JsonRecord) : {};
}
function toProxyMap(value: unknown): ProxyMap {
return value && typeof value === "object" ? (value as ProxyMap) : {};
}
function toProxyValue(value: unknown): ProxyValue {
if (value === null || typeof value === "string") return value as string | null;
if (value && typeof value === "object") return value as JsonRecord;
return null;
}
// Legacy proxyConfig store (key_value namespace 'proxyConfig') predates the
// IPv6-only `family` directive, so its object configs have no family field.
// Default to "auto" so the family marker rides along the cascade end-to-end
// (consumed by proxyConfigToUrl). String configs are returned unchanged.
function withFamilyDefault(value: ProxyValue): ProxyValue {
if (value && typeof value === "object" && !Array.isArray(value)) {
const record = value as JsonRecord;
if (typeof record.family === "string") return record;
return { ...record, family: "auto" };
}
return value;
}
// ──────────────── Settings ────────────────
export async function getSettings() {
const db = getDbInstance();
const rows = db.prepare("SELECT key, value FROM key_value WHERE namespace = 'settings'").all();
const settings: Record<string, unknown> = {
cloudEnabled: true,
tailscaleEnabled: false,
tailscaleUrl: "",
stickyRoundRobinLimit: 3,
requestRetry: 3,
maxRetryIntervalSec: 30,
antigravitySignatureCacheMode: "enabled",
requireLogin: true,
mcpEnabled: false,
a2aEnabled: false,
hiddenSidebarItems: [],
hiddenSidebarGroupLabels: [],
sidebarSectionOrder: [],
sidebarItemOrder: {},
sidebarActivePreset: null,
hideEndpointCloudflaredTunnel: false,
hideEndpointTailscaleFunnel: false,
hideEndpointNgrokTunnel: false,
preferClaudeCodeForUnprefixedClaudeModels: isTruthyEnvFlag(
process.env.OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS
),
autoRefreshProviderQuota: false,
autoRefreshProviderQuotaInterval: 180,
comboConfigMode: "guided",
codexServiceTier: { enabled: false },
claudeFastMode: {
enabled: false,
supportedModels: ["claude-fable-5", "claude-opus-4-8", "claude-opus-4-7", "claude-opus-4-6"],
},
codexSessionAffinityTtlMs: 0,
responsesPreviousResponseIdMode: DEFAULT_RESPONSES_PREVIOUS_RESPONSE_ID_MODE,
alwaysPreserveClientCache: "auto",
idempotencyWindowMs: 5000,
wsAuth: false,
maxBodySizeMb: requestBodyLimitMbFromEnv(process.env.MAX_BODY_SIZE_BYTES),
debugMode: true,
// LOCAL_ONLY manage-scope bypass policy defaults (T-011 / spec §Data Model).
// Preserves PR #2473 behaviour on migration — the bypass starts ENABLED
// for `/api/mcp/` so existing manage-scope Bearer clients keep working.
// Operators flip the kill-switch to false (or drop the prefix) via the
// Settings UI; the change hot-reloads through `applyRuntimeSettings` →
// `applyAuthzBypassSection` → `getAuthzBypassSnapshot()`.
localOnlyManageScopeBypassEnabled: true,
localOnlyManageScopeBypassPrefixes: ["/api/mcp/"],
customBannedSignals: [],
proxyEnabled: true,
perKeyProxyEnabled: false,
};
for (const row of rows) {
const record = toRecord(row);
const key = typeof record.key === "string" ? record.key : null;
const rawValue = typeof record.value === "string" ? record.value : null;
if (!key || rawValue === null) continue;
settings[key] = JSON.parse(rawValue);
}
// Auto-complete onboarding for pre-configured deployments (Docker/VM)
// If INITIAL_PASSWORD is set via env, this is a headless deploy — skip the wizard
if (!settings.setupComplete && process.env.INITIAL_PASSWORD) {
settings.setupComplete = true;
settings.requireLogin = true;
db.prepare(
"INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES ('settings', 'setupComplete', 'true')"
).run();
db.prepare(
"INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES ('settings', 'requireLogin', 'true')"
).run();
}
return settings;
}
export async function updateSettings(updates: Record<string, unknown>) {
const db = getDbInstance();
const insert = db.prepare(
"INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES ('settings', ?, ?)"
);
const tx = db.transaction(() => {
for (const [key, value] of Object.entries(updates)) {
insert.run(key, JSON.stringify(value));
}
});
tx();
backupDbFile("pre-write");
invalidateDbCache("settings"); // Bust the read cache immediately
// Bust proxy resolution cache when proxy toggle settings change
const PROXY_TOGGLE_KEYS = ["proxyEnabled", "perKeyProxyEnabled"];
if (Object.keys(updates).some((k) => PROXY_TOGGLE_KEYS.includes(k))) {
bumpProxyConfigGeneration();
}
const nextSettings = await getSettings();
try {
const { applyRuntimeSettings } = await import("@/lib/config/runtimeSettings");
await applyRuntimeSettings(nextSettings, { source: "settings:update" });
} catch (error) {
console.warn(
"[HOT_RELOAD] Failed to apply runtime settings after update:",
error instanceof Error ? error.message : error
);
}
return nextSettings;
}
export async function isCloudEnabled() {
const settings = await getSettings();
return settings.cloudEnabled === true;
}
// ──────────────── Pricing ────────────────
function readPricingNamespace(
db: ReturnType<typeof getDbInstance>,
namespace: string
): PricingByProvider {
const rows = db.prepare("SELECT key, value FROM key_value WHERE namespace = ?").all(namespace);
const pricing: PricingByProvider = {};
for (const row of rows) {
const record = toRecord(row);
const key = typeof record.key === "string" ? record.key : null;
const rawValue = typeof record.value === "string" ? record.value : null;
if (!key || rawValue === null) continue;
try {
pricing[key] = toRecord(JSON.parse(rawValue)) as PricingModels;
} catch {
// Corrupted data — skip silently, fallback to lower layers
}
}
return pricing;
}
function mergePricingLayers(layers: PricingByProvider[]): PricingByProvider {
const mergedPricing: PricingByProvider = {};
for (const layer of layers) {
for (const [provider, models] of Object.entries(layer)) {
if (!mergedPricing[provider]) {
mergedPricing[provider] = { ...models };
continue;
}
for (const [model, pricing] of Object.entries(models)) {
mergedPricing[provider][model] = mergedPricing[provider][model]
? { ...(mergedPricing[provider][model] || {}), ...toRecord(pricing) }
: pricing;
}
}
}
return mergedPricing;
}
function buildPricingSourceMap(layers: {
defaults: PricingByProvider;
litellm: PricingByProvider;
modelsDev: PricingByProvider;
user: PricingByProvider;
}): PricingSourceMap {
const sourceMap: PricingSourceMap = {};
const mergedPricing = mergePricingLayers([
layers.defaults,
layers.litellm,
layers.modelsDev,
layers.user,
]);
for (const [provider, models] of Object.entries(mergedPricing)) {
sourceMap[provider] = {};
for (const model of Object.keys(models)) {
if (layers.user[provider]?.[model]) {
sourceMap[provider][model] = "user";
} else if (layers.modelsDev[provider]?.[model]) {
sourceMap[provider][model] = "modelsDev";
} else if (layers.litellm[provider]?.[model]) {
sourceMap[provider][model] = "litellm";
} else {
sourceMap[provider][model] = "default";
}
}
}
return sourceMap;
}
async function getPricingLayers() {
const db = getDbInstance();
// Layer 1: Hardcoded defaults (lowest priority)
const { getDefaultPricing } = await import("@/shared/constants/pricing");
return {
defaults: getDefaultPricing(),
litellm: readPricingNamespace(db, "pricing_synced"),
modelsDev: readPricingNamespace(db, "models_dev_pricing"),
user: readPricingNamespace(db, "pricing"),
};
}
export async function getPricing() {
const layers = await getPricingLayers();
// Merge: defaults → LiteLLM → models.dev → user (each layer overrides the previous)
return mergePricingLayers([layers.defaults, layers.litellm, layers.modelsDev, layers.user]);
}
export async function getPricingWithSources(): Promise<{
pricing: PricingByProvider;
sourceMap: PricingSourceMap;
}> {
const layers = await getPricingLayers();
return {
pricing: mergePricingLayers([layers.defaults, layers.litellm, layers.modelsDev, layers.user]),
sourceMap: buildPricingSourceMap(layers),
};
}
export async function getPricingForModel(provider: string, model: string) {
const pricing = await getPricing();
const findKeyInsensitive = <T>(
obj: Record<string, T> | undefined | null,
key: string
): T | undefined => {
if (!obj || !key) return undefined;
const lowerKey = key.toLowerCase();
for (const [k, v] of Object.entries(obj)) {
if (k.toLowerCase() === lowerKey) return v;
}
return undefined;
};
const pLower = (provider || "").toLowerCase();
let providerPricing = findKeyInsensitive<PricingModels>(pricing, pLower);
if (!providerPricing) {
const alias = findKeyInsensitive<string>(PROVIDER_ID_TO_ALIAS, pLower);
if (alias) providerPricing = findKeyInsensitive(pricing, alias);
}
if (!providerPricing) {
for (const [id, mappedAlias] of Object.entries(PROVIDER_ID_TO_ALIAS)) {
if (typeof mappedAlias === "string" && mappedAlias.toLowerCase() === pLower) {
providerPricing = findKeyInsensitive(pricing, id);
if (providerPricing) break;
}
}
}
if (!providerPricing) {
const np = pLower.replace(/-cn$/, "");
if (np && np !== pLower) {
providerPricing = findKeyInsensitive(pricing, np);
}
}
if (!providerPricing) return null;
const mLower = (model || "").toLowerCase();
let modelPricing = findKeyInsensitive<JsonRecord>(providerPricing, mLower);
if (!modelPricing) {
const hyphenModel = mLower.replace(/\./g, "-");
modelPricing = findKeyInsensitive(providerPricing, hyphenModel);
}
return modelPricing || null;
}
export async function updatePricing(pricingData: PricingByProvider) {
const db = getDbInstance();
const insert = db.prepare(
"INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES ('pricing', ?, ?)"
);
const rows = db.prepare("SELECT key, value FROM key_value WHERE namespace = 'pricing'").all();
const existing: PricingByProvider = {};
for (const row of rows) {
const record = toRecord(row);
const key = typeof record.key === "string" ? record.key : null;
const rawValue = typeof record.value === "string" ? record.value : null;
if (!key || rawValue === null) continue;
existing[key] = toRecord(JSON.parse(rawValue)) as PricingModels;
}
const tx = db.transaction(() => {
for (const [provider, models] of Object.entries(pricingData)) {
insert.run(provider, JSON.stringify({ ...(existing[provider] || {}), ...models }));
}
});
tx();
backupDbFile("pre-write");
invalidateDbCache("pricing"); // Bust the pricing read cache
const updated: PricingByProvider = {};
const allRows = db.prepare("SELECT key, value FROM key_value WHERE namespace = 'pricing'").all();
for (const row of allRows) {
const record = toRecord(row);
const key = typeof record.key === "string" ? record.key : null;
const rawValue = typeof record.value === "string" ? record.value : null;
if (!key || rawValue === null) continue;
updated[key] = toRecord(JSON.parse(rawValue)) as PricingModels;
}
return updated;
}
export async function resetPricing(provider: string, model?: string) {
const db = getDbInstance();
if (model) {
const row = db
.prepare("SELECT value FROM key_value WHERE namespace = 'pricing' AND key = ?")
.get(provider);
if (row) {
const rowRecord = toRecord(row);
const value = typeof rowRecord.value === "string" ? rowRecord.value : "{}";
const models = toRecord(JSON.parse(value));
delete models[model];
if (Object.keys(models).length === 0) {
db.prepare("DELETE FROM key_value WHERE namespace = 'pricing' AND key = ?").run(provider);
} else {
db.prepare("UPDATE key_value SET value = ? WHERE namespace = 'pricing' AND key = ?").run(
JSON.stringify(models),
provider
);
}
}
} else {
db.prepare("DELETE FROM key_value WHERE namespace = 'pricing' AND key = ?").run(provider);
}
backupDbFile("pre-write");
const allRows = db.prepare("SELECT key, value FROM key_value WHERE namespace = 'pricing'").all();
const result: Record<string, unknown> = {};
for (const row of allRows) {
const record = toRecord(row);
const key = typeof record.key === "string" ? record.key : null;
const rawValue = typeof record.value === "string" ? record.value : null;
if (!key || rawValue === null) continue;
result[key] = JSON.parse(rawValue);
}
return result;
}
export async function resetAllPricing() {
const db = getDbInstance();
db.prepare("DELETE FROM key_value WHERE namespace = 'pricing'").run();
backupDbFile("pre-write");
return {};
}
// ──────────────── LKGP (Last Known Good Provider) ────────────────
export interface LKGPRecord {
provider: string;
connectionId?: string;
}
export async function getLKGP(comboName: string, modelId: string): Promise<LKGPRecord | null> {
const db = getDbInstance();
const key = `${comboName}:${modelId}`;
const row = db
.prepare("SELECT value FROM key_value WHERE namespace = 'lkgp' AND key = ?")
.get(key) as { value?: string } | undefined;
if (!row?.value) return null;
try {
const parsed = JSON.parse(row.value);
if (typeof parsed === "object" && parsed !== null && "provider" in parsed) {
return parsed as LKGPRecord;
}
return { provider: String(parsed) };
} catch {
return { provider: row.value };
}
}
export async function setLKGP(
comboName: string,
modelId: string,
providerId: string,
connectionId?: string
) {
const db = getDbInstance();
const key = `${comboName}:${modelId}`;
const value: LKGPRecord = { provider: providerId };
if (connectionId) value.connectionId = connectionId;
db.prepare("INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES ('lkgp', ?, ?)").run(
key,
JSON.stringify(value)
);
}
export function clearAllLKGP(): void {
const db = getDbInstance();
db.prepare("DELETE FROM key_value WHERE namespace = 'lkgp'").run();
}
// ──────────────── Proxy Config ────────────────
const DEFAULT_PROXY_CONFIG: ProxyConfig = { global: null, providers: {}, combos: {}, keys: {} };
const ALIAS_TO_PROVIDER_ID = Object.entries(PROVIDER_ID_TO_ALIAS).reduce(
(acc, [providerId, alias]) => {
if (alias) acc[alias] = providerId;
acc[providerId] = providerId;
return acc;
},
{} as Record<string, string>
);
function resolveProviderAliasOrId(providerOrAlias: string): string {
if (typeof providerOrAlias !== "string") return providerOrAlias;
return ALIAS_TO_PROVIDER_ID[providerOrAlias] || providerOrAlias;
}
function getComboModelProvider(modelEntry: unknown): string | null {
const providerOrAlias = getComboEntryProvider(modelEntry);
return providerOrAlias ? resolveProviderAliasOrId(providerOrAlias) : null;
}
function migrateProxyEntry(value: unknown): JsonRecord | null {
if (!value) return null;
if (typeof value === "object") {
const record = toRecord(value);
if (record.type) return record;
}
if (typeof value !== "string") return null;
try {
const url = new URL(value);
return {
type: url.protocol.replace(":", "") || "http",
host: url.hostname,
port:
url.port ||
(url.protocol === "socks5:" ? "1080" : url.protocol === "https:" ? "443" : "8080"),
username: url.username ? decodeURIComponent(url.username) : "",
password: url.password ? decodeURIComponent(url.password) : "",
};
} catch {
const parts = value.split(":");
return {
type: "http",
host: parts[0] || value,
port: parts[1] || "8080",
username: "",
password: "",
};
}
}
export async function getProxyConfig() {
const db = getDbInstance();
const rows = db.prepare("SELECT key, value FROM key_value WHERE namespace = 'proxyConfig'").all();
const raw: ProxyConfig = { ...DEFAULT_PROXY_CONFIG };
for (const row of rows) {
const record = toRecord(row);
const key = typeof record.key === "string" ? record.key : null;
const rawValue = typeof record.value === "string" ? record.value : null;
if (!key || rawValue === null) continue;
raw[key] = JSON.parse(rawValue);
}
let migrated = false;
if (raw.global && typeof raw.global === "string") {
raw.global = migrateProxyEntry(raw.global);
migrated = true;
}
if (raw.providers) {
for (const [k, v] of Object.entries(raw.providers)) {
if (typeof v === "string") {
raw.providers[k] = migrateProxyEntry(v);
migrated = true;
}
}
}
if (migrated) {
const insert = db.prepare(
"INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES ('proxyConfig', ?, ?)"
);
if (raw.global !== undefined) insert.run("global", JSON.stringify(raw.global));
if (raw.providers) insert.run("providers", JSON.stringify(raw.providers));
}
return raw;
}
export async function getProxyForLevel(level: string, id?: string | null) {
const config = await getProxyConfig();
if (level === "global") return config.global || null;
const map = toProxyMap(config[level + "s"] || config[level] || {});
return (id ? map[id] : null) || null;
}
export async function setProxyForLevel(level: string, id: string | null, proxy: ProxyValue) {
const db = getDbInstance();
const config = await getProxyConfig();
if (level === "global") {
config.global = proxy || null;
db.prepare(
"INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES ('proxyConfig', 'global', ?)"
).run(JSON.stringify(config.global));
} else {
const mapKey = level + "s";
const map = toProxyMap(config[mapKey] || {});
if (proxy && id) {
map[id] = proxy;
} else {
if (id) delete map[id];
}
config[mapKey] = map;
db.prepare(
"INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES ('proxyConfig', ?, ?)"
).run(mapKey, JSON.stringify(map));
}
backupDbFile("pre-write");
bumpProxyConfigGeneration();
return config;
}
export async function deleteProxyForLevel(level: string, id: string | null) {
return setProxyForLevel(level, id, null);
}
export async function resolveProxyForConnection(connectionId: string, apiKeyId?: string) {
const cacheKey = apiKeyId ? `${connectionId}:${apiKeyId}` : connectionId;
const startGeneration = proxyConfigGeneration;
const startRegistryGeneration = getProxyRegistryGeneration();
const cached = proxyResolutionCache.get(cacheKey);
if (
cached &&
cached.generation === startGeneration &&
cached.registryGeneration === startRegistryGeneration
) {
return cached.result;
}
const db = getDbInstance();
// Step 1: Check global proxyEnabled setting
// Read only the proxyEnabled key for performance instead of loading all settings.
let globalProxyEnabled = true;
try {
const proxyEnabledRow = db
.prepare("SELECT value FROM key_value WHERE namespace = 'settings' AND key = 'proxyEnabled'")
.get() as { value?: string } | undefined;
if (proxyEnabledRow?.value) {
globalProxyEnabled = JSON.parse(proxyEnabledRow.value) !== false;
}
} catch {
// Default to true on read error
}
if (!globalProxyEnabled) {
const result: ProxyResolutionResult = { proxy: null, level: "direct", levelId: null };
// Do not cache the "direct" result when global toggle is off so that
// toggling it back on takes effect immediately without a generation bump.
return result;
}
let connectionRecord: JsonRecord | null = null;
let connectionProvider: string | null = null;
let connectionProxyEnabled = true;
let connectionPerKeyProxyEnabled = false;
const row = db
.prepare(
"SELECT provider, proxy_enabled, per_key_proxy_enabled FROM provider_connections WHERE id = ?"
)
.get(connectionId);
if (row) {
connectionRecord = toRecord(row);
connectionProvider =
typeof connectionRecord.provider === "string" ? connectionRecord.provider : null;
connectionProxyEnabled = connectionRecord.proxy_enabled !== 0;
connectionPerKeyProxyEnabled = connectionRecord.per_key_proxy_enabled === 1;
}
// A connection-level Proxy Off is explicit: it must bypass every stored proxy
// source for this connection, including account, provider, global, and automatic
// fallback candidates from the proxy pool.
if (connectionRecord && !connectionProxyEnabled) {
const result: ProxyResolutionResult = { proxy: null, level: "direct", levelId: null };
cacheProxyResolution(cacheKey, startGeneration, startRegistryGeneration, result);
return result;
}
// Step 1.5: Check global perKeyProxyEnabled setting
let globalPerKeyProxyEnabled = false;
try {
const perKeyRow = db
.prepare(
"SELECT value FROM key_value WHERE namespace = 'settings' AND key = 'perKeyProxyEnabled'"
)
.get() as { value?: string } | undefined;
if (perKeyRow?.value) {
globalPerKeyProxyEnabled = JSON.parse(perKeyRow.value) !== false;
}
} catch {
// Default to false on read error
}
const config = await getProxyConfig();
// Step 2: API key-level proxy (only if per-key proxy is enabled globally or per-connection)
if (apiKeyId) {
// Check if per-key proxy is allowed: globally OR per-connection
const perKeyEnabled = globalPerKeyProxyEnabled || connectionPerKeyProxyEnabled;
if (perKeyEnabled) {
try {
const apiKeyRow = db.prepare("SELECT proxy_id FROM api_keys WHERE id = ?").get(apiKeyId) as
| { proxy_id?: string | null }
| undefined;
if (apiKeyRow?.proxy_id) {
const proxyRow = db
.prepare(
"SELECT p.type, p.host, p.port, p.username, p.password, p.family FROM proxy_registry p WHERE p.id = ?"
)
.get(apiKeyRow.proxy_id) as
| {
type: string;
host: string;
port: number;
username: string;
password: string;
family?: string;
}
| undefined;
if (proxyRow) {
const result = {
proxy: {
type: proxyRow.type,
host: proxyRow.host,
port: proxyRow.port,
username: proxyRow.username,
password: proxyRow.password,
family: typeof proxyRow.family === "string" ? proxyRow.family : "auto",
},
level: "apiKey" as const,
levelId: apiKeyId,
source: "api_key" as const,
};
cacheProxyResolution(cacheKey, startGeneration, startRegistryGeneration, result);
return result;
}
}
} catch {
// Fall through to existing resolution
}
}
}
// Step 3: Account-level registry
const registryAccount = await resolveProxyForScopeFromRegistry("account", connectionId);
if (registryAccount?.proxy) {
cacheProxyResolution(cacheKey, startGeneration, startRegistryGeneration, registryAccount);
return registryAccount;
}
// Step 4: Legacy key-level
if (connectionId && config.keys?.[connectionId]) {
const result = {
proxy: withFamilyDefault(config.keys[connectionId]),
level: "key",
levelId: connectionId,
};
cacheProxyResolution(cacheKey, startGeneration, startRegistryGeneration, result);
return result;
}
// Step 5: Use the connection's provider for provider/combo scoped proxies.
if (connectionRecord) {
// Step 6: Provider-level registry (only if proxy_enabled)
if (connectionProvider && connectionProxyEnabled) {
const registryProvider = await resolveProxyForScopeFromRegistry(
"provider",
connectionProvider
);
if (registryProvider?.proxy) {
cacheProxyResolution(cacheKey, startGeneration, startRegistryGeneration, registryProvider);
return registryProvider;
}
}
// Step 7: Legacy combo-level (only if proxy_enabled)
if (connectionProxyEnabled && config.combos && Object.keys(config.combos).length > 0) {
const combos = db.prepare("SELECT id, data FROM combos").all();
for (const comboRow of combos) {
const comboRecord = toRecord(comboRow);
const comboId = typeof comboRecord.id === "string" ? comboRecord.id : null;
if (comboId && config.combos[comboId]) {
try {
const comboRaw = typeof comboRecord.data === "string" ? comboRecord.data : null;
if (!comboRaw) continue;
const combo = toRecord(JSON.parse(comboRaw));
const comboModels = Array.isArray(combo.models) ? combo.models : [];
const usesProvider = comboModels.some(
(entry) => getComboModelProvider(entry) === connectionProvider
);
if (usesProvider) {
const result = {
proxy: withFamilyDefault(config.combos[comboId]),
level: "combo",
levelId: comboId,
};
cacheProxyResolution(cacheKey, startGeneration, startRegistryGeneration, result);
return result;
}
} catch {
// Ignore malformed combo records during proxy resolution.
}
}
}
}
// Step 8: Legacy provider-level (only if proxy_enabled)
if (connectionProvider && connectionProxyEnabled && config.providers?.[connectionProvider]) {
const result = {
proxy: withFamilyDefault(config.providers[connectionProvider]),
level: "provider",
levelId: connectionProvider,
};
cacheProxyResolution(cacheKey, startGeneration, startRegistryGeneration, result);
return result;
}
}
// Step 9: Global registry
const registryGlobal = await resolveProxyForScopeFromRegistry("global");
if (registryGlobal?.proxy) {
cacheProxyResolution(cacheKey, startGeneration, startRegistryGeneration, registryGlobal);
return registryGlobal;
}
// Step 10: Legacy global
if (config.global) {
const result = { proxy: withFamilyDefault(config.global), level: "global", levelId: null };
cacheProxyResolution(cacheKey, startGeneration, startRegistryGeneration, result);
return result;
}
// Step 11: Auto-selection fallback (only when global proxy is enabled)
try {
const { selectWorkingProxyFallback } = await import("@omniroute/open-sse/utils/proxyFallback");
const fallback = await selectWorkingProxyFallback(connectionId);
if (fallback) {
// Auto-selected proxies are probed via a URL roundtrip that drops any
// per-registry family policy, so default the family marker to "auto"
// (no IPv6-only enforcement) when the fallback object omits it.
const normalizedFallback =
fallback.proxy && typeof fallback.proxy === "object"
? { ...fallback, proxy: withFamilyDefault(fallback.proxy as ProxyValue) }
: fallback;
cacheProxyResolution(
cacheKey,
startGeneration,
startRegistryGeneration,
normalizedFallback as ProxyResolutionResult
);
return normalizedFallback;
}
} catch (err) {
console.warn({ err, connectionId }, "Proxy fallback auto-selection failed");
}
// Step 12: Return direct
return { proxy: null, level: "direct", levelId: null };
}
export async function setProxyConfig(config: Record<string, unknown>) {
if (config.level !== undefined) {
const level = typeof config.level === "string" ? config.level : "global";
const id = typeof config.id === "string" ? config.id : null;
const proxy = (config.proxy as ProxyValue) || null;
return setProxyForLevel(level, id, proxy);
}
const db = getDbInstance();
const current = await getProxyConfig();
const insert = db.prepare(
"INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES ('proxyConfig', ?, ?)"
);
const tx = db.transaction(() => {
if (config.global !== undefined) {
current.global = toProxyValue(config.global);
insert.run("global", JSON.stringify(current.global));
}
for (const mapKey of ["providers", "combos", "keys"]) {
if (config[mapKey]) {
const merged = { ...toProxyMap(current[mapKey]), ...toProxyMap(config[mapKey]) };
for (const [k, v] of Object.entries(merged)) {
if (!v) delete merged[k];
}
current[mapKey] = merged;
insert.run(mapKey, JSON.stringify(merged));
}
}
});
tx();
backupDbFile("pre-write");
bumpProxyConfigGeneration();
return current;
}
// ──────────────── Cache Control Metrics ────────────────
// Cache metrics are now computed from usage_history table on-the-fly
// This avoids race conditions and keeps a single source of truth for token data
export async function getCacheMetrics() {
const db = getDbInstance();
try {
// Aggregate totals from usage_history
const totalsRow = db
.prepare(
`
SELECT
COUNT(*) as totalRequests,
SUM(tokens_input) as totalInputTokens,
SUM(tokens_cache_read) as totalCachedTokens,
SUM(tokens_cache_creation) as totalCacheCreationTokens
FROM usage_history
WHERE tokens_cache_read > 0 OR tokens_cache_creation > 0
`
)
.get() as
| {
totalRequests: number;
totalInputTokens: number | null;
totalCachedTokens: number | null;
totalCacheCreationTokens: number | null;
}
| undefined;
// Get all requests count (including those without cache activity)
const allRequestsRow = db
.prepare(
`
SELECT COUNT(*) as totalRequests
FROM usage_history
`
)
.get() as { totalRequests: number } | undefined;
// Aggregate by provider
const byProviderRows = db
.prepare(
`
SELECT
provider,
COUNT(*) as totalRequests,
SUM(CASE WHEN tokens_cache_read > 0 OR tokens_cache_creation > 0 THEN 1 ELSE 0 END) as cachedRequests,
SUM(CASE WHEN tokens_cache_read > 0 OR tokens_cache_creation > 0 THEN tokens_input ELSE 0 END) as inputTokens,
SUM(tokens_cache_read) as cachedTokens,
SUM(tokens_cache_creation) as cacheCreationTokens
FROM usage_history
WHERE provider IS NOT NULL
GROUP BY provider
HAVING cachedRequests > 0
`
)
.all() as Array<{
provider: string;
totalRequests: number;
cachedRequests: number;
inputTokens: number | null;
cachedTokens: number | null;
cacheCreationTokens: number | null;
}>;
// Aggregate by combo strategy (direct requests stored as 'direct')
const byStrategyRows = db
.prepare(
`
SELECT
COALESCE(combo_strategy, 'direct') as strategy,
COUNT(*) as requests,
SUM(tokens_input) as inputTokens,
SUM(tokens_cache_read) as cachedTokens,
SUM(tokens_cache_creation) as cacheCreationTokens
FROM usage_history
WHERE (tokens_cache_read > 0 OR tokens_cache_creation > 0)
GROUP BY combo_strategy
`
)
.all() as Array<{
strategy: string;
requests: number;
inputTokens: number | null;
cachedTokens: number | null;
cacheCreationTokens: number | null;
}>;
const tokensSaved = totalsRow?.totalCachedTokens || 0;
const AVG_INPUT_PRICE_PER_MILLION = 3;
const CACHE_DISCOUNT = 0.9;
const estimatedCostSaved =
Math.round((tokensSaved / 1_000_000) * AVG_INPUT_PRICE_PER_MILLION * CACHE_DISCOUNT * 100) /
100;
// Build byProvider object
const byProvider: Record<
string,
{
requests: number;
totalRequests: number;
cachedRequests: number;
inputTokens: number;
cachedTokens: number;
cacheCreationTokens: number;
}
> = {};
for (const row of byProviderRows) {
byProvider[row.provider] = {
requests: row.cachedRequests,
totalRequests: row.totalRequests,
cachedRequests: row.cachedRequests,
inputTokens: row.inputTokens || 0,
cachedTokens: row.cachedTokens || 0,
cacheCreationTokens: row.cacheCreationTokens || 0,
};
}
// Build byStrategy object
const byStrategy: Record<
string,
{
requests: number;
inputTokens: number;
cachedTokens: number;
cacheCreationTokens: number;
}
> = {};
for (const row of byStrategyRows) {
byStrategy[row.strategy] = {
requests: row.requests,
inputTokens: row.inputTokens || 0,
cachedTokens: row.cachedTokens || 0,
cacheCreationTokens: row.cacheCreationTokens || 0,
};
}
return {
totalRequests: allRequestsRow?.totalRequests || totalsRow?.totalRequests || 0,
requestsWithCacheControl: totalsRow?.totalRequests || 0,
totalInputTokens: totalsRow?.totalInputTokens || 0,
totalCachedTokens: totalsRow?.totalCachedTokens || 0,
totalCacheCreationTokens: totalsRow?.totalCacheCreationTokens || 0,
tokensSaved,
estimatedCostSaved,
byProvider,
byStrategy,
lastUpdated: new Date().toISOString(),
};
} catch (error) {
console.error("Failed to fetch cache metrics from usage_history:", error);
return {
totalRequests: 0,
requestsWithCacheControl: 0,
totalInputTokens: 0,
totalCachedTokens: 0,
totalCacheCreationTokens: 0,
tokensSaved: 0,
estimatedCostSaved: 0,
byProvider: {},
byStrategy: {},
lastUpdated: new Date().toISOString(),
};
}
}
export async function updateCacheMetrics(_metrics: Record<string, unknown>) {
// No-op: metrics are now computed from usage_history on-the-fly
// The usage_history table is the single source of truth
return getCacheMetrics();
}
export interface CacheTrendPoint {
timestamp: string;
requests: number;
cachedRequests: number;
inputTokens: number;
cachedTokens: number;
cacheCreationTokens: number;
}
export async function getCacheTrend(hours = 24): Promise<CacheTrendPoint[]> {
const db = getDbInstance();
try {
const rows = db
.prepare(
`
SELECT
strftime('%Y-%m-%dT%H:00:00Z', timestamp) as hour,
COUNT(*) as requests,
SUM(CASE WHEN tokens_cache_read > 0 OR tokens_cache_creation > 0 THEN 1 ELSE 0 END) as cachedRequests,
SUM(tokens_input) as inputTokens,
SUM(tokens_cache_read) as cachedTokens,
SUM(tokens_cache_creation) as cacheCreationTokens
FROM usage_history
WHERE timestamp >= datetime('now', ?)
GROUP BY hour
ORDER BY hour ASC
`
)
.all(`-${hours} hours`) as Array<{
hour: string;
requests: number;
cachedRequests: number;
inputTokens: number | null;
cachedTokens: number | null;
cacheCreationTokens: number | null;
}>;
return rows.map((r) => ({
timestamp: r.hour,
requests: r.requests,
cachedRequests: r.cachedRequests,
inputTokens: r.inputTokens || 0,
cachedTokens: r.cachedTokens || 0,
cacheCreationTokens: r.cacheCreationTokens || 0,
}));
} catch (error) {
console.error("Failed to fetch cache trend:", error);
return [];
}
}
export async function resetCacheMetrics() {
// No-op: cache metrics are computed from usage_history.
console.warn(
"resetCacheMetrics is deprecated - cache metrics are now computed from usage_history"
);
return getCacheMetrics();
}