Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2
3import { classifyAndBundle } from '#/server/ingest/sync.ts'
4import listing from '../fixtures/replicate-models.json'
5import openapi from '../fixtures/replicate-openapi.json'
6import type { OpenApiDocument } from '../types.ts'
7import {
8 provider,
9 replicateChatFacts,
10 replicateModelSpec,
11} from './replicate.ts'
12import type { ReplicateModel } from './replicate.ts'
13
14// Rows of GET https://api.replicate.com/v1/models, trimmed to the fields read.
15const MODELS: Array<ReplicateModel> = listing
16const SPEC: OpenApiDocument = openapi
17
18function model(rawId: string): ReplicateModel {
19 const found = MODELS.find((row) => `${row.owner}/${row.name}` === rawId)
20 if (!found) throw new Error(`fixture has no ${rawId}`)
21 return structuredClone(found)
22}
23
24function inputProperties(row: ReplicateModel): Record<string, unknown> {
25 const schemas = row.latest_version?.openapi_schema?.components?.schemas as {
26 Input: { properties: Record<string, unknown> }
27 }
28 return schemas.Input.properties
29}
30
31const INPUT = '/latest_version/openapi_schema/components/schemas/Input'
32
33describe('replicate classify', () => {
34 it('maps generation creates onto chat, image, video, and audio', () => {
35 expect(
36 provider.classify(
37 '/models/meta/meta-llama-3-70b-instruct/predictions',
38 {},
39 ),
40 ).toBe('chat')
41 expect(
42 provider.classify(
43 '/v1/models/meta/llama-3.1-405b-instruct/predictions',
44 {},
45 ),
46 ).toBe('chat')
47 expect(provider.classify('/predictions', {})).toBe('image')
48 expect(provider.classify('/v1/predictions', {})).toBe('image')
49 expect(
50 provider.classify(
51 '/models/black-forest-labs/flux-schnell/predictions',
52 {},
53 ),
54 ).toBe('image')
55 expect(provider.classify('/models/minimax/video-01/predictions', {})).toBe(
56 'video',
57 )
58 expect(provider.classify('/models/openai/whisper/predictions', {})).toBe(
59 'audio',
60 )
61 })
62
63 it('drops account, collections, hardware, trainings, and cancel', () => {
64 expect(provider.classify('/account', {})).toBeNull()
65 expect(provider.classify('/collections', {})).toBeNull()
66 expect(provider.classify('/hardware', {})).toBeNull()
67 expect(provider.classify('/models', {})).toBeNull()
68 expect(
69 provider.classify(
70 '/models/{model_owner}/{model_name}/versions/{version_id}/trainings',
71 {},
72 ),
73 ).toBeNull()
74 expect(
75 provider.classify('/predictions/{prediction_id}/cancel', {}),
76 ).toBeNull()
77 expect(
78 provider.classify(
79 '/deployments/{deployment_owner}/{deployment_name}/predictions',
80 {},
81 ),
82 ).toBeNull()
83 })
84})
85
86describe('replicate listModels', () => {
87 it('skips when REPLICATE_API_TOKEN is absent', async () => {
88 const result = await provider.listModels({})
89 expect(result.skipped).toBe(
90 'replicate: REPLICATE_API_TOKEN not set — skipped',
91 )
92 expect(result.models).toEqual([])
93 })
94
95 it('pages GET /v1/models and maps owner/name', async () => {
96 const pages: Record<string, unknown> = {
97 'https://api.replicate.com/v1/models': {
98 next: 'https://api.replicate.com/v1/models?cursor=p2',
99 results: [
100 {
101 owner: 'black-forest-labs',
102 name: 'flux-schnell',
103 description: 'Fast text-to-image',
104 visibility: 'public',
105 run_count: 26026,
106 created_at: '2024-08-01T00:00:00Z',
107 is_official: true,
108 },
109 ],
110 },
111 'https://api.replicate.com/v1/models?cursor=p2': {
112 next: null,
113 results: [
114 {
115 owner: 'openai',
116 name: 'whisper',
117 description: 'Speech-to-text',
118 latest_version: { created_at: '2023-01-02T00:00:00Z' },
119 },
120 ],
121 },
122 }
123 const original = globalThis.fetch
124 const calls: Array<{ url: string; auth: string | null }> = []
125 globalThis.fetch = ((url: string, init?: RequestInit) => {
126 const href = String(url)
127 calls.push({
128 url: href,
129 auth: new Headers(init?.headers).get('authorization'),
130 })
131 const body = pages[href]
132 return Promise.resolve(
133 body
134 ? new Response(JSON.stringify(body))
135 : new Response('not found', { status: 404 }),
136 )
137 }) as typeof fetch
138 try {
139 const result = await provider.listModels({
140 REPLICATE_API_TOKEN: 'tok-test',
141 })
142 expect(calls.map((c) => c.url)).toEqual([
143 'https://api.replicate.com/v1/models',
144 'https://api.replicate.com/v1/models?cursor=p2',
145 'https://replicate.com/black-forest-labs/flux-schnell',
146 ])
147 expect(calls[0]?.auth).toBe('Bearer tok-test')
148 expect(result.skipped).toBeUndefined()
149 expect(result.models.map((m) => [m.rawId, m.activity])).toEqual([
150 ['black-forest-labs/flux-schnell', 'image'],
151 ['openai/whisper', 'audio'],
152 ])
153 // run_count is usage telemetry; storing it made every poll a model.updated (#92).
154 expect(result.models[0]?.providerMetadata).toEqual({
155 visibility: 'public',
156 official: true,
157 })
158 expect(result.models[0]?.releasedAt).toBe(
159 Date.parse('2024-08-01T00:00:00Z') / 1000,
160 )
161 } finally {
162 globalThis.fetch = original
163 }
164 })
165})
166
167describe('replicate fetchSpec', () => {
168 it('loads the public OpenAPI document', async () => {
169 const spec: OpenApiDocument = {
170 openapi: '3.1.0',
171 paths: {
172 '/predictions': {
173 post: {
174 summary: 'Create a prediction',
175 requestBody: {
176 content: {
177 'application/json': {
178 schema: {
179 type: 'object',
180 properties: {
181 version: { type: 'string' },
182 input: { type: 'object' },
183 },
184 },
185 },
186 },
187 },
188 responses: {
189 '200': {
190 content: {
191 'application/json': {
192 schema: {
193 type: 'object',
194 properties: { id: { type: 'string' } },
195 },
196 },
197 },
198 },
199 },
200 },
201 },
202 '/account': { get: { summary: 'Get the current account' } },
203 },
204 }
205 const original = globalThis.fetch
206 const urls: Array<string> = []
207 globalThis.fetch = ((url: string) => {
208 urls.push(String(url))
209 const body = String(url).endsWith('/openapi.json') ? spec : {}
210 return Promise.resolve(new Response(JSON.stringify(body)))
211 }) as typeof fetch
212 try {
213 // No token: skipped whole, never a sync with the model routes missing.
214 const keyless = await provider.fetchSpec({})
215 expect(keyless.skipped).toBe(
216 'replicate: REPLICATE_API_TOKEN not set — skipped',
217 )
218 expect(urls).toEqual([])
219
220 const fetched = await provider.fetchSpec({ REPLICATE_API_TOKEN: 'tok' })
221 expect(urls).toEqual([
222 'https://api.replicate.com/openapi.json',
223 'https://api.replicate.com/v1/models',
224 ])
225 expect(fetched.outputStrategy).toBe('post-200')
226 expect(fetched.skipped).toBeUndefined()
227 expect(fetched.sources[0]?.url).toBe(
228 'https://api.replicate.com/openapi.json',
229 )
230 expect(fetched.sources[0]?.hash).toMatch(/^[0-9a-f]{64}$/)
231
232 const { endpoints, warnings } = classifyAndBundle(provider, fetched)
233 expect(warnings).toEqual([])
234 expect(endpoints.map((e) => [e.dbId, e.activity])).toEqual([
235 ['replicate/predictions', 'image'],
236 ])
237 expect(endpoints[0]?.derivation).toBe('upstream-spec')
238 } finally {
239 globalThis.fetch = original
240 }
241 })
242})
243
244describe('replicate seed metadata', () => {
245 it('exports the adapter contract', () => {
246 expect(provider.id).toBe('replicate')
247 expect(provider.displayName).toBe('Replicate')
248 expect(provider.authEnvVar).toBe('REPLICATE_API_TOKEN')
249 expect(provider.defaultDerivation).toBe('upstream-spec')
250 expect(provider.specSourceUrl).toBe(
251 'https://api.replicate.com/openapi.json',
252 )
253 expect(provider.modelsEndpoint).toBe('https://api.replicate.com/v1/models')
254 })
255})
256
257describe('replicate chat facts from a model schema', () => {
258 it('reads a language model off its schema, not its name', () => {
259 const chat = MODELS.filter((row) => replicateChatFacts(row) !== null)
260 expect(chat.map((row) => `${row.owner}/${row.name}`).sort()).toEqual([
261 'anthropic/claude-sonnet-5',
262 'deepseek-ai/deepseek-v3.1',
263 'google/gemini-3-flash',
264 'ibm-granite/granite-4.1-8b',
265 'meta/llama-4-maverick-instruct',
266 'meta/llama-guard-4-12b',
267 'openai/gpt-5.4',
268 'prunaai/gpt-oss-120b-fast',
269 ])
270 // Returns an image URL, an embedding, and a trainer's text: not chat.
271 expect(replicateChatFacts(model('alibaba/qwen-image-3'))).toBeNull()
272 expect(
273 replicateChatFacts(
274 model('ibm-granite/granite-embedding-small-english-r2'),
275 ),
276 ).toBeNull()
277 expect(replicateChatFacts(model('replicate/fast-flux-trainer'))).toBeNull()
278 })
279
280 it('fills flags, modalities, and the output cap with their source', () => {
281 const facts = replicateChatFacts(model('meta/llama-4-maverick-instruct'))
282 expect(facts?.capabilities).toEqual([
283 'frequency_penalty',
284 'max_tokens',
285 'presence_penalty',
286 'temperature',
287 'top_k',
288 'top_p',
289 ])
290 expect(facts?.modalities).toEqual({ input: ['text'], output: ['text'] })
291 expect(facts?.reasoning).toBeUndefined()
292 expect(facts?.schemaEndpointId).toBe(
293 'models/meta/llama-4-maverick-instruct/predictions',
294 )
295 const sourceUrl =
296 'https://api.replicate.com/v1/models/meta/llama-4-maverick-instruct'
297 const guard = replicateChatFacts(model('meta/llama-guard-4-12b'))
298 expect(guard?.maxOutput).toBe(1024)
299 expect(guard?.factSources?.maxOutput).toEqual({
300 derivation: 'listing',
301 sourceUrl: 'https://api.replicate.com/v1/models/meta/llama-guard-4-12b',
302 path: `${INPUT}/properties/max_completion_tokens/maximum`,
303 })
304 expect(facts?.factSources?.capabilities?.top_p).toEqual({
305 derivation: 'listing',
306 sourceUrl,
307 path: `${INPUT}/properties/top_p`,
308 })
309 expect(facts?.factSources?.modalities?.sourceUrl).toBe(sourceUrl)
310 })
311
312 it('names one modality per file input', () => {
313 expect(
314 replicateChatFacts(model('google/gemini-3-flash'))?.modalities,
315 ).toEqual({
316 input: ['text', 'image', 'audio', 'video'],
317 output: ['text'],
318 })
319 expect(replicateChatFacts(model('openai/gpt-5.4'))?.modalities).toEqual({
320 input: ['text', 'image'],
321 output: ['text'],
322 })
323 })
324
325 it('states no modalities when a file input does not say what it is', () => {
326 const row = model('openai/gpt-5.4')
327 const properties = inputProperties(row)
328 properties.attachment = properties.image_input
329 delete properties.image_input
330 const facts = replicateChatFacts(row)
331 expect(facts?.modalities).toBeUndefined()
332 expect(facts?.factSources?.modalities).toBeUndefined()
333 })
334
335 it('reads an image input the description names, even without format uri', () => {
336 // llama-guard `image_input: string[]`: "List of images to send".
337 const guard = replicateChatFacts(model('meta/llama-guard-4-12b'))
338 expect(guard?.modalities).toEqual({
339 input: ['text', 'image'],
340 output: ['text'],
341 })
342 const undescribed = model('meta/llama-guard-4-12b')
343 ;(
344 inputProperties(undescribed).image_input as { description: string }
345 ).description = 'Optional attachment'
346 expect(replicateChatFacts(undescribed)?.modalities).toBeUndefined()
347 // `max_image_resolution` (integer) and `video_fps` (number) are settings.
348 expect(
349 replicateChatFacts(model('anthropic/claude-sonnet-5'))?.modalities,
350 ).toEqual({ input: ['text', 'image'], output: ['text'] })
351 })
352
353 it('reads the output cap the schema states, including one above 128k', () => {
354 // Llama 4 states max_tokens.maximum 131072 as the output cap.
355 const llama = replicateChatFacts(model('meta/llama-4-maverick-instruct'))
356 expect(llama?.maxOutput).toBe(131072)
357 expect(llama?.factSources?.maxOutput?.path).toBe(
358 `${INPUT}/properties/max_tokens/maximum`,
359 )
360 })
361
362 it('states no output cap without one stated maximum', () => {
363 // gpt-5.4 caps nothing; granite has two token fields and no maximum.
364 expect(replicateChatFacts(model('openai/gpt-5.4'))?.maxOutput).toBe(
365 undefined,
366 )
367 expect(
368 replicateChatFacts(model('ibm-granite/granite-4.1-8b'))?.maxOutput,
369 ).toBeUndefined()
370
371 const disagree = model('anthropic/claude-sonnet-5')
372 inputProperties(disagree).max_completion_tokens = {
373 type: 'integer',
374 maximum: 4096,
375 }
376 expect(replicateChatFacts(disagree)?.maxOutput).toBeUndefined()
377
378 const fractional = model('anthropic/claude-sonnet-5')
379 inputProperties(fractional).max_tokens = { type: 'integer', maximum: 0.5 }
380 expect(replicateChatFacts(fractional)?.maxOutput).toBeUndefined()
381 })
382
383 it('reads reasoning from an effort enum that accepts none', () => {
384 const gpt = replicateChatFacts(model('openai/gpt-5.4'))
385 expect(gpt?.reasoning).toEqual({
386 mode: 'effort',
387 mandatory: false,
388 efforts: ['none', 'low', 'medium', 'high', 'xhigh'],
389 })
390 expect(gpt?.factSources?.reasoning?.path).toBe(
391 `${INPUT}/properties/reasoning_effort`,
392 )
393 })
394
395 it('leaves mandatory unstated where none means unset, not off', () => {
396 // `thinking_level` ["none","low","high"], default "none": "Thinking
397 // level for reasoning (low or high)". The default is not a level.
398 const gemini = replicateChatFacts(model('google/gemini-3-flash'))
399 expect(gemini?.reasoning).toEqual({
400 mode: 'effort',
401 mandatory: null,
402 efforts: ['low', 'high'],
403 })
404 expect(gemini?.factSources?.reasoning?.path).toBe(
405 `${INPUT}/properties/thinking_level`,
406 )
407 // `thinking` ["medium","None"]: "leave as None for default behavior".
408 const deepseek = replicateChatFacts(model('deepseek-ai/deepseek-v3.1'))
409 expect(deepseek?.capabilities).toContain('reasoning')
410 expect(deepseek?.reasoning).toEqual({
411 mode: 'effort',
412 mandatory: null,
413 efforts: ['medium'],
414 })
415 expect(deepseek?.factSources?.reasoning?.path).toBe(
416 `${INPUT}/properties/thinking`,
417 )
418
419 // A `none` that is not the default is a published value, still unstated.
420 const explicit = model('google/gemini-3-flash')
421 ;(inputProperties(explicit).thinking_level as { default: string }).default =
422 'low'
423 expect(replicateChatFacts(explicit)?.reasoning).toEqual({
424 mode: 'effort',
425 mandatory: null,
426 efforts: ['none', 'low', 'high'],
427 })
428 })
429
430 it('reads off from the description, and an own list with no off as mandatory', () => {
431 // `effort` low…max: "'low' disables thinking for the fastest, cheapest
432 // responses."
433 const claude = replicateChatFacts(model('anthropic/claude-sonnet-5'))
434 expect(claude?.capabilities).toContain('reasoning_effort')
435 expect(claude?.reasoning).toEqual({
436 mode: 'effort',
437 mandatory: false,
438 efforts: ['low', 'medium', 'high', 'xhigh', 'max'],
439 })
440 expect(claude?.factSources?.reasoning?.path).toBe(
441 `${INPUT}/properties/effort`,
442 )
443
444 const effort = (description: string) => {
445 const row = model('anthropic/claude-sonnet-5')
446 ;(inputProperties(row).effort as { description: string }).description =
447 description
448 return replicateChatFacts(row)?.reasoning
449 }
450 // Reworded, or naming a level the enum does not list: the own list has
451 // no off value, so thinking cannot be turned off.
452 expect(effort('How much thinking Claude does.')?.mandatory).toBe(true)
453 expect(effort("'low' keeps thinking short.")?.mandatory).toBe(true)
454 expect(effort("'none' disables thinking.")?.mandatory).toBe(true)
455 expect(effort("Use 'low' to disable.")?.mandatory).toBe(false)
456
457 // `reasoning_effort` without `none`: this model's only control.
458 const gpt = model('openai/gpt-5.4')
459 const schemas = gpt.latest_version?.openapi_schema?.components
460 ?.schemas as Record<string, { enum?: Array<string> }>
461 schemas.reasoning_effort!.enum = ['low', 'medium', 'high']
462 expect(replicateChatFacts(gpt)?.reasoning).toEqual({
463 mode: 'effort',
464 mandatory: true,
465 efforts: ['low', 'medium', 'high'],
466 })
467
468 const dangling = model('openai/gpt-5.4')
469 delete (
470 dangling.latest_version!.openapi_schema!.components!.schemas as Record<
471 string,
472 unknown
473 >
474 ).reasoning_effort
475 expect(replicateChatFacts(dangling)?.reasoning).toBeUndefined()
476 })
477
478 it('reads a budget and a boolean switch from the model’s own fields', () => {
479 const withFields = (fields: Record<string, unknown>) => {
480 const row = model('meta/llama-4-maverick-instruct')
481 Object.assign(inputProperties(row), fields)
482 return replicateChatFacts(row)
483 }
484 // google/gemini-2.5-flash (2026-10-07).
485 const BUDGET = {
486 type: 'integer',
487 title: 'Thinking Budget',
488 maximum: 24576,
489 minimum: 0,
490 nullable: true,
491 description:
492 'Thinking budget for reasoning (0 to disable thinking, higher values allow more reasoning)',
493 }
494 const budget = withFields({ thinking_budget: BUDGET })
495 expect(budget?.reasoning).toEqual({ mode: 'budget', mandatory: false })
496 expect(budget?.factSources?.reasoning?.path).toBe(
497 `${INPUT}/properties/thinking_budget`,
498 )
499 expect(
500 withFields({
501 thinking_budget: { ...BUDGET, description: 'Thinking budget.' },
502 })?.reasoning,
503 ).toEqual({ mode: 'budget', mandatory: null })
504 expect(
505 withFields({ thinking_budget: { ...BUDGET, type: 'string' } })?.reasoning,
506 ).toBeUndefined()
507
508 // prunaai/gemma-4-26b-a4b-fast (2026-10-07).
509 const SWITCH = {
510 type: 'boolean',
511 title: 'Enable Thinking',
512 default: false,
513 description:
514 'Enable thinking mode (model reasons internally before answering)',
515 }
516 const toggle = withFields({ enable_thinking: SWITCH })
517 expect(toggle?.reasoning).toEqual({ mode: 'toggle', mandatory: false })
518 expect(toggle?.factSources?.reasoning?.path).toBe(
519 `${INPUT}/properties/enable_thinking`,
520 )
521 // Not a two-position switch: nothing is stored.
522 for (const field of [
523 { ...SWITCH, type: 'string' },
524 { ...SWITCH, enum: [true] },
525 ]) {
526 const got = withFields({ enable_thinking: field })
527 expect(got?.reasoning).toBeUndefined()
528 expect(got?.factSources?.reasoning).toBeUndefined()
529 }
530 // Two level fields, or a `thinking` enum that is a switch: not read.
531 const two = model('anthropic/claude-sonnet-5')
532 inputProperties(two).thinking_level = inputProperties(two).effort
533 expect(replicateChatFacts(two)?.reasoning).toBeUndefined()
534 const switched = model('deepseek-ai/deepseek-v3.1')
535 ;(
536 switched.latest_version!.openapi_schema!.components!.schemas as Record<
537 string,
538 { enum?: Array<string> }
539 >
540 ).thinking!.enum = ['enabled', 'disabled']
541 expect(replicateChatFacts(switched)?.reasoning).toBeUndefined()
542 })
543
544 it('binds a run route only for an official model', () => {
545 const facts = replicateChatFacts(model('prunaai/gpt-oss-120b-fast'))
546 expect(facts?.capabilities).toContain('max_tokens')
547 expect(facts?.schemaEndpointId).toBeUndefined()
548 })
549})
550
551describe('replicate per-model run routes', () => {
552 function stubFetch(spec: OpenApiDocument): () => void {
553 const original = globalThis.fetch
554 globalThis.fetch = ((url: string) => {
555 const body = String(url).endsWith('/openapi.json')
556 ? spec
557 : { next: null, results: MODELS }
558 return Promise.resolve(new Response(JSON.stringify(body)))
559 }) as typeof fetch
560 return () => {
561 globalThis.fetch = original
562 }
563 }
564
565 it('syncs each official language model with its own input schema', async () => {
566 const restore = stubFetch(SPEC)
567 try {
568 const fetched = await provider.fetchSpec({ REPLICATE_API_TOKEN: 'tok' })
569 const { endpoints, warnings } = classifyAndBundle(provider, fetched)
570 expect(warnings).toEqual([])
571 expect(endpoints.map((e) => [e.dbId, e.activity])).toEqual([
572 ['replicate/models/{model_owner}/{model_name}/predictions', 'image'],
573 ['replicate/models/meta/llama-4-maverick-instruct/predictions', 'chat'],
574 ['replicate/models/meta/llama-guard-4-12b/predictions', 'chat'],
575 ['replicate/models/deepseek-ai/deepseek-v3.1/predictions', 'chat'],
576 ['replicate/models/google/gemini-3-flash/predictions', 'chat'],
577 ['replicate/models/openai/gpt-5.4/predictions', 'chat'],
578 ['replicate/models/anthropic/claude-sonnet-5/predictions', 'chat'],
579 ['replicate/models/ibm-granite/granite-4.1-8b/predictions', 'chat'],
580 ])
581 // Every route a chat row binds is synced.
582 const synced = new Set(endpoints.map((e) => e.dbId))
583 for (const row of MODELS) {
584 const bound = replicateChatFacts(row)?.schemaEndpointId
585 if (bound) expect(synced.has(`replicate/${bound}`)).toBe(true)
586 }
587
588 const gpt = endpoints.find((e) => e.dbId.includes('gpt-5.4'))
589 expect(gpt?.source?.url).toBe(
590 'https://api.replicate.com/v1/models/openai/gpt-5.4',
591 )
592 const input = gpt?.input as {
593 required: Array<string>
594 properties: Record<string, unknown>
595 $defs: Record<string, { properties?: Record<string, unknown> }>
596 }
597 expect(input.required).toEqual(['input'])
598 expect(Object.keys(input.properties)).toContain('webhook')
599 expect(input.properties.input).toEqual({ $ref: '#/$defs/Input' })
600 expect(Object.keys(input.$defs.Input?.properties ?? {})).toContain(
601 'max_completion_tokens',
602 )
603 // gpt-5.4's schema is its own: no llama field leaks in.
604 expect(input.$defs.Input?.properties).not.toHaveProperty('top_k')
605 const output = gpt?.output as {
606 properties: Record<string, unknown>
607 $defs: Record<string, unknown>
608 }
609 expect(output.properties.output).toEqual({ $ref: '#/$defs/Output' })
610 expect(output.$defs.Output).toMatchObject({ type: 'array' })
611 } finally {
612 restore()
613 }
614 })
615
616 it('adds no route when the spec has no official run operation', async () => {
617 const reworded = structuredClone(SPEC)
618 const request = reworded.components?.schemas
619 ?.schemas_prediction_request as {
620 properties: Record<string, unknown>
621 }
622 delete request.properties.input
623 expect(replicateModelSpec(reworded, model('openai/gpt-5.4'))).toBeNull()
624 expect(replicateModelSpec({ paths: {} }, model('openai/gpt-5.4'))).toBe(
625 null,
626 )
627
628 const restore = stubFetch(reworded)
629 try {
630 const fetched = await provider.fetchSpec({ REPLICATE_API_TOKEN: 'tok' })
631 expect(fetched.specs).toHaveLength(1)
632 expect(fetched.warnings).toContain(
633 'replicate openai/gpt-5.4: no official run route in the spec',
634 )
635 } finally {
636 restore()
637 }
638 })
639})
640
641describe('replicate catalog walk', () => {
642 it('fails on a next link that leaves the models API', async () => {
643 const original = globalThis.fetch
644 globalThis.fetch = () =>
645 Promise.resolve(
646 new Response(
647 JSON.stringify({
648 next: 'https://example.com/v1/models',
649 results: [],
650 }),
651 ),
652 )
653 try {
654 await expect(
655 provider.listModels({ REPLICATE_API_TOKEN: 'tok' }),
656 ).rejects.toThrow('unexpected catalog page url')
657 } finally {
658 globalThis.fetch = original
659 }
660 })
661
662 describe('a 502 on a later page', () => {
663 const PAGE_2 = 'https://api.replicate.com/v1/models?cursor=abc'
664
665 beforeEach(() => {
666 vi.useFakeTimers()
667 })
668 afterEach(() => {
669 vi.unstubAllGlobals()
670 vi.useRealTimers()
671 })
672
673 function stubCatalog(page2: () => Response): ReturnType<typeof vi.fn> {
674 const fetchMock = vi.fn((url: string) => {
675 const href = String(url)
676 if (href === PAGE_2) return Promise.resolve(page2())
677 if (href.startsWith('https://api.replicate.com/v1/models')) {
678 return Promise.resolve(
679 new Response(JSON.stringify({ next: PAGE_2, results: [] })),
680 )
681 }
682 return Promise.resolve(new Response('', { status: 404 }))
683 })
684 vi.stubGlobal('fetch', fetchMock)
685 return fetchMock
686 }
687
688 async function flushed<T>(promise: Promise<T>): Promise<T> {
689 void promise.catch(() => undefined)
690 await vi.runAllTimersAsync()
691 return promise
692 }
693
694 it('retries the page and completes the walk', async () => {
695 let calls = 0
696 const fetchMock = stubCatalog(() =>
697 ++calls === 1
698 ? new Response('bad gateway', { status: 502 })
699 : new Response(
700 JSON.stringify({
701 next: null,
702 results: [model('openai/gpt-5.4')],
703 }),
704 ),
705 )
706 const { models } = await flushed(
707 provider.listModels({ REPLICATE_API_TOKEN: 'tok' }),
708 )
709 expect(models.map((m) => m.rawId)).toContain('openai/gpt-5.4')
710 expect(fetchMock.mock.calls.filter(([u]) => u === PAGE_2)).toHaveLength(2)
711 })
712
713 it('throws with the page URL when every attempt fails', async () => {
714 const fetchMock = stubCatalog(
715 () => new Response('bad gateway', { status: 502 }),
716 )
717 await expect(
718 flushed(provider.listModels({ REPLICATE_API_TOKEN: 'tok' })),
719 ).rejects.toThrow(`fetch failed after 3 attempts: ${PAGE_2} → 502`)
720 expect(fetchMock.mock.calls.filter(([u]) => u === PAGE_2)).toHaveLength(3)
721 })
722 })
723})
724
725describe('replicate listModels chat rows', () => {
726 it('classifies by schema and keeps the price source beside the facts', async () => {
727 const page = `<script>{"billingConfig": {"current_tiers": [{"criteria": [], "prices": [{"metric": "token_input_count", "price": "$2.50", "title": "per million input tokens", "type": "per-unit"}, {"metric": "token_output_count", "price": "$0.015", "title": "per thousand output tokens", "type": "per-unit"}]}]}, "modelName": "x"}</script>`
728 const original = globalThis.fetch
729 globalThis.fetch = ((url: string) => {
730 const href = String(url)
731 if (href.startsWith('https://api.replicate.com/')) {
732 return Promise.resolve(
733 new Response(JSON.stringify({ next: null, results: MODELS })),
734 )
735 }
736 // One official page answers 200 with an error page.
737 return Promise.resolve(
738 new Response(
739 href.endsWith('/claude-sonnet-5')
740 ? '<html>Just a moment</html>'
741 : page,
742 ),
743 )
744 }) as typeof fetch
745 try {
746 const { models } = await provider.listModels({
747 REPLICATE_API_TOKEN: 'tok',
748 })
749 const byId = new Map(models.map((m) => [m.rawId, m]))
750 expect(byId.get('alibaba/qwen-image-3')?.activity).not.toBe('chat')
751 expect(byId.get('alibaba/qwen-image-3')?.providerMetadata).toEqual({
752 visibility: 'public',
753 official: true,
754 })
755 const gpt = byId.get('openai/gpt-5.4')
756 expect(gpt?.activity).toBe('chat')
757 expect(gpt?.capabilities).toEqual(['max_tokens', 'reasoning_effort'])
758 expect(gpt?.pricing).toMatchObject({
759 tables: {
760 rate: { base: { input_tokens: 2.5e-6, output_tokens: 1.5e-5 } },
761 },
762 })
763 expect(gpt?.factSources?.pricing?.sourceUrl).toBe(
764 'https://replicate.com/openai/gpt-5.4',
765 )
766 expect(gpt?.factSources?.reasoning?.derivation).toBe('listing')
767
768 const errored = byId.get('anthropic/claude-sonnet-5')
769 expect(errored?.activity).toBe('chat')
770 expect(errored?.pricing).toBeUndefined()
771 expect(errored?.maxOutput).toBe(64000)
772 // Hardware-billed community model: no page fetch, no price.
773 expect(byId.get('prunaai/gpt-oss-120b-fast')?.pricing).toBeUndefined()
774 // An official model's owner names the maker; a community owner does not.
775 expect(errored?.upstream).toEqual({
776 providerNamespace: 'anthropic',
777 rawId: 'claude-sonnet-5',
778 source: {
779 derivation: 'listing',
780 sourceUrl: 'https://api.replicate.com/v1/models',
781 path: 'results[].owner (is_official)',
782 },
783 })
784 expect(byId.get('google/gemini-3-flash')?.upstream).toMatchObject({
785 providerNamespace: 'google',
786 rawId: 'gemini-3-flash',
787 })
788 expect(byId.get('prunaai/gpt-oss-120b-fast')?.upstream).toBeNull()
789 } finally {
790 globalThis.fetch = original
791 }
792 })
793
794 it('reads a context window and a missing output cap from the README', async () => {
795 const readme = [
796 '## Specs',
797 '',
798 '| | |',
799 '|---|---|',
800 '| **Context window** | 1,050,000 tokens |',
801 '| **Max output tokens** | 128,000 |',
802 ].join('\n')
803 const original = globalThis.fetch
804 globalThis.fetch = ((url: string) => {
805 const href = String(url)
806 if (href.endsWith('/readme')) {
807 return Promise.resolve(new Response(readme))
808 }
809 if (href.startsWith('https://api.replicate.com/')) {
810 return Promise.resolve(
811 new Response(JSON.stringify({ next: null, results: MODELS })),
812 )
813 }
814 return Promise.resolve(new Response('<html>no billing</html>'))
815 }) as typeof fetch
816 try {
817 const { models } = await provider.listModels({
818 REPLICATE_API_TOKEN: 'tok',
819 })
820 const gpt = models.find((row) => row.rawId === 'openai/gpt-5.4')
821 expect(gpt?.contextWindow).toBe(1_050_000)
822 expect(gpt?.maxOutput).toBe(128_000)
823 expect(gpt?.factSources?.contextWindow).toMatchObject({
824 derivation: 'docs-derived',
825 sourceUrl: 'https://api.replicate.com/v1/models/openai/gpt-5.4/readme',
826 path: 'context window',
827 })
828 expect(gpt?.factSources?.maxOutput?.path).toBe('max output tokens')
829 // The schema already states 64000. The README must not replace it.
830 const claude = models.find(
831 (row) => row.rawId === 'anthropic/claude-sonnet-5',
832 )
833 expect(claude?.maxOutput).toBe(64000)
834 expect(claude?.factSources?.maxOutput?.derivation).toBe('listing')
835 } finally {
836 globalThis.fetch = original
837 }
838 })
839})