Open History to see the last commit
1import type { BrowserRunContentOptions } from '@cloudflare/workers-types'
2import { Validator } from '@cfworker/json-schema'
3import { afterEach, expect, it } from 'vitest'
4import { cardCurrency, price } from '@modelschemas/rate-card'
5import { classifyAndBundle } from '../../ingest/sync.ts'
6import fixtures from '../fixtures/ant-ling-docs.json'
7import sourceFailure from '../fixtures/ant-ling-native-source-failure.json'
8import seriesThinking from '../fixtures/ant-ling-openai-series-thinking.json'
9import reasoningEffort from '../fixtures/ant-ling-openai-reasoning-effort.json'
10import noEffort from '../fixtures/ant-ling-openai-no-effort.json'
11import {
12 ANT_OPENAI,
13 ANT_PRICE,
14 nativePrices,
15 nativeRequest,
16} from '../ant-ling-docs.ts'
17import { provider } from './ant-ling.ts'
18import { sha256Text } from '../types.ts'
19import type { ProviderEnvironment } from '../types.ts'
20
21const native = fixtures as Record<string, string>
22const originalFetch = globalThis.fetch
23let nativeEnv: ProviderEnvironment = {}
24function serve(overrides: Record<string, string> = {}) {
25 const urls: Array<string> = []
26 nativeEnv = {
27 BROWSER: {
28 quickAction: async (action: string, options: { url?: string }) => {
29 if (action !== 'content' || !options.url)
30 throw new Error('unexpected browser action')
31 const url = options.url
32 urls.push(url)
33 const body = overrides[url] ?? native[url]
34 if (body === undefined) throw new Error(`unexpected source ${url}`)
35 return Response.json({
36 success: true,
37 result: body,
38 meta: { status: 200, finalUrl: url, title: 'native fixture' },
39 })
40 },
41 } as unknown as Pick<BrowserRun, 'quickAction'>,
42 }
43 return urls
44}
45afterEach(() => {
46 globalThis.fetch = originalFetch
47})
48it('refreshes direct IDs, CNY sale/free rates and hosted contexts without a key', async () => {
49 const urls = serve()
50 const fetched = await provider.listModels(nativeEnv)
51 expect(fetched.skipped).toBeUndefined()
52 expect(fetched.models).toHaveLength(8)
53 const flagship = fetched.models.find((m) => m.rawId === 'Ling-2.6-1T')
54 expect(flagship?.contextWindow).toBe(256000)
55 expect(flagship?.pricing).toMatchObject({
56 tables: {
57 rate: {
58 base: {
59 input_tokens: 4.5 / 1e6,
60 output_tokens: 18 / 1e6,
61 cache_read_tokens: 0.9 / 1e6,
62 },
63 },
64 },
65 })
66 const flash = fetched.models.find((m) => m.rawId === 'Ling-3.0-flash')
67 expect(
68 cardCurrency(flash?.pricing as Parameters<typeof cardCurrency>[0]),
69 ).toBe('CNY')
70 expect(flash?.pricing).toMatchObject({
71 tables: {
72 rate: {
73 base: {
74 input_tokens: 0.125 / 1e6,
75 output_tokens: 0.375 / 1e6,
76 cache_read_tokens: 0.025 / 1e6,
77 },
78 },
79 },
80 })
81 const free = fetched.models.find((m) => m.rawId === 'Ling-3.1-flash')
82 expect(price(free?.pricing as Parameters<typeof price>[0], {})).toBe(0)
83 expect(
84 fetched.models.find((m) => m.rawId === 'AntAngelMed')?.pricing,
85 ).toBeNull()
86 expect(
87 fetched.models.find((m) => m.rawId === 'Ling-3.0-tiny')?.contextWindow,
88 ).toBeNull()
89 expect(fetched.models.every((m) => m.maxOutput === null)).toBe(true)
90 expect(
91 urls.every((url) =>
92 url.startsWith('https://developer.ant-ling.com/en/docs/'),
93 ),
94 ).toBe(true)
95})
96it('keeps scoped native reasoning bodies and unknown max_tokens null', async () => {
97 serve()
98 const { models } = await provider.listModels(nativeEnv)
99 const ring = models.find((m) => m.rawId === 'Ring-2.6-1T')
100 expect(ring).toMatchObject({
101 reasoning: { mode: 'effort', mandatory: null, efforts: ['high', 'xhigh'] },
102 requestMap: {
103 thinking: {
104 on: { reasoning: { effort: 'high' } },
105 off: null,
106 levels: { high: 'high', xhigh: 'xhigh', medium: null },
107 },
108 maxTokensField: null,
109 },
110 })
111 const flash = models.find((m) => m.rawId === 'Ling-3.0-flash')
112 expect(flash?.requestMap?.thinking).toMatchObject({
113 on: { thinking: { type: 'enabled' } },
114 off: { thinking: { type: 'disabled' } },
115 })
116 expect(
117 models.find((m) => m.rawId === 'Ling-2.6-1T')?.requestMap?.thinking,
118 ).toBeNull()
119 expect(
120 models.find((m) => m.rawId === 'Ling-3.0-flash-VL')?.modalities,
121 ).toEqual({ input: ['text', 'image', 'video'], output: ['text'] })
122})
123it('binds the thinking toggle to every id in the series the page names', async () => {
124 serve({ [ANT_OPENAI]: seriesThinking.html })
125 const { models } = await provider.listModels(nativeEnv)
126 const toggle = {
127 on: { thinking: { type: 'enabled' } },
128 off: { thinking: { type: 'disabled' } },
129 levels: null,
130 }
131 for (const id of [
132 'Ling-3.1-flash',
133 'Ling-3.0-flash-VL',
134 'Ling-3.0-flash',
135 'Ling-3.0-tiny',
136 ]) {
137 const row = models.find((m) => m.rawId === id)
138 expect(row?.reasoning).toEqual({ mode: 'toggle', mandatory: false })
139 expect(row?.requestMap?.thinking).toEqual(toggle)
140 }
141 for (const id of ['Ling-2.6-1T', 'Ling-2.6-flash', 'AntAngelMed']) {
142 const row = models.find((m) => m.rawId === id)
143 expect(row?.reasoning).toBeNull()
144 expect(row?.requestMap?.thinking).toBeNull()
145 }
146 expect(models.find((m) => m.rawId === 'Ring-2.6-1T')?.reasoning).toEqual({
147 mode: 'effort',
148 mandatory: null,
149 efforts: ['high', 'xhigh'],
150 })
151})
152it('reads the top-level reasoning_effort string the page replaced reasoning.effort with', async () => {
153 serve({ [ANT_OPENAI]: reasoningEffort.html })
154 const { models } = await provider.listModels(nativeEnv)
155 const ring = models.find((m) => m.rawId === 'Ring-2.6-1T')
156 expect(ring?.reasoning).toEqual({
157 mode: 'effort',
158 mandatory: null,
159 efforts: ['high', 'xhigh'],
160 })
161 expect(ring?.requestMap?.thinking).toMatchObject({
162 off: null,
163 levels: { high: 'high', xhigh: 'xhigh', medium: null },
164 })
165 expect(ring?.requestMap?.thinking?.on).toEqual({ reasoning_effort: 'high' })
166 for (const id of ['Ling-3.0-flash', 'Ling-3.1-flash'])
167 expect(models.find((m) => m.rawId === id)?.reasoning).toEqual({
168 mode: 'toggle',
169 mandatory: false,
170 })
171 expect(models.find((m) => m.rawId === 'Ling-2.6-1T')?.reasoning).toBeNull()
172 const input = nativeRequest(reasoningEffort.html)
173 expect(
174 (input.properties as Record<string, unknown>).reasoning_effort,
175 ).toMatchObject({ type: 'string', enum: ['high', 'xhigh'], default: 'high' })
176 const bundled = classifyAndBundle(
177 provider,
178 await provider.fetchSpec(nativeEnv),
179 )
180 expect(bundled.endpoints).toHaveLength(1)
181})
182it('reads a reference that dropped reasoning_effort with Ring as no effort model', async () => {
183 serve({ [ANT_OPENAI]: noEffort.html })
184 const { models } = await provider.listModels(nativeEnv)
185 for (const id of [
186 'Ling-3.1-flash',
187 'Ling-3.0-flash-VL',
188 'Ling-3.0-flash',
189 'Ling-3.0-tiny',
190 ]) {
191 const row = models.find((m) => m.rawId === id)
192 expect(row?.reasoning).toEqual({ mode: 'toggle', mandatory: false })
193 expect(row?.requestMap?.thinking).toEqual({
194 on: { thinking: { type: 'enabled' } },
195 off: { thinking: { type: 'disabled' } },
196 levels: null,
197 })
198 }
199 expect(models.some((m) => m.reasoning?.mode === 'effort')).toBe(false)
200 expect(models.find((m) => m.rawId === 'Ring-2.6-1T')?.requestMap).toBeNull()
201 expect(
202 models.find((m) => m.rawId === 'Ming-3.0-audio-flash')?.modalities,
203 ).toEqual({ input: ['text', 'audio'], output: ['text'] })
204 expect(
205 models.find((m) => m.rawId === 'Ling-3.0-flash-VL')?.modalities,
206 ).toEqual({ input: ['text', 'image', 'video'], output: ['text'] })
207 expect(models.find((m) => m.rawId === 'Ling-3.0-flash')?.modalities).toEqual({
208 input: ['text'],
209 output: ['text'],
210 })
211})
212it('reads a "natively accepts ... with native multimodal understanding" statement', async () => {
213 const html = noEffort.html.replace(
214 'the request accepts text, images, and videos.',
215 'the request natively accepts text, images, and videos with native multimodal understanding.',
216 )
217 expect(html).not.toBe(noEffort.html)
218 serve({ [ANT_OPENAI]: html })
219 const { models } = await provider.listModels(nativeEnv)
220 expect(
221 models.find((m) => m.rawId === 'Ling-3.0-flash-VL')?.modalities,
222 ).toEqual({ input: ['text', 'image', 'video'], output: ['text'] })
223})
224it('fails an input-modality statement it cannot read', async () => {
225 for (const html of [
226 noEffort.html.replace('accepts text and audio', 'accepts text and smell'),
227 noEffort.html.replace(
228 'the request accepts text, images, and videos',
229 'the request also accepts text, images, and videos',
230 ),
231 noEffort.html.replace(
232 'the request accepts text, images, and videos.',
233 'the request accepts text with images and videos.',
234 ),
235 ]) {
236 expect(html).not.toBe(noEffort.html)
237 serve({ [ANT_OPENAI]: html })
238 await expect(provider.listModels(nativeEnv)).rejects.toThrow(
239 /unreadable native input modality|missing native multimodal applicability/,
240 )
241 }
242})
243it('fails a reasoning_effort it cannot scope or whose default is no option', async () => {
244 const detailDefault =
245 'default <code class="nextra-code" dir="ltr">high</code>'
246 const overviewDefault =
247 /(<td[^>]*>\s*)<code class="nextra-code" dir="ltr">high<\/code>/
248 const description =
249 'Controls how much reasoning depth Ring-2.6-1T applies when responding.'
250 const cases: Array<[string, RegExp]> = [
251 [
252 reasoningEffort.html.replace('(Ring-2.6-1T only)', ''),
253 /unreadable reasoning_effort applicability/,
254 ],
255 [
256 reasoningEffort.html.replace(
257 description,
258 'Only takes effect for Ring-3.0-1T.',
259 ),
260 /conflicting reasoning_effort applicability/,
261 ],
262 [
263 reasoningEffort.html.replace(
264 description,
265 'Controls reasoning depth. Supported by 2.6 series models.',
266 ),
267 /conflicting reasoning_effort applicability/,
268 ],
269 [
270 reasoningEffort.html.replace(
271 description,
272 'Controls how much reasoning depth Ring-3.0-1T applies when responding.',
273 ),
274 /conflicting reasoning_effort applicability/,
275 ],
276 [
277 reasoningEffort.html.replace(
278 detailDefault,
279 'default <code class="nextra-code" dir="ltr">max</code>',
280 ),
281 /reasoning_effort defaults disagree/,
282 ],
283 [
284 reasoningEffort.html.replace(detailDefault, ''),
285 /reasoning_effort default unstated/,
286 ],
287 [
288 reasoningEffort.html.replace(
289 description,
290 'Controls how much reasoning depth Ring-2.6-1T-mini applies when responding.',
291 ),
292 /conflicting reasoning_effort applicability/,
293 ],
294 [
295 reasoningEffort.html.replace(
296 overviewDefault,
297 '$1<code class="nextra-code" dir="ltr">xhigh</code>',
298 ),
299 /reasoning_effort defaults disagree/,
300 ],
301 [
302 reasoningEffort.html
303 .replace(
304 detailDefault,
305 'default <code class="nextra-code" dir="ltr">max</code>',
306 )
307 .replace(
308 overviewDefault,
309 '$1<code class="nextra-code" dir="ltr">max</code>',
310 ),
311 /unknown parameter default/,
312 ],
313 [
314 reasoningEffort.html.replace(
315 '<h3 id="thinking"',
316 '<h3 id="reasoning">reasoning</h3><ul><li><strong>Description</strong>: Only takes effect for Ring-2.6-1T.</li></ul><h4 id="reasoningeffort">reasoning.effort</h4><ul><li><strong>Type</strong>: <code>string</code></li></ul><h3 id="thinking"',
317 ),
318 /two native effort fields/,
319 ],
320 ]
321 const search = reasoningEffort.html
322 .replace(
323 /(<code class="nextra-code" dir="ltr">enable_search<\/code><\/td>(?:<td[^>]*>[\s\S]*?<\/td>){2}<td[^>]*>)<code class="nextra-code" dir="ltr">false<\/code>/,
324 '$1<code class="nextra-code" dir="ltr">auto</code>',
325 )
326 .replace(
327 'Whether to allow the model to use web search.</li>',
328 'Whether to allow the model to use web search.</li><li><strong>Options</strong>:<ul><li><code>auto</code></li></ul></li>',
329 )
330 expect(search).not.toBe(reasoningEffort.html)
331 expect(() => nativeRequest(search)).toThrow('unknown parameter default')
332 for (const [html, error] of cases) {
333 expect(html).not.toBe(reasoningEffort.html)
334 serve({ [ANT_OPENAI]: html })
335 await expect(provider.listModels(nativeEnv)).rejects.toThrow(error)
336 }
337})
338it('fails thinking scopes it cannot read as stated support', async () => {
339 const sentence = 'Supported by 3.0 series models and 3.1 series models.'
340 const cases: Array<[string, RegExp]> = [
341 [
342 seriesThinking.html.replace(
343 sentence,
344 'Supported by 3.0 series models and 4.0 series models.',
345 ),
346 /no native model in the 4\.0 series/,
347 ],
348 [
349 seriesThinking.html.replace(sentence, `Not s${sentence.slice(1)}`),
350 /unreadable thinking applicability/,
351 ],
352 [
353 seriesThinking.html.replace(
354 sentence,
355 `${sentence} Not supported by Ling-3.0-tiny.`,
356 ),
357 /unreadable thinking applicability/,
358 ],
359 [
360 seriesThinking.html.replace(
361 '3.0 series models and 3.1 series models enable reasoning',
362 '3.0 series models enable reasoning',
363 ),
364 /thinking\.type names other models than thinking/,
365 ],
366 [
367 seriesThinking.html.replaceAll(
368 '3.0 series models and 3.1 series models',
369 '2.6 series models',
370 ),
371 /a model has both native reasoning controls/,
372 ],
373 ]
374 for (const [html, error] of cases) {
375 serve({ [ANT_OPENAI]: html })
376 await expect(provider.listModels(nativeEnv)).rejects.toThrow(error)
377 }
378})
379it('derives native parameter tables and nested constraints without borrowing a schema', async () => {
380 serve()
381 const fetched = await provider.fetchSpec(nativeEnv)
382 const bundled = classifyAndBundle(provider, fetched)
383 expect(bundled.endpoints).toHaveLength(1)
384 expect(bundled.endpoints[0]?.input).toBeTruthy()
385 expect(bundled.endpoints[0]?.output).toBeUndefined()
386 const input = nativeRequest(native[ANT_OPENAI] ?? '')
387 expect(
388 (input.properties as Record<string, Record<string, unknown>>).model?.[
389 'x-source-options'
390 ],
391 ).toContain('Ring-2.6-1T')
392 expect(input).toMatchObject({
393 required: ['model', 'messages'],
394 properties: {
395 temperature: { type: 'number', minimum: 0, maximum: 1 },
396 top_p: { exclusiveMinimum: 0, maximum: 1 },
397 messages: {
398 items: {
399 required: ['role', 'content'],
400 properties: { role: { enum: ['system', 'user', 'assistant'] } },
401 },
402 },
403 },
404 })
405 expect(
406 (input.properties as Record<string, { enum?: unknown }>).model?.enum,
407 ).toBeUndefined()
408 expect(
409 (input.properties as Record<string, unknown>).max_tokens,
410 ).toBeUndefined()
411})
412it('ignores all reseller USD rows, including conflicting later rates', () => {
413 const prices = nativePrices(native[ANT_PRICE] ?? '')
414 expect(prices.get('Ling-2.6-1T')?.rates.input_tokens).toBe(4.5 / 1e6)
415 expect(
416 nativePrices((native[ANT_PRICE] ?? '').replace('$0.30', '$999999')).get(
417 'Ling-2.6-1T',
418 ),
419 ).toEqual(prices.get('Ling-2.6-1T'))
420})
421it('fails missing sale amounts, missing price sections and changed field types', () => {
422 const source = native[ANT_PRICE] ?? ''
423 expect(() =>
424 nativePrices(
425 source.replace('<span>¥0.14</span>', '<span>unreadable</span>'),
426 ),
427 ).toThrow('unreadable current CNY price')
428 expect(() =>
429 nativePrices(source.replace('id="model-pricing"', 'id="changed-pricing"')),
430 ).toThrow('missing model-pricing')
431 expect(() =>
432 nativeRequest(
433 (native[ANT_OPENAI] ?? '').replace(
434 '<code>double</code>',
435 '<code>unknown-unit</code>',
436 ),
437 ),
438 ).toThrow('unknown native field type')
439})
440it('reads each price unit from its own column and lists per-image rows without a token card', async () => {
441 const source = native[ANT_PRICE] ?? ''
442 const image =
443 '<tr><td><strong>Ming-Image-0.1-Design</strong></td><td>Design image generation</td><td>—</td><td>—</td><td><del>¥0.10</del> <span>¥0.03</span></td><td>image</td><td>—</td><td>—</td></tr>'
444 const withImage = source.replace('</tbody>', `${image}</tbody>`)
445 serve({ [ANT_PRICE]: withImage })
446 const { models } = await provider.listModels(nativeEnv)
447 const ming = models.find((m) => m.rawId === 'Ming-Image-0.1-Design')
448 expect(ming?.pricing).toBeNull()
449 expect(ming?.absent).toBeUndefined()
450 expect(models.find((m) => m.rawId === 'Ling-2.6-1T')?.pricing).not.toBeNull()
451 expect(() =>
452 nativePrices(withImage.replace('<td>image</td>', '<td>1K characters</td>')),
453 ).toThrow('unreadable direct price units for Ming-Image-0.1-Design')
454 expect(() =>
455 nativePrices(
456 withImage.replace(
457 '<td>—</td><td>—</td><td><del>',
458 '<td>¥0.01</td><td>—</td><td><del>',
459 ),
460 ),
461 ).toThrow('unreadable direct price units for Ming-Image-0.1-Design')
462 expect(() =>
463 nativePrices(withImage.replace('<span>¥0.03</span>', '<span>free</span>')),
464 ).toThrow('unreadable current CNY price')
465 expect(() =>
466 nativePrices(source.replace('<td>1M tokens</td>', '<td>1K tokens</td>')),
467 ).toThrow('unreadable direct price units')
468 expect(() =>
469 nativePrices(
470 source.replace(
471 '<th>Input Price</th><th>Unit</th>',
472 '<th>Input (per 1M tokens)</th>',
473 ),
474 ),
475 ).toThrow('direct pricing headers changed')
476})
477it('fails an empty native catalog instead of silently retiring stored rows', async () => {
478 serve({
479 [ANT_OPENAI]: '<article><h2 id="request-body">Request Body</h2></article>',
480 })
481 await expect(provider.listModels(nativeEnv)).rejects.toThrow('missing native')
482})
483
484it('refreshes newly published model IDs and changes free rows to paid from source', async () => {
485 serve({
486 [ANT_OPENAI]: (native[ANT_OPENAI] ?? '').replaceAll(
487 'AntAngelMed',
488 'Native-New-ID',
489 ),
490 })
491 const { models } = await provider.listModels(nativeEnv)
492 expect(models.some((m) => m.rawId === 'Native-New-ID')).toBe(true)
493 expect(models.some((m) => m.rawId === 'AntAngelMed')).toBe(false)
494 const quotes = nativePrices(
495 (native[ANT_PRICE] ?? '').replaceAll('¥0.00', '¥1.00'),
496 )
497 expect(quotes.get('Ling-3.1-flash')).toEqual({
498 free: false,
499 rates: {
500 input_tokens: 1 / 1e6,
501 output_tokens: 1 / 1e6,
502 cache_read_tokens: 1 / 1e6,
503 },
504 })
505})
506
507it('keeps conflicting content shape unknown without fabricating block schemas', () => {
508 const schema = nativeRequest(native[ANT_OPENAI] ?? '')
509 const props = schema.properties as Record<string, Record<string, unknown>>
510 const message = props.messages!.items as Record<string, unknown>
511 const content = (
512 message.properties as Record<string, Record<string, unknown>>
513 ).content!
514 expect(content.type).toBeUndefined()
515 expect(content['x-source-type']).toBeNull()
516 expect(content['x-source-declared-type']).toBe('string')
517 expect(content['x-source-conflicting-statement']).toContain(
518 'the request accepts text, images, and videos',
519 )
520 expect(content.items).toBeUndefined()
521 const result = new Validator(schema).validate({
522 model: 'Ling-3.0-flash-VL',
523 messages: [
524 {
525 role: 'user',
526 content: [
527 {
528 type: 'image_url',
529 image_url: { url: 'data:image/png;base64,example' },
530 },
531 { type: 'text', text: 'Describe' },
532 ],
533 },
534 ],
535 })
536 expect(result.valid).toBe(true)
537})
538it('clears missing native prices and binds only API-documented models', async () => {
539 serve()
540 const models = (await provider.listModels(nativeEnv)).models
541 expect(models).toHaveLength(8)
542 for (const id of ['AntAngelMed', 'Ling-3.0-tiny']) {
543 const m = models.find((candidate) => candidate.rawId === id)
544 expect(m?.pricing).toBeNull()
545 expect(m?.absent?.pricing).toBe('cleared')
546 }
547 const newlyPriced = models.find((m) => m.rawId === 'Ling-3.1-flash')
548 expect(newlyPriced?.pricing).not.toBeNull()
549 expect(newlyPriced?.activity).toBeNull()
550 expect(newlyPriced?.schemaEndpointId).toBeNull()
551 expect(newlyPriced?.requestMap).toBeNull()
552 expect(newlyPriced?.factSources?.schemaEndpointId).toBeUndefined()
553 const published = models.find((m) => m.rawId === 'Ling-3.0-flash-VL')
554 expect(published?.schemaEndpointId).toBe('v1/chat/completions')
555 expect(published?.factSources?.schemaEndpointId).toMatchObject({
556 sourceUrl: ANT_OPENAI,
557 path: 'Request Address + model.Options',
558 })
559 expect(provider.generationEndpointId).toBeUndefined()
560 expect(provider.bindSyncedRoutesOnly).toBe(true)
561})
562
563function docsKv(initial: Record<string, string> = {}) {
564 const stored = new Map(Object.entries(initial))
565 const writes: Array<string> = []
566 const kv = {
567 get: async (key: string) => stored.get(key) ?? null,
568 put: async (key: string, value: string) => {
569 writes.push(key)
570 stored.set(key, value)
571 },
572 } as unknown as KVNamespace
573 return { kv, stored, writes }
574}
575it('rejects the actual production captcha before caching and retries native docs', async () => {
576 const { kv, writes } = docsKv()
577 serve(
578 Object.fromEntries(
579 Object.keys(native).map((url) => [url, sourceFailure.html]),
580 ),
581 )
582 await expect(provider.listModels(nativeEnv, kv)).rejects.toThrow(
583 `ant-ling: native source ${ANT_OPENAI}: native documentation blocked by Alipay WAF/captcha`,
584 )
585 expect(writes).toEqual([])
586 serve()
587 expect((await provider.listModels(nativeEnv, kv)).models).toHaveLength(8)
588 expect(writes).toHaveLength(5)
589 expect(
590 writes.every((key) => key.includes('#cloudflare-browser-content-v1')),
591 ).toBe(true)
592})
593it('validates cached articles and never serves a cached blocked document', async () => {
594 const writes: Array<string> = []
595 const reads: Array<string> = []
596 const kv = {
597 get: async (key: string) => {
598 reads.push(key)
599 return JSON.stringify({
600 html: sourceFailure.html,
601 hash: 'cached-source-hash',
602 })
603 },
604 put: async (key: string) => {
605 writes.push(key)
606 },
607 } as unknown as KVNamespace
608 serve(
609 Object.fromEntries(
610 Object.keys(native).map((url) => [url, sourceFailure.html]),
611 ),
612 )
613 await expect(provider.listModels(nativeEnv, kv)).rejects.toThrow(
614 `ant-ling: native source ${ANT_OPENAI}: native documentation blocked by Alipay WAF/captcha`,
615 )
616 expect(writes).toEqual([])
617 expect(reads).toHaveLength(1)
618 expect(
619 reads.every((key) => key.endsWith('#cloudflare-browser-content-v1')),
620 ).toBe(true)
621})
622it('reports malformed native HTML with its URL before it can enter the cache', async () => {
623 const { kv, writes } = docsKv()
624 serve(
625 Object.fromEntries(
626 Object.keys(native).map((url) => [
627 url,
628 '<html><body>upstream unavailable</body></html>',
629 ]),
630 ),
631 )
632 await expect(provider.listModels(nativeEnv, kv)).rejects.toThrow(
633 `ant-ling: native source ${ANT_OPENAI}: ant-ling: missing native article`,
634 )
635 expect(writes).toEqual([])
636})
637
638it('requires the browser binding even if documents are cached', async () => {
639 const { kv, writes } = docsKv()
640 await expect(provider.listModels({}, kv)).rejects.toThrow(
641 `ant-ling: native source ${ANT_OPENAI}: Cloudflare Browser Rendering BROWSER binding is required`,
642 )
643 await expect(provider.fetchSpec({})).rejects.toThrow(
644 'BROWSER binding is required',
645 )
646 expect(writes).toEqual([])
647})
648it.each([
649 [
650 'service failure',
651 () => new Response('unavailable', { status: 503 }),
652 'request failed: HTTP 503',
653 ],
654 [
655 'invalid JSON',
656 () => new Response('<html>bad wrapper</html>'),
657 'native source',
658 ],
659 [
660 'unsuccessful result',
661 () => Response.json({ success: false, errors: [] }),
662 'unreadable',
663 ],
664 [
665 'array result',
666 () =>
667 Response.json({
668 success: true,
669 result: [],
670 meta: { status: 200, finalUrl: ANT_OPENAI },
671 }),
672 'unreadable',
673 ],
674 [
675 'missing meta',
676 () => Response.json({ success: true, result: native[ANT_OPENAI] }),
677 'unreadable',
678 ],
679 [
680 'native HTTP error',
681 () =>
682 Response.json({
683 success: true,
684 result: native[ANT_OPENAI],
685 meta: { status: 403, finalUrl: ANT_OPENAI },
686 }),
687 'native page failed',
688 ],
689 [
690 'unreadable native status',
691 () =>
692 Response.json({
693 success: true,
694 result: native[ANT_OPENAI],
695 meta: { status: '200', finalUrl: ANT_OPENAI },
696 }),
697 'native page failed',
698 ],
699 [
700 'wrong native host',
701 () =>
702 Response.json({
703 success: true,
704 result: native[ANT_OPENAI],
705 meta: {
706 status: 200,
707 finalUrl: 'https://other.example/en/docs/api-reference/openai/',
708 },
709 }),
710 'URL mismatch',
711 ],
712 [
713 'wrong native page',
714 () =>
715 Response.json({
716 success: true,
717 result: native[ANT_OPENAI],
718 meta: { status: 200, finalUrl: ANT_PRICE },
719 }),
720 'URL mismatch',
721 ],
722 [
723 'missing final URL',
724 () =>
725 Response.json({
726 success: true,
727 result: native[ANT_OPENAI],
728 meta: { status: 200 },
729 }),
730 'URL mismatch',
731 ],
732] as const)(
733 'rejects browser %s without direct-fetch recovery or caching',
734 async (_name, response, error) => {
735 let directFetches = 0
736 globalThis.fetch = async () => {
737 directFetches++
738 throw new Error('direct fetch must not recover browser errors')
739 }
740 const browser = { quickAction: async () => response() } as unknown as Pick<
741 BrowserRun,
742 'quickAction'
743 >
744 const { kv, writes } = docsKv()
745 await expect(provider.listModels({ BROWSER: browser }, kv)).rejects.toThrow(
746 error,
747 )
748 expect(writes).toEqual([])
749 expect(directFetches).toBe(0)
750 },
751)
752it('hashes the rendered native HTML and bounds browser source reads sequentially', async () => {
753 const urls = serve()
754 let active = 0
755 let peak = 0
756 const browser = nativeEnv.BROWSER!
757 const originalAction = browser.quickAction.bind(browser)
758 browser.quickAction = (async (action: string, options: { url?: string }) => {
759 active++
760 peak = Math.max(peak, active)
761 try {
762 await Promise.resolve()
763 return await originalAction(
764 action as 'content',
765 options as BrowserRunContentOptions,
766 )
767 } finally {
768 active--
769 }
770 }) as typeof browser.quickAction
771 const { models } = await provider.listModels(nativeEnv)
772 expect(models).toHaveLength(8)
773 expect(urls).toHaveLength(5)
774 expect(peak).toBe(1)
775 const spec = await provider.fetchSpec(nativeEnv)
776 expect(spec.sources).toEqual([
777 { url: ANT_OPENAI, hash: await sha256Text(native[ANT_OPENAI]!) },
778 ])
779})