Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(chat): sync the models' prices daily from OpenRouter's catalog (#1771)

Cihand33fb0f283a1
diff --git a/server/.env.example b/server/.env.example
index 65f71df99..abd75b6bb 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -83,6 +83,9 @@ COMPETITOR_SUGGESTION_MODEL=google/gemini-3-flash-preview
# comma-separated); empty = every organization.
# CHAT_AGENTIC=
# CHAT_AGENTIC_ORGS=
+# With Chat on, the models' prices are synced daily from OpenRouter's public
+# catalog (no key needed). Cron expression, UTC; unset = 05:17 every day.
+# MODEL_PRICES_SCHEDULE=17 5 * * *
# Content Editor Quality (Drive quality spec): which phase is live on the
# server, 0 (unset) for none, as the web's NEXT_PUBLIC_CONTENT_QUALITY_PHASE.
# 2 tells the Content Agent the brand's site type (CE-056), and turns on the
diff --git a/server/src/lib/chat-flag.js b/server/src/lib/chat-flag.js
index 6a1cd5c7a..325859802 100644
--- a/server/src/lib/chat-flag.js
+++ b/server/src/lib/chat-flag.js
@@ -13,12 +13,20 @@
* @returns {boolean}
*/
export function chatAgenticEnabled(organizationId) {
- if (process.env.CHAT_AGENTIC !== 'true') return false;
+ if (!chatAgenticDeployed()) return false;
const orgs = chatAgenticOrgs();
if (orgs.length === 0) return true;
return !!organizationId && orgs.includes(String(organizationId).trim().toLowerCase());
}
+/**
+ * Whether this deployment runs the new Chat at all, whichever workspaces it
+ * is on for: what the server's own Chat jobs (the model price sync) start on.
+ */
+export function chatAgenticDeployed() {
+ return process.env.CHAT_AGENTIC === 'true';
+}
+
/** CHAT_AGENTIC_ORGS as a list: trimmed, lower-cased, blanks dropped. */
function chatAgenticOrgs() {
return (process.env.CHAT_AGENTIC_ORGS ?? '')
diff --git a/server/src/lib/chat-flag.test.js b/server/src/lib/chat-flag.test.js
index 094145228..b8e0fcd76 100644
--- a/server/src/lib/chat-flag.test.js
+++ b/server/src/lib/chat-flag.test.js
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { chatAgenticEnabled } from './chat-flag.js';
+import { chatAgenticDeployed, chatAgenticEnabled } from './chat-flag.js';
/** The new Chat's switch: CHAT_AGENTIC, narrowed by CHAT_AGENTIC_ORGS. */
@@ -61,3 +61,18 @@ describe('chatAgenticEnabled', () => {
expect(chatAgenticEnabled(ORG_A)).toBe(true);
});
});
+
+describe('chatAgenticDeployed', () => {
+ it('is on with CHAT_AGENTIC=true whatever CHAT_AGENTIC_ORGS lists, for server-wide jobs', () => {
+ vi.stubEnv('CHAT_AGENTIC', 'true');
+ vi.stubEnv('CHAT_AGENTIC_ORGS', ORG_A);
+ expect(chatAgenticDeployed()).toBe(true);
+ });
+
+ it('is off for anything but "true"', () => {
+ for (const value of [undefined, '', 'false', 'TRUE']) {
+ vi.stubEnv('CHAT_AGENTIC', value);
+ expect(chatAgenticDeployed()).toBe(false);
+ }
+ });
+});
diff --git a/server/src/lib/improve-cost.js b/server/src/lib/improve-cost.js
index 8da720f36..bf7cfa40e 100644
--- a/server/src/lib/improve-cost.js
+++ b/server/src/lib/improve-cost.js
@@ -3,12 +3,17 @@
* quota can be a dollar budget — a share of what the customer pays — and stay
* there whichever model IMPROVE_SUGGESTION_MODEL points at.
*
- * List prices in USD per million tokens. Update this table when a provider
- * changes its prices or a new model is configured; a model missing here is
- * charged at FALLBACK_PRICE, deliberately expensive, so an unknown model can
- * only use the budget up faster, never overspend it.
+ * List prices in USD per million tokens. While CHAT_AGENTIC is on, the
+ * prices synced daily from OpenRouter's catalog come first (model-prices.js,
+ * CHAT-16 §A), at the price in effect; this table prices a model the sync
+ * doesn't have, or every model with the flag off. Update it when a provider
+ * changes its prices or a new model is configured; a model missing from both
+ * is charged at FALLBACK_PRICE, deliberately expensive, so an unknown model
+ * can only use the budget up faster, never overspend it.
*/
+import { syncedPriceFor } from './model-price-cache.js';
+
export const MODEL_PRICES = {
'google/gemini-3-flash-preview': { input: 0.5, output: 3 },
'google/gemini-3-flash': { input: 0.5, output: 3 },
@@ -26,18 +31,22 @@ export const FALLBACK_PRICE = { input: 5, output: 25 };
const TYPICAL_TOKENS = { input: 7000, output: 2000 };
/**
+ * A model's price: the synced one in effect now (for a call of
+ * `promptTokens`, which may cross a prompt-size price), else this table's.
* OpenRouter ids carry the provider id after an `openrouter/` prefix
* (`openrouter/google/gemini-3-flash-preview`); they're priced as that model.
*/
-export function priceFor(modelId) {
+export function priceFor(modelId, { promptTokens = 0 } = {}) {
+ const synced = syncedPriceFor(modelId, { promptTokens });
+ if (synced) return synced;
const id = String(modelId ?? '').replace(/^openrouter\//, '');
return MODEL_PRICES[id] ?? FALLBACK_PRICE;
}
/** USD cost of one call from the AI SDK's `usage`. */
export function generationCostUsd(modelId, usage) {
- const price = priceFor(modelId);
const input = Number(usage?.inputTokens) || 0;
+ const price = priceFor(modelId, { promptTokens: input });
const output = Number(usage?.outputTokens) || 0;
return (input * price.input + output * price.output) / 1_000_000;
}
diff --git a/server/src/lib/improve-cost.test.js b/server/src/lib/improve-cost.test.js
index a63240c34..4be7ac25b 100644
--- a/server/src/lib/improve-cost.test.js
+++ b/server/src/lib/improve-cost.test.js
@@ -1,4 +1,5 @@
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it } from 'vitest';
+import { setSyncedPrices } from './model-price-cache.js';
import {
FALLBACK_PRICE,
MODEL_PRICES,
@@ -40,6 +41,46 @@ describe('generationCostUsd', () => {
});
});
+describe('priceFor with synced prices (CHAT-16 §A)', () => {
+ afterEach(() => setSyncedPrices([]));
+
+ const HAIKU = {
+ model_id: 'anthropic/claude-haiku-5.5',
+ input_per_m: 0.1,
+ output_per_m: 0.5,
+ overrides: [{ min_prompt_tokens: 100000, prompt: '0.0000005', completion: '0.0000025' }],
+ };
+
+ it('reads the synced price first, under its hyphened or OpenRouter id too', () => {
+ setSyncedPrices([HAIKU]);
+ for (const id of [
+ 'anthropic/claude-haiku-5.5',
+ 'anthropic/claude-haiku-5-5',
+ 'openrouter/anthropic/claude-haiku-5.5',
+ ]) {
+ expect(priceFor(id)).toEqual({ input: 0.1, output: 0.5 });
+ }
+ });
+
+ it("falls back to the server's own table for a model that isn't synced", () => {
+ setSyncedPrices([HAIKU]);
+ expect(priceFor('google/gemini-3-flash-preview')).toBe(
+ MODEL_PRICES['google/gemini-3-flash-preview'],
+ );
+ expect(priceFor('someone/new-model')).toBe(FALLBACK_PRICE);
+ });
+
+ it('prices a call at the prompt-size override once its input is that large', () => {
+ setSyncedPrices([HAIKU]);
+ expect(
+ generationCostUsd('anthropic/claude-haiku-5.5', { inputTokens: 10_000, outputTokens: 1000 }),
+ ).toBeCloseTo(0.0015, 8);
+ expect(
+ generationCostUsd('anthropic/claude-haiku-5.5', { inputTokens: 100_000, outputTokens: 1000 }),
+ ).toBeCloseTo(0.0525, 8);
+ });
+});
+
describe('the same 1% budget buys more on a cheaper model', () => {
it('Growth ($2.49) on Flash vs GPT-5 mini vs Haiku', () => {
const left = (model) => estimateGenerationsLeft(2.49, typicalCostUsd(model));
diff --git a/server/src/lib/model-price-cache.js b/server/src/lib/model-price-cache.js
new file mode 100644
index 000000000..509b1d867
--- /dev/null
+++ b/server/src/lib/model-price-cache.js
@@ -0,0 +1,117 @@
+/**
+ * The synced model prices (chat_model_prices, 00404), held in this process
+ * so a call's cost is worked out without a database read (lib/improve-cost.js
+ * asks synchronously). model-prices.js fills it at start and after each
+ * daily sync; empty, every model is priced from improve-cost's own table, as
+ * before the sync existed.
+ *
+ * Pure: no database, no network.
+ */
+
+const DAY_NAMES = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
+
+/** model_id → its row, as model-prices.js reads it. */
+let synced = new Map();
+
+/** Replaces what the process holds with these rows. */
+export function setSyncedPrices(rows) {
+ synced = new Map((rows ?? []).map((row) => [row.model_id, row]));
+}
+
+/** How many models the process holds. */
+export function syncedCount() {
+ return synced.size;
+}
+
+/** A per-token price string as USD per million tokens; null when absent or variable ("-1"). */
+export function perMillion(value) {
+ if (value === null || value === undefined || value === '') return null;
+ const n = Number(value);
+ return Number.isFinite(n) && n >= 0 ? n * 1_000_000 : null;
+}
+
+/** HHMM (0–2400) as minutes into the day. */
+const minutesOf = (hhmm) => Math.floor(hhmm / 100) * 60 + (hhmm % 100);
+
+/**
+ * Whether a time override applies at `now` (UTC): its days, when it names
+ * any, and its window, when it has one (HHMM, end excluded; an end before the
+ * start runs past midnight).
+ */
+export function inTimeWindow(override, now) {
+ const days = Array.isArray(override.utc_days)
+ ? override.utc_days.map((d) => String(d).toLowerCase())
+ : null;
+ if (days && !days.includes(DAY_NAMES[now.getUTCDay()])) return false;
+ const start = Number(override.utc_start);
+ const end = Number(override.utc_end);
+ if (!Number.isFinite(start) || !Number.isFinite(end)) return true;
+ const at = now.getUTCHours() * 60 + now.getUTCMinutes();
+ const from = minutesOf(start);
+ const to = minutesOf(end);
+ return from <= to ? at >= from && at < to : at >= from || at < to;
+}
+
+const isTimeOverride = (o) => o && ('utc_days' in o || 'utc_start' in o || 'utc_end' in o);
+const isSizeOverride = (o) => o && Number.isFinite(Number(o.min_prompt_tokens));
+
+/** Whether the model's price changes by the hour or day (a time override). */
+export function variesByTime(row) {
+ return (row?.overrides ?? []).some(isTimeOverride);
+}
+
+/**
+ * The price in effect for a row: its time override at `now`, when one
+ * applies (CHAT-16 item 3), and on top the prompt-size override for a call
+ * that large (`promptTokens` at or above its min_prompt_tokens; the largest
+ * that fits). `{ input, output }` in USD per million tokens; null when the
+ * row has no usable base price.
+ *
+ * @param {object} row a chat_model_prices row
+ * @param {{ now?: Date, promptTokens?: number }} [at]
+ */
+export function priceInEffect(row, { now = new Date(), promptTokens = 0 } = {}) {
+ if (!row || row.input_per_m == null || row.output_per_m == null) return null;
+ let price = { input: Number(row.input_per_m), output: Number(row.output_per_m) };
+ const overrides = Array.isArray(row.overrides) ? row.overrides : [];
+ const apply = (override) => {
+ const input = perMillion(override.prompt);
+ const output = perMillion(override.completion);
+ price = {
+ input: input ?? price.input,
+ output: output ?? price.output,
+ };
+ };
+ const timed = overrides.find((o) => isTimeOverride(o) && inTimeWindow(o, now));
+ if (timed) apply(timed);
+ const sized = overrides
+ .filter((o) => isSizeOverride(o) && promptTokens >= Number(o.min_prompt_tokens))
+ .sort((a, b) => Number(b.min_prompt_tokens) - Number(a.min_prompt_tokens))[0];
+ if (sized) apply(sized);
+ return price;
+}
+
+/**
+ * The ids a model may be synced under: as given, without an `openrouter/`
+ * prefix, and with a trailing version's hyphen as OpenRouter's dot
+ * (`anthropic/claude-haiku-4-5` → `anthropic/claude-haiku-4.5`).
+ */
+export function catalogIds(modelId) {
+ const id = String(modelId ?? '').replace(/^openrouter\//, '');
+ const dotted = id.replace(/-(\d+)-(\d+)$/, '-$1.$2');
+ return dotted === id ? [id] : [id, dotted];
+}
+
+/** The synced row for a model, under any id it may be synced under; null when none. */
+export function syncedRow(modelId) {
+ for (const id of catalogIds(modelId)) {
+ const row = synced.get(id);
+ if (row) return row;
+ }
+ return null;
+}
+
+/** The synced price in effect for a model, or null when it isn't synced. */
+export function syncedPriceFor(modelId, at) {
+ return priceInEffect(syncedRow(modelId), at);
+}
diff --git a/server/src/lib/model-price-cache.test.js b/server/src/lib/model-price-cache.test.js
new file mode 100644
index 000000000..6640c7efe
--- /dev/null
+++ b/server/src/lib/model-price-cache.test.js
@@ -0,0 +1,133 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import {
+ catalogIds,
+ inTimeWindow,
+ perMillion,
+ priceInEffect,
+ setSyncedPrices,
+ syncedPriceFor,
+ variesByTime,
+} from './model-price-cache.js';
+
+/** The synced model prices, held in the process (CHAT-16 §A, 00404). */
+
+afterEach(() => setSyncedPrices([]));
+
+// Wednesday 2026-10-28 at 00:30, 01:30, 07:00 and 12:00 UTC, and Saturday 2026-10-31 at noon.
+const WED_0030 = new Date('2026-10-28T00:30:00Z');
+const WED_0130 = new Date('2026-10-28T01:30:00Z');
+const WED_0700 = new Date('2026-10-28T07:00:00Z');
+const WED_NOON = new Date('2026-10-28T12:00:00Z');
+const SAT_NOON = new Date('2026-10-31T12:00:00Z');
+
+/** OpenRouter's shapes, as the 2026-10-29 catalog lists them. */
+const WEEKDAYS = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'];
+const OFF_PEAK = { prompt: '0.00000066', completion: '0.00000198' };
+const PEAK = { prompt: '0.00000132', completion: '0.00000396' };
+const DEEPSEEK = {
+ model_id: 'deepseek/deepseek-v4-pro-0813',
+ input_per_m: 0.66,
+ output_per_m: 1.98,
+ overrides: [
+ { utc_days: ['saturday', 'sunday'], ...OFF_PEAK },
+ { utc_days: WEEKDAYS, utc_start: 0, utc_end: 100, ...OFF_PEAK },
+ { utc_days: WEEKDAYS, utc_start: 100, utc_end: 400, ...PEAK },
+ { utc_days: WEEKDAYS, utc_start: 400, utc_end: 600, ...OFF_PEAK },
+ { utc_days: WEEKDAYS, utc_start: 600, utc_end: 1000, ...PEAK },
+ { utc_days: WEEKDAYS, utc_start: 1000, utc_end: 0, ...OFF_PEAK },
+ ],
+};
+const HAIKU = {
+ model_id: 'anthropic/claude-haiku-5.5',
+ input_per_m: 0.1,
+ output_per_m: 0.5,
+ overrides: [{ min_prompt_tokens: 100000, prompt: '0.0000005', completion: '0.0000025' }],
+};
+
+describe('perMillion', () => {
+ it('reads a per-token price as USD per million tokens, and none for a variable one', () => {
+ expect(perMillion('0.000002')).toBeCloseTo(2);
+ expect(perMillion('0')).toBe(0);
+ expect(perMillion('-1')).toBeNull();
+ expect(perMillion(undefined)).toBeNull();
+ expect(perMillion('')).toBeNull();
+ });
+});
+
+describe('inTimeWindow', () => {
+ const nights = { utc_days: ['monday', 'wednesday'], utc_start: 0, utc_end: 100 };
+ it('applies on its days, inside its HHMM window, the end left out', () => {
+ expect(inTimeWindow(nights, WED_0030)).toBe(true);
+ expect(inTimeWindow(nights, WED_0130)).toBe(false);
+ expect(inTimeWindow(nights, new Date('2026-10-28T01:00:00Z'))).toBe(false);
+ expect(inTimeWindow(nights, new Date('2026-10-29T00:30:00Z'))).toBe(false);
+ });
+
+ it('applies all day on days without a window, and every day for a window without days', () => {
+ expect(inTimeWindow({ utc_days: ['Saturday'] }, SAT_NOON)).toBe(true);
+ expect(inTimeWindow({ utc_start: 1100, utc_end: 1600 }, SAT_NOON)).toBe(true);
+ });
+
+ it('runs a window past midnight when it ends before it starts, and to midnight at an end of 0', () => {
+ const overnight = { utc_start: 2200, utc_end: 200 };
+ expect(inTimeWindow(overnight, new Date('2026-10-28T23:30:00Z'))).toBe(true);
+ expect(inTimeWindow(overnight, WED_0130)).toBe(true);
+ expect(inTimeWindow(overnight, SAT_NOON)).toBe(false);
+ const evening = { utc_start: 1600, utc_end: 0 };
+ expect(inTimeWindow(evening, new Date('2026-10-28T23:59:00Z'))).toBe(true);
+ expect(inTimeWindow(evening, WED_NOON)).toBe(false);
+ });
+});
+
+describe('priceInEffect', () => {
+ it('takes the time override whose window it is', () => {
+ const at = (now) => priceInEffect(DEEPSEEK, { now });
+ expect(at(WED_0030)).toEqual({ input: expect.closeTo(0.66), output: expect.closeTo(1.98) });
+ expect(at(WED_0130)).toEqual({ input: expect.closeTo(1.32), output: expect.closeTo(3.96) });
+ expect(at(WED_0700).input).toBeCloseTo(1.32);
+ expect(at(WED_NOON).input).toBeCloseTo(0.66);
+ expect(at(SAT_NOON).input).toBeCloseTo(0.66);
+ });
+
+ it('keeps the base price where no time override applies', () => {
+ const nightsOnly = { ...DEEPSEEK, overrides: [DEEPSEEK.overrides[2]] };
+ expect(priceInEffect(nightsOnly, { now: WED_NOON })).toEqual({ input: 0.66, output: 1.98 });
+ });
+
+ it('takes the prompt-size price for a call that large, and not below it', () => {
+ expect(priceInEffect(HAIKU, { promptTokens: 7000 })).toEqual({ input: 0.1, output: 0.5 });
+ expect(priceInEffect(HAIKU, { promptTokens: 100000 })).toEqual({
+ input: expect.closeTo(0.5),
+ output: expect.closeTo(2.5),
+ });
+ });
+
+ it('gives none without a base price (a variable-priced router)', () => {
+ expect(
+ priceInEffect({ model_id: 'openrouter/auto', input_per_m: null, output_per_m: null }),
+ ).toBeNull();
+ expect(priceInEffect(null)).toBeNull();
+ });
+
+ it('says a model varies by the hour only for a time override', () => {
+ expect(variesByTime(DEEPSEEK)).toBe(true);
+ expect(variesByTime(HAIKU)).toBe(false);
+ });
+});
+
+describe('syncedPriceFor and catalogIds', () => {
+ it("finds a model under OpenRouter's id, its prefix or a hyphened version", () => {
+ expect(catalogIds('openrouter/anthropic/claude-haiku-5-5')).toEqual([
+ 'anthropic/claude-haiku-5-5',
+ 'anthropic/claude-haiku-5.5',
+ ]);
+ setSyncedPrices([HAIKU]);
+ expect(syncedPriceFor('anthropic/claude-haiku-5.5')).toEqual({ input: 0.1, output: 0.5 });
+ expect(syncedPriceFor('anthropic/claude-haiku-5-5')).toEqual({ input: 0.1, output: 0.5 });
+ expect(syncedPriceFor('openrouter/anthropic/claude-haiku-5.5')).toEqual({
+ input: 0.1,
+ output: 0.5,
+ });
+ expect(syncedPriceFor('google/gemini-3-flash')).toBeNull();
+ });
+});
diff --git a/server/src/lib/model-prices.js b/server/src/lib/model-prices.js
new file mode 100644
index 000000000..42fd2cee0
--- /dev/null
+++ b/server/src/lib/model-prices.js
@@ -0,0 +1,255 @@
+import cron from 'node-cron';
+import supabaseAdmin from '../config/supabase.js';
+import { logger } from './logger.js';
+import {
+ perMillion,
+ priceInEffect,
+ setSyncedPrices,
+ syncedRow,
+ variesByTime,
+} from './model-price-cache.js';
+
+/**
+ * The models' prices from OpenRouter's public catalog (CHAT-16 §A–B),
+ * synced daily into chat_model_prices (00404), behind CHAT_AGENTIC.
+ *
+ * The catalog needs no key. A sync upserts every model it lists and removes
+ * none: a failed or short read keeps the last good prices. After a sync, and
+ * when the server starts, the rows are loaded into model-price-cache.js, where
+ * a call's cost (improve-cost.js) and the multipliers below read them.
+ *
+ * Multipliers (CHAT-16 §B): a model's blended cost is 3 × its input price +
+ * its output price, at the price in effect; its multiplier is that over
+ * Auto's, so Auto is 1x. Dollars stay on the server: what a browser is ever
+ * sent is the multiplier's label.
+ */
+
+export const CATALOG_URL = 'https://openrouter.ai/api/v1/models';
+
+/** Fewer models than this in a read means a broken one: nothing is written. */
+const MIN_MODELS = 50;
+/** More models than this is a broken read too (the catalog lists a few hundred). */
+const MAX_MODELS = 5000;
+/** The most of the catalog's answer read (it is a few MB); a longer one is refused. */
+export const MAX_CATALOG_BYTES = 32 * 1024 * 1024;
+/** Rows one read of chat_model_prices gets (PostgREST's default cap is 1000). */
+const LOAD_PAGE = 1000;
+/** Rows one upsert writes. */
+const CHUNK = 200;
+const FETCH_TIMEOUT_MS = 20_000;
+/** Older than this at start, and the server syncs at once instead of waiting for the schedule. */
+const STALE_MS = 20 * 60 * 60 * 1000;
+
+/**
+ * Auto (CHAT-16 item 5): Claude Haiku 5.5 reads, Claude Sonnet 5.5 writes.
+ * Its blended cost is theirs mixed by how a run's steps usually split, 60%
+ * reading and 40% writing: the mix that gives every badge of the 2026-10-18
+ * fixture (item 8; model-prices.test.js).
+ */
+export const AUTO_MIX = Object.freeze({
+ 'anthropic/claude-haiku-5.5': 0.6,
+ 'anthropic/claude-sonnet-5.5': 0.4,
+});
+
+/**
+ * One catalog model as a chat_model_prices row; null for one without an id.
+ *
+ * @param {object} model an entry of the catalog's `data`
+ * @param {string} syncedAt
+ */
+export function rowOf(model, syncedAt) {
+ const id = typeof model?.id === 'string' ? model.id.trim() : '';
+ if (!id || id.length > 200) return null;
+ const pricing = model.pricing ?? {};
+ const arch = model.architecture ?? {};
+ const list = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string') : []);
+ return {
+ model_id: id,
+ name: typeof model.name === 'string' ? model.name : '',
+ provider: id.includes('/') ? id.split('/')[0] : '',
+ input_modalities: list(arch.input_modalities),
+ output_modalities: list(arch.output_modalities),
+ input_per_m: perMillion(pricing.prompt),
+ output_per_m: perMillion(pricing.completion),
+ cache_read_per_m: perMillion(pricing.input_cache_read),
+ image_output_per_m: perMillion(pricing.image_output),
+ overrides: Array.isArray(pricing.overrides)
+ ? pricing.overrides.filter((o) => o && typeof o === 'object')
+ : [],
+ is_batch: id.endsWith(':batch'),
+ synced_at: syncedAt,
+ };
+}
+
+/** The catalog's response as rows, the ones without an id left out. */
+export function rowsOf(catalog, syncedAt) {
+ const data = Array.isArray(catalog?.data) ? catalog.data : [];
+ return data.map((m) => rowOf(m, syncedAt)).filter(Boolean);
+}
+
+/**
+ * The catalog's answer as JSON, read up to MAX_CATALOG_BYTES: a longer one
+ * (by its Content-Length, or as it streams) throws before it is all in memory.
+ *
+ * @param {Response} res
+ * @param {number} [maxBytes]
+ */
+export async function readCatalog(res, maxBytes = MAX_CATALOG_BYTES) {
+ const declared = Number(res.headers?.get?.('content-length'));
+ if (Number.isFinite(declared) && declared > maxBytes) throw new Error('catalog too large');
+ if (!res.body?.getReader) throw new Error('catalog unreadable');
+ const reader = res.body.getReader();
+ const chunks = [];
+ let size = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ size += value.byteLength;
+ if (size > maxBytes) {
+ await reader.cancel().catch(() => {});
+ throw new Error('catalog too large');
+ }
+ chunks.push(value);
+ }
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
+}
+
+/**
+ * Reads the catalog and upserts every model it lists, then loads the rows
+ * into the process. A read that fails, or lists fewer than MIN_MODELS, writes
+ * nothing: the last good prices stay (CHAT-16 item 4).
+ *
+ * @returns {Promise<{ ok: boolean, models: number, syncedAt?: string, error?: string }>}
+ */
+export async function syncModelPrices({
+ fetcher = fetch,
+ db = supabaseAdmin,
+ now = new Date(),
+} = {}) {
+ let catalog;
+ try {
+ const res = await fetcher(CATALOG_URL, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
+ if (!res.ok) throw new Error(`catalog answered ${res.status}`);
+ catalog = await readCatalog(res);
+ } catch (err) {
+ logger.warn({ err: err.message }, '[model-prices] catalog unread; last prices kept');
+ return { ok: false, models: 0, error: err.message };
+ }
+ const syncedAt = now.toISOString();
+ const rows = rowsOf(catalog, syncedAt);
+ if (rows.length < MIN_MODELS) {
+ logger.warn({ models: rows.length }, '[model-prices] catalog too short; last prices kept');
+ return { ok: false, models: rows.length, error: 'too_few_models' };
+ }
+ if (rows.length > MAX_MODELS) {
+ logger.warn({ models: rows.length }, '[model-prices] catalog too long; last prices kept');
+ return { ok: false, models: rows.length, error: 'too_many_models' };
+ }
+ for (let i = 0; i < rows.length; i += CHUNK) {
+ const { error } = await db
+ .from('chat_model_prices')
+ .upsert(rows.slice(i, i + CHUNK), { onConflict: 'model_id' });
+ if (error) {
+ logger.error({ err: error.message }, '[model-prices] upsert failed');
+ return { ok: false, models: i, error: error.message };
+ }
+ }
+ await loadModelPrices({ db });
+ logger.info({ models: rows.length }, '[model-prices] synced');
+ return { ok: true, models: rows.length, syncedAt };
+}
+
+/**
+ * Loads every synced row into the process, LOAD_PAGE rows a read, and says
+ * when the last sync was (the newest synced_at); null with none. A failed
+ * read keeps what the process holds.
+ */
+export async function loadModelPrices({ db = supabaseAdmin } = {}) {
+ const data = [];
+ for (let from = 0; from < MAX_MODELS * 2; from += LOAD_PAGE) {
+ const { data: page, error } = await db
+ .from('chat_model_prices')
+ .select('*')
+ .order('model_id')
+ .range(from, from + LOAD_PAGE - 1);
+ if (error) {
+ logger.warn({ err: error.message }, '[model-prices] rows unread');
+ return null;
+ }
+ data.push(...(page ?? []));
+ if (!page || page.length < LOAD_PAGE) break;
+ }
+ setSyncedPrices(data);
+ const newest = data.reduce((max, r) => (r.synced_at > max ? r.synced_at : max), '');
+ return newest || null;
+}
+
+/**
+ * Started with the server while CHAT_AGENTIC is on: schedules the daily sync
+ * at MODEL_PRICES_SCHEDULE (05:17 UTC by default), then loads the rows and
+ * syncs at once when the last sync is older than a day (or there is none).
+ * Scheduled first, so a failed first sync still leaves the daily one.
+ */
+export async function startModelPriceSync({
+ schedule = process.env.MODEL_PRICES_SCHEDULE,
+ db = supabaseAdmin,
+ fetcher = fetch,
+} = {}) {
+ const at = schedule || '17 5 * * *';
+ cron.schedule(at, () => {
+ syncModelPrices({ db, fetcher }).catch((err) =>
+ logger.error({ err }, '[model-prices] sync crashed'),
+ );
+ });
+ logger.info({ schedule: at }, '[model-prices] daily sync scheduled');
+ const last = await loadModelPrices({ db });
+ if (!last || Date.now() - Date.parse(last) > STALE_MS) await syncModelPrices({ db, fetcher });
+}
+
+/** A model's blended cost at the price in effect (CHAT-16 item 6); null without a price. */
+export function blendedCost(modelId, now = new Date()) {
+ const price = priceInEffect(syncedRow(modelId), { now });
+ return price ? 3 * price.input + price.output : null;
+}
+
+/** Auto's blended cost: its models' mixed by AUTO_MIX; null while one isn't synced. */
+export function autoBlendedCost(now = new Date()) {
+ let total = 0;
+ for (const [id, share] of Object.entries(AUTO_MIX)) {
+ const cost = blendedCost(id, now);
+ if (cost === null) return null;
+ total += share * cost;
+ }
+ return total;
+}
+
+/** A model's multiplier against Auto (Auto = 1x); null when either isn't priced. */
+export function multiplierFor(modelId, now = new Date()) {
+ const auto = autoBlendedCost(now);
+ const cost = blendedCost(modelId, now);
+ if (!auto || cost === null) return null;
+ return cost / auto;
+}
+
+/** A multiplier as the menu shows it (CHAT-16 item 7): "1x", "2.3x", "<0.1x". */
+export function multiplierLabel(multiplier) {
+ if (multiplier < 0.1) return '<0.1x';
+ return `${Number(multiplier.toFixed(1))}x`;
+}
+
+/**
+ * What a model shows in a menu, and nothing that costs: its id, name, the
+ * multiplier's label and whether its price moves by the hour. No price
+ * leaves the server (CHAT-04).
+ */
+export function menuEntry(modelId, now = new Date()) {
+ const row = syncedRow(modelId);
+ const multiplier = multiplierFor(modelId, now);
+ if (!row || multiplier === null) return null;
+ return {
+ id: row.model_id,
+ name: row.name,
+ multiplier: multiplierLabel(multiplier),
+ variesByHour: variesByTime(row),
+ };
+}
diff --git a/server/src/lib/model-prices.test.js b/server/src/lib/model-prices.test.js
new file mode 100644
index 000000000..71e99adae
--- /dev/null
+++ b/server/src/lib/model-prices.test.js
@@ -0,0 +1,315 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const { Response, ReadableStream } = globalThis;
+
+vi.mock('../config/supabase.js', () => ({ default: {} }));
+vi.mock('./logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
+vi.mock('node-cron', () => ({ default: { schedule: vi.fn() } }));
+
+const cron = (await import('node-cron')).default;
+const { setSyncedPrices, syncedCount } = await import('./model-price-cache.js');
+const {
+ AUTO_MIX,
+ CATALOG_URL,
+ menuEntry,
+ multiplierFor,
+ multiplierLabel,
+ rowOf,
+ rowsOf,
+ startModelPriceSync,
+ syncModelPrices,
+} = await import('./model-prices.js');
+
+/** The models' prices from OpenRouter's catalog, and the multipliers (CHAT-16 §A–B). */
+
+afterEach(() => setSyncedPrices([]));
+
+const NOW = new Date('2026-10-29T12:00:00Z');
+const SYNCED = NOW.toISOString();
+
+const model = (id, prompt, completion, extra = {}) => ({
+ id,
+ name: id,
+ architecture: { input_modalities: ['text'], output_modalities: ['text'] },
+ pricing: { prompt, completion, ...extra },
+});
+
+describe('rowOf', () => {
+ it("keeps a model's prices per million tokens, its overrides as given, and its batch variant", () => {
+ const haiku = rowOf(
+ {
+ id: 'anthropic/claude-haiku-5.5',
+ name: 'Anthropic: Claude Haiku 5.5',
+ architecture: { input_modalities: ['text', 'image'], output_modalities: ['text'] },
+ pricing: {
+ prompt: '0.0000001',
+ completion: '0.0000005',
+ input_cache_read: '0.00000001',
+ overrides: [{ min_prompt_tokens: 100000, prompt: '0.0000005', completion: '0.0000025' }],
+ },
+ },
+ SYNCED,
+ );
+ expect(haiku).toEqual({
+ model_id: 'anthropic/claude-haiku-5.5',
+ name: 'Anthropic: Claude Haiku 5.5',
+ provider: 'anthropic',
+ input_modalities: ['text', 'image'],
+ output_modalities: ['text'],
+ input_per_m: expect.closeTo(0.1),
+ output_per_m: expect.closeTo(0.5),
+ cache_read_per_m: expect.closeTo(0.01),
+ image_output_per_m: null,
+ overrides: [{ min_prompt_tokens: 100000, prompt: '0.0000005', completion: '0.0000025' }],
+ is_batch: false,
+ synced_at: SYNCED,
+ });
+ expect(
+ rowOf(model('anthropic/claude-haiku-5.5:batch', '0.00000005', '0.00000025'), SYNCED),
+ ).toMatchObject({ is_batch: true });
+ expect(
+ rowOf(
+ model('google/gemini-3.1-flash-image', '0.0000005', '0.000003', {
+ image_output: '0.00006',
+ }),
+ SYNCED,
+ ).image_output_per_m,
+ ).toBeCloseTo(60);
+ });
+
+ it('keeps no price for a variable-priced router, and no row without an id', () => {
+ expect(rowOf(model('openrouter/auto', '-1', '-1'), SYNCED)).toMatchObject({
+ input_per_m: null,
+ output_per_m: null,
+ });
+ expect(rowOf({ name: 'nameless' }, SYNCED)).toBeNull();
+ expect(rowsOf({ data: [model('a/b', '0', '0'), {}] }, SYNCED)).toHaveLength(1);
+ expect(rowsOf(null, SYNCED)).toEqual([]);
+ });
+});
+
+/** A database that keeps the upserts, and gives them back on a read. */
+function fakeDb({ upsertError = null } = {}) {
+ const table = new Map();
+ const upserts = [];
+ const reads = [];
+ return {
+ table,
+ upserts,
+ reads,
+ from: () => ({
+ upsert: async (rows, opts) => {
+ upserts.push({ count: rows.length, opts });
+ if (upsertError) return { error: { message: upsertError } };
+ for (const r of rows) table.set(r.model_id, r);
+ return { error: null };
+ },
+ select: () => ({
+ order: () => ({
+ range: async (from, to) => {
+ reads.push([from, to]);
+ const rows = [...table.values()].sort((x, y) => (x.model_id < y.model_id ? -1 : 1));
+ return { data: rows.slice(from, to + 1), error: null };
+ },
+ }),
+ }),
+ }),
+ };
+}
+const catalog = (n) => ({
+ data: Array.from({ length: n }, (_, i) => model(`p/model-${i}`, '0.000001', '0.000002')),
+});
+const answer = (body, status = 200) =>
+ vi.fn(async () => new Response(JSON.stringify(body), { status }));
+
+describe('syncModelPrices', () => {
+ it('reads the public catalog with no key, upserts every model in chunks and loads them', async () => {
+ const db = fakeDb();
+ const fetcher = answer(catalog(450));
+ const result = await syncModelPrices({ fetcher, db, now: NOW });
+ expect(result).toEqual({ ok: true, models: 450, syncedAt: SYNCED });
+ expect(fetcher).toHaveBeenCalledWith(
+ CATALOG_URL,
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ );
+ expect(fetcher.mock.calls[0][1].headers).toBeUndefined();
+ expect(db.upserts.map((u) => u.count)).toEqual([200, 200, 50]);
+ expect(db.upserts[0].opts).toEqual({ onConflict: 'model_id' });
+ expect(db.table.get('p/model-7').synced_at).toBe(SYNCED);
+ expect(syncedCount()).toBe(450);
+ });
+
+ it('writes nothing when the catalog fails, answers badly or lists too few models', async () => {
+ for (const fetcher of [
+ vi.fn(async () => {
+ throw new Error('timeout');
+ }),
+ answer({}, 503),
+ answer(catalog(12)),
+ ]) {
+ const db = fakeDb();
+ const result = await syncModelPrices({ fetcher, db, now: NOW });
+ expect(result.ok).toBe(false);
+ expect(db.upserts).toEqual([]);
+ }
+ });
+
+ it('writes nothing for a catalog over the size cap or with too many models', async () => {
+ const big = vi.fn(
+ async () =>
+ new Response(
+ new ReadableStream({
+ pull(controller) {
+ controller.enqueue(new Uint8Array(1024 * 1024).fill(32));
+ },
+ }),
+ ),
+ );
+ const db = fakeDb();
+ const result = await syncModelPrices({ fetcher: big, db, now: NOW });
+ expect(result).toMatchObject({ ok: false, error: 'catalog too large' });
+ expect(db.upserts).toEqual([]);
+
+ const declared = vi.fn(
+ async () => new Response('{}', { headers: { 'content-length': String(64 * 1024 * 1024) } }),
+ );
+ expect(await syncModelPrices({ fetcher: declared, db, now: NOW })).toMatchObject({
+ ok: false,
+ error: 'catalog too large',
+ });
+
+ expect(await syncModelPrices({ fetcher: answer(catalog(5001)), db, now: NOW })).toMatchObject({
+ ok: false,
+ error: 'too_many_models',
+ });
+ expect(db.upserts).toEqual([]);
+ });
+
+ it('loads more rows than one read gives, a page at a time', async () => {
+ const db = fakeDb();
+ const result = await syncModelPrices({ fetcher: answer(catalog(2500)), db, now: NOW });
+ expect(result.ok).toBe(true);
+ expect(db.reads).toEqual([
+ [0, 999],
+ [1000, 1999],
+ [2000, 2999],
+ ]);
+ expect(syncedCount()).toBe(2500);
+ });
+
+ it('stops at an upsert that fails, keeping the prices it already had', async () => {
+ setSyncedPrices([{ model_id: 'kept/model', input_per_m: 1, output_per_m: 2 }]);
+ const result = await syncModelPrices({
+ fetcher: answer(catalog(80)),
+ db: fakeDb({ upsertError: 'db down' }),
+ now: NOW,
+ });
+ expect(result).toMatchObject({ ok: false, error: 'db down' });
+ expect(syncedCount()).toBe(1);
+ });
+});
+
+describe('startModelPriceSync', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ cron.schedule.mockClear();
+ });
+
+ it('schedules the sync daily at 05:17 UTC, and a run stamps every model with today', async () => {
+ vi.useFakeTimers({ now: NOW, toFake: ['Date'] });
+ const db = fakeDb();
+ const fetcher = answer(catalog(60));
+ await startModelPriceSync({ schedule: undefined, db, fetcher });
+ expect(cron.schedule).toHaveBeenCalledWith('17 5 * * *', expect.any(Function));
+ expect(fetcher).toHaveBeenCalledTimes(1);
+
+ vi.setSystemTime(new Date('2026-10-30T05:17:00Z'));
+ cron.schedule.mock.calls[0][1]();
+ await vi.waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));
+ await vi.waitFor(() =>
+ expect(db.table.get('p/model-0').synced_at).toBe('2026-10-30T05:17:00.000Z'),
+ );
+ });
+
+ it("doesn't sync at start when the last sync is under a day old", async () => {
+ vi.useFakeTimers({ now: NOW, toFake: ['Date'] });
+ const db = fakeDb();
+ db.table.set('p/model-0', { model_id: 'p/model-0', synced_at: '2026-10-29T05:17:00.000Z' });
+ const fetcher = answer(catalog(60));
+ await startModelPriceSync({ schedule: '0 3 * * *', db, fetcher });
+ expect(cron.schedule).toHaveBeenCalledWith('0 3 * * *', expect.any(Function));
+ expect(fetcher).not.toHaveBeenCalled();
+ expect(syncedCount()).toBe(1);
+ });
+
+ it('keeps the daily sync scheduled when the start throws', async () => {
+ const db = {
+ from: () => ({
+ select: () => ({
+ order: () => ({
+ range: async () => {
+ throw new Error('connection reset');
+ },
+ }),
+ }),
+ }),
+ };
+ await expect(startModelPriceSync({ db, fetcher: answer(catalog(60)) })).rejects.toThrow(
+ 'connection reset',
+ );
+ expect(cron.schedule).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('multipliers', () => {
+ /** CHAT-16 item 8's fixture, 2026-10-18: price line in, badge out. */
+ const FIXTURE = [
+ ['anthropic/claude-sonnet-5.5', 2, 10, '2.3x'],
+ ['anthropic/claude-opus-5.5', 4, 20, '4.7x'],
+ ['openai/gpt-6.1-sol', 2, 10, '2.3x'],
+ ['google/gemini-4-argon', 2, 10, '2.3x'],
+ ['x-ai/grok-4.7', 2, 6, '1.7x'],
+ ['google/gemini-3.8-flash', 0.83, 4.13, '1x'],
+ ['mistralai/mistral-large-4', 0.68, 2.09, '0.6x'],
+ ['anthropic/claude-haiku-5.5', 0.1, 0.5, '0.1x'],
+ ['deepseek/deepseek-v4.1-flash', 0.07, 0.14, '<0.1x'],
+ ];
+ const rows = FIXTURE.map(([model_id, input_per_m, output_per_m]) => ({
+ model_id,
+ name: model_id,
+ input_per_m,
+ output_per_m,
+ overrides: [],
+ }));
+
+ it("gives every badge of the fixture, with Auto's mix of Haiku and Sonnet at 1x", () => {
+ setSyncedPrices(rows);
+ for (const [id, , , badge] of FIXTURE)
+ expect(multiplierLabel(multiplierFor(id, NOW)), id).toBe(badge);
+ expect(Object.values(AUTO_MIX).reduce((a, b) => a + b, 0)).toBeCloseTo(1);
+ });
+
+ it('labels with one decimal, no trailing ".0", and "<0.1x" below a tenth', () => {
+ expect(multiplierLabel(1)).toBe('1x');
+ expect(multiplierLabel(0.96)).toBe('1x');
+ expect(multiplierLabel(2.33)).toBe('2.3x');
+ expect(multiplierLabel(0.0999)).toBe('<0.1x');
+ });
+
+ it("has no multiplier until Auto's models are synced", () => {
+ setSyncedPrices(rows.filter((r) => r.model_id !== 'anthropic/claude-haiku-5.5'));
+ expect(multiplierFor('x-ai/grok-4.7', NOW)).toBeNull();
+ });
+
+ it('gives a menu entry with no price in it: dollars stay on the server', () => {
+ setSyncedPrices(rows);
+ const entry = menuEntry('x-ai/grok-4.7', NOW);
+ expect(entry).toEqual({
+ id: 'x-ai/grok-4.7',
+ name: 'x-ai/grok-4.7',
+ multiplier: '1.7x',
+ variesByHour: false,
+ });
+ expect(JSON.stringify(entry)).not.toMatch(/per_m|input|output|\$|\b2\b|\b6\b/);
+ });
+});
diff --git a/server/src/server.js b/server/src/server.js
index 58e441e46..6013f86b4 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -63,6 +63,8 @@ import { sweepTaskChecks } from './lib/action-center/task-checks.js';
import { sendHealthReport } from './lib/health/report.js';
import { checkPromptUsageCounters } from './lib/prompt-usage-counters.js';
import { refreshCloroCountries } from './lib/cloro-countries.js';
+import { chatAgenticDeployed } from './lib/chat-flag.js';
+import { startModelPriceSync } from './lib/model-prices.js';
const app = express();
app.set('trust proxy', 1);
@@ -826,6 +828,13 @@ server.listen(PORT, async () => {
);
});
+ // Chat's model prices, from OpenRouter's public catalog, daily (CHAT-16 §A):
+ // only with the new Chat on. Off, nothing is fetched and every cost is
+ // read from improve-cost.js's own table, as before.
+ if (chatAgenticDeployed()) {
+ startModelPriceSync().catch((err) => logger.error({ err }, '[model-prices] start failed'));
+ }
+
if (!isCloud()) {
const schedule = process.env.DAILY_CRON_SCHEDULE || '0 6 * * *';
cron.schedule(schedule, async () => {
diff --git a/supabase/migrations/00404_chat_model_prices.sql b/supabase/migrations/00404_chat_model_prices.sql
new file mode 100644
index 000000000..2f2c67070
--- /dev/null
+++ b/supabase/migrations/00404_chat_model_prices.sql
@@ -0,0 +1,47 @@
+-- ============================================================================
+-- 00404: the models' prices, synced daily from OpenRouter's public catalog
+-- ============================================================================
+-- Chat (CHAT-16 §A, CHAT-00 `model_price`), behind CHAT_AGENTIC: a daily job
+-- reads https://openrouter.ai/api/v1/models (public, no key) and keeps every
+-- model's price here (server/src/lib/model-prices.js). What a model call costs
+-- is read from it first, and from the server's own table when a model isn't
+-- here (lib/improve-cost.js); multipliers (Auto = 1x) are worked out from it
+-- on the server.
+--
+-- * Prices are USD per million tokens (OpenRouter's per-token prices ×
+-- 1,000,000); null where OpenRouter gives none or a variable one ("-1").
+-- * overrides: OpenRouter's pricing.overrides as given. A time window
+-- (utc_days, utc_start/utc_end as HHMM) or a prompt size
+-- (min_prompt_tokens), each with the prices that apply in it.
+-- * is_batch: a ":batch" variant, kept as its own row and never offered.
+-- * synced_at: the last sync that listed the model. A model the catalog
+-- drops keeps its last row: a failed or partial sync never loses prices.
+--
+-- Dollars never reach a browser (CHAT-04, owner decision 2026-10-27): no
+-- policy lets a member read this table; only the server does.
+
+create table if not exists public.chat_model_prices (
+ model_id text primary key check (char_length(model_id) between 1 and 200),
+ name text not null default '',
+ provider text not null default '',
+ input_modalities text[] not null default '{}',
+ output_modalities text[] not null default '{}',
+ input_per_m numeric check (input_per_m is null or input_per_m >= 0),
+ output_per_m numeric check (output_per_m is null or output_per_m >= 0),
+ cache_read_per_m numeric check (cache_read_per_m is null or cache_read_per_m >= 0),
+ image_output_per_m numeric check (image_output_per_m is null or image_output_per_m >= 0),
+ overrides jsonb not null default '[]'::jsonb check (jsonb_typeof(overrides) = 'array'),
+ is_batch boolean not null default false,
+ synced_at timestamptz not null default now()
+);
+
+comment on table public.chat_model_prices is
+ 'CHAT-16 §A: OpenRouter''s public model catalog, synced daily (model-prices.js). USD per million tokens; server only, never sent to a browser.';
+comment on column public.chat_model_prices.overrides is
+ 'OpenRouter pricing.overrides as given: a UTC time window (utc_days, utc_start/utc_end HHMM) or a prompt size (min_prompt_tokens) with its per-token prices.';
+comment on column public.chat_model_prices.synced_at is
+ 'The last sync that listed the model; a model the catalog drops keeps its last row.';
+
+alter table public.chat_model_prices enable row level security;
+revoke all on table public.chat_model_prices from anon, authenticated;
+grant all on table public.chat_model_prices to service_role;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 1f18ca146..b0a0ba078 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -43536,3 +43536,54 @@ create policy "chat_user_prefs: own update"
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00404_chat_model_prices.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00404: the models' prices, synced daily from OpenRouter's public catalog
+-- ============================================================================
+-- Chat (CHAT-16 §A, CHAT-00 `model_price`), behind CHAT_AGENTIC: a daily job
+-- reads https://openrouter.ai/api/v1/models (public, no key) and keeps every
+-- model's price here (server/src/lib/model-prices.js). What a model call costs
+-- is read from it first, and from the server's own table when a model isn't
+-- here (lib/improve-cost.js); multipliers (Auto = 1x) are worked out from it
+-- on the server.
+--
+-- * Prices are USD per million tokens (OpenRouter's per-token prices ×
+-- 1,000,000); null where OpenRouter gives none or a variable one ("-1").
+-- * overrides: OpenRouter's pricing.overrides as given. A time window
+-- (utc_days, utc_start/utc_end as HHMM) or a prompt size
+-- (min_prompt_tokens), each with the prices that apply in it.
+-- * is_batch: a ":batch" variant, kept as its own row and never offered.
+-- * synced_at: the last sync that listed the model. A model the catalog
+-- drops keeps its last row: a failed or partial sync never loses prices.
+--
+-- Dollars never reach a browser (CHAT-04, owner decision 2026-10-27): no
+-- policy lets a member read this table; only the server does.
+
+create table if not exists public.chat_model_prices (
+ model_id text primary key check (char_length(model_id) between 1 and 200),
+ name text not null default '',
+ provider text not null default '',
+ input_modalities text[] not null default '{}',
+ output_modalities text[] not null default '{}',
+ input_per_m numeric check (input_per_m is null or input_per_m >= 0),
+ output_per_m numeric check (output_per_m is null or output_per_m >= 0),
+ cache_read_per_m numeric check (cache_read_per_m is null or cache_read_per_m >= 0),
+ image_output_per_m numeric check (image_output_per_m is null or image_output_per_m >= 0),
+ overrides jsonb not null default '[]'::jsonb check (jsonb_typeof(overrides) = 'array'),
+ is_batch boolean not null default false,
+ synced_at timestamptz not null default now()
+);
+
+comment on table public.chat_model_prices is
+ 'CHAT-16 §A: OpenRouter''s public model catalog, synced daily (model-prices.js). USD per million tokens; server only, never sent to a browser.';
+comment on column public.chat_model_prices.overrides is
+ 'OpenRouter pricing.overrides as given: a UTC time window (utc_days, utc_start/utc_end HHMM) or a prompt size (min_prompt_tokens) with its per-token prices.';
+comment on column public.chat_model_prices.synced_at is
+ 'The last sync that listed the model; a model the catalog drops keeps its last row.';
+
+alter table public.chat_model_prices enable row level security;
+revoke all on table public.chat_model_prices from anon, authenticated;
+grant all on table public.chat_model_prices to service_role;
+