Open History to see the last commit
1/** OpenCode owns models.dev. Only its two providers may read these facts. */
2import { cachedDocs } from './model-facts.ts'
3import type { ChatRequestMap } from './request-map.ts'
4import { fetchText, sha256Text } from './types.ts'
5import type {
6 FactSource,
7 ModelFactSources,
8 ModelInfo,
9 ModelReasoning,
10} from './types.ts'
11
12export const OPENCODE_CATALOG_URL = 'https://models.dev/api.json'
13type OpenCodeProvider = 'opencode' | 'opencode-go'
14
15/** Path under the provider api. A package this map does not name has no route. */
16const PACKAGE_SUFFIX: Record<string, (id: string) => string> = {
17 '@ai-sdk/anthropic': () => 'messages',
18 '@ai-sdk/openai': () => 'responses',
19 // The action is part of the path: .../models/<id>:generateContent
20 '@ai-sdk/google': (id) => `models/${id}:generateContent`,
21 '@ai-sdk/openai-compatible': () => 'chat/completions',
22}
23
24export interface OpenCodeCatalogLoad {
25 payload: unknown
26 hash: string
27}
28
29function record(value: unknown): value is Record<string, unknown> {
30 return value !== null && typeof value === 'object' && !Array.isArray(value)
31}
32function strings(value: unknown): value is Array<string> {
33 return Array.isArray(value) && value.every((v) => typeof v === 'string')
34}
35function reasoning(value: unknown): ModelReasoning | null {
36 if (value === undefined) return null
37 if (!Array.isArray(value))
38 throw new Error('opencode: unreadable reasoning_options')
39 const options = value.map((option: unknown) => {
40 if (
41 !record(option) ||
42 !['toggle', 'effort', 'budget_tokens'].includes(String(option.type))
43 ) {
44 throw new Error('opencode: unreadable reasoning option')
45 }
46 if (
47 option.type === 'effort' &&
48 (!strings(option.values) || option.values.length === 0)
49 ) {
50 throw new Error('opencode: unreadable effort values')
51 }
52 return option
53 })
54 const toggle = options.some((option) => option.type === 'toggle')
55 const effort = options.find((option) => option.type === 'effort')
56 if (effort && strings(effort.values))
57 return {
58 mode: 'effort',
59 efforts: effort.values,
60 mandatory:
61 toggle ||
62 effort.values.some((v) => ['none', 'off', 'disabled'].includes(v))
63 ? false
64 : null,
65 }
66 if (options.some((option) => option.type === 'budget_tokens'))
67 return { mode: 'budget', mandatory: toggle ? false : null }
68 return toggle ? { mode: 'toggle', mandatory: false } : null
69}
70
71/** The base path under opencode.ai, from a provider or model `api`. */
72function openCodeApiPath(
73 provider: OpenCodeProvider,
74 api: string,
75 field: string,
76): string {
77 const url = URL.parse(api)
78 const path = url?.pathname.replace(/^\//, '').replace(/\/$/, '') ?? ''
79 if (url?.origin !== 'https://opencode.ai' || path.length === 0) {
80 throw new Error(
81 `${provider}: models.dev ${field} is not an opencode.ai path`,
82 )
83 }
84 return path
85}
86
87/** The passed api path (model, else provider) plus the package suffix. */
88function schemaEndpointId(
89 provider: OpenCodeProvider,
90 apiPath: string,
91 npm: string,
92 id: string,
93): string | null {
94 const suffix = PACKAGE_SUFFIX[npm]?.(id) ?? null
95 if (!suffix) return null
96 // go.mdx lists Go Gemini as `.../v1beta/models/<id>` with no method, and no
97 // Go page states the `:generateContent` route, so Go Gemini binds none.
98 if (provider === 'opencode-go' && npm === '@ai-sdk/google') return null
99 if (id.includes('/'))
100 throw new Error(`${provider}: unreadable model id ${id}`)
101 return `${apiPath}/${suffix}`
102}
103
104export function parseOpenCodeCatalog(
105 payload: unknown,
106 provider: OpenCodeProvider,
107 hash: string,
108): Record<string, ModelInfo> {
109 if (!record(payload) || !record(payload[provider])) {
110 throw new Error(`${provider}: models.dev has no provider models object`)
111 }
112 const block = payload[provider]
113 const models = block.models
114 if (!record(models)) {
115 throw new Error(`${provider}: models.dev has no provider models object`)
116 }
117 if (typeof block.npm !== 'string' || block.npm.length === 0) {
118 throw new Error(`${provider}: models.dev provider npm is missing`)
119 }
120 if (typeof block.api !== 'string') {
121 throw new Error(`${provider}: models.dev api is missing`)
122 }
123 const apiPath = openCodeApiPath(provider, block.api, 'api')
124 const out: Record<string, ModelInfo> = {}
125 for (const [id, row] of Object.entries(models)) {
126 if (!record(row) || row.id !== id)
127 throw new Error(`${provider}: unreadable catalog model ${id}`)
128 const source = (path: string): FactSource => ({
129 derivation: 'listing',
130 sourceUrl: OPENCODE_CATALOG_URL,
131 sourceHash: hash,
132 path: `${provider}.models.${id}.${path}`,
133 })
134 const factSources: ModelFactSources = {}
135 const model: ModelInfo = {
136 rawId: id,
137 releasedAt: null,
138 knowledgeCutoff: null,
139 openWeights: null,
140 contextWindow: null,
141 maxOutput: null,
142 modalities: null,
143 capabilities: null,
144 reasoning: reasoning(row.reasoning_options),
145 requestMap: null,
146 providerMetadata: row,
147 }
148 if (row.name !== undefined) {
149 if (typeof row.name !== 'string' || row.name.length === 0) {
150 throw new Error(`${provider}: unreadable name for ${id}`)
151 }
152 model.displayName = row.name
153 }
154 let modelNpm: string | null = null
155 let modelApiPath = apiPath
156 let routeFact = `${provider}.npm`
157 if (row.provider !== undefined) {
158 if (!record(row.provider)) {
159 throw new Error(`${provider}: unreadable provider for ${id}`)
160 }
161 if (row.provider.npm !== undefined) {
162 if (
163 typeof row.provider.npm !== 'string' ||
164 row.provider.npm.length === 0
165 ) {
166 throw new Error(`${provider}: unreadable provider.npm for ${id}`)
167 }
168 modelNpm = row.provider.npm
169 routeFact = `${provider}.models.${id}.provider.npm`
170 }
171 if (row.provider.api !== undefined) {
172 if (typeof row.provider.api !== 'string') {
173 throw new Error(`${provider}: unreadable provider.api for ${id}`)
174 }
175 modelApiPath = openCodeApiPath(
176 provider,
177 row.provider.api,
178 `provider.api for ${id}`,
179 )
180 routeFact = `${provider}.models.${id}.provider`
181 }
182 }
183 const npm = modelNpm ?? block.npm
184 const endpoint = schemaEndpointId(provider, modelApiPath, npm, id)
185 if (endpoint) {
186 model.schemaEndpointId = endpoint
187 model.activity = 'chat'
188 factSources.schemaEndpointId = {
189 derivation: 'listing',
190 sourceUrl: OPENCODE_CATALOG_URL,
191 sourceHash: hash,
192 // Not an endpoint field: the package suffix joined to the model api,
193 // else the provider api.
194 path: routeFact,
195 }
196 } else if (PACKAGE_SUFFIX[npm]) {
197 model.activity = 'chat'
198 }
199 if (row.release_date !== undefined) {
200 if (
201 typeof row.release_date !== 'string' ||
202 !/^\d{4}-\d{2}-\d{2}$/.test(row.release_date)
203 )
204 throw new Error(`${provider}: unreadable release_date for ${id}`)
205 const timestamp = Date.parse(`${row.release_date}T00:00:00.000Z`)
206 if (
207 !Number.isFinite(timestamp) ||
208 new Date(timestamp).toISOString().slice(0, 10) !== row.release_date
209 )
210 throw new Error(`${provider}: unreadable release_date for ${id}`)
211 model.releasedAt = timestamp / 1000
212 }
213 if (row.knowledge !== undefined) {
214 if (
215 typeof row.knowledge !== 'string' ||
216 !/^\d{4}-(0[1-9]|1[0-2])(?:-\d{2})?$/.test(row.knowledge)
217 )
218 throw new Error(`${provider}: unreadable knowledge for ${id}`)
219 if (row.knowledge.length === 10) {
220 const timestamp = Date.parse(`${row.knowledge}T00:00:00.000Z`)
221 if (
222 !Number.isFinite(timestamp) ||
223 new Date(timestamp).toISOString().slice(0, 10) !== row.knowledge
224 )
225 throw new Error(`${provider}: unreadable knowledge for ${id}`)
226 }
227 model.knowledgeCutoff = row.knowledge
228 factSources.knowledgeCutoff = source('knowledge')
229 }
230 if (row.open_weights !== undefined) {
231 if (typeof row.open_weights !== 'boolean')
232 throw new Error(`${provider}: unreadable open_weights for ${id}`)
233 model.openWeights = row.open_weights
234 factSources.openWeights = source('open_weights')
235 }
236 if (row.limit !== undefined) {
237 if (!record(row.limit))
238 throw new Error(`${provider}: unreadable limits for ${id}`)
239 for (const [key, fact] of [
240 ['context', 'contextWindow'],
241 ['output', 'maxOutput'],
242 ] as const) {
243 const value = row.limit[key]
244 if (value === undefined) continue
245 if (
246 typeof value !== 'number' ||
247 !Number.isSafeInteger(value) ||
248 value <= 0
249 )
250 throw new Error(`${provider}: unreadable ${key} limit for ${id}`)
251 model[fact] = value
252 factSources[fact] = source(`limit.${key}`)
253 }
254 }
255 if (row.modalities !== undefined) {
256 if (
257 !record(row.modalities) ||
258 !strings(row.modalities.input) ||
259 !strings(row.modalities.output)
260 )
261 throw new Error(`${provider}: unreadable modalities for ${id}`)
262 model.modalities = row.modalities
263 factSources.modalities = source('modalities')
264 }
265 const capabilities: Record<string, boolean> = {}
266 const sources: Record<string, FactSource> = {}
267 for (const [field, flag] of [
268 ['tool_call', 'tools'],
269 ['reasoning', 'reasoning'],
270 ['structured_output', 'structured_outputs'],
271 ] as const) {
272 if (row[field] === undefined) continue
273 if (typeof row[field] !== 'boolean')
274 throw new Error(`${provider}: unreadable ${field} for ${id}`)
275 capabilities[flag] = row[field]
276 sources[flag] = source(field)
277 }
278 if (record(row.modalities) && strings(row.modalities.input)) {
279 capabilities.vision = row.modalities.input.includes('image')
280 sources.vision = source('modalities.input')
281 }
282 if (Object.keys(capabilities).length) {
283 model.capabilities = capabilities
284 factSources.capabilities = sources
285 }
286 if (model.reasoning) factSources.reasoning = source('reasoning_options')
287 if (
288 row.interleaved !== undefined &&
289 typeof row.interleaved !== 'boolean' &&
290 (!record(row.interleaved) || typeof row.interleaved.field !== 'string')
291 )
292 throw new Error(`${provider}: unreadable interleaved for ${id}`)
293 if (
294 record(row.interleaved) &&
295 row.interleaved.field === 'reasoning_content'
296 ) {
297 const map: ChatRequestMap = {
298 thinking: null,
299 maxTokensField: null,
300 developerRole: null,
301 replayReasoningContent: true,
302 store: null,
303 strictTools: null,
304 sessionAffinity: null,
305 cacheControl: null,
306 toolStream: null,
307 reasoningEffort: null,
308 }
309 model.requestMap = map
310 factSources.requestMap = source('interleaved.field')
311 }
312 model.factSources = factSources
313 out[id] = model
314 }
315 if (!Object.keys(out).length)
316 throw new Error(`${provider}: models.dev listed no models`)
317 return out
318}
319
320export async function loadOpenCodeCatalog(
321 kv?: KVNamespace,
322): Promise<OpenCodeCatalogLoad> {
323 return cachedDocs(kv, OPENCODE_CATALOG_URL, async () => {
324 const text = await fetchText(OPENCODE_CATALOG_URL, {
325 signal: AbortSignal.timeout(30_000),
326 })
327 return {
328 payload: JSON.parse(text) as unknown,
329 hash: await sha256Text(text),
330 }
331 })
332}
333
334export async function openCodeCatalog(
335 provider: OpenCodeProvider,
336 kv?: KVNamespace,
337): Promise<Record<string, ModelInfo>> {
338 const catalog = await loadOpenCodeCatalog(kv)
339 return parseOpenCodeCatalog(catalog.payload, provider, catalog.hash)
340}