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