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

opencode-catalog.ts

228 lines7.7 KB

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​
15function record(value: unknown): value is Record<string, unknown> {
16 return value !== null && typeof value === 'object' && !Array.isArray(value)
18function strings(value: unknown): value is Array<string> {
19 return Array.isArray(value) && value.every((v) => typeof v === 'string')
21function reasoning(value: unknown): ModelReasoning | null {
22 if (value === undefined) return null
23 if (!Array.isArray(value))
24 throw new Error('opencode: unreadable reasoning_options')
25 const options = value.map((option: unknown) => {
26 if (
27 !record(option) ||
28 !['toggle', 'effort', 'budget_tokens'].includes(String(option.type))
29 ) {
30 throw new Error('opencode: unreadable reasoning option')
31 }
32 if (
33 option.type === 'effort' &&
34 (!strings(option.values) || option.values.length === 0)
35 ) {
36 throw new Error('opencode: unreadable effort values')
37 }
38 return option
39 })
40 const toggle = options.some((option) => option.type === 'toggle')
41 const effort = options.find((option) => option.type === 'effort')
42 if (effort && strings(effort.values))
43 return {
44 mode: 'effort',
45 efforts: effort.values,
46 mandatory:
47 toggle ||
48 effort.values.some((v) => ['none', 'off', 'disabled'].includes(v))
49 ? false
50 : null,
51 }
52 if (options.some((option) => option.type === 'budget_tokens'))
53 return { mode: 'budget', mandatory: toggle ? false : null }
54 return toggle ? { mode: 'toggle', mandatory: false } : null
56​
57export function parseOpenCodeCatalog(
58 payload: unknown,
59 provider: OpenCodeProvider,
60 hash: string,
61): Record<string, ModelInfo> {
62 if (
63 !record(payload) ||
64 !record(payload[provider]) ||
65 !record(payload[provider].models)
66 ) {
67 throw new Error(`${provider}: models.dev has no provider models object`)
68 }
69 const out: Record<string, ModelInfo> = {}
70 for (const [id, row] of Object.entries(payload[provider].models)) {
71 if (!record(row) || row.id !== id)
72 throw new Error(`${provider}: unreadable catalog model ${id}`)
73 const source = (path: string): FactSource => ({
74 derivation: 'listing',
75 sourceUrl: OPENCODE_CATALOG_URL,
76 sourceHash: hash,
77 path: `${provider}.models.${id}.${path}`,
78 })
79 const factSources: ModelFactSources = {}
80 const model: ModelInfo = {
81 rawId: id,
82 releasedAt: null,
83 knowledgeCutoff: null,
84 openWeights: null,
85 contextWindow: null,
86 maxOutput: null,
87 modalities: null,
88 capabilities: null,
89 reasoning: reasoning(row.reasoning_options),
90 requestMap: null,
91 providerMetadata: row,
92 }
93 if (row.release_date !== undefined) {
94 if (
95 typeof row.release_date !== 'string' ||
96 !/^\d{4}-\d{2}-\d{2}$/.test(row.release_date)
97 )
98 throw new Error(`${provider}: unreadable release_date for ${id}`)
99 const timestamp = Date.parse(`${row.release_date}T00:00:00.000Z`)
100 if (
101 !Number.isFinite(timestamp) ||
102 new Date(timestamp).toISOString().slice(0, 10) !== row.release_date
103 )
104 throw new Error(`${provider}: unreadable release_date for ${id}`)
105 model.releasedAt = timestamp / 1000
106 }
107 if (row.knowledge !== undefined) {
108 if (
109 typeof row.knowledge !== 'string' ||
110 !/^\d{4}-(0[1-9]|1[0-2])(?:-\d{2})?$/.test(row.knowledge)
111 )
112 throw new Error(`${provider}: unreadable knowledge for ${id}`)
113 if (row.knowledge.length === 10) {
114 const timestamp = Date.parse(`${row.knowledge}T00:00:00.000Z`)
115 if (
116 !Number.isFinite(timestamp) ||
117 new Date(timestamp).toISOString().slice(0, 10) !== row.knowledge
118 )
119 throw new Error(`${provider}: unreadable knowledge for ${id}`)
120 }
121 model.knowledgeCutoff = row.knowledge
122 factSources.knowledgeCutoff = source('knowledge')
123 }
124 if (row.open_weights !== undefined) {
125 if (typeof row.open_weights !== 'boolean')
126 throw new Error(`${provider}: unreadable open_weights for ${id}`)
127 model.openWeights = row.open_weights
128 factSources.openWeights = source('open_weights')
129 }
130 if (row.limit !== undefined) {
131 if (!record(row.limit))
132 throw new Error(`${provider}: unreadable limits for ${id}`)
133 for (const [key, fact] of [
134 ['context', 'contextWindow'],
135 ['output', 'maxOutput'],
136 ] as const) {
137 const value = row.limit[key]
138 if (value === undefined) continue
139 if (
140 typeof value !== 'number' ||
141 !Number.isSafeInteger(value) ||
142 value <= 0
143 )
144 throw new Error(`${provider}: unreadable ${key} limit for ${id}`)
145 model[fact] = value
146 factSources[fact] = source(`limit.${key}`)
147 }
148 }
149 if (row.modalities !== undefined) {
150 if (
151 !record(row.modalities) ||
152 !strings(row.modalities.input) ||
153 !strings(row.modalities.output)
154 )
155 throw new Error(`${provider}: unreadable modalities for ${id}`)
156 model.modalities = row.modalities
157 factSources.modalities = source('modalities')
158 }
159 const capabilities: Record<string, boolean> = {}
160 const sources: Record<string, FactSource> = {}
161 for (const [field, flag] of [
162 ['tool_call', 'tools'],
163 ['reasoning', 'reasoning'],
164 ['structured_output', 'structured_outputs'],
165 ] as const) {
166 if (row[field] === undefined) continue
167 if (typeof row[field] !== 'boolean')
168 throw new Error(`${provider}: unreadable ${field} for ${id}`)
169 capabilities[flag] = row[field]
170 sources[flag] = source(field)
171 }
172 if (record(row.modalities) && strings(row.modalities.input)) {
173 capabilities.vision = row.modalities.input.includes('image')
174 sources.vision = source('modalities.input')
175 }
176 if (Object.keys(capabilities).length) {
177 model.capabilities = capabilities
178 factSources.capabilities = sources
179 }
180 if (model.reasoning) factSources.reasoning = source('reasoning_options')
181 if (
182 row.interleaved !== undefined &&
183 typeof row.interleaved !== 'boolean' &&
184 (!record(row.interleaved) || typeof row.interleaved.field !== 'string')
185 )
186 throw new Error(`${provider}: unreadable interleaved for ${id}`)
187 if (
188 record(row.interleaved) &&
189 row.interleaved.field === 'reasoning_content'
190 ) {
191 const map: ChatRequestMap = {
192 thinking: null,
193 maxTokensField: null,
194 developerRole: null,
195 replayReasoningContent: true,
196 store: null,
197 strictTools: null,
198 sessionAffinity: null,
199 cacheControl: null,
200 toolStream: null,
201 reasoningEffort: null,
202 }
203 model.requestMap = map
204 factSources.requestMap = source('interleaved.field')
205 }
206 model.factSources = factSources
207 out[id] = model
208 }
209 if (!Object.keys(out).length)
210 throw new Error(`${provider}: models.dev listed no models`)
211 return out
213​
214export async function openCodeCatalog(
215 provider: OpenCodeProvider,
216 kv?: KVNamespace,
217): Promise<Record<string, ModelInfo>> {
218 const catalog = await cachedDocs(kv, OPENCODE_CATALOG_URL, async () => {
219 const text = await fetchText(OPENCODE_CATALOG_URL, {
220 signal: AbortSignal.timeout(30_000),
221 })
222 return {
223 payload: JSON.parse(text) as unknown,
224 hash: await sha256Text(text),
225 }
226 })
227 return parseOpenCodeCatalog(catalog.payload, provider, catalog.hash)