Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

ant-ling.ts

368 lines12.4 KB

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)
43​
44const INPUT_WORDS: Record<string, string> = {
45 text: 'text',
46 images: 'image',
47 videos: 'video',
48 audio: 'audio',
50​
51function record(value: unknown): value is Record<string, unknown> {
52 return !!value && typeof value === 'object' && !Array.isArray(value)
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
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 }
120export const provider: ProviderConfig = {
121 id: 'ant-ling',
122 displayName: 'Ant Ling',
123 specSourceUrl: ANT_OPENAI,
124 modelsEndpoint: ANT_PRICE,
125 defaultDerivation: 'docs-derived',
126 bindSyncedRoutesOnly: true,
127 perModelSchemaFlags: ['reasoning'],
128 connect: bearerConnect('https://api.ant-ling.com'),
129 async listModels(env, kv) {
130 // Sequential cache misses keep browser requests within session capacity.
131 const sources = []
132 for (const url of [
133 ANT_OPENAI,
134 ANT_OVERVIEW,
135 ANT_PRICE,
136 ANT_LING,
137 ANT_EFFORT,
138 ])
139 sources.push(await load(url, env, kv))
140 const [api, overview, pricing, ling, effort] = sources
141 if (!api || !overview || !pricing || !ling || !effort)
142 throw new Error('ant-ling: missing loaded source')
143 const overviewIds = overviewContextIds(overview.html)
144 const contexts = nativeContexts(overview.html, ling.html)
145 const { tokens: quotes, perImage } = nativePriceTable(pricing.html)
146 const cards = priceCards(quotes, {
147 url: ANT_PRICE,
148 hash: pricing.hash,
149 extractedAt: new Date().toISOString(),
150 })
151 const control = controls(api.html)
152 const fields = nativeFields(api.html)
153 const schema = nativeRequest(api.html)
154 const properties = schema.properties as Record<string, unknown>
155 const role = fields.get('messages.role')
156 if (!role) throw new Error('ant-ling: missing native role declaration')
157 const apiIds = new Set(nativeModelIds(api.html))
158 const nativePaths = Object.keys(antSpec(api.html).paths)
159 if (nativePaths.length !== 1 || !nativePaths[0])
160 throw new Error('ant-ling: unreadable native API route')
161 const nativeEndpointId = nativePaths[0].replace(/^\//, '')
162 const apiOverview = text(article(overview.html))
163 // "When using <id>, the request accepts text, images, and videos." — one
164 // statement per model that takes more than text. Since 2026-10-27 a model
165 // may read "natively accepts <list> with native multimodal understanding."
166 const accepts = new Map(
167 [
168 ...text(fields.get('model') ?? '').matchAll(
169 /When using ([\w.-]+)\s*, the request (?:natively )?accepts ([^.]+?)(?: with native multimodal understanding)?\./g,
170 ),
171 ].map(([, id = '', list = '']) => [
172 id,
173 list.split(/,\s*(?:and\s+)?|\s+and\s+/).map((word) => {
174 const modality = INPUT_WORDS[word]
175 if (!modality)
176 throw new Error(
177 `ant-ling: unreadable native input modality ${word}`,
178 )
179 return modality
180 }),
181 ]),
182 )
183 if (
184 !accepts.size ||
185 accepts.size !==
186 text(fields.get('model') ?? '').split('When using ').length - 1 ||
187 [...accepts.keys()].some((id) => !apiIds.has(id))
188 )
189 throw new Error('ant-ling: missing native multimodal applicability')
190 const levels = Object.fromEntries(
191 SHARED_EFFORT_LEVELS.map((level) => [
192 level,
193 control.efforts.includes(level) ? level : null,
194 ]),
195 ) as EffortLevelMap
196 const toggleOn = control.toggles.find((v) => v === 'enabled')
197 const toggleOff = control.toggles.find((v) => v === 'disabled')
198 if (
199 !toggleOn ||
200 !toggleOff ||
201 (control.effortIds.length > 0 &&
202 (!control.efforts.length ||
203 !control.effortDefault ||
204 !control.efforts.includes(control.effortDefault)))
205 )
206 throw new Error('ant-ling: unreadable native control values')
207 const effortText = text(article(effort.html))
208 if (!control.effortIds.every((id) => effortText.includes(id)))
209 throw new Error('ant-ling: effort source model disagreement')
210 const map: ChatRequestMap = {
211 thinking: null,
212 maxTokensField: 'max_tokens' in properties ? 'max_tokens' : null,
213 developerRole: text(role).includes('developer') ? null : false,
214 replayReasoningContent: null,
215 store: null,
216 strictTools: null,
217 sessionAffinity: null,
218 cacheControl: null,
219 toolStream: null,
220 reasoningEffort: null,
221 }
222 return {
223 models: antModelRows(api.html, pricing.html, contexts).map(
224 (model): ModelInfo => {
225 const hasEffort = control.effortIds.includes(model.rawId)
226 const hasToggle = control.toggleIds.includes(model.rawId)
227 const reasoning = hasEffort
228 ? {
229 mode: 'effort' as const,
230 mandatory: null,
231 efforts: control.efforts,
232 }
233 : hasToggle
234 ? { mode: 'toggle' as const, mandatory: false }
235 : null
236 const thinking = hasEffort
237 ? {
238 on:
239 control.effortField === 'reasoning'
240 ? { reasoning: { effort: control.effortDefault } }
241 : { reasoning_effort: control.effortDefault },
242 off: null,
243 levels,
244 }
245 : hasToggle
246 ? {
247 on: { thinking: { type: toggleOn } },
248 off: { thinking: { type: toggleOff } },
249 levels: null,
250 }
251 : null
252 const declaredText =
253 apiIds.has(model.rawId) && apiOverview.includes('Text Conversation')
254 // Text-only rows are sourced from the native text-conversation scope;
255 // a price-only ID (a newer chat ID, a per-image Ming-Image row) has
256 // no API-scoped modality statement.
257 const modalities = declaredText
258 ? {
259 input: accepts.get(model.rawId) ?? ['text'],
260 output: ['text'],
261 }
262 : null
263 const lingDetail = text(
264 blocks(article(ling.html)).get(model.rawId) ?? '',
265 )
266 const capabilities = declaredText
267 ? ['tools', ...(reasoning ? ['reasoning'] : [])]
268 : /tool calling/.test(lingDetail)
269 ? [
270 'tools',
271 ...(/hybrid reasoning/.test(lingDetail) ? ['reasoning'] : []),
272 ]
273 : null
274 const requestMap = apiIds.has(model.rawId)
275 ? { ...map, thinking }
276 : null
277 const facts = {
278 ...model,
279 modalities,
280 capabilities,
281 pricing: cards.get(model.rawId) ?? null,
282 // A per-image price is stated but no token card carries it, so
283 // no reason is given: a new row stays null, and a stored card
284 // hidden behind one is kept with a pricing_lost signal.
285 absent:
286 cards.has(model.rawId) || perImage.has(model.rawId)
287 ? undefined
288 : { pricing: 'cleared' as const },
289 schemaEndpointId: apiIds.has(model.rawId) ? nativeEndpointId : null,
290 reasoning,
291 requestMap,
292 }
293 const contextUrl = overviewIds.has(model.rawId)
294 ? ANT_OVERVIEW
295 : ANT_LING
296 const contextHash =
297 contextUrl === ANT_OVERVIEW ? overview.hash : ling.hash
298 return {
299 ...facts,
300 providerMetadata: {
301 ...(quotes.has(model.rawId)
302 ? {
303 directQuote: quotes.get(model.rawId)?.free
304 ? 'currently-free'
305 : 'paid',
306 }
307 : {}),
308 ...(control.effortIds.includes(model.rawId)
309 ? { nativeReasoningModelSource: ANT_EFFORT }
310 : {}),
311 },
312 factSources: {
313 ...(apiIds.has(model.rawId)
314 ? {
315 schemaEndpointId: {
316 derivation: 'docs-derived' as const,
317 sourceUrl: ANT_OPENAI,
318 sourceHash: api.hash,
319 path: 'Request Address + model.Options',
320 },
321 }
322 : {}),
323 ...tagDocsFacts(
324 { contextWindow: model.contextWindow },
325 contextUrl,
326 contextHash,
327 ),
328 ...tagDocsFacts({ modalities, reasoning }, ANT_OPENAI, api.hash),
329 ...(capabilities
330 ? tagDocsFacts(
331 { capabilities },
332 declaredText ? ANT_OPENAI : ANT_LING,
333 declaredText ? api.hash : ling.hash,
334 )
335 : {}),
336 ...(requestMap
337 ? {
338 requestMap: {
339 derivation: 'docs-derived' as const,
340 sourceUrl: ANT_OPENAI,
341 sourceHash: api.hash,
342 path: 'Request Body',
343 },
344 }
345 : {}),
346 ...(facts.pricing
347 ? tagDocsFacts(
348 { pricing: facts.pricing },
349 ANT_PRICE,
350 pricing.hash,
351 )
352 : {}),
353 },
354 }
355 },
356 ),
357 }
358 },
359 async fetchSpec(env) {
360 const api = await load(ANT_OPENAI, env)
361 return {
362 specs: [antSpec(api.html)],
363 sources: [{ url: ANT_OPENAI, hash: api.hash }],
364 outputStrategy: 'post-200',
365 }
366 },
367 classify: (path) => (path === '/v1/chat/completions' ? 'chat' : null),