Open History to see the last commit
1/** Dynamic direct Ant Ling facts; never reseller prices or borrowed schemas. */
2import { cachedDocs } from '../model-facts.ts'
3import { tagDocsFacts } from '../fact-sources.ts'
4import { bearerConnect } from '../connect.ts'
5import { sha256Text } from '../types.ts'
6import { SHARED_EFFORT_LEVELS } from '../request-map.ts'
7import type { ChatRequestMap, EffortLevelMap } from '../request-map.ts'
8import type {
9 ModelInfo,
10 ProviderConfig,
11 ProviderEnvironment,
12} from '../types.ts'
13import {
14 ANT_OPENAI,
15 ANT_OVERVIEW,
16 ANT_PRICE,
17 ANT_LING,
18 ANT_EFFORT,
19 text,
20 article,
21 controls,
22 blocks,
23 overviewContextIds,
24 antModelRows,
25 nativeModelIds,
26 nativePriceTable,
27 priceCards,
28 nativeContexts,
29 nativeFields,
30 nativeRequest,
31 antSpec,
32} from '../ant-ling-docs.ts'
33
34function validateNativeArticle(html: string): void {
35 if (
36 /window\.netd\s*=|id=["']netd-iframe["']|waf\.alipay\.com\/api\/v1\/sec-human-appeal/.test(
37 html,
38 )
39 )
40 throw new Error('native documentation blocked by Alipay WAF/captcha')
41 article(html)
42}
43
44const INPUT_WORDS: Record<string, string> = {
45 text: 'text',
46 images: 'image',
47 videos: 'video',
48 audio: 'audio',
49}
50
51function record(value: unknown): value is Record<string, unknown> {
52 return !!value && typeof value === 'object' && !Array.isArray(value)
53}
54
55async function browserHtml(
56 url: string,
57 env: ProviderEnvironment,
58): Promise<string> {
59 if (!env.BROWSER || typeof env.BROWSER.quickAction !== 'function')
60 throw new Error('Cloudflare Browser Rendering BROWSER binding is required')
61 const response = await env.BROWSER.quickAction('content', {
62 url,
63 gotoOptions: { timeout: 30_000, waitUntil: 'domcontentloaded' },
64 actionTimeout: 30_000,
65 })
66 if (!response.ok)
67 throw new Error(
68 `Cloudflare Browser Rendering request failed: HTTP ${response.status}`,
69 )
70 const body: unknown = await response.json()
71 if (
72 !record(body) ||
73 body.success !== true ||
74 typeof body.result !== 'string' ||
75 !record(body.meta)
76 )
77 throw new Error('unreadable Cloudflare Browser Rendering content response')
78 const meta = body.meta
79 if (
80 typeof meta.status !== 'number' ||
81 !Number.isInteger(meta.status) ||
82 meta.status < 200 ||
83 meta.status >= 300
84 )
85 throw new Error(
86 `Cloudflare Browser Rendering native page failed: status ${String(meta.status)}`,
87 )
88 if (
89 typeof meta.finalUrl !== 'string' ||
90 new URL(meta.finalUrl).href !== new URL(url).href
91 )
92 throw new Error('Cloudflare Browser Rendering native page URL mismatch')
93 return body.result
94}
95
96async function load(url: string, env: ProviderEnvironment, kv?: KVNamespace) {
97 try {
98 if (!env.BROWSER || typeof env.BROWSER.quickAction !== 'function')
99 throw new Error(
100 'Cloudflare Browser Rendering BROWSER binding is required',
101 )
102 const doc = await cachedDocs(
103 kv,
104 `ant-ling:${url}#cloudflare-browser-content-v1`,
105 async () => {
106 const html = await browserHtml(url, env)
107 validateNativeArticle(html)
108 return { html, hash: await sha256Text(html) }
109 },
110 )
111 validateNativeArticle(doc.html)
112 return doc
113 } catch (error) {
114 throw new Error(
115 `ant-ling: native source ${url}: ${error instanceof Error ? error.message : String(error)}`,
116 { cause: error },
117 )
118 }
119}
120export const provider: ProviderConfig = {
121 id: 'ant-ling',
122 // Ant's Hugging Face org (`inclusionAI/Ling-3.1-flash`).
123 modelNamespaces: ['inclusionAI'],
124 displayName: 'Ant Ling',
125 specSourceUrl: ANT_OPENAI,
126 modelsEndpoint: ANT_PRICE,
127 defaultDerivation: 'docs-derived',
128 bindSyncedRoutesOnly: true,
129 perModelSchemaFlags: ['reasoning'],
130 connect: bearerConnect('https://api.ant-ling.com'),
131 async listModels(env, kv) {
132 // Sequential cache misses keep browser requests within session capacity.
133 const sources = []
134 for (const url of [
135 ANT_OPENAI,
136 ANT_OVERVIEW,
137 ANT_PRICE,
138 ANT_LING,
139 ANT_EFFORT,
140 ])
141 sources.push(await load(url, env, kv))
142 const [api, overview, pricing, ling, effort] = sources
143 if (!api || !overview || !pricing || !ling || !effort)
144 throw new Error('ant-ling: missing loaded source')
145 const overviewIds = overviewContextIds(overview.html)
146 const contexts = nativeContexts(overview.html, ling.html)
147 const { tokens: quotes, perImage } = nativePriceTable(pricing.html)
148 const cards = priceCards(quotes, {
149 url: ANT_PRICE,
150 hash: pricing.hash,
151 extractedAt: new Date().toISOString(),
152 })
153 const control = controls(api.html)
154 const fields = nativeFields(api.html)
155 const schema = nativeRequest(api.html)
156 const properties = schema.properties as Record<string, unknown>
157 const role = fields.get('messages.role')
158 if (!role) throw new Error('ant-ling: missing native role declaration')
159 const apiIds = new Set(nativeModelIds(api.html))
160 const nativePaths = Object.keys(antSpec(api.html).paths)
161 if (nativePaths.length !== 1 || !nativePaths[0])
162 throw new Error('ant-ling: unreadable native API route')
163 const nativeEndpointId = nativePaths[0].replace(/^\//, '')
164 const apiOverview = text(article(overview.html))
165 // "When using <id>, the request accepts text, images, and videos." — one
166 // statement per model that takes more than text. Since 2026-10-27 a model
167 // may read "natively accepts <list> with native multimodal understanding."
168 const accepts = new Map(
169 [
170 ...text(fields.get('model') ?? '').matchAll(
171 /When using ([\w.-]+)\s*, the request (?:natively )?accepts ([^.]+?)(?: with native multimodal understanding)?\./g,
172 ),
173 ].map(([, id = '', list = '']) => [
174 id,
175 list.split(/,\s*(?:and\s+)?|\s+and\s+/).map((word) => {
176 const modality = INPUT_WORDS[word]
177 if (!modality)
178 throw new Error(
179 `ant-ling: unreadable native input modality ${word}`,
180 )
181 return modality
182 }),
183 ]),
184 )
185 if (
186 !accepts.size ||
187 accepts.size !==
188 text(fields.get('model') ?? '').split('When using ').length - 1 ||
189 [...accepts.keys()].some((id) => !apiIds.has(id))
190 )
191 throw new Error('ant-ling: missing native multimodal applicability')
192 const levels = Object.fromEntries(
193 SHARED_EFFORT_LEVELS.map((level) => [
194 level,
195 control.efforts.includes(level) ? level : null,
196 ]),
197 ) as EffortLevelMap
198 const toggleOn = control.toggles.find((v) => v === 'enabled')
199 const toggleOff = control.toggles.find((v) => v === 'disabled')
200 if (
201 !toggleOn ||
202 !toggleOff ||
203 (control.effortIds.length > 0 &&
204 (!control.efforts.length ||
205 !control.effortDefault ||
206 !control.efforts.includes(control.effortDefault)))
207 )
208 throw new Error('ant-ling: unreadable native control values')
209 const effortText = text(article(effort.html))
210 if (!control.effortIds.every((id) => effortText.includes(id)))
211 throw new Error('ant-ling: effort source model disagreement')
212 const map: ChatRequestMap = {
213 thinking: null,
214 maxTokensField: 'max_tokens' in properties ? 'max_tokens' : null,
215 developerRole: text(role).includes('developer') ? null : false,
216 replayReasoningContent: null,
217 store: null,
218 strictTools: null,
219 sessionAffinity: null,
220 cacheControl: null,
221 toolStream: null,
222 reasoningEffort: null,
223 }
224 return {
225 models: antModelRows(api.html, pricing.html, contexts).map(
226 (model): ModelInfo => {
227 const hasEffort = control.effortIds.includes(model.rawId)
228 const hasToggle = control.toggleIds.includes(model.rawId)
229 const reasoning = hasEffort
230 ? {
231 mode: 'effort' as const,
232 mandatory: null,
233 efforts: control.efforts,
234 }
235 : hasToggle
236 ? { mode: 'toggle' as const, mandatory: false }
237 : null
238 const thinking = hasEffort
239 ? {
240 on:
241 control.effortField === 'reasoning'
242 ? { reasoning: { effort: control.effortDefault } }
243 : { reasoning_effort: control.effortDefault },
244 off: null,
245 levels,
246 }
247 : hasToggle
248 ? {
249 on: { thinking: { type: toggleOn } },
250 off: { thinking: { type: toggleOff } },
251 levels: null,
252 }
253 : null
254 const declaredText =
255 apiIds.has(model.rawId) && apiOverview.includes('Text Conversation')
256 // Text-only rows are sourced from the native text-conversation scope;
257 // a price-only ID (a newer chat ID, a per-image Ming-Image row) has
258 // no API-scoped modality statement.
259 const modalities = declaredText
260 ? {
261 input: accepts.get(model.rawId) ?? ['text'],
262 output: ['text'],
263 }
264 : null
265 const lingDetail = text(
266 blocks(article(ling.html)).get(model.rawId) ?? '',
267 )
268 const capabilities = declaredText
269 ? ['tools', ...(reasoning ? ['reasoning'] : [])]
270 : /tool calling/.test(lingDetail)
271 ? [
272 'tools',
273 ...(/hybrid reasoning/.test(lingDetail) ? ['reasoning'] : []),
274 ]
275 : null
276 const requestMap = apiIds.has(model.rawId)
277 ? { ...map, thinking }
278 : null
279 const facts = {
280 ...model,
281 modalities,
282 capabilities,
283 pricing: cards.get(model.rawId) ?? null,
284 // A per-image price is stated but no token card carries it, so
285 // no reason is given: a new row stays null, and a stored card
286 // hidden behind one is kept with a pricing_lost signal.
287 absent:
288 cards.has(model.rawId) || perImage.has(model.rawId)
289 ? undefined
290 : { pricing: 'cleared' as const },
291 schemaEndpointId: apiIds.has(model.rawId) ? nativeEndpointId : null,
292 reasoning,
293 requestMap,
294 }
295 const contextUrl = overviewIds.has(model.rawId)
296 ? ANT_OVERVIEW
297 : ANT_LING
298 const contextHash =
299 contextUrl === ANT_OVERVIEW ? overview.hash : ling.hash
300 return {
301 ...facts,
302 providerMetadata: {
303 ...(quotes.has(model.rawId)
304 ? {
305 directQuote: quotes.get(model.rawId)?.free
306 ? 'currently-free'
307 : 'paid',
308 }
309 : {}),
310 ...(control.effortIds.includes(model.rawId)
311 ? { nativeReasoningModelSource: ANT_EFFORT }
312 : {}),
313 },
314 factSources: {
315 ...(apiIds.has(model.rawId)
316 ? {
317 schemaEndpointId: {
318 derivation: 'docs-derived' as const,
319 sourceUrl: ANT_OPENAI,
320 sourceHash: api.hash,
321 path: 'Request Address + model.Options',
322 },
323 }
324 : {}),
325 ...tagDocsFacts(
326 { contextWindow: model.contextWindow },
327 contextUrl,
328 contextHash,
329 ),
330 ...tagDocsFacts({ modalities, reasoning }, ANT_OPENAI, api.hash),
331 ...(capabilities
332 ? tagDocsFacts(
333 { capabilities },
334 declaredText ? ANT_OPENAI : ANT_LING,
335 declaredText ? api.hash : ling.hash,
336 )
337 : {}),
338 ...(requestMap
339 ? {
340 requestMap: {
341 derivation: 'docs-derived' as const,
342 sourceUrl: ANT_OPENAI,
343 sourceHash: api.hash,
344 path: 'Request Body',
345 },
346 }
347 : {}),
348 ...(facts.pricing
349 ? tagDocsFacts(
350 { pricing: facts.pricing },
351 ANT_PRICE,
352 pricing.hash,
353 )
354 : {}),
355 },
356 }
357 },
358 ),
359 }
360 },
361 async fetchSpec(env) {
362 const api = await load(ANT_OPENAI, env)
363 return {
364 specs: [antSpec(api.html)],
365 sources: [{ url: ANT_OPENAI, hash: api.hash }],
366 outputStrategy: 'post-200',
367 }
368 },
369 classify: (path) => (path === '/v1/chat/completions' ? 'chat' : null),
370}