Open History to see the last commit
1import {
2 GEMINI_LIVE_GUIDE_URL,
3 geminiNativeAudioThinking,
4} from './gemini-live-thinking.ts'
5/**
6 * Gemini thinking configuration and Google-hosted tools (issue #77).
7 *
8 * Pages are aistudio.google.com Markdoc (issue #568); `markdocTables`
9 * rewrites their tables as the `| a | b |` rows these parsers read.
10 *
11 * Tools: every model page (`/docs/models/{slug}.md`) has a Capabilities
12 * row of `**[Name](url)** Supported|Not supported` pairs.
13 * Thinking: the generateContent thinking page has a `thinkingLevel` table
14 * whose columns name Gemini 3 families, and a `thinkingBudget` table whose
15 * rows name Gemini 2.5 families. Both key by family, so an id resolves to
16 * the longest family it extends with a `-preview…`/`-latest`/`-NNN` suffix.
17 * `mandatory` on a thinking-level column is true only when the page's prose
18 * says that family cannot turn thinking off.
19 * A model page that lists thinking levels in backticks fills a family the
20 * table does not name. Modalities: the same page's `Supported data types`
21 * row, bound to the model-code and version ids on that page, and to the
22 * endpoint ids the models index names for that page.
23 */
24import {
25 assertParsed,
26 docsReport,
27 docsRun,
28 mapConcurrent,
29 markdocTables,
30 markdownTableRows,
31 tryDocs,
32 unavailable,
33} from './model-facts.ts'
34import { fetchOptional } from './provider-aliases.ts'
35import { fetchText, sha256Text } from './types.ts'
36import type {
37 DocsFailures,
38 FactSource,
39 ModelFact,
40 ModelFactSources,
41 ModelInfo,
42 ModelReasoning,
43} from './types.ts'
44
45export const GEMINI_MODELS_INDEX_URL =
46 'https://aistudio.google.com/docs/models.md'
47const GEMINI_DOCS_ORIGIN = 'https://aistudio.google.com'
48const GEMINI_MODEL_PAGE_BASE = `${GEMINI_DOCS_ORIGIN}/docs/models/`
49export const GEMINI_THINKING_URL =
50 'https://aistudio.google.com/docs/thinking.md?generate-content=true'
51
52/** Capabilities entry → generateContent `Tool` field. */
53const TOOL_FIELDS: Record<string, string> = {
54 'Code execution': 'codeExecution',
55 'Computer use': 'computerUse',
56 'File search': 'fileSearch',
57 'Grounding with Google Maps': 'googleMaps',
58 'Search grounding': 'googleSearch',
59 'URL context': 'urlContext',
60}
61
62/** Tool fields a model page marks Supported (including "(Preview)"). */
63export function parsePageTools(markdown: string): Array<string> {
64 const row = markdown
65 .split('\n')
66 .find((line) => line.startsWith('| Capabilities |'))
67 if (!row) return []
68 const out: Array<string> = []
69 for (const m of row.matchAll(/\*\*\[([^\]]+)\]\([^)]*\)\*\*\s*([^*|]*)/g)) {
70 const field = TOOL_FIELDS[m[1] ?? '']
71 if (field && (m[2] ?? '').trim().startsWith('Supported')) out.push(field)
72 }
73 return out
74}
75
76/** Native capability cells are model evidence even when listing omits thinking. */
77export function parsePageThinkingSupported(markdown: string): boolean {
78 return /\*\*\[Thinking\]\([^)]*\)\*\*\s*Supported\b/.test(markdown)
79}
80
81/** Words a `Supported data types` cell uses → medium, in stored order. */
82const MEDIA: Record<string, string> = {
83 text: 'text',
84 image: 'image',
85 images: 'image',
86 audio: 'audio',
87 video: 'video',
88 videos: 'video',
89 pdf: 'file',
90 pdfs: 'file',
91 document: 'file',
92 documents: 'file',
93}
94const MEDIA_ORDER = [...new Set(Object.values(MEDIA))]
95
96/**
97 * Word-level timestamp metadata on the transcribe page. It is not a medium.
98 * Dropping only this phrase keeps Text and Audio; any other unknown word
99 * still rejects the whole list.
100 */
101const NOT_MEDIA = new Set(['word annotation', 'word annotations'])
102
103/**
104 * `Text, Image, Video, Audio, and PDF` → media, or null on any other word.
105 * A parenthetical is a qualifier (`Audio (MP3)`, `Video (up to 10s)`) and is
106 * dropped, unless it names a medium itself (`Text (and Image, Audio)`): then
107 * the list is inside it and the cell is not read.
108 */
109function mediaList(cell: string): Array<string> | null {
110 const found = new Set<string>()
111 for (const [, inside = ''] of cell.matchAll(/\(([^)]*)\)/g)) {
112 const words = inside.toLowerCase().match(/[a-z]+/g) ?? []
113 if (words.some((word) => word in MEDIA)) return null
114 }
115 const items = cell
116 .replace(/\([^)]*\)/g, '')
117 .split(/,|\band\b/i)
118 .map((item) => item.trim().toLowerCase())
119 .filter((item) => item !== '')
120 for (const item of items) {
121 if (NOT_MEDIA.has(item)) continue
122 const medium = MEDIA[item]
123 if (!medium) return null
124 found.add(medium)
125 }
126 return found.size > 0 ? MEDIA_ORDER.filter((m) => found.has(m)) : null
127}
128
129/**
130 * A model page's `| Supported data types | **Inputs** … **Output** … |` row.
131 * Null when the row is missing or either side names something that is not a
132 * medium ("Text embeddings", "Video with audio"): a partial list would read
133 * as the whole answer.
134 */
135export function parsePageModalities(
136 markdown: string,
137): { input: Array<string>; output: Array<string> } | null {
138 const row = markdown.match(
139 /^\| Supported data types \|\s*\*\*Inputs?\*\*(.*?)\*\*Outputs?\*\*(.*?)\|\s*$/m,
140 )
141 const input = mediaList(row?.[1] ?? '')
142 const output = mediaList(row?.[2] ?? '')
143 return input && output ? { input, output } : null
144}
145
146/** `Gemini 3.8 \& 3.7 Flash` → [`gemini-3.8-flash`, `gemini-3.7-flash`]. */
147function familyIds(label: string): Array<string> {
148 const clean = label
149 .replace(/\*\*|\\/g, '')
150 .replace(/^Gemini\s+/i, '')
151 .trim()
152 const match = clean.match(/^([\d.]+(?:\s*&\s*[\d.]+)*)\s+(.+)$/)
153 const slug = (rest: string) => rest.toLowerCase().replace(/\s+/g, '-')
154 if (!match?.[1] || !match[2]) return [`gemini-${slug(clean)}`]
155 const tail = slug(match[2])
156 return match[1].split('&').map((v) => `gemini-${v.trim()}-${tail}`)
157}
158
159const CANNOT_DISABLE =
160 /cannot (be )?disable|cannot be turned off|do not support full thinking-off/i
161
162/**
163 * Families the thinking page says cannot turn thinking fully off.
164 * `flashLite` is the bare "Flash-Lite" mention, which covers every
165 * flash-lite column. A versioned "Gemini 3.1 Flash-Lite" is one exact id.
166 */
167function mandatoryEffortFamilies(markdown: string): {
168 exact: Set<string>
169 flashLite: boolean
170} {
171 const exact = new Set<string>()
172 let flashLite = false
173 for (const para of markdown.split(/\n\s*\n/)) {
174 for (const sentence of para.split(/(?<=[.!?])\s+/)) {
175 if (!CANNOT_DISABLE.test(sentence)) continue
176 if (
177 /flash-lite/i.test(sentence) &&
178 !/Gemini\s+\d+(?:\.\d+)*\s+Flash-Lite/i.test(sentence)
179 ) {
180 flashLite = true
181 }
182 for (const match of sentence.matchAll(
183 /Gemini\s+(\d+(?:\.\d+)*)\s+([A-Za-z][\w-]*)/g,
184 )) {
185 const version = match[1]
186 const tail = (match[2] ?? '').toLowerCase()
187 if (version && tail) exact.add(`gemini-${version}-${tail}`)
188 }
189 }
190 }
191 return { exact, flashLite }
192}
193
194function effortMandatory(
195 id: string,
196 named: { exact: Set<string>; flashLite: boolean },
197): boolean | null {
198 if (named.exact.has(id)) return true
199 if (named.flashLite && id.endsWith('-flash-lite')) return true
200 return null
201}
202
203/** Family id → reasoning, from both thinking tables. */
204export function parseThinkingPage(page: string): Map<string, ModelReasoning> {
205 const markdown = markdocTables(page)
206 const out = new Map<string, ModelReasoning>()
207 const named = mandatoryEffortFamilies(markdown)
208 const rows = markdownTableRows(markdown)
209 const levelHeader = rows.find((row) => row[0] === 'Thinking Level')
210 if (levelHeader) {
211 const levelRows = rows.filter((row) =>
212 /^\*\*`[a-z]+`\*\*$/.test(row[0] ?? ''),
213 )
214 levelHeader.forEach((label, col) => {
215 if (col === 0 || label === 'Description') return
216 const efforts = levelRows
217 .filter((row) => /^supported/i.test(row[col] ?? ''))
218 .map((row) => (row[0] ?? '').replace(/[*`]/g, ''))
219 if (efforts.length === 0) return
220 for (const id of familyIds(label)) {
221 out.set(id, {
222 mode: 'effort',
223 mandatory: effortMandatory(id, named),
224 efforts,
225 })
226 }
227 })
228 }
229 for (const [model = '', , range, disable] of rows) {
230 if (!/^\*\*[\d.]+ /.test(model) || !range?.includes('`')) continue
231 for (const id of budgetIds(model)) {
232 out.set(id, {
233 mode: 'budget',
234 mandatory: (disable ?? '').startsWith('N/A'),
235 })
236 }
237 }
238 return out
239}
240
241/** `thinkingBudget = -1` from a budget-table cell, or null. */
242function budgetNumber(cell: string | undefined): number | null {
243 const match = cell?.match(/thinkingBudget\s*=\s*(-?\d+)/)
244 if (!match?.[1]) return null
245 const value = Number(match[1])
246 return Number.isInteger(value) ? value : null
247}
248
249export interface GeminiBudgetBody {
250 /** Dynamic-thinking cell. Gemini publishes -1, not an effort name. */
251 on: number
252 /** Disable cell, when it publishes a `thinkingBudget` number. */
253 off: number | null
254}
255
256/**
257 * Budget-table model cell → API ids. The native-audio row says
258 * "Flash Live Native Audio" and dates the snapshot in parentheses; the
259 * API id drops "Live" and keeps that date only.
260 */
261export function budgetIds(modelCell: string): Array<string> {
262 const plain = modelCell.replace(/\*\*/g, '').trim()
263 const dated = plain.match(/^(.*?)\s*\((\d{2}-\d{4})\)$/)
264 const name = (dated?.[1] ?? plain).trim()
265 const date = dated?.[2]
266 const native = name.match(/^([\d.]+)\s+Flash Live Native Audio Preview$/i)
267 if (native) {
268 return native[1] && date
269 ? [`gemini-${native[1]}-flash-native-audio-preview-${date}`]
270 : []
271 }
272 return familyIds(modelCell.replace(/\s*\([^)]*\)/, ''))
273}
274
275/** Family id → dynamic and disable `thinkingBudget` numbers. */
276export function parseThinkingBudgets(
277 markdown: string,
278): Map<string, GeminiBudgetBody> {
279 const out = new Map<string, GeminiBudgetBody>()
280 for (const row of markdownTableRows(markdocTables(markdown))) {
281 const [model = '', , range, disable, dynamic] = row
282 if (!/^\*\*[\d.]+ /.test(model) || !range?.includes('`')) continue
283 const on = budgetNumber(dynamic)
284 if (on === null) continue
285 for (const id of budgetIds(model)) {
286 out.set(id, { on, off: budgetNumber(disable) })
287 }
288 }
289 return out
290}
291
292const EFFORT_WORDS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max']
293
294/**
295 * Backtick thinking levels on a model page. Quoted samples do not count.
296 * Two paragraphs that list different levels return null. `mandatory` is
297 * true only when the paragraph that lists the levels says thinking cannot
298 * be turned off.
299 */
300export function parsePageThinking(page: string): ModelReasoning | null {
301 const prose = markdocTables(page).replace(/```[\s\S]*?```/g, '')
302 const sets: Array<Array<string>> = []
303 let mandatory: boolean | null = null
304 const cell = prose.match(
305 /\*\*\[Thinking\]\([^)]*\)\*\*\s*Supported\s*\(([^)]+)\)/,
306 )?.[1]
307 if (cell) {
308 if (cell.trim() === 'interleaved reasoning') return null
309 const declared = cell.split(/,|\band\b/).map((value) => value.trim())
310 if (!declared.every((value) => EFFORT_WORDS.includes(value)))
311 throw new Error('gemini model page: unreadable native thinking levels')
312 sets.push(declared)
313 }
314 for (const para of prose.split(/\n\s*\n/)) {
315 if (!/thinking[_\s-]?levels?/i.test(para)) continue
316 const unsupported = new Set<string>()
317 for (const match of para.matchAll(
318 /\b(minimal|low|medium|high|xhigh|max)\b[^.]{0,80}?not supported/gi,
319 )) {
320 unsupported.add((match[1] ?? '').toLowerCase())
321 }
322 const efforts: Array<string> = []
323 for (const match of para.matchAll(/`([^`]+)`/g)) {
324 const word = (match[1] ?? '').trim().toLowerCase()
325 if (!EFFORT_WORDS.includes(word) || unsupported.has(word)) continue
326 if (!efforts.includes(word)) efforts.push(word)
327 }
328 if (efforts.length === 0) continue
329 sets.push(efforts)
330 if (CANNOT_DISABLE.test(para)) mandatory = true
331 }
332 const efforts = sets[0]
333 if (!efforts) return null
334 if (sets.some((set) => set.join() !== efforts.join())) return null
335 return { mode: 'effort', mandatory, efforts }
336}
337
338const MODEL_ID = /^[a-z0-9]+(?:[.-][a-z0-9]+)+$/
339
340function backtickIds(line: string): Array<string> {
341 const chunks: Array<string> = []
342 const stripped = line.replace(/```([^`]*)```/g, (_match, body: string) => {
343 chunks.push(body)
344 return ' '
345 })
346 for (const match of stripped.matchAll(/`([^`]+)`/g)) {
347 chunks.push(match[1] ?? '')
348 }
349 const ids: Array<string> = []
350 for (const chunk of chunks) {
351 for (const token of chunk.split(/\s+/)) {
352 // The Models API id drops a leading `models/` (`models/genie-4`).
353 const bare = token.replace(/^models\//, '')
354 if (MODEL_ID.test(bare)) ids.push(bare)
355 }
356 }
357 return ids
358}
359
360export interface GeminiIndexDoc {
361 url: string
362 ids: Array<string>
363}
364
365function cleanDocUrl(raw: string): string {
366 return `${GEMINI_DOCS_ORIGIN}${raw.replace(/[),.;]+$/, '').replace(/\.md$/, '')}`
367}
368
369/**
370 * Models index: each `/docs/…` link (relative, as the page writes them),
371 * plus endpoint ids from table rows only.
372 */
373export function parseModelIndexDocs(markdown: string): Array<GeminiIndexDoc> {
374 const byUrl = new Map<string, Set<string>>()
375 for (const line of markdocTables(markdown).split('\n')) {
376 const urls = [
377 ...line.matchAll(
378 /(?<=[("]|https:\/\/aistudio\.google\.com)\/docs\/[a-z0-9._/-]+/g,
379 ),
380 ]
381 if (urls.length === 0) continue
382 const ids = line.startsWith('|') ? backtickIds(line) : []
383 for (const match of urls) {
384 const url = cleanDocUrl(match[0])
385 const set = byUrl.get(url) ?? new Set<string>()
386 for (const id of ids) set.add(id)
387 byUrl.set(url, set)
388 }
389 }
390 return [...byUrl].map(([url, ids]) => ({ url, ids: [...ids] }))
391}
392
393function modelSlug(url: string): string | null {
394 return url.match(/\/models\/([a-z0-9.-]+?)(?:\.md)?$/)?.[1] ?? null
395}
396
397export function parseModelIndex(markdown: string): Array<string> {
398 return [
399 ...new Set(
400 parseModelIndexDocs(markdown).flatMap((doc) => {
401 const slug = modelSlug(doc.url)
402 return slug ? [slug] : []
403 }),
404 ),
405 ]
406}
407
408/** Whole seconds a model page's `Output video` limit states, both ends included. */
409export interface GeminiClipVideo {
410 minSeconds: number
411 maxSeconds: number
412}
413
414/**
415 * A real-time stream. The page states a frame size and a token rate, and
416 * no clip duration. `Max session duration` on the same row is a session
417 * cap, not a duration to invent.
418 */
419export interface GeminiStreamVideo {
420 width: number
421 height: number
422 fps: number
423 tokensPerFrame: number
424 tokensPerSecond: number
425}
426
427/** A stated `Output video` limit: a fixed clip, or a real-time stream. */
428export type GeminiOutputVideo = GeminiClipVideo | { stream: GeminiStreamVideo }
429
430function wholeNumber(raw: string | undefined): number | null {
431 if (raw === undefined) return null
432 const value = Number(raw.replace(/,/g, ''))
433 return Number.isInteger(value) && value >= 1 ? value : null
434}
435
436/**
437 * `**Output video**` in a model page's limits row. Null when the page has
438 * no such limit. `Ns-Ms` is a clip. A resolution, fps and token rate is a
439 * stream and carries no duration. Anything else throws: an unknown shape
440 * must not publish an unbounded duration.
441 */
442export function parsePageOutputVideo(
443 markdown: string,
444): GeminiOutputVideo | null {
445 const stated = markdown.match(/\*\*Output video\*\*\s*([^|\n]*)/)?.[1]
446 if (stated === undefined) return null
447 const range = stated.match(/^(\d+)s\s*[-–]\s*(\d+)s\b/)
448 const minSeconds = Number(range?.[1])
449 const maxSeconds = Number(range?.[2])
450 if (range && minSeconds >= 1 && maxSeconds >= minSeconds) {
451 return { minSeconds, maxSeconds }
452 }
453 const stream = stated.match(
454 /^`?(\d+)x(\d+)`?\s*\([^)]*\b(\d+)\s*fps\b[^)]*\)\s*,\s*`?([\d,]+)`?\s*video output tokens per frame\s*\(\s*`?([\d,]+)`?\s*tokens\/sec\)/i,
455 )
456 const width = wholeNumber(stream?.[1])
457 const height = wholeNumber(stream?.[2])
458 const fps = wholeNumber(stream?.[3])
459 const tokensPerFrame = wholeNumber(stream?.[4])
460 const tokensPerSecond = wholeNumber(stream?.[5])
461 if (
462 stream &&
463 width !== null &&
464 height !== null &&
465 fps !== null &&
466 tokensPerFrame !== null &&
467 tokensPerSecond !== null
468 ) {
469 return {
470 stream: { width, height, fps, tokensPerFrame, tokensPerSecond },
471 }
472 }
473 throw new Error(
474 `gemini model page: unreadable Output video limit "${stated.trim().slice(0, 80)}"`,
475 )
476}
477
478export interface GeminiPageSection {
479 /** Model-code, agent-code, then version ids, in that order. */
480 ids: Array<string>
481 codes: Array<string>
482 versions: Array<string>
483 modalities: { input: Array<string>; output: Array<string> } | null
484 tools: Array<string>
485 thinking?: true
486 /** Present on a video model's section only. */
487 outputVideo?: GeminiOutputVideo
488}
489
490function labeledIds(chunk: string, label: string): Array<string> {
491 const ids: Array<string> = []
492 for (const line of chunk.split('\n')) {
493 if (!line.startsWith(`| ${label} |`)) continue
494 // "(… automatically routed to `gemini-3.5-flash-lite`)" names another
495 // model, not a version of this one.
496 ids.push(...backtickIds(line.replace(/\([^)]*\)/g, '')))
497 }
498 return [...new Set(ids)]
499}
500
501function sectionFrom(chunk: string): GeminiPageSection {
502 const codes = [
503 ...new Set([
504 ...labeledIds(chunk, 'Model code'),
505 ...labeledIds(chunk, 'Agent code'),
506 ]),
507 ]
508 const versions = labeledIds(chunk, 'Versions').filter(
509 (id) => !codes.includes(id),
510 )
511 const outputVideo = parsePageOutputVideo(chunk)
512 return {
513 ids: [...codes, ...versions],
514 codes,
515 versions,
516 modalities: parsePageModalities(chunk),
517 tools: parsePageTools(chunk),
518 ...(parsePageThinkingSupported(chunk) ? { thinking: true as const } : {}),
519 ...(outputVideo ? { outputVideo } : {}),
520 }
521}
522
523/**
524 * One section per model-code heading. A page with no model code stays one
525 * anonymous section, so a property table with no heading still parses.
526 * Preamble in front of the first model code is dropped.
527 */
528export function parsePageSections(page: string): Array<GeminiPageSection> {
529 const markdown = markdocTables(page)
530 const chunks = markdown
531 .split(/^(?=#{2,3} )/m)
532 .filter((chunk) => /^#{2,3} /.test(chunk))
533 const sections = (chunks.length > 0 ? chunks : [markdown]).map(sectionFrom)
534 const named = sections.filter((section) => section.ids.length > 0)
535 if (named.length > 0) return named
536 const modalities = parsePageModalities(markdown)
537 const tools = parsePageTools(markdown)
538 return modalities || tools.length > 0
539 ? [{ ids: [], codes: [], versions: [], modalities, tools }]
540 : []
541}
542
543/** Longest family `rawId` is, or extends with a version suffix. */
544export function familyOf(
545 rawId: string,
546 families: Iterable<string>,
547): string | null {
548 let best: string | null = null
549 for (const family of families) {
550 const exact = rawId === family
551 const extends_ =
552 rawId.startsWith(`${family}-`) &&
553 /^(preview|latest|exp|\d)/.test(rawId.slice(family.length + 1))
554 if ((exact || extends_) && (!best || family.length > best.length)) {
555 best = family
556 }
557 }
558 return best
559}
560
561type GeminiFeatures = Pick<ModelInfo, 'absent'> & {
562 capabilities?: Array<string>
563 reasoning: ModelReasoning | null
564 budget: GeminiBudgetBody | null
565 serverTools: Array<string> | null
566 modalities: { input: Array<string>; output: Array<string> } | null
567 /** The model page states an output video limit: a video model. */
568 outputVideo?: GeminiOutputVideo
569 factSources: ModelFactSources
570}
571
572interface LoadedPage {
573 url: string
574 sections: Array<GeminiPageSection>
575 reasoning: ModelReasoning | null
576 hash: string
577}
578
579interface BoundSection {
580 modalities: GeminiPageSection['modalities']
581 outputVideo?: GeminiOutputVideo
582 tools: Array<string>
583 reasoning: ModelReasoning | null
584 thinking: boolean
585 sourceUrl: string
586 hash: string
587}
588
589function pageUrl(url: string): string {
590 return `${url.replace(/\.md$/, '')}.md`
591}
592
593function docMatches(rawId: string, doc: GeminiIndexDoc): boolean {
594 if (doc.ids.includes(rawId)) return true
595 const slug = modelSlug(doc.url)
596 return slug !== null && familyOf(rawId, [slug]) === slug
597}
598
599/**
600 * Reasoning, server tools and modalities per listed id, with provenance.
601 * A model page that fails to load is that family's alone: its rows keep the
602 * stored tools and modalities (`absent`) and the failure is in
603 * `docsFailures`. The models index and the thinking page are the same kind
604 * of load: a throw is counted and the facts they feed stay `unavailable`,
605 * so one reshaped docs host does not drop the listing (#567). Reasoning
606 * the thinking table does not name is kept the same way, so a stored
607 * page-derived object survives a blip.
608 */
609export async function geminiModelFeatures(
610 rawIds: Array<string>,
611 kv?: KVNamespace,
612): Promise<{
613 features: (rawId: string, thinking: boolean | undefined) => GeminiFeatures
614 docsFailures: DocsFailures
615 /** False when the thinking page failed. The request map stays stored. */
616 thinkingLoaded: boolean
617}> {
618 const run = docsRun()
619 const [index, thinking, nativeAudio] = await Promise.all([
620 tryDocs(run, GEMINI_MODELS_INDEX_URL, (cached) =>
621 cached(kv, GEMINI_MODELS_INDEX_URL, async () => {
622 const parsed = parseModelIndexDocs(
623 await fetchText(GEMINI_MODELS_INDEX_URL),
624 )
625 if (!parsed.some((doc) => modelSlug(doc.url))) {
626 throw new Error('gemini models index: 0 slugs')
627 }
628 return parsed
629 }),
630 ),
631 tryDocs(run, GEMINI_THINKING_URL, (cached) =>
632 cached(kv, GEMINI_THINKING_URL, async () => {
633 const markdown = await fetchText(GEMINI_THINKING_URL)
634 const parsed = parseThinkingPage(markdown)
635 assertParsed(parsed, 'gemini thinking page')
636 return {
637 reasoning: Object.fromEntries(parsed),
638 budgets: Object.fromEntries(parseThinkingBudgets(markdown)),
639 hash: await sha256Text(markdown),
640 }
641 }),
642 ),
643 tryDocs(run, GEMINI_LIVE_GUIDE_URL, (cached) =>
644 geminiNativeAudioThinking(rawIds, kv, cached),
645 ),
646 ])
647 // Null is also "no native audio id listed"; only a listed one can fail.
648 const nativeAudioFailed =
649 nativeAudio === null && rawIds.some((id) => id.includes('native-audio'))
650 const indexDocs = index ?? []
651 const thinkingDoc = thinking ?? {
652 reasoning: {},
653 budgets: {},
654 hash: '',
655 }
656 const slugs = indexDocs.flatMap((doc) => {
657 const slug = modelSlug(doc.url)
658 return slug ? [slug] : []
659 })
660 // Google serves some model pages the index does not link (gemini-3.5-flash,
661 // #409). A listed id no index page covers is looked up at its own
662 // `/models/{id}` path. A 404 there is no page. Such a page names no ids
663 // for the index. A family page repeats its siblings' tables; those bind only
664 // where no other page states the sibling (`sibling` placements).
665 const unindexed: Array<GeminiIndexDoc> = rawIds
666 .filter(
667 (id) =>
668 /^[a-z0-9][a-z0-9.-]*$/.test(id) &&
669 !indexDocs.some((doc) => docMatches(id, doc)),
670 )
671 .map((id) => ({ url: `${GEMINI_MODEL_PAGE_BASE}${id}`, ids: [] }))
672 // No index: the per-id URLs are a guess, and a 404 there would write
673 // null modalities. Keep the stored page facts instead of fetching.
674 const docs = index ? [...index, ...unindexed] : []
675 const needed = index
676 ? [
677 ...index.filter((doc) => rawIds.some((id) => docMatches(id, doc))),
678 ...unindexed,
679 ]
680 : []
681 const pages = await mapConcurrent(needed, 8, (doc) => {
682 const url = pageUrl(doc.url)
683 const optional = unindexed.includes(doc)
684 return tryDocs(run, url, (cached) =>
685 cached(kv, url, async () => {
686 const markdown = optional
687 ? ((await fetchOptional(url)) ?? '')
688 : await fetchText(url)
689 const sections = markdown === '' ? [] : parsePageSections(markdown)
690 const named = sections.filter((section) => section.ids.length > 0)
691 return {
692 url,
693 sections,
694 reasoning: named.length <= 1 ? parsePageThinking(markdown) : null,
695 hash: await sha256Text(markdown),
696 }
697 }),
698 )
699 })
700 const loaded = pages.flatMap((page) => (page ? [page] : []))
701 // Every page read and none states modalities is a reshaped site, not a
702 // catalog without media. Throwing keeps the stored column.
703 if (
704 loaded.length > 0 &&
705 !loaded.some((page) => page.sections.some((section) => section.modalities))
706 ) {
707 throw new Error(
708 `gemini model pages: 0 of ${String(loaded.length)} state modalities`,
709 )
710 }
711 const byId = new Map<string, BoundSection>()
712 const bySlug = new Map<string, BoundSection>()
713 const loadedUrls = new Set(loaded.map((page) => page.url))
714 const placements = loaded.flatMap((page) =>
715 pagePlacements(page, indexDocs, bySlug),
716 )
717 for (const kind of ['code', 'version', 'index', 'sibling'] as const) {
718 for (const place of placements) {
719 if (place.kind !== kind) continue
720 const prev = byId.get(place.id)
721 byId.set(
722 place.id,
723 prev ? chooseBound(place.id, prev, place.bound, kind) : place.bound,
724 )
725 }
726 }
727 const lookup = (rawId: string): BoundSection | undefined => {
728 const exact = byId.get(rawId)
729 if (exact) return exact
730 const fromId = familyOf(rawId, byId.keys())
731 if (fromId) {
732 const bound = byId.get(fromId)
733 if (bound) return bound
734 }
735 const slug = familyOf(rawId, slugs)
736 return slug ? bySlug.get(slug) : undefined
737 }
738 const keepFailedDocs = (
739 rawId: string,
740 result: GeminiFeatures,
741 modelThinks: boolean | undefined,
742 ): GeminiFeatures => {
743 const facts: Array<ModelFact> = []
744 if (!index) facts.push('serverTools', 'modalities')
745 // The thinking page (or, for a native audio id, the live guide) failed
746 // and no model page stated a replacement. `false` from the listing is
747 // the API saying this model does not think.
748 const sourceFailed =
749 !thinking || (nativeAudioFailed && rawId.includes('native-audio'))
750 if (
751 sourceFailed &&
752 modelThinks !== false &&
753 result.reasoning == null &&
754 result.absent?.reasoning !== 'unavailable'
755 ) {
756 facts.push('reasoning')
757 }
758 if (facts.length === 0) return result
759 return {
760 ...result,
761 ...(!index ? { serverTools: null, modalities: null } : {}),
762 absent: { ...result.absent, ...unavailable(...facts).absent },
763 }
764 }
765 const features = (
766 rawId: string,
767 modelThinks: boolean | undefined,
768 ): GeminiFeatures =>
769 keepFailedDocs(rawId, readFeatures(rawId, modelThinks), modelThinks)
770 const readFeatures = (
771 rawId: string,
772 modelThinks: boolean | undefined,
773 ): GeminiFeatures => {
774 const factSources: ModelFactSources = {}
775 const budgetId = familyOf(rawId, Object.keys(thinkingDoc.budgets))
776 const budget =
777 modelThinks !== false && budgetId
778 ? (thinkingDoc.budgets[budgetId] ?? null)
779 : null
780 const bound = lookup(rawId)
781 const documentedThinking =
782 modelThinks !== false &&
783 (bound?.thinking === true || bound?.reasoning != null)
784 const thinks = modelThinks === true || documentedThinking
785 const family = thinks
786 ? familyOf(rawId, Object.keys(thinkingDoc.reasoning))
787 : null
788 let reasoning = family ? (thinkingDoc.reasoning[family] ?? null) : null
789 if (reasoning && family && thinking) {
790 factSources.reasoning = {
791 derivation: 'docs-derived',
792 sourceUrl: GEMINI_THINKING_URL,
793 sourceHash: thinking.hash,
794 path: family,
795 }
796 }
797 if (nativeAudio?.rawId === rawId && modelThinks !== false) {
798 reasoning = nativeAudio.reasoning
799 factSources.reasoning = {
800 derivation: 'docs-derived',
801 sourceUrl: GEMINI_LIVE_GUIDE_URL,
802 sourceHash: nativeAudio.hash,
803 path: 'Model comparison; Thinking; exact native audio model',
804 }
805 }
806 const failed = docs
807 .filter((doc) => docMatches(rawId, doc))
808 .some((doc) => !loadedUrls.has(pageUrl(doc.url)))
809 if (failed) {
810 const absentFacts: Array<ModelFact> = ['serverTools', 'modalities']
811 if (modelThinks !== false && !reasoning) absentFacts.push('reasoning')
812 return {
813 reasoning,
814 budget,
815 serverTools: null,
816 modalities: null,
817 factSources,
818 ...unavailable(...absentFacts),
819 }
820 }
821 if (!reasoning && thinks && !family && bound?.reasoning) {
822 reasoning = bound.reasoning
823 factSources.reasoning = {
824 derivation: 'docs-derived',
825 sourceUrl: bound.sourceUrl,
826 sourceHash: bound.hash,
827 path: 'thinking level',
828 }
829 } else if (thinking && thinks && !reasoning) {
830 factSources.reasoning = {
831 derivation: 'docs-derived',
832 sourceUrl: GEMINI_THINKING_URL,
833 sourceHash: thinking.hash,
834 path: 'silent',
835 }
836 }
837 if (!bound) {
838 return {
839 reasoning,
840 budget,
841 serverTools: null,
842 modalities: null,
843 factSources,
844 }
845 }
846 const source = (path: string): FactSource => ({
847 derivation: 'docs-derived',
848 sourceUrl: bound.sourceUrl,
849 sourceHash: bound.hash,
850 path,
851 })
852 if (bound.modalities) {
853 factSources.modalities = source('Supported data types')
854 }
855 if (bound.tools.length > 0) {
856 factSources.serverTools = Object.fromEntries(
857 bound.tools.map((tool) => [tool, source('Capabilities')]),
858 )
859 }
860 return {
861 reasoning,
862 budget,
863 serverTools: bound.tools.length > 0 ? bound.tools : null,
864 modalities: bound.modalities,
865 ...(bound.outputVideo ? { outputVideo: bound.outputVideo } : {}),
866 ...(documentedThinking ? { capabilities: ['reasoning'] } : {}),
867 factSources: {
868 ...factSources,
869 ...(documentedThinking
870 ? {
871 capabilities: {
872 reasoning: source(
873 bound.thinking ? 'Capabilities.Thinking' : 'thinking level',
874 ),
875 },
876 }
877 : {}),
878 },
879 }
880 }
881 return {
882 features,
883 docsFailures: docsReport(run),
884 thinkingLoaded: thinking !== null,
885 }
886}
887
888interface Placement {
889 id: string
890 kind: 'code' | 'version' | 'index' | 'sibling'
891 bound: BoundSection
892}
893
894/**
895 * A dedicated `/models/{id}` page wins over another page that repeats the
896 * id. Two model codes and no dedicated page is a real conflict. A version
897 * row, or a sibling table a looked-up page repeats, keeps the earlier page.
898 */
899function chooseBound(
900 id: string,
901 prev: BoundSection,
902 next: BoundSection,
903 kind: Placement['kind'],
904): BoundSection {
905 if (prev.sourceUrl === next.sourceUrl) return prev
906 const prevExact = modelSlug(prev.sourceUrl) === id
907 const nextExact = modelSlug(next.sourceUrl) === id
908 if (nextExact && !prevExact) return next
909 if (prevExact && !nextExact) return prev
910 if (kind === 'code') {
911 throw new Error(`gemini model pages: ${id} is documented twice`)
912 }
913 return prev
914}
915
916function pagePlacements(
917 page: LoadedPage,
918 index: Array<GeminiIndexDoc>,
919 bySlug: Map<string, BoundSection>,
920): Array<Placement> {
921 const doc = index.find((item) => pageUrl(item.url) === page.url)
922 const slug = modelSlug(page.url)
923 const placements = sectionPlacements(page, doc, slug, bySlug)
924 if (doc || !slug) return placements
925 // A page the index does not link was looked up for its own id. Another
926 // model's table on it is a repeat, outranked by any page that states it.
927 return placements.map((place) =>
928 familyOf(place.id, [slug]) === slug ||
929 familyOf(slug, [place.id]) === place.id
930 ? place
931 : { ...place, kind: 'sibling' as const },
932 )
933}
934
935function sectionPlacements(
936 page: LoadedPage,
937 doc: GeminiIndexDoc | undefined,
938 slug: string | null,
939 bySlug: Map<string, BoundSection>,
940): Array<Placement> {
941 const named = page.sections.filter((section) => section.ids.length > 0)
942 const out: Array<Placement> = []
943 const add = (
944 ids: Array<string>,
945 kind: Placement['kind'],
946 bound: BoundSection,
947 ) => {
948 for (const id of ids) out.push({ id, kind, bound })
949 }
950 if (named.length === 1 && named[0]) {
951 const bound: BoundSection = {
952 modalities: named[0].modalities,
953 outputVideo: named[0].outputVideo,
954 tools: named[0].tools,
955 reasoning: page.reasoning,
956 thinking: page.sections.some((section) => section.thinking === true),
957 sourceUrl: page.url,
958 hash: page.hash,
959 }
960 add(named[0].codes, 'code', bound)
961 add(named[0].versions, 'version', bound)
962 if (slug) bySlug.set(slug, bound)
963 add(
964 (doc?.ids ?? []).filter((id) => !named[0]?.ids.includes(id)),
965 'index',
966 bound,
967 )
968 return out
969 }
970 if (named.length === 0 && page.sections[0]) {
971 const bound: BoundSection = {
972 modalities: page.sections[0].modalities,
973 outputVideo: page.sections[0].outputVideo,
974 tools: page.sections[0].tools,
975 reasoning: page.reasoning,
976 thinking: page.sections.some((section) => section.thinking === true),
977 sourceUrl: page.url,
978 hash: page.hash,
979 }
980 if (slug) bySlug.set(slug, bound)
981 add(doc?.ids ?? [], 'index', bound)
982 return out
983 }
984 for (const section of named) {
985 const bound: BoundSection = {
986 modalities: section.modalities,
987 outputVideo: section.outputVideo,
988 tools: section.tools,
989 reasoning: null,
990 thinking: section.thinking === true,
991 sourceUrl: page.url,
992 hash: page.hash,
993 }
994 add(section.codes, 'code', bound)
995 add(section.versions, 'version', bound)
996 }
997 return out
998}