Repository navigation
feat(chat): charge Chat's model calls to the one AI budget - #1788
Merged
Merged
Conversation
CHAT-04 §C items 11–14 and CHAT-16 items 22, 26 and 28–30 (DECISIONS P),
behind CHAT_AGENTIC. With the flag on, Chat runs on Ansvisor's key and
each model step draws on the monthly AI budget that Improve, the Content
Editor and the task writer already share, at the model's real cost (1x;
the margin stays with purchased AI credits).
- 00405: prompt_improve_usage.feature takes chat, agent, schedule and
image; own_key, chat_run_id and chat_run_step_id (on delete set null).
reserve_chat_ai_usage holds a step's worst case under the same
per-organization lock as reserve_ai_usage, and only while spend, holds
in flight and that worst case stay within the budget, so parallel runs
can't pass it. Own-key rows are written but left out of every sum
(reserve_ai_usage, ai_usage_by_feature, plan-guard's reads).
organizations.legacy_key_grandfathered marks Starter (and Growth trial)
workspaces that had a key, guarded as a server column.
- Server: lib/chat-budget.js and /api/internal/chat/budget/{reserve,
charge,release} (CRON_SECRET, Zod). The server prices every step; the
web never sends a cost, and no answer carries dollars.
- Web: lib/chat/key.ts picks the key (own key on Growth+, a kept Starter
key, else Ansvisor's ANTHROPIC_API_KEY); lib/chat/budget.ts reserves,
then charges, releases or keeps (a Stop's call is still billed). It
never throws: a refusal comes back typed with its words (chatBudget),
calls have 5 s limits, a reserve that gets no answer refuses the step,
and charge/release retry once after a 502.
- Billing: a Chat row in percent, and the "Agent Chat runs on your own AI
key" line changes while Chat is on. A key saved while Chat is off marks
the workspace to keep it.
With the flag off nothing changes: Agent Chat keeps the workspace's own
key only, and nothing is held or written.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…IP limit Every Chat model step makes two calls to /api/internal/chat/budget, and on Vercel the web's calls come from a few shared addresses, so the API limiter's 250-a-quarter-hour IP bucket would stop Chat for every workspace at once. apiLimiter now skips a request only when it is on that path and carries the internal secret (CRON_SECRET, compared in constant time); the same path without it, or the secret on any other path, is counted as before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
5 of 7 tasks
… a paid model at $0 The synced OpenRouter prices replaced improve-cost.js's table for every AI call in the deployment once CHAT_AGENTIC was on, not only for the pilot workspaces' Chat steps, and a catalog price of $0 metered a paid model's calls at nothing. priceFor now reads the synced price only when asked (chat-budget.js's hold and charge), and falls back to the table, or FALLBACK_PRICE, when a paid model's synced rate is $0. The table also prices OpenRouter's dotted ids (claude-haiku-5.5) as its own.
…on their own They're server to server (CRON_SECRET) and keyed by a run, not a brand, so the demo-brand guard on routes/index.js doesn't apply. The demo coverage test failed without the entry.
gkhngyk
approved these changes
Oct 29, 2026
gkhngyk
left a comment
Contributor
There was a problem hiding this comment.
Looks good with 0d593fc (take-1788). I merged main in (one conflict, an import list in rate-limiter.test.js) and added two commits.
What I changed
- Synced prices now price Chat's steps only, and a $0 catalog rate never meters a paid model.
- Before, with
CHAT_AGENTIC=true,priceForread the synced OpenRouter price first for every AI call in the deployment: Improve, the Content Editor, briefs and the task writer, in every workspace, not only the pilot ones. A catalog rate of $0 for a paid model metered its calls at $0. - Now
priceForandgenerationCostUsdread the synced price only with{ synced: true }. Onlychat-budget.jsasks for it, for the hold and the charge, and its routes answerchat_offoutsideCHAT_AGENTIC_ORGS. - A synced price with a $0 input or output rate is ignored unless the model is a
:freeone. The table prices it instead, orFALLBACK_PRICE. - The table also prices OpenRouter's dotted ids as its own. Chat's budget ids are
anthropic/claude-haiku-5.5andanthropic/claude-sonnet-5.5. Before, when the sync had no row for them, they fell toFALLBACK_PRICE($5/$25, about 50x Haiku's price). - Every other call is priced from
improve-cost.js's table, as before #1771.
- Before, with
- The demo coverage test failed.
demo-brand.test.jslists the route files mounted outsideroutes/index.js, andinternal-chat-budget.jsis one of them. It's server to server and keyed by a run, so I added it to the list with that reason.
What I checked
- Every Chat model call is metered once.
reserveholds the step's worst case, under the same per-organization lock asreserve_ai_usage. It is never retried, because a lost answer retried would hold twice.- Then exactly one of these happens:
charge: the row becomes the real cost (1x). Retrying it is safe, since it sets the row.release: the row goes. The web'ssettledguard makes it a no-op after a charge.keep: a Stop. The hold stays as the cost.
- If the API doesn't answer, the step doesn't run. If the web's flag is on and the API's is off,
reserveanswerschat_offand the step doesn't run either, so there is no unmetered path. - Own-key rows are written but left out of every sum: both SQL functions and the three
plan-guard.jsreads.
- Flag off.
reserveChatStepreturns the unmetered no-op and calls nothing.- The routes answer
chat_offbefore any read. getAiUsageonly addschatMetered: false.- The one write with the flag off is by design: the AI-providers PUT marks
legacy_key_grandfatheredon Starter and Growth-trial workspaces, so the cut-off is when the flag goes on.
- Rate limiter. It skips only
/api/internal/chat/budget/*with the rightCRON_SECRET, compared in constant time. - Migration 00405.
- It widens
prompt_improve_usage.feature. Adding the check scans the table once while holding an exclusive lock on it (see the sizing query below). - It adds three columns:
own_key boolean not null default false. That default is metadata-only, so no table rewrite.chat_run_idandchat_run_step_id, bothon delete set null, with partial indexes.
reserve_ai_usageandai_usage_by_featureare recreated with the same signatures, so their grants stay.reserve_chat_ai_usageissecurity definer, withsearch_path = public. It's revoked frompublic,anonandauthenticated, and granted toservice_role. It checks that the run belongs to the organization, and that the step belongs to the run.organizations.legacy_key_grandfatheredis added toguard_organization_server_columns(). The function is otherwise exactly main's current one (00276).prompt_improve_usagestays service-only: RLS on, no policies.
- It widens
- The rest.
- No embeds.
- No client→server import (
plan-row.test.tspasses).
Deploy order (important)
00405 must be on prod before this merges. Two things depend on it:
- The API's
plan-guard.jsnow filters onown_key. Without the column, every AI budget read fails. - The web's AI-providers PUT writes
legacy_key_grandfathered.
The web deploys on merge. Then the API.
Follow-ups (not blocking)
- A sweep for holds whose
reserveanswer was lost after 5 s. Today they stay as cost: over, never under. releasedeletes any of the workspace's Chat rows by id. The web never releases after a charge, but deleting only a row that is still a hold would be safer if another caller is ever added.- Clearing
legacy_key_grandfatheredon a plan change, as the PR says.
Tests:
improve-cost,chat-budget,internal-chat-budget,rate-limiter,model-prices,model-price-cacheanddemo-brandpass.- I checked that each new test fails without its fix.
- The full stack passes (see #1794).
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 C2: each Chat model step is charged to the workspace's one AI budget at its real cost (1x) (CHAT-04 §C items 11–14, 17; CHAT-16 items 22, 28, 29; DECISIONS P). Behind
CHAT_AGENTIC.The product owner confirmed on 2026-10-29: the plan budget is charged at 1x, and the 2x markup applies only to extra credit packs (CHAT-16 30a).
Server: internal endpoints
/api/internal/chat/budget/{reserve,charge,release}CRON_SECRET, Zod bodies. They never throw; every answer has a typed code. No dollars are sent or received: the web sends no cost, and the server prices each step.reserve: holds the step's worst case.201 { usageId };429 ai_limit { trial };402 plan_limit;404 not_found(the run isn't this workspace's);403 chat_off.charge: turns the hold into the real cost (generationCostUsd). If the provider reports no usage, the hold stays as the cost, so usage can be over-counted but never under-counted.release: lets the hold go. It is idempotent. A Stop keeps the hold as the cost, since the provider still bills an aborted call./apilimiter skips/api/internal/chat/budget/*, but only with a validCRON_SECRET(constant-timewebhookSecretsMatch). Vercel's calls can come from one IP, and 250 per 15 min would stop Chat.Migration 00405
prompt_improve_usage:featureaddschat,agent,scheduleandimage;own_key,chat_run_idandchat_run_step_id(FKon delete set null, partial indexes).reserve_chat_ai_usage:reserve_ai_usage, but stricter: a step starts only if spent + in-flight holds + this step's worst case ≤ the budget.reserve_ai_usage,ai_usage_by_featureandplan-guard's reads skip rows written with the workspace's own key.organizations.legacy_key_grandfathered: a server-only column.ai-providersPUT also sets it while the flag is off, so the cut-off is the moment the flag goes on.Which key (
web/src/lib/chat/key.ts)own_key); % doesn't moveANTHROPIC_API_KEYWeb
web/src/lib/chat/budget.ts: the engine's client. Every call has a 5 s limit.reservegets no answer or a 502, the step doesn't start, and the client returns{ ok: false, refusal: 'unavailable', retryable: true, message }withchatBudgetcopy.reserveisn't retried, since a lost answer retried would hold twice.chargeandreleaseretry once.Related issue
None (Chat P0, Drive › Chat).
Type of change
feat— New feature (behindCHAT_AGENTIC)How to test
cd server && npx vitest run src/lib/chat-budget.test.js src/routes/internal-chat-budget.test.js src/middleware/rate-limiter.test.js. They cover:chat_off;cd web && yarn vitest run src/lib/chat/budget.test.ts src/lib/chat/key.test.ts src/components/settings/ai-usage-card.test.tsx.For the maintainer:
ANTHROPIC_API_KEYin the web's Vercel environment.aiUsageHintcopy on plan cards;get_ai_usage's new lines.Checklist
bash supabase/build-schema.sh:schema.sqlis current🤖 Generated with Claude Code