Skip to content

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

Merged
gkhngyk merged 10 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-model-prices
Oct 29, 2026
Merged

gkhngyk merged 10 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-model-prices

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

Chat P0, part C1: model prices synced daily from OpenRouter's public model list (no key), with the cost multipliers Chat's model menu will show (CHAT-16 §A, §B items 1–6). No dollar amount reaches a browser (CHAT-04, the "no dollars in the UI" rule). Nothing is visible yet.

Migration 00404 (chat_model_prices)

  • Columns: model id (PK), name, provider, modalities, input / output / cache / image prices ($ per 1M; -1 or missing becomes null), the catalog's overrides as they are, is_batch, synced_at.
  • Access: RLS on, revoke all from anon and authenticated, service role only. No browser can read it.
  • It is named like the other chat_* tables, not CHAT-00's model_price.

server/src/lib/model-price-cache.js (pure)

  • Prices kept in memory: perMillion, catalogIds (handles the openrouter/ prefix and -5-5 ↔ -5.5), syncedPriceFor.
  • Overrides:
    • inTimeWindow reads a UTC day and HHMM window, wrapping past midnight when needed.
    • priceInEffect applies the hour override first, then the prompt-size override (min_prompt_tokens).

server/src/lib/model-prices.js

  • syncModelPrices:
    • Reads GET https://openrouter.ai/api/v1/models with a 20 s timeout.
    • Fewer than 50 models, or a failed read, writes nothing and keeps the last good prices.
    • Upserts in chunks of 200, deletes nothing, then reloads the cache.
  • startModelPriceSync:
    • Schedules the daily cron first (MODEL_PRICES_SCHEDULE, default 17 5 * * * UTC), then loads the rows.
    • It syncs at once when the last sync is over 20 hours old or missing.
    • A failed first sync leaves the daily job in place.
  • Multipliers: blended cost = 3 × input + output, and multiplierFor = that ÷ Auto's. Labels look like "2.3x", "1x", "<0.1x". menuEntry returns { id, name, multiplier, variesByHour } with no price, and a test checks that.

improve-cost.js: priceFor(modelId, { promptTokens }) reads the synced price in effect first, then the table as before. generationCostUsd passes the prompt size, so a model's long-prompt price applies.

server.js:

  • In production startup, if (chatAgenticDeployed()) startModelPriceSync(). With the flag off nothing is fetched, and costs are computed exactly as today.
  • chatAgenticDeployed() (in chat-flag.js) is CHAT_AGENTIC === 'true', whatever CHAT_AGENTIC_ORGS says.

Notes

  1. Flag scope: once the flag is on, even for one organization through CHAT_AGENTIC_ORGS, priceFor uses synced prices for every caller (plan guard, task writer, suggestion relevance). OpenRouter's list prices match the providers'. The table still prices models the catalog lacks.
  2. Auto's mix is an assumption: Haiku 5.5 60%, Sonnet 5.5 40%. It reproduces every badge in CHAT-16 §B8's 18 Oct table (fixture test). The spec doesn't state the mix.
  3. Overrides in the catalog: most are by prompt size. GPT-6.1 Sol and Grok vary by size, not by hour, as CHAT-16 said. Only 4 models vary by hour.
  4. Development: there is no menu route yet. Development doesn't sync, so multipliers are null locally until a sync is triggered by hand.

Conflict with #1743 (small, expected): both touch the same doc paragraph and the priceFor line in generationCostUsd in improve-cost.js. Whichever merges second should combine them:

const input = Number(usage?.inputTokens) || 0;
const base = priceFor(modelId, { promptTokens: input });
const output = Number(usage?.outputTokens) || 0;
const price = base.long && input > base.long.over ? base.long : base;

Related issue

None (Chat P0, Drive › Chat).

Stacked on #1758 (Chat A1, for the flag). The diff against it holds only this change.

Type of change

  • feat — New feature (behind CHAT_AGENTIC)

How to test

  1. Apply 00404 and deploy the server with CHAT_AGENTIC=true on staging. The log shows "[model-prices] daily sync scheduled" and "[model-prices] synced" (~457 models), and chat_model_prices.synced_at is today.
  2. cd server && npx vitest run src/lib/model-price-cache.test.js src/lib/model-prices.test.js.
  3. A manual run on a copy of the real catalog (457 models: 71 batch, 7 without prices, 4 varying by hour) gave these badges: Haiku 0.1x, Sonnet 2.3x, Opus 4.7x, GPT-6.1 Sol 2.3x, Grok 4.7 1.7x, DeepSeek V4.1 Flash <0.1x.

Checklist

🤖 Generated with Claude Code

cihan-gyk and others added 6 commits October 29, 2026 12:51
…eams

The first part of the new Chat (Drive Chat specs, P0 part A1). Nothing
uses it yet, and with the flag off nothing changes: today's
/dashboard/agent keeps its own tables and code.

- CHAT_AGENTIC turns the new Chat on, read on the server at request time
  (web lib/chat/flag.ts, server lib/chat-flag.js), so the same build runs
  with it on or off. CHAT_AGENTIC_ORGS narrows it to listed workspaces.
  Off unless "true", so a self-hosted install sees nothing new.
- 00400 adds chat_conversations, chat_messages, chat_runs, chat_run_steps
  and chat_user_prefs. A chat is private to its author (CHAT-20 §16c):
  only they read it, admins included, and messages, runs and steps follow
  their chat's policies, so sharing with the team can be one more policy
  later. The server writes them; a person writes only their own Chat
  settings (menu, where pages open, focus areas, model, effort), kept on
  the server so they follow them across devices (DECISIONS N3).
- A step's tool and debug record stay with the server: members are
  granted every other column. Step kinds live in chat_step_kinds, so a
  new kind is an inserted row, not a rewritten check.
- web lib/chat/events.ts types every event a run streams (CHAT-00, with
  room for CHAT-25's), names steps by their place in the run, and
  chatEvent() refuses a tool's name, a debug record, an id or a dollar
  amount before an event reaches the browser.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A deleted brand now leaves its chats with their author, as about the
workspace, the way agent_conversations does (00009), rather than
deleting a person's private history with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nd add app links and the step converter

A uuid in an event's text (a page path, a link the person pasted) no
longer stops the run: chatEvent() shows it as "…". The answer's own text
is still sent as it is, and forbidden keys still throw.

- Forbidden keys are patterns now, in the type (ChatForbiddenKey) and at
  run time alike: any tool key (toolInput, toolResult…) and params; debug,
  tokens and latency; money (usd, price, amount, spend, cost, cents). A
  cost multiplier, a percent and a tooltip still pass.
- Deliverable cards and page.opened get an optional href for their Open
  (CHAT-06, CHAT-25): a path under /dashboard/ only, with no host, query,
  fragment, "//" or ".." part, kept whole by the masking.
- steps.ts holds chat_run_steps' member columns (every one but tool and
  debug_json, checked against the migration's grant) and toClientStep(),
  the one way a stored step reaches the browser: built field by field, so
  a row read with the service role gives up its tool and debug record too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ch new message

- chat_user_prefs.focus holds at most the 8 areas, each once
  (chat_text_array_distinct: a check can't hold a subquery); the model
  column says the server checks it against the catalog before a run.
- A trigger on chat_messages sets its chat's last_message_at (security
  definer, so it reaches the chat whoever writes the message; it never
  moves back).
- The step kinds comment no longer says a kind can be removed: steps
  keep theirs, and there is no index on kind to find out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y be read

A change applies when the app starts again: a restart when self-hosted,
a new deployment on Vercel. The web flag is for dynamic server code only;
a page rendered at build time would keep the build's value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
CHAT-16 §A–B, behind CHAT_AGENTIC: with the flag on, the deployed server
reads OpenRouter's public model catalog (no key) at start when the last
sync is over 20 h old, and daily at MODEL_PRICES_SCHEDULE (05:17 UTC by
default), into chat_model_prices (00404). A failed read, or one listing
fewer than 50 models, writes nothing; a sync never deletes rows.

The rows are held in the process (model-price-cache.js), so priceFor
stays synchronous: the synced price in effect comes first, with its
time-of-day override and its prompt-size override for a large call, and
improve-cost.js's own table prices a model the sync doesn't have, or
every model with the flag off.

Multipliers are worked out on the server: blended cost 3 x input +
output, over Auto's (Claude Haiku 5.5 / Sonnet 5.5 at 60/40, the mix that
gives every badge of CHAT-16's 2026-10-18 fixture). menuEntry gives a
model's id, name, multiplier label and whether it varies by the hour,
and no price: the table has no member policy and no route reads it yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 29, 2026
… in the database

A message's content_md takes up to 200,000 characters, a step's scope_json
up to 8 KB and its debug_json up to 1 MB as text, so a run that forgets to
shorten a tool's output can't grow a row without limit. Checked now, while
the tables are new, so no later migration has to scan them to add it.
The catalog's answer is read up to 32 MB (by its Content-Length, then as it
streams), and a read listing more than 5,000 models writes nothing, as one
listing too few already did. The synced rows are loaded 1,000 at a time, so
a catalog past PostgREST's row cap still prices every model.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good with 137f8e0: I made one change on top (and merged #1758's fix in, 0db4d0b).

What I changed

  • The catalog's read had no size bound. res.json() read the whole answer into memory, however long. The new readCatalog refuses an answer whose Content-Length is over 32 MB, and stops a streamed one once it passes that. Today's catalog is a few MB.
  • No upper bound on models. A read listing more than 5,000 models now writes nothing (too_many_models), as a read with fewer than 50 already did.
  • Loading the rows could stop at 1,000. loadModelPrices did one select('*'), and PostgREST returns at most 1,000 rows by default. Once the catalog (with :batch and :free variants) passed that, the models past the cap would have fallen back to the table or FALLBACK_PRICE without a word. It now reads 1,000 rows at a time, ordered by model_id.
  • Tests.
    • An endless stream and an oversized Content-Length both write nothing.
    • 5,001 models write nothing.
    • 2,500 rows load in three pages.
    • The test's fake responses are now real Responses, so the bounded reader is what's tested. On the PR's head, the endless stream ran the worker out of memory.

What I checked

  • Flag off changes nothing.
    • server.js starts the sync only when chatAgenticDeployed() (CHAT_AGENTIC === 'true').
    • Off, nothing is scheduled or fetched, and nothing reads or writes chat_model_prices.
    • The in-process map stays empty, so priceFor reads improve-cost.js's table exactly as before (improve-cost.test.js covers it).
  • The outbound read.
    • It's a fixed https://openrouter.ai/api/v1/models, with no key and no headers.
    • The 20 s AbortSignal.timeout covers the body as well as the connection.
    • It's bounded now (above).
    • A failure, a non-2xx, too few or too many models, or an upsert error keeps the last prices. Rows are upserted, never deleted.
  • No dollars reach a browser.
    • This PR adds no route, action, page or prop. chat_model_prices has RLS on with no member grants.
    • menuEntry() returns id, name, the multiplier label and variesByHour, with no price.
    • The registry and event code from #1758/#1759 refuse price/usd/cost keys.
  • Migration 00404.
    • A new table: model_id primary key, non-negative price checks, overrides must be an array.
    • RLS is on. anon and authenticated have everything revoked, and only the service role is granted.
    • if not exists, no backfill, no lock on an existing table.
    • The table is server-only, so there's no types/supabase.ts change.
  • Prices.
    • Prices are per million tokens. A -1 (variable) becomes null and falls back to the table.
    • A time override applies within its UTC window, which can wrap past midnight.
    • For prompt size, the largest min_prompt_tokens that fits applies on top of the time override.
    • catalogIds also maps a hyphenated version to OpenRouter's dotted id.
  • Several API instances. Each one schedules the sync. The upserts are idempotent, so that's harmless.
  • No PostgREST embeds.
  • Tests:
    • model-prices, model-price-cache, improve-cost and chat-flag pass (44).
    • The full server suite passes on the stack merged with main (4,019).
    • The full web suite passes too (5,623).
    • eslint and prettier pass, and build-schema.sh leaves schema.sql unchanged.

Follow-ups

  1. Worth a decision before turning the flag on for a pilot. With CHAT_AGENTIC=true, synced prices replace improve-cost.js's table for every model call in the deployment: Improve, content, briefs, and every workspace, not only those in CHAT_AGENTIC_ORGS. They're list prices, so the numbers should be close. Still, AI-budget metering for workspaces outside the pilot then follows OpenRouter's catalog, including its time-window and prompt-size prices. If that should wait for Chat's launch, priceFor could read the synced price only for Chat's own calls.
  2. rowOf keeps name and each overrides entry as given. That's fine with the size bound, but a slice(0, 200) on name would keep the row tidy.

@gkhngyk
gkhngyk merged commit d33fb0f into ansvisor:main Oct 29, 2026
4 of 5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants