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