Open History to see the last commit
1/**
2 * Shared helpers for catalog facts the native `/models` endpoints omit
3 * (issue #53): context window, max output, modalities, request-feature
4 * capabilities. Docs parses fail closed (zero rows throws). Parsed docs
5 * live in KV for six hours so cron isolates do not refetch every tick.
6 */
7import { errorMessage } from '#/server/errors.ts'
8import { noteIngest, parseRowsEvent } from '#/server/ingest/ingest-signals.ts'
9import { getJson, putJson } from '#/server/kv.ts'
10
11import type { DocsFailures, ModelFact, ModelInfo } from './types.ts'
12
13export type ModelFacts = Pick<
14 ModelInfo,
15 | 'contextWindow'
16 | 'maxOutput'
17 | 'modalities'
18 | 'capabilities'
19 | 'pricing'
20 | 'reasoning'
21 | 'serverTools'
22 | 'factSources'
23>
24
25export const NO_FACTS: ModelFacts = {
26 contextWindow: null,
27 maxOutput: null,
28 modalities: null,
29 capabilities: null,
30 pricing: null,
31}
32
33/**
34 * Snapshot ids fall back to their alias:
35 * `gpt-5-2025-08-07` → `gpt-5`, `claude-opus-4-5-20251101` → `claude-opus-4-5`.
36 */
37export function undatedId(rawId: string): string {
38 return rawId.replace(/-\d{4}-\d{2}-\d{2}$|-\d{8}$/, '')
39}
40
41const MONTHS = [
42 'january',
43 'february',
44 'march',
45 'april',
46 'may',
47 'june',
48 'july',
49 'august',
50 'september',
51 'october',
52 'november',
53 'december',
54]
55
56/** `December 31, 2026` → that day's UTC midnight, case-insensitive. */
57export function parseDay(text: string): number | null {
58 const match = text
59 .trim()
60 .toLowerCase()
61 .match(/^([a-z]+) (\d{1,2}), (\d{4})$/)
62 const month = match?.[1] ? MONTHS.indexOf(match[1]) : -1
63 if (!match || month < 0) return null
64 return Date.UTC(Number(match[3]), month, Number(match[2]))
65}
66
67/** `1,048,576` / `500k` / `1M` → number. */
68export function tokenCount(text: string | undefined): number | null {
69 const match = text?.match(/([\d,]*\.?\d+)\s*([kKmM])?/)
70 if (!match?.[1]) return null
71 const base = Number(match[1].replace(/,/g, ''))
72 const unit = match[2]?.toLowerCase()
73 return Math.round(base * (unit === 'm' ? 1e6 : unit === 'k' ? 1e3 : 1))
74}
75
76/**
77 * Every `| a | b |` row in a markdown document as trimmed cells, separator
78 * rows dropped. Callers pick rows by content; header rows come along.
79 */
80export function markdownTableRows(text: string): Array<Array<string>> {
81 const rows: Array<Array<string>> = []
82 // A cell may hold a newline ("Portrait: 720x1280\nLandscape: 1280x720"),
83 // splitting one row over two lines; join until the row closes, and give
84 // up on a line that carries no cell of its own.
85 let pending = ''
86 for (const line of text.split('\n')) {
87 if (pending === '') {
88 if (!line.startsWith('|')) continue
89 pending = line
90 } else if (line.includes('|')) {
91 pending = `${pending} ${line}`
92 } else {
93 pending = ''
94 continue
95 }
96 if (!pending.endsWith('|')) continue
97 const cells = pending
98 .slice(1, -1)
99 .split('|')
100 .map((cell) => cell.trim())
101 pending = ''
102 if (cells.every((cell) => /^:?-+:?$/.test(cell))) continue
103 rows.push(cells)
104 }
105 return rows
106}
107
108/** Text of one Markdoc table cell, its lines already de-indented. */
109function markdocCell(lines: Array<string>): string {
110 let out = ''
111 for (const line of lines) {
112 if (line.trim() === '') {
113 // A paragraph break inside a cell reads as one space.
114 if (out !== '' && !out.endsWith(' ') && !out.endsWith('<br>')) out += ' '
115 continue
116 }
117 // Two trailing spaces, or a trailing backslash, are a hard line break:
118 // one price per line.
119 const hard = /( {2,}|\\+\s*)$/.test(line)
120 const text = line.replace(/\s*\\+\s*$/, '').trim()
121 out += `${out === '' || out.endsWith(' ') || out.endsWith('<br>') ? '' : ' '}${text}`
122 if (hard) out += '<br>'
123 }
124 return (
125 out
126 .replace(/(?:<br>\s*)+$/, '')
127 // Footnote markers are not part of the value.
128 .replace(/\{%\s*sup\s*%\}[\s\S]*?\{%\s*\/sup\s*%\}/g, '')
129 // `label=Supported (low, medium, high)` is the badge's whole text.
130 .replace(/\{%\s*badge\s+label=("?)(.*?)\1\s+type="[^"]*"\s*\/%\}/g, '$2')
131 .replace(/\{%\s*badge type="supported"\s*\/%\}/g, 'Supported')
132 .replace(/\{%\s*badge type="not-supported"\s*\/%\}/g, 'Not supported')
133 .replace(/\{%[\s\S]*?%\}/g, '')
134 // `[**Name**](url)` reads as the `**[Name](url)**` older pages used.
135 .replace(/\[\*\*([^\]*]+)\*\*\]\(([^)]*)\)/g, '**[$1]($2)**')
136 .replace(/\|/g, '/')
137 .replace(/\s+/g, ' ')
138 .trim()
139 )
140}
141
142/**
143 * Rewrites every Markdoc `{% table %}` block (the aistudio.google.com docs
144 * format) as `| a | b |` rows, one line per row, so `markdownTableRows` and
145 * line-based parsers read it. Rows are split by `---`; a cell is a `* `
146 * item at the row's own indent, and a deeper `* ` stays inside its cell.
147 * A hard line break inside a cell becomes `<br>`. Everything outside the
148 * tables is left as it is.
149 */
150export function markdocTables(text: string): string {
151 return text.replace(
152 /^[ \t]*\{%\s*table\b[^%]*%\}[ \t]*\n([\s\S]*?)^[ \t]*\{%\s*\/table\s*%\}[ \t]*$/gm,
153 (_block, body: string) =>
154 body
155 .split(/^[ \t]*---[ \t]*$/m)
156 .map((row) => {
157 const lines = row.split('\n')
158 const indent = lines.find((line) => /^\s*\* /.test(line))
159 if (indent === undefined) return null
160 const marker = indent.slice(0, indent.indexOf('*'))
161 const cells: Array<Array<string>> = []
162 for (const line of lines) {
163 if (line.startsWith(`${marker}* `) || line === `${marker}*`) {
164 cells.push([line.slice(marker.length + 1)])
165 } else {
166 cells.at(-1)?.push(line)
167 }
168 }
169 return `| ${cells.map(markdocCell).join(' | ')} |`
170 })
171 .filter((row) => row !== null)
172 .join('\n'),
173 )
174}
175
176/**
177 * One `## <heading>` section of a markdown document, up to the next `## `.
178 * Empty when the heading is absent.
179 */
180export function markdownSection(text: string, heading: string): string {
181 const start = text.indexOf(`\n## ${heading}`)
182 if (start < 0) return ''
183 const rest = text.slice(start + 1)
184 const end = rest.indexOf('\n## ')
185 return end < 0 ? rest : rest.slice(0, end)
186}
187
188/**
189 * One page of a Mintlify `llms-full.txt`: each page opens with a `# <title>`
190 * line followed by `Source: <url>`, and runs to the next such pair. Throws
191 * unless exactly one page names `url`.
192 */
193export function llmsFullPage(text: string, url: string): string {
194 const lines = text.split('\n')
195 const opens = (index: number) =>
196 lines[index]?.startsWith('# ') === true &&
197 lines[index + 1]?.startsWith('Source: ') === true
198 const starts = lines.flatMap((_line, index) =>
199 opens(index) && lines[index + 1] === `Source: ${url}` ? [index] : [],
200 )
201 if (starts.length !== 1) {
202 throw new Error(
203 `llms-full.txt names ${url} ${String(starts.length)} times, not once`,
204 )
205 }
206 const start = starts[0] ?? 0
207 let end = start + 2
208 while (end < lines.length && !opens(end)) end += 1
209 return lines.slice(start, end).join('\n')
210}
211
212export const DOCS_TTL_SECONDS = 6 * 60 * 60
213
214/**
215 * Bumped whenever a parsed-docs shape changes. A deploy that changed the
216 * shape would otherwise read the old one back out of KV for six hours and
217 * see missing fields as missing facts.
218 */
219// v7: OpenAI model pages price the first token table and only the default
220// snapshot. A v6 entry would keep o3's batch table and gpt-4o's old snapshot.
221// v8: Grok model-page cache includes maxOutput (#119).
222// v9: BytePlus and Mistral cached docs include serverTools. A v8 entry
223// would keep the old card and leave tools null for six hours.
224// v10: BytePlus image and video cards copy published alias ids. A v9 entry
225// would leave those aliases unpriced for six hours.
226// v11: Grok maxOutput (#119) lands after v10 shipped; a v10 entry has no
227// maxOutput on Grok pages for six hours.
228// v12: Azure rows gain `tabulated` and the price doc gains `thresholds`. A
229// v11 entry written by the PR's preview build would drop every Azure row.
230// v13: MiniMax M2 rows store no maxOutput (the spec maximum is the context
231// window). A v12 entry would keep 204800 on them for six hours.
232// v14: Gemini and Mistral model pages gain `modalities`. A v13 entry has
233// none, and the schema walk that used to fill the field no longer does.
234// v15: open fill-gaps PRs #242 and #244. Do not reuse.
235// v16: Mistral model pages gain maxOutput and page pricing, and the pricing
236// doc stores the table without those pages. A v14 entry would keep Large 4's
237// sale row skipped and leave the new fields null for six hours.
238// v21: Azure rows gain effort lists, request maps, and the gpt-4 /
239// computer-use-preview meter match. A v16 entry would leave those null
240// for six hours.
241// v22: DashScope compat cache includes `scope`. A v21 entry has no scope,
242// so a chat id the page does not name would still get the compat map.
243// v23: Gemini's cached index is `{url, ids}` rows, thinking pages cache
244// budget bodies, and model pages cache per-id sections. Thinking-level
245// `mandatory` is true only when the page says that family cannot turn
246// thinking off. A v22 entry has none of that, so Gemini facts read from
247// it would stay null or mark every level column mandatory.
248// v24: Cerebras model pages include paid maxOutput. A v23 entry has no
249// maxOutput and would leave it null for six hours.
250// v25: Bedrock cards gain request maps, feature flags, and price-list
251// rates. A v24 entry would leave those null for six hours.
252// v26: Together reasoning pages and the serverless chat catalog cache
253// plain records. A v25 entry stored Maps, which JSON reads back as {},
254// and the next poll throws before any together row is written.
255// v27: native reasoning controls now distinguish published levels, mandatory
256// status and genuine source silence. Re-read cached parsed facts so earlier
257// guesses cannot survive the new parsers until the six-hour TTL expires.
258// v28: re-read native budget applicability and replay declarations after the
259// scoped guide enrichments and stricter normative-prose checks.
260// v30: DashScope China priced rows no longer carry absent.pricing 'cleared'.
261// A v29 entry would keep dropping every CNY card for six hours.
262// v31: the Gemini pricing entry gained `named`; a v30 entry has none.
263// v32: OpenAI "only supports" a non-none effort is mandatory true. A v31
264// model-page entry would keep gpt-5-pro at mandatory null for six hours.
265// v33: Vertex Claude card titles drop a leading "Anthropic's" (#390). A v32
266// entry keeps every row unpriced, so the poll refuses the clear for six hours.
267// v34: OpenAI pages add `file` input from `file_uploads` and Mistral pages from
268// `document-qna` (#407). A v33 entry would keep them without it for six hours.
269// v35: Mistral pages cache their Features (and the web search guide is read);
270// Gemini caches probed pages; Perplexity caches stated limits
271// (#408, #409). A v34 entry has none of them for six hours.
272// v36: Mistral OCR cells take the unit from their "Prices /1000 Pages"
273// header (#439). A v35 entry would keep OCR rows unpriced for six hours.
274// v37: DeepSeek cards store off-peak and peak behind pricing_period (#449).
275// A v36 entry would keep serving the off-peak rate alone for six hours.
276// v38: Anthropic Haiku 5.5 stores the over-100k prompt tier (#481). A v37
277// entry is the short rate alone and would underprice long prompts for six
278// hours.
279// v39: Deepgram rates are keyed by the pricing page's OfferCatalog product
280// names (#528). A v38 entry's old keys would leave every row unpriced.
281// v41: A Mistral model the pricing table dropped keeps the price its
282// markdown page states (#543). A v40 page entry has no markdown price
283// and would log pricing_lost until the TTL.
284// v42: the BytePlus pricing entry gained `named` (#646); a v41 entry has none.
285const DOCS_CACHE_VERSION = 'v42'
286
287/** Fresh-window key for one parsed docs page. Shared with the stale copy. */
288export function docsCacheKey(url: string): string {
289 return `docs:${DOCS_CACHE_VERSION}:${url}`
290}
291
292/**
293 * KV cache for parsed docs, keyed by source URL. A failed load is not
294 * stored, so the next poll retries. `kv` is omitted in unit tests that
295 * never hit the network.
296 */
297export async function cachedDocs<T>(
298 kv: KVNamespace | undefined,
299 url: string,
300 load: () => Promise<T>,
301): Promise<T> {
302 const key = docsCacheKey(url)
303 if (kv) {
304 const hit = await getJson<T>(kv, key)
305 if (hit !== null) return hit
306 }
307 const value = await load()
308 if (kv) {
309 await putJson(kv, key, value, { expirationTtl: DOCS_TTL_SECONDS })
310 }
311 return value
312}
313
314/**
315 * Once one provider's failed docs loads have cost this much wall-clock time
316 * in a poll, nothing more is fetched for it: a docs host that is down would
317 * otherwise spend a timeout per document and stall every provider polled
318 * after it. Loads that overlap count once, so eight concurrent failures of
319 * 2.5 s cost 2.5 s. A host that hangs still costs one full round of its
320 * timeout (60 s for an NVIDIA card) before this can trip. A few pages that
321 * fail fast never reach it, so they do not stop the healthy ones loading.
322 */
323const DOCS_FAILURE_BUDGET_MS = 15_000
324
325/** Failures kept in full per provider per poll; the rest are only counted. */
326const DOCS_FAILURES_KEPT = 5
327
328/** One provider's docs loads in one poll. Make it with `docsRun()`. */
329export interface DocsRun extends DocsFailures {
330 /** Wall-clock time lost to failed loads so far. */
331 lostMs: number
332 /** When the latest failed load ended; where the next one's cost starts. */
333 lostUntil: number
334}
335
336export function docsRun(): DocsRun {
337 return { failed: 0, skipped: 0, first: [], lostMs: 0, lostUntil: 0 }
338}
339
340/** `ListModelsResult.docsFailures` for a finished run. */
341export function docsReport(run: DocsRun): DocsFailures {
342 return { failed: run.failed, skipped: run.skipped, first: run.first }
343}
344
345class DocsSkipped extends Error {}
346
347/** `cachedDocs` that serves a KV hit and refuses to fetch. */
348const cachedOnly: typeof cachedDocs = (kv, url) =>
349 cachedDocs(kv, url, () => Promise.reject(new DocsSkipped()))
350
351/**
352 * Load and parse one docs source for `listModels`. A throw is counted in
353 * `run` and returns null, so the listing and the other sources still poll.
354 * The caller gives the rows that source feeds `unavailable(...)` and
355 * returns `docsReport(run)` as `docsFailures`. Parsers stay strict: they
356 * throw, and only this catches. Never wrap the listing itself.
357 *
358 * `load` must fetch through the `cached` it is handed: once the failure
359 * budget is spent that one serves KV hits only, and a miss is counted as
360 * skipped rather than fetched.
361 */
362export async function tryDocs<T>(
363 run: DocsRun,
364 source: string,
365 load: (cached: typeof cachedDocs) => Promise<T>,
366): Promise<T | null> {
367 const started = Date.now()
368 try {
369 return await load(
370 run.lostMs >= DOCS_FAILURE_BUDGET_MS ? cachedOnly : cachedDocs,
371 )
372 } catch (error) {
373 if (error instanceof DocsSkipped) {
374 run.skipped++
375 return null
376 }
377 const ended = Date.now()
378 run.lostMs += Math.max(0, ended - Math.max(started, run.lostUntil))
379 run.lostUntil = Math.max(run.lostUntil, ended)
380 run.failed++
381 if (run.first.length < DOCS_FAILURES_KEPT) {
382 run.first.push({
383 source,
384 error: errorMessage(error),
385 elapsedMs: ended - started,
386 })
387 }
388 return null
389 }
390}
391
392/** Row patch: the source of these facts failed, keep what is stored. */
393export function unavailable(
394 ...facts: Array<ModelFact>
395): Pick<ModelInfo, 'absent'> {
396 return {
397 absent: Object.fromEntries(facts.map((fact) => [fact, 'unavailable'])),
398 }
399}
400
401/**
402 * Throw when a docs parse comes back empty — never silently null a catalog.
403 * A non-empty parse records one `parse_rows` event (`source`, `rows`).
404 * Cache hits do not emit, so the daily event count swings with the six-hour
405 * TTL and with deploys. The drop alert counts distinct `source` values on a
406 * finished UTC day and fires when that set shrinks. The zero-row throw is
407 * `ingest_failed` at the job boundary.
408 */
409export function assertParsed<T>(rows: Map<string, T>, source: string): void {
410 if (rows.size === 0) throw new Error(`${source}: parsed 0 model rows`)
411 noteIngest(parseRowsEvent(source, rows.size))
412}
413
414/** Bounded-concurrency map, order preserved. */
415export async function mapConcurrent<T, TResult>(
416 items: Array<T>,
417 limit: number,
418 fn: (item: T) => Promise<TResult>,
419): Promise<Array<TResult>> {
420 const results: Array<TResult> = Array.from({ length: items.length })
421 let next = 0
422 const worker = async () => {
423 while (next < items.length) {
424 const index = next++
425 const item = items[index]
426 if (item === undefined) continue
427 results[index] = await fn(item)
428 }
429 }
430 await Promise.all(
431 Array.from({ length: Math.min(limit, items.length) }, () => worker()),
432 )
433 return results
434}