Billing

BuiltFixture onlyChecked 16 November 2026

In short

  • Every call: quote, hold the most it could cost, settle at what it really cost.
  • A charge is never above the hold.
  • Caps per account, project, key, agent and session; loops are paused before they are paid for.

Petrova is not live. This page describes the billing code as it runs against fixtures. No real money has moved. Each promise names the test that proves it. The section Where the code does not keep the promise lists every gap found.

How Petrova earns

Every tool is charged at its own price: nothing is added to a call. Petrova earns when money is added to an agent's balance:

Way to add moneyFeeExample
USDG on Robinhood Chain or USDC on Base2%Add $20.00: you send $20.40, the agent gets $20.00
Card (not connected yet)4%Add $20.00: you pay $20.80
Test payment (test mode)2%, shown as it will be liveNo real money moves

The person sees the fee as an amount before paying. The whole amount goes to the agent's balance; the fee is booked to Petrova (platform_revenue) in the same journal. Rounding: the fee is rounded up once to the next nano-USD. Money that does not match a link exactly (a part, a late or extra transfer) is split by the same rule: the balance gets the largest amount whose price fits in what arrived (splitReceived, packages/billing/src/add-fee.ts). Tests: tests/unit/add-fee.test.ts.

Quote, hold, settle

Every paid thing (model call, tool call, chain.watch block, repo index, listing call) goes through three steps.

  1. Quote. Petrova prices the most the call could cost: the ceiling. The quote is bound to your account, project, key and a digest of the request (for a model call or a tool URL, an HMAC under a per-account key, so the digest cannot confirm a guessed prompt). It lasts 120 seconds by default (60 seconds on the gateway). A quote cannot change after it is made.
  2. Hold. Under a lock on your account, Petrova checks your balance and every cap, then holds the ceiling. The hold, the request record and the work order are written in one transaction. Nothing is sent to a supplier before that transaction commits.
  3. Settle. When the call ends, Petrova charges the actual cost and releases the rest of the hold. A tool call is charged the tool's own price, nothing added. A model call (not on sale) adds a 5.5% fee; on reseller calls, the savings fee below.

For a model call, the ceiling is: the input bound (body bytes ÷ 3, rounded up) at the highest input-side price the request could reach, plus max_tokens at the output price, plus the fee. The 1-hour cache write price is used only if the request asks for a 1-hour cache.

Tests (tests/integration/quotes.test.ts):

  • "a quote is bound to its payload, its tenant and a single use"
  • "an expired quote cannot be accepted and creates no liability"
  • "price drift cannot raise accepted liability: quotes are immutable"
  • "idempotent accept replays one hold; a different payload conflicts"
  • "nothing is dispatchable until the hold commits"
  • "100 concurrent accepts cannot overspend the balance"

What counts as an answer

A tool call that returns 2xx is not charged if the reply is empty, shaped like an error, or the wrong shape for a tool with an output schema. A seller's http_2xx success check no longer pays out on an empty reply either. Some wrong answers cannot be detected and are charged: see what cannot be detected.

Who can settle

Only Petrova settles. POST /v1/settlements needs the operator:settle scope. No customer key can have it: createKey refuses it, and only the operator script npm run operator:key issues it. A hold that a running call owns (the gateway or the memory worker) is refused even to an operator key; that process settles it, or the sweeper does. The MCP server has no settle tool.

A bare hold is operator work too: POST /v1/holds needs operator:hold, which no customer key can have. Holds for real calls are taken by the call itself. A bare hold is closed by the sweeper (free) if no operator settles it. Its idempotency keys are stored as api:<key>, so they can never take a key that one of Petrova's own flows uses (for example a chain.watch hold).

Tests (tests/integration/settle-auth.test.ts):

  • "a customer key gets 403 on settlement, and the gateway settlement still works"
  • "createKey can never grant operator:settle, and an operator key cannot spend"
  • "an operator key cannot settle a hold a running call owns"
  • "customer idempotency keys get their own namespace, so they cannot occupy an internal flow's key"
  • "the MCP server exposes no settle tool"

Never above the hold

The charge can never be higher than the hold. If the real cost is higher, Petrova pays the difference, not you. This is enforced in every settlement path:

PathRuleTest
Model callcharge = min(cost + fee, hold); the excess is booked to Petrova's absorbed_costsettlement.test.ts, "the quote is a ceiling: overspend is absorbed, never charged"; pricing.test.ts, "a charge never exceeds list price plus the fee, and the hold always covers it"
No usable usage from the suppliercharge = a local estimate (see below), never the hold, flagged for a true-updelivery.test.ts, "a 200 with no usage is charged a local estimate (input from the body, output from the bytes delivered), flagged for true-up"
Unknown cost (only after a crash: the sweeper)charge = the hold, flagged for reconciliationsettlement.test.ts, "unknown supplier cost charges the hold and is flagged for reconciliation"
True-upcharge = min(what was charged, invoice + 5.5%): it can only go downtrueup.test.ts, "an ingested invoice file trues up estimated and unknown-cost charges, only ever downward, and receipts show it"
Reseller callcharge = min(list, cost + savings fee, hold)resellers.test.ts, "an Anthropic-format reseller serves a call: the customer pays cost plus the savings fee, the reseller is paid its cost for that call"
x402 "exact" toolcharge = the challenge price + fee, which is what was heldtools.test.ts, "happy path: 402, verify, hold, sign, retry, settle at the challenge amount"
x402 "upto" toolcharge = the amount the tool settled + fee; the rest of the ceiling is releasedtools.test.ts, "an x402 "upto" tool is charged the amount it settled, not the authorised ceiling; a missing or bad amount charges the ceiling"
chain.watchcharge = delivered × price; above the hold throwschain.test.ts, "stream delivers events with summaries and charges exactly delivered x price, in blocks of N"
Customer AWScharge = min(fee, hold)bedrock.test.ts, "above $3,000 of list spend in the month, the fee is 5% of the excess, charged once"
Listing calla price above the hold is refusedearn.test.ts, "a successful call moves the listed price from buyer to seller, minus the seller fee, inside the ledger"

Pay-later: an agent with income from other accounts may hold more than its cash, up to the lower of $500 and 30% of its last 7 days of income. A charge still never passes the hold, but the agent can end up owing the shortfall, which its next income repays first.

Reseller calls: the savings fee

When a reseller serves a call for less than list, you pay the reseller's cost plus Petrova's fee, and the fee is 25% of the saving against list, capped at 6% of what you pay. No saving, no fee. Your price is never above list and never below Petrova's cost. If a reseller ever cost more than list, you pay list and Petrova absorbs the rest. A reseller is used for a call only when its cost ceiling is below the list ceiling. One rounding step, down, in your favour (savingsFeeNusd, packages/billing/src/resale.ts).

Example: list $4.00, reseller cost $2.00. 25% of the $2.00 saving is $0.50; 6% of spend caps the fee at $0.127659. You pay $2.127659 and keep $1.872341.

The receipt shows list_nusd, charged_nusd (what you paid) and saving_nusd.

Tests: tests/unit/resellers.test.ts, "resale split: cost plus the savings fee (25% of the saving, at most 6% of spend), never above list or below cost, capped at the hold"; resellers.test.ts (above).

Direct calls (and the Venice-style upstream, which has no configured cost) still pay list + 5.5%.

Failures before the first word

If a supplier fails before it sends the first piece of content, Petrova moves to the next supplier. Once content has started, it never switches. If every supplier fails, the hold is released and you pay nothing.

Tests (tests/integration/messages.test.ts):

  • "a 529 from the first upstream fails over to the next, stream and non-stream"
  • "a stream that errors before content fails over; a connection error fails over too"
  • "no failover once content has started"
  • "when every upstream fails the hold is released and the last error is returned"

Also settlement.test.ts, "a failed call costs the customer nothing", and openai.test.ts, "openai routes fail over before first content, stream and non-stream, and record call progress".

Nothing delivered, nothing charged

You never pay for output you did not get. When a supplier may have charged Petrova for a call you left, you pay at most what was measured, never the full hold.

What happenedYou payTest (tests/integration/delivery.test.ts)
Your client leaves before content, on a supplier that reports usage only at the end (Venice-style)The supplier request is aborted. Only the input tokens counted locally (body bytes ÷ 4), at catalog prices + fee. No output. Flagged input_only; any gap to the supplier's invoice is Petrova's"Venice-style supplier, client leaves before content: the upstream is aborted and only the locally counted input is charged"
Your client leaves before content, on a Claude-format supplier that already reported inputThe reported input tokens + fee. No output—
The stream ends with no content block (an error event, or empty)Nothing"a stream that ends with no content block is a failure before the first word: free"
A 200 answer with no usable usageA local estimate: input from the body (bytes ÷ 4), output from the content bytes delivered (÷ 4). Flagged estimated"a 200 with no usage is charged a local estimate (input from the body, output from the bytes delivered), flagged for true-up"
A stream cut after content, from a supplier that reports usage only at the endThe same local estimate, output from the bytes that reached you"a stream cut after content from an end-reporting supplier is charged a local estimate, not the hold"

An estimate is never above the hold. When the supplier's invoice arrives, the true-up can only lower it (below).

Crash cleanup

While a call runs, the gateway writes a lease (900 seconds, renewed every 300 seconds) and, once a supplier has answered, a "served" mark with the supplier's reference.

A sweeper closes holds that are older than 15 minutes (900 seconds) and whose lease has run out:

  • Not served: closed as failed, reason swept_stale. You pay nothing. A queued repo index whose hold is closed this way also loses its staged file text.
  • Served: closed as unknown cost, at the hold, flagged until a supplier invoice arrives.
  • Served on your own AWS: closed as failed, free.

Concurrent sweepers close each hold exactly once.

The sweeper is on by default in the API process: every 60 seconds, for holds older than 900 seconds. PETROVA_SWEEP_INTERVAL_SECONDS=0 turns it off; npm run sweep runs one pass.

Tests (tests/integration/sweeper.test.ts):

  • "the sweeper fails a stale unserved hold as swept_stale, charges nothing, and is idempotent"
  • "a stale hold whose call was served settles as unknown_cost, flagged for reconciliation"
  • "concurrent sweepers close each stale hold exactly once"
  • "a gateway killed mid-call leaves its hold to the sweeper: unserved fails free, served settles as unknown_cost"

Default on: tests/unit/config.test.ts, "the API process runs the stale-hold sweeper by default (every 60 s, holds older than 900 s); the env var turns it off".

Refunds and true-ups

  • Refund. A refund returns the whole charge, once, as a new journal. The database refuses a refund above the charge. Test: sellers.test.ts, "a refund returns the whole charge once, as a balanced journal, and never more than was charged".
  • Seller check. 2% of eligible (temperature 0) calls are re-run on a reference supplier, streamed calls too: the gateway rebuilds the final message in memory and sends the reference the same request as non-stream. It is on by default when a non-direct supplier (a reseller or the Venice-style upstream) is configured next to a direct one, which is the reference. A supplier that fails is suspended and every call it served in the last 24 hours is refunded, across accounts. Tests: sellers.test.ts, "a seller whose output diverges is suspended, skipped by the router, and its last-24h calls are refunded"; "streamed calls are re-checked too: the assembled final message is compared, and a diverging stream seller is refunded"; "sampling is on by default at 2% when a non-direct supplier is configured next to a direct one".
  • True-up. When a supplier invoice arrives for an unknown-cost or estimated call, the charge becomes min(what was charged, invoice + 5.5%) and the rest is refunded, once. An invoice above an estimate never raises your charge; Petrova absorbs it. The operator records invoices with npm run invoices:ingest -- invoices.json (fixture files only; no supplier API is called). Tests: clawback.test.ts, "an invoice for an unknown_cost reservation refunds the customer the difference automatically, exactly once"; trueup.test.ts, "an ingested invoice file trues up estimated and unknown-cost charges, only ever downward, and receipts show it".
  • Refunded calls stop counting against every cap. Test: hardening.test.ts, "a refunded call no longer counts against agent, session, key, project or account caps".

There is no refund request API for customers.

Caps

Caps can be set per account, project, key, agent and session. A parent agent's cap covers its own spend plus every child agent that names it as parent, so one budget can be split across subagents. Caps are checked under the same account lock as the balance. A settled call counts what it charged, not what it held.

On every model route, agent and session ids come from x-petrova-agent-id, x-petrova-parent-agent-id and x-petrova-session-id, or the x-claude-code-* headers Claude Code sends. On the OpenAI-format routes they also come from metadata, user, or Codex's session-id header. A malformed id is refused, never dropped, because a dropped id would skip its cap.

A call that sends no agent or session id is not counted by those caps. Key, project and account caps always apply.

POST /v1/budgets sets all five, with the body { "scope", "ref", "limit_nusd" }. The limit is a string of whole nano-USD: {"scope":"agent","ref":"research-bot","limit_nusd":"5000000000"} is a $5 cap. The answer shows committed_nusd (charged plus held right now) and remaining_nusd. There is no route to list or delete caps yet. It needs the budget:write scope, so a key that can spend cannot raise its own caps. scope: "account" caps your account; "project" and "key" take a project or key id of your account in ref (default: the calling key's own); "agent" and "session" take the id. A project or key of another account is refused.

Tests:

  • budgets.test.ts: "POST /v1/budgets sets account, project and key caps under budget:write; a spending key cannot"; "a project or key of another account cannot be capped; malformed refs are refused"; "50 concurrent holds across two projects cannot overspend an account cap set over HTTP"
  • quotes.test.ts: "100 concurrent accepts cannot overspend a key budget"; "project and account budgets are enforced independently"
  • agents.test.ts: "50 concurrent holds cannot overspend an agent budget"; "50 concurrent holds cannot overspend a session budget"; "a parent agent budget bounds the sum of its children (budget split)"
  • messages.test.ts: "an agent over its cap gets the clean spend-limit 429 and nothing is held"

Loop pause

Before quoting a model call, Petrova looks at the last 20 tool calls in the request. Each call is fingerprinted by name and arguments, with ids and timestamps masked.

  • The same call 3 times: warn (x-petrova-loop: warn header, on streams too).
  • The same call 5 times: pause. Petrova returns 429 with x-petrova-loop: pause and x-should-retry: false, before anything is held or sent.
  • An A-B-A-B run: warn at 4, pause at 8.
  • Operator override: PETROVA_LOOP_PAUSE=off in the API process lets a would-be pause through, marked x-petrova-loop: pause-overridden. No key can change it.

Tests: messages.test.ts, "a repeating tool loop is paused before it is paid for again"; "the loop warning also reaches a streaming client, and an operator override lets a would-be pause through"; openai.test.ts, "openai routes pause a repeating tool loop before it is paid for again"; loops.test.ts, "three identical calls in the last 20 warn, five pause".

Receipts

Each call gets a receipt id in the x-petrova-receipt header (and, on streams, a final SSE comment with outcome and charge). GET /v1/receipts?session_id= and GET /v1/receipts/:id show: model (the model id, e.g. claude-opus-5-5) and resource (what was quoted), the supplier that served the call (on a failed call, the last one tried), upstreams_attempted (every supplier tried, in order), agent, parent agent and session, token counts, held, list price, fee, charged, absorbed, released, status, cost_basis (reported, estimated or input_only), whether it was re-checked, and what came back: refund_nusd, true_up_refunded_nusd and their sum refunded_nusd. Reseller calls add list_nusd and saving_nusd.

Tests: agents.test.ts, "receipts join quote, hold and settlement correctly and stay inside the tenant"; messages.test.ts, "receipts list every supplier attempted, name the supplier on a failed call, and show the real model id"; trueup.test.ts (above).

Response headers

Built today, on model calls:

HeaderWhat it says
x-petrova-receiptThe receipt id for this call. On streams, a final comment also carries the outcome and charge.
x-petrova-loopwarn, pause or pause-overridden. See loop pause.
x-petrova-memory-tokensHow many tokens repo memory added.
x-petrova-max-tokensmax_tokens was lowered to fit the hold, and this is the value the supplier was given. See below.
x-should-retryfalse means fix something first. true on some supplier errors.

A large max_tokens means a large hold, which could refuse a call that would cost cents. So when the hold does not fit your balance or a cap, Petrova lowers max_tokens until it does, and tells you with x-petrova-max-tokens. It never goes below 1,024 tokens: below that, the call is refused as before. The hold is still a true ceiling. This does not apply on your own AWS.

Planned, not built. No response carries these yet. Read the receipt or GET /v1/balance instead. The names may change.

HeaderWhat it would say
x-petrova-cost-nusdWhat this call cost
x-petrova-balance-nusdThe available balance after this call
x-petrova-hold-nusdWhat was held for this call
x-petrova-cap-remaining-nusdWhat is left under the tightest cap

Where the code does not keep the promise

  1. Estimates are estimates. Without usable usage, input is counted as body bytes ÷ 4 and output as delivered content bytes ÷ 4. That can be above or below the supplier's count. Above: the true-up gives the difference back once the invoice arrives. Below: Petrova absorbs it.
  2. A Claude-format client that leaves after the supplier's first event pays the input the supplier reported. No output is charged.
  3. The savings fee covers configured resellers only. The Venice-style upstream has no configured cost, so its calls pay list + 5.5%, above the plan's rule.
  4. The loop-pause override is process-wide, not per agent.
  5. Invoices come from a file. No supplier invoice API is connected; until an invoice file is ingested, an estimated or unknown-cost call is not trued up.

Last checked against the code: 16 November 2026. Something wrong? The source of this page is in the repository, so a fix is one edit.