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

reasoning-config.ts

733 lines24.4 KB

1/**
2 * Reasoning objects for chat rows whose capabilities already say `reasoning`
3 * (issue #110). Mode and effort names come only from a native listing or
4 * docs page. A model the source does not configure stays null; `path:
5 * 'silent'` records that the page was read and did not state a mode.
6 */
7import { ingestFailedEvent, noteIngest } from '../ingest/ingest-signals.ts'
8import { emptySources } from './fact-sources.ts'
9import {
10 assertParsed,
11 cachedDocs,
12 markdownTableRows,
13 tryDocs,
14 unavailable,
15} from './model-facts.ts'
16import type { DocsRun } from './model-facts.ts'
17import { groqModelPageUrl } from './groq-pricing.ts'
18import { fetchByteplusDoc } from './byteplus-docs.ts'
19import { pricingContent, tableRows } from './byteplus-pricing.ts'
20import type { ByteplusDoc } from './byteplus-pricing.ts'
21import { fetchText, reasoningViolation, sha256Text } from './types.ts'
22import type { ModelFactSources, ModelInfo, ModelReasoning } from './types.ts'
23​
24/**
25 * The rendered reasoning guide. `https://docs.mistral.ai/llms.txt` links
26 * `https://docs.mistral.ai/inference/conversations/reasoning.md`, and the
27 * old `/studio/conversations/reasoning.md` redirects there, but that
28 * markdown twin 404s (checked 2026-11-19). This HTML page is what serves
29 * the guide.
30 */
31export const MISTRAL_REASONING_URL =
32 'https://docs.mistral.ai/inference/conversations/reasoning'
33​
34/**
35 * Mistral's docs site returns a full HTML document where `llms.txt` still
36 * names a `.md` twin. The reasoning and web-search parsers read the
37 * markdown shape, so a rendered page becomes that shape: code becomes
38 * backticks, links become `[text]`, list items become bullets. A markdown
39 * body is returned unchanged.
40 */
41export function mistralDocsMarkdown(body: string): string {
42 if (!/<!doctype html|<html[\s>]/i.test(body)) return body
43 let text = body
44 .replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '')
45 .replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, '')
46 const main = text.match(/<main\b[^>]*>[\s\S]*?<\/main>/i)
47 text = main?.[0] ?? text
48 // Code before links, so a linked code span is still a backtick.
49 // Links need brackets: the web-search parser matches `[Conversations API]`.
50 text = text
51 .replace(/<code\b[^>]*>/gi, '`')
52 .replace(/<\/code>/gi, '`')
53 .replace(/<a\b[^>]*>([\s\S]*?)<\/a>/gi, '[$1]')
54 .replace(/<li\b[^>]*>/gi, '\n- ')
55 .replace(
56 /<h([1-6])\b[^>]*>/gi,
57 (_, level: string) => `\n${'#'.repeat(Number(level))} `,
58 )
59 .replace(/<\/h[1-6]>/gi, '\n')
60 .replace(/<br\s*\/?>/gi, '\n')
61 .replace(/<\/(p|div|li|tr|ul|ol|section)>/gi, '\n')
62 .replace(/<[^>]+>/g, '')
63 text = text
64 .replace(/&nbsp;/g, ' ')
65 .replace(/&quot;/g, '"')
66 .replace(/&#39;|&apos;/g, "'")
67 .replace(/&lt;/g, '<')
68 .replace(/&gt;/g, '>')
69 .replace(/&#(\d+);/g, (_, digits: string) =>
70 String.fromCodePoint(Number(digits)),
71 )
72 .replace(/&#x([0-9a-f]+);/gi, (_, hex: string) =>
73 String.fromCodePoint(Number.parseInt(hex, 16)),
74 )
75 .replace(/&amp;/g, '&')
76 return text.replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n')
78​
79export const GROQ_REASONING_URL = 'https://console.groq.com/docs/reasoning.md'
80export const COHERE_REASONING_URL = 'https://docs.cohere.com/docs/reasoning.md'
81export const BYTEPLUS_REASONING_URL =
82 'https://docs.byteplus.com/en/docs/ModelArk/1449737'
83​
84/** The thinking page names no mode for this id. */
85export const REASONING_SOURCE_SILENT = 'silent'
86​
87/**
88 * The write gate for `reasoning`. A listed object that breaks the shape is
89 * not stored: the row keeps the value and source it had (null on a new row),
90 * the poll goes on, and an `ingest_failed` event names the model and reason.
91 */
92export function keepValidReasoning(
93 providerId: string,
94 info: ModelInfo,
95 prior?: { reasoning: unknown; factSources: unknown },
96): ModelInfo {
97 if (info.reasoning == null) return info
98 const reason = reasoningViolation(info.reasoning)
99 if (reason === null) return info
100 noteIngest(
101 ingestFailedEvent(
102 'models-poll',
103 providerId,
104 `${info.rawId}: reasoning not stored: ${reason}`,
105 ),
106 )
107 const { reasoning: _refused, ...sources } = info.factSources ?? {}
108 const priorSource = (prior?.factSources as ModelFactSources | null)?.reasoning
109 const factSources = priorSource
110 ? { ...sources, reasoning: priorSource }
111 : sources
112 return {
113 ...info,
114 reasoning: (prior?.reasoning ?? null) as ModelReasoning | null,
115 factSources: emptySources(factSources) ? undefined : factSources,
116 }
118​
119export function listsReasoning(capabilities: unknown): boolean {
120 return Array.isArray(capabilities) && capabilities.includes('reasoning')
122​
123function docsReasoningSource(
124 sourceUrl: string,
125 sourceHash: string,
126 path: string,
127): ModelFactSources {
128 return {
129 reasoning: {
130 derivation: 'docs-derived',
131 sourceUrl,
132 sourceHash,
133 path,
134 },
135 }
137​
138/**
139 * Attach a parsed reasoning object, or a silent note when the row already
140 * has the reasoning capability and this source does not configure it.
141 */
142export function reasoningFactsFor(
143 rawId: string,
144 byId: Record<string, ModelReasoning>,
145 source: { url: string; hash: string },
146 capability: boolean,
147): Partial<ModelInfo> {
148 const reasoning = byId[rawId]
149 if (reasoning) {
150 return {
151 reasoning,
152 factSources: docsReasoningSource(source.url, source.hash, 'reasoning'),
153 }
154 }
155 if (!capability) return {}
156 return {
157 factSources: docsReasoningSource(
158 source.url,
159 source.hash,
160 REASONING_SOURCE_SILENT,
161 ),
162 }
164​
165/** Merge docs patches without letting one factSources bag replace another. */
166export function overlayModelFacts(
167 model: ModelInfo,
168 ...patches: Array<Partial<ModelInfo>>
169): ModelInfo {
170 let next: ModelInfo = { ...model }
171 const factSources: ModelFactSources = { ...model.factSources }
172 for (const patch of patches) {
173 const { factSources: more, absent, ...rest } = patch
174 next = { ...next, ...rest }
175 // Each patch may mark its own facts absent; one must not erase another's.
176 if (absent) next.absent = { ...next.absent, ...absent }
177 if (more) Object.assign(factSources, more)
178 }
179 if (emptySources(factSources)) {
180 const { factSources: _drop, ...bare } = next
181 return bare
182 }
183 return { ...next, factSources }
185​
186/**
187 * OpenRouter `GET /api/v1/models` reasoning object. `supported_efforts`
188 * names the effort mode. `null` accepts gateway effort names supplied from
189 * normative host docs; mandatory rows reject the documented disable value.
190 * Without gateway docs, null keeps its effort names unknown. `supports_max_tokens` is a budget
191 * only when the listing does not speak about efforts. No reasoning object,
192 * or a mandatory flag that is not a boolean, stays null.
193 */
194export function openRouterReasoning(
195 row: {
196 reasoning?: {
197 supported_efforts?: Array<string | null> | null
198 mandatory?: unknown
199 supports_max_tokens?: unknown
200 } | null
201 },
202 gatewayEfforts?: ReadonlyArray<string>,
203 gatewayToggle?: boolean,
204): ModelReasoning | null {
205 const reasoning = row.reasoning
206 if (!reasoning || typeof reasoning !== 'object') return null
207 for (const key of ['mandatory', 'supports_max_tokens'] as const) {
208 const value = reasoning[key]
209 if (value != null && typeof value !== 'boolean')
210 throw new Error(`openrouter: malformed native ${key}`)
211 }
212 const declared = reasoning.supported_efforts
213 if (
214 declared != null &&
215 (!Array.isArray(declared) ||
216 declared.some(
217 (value) =>
218 value != null && (typeof value !== 'string' || !value.length),
219 ))
220 )
221 throw new Error('openrouter: malformed native supported_efforts')
222 if (typeof reasoning.mandatory !== 'boolean') return null
223 const mandatory = reasoning.mandatory
224 if (Array.isArray(reasoning.supported_efforts)) {
225 const efforts = reasoning.supported_efforts.filter(
226 (effort): effort is string =>
227 typeof effort === 'string' && effort.length > 0,
228 )
229 if (efforts.length === 0) return null
230 return { mode: 'effort', mandatory, efforts }
231 }
232 if (reasoning.supported_efforts === null) {
233 return {
234 mode: 'effort',
235 mandatory,
236 ...(gatewayEfforts
237 ? {
238 efforts: gatewayEfforts.filter(
239 (value) => !mandatory || value !== 'none',
240 ),
241 }
242 : {}),
243 }
244 }
245 if (reasoning.supports_max_tokens === true) {
246 return { mode: 'budget', mandatory }
247 }
248 if (gatewayToggle === true && mandatory === false)
249 return { mode: 'toggle', mandatory: false }
250 return null
252​
253/**
254 * Mistral's reasoning guide. Bullets that name `reasoning_effort` are effort
255 * mode. Effort names are the `reasoning_effort = "…"` values, unless the
256 * same bullet publishes its own list. A bullet that names its own effort
257 * levels ("Supports `low`, `medium`, and `high` reasoning effort") is that
258 * model's list, not the shared one. Native "always on, no parameter"
259 * prose names no mode and contributes nothing.
260 */
261export function parseMistralReasoning(
262 markdown: string,
263): Map<string, ModelReasoning> {
264 const out = new Map<string, ModelReasoning>()
265 const prose = mistralDocsMarkdown(markdown).replace(/```[\s\S]*?```/g, '')
266 const preludeEnd = prose.search(/handling thinking chunks/i)
267 const prelude = preludeEnd < 0 ? prose : prose.slice(0, preludeEnd)
268 const bullet =
269 /`([a-z0-9][a-z0-9.-]*)`\)?:\s*Supports adjustable reasoning via the `reasoning_effort`/g
270 // `reasoning_effort = "none"` omits the thinking chunk for Mistral models.
271 // Example assignments are still not an allowlist. A model's own value list
272 // below replaces this.
273 const noneOmits =
274 /reasoning_effort\s*=\s*"none"[\s\S]{0,240}thinking chunk (?:is )?omitted/i.test(
275 prelude,
276 )
277 for (const match of prelude.matchAll(bullet)) {
278 const id = match[1]
279 if (!id) continue
280 out.set(id, { mode: 'effort', mandatory: noneOmits ? false : null })
281 }
282 // The scoped model list is followed by normative parameter values. These
283 // are not code examples; an explicit model-specific list overrides them.
284 const valueSection = prelude.split(
285 'The `reasoning_effort` parameter controls',
286 )[1]
287 const levels = [
288 ...(valueSection?.matchAll(/^- `reasoning_effort\s*=\s*"([a-z]+)"`:/gm) ??
289 []),
290 ].flatMap((match) => (match[1] ? [match[1]] : []))
291 if (levels.length) {
292 for (const id of out.keys())
293 out.set(id, {
294 mode: 'effort',
295 mandatory: noneOmits && levels.includes('none') ? false : null,
296 efforts: levels,
297 })
298 }
299 const ownList =
300 /`([a-z0-9][a-z0-9.-]*)`:[^\n]{0,240}?Supported values are ([^\n.]+)/g
301 for (const match of prelude.matchAll(ownList)) {
302 const id = match[1]
303 if (!id || !out.has(id)) continue
304 const efforts = [...(match[2] ?? '').matchAll(/`([a-z]+)`/g)].flatMap(
305 (found) => (found[1] ? [found[1]] : []),
306 )
307 if (efforts.length === 0) continue
308 const ownNote = prelude
309 .split(/\n\s*\n/)
310 .find(
311 (para) =>
312 para.split('\n').some((line) => line.startsWith('`' + id + '` ')) &&
313 /always|cannot/i.test(para),
314 )
315 const alwaysThinking =
316 !!ownNote &&
317 /(?:reasoning|thinking)\s+(?:is\s+)?(?:always on|cannot be disabled|cannot be turned off)|is always returned[^.\n]*\(thinking\s*\+\s*text\)/i.test(
318 ownNote,
319 )
320 out.set(id, {
321 mode: 'effort',
322 mandatory: alwaysThinking
323 ? true
324 : noneOmits && efforts.includes('none')
325 ? false
326 : null,
327 efforts,
328 })
329 }
330 // Own effort names on the bullet itself. Applied after the shared
331 // high/none list so that list does not replace them. A list with no
332 // `none` leaves mandatory null until prose says the model always reasons.
333 const namedEfforts = new Set<string>()
334 const named =
335 /`([a-z0-9][a-z0-9.-]*)`\)?:\s*Supports\s+([^.\n]{0,200}?)\sreasoning effort/g
336 for (const match of prose.matchAll(named)) {
337 const id = match[1]
338 const efforts = [...(match[2] ?? '').matchAll(/`([a-z]+)`/g)].flatMap(
339 (found) => (found[1] ? [found[1]] : []),
340 )
341 if (!id || efforts.length === 0) continue
342 out.set(id, { mode: 'effort', mandatory: null, efforts })
343 namedEfforts.add(id)
344 }
345 // "`mistral-large-4` / `mistral-large-4-0`) supports three reasoning levels"
346 const sharedLadder =
347 /`([a-z0-9][a-z0-9.-]*)`\s*\/\s*`([a-z0-9][a-z0-9.-]*)`\)\s*supports three reasoning levels/gi
348 for (const match of prose.matchAll(sharedLadder)) {
349 const leftId = match[1]
350 const rightId = match[2]
351 if (!leftId || !rightId) continue
352 const left = out.get(leftId)
353 const right = out.get(rightId)
354 if (left && !right) {
355 out.set(rightId, { ...left })
356 namedEfforts.add(rightId)
357 } else if (right && !left) {
358 out.set(leftId, { ...right })
359 namedEfforts.add(leftId)
360 }
361 }
362 for (const id of namedEfforts) {
363 const reasoning = out.get(id)
364 if (!reasoning || reasoning.efforts?.includes('none')) continue
365 if (!statesAlwaysReasons(prose, id)) continue
366 out.set(id, { ...reasoning, mandatory: true })
367 }
368 return out
370​
371/** The id's section says reasoning cannot be turned off. */
372function statesAlwaysReasons(prose: string, id: string): boolean {
373 const needle = '`' + id + '`'
374 let from = 0
375 while (from < prose.length) {
376 const at = prose.indexOf(needle, from)
377 if (at < 0) return false
378 const rest = prose.slice(at)
379 const heading = rest.search(/\n#{2,3} /)
380 const block = heading < 0 ? rest.slice(0, 1600) : rest.slice(0, heading)
381 if (/always reasons/i.test(block)) return true
382 from = at + needle.length
383 }
384 return false
386​
387interface NamedModel {
388 id: string
389 label: string
391​
392function headingBlocks(
393 markdown: string,
394): Array<{ title: string; body: string }> {
395 return markdown.split(/\n(?=#{2,3} )/).flatMap((part) => {
396 const match = part.match(/^#{2,3} (.+)$/m)
397 const title = (match?.[1] ?? '')
398 .replace(/^\s*\[([^\]]+)\]\([^)]*\)\s*/, '$1')
399 .replace(/\s*\([^)]*\)\s*$/, '')
400 .trim()
401 if (!match || title.length === 0) return []
402 return [{ title, body: part.slice(part.indexOf('\n') + 1) }]
403 })
405​
406function linkLabel(cell: string): string {
407 return cell
408 .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
409 .replace(/\\/g, '')
410 .trim()
412​
413/** Rows of the Groq reasoning guide's Supported Models table. */
414function groqSupportedModels(markdown: string): Array<NamedModel> {
415 return headingBlocks(markdown)
416 .filter((block) => block.title === 'Supported Models')
417 .flatMap((block) => markdownTableRows(block.body))
418 .flatMap((row) => {
419 const id = (row[0] ?? '').trim()
420 if (!/^[A-Za-z0-9][A-Za-z0-9./_-]*$/.test(id) || id === 'Model ID') {
421 return []
422 }
423 return [{ id, label: linkLabel(row[1] ?? '') }]
424 })
426​
427/** Groq reasoning page: per-model `reasoning_effort` tables. Ids the page lists as reasoning models but never gives options stay absent. */
428export function parseGroqReasoning(
429 markdown: string,
430): Map<string, ModelReasoning> {
431 const models = groqSupportedModels(markdown)
432 const effortsById = new Map<string, Array<string>>()
433 const conflicts = new Set<string>()
434 for (const block of headingBlocks(markdown)) {
435 if (!block.title.startsWith('Options for Reasoning Effort')) continue
436 const efforts: Array<string> = []
437 for (const row of markdownTableRows(block.body)) {
438 const name = (row[0] ?? '').replace(/[`\\]/g, '').trim()
439 if (/^[a-z]+$/.test(name) && !efforts.includes(name)) efforts.push(name)
440 }
441 if (efforts.length === 0) continue
442 const norm = (value: string) =>
443 value.toLowerCase().replace(/[^a-z0-9]/g, '')
444 const sectionNorm = norm(block.body)
445 const linked = [...block.body.matchAll(/\[([^\]]+)\]/g)].map((match) =>
446 norm(match[1] ?? ''),
447 )
448 for (const model of models) {
449 const labelNorm = norm(model.label)
450 const named =
451 block.body.includes(model.id) ||
452 (labelNorm.length > 0 && sectionNorm.includes(labelNorm)) ||
453 linked.some((name) => name.length >= 6 && labelNorm.includes(name))
454 if (!named) continue
455 const prior = effortsById.get(model.id)
456 if (prior && prior.join('\0') !== efforts.join('\0')) {
457 conflicts.add(model.id)
458 continue
459 }
460 effortsById.set(model.id, efforts)
461 }
462 }
463 const out = new Map<string, ModelReasoning>()
464 for (const [id, efforts] of effortsById) {
465 if (conflicts.has(id)) continue
466 out.set(id, {
467 mode: 'effort',
468 mandatory: !efforts.includes('none'),
469 efforts,
470 })
471 }
472 return out
474​
475/**
476 * Cohere's reasoning guide. `thinking.token_budget` is budget mode, and
477 * thinking can be turned off, so it is not mandatory. No effort names are
478 * published. A page that does not state `token_budget` configures nothing.
479 *
480 * The guide names one model in its examples but says "Cohere's reasoning
481 * models are hybrid", enabled or disabled. While it says so, the same
482 * configuration is kept under `COHERE_ANY_REASONING` for the other models
483 * the listing flags `reasoning` (Command A+, North Mini Code).
484 */
485export const COHERE_ANY_REASONING = '*'
486​
487export function parseCohereReasoning(
488 markdown: string,
489): Map<string, ModelReasoning> {
490 const out = new Map<string, ModelReasoning>()
491 if (!/token_budget/.test(markdown)) return out
492 if (!/"type":\s*"disabled"|turns off thinking/i.test(markdown)) return out
493 const ids = new Set<string>()
494 for (const match of markdown.matchAll(
495 /`([a-z0-9][a-z0-9._-]*-\d{2}-\d{4})`/g,
496 )) {
497 if (match[1]) ids.add(match[1])
498 }
499 for (const match of markdown.matchAll(/model="([^"]+)"/g)) {
500 if (match[1]) ids.add(match[1])
501 }
502 if (
503 /Cohere's reasoning models are \*hybrid\*, meaning reasoning can be enabled \([^)]*\) or disabled/.test(
504 markdown,
505 )
506 ) {
507 ids.add(COHERE_ANY_REASONING)
508 }
509 for (const id of ids) {
510 out.set(id, { mode: 'budget', mandatory: false })
511 }
512 return out
514​
515const BYTEPLUS_EFFORT = /^(none|minimal|low|medium|high|xhigh|max)$/
516const BYTEPLUS_MODEL_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*-\d{4,}$/
517​
518/**
519 * The ModelArk deep-thinking page is a Lark doc (`curDoc.Content`). Under
520 * the "Adjust chain-of-thought length" heading, effort names are the
521 * published value list and model ids are the cells of that section's
522 * "Supported models" table, nothing else on the page (#432). Missing either
523 * configures nothing, so the load fails closed.
524 */
525export function parseByteplusReasoning(
526 body: string,
527): Map<string, ModelReasoning> {
528 const doc = JSON.parse(
529 pricingContent(body, 'byteplus reasoning page'),
530 ) as ByteplusDoc
531 const efforts: Array<string> = []
532 const ids: Array<string> = []
533 let inSection = false
534 for (const op of doc.data['0']?.ops ?? []) {
535 if (typeof op.insert !== 'string') continue
536 const text = op.insert.trim()
537 if (!inSection) {
538 inSection = /^adjust chain-of-thought length$/i.test(text)
539 continue
540 }
541 if (op.attributes?.heading) break
542 // Effort names are the value list, which ends where the table begins.
543 if (
544 ids.length === 0 &&
545 BYTEPLUS_EFFORT.test(text) &&
546 !efforts.includes(text)
547 ) {
548 efforts.push(text)
549 }
550 const spec = op.attributes?.aceTable
551 const [header, ...rows] = spec ? (tableRows(doc, spec) ?? []) : []
552 if (!/^supported models$/i.test(header?.[0] ?? '')) continue
553 for (const cell of rows.map((row) => row[0] ?? '')) {
554 for (const token of cell.split(/[\s*]+/)) {
555 if (BYTEPLUS_MODEL_ID.test(token) && !ids.includes(token)) {
556 ids.push(token)
557 }
558 }
559 }
560 }
561 const out = new Map<string, ModelReasoning>()
562 if (efforts.length === 0) return out
563 const reasoning: ModelReasoning = {
564 mode: 'effort',
565 mandatory: !efforts.includes('none'),
566 efforts,
567 }
568 for (const id of ids) out.set(id, reasoning)
569 return out
571​
572async function loadReasoningMap(
573 kv: KVNamespace | undefined,
574 url: string,
575 source: string,
576 parse: (body: string) => Map<string, ModelReasoning>,
577 fetchBody: (url: string) => Promise<string> = fetchText,
578 cached: typeof cachedDocs = cachedDocs,
579): Promise<{
580 byId: Record<string, ModelReasoning>
581 hash: string
582 url: string
583}> {
584 return cached(kv, url, async () => {
585 const body = await fetchBody(url)
586 const parsed = parse(body)
587 assertParsed(parsed, source)
588 return { byId: Object.fromEntries(parsed), hash: await sha256Text(body) }
589 }).then((doc) => ({ ...doc, url }))
591​
592function lookup(doc: {
593 byId: Record<string, ModelReasoning>
594 hash: string
595 url: string
596}): (rawId: string, capability: boolean) => Partial<ModelInfo> {
597 return (rawId, capability) =>
598 reasoningFactsFor(rawId, doc.byId, doc, capability)
600​
601export async function mistralModelReasoning(
602 kv?: KVNamespace,
603 cached: typeof cachedDocs = cachedDocs,
604) {
605 const doc = await loadReasoningMap(
606 kv,
607 MISTRAL_REASONING_URL,
608 'mistral reasoning page',
609 parseMistralReasoning,
610 fetchText,
611 cached,
612 )
613 return lookup(doc)
615​
616/**
617 * A Groq model page's own effort list: "low/medium/high reasoning effort"
618 * on openai/gpt-oss-safeguard-20b. No such sentence is null. A word in it
619 * that is not an effort name throws.
620 */
621export function parseGroqPageEfforts(markdown: string): Array<string> | null {
622 const list = markdown.match(
623 /\b([a-z]+(?:\/[a-z]+)+) reasoning effort\b/i,
624 )?.[1]
625 if (!list) return null
626 const efforts = list.toLowerCase().split('/')
627 if (
628 !efforts.every((effort) =>
629 /^(none|minimal|low|medium|high|xhigh|max)$/.test(effort),
630 )
631 ) {
632 throw new Error(`groq model page: unreadable reasoning effort "${list}"`)
633 }
634 return efforts
636​
637/**
638 * The reasoning guide's effort tables. A model the guide lists as reasoning
639 * but gives no options is read from its own model page (#432): the guide
640 * says `reasoning_effort` is GPT-OSS 20B/120B only, while the
641 * gpt-oss-safeguard-20b page states low/medium/high, and a live probe on
642 * 2026-10-23 accepted them. `mandatory` stays null: no page says `none`
643 * is refused. A guide or page that fails to load marks reasoning
644 * `unavailable` (kept) and is counted in `run`.
645 */
646export async function groqModelReasoning(
647 kv: KVNamespace | undefined,
648 run: DocsRun,
649 rawIds: Array<string>,
650): Promise<(rawId: string, capability: boolean) => Partial<ModelInfo>> {
651 // Its own cache key: this entry's shape (with `listed`) is not the plain
652 // reasoning map other loaders cache under the URL.
653 const guide = await tryDocs(run, GROQ_REASONING_URL, (cached) =>
654 cached(kv, `${GROQ_REASONING_URL}#models`, async () => {
655 const body = await fetchText(GROQ_REASONING_URL)
656 const parsed = parseGroqReasoning(body)
657 assertParsed(parsed, 'groq reasoning page')
658 return {
659 byId: Object.fromEntries(parsed),
660 listed: groqSupportedModels(body).map((model) => model.id),
661 hash: await sha256Text(body),
662 }
663 }),
664 )
665 if (!guide) return () => unavailable('reasoning')
666 const doc = { ...guide, url: GROQ_REASONING_URL }
667 const fromPages = new Map<string, Partial<ModelInfo>>()
668 const pageIds = guide.listed.filter(
669 (id) => !(id in guide.byId) && rawIds.includes(id),
670 )
671 await Promise.all(
672 pageIds.map(async (id) => {
673 const url = groqModelPageUrl(id)
674 const page = await tryDocs(run, url, (cached) =>
675 cached(kv, url, async () => {
676 const body = await fetchText(url)
677 return {
678 efforts: parseGroqPageEfforts(body),
679 hash: await sha256Text(body),
680 }
681 }),
682 )
683 if (!page) {
684 fromPages.set(id, unavailable('reasoning'))
685 } else if (page.efforts) {
686 const reasoning: ModelReasoning = {
687 mode: 'effort',
688 mandatory: null,
689 efforts: page.efforts,
690 }
691 fromPages.set(
692 id,
693 reasoningFactsFor(
694 id,
695 { [id]: reasoning },
696 { url, hash: page.hash },
697 true,
698 ),
699 )
700 }
701 }),
702 )
703 return (rawId, capability) =>
704 fromPages.get(rawId) ?? reasoningFactsFor(rawId, doc.byId, doc, capability)
706​
707export async function cohereModelReasoning(kv?: KVNamespace) {
708 const doc = await loadReasoningMap(
709 kv,
710 COHERE_REASONING_URL,
711 'cohere reasoning page',
712 parseCohereReasoning,
713 )
714 const any = COHERE_ANY_REASONING in doc.byId
715 return (rawId: string, capability: boolean): Partial<ModelInfo> =>
716 reasoningFactsFor(
717 capability && any && !(rawId in doc.byId) ? COHERE_ANY_REASONING : rawId,
718 doc.byId,
719 doc,
720 capability,
721 )
723​
724export async function byteplusModelReasoning(kv?: KVNamespace) {
725 const doc = await loadReasoningMap(
726 kv,
727 BYTEPLUS_REASONING_URL,
728 'byteplus reasoning page',
729 parseByteplusReasoning,
730 fetchByteplusDoc,
731 )
732 return lookup(doc)