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/**
109 * One `## <heading>` section of a markdown document, up to the next `## `.
110 * Empty when the heading is absent.
111 */
112export function markdownSection(text: string, heading: string): string {
113 const start = text.indexOf(`\n## ${heading}`)
114 if (start < 0) return ''
115 const rest = text.slice(start + 1)
116 const end = rest.indexOf('\n## ')
117 return end < 0 ? rest : rest.slice(0, end)
118}
119
120const DOCS_TTL_SECONDS = 6 * 60 * 60
121
122/**
123 * Bumped whenever a parsed-docs shape changes. A deploy that changed the
124 * shape would otherwise read the old one back out of KV for six hours and
125 * see missing fields as missing facts.
126 */
127// v7: OpenAI model pages price the first token table and only the default
128// snapshot. A v6 entry would keep o3's batch table and gpt-4o's old snapshot.
129// v8: Grok model-page cache includes maxOutput (#119).
130// v9: BytePlus and Mistral cached docs include serverTools. A v8 entry
131// would keep the old card and leave tools null for six hours.
132// v10: BytePlus image and video cards copy published alias ids. A v9 entry
133// would leave those aliases unpriced for six hours.
134// v11: Grok maxOutput (#119) lands after v10 shipped; a v10 entry has no
135// maxOutput on Grok pages for six hours.
136// v12: Azure rows gain `tabulated` and the price doc gains `thresholds`. A
137// v11 entry written by the PR's preview build would drop every Azure row.
138// v13: MiniMax M2 rows store no maxOutput (the spec maximum is the context
139// window). A v12 entry would keep 204800 on them for six hours.
140// v14: Gemini and Mistral model pages gain `modalities`. A v13 entry has
141// none, and the schema walk that used to fill the field no longer does.
142// v15: open fill-gaps PRs #242 and #244. Do not reuse.
143// v16: Mistral model pages gain maxOutput and page pricing, and the pricing
144// doc stores the table without those pages. A v14 entry would keep Large 4's
145// sale row skipped and leave the new fields null for six hours.
146// v21: Azure rows gain effort lists, request maps, and the gpt-4 /
147// computer-use-preview meter match. A v16 entry would leave those null
148// for six hours.
149// v22: DashScope compat cache includes `scope`. A v21 entry has no scope,
150// so a chat id the page does not name would still get the compat map.
151// v23: Gemini's cached index is `{url, ids}` rows, thinking pages cache
152// budget bodies, and model pages cache per-id sections. Thinking-level
153// `mandatory` is true only when the page says that family cannot turn
154// thinking off. A v22 entry has none of that, so Gemini facts read from
155// it would stay null or mark every level column mandatory.
156// v24: Cerebras model pages include paid maxOutput. A v23 entry has no
157// maxOutput and would leave it null for six hours.
158// v25: Bedrock cards gain request maps, feature flags, and price-list
159// rates. A v24 entry would leave those null for six hours.
160// v26: Together reasoning pages and the serverless chat catalog cache
161// plain records. A v25 entry stored Maps, which JSON reads back as {},
162// and the next poll throws before any together row is written.
163// v27: native reasoning controls now distinguish published levels, mandatory
164// status and genuine source silence. Re-read cached parsed facts so earlier
165// guesses cannot survive the new parsers until the six-hour TTL expires.
166// v28: re-read native budget applicability and replay declarations after the
167// scoped guide enrichments and stricter normative-prose checks.
168const DOCS_CACHE_VERSION = 'v29'
169
170/**
171 * KV cache for parsed docs, keyed by source URL. A failed load is not
172 * stored, so the next poll retries. `kv` is omitted in unit tests that
173 * never hit the network.
174 */
175export async function cachedDocs<T>(
176 kv: KVNamespace | undefined,
177 url: string,
178 load: () => Promise<T>,
179): Promise<T> {
180 const key = `docs:${DOCS_CACHE_VERSION}:${url}`
181 if (kv) {
182 const hit = await getJson<T>(kv, key)
183 if (hit !== null) return hit
184 }
185 const value = await load()
186 if (kv) {
187 await putJson(kv, key, value, { expirationTtl: DOCS_TTL_SECONDS })
188 }
189 return value
190}
191
192/**
193 * Once one provider's failed docs loads have cost this much wall-clock time
194 * in a poll, nothing more is fetched for it: a docs host that is down would
195 * otherwise spend a timeout per document and stall every provider polled
196 * after it. Loads that overlap count once, so eight concurrent failures of
197 * 2.5 s cost 2.5 s. A host that hangs still costs one full round of its
198 * timeout (60 s for an NVIDIA card) before this can trip. A few pages that
199 * fail fast never reach it, so they do not stop the healthy ones loading.
200 */
201const DOCS_FAILURE_BUDGET_MS = 15_000
202
203/** Failures kept in full per provider per poll; the rest are only counted. */
204const DOCS_FAILURES_KEPT = 5
205
206/** One provider's docs loads in one poll. Make it with `docsRun()`. */
207export interface DocsRun extends DocsFailures {
208 /** Wall-clock time lost to failed loads so far. */
209 lostMs: number
210 /** When the latest failed load ended; where the next one's cost starts. */
211 lostUntil: number
212}
213
214export function docsRun(): DocsRun {
215 return { failed: 0, skipped: 0, first: [], lostMs: 0, lostUntil: 0 }
216}
217
218/** `ListModelsResult.docsFailures` for a finished run. */
219export function docsReport(run: DocsRun): DocsFailures {
220 return { failed: run.failed, skipped: run.skipped, first: run.first }
221}
222
223class DocsSkipped extends Error {}
224
225/** `cachedDocs` that serves a KV hit and refuses to fetch. */
226const cachedOnly: typeof cachedDocs = (kv, url) =>
227 cachedDocs(kv, url, () => Promise.reject(new DocsSkipped()))
228
229/**
230 * Load and parse one docs source for `listModels`. A throw is counted in
231 * `run` and returns null, so the listing and the other sources still poll.
232 * The caller gives the rows that source feeds `unavailable(...)` and
233 * returns `docsReport(run)` as `docsFailures`. Parsers stay strict: they
234 * throw, and only this catches. Never wrap the listing itself.
235 *
236 * `load` must fetch through the `cached` it is handed: once the failure
237 * budget is spent that one serves KV hits only, and a miss is counted as
238 * skipped rather than fetched.
239 */
240export async function tryDocs<T>(
241 run: DocsRun,
242 source: string,
243 load: (cached: typeof cachedDocs) => Promise<T>,
244): Promise<T | null> {
245 const started = Date.now()
246 try {
247 return await load(
248 run.lostMs >= DOCS_FAILURE_BUDGET_MS ? cachedOnly : cachedDocs,
249 )
250 } catch (error) {
251 if (error instanceof DocsSkipped) {
252 run.skipped++
253 return null
254 }
255 const ended = Date.now()
256 run.lostMs += Math.max(0, ended - Math.max(started, run.lostUntil))
257 run.lostUntil = Math.max(run.lostUntil, ended)
258 run.failed++
259 if (run.first.length < DOCS_FAILURES_KEPT) {
260 run.first.push({
261 source,
262 error: errorMessage(error),
263 elapsedMs: ended - started,
264 })
265 }
266 return null
267 }
268}
269
270/** Row patch: the source of these facts failed, keep what is stored. */
271export function unavailable(
272 ...facts: Array<ModelFact>
273): Pick<ModelInfo, 'absent'> {
274 return {
275 absent: Object.fromEntries(facts.map((fact) => [fact, 'unavailable'])),
276 }
277}
278
279/**
280 * Throw when a docs parse comes back empty — never silently null a catalog.
281 * A non-empty parse records one `parse_rows` event (`source`, `rows`).
282 * Cache hits do not emit, so the daily event count swings with the six-hour
283 * TTL and with deploys. The drop alert counts distinct `source` values on a
284 * finished UTC day and fires when that set shrinks. The zero-row throw is
285 * `ingest_failed` at the job boundary.
286 */
287export function assertParsed<T>(rows: Map<string, T>, source: string): void {
288 if (rows.size === 0) throw new Error(`${source}: parsed 0 model rows`)
289 noteIngest(parseRowsEvent(source, rows.size))
290}
291
292/** Bounded-concurrency map, order preserved. */
293export async function mapConcurrent<T, TResult>(
294 items: Array<T>,
295 limit: number,
296 fn: (item: T) => Promise<TResult>,
297): Promise<Array<TResult>> {
298 const results: Array<TResult> = new Array<TResult>(items.length)
299 let next = 0
300 const worker = async () => {
301 while (next < items.length) {
302 const index = next++
303 const item = items[index]
304 if (item === undefined) continue
305 results[index] = await fn(item)
306 }
307 }
308 await Promise.all(
309 Array.from({ length: Math.min(limit, items.length) }, () => worker()),
310 )
311 return results
312}