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