Open History to see the last commit
1/** OpenCode Zen: live ids, routes from OpenCode's models.dev catalog, prices from its console models page. */
2import { openCodeRouteSpec, classifyOpenCodeRoute } from '../opencode-routes.ts'
3import {
4 loadOpenCodeCatalog,
5 OPENCODE_CATALOG_URL,
6 parseOpenCodeCatalog,
7} from '../opencode-catalog.ts'
8import { docsReport, docsRun, tryDocs } from '../model-facts.ts'
9import {
10 loadOpenCodePricing,
11 OPENCODE_PRICING_URL,
12} from '../opencode-pricing.ts'
13import { fetchJson } from '../types.ts'
14import type { RateCard } from '@modelschemas/rate-card'
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/inference/v1/models'
24
25const FETCH_TIMEOUT_MS = 30_000
26
27function isRecord(value: unknown): value is Record<string, unknown> {
28 return typeof value === 'object' && value !== null && !Array.isArray(value)
29}
30
31export function parseOpencodeModels(
32 payload: unknown,
33 tag = 'opencode',
34): Array<ModelInfo> {
35 if (!isRecord(payload) || !Array.isArray(payload.data)) {
36 throw new Error(`${tag}: models payload has no data array`)
37 }
38 const models: Array<ModelInfo> = []
39 for (const row of payload.data) {
40 if (!isRecord(row) || typeof row.id !== 'string' || row.id.length === 0) {
41 continue
42 }
43 models.push({
44 rawId: row.id,
45 releasedAt: null,
46 pricing: null,
47 })
48 }
49 if (models.length === 0) {
50 throw new Error(`${tag}: models payload listed no ids`)
51 }
52 return models
53}
54
55function withSources(
56 listed: Array<ModelInfo>,
57 catalog: Record<string, ModelInfo>,
58 prices: Map<string, RateCard> | null,
59): Array<ModelInfo> {
60 return listed.map((model): ModelInfo => {
61 const facts = catalog[model.rawId]
62 const absent: NonNullable<ModelInfo['absent']> = {
63 ...(facts?.releasedAt == null ? { releasedAt: 'cleared' } : {}),
64 }
65 const out: ModelInfo = { ...model, ...facts }
66 const card = prices?.get(model.rawId)
67 if (!prices) absent.pricing = 'unavailable'
68 // The console page is the only price source: an id it does not price
69 // states no price, so a stored card is cleared.
70 else if (!card) absent.pricing = 'cleared'
71 else {
72 out.pricing = card
73 out.factSources = {
74 ...facts?.factSources,
75 pricing: {
76 derivation: 'docs-derived',
77 sourceUrl: OPENCODE_PRICING_URL,
78 sourceHash: card.source.hash,
79 },
80 }
81 }
82 return Object.keys(absent).length ? { ...out, absent } : out
83 })
84}
85
86async function listModels(
87 _env: ProviderSecrets,
88 kv?: KVNamespace,
89): Promise<ListModelsResult> {
90 const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS)
91 const docs = docsRun()
92 const [payload, loaded, prices] = await Promise.all([
93 fetchJson(OPENCODE_MODELS_URL, { signal }),
94 loadOpenCodeCatalog(kv),
95 tryDocs(docs, OPENCODE_PRICING_URL, (cached) =>
96 loadOpenCodePricing(kv, cached),
97 ),
98 ])
99 const catalog = parseOpenCodeCatalog(loaded.payload, 'opencode', loaded.hash)
100 return {
101 models: withSources(parseOpencodeModels(payload), catalog, prices),
102 docsFailures: docsReport(docs),
103 }
104}
105
106async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
107 const loaded = await loadOpenCodeCatalog()
108 const catalog = parseOpenCodeCatalog(loaded.payload, 'opencode', loaded.hash)
109 return openCodeRouteSpec(
110 Object.values(catalog),
111 { url: OPENCODE_CATALOG_URL, hash: loaded.hash },
112 false,
113 )
114}
115
116// No `upstreamModelIdentity`, here or for OpenCode Go: OpenCode names no
117// maker. `owned_by` is `opencode` on every row, and the catalog's AI SDK
118// package names the wire protocol: `@ai-sdk/anthropic` also serves the Qwen
119// rows, `@ai-sdk/openai` the Grok and Muse Spark rows.
120export const provider: ProviderConfig = {
121 id: 'opencode',
122 displayName: 'OpenCode Zen',
123 specSourceUrl: OPENCODE_CATALOG_URL,
124 modelsEndpoint: OPENCODE_MODELS_URL,
125 defaultDerivation: 'docs-derived',
126 bindSyncedRoutesOnly: true,
127 bindStoredRoutesWithoutSchemas: true,
128 fetchSpec,
129 listModels,
130 classify: classifyOpenCodeRoute,
131}