Open History to see the last commit
1/**
2 * Rate cards on the catalog (issue #60): store only values that parse as
3 * RateCard, compile OpenRouter listings at write, and project a compact
4 * token formula on list rows.
5 */
6import {
7 cardParams,
8 cardCurrency,
9 compileOpenRouterPricing,
10 price,
11 rateCardSchema,
12 RateCardError,
13 verifyExamples,
14} from '@modelschemas/rate-card'
15import type { RateCard } from '@modelschemas/rate-card'
16
17import { contentHash, stableStringify } from '#/server/kv.ts'
18import { emptySources } from '#/server/providers/fact-sources.ts'
19import type { ModelFactSources } from '#/server/providers/types.ts'
20
21/**
22 * Request-bound param names allowed even when they are not properties of
23 * the bound input schema (`input_tokens` is the type specimen). Usage-bound
24 * params skip this check.
25 */
26const CARD_LEVEL_LEVERS = new Set([
27 'input_tokens',
28 'output_tokens',
29 'cache_read_tokens',
30 'cache_write_tokens',
31 'cache_write_1h_tokens',
32 'reasoning_tokens',
33 'image_tokens',
34 'image_output_tokens',
35 'audio_tokens',
36 'audio_output_tokens',
37 'audio_cache_tokens',
38 'web_searches',
39 'requests',
40 // Seedance reference-video seconds. Not a generation-schema property;
41 // refusing it nulled the whole stored card.
42 'input_video_duration',
43])
44
45/**
46 * What a list row says about a stored card. `null` on the row means no
47 * card; this means there is one. Token cards carry their per-million rates
48 * when those are linear (`tiered` marks a long-prompt re-quote above some
49 * threshold — the rates shown are the base); everything else names the
50 * unit it bills by and points at the full card. `currency` is the
51 * ISO-4217 code the rates are in; rows in different currencies do not
52 * compare.
53 */
54export type CompactPricing = {
55 currency: string
56 per: 'token' | 'second' | 'character' | 'image' | 'request' | 'unit'
57 inputPerMillion?: number
58 outputPerMillion?: number
59 tiered?: true
60}
61
62export function parseStoredRateCard(value: unknown): RateCard | null {
63 const parsed = rateCardSchema.safeParse(value)
64 return parsed.success ? parsed.data : null
65}
66
67function requestParamAllowed(
68 param: string,
69 requestProperties: ReadonlySet<string> | undefined,
70): boolean {
71 if (requestProperties === undefined) return true
72 if (CARD_LEVEL_LEVERS.has(param)) return true
73 if (requestProperties.has(param)) return true
74 const root = param.split('.')[0]
75 return root !== undefined && requestProperties.has(root)
76}
77
78export function cardRequestParamsOk(
79 card: RateCard,
80 requestProperties: ReadonlySet<string> | undefined,
81): boolean {
82 return cardParams(card).request.every((param) =>
83 requestParamAllowed(param, requestProperties),
84 )
85}
86
87function examplesOk(card: RateCard): boolean {
88 return !verifyExamples(card).some((result) => !result.ok)
89}
90
91export interface StoreRateCardOptions {
92 /** Previously stored `models.pricing`, used to keep `source.extractedAt`. */
93 existing?: unknown
94 /**
95 * Top-level properties of the bound input schema. `undefined` skips the
96 * invented-field check (no bound schema). An empty set still refuses
97 * unknown request-bound params.
98 */
99 requestProperties?: ReadonlySet<string>
100 sourceUrl: string
101 /** Poll time, epoch seconds. */
102 now: number
103}
104
105export type RateCardRefuse = 'invented_param' | 'examples' | 'uncompilable'
106
107export type StoredPricing = {
108 card: RateCard | null
109 refused?: RateCardRefuse
110}
111
112/**
113 * Value to write to `models.pricing`. Null means unknown — never a vendor
114 * blob, never an all-zero OpenRouter-shaped listing.
115 */
116/** Every source text a card was read from: its own plus each estimate's. */
117function sourceHashes(card: RateCard): string {
118 return [
119 card.source.hash,
120 ...Object.values(card.inputs).flatMap((input) =>
121 input.kind === 'number' && input.estimate
122 ? [input.estimate.source.hash]
123 : [],
124 ),
125 ].join()
126}
127
128/**
129 * A stored card stands in for a fresh one while all its source text is
130 * unchanged — except past `expiresAt`, the instant the source said the
131 * price changes, where the re-read wins.
132 */
133function reusable(
134 prior: RateCard | null,
135 hashes: string,
136 now: number,
137): prior is RateCard {
138 if (!prior || sourceHashes(prior) !== hashes) return false
139 const expiresAt = prior.source.expiresAt
140 return expiresAt === undefined || Date.parse(expiresAt) > now * 1000
141}
142
143/** Card contents with `extractedAt` removed, so a poll clock is not a rate change. */
144function rateBody(card: RateCard): string {
145 const { extractedAt: _extractedAt, ...source } = card.source
146 return stableStringify({ ...card, source })
147}
148
149export async function storeListedPricing(
150 pricing: unknown,
151 options: StoreRateCardOptions,
152): Promise<StoredPricing> {
153 if (pricing == null) return { card: null }
154
155 const parsed = parseStoredRateCard(pricing)
156 if (parsed) {
157 if (!cardRequestParamsOk(parsed, options.requestProperties)) {
158 return { card: null, refused: 'invented_param' }
159 }
160 if (!examplesOk(parsed)) return { card: null, refused: 'examples' }
161 // Same source text and the same rates: keep the stored card so a fresh
162 // `extractedAt` alone is not a price change on every poll. A parser that
163 // reads different levers from that text replaces the stored card.
164 const prior = parseStoredRateCard(options.existing)
165 const sameRates =
166 reusable(prior, sourceHashes(parsed), options.now) &&
167 rateBody(prior) === rateBody(parsed)
168 return { card: sameRates ? prior : parsed }
169 }
170
171 const existing = parseStoredRateCard(options.existing)
172 const listingHash = await contentHash(pricing)
173 if (reusable(existing, listingHash, options.now)) {
174 if (!cardRequestParamsOk(existing, options.requestProperties)) {
175 return { card: null, refused: 'invented_param' }
176 }
177 return { card: existing }
178 }
179
180 const compiled = compileOpenRouterPricing(pricing, {
181 url: options.sourceUrl,
182 hash: listingHash,
183 extractedAt: new Date(options.now * 1000).toISOString(),
184 })
185 if (!compiled) return { card: null, refused: 'uncompilable' }
186 if (!cardRequestParamsOk(compiled, options.requestProperties)) {
187 return { card: null, refused: 'invented_param' }
188 }
189 return { card: compiled }
190}
191
192export async function toStoredRateCard(
193 pricing: unknown,
194 options: StoreRateCardOptions,
195): Promise<RateCard | null> {
196 return (await storeListedPricing(pricing, options)).card
197}
198
199/**
200 * Drop `factSources.pricing` when the stored card is null. If a card is
201 * stored and pricing provenance is missing, stamp `{ derivation: listing }`.
202 */
203export function reconcilePricingSource(
204 sources: ModelFactSources | null | undefined,
205 card: RateCard | null,
206): ModelFactSources | null {
207 const next: ModelFactSources = { ...(sources ?? {}) }
208 if (card === null) delete next.pricing
209 else if (next.pricing === undefined) next.pricing = { derivation: 'listing' }
210 return emptySources(next) ? null : next
211}
212
213function isTokenCard(card: RateCard): boolean {
214 let hasInput = false
215 for (const input of Object.values(card.inputs)) {
216 if (input.bound !== 'usage' || input.kind !== 'number') return false
217 if (input.param === 'input_tokens') hasInput = true
218 }
219 return hasInput
220}
221
222function tryPrice(
223 card: RateCard,
224 usage: Record<string, number>,
225): number | null {
226 try {
227 return price(card, {}, usage)
228 } catch (error) {
229 if (error instanceof RateCardError) return null
230 throw error
231 }
232}
233
234const LINEAR_REL_TOL = 1e-6
235
236function linear(unitRate: number, count: number, total: number): boolean {
237 return (
238 Math.abs(unitRate * count - total) <=
239 Math.max(1e-9, Math.abs(total) * LINEAR_REL_TOL)
240 )
241}
242
243/**
244 * Per-million rate of one lever, probed below any prompt-size tier
245 * (1 and 1,000 tokens), plus whether a million tokens still price
246 * linearly. Null when a per-request fee or the like breaks linearity.
247 */
248function perMillion(
249 card: RateCard,
250 lever: string,
251 zeros: Record<string, number>,
252): { rate: number; tiered: boolean } | null {
253 const at1 = tryPrice(card, { ...zeros, [lever]: 1 })
254 const at1k = tryPrice(card, { ...zeros, [lever]: 1_000 })
255 const at1m = tryPrice(card, { ...zeros, [lever]: 1_000_000 })
256 if (at1 === null || at1k === null || at1m === null) return null
257 if (!linear(at1, 1_000, at1k)) return null
258 return {
259 // 2e-7 * 1e6 is 0.19999999999999998: drop the float noise, which sits
260 // past any digit a price is published to.
261 rate: Number((at1 * 1_000_000).toPrecision(12)),
262 tiered: !linear(at1, 1_000_000, at1m),
263 }
264}
265
266/** The unit a non-token card's quantity lever counts. */
267const UNIT_OF_LEVER: Record<string, CompactPricing['per']> = {
268 seconds: 'second',
269 audio_seconds: 'second',
270 video_seconds: 'second',
271 duration: 'second',
272 characters: 'character',
273 n: 'image',
274 num_images: 'image',
275 images: 'image',
276}
277
278/**
279 * List-row summary of a card. A token card gets `inputPerMillion` (and
280 * `outputPerMillion` when it prices output) at the base rate, `tiered`
281 * when a long prompt re-quotes the request; a token card whose price is
282 * not linear in either (a per-request fee) gets `per: 'token'` alone.
283 * Other cards name what they bill by, or `unit` when that is not obvious.
284 */
285export function projectTokenPricing(card: RateCard): CompactPricing {
286 const currency = cardCurrency(card)
287 if (!isTokenCard(card)) {
288 const quantity = Object.values(card.inputs).find(
289 (input) => input.kind === 'number',
290 )
291 return {
292 currency,
293 per: quantity ? (UNIT_OF_LEVER[quantity.param] ?? 'unit') : 'request',
294 }
295 }
296 const hasOutput = Object.values(card.inputs).some(
297 (input) => input.param === 'output_tokens',
298 )
299 const zeros: Record<string, number> = hasOutput
300 ? { input_tokens: 0, output_tokens: 0 }
301 : {}
302 const input = perMillion(card, 'input_tokens', zeros)
303 const output = hasOutput ? perMillion(card, 'output_tokens', zeros) : null
304 if (input === null || (hasOutput && output === null)) {
305 return { currency, per: 'token' }
306 }
307 return {
308 currency,
309 per: 'token',
310 inputPerMillion: input.rate,
311 ...(output && { outputPerMillion: output.rate }),
312 ...((input.tiered || output?.tiered) && { tiered: true as const }),
313 }
314}
315
316export function servePricing(
317 value: unknown,
318 mode: 'compact' | 'full',
319): RateCard | CompactPricing | null {
320 const card = parseStoredRateCard(value)
321 if (!card) return null
322 if (mode === 'full') return card
323 return projectTokenPricing(card)
324}