Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

opencode-pricing.ts

222 lines7.5 KB

1/**
2 * OpenCode Zen prices from OpenCode's own console models page (issue #314).
3 * It is the only Zen price source: models.dev `cost` is not read, and an id
4 * the page does not price states no price.
5 */
6import { compileTokenCard } from '@modelschemas/rate-card'
7import type { RateCard, TokenRateTier } from '@modelschemas/rate-card'
8​
9import { assertParsed, cachedDocs } from './model-facts.ts'
10import { fetchText, sha256Text } from './types.ts'
11​
12/** Source of https://opencode.ai/v2/docs/console/models/; markdown tables parse more stably than the rendered HTML. */
13export const OPENCODE_PRICING_URL =
14 'https://raw.githubusercontent.com/anomalyco/opencode/dev/services/www/src/docs/content/console/models.mdx'
15​
16const PRICE_HEADER = ['Model', 'Input', 'Output', 'Cached Read', 'Cached Write']
17const PRICE_LEVERS = [
18 'input_tokens',
19 'output_tokens',
20 'cache_read_tokens',
21 'cache_write_tokens',
22] as const
23​
24export interface OpenCodePricingDoc {
25 text: string
26 hash: string
27 extractedAt: string
29​
30/** Page rates, USD per 1M tokens, keyed by rate-card lever (`input_tokens`, …). */
31export type OpenCodeCost = Record<string, number>
32​
33function sameKeys(a: object, b: object): boolean {
34 const left = Object.keys(a).sort().join()
35 return left === Object.keys(b).sort().join()
37​
38/**
39 * Page rates (USD per 1M) with an optional context tier → card. Throws on
40 * missing input or output, a tier with other levers, or a zero base with a
41 * tier. An all-zero base with no tier is a sourced free card.
42 */
43export function compileOpenCodeCost(
44 base: OpenCodeCost,
45 tiers: Array<{ minPromptTokens: number; rates: OpenCodeCost }>,
46 id: string,
47 source: RateCard['source'],
48): RateCard {
49 if (base.input_tokens === undefined || base.output_tokens === undefined) {
50 throw new Error(`opencode: price for ${id} omits input or output`)
51 }
52 const perToken = (rates: OpenCodeCost) =>
53 Object.fromEntries(
54 Object.entries(rates).map(([lever, rate]) => [lever, rate / 1e6]),
55 )
56 const tokenTiers: Array<TokenRateTier> = tiers.map((tier) => {
57 if (!sameKeys(base, tier.rates)) {
58 throw new Error(`opencode: price tier for ${id} changes the levers`)
59 }
60 return {
61 minPromptTokens: tier.minPromptTokens,
62 rates: perToken(tier.rates),
63 }
64 })
65 const rates = perToken(base)
66 if (Object.values(rates).every((rate) => rate === 0)) {
67 if (tiers.length > 0) {
68 throw new Error(`opencode: zero base rate with a tier for ${id}`)
69 }
70 return {
71 inputs: Object.fromEntries(
72 Object.keys(rates).map((lever) => [
73 lever,
74 {
75 param: lever,
76 bound: 'usage',
77 kind: 'number',
78 ...(!['input_tokens', 'output_tokens'].includes(lever)
79 ? { default: 0 }
80 : {}),
81 },
82 ]),
83 ),
84 tables: { rate: { base: rates } },
85 price: 0,
86 examples: [],
87 source,
88 }
89 }
90 const card = compileTokenCard(rates, tokenTiers, source)
91 if (!card) throw new Error(`opencode: unreadable price for ${id}`)
92 return card
94​
95/** Cells of the first markdown table under `## <heading>`. */
96function sectionTable(page: string, heading: string): Array<Array<string>> {
97 const text = `\n${page}`
98 const start = text.indexOf(`\n## ${heading}\n`)
99 if (start < 0) throw new Error(`opencode: pricing page has no ${heading}`)
100 const rows: Array<Array<string>> = []
101 for (const line of text
102 .slice(start + 1)
103 .split('\n')
104 .slice(1)) {
105 if (line.startsWith('## ')) break
106 if (!line.startsWith('|')) {
107 if (rows.length > 0) break
108 continue
109 }
110 rows.push(
111 line
112 .trim()
113 .replace(/^\||\|$/g, '')
114 .split('|')
115 .map((cell) => cell.trim()),
116 )
117 }
118 // Header, then the `| --- |` separator.
119 if (rows.length < 3 || !rows[1]!.every((cell) => /^:?-+:?$/.test(cell))) {
120 throw new Error(`opencode: pricing page ${heading} table is unreadable`)
121 }
122 return rows
124​
125/** `Free` → 0, `-` → not billed, `$1.40` → 1.4, `~~$1.36~~ $0.68` → the billed 0.68. */
126function usd(value: string, name: string): number | undefined {
127 if (value === '-') return undefined
128 if (value === 'Free') return 0
129 const match = /^(?:~~\$\d+(?:\.\d+)?~~\s+)?\$(\d+(?:\.\d+)?)$/.exec(value)
130 if (!match) throw new Error(`opencode: unreadable price ${value} for ${name}`)
131 return Number(match[1])
133​
134/** Listed id → card. Joins the Pricing table to the Endpoints table by model name. */
135export function parseOpenCodePricing(
136 doc: OpenCodePricingDoc,
137): Map<string, RateCard> {
138 const endpoints = sectionTable(doc.text, 'Endpoints')
139 if (endpoints[0]![0] !== 'Model' || endpoints[0]![1] !== 'Model ID') {
140 throw new Error('opencode: pricing page Endpoints header changed')
141 }
142 const idByName = new Map<string, string>()
143 for (const [name, id] of endpoints.slice(2)) {
144 if (!name || !id || idByName.has(name)) {
145 throw new Error(`opencode: unreadable endpoint row ${name}`)
146 }
147 idByName.set(name, id)
148 }
149​
150 const priced = sectionTable(doc.text, 'Pricing')
151 if (priced[0]!.join('|') !== PRICE_HEADER.join('|')) {
152 throw new Error('opencode: pricing page Pricing header changed')
153 }
154 const rows = new Map<
155 string,
156 { base?: OpenCodeCost; over?: OpenCodeCost; upTo?: number; from?: number }
157 >()
158 for (const [label, ...cells] of priced.slice(2)) {
159 if (!label || cells.length !== PRICE_LEVERS.length) {
160 throw new Error(`opencode: unreadable price row ${label}`)
161 }
162 // `(50% off)` names a discount; the cell already shows the billed price.
163 const plain = label.replace(/\s*\(\d+% off\)$/, '')
164 const tier = /^(.*?)\s*\((≤|>) (\d+)K tokens\)$/.exec(plain)
165 const name = tier ? tier[1]! : plain
166 const rates: OpenCodeCost = {}
167 PRICE_LEVERS.forEach((lever, i) => {
168 const value = usd(cells[i]!, label)
169 if (value !== undefined) rates[lever] = value
170 })
171 const row = rows.get(name) ?? {}
172 const slot = !tier || tier[2] === '≤' ? 'base' : 'over'
173 if (row[slot]) throw new Error(`opencode: duplicate price row ${label}`)
174 row[slot] = rates
175 if (tier) row[tier[2] === '≤' ? 'upTo' : 'from'] = Number(tier[3]) * 1000
176 rows.set(name, row)
177 }
178​
179 const source = {
180 url: OPENCODE_PRICING_URL,
181 hash: doc.hash,
182 extractedAt: doc.extractedAt,
183 }
184 const cards = new Map<string, RateCard>()
185 for (const [name, row] of rows) {
186 const id = idByName.get(name)
187 if (!id) throw new Error(`opencode: price row ${name} names no model id`)
188 if (!row.base || row.upTo !== row.from) {
189 throw new Error(`opencode: unreadable context tiers for ${name}`)
190 }
191 const tiers = row.over
192 ? [{ minPromptTokens: row.from!, rates: row.over }]
193 : []
194 cards.set(id, compileOpenCodeCost(row.base, tiers, id, source))
195 }
196 // The Endpoints table names the model set. A price table that ends early
197 // (a blank line, a split table) would otherwise clear the rows after it.
198 for (const name of idByName.keys()) {
199 if (!rows.has(name)) {
200 throw new Error(`opencode: ${name} has an endpoint but no price row`)
201 }
202 }
203 assertParsed(cards, 'opencode-pricing')
204 return cards
206​
207export async function loadOpenCodePricing(
208 kv: KVNamespace | undefined,
209 cached: typeof cachedDocs = cachedDocs,
210): Promise<Map<string, RateCard>> {
211 const doc = await cached(kv, OPENCODE_PRICING_URL, async () => {
212 const text = await fetchText(OPENCODE_PRICING_URL, {
213 signal: AbortSignal.timeout(30_000),
214 })
215 return {
216 text,
217 hash: await sha256Text(text),
218 extractedAt: new Date().toISOString(),
219 }
220 })
221 return parseOpenCodePricing(doc)