Open History to see the last commit
1/** Public Beijing catalog and RMB quotes, without international substitution. */
2import { compileTokenCard } from '@modelschemas/rate-card'
3import type { FactSource, ModelInfo } from './types.ts'
4
5export const DASHSCOPE_CN_PRICES =
6 'https://help.aliyun.com/zh/model-studio/model-pricing.md'
7export const DASHSCOPE_CN_MODELS =
8 'https://help.aliyun.com/zh/model-studio/models.md'
9export interface CnDoc {
10 text: string
11 url: string
12 hash: string
13}
14function fail(message: string): never {
15 throw new Error(`dashscope-cn: ${message}`)
16}
17export function cnText(value: string): string {
18 return value
19 .replace(/\\</g, '<')
20 .replace(/<[^>]+>/g, ' ')
21 .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
22 .replace(/</g, '<')
23 .replace(/>/g, '>')
24 .replace(/&/g, '&')
25 .replace(/ /g, ' ')
26 .replace(/\\</g, '<')
27 .replace(/\\([_*-])/g, '$1')
28 .replace(/[*`]/g, '')
29 .replace(/\s+/g, ' ')
30 .trim()
31}
32/** Expand actual MDX rowSpan/colSpan values, including self-closing empty cells. */
33export function cnTable(table: string): string[][] {
34 const grid: string[][] = []
35 const pending = new Map<number, { text: string; remaining: number }>()
36 for (const row of table.matchAll(/<tr\b[^>]*>([\s\S]*?)<\/tr>/gi)) {
37 const values: string[] = []
38 let column = 0
39 const fill = () => {
40 while (pending.has(column)) {
41 const span = pending.get(column)!
42 values[column++] = span.text
43 if (--span.remaining === 0) pending.delete(column - 1)
44 }
45 }
46 for (const cell of row[1]!.matchAll(
47 /<t[dh]\b([^>]*?)(?:\/>|>([\s\S]*?)<\/t[dh]>)/gi,
48 )) {
49 fill()
50 const span = (name: string) => {
51 const attrs = cell[1] ?? ''
52 const found = new RegExp(
53 `${name}\\s*=\\s*(?:\\{(\\d+)\\}|"(\\d+)")`,
54 'i',
55 ).exec(attrs)
56 if (new RegExp(name, 'i').test(attrs) && !found)
57 fail('unreadable table span')
58 const value = Number(found?.[1] ?? found?.[2] ?? 1)
59 if (!Number.isSafeInteger(value) || value < 1)
60 fail('invalid table span')
61 return value
62 }
63 const across = span('colspan'),
64 down = span('rowspan')
65 for (let index = 0; index < across; index++) {
66 if (pending.has(column)) fail('overlapping table span')
67 values[column] = cell[2] ?? ''
68 if (down > 1)
69 pending.set(column, { text: cell[2] ?? '', remaining: down - 1 })
70 column++
71 }
72 }
73 fill()
74 if (values.length) grid.push(values)
75 }
76 // A rowSpan past the table's last row is clipped, as a browser shows it.
77 return grid
78}
79function cellIds(cell: string): string[] {
80 const body = cell.split(/\n\s*>/)[0] ?? ''
81 const text = cnText(body.replace(/<\/(?:p|div)>|<br\s*\/?\s*>/gi, '\n'))
82 const ids = [
83 ...new Set(
84 text.split(/\s+/).filter((id) => /^[a-z][a-z0-9_./-]+$/i.test(id)),
85 ),
86 ]
87 if (
88 !ids.length &&
89 /^参见\s*模型列表$/.test(text) &&
90 /(?:\[模型列表\]\([^)]*\)|<a\b[^>]*href=)/.test(body)
91 )
92 return []
93 if (!ids.length) fail(`unreadable model ID cell: ${text}`)
94 return ids
95}
96function activity(heading: string): ModelInfo['activity'] {
97 if (/文本生成/.test(heading)) return 'chat'
98 if (/向量|文本嵌入|多模态嵌入/.test(heading)) return 'embeddings'
99 if (/重排序|排序模型/.test(heading)) return null // The repository has no rerank activity.;
100 if (/图像|图片/.test(heading)) return 'image'
101 if (/视频/.test(heading)) return 'video'
102 if (/音频|语音|音乐/.test(heading)) return 'audio'
103 return null
104}
105function ownSource(doc: CnDoc, path: string): FactSource {
106 return {
107 derivation: 'docs-derived',
108 sourceUrl: doc.url,
109 sourceHash: doc.hash,
110 path,
111 }
112}
113function yuanPerMillion(raw: string): number {
114 const value = Number(raw) / 1e6
115 if (!Number.isFinite(value) || value < 0) fail('invalid RMB token quote')
116 return value
117}
118function amount(text: string): number {
119 const match = /^(\d+(?:\.\d+)?)元$/.exec(text)
120 if (!match) fail(`unreadable RMB token quote: ${text}`)
121 return yuanPerMillion(match[1]!)
122}
123interface YuanQuote {
124 rate: number
125 /** Cache-hit input, only when the same cell states it. */
126 cacheRead?: number
127}
128/**
129 * A plain cell is `<n>元`. It may also state the cache-hit input rate:
130 * `13元 缓存命中输入:1.3元`.
131 *
132 * `原价2元 (限时2.5折)` states a list price and the share billed while
133 * the promo runs (N折 = N/10 of list, so 2.5折 of 2元 is 0.5元). The cell
134 * names no end, so the card carries no `expiresAt` (#552). Any other promo
135 * wording throws.
136 */
137function plainQuote(text: string): YuanQuote {
138 const match =
139 /^(\d+(?:\.\d+)?)元(?:\s+缓存命中输入:(\d+(?:\.\d+)?)元)?$/.exec(text)
140 if (match) {
141 const quote: YuanQuote = { rate: yuanPerMillion(match[1]!) }
142 if (match[2] !== undefined) quote.cacheRead = yuanPerMillion(match[2])
143 return quote
144 }
145 const promo = /^原价(\d+(?:\.\d+)?)元\s*(限时(\d+(?:\.\d+)?)折)$/.exec(text)
146 if (!promo) fail(`unreadable RMB token quote: ${text}`)
147 const fold = Number(promo[2])
148 // 10折 is the list price. Above that, or a zero fold, is not this wording.
149 if (!(fold > 0) || fold > 10) fail(`unreadable RMB token quote: ${text}`)
150 return { rate: yuanPerMillion(String(Number(promo[1]) * (fold / 10))) }
151}
152/**
153 * One quote per prompt-size floor. A cell may tier itself, as MiniMax-M3's
154 * does: "输入不超过 512k Token:2.1元 输入超过 512k Token:4.2元".
155 * The cache-hit suffix is read only on a plain cell; a tiered cell that
156 * carries any other text still throws.
157 */
158function amounts(cell: string): Map<number, YuanQuote> {
159 const text = cnText(cell)
160 if (!/Token:/.test(text)) return new Map([[0, plainQuote(text)]])
161 const match =
162 /^输入不超过\s*(\d+(?:\.\d+)?)([KM])\s*Token:(\S+)\s+输入超过\s*(\d+(?:\.\d+)?)([KM])\s*Token:(\S+)$/i.exec(
163 text,
164 )
165 if (!match || match[1] !== match[4] || match[2] !== match[5])
166 fail(`unreadable tiered RMB token quote: ${text}`)
167 const bound = Number(match[1]) * (match[2]!.toUpperCase() === 'M' ? 1e6 : 1e3)
168 if (!Number.isSafeInteger(bound) || bound <= 0)
169 fail('invalid tiered token bound')
170 return new Map([
171 [0, { rate: amount(match[3]!) }],
172 [bound, { rate: amount(match[6]!) }],
173 ])
174}
175function floor(cell: string): number {
176 const text = cnText(cell).replace(/\s+/g, '')
177 if (text === '无阶梯计价' || text === '不区分阶梯') return 0
178 const match =
179 /^(\d+(?:\.\d+)?)([KM]?)<Token[≤<](?:=?)(\d+(?:\.\d+)?)([KM]?)$/i.exec(text)
180 if (!match) fail(`unreadable token range: ${text}`)
181 const scale = (unit: string) =>
182 unit.toUpperCase() === 'M' ? 1e6 : unit.toUpperCase() === 'K' ? 1e3 : 1
183 const min = Number(match[1]) * scale(match[2]!),
184 max = Number(match[3]) * scale(match[4]!)
185 if (!Number.isFinite(min) || max <= min) fail('invalid token range')
186 return min
187}
188interface Quoted {
189 models: string[]
190 mode: string
191 floor: number
192 rates: Record<string, number>
193}
194/** Balance nested model-family Tabs inside each explicitly Beijing panel. */
195export function cnBeijingTabs(
196 text: string,
197): Array<{ body: string; start: number }> {
198 const panels: Array<{ body: string; start: number }> = []
199 const stack: Array<{ start: number; bodyAt: number; beijing: boolean }> = []
200 for (const tag of text.matchAll(/<\/?Tab\b[^>]*>/g)) {
201 if (tag[0].startsWith('</')) {
202 const open = stack.pop()
203 if (!open) fail('unbalanced region Tab')
204 if (open.beijing)
205 panels.push({
206 body: text.slice(open.bodyAt, tag.index),
207 start: open.start,
208 })
209 } else
210 stack.push({
211 start: tag.index,
212 bodyAt: tag.index + tag[0].length,
213 beijing: /\btitle="华北2(北京)"/.test(tag[0]),
214 })
215 }
216 if (stack.length) fail('unclosed region Tab')
217 return panels
218}
219export function cnPriceModels(doc: CnDoc): ModelInfo[] {
220 const result = new Map<string, ModelInfo>()
221 const quoted = new Map<string, Quoted[]>()
222 let tabs = 0
223 for (const tab of cnBeijingTabs(doc.text)) {
224 tabs++
225 const prior = doc.text.slice(0, tab.start)
226 const major = [...prior.matchAll(/^## (.*)$/gm)].at(-1)?.[1] ?? ''
227 for (const table of tab.body.matchAll(/<table\b[^>]*>[\s\S]*?<\/table>/g)) {
228 const rows = cnTable(table[0])
229 const head = (rows.shift() ?? []).map(cnText)
230 const idAt = head.findIndex((column) => /模型\s*ID/.test(column))
231 if (idAt < 0) continue // Native cache/promotion tables are not model listings.
232 for (const column of head) {
233 if (
234 /^(?:输入|输出)单价.*Token/.test(column) &&
235 !/^(?:输入|输出)单价\s*(每百万\s*Token)/.test(column)
236 )
237 fail(`unknown token price unit ${column}`)
238 }
239 const inputAt = head.findIndex((column) =>
240 /^输入单价\s*(每百万\s*Token)/.test(column),
241 )
242 const multipleTokenMeters =
243 head.filter((column) => /^输入单价\s*(每百万\s*Token)/.test(column))
244 .length > 1 ||
245 head.filter((column) => /^输出单价\s*(每百万\s*Token)/.test(column))
246 .length > 1
247 while (rows[0] && cnText(rows[0][idAt] ?? '') === head[idAt]) rows.shift()
248 const outputAt = head.findIndex((column) =>
249 /^输出单价\s*(每百万\s*Token)/.test(column),
250 )
251 const rangeAt = head.findIndex((column) =>
252 /输入Token(?:数|范围|数量)/.test(column),
253 )
254 const modeAt = head.indexOf('模式')
255 for (const row of rows) {
256 if (row.length !== head.length)
257 fail(`unequal model table columns ${head.join('|')}`)
258 const ids = cellIds(row[idAt]!)
259 for (const rawId of ids) {
260 if (!result.has(rawId))
261 result.set(rawId, {
262 rawId,
263 displayName: null,
264 activity: activity(major),
265 pricing: null,
266 contextWindow: null,
267 maxOutput: null,
268 capabilities: null,
269 serverTools: null,
270 modalities: null,
271 reasoning: null,
272 requestMap: null,
273 schemaEndpointId: null,
274 absent: { pricing: 'cleared' },
275 providerMetadata: {
276 listingScope: 'public Beijing documentation',
277 nativePricingColumns: head,
278 },
279 })
280 }
281 // Dimensional audio/image/video/size pricing is sourced but requires its
282 // own usage model; it is not a single text token quote. Remain null.
283 if (inputAt < 0 || multipleTokenMeters) continue
284 if (/^已下线(?:[ >]|$)/.test(cnText(row[inputAt]!))) {
285 for (const id of ids) result.get(id)!.deprecated = true
286 continue
287 }
288 if (/^目前仅供免费体验[。.]?|^限时免费$/.test(cnText(row[inputAt]!)))
289 continue
290 if (
291 /忙时.+闲时|^(?:文本|图片|视频|音频)输入:/.test(
292 cnText(row[inputAt]!),
293 )
294 )
295 continue
296 const input = amounts(row[inputAt]!)
297 const output = outputAt >= 0 ? amounts(row[outputAt]!) : null
298 if (
299 output &&
300 JSON.stringify([...input.keys()]) !==
301 JSON.stringify([...output.keys()])
302 )
303 fail(`mismatched input and output price tiers ${ids.join(',')}`)
304 if (input.size > 1 && rangeAt >= 0)
305 fail(`tiered price cell inside a token range row ${ids.join(',')}`)
306 for (const [cellFloor, inputRate] of input) {
307 const rates: Record<string, number> = {
308 input_tokens: inputRate.rate,
309 }
310 if (inputRate.cacheRead !== undefined)
311 rates.cache_read_tokens = inputRate.cacheRead
312 const outputRate = output?.get(cellFloor)
313 if (outputRate?.cacheRead !== undefined)
314 fail(`cached-input quote on an output price ${ids.join(',')}`)
315 if (outputRate) rates.output_tokens = outputRate.rate
316 const quote: Quoted = {
317 models: ids,
318 mode: modeAt >= 0 ? cnText(row[modeAt]!) : '',
319 floor: rangeAt >= 0 ? floor(row[rangeAt]!) : cellFloor,
320 rates,
321 }
322 for (const id of ids)
323 quoted.set(id, [...(quoted.get(id) ?? []), quote])
324 }
325 }
326 }
327 }
328 if (!tabs || !result.size) fail('no Beijing model listing tables')
329 for (const [id, rows] of quoted) {
330 const modes = new Set(rows.map((row) => row.mode))
331 // Distinct thinking-mode prices cannot be selected silently.
332 if (modes.size > 1) continue
333 const tiers = new Map<number, Record<string, number>>()
334 for (const row of rows) {
335 const old = tiers.get(row.floor)
336 if (old && JSON.stringify(old) !== JSON.stringify(row.rates))
337 fail(`conflicting Beijing price ${id}`)
338 tiers.set(row.floor, row.rates)
339 }
340 const base = tiers.get(0)
341 if (
342 base &&
343 [...tiers.values()].some((rates) =>
344 Object.keys(base).some((lever) => rates[lever] === undefined),
345 )
346 )
347 fail(`incomplete price tier ${id}`)
348 if (!base) fail(`missing base price tier ${id}`)
349 const pricing = compileTokenCard(
350 base,
351 [...tiers]
352 .filter(([min]) => min > 0)
353 .sort(([a], [b]) => a - b)
354 .map(([minPromptTokens, rates]) => ({ minPromptTokens, rates })),
355 { url: doc.url, hash: doc.hash, extractedAt: new Date().toISOString() },
356 { currency: 'CNY' },
357 )
358 if (!pricing) fail(`unrepresentable token quote ${id}`)
359 const model = result.get(id)!
360 model.pricing = pricing
361 delete model.absent
362 model.factSources = {
363 pricing: ownSource(doc, '华北2(北京) model pricing table'),
364 }
365 }
366 return [...result.values()]
367}
368
369/** Exact ids and expressly included snapshots in the provider's Chinese table. */
370export function applyCnTextFacts(models: ModelInfo[], doc: CnDoc): ModelInfo[] {
371 const facts = new Map<
372 string,
373 {
374 contextWindow: number
375 capabilities: string[]
376 unsupportedCapabilities: string[]
377 snapshots: boolean
378 }
379 >()
380 for (const table of doc.text.matchAll(/<table\b[^>]*>[\s\S]*?<\/table>/g)) {
381 const rows = cnTable(table[0]),
382 head = (rows.shift() ?? []).map(cnText)
383 if (head[0] !== '模型ID' || !head.includes('上下文')) continue
384 const contextAt = head.indexOf('上下文')
385 const mapped: Record<string, string> = {
386 思考模式: 'reasoning',
387 'Function Calling': 'tools',
388 结构化输出: 'structured_outputs',
389 }
390 for (const row of rows) {
391 if (row.length !== head.length) fail('unequal native capability table')
392 const ids = [...row[0]!.matchAll(/<code>([^<]+)<\/code>/g)].map(
393 (match) => match[1]!,
394 )
395 if (!ids.length) ids.push(...cellIds(row[0]!))
396 const contextValue = cnText(row[contextAt]!),
397 match = /^(\d+(?:\.\d+)?)([KM])$/i.exec(contextValue)
398 if (!match) fail(`unreadable native context limit ${contextValue}`)
399 const contextWindow =
400 Number(match[1]) * (match[2]!.toUpperCase() === 'M' ? 1e6 : 1e3)
401 if (!Number.isSafeInteger(contextWindow) || contextWindow <= 0)
402 fail('invalid native context limit')
403 const capabilities: string[] = [],
404 unsupportedCapabilities: string[] = []
405 for (let index = 0; index < head.length; index++) {
406 const flag = mapped[head[index]!]
407 if (!flag) continue
408 const value = cnText(row[index]!)
409 // JSON Mode is a response_format yes and says nothing about strict
410 // structured outputs (same split as openai-compat's json_mode).
411 if (flag === 'structured_outputs' && value === '支持(JSON Mode)') {
412 capabilities.push('response_format')
413 continue
414 }
415 if (value !== '支持' && value !== '不支持')
416 fail(`unknown capability support value: ${value}`)
417 if (value === '支持') capabilities.push(flag)
418 else unsupportedCapabilities.push(flag)
419 }
420 for (const id of ids) {
421 const fact = {
422 contextWindow,
423 capabilities,
424 unsupportedCapabilities,
425 snapshots: /及其快照版本/.test(cnText(row[0]!)),
426 }
427 if (
428 facts.has(id) &&
429 JSON.stringify(facts.get(id)) !== JSON.stringify(fact)
430 )
431 fail('conflicting native capability rows')
432 facts.set(id, fact)
433 }
434 }
435 }
436 if (!facts.size) fail('native text catalog has no capability tables')
437 return models.map((model) => {
438 const candidates = [...facts].filter(
439 ([id, fact]) =>
440 id === model.rawId ||
441 (fact.snapshots &&
442 model.rawId.startsWith(`${id}-`) &&
443 /^\d{4}-\d{2}-\d{2}$/.test(model.rawId.slice(id.length + 1))),
444 )
445 if (candidates.length > 1) fail('ambiguous native snapshot scope')
446 const fact = candidates[0]?.[1]
447 if (!fact) return model
448 return {
449 ...model,
450 contextWindow: fact.contextWindow,
451 capabilities: fact.capabilities,
452 unsupportedCapabilities: fact.unsupportedCapabilities,
453 factSources: {
454 ...model.factSources,
455 contextWindow: ownSource(doc, '上下文'),
456 capabilities: Object.fromEntries(
457 [...fact.capabilities, ...fact.unsupportedCapabilities].map(
458 (flag) => [flag, ownSource(doc, `model capability table.${flag}`)],
459 ),
460 ),
461 },
462 }
463 })
464}
465
466/** Own card headings define exact ids; Beijing capability tables alone win. */
467export function applyCnCardFacts(models: ModelInfo[], doc: CnDoc): ModelInfo[] {
468 const byId = new Map<
469 string,
470 Partial<Omit<ModelInfo, 'capabilities'>> & { capabilities?: string[] }
471 >()
472 const completed = new Map<string, Set<string>>()
473 let current: string | null = null
474 const starts = [...doc.text.matchAll(/^#{1,6}\s+([^\n]+)$/gm)]
475 for (let index = 0; index < starts.length; index++) {
476 const heading = cnText(starts[index]![1]!)
477 if (/^[a-z][a-z0-9._-]*-[a-z0-9._-]+$/.test(heading)) current = heading
478 if (!current) continue
479 const section = doc.text.slice(
480 starts[index]!.index + starts[index]![0].length,
481 starts[index + 1]?.index ?? doc.text.length,
482 )
483 const facts = byId.get(current) ?? {}
484 const seen = completed.get(current) ?? new Set<string>()
485 if (heading === '上下文限制') {
486 for (const table of section.matchAll(
487 /<table\b[^>]*>[\s\S]*?<\/table>/g,
488 )) {
489 for (const row of cnTable(table[0]).slice(1))
490 for (let column = 0; column + 1 < row.length; column += 2) {
491 const label = cnText(row[column]!),
492 text = cnText(row[column + 1]!)
493 if (label !== '上下文长度' && label !== '最大输出长度') continue
494 if (
495 !/^\d+$/.test(text) ||
496 !Number.isSafeInteger(Number(text)) ||
497 Number(text) <= 0
498 )
499 fail('unreadable card token limit')
500 const key = label === '上下文长度' ? 'contextWindow' : 'maxOutput'
501 if (facts[key] != null && facts[key] !== Number(text))
502 fail('conflicting card token limit')
503 facts[key] = Number(text)
504 seen.add(key)
505 }
506 }
507 }
508 if (heading === '模型能力') {
509 const modes: Record<string, string> = {
510 Text: 'text',
511 Image: 'image',
512 Audio: 'audio',
513 Video: 'video',
514 }
515 let input: string[] | null = null,
516 output: string[] | null = null
517 const flags = new Set<string>(),
518 unsupported = new Set<string>()
519 const checked = new Set<string>()
520 const panels = cnBeijingTabs(section)
521 if (!panels.length) fail('card has no Beijing capability panel')
522 for (const panel of panels)
523 for (const table of panel.body.matchAll(
524 /<table\b[^>]*>[\s\S]*?<\/table>/g,
525 )) {
526 for (const row of cnTable(table[0]).slice(1))
527 for (let column = 0; column + 1 < row.length; column += 2) {
528 const label = cnText(row[column]!),
529 value = cnText(row[column + 1]!)
530 if (label === '输入模态' || label === '输出模态') {
531 const kinds = value
532 .split(/[,,/\s]+/)
533 .map(
534 (kind) =>
535 modes[kind] ?? fail(`unknown card modality ${kind}`),
536 )
537 const old = label === '输入模态' ? input : output
538 if (old && JSON.stringify(old) !== JSON.stringify(kinds))
539 fail('conflicting card modality')
540 if (label === '输入模态') input = kinds
541 else output = kinds
542 }
543 const flag =
544 label === 'Function Calling'
545 ? 'tools'
546 : label === '结构化输出'
547 ? 'structured_outputs'
548 : null
549 if (flag) {
550 if (value !== '支持' && value !== '不支持')
551 fail('unknown card capability status')
552 if (
553 (flags.has(flag) && value === '不支持') ||
554 (unsupported.has(flag) && value === '支持')
555 )
556 fail('conflicting card capability status')
557 checked.add(flag)
558 if (value === '支持') flags.add(flag)
559 else unsupported.add(flag)
560 }
561 }
562 }
563 if (
564 !input ||
565 !output ||
566 !checked.has('tools') ||
567 !checked.has('structured_outputs')
568 )
569 fail('incomplete Beijing card capability table')
570 facts.modalities = { input, output }
571 facts.capabilities = [...flags]
572 facts.unsupportedCapabilities = [...unsupported]
573 seen.add('capabilities')
574 }
575 byId.set(current, facts)
576 completed.set(current, seen)
577 }
578 if (!byId.size) fail('own card names no model ids')
579 for (const [id, seen] of completed)
580 if (
581 !['contextWindow', 'maxOutput', 'capabilities'].every((key) =>
582 seen.has(key),
583 )
584 )
585 fail(`incomplete native card ${id}`)
586 return models.map((model) => {
587 const fact = byId.get(model.rawId)
588 if (!fact) return model
589 const capabilities = [
590 ...new Set([
591 ...(Array.isArray(model.capabilities)
592 ? (model.capabilities as string[]).filter(
593 (flag) =>
594 !Array.isArray(fact.capabilities) ||
595 (flag !== 'tools' && flag !== 'structured_outputs'),
596 )
597 : []),
598 ...(Array.isArray(fact.capabilities) ? fact.capabilities : []),
599 ]),
600 ]
601 const sources = { ...model.factSources }
602 if (fact.contextWindow != null)
603 sources.contextWindow = ownSource(doc, '上下文限制.上下文长度')
604 if (fact.maxOutput != null)
605 sources.maxOutput = ownSource(doc, '上下文限制.最大输出长度')
606 if (fact.modalities != null)
607 sources.modalities = ownSource(
608 doc,
609 '华北2(北京).模型能力.输入/输出模态',
610 )
611 if (Array.isArray(fact.capabilities))
612 sources.capabilities = {
613 ...Object.fromEntries(
614 Object.entries(model.factSources?.capabilities ?? {}).filter(
615 ([flag]) => flag !== 'tools' && flag !== 'structured_outputs',
616 ),
617 ),
618 ...Object.fromEntries(
619 [...fact.capabilities, ...(fact.unsupportedCapabilities ?? [])].map(
620 (flag) => [flag, ownSource(doc, `华北2(北京).模型能力.${flag}`)],
621 ),
622 ),
623 }
624 const unsupportedCapabilities = [
625 ...new Set([
626 ...(model.unsupportedCapabilities ?? []).filter(
627 (flag) => !['tools', 'structured_outputs'].includes(flag),
628 ),
629 ...(fact.unsupportedCapabilities ?? []),
630 ]),
631 ]
632 return {
633 ...model,
634 ...fact,
635 capabilities,
636 unsupportedCapabilities,
637 factSources: sources,
638 }
639 })
640}
641
642const CN_CONSOLE_DETAIL =
643 'https:\\/\\/bailian\\.console\\.aliyun\\.com\\/cn-beijing\\/model\\/market\\/detail\\/[^"?#]+'
644
645/**
646 * Beijing console links on the selection page: `<a href>name</a>`, or the
647 * MDX `<Card title="name" href>` the page uses as of 2026-10-27.
648 */
649function cnConsoleLinks(text: string) {
650 const links: { href: string; name: string; index: number }[] = []
651 for (const anchor of text.matchAll(
652 new RegExp(
653 `<a\\b[^>]*href="(${CN_CONSOLE_DETAIL})"[^>]*>([\\s\\S]*?)<\\/a>`,
654 'g',
655 ),
656 ))
657 links.push({ href: anchor[1]!, name: anchor[2]!, index: anchor.index })
658 for (const card of text.matchAll(/<Card\b([^>]*)>/g)) {
659 const href = /(?:^|\s)href="([^"]+)"/.exec(card[1]!)?.[1]
660 if (!href || !new RegExp(`^${CN_CONSOLE_DETAIL}$`).test(href)) continue
661 const name = /(?:^|\s)title="([^"]*)"/.exec(card[1]!)?.[1]
662 if (name === undefined) fail('native console card has no title')
663 links.push({ href, name, index: card.index })
664 }
665 return links.sort((a, b) => a.index - b.index)
666}
667
668/** Native CN console links publish their exact encoded model ids. */
669export function applyCnCatalog(models: ModelInfo[], doc: CnDoc): ModelInfo[] {
670 const out = new Map(models.map((model) => [model.rawId, model]))
671 let count = 0
672 for (const link of cnConsoleLinks(doc.text)) {
673 const encoded = new URL(link.href).pathname.split('/detail/')[1]
674 if (!encoded) fail('empty native console id')
675 const rawId = decodeURIComponent(encoded)
676 if (!/^[a-z][a-z0-9_./-]+$/i.test(rawId))
677 fail('malformed native console id')
678 count++
679 if (out.has(rawId)) {
680 out.get(rawId)!.displayName = cnText(link.name) || null
681 continue
682 }
683 const prior = doc.text.slice(0, link.index)
684 const major = [...prior.matchAll(/^## (.*)$/gm)].at(-1)?.[1] ?? ''
685 const ambiguous = /图像与视频|向量与重排序/.test(major)
686 out.set(rawId, {
687 rawId,
688 displayName: cnText(link.name) || null,
689 activity: ambiguous ? null : activity(major),
690 pricing: null,
691 absent: { pricing: 'cleared' },
692 contextWindow: null,
693 maxOutput: null,
694 modalities: null,
695 capabilities: null,
696 serverTools: null,
697 reasoning: null,
698 requestMap: null,
699 schemaEndpointId: null,
700 providerMetadata: {
701 listingScope: 'public Beijing console links',
702 catalogSource: doc.url,
703 },
704 })
705 }
706 if (!count) fail('native selection docs have no Beijing console models')
707 return [...out.values()]
708}