Open History to see the last commit
1import { price } from '@modelschemas/rate-card'
2import type { RateCard } from '@modelschemas/rate-card'
3import { OPENCODE_CATALOG_URL } from '../opencode-catalog.ts'
4import { OPENCODE_PRICING_URL } from '../opencode-pricing.ts'
5import { OPENCODE_ROUTE_DOCS_URL } from '../opencode-routes.ts'
6
7import { afterEach, describe, expect, it } from 'vitest'
8
9import { OPENCODE_MODELS_URL, provider } from './opencode.ts'
10
11/** Excerpt-shaped listing. Ids are fixtures, not a live snapshot. */
12const LISTING = {
13 object: 'list',
14 data: [
15 'opus',
16 'gpt',
17 'gemini',
18 'qwen',
19 'pickle',
20 'unlisted',
21 'mistral',
22 'jev',
23 ].map((id) => ({ id, object: 'model', owned_by: 'opencode' })),
24}
25
26const CATALOG = {
27 opencode: {
28 npm: '@ai-sdk/openai-compatible',
29 api: 'https://opencode.ai/inference/v1',
30 models: {
31 opus: {
32 id: 'opus',
33 name: 'Opus',
34 provider: { npm: '@ai-sdk/anthropic' },
35 limit: { context: 1234, output: 234 },
36 tool_call: true,
37 reasoning_options: [{ type: 'budget_tokens', min: 1 }],
38 interleaved: { field: 'reasoning_content' },
39 },
40 gpt: {
41 id: 'gpt',
42 name: 'GPT',
43 provider: { npm: '@ai-sdk/openai' },
44 },
45 gemini: {
46 id: 'gemini',
47 name: 'Gemini',
48 provider: { npm: '@ai-sdk/google' },
49 },
50 qwen: {
51 id: 'qwen',
52 name: 'Qwen',
53 },
54 pickle: {
55 id: 'pickle',
56 name: 'Pickle',
57 },
58 mistral: {
59 id: 'mistral',
60 name: 'Mistral',
61 provider: { npm: '@ai-sdk/mistral' },
62 },
63 },
64 },
65}
66
67/** Console page excerpt: prices `jev`, an id models.dev has no record of, and not `qwen`. */
68const PAGE = `## Endpoints
69
70| Model | Model ID | Endpoint | AI SDK Package |
71| ------- | -------- | -------- | -------------- |
72| Opus | opus | - | - |
73| GPT | gpt | - | - |
74| Gemini | gemini | - | - |
75| Pickle | pickle | - | - |
76| Mistral | mistral | - | - |
77| Jev | jev | - | - |
78
79## Pricing
80
81| Model | Input | Output | Cached Read | Cached Write |
82| ------------------- | ------ | ------ | ----------- | ------------ |
83| Opus | $4.00 | $20.00 | $0.20 | $5.00 |
84| GPT (≤ 272K tokens) | $5.00 | $30.00 | $0.50 | - |
85| GPT (> 272K tokens) | $10.00 | $45.00 | $1.00 | - |
86| Gemini | $2.00 | $12.00 | $0.20 | - |
87| Pickle | Free | Free | Free | - |
88| Mistral | $1.00 | $2.00 | - | - |
89| Jev | $0.042 | Free | - | - |
90`
91
92/** inference.mdx Endpoints table, listing the paths CATALOG's api yields. */
93const ROUTE_DOCS = `# Inference API
94
95## Endpoints
96
97| API | Path |
98| --------- | -------------------------------------------------- |
99| Chat | \`/inference/v1/chat/completions\` |
100| Responses | \`/inference/v1/responses\` |
101| Messages | \`/inference/v1/messages\` |
102| Gemini | \`/inference/v1/models/<model>:generateContent\` |
103`
104
105const originalFetch = globalThis.fetch
106
107afterEach(() => {
108 globalThis.fetch = originalFetch
109})
110
111function serve(catalog: unknown = CATALOG, page = PAGE) {
112 const urls: Array<string> = []
113 globalThis.fetch = ((url: string) => {
114 urls.push(String(url))
115 if (String(url) === OPENCODE_MODELS_URL) {
116 return Promise.resolve(new Response(JSON.stringify(LISTING)))
117 }
118 if (String(url) === OPENCODE_CATALOG_URL) {
119 return Promise.resolve(new Response(JSON.stringify(catalog)))
120 }
121 if (String(url) === OPENCODE_PRICING_URL) {
122 return Promise.resolve(new Response(page))
123 }
124 if (String(url) === OPENCODE_ROUTE_DOCS_URL) {
125 return Promise.resolve(new Response(ROUTE_DOCS))
126 }
127 return Promise.reject(new Error(`unexpected fetch: ${String(url)}`))
128 }) as typeof fetch
129 return urls
130}
131
132type Card = { tables: { rate: Record<string, Record<string, number>> } }
133
134describe('opencode', () => {
135 it('reads routes from the catalog and prices from the console page', async () => {
136 const urls = serve()
137 const { models } = await provider.listModels({})
138 const byId = Object.fromEntries(models.map((m) => [m.rawId, m]))
139
140 expect(models.map((m) => m.rawId)).toEqual(LISTING.data.map((r) => r.id))
141 expect(urls.some((url) => url.includes('opencode.ai/docs/'))).toBe(false)
142
143 expect(byId.opus).toMatchObject({
144 displayName: 'Opus',
145 activity: 'chat',
146 schemaEndpointId: 'inference/v1/messages',
147 contextWindow: 1234,
148 factSources: {
149 pricing: {
150 derivation: 'docs-derived',
151 sourceUrl: OPENCODE_PRICING_URL,
152 },
153 schemaEndpointId: {
154 derivation: 'listing',
155 path: 'opencode.models.opus.provider.npm',
156 },
157 },
158 })
159 expect((byId.opus!.pricing as Card).tables.rate).toEqual({
160 base: {
161 input_tokens: 4 / 1e6,
162 output_tokens: 20 / 1e6,
163 cache_read_tokens: 0.2 / 1e6,
164 cache_write_tokens: 5 / 1e6,
165 },
166 })
167
168 expect((byId.gpt!.pricing as Card).tables.rate).toEqual({
169 base: {
170 input_tokens: 5 / 1e6,
171 output_tokens: 30 / 1e6,
172 cache_read_tokens: 0.5 / 1e6,
173 },
174 '272000': {
175 input_tokens: 10 / 1e6,
176 output_tokens: 45 / 1e6,
177 cache_read_tokens: 1 / 1e6,
178 },
179 })
180 expect(byId.gpt?.schemaEndpointId).toBe('inference/v1/responses')
181 expect(byId.gemini?.schemaEndpointId).toBe(
182 'inference/v1/models/gemini:generateContent',
183 )
184 expect(byId.qwen?.schemaEndpointId).toBe('inference/v1/chat/completions')
185 expect(byId.qwen?.factSources?.schemaEndpointId?.path).toBe('opencode.npm')
186 // The page does not price qwen: a stored card is cleared.
187 expect(byId.qwen?.pricing).toBeNull()
188 expect(byId.qwen?.absent).toEqual({
189 releasedAt: 'cleared',
190 pricing: 'cleared',
191 })
192 // jev has no models.dev record but the page prices it.
193 expect(byId.jev?.absent).toEqual({ releasedAt: 'cleared' })
194 expect(
195 price(
196 byId.jev!.pricing as RateCard,
197 {},
198 { input_tokens: 1_000_000, output_tokens: 1_000_000 },
199 ),
200 ).toBeCloseTo(0.042)
201
202 expect(byId.pickle).toMatchObject({
203 activity: 'chat',
204 pricing: {
205 price: 0,
206 tables: {
207 rate: {
208 base: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0 },
209 },
210 },
211 },
212 })
213 expect(
214 price(
215 byId.pickle!.pricing as RateCard,
216 {},
217 { input_tokens: 10_000, output_tokens: 2_000, cache_read_tokens: 300 },
218 ),
219 ).toBe(0)
220
221 expect(byId.mistral?.displayName).toBe('Mistral')
222 expect(byId.mistral?.schemaEndpointId).toBeUndefined()
223 expect(byId.mistral?.activity).toBeUndefined()
224 expect(byId.mistral?.pricing).toBeTruthy()
225
226 expect(byId.unlisted).toEqual({
227 rawId: 'unlisted',
228 releasedAt: null,
229 absent: { releasedAt: 'cleared', pricing: 'cleared' },
230 pricing: null,
231 })
232 expect(provider.bindSyncedRoutesOnly).toBe(true)
233
234 const spec = await provider.fetchSpec({})
235 expect(
236 spec.specs[0]?.paths?.['/inference/v1/messages']?.post,
237 ).toMatchObject({
238 'x-modelschemas-route-only': true,
239 })
240 expect(spec.specs[0]?.paths?.['/v1/messages']).toBeUndefined()
241 const source = spec.specs[0]?.paths?.['/inference/v1/messages']?.post?.[
242 'x-modelschemas-method-source'
243 ] as { url: string }
244 expect(source.url).toBe(OPENCODE_ROUTE_DOCS_URL)
245 })
246
247 it('fails the poll when the catalog is unavailable', async () => {
248 serve()
249 const fetchCatalog = globalThis.fetch
250 globalThis.fetch = ((url: string, init?: RequestInit) =>
251 String(url) === OPENCODE_CATALOG_URL
252 ? Promise.resolve(new Response('unavailable', { status: 503 }))
253 : fetchCatalog(url, init)) as typeof fetch
254 await expect(provider.listModels({})).rejects.toThrow()
255 })
256
257 it('prices a model that was free once the page quotes a rate', async () => {
258 serve(
259 CATALOG,
260 PAGE.replace(
261 '| Pickle | Free | Free | Free |',
262 '| Pickle | $0.10 | $0.20 | $0.01 |',
263 ),
264 )
265 const paid = (await provider.listModels({})).models.find(
266 (model) => model.rawId === 'pickle',
267 )!
268 expect(
269 price(
270 paid.pricing as RateCard,
271 {},
272 { input_tokens: 1_000_000, output_tokens: 1_000_000 },
273 ),
274 ).toBeCloseTo(0.3)
275 })
276
277 it('keeps stored prices when the page fails, and still polls', async () => {
278 serve(CATALOG, '## Pricing\n\nmoved\n')
279 const result = await provider.listModels({})
280 expect(result.docsFailures).toMatchObject({ failed: 1 })
281 for (const model of result.models) {
282 expect(model.pricing ?? null).toBeNull()
283 expect(model.absent?.pricing).toBe('unavailable')
284 }
285 })
286})