# Pricing math (/docs/pricing)



`@pleach/core/pricing` is the cost math. It turns a turn's token
counts into a dollar figure against a `(family × callClass)` rate
matrix. It's what puts the USD number next to a row in the
[audit ledger](/docs/audit-ledger) — pure functions plus an optional
live-rate resolver, no side effects in the hot path.

## `computeTurnCost` [#computeturncost]

The pure primitive. Give it the token counts and a matrix; get back
the cost, or `null` when the matrix has no cell for that
`(family, callClass)`.

```ts
import { computeTurnCost, DEFAULT_PRICING_MATRIX } from "@pleach/core/pricing"

const cost = computeTurnCost(
  {
    family: "anthropic",
    callClass: "converse",
    inputTokens: 1_200,
    outputTokens: 800,
    reasoningTokens: 400, // folded into output at the output rate
  },
  DEFAULT_PRICING_MATRIX, // optional; this is the default
)
// cost: ComputeTurnCostResult | null
```

`ComputeTurnCostInput` carries `family`, `callClass`, `inputTokens`,
`outputTokens`, and optional `reasoningTokens`. Input tokens are
*fresh* tokens — cache reads are not billed at the input rate.
Reasoning tokens bill at the output rate. A missing matrix cell
returns `null` rather than guessing, so a caller never silently
under-reports.

## `DEFAULT_PRICING_MATRIX` [#default_pricing_matrix]

The bundled rate table. Every `(family × callClass)` cell is present —
no missing-cell fallback needed. Each cell is a `PricingEntry`:

```ts
interface PricingEntry {
  readonly inputCostPer1M: number   // USD per 1M input tokens
  readonly outputCostPer1M: number  // USD per 1M output tokens
}
```

## Live rates — `createPricingResolver` [#live-rates--createpricingresolver]

Bundled rates drift. `createPricingResolver` caches a fetched matrix
and re-fetches when it goes stale.

```ts
import { createPricingResolver, DEFAULT_PRICING_MATRIX } from "@pleach/core/pricing"

const resolver = createPricingResolver({
  ttlMs: 60 * 60 * 1000,          // consider a fetched matrix fresh for 1h
  fallback: DEFAULT_PRICING_MATRIX, // used until the first fetch lands
})

const matrix = await resolver.resolve()
const cost = computeTurnCost(input, matrix)
```

* `ttlMs` — freshness window. Within it, `.resolve()` returns the
  cached matrix synchronously (wrapped in a resolved promise); past it,
  the next `.resolve()` triggers a fetch that blocks until the new data
  lands. Set `ttlMs: Infinity` to fetch exactly once — the right choice
  in a short-lived function invocation.
* `fallback` — returned when no matrix is cached and the first fetch
  fails. After that, a failed fetch returns the last-good matrix. Pass
  `DEFAULT_PRICING_MATRIX`.
* Concurrent `.resolve()` calls during a fetch share one in-flight
  request — no fetch stampede.

`schedulePricingRefresh(resolver, { intervalMs })` drives the refresh
on a timer instead of lazily on read.

## OpenRouter rates [#openrouter-rates]

The live source behind the resolver is OpenRouter's model list.

* `fetchOpenRouterPricing(opts?)` → `FetchOpenRouterPricingResult` —
  pulls current per-model rates (override `endpoint` to point at a
  mirror).
* `fetchOpenRouterPricing` keeps a published cache-read rate only when it
  is at least a tenth of the prompt rate, with one exception: for a
  trusted provider family it keeps the rate whenever it is above 0, still
  capped at the prompt rate. The default trusted family is
  `deepseek`; the family is parsed from the catalog slug's
  provider segment with `parseModelSlug`. Pass `trustedCacheReadFamilies` (a
  `ReadonlySet<ProviderFamily>` that replaces the default) to change the set,
  or an empty set to apply the floor to every model. A missing, zero or
  unparseable rate is still omitted.
* `parseOpenRouterEndpointPrices(body, opts?)` and
  `createOpenRouterEndpointPriceCache` apply the same cache-read rule to the
  per-endpoint rates that price a call at the upstream that served it. A
  published `input_cache_read` rate is kept only when it is above 0, at least a
  tenth of that endpoint's prompt rate unless the model's provider family is
  trusted, and it is capped at the prompt rate. Any other rate is omitted, so
  cached prompt tokens on that upstream are priced at the full input rate. A
  published rate of `0` is not applied. The family is parsed from the model id
  with `parseModelSlug`. `createOpenRouterEndpointPriceCache` takes the same
  `trustedCacheReadFamilies` option as `fetchOpenRouterPricing`;
  `parseOpenRouterEndpointPrices` takes it, and an optional `modelId` (default:
  the body's `data.id`), in `ParseOpenRouterEndpointPricesOptions`. Because the
  cap and the floor apply per endpoint, an upstream whose endpoints differ only
  in raw cache-read rate resolves to a price once the rule makes those rates
  agree, rather than falling back to the catalog rate.
* `applyToMatrix({ base, byModelId, modelIdMap })` — folds fetched
  per-model rates into a `(family × callClass)` matrix, mapping model
  IDs to matrix cells.

## Per-call pricing and the cost table [#per-call-pricing-and-the-cost-table]

The matrix prices a turn by `(family × callClass)`. The per-call pricer
prices one model call from its own token counts and the rates for the
model that served it. The audit ledger uses it for each `modelCall`
row.

**The cost table.** The bundled per-model table carries each OpenRouter
slug's list price from the `/models` catalog, and so does each bare alias
that mirrors one. A drift test compares it with a committed catalog
snapshot, so it can't quietly diverge. Anthropic rows also carry
`cacheReadPer1M` and `cacheWritePer1M`, the 5-minute cache-write rate.
A row without a cache rate leaves that token class unpriced.

**`priceCallUsd` and `buildModelRateIndex`.** Both are exported from
`@pleach/core/pricing`.

```ts
import { buildModelRateIndex, priceCallUsd } from "@pleach/core/pricing"

const usd = priceCallUsd(
  { inputTokens: 12_000, outputTokens: 800, cachedInputTokens: 9_000 },
  { inputCostPer1M: 3, outputCostPer1M: 15, cacheReadCostPer1M: 0.3 },
)
// number, or undefined when the call can't be priced

const rates = buildModelRateIndex([
  { id: "my-model", rates: { inputCostPer1M: 3, outputCostPer1M: 15 } },
])
```

`inputTokens` is the whole prompt. Cache reads and cache writes are
subsets of it, priced at their own rates, and the rest is priced at the
input rate. The result is `undefined`, never `0` and never a fallback
rate, when:

* the call read the cache and no cache-read rate exists;
* the call wrote the cache without a 5-minute and 1-hour split, or with
  no rate for a lifetime it wrote (`cacheWrite5mCostPer1M`,
  `cacheWrite1hCostPer1M`);
* the counts don't add up, or a count is fractional, negative or unsafe.

`@pleach/observe` uses both to price rows when it records them. Pass
`init({ modelRates })` a rate index from `buildModelRateIndex`. A row
that carries no cost is then priced from it, looked up by model id. A
cost that can't be known stays `costOmitted: "unpriced"`.

**Ambiguous upstreams.** Some OpenRouter models are served by several
upstreams that publish different rows. `lookup` still answers `ambiguous`
for these, and the call is refused unless you answer it.
`OpenRouterEndpointPriceCache.lookupCandidates(model, provider, atMs?)`
returns every published row of an upstream at one instant. The pure
`highestPricedServedPrice(usage, prices)` then picks the row that
charges the call the most, graded as a whole row on the call's token
mix. Use it to price an ambiguous upstream at its dearest published
rate. `parseOpenRouterEndpointCandidates` builds the same rows from an
`/endpoints` response. A custom `OpenRouterEndpointPriceCache` must
implement `lookupCandidates`.

**Time-of-day prices.** OpenRouter publishes some rates that change by
UTC day and hour. `fetchOpenRouterPricing` keeps those windows on
`PricingEntry.timeOfDay`, beside the unchanged base rates, and
`parseOpenRouterEndpointPrices` keeps them per upstream. Two upstream rows
that differ only by schedule read as ambiguous.

`servedPriceAt(modelId, price, schedule, atMs, trustedFamilies?)` returns
the flat price at one instant. Applicable windows overlay the base rate
in published order, per rate, and the cache-read rule below applies to the
result. With no schedule or no open window you get the same `price`
object back. `OpenRouterEndpointPriceCache.lookup` takes an optional
`atMs` and defaults to the cache's clock. Pass your own server clock,
never a time read from a request.

A window that can't be applied as published is refused whole: an unknown
condition, an unreadable rate or clock, a one-sided clock, or equal start
and end. Windows conditioned on prompt size are refused too, so those
models parse to the entry they always did. `computeTurnCost` and
`createPricingResolver` read only the flat rates and ignore the schedule.

**The cache-read floor.** A published cache-read rate counts only when it
is above 0, at least a tenth of the prompt rate unless the provider
family is trusted, and capped at the prompt rate. The catalog and the
per-endpoint source apply this one rule, so the same cached tokens price
the same on both. Cached tokens with no usable rate price at the full
input rate. Two edges can lower a price. A cache-read rate above the
upstream's own prompt rate is now capped at it. An upstream whose
endpoints differed only in raw cache-read rate used to resolve
`ambiguous`, and now resolves to a price once the rule makes those rates
agree.

For how a row records which of these priced it, see
[Price basis](/docs/auditable-call-row#price-basis) and
[Catalog price and drift](/docs/auditable-call-row#catalog-price-and-drift).

## Helpers [#helpers]

* `parseModelSlug(slug)` → `ParseModelSlugResult | null` — splits a
  `"vendor/model"` slug into its parts, or `null` when the slug isn't a
  single `vendor/model` pair.
* `resolveCostEventUsd(event, matrix?)` — returns the event's own
  `costUsd` when the seam already priced it (a real rate is never
  overridden), and otherwise computes the cost from the event's token
  counts. This is the reconciliation seam: providers that report a
  price keep it; providers that don't get one derived.

## Where it sits [#where-it-sits]

The cost figure this module computes rolls up per turn into the audit
ledger's `TokenCostRecord` (see [Typed records](/docs/typed-records))
and, in a multi-tenant deployment, into
[`@pleach/gateway`'s cost events](/docs/gateway/cost-events). Pricing
is the shared arithmetic underneath both.
