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 {
9 ANT_OPENAI,
10 ANT_PRICE,
11 nativePrices,
12 nativeRequest,
13} from '../ant-ling-docs.ts'
14import { provider } from './ant-ling.ts'
15import { sha256Text } from '../types.ts'
16import type { ProviderEnvironment } from '../types.ts'
17
18const native = fixtures as Record<string, string>
19const originalFetch = globalThis.fetch
20let nativeEnv: ProviderEnvironment = {}
21function serve(overrides: Record<string, string> = {}) {
22 const urls: Array<string> = []
23 nativeEnv = {
24 BROWSER: {
25 quickAction: async (action: string, options: { url?: string }) => {
26 if (action !== 'content' || !options.url)
27 throw new Error('unexpected browser action')
28 const url = options.url
29 urls.push(url)
30 const body = overrides[url] ?? native[url]
31 if (body === undefined) throw new Error(`unexpected source ${url}`)
32 return Response.json({
33 success: true,
34 result: body,
35 meta: { status: 200, finalUrl: url, title: 'native fixture' },
36 })
37 },
38 } as unknown as Pick<BrowserRun, 'quickAction'>,
39 }
40 return urls
41}
42afterEach(() => {
43 globalThis.fetch = originalFetch
44})
45it('refreshes direct IDs, CNY sale/free rates and hosted contexts without a key', async () => {
46 const urls = serve()
47 const fetched = await provider.listModels(nativeEnv)
48 expect(fetched.skipped).toBeUndefined()
49 expect(fetched.models).toHaveLength(8)
50 const flagship = fetched.models.find((m) => m.rawId === 'Ling-2.6-1T')
51 expect(flagship?.contextWindow).toBe(256000)
52 expect(flagship?.pricing).toMatchObject({
53 tables: {
54 rate: {
55 base: {
56 input_tokens: 4.5 / 1e6,
57 output_tokens: 18 / 1e6,
58 cache_read_tokens: 0.9 / 1e6,
59 },
60 },
61 },
62 })
63 const flash = fetched.models.find((m) => m.rawId === 'Ling-3.0-flash')
64 expect(
65 cardCurrency(flash?.pricing as Parameters<typeof cardCurrency>[0]),
66 ).toBe('CNY')
67 expect(flash?.pricing).toMatchObject({
68 tables: {
69 rate: {
70 base: {
71 input_tokens: 0.125 / 1e6,
72 output_tokens: 0.375 / 1e6,
73 cache_read_tokens: 0.025 / 1e6,
74 },
75 },
76 },
77 })
78 const free = fetched.models.find((m) => m.rawId === 'Ling-3.1-flash')
79 expect(price(free?.pricing as Parameters<typeof price>[0], {})).toBe(0)
80 expect(
81 fetched.models.find((m) => m.rawId === 'AntAngelMed')?.pricing,
82 ).toBeNull()
83 expect(
84 fetched.models.find((m) => m.rawId === 'Ling-3.0-tiny')?.contextWindow,
85 ).toBeNull()
86 expect(fetched.models.every((m) => m.maxOutput === null)).toBe(true)
87 expect(
88 urls.every((url) =>
89 url.startsWith('https://developer.ant-ling.com/en/docs/'),
90 ),
91 ).toBe(true)
92})
93it('keeps scoped native reasoning bodies and unknown max_tokens null', async () => {
94 serve()
95 const { models } = await provider.listModels(nativeEnv)
96 const ring = models.find((m) => m.rawId === 'Ring-2.6-1T')
97 expect(ring).toMatchObject({
98 reasoning: { mode: 'effort', mandatory: null, efforts: ['high', 'xhigh'] },
99 requestMap: {
100 thinking: {
101 on: { reasoning: { effort: 'high' } },
102 off: null,
103 levels: { high: 'high', xhigh: 'xhigh', medium: null },
104 },
105 maxTokensField: null,
106 },
107 })
108 const flash = models.find((m) => m.rawId === 'Ling-3.0-flash')
109 expect(flash?.requestMap?.thinking).toMatchObject({
110 on: { thinking: { type: 'enabled' } },
111 off: { thinking: { type: 'disabled' } },
112 })
113 expect(
114 models.find((m) => m.rawId === 'Ling-2.6-1T')?.requestMap?.thinking,
115 ).toBeNull()
116 expect(
117 models.find((m) => m.rawId === 'Ling-3.0-flash-VL')?.modalities,
118 ).toEqual({ input: ['text', 'image', 'video'], output: ['text'] })
119})
120it('derives native parameter tables and nested constraints without borrowing a schema', async () => {
121 serve()
122 const fetched = await provider.fetchSpec(nativeEnv)
123 const bundled = classifyAndBundle(provider, fetched)
124 expect(bundled.endpoints).toHaveLength(1)
125 expect(bundled.endpoints[0]?.input).toBeTruthy()
126 expect(bundled.endpoints[0]?.output).toBeUndefined()
127 const input = nativeRequest(native[ANT_OPENAI] ?? '')
128 expect(
129 (input.properties as Record<string, Record<string, unknown>>).model?.[
130 'x-source-options'
131 ],
132 ).toContain('Ring-2.6-1T')
133 expect(input).toMatchObject({
134 required: ['model', 'messages'],
135 properties: {
136 temperature: { type: 'number', minimum: 0, maximum: 1 },
137 top_p: { exclusiveMinimum: 0, maximum: 1 },
138 messages: {
139 items: {
140 required: ['role', 'content'],
141 properties: { role: { enum: ['system', 'user', 'assistant'] } },
142 },
143 },
144 },
145 })
146 expect(
147 (input.properties as Record<string, { enum?: unknown }>).model?.enum,
148 ).toBeUndefined()
149 expect(
150 (input.properties as Record<string, unknown>).max_tokens,
151 ).toBeUndefined()
152})
153it('ignores all reseller USD rows, including conflicting later rates', () => {
154 const prices = nativePrices(native[ANT_PRICE] ?? '')
155 expect(prices.get('Ling-2.6-1T')?.rates.input_tokens).toBe(4.5 / 1e6)
156 expect(
157 nativePrices((native[ANT_PRICE] ?? '').replace('$0.30', '$999999')).get(
158 'Ling-2.6-1T',
159 ),
160 ).toEqual(prices.get('Ling-2.6-1T'))
161})
162it('fails missing sale amounts, missing price sections and changed field types', () => {
163 const source = native[ANT_PRICE] ?? ''
164 expect(() =>
165 nativePrices(
166 source.replace('<span>¥0.14</span>', '<span>unreadable</span>'),
167 ),
168 ).toThrow('unreadable current CNY price')
169 expect(() =>
170 nativePrices(source.replace('id="model-pricing"', 'id="changed-pricing"')),
171 ).toThrow('missing model-pricing')
172 expect(() =>
173 nativeRequest(
174 (native[ANT_OPENAI] ?? '').replace(
175 '<code>double</code>',
176 '<code>unknown-unit</code>',
177 ),
178 ),
179 ).toThrow('unknown native field type')
180})
181it('fails an empty native catalog instead of silently retiring stored rows', async () => {
182 serve({
183 [ANT_OPENAI]: '<article><h2 id="request-body">Request Body</h2></article>',
184 })
185 await expect(provider.listModels(nativeEnv)).rejects.toThrow('missing native')
186})
187
188it('refreshes newly published model IDs and changes free rows to paid from source', async () => {
189 serve({
190 [ANT_OPENAI]: (native[ANT_OPENAI] ?? '').replaceAll(
191 'AntAngelMed',
192 'Native-New-ID',
193 ),
194 })
195 const { models } = await provider.listModels(nativeEnv)
196 expect(models.some((m) => m.rawId === 'Native-New-ID')).toBe(true)
197 expect(models.some((m) => m.rawId === 'AntAngelMed')).toBe(false)
198 const quotes = nativePrices(
199 (native[ANT_PRICE] ?? '').replaceAll('¥0.00', '¥1.00'),
200 )
201 expect(quotes.get('Ling-3.1-flash')).toEqual({
202 free: false,
203 rates: {
204 input_tokens: 1 / 1e6,
205 output_tokens: 1 / 1e6,
206 cache_read_tokens: 1 / 1e6,
207 },
208 })
209})
210
211it('keeps conflicting content shape unknown without fabricating block schemas', () => {
212 const schema = nativeRequest(native[ANT_OPENAI] ?? '')
213 const props = schema.properties as Record<string, Record<string, unknown>>
214 const message = props.messages!.items as Record<string, unknown>
215 const content = (
216 message.properties as Record<string, Record<string, unknown>>
217 ).content!
218 expect(content.type).toBeUndefined()
219 expect(content['x-source-type']).toBeNull()
220 expect(content['x-source-declared-type']).toBe('string')
221 expect(content['x-source-conflicting-statement']).toContain(
222 'the request accepts text, images, and videos',
223 )
224 expect(content.items).toBeUndefined()
225 const result = new Validator(schema).validate({
226 model: 'Ling-3.0-flash-VL',
227 messages: [
228 {
229 role: 'user',
230 content: [
231 {
232 type: 'image_url',
233 image_url: { url: 'data:image/png;base64,example' },
234 },
235 { type: 'text', text: 'Describe' },
236 ],
237 },
238 ],
239 })
240 expect(result.valid).toBe(true)
241})
242it('clears missing native prices and binds only API-documented models', async () => {
243 serve()
244 const models = (await provider.listModels(nativeEnv)).models
245 expect(models).toHaveLength(8)
246 for (const id of ['AntAngelMed', 'Ling-3.0-tiny']) {
247 const m = models.find((candidate) => candidate.rawId === id)
248 expect(m?.pricing).toBeNull()
249 expect(m?.absent?.pricing).toBe('cleared')
250 }
251 const newlyPriced = models.find((m) => m.rawId === 'Ling-3.1-flash')
252 expect(newlyPriced?.pricing).not.toBeNull()
253 expect(newlyPriced?.activity).toBeNull()
254 expect(newlyPriced?.schemaEndpointId).toBeNull()
255 expect(newlyPriced?.requestMap).toBeNull()
256 expect(newlyPriced?.factSources?.schemaEndpointId).toBeUndefined()
257 const published = models.find((m) => m.rawId === 'Ling-3.0-flash-VL')
258 expect(published?.schemaEndpointId).toBe('v1/chat/completions')
259 expect(published?.factSources?.schemaEndpointId).toMatchObject({
260 sourceUrl: ANT_OPENAI,
261 path: 'Request Address + model.Options',
262 })
263 expect(provider.generationEndpointId).toBeUndefined()
264 expect(provider.bindSyncedRoutesOnly).toBe(true)
265})
266
267function docsKv(initial: Record<string, string> = {}) {
268 const stored = new Map(Object.entries(initial))
269 const writes: Array<string> = []
270 const kv = {
271 get: async (key: string) => stored.get(key) ?? null,
272 put: async (key: string, value: string) => {
273 writes.push(key)
274 stored.set(key, value)
275 },
276 } as unknown as KVNamespace
277 return { kv, stored, writes }
278}
279it('rejects the actual production captcha before caching and retries native docs', async () => {
280 const { kv, writes } = docsKv()
281 serve(
282 Object.fromEntries(
283 Object.keys(native).map((url) => [url, sourceFailure.html]),
284 ),
285 )
286 await expect(provider.listModels(nativeEnv, kv)).rejects.toThrow(
287 `ant-ling: native source ${ANT_OPENAI}: native documentation blocked by Alipay WAF/captcha`,
288 )
289 expect(writes).toEqual([])
290 serve()
291 expect((await provider.listModels(nativeEnv, kv)).models).toHaveLength(8)
292 expect(writes).toHaveLength(6)
293 expect(
294 writes.every((key) => key.includes('#cloudflare-browser-content-v1')),
295 ).toBe(true)
296})
297it('validates cached articles and never serves a cached blocked document', async () => {
298 const writes: Array<string> = []
299 const reads: Array<string> = []
300 const kv = {
301 get: async (key: string) => {
302 reads.push(key)
303 return JSON.stringify({
304 html: sourceFailure.html,
305 hash: 'cached-source-hash',
306 })
307 },
308 put: async (key: string) => {
309 writes.push(key)
310 },
311 } as unknown as KVNamespace
312 serve(
313 Object.fromEntries(
314 Object.keys(native).map((url) => [url, sourceFailure.html]),
315 ),
316 )
317 await expect(provider.listModels(nativeEnv, kv)).rejects.toThrow(
318 `ant-ling: native source ${ANT_OPENAI}: native documentation blocked by Alipay WAF/captcha`,
319 )
320 expect(writes).toEqual([])
321 expect(reads).toHaveLength(1)
322 expect(
323 reads.every((key) => key.endsWith('#cloudflare-browser-content-v1')),
324 ).toBe(true)
325})
326it('reports malformed native HTML with its URL before it can enter the cache', async () => {
327 const { kv, writes } = docsKv()
328 serve(
329 Object.fromEntries(
330 Object.keys(native).map((url) => [
331 url,
332 '<html><body>upstream unavailable</body></html>',
333 ]),
334 ),
335 )
336 await expect(provider.listModels(nativeEnv, kv)).rejects.toThrow(
337 `ant-ling: native source ${ANT_OPENAI}: ant-ling: missing native article`,
338 )
339 expect(writes).toEqual([])
340})
341
342it('requires the browser binding even if documents are cached', async () => {
343 const { kv, writes } = docsKv()
344 await expect(provider.listModels({}, kv)).rejects.toThrow(
345 `ant-ling: native source ${ANT_OPENAI}: Cloudflare Browser Rendering BROWSER binding is required`,
346 )
347 await expect(provider.fetchSpec({})).rejects.toThrow(
348 'BROWSER binding is required',
349 )
350 expect(writes).toEqual([])
351})
352it.each([
353 [
354 'service failure',
355 () => new Response('unavailable', { status: 503 }),
356 'request failed: HTTP 503',
357 ],
358 [
359 'invalid JSON',
360 () => new Response('<html>bad wrapper</html>'),
361 'native source',
362 ],
363 [
364 'unsuccessful result',
365 () => Response.json({ success: false, errors: [] }),
366 'unreadable',
367 ],
368 [
369 'array result',
370 () =>
371 Response.json({
372 success: true,
373 result: [],
374 meta: { status: 200, finalUrl: ANT_OPENAI },
375 }),
376 'unreadable',
377 ],
378 [
379 'missing meta',
380 () => Response.json({ success: true, result: native[ANT_OPENAI] }),
381 'unreadable',
382 ],
383 [
384 'native HTTP error',
385 () =>
386 Response.json({
387 success: true,
388 result: native[ANT_OPENAI],
389 meta: { status: 403, finalUrl: ANT_OPENAI },
390 }),
391 'native page failed',
392 ],
393 [
394 'unreadable native status',
395 () =>
396 Response.json({
397 success: true,
398 result: native[ANT_OPENAI],
399 meta: { status: '200', finalUrl: ANT_OPENAI },
400 }),
401 'native page failed',
402 ],
403 [
404 'wrong native host',
405 () =>
406 Response.json({
407 success: true,
408 result: native[ANT_OPENAI],
409 meta: {
410 status: 200,
411 finalUrl: 'https://other.example/en/docs/api-reference/openai/',
412 },
413 }),
414 'URL mismatch',
415 ],
416 [
417 'wrong native page',
418 () =>
419 Response.json({
420 success: true,
421 result: native[ANT_OPENAI],
422 meta: { status: 200, finalUrl: ANT_PRICE },
423 }),
424 'URL mismatch',
425 ],
426 [
427 'missing final URL',
428 () =>
429 Response.json({
430 success: true,
431 result: native[ANT_OPENAI],
432 meta: { status: 200 },
433 }),
434 'URL mismatch',
435 ],
436] as const)(
437 'rejects browser %s without direct-fetch recovery or caching',
438 async (_name, response, error) => {
439 let directFetches = 0
440 globalThis.fetch = async () => {
441 directFetches++
442 throw new Error('direct fetch must not recover browser errors')
443 }
444 const browser = { quickAction: async () => response() } as unknown as Pick<
445 BrowserRun,
446 'quickAction'
447 >
448 const { kv, writes } = docsKv()
449 await expect(provider.listModels({ BROWSER: browser }, kv)).rejects.toThrow(
450 error,
451 )
452 expect(writes).toEqual([])
453 expect(directFetches).toBe(0)
454 },
455)
456it('hashes the rendered native HTML and bounds browser source reads sequentially', async () => {
457 const urls = serve()
458 let active = 0
459 let peak = 0
460 const browser = nativeEnv.BROWSER!
461 const originalAction = browser.quickAction.bind(browser)
462 browser.quickAction = (async (action: string, options: { url?: string }) => {
463 active++
464 peak = Math.max(peak, active)
465 try {
466 await Promise.resolve()
467 return await originalAction(
468 action as 'content',
469 options as BrowserRunContentOptions,
470 )
471 } finally {
472 active--
473 }
474 }) as typeof browser.quickAction
475 const { models } = await provider.listModels(nativeEnv)
476 expect(models).toHaveLength(8)
477 expect(urls).toHaveLength(6)
478 expect(peak).toBe(1)
479 const spec = await provider.fetchSpec(nativeEnv)
480 expect(spec.sources).toEqual([
481 { url: ANT_OPENAI, hash: await sha256Text(native[ANT_OPENAI]!) },
482 ])
483})