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

opencode.ts

364 lines11.7 KB

1import { openCodeRouteSpec, classifyOpenCodeRoute } from '../opencode-routes.ts'
2/** OpenCode Zen: live ids, first-party catalog facts, and documented routes/prices. */
3import { compileTokenCard } from '@modelschemas/rate-card'
4import type { RateCard, TokenRateTier } from '@modelschemas/rate-card'
5​
6import type { Activity } from '#/db/schema.ts'
7​
8import {
9 cachedDocs,
10 markdownSection,
11 markdownTableRows,
12} from '../model-facts.ts'
13import { openCodeCatalog } from '../opencode-catalog.ts'
14import { fetchJson, fetchText, sha256Text } from '../types.ts'
15import type {
16 ListModelsResult,
17 ModelInfo,
18 ProviderConfig,
19 ProviderSecrets,
20 SpecFetchResult,
21} from '../types.ts'
22​
23export const OPENCODE_MODELS_URL = 'https://opencode.ai/zen/v1/models'
24​
25/** Page readers see; the facts are parsed from its markdown twin. */
26export const OPENCODE_DOCS_URL = 'https://opencode.ai/docs/zen'
27​
28export const OPENCODE_DOCS_MARKDOWN = `${OPENCODE_DOCS_URL}.md`
29​
30const FETCH_TIMEOUT_MS = 30_000
31​
32const ENDPOINT_HEADER = ['Model', 'Model ID', 'Endpoint', 'AI SDK Package']
33const PRICING_HEADER = [
34 'Model',
35 'Input',
36 'Output',
37 'Cached Read',
38 'Cached Write',
40const PRICE_LEVERS = [
41 'input_tokens',
42 'output_tokens',
43 'cache_read_tokens',
44 'cache_write_tokens',
46​
47/** Routes that take a text-generation request. Any other route is unclassified. */
48const CHAT_ROUTES = new Set([
49 'v1/responses',
50 'v1/messages',
51 'v1/chat/completions',
52])
53​
54interface Rates {
55 base: Record<string, number>
56 tiers: Array<TokenRateTier>
58​
59export interface ZenDocsModel {
60 displayName: string
61 activity: Activity | null
62 schemaEndpointId: string | null
63 /** Null when the Pricing table does not quote this model. */
64 rates: Rates | null
66​
67function isRecord(value: unknown): value is Record<string, unknown> {
68 return typeof value === 'object' && value !== null && !Array.isArray(value)
70​
71function sameCells(row: Array<string> | undefined, header: Array<string>) {
72 return row?.length === header.length && row.every((c, i) => c === header[i])
74​
75/** `$1.25` → USD per token, `Free` → 0, `-` → null (not quoted), else undefined. */
76function rateCell(cell: string): number | null | undefined {
77 if (cell === '-') return null
78 if (cell === 'Free') return 0
79 const match = cell.match(/^(?:~~\$\d+(?:\.\d+)?~~ )?\$(\d+(?:\.\d+)?)$/)
80 return match?.[1] ? Number(match[1]) / 1e6 : undefined
82​
83/**
84 * Pricing table → rates by model name. `Name (≤ 200K tokens)` is the base
85 * row and `Name (> 200K tokens)` its tier. A name with a cell or a
86 * qualifier pairing this does not recognise throws.
87 */
88function parsePricing(markdown: string): Map<string, Rates | null> {
89 const section = markdownSection(markdown, 'Pricing').split('\n### ')[0] ?? ''
90 const rows = markdownTableRows(section)
91 if (
92 !section.includes('per 1M tokens') ||
93 !sameCells(rows[0], PRICING_HEADER)
94 ) {
95 throw new Error('opencode: docs Pricing table is not per-1M-token rates')
96 }
97 type Slot = { rates: Record<string, number>; at: number | null }
98 const slots = new Map<string, { base?: Slot; tier?: Slot; bad?: true }>()
99 for (const row of rows.slice(1)) {
100 const nameCell = row[0]?.replace(/ \(\d+(?:\.\d+)?% off\)$/, '')
101 const match = nameCell?.match(/^(.+?)(?: \((≤|>) (\d+)K tokens\))?$/)
102 const name = match?.[1]
103 if (!match || !name) continue
104 const entry = slots.get(name) ?? {}
105 slots.set(name, entry)
106 const rates: Record<string, number> = {}
107 const cells = row.slice(1).map(rateCell)
108 if (row.length !== PRICING_HEADER.length || cells.includes(undefined)) {
109 entry.bad = true
110 continue
111 }
112 cells.forEach((value, index) => {
113 const lever = PRICE_LEVERS[index]
114 if (lever && typeof value === 'number') rates[lever] = value
115 })
116 const slot = match[2] === '>' ? 'tier' : 'base'
117 if (entry[slot]) entry.bad = true
118 entry[slot] = { rates, at: match[3] ? Number(match[3]) * 1000 : null }
119 }
120 const out = new Map<string, Rates | null>()
121 for (const [name, { base, tier, bad }] of slots) {
122 // A tier row needs its `≤` base row at the same threshold, and back.
123 // It must also quote every rate the base does: the compiled tier fills
124 // a missing lever from the base, which would invent a tier price.
125 const unquoted =
126 base && tier && Object.keys(base.rates).some((k) => !(k in tier.rates))
127 if (bad || !base || unquoted || (tier?.at ?? null) !== base.at) {
128 throw new Error(`opencode: unreadable Pricing row or tier for ${name}`)
129 }
130 out.set(name, {
131 base: base.rates,
132 tiers:
133 tier?.at != null
134 ? // The page says only `(> 272K tokens)`, not what is counted. The
135 // card counts prompt tokens: input plus cache read and write.
136 [{ minPromptTokens: tier.at, rates: tier.rates }]
137 : [],
138 })
139 }
140 return out
142​
143export interface DocsEndpointRow {
144 id: string
145 displayName: string
146 activity: Activity | null
147 schemaEndpointId: string | null
149​
150/**
151 * Rows of a docs page's Endpoints table. `tag` prefixes the errors and
152 * every route cell must sit under `routeBase`. Shared with the OpenCode Go
153 * page, whose table has the same shape.
154 */
155export function parseDocsEndpoints(
156 markdown: string,
157 tag: string,
158 routeBase: string,
159): Array<DocsEndpointRow> {
160 // A 200 that is an HTML error page must not be read as the document.
161 if (/^\s*<(?:!doctype|html)/i.test(markdown)) {
162 throw new Error(`${tag}: docs page returned HTML, not markdown`)
163 }
164 const rows = markdownTableRows(markdownSection(markdown, 'Endpoints'))
165 if (!sameCells(rows[0], ENDPOINT_HEADER)) {
166 throw new Error(`${tag}: docs Endpoints table not found`)
167 }
168 const seen = new Set<string>()
169 return rows.slice(1).map((row) => {
170 const [name, id, endpointCell, packageCell] = row
171 const url = endpointCell?.match(/^`([^`\s]+)`$/)?.[1]
172 const endpoint = url?.startsWith(`${routeBase}v1/`)
173 ? url.slice(routeBase.length)
174 : undefined
175 if (row.length !== ENDPOINT_HEADER.length || !name || !id || !endpoint) {
176 throw new Error(`${tag}: unreadable Endpoints row: ${row.join(' | ')}`)
177 }
178 if (seen.has(id)) throw new Error(`${tag}: duplicate model id ${id}`)
179 seen.add(id)
180 return {
181 id,
182 displayName: name,
183 schemaEndpointId:
184 (endpoint === 'v1/messages' && packageCell === '`@ai-sdk/anthropic`') ||
185 (endpoint === 'v1/responses' && packageCell === '`@ai-sdk/openai`') ||
186 (endpoint === `v1/models/${id}` &&
187 packageCell === '`@ai-sdk/google`') ||
188 (endpoint === 'v1/chat/completions' &&
189 packageCell === '`@ai-sdk/openai-compatible`')
190 ? endpoint
191 : null,
192 // Gemini models are served at `v1/models/<id>`.
193 activity:
194 CHAT_ROUTES.has(endpoint) || endpoint === `v1/models/${id}`
195 ? 'chat'
196 : null,
197 }
198 })
200​
201/** Endpoints and Pricing tables of the Zen docs page, keyed by model id. */
202export function parseZenDocs(markdown: string): Record<string, ZenDocsModel> {
203 const rows = parseDocsEndpoints(
204 markdown,
205 'opencode',
206 'https://opencode.ai/zen/',
207 )
208 const prices = parsePricing(markdown)
209 const byId: Record<string, ZenDocsModel> = {}
210 let priced = 0
211 for (const { id, displayName, activity, schemaEndpointId } of rows) {
212 const rates = prices.get(displayName) ?? null
213 if (rates) priced += 1
214 byId[id] = { displayName, activity, schemaEndpointId, rates }
215 }
216 if (priced === 0) throw new Error('opencode: docs priced 0 model rows')
217 return byId
219​
220export function parseOpencodeModels(payload: unknown): Array<ModelInfo> {
221 if (!isRecord(payload) || !Array.isArray(payload.data)) {
222 throw new Error('opencode: models payload has no data array')
223 }
224 const models: Array<ModelInfo> = []
225 for (const row of payload.data) {
226 if (!isRecord(row) || typeof row.id !== 'string' || row.id.length === 0) {
227 continue
228 }
229 models.push({
230 rawId: row.id,
231 releasedAt: null,
232 pricing: null,
233 })
234 }
235 if (models.length === 0) {
236 throw new Error('opencode: models payload listed no ids')
237 }
238 return models
240​
241/** Literal native Free quotes are a sourced zero, not an unknown rate sheet. */
242function zenPrice(rates: Rates, source: RateCard['source']): RateCard | null {
243 if (
244 rates.tiers.length === 0 &&
245 rates.base.input_tokens === 0 &&
246 rates.base.output_tokens === 0 &&
247 Object.values(rates.base).every((rate) => rate === 0)
248 ) {
249 return {
250 inputs: Object.fromEntries(
251 Object.keys(rates.base).map((lever) => [
252 lever,
253 {
254 param: lever,
255 bound: 'usage',
256 kind: 'number',
257 ...(!['input_tokens', 'output_tokens'].includes(lever)
258 ? { default: 0 }
259 : {}),
260 },
261 ]),
262 ),
263 tables: { rate: { base: rates.base } },
264 price: 0,
265 examples: [],
266 source,
267 }
268 }
269 return compileTokenCard(rates.base, rates.tiers, source)
271​
272async function listModels(
273 _env: ProviderSecrets,
274 kv?: KVNamespace,
275): Promise<ListModelsResult> {
276 const signal = () => AbortSignal.timeout(FETCH_TIMEOUT_MS)
277 const payload = await fetchJson(OPENCODE_MODELS_URL, { signal: signal() })
278 const docs = await cachedDocs(kv, OPENCODE_DOCS_MARKDOWN, async () => {
279 const markdown = await fetchText(OPENCODE_DOCS_MARKDOWN, {
280 signal: signal(),
281 })
282 return {
283 byId: parseZenDocs(markdown),
284 hash: await sha256Text(markdown),
285 extractedAt: new Date().toISOString(),
286 }
287 })
288 const catalog = await openCodeCatalog('opencode', kv)
289 const source = {
290 url: OPENCODE_DOCS_URL,
291 hash: docs.hash,
292 extractedAt: docs.extractedAt,
293 }
294 const models = parseOpencodeModels(payload).map((model): ModelInfo => {
295 const row = docs.byId[model.rawId]
296 const facts = catalog[model.rawId]
297 const enriched: ModelInfo = {
298 ...model,
299 ...facts,
300 ...(facts?.releasedAt == null
301 ? { absent: { releasedAt: 'cleared' } }
302 : {}),
303 }
304 if (!row) return enriched
305 const pricing = row.rates ? zenPrice(row.rates, source) : null
306 return {
307 ...enriched,
308 schemaEndpointId: row.schemaEndpointId,
309 displayName: row.displayName,
310 activity: row.activity,
311 pricing,
312 factSources: {
313 ...facts?.factSources,
314 ...(row.schemaEndpointId
315 ? {
316 schemaEndpointId: {
317 derivation: 'docs-derived',
318 sourceUrl: OPENCODE_DOCS_URL,
319 sourceHash: docs.hash,
320 path: 'Endpoints',
321 },
322 }
323 : {}),
324 ...(pricing
325 ? {
326 pricing: {
327 derivation: 'docs-derived',
328 sourceUrl: OPENCODE_DOCS_URL,
329 sourceHash: docs.hash,
330 path: 'Pricing',
331 },
332 }
333 : {}),
334 },
335 }
336 })
337 return { models }
339​
340async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
341 const text = await fetchText(OPENCODE_DOCS_MARKDOWN, {
342 signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
343 })
344 const rows = parseDocsEndpoints(text, 'opencode', 'https://opencode.ai/zen/')
345 return openCodeRouteSpec(rows, { url: OPENCODE_DOCS_MARKDOWN, text }, false)
347​
348// No `upstreamModelIdentity`, here or for OpenCode Go: OpenCode names no
349// maker. `owned_by` is `opencode` on every row, and the Endpoints table's
350// AI SDK package names the wire protocol: `@ai-sdk/anthropic` also serves
351// the Qwen and (on Go) MiniMax rows, `@ai-sdk/openai` the Grok and Muse
352// Spark rows.
353export const provider: ProviderConfig = {
354 id: 'opencode',
355 displayName: 'OpenCode Zen',
356 specSourceUrl: OPENCODE_DOCS_URL,
357 modelsEndpoint: OPENCODE_MODELS_URL,
358 defaultDerivation: 'docs-derived',
359 bindSyncedRoutesOnly: true,
360 bindStoredRoutesWithoutSchemas: true,
361 fetchSpec,
362 listModels,
363 classify: classifyOpenCodeRoute,