Repository navigation
feat(chat): sync the models' prices daily from OpenRouter's catalog - #1771
Merged
Merged
Conversation
…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]>
… 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.
8 tasks done
gkhngyk
approved these changes
Oct 29, 2026
gkhngyk
left a comment
Contributor
There was a problem hiding this comment.
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 newreadCatalogrefuses an answer whoseContent-Lengthis 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.
loadModelPricesdid oneselect('*'), and PostgREST returns at most 1,000 rows by default. Once the catalog (with:batchand:freevariants) passed that, the models past the cap would have fallen back to the table orFALLBACK_PRICEwithout a word. It now reads 1,000 rows at a time, ordered bymodel_id. - Tests.
- An endless stream and an oversized
Content-Lengthboth 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.
- An endless stream and an oversized
What I checked
- Flag off changes nothing.
server.jsstarts the sync only whenchatAgenticDeployed()(CHAT_AGENTIC === 'true').- Off, nothing is scheduled or fetched, and nothing reads or writes
chat_model_prices. - The in-process map stays empty, so
priceForreadsimprove-cost.js's table exactly as before (improve-cost.test.jscovers it).
- The outbound read.
- It's a fixed
https://openrouter.ai/api/v1/models, with no key and no headers. - The 20 s
AbortSignal.timeoutcovers 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.
- It's a fixed
- No dollars reach a browser.
- Migration 00404.
- A new table:
model_idprimary key, non-negative price checks,overridesmust be an array. - RLS is on.
anonandauthenticatedhave 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.tschange.
- A new table:
- Prices.
- Prices are per million tokens. A
-1(variable) becomesnulland 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_tokensthat fits applies on top of the time override. catalogIdsalso maps a hyphenated version to OpenRouter's dotted id.
- Prices are per million tokens. A
- 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-costandchat-flagpass (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.shleavesschema.sqlunchanged.
Follow-ups
- Worth a decision before turning the flag on for a pilot. With
CHAT_AGENTIC=true, synced prices replaceimprove-cost.js's table for every model call in the deployment: Improve, content, briefs, and every workspace, not only those inCHAT_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,priceForcould read the synced price only for Chat's own calls. rowOfkeepsnameand eachoverridesentry as given. That's fine with the size bound, but aslice(0, 200)onnamewould keep the row tidy.
6 of 7 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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)-1or missing becomes null), the catalog'soverridesas they are,is_batch,synced_at.revoke allfrom anon and authenticated, service role only. No browser can read it.chat_*tables, not CHAT-00'smodel_price.server/src/lib/model-price-cache.js(pure)perMillion,catalogIds(handles theopenrouter/prefix and-5-5↔-5.5),syncedPriceFor.inTimeWindowreads a UTC day and HHMM window, wrapping past midnight when needed.priceInEffectapplies the hour override first, then the prompt-size override (min_prompt_tokens).server/src/lib/model-prices.jssyncModelPrices:GET https://openrouter.ai/api/v1/modelswith a 20 s timeout.startModelPriceSync:MODEL_PRICES_SCHEDULE, default17 5 * * *UTC), then loads the rows.multiplierFor= that ÷ Auto's. Labels look like "2.3x", "1x", "<0.1x".menuEntryreturns{ 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.generationCostUsdpasses the prompt size, so a model's long-prompt price applies.server.js:if (chatAgenticDeployed()) startModelPriceSync(). With the flag off nothing is fetched, and costs are computed exactly as today.chatAgenticDeployed()(inchat-flag.js) isCHAT_AGENTIC === 'true', whateverCHAT_AGENTIC_ORGSsays.Notes
CHAT_AGENTIC_ORGS,priceForuses 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.Conflict with #1743 (small, expected): both touch the same doc paragraph and the
priceForline ingenerationCostUsdinimprove-cost.js. Whichever merges second should combine them: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 (behindCHAT_AGENTIC)How to test
CHAT_AGENTIC=trueon staging. The log shows "[model-prices] daily sync scheduled" and "[model-prices] synced" (~457 models), andchat_model_prices.synced_atis today.cd server && npx vitest run src/lib/model-price-cache.test.js src/lib/model-prices.test.js.Checklist
bash supabase/build-schema.sh:schema.sqlis current🤖 Generated with Claude Code