Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
feat(api): add external pricing sync with LiteLLM source
Regis192c06cadf19
diff --git a/open-sse/mcp-server/__tests__/pricingSync.test.ts b/open-sse/mcp-server/__tests__/pricingSync.test.tsnew file mode 100644index 0000000000..e4696c8cd9--- /dev/null+++ b/open-sse/mcp-server/__tests__/pricingSync.test.ts@@ -0,0 +1,60 @@+import { describe, it, expect } from "vitest";+import { z } from "zod";+import { syncPricingInput, syncPricingTool, MCP_TOOLS, MCP_TOOL_MAP } from "../schemas/tools.ts";++describe("omniroute_sync_pricing MCP tool schema", () => {+ it("should be registered in MCP_TOOLS", () => {+ const tool = MCP_TOOLS.find((t) => t.name === "omniroute_sync_pricing");+ expect(tool).toBeDefined();+ expect(tool?.phase).toBe(2);+ });++ it("should be in MCP_TOOL_MAP", () => {+ expect(MCP_TOOL_MAP["omniroute_sync_pricing"]).toBeDefined();+ });++ it("should require pricing:write scope", () => {+ expect(syncPricingTool.scopes).toContain("pricing:write");+ });++ it("should have full audit level", () => {+ expect(syncPricingTool.auditLevel).toBe("full");+ });++ it("should validate empty input (all fields optional)", () => {+ const result = syncPricingInput.safeParse({});+ expect(result.success).toBe(true);+ });++ it("should validate input with sources array", () => {+ const result = syncPricingInput.safeParse({ sources: ["litellm"] });+ expect(result.success).toBe(true);+ });++ it("should validate input with dryRun", () => {+ const result = syncPricingInput.safeParse({ dryRun: true });+ expect(result.success).toBe(true);+ });++ it("should validate full input", () => {+ const result = syncPricingInput.safeParse({+ sources: ["litellm"],+ dryRun: false,+ });+ expect(result.success).toBe(true);+ });++ it("should reject invalid sources type", () => {+ const result = syncPricingInput.safeParse({ sources: "litellm" });+ expect(result.success).toBe(false);+ });++ it("should reject invalid dryRun type", () => {+ const result = syncPricingInput.safeParse({ dryRun: "yes" });+ expect(result.success).toBe(false);+ });++ it("should point to correct source endpoint", () => {+ expect(syncPricingTool.sourceEndpoints).toContain("/api/pricing/sync");+ });+});diff --git a/open-sse/mcp-server/schemas/tools.ts b/open-sse/mcp-server/schemas/tools.tsindex 38730de507..303e01ed4c 100644--- a/open-sse/mcp-server/schemas/tools.ts+++ b/open-sse/mcp-server/schemas/tools.ts@@ -723,6 +723,40 @@ export const getSessionSnapshotTool: McpToolDefinition<sourceEndpoints: ["/api/usage/analytics", "/api/telemetry/summary"],};+// --- Tool 17: omniroute_sync_pricing ---+export const syncPricingInput = z.object({+ sources: z+ .array(z.string())+ .optional()+ .describe("External pricing sources to sync from (default: ['litellm'])"),+ dryRun: z+ .boolean()+ .optional()+ .describe("If true, preview sync results without saving to database"),+});++export const syncPricingOutput = z.object({+ success: z.boolean(),+ modelCount: z.number(),+ providerCount: z.number(),+ source: z.string(),+ dryRun: z.boolean(),+ error: z.string().optional(),+});++export const syncPricingTool: McpToolDefinition<typeof syncPricingInput, typeof syncPricingOutput> =+ {+ name: "omniroute_sync_pricing",+ description:+ "Syncs pricing data from external sources (LiteLLM) into OmniRoute. Synced pricing fills gaps not covered by hardcoded defaults without overwriting user-set prices. Use dryRun=true to preview.",+ inputSchema: syncPricingInput,+ outputSchema: syncPricingOutput,+ scopes: ["pricing:write"],+ auditLevel: "full",+ phase: 2,+ sourceEndpoints: ["/api/pricing/sync"],+ };+// ============ Tool Registry ============/** All MCP tool definitions, ordered by phase then name */@@ -745,6 +779,7 @@ export const MCP_TOOLS = [bestComboForTaskTool,explainRouteTool,getSessionSnapshotTool,+ syncPricingTool,] as const;/** Essential tools only (Phase 1) */diff --git a/open-sse/mcp-server/server.ts b/open-sse/mcp-server/server.tsindex 4bfeaf0dee..33039e7046 100644--- a/open-sse/mcp-server/server.ts+++ b/open-sse/mcp-server/server.ts@@ -31,6 +31,7 @@ import {bestComboForTaskInput,explainRouteInput,getSessionSnapshotInput,+ syncPricingInput,} from "./schemas/tools.ts";import { startMcpHeartbeat } from "./runtimeHeartbeat.ts";@@ -50,6 +51,7 @@ import {handleBestComboForTask,handleExplainRoute,handleGetSessionSnapshot,+ handleSyncPricing,} from "./tools/advancedTools.ts";import { normalizeQuotaResponse } from "../../src/shared/contracts/quota.ts";@@ -664,6 +666,18 @@ export function createMcpServer(): McpServer {}));+ server.registerTool(+ "omniroute_sync_pricing",+ {+ description:+ "Syncs pricing data from external sources (LiteLLM) into OmniRoute without overwriting user-set prices",+ inputSchema: syncPricingInput,+ },+ withScopeEnforcement("omniroute_sync_pricing", (args) =>+ handleSyncPricing(syncPricingInput.parse(args))+ )+ );+return server;}diff --git a/open-sse/mcp-server/tools/advancedTools.ts b/open-sse/mcp-server/tools/advancedTools.tsindex 02e44642a8..a9b24c433f 100644--- a/open-sse/mcp-server/tools/advancedTools.ts+++ b/open-sse/mcp-server/tools/advancedTools.ts@@ -678,6 +678,28 @@ export async function handleExplainRoute(args: { requestId: string }) {}}+export async function handleSyncPricing(args: { sources?: string[]; dryRun?: boolean }) {+ const start = Date.now();+ try {+ const result = toRecord(+ await apiFetch("/api/pricing/sync", {+ method: "POST",+ body: JSON.stringify({+ sources: args.sources,+ dryRun: args.dryRun ?? false,+ }),+ })+ );++ await logToolCall("omniroute_sync_pricing", args, result, Date.now() - start, true);+ return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ await logToolCall("omniroute_sync_pricing", args, null, Date.now() - start, false, msg);+ return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };+ }+}+export async function handleGetSessionSnapshot() {const start = Date.now();try {diff --git a/src/app/api/pricing/sync/route.ts b/src/app/api/pricing/sync/route.tsnew file mode 100644index 0000000000..cdc7a16599--- /dev/null+++ b/src/app/api/pricing/sync/route.ts@@ -0,0 +1,46 @@+/**+ * API Route: /api/pricing/sync+ *+ * POST — Trigger a manual pricing sync from external sources.+ * GET — Get current sync status.+ * DELETE — Clear all synced pricing data.+ */++import { NextRequest, NextResponse } from "next/server";++export async function POST(request: NextRequest) {+ try {+ const body = await request.json().catch(() => ({}));+ const sources = Array.isArray(body.sources) ? body.sources : undefined;+ const dryRun = body.dryRun === true;++ const { syncPricingFromSources } = await import("@/lib/pricingSync");+ const result = await syncPricingFromSources({ sources, dryRun });++ return NextResponse.json(result, { status: result.success ? 200 : 502 });+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ return NextResponse.json({ error: message }, { status: 500 });+ }+}++export async function GET() {+ try {+ const { getSyncStatus } = await import("@/lib/pricingSync");+ return NextResponse.json(getSyncStatus());+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ return NextResponse.json({ error: message }, { status: 500 });+ }+}++export async function DELETE() {+ try {+ const { clearSyncedPricing } = await import("@/lib/pricingSync");+ clearSyncedPricing();+ return NextResponse.json({ success: true, message: "Synced pricing data cleared" });+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ return NextResponse.json({ error: message }, { status: 500 });+ }+}diff --git a/src/lib/db/settings.ts b/src/lib/db/settings.tsindex fca130eb13..c68de5d71d 100644--- a/src/lib/db/settings.ts+++ b/src/lib/db/settings.ts@@ -94,6 +94,25 @@ export async function isCloudEnabled() {export async function getPricing() {const db = getDbInstance();++ // Layer 1: Hardcoded defaults (lowest priority)+ const { getDefaultPricing } = await import("@/shared/constants/pricing");+ const defaultPricing = getDefaultPricing();++ // Layer 2: Synced external pricing (middle priority)+ const syncedRows = db+ .prepare("SELECT key, value FROM key_value WHERE namespace = 'pricing_synced'")+ .all();+ const syncedPricing: PricingByProvider = {};+ for (const row of syncedRows) {+ 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;+ syncedPricing[key] = toRecord(JSON.parse(rawValue)) as PricingModels;+ }++ // Layer 3: User overrides (highest priority)const rows = db.prepare("SELECT key, value FROM key_value WHERE namespace = 'pricing'").all();const userPricing: PricingByProvider = {};for (const row of rows) {@@ -104,14 +123,20 @@ export async function getPricing() {userPricing[key] = toRecord(JSON.parse(rawValue)) as PricingModels;}- const { getDefaultPricing } = await import("@/shared/constants/pricing");- const defaultPricing = getDefaultPricing();-+ // Merge: defaults → synced → user (each layer overrides the previous)const mergedPricing: PricingByProvider = {};++ // Start with defaultsfor (const [provider, models] of Object.entries(defaultPricing) as Array<[string, unknown]>) {mergedPricing[provider] = { ...(toRecord(models) as PricingModels) };- if (userPricing[provider]) {- for (const [model, pricing] of Object.entries(userPricing[provider])) {+ }++ // Layer synced on top of defaults+ for (const [provider, models] of Object.entries(syncedPricing)) {+ if (!mergedPricing[provider]) {+ mergedPricing[provider] = { ...models };+ } else {+ for (const [model, pricing] of Object.entries(models)) {mergedPricing[provider][model] = mergedPricing[provider][model]? { ...(mergedPricing[provider][model] || {}), ...toRecord(pricing) }: pricing;@@ -119,14 +144,15 @@ export async function getPricing() {}}+ // Layer user overrides on top (highest priority)for (const [provider, models] of Object.entries(userPricing)) {if (!mergedPricing[provider]) {mergedPricing[provider] = { ...models };} else {for (const [model, pricing] of Object.entries(models)) {- if (!mergedPricing[provider][model]) {- mergedPricing[provider][model] = pricing;- }+ mergedPricing[provider][model] = mergedPricing[provider][model]+ ? { ...(mergedPricing[provider][model] || {}), ...toRecord(pricing) }+ : pricing;}}}diff --git a/src/lib/localDb.ts b/src/lib/localDb.tsindex 4d096427ec..ceb9befb5a 100644--- a/src/lib/localDb.ts+++ b/src/lib/localDb.ts@@ -89,6 +89,18 @@ export {setProxyConfig,} from "./db/settings";+export {+ // Pricing Sync+ getSyncedPricing,+ saveSyncedPricing,+ clearSyncedPricing,+ syncPricingFromSources,+ getSyncStatus,+ initPricingSync,+ startPeriodicSync,+ stopPeriodicSync,+} from "./pricingSync";+export {// Backup ManagementbackupDbFile,diff --git a/src/lib/pricingSync.ts b/src/lib/pricingSync.tsnew file mode 100644index 0000000000..9362a75842--- /dev/null+++ b/src/lib/pricingSync.ts@@ -0,0 +1,347 @@+/**+ * pricingSync.ts — External pricing sync engine.+ *+ * Fetches pricing data from external sources (LiteLLM) and stores it+ * in a separate namespace (`pricing_synced`) so user overrides are+ * never touched.+ *+ * Resolution order: user overrides > synced external > hardcoded defaults+ *+ * Opt-in via PRICING_SYNC_ENABLED=true (default: false).+ */++import { getDbInstance } from "./db/core";+import { invalidateDbCache } from "./db/readCache";+import { backupDbFile } from "./db/backup";++// ─── Types ───────────────────────────────────────────────++type PricingEntry = {+ input: number;+ output: number;+ cached?: number;+ cache_creation?: number;+};++type PricingModels = Record<string, PricingEntry>;+type PricingByProvider = Record<string, PricingModels>;++interface LiteLLMModelInfo {+ input_cost_per_token?: number;+ output_cost_per_token?: number;+ cache_read_input_token_cost?: number;+ cache_creation_input_token_cost?: number;+ litellm_provider?: string;+ mode?: string;+}++interface SyncStatus {+ enabled: boolean;+ lastSync: string | null;+ lastSyncModelCount: number;+ nextSync: string | null;+ intervalMs: number;+ sources: string[];+}++interface SyncResult {+ success: boolean;+ modelCount: number;+ providerCount: number;+ source: string;+ dryRun: boolean;+ data?: PricingByProvider;+ error?: string;+}++// ─── Configuration ───────────────────────────────────────++const SYNC_INTERVAL_MS = parseInt(process.env.PRICING_SYNC_INTERVAL || "86400", 10) * 1000;+const SYNC_SOURCES = (process.env.PRICING_SYNC_SOURCES || "litellm")+ .split(",")+ .map((s) => s.trim());++const LITELLM_PRICING_URL =+ "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";++// ─── Provider mapping: LiteLLM provider → OmniRoute aliases ─────++const LITELLM_PROVIDER_MAP: Record<string, string[]> = {+ openai: ["openai", "cx"],+ anthropic: ["anthropic", "cc"],+ vertex_ai: ["gemini", "gc"],+ "vertex_ai-anthropic_models": ["anthropic"],+ google: ["gemini", "gc"],+ deepseek: ["if"],+ groq: ["groq"],+ together_ai: ["openrouter"],+ bedrock: ["kiro"],+ fireworks_ai: ["fireworks"],+ cerebras: ["cerebras"],+ nvidia_nim: ["nvidia"],+ siliconflow: ["siliconflow"],+};++// ─── Periodic sync state ─────────────────────────────────++let syncTimer: ReturnType<typeof setInterval> | null = null;+let lastSyncTime: string | null = null;+let lastSyncModelCount = 0;++// ─── Core: Fetch + Transform ─────────────────────────────++/**+ * Fetch raw pricing data from LiteLLM GitHub.+ */+export async function fetchLiteLLMPricing(): Promise<Record<string, LiteLLMModelInfo>> {+ const response = await fetch(LITELLM_PRICING_URL, {+ signal: AbortSignal.timeout(30000),+ });+ if (!response.ok) {+ throw new Error(`LiteLLM fetch failed [${response.status}]: ${response.statusText}`);+ }+ return response.json() as Promise<Record<string, LiteLLMModelInfo>>;+}++/**+ * Transform LiteLLM raw data → OmniRoute PricingByProvider format.+ *+ * Conversion: cost_per_token × 1_000_000 → $/1M tokens (OmniRoute format)+ * Filters: only chat/completion modes (skip image/audio/embedding)+ */+export function transformToOmniRoute(raw: Record<string, LiteLLMModelInfo>): PricingByProvider {+ const result: PricingByProvider = {};++ for (const [modelKey, info] of Object.entries(raw)) {+ // Skip non-chat models+ if (info.mode && !["chat", "completion"].includes(info.mode)) continue;++ // Must have at least input pricing+ if (!info.input_cost_per_token && info.input_cost_per_token !== 0) continue;++ const inputCost = (info.input_cost_per_token || 0) * 1_000_000;+ const outputCost = (info.output_cost_per_token || 0) * 1_000_000;++ const entry: PricingEntry = {+ input: Math.round(inputCost * 1000) / 1000,+ output: Math.round(outputCost * 1000) / 1000,+ };++ if (info.cache_read_input_token_cost != null) {+ entry.cached = Math.round(info.cache_read_input_token_cost * 1_000_000 * 1000) / 1000;+ }+ if (info.cache_creation_input_token_cost != null) {+ entry.cache_creation =+ Math.round(info.cache_creation_input_token_cost * 1_000_000 * 1000) / 1000;+ }++ // Extract model name (strip provider prefix from key)+ // LiteLLM keys look like: "openai/gpt-4o", "anthropic/claude-3-opus"+ const slashIdx = modelKey.indexOf("/");+ const modelName = slashIdx >= 0 ? modelKey.slice(slashIdx + 1) : modelKey;++ // Map to OmniRoute providers+ const litellmProvider = info.litellm_provider || "";+ const omniRouteProviders = LITELLM_PROVIDER_MAP[litellmProvider];++ if (omniRouteProviders) {+ for (const provider of omniRouteProviders) {+ if (!result[provider]) result[provider] = {};+ result[provider][modelName] = entry;+ }+ } else if (litellmProvider) {+ // Use litellm_provider as-is for unknown providers+ if (!result[litellmProvider]) result[litellmProvider] = {};+ result[litellmProvider][modelName] = entry;+ }+ }++ return result;+}++// ─── DB: Synced pricing namespace ────────────────────────++function toRecord(value: unknown): Record<string, unknown> {+ return value && typeof value === "object" ? (value as Record<string, unknown>) : {};+}++/**+ * Read synced pricing from `pricing_synced` namespace.+ */+export function getSyncedPricing(): PricingByProvider {+ const db = getDbInstance();+ const rows = db+ .prepare("SELECT key, value FROM key_value WHERE namespace = 'pricing_synced'")+ .all();+ const synced: 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;+ synced[key] = JSON.parse(rawValue) as PricingModels;+ }+ return synced;+}++/**+ * Save synced pricing to `pricing_synced` namespace (full replace).+ */+export function saveSyncedPricing(data: PricingByProvider): void {+ const db = getDbInstance();+ const del = db.prepare("DELETE FROM key_value WHERE namespace = 'pricing_synced'");+ const insert = db.prepare(+ "INSERT INTO key_value (namespace, key, value) VALUES ('pricing_synced', ?, ?)"+ );+ const tx = db.transaction(() => {+ del.run();+ for (const [provider, models] of Object.entries(data)) {+ insert.run(provider, JSON.stringify(models));+ }+ });+ tx();+ backupDbFile("pre-write");+ invalidateDbCache("pricing");+}++/**+ * Clear all synced pricing data.+ */+export function clearSyncedPricing(): void {+ const db = getDbInstance();+ db.prepare("DELETE FROM key_value WHERE namespace = 'pricing_synced'").run();+ backupDbFile("pre-write");+ invalidateDbCache("pricing");+}++// ─── Main sync function ─────────────────────────────────++/**+ * Fetch, transform, and save pricing from external sources.+ */+export async function syncPricingFromSources(opts?: {+ sources?: string[];+ dryRun?: boolean;+}): Promise<SyncResult> {+ const sources = opts?.sources || SYNC_SOURCES;+ const dryRun = opts?.dryRun ?? false;++ try {+ let aggregated: PricingByProvider = {};++ for (const source of sources) {+ if (source === "litellm") {+ const raw = await fetchLiteLLMPricing();+ const transformed = transformToOmniRoute(raw);+ // Merge into aggregated+ for (const [provider, models] of Object.entries(transformed)) {+ if (!aggregated[provider]) aggregated[provider] = {};+ Object.assign(aggregated[provider], models);+ }+ }+ }++ const modelCount = Object.values(aggregated).reduce(+ (sum, models) => sum + Object.keys(models).length,+ 0+ );+ const providerCount = Object.keys(aggregated).length;++ if (!dryRun) {+ saveSyncedPricing(aggregated);+ lastSyncTime = new Date().toISOString();+ lastSyncModelCount = modelCount;+ }++ return {+ success: true,+ modelCount,+ providerCount,+ source: sources.join(","),+ dryRun,+ ...(dryRun ? { data: aggregated } : {}),+ };+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ console.warn("[PRICING_SYNC] Sync failed:", message);+ return {+ success: false,+ modelCount: 0,+ providerCount: 0,+ source: sources.join(","),+ dryRun,+ error: message,+ };+ }+}++// ─── Periodic sync ───────────────────────────────────────++/**+ * Start periodic pricing sync (non-blocking).+ */+export function startPeriodicSync(intervalMs?: number): void {+ if (syncTimer) return; // Already running++ const interval = intervalMs ?? SYNC_INTERVAL_MS;+ console.log(`[PRICING_SYNC] Starting periodic sync every ${interval / 1000}s`);++ // Initial sync (non-blocking)+ syncPricingFromSources().then((result) => {+ if (result.success) {+ console.log(+ `[PRICING_SYNC] Initial sync complete: ${result.modelCount} models from ${result.providerCount} providers`+ );+ }+ });++ syncTimer = setInterval(() => {+ syncPricingFromSources().then((result) => {+ if (result.success) {+ console.log(`[PRICING_SYNC] Periodic sync complete: ${result.modelCount} models`);+ }+ });+ }, interval);+}++/**+ * Stop periodic sync and cleanup timer.+ */+export function stopPeriodicSync(): void {+ if (syncTimer) {+ clearInterval(syncTimer);+ syncTimer = null;+ console.log("[PRICING_SYNC] Periodic sync stopped");+ }+}++/**+ * Get current sync status.+ */+export function getSyncStatus(): SyncStatus {+ const enabled = process.env.PRICING_SYNC_ENABLED === "true";+ return {+ enabled,+ lastSync: lastSyncTime,+ lastSyncModelCount,+ nextSync:+ syncTimer && lastSyncTime+ ? new Date(new Date(lastSyncTime).getTime() + SYNC_INTERVAL_MS).toISOString()+ : null,+ intervalMs: SYNC_INTERVAL_MS,+ sources: SYNC_SOURCES,+ };+}++// ─── Init (called from server-init.ts) ───────────────────++/**+ * Initialize pricing sync if enabled.+ */+export async function initPricingSync(): Promise<void> {+ if (process.env.PRICING_SYNC_ENABLED !== "true") {+ console.log("[PRICING_SYNC] Disabled (set PRICING_SYNC_ENABLED=true to enable)");+ return;+ }+ startPeriodicSync();+}diff --git a/src/server-init.ts b/src/server-init.tsindex 10a443cfcf..f254547c98 100644--- a/src/server-init.ts+++ b/src/server-init.ts@@ -42,6 +42,19 @@ async function startServer() {console.error("[FATAL] Error initializing cloud sync:", error);process.exit(1);}++ // Pricing sync: opt-in external pricing data (non-blocking, never fatal)+ if (process.env.PRICING_SYNC_ENABLED === "true") {+ try {+ const { initPricingSync } = await import("./lib/pricingSync");+ await initPricingSync();+ } catch (err) {+ console.warn(+ "[PRICING_SYNC] Could not initialize:",+ err instanceof Error ? err.message : err+ );+ }+ }}// Start the server initializationdiff --git a/tests/unit/pricing-sync.test.mjs b/tests/unit/pricing-sync.test.mjsnew file mode 100644index 0000000000..0169f3fd42--- /dev/null+++ b/tests/unit/pricing-sync.test.mjs@@ -0,0 +1,226 @@+import { test, describe } from "node:test";+import assert from "node:assert/strict";+import { transformToOmniRoute } from "../../src/lib/pricingSync.ts";++// ─── transformToOmniRoute ────────────────────────────────++describe("transformToOmniRoute", () => {+ test("converts LiteLLM per-token pricing to OmniRoute per-million format", () => {+ const raw = {+ "openai/gpt-4o": {+ input_cost_per_token: 0.0000025,+ output_cost_per_token: 0.00001,+ litellm_provider: "openai",+ mode: "chat",+ },+ };++ const result = transformToOmniRoute(raw);++ assert.ok(result.openai, "Should have openai provider");+ assert.ok(result.openai["gpt-4o"], "Should have gpt-4o model");+ assert.strictEqual(result.openai["gpt-4o"].input, 2.5);+ assert.strictEqual(result.openai["gpt-4o"].output, 10);+ });++ test("maps anthropic provider to cc alias", () => {+ const raw = {+ "anthropic/claude-sonnet-4-20250514": {+ input_cost_per_token: 0.000003,+ output_cost_per_token: 0.000015,+ litellm_provider: "anthropic",+ mode: "chat",+ },+ };++ const result = transformToOmniRoute(raw);++ assert.ok(result.cc, "Should map to cc alias");+ assert.ok(result.cc["claude-sonnet-4-20250514"]);+ assert.strictEqual(result.cc["claude-sonnet-4-20250514"].input, 3);+ assert.strictEqual(result.cc["claude-sonnet-4-20250514"].output, 15);+ });++ test("maps vertex_ai provider to gemini and gc aliases", () => {+ const raw = {+ "vertex_ai/gemini-2.5-flash": {+ input_cost_per_token: 0.0000003,+ output_cost_per_token: 0.0000025,+ litellm_provider: "vertex_ai",+ mode: "chat",+ },+ };++ const result = transformToOmniRoute(raw);++ assert.ok(result.gemini, "Should map to gemini alias");+ assert.ok(result.gc, "Should map to gc alias");+ assert.strictEqual(result.gemini["gemini-2.5-flash"].input, 0.3);+ assert.strictEqual(result.gc["gemini-2.5-flash"].input, 0.3);+ });++ test("skips non-chat models (embedding, image, audio)", () => {+ const raw = {+ "openai/text-embedding-3-small": {+ input_cost_per_token: 0.00000002,+ output_cost_per_token: 0,+ litellm_provider: "openai",+ mode: "embedding",+ },+ "openai/dall-e-3": {+ input_cost_per_token: 0,+ output_cost_per_token: 0,+ litellm_provider: "openai",+ mode: "image_generation",+ },+ };++ const result = transformToOmniRoute(raw);++ // openai key should not exist since all models were filtered+ const openaiModels = result.openai || {};+ assert.strictEqual(Object.keys(openaiModels).length, 0, "Should skip non-chat models");+ });++ test("includes cache pricing when available", () => {+ const raw = {+ "anthropic/claude-sonnet-4-20250514": {+ input_cost_per_token: 0.000003,+ output_cost_per_token: 0.000015,+ cache_read_input_token_cost: 0.0000003,+ cache_creation_input_token_cost: 0.00000375,+ litellm_provider: "anthropic",+ mode: "chat",+ },+ };++ const result = transformToOmniRoute(raw);++ const model = result.anthropic["claude-sonnet-4-20250514"];+ assert.ok(model, "Should have model");+ assert.strictEqual(model.cached, 0.3);+ assert.strictEqual(model.cache_creation, 3.75);+ });++ test("handles models without explicit mode (treated as chat)", () => {+ const raw = {+ "deepseek/deepseek-chat": {+ input_cost_per_token: 0.00000014,+ output_cost_per_token: 0.00000028,+ litellm_provider: "deepseek",+ },+ };++ const result = transformToOmniRoute(raw);++ // deepseek maps to "if" alias+ assert.ok(result.if, "Should map deepseek to if alias");+ assert.ok(result.if["deepseek-chat"]);+ });++ test("skips entries without input cost", () => {+ const raw = {+ "unknown/model": {+ litellm_provider: "unknown",+ mode: "chat",+ },+ };++ const result = transformToOmniRoute(raw);+ const unknownModels = result.unknown || {};+ assert.strictEqual(Object.keys(unknownModels).length, 0);+ });++ test("handles zero-cost (free) models", () => {+ const raw = {+ "groq/llama-3.3-70b-versatile": {+ input_cost_per_token: 0,+ output_cost_per_token: 0,+ litellm_provider: "groq",+ mode: "chat",+ },+ };++ const result = transformToOmniRoute(raw);++ assert.ok(result.groq, "Should have groq provider");+ assert.strictEqual(result.groq["llama-3.3-70b-versatile"].input, 0);+ assert.strictEqual(result.groq["llama-3.3-70b-versatile"].output, 0);+ });++ test("uses litellm_provider as-is for unmapped providers", () => {+ const raw = {+ "newprovider/some-model": {+ input_cost_per_token: 0.000001,+ output_cost_per_token: 0.000002,+ litellm_provider: "newprovider",+ mode: "chat",+ },+ };++ const result = transformToOmniRoute(raw);++ assert.ok(result.newprovider, "Should use litellm_provider as-is");+ assert.ok(result.newprovider["some-model"]);+ });++ test("strips provider prefix from model key", () => {+ const raw = {+ "openai/gpt-4o-mini": {+ input_cost_per_token: 0.00000015,+ output_cost_per_token: 0.0000006,+ litellm_provider: "openai",+ mode: "chat",+ },+ };++ const result = transformToOmniRoute(raw);++ assert.ok(result.openai["gpt-4o-mini"], "Should strip openai/ prefix");+ assert.strictEqual(result.openai["gpt-4o-mini"].input, 0.15);+ });++ test("rounds pricing to 3 decimal places", () => {+ const raw = {+ "test/model": {+ input_cost_per_token: 0.00000033333,+ output_cost_per_token: 0.00000066666,+ litellm_provider: "openai",+ mode: "chat",+ },+ };++ const result = transformToOmniRoute(raw);++ // 0.00000033333 * 1e6 = 0.33333 → rounded to 0.333+ assert.strictEqual(result.openai.model.input, 0.333);+ assert.strictEqual(result.openai.model.output, 0.667);+ });+});++// ─── Merge precedence ────────────────────────────────────++describe("pricing merge precedence", () => {+ test("user overrides > synced > defaults conceptual order", () => {+ // This test validates the conceptual model.+ // The actual merge is tested via integration with settings.ts.+ // Here we verify transform doesn't lose data needed for merge.+ const raw = {+ "openai/gpt-4o": {+ input_cost_per_token: 0.0000025,+ output_cost_per_token: 0.00001,+ litellm_provider: "openai",+ mode: "chat",+ },+ };++ const synced = transformToOmniRoute(raw);+ const userOverride = { openai: { "gpt-4o": { input: 999 } } };++ // Simulate merge: synced then user+ const merged = { ...synced.openai["gpt-4o"], ...userOverride.openai["gpt-4o"] };++ assert.strictEqual(merged.input, 999, "User override should win");+ assert.strictEqual(merged.output, 10, "Non-overridden fields from synced should remain");+ });+});