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 // The models list names `generate-content` without choosing Google's
98 // method. Bind only an exact probe record.
99 if (provider === 'opencode-go' && npm === '@ai-sdk/google') {
100 return probedRoute(provider, id)
101 }
102 if (id.includes('/'))
103 throw new Error(`${provider}: unreadable model id ${id}`)
104 return `${apiPath}/${suffix}`
105}
106
107export function parseOpenCodeCatalog(
108 payload: unknown,
109 provider: OpenCodeProvider,
110 hash: string,
111): Record<string, ModelInfo> {
112 if (!record(payload) || !record(payload[provider])) {
113 throw new Error(`${provider}: models.dev has no provider models object`)
114 }
115 const block = payload[provider]
116 const models = block.models
117 if (!record(models)) {
118 throw new Error(`${provider}: models.dev has no provider models object`)
119 }
120 if (typeof block.npm !== 'string' || block.npm.length === 0) {
121 throw new Error(`${provider}: models.dev provider npm is missing`)
122 }
123 if (typeof block.api !== 'string') {
124 throw new Error(`${provider}: models.dev api is missing`)
125 }
126 const apiPath = openCodeApiPath(provider, block.api, 'api')
127 const out: Record<string, ModelInfo> = {}
128 for (const [id, row] of Object.entries(models)) {
129 if (!record(row) || row.id !== id)
130 throw new Error(`${provider}: unreadable catalog model ${id}`)
131 const source = (path: string): FactSource => ({
132 derivation: 'listing',
133 sourceUrl: OPENCODE_CATALOG_URL,
134 sourceHash: hash,
135 path: `${provider}.models.${id}.${path}`,
136 })
137 const factSources: ModelFactSources = {}
138 const model: ModelInfo = {
139 rawId: id,
140 releasedAt: null,
141 knowledgeCutoff: null,
142 openWeights: null,
143 contextWindow: null,
144 maxOutput: null,
145 modalities: null,
146 capabilities: null,
147 reasoning: reasoning(row.reasoning_options),
148 requestMap: null,
149 providerMetadata: row,
150 }
151 if (row.name !== undefined) {
152 if (typeof row.name !== 'string' || row.name.length === 0) {
153 throw new Error(`${provider}: unreadable name for ${id}`)
154 }
155 model.displayName = row.name
156 }
157 let modelNpm: string | null = null
158 let modelApiPath = apiPath
159 let routeFact = `${provider}.npm`
160 if (row.provider !== undefined) {
161 if (!record(row.provider)) {
162 throw new Error(`${provider}: unreadable provider for ${id}`)
163 }
164 if (row.provider.npm !== undefined) {
165 if (
166 typeof row.provider.npm !== 'string' ||
167 row.provider.npm.length === 0
168 ) {
169 throw new Error(`${provider}: unreadable provider.npm for ${id}`)
170 }
171 modelNpm = row.provider.npm
172 routeFact = `${provider}.models.${id}.provider.npm`
173 }
174 if (row.provider.api !== undefined) {
175 if (typeof row.provider.api !== 'string') {
176 throw new Error(`${provider}: unreadable provider.api for ${id}`)
177 }
178 modelApiPath = openCodeApiPath(
179 provider,
180 row.provider.api,
181 `provider.api for ${id}`,
182 )
183 routeFact = `${provider}.models.${id}.provider`
184 }
185 }
186 const npm = modelNpm ?? block.npm
187 const endpoint = schemaEndpointId(provider, modelApiPath, npm, id)
188 if (endpoint) {
189 model.schemaEndpointId = endpoint
190 model.activity = 'chat'
191 const probed = probeFactSource(provider, id, endpoint)
192 factSources.schemaEndpointId = probed ?? {
193 derivation: 'listing',
194 sourceUrl: OPENCODE_CATALOG_URL,
195 sourceHash: hash,
196 // Not an endpoint field: the package suffix joined to the model api,
197 // else the provider api.
198 path: routeFact,
199 }
200 } else if (PACKAGE_SUFFIX[npm]) {
201 model.activity = 'chat'
202 }
203 if (row.release_date !== undefined) {
204 if (
205 typeof row.release_date !== 'string' ||
206 !/^\d{4}-\d{2}-\d{2}$/.test(row.release_date)
207 )
208 throw new Error(`${provider}: unreadable release_date for ${id}`)
209 const timestamp = Date.parse(`${row.release_date}T00:00:00.000Z`)
210 if (
211 !Number.isFinite(timestamp) ||
212 new Date(timestamp).toISOString().slice(0, 10) !== row.release_date
213 )
214 throw new Error(`${provider}: unreadable release_date for ${id}`)
215 model.releasedAt = timestamp / 1000
216 }
217 if (row.knowledge !== undefined) {
218 if (
219 typeof row.knowledge !== 'string' ||
220 !/^\d{4}-(0[1-9]|1[0-2])(?:-\d{2})?$/.test(row.knowledge)
221 )
222 throw new Error(`${provider}: unreadable knowledge for ${id}`)
223 if (row.knowledge.length === 10) {
224 const timestamp = Date.parse(`${row.knowledge}T00:00:00.000Z`)
225 if (
226 !Number.isFinite(timestamp) ||
227 new Date(timestamp).toISOString().slice(0, 10) !== row.knowledge
228 )
229 throw new Error(`${provider}: unreadable knowledge for ${id}`)
230 }
231 model.knowledgeCutoff = row.knowledge
232 factSources.knowledgeCutoff = source('knowledge')
233 }
234 if (row.open_weights !== undefined) {
235 if (typeof row.open_weights !== 'boolean')
236 throw new Error(`${provider}: unreadable open_weights for ${id}`)
237 model.openWeights = row.open_weights
238 factSources.openWeights = source('open_weights')
239 }
240 if (row.limit !== undefined) {
241 if (!record(row.limit))
242 throw new Error(`${provider}: unreadable limits for ${id}`)
243 for (const [key, fact] of [
244 ['context', 'contextWindow'],
245 ['output', 'maxOutput'],
246 ] as const) {
247 const value = row.limit[key]
248 if (value === undefined) continue
249 if (
250 typeof value !== 'number' ||
251 !Number.isSafeInteger(value) ||
252 value <= 0
253 )
254 throw new Error(`${provider}: unreadable ${key} limit for ${id}`)
255 model[fact] = value
256 factSources[fact] = source(`limit.${key}`)
257 }
258 }
259 if (row.modalities !== undefined) {
260 if (
261 !record(row.modalities) ||
262 !strings(row.modalities.input) ||
263 !strings(row.modalities.output)
264 )
265 throw new Error(`${provider}: unreadable modalities for ${id}`)
266 model.modalities = row.modalities
267 factSources.modalities = source('modalities')
268 }
269 const capabilities: Record<string, boolean> = {}
270 const sources: Record<string, FactSource> = {}
271 for (const [field, flag] of [
272 ['tool_call', 'tools'],
273 ['reasoning', 'reasoning'],
274 ['structured_output', 'structured_outputs'],
275 ] as const) {
276 if (row[field] === undefined) continue
277 if (typeof row[field] !== 'boolean')
278 throw new Error(`${provider}: unreadable ${field} for ${id}`)
279 capabilities[flag] = row[field]
280 sources[flag] = source(field)
281 }
282 if (record(row.modalities) && strings(row.modalities.input)) {
283 capabilities.vision = row.modalities.input.includes('image')
284 sources.vision = source('modalities.input')
285 }
286 if (Object.keys(capabilities).length) {
287 model.capabilities = capabilities
288 factSources.capabilities = sources
289 }
290 if (model.reasoning) factSources.reasoning = source('reasoning_options')
291 if (
292 row.interleaved !== undefined &&
293 typeof row.interleaved !== 'boolean' &&
294 (!record(row.interleaved) || typeof row.interleaved.field !== 'string')
295 )
296 throw new Error(`${provider}: unreadable interleaved for ${id}`)
297 if (
298 record(row.interleaved) &&
299 row.interleaved.field === 'reasoning_content'
300 ) {
301 const map: ChatRequestMap = {
302 thinking: null,
303 maxTokensField: null,
304 developerRole: null,
305 replayReasoningContent: true,
306 store: null,
307 strictTools: null,
308 sessionAffinity: null,
309 cacheControl: null,
310 toolStream: null,
311 reasoningEffort: null,
312 }
313 model.requestMap = map
314 factSources.requestMap = source('interleaved.field')
315 }
316 model.factSources = factSources
317 out[id] = model
318 }
319 if (!Object.keys(out).length)
320 throw new Error(`${provider}: models.dev listed no models`)
321 return out
322}
323
324export async function loadOpenCodeCatalog(
325 kv?: KVNamespace,
326): Promise<OpenCodeCatalogLoad> {
327 return cachedDocs(kv, OPENCODE_CATALOG_URL, async () => {
328 const text = await fetchText(OPENCODE_CATALOG_URL, {
329 signal: AbortSignal.timeout(30_000),
330 })
331 return {
332 payload: JSON.parse(text) as unknown,
333 hash: await sha256Text(text),
334 }
335 })
336}
337
338export async function openCodeCatalog(
339 provider: OpenCodeProvider,
340 kv?: KVNamespace,
341): Promise<Record<string, ModelInfo>> {
342 const catalog = await loadOpenCodeCatalog(kv)
343 return parseOpenCodeCatalog(catalog.payload, provider, catalog.hash)
344}