/** * pricing.ts — pure, zero-dependency pricing math for LLM API cost estimation. * * Extracted from the pricing/cache-multiplier pattern in the author's own * Anthropic-calling apps (cruise-almanac's and first's * `api/_cost-monitoring.js`). No I/O, no SDK dependency, no product-specific * field names: token counts in, dollars out. * * THE BUG THIS FIXES * ------------------- * Anthropic's usage payload reports input in separate buckets: * - input_tokens (uncached remainder, base input rate) * - cache_read_input_tokens (served from cache; 0.1x the input rate * on most models, see CACHE_READ_MULTIPLIER) * - cache_creation_input_tokens (written to cache; the total of * cache_creation.ephemeral_5m_input_tokens * at 1.25x and * cache_creation.ephemeral_1h_input_tokens * at 2x the input rate) * - output_tokens (output rate) * * A real bug in that lineage (AUDIT-2026-05-01-v2, finding A3-CC-E-1) * collapsed both cache-creation TTLs into a single flat 1.25x multiplier. * That is correct for 5-minute writes but wrong for 1-hour writes, which cost * 2x. Applying 1.25x to a 1-hour write under-reports its cost by * (2.0 - 1.25) / 2.0 = 37.5%. This module keeps cache reads, 5-minute writes * and 1-hour writes as three distinct line items, each with its own * multiplier. `pricing.test.ts` shows the collapsed calculation gives a * different number. */ import { estimateCostMicros, priceFor, type DatedPricingTable, type LongContextRates, type MicrosPrice, type MicrosRates, type PriceLookup, type PricingTableDefinition } from './micros.js'; export { estimateCostMicros, priceFor }; export type { DatedPricingTable, LongContextRates, MicrosPrice, MicrosRates, PriceLookup, PricingTableDefinition }; /** * List-price rates for one model, supplied by the caller. This library ships * no price table and no default rates. * * Batch discounts, data-residency surcharges and fast-mode prices are not * modeled separately; fold them into these two numbers if they apply. The * cache multipliers are then applied to `inputPerMillion`. * * Pass a plain object or a null-prototype object. A `Map`, `Set`, `Date`, * `RegExp`, array or class instance throws a `TypeError` wherever rates are * read. */ export interface ModelRates { /** USD per 1,000,000 uncached input tokens. Must be a finite number >= 0. */ inputPerMillion: number; /** USD per 1,000,000 output tokens. Must be a finite number >= 0. */ outputPerMillion: number; /** * USD per 1,000,000 cache-read tokens (`cache_read_input_tokens`). Optional; * must be a finite number >= 0 when present. When set, it REPLACES * {@link CACHE_READ_MULTIPLIER} entirely for this call: cache-read cost * becomes `cacheReadTokens x cacheReadPerMillion`, not * `cacheReadTokens x inputPerMillion x CACHE_READ_MULTIPLIER`. Use it for a * model whose real cache-read rate is not 0.1x of `inputPerMillion` (see * {@link CACHE_READ_MULTIPLIER}), instead of the separate-call scaling * workaround. When omitted, cache reads keep pricing at * `inputPerMillion x CACHE_READ_MULTIPLIER`. Does not appear in * {@link formatRatesForLog}'s output. */ cacheReadPerMillion?: number; } /** * A pricing table keyed by model id, for example * `{ "my-model": { inputPerMillion: 3, outputPerMillion: 15 } }` (illustrative * numbers). Build it however you like (config file, remote fetch). Look models * up with {@link getRatesOrThrow}, which only matches the table's own keys. The * table must be a plain or null-prototype object; a `Map` is rejected rather * than read as an empty table. */ export type PricingTable = Record; /** * Cache reads (`cache_read_input_tokens`) are priced at 0.1x the base input * rate by default. This matches Anthropic's standard multiplier, but not * every model: Anthropic's pricing page (checked 2026-09-24) lists 0.025x for * Claude Fable 5.1 and Claude Mythos 5.1 and 0.05x for Claude Opus 5.5. For * those models this default over-estimates cache-read cost (4x and 2x). Set * {@link ModelRates.cacheReadPerMillion} to price such a model exactly * (preferred), or price its cache reads in a separate call with * `inputPerMillion` scaled by (model multiplier / 0.1). */ export declare const CACHE_READ_MULTIPLIER = 0.1; /** 5-minute-TTL cache writes (`cache_creation.ephemeral_5m_input_tokens`) are priced at 1.25x the base input rate. */ export declare const CACHE_CREATION_5M_MULTIPLIER = 1.25; /** * 1-hour-TTL cache writes (`cache_creation.ephemeral_1h_input_tokens`) are * priced at 2x the base input rate. Deliberately different from * {@link CACHE_CREATION_5M_MULTIPLIER}; never collapse the two. */ export declare const CACHE_CREATION_1H_MULTIPLIER = 2; /** * Token counts for one call, actual or projected. Every field is optional and * defaults to 0 when omitted or `undefined`. A supplied count must be a * non-negative safe integer; `null`, fractions, negatives, NaN and Infinity * throw. Any other key throws too, so a provider payload passed as-is (for * example `{ input_tokens }`) is rejected instead of priced at $0. * * Pass a plain object or a null-prototype object. A `Map`, `Set`, `Date`, * `RegExp`, array or class instance throws a `TypeError` instead of being * priced as zero usage. * * Mapping from an Anthropic `usage` block: `input_tokens` -> `inputTokens`, * `output_tokens` -> `outputTokens`, `cache_read_input_tokens` -> * `cacheReadTokens`, `cache_creation.ephemeral_5m_input_tokens` -> * `cacheCreation5mTokens`, `cache_creation.ephemeral_1h_input_tokens` -> * `cacheCreation1hTokens`. */ export interface UsageTokens { /** Uncached input tokens, priced at `inputPerMillion`. */ inputTokens?: number; /** Output tokens, priced at `outputPerMillion`. */ outputTokens?: number; /** Tokens served from cache, priced at {@link CACHE_READ_MULTIPLIER} x `inputPerMillion`. */ cacheReadTokens?: number; /** Tokens written to the 5-minute cache, priced at {@link CACHE_CREATION_5M_MULTIPLIER} x `inputPerMillion`. */ cacheCreation5mTokens?: number; /** Tokens written to the 1-hour cache, priced at {@link CACHE_CREATION_1H_MULTIPLIER} x `inputPerMillion`. Keep separate from 5-minute writes. */ cacheCreation1hTokens?: number; } /** * Compute the USD cost of one call, actual or projected. * * Formula, in this order, in IEEE-754 double precision: * `(input x inRate + cacheRead x readRate + write5m x inRate x 1.25 + * write1h x inRate x 2 + output x outRate) / 1,000,000`, then rounded to the * nearest micro-dollar ($0.000001) with `Math.round`, where `readRate` is * `rates.cacheReadPerMillion` when supplied, otherwise `inRate x 0.1` * ({@link CACHE_READ_MULTIPLIER}). * * Rounding policy: a value exactly halfway between two micro-dollars in binary * rounds up, but a cost that is a decimal half (for example 50 tokens at * $0.29/M = 14.5 micro-dollars) can round down because the intermediate * arithmetic is binary. A call cheaper than $0.0000005 returns 0. The result * is always the double nearest a whole number of micro-dollars, so it compares * equal to a decimal literal such as `0.0195`. * * Each field of `rates` and `usage` is read exactly once, before anything is * priced, and the cost is computed from those values, so a getter or proxy * that answers differently the second time cannot change the result. * * @param rates - Caller-supplied rates; there is no default. Both must be finite and >= 0. * @param usage - Token counts; see {@link UsageTokens}. * @returns Cost in USD, rounded to the nearest micro-dollar. * @throws TypeError if `rates` or `usage` is not a plain or null-prototype * object (`null`, `undefined`, a primitive, an array, a `Map`, `Set`, * `Date`, `RegExp` or class instance), a rate is not a number, an unknown * usage key is present (any own key that is not one of the five bucket names: * string or symbol, enumerable or not), or a token count is not a number. * A known bucket is read and validated whether or not it is enumerable. * @throws RangeError if a rate or token count is negative, non-finite (`NaN` * or `Infinity`), or not a safe integer (token counts only). Error messages * name the field but never echo the rejected value; an unknown usage key is * echoed escaped. * @throws Error (not TypeError/RangeError) only for the internal "result * must remain finite" safety net below: that guards the computed cost, * not a single bad input field. */ export declare function estimateCostUsd(rates: ModelRates, usage: UsageTokens): number; /** * Format a rate pair for logging, e.g. `"$3/M in, $15/M out"`. Log it on * every run so a stale or wrong rate is visible. * * Numbers are printed with JavaScript's default formatting and are not * validated or rounded: `NaN` prints as `$NaN/M`. A value that is not a number * is printed by kind (a string is quoted, with control, line-break and bidi * characters escaped), never through its own `toString`, so a bad rate cannot * forge a log line or send a terminal escape. Each rate is read once. * * @throws TypeError if `rates` is not a plain or null-prototype object * (`null`, `undefined`, an array, a `Map`, `Date`, class instance, ...). */ export declare function formatRatesForLog(rates: ModelRates): string; /** * Look up a model's rates in a pricing table, throwing instead of falling back * to a guessed default. * * Only the table's own keys match: inherited names such as `constructor`, * `toString` or `__proto__` throw like any unknown model. The returned * entry is the table's own object, not a copy, and is not validated here; * {@link estimateCostUsd} validates rates when it uses them. The model name * and the known-model list in the error message are escaped, so a model name * cannot forge a log line. * * @throws TypeError if `table` is not a plain or null-prototype object (a * `Map` is rejected, not read as an empty table) or `model` is not a string * (a `String` object, an array or an object with a `toString` is never * coerced into a key). * @throws Error naming the model and listing the table's known models. Plain * `Error`, not `TypeError`/`RangeError`: `model` isn't malformed input, * it's a validly-shaped key that has no configured entry — the same * "unconfigured lookup key" case trust-core's `identified.signalWeight` * also leaves as a plain `Error`. */ export declare function getRatesOrThrow(table: PricingTable, model: string): ModelRates; /** * What {@link usageFromAnthropic} and {@link usageFromOpenAI} return: the * token counts, or the fact that this response's usage cannot be told. * `unknown` is never zero: settle it as `{ usage: 'unknown' }` and a * reservation keeps its full estimate. */ export type UsageReading = { status: 'known'; usage: UsageTokens; } | { status: 'unknown'; reason: string; }; /** Options for {@link usageFromAnthropic}. */ export interface AnthropicUsageOptions { /** * Inference regions, besides the default (`'global'`), whose price your * table already covers. A response from any other region reads as unknown. */ allowInferenceGeo?: readonly string[]; } /** * Read an Anthropic Messages API `usage` block: `{ status: 'known', usage }` * with the token counts, or `{ status: 'unknown', reason }`. Never throws for a * malformed `usage`; only malformed `options` (static configuration) throw. * * - `input_tokens` and `output_tokens` are required non-negative safe * integers. A streaming `message_start` usage is NOT final (its * `output_tokens` is a placeholder): read a stream with * {@link usageFromAnthropicStream}, which wants the closing `message_delta`. * - `cache_read_input_tokens` maps to `cacheReadTokens`. * - Cache writes: when the `cache_creation` split is present, its * `ephemeral_5m_input_tokens` and `ephemeral_1h_input_tokens` map to the 5m * and 1h buckets, and `cache_creation_input_tokens`, if also present, must * equal their sum. When the split is absent, the whole * `cache_creation_input_tokens` total is priced as 5-minute writes (the * default TTL), never dropped. * - A cache field that is **absent** (or `null`) counts as 0: older API * versions omit them when no caching was used. One that is present but * malformed makes the reading unknown. * - Informational fields the SDK declares are accepted: `service_tier` (a * string; fold the tier's price into your table), `output_tokens_details` * (a breakdown inside `output_tokens`, which stays the billed total) and * `inference_geo`. `inference_geo` of `null` or `'global'` is known; another * region reads as unknown unless you list it in `options.allowInferenceGeo` * because your table prices it. `server_tool_use` is accepted only when * every count is 0, because per-request tool fees are not priced here. * - Beta fields are accepted when they are null/default (`speed` of * `'standard'`, `iterations`, `fallback_credit`) and unknown when populated. * * The reading is `unknown` when `usage` is missing, `null` or not a plain * object; `input_tokens` or `output_tokens` is missing; any count is not a * non-negative safe integer (a string such as `"123"`, `NaN`, `Infinity`, a * fraction, a BigInt, or above 2^53 - 1); a field this version does not know is * present (it might be a new billed bucket); a cache-write total disagrees * with its split; tool fees are nonzero; or a getter or Proxy trap throws. * `reason` is a short escaped sentence for logs. Each field is read once, and * `-0` reads as `0`. */ export declare function usageFromAnthropic(usage: unknown, options?: AnthropicUsageOptions): UsageReading; /** * Read a finished Anthropic stream: the `message.usage` of the `message_start` * event plus the usage of the final `message_delta` event. * * `message_start` carries the input side with a placeholder `output_tokens`; * `message_delta` carries the cumulative totals. A stream that ended before a * `message_delta` arrived (a client abort, a dropped connection) has no final * usage, so the reading is `unknown` with a reason naming `message_delta`, and * a reservation keeps its full estimate. A `message_delta` whose * `output_tokens` is not a number is not final either. * * Merge rule: for `input_tokens`, the cache counts, `output_tokens_details` * and `server_tool_use`, the delta's value wins when it is not null; otherwise * the start's value is kept. `output_tokens` always comes from the delta. The * `cache_creation` split, `service_tier` and `inference_geo` come from the * start. The merged usage is then read exactly like {@link usageFromAnthropic} * (so a delta total that disagrees with the start's cache split is unknown). * Never throws for malformed events. */ export declare function usageFromAnthropicStream(start: unknown, delta: unknown, options?: AnthropicUsageOptions): UsageReading; /** * Read an OpenAI `usage` object (Chat Completions or Responses shape): * `{ status: 'known', usage }` or `{ status: 'unknown', reason }`. Never * throws. Cached prompt tokens become `cacheReadTokens` and are subtracted * from `inputTokens`. `cache_write_tokens` of 0 is accepted and a nonzero one * is unknown (there is no priced OpenAI cache-write bucket); the same goes for * audio and image tokens. `text_tokens` and `reasoning_tokens` are informational * parts of the totals. A Chat Completions shape and a Responses shape mixed * together, cached tokens above the prompt total, a `total_tokens` that does * not add up and every other case that {@link usageFromAnthropic} lists are * `unknown`. A response with no `usage` at all is `unknown`, never zero. For an * embeddings response use {@link usageFromOpenAIEmbeddings}. */ export declare function usageFromOpenAI(usage: unknown): UsageReading; /** * Read the `usage` of an OpenAI embeddings response, `{ prompt_tokens, * total_tokens }`, as an input-only reading. It is a separate function because * a chat or Responses usage that lacks its output count must stay unknown; * only you know that this call was an embeddings call. `total_tokens`, when * present, must equal `prompt_tokens`; any other field is unknown. */ export declare function usageFromOpenAIEmbeddings(usage: unknown): UsageReading; /** * Validate and freeze a dated pricing table. This kit ships no prices: you * supply them, with the date you checked them and where you read them. * * Each entry is `{ inputPerMTokMicros, outputPerMTokMicros, * cacheWritePerMTokMicros?, cacheWrite1hPerMTokMicros?, cacheReadPerMTokMicros?, * longContext? }`: every price a non-negative safe integer of micro-dollars per * million tokens (a value above 2^53 - 1 is rejected and a BigInt is not * accepted). Look prices up with {@link priceFor} and cost usage with * {@link estimateCostMicros}. * * Any other key in an entry (a typo like `cacheWritePerMillion`) throws. Keys * must look like `provider:model` with a lowercase provider. The result is * frozen all the way down, with a null-prototype `rates` record, so editing * your input afterward changes nothing. A `-0` price reads as 0. Each entry is * read once. Pure: no clock is read here; check age with * {@link assertPricingFresh}. * * @throws TypeError for a wrong type or shape, RangeError for a bad date, * blank source, empty table, malformed key or invalid price. */ export declare function definePricingTable(definition: PricingTableDefinition): DatedPricingTable; /** Options for {@link assertPricingFresh}. */ export interface PricingFreshnessOptions { /** The current time, from your clock. Never read here. */ now: Date; /** The oldest acceptable table, in days. A finite number > 0. */ maxAgeDays: number; } /** * Throw unless `table` was checked within the last `maxAgeDays` days of * `now`. Call it at startup or per request, with a `now` from your clock. * The options object's two fields are each read once, and any other key is * rejected. * * A table that is exactly `maxAgeDays` old passes; one millisecond older * fails. A `checkedAt` up to one day in the future is allowed (a date written * in a time zone ahead of UTC); further in the future throws. * * @throws TypeError or RangeError for a malformed table or options, an invalid * `now`, or a `maxAgeDays` that is not a finite number > 0; RangeError for a * `checkedAt` more than a day in the future; Error when the table is older * than `maxAgeDays` (the message names its date, age and source). */ export declare function assertPricingFresh(table: DatedPricingTable, options: PricingFreshnessOptions): void;