Open History to see the last commit
1import { requestUrl } from '#/lib/text.ts'
2import { expect, it, afterEach, vi } from 'vitest'
3import native from './fixtures/nvidia-native-build-spec.json'
4import reference from './fixtures/nvidia-native-reasoning-discovery.json'
5import { NVIDIA_REFERENCE_INDEXES, nvidiaWireFacts } from './nvidia-openapi.ts'
6import {
7 parseNvidiaBuildSpec,
8 validateNvidiaBuildFacts,
9} from './nvidia-build-spec.ts'
10
11import { provider, NVIDIA_MODELS_URL } from './adapters/nvidia.ts'
12import { sha256Text } from './types.ts'
13
14const rawId = 'nvidia/nemotron-3.5-content-safety'
15const html = native[rawId].html
16it('reads the actual hosted Build spec independently of the incorrect ReadMe Nano schema', () => {
17 const facts = parseNvidiaBuildSpec(html, rawId)
18 expect(facts?.document.info?.title).toBe('NVIDIA NIM API for ' + rawId)
19 expect(facts?.reasoning).toEqual({ mode: 'toggle', mandatory: false })
20 expect(facts?.maxOutput).toBe(4096)
21 expect(facts?.activity).toBe('chat')
22 expect(facts?.document.servers).toContainEqual({
23 url: 'https://integrate.api.nvidia.com/v1',
24 })
25 expect(Object.keys(facts?.document.paths ?? {})).toContain(
26 '/chat/completions',
27 )
28})
29it('binds actual native request selectors independently of API display titles', () => {
30 for (const id of [
31 'nvidia/llama-3.1-nemotron-safety-guard-8b-v3',
32 'nvidia/nemotron-parse-2.0',
33 ] as const) {
34 expect(
35 parseNvidiaBuildSpec(native[id].html, id)?.document.info?.title,
36 ).not.toContain(id)
37 }
38})
39it('fails on malformed published primary schema data', () => {
40 expect(() =>
41 parseNvidiaBuildSpec(
42 html.replaceAll('openAPISpec', 'openAPISpecBROKEN'),
43 rawId,
44 ),
45 ).toThrow('marker is unreadable')
46 expect(() => parseNvidiaBuildSpec('<html>Challenge</html>', rawId)).toThrow(
47 'no native Flight',
48 )
49 expect(parseNvidiaBuildSpec('NEXT_HTTP_ERROR_FALLBACK;404', rawId)).toBeNull()
50 expect(() => parseNvidiaBuildSpec(html, 'nvidia/another-model')).toThrow(
51 'identity conflict',
52 )
53})
54it('only a healthy native page without a schema can report absence', () => {
55 expect(
56 parseNvidiaBuildSpec(
57 '<script>self.__next_f.push([1,"1:{\\"model\\":\\"nvidia/example\\"}"])</script>',
58 'nvidia/example',
59 ),
60 ).toBeNull()
61})
62const originalFetch = globalThis.fetch
63afterEach(() => {
64 globalThis.fetch = originalFetch
65 vi.restoreAllMocks()
66})
67function ownSources(page: string) {
68 const requested: string[] = []
69 const url = native[rawId].sourceUrl
70 globalThis.fetch = async (input) => {
71 const source = requestUrl(input)
72 requested.push(source)
73 if (source === NVIDIA_MODELS_URL)
74 return new Response(JSON.stringify({ data: [{ id: rawId }] }))
75 if (source === url + '.md') return new Response(native[rawId].markdown)
76 if (source === url) return new Response(page)
77 if ((reference as Record<string, string>)[source])
78 return new Response((reference as Record<string, string>)[source])
79 if (NVIDIA_REFERENCE_INDEXES.includes(source))
80 return new Response('---\n---\n# No relevant models\n')
81 throw new Error('Unselected secondary source requested: ' + source)
82 }
83 return requested
84}
85it('syncs the native primary before secondary discovery and keeps real path separate from model identity', async () => {
86 const requested = ownSources(html)
87 const rows = await provider.listModels({})
88 expect(requested).toContain(native[rawId].sourceUrl)
89 expect(requested).toContain(
90 'https://docs.api.nvidia.com/nim/reference/nvidia-nemotron-3-5-content-safety-infer.md',
91 )
92 const model = rows.models[0]
93 expect(rows.docsFailures).toEqual({ failed: 0, skipped: 0, first: [] })
94 expect(model?.reasoning).toEqual({ mode: 'toggle', mandatory: false })
95 expect(model?.capabilities).toContain('reasoning')
96 expect(model?.factSources?.reasoning).toMatchObject({
97 sourceUrl: native[rawId].sourceUrl,
98 sourceHash: await sha256Text(html),
99 path: 'chat_template_kwargs.enable_thinking',
100 })
101 expect(model?.factSources?.schemaEndpointId?.sourceUrl).toBe(
102 native[rawId].sourceUrl,
103 )
104 const synced = await provider.fetchSpec({})
105 expect(synced.specs).toEqual([])
106 expect(synced.bundledEndpoints).toHaveLength(1)
107 const endpoint = synced.bundledEndpoints?.[0]
108 expect(endpoint).toMatchObject({
109 publicId: rawId,
110 path: '/chat/completions',
111 source: { url: native[rawId].sourceUrl, hash: await sha256Text(html) },
112 })
113 expect(endpoint?.input).toBeDefined()
114 expect(endpoint?.output).toBeDefined()
115 expect(provider.specGrain).toBe('model')
116 expect(
117 synced.warnings?.some((warning) =>
118 warning.includes('rejected competing reference identity'),
119 ),
120 ).toBe(true)
121})
122it('never recovers an erroneous primary with another provider body', async () => {
123 const requested = ownSources(
124 html.replaceAll(
125 'nvidia/nemotron-3.5-content-safety',
126 'nvidia/incorrect-model',
127 ),
128 )
129 const rows = await provider.listModels({})
130 expect(rows.docsFailures?.failed).toBe(1)
131 expect(rows.docsFailures?.first[0]?.source).toBe(native[rawId].sourceUrl)
132 expect(rows.docsFailures?.first[0]?.error).toContain('identity conflict')
133 expect(rows.models[0]?.reasoning).toBeUndefined()
134 expect(rows.models[0]?.absent?.reasoning).toBe('unavailable')
135 await expect(provider.fetchSpec({})).rejects.toThrow('identity conflict')
136 expect(
137 requested.filter((url) => url === native[rawId].sourceUrl),
138 ).toHaveLength(2)
139})
140
141it('revalidates cached primary identity and derives controls from its document', () => {
142 const facts = parseNvidiaBuildSpec(html, rawId)
143 if (!facts) throw new Error('Missing native fixture contract')
144 expect(
145 validateNvidiaBuildFacts(
146 {
147 ...facts,
148 reasoning: { mode: 'effort', mandatory: true, efforts: ['invented'] },
149 },
150 rawId,
151 ).reasoning,
152 ).toEqual({ mode: 'toggle', mandatory: false })
153 expect(() =>
154 validateNvidiaBuildFacts(facts, 'nvidia/unrelated-model'),
155 ).toThrow('identity conflict')
156})
157
158it('reads published native JSON even when its response examples contain Markdown fences', () => {
159 const id = 'microsoft/phi-3-vision-128k-instruct'
160 const facts = parseNvidiaBuildSpec(native[id].html, id)
161 expect(facts?.document.info?.title).toBe('NVIDIA NIM API for ' + id)
162 expect(
163 facts?.document.paths?.['/vlm/microsoft/phi-3-vision-128k-instruct']?.post,
164 ).toBeDefined()
165 expect(facts?.activity).toBeNull()
166})
167
168it('records local native identity failures without charging successful fetch time to the network failure budget', async () => {
169 ownSources(html.replaceAll(rawId, 'nvidia/unrelated-model'))
170 const fetchSource = globalThis.fetch
171 let now = 100_000
172 vi.spyOn(Date, 'now').mockImplementation(() => now)
173 globalThis.fetch = async (...args) => {
174 if (requestUrl(args[0]) === native[rawId].sourceUrl) now += 20_000
175 return fetchSource(...args)
176 }
177 const listing = await provider.listModels({})
178 expect(listing.docsFailures?.failed).toBe(1)
179 expect(listing.docsFailures?.skipped).toBe(0)
180 expect(listing.docsFailures?.first[0]?.elapsedMs).toBe(0)
181 expect(listing.docsFailures?.first[0]?.error).toContain('identity conflict')
182})
183
184it('never caches a malformed primary and rejects cached wrong identities without requesting secondary sources', async () => {
185 const values = new Map<string, string>()
186 const kv = {
187 get: async (key: string) => values.get(key) ?? null,
188 put: async (key: string, value: string) => {
189 values.set(key, value)
190 },
191 } as unknown as KVNamespace
192 const key = 'nvidia-build-contract:v1:' + native[rawId].sourceUrl
193 ownSources(html.replaceAll(rawId, 'nvidia/unrelated-model'))
194 const invalid = await provider.listModels({}, kv)
195 expect(invalid.docsFailures?.failed).toBe(1)
196 expect(values.has(key)).toBe(false)
197 ownSources(html)
198 expect((await provider.listModels({}, kv)).docsFailures).toEqual({
199 failed: 0,
200 skipped: 0,
201 first: [],
202 })
203 expect(values.has(key)).toBe(true)
204 const contract = values.get(key)
205 if (!contract) throw new Error('Missing healthy native cached contract')
206 values.set(key, contract.replaceAll(rawId, 'nvidia/unrelated-model'))
207 const requested = ownSources(html)
208 const badCache = await provider.listModels({}, kv)
209 expect(badCache.docsFailures?.first[0]?.error).toContain('identity conflict')
210 expect(requested).not.toContain(native[rawId].sourceUrl)
211})
212
213it('keeps an exact healthy ReadMe contract primary when the competing Build body omits its native thinking control', async () => {
214 const id = 'google/gemma-4-31b-it'
215 expect(parseNvidiaBuildSpec(native[id].html, id)?.reasoning).toBeUndefined()
216 const requested: string[] = []
217 globalThis.fetch = async (input) => {
218 const url = requestUrl(input)
219 requested.push(url)
220 if (url === NVIDIA_MODELS_URL) return Response.json({ data: [{ id }] })
221 if (url === native[id].sourceUrl) return new Response(native[id].html)
222 const body = (reference as Record<string, string>)[url]
223 if (body) return new Response(body)
224 if (NVIDIA_REFERENCE_INDEXES.includes(url))
225 return new Response('---\n---\n# No relevant models\n')
226 throw new Error('Unexpected native source ' + url)
227 }
228 const result = await provider.listModels({})
229 expect(result.docsFailures).toEqual({ failed: 0, skipped: 0, first: [] })
230 expect(result.models[0]?.reasoning).toEqual({
231 mode: 'toggle',
232 mandatory: false,
233 })
234 expect(result.models[0]?.factSources?.reasoning?.sourceUrl).toBe(
235 'https://docs.api.nvidia.com/nim/reference/google-gemma-4-31b-it-infer.md',
236 )
237 expect(requested).not.toContain(native[id].sourceUrl)
238})
239
240it('never uses a healthy Build body to recover a ReadMe network or malformed-content error', async () => {
241 for (const bad of [
242 new Response('Unavailable', { status: 503 }),
243 new Response('not a provider schema'),
244 ]) {
245 const requested = ownSources(html)
246 const nativeFetch = globalThis.fetch
247 globalThis.fetch = async (...args) =>
248 requestUrl(args[0]) ===
249 'https://docs.api.nvidia.com/nim/reference/nvidia-nemotron-3-5-content-safety-infer.md'
250 ? bad
251 : nativeFetch(...args)
252 const result = await provider.listModels({})
253 expect(result.docsFailures?.failed).toBe(1)
254 expect(result.models[0]?.absent?.reasoning).toBe('unavailable')
255 expect(result.models[0]?.schemaEndpointId).toBeUndefined()
256 expect(requested).not.toContain(native[rawId].sourceUrl)
257 }
258})
259
260it('never converts failed complete or partial ReadMe index discovery into unpublished-source Build selection', async () => {
261 for (const allFailed of [true, false]) {
262 const requested = ownSources(html)
263 const ownFetch = globalThis.fetch
264 globalThis.fetch = async (...args) => {
265 const url = requestUrl(args[0])
266 if (NVIDIA_REFERENCE_INDEXES.includes(url)) {
267 if (allFailed || url === NVIDIA_REFERENCE_INDEXES[0])
268 return new Response('unavailable', { status: 503 })
269 return new Response('---\n---\n# No relevant models\n')
270 }
271 if (url === 'https://docs.api.nvidia.com/sitemap.xml')
272 return new Response(
273 '<urlset><url><loc>https://docs.api.nvidia.com/nim/reference/google-gemma-4-31b-it-infer</loc></url></urlset>',
274 )
275 return ownFetch(...args)
276 }
277 const result = await provider.listModels({})
278 expect(result.docsFailures?.failed).toBeGreaterThan(0)
279 expect(result.models[0]?.absent?.reasoning).toBe('unavailable')
280 expect(result.models[0]?.schemaEndpointId).toBeUndefined()
281 expect(requested).not.toContain(native[rawId].sourceUrl)
282 }
283})
284
285it('retains native explicit capability negatives and surfaces a contradictory selected schema', async () => {
286 const requested = ownSources(html)
287 const nativeFetch = globalThis.fetch
288 globalThis.fetch = async (...args) =>
289 requestUrl(args[0]) === native[rawId].sourceUrl + '.md'
290 ? new Response(
291 native[rawId].markdown.replace(
292 '**Reasoning:** Supported',
293 '**Reasoning:** Not supported',
294 ),
295 )
296 : nativeFetch(...args)
297 const result = await provider.listModels({})
298 expect(result.docsFailures?.first[0]?.error).toContain(
299 'explicitly rejects reasoning',
300 )
301 expect(result.models[0]?.unsupportedCapabilities).toContain('reasoning')
302 expect(
303 result.models[0]?.factSources?.capabilities?.reasoning?.sourceUrl,
304 ).toBe(native[rawId].sourceUrl)
305 expect(
306 result.models[0]?.factSources?.capabilities?.reasoning?.sourceHash,
307 ).toBe(
308 await sha256Text(
309 native[rawId].markdown.replace(
310 '**Reasoning:** Supported',
311 '**Reasoning:** Not supported',
312 ),
313 ),
314 )
315 expect(result.models[0]?.capabilities).not.toContain('reasoning')
316 expect(result.models[0]?.requestMap).toBeNull()
317 expect(result.models[0]?.schemaEndpointId).toBeUndefined()
318 expect(requested).toContain(native[rawId].sourceUrl)
319})
320
321it('does not turn an absent capability label into an unsupported fact', async () => {
322 ownSources(html)
323 const nativeFetch = globalThis.fetch
324 globalThis.fetch = async (...args) =>
325 requestUrl(args[0]) === native[rawId].sourceUrl + '.md'
326 ? new Response(
327 native[rawId].markdown.replace('- **Reasoning:** Supported\n', ''),
328 )
329 : nativeFetch(...args)
330 const result = await provider.listModels({})
331 expect(result.docsFailures).toEqual({ failed: 0, skipped: 0, first: [] })
332 expect(result.models[0]?.unsupportedCapabilities).not.toContain('reasoning')
333 expect(result.models[0]?.capabilities).toContain('reasoning')
334})
335
336it('derives wire fields from the exact native request members and preserves unknown leaves', async () => {
337 ownSources(html)
338 const model = (await provider.listModels({})).models[0]
339 expect(model?.requestMap?.maxTokensField).toBe('max_tokens')
340 expect(model?.requestMap?.thinking).toEqual({
341 on: { chat_template_kwargs: { enable_thinking: true } },
342 off: { chat_template_kwargs: { enable_thinking: false } },
343 levels: null,
344 })
345 expect(model?.requestMap?.store).toBeNull()
346 expect(model?.factSources?.requestMapFields?.maxTokensField?.sourceUrl).toBe(
347 native[rawId].sourceUrl,
348 )
349 expect(model?.factSources?.requestMapFields?.thinking?.sourceHash).toBe(
350 await sha256Text(html),
351 )
352})
353
354it('responds to native role-enum and token-member changes without static per-provider flags', () => {
355 const facts = parseNvidiaBuildSpec(html, rawId)
356 if (!facts) throw new Error('Missing native fixture')
357 const doc = structuredClone(facts.document)
358 expect(nvidiaWireFacts(doc).fields.developerRole).toBe(false)
359 const role = doc.components?.schemas?.Role
360 if (
361 !role ||
362 typeof role !== 'object' ||
363 Array.isArray(role) ||
364 !('enum' in role)
365 )
366 throw new Error('Missing native role enum')
367 const nativeRoles: unknown = role.enum
368 role.enum = [
369 ...(Array.isArray(nativeRoles) ? (nativeRoles as unknown[]) : []),
370 'developer',
371 ]
372 expect(nvidiaWireFacts(doc).fields.developerRole).toBe(true)
373 delete role.enum
374 expect(nvidiaWireFacts(doc).fields.developerRole).toBeUndefined()
375 const request = doc.components?.schemas?.NIMLLMChatCompletionRequest
376 if (
377 !request ||
378 typeof request !== 'object' ||
379 !('properties' in request) ||
380 !request.properties ||
381 typeof request.properties !== 'object' ||
382 Array.isArray(request.properties)
383 )
384 throw new Error('Missing native request properties')
385 const props = request.properties as Record<string, unknown>
386 props.max_completion_tokens = props.max_tokens
387 delete props.max_tokens
388 expect(nvidiaWireFacts(doc).fields.maxTokensField).toBe(
389 'max_completion_tokens',
390 )
391 delete props.max_completion_tokens
392 expect(nvidiaWireFacts(doc).fields.maxTokensField).toBeUndefined()
393})