Open History to see the last commit
1import { readFileSync } from 'node:fs'
2
3import { describe, expect, it } from 'vitest'
4
5import {
6 MISTRAL_WEBSEARCH_GUIDE,
7 mistralModelPage,
8 tip,
9} from '../fixtures/mistral-model-page.ts'
10import { mistralAliasFacts, provider } from './mistral.ts'
11import { MISTRAL_DEPRECATIONS_URL } from '../deprecations.ts'
12import {
13 MISTRAL_WEBSEARCH_URL,
14 mistralSummaryMaker,
15 parseMistralMakers,
16 parseMistralMarkdownReleaseDate,
17} from '../mistral-pricing.ts'
18import { MISTRAL_REASONING_URL } from '../reasoning-config.ts'
19
20const MODELS_PAGE = readFileSync(
21 new URL('../fixtures/mistral-models.md.txt', import.meta.url),
22 'utf8',
23)
24// https://docs.mistral.ai/models/mistral-small-4-0-26-03.md, 2026-11-21.
25const SMALL_4_MARKDOWN = readFileSync(
26 new URL('../fixtures/mistral-small-4-0-26-03.md.txt', import.meta.url),
27 'utf8',
28)
29
30describe('mistral classify', () => {
31 it('maps generation paths to the claimed activities', () => {
32 expect(provider.classify('/v1/chat/completions', {})).toBe('chat')
33 expect(provider.classify('/v1/fim/completions', {})).toBe('chat')
34 expect(provider.classify('/v1/agents/completions', {})).toBe('chat')
35 expect(provider.classify('/v1/embeddings', {})).toBe('embeddings')
36 expect(provider.classify('/v1/moderations', {})).toBe('moderation')
37 expect(provider.classify('/v1/chat/moderations', {})).toBe('moderation')
38 expect(provider.classify('/v1/audio/transcriptions', {})).toBe('audio')
39 expect(provider.classify('/v1/audio/transcriptions#stream', {})).toBe(
40 'audio',
41 )
42 expect(provider.classify('/v1/audio/speech', {})).toBe('audio')
43 })
44
45 it('drops platform, admin, files, fine-tune, batch, and classifiers that are not moderation', () => {
46 expect(provider.classify('/v1/files', {})).toBeNull()
47 expect(
48 provider.classify('/v1/fine_tuning/models/{model_id}', {}),
49 ).toBeNull()
50 expect(provider.classify('/v1/batch/jobs', {})).toBeNull()
51 expect(provider.classify('/v1/admin/users', {})).toBeNull()
52 expect(provider.classify('/v1/agents', {})).toBeNull()
53 expect(provider.classify('/v1/conversations', {})).toBeNull()
54 expect(provider.classify('/v1/ocr', {})).toBeNull()
55 expect(provider.classify('/v1/classifications', {})).toBeNull()
56 expect(provider.classify('/v1/chat/classifications', {})).toBeNull()
57 expect(provider.classify('/v1/models', {})).toBeNull()
58 })
59})
60
61describe('mistral listModels', () => {
62 it('skips with an empty catalog when MISTRAL_API_KEY is absent', async () => {
63 const { models, skipped } = await provider.listModels({})
64 expect(models).toEqual([])
65 expect(skipped).toBe('mistral: MISTRAL_API_KEY not set — skipped')
66 })
67
68 it('maps live rows and sends the bearer key', async () => {
69 const original = globalThis.fetch
70 const calls: Array<{ url: string; auth: string | null }> = []
71 globalThis.fetch = ((url: string, init?: RequestInit) => {
72 const href = String(url)
73 calls.push({
74 url: href,
75 auth: new Headers(init?.headers).get('authorization'),
76 })
77 if (href === MISTRAL_DEPRECATIONS_URL) {
78 return Promise.resolve(new Response(MODELS_PAGE))
79 }
80 // Docs stay off the network. A live pricing table plus one page
81 // per slug blows the 5s test limit once missing ids pull markdown.
82 if (!href.startsWith('https://api.mistral.ai/')) {
83 return Promise.resolve(new Response('not found', { status: 404 }))
84 }
85 return Promise.resolve(
86 new Response(
87 JSON.stringify({
88 object: 'list',
89 data: [
90 { id: 'mistral-small-latest', created: 1_700_000_000 },
91 { id: 'mistral-embed' },
92 ],
93 }),
94 ),
95 )
96 }) as typeof fetch
97 try {
98 const { models, skipped, deprecations } = await provider.listModels({
99 MISTRAL_API_KEY: 'mistral-test',
100 })
101 expect(skipped).toBeUndefined()
102 expect(
103 deprecations?.find((entry) => entry.rawId === 'pixtral-12b-2409')
104 ?.replacedBy,
105 ).toEqual(['ministral-14b-2512'])
106 expect(calls[0]?.url).toBe('https://api.mistral.ai/v1/models')
107 expect(calls[0]?.auth).toBe('Bearer mistral-test')
108 expect(
109 models.map(
110 ({
111 pricing: _pricing,
112 factSources: _sources,
113 reasoning: _reasoning,
114 modalities: _modalities,
115 serverTools: _tools,
116 maxOutput: _maxOutput,
117 requestMap: _requestMap,
118 absent: _absent,
119 ...rest
120 }) => rest,
121 ),
122 ).toEqual([
123 // `created` is the request time on every row (#708), not a date.
124 // Neither id is in the overview's API name column: no maker fact.
125 { rawId: 'mistral-small-latest', releasedAt: null, activity: null },
126 { rawId: 'mistral-embed', releasedAt: null, activity: 'embeddings' },
127 ])
128 } finally {
129 globalThis.fetch = original
130 }
131 })
132})
133
134describe('mistral listModels modalities', () => {
135 it('puts the modalities a model page states on the rows it names', async () => {
136 const pages: Record<string, string> = {
137 'https://api.mistral.ai/v1/models': JSON.stringify({
138 data: [
139 {
140 id: 'mistral-small-latest',
141 capabilities: { completion_chat: true },
142 aliases: ['mistral-vibe-cli-fast'],
143 },
144 {
145 id: 'mistral-vibe-cli-fast',
146 capabilities: { completion_chat: true },
147 aliases: ['mistral-small-latest'],
148 },
149 { id: 'mistral-unpriced', capabilities: { completion_chat: true } },
150 ],
151 }),
152 'https://docs.mistral.ai/inference/pricing': `<h2>Flagship models</h2>
153<p>Prices /M Tokens</p>
154<table>
155<tr><td><a href="/models/mistral-small-4-0-26-03">Small</a></td><td>$0.1</td><td>—</td><td>$0.3</td></tr>
156</table>`,
157 'https://docs.mistral.ai/resources/changelogs': '',
158 [MISTRAL_WEBSEARCH_URL]: MISTRAL_WEBSEARCH_GUIDE,
159 'https://docs.mistral.ai/models/mistral-small-4-0-26-03':
160 mistralModelPage(
161 ['mistral-small-2603', 'mistral-small-latest'],
162 [
163 [
164 tip('Text input'),
165 tip('Image input'),
166 tip('Reasoning output'),
167 tip('Text output'),
168 ],
169 ],
170 ),
171 'https://docs.mistral.ai/models/mistral-small-4-0-26-03.md':
172 SMALL_4_MARKDOWN,
173 [MISTRAL_REASONING_URL]:
174 '- `mistral-small-latest`: Supports adjustable reasoning via the `reasoning_effort` parameter.',
175 'https://docs.mistral.ai/models':
176 '<a href="/models/not-a-listed-id">x</a>',
177 'https://docs.mistral.ai/models.md':
178 '| [Nope](/models/not-a-listed-id) | `not-a-listed-id` | GA |',
179 'https://docs.mistral.ai/openapi.yaml': `components:
180 schemas:
181 ChatCompletionRequest:
182 additionalProperties: false
183 properties:
184 max_tokens: { type: integer }
185 reasoning_effort: { type: string }
186 messages:
187 items:
188 discriminator:
189 propertyName: role
190 mapping:
191 system: '#/components/schemas/SystemMessage'
192 user: '#/components/schemas/UserMessage'
193 assistant: '#/components/schemas/AssistantMessage'
194 tool: '#/components/schemas/ToolMessage'
195`,
196 }
197 const original = globalThis.fetch
198 globalThis.fetch = ((url: string) => {
199 const body = pages[String(url)]
200 return Promise.resolve(
201 body === undefined
202 ? new Response('not found', { status: 404 })
203 : new Response(body),
204 )
205 }) as typeof fetch
206 try {
207 const { models } = await provider.listModels({ MISTRAL_API_KEY: 'k' })
208 const [small, vibe, unpriced] = models
209 expect(small?.modalities).toEqual({
210 input: ['text', 'image'],
211 output: ['text'],
212 })
213 expect(small?.factSources?.modalities).toMatchObject({
214 derivation: 'docs-derived',
215 sourceUrl: 'https://docs.mistral.ai/models/mistral-small-4-0-26-03',
216 path: 'modalities',
217 })
218 expect(small?.pricing).toBeTruthy()
219 expect(small?.requestMap).toMatchObject({
220 maxTokensField: 'max_tokens',
221 developerRole: false,
222 reasoningEffort: true,
223 thinking: { on: { reasoning_effort: 'high' }, off: null, levels: null },
224 })
225 expect(small?.factSources?.requestMap).toMatchObject({
226 derivation: 'docs-derived',
227 sourceUrl: 'https://docs.mistral.ai/openapi.yaml',
228 })
229 // The page names only small-latest. The listing says vibe is that model.
230 expect(vibe?.modalities).toEqual(small?.modalities)
231 expect(vibe?.pricing).toEqual(small?.pricing)
232 expect(vibe?.factSources?.modalities?.sourceUrl).toBe(
233 'https://docs.mistral.ai/models/mistral-small-4-0-26-03',
234 )
235 // The markdown twin's `Release date: 2026-03-16` (#708).
236 expect(small?.releasedAt).toBe(Date.UTC(2026, 2, 16) / 1000)
237 expect(small?.factSources?.releasedAt).toMatchObject({
238 derivation: 'docs-derived',
239 sourceUrl: 'https://docs.mistral.ai/models/mistral-small-4-0-26-03.md',
240 path: 'Release date',
241 })
242 expect(vibe?.releasedAt).toBe(small?.releasedAt)
243 expect(unpriced?.releasedAt).toBeNull()
244 // No page names this id: unknown, not a guess, and not a cleared price.
245 expect(unpriced?.modalities).toBeUndefined()
246 expect(unpriced?.factSources?.modalities).toBeUndefined()
247 expect(unpriced?.absent).toBeUndefined()
248 } finally {
249 globalThis.fetch = original
250 }
251 })
252})
253
254describe('mistral listModels release dates', () => {
255 it('lets the listing alias settle an id two pages date differently', async () => {
256 const page = (ids: Array<string>) =>
257 mistralModelPage(ids, [[tip('Text input'), tip('Audio output')]])
258 const pages: Record<string, string> = {
259 'https://api.mistral.ai/v1/models': JSON.stringify({
260 data: [
261 { id: 'voxtral-mini-tts-2603', aliases: ['voxtral-mini-tts-latest'] },
262 { id: 'voxtral-mini-tts-latest', aliases: ['voxtral-mini-tts-2603'] },
263 { id: 'voxtral-mini-tts-3-0' },
264 { id: 'tts-orphan' },
265 ],
266 }),
267 'https://docs.mistral.ai/inference/pricing': `<h2>Audio models</h2>
268<p>Prices /M Chars</p>
269<table>
270<tr><td><a href="/models/voxtral-tts-26-03">TTS</a></td><td>$16</td></tr>
271<tr><td><a href="/models/voxtral-mini-tts-3-0">TTS 3</a></td><td>$16</td></tr>
272</table>`,
273 'https://docs.mistral.ai/resources/changelogs': '',
274 [MISTRAL_WEBSEARCH_URL]: MISTRAL_WEBSEARCH_GUIDE,
275 // Both pages name `-latest` and `tts-orphan`, with different dates.
276 'https://docs.mistral.ai/models/voxtral-tts-26-03': page([
277 'voxtral-mini-tts-2603',
278 'voxtral-mini-tts-latest',
279 'tts-orphan',
280 ]),
281 'https://docs.mistral.ai/models/voxtral-tts-26-03.md':
282 '- Release date: 2026-03-23\n',
283 'https://docs.mistral.ai/models/voxtral-mini-tts-3-0': page([
284 'voxtral-mini-tts-3-0',
285 'voxtral-mini-tts-latest',
286 'tts-orphan',
287 ]),
288 'https://docs.mistral.ai/models/voxtral-mini-tts-3-0.md':
289 '- Release date: 2026-10-20\n',
290 }
291 const original = globalThis.fetch
292 globalThis.fetch = ((url: string) => {
293 const body = pages[String(url)]
294 return Promise.resolve(
295 body === undefined
296 ? new Response('not found', { status: 404 })
297 : new Response(body),
298 )
299 }) as typeof fetch
300 try {
301 const { models } = await provider.listModels({ MISTRAL_API_KEY: 'k' })
302 const byId = new Map(models.map((model) => [model.rawId, model]))
303 const latest = byId.get('voxtral-mini-tts-latest')
304 // The listing says `-latest` is the 2603 snapshot: its page's date.
305 expect(latest?.releasedAt).toBe(Date.UTC(2026, 2, 23) / 1000)
306 expect(latest?.factSources?.releasedAt?.sourceUrl).toBe(
307 'https://docs.mistral.ai/models/voxtral-tts-26-03.md',
308 )
309 expect(byId.get('voxtral-mini-tts-3-0')?.releasedAt).toBe(
310 Date.UTC(2026, 9, 20) / 1000,
311 )
312 // Same page conflict, no mutual alias: no date.
313 const orphan = byId.get('tts-orphan')
314 expect(orphan?.releasedAt).toBeNull()
315 expect(orphan?.factSources?.releasedAt).toBeUndefined()
316 } finally {
317 globalThis.fetch = original
318 }
319 })
320})
321
322describe('parseMistralMarkdownReleaseDate', () => {
323 it('reads the page date, null for a page with none, throws on junk', () => {
324 expect(parseMistralMarkdownReleaseDate(SMALL_4_MARKDOWN)).toBe(
325 Date.UTC(2026, 2, 16) / 1000,
326 )
327 // Timestral pages state no release date.
328 expect(parseMistralMarkdownReleaseDate('- Version: 1.0\n')).toBeNull()
329 expect(() =>
330 parseMistralMarkdownReleaseDate('- Release date: March 2026\n'),
331 ).toThrow(/release date/)
332 expect(() =>
333 parseMistralMarkdownReleaseDate('- Release date: 2026-02-30\n'),
334 ).toThrow(/release date/)
335 })
336})
337
338describe('mistral listModels docs failures', () => {
339 it('keeps stored facts and reports the pages when the docs 404', async () => {
340 const original = globalThis.fetch
341 globalThis.fetch = ((url: string) => {
342 const href = String(url)
343 if (href === 'https://api.mistral.ai/v1/models') {
344 return Promise.resolve(
345 new Response(
346 JSON.stringify({
347 data: [
348 {
349 id: 'mistral-small-latest',
350 capabilities: { completion_chat: true },
351 },
352 ],
353 }),
354 ),
355 )
356 }
357 if (href === 'https://docs.mistral.ai/openapi.yaml') {
358 return Promise.resolve(
359 new Response(`components:
360 schemas:
361 ChatCompletionRequest:
362 properties:
363 max_tokens: { type: integer }
364`),
365 )
366 }
367 return Promise.resolve(new Response('not found', { status: 404 }))
368 }) as typeof fetch
369 try {
370 const { models, docsFailures } = await provider.listModels({
371 MISTRAL_API_KEY: 'k',
372 })
373 expect(models.map((model) => model.rawId)).toEqual([
374 'mistral-small-latest',
375 ])
376 expect(models[0]?.absent).toMatchObject({
377 pricing: 'unavailable',
378 serverTools: 'unavailable',
379 modalities: 'unavailable',
380 maxOutput: 'unavailable',
381 reasoning: 'unavailable',
382 requestMap: 'unavailable',
383 maker: 'unavailable',
384 })
385 expect(models[0]?.requestMap).toBeUndefined()
386 expect(docsFailures?.first.map((failure) => failure.source)).toEqual(
387 expect.arrayContaining([
388 'https://docs.mistral.ai/inference/pricing',
389 MISTRAL_REASONING_URL,
390 `${MISTRAL_DEPRECATIONS_URL}#makers`,
391 ]),
392 )
393 } finally {
394 globalThis.fetch = original
395 }
396 })
397})
398
399describe('mistral fetchSpec', () => {
400 it('loads the public OpenAPI document without a key', async () => {
401 const fixture = JSON.stringify({
402 openapi: '3.1.0',
403 info: { title: 'Mistral AI API', version: '1.0.0' },
404 paths: {
405 '/v1/chat/completions': { post: { summary: 'Chat Completion' } },
406 },
407 })
408 const original = globalThis.fetch
409 const urls: Array<string> = []
410 globalThis.fetch = ((url: string) => {
411 urls.push(String(url))
412 return Promise.resolve(new Response(fixture))
413 }) as typeof fetch
414 try {
415 const fetched = await provider.fetchSpec({})
416 expect(urls).toEqual(['https://docs.mistral.ai/openapi.yaml'])
417 expect(fetched.outputStrategy).toBe('post-200')
418 expect(fetched.specs).toHaveLength(1)
419 expect(fetched.specs[0]?.info?.title).toBe('Mistral AI API')
420 expect(fetched.sources[0]?.url).toBe(
421 'https://docs.mistral.ai/openapi.yaml',
422 )
423 expect(fetched.sources[0]?.hash).toMatch(/^[0-9a-f]{64}$/)
424 } finally {
425 globalThis.fetch = original
426 }
427 })
428})
429
430describe('mistral provider metadata', () => {
431 it('exports the seed fields required for auto-registration', () => {
432 expect(provider.id).toBe('mistral')
433 expect(provider.displayName).toBe('Mistral')
434 expect(provider.authEnvVar).toBe('MISTRAL_API_KEY')
435 expect(provider.defaultDerivation).toBe('upstream-spec')
436 expect(provider.specSourceUrl).toBe('https://docs.mistral.ai/openapi.yaml')
437 expect(provider.modelsEndpoint).toBe('https://api.mistral.ai/v1/models')
438 })
439})
440
441describe('mistral alias links (#709)', () => {
442 // Trimmed `GET /v1/models` (id, name, aliases), 2026-11-21.
443 const listing = JSON.parse(
444 readFileSync(
445 new URL('../fixtures/mistral-models-aliases.json', import.meta.url),
446 'utf8',
447 ),
448 ) as { data: Array<{ id: string; name: string; aliases: Array<string> }> }
449 const facts = new Map(
450 listing.data.map((row) => [row.id, mistralAliasFacts(row)]),
451 )
452
453 it('lists the stated group and never reads name as a target', () => {
454 // The listing's name is `mistral-large-4` on every member: not a target.
455 const large = facts.get('mistral-large-latest')
456 expect(large?.aliasOf).toBeNull()
457 expect(large?.aliases).toEqual(['mistral-large-4', 'mistral-large-4-0'])
458 expect(large?.factSources).toEqual({
459 aliases: {
460 derivation: 'listing',
461 sourceUrl: 'https://api.mistral.ai/v1/models',
462 path: 'aliases',
463 },
464 aliasOf: {
465 derivation: 'listing',
466 sourceUrl: 'https://api.mistral.ai/v1/models',
467 path: 'unstated',
468 },
469 })
470 // A dated snapshot does not resolve to a moving alias.
471 const dated = facts.get('mistral-medium-2604')
472 expect(dated?.aliasOf).toBeNull()
473 expect(dated?.aliases).toContain('mistral-medium-latest')
474 })
475
476 it('leaves a row with no aliases bare', () => {
477 expect(facts.get('mistral-large-2512')).toEqual({})
478 })
479
480 it('links every -latest row through its group, target unstated', () => {
481 const latest = [...facts].filter(([id]) => id.endsWith('-latest'))
482 expect(latest).toHaveLength(18)
483 for (const [, row] of latest) {
484 expect(row.aliases?.length).toBeGreaterThan(0)
485 expect(row.aliasOf).toBeNull()
486 expect(row.factSources?.aliasOf?.path).toBe('unstated')
487 }
488 })
489})
490
491describe('mistral maker (#710)', () => {
492 const OVERVIEW = readFileSync(
493 new URL('../fixtures/mistral-models-makers.md.txt', import.meta.url),
494 'utf8',
495 )
496
497 it('reads "third-party ... model from X" off the overview (2026-11-21)', () => {
498 const { makers, named } = parseMistralMakers(OVERVIEW)
499 expect(Object.fromEntries(makers)).toEqual({
500 'zai-glm-5-3-flash': 'Z.ai',
501 'deepseek-v4-1-flash-1017': 'DeepSeek',
502 'zai-glm-5-3': 'Z.ai',
503 'zai-glm-5-2': 'Z.ai',
504 })
505 expect(named.has('mistral-large-4')).toBe(true)
506 expect(named.has('mistral-large-2512')).toBe(true)
507 expect(named.has('mistral-large-latest')).toBe(false)
508 })
509
510 it('ends the name at the sentence and keeps dotted names whole', () => {
511 expect(mistralSummaryMaker('A third-party model from xAI.')).toBe('xAI')
512 expect(mistralSummaryMaker('A third-party model from 01.AI.')).toBe('01.AI')
513 expect(
514 mistralSummaryMaker('A third-party model from Z.ai. Great for coding.'),
515 ).toBe('Z.ai')
516 expect(
517 mistralSummaryMaker(
518 'A third-party open weight text model from Z.ai with a 1M-token context window.',
519 ),
520 ).toBe('Z.ai')
521 expect(mistralSummaryMaker('A third-party model from Alibaba Cloud')).toBe(
522 'Alibaba Cloud',
523 )
524 expect(mistralSummaryMaker('Mistral Small 4.')).toBeNull()
525 })
526
527 it('throws on any other third-party wording', () => {
528 for (const summary of [
529 'A third-party model built by Z.ai.',
530 'A third-party model from the Qwen team at Alibaba Cloud.',
531 'Our flagship model. Beats the third-party model from DeepSeek on coding.',
532 ]) {
533 expect(() => mistralSummaryMaker(summary), summary).toThrow(
534 /unreadable third-party summary/,
535 )
536 }
537 })
538
539 it('throws when the overview table is gone', () => {
540 expect(() => parseMistralMakers('# Models Overview\n')).toThrow(
541 /parsed 0 API slugs/,
542 )
543 })
544
545 it('names the maker on every alias, says listed Mistral rows state none, says nothing of unlisted ids', async () => {
546 const original = globalThis.fetch
547 const group = ['zai-glm-5-3', 'zai-glm-5', 'zai-glm-latest']
548 globalThis.fetch = ((url: string) => {
549 const href = String(url)
550 if (href === MISTRAL_DEPRECATIONS_URL) {
551 return Promise.resolve(new Response(OVERVIEW))
552 }
553 if (href !== 'https://api.mistral.ai/v1/models') {
554 return Promise.resolve(new Response('not found', { status: 404 }))
555 }
556 return Promise.resolve(
557 new Response(
558 JSON.stringify({
559 data: [
560 ...group.map((id) => ({
561 id,
562 aliases: group.filter((other) => other !== id),
563 })),
564 { id: 'glm-5-2', aliases: ['zai-glm-5-2'] },
565 { id: 'zai-glm-5-2', aliases: ['glm-5-2'] },
566 { id: 'mistral-large-4', aliases: ['mistral-large-latest'] },
567 { id: 'mistral-large-latest', aliases: ['mistral-large-4'] },
568 { id: 'labs-unlisted' },
569 ],
570 }),
571 ),
572 )
573 }) as typeof fetch
574 try {
575 const { models } = await provider.listModels({ MISTRAL_API_KEY: 'k' })
576 const makers = Object.fromEntries(
577 models.map((model) => [
578 model.rawId,
579 [model.maker, model.factSources?.maker?.path],
580 ]),
581 )
582 expect(makers).toEqual({
583 'zai-glm-5-3': ['Z.ai', 'Summary'],
584 'zai-glm-5': ['Z.ai', 'Summary'],
585 'zai-glm-latest': ['Z.ai', 'Summary'],
586 'glm-5-2': ['Z.ai', 'Summary'],
587 'zai-glm-5-2': ['Z.ai', 'Summary'],
588 'mistral-large-4': [null, 'unstated'],
589 'mistral-large-latest': [null, 'unstated'],
590 // The overview never lists it: no maker and no source.
591 'labs-unlisted': [undefined, undefined],
592 })
593 } finally {
594 globalThis.fetch = original
595 }
596 })
597})