Open History to see the last commit
1/**
2 * OpenCode Zen prices from OpenCode's own console models page (issue #314).
3 * Token rows are the Pricing table. Image models are the Image pricing
4 * table (issue #100007). It is the only Zen price source: models.dev
5 * `cost` is not read, and an id the page does not price states no price.
6 */
7import { compileTokenCard } from '@modelschemas/rate-card'
8import type { RateCard, TokenRateTier } from '@modelschemas/rate-card'
9
10import { assertParsed, cachedDocs } from './model-facts.ts'
11import { fetchText, sha256Text } from './types.ts'
12
13/** Source of https://opencode.ai/docs/console/models/; markdown tables parse more stably than the rendered HTML. */
14export const OPENCODE_PRICING_URL =
15 'https://raw.githubusercontent.com/anomalyco/opencode/dev/services/site/src/docs/content/console/models.mdx'
16
17const PRICE_HEADER = ['Model', 'Input', 'Output', 'Cached Read', 'Cached Write']
18const IMAGE_HEADER = ['Model', 'Price', 'Notes']
19const PRICE_LEVERS = [
20 'input_tokens',
21 'output_tokens',
22 'cache_read_tokens',
23 'cache_write_tokens',
24] as const
25
26/** `$1.00 / image` plus token add-ons, as the Image pricing notes state them. */
27const PER_IMAGE = /^\$(\d+(?:\.\d+)?) \/ image$/
28const IMAGE_TOKEN_NOTES =
29 /^Plus \$(\d+(?:\.\d+)?) \/ \$(\d+(?:\.\d+)?) per 1M input \/ output tokens, and \$(\d+(?:\.\d+)?) per 1M cached input tokens\.$/
30/** Input / text output / image output. An "About …" clause is an approximation, not a rate. */
31const TOKEN_TRIPLE =
32 /^\$(\d+(?:\.\d+)?) \/ \$(\d+(?:\.\d+)?) \/ \$(\d+(?:\.\d+)?) per 1M tokens$/
33const TOKEN_TRIPLE_NOTES =
34 /^Input \/ text output \/ image output\.(?: About \$\d+(?:\.\d+)? per 1K image, \$\d+(?:\.\d+)? per 2K, \$\d+(?:\.\d+)? per 4K\.)?$/
35/**
36 * A floor per image, a per-input-image fee, and a higher output band with
37 * no quality or resolution rule. That row is unverified: no card.
38 */
39const UNRULED_BAND_NOTES =
40 /^\$(\d+(?:\.\d+)?) per input image; quality and resolution can raise the output price to \$(\d+(?:\.\d+)?)(?:–|-)\$(\d+(?:\.\d+)?)\.$/
41
42export interface OpenCodePricingDoc {
43 text: string
44 hash: string
45 extractedAt: string
46}
47
48/** Page rates, USD per 1M tokens, keyed by rate-card lever (`input_tokens`, …). */
49export type OpenCodeCost = Record<string, number>
50
51function sameKeys(a: object, b: object): boolean {
52 const left = Object.keys(a).sort().join()
53 return left === Object.keys(b).sort().join()
54}
55
56/**
57 * Page rates (USD per 1M) with an optional context tier → card. Throws on
58 * missing input or output, a tier with other levers, or a zero base with a
59 * tier. An all-zero base with no tier is a sourced free card.
60 */
61export function compileOpenCodeCost(
62 base: OpenCodeCost,
63 tiers: Array<{ minPromptTokens: number; rates: OpenCodeCost }>,
64 id: string,
65 source: RateCard['source'],
66): RateCard {
67 if (base.input_tokens === undefined || base.output_tokens === undefined) {
68 throw new Error(`opencode: price for ${id} omits input or output`)
69 }
70 const perToken = (rates: OpenCodeCost) =>
71 Object.fromEntries(
72 Object.entries(rates).map(([lever, rate]) => [lever, rate / 1e6]),
73 )
74 const tokenTiers: Array<TokenRateTier> = tiers.map((tier) => {
75 if (!sameKeys(base, tier.rates)) {
76 throw new Error(`opencode: price tier for ${id} changes the levers`)
77 }
78 return {
79 minPromptTokens: tier.minPromptTokens,
80 rates: perToken(tier.rates),
81 }
82 })
83 const rates = perToken(base)
84 if (Object.values(rates).every((rate) => rate === 0)) {
85 if (tiers.length > 0) {
86 throw new Error(`opencode: zero base rate with a tier for ${id}`)
87 }
88 return {
89 inputs: Object.fromEntries(
90 Object.keys(rates).map((lever) => [
91 lever,
92 {
93 param: lever,
94 bound: 'usage',
95 kind: 'number',
96 ...(!['input_tokens', 'output_tokens'].includes(lever)
97 ? { default: 0 }
98 : {}),
99 },
100 ]),
101 ),
102 tables: { rate: { base: rates } },
103 price: 0,
104 examples: [],
105 source,
106 }
107 }
108 const card = compileTokenCard(rates, tokenTiers, source)
109 if (!card) throw new Error(`opencode: unreadable price for ${id}`)
110 return card
111}
112
113/** `$ per image` added to a token card. The count has no default: 1 would be a guess. */
114function addPerImage(card: RateCard, usdEach: number): RateCard {
115 const tokenPrice = card.price
116 if (typeof tokenPrice !== 'object' || 'currency' in tokenPrice) {
117 throw new Error('opencode: image prices are USD')
118 }
119 return {
120 ...card,
121 inputs: {
122 num_images: { param: 'num_images', bound: 'usage', kind: 'number' },
123 ...card.inputs,
124 },
125 price: { '+': [{ '*': [{ var: 'num_images' }, usdEach] }, tokenPrice] },
126 }
127}
128
129function imageRowUnreadable(name: string): Error {
130 return new Error(`opencode: unreadable image price row ${name}`)
131}
132
133/**
134 * One Image pricing row. A shape this does not recognise throws.
135 * `'unverified'` is an explicit absence: the row was read, and no card
136 * is stored because a price would be a fallback.
137 */
138function compileImagePrice(
139 name: string,
140 priceCell: string,
141 notes: string,
142 source: RateCard['source'],
143): RateCard | 'unverified' {
144 const triple = TOKEN_TRIPLE.exec(priceCell)
145 if (triple) {
146 if (!TOKEN_TRIPLE_NOTES.test(notes)) throw imageRowUnreadable(name)
147 return compileOpenCodeCost(
148 {
149 input_tokens: Number(triple[1]),
150 output_tokens: Number(triple[2]),
151 image_output_tokens: Number(triple[3]),
152 },
153 [],
154 name,
155 source,
156 )
157 }
158 const each = PER_IMAGE.exec(priceCell)
159 if (!each) throw imageRowUnreadable(name)
160 const withTokens = IMAGE_TOKEN_NOTES.exec(notes)
161 if (withTokens) {
162 return addPerImage(
163 compileOpenCodeCost(
164 {
165 input_tokens: Number(withTokens[1]),
166 output_tokens: Number(withTokens[2]),
167 cache_read_tokens: Number(withTokens[3]),
168 },
169 [],
170 name,
171 source,
172 ),
173 Number(each[1]),
174 )
175 }
176 const unruled = UNRULED_BAND_NOTES.exec(notes)
177 if (!unruled) throw imageRowUnreadable(name)
178 const low = Number(unruled[2])
179 const high = Number(unruled[3])
180 if (!(low < high)) throw imageRowUnreadable(name)
181 // The floor and the per-input-image fee are stated, and so is a higher
182 // output band. Nothing maps quality or resolution onto that band, so a
183 // card at $0.04 would bill every request at a price the page says can
184 // be higher. Same outcome as a FAL extract that returns unverified.
185 return 'unverified'
186}
187
188/** Cells of the first markdown table under `##` or `### <heading>`. `###` may be absent. */
189function sectionTable(
190 page: string,
191 heading: string,
192 level?: 2,
193): Array<Array<string>>
194function sectionTable(
195 page: string,
196 heading: string,
197 level: 3,
198): Array<Array<string>> | null
199function sectionTable(
200 page: string,
201 heading: string,
202 level: 2 | 3 = 2,
203): Array<Array<string>> | null {
204 const text = `\n${page}`
205 const start = text.indexOf(`\n${'#'.repeat(level)} ${heading}\n`)
206 if (start < 0) {
207 if (level === 3) return null
208 throw new Error(`opencode: pricing page has no ${heading}`)
209 }
210 const rows: Array<Array<string>> = []
211 for (const line of text
212 .slice(start + 1)
213 .split('\n')
214 .slice(1)) {
215 if (line.startsWith('## ')) break
216 if (!line.startsWith('|')) {
217 if (rows.length > 0) break
218 continue
219 }
220 rows.push(
221 line
222 .trim()
223 .replace(/^\||\|$/g, '')
224 .split('|')
225 .map((cell) => cell.trim()),
226 )
227 }
228 // Header, then the `| --- |` separator.
229 if (rows.length < 3 || !rows[1]!.every((cell) => /^:?-+:?$/.test(cell))) {
230 throw new Error(`opencode: pricing page ${heading} table is unreadable`)
231 }
232 return rows
233}
234
235/** `Free` → 0, `-` → not billed, `$1.40` → 1.4, `~~$1.36~~ $0.68` → the billed 0.68. */
236function usd(value: string, name: string): number | undefined {
237 if (value === '-') return undefined
238 if (value === 'Free') return 0
239 const match = /^(?:~~\$\d+(?:\.\d+)?~~\s+)?\$(\d+(?:\.\d+)?)$/.exec(value)
240 if (!match) throw new Error(`opencode: unreadable price ${value} for ${name}`)
241 return Number(match[1])
242}
243
244/** Listed id → card. Joins Pricing and Image pricing to the Endpoints table by model name. */
245export function parseOpenCodePricing(
246 doc: OpenCodePricingDoc,
247): Map<string, RateCard> {
248 const endpoints = sectionTable(doc.text, 'Endpoints')
249 if (endpoints[0]![0] !== 'Model' || endpoints[0]![1] !== 'Model ID') {
250 throw new Error('opencode: pricing page Endpoints header changed')
251 }
252 const idByName = new Map<string, string>()
253 for (const [name, id] of endpoints.slice(2)) {
254 if (!name || !id || idByName.has(name)) {
255 throw new Error(`opencode: unreadable endpoint row ${name}`)
256 }
257 idByName.set(name, id)
258 }
259
260 const priced = sectionTable(doc.text, 'Pricing')
261 if (priced[0]!.join('|') !== PRICE_HEADER.join('|')) {
262 throw new Error('opencode: pricing page Pricing header changed')
263 }
264 const rows = new Map<
265 string,
266 { base?: OpenCodeCost; over?: OpenCodeCost; upTo?: number; from?: number }
267 >()
268 for (const [label, ...cells] of priced.slice(2)) {
269 if (!label || cells.length !== PRICE_LEVERS.length) {
270 throw new Error(`opencode: unreadable price row ${label}`)
271 }
272 // `(50% off)` names a discount; the cell already shows the billed price.
273 const plain = label.replace(/\s*\(\d+% off\)$/, '')
274 const tier = /^(.*?)\s*\((≤|>) (\d+)K tokens\)$/.exec(plain)
275 const name = tier ? tier[1]! : plain
276 const rates: OpenCodeCost = {}
277 PRICE_LEVERS.forEach((lever, i) => {
278 const value = usd(cells[i]!, label)
279 if (value !== undefined) rates[lever] = value
280 })
281 const row = rows.get(name) ?? {}
282 const slot = !tier || tier[2] === '≤' ? 'base' : 'over'
283 if (row[slot]) throw new Error(`opencode: duplicate price row ${label}`)
284 row[slot] = rates
285 if (tier) row[tier[2] === '≤' ? 'upTo' : 'from'] = Number(tier[3]) * 1000
286 rows.set(name, row)
287 }
288
289 const imageTable = sectionTable(doc.text, 'Image pricing', 3)
290 const imageRows = new Map<string, { price: string; notes: string }>()
291 if (imageTable) {
292 if (imageTable[0]!.join('|') !== IMAGE_HEADER.join('|')) {
293 throw new Error('opencode: pricing page Image pricing header changed')
294 }
295 for (const [name, price, notes, ...rest] of imageTable.slice(2)) {
296 if (
297 !name ||
298 price === undefined ||
299 notes === undefined ||
300 rest.length > 0
301 ) {
302 throw new Error(`opencode: unreadable image price row ${name ?? ''}`)
303 }
304 if (imageRows.has(name)) {
305 throw new Error(`opencode: duplicate image price row ${name}`)
306 }
307 imageRows.set(name, { price, notes })
308 }
309 }
310
311 const source = {
312 url: OPENCODE_PRICING_URL,
313 hash: doc.hash,
314 extractedAt: doc.extractedAt,
315 }
316 const cards = new Map<string, RateCard>()
317 for (const [name, row] of rows) {
318 if (imageRows.has(name)) {
319 throw new Error(`opencode: ${name} is priced twice`)
320 }
321 const id = idByName.get(name)
322 if (!id) throw new Error(`opencode: price row ${name} names no model id`)
323 if (!row.base || row.upTo !== row.from) {
324 throw new Error(`opencode: unreadable context tiers for ${name}`)
325 }
326 const tiers = row.over
327 ? [{ minPromptTokens: row.from!, rates: row.over }]
328 : []
329 cards.set(id, compileOpenCodeCost(row.base, tiers, id, source))
330 }
331 const imagePriced = new Set<string>()
332 const unverified = new Set<string>()
333 for (const [name, cells] of imageRows) {
334 const id = idByName.get(name)
335 if (!id) throw new Error(`opencode: price row ${name} names no model id`)
336 const card = compileImagePrice(name, cells.price, cells.notes, source)
337 if (card === 'unverified') unverified.add(name)
338 else {
339 imagePriced.add(name)
340 cards.set(id, card)
341 }
342 }
343 // The Endpoints table names the model set. A price table that ends early
344 // (a blank line, a split table) would otherwise clear the rows after it.
345 // An image model is priced in Image pricing, not in the token table.
346 // An unverified image row is an explicit absence, not a missing row.
347 for (const name of idByName.keys()) {
348 if (!rows.has(name) && !imagePriced.has(name) && !unverified.has(name)) {
349 throw new Error(`opencode: ${name} has an endpoint but no price row`)
350 }
351 }
352 assertParsed(cards, 'opencode-pricing')
353 return cards
354}
355
356export async function loadOpenCodePricing(
357 kv: KVNamespace | undefined,
358 cached: typeof cachedDocs = cachedDocs,
359): Promise<Map<string, RateCard>> {
360 const doc = await cached(kv, OPENCODE_PRICING_URL, async () => {
361 const text = await fetchText(OPENCODE_PRICING_URL, {
362 signal: AbortSignal.timeout(30_000),
363 })
364 return {
365 text,
366 hash: await sha256Text(text),
367 extractedAt: new Date().toISOString(),
368 }
369 })
370 return parseOpenCodePricing(doc)
371}