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.
285// v43: an OpenAI page that rejects `none` effort is effort mode, mandatory
286// true (#711). A v42 entry would keep GPT-6.2 reasoning null for six hours.
287// v44: a Mistral model page entry gained `releasedAt` from its markdown
288// twin (#708); a v43 entry has none.
289// v45: Gemini model pages read "Grounding with Google Search" as
290// `googleSearch` (#707), and OpenAI pages cache their Endpoints support.
291// A v44 entry would leave both out for six hours.
292// v46: the Gemma card entry gained `card` (maker, open weights), and the
293// Mistral overview and BytePlus model list gained maker entries (#710).
294const DOCS_CACHE_VERSION = 'v46'
295
296/** Fresh-window key for one parsed docs page. Shared with the stale copy. */
297export function docsCacheKey(url: string): string {
298 return `docs:${DOCS_CACHE_VERSION}:${url}`
299}
300
301/**
302 * KV cache for parsed docs, keyed by source URL. A failed load is not
303 * stored, so the next poll retries. `kv` is omitted in unit tests that
304 * never hit the network.
305 */
306export async function cachedDocs<T>(
307 kv: KVNamespace | undefined,
308 url: string,
309 load: () => Promise<T>,
310): Promise<T> {
311 const key = docsCacheKey(url)
312 if (kv) {
313 const hit = await getJson<T>(kv, key)
314 if (hit !== null) return hit
315 }
316 const value = await load()
317 if (kv) {
318 await putJson(kv, key, value, { expirationTtl: DOCS_TTL_SECONDS })
319 }
320 return value
321}
322
323/**
324 * Once one provider's failed docs loads have cost this much wall-clock time
325 * in a poll, nothing more is fetched for it: a docs host that is down would
326 * otherwise spend a timeout per document and stall every provider polled
327 * after it. Loads that overlap count once, so eight concurrent failures of
328 * 2.5 s cost 2.5 s. A host that hangs still costs one full round of its
329 * timeout (60 s for an NVIDIA card) before this can trip. A few pages that
330 * fail fast never reach it, so they do not stop the healthy ones loading.
331 */
332const DOCS_FAILURE_BUDGET_MS = 15_000
333
334/** Failures kept in full per provider per poll; the rest are only counted. */
335const DOCS_FAILURES_KEPT = 5
336
337/** One provider's docs loads in one poll. Make it with `docsRun()`. */
338export interface DocsRun extends DocsFailures {
339 /** Wall-clock time lost to failed loads so far. */
340 lostMs: number
341 /** When the latest failed load ended; where the next one's cost starts. */
342 lostUntil: number
343}
344
345export function docsRun(): DocsRun {
346 return { failed: 0, skipped: 0, first: [], lostMs: 0, lostUntil: 0 }
347}
348
349/** `ListModelsResult.docsFailures` for a finished run. */
350export function docsReport(run: DocsRun): DocsFailures {
351 return { failed: run.failed, skipped: run.skipped, first: run.first }
352}
353
354class DocsSkipped extends Error {}
355
356/** `cachedDocs` that serves a KV hit and refuses to fetch. */
357const cachedOnly: typeof cachedDocs = (kv, url) =>
358 cachedDocs(kv, url, () => Promise.reject(new DocsSkipped()))
359
360/**
361 * Load and parse one docs source for `listModels`. A throw is counted in
362 * `run` and returns null, so the listing and the other sources still poll.
363 * The caller gives the rows that source feeds `unavailable(...)` and
364 * returns `docsReport(run)` as `docsFailures`. Parsers stay strict: they
365 * throw, and only this catches. Never wrap the listing itself.
366 *
367 * `load` must fetch through the `cached` it is handed: once the failure
368 * budget is spent that one serves KV hits only, and a miss is counted as
369 * skipped rather than fetched.
370 */
371export async function tryDocs<T>(
372 run: DocsRun,
373 source: string,
374 load: (cached: typeof cachedDocs) => Promise<T>,
375): Promise<T | null> {
376 const started = Date.now()
377 try {
378 return await load(
379 run.lostMs >= DOCS_FAILURE_BUDGET_MS ? cachedOnly : cachedDocs,
380 )
381 } catch (error) {
382 if (error instanceof DocsSkipped) {
383 run.skipped++
384 return null
385 }
386 const ended = Date.now()
387 run.lostMs += Math.max(0, ended - Math.max(started, run.lostUntil))
388 run.lostUntil = Math.max(run.lostUntil, ended)
389 run.failed++
390 if (run.first.length < DOCS_FAILURES_KEPT) {
391 run.first.push({
392 source,
393 error: errorMessage(error),
394 elapsedMs: ended - started,
395 })
396 }
397 return null
398 }
399}
400
401/** Row patch: the source of these facts failed, keep what is stored. */
402export function unavailable(
403 ...facts: Array<ModelFact>
404): Pick<ModelInfo, 'absent'> {
405 return {
406 absent: Object.fromEntries(facts.map((fact) => [fact, 'unavailable'])),
407 }
408}
409
410/**
411 * Throw when a docs parse comes back empty — never silently null a catalog.
412 * A non-empty parse records one `parse_rows` event (`source`, `rows`).
413 * Cache hits do not emit, so the daily event count swings with the six-hour
414 * TTL and with deploys. The drop alert counts distinct `source` values on a
415 * finished UTC day and fires when that set shrinks. The zero-row throw is
416 * `ingest_failed` at the job boundary.
417 */
418export function assertParsed<T>(rows: Map<string, T>, source: string): void {
419 if (rows.size === 0) throw new Error(`${source}: parsed 0 model rows`)
420 noteIngest(parseRowsEvent(source, rows.size))
421}
422
423/** Bounded-concurrency map, order preserved. */
424export async function mapConcurrent<T, TResult>(
425 items: Array<T>,
426 limit: number,
427 fn: (item: T) => Promise<TResult>,
428): Promise<Array<TResult>> {
429 const results: Array<TResult> = Array.from({ length: items.length })
430 let next = 0
431 const worker = async () => {
432 while (next < items.length) {
433 const index = next++
434 const item = items[index]
435 if (item === undefined) continue
436 results[index] = await fn(item)
437 }
438 }
439 await Promise.all(
440 Array.from({ length: Math.min(limit, items.length) }, () => worker()),
441 )
442 return results
443}