Open History to see the last commit
1import { describe, expect, it } 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, never from the absence of none', () => {
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: unstated.
451 expect(effort('How much thinking Claude does.')?.mandatory).toBeNull()
452 expect(effort("'low' keeps thinking short.")?.mandatory).toBeNull()
453 expect(effort("'none' disables thinking.")?.mandatory).toBeNull()
454 expect(effort("Use 'low' to disable.")?.mandatory).toBe(false)
455
456 // `reasoning_effort` without `none`: levels, off unstated.
457 const gpt = model('openai/gpt-5.4')
458 const schemas = gpt.latest_version?.openapi_schema?.components
459 ?.schemas as Record<string, { enum?: Array<string> }>
460 schemas.reasoning_effort!.enum = ['low', 'medium', 'high']
461 expect(replicateChatFacts(gpt)?.reasoning).toEqual({
462 mode: 'effort',
463 mandatory: null,
464 efforts: ['low', 'medium', 'high'],
465 })
466
467 const dangling = model('openai/gpt-5.4')
468 delete (
469 dangling.latest_version?.openapi_schema?.components?.schemas as Record<
470 string,
471 unknown
472 >
473 ).reasoning_effort
474 expect(replicateChatFacts(dangling)?.reasoning).toBeUndefined()
475 })
476
477 it('reads a budget and a boolean switch from the model’s own fields', () => {
478 const withFields = (fields: Record<string, unknown>) => {
479 const row = model('meta/llama-4-maverick-instruct')
480 Object.assign(inputProperties(row), fields)
481 return replicateChatFacts(row)
482 }
483 // google/gemini-2.5-flash (2026-10-07).
484 const BUDGET = {
485 type: 'integer',
486 title: 'Thinking Budget',
487 maximum: 24576,
488 minimum: 0,
489 nullable: true,
490 description:
491 'Thinking budget for reasoning (0 to disable thinking, higher values allow more reasoning)',
492 }
493 const budget = withFields({ thinking_budget: BUDGET })
494 expect(budget?.reasoning).toEqual({ mode: 'budget', mandatory: false })
495 expect(budget?.factSources?.reasoning?.path).toBe(
496 `${INPUT}/properties/thinking_budget`,
497 )
498 expect(
499 withFields({
500 thinking_budget: { ...BUDGET, description: 'Thinking budget.' },
501 })?.reasoning,
502 ).toEqual({ mode: 'budget', mandatory: null })
503 expect(
504 withFields({ thinking_budget: { ...BUDGET, type: 'string' } })?.reasoning,
505 ).toBeUndefined()
506
507 // prunaai/gemma-4-26b-a4b-fast (2026-10-07).
508 const SWITCH = {
509 type: 'boolean',
510 title: 'Enable Thinking',
511 default: false,
512 description:
513 'Enable thinking mode (model reasons internally before answering)',
514 }
515 const toggle = withFields({ enable_thinking: SWITCH })
516 expect(toggle?.reasoning).toEqual({ mode: 'toggle', mandatory: false })
517 expect(toggle?.factSources?.reasoning?.path).toBe(
518 `${INPUT}/properties/enable_thinking`,
519 )
520 // Not a two-position switch: nothing is stored.
521 for (const field of [
522 { ...SWITCH, type: 'string' },
523 { ...SWITCH, enum: [true] },
524 ]) {
525 const got = withFields({ enable_thinking: field })
526 expect(got?.reasoning).toBeUndefined()
527 expect(got?.factSources?.reasoning).toBeUndefined()
528 }
529 // Two level fields, or a `thinking` enum that is a switch: not read.
530 const two = model('anthropic/claude-sonnet-5')
531 inputProperties(two).thinking_level = inputProperties(two).effort
532 expect(replicateChatFacts(two)?.reasoning).toBeUndefined()
533 const switched = model('deepseek-ai/deepseek-v3.1')
534 ;(
535 switched.latest_version?.openapi_schema?.components?.schemas as Record<
536 string,
537 { enum?: Array<string> }
538 >
539 ).thinking!.enum = ['enabled', 'disabled']
540 expect(replicateChatFacts(switched)?.reasoning).toBeUndefined()
541 })
542
543 it('binds a run route only for an official model', () => {
544 const facts = replicateChatFacts(model('prunaai/gpt-oss-120b-fast'))
545 expect(facts?.capabilities).toContain('max_tokens')
546 expect(facts?.schemaEndpointId).toBeUndefined()
547 })
548})
549
550describe('replicate per-model run routes', () => {
551 function stubFetch(spec: OpenApiDocument): () => void {
552 const original = globalThis.fetch
553 globalThis.fetch = ((url: string) => {
554 const body = String(url).endsWith('/openapi.json')
555 ? spec
556 : { next: null, results: MODELS }
557 return Promise.resolve(new Response(JSON.stringify(body)))
558 }) as typeof fetch
559 return () => {
560 globalThis.fetch = original
561 }
562 }
563
564 it('syncs each official language model with its own input schema', async () => {
565 const restore = stubFetch(SPEC)
566 try {
567 const fetched = await provider.fetchSpec({ REPLICATE_API_TOKEN: 'tok' })
568 const { endpoints, warnings } = classifyAndBundle(provider, fetched)
569 expect(warnings).toEqual([])
570 expect(endpoints.map((e) => [e.dbId, e.activity])).toEqual([
571 ['replicate/models/{model_owner}/{model_name}/predictions', 'image'],
572 ['replicate/models/meta/llama-4-maverick-instruct/predictions', 'chat'],
573 ['replicate/models/meta/llama-guard-4-12b/predictions', 'chat'],
574 ['replicate/models/deepseek-ai/deepseek-v3.1/predictions', 'chat'],
575 ['replicate/models/google/gemini-3-flash/predictions', 'chat'],
576 ['replicate/models/openai/gpt-5.4/predictions', 'chat'],
577 ['replicate/models/anthropic/claude-sonnet-5/predictions', 'chat'],
578 ['replicate/models/ibm-granite/granite-4.1-8b/predictions', 'chat'],
579 ])
580 // Every route a chat row binds is synced.
581 const synced = new Set(endpoints.map((e) => e.dbId))
582 for (const row of MODELS) {
583 const bound = replicateChatFacts(row)?.schemaEndpointId
584 if (bound) expect(synced.has(`replicate/${bound}`)).toBe(true)
585 }
586
587 const gpt = endpoints.find((e) => e.dbId.includes('gpt-5.4'))
588 expect(gpt?.source?.url).toBe(
589 'https://api.replicate.com/v1/models/openai/gpt-5.4',
590 )
591 const input = gpt?.input as {
592 required: Array<string>
593 properties: Record<string, unknown>
594 $defs: Record<string, { properties?: Record<string, unknown> }>
595 }
596 expect(input.required).toEqual(['input'])
597 expect(Object.keys(input.properties)).toContain('webhook')
598 expect(input.properties.input).toEqual({ $ref: '#/$defs/Input' })
599 expect(Object.keys(input.$defs.Input?.properties ?? {})).toContain(
600 'max_completion_tokens',
601 )
602 // gpt-5.4's schema is its own: no llama field leaks in.
603 expect(input.$defs.Input?.properties).not.toHaveProperty('top_k')
604 const output = gpt?.output as {
605 properties: Record<string, unknown>
606 $defs: Record<string, unknown>
607 }
608 expect(output.properties.output).toEqual({ $ref: '#/$defs/Output' })
609 expect(output.$defs.Output).toMatchObject({ type: 'array' })
610 } finally {
611 restore()
612 }
613 })
614
615 it('adds no route when the spec has no official run operation', async () => {
616 const reworded = structuredClone(SPEC)
617 const request = reworded.components?.schemas
618 ?.schemas_prediction_request as {
619 properties: Record<string, unknown>
620 }
621 delete request.properties.input
622 expect(replicateModelSpec(reworded, model('openai/gpt-5.4'))).toBeNull()
623 expect(replicateModelSpec({ paths: {} }, model('openai/gpt-5.4'))).toBe(
624 null,
625 )
626
627 const restore = stubFetch(reworded)
628 try {
629 const fetched = await provider.fetchSpec({ REPLICATE_API_TOKEN: 'tok' })
630 expect(fetched.specs).toHaveLength(1)
631 expect(fetched.warnings).toContain(
632 'replicate openai/gpt-5.4: no official run route in the spec',
633 )
634 } finally {
635 restore()
636 }
637 })
638})
639
640describe('replicate catalog walk', () => {
641 it('fails on a next link that leaves the models API', async () => {
642 const original = globalThis.fetch
643 globalThis.fetch = () =>
644 Promise.resolve(
645 new Response(
646 JSON.stringify({
647 next: 'https://example.com/v1/models',
648 results: [],
649 }),
650 ),
651 )
652 try {
653 await expect(
654 provider.listModels({ REPLICATE_API_TOKEN: 'tok' }),
655 ).rejects.toThrow('unexpected catalog page url')
656 } finally {
657 globalThis.fetch = original
658 }
659 })
660})
661
662describe('replicate listModels chat rows', () => {
663 it('classifies by schema and keeps the price source beside the facts', async () => {
664 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>`
665 const original = globalThis.fetch
666 globalThis.fetch = ((url: string) => {
667 const href = String(url)
668 if (href.startsWith('https://api.replicate.com/')) {
669 return Promise.resolve(
670 new Response(JSON.stringify({ next: null, results: MODELS })),
671 )
672 }
673 // One official page answers 200 with an error page.
674 return Promise.resolve(
675 new Response(
676 href.endsWith('/claude-sonnet-5')
677 ? '<html>Just a moment</html>'
678 : page,
679 ),
680 )
681 }) as typeof fetch
682 try {
683 const { models } = await provider.listModels({
684 REPLICATE_API_TOKEN: 'tok',
685 })
686 const byId = new Map(models.map((m) => [m.rawId, m]))
687 expect(byId.get('alibaba/qwen-image-3')?.activity).not.toBe('chat')
688 expect(byId.get('alibaba/qwen-image-3')?.providerMetadata).toEqual({
689 visibility: 'public',
690 official: true,
691 })
692 const gpt = byId.get('openai/gpt-5.4')
693 expect(gpt?.activity).toBe('chat')
694 expect(gpt?.capabilities).toEqual(['max_tokens', 'reasoning_effort'])
695 expect(gpt?.pricing).toMatchObject({
696 tables: {
697 rate: { base: { input_tokens: 2.5e-6, output_tokens: 1.5e-5 } },
698 },
699 })
700 expect(gpt?.factSources?.pricing?.sourceUrl).toBe(
701 'https://replicate.com/openai/gpt-5.4',
702 )
703 expect(gpt?.factSources?.reasoning?.derivation).toBe('listing')
704
705 const errored = byId.get('anthropic/claude-sonnet-5')
706 expect(errored?.activity).toBe('chat')
707 expect(errored?.pricing).toBeUndefined()
708 expect(errored?.maxOutput).toBe(64000)
709 // Hardware-billed community model: no page fetch, no price.
710 expect(byId.get('prunaai/gpt-oss-120b-fast')?.pricing).toBeUndefined()
711 } finally {
712 globalThis.fetch = original
713 }
714 })
715
716 it('reads a context window and a missing output cap from the README', async () => {
717 const readme = [
718 '## Specs',
719 '',
720 '| | |',
721 '|---|---|',
722 '| **Context window** | 1,050,000 tokens |',
723 '| **Max output tokens** | 128,000 |',
724 ].join('\n')
725 const original = globalThis.fetch
726 globalThis.fetch = ((url: string) => {
727 const href = String(url)
728 if (href.endsWith('/readme')) {
729 return Promise.resolve(new Response(readme))
730 }
731 if (href.startsWith('https://api.replicate.com/')) {
732 return Promise.resolve(
733 new Response(JSON.stringify({ next: null, results: MODELS })),
734 )
735 }
736 return Promise.resolve(new Response('<html>no billing</html>'))
737 }) as typeof fetch
738 try {
739 const { models } = await provider.listModels({
740 REPLICATE_API_TOKEN: 'tok',
741 })
742 const gpt = models.find((row) => row.rawId === 'openai/gpt-5.4')
743 expect(gpt?.contextWindow).toBe(1_050_000)
744 expect(gpt?.maxOutput).toBe(128_000)
745 expect(gpt?.factSources?.contextWindow).toMatchObject({
746 derivation: 'docs-derived',
747 sourceUrl: 'https://api.replicate.com/v1/models/openai/gpt-5.4/readme',
748 path: 'context window',
749 })
750 expect(gpt?.factSources?.maxOutput?.path).toBe('max output tokens')
751 // The schema already states 64000. The README must not replace it.
752 const claude = models.find(
753 (row) => row.rawId === 'anthropic/claude-sonnet-5',
754 )
755 expect(claude?.maxOutput).toBe(64000)
756 expect(claude?.factSources?.maxOutput?.derivation).toBe('listing')
757 } finally {
758 globalThis.fetch = original
759 }
760 })
761})