Open History to see the last commit
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 { assertParsed, cachedDocs, markdownTableRows } from './model-facts.ts'
10import { fetchByteplusDoc } from './byteplus-docs.ts'
11import { fetchText, reasoningViolation, sha256Text } from './types.ts'
12import type { ModelFactSources, ModelInfo, ModelReasoning } from './types.ts'
13
14export const MISTRAL_REASONING_URL =
15 'https://docs.mistral.ai/studio/conversations/reasoning.md'
16export const GROQ_REASONING_URL = 'https://console.groq.com/docs/reasoning.md'
17export const COHERE_REASONING_URL = 'https://docs.cohere.com/docs/reasoning.md'
18export const BYTEPLUS_REASONING_URL =
19 'https://docs.byteplus.com/en/docs/ModelArk/1449737'
20
21/** The thinking page names no mode for this id. */
22export const REASONING_SOURCE_SILENT = 'silent'
23
24/**
25 * The write gate for `reasoning`. A listed object that breaks the shape is
26 * not stored: the row keeps the value and source it had (null on a new row),
27 * the poll goes on, and an `ingest_failed` event names the model and reason.
28 */
29export function keepValidReasoning(
30 providerId: string,
31 info: ModelInfo,
32 prior?: { reasoning: unknown; factSources: unknown },
33): ModelInfo {
34 if (info.reasoning == null) return info
35 const reason = reasoningViolation(info.reasoning)
36 if (reason === null) return info
37 noteIngest(
38 ingestFailedEvent(
39 'models-poll',
40 providerId,
41 `${info.rawId}: reasoning not stored: ${reason}`,
42 ),
43 )
44 const { reasoning: _refused, ...sources } = info.factSources ?? {}
45 const priorSource = (prior?.factSources as ModelFactSources | null)?.reasoning
46 const factSources = priorSource
47 ? { ...sources, reasoning: priorSource }
48 : sources
49 return {
50 ...info,
51 reasoning: (prior?.reasoning ?? null) as ModelReasoning | null,
52 factSources: emptySources(factSources) ? undefined : factSources,
53 }
54}
55
56export function listsReasoning(capabilities: unknown): boolean {
57 return Array.isArray(capabilities) && capabilities.includes('reasoning')
58}
59
60function docsReasoningSource(
61 sourceUrl: string,
62 sourceHash: string,
63 path: string,
64): ModelFactSources {
65 return {
66 reasoning: {
67 derivation: 'docs-derived',
68 sourceUrl,
69 sourceHash,
70 path,
71 },
72 }
73}
74
75/**
76 * Attach a parsed reasoning object, or a silent note when the row already
77 * has the reasoning capability and this source does not configure it.
78 */
79export function reasoningFactsFor(
80 rawId: string,
81 byId: Record<string, ModelReasoning>,
82 source: { url: string; hash: string },
83 capability: boolean,
84): Partial<ModelInfo> {
85 const reasoning = byId[rawId]
86 if (reasoning) {
87 return {
88 reasoning,
89 factSources: docsReasoningSource(source.url, source.hash, 'reasoning'),
90 }
91 }
92 if (!capability) return {}
93 return {
94 factSources: docsReasoningSource(
95 source.url,
96 source.hash,
97 REASONING_SOURCE_SILENT,
98 ),
99 }
100}
101
102/** Merge docs patches without letting one factSources bag replace another. */
103export function overlayModelFacts(
104 model: ModelInfo,
105 ...patches: Array<Partial<ModelInfo>>
106): ModelInfo {
107 let next: ModelInfo = { ...model }
108 const factSources: ModelFactSources = { ...(model.factSources ?? {}) }
109 for (const patch of patches) {
110 const { factSources: more, absent, ...rest } = patch
111 next = { ...next, ...rest }
112 // Each patch may mark its own facts absent; one must not erase another's.
113 if (absent) next.absent = { ...next.absent, ...absent }
114 if (more) Object.assign(factSources, more)
115 }
116 if (emptySources(factSources)) {
117 const { factSources: _drop, ...bare } = next
118 return bare
119 }
120 return { ...next, factSources }
121}
122
123/**
124 * OpenRouter `GET /api/v1/models` reasoning object. `supported_efforts`
125 * names the effort mode. `null` accepts gateway effort names supplied from
126 * normative host docs; mandatory rows reject the documented disable value.
127 * Without gateway docs, null keeps its effort names unknown. `supports_max_tokens` is a budget
128 * only when the listing does not speak about efforts. No reasoning object,
129 * or a mandatory flag that is not a boolean, stays null.
130 */
131export function openRouterReasoning(
132 row: {
133 reasoning?: {
134 supported_efforts?: Array<string | null> | null
135 mandatory?: unknown
136 supports_max_tokens?: unknown
137 } | null
138 },
139 gatewayEfforts?: ReadonlyArray<string>,
140 gatewayToggle?: boolean,
141): ModelReasoning | null {
142 const reasoning = row.reasoning
143 if (!reasoning || typeof reasoning !== 'object') return null
144 for (const key of ['mandatory', 'supports_max_tokens'] as const) {
145 const value = reasoning[key]
146 if (value != null && typeof value !== 'boolean')
147 throw new Error(`openrouter: malformed native ${key}`)
148 }
149 const declared = reasoning.supported_efforts
150 if (
151 declared != null &&
152 (!Array.isArray(declared) ||
153 declared.some(
154 (value) =>
155 value != null && (typeof value !== 'string' || !value.length),
156 ))
157 )
158 throw new Error('openrouter: malformed native supported_efforts')
159 if (typeof reasoning.mandatory !== 'boolean') return null
160 const mandatory = reasoning.mandatory
161 if (Array.isArray(reasoning.supported_efforts)) {
162 const efforts = reasoning.supported_efforts.filter(
163 (effort): effort is string =>
164 typeof effort === 'string' && effort.length > 0,
165 )
166 if (efforts.length === 0) return null
167 return { mode: 'effort', mandatory, efforts }
168 }
169 if (reasoning.supported_efforts === null) {
170 return {
171 mode: 'effort',
172 mandatory,
173 ...(gatewayEfforts
174 ? {
175 efforts: gatewayEfforts.filter(
176 (value) => !mandatory || value !== 'none',
177 ),
178 }
179 : {}),
180 }
181 }
182 if (reasoning.supports_max_tokens === true) {
183 return { mode: 'budget', mandatory }
184 }
185 if (gatewayToggle === true && mandatory === false)
186 return { mode: 'toggle', mandatory: false }
187 return null
188}
189
190/**
191 * Mistral's reasoning guide. Bullets that name `reasoning_effort` are effort
192 * mode. Effort names are the `reasoning_effort = "…"` values, unless the
193 * same bullet publishes its own list. Native "always on, no parameter"
194 * prose names no mode and contributes nothing.
195 */
196export function parseMistralReasoning(
197 markdown: string,
198): Map<string, ModelReasoning> {
199 const out = new Map<string, ModelReasoning>()
200 const prose = markdown.replace(/```[\s\S]*?```/g, '')
201 const preludeEnd = prose.search(/handling thinking chunks/i)
202 const prelude = preludeEnd < 0 ? prose : prose.slice(0, preludeEnd)
203 const bullet =
204 /`([a-z0-9][a-z0-9.-]*)`:\s*Supports adjustable reasoning via the `reasoning_effort`/g
205 // `reasoning_effort = "none"` omits the thinking chunk for Mistral models.
206 // Example assignments are still not an allowlist. A model's own value list
207 // below replaces this.
208 const noneOmits =
209 /reasoning_effort\s*=\s*"none"[\s\S]{0,240}thinking chunk (?:is )?omitted/i.test(
210 prelude,
211 )
212 for (const match of prelude.matchAll(bullet)) {
213 const id = match[1]
214 if (!id) continue
215 out.set(id, { mode: 'effort', mandatory: noneOmits ? false : null })
216 }
217 // The scoped model list is followed by normative parameter values. These
218 // are not code examples; an explicit model-specific list overrides them.
219 const valueSection = prelude.split(
220 'The `reasoning_effort` parameter controls',
221 )[1]
222 const levels = [
223 ...(valueSection?.matchAll(/^- `reasoning_effort\s*=\s*"([a-z]+)"`:/gm) ??
224 []),
225 ].flatMap((match) => (match[1] ? [match[1]] : []))
226 if (levels.length) {
227 for (const id of out.keys())
228 out.set(id, {
229 mode: 'effort',
230 mandatory: noneOmits && levels.includes('none') ? false : null,
231 efforts: levels,
232 })
233 }
234 const ownList =
235 /`([a-z0-9][a-z0-9.-]*)`:[^\n]{0,240}?Supported values are ([^\n.]+)/g
236 for (const match of prelude.matchAll(ownList)) {
237 const id = match[1]
238 if (!id || !out.has(id)) continue
239 const efforts = [...(match[2] ?? '').matchAll(/`([a-z]+)`/g)].flatMap(
240 (found) => (found[1] ? [found[1]] : []),
241 )
242 if (efforts.length === 0) continue
243 const ownNote = prelude
244 .split(/\n\s*\n/)
245 .find(
246 (para) =>
247 para.split('\n').some((line) => line.startsWith('`' + id + '` ')) &&
248 /always|cannot/i.test(para),
249 )
250 const alwaysThinking =
251 !!ownNote &&
252 /(?:reasoning|thinking)\s+(?:is\s+)?(?:always on|cannot be disabled|cannot be turned off)|is always returned[^.\n]*\(thinking\s*\+\s*text\)/i.test(
253 ownNote,
254 )
255 out.set(id, {
256 mode: 'effort',
257 mandatory: alwaysThinking
258 ? true
259 : noneOmits && efforts.includes('none')
260 ? false
261 : null,
262 efforts,
263 })
264 }
265 return out
266}
267
268interface NamedModel {
269 id: string
270 label: string
271}
272
273function headingBlocks(
274 markdown: string,
275): Array<{ title: string; body: string }> {
276 return markdown.split(/\n(?=#{2,3} )/).flatMap((part) => {
277 const match = part.match(/^#{2,3} (.+)$/m)
278 const title = (match?.[1] ?? '')
279 .replace(/^\s*\[([^\]]+)\]\([^)]*\)\s*/, '$1')
280 .replace(/\s*\([^)]*\)\s*$/, '')
281 .trim()
282 if (!match || title.length === 0) return []
283 return [{ title, body: part.slice(part.indexOf('\n') + 1) }]
284 })
285}
286
287function linkLabel(cell: string): string {
288 return cell
289 .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
290 .replace(/\\/g, '')
291 .trim()
292}
293
294/** Groq reasoning page: per-model `reasoning_effort` tables. Ids the page lists as reasoning models but never gives options stay absent. */
295export function parseGroqReasoning(
296 markdown: string,
297): Map<string, ModelReasoning> {
298 const models: Array<NamedModel> = []
299 const effortsById = new Map<string, Array<string>>()
300 const conflicts = new Set<string>()
301 for (const block of headingBlocks(markdown)) {
302 if (block.title === 'Supported Models') {
303 for (const row of markdownTableRows(block.body)) {
304 const id = (row[0] ?? '').trim()
305 if (!/^[A-Za-z0-9][A-Za-z0-9./_-]*$/.test(id) || id === 'Model ID') {
306 continue
307 }
308 models.push({ id, label: linkLabel(row[1] ?? '') })
309 }
310 continue
311 }
312 if (!block.title.startsWith('Options for Reasoning Effort')) continue
313 const efforts: Array<string> = []
314 for (const row of markdownTableRows(block.body)) {
315 const name = (row[0] ?? '').replace(/[`\\]/g, '').trim()
316 if (/^[a-z]+$/.test(name) && !efforts.includes(name)) efforts.push(name)
317 }
318 if (efforts.length === 0) continue
319 const norm = (value: string) =>
320 value.toLowerCase().replace(/[^a-z0-9]/g, '')
321 const sectionNorm = norm(block.body)
322 const linked = [...block.body.matchAll(/\[([^\]]+)\]/g)].map((match) =>
323 norm(match[1] ?? ''),
324 )
325 for (const model of models) {
326 const labelNorm = norm(model.label)
327 const named =
328 block.body.includes(model.id) ||
329 (labelNorm.length > 0 && sectionNorm.includes(labelNorm)) ||
330 linked.some((name) => name.length >= 6 && labelNorm.includes(name))
331 if (!named) continue
332 const prior = effortsById.get(model.id)
333 if (prior && prior.join('\0') !== efforts.join('\0')) {
334 conflicts.add(model.id)
335 continue
336 }
337 effortsById.set(model.id, efforts)
338 }
339 }
340 const out = new Map<string, ModelReasoning>()
341 for (const [id, efforts] of effortsById) {
342 if (conflicts.has(id)) continue
343 out.set(id, {
344 mode: 'effort',
345 mandatory: !efforts.includes('none'),
346 efforts,
347 })
348 }
349 return out
350}
351
352/**
353 * Cohere's reasoning guide. `thinking.token_budget` is budget mode, and
354 * thinking can be turned off, so it is not mandatory. No effort names are
355 * published. A page that does not state `token_budget` configures nothing.
356 *
357 * The guide names one model in its examples but says "Cohere's reasoning
358 * models are hybrid", enabled or disabled. While it says so, the same
359 * configuration is kept under `COHERE_ANY_REASONING` for the other models
360 * the listing flags `reasoning` (Command A+, North Mini Code).
361 */
362export const COHERE_ANY_REASONING = '*'
363
364export function parseCohereReasoning(
365 markdown: string,
366): Map<string, ModelReasoning> {
367 const out = new Map<string, ModelReasoning>()
368 if (!/token_budget/.test(markdown)) return out
369 if (!/"type":\s*"disabled"|turns off thinking/i.test(markdown)) return out
370 const ids = new Set<string>()
371 for (const match of markdown.matchAll(
372 /`([a-z0-9][a-z0-9._-]*-\d{2}-\d{4})`/g,
373 )) {
374 if (match[1]) ids.add(match[1])
375 }
376 for (const match of markdown.matchAll(/model="([^"]+)"/g)) {
377 if (match[1]) ids.add(match[1])
378 }
379 if (
380 /Cohere's reasoning models are \*hybrid\*, meaning reasoning can be enabled \([^)]*\) or disabled/.test(
381 markdown,
382 )
383 ) {
384 ids.add(COHERE_ANY_REASONING)
385 }
386 for (const id of ids) {
387 out.set(id, { mode: 'budget', mandatory: false })
388 }
389 return out
390}
391
392/** Pull the chain-of-thought section out of the docs HTML or a markdown fixture. */
393export function byteplusReasoningSection(body: string): string {
394 const text = body
395 .replace(/\\u003C/gi, '<')
396 .replace(/\\u003E/gi, '>')
397 .replace(/\\u0026/gi, '&')
398 .replace(/\\u002F/gi, '/')
399 .replace(/\\n/g, '\n')
400 .replace(/\\-/g, '-')
401 .replace(/<br\s*\/?>/gi, ' ')
402 .replace(/<[^>]+>/g, '')
403 const headed = text.search(/(?:^|\n)## Adjust chain-of-thought length/i)
404 const start =
405 headed >= 0 ? headed : text.search(/adjust chain-of-thought length/i)
406 if (start < 0) return ''
407 const rest = text.slice(start)
408 const end = rest.search(/\n## (?!Adjust)/)
409 return end < 0 ? rest : rest.slice(0, end)
410}
411
412/**
413 * Doc-center delta: each visible string is an `"insert":"..."` fragment.
414 * Effort names are the published value list. Model ids are the dated ids
415 * after that list. Markdown fixtures fall through to the table parser.
416 */
417function parseByteplusInserts(section: string): Map<string, ModelReasoning> {
418 const out = new Map<string, ModelReasoning>()
419 const inserts = [
420 ...section.matchAll(/\\"insert\\":\\"([^\\"]*)\\"/g),
421 ].flatMap((match) => {
422 const text = (match[1] ?? '').replace(/\\n/g, '').trim()
423 return text.length > 0 ? [text] : []
424 })
425 const efforts: Array<string> = []
426 const ids: Array<string> = []
427 let phase: 'seek' | 'values' | 'models' = 'seek'
428 for (const insert of inserts) {
429 if (phase === 'seek') {
430 if (insert === 'reasoning_effort' || insert === 'reasoning.effort') {
431 phase = 'values'
432 }
433 continue
434 }
435 if (phase === 'values') {
436 if (/the table below|^supported models$/i.test(insert)) {
437 phase = 'models'
438 continue
439 }
440 if (
441 /^(none|minimal|low|medium|high|xhigh|max)$/.test(insert) &&
442 !efforts.includes(insert)
443 ) {
444 efforts.push(insert)
445 }
446 continue
447 }
448 if (
449 /^[a-z0-9]+(?:-[a-z0-9]+)*-\d{4,}$/.test(insert) &&
450 !ids.includes(insert)
451 ) {
452 ids.push(insert)
453 }
454 }
455 if (efforts.length === 0 || ids.length === 0) return out
456 const reasoning: ModelReasoning = {
457 mode: 'effort',
458 mandatory: !efforts.includes('none'),
459 efforts,
460 }
461 for (const id of ids) out.set(id, reasoning)
462 return out
463}
464
465export function parseByteplusReasoning(
466 body: string,
467): Map<string, ModelReasoning> {
468 const section = byteplusReasoningSection(body)
469 const out = new Map<string, ModelReasoning>()
470 if (!section) return out
471 const inserted = parseByteplusInserts(section)
472 if (inserted.size > 0) return inserted
473 const [values = ''] = section.split(/\| ?Supported models/i)
474 const efforts: Array<string> = []
475 for (const line of values.split('\n')) {
476 const name = line.match(/^\*\s*`([a-z]+)`/)?.[1]
477 if (name && !efforts.includes(name)) efforts.push(name)
478 }
479 if (efforts.length === 0) return out
480 const reasoning: ModelReasoning = {
481 mode: 'effort',
482 mandatory: !efforts.includes('none'),
483 efforts,
484 }
485 let inTable = false
486 for (const row of markdownTableRows(section)) {
487 const head = (row[0] ?? '').replace(/\\/g, '').trim()
488 if (/^supported models$/i.test(head)) {
489 inTable = true
490 continue
491 }
492 if (!inTable) continue
493 if (/^(api|example)$/i.test(head)) break
494 for (const match of head.matchAll(/`([a-z0-9]+(?:-[a-z0-9]+)*-\d{4,})`/g)) {
495 const id = match[1]
496 if (id) out.set(id, reasoning)
497 }
498 }
499 return out
500}
501
502async function loadReasoningMap(
503 kv: KVNamespace | undefined,
504 url: string,
505 source: string,
506 parse: (body: string) => Map<string, ModelReasoning>,
507 fetchBody: (url: string) => Promise<string> = fetchText,
508): Promise<{
509 byId: Record<string, ModelReasoning>
510 hash: string
511 url: string
512}> {
513 return cachedDocs(kv, url, async () => {
514 const body = await fetchBody(url)
515 const parsed = parse(body)
516 assertParsed(parsed, source)
517 return { byId: Object.fromEntries(parsed), hash: await sha256Text(body) }
518 }).then((doc) => ({ ...doc, url }))
519}
520
521function lookup(doc: {
522 byId: Record<string, ModelReasoning>
523 hash: string
524 url: string
525}): (rawId: string, capability: boolean) => Partial<ModelInfo> {
526 return (rawId, capability) =>
527 reasoningFactsFor(rawId, doc.byId, doc, capability)
528}
529
530export async function mistralModelReasoning(kv?: KVNamespace) {
531 const doc = await loadReasoningMap(
532 kv,
533 MISTRAL_REASONING_URL,
534 'mistral reasoning page',
535 parseMistralReasoning,
536 )
537 return lookup(doc)
538}
539
540export async function groqModelReasoning(kv?: KVNamespace) {
541 const doc = await loadReasoningMap(
542 kv,
543 GROQ_REASONING_URL,
544 'groq reasoning page',
545 parseGroqReasoning,
546 )
547 return lookup(doc)
548}
549
550export async function cohereModelReasoning(kv?: KVNamespace) {
551 const doc = await loadReasoningMap(
552 kv,
553 COHERE_REASONING_URL,
554 'cohere reasoning page',
555 parseCohereReasoning,
556 )
557 const any = COHERE_ANY_REASONING in doc.byId
558 return (rawId: string, capability: boolean): Partial<ModelInfo> =>
559 reasoningFactsFor(
560 capability && any && !(rawId in doc.byId) ? COHERE_ANY_REASONING : rawId,
561 doc.byId,
562 doc,
563 capability,
564 )
565}
566
567export async function byteplusModelReasoning(kv?: KVNamespace) {
568 const doc = await loadReasoningMap(
569 kv,
570 BYTEPLUS_REASONING_URL,
571 'byteplus reasoning page',
572 parseByteplusReasoning,
573 fetchByteplusDoc,
574 )
575 return lookup(doc)
576}