Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

gemini-features.ts

953 lines31.3 KB

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',
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
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)
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',
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
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
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}`)
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 }
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
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
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
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
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*\([^)]*\)/, ''))
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
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 }
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 if (MODEL_ID.test(token)) ids.push(token)
353 }
354 }
355 return ids
357​
358export interface GeminiIndexDoc {
359 url: string
360 ids: Array<string>
362​
363function cleanDocUrl(raw: string): string {
364 return `${GEMINI_DOCS_ORIGIN}${raw.replace(/[),.;]+$/, '').replace(/\.md$/, '')}`
366​
367/**
368 * Models index: each `/docs/…` link (relative, as the page writes them),
369 * plus endpoint ids from table rows only.
370 */
371export function parseModelIndexDocs(markdown: string): Array<GeminiIndexDoc> {
372 const byUrl = new Map<string, Set<string>>()
373 for (const line of markdocTables(markdown).split('\n')) {
374 const urls = [
375 ...line.matchAll(
376 /(?<=[("]|https:\/\/aistudio\.google\.com)\/docs\/[a-z0-9._/-]+/g,
377 ),
378 ]
379 if (urls.length === 0) continue
380 const ids = line.startsWith('|') ? backtickIds(line) : []
381 for (const match of urls) {
382 const url = cleanDocUrl(match[0])
383 const set = byUrl.get(url) ?? new Set<string>()
384 for (const id of ids) set.add(id)
385 byUrl.set(url, set)
386 }
387 }
388 return [...byUrl].map(([url, ids]) => ({ url, ids: [...ids] }))
390​
391function modelSlug(url: string): string | null {
392 return url.match(/\/models\/([a-z0-9.-]+?)(?:\.md)?$/)?.[1] ?? null
394​
395export function parseModelIndex(markdown: string): Array<string> {
396 return [
397 ...new Set(
398 parseModelIndexDocs(markdown).flatMap((doc) => {
399 const slug = modelSlug(doc.url)
400 return slug ? [slug] : []
401 }),
402 ),
403 ]
405​
406/** Whole seconds a model page's `Output video` limit states, both ends included. */
407export interface GeminiOutputVideo {
408 minSeconds: number
409 maxSeconds: number
411​
412/**
413 * `**Output video** 3s-15s (…)` in a model page's Limits row. Null when the
414 * page has no such limit. A limit that is not `Ns-Ms` throws: a video model
415 * with no range would publish an unbounded duration.
416 */
417export function parsePageOutputVideo(
418 markdown: string,
419): GeminiOutputVideo | null {
420 const stated = markdown.match(/\*\*Output video\*\*\s*([^|\n]*)/)?.[1]
421 if (stated === undefined) return null
422 const range = stated.match(/^(\d+)s\s*[-–]\s*(\d+)s\b/)
423 const minSeconds = Number(range?.[1])
424 const maxSeconds = Number(range?.[2])
425 if (!range || minSeconds < 1 || maxSeconds < minSeconds) {
426 throw new Error(
427 `gemini model page: unreadable Output video limit "${stated.trim().slice(0, 80)}"`,
428 )
429 }
430 return { minSeconds, maxSeconds }
432​
433export interface GeminiPageSection {
434 /** Model-code, agent-code, then version ids, in that order. */
435 ids: Array<string>
436 codes: Array<string>
437 versions: Array<string>
438 modalities: { input: Array<string>; output: Array<string> } | null
439 tools: Array<string>
440 thinking?: true
441 /** Present on a video model's section only. */
442 outputVideo?: GeminiOutputVideo
444​
445function labeledIds(chunk: string, label: string): Array<string> {
446 const ids: Array<string> = []
447 for (const line of chunk.split('\n')) {
448 if (!line.startsWith(`| ${label} |`)) continue
449 // "(… automatically routed to `gemini-3.5-flash-lite`)" names another
450 // model, not a version of this one.
451 ids.push(...backtickIds(line.replace(/\([^)]*\)/g, '')))
452 }
453 return [...new Set(ids)]
455​
456function sectionFrom(chunk: string): GeminiPageSection {
457 const codes = [
458 ...new Set([
459 ...labeledIds(chunk, 'Model code'),
460 ...labeledIds(chunk, 'Agent code'),
461 ]),
462 ]
463 const versions = labeledIds(chunk, 'Versions').filter(
464 (id) => !codes.includes(id),
465 )
466 const outputVideo = parsePageOutputVideo(chunk)
467 return {
468 ids: [...codes, ...versions],
469 codes,
470 versions,
471 modalities: parsePageModalities(chunk),
472 tools: parsePageTools(chunk),
473 ...(parsePageThinkingSupported(chunk) ? { thinking: true as const } : {}),
474 ...(outputVideo ? { outputVideo } : {}),
475 }
477​
478/**
479 * One section per model-code heading. A page with no model code stays one
480 * anonymous section, so a property table with no heading still parses.
481 * Preamble in front of the first model code is dropped.
482 */
483export function parsePageSections(page: string): Array<GeminiPageSection> {
484 const markdown = markdocTables(page)
485 const chunks = markdown
486 .split(/^(?=#{2,3} )/m)
487 .filter((chunk) => /^#{2,3} /.test(chunk))
488 const sections = (chunks.length > 0 ? chunks : [markdown]).map(sectionFrom)
489 const named = sections.filter((section) => section.ids.length > 0)
490 if (named.length > 0) return named
491 const modalities = parsePageModalities(markdown)
492 const tools = parsePageTools(markdown)
493 return modalities || tools.length > 0
494 ? [{ ids: [], codes: [], versions: [], modalities, tools }]
495 : []
497​
498/** Longest family `rawId` is, or extends with a version suffix. */
499export function familyOf(
500 rawId: string,
501 families: Iterable<string>,
502): string | null {
503 let best: string | null = null
504 for (const family of families) {
505 const exact = rawId === family
506 const extends_ =
507 rawId.startsWith(`${family}-`) &&
508 /^(preview|latest|exp|\d)/.test(rawId.slice(family.length + 1))
509 if ((exact || extends_) && (!best || family.length > best.length)) {
510 best = family
511 }
512 }
513 return best
515​
516type GeminiFeatures = Pick<ModelInfo, 'absent'> & {
517 capabilities?: Array<string>
518 reasoning: ModelReasoning | null
519 budget: GeminiBudgetBody | null
520 serverTools: Array<string> | null
521 modalities: { input: Array<string>; output: Array<string> } | null
522 /** The model page states an output video limit: a video model. */
523 outputVideo?: GeminiOutputVideo
524 factSources: ModelFactSources
526​
527interface LoadedPage {
528 url: string
529 sections: Array<GeminiPageSection>
530 reasoning: ModelReasoning | null
531 hash: string
533​
534interface BoundSection {
535 modalities: GeminiPageSection['modalities']
536 outputVideo?: GeminiOutputVideo
537 tools: Array<string>
538 reasoning: ModelReasoning | null
539 thinking: boolean
540 sourceUrl: string
541 hash: string
543​
544function pageUrl(url: string): string {
545 return `${url.replace(/\.md$/, '')}.md`
547​
548function docMatches(rawId: string, doc: GeminiIndexDoc): boolean {
549 if (doc.ids.includes(rawId)) return true
550 const slug = modelSlug(doc.url)
551 return slug !== null && familyOf(rawId, [slug]) === slug
553​
554/**
555 * Reasoning, server tools and modalities per listed id, with provenance.
556 * A model page that fails to load is that family's alone: its rows keep the
557 * stored tools and modalities (`absent`) and the failure is in
558 * `docsFailures`. The models index and the thinking page are the same kind
559 * of load: a throw is counted and the facts they feed stay `unavailable`,
560 * so one reshaped docs host does not drop the listing (#567). Reasoning
561 * the thinking table does not name is kept the same way, so a stored
562 * page-derived object survives a blip.
563 */
564export async function geminiModelFeatures(
565 rawIds: Array<string>,
566 kv?: KVNamespace,
567): Promise<{
568 features: (rawId: string, thinking: boolean | undefined) => GeminiFeatures
569 docsFailures: DocsFailures
570 /** False when the thinking page failed. The request map stays stored. */
571 thinkingLoaded: boolean
572}> {
573 const run = docsRun()
574 const [index, thinking, nativeAudio] = await Promise.all([
575 tryDocs(run, GEMINI_MODELS_INDEX_URL, (cached) =>
576 cached(kv, GEMINI_MODELS_INDEX_URL, async () => {
577 const parsed = parseModelIndexDocs(
578 await fetchText(GEMINI_MODELS_INDEX_URL),
579 )
580 if (!parsed.some((doc) => modelSlug(doc.url))) {
581 throw new Error('gemini models index: 0 slugs')
582 }
583 return parsed
584 }),
585 ),
586 tryDocs(run, GEMINI_THINKING_URL, (cached) =>
587 cached(kv, GEMINI_THINKING_URL, async () => {
588 const markdown = await fetchText(GEMINI_THINKING_URL)
589 const parsed = parseThinkingPage(markdown)
590 assertParsed(parsed, 'gemini thinking page')
591 return {
592 reasoning: Object.fromEntries(parsed),
593 budgets: Object.fromEntries(parseThinkingBudgets(markdown)),
594 hash: await sha256Text(markdown),
595 }
596 }),
597 ),
598 tryDocs(run, GEMINI_LIVE_GUIDE_URL, (cached) =>
599 geminiNativeAudioThinking(rawIds, kv, cached),
600 ),
601 ])
602 // Null is also "no native audio id listed"; only a listed one can fail.
603 const nativeAudioFailed =
604 nativeAudio === null && rawIds.some((id) => id.includes('native-audio'))
605 const indexDocs = index ?? []
606 const thinkingDoc = thinking ?? {
607 reasoning: {},
608 budgets: {},
609 hash: '',
610 }
611 const slugs = indexDocs.flatMap((doc) => {
612 const slug = modelSlug(doc.url)
613 return slug ? [slug] : []
614 })
615 // Google serves some model pages the index does not link (gemini-3.5-flash,
616 // #409). A listed id no index page covers is looked up at its own
617 // `/models/{id}` path. A 404 there is no page. Such a page names no ids
618 // for the index. A family page repeats its siblings' tables; those bind only
619 // where no other page states the sibling (`sibling` placements).
620 const unindexed: Array<GeminiIndexDoc> = rawIds
621 .filter(
622 (id) =>
623 /^[a-z0-9][a-z0-9.-]*$/.test(id) &&
624 !indexDocs.some((doc) => docMatches(id, doc)),
625 )
626 .map((id) => ({ url: `${GEMINI_MODEL_PAGE_BASE}${id}`, ids: [] }))
627 // No index: the per-id URLs are a guess, and a 404 there would write
628 // null modalities. Keep the stored page facts instead of fetching.
629 const docs = index ? [...index, ...unindexed] : []
630 const needed = index
631 ? [
632 ...index.filter((doc) => rawIds.some((id) => docMatches(id, doc))),
633 ...unindexed,
634 ]
635 : []
636 const pages = await mapConcurrent(needed, 8, (doc) => {
637 const url = pageUrl(doc.url)
638 const optional = unindexed.includes(doc)
639 return tryDocs(run, url, (cached) =>
640 cached(kv, url, async () => {
641 const markdown = optional
642 ? ((await fetchOptional(url)) ?? '')
643 : await fetchText(url)
644 const sections = markdown === '' ? [] : parsePageSections(markdown)
645 const named = sections.filter((section) => section.ids.length > 0)
646 return {
647 url,
648 sections,
649 reasoning: named.length <= 1 ? parsePageThinking(markdown) : null,
650 hash: await sha256Text(markdown),
651 }
652 }),
653 )
654 })
655 const loaded = pages.flatMap((page) => (page ? [page] : []))
656 // Every page read and none states modalities is a reshaped site, not a
657 // catalog without media. Throwing keeps the stored column.
658 if (
659 loaded.length > 0 &&
660 !loaded.some((page) => page.sections.some((section) => section.modalities))
661 ) {
662 throw new Error(
663 `gemini model pages: 0 of ${String(loaded.length)} state modalities`,
664 )
665 }
666 const byId = new Map<string, BoundSection>()
667 const bySlug = new Map<string, BoundSection>()
668 const loadedUrls = new Set(loaded.map((page) => page.url))
669 const placements = loaded.flatMap((page) =>
670 pagePlacements(page, indexDocs, bySlug),
671 )
672 for (const kind of ['code', 'version', 'index', 'sibling'] as const) {
673 for (const place of placements) {
674 if (place.kind !== kind) continue
675 const prev = byId.get(place.id)
676 byId.set(
677 place.id,
678 prev ? chooseBound(place.id, prev, place.bound, kind) : place.bound,
679 )
680 }
681 }
682 const lookup = (rawId: string): BoundSection | undefined => {
683 const exact = byId.get(rawId)
684 if (exact) return exact
685 const fromId = familyOf(rawId, byId.keys())
686 if (fromId) {
687 const bound = byId.get(fromId)
688 if (bound) return bound
689 }
690 const slug = familyOf(rawId, slugs)
691 return slug ? bySlug.get(slug) : undefined
692 }
693 const keepFailedDocs = (
694 rawId: string,
695 result: GeminiFeatures,
696 modelThinks: boolean | undefined,
697 ): GeminiFeatures => {
698 const facts: Array<ModelFact> = []
699 if (!index) facts.push('serverTools', 'modalities')
700 // The thinking page (or, for a native audio id, the live guide) failed
701 // and no model page stated a replacement. `false` from the listing is
702 // the API saying this model does not think.
703 const sourceFailed =
704 !thinking || (nativeAudioFailed && rawId.includes('native-audio'))
705 if (
706 sourceFailed &&
707 modelThinks !== false &&
708 result.reasoning == null &&
709 result.absent?.reasoning !== 'unavailable'
710 ) {
711 facts.push('reasoning')
712 }
713 if (facts.length === 0) return result
714 return {
715 ...result,
716 ...(!index ? { serverTools: null, modalities: null } : {}),
717 absent: { ...result.absent, ...unavailable(...facts).absent },
718 }
719 }
720 const features = (
721 rawId: string,
722 modelThinks: boolean | undefined,
723 ): GeminiFeatures =>
724 keepFailedDocs(rawId, readFeatures(rawId, modelThinks), modelThinks)
725 const readFeatures = (
726 rawId: string,
727 modelThinks: boolean | undefined,
728 ): GeminiFeatures => {
729 const factSources: ModelFactSources = {}
730 const budgetId = familyOf(rawId, Object.keys(thinkingDoc.budgets))
731 const budget =
732 modelThinks !== false && budgetId
733 ? (thinkingDoc.budgets[budgetId] ?? null)
734 : null
735 const bound = lookup(rawId)
736 const documentedThinking =
737 modelThinks !== false &&
738 (bound?.thinking === true || bound?.reasoning != null)
739 const thinks = modelThinks === true || documentedThinking
740 const family = thinks
741 ? familyOf(rawId, Object.keys(thinkingDoc.reasoning))
742 : null
743 let reasoning = family ? (thinkingDoc.reasoning[family] ?? null) : null
744 if (reasoning && family && thinking) {
745 factSources.reasoning = {
746 derivation: 'docs-derived',
747 sourceUrl: GEMINI_THINKING_URL,
748 sourceHash: thinking.hash,
749 path: family,
750 }
751 }
752 if (nativeAudio?.rawId === rawId && modelThinks !== false) {
753 reasoning = nativeAudio.reasoning
754 factSources.reasoning = {
755 derivation: 'docs-derived',
756 sourceUrl: GEMINI_LIVE_GUIDE_URL,
757 sourceHash: nativeAudio.hash,
758 path: 'Model comparison; Thinking; exact native audio model',
759 }
760 }
761 const failed = docs
762 .filter((doc) => docMatches(rawId, doc))
763 .some((doc) => !loadedUrls.has(pageUrl(doc.url)))
764 if (failed) {
765 const absentFacts: Array<ModelFact> = ['serverTools', 'modalities']
766 if (modelThinks !== false && !reasoning) absentFacts.push('reasoning')
767 return {
768 reasoning,
769 budget,
770 serverTools: null,
771 modalities: null,
772 factSources,
773 ...unavailable(...absentFacts),
774 }
775 }
776 if (!reasoning && thinks && !family && bound?.reasoning) {
777 reasoning = bound.reasoning
778 factSources.reasoning = {
779 derivation: 'docs-derived',
780 sourceUrl: bound.sourceUrl,
781 sourceHash: bound.hash,
782 path: 'thinking level',
783 }
784 } else if (thinking && thinks && !reasoning) {
785 factSources.reasoning = {
786 derivation: 'docs-derived',
787 sourceUrl: GEMINI_THINKING_URL,
788 sourceHash: thinking.hash,
789 path: 'silent',
790 }
791 }
792 if (!bound) {
793 return {
794 reasoning,
795 budget,
796 serverTools: null,
797 modalities: null,
798 factSources,
799 }
800 }
801 const source = (path: string): FactSource => ({
802 derivation: 'docs-derived',
803 sourceUrl: bound.sourceUrl,
804 sourceHash: bound.hash,
805 path,
806 })
807 if (bound.modalities) {
808 factSources.modalities = source('Supported data types')
809 }
810 if (bound.tools.length > 0) {
811 factSources.serverTools = Object.fromEntries(
812 bound.tools.map((tool) => [tool, source('Capabilities')]),
813 )
814 }
815 return {
816 reasoning,
817 budget,
818 serverTools: bound.tools.length > 0 ? bound.tools : null,
819 modalities: bound.modalities,
820 ...(bound.outputVideo ? { outputVideo: bound.outputVideo } : {}),
821 ...(documentedThinking ? { capabilities: ['reasoning'] } : {}),
822 factSources: {
823 ...factSources,
824 ...(documentedThinking
825 ? {
826 capabilities: {
827 reasoning: source(
828 bound.thinking ? 'Capabilities.Thinking' : 'thinking level',
829 ),
830 },
831 }
832 : {}),
833 },
834 }
835 }
836 return {
837 features,
838 docsFailures: docsReport(run),
839 thinkingLoaded: thinking !== null,
840 }
842​
843interface Placement {
844 id: string
845 kind: 'code' | 'version' | 'index' | 'sibling'
846 bound: BoundSection
848​
849/**
850 * A dedicated `/models/{id}` page wins over another page that repeats the
851 * id. Two model codes and no dedicated page is a real conflict. A version
852 * row, or a sibling table a looked-up page repeats, keeps the earlier page.
853 */
854function chooseBound(
855 id: string,
856 prev: BoundSection,
857 next: BoundSection,
858 kind: Placement['kind'],
859): BoundSection {
860 if (prev.sourceUrl === next.sourceUrl) return prev
861 const prevExact = modelSlug(prev.sourceUrl) === id
862 const nextExact = modelSlug(next.sourceUrl) === id
863 if (nextExact && !prevExact) return next
864 if (prevExact && !nextExact) return prev
865 if (kind === 'code') {
866 throw new Error(`gemini model pages: ${id} is documented twice`)
867 }
868 return prev
870​
871function pagePlacements(
872 page: LoadedPage,
873 index: Array<GeminiIndexDoc>,
874 bySlug: Map<string, BoundSection>,
875): Array<Placement> {
876 const doc = index.find((item) => pageUrl(item.url) === page.url)
877 const slug = modelSlug(page.url)
878 const placements = sectionPlacements(page, doc, slug, bySlug)
879 if (doc || !slug) return placements
880 // A page the index does not link was looked up for its own id. Another
881 // model's table on it is a repeat, outranked by any page that states it.
882 return placements.map((place) =>
883 familyOf(place.id, [slug]) === slug ||
884 familyOf(slug, [place.id]) === place.id
885 ? place
886 : { ...place, kind: 'sibling' as const },
887 )
889​
890function sectionPlacements(
891 page: LoadedPage,
892 doc: GeminiIndexDoc | undefined,
893 slug: string | null,
894 bySlug: Map<string, BoundSection>,
895): Array<Placement> {
896 const named = page.sections.filter((section) => section.ids.length > 0)
897 const out: Array<Placement> = []
898 const add = (
899 ids: Array<string>,
900 kind: Placement['kind'],
901 bound: BoundSection,
902 ) => {
903 for (const id of ids) out.push({ id, kind, bound })
904 }
905 if (named.length === 1 && named[0]) {
906 const bound: BoundSection = {
907 modalities: named[0].modalities,
908 outputVideo: named[0].outputVideo,
909 tools: named[0].tools,
910 reasoning: page.reasoning,
911 thinking: page.sections.some((section) => section.thinking === true),
912 sourceUrl: page.url,
913 hash: page.hash,
914 }
915 add(named[0].codes, 'code', bound)
916 add(named[0].versions, 'version', bound)
917 if (slug) bySlug.set(slug, bound)
918 add(
919 (doc?.ids ?? []).filter((id) => !named[0]?.ids.includes(id)),
920 'index',
921 bound,
922 )
923 return out
924 }
925 if (named.length === 0 && page.sections[0]) {
926 const bound: BoundSection = {
927 modalities: page.sections[0].modalities,
928 outputVideo: page.sections[0].outputVideo,
929 tools: page.sections[0].tools,
930 reasoning: page.reasoning,
931 thinking: page.sections.some((section) => section.thinking === true),
932 sourceUrl: page.url,
933 hash: page.hash,
934 }
935 if (slug) bySlug.set(slug, bound)
936 add(doc?.ids ?? [], 'index', bound)
937 return out
938 }
939 for (const section of named) {
940 const bound: BoundSection = {
941 modalities: section.modalities,
942 outputVideo: section.outputVideo,
943 tools: section.tools,
944 reasoning: null,
945 thinking: section.thinking === true,
946 sourceUrl: page.url,
947 hash: page.hash,
948 }
949 add(section.codes, 'code', bound)
950 add(section.versions, 'version', bound)
951 }
952 return out