mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-04 06:12:10 +03:00
* chore(release): open v3.8.37 development cycle * chore(ci): harden release flow — ratchet decoupling, fast-path drift gates, build-scope guard, heap default (#5054) Implements improvements 1-4 from the v3.8.36 release benchmark (_tasks/release-bench/v3.8.36/PLANO-MELHORIA.md): 1. Quality Ratchet decoupled from flaky coverage (ci.yml): the shard→coverage→ratchet chain meant a single flaky Coverage Shard SKIPPED the whole Quality Ratchet on the release PR (v3.8.36 #4854), so cycle drift only surfaced post-merge in #5029. The job now runs on !cancelled(); coverage download is continue-on-error and the ratchet runs --allow-missing, so the DETERMINISTIC gates (eslint/complexity/cognitive/duplication/ codeql) stay blocking even when coverage is unavailable. 2. Fast-path drift gates (quality.yml PR→release): added check:complexity, check:cognitive-complexity, and a new lightweight check:pack-policy (pack-artifact unexpected-files check WITHOUT a build, via --policy-only) so drift + stray-tarball-file regressions are caught/rebaselined PER-PR instead of cascading onto the release PR. 3. Build heap default 4096→8192 MB (build-next-isolated.mjs): the clean graph peaks ~3.9 GB and brushed the old 4 GB ceiling; 8 GB gives headroom. Comment notes heap is NOT the fix for a poisoned scope (run check:build-scope instead). 4. check:build-scope gate (new): fails if .ts/.tsx/.js/.jsx files in the tsconfig scope exceed a threshold — catches worktrees/cruft leaking into the build scope (the v3.8.36 OOM root cause: 355,215 vs 4,547 files) BEFORE it detonates next build. Wired into the fast-path. * fix(auth): only trust forwarding headers from loopback TCP peers (#4689) Integrated into release/v3.8.37 — loopback-gated forwarding headers (IP spoofing fix). Cherry-picked onto current release tip; ipUtils.test.ts 9/9 green. * fix(codex): treat OAuth 401 as unrecoverable refresh failure (#4686) Integrated into release/v3.8.37 — codex OAuth 401 treated as unrecoverable refresh. Cherry-picked onto release tip; token-refresh-service.test.ts 38/38 green. * fix(translator): preserve reasoning_effort for non-Copilot Responses clients (#4688) Integrated into release/v3.8.37 — preserve reasoning_effort for non-Copilot Responses clients. Cherry-picked onto release tip; tests 47/47 green. * fix(translator): coerce tool descriptions to strings in OpenAI normalization (#4675) Integrated into release/v3.8.37 — coerce tool descriptions to strings in OpenAI normalization. Cherry-picked onto release tip; tests 3/3 green. * feat(sse): x-omniroute-strip-reasoning header to drop reasoning_content (#4678) Integrated into release/v3.8.37 — x-omniroute-strip-reasoning header. Cherry-picked onto release tip (resolved chatCore.ts/headers.ts adjacency conflict, kept resolveCompressionHeader + isStripReasoningRequested); tests 8/8 green. * fix(combo): flatten Anthropic tool messages + tool history to prevent upstream 503 (#4648) Integrated into release/v3.8.37 — flattenToolHistory helper (combo anti-503). Cherry-picked onto release tip; tests 9/9 green. * feat(headroom): proxy lifecycle management + dashboard UI (Docker sidecar supported) (#4649) Integrated into release/v3.8.37 — headroom proxy lifecycle (status/start/stop, local-only + spawn-capable per Rules #15/#17). Cherry-picked onto release tip; lifecycle 7/7 + route-guard 43/43 + check:cycles green. * feat(cli): multi-model support for Factory Droid CLI (#4682) Integrated into release/v3.8.37 — Factory Droid multi-model support. Cherry-picked onto release tip (kept readJsoncConfig + droidCustomModels imports); droid-custom-models 11/11 green. * fix(providers): require Default Model in compatible-provider API-key setup (#4641) Integrated into release/v3.8.37 — require Default Model in compatible-provider API-key setup. Cherry-picked fix + test-move onto release tip (kept release providerSpecificData + QuotaScrapingFields; fixed moved-test import path; baseline rebaseline unneeded, 865<866); UI test 2/2 green. * fix(dashboard): stop double-masking already-masked API key in list (E2E 3/9 regression) (#4671) Integrated into release/v3.8.37 — render server-masked key verbatim (drop redundant maskKey call). Note: release's maskKey already guards '****' (since v3.8.34), so this is a safe simplification; added a contract test pinning the **** passthrough invariant (2/2 green, would fail against the pre-guard maskKey = the historical double-mask bug). * chore(quality): rebaseline file-size for rc17 PR batch drift Own growth from the merged rc17 PRs (#4678/#4686/#4688) at existing chokepoints — cohesive, not extractable: - open-sse/handlers/responseSanitizer.ts 1103->1122 (SanitizeOpenAIResponseOptions + stripReasoning, #4678) - open-sse/services/tokenRefresh.ts 2070->2090 (codex 401 unrecoverable-refresh guard, #4686) - tests/unit/token-refresh-service.test.ts 1322->1353 (401 regression case, #4686) - tests/unit/translator-openai-responses-req.test.ts 1047->1050 (reasoning_effort assertion, #4688) * docs(env): document HEADROOM_URL in .env.example + ENVIRONMENT.md The headroom proxy lifecycle (#4649) reads HEADROOM_URL (src/lib/headroom/detect.ts, default http://localhost:8787) but it was missing from the env contract, tripping check:env-doc-sync. Adds the var to both .env.example (commented, has a default) and the Proxy Health table in ENVIRONMENT.md. * fix(sse): stream writer mock abort() returns a Promise (#4788) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(cli): fall back to default data dir when DATA_DIR is not writable (#4767) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(oauth): verify Cursor installation on Linux before auto-import (#4770) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(sse): track Ollama streaming usage from raw NDJSON chunks (#4754) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(sse): strip enumDescriptions from antigravity tool schema (#4740) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(sse): include low-level cause details in formatProviderError (#4741) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(translator): strip x-anthropic-billing-header in claude-to-openai (#4728) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(sse): gate Kiro image attachments behind a Claude-capability check (#4763) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(sse): read Antigravity usage from the response.usageMetadata envelope (#4785) Integrated into release/v3.8.37 — Antigravity response.usageMetadata envelope. Cherry-picked onto release tip (resolved test-tail adjacency with #4754 Ollama block); usage-extractor 23/23 green. * fix(api): fall back to existing access token for any OAuth provider on refresh failure (#4786) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(cli): verify launchd registration + skip self-SIGTERM in macOS autostart (#4765) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(executors): anthropic-compatible-* gateways get Bearer alongside x-api-key (#4729) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(sse): json_schema fallback for OpenAI-compatible providers (#4766) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(sse): use workos auth token shape for cline (#4787) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * feat(sse): parse Gemini CLI 429 retryDelay from structured RetryInfo (#4738) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(sse): finalize tool_calls finish_reason on early stream end in OpenAI Responses translator (#4764) Integrated into release/v3.8.37 — computeFinishReason finalizes tool_calls on early stream end (Responses translator). Cherry-picked onto release tip; responses-translation-fixes 29/29 green. * test(sse): golden-lock provider.ts translate-path across all providers (#4734) Integrated into release/v3.8.37 — golden-lock for provider.ts translate-path. Cherry-picked onto release tip; snapshot regenerated against the current provider set (UPDATE_GOLDEN=1, 167 entries); golden test 3/3 deterministic. * chore(quality): rebaseline file-size for rc17 leva2 PR batch drift Own growth from the merged leva2 PRs (cohesive, not extractable): - src/lib/usage/providerLimits.ts 950->955 (#4786) - open-sse/executors/default.ts NEW frozen @828 (#4729 + #4766 + #4787 header branches) - open-sse/translator/request/openai-to-kiro.ts 807->814 (#4763) - open-sse/translator/response/openai-responses.ts 923->937 (#4764) - tests/unit/executor-default-base.test.ts 1339->1440 (#4766) - tests/unit/translator-openai-to-kiro.test.ts 918->980 (#4763) * fix(dashboard): align Engine Combos editor engines with API schema (#4955) (#5062) The named-combos pipeline dropdown offered four engines (headroom, session-dedup, ccr, llmlingua) that stackedPipelineStepSchema rejects, so selecting one made PUT /api/context/combos/[id] return HTTP 400 while saveCombo swallowed the non-OK response (if (!res.ok) return). Editing the default 'Standard Savings' combo and changing an engine reproduced the 400. - Add canonical STACKED_PIPELINE_ENGINE_INTENSITIES next to the schema as the single source of truth; the client dropdown imports it so it can never drift from the discriminated union the API validates against. - Surface save errors and empty-name/empty-pipeline validation in the editor instead of failing silently. - Add a parity unit test asserting the UI engine map equals the schema union and that every (engine, intensity) the UI emits is accepted. * fix(sse): filter nameless hosted tools when converting Responses API to Chat format (#4789) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(dashboard): keep desktop sidebar visible via explicit CSS class (#4812) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): strip enumDescriptions from Antigravity tool schemas (#4813) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(dashboard): resolve passthrough model aliases by providerId in ModelSelectModal (#4815) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(oauth): allow per-connection refresh lead-time override via providerSpecificData.refreshLeadMs (#4818) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): strip X-Stainless-* headers and normalize SDK User-Agent for OpenAI-compatible endpoints (#4820) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): strip Gemini built-in tools when functionDeclarations present in Antigravity envelope (#4821) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(api): surface a Docker-localhost hint on provider-node validation connection errors (#4822) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): resolve bare model names to connection defaultModel before upstream calls (#4825) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(build): trace-include sql.js sql-wasm.wasm in standalone bundle (#4839) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): strip Composer <|final|> sentinel markers leaking after Composer reasoning (#4842) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(config): sync full SiliconFlow model list into registry (#4844) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): close reasoning before message content in Responses stream (#4848) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): reject unsupported Kiro [1m] context suffix (#4816) Integrated into release/v3.8.37 — cherry-picked onto release tip; test-tail conflict with #4763 resolved (kept both image + [1m] test blocks); CHANGELOG re-merged; 29/29 green. * fix(db): validate HuggingFace tokens via whoami-v2 auth probe (#4819) Integrated into release/v3.8.37 — defining commit re-homed onto the god-file-split validation module (validateHuggingFaceProvider in validation/openaiFormat.ts + map wiring); 115/115 green. * fix(sse): make anthropic-version default-guard case-insensitive (#4823) Integrated into release/v3.8.37 — conflict with #4729 Bearer-fallback resolved (kept both Bearer fallback + case-insensitive anthropic-version guard); 48/48 green. * fix(sse): sanitize Kiro tool schemas to avoid 400 "Improperly formed request" (#4847) Integrated into release/v3.8.37 — conflict in kiro-to-openai.ts resolved (kept release fallbackToolCallId + adopted #1375 toolNameMap remap); 7/7 green. * feat(sse): add GPT-4 to the GitHub Copilot provider (#4798) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * feat(sse): add GPT-4o mini to GitHub Copilot provider (#4797) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * feat(api): add MiniMax-M3 pricing row (#4814) Integrated into release/v3.8.37 — pricing row re-homed onto god-file-split pricing/regional.ts (pricing.ts is now a barrel); 4/4 green. * fix(cli): save runtime deps with --save-exact so a sibling install can't prune them (#4841) Integrated into release/v3.8.37 — trayRuntime conflict resolved (kept release SYSTRAY_SPEC + added --save-exact); 2/2 green. * fix(sse): preserve required fields in antigravity tool schemas (#4843) Integrated into release/v3.8.37 — conflict resolved (kept #4740/#4813 enumDescriptions strip + typed normalizeSchemaTypes, added required-preservation helpers; test-tail merged keeping both enumDescriptions + required tests); 7/7 green. * chore(quality): rebaseline file-size for rc17b leva3 PR batch drift * fix(sse): strip reasoning blobs from agentic context to prevent O(n^2) token growth (#4849) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): unwrap Qoder HTTP 200 SSE error envelope so fallback can trigger (#4850) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): strip temperature for Claude models with extended thinking (#4853) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): emit valid concatenable kiro tool_calls.arguments deltas (#4855) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * feat(sse): add toggleable tool-source diagnostics (#4856) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): redact api key from the AUTH debug log in the chat handler (#4858) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): forward AI SDK image parts in Responses translator (#4859) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): resolve custom combos by id and case-insensitive name (#4446) (#4869) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): exclude WS bridge controller-closed error from provider breaker (#4602) (#4870) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * feat(providers): add xAI Grok inbound translators and thinking patcher (#4910) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * feat(embeddings): add dimensions override field to embedding combos (#4913) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * feat(oauth): Codex bulk-import endpoint — POST /api/oauth/codex/import (#4914) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(antigravity): retry transient upstream failures (#4941) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): surface malformed HTTP-200 upstream responses (#4942) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): normalize Codex custom tools (apply_patch) to { input: string } schema (#4862) Integrated into release/v3.8.37 — conflict in request/openai-responses.ts resolved (kept #4789 nameless-tool skip + added #1007 custom-tool {input:string} normalization); 48/48 green incl. #4789/#4859 regression. * fix(sse): dense, deterministic output ordering in Responses API response.completed (#4906) Integrated into release/v3.8.37 — manual integration with #4862 in response/openai-responses.ts (custom-tool funcItem + dense recordCompletedItem). Fixed a latent #4848 interaction: the close-reasoning-before-message guard force-closed <think>-tag reasoning prematurely, which dense output (#4906) then snapshotted as a partial buffer ("plan" vs "planning") — scoped the guard to native reasoning_content (!inThinking) in BOTH transformer + translator paths. Full Responses suite 203/203 green incl. #4848/#4862 regression. * feat(sse): auto-promote successful combo model to position #1 (#4852) Integrated into release/v3.8.37 — dropped the stale file-size-baseline.json hunk (re-derived against the rc17b rebaseline); code+test applied clean; 13/13 green. * feat(providers): add Pioneer AI (Fastino Labs) provider (#4909) Integrated into release/v3.8.37 — providers.ts apikey block re-homed onto god-file-split src/shared/constants/providers/apikey/frontier-labs.ts (inline APIKEY_PROVIDERS no longer exists); registry/pioneer + providers/index.ts applied clean; 6/6 green. * add DGrid AI gateway provider (#4931) Integrated into release/v3.8.37 — rebased the contributor's commit onto the release tip; providers.ts god-file-split conflict resolved by relocating the dgrid APIKEY_PROVIDERS entry into apikey/gateways.ts; CHANGELOG added. 7/7 green. Thanks @dgridOP! * chore(quality): rebaseline file-size for rc17b leva4 PR batch drift * docs(routing): sync combo strategy docs for Fusion (17 strategies) (#5067) Fusion (16th strategy, panel fan-out + judge synthesis) and headroom shipped but the strategy-count docs were stale (14/15) and omitted both. Update every combo-strategy reference to the canonical 17, add fusion + headroom to all strategy tables, and add a dedicated Fusion section to AUTO-COMBO.md documenting judgeModel / fusionTuning config + an example. - CLAUDE.md, README.md, FEATURES.md, RESILIENCE_GUIDE.md, ARCHITECTURE.md, OPEN_SSE_ARCHITECTURE.md, OMNIROUTE_VS_ALTERNATIVES.md, docs/README.md, request-pipeline.mmd: 14/15 -> 17, list fusion + headroom - docs/routing/AUTO-COMBO.md: strategy table + new Fusion strategy section - docs/openapi.yaml: add reset-window, headroom, fusion to the strategy enum * fix(oauth): classify /api/oauth/cursor/auto-import as local-only (route-guard) (#5070) The Cursor auto-import route runs execFile("which", ["cursor"]) to verify a local Cursor install before importing credentials — a child-process spawn. The check:route-guard-membership gate (Hard Rules #15/#17) flagged it as an unclassified spawn-capable route: reachable past the loopback gate, an RCE-via-tunnel surface (a leaked JWT over a tunnel could trigger the spawn). Classify the specific path in LOCAL_ONLY_API_PREFIXES so loopback enforcement runs unconditionally before any auth check. Scoped to the exact path — the rest of /api/oauth/ (browser redirect/callback flows) stays remote-reachable. TDD: added a failing-then-passing assertion in route-guard-local-prefix.test.ts (classification + an over-broadening guard proving sibling OAuth paths stay remote). check:route-guard-membership now reports 0 new gaps. * chore(release): v3.8.37 — 2026-06-26 --------- Co-authored-by: dgridOP <dgrid_op@outlook.com>
1155 lines
38 KiB
TypeScript
1155 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",
|
|
comboAutoPromoteEnabled: false,
|
|
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,
|
|
// Opt-in diagnostic: when true, the chat handler emits a `log.debug("TOOLS", …)`
|
|
// line per request summarizing tool count + MCP/hosted/client source breakdown.
|
|
logToolSources: false,
|
|
// 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,
|
|
customSystemPromptEnabled: false,
|
|
customSystemPrompt: "",
|
|
};
|
|
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();
|
|
}
|