Open History to see the last commit
1/** Controls from AWS-hosted guides, scoped by their own model tables. */
2import { nativeReasoningCapability } from './native-host-reasoning.ts'
3import { tagDocsFacts } from './fact-sources.ts'
4import {
5 markdownSection,
6 markdownTableRows,
7 tryDocs,
8 unavailable,
9} from './model-facts.ts'
10import type { DocsRun } from './model-facts.ts'
11import { fetchText, sha256Text } from './types.ts'
12import type { ModelInfo, ModelReasoning } from './types.ts'
13
14const DOCS = 'https://docs.aws.amazon.com/bedrock/latest/userguide/'
15export const BEDROCK_EXTENDED_THINKING_URL = `${DOCS}claude-messages-extended-thinking.md`
16export const BEDROCK_NOVA_THINKING_URL =
17 'https://docs.aws.amazon.com/nova/latest/nova2-userguide/using-converse-api.md'
18export const BEDROCK_ADAPTIVE_THINKING_URL = `${DOCS}claude-messages-adaptive-thinking.md`
19export interface BedrockThinkingGuide {
20 controls: Record<string, ModelReasoning>
21 namedControls?: Record<string, ModelReasoning>
22 runtimeNamedControls?: Record<string, ModelReasoning>
23 url: string
24 hash: string
25}
26export interface BedrockCardOwnedGroup {
27 /** Only base IDs and profile IDs explicitly declared by this one card. */
28 modelName: string | null
29 runtimeRowIds?: Array<string>
30 baseIds: Array<string>
31 rowIds: Array<string>
32}
33
34const prose = (text: string) => text.replace(/```[\s\S]*?```/g, '')
35const rows = (text: string) => markdownTableRows(text.replace(/[ \t]+$/gm, ''))
36const clean = (text: string) => text.replace(/[*`]/g, '').trim()
37const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
38
39function models(text: string): Map<string, string> {
40 const beforeExamples = text.split(/^## /m)[0] ?? ''
41 const table = rows(beforeExamples)
42 const header = table[0]
43 if (header?.[0] !== 'Model' || header[1] !== 'Model ID') {
44 throw new Error(
45 'amazon-bedrock thinking guide: missing supported model table',
46 )
47 }
48 const result = new Map<string, string>()
49 for (const row of table.slice(1)) {
50 const name = row[0]?.trim()
51 const id = row[1]?.match(/^`(anthropic\.[a-z0-9.:-]+)`$/)?.[1]
52 if (!name || !id || row.length !== 2 || result.has(name)) {
53 throw new Error(
54 'amazon-bedrock thinking guide: unreadable supported model row',
55 )
56 }
57 result.set(name, id)
58 }
59 if (!result.size)
60 throw new Error(
61 'amazon-bedrock thinking guide: empty supported model table',
62 )
63 return result
64}
65
66/** Whole names only: Opus 5 is never an abbreviation for Opus 5.5. */
67function namedIds(text: string, names: Map<string, string>): Array<string> {
68 const result: Array<string> = []
69 for (const [name, id] of names) {
70 if (
71 new RegExp(`(?<![\\w.])${escape(name)}(?![\\w]|\\.\\d|\\s+\\d)`).test(
72 clean(text),
73 )
74 )
75 result.push(id)
76 }
77 return result
78}
79
80export function parseBedrockExtendedThinking(
81 text: string,
82): Record<string, ModelReasoning> {
83 const native = prose(text)
84 const supported = models(native)
85 const use = markdownSection(native, 'How to use extended thinking')
86 if (
87 !/^To turn on extended thinking, add a `thinking` object/m.test(use) ||
88 !/^The `budget_tokens` parameter determines the maximum number of tokens/m.test(
89 use,
90 )
91 ) {
92 throw new Error(
93 'amazon-bedrock extended thinking: missing native budget declaration',
94 )
95 }
96 return Object.fromEntries(
97 [...supported.values()].map((id) => [
98 id,
99 { mode: 'budget', mandatory: null },
100 ]),
101 )
102}
103
104export function parseBedrockAdaptiveThinking(
105 text: string,
106): Record<string, ModelReasoning> {
107 const native = prose(text)
108 const supported = models(native)
109 const effortSection = markdownSection(
110 native,
111 'Adaptive thinking with the effort parameter',
112 )
113 const table = rows(effortSection)
114 if (
115 table[0]?.[0] !== 'Effort level' ||
116 table[0][1] !== 'Thinking behavior' ||
117 table.length < 2 ||
118 !/^Set `thinking.type` to `"adaptive"` in your API request:$/m.test(native)
119 ) {
120 throw new Error(
121 'amazon-bedrock adaptive thinking: missing native mode or effort table',
122 )
123 }
124 const result: Record<string, ModelReasoning> = Object.fromEntries(
125 [...supported.values()].map((id) => [
126 id,
127 { mode: 'adaptive', mandatory: null, efforts: [] },
128 ]),
129 )
130 const seen = new Set<string>()
131 for (const row of table.slice(1)) {
132 const level = row[0]?.match(/^([a-z][a-z0-9_-]*)(?: \(default\))?$/)?.[1]
133 const description = row[1]
134 if (!level || !description || row.length !== 2 || seen.has(level))
135 throw new Error('amazon-bedrock adaptive thinking: unreadable effort row')
136 seen.add(level)
137 const named = namedIds(description, supported)
138 let unmatched = clean(description)
139 for (const name of supported.keys())
140 unmatched = unmatched.replace(
141 new RegExp(`(?<![\\w.])${escape(name)}(?![\\w]|\\.\\d|\\s+\\d)`, 'g'),
142 '',
143 )
144 if (/\bClaude\s+[A-Z0-9]/.test(unmatched))
145 throw new Error(
146 `amazon-bedrock adaptive thinking: unsupported named scope for ${level}`,
147 )
148 const scoped = /\bonly\b|\bsupport(?:s)?\b|unsupported models/.test(
149 description,
150 )
151 if (scoped && !named.length)
152 throw new Error(
153 `amazon-bedrock adaptive thinking: unreadable model scope for ${level}`,
154 )
155 if (named.length && !scoped)
156 throw new Error(
157 `amazon-bedrock adaptive thinking: ambiguous model scope for ${level}`,
158 )
159 for (const id of scoped ? named : supported.values())
160 result[id]?.efforts?.push(level)
161 }
162 for (const control of Object.values(result)) {
163 if (!control.efforts?.length)
164 throw new Error(
165 'amazon-bedrock adaptive thinking: model has no published effort levels',
166 )
167 }
168 // Read operational declarations, never infer mandatory from defaults or enums.
169 const declare = (ids: Array<string>, mandatory: boolean) => {
170 for (const id of ids) {
171 const control = result[id]
172 if (!control) continue
173 if (control.mandatory != null && control.mandatory !== mandatory)
174 throw new Error(
175 `amazon-bedrock adaptive thinking: contradictory disabling evidence for ${id}`,
176 )
177 control.mandatory = mandatory
178 }
179 }
180 for (const line of native.split('\n')) {
181 if (
182 /disabled thinking[^\n]*are not supported on these models/.test(line) &&
183 !/\b(?:not|never|assume|example|hypothetical)\b/i.test(
184 line.split(/only\*? support adaptive thinking/)[0] ?? '',
185 )
186 ) {
187 declare(
188 namedIds(
189 line.split(/only\*? support adaptive thinking/)[0] ?? '',
190 supported,
191 ),
192 true,
193 )
194 }
195 if (
196 /supports adaptive and disabled thinking/.test(line) &&
197 !/\b(?:not|never|assume|example|hypothetical)\b/i.test(
198 line.split('supports adaptive and disabled thinking')[0] ?? '',
199 )
200 ) {
201 declare(
202 namedIds(
203 line.split('supports adaptive and disabled thinking')[0] ?? '',
204 supported,
205 ),
206 false,
207 )
208 }
209 if (
210 /also supports disabled thinking/.test(line) &&
211 !/\b(?:not|never|assume|example|hypothetical)\b/i.test(
212 line.split('also supports disabled thinking')[0] ?? '',
213 )
214 ) {
215 declare(
216 namedIds(
217 line.split('also supports disabled thinking')[0] ?? '',
218 supported,
219 ),
220 false,
221 )
222 }
223 }
224 const defaultBlock = native.match(
225 /^\*\*Adaptive thinking is on by default on (.+?)\.\*\*[^\n]*\n([^\n]+)/m,
226 )
227 if (
228 defaultBlock &&
229 /To turn thinking off entirely on these models[^\n]*disabled/.test(
230 defaultBlock[2] ?? '',
231 )
232 ) {
233 declare(namedIds(defaultBlock[1] ?? '', supported), false)
234 }
235 return result
236}
237
238/** The hosted guide names one model explicitly; examples cannot add scope. */
239export function parseBedrockNovaThinking(text: string): {
240 modelName: string
241 reasoning: ModelReasoning
242} {
243 const native = markdownSection(prose(text), 'Using reasoning')
244 const modelName = native.match(
245 /^([^\n]+) supports extended thinking for complex problem-solving\. Enable reasoning with `reasoningConfig`\.$/m,
246 )?.[1]
247 const type = native.match(/^\+ `type`: (.+)$/m)?.[1]
248 const declaration = native.match(
249 /^\+ `maxReasoningEffort`: (.+?)\. This is required when reasoning is enabled\./m,
250 )?.[1]
251 if (
252 !modelName ||
253 !type ||
254 !/^`enabled` or `disabled` \(default: `disabled`\)$/.test(type) ||
255 !declaration
256 ) {
257 throw new Error(
258 'amazon-bedrock Nova thinking: missing native model, type or effort declaration',
259 )
260 }
261 const efforts = [...declaration.matchAll(/`([a-z][a-z0-9_-]*)`/g)].map(
262 (match) => match[1] ?? '',
263 )
264 if (
265 !efforts.length ||
266 new Set(efforts).size !== efforts.length ||
267 declaration
268 .replace(/`[a-z][a-z0-9_-]*`/g, '')
269 .replace(/[,\s]|\bor\b/g, '') !== ''
270 ) {
271 throw new Error(
272 'amazon-bedrock Nova thinking: unreadable native effort list',
273 )
274 }
275 return { modelName, reasoning: { mode: 'effort', mandatory: false, efforts } }
276}
277
278/** A profile is enriched only through IDs explicitly declared on its card. */
279export function applyBedrockThinkingGuides(
280 catalog: Array<ModelInfo>,
281 groups: Array<BedrockCardOwnedGroup>,
282 guides: Array<BedrockThinkingGuide>,
283): Array<ModelInfo> {
284 const byRow = new Map<
285 string,
286 ModelReasoning & { url: string; hash: string }
287 >()
288 // Adaptive is AWS's recommended successor where its table overlaps extended.
289 for (const guide of guides) {
290 for (const group of groups) {
291 const named = group.modelName
292 ? (guide.namedControls ?? guide.runtimeNamedControls)?.[group.modelName]
293 : undefined
294 const byId = group.baseIds
295 .map((id) => guide.controls[id])
296 .filter((value): value is ModelReasoning => value != null)
297 const useName = !!guide.namedControls || (!byId.length && named != null)
298 const declarations = useName ? (named ? [named] : []) : byId
299 if (
300 useName &&
301 named &&
302 (!Array.isArray(group.runtimeRowIds) ||
303 !group.runtimeRowIds.every((id) => typeof id === 'string'))
304 )
305 throw new Error(
306 'amazon-bedrock thinking: unreadable native runtime card binding',
307 )
308 const targetIds = useName
309 ? (group.runtimeRowIds ?? []).filter((id) => group.rowIds.includes(id))
310 : group.rowIds
311 if (
312 useName &&
313 named &&
314 groups.filter((candidate) => candidate.modelName === group.modelName)
315 .length !== 1
316 )
317 throw new Error(
318 'amazon-bedrock thinking: ambiguous native card title binding',
319 )
320 if (!declarations.length) continue
321 if (
322 declarations.some(
323 (value) => JSON.stringify(value) !== JSON.stringify(declarations[0]),
324 )
325 )
326 throw new Error(
327 'amazon-bedrock thinking: contradictory controls for card-owned base IDs',
328 )
329 for (const id of targetIds)
330 byRow.set(id, { ...declarations[0]!, url: guide.url, hash: guide.hash })
331 }
332 }
333 return catalog.map((model) => {
334 const declaration = byRow.get(model.rawId)
335 if (!declaration) return model
336 const capSource = tagDocsFacts(
337 { capabilities: ['reasoning'] },
338 declaration.url,
339 declaration.hash,
340 ).capabilities!.reasoning!
341 const capable = nativeReasoningCapability(model, capSource)
342 const existing = model.reasoning
343 if (
344 existing?.mandatory != null &&
345 declaration.mandatory != null &&
346 existing.mandatory !== declaration.mandatory
347 )
348 throw new Error(
349 `amazon-bedrock thinking: native guide contradicts card mandatory for ${model.rawId}`,
350 )
351 // Do not add adaptive efforts to a budget/effort object from a card.
352 if (existing && existing.mode !== declaration.mode) return model
353 if (existing?.efforts?.length && existing.mandatory != null) return model
354 // Only cite the guide for a complete object when every retained value is
355 // independently supported by that guide. Otherwise leave the card intact.
356 if (
357 existing?.mandatory != null &&
358 existing.mandatory !== declaration.mandatory
359 )
360 return model
361 if (
362 existing?.efforts?.length &&
363 JSON.stringify([...existing.efforts].sort()) !==
364 JSON.stringify([...(declaration.efforts ?? [])].sort())
365 )
366 return model
367 const reasoning: ModelReasoning = {
368 mode: existing?.mode ?? declaration.mode,
369 mandatory: existing?.mandatory ?? declaration.mandatory,
370 ...(existing?.efforts?.length
371 ? { efforts: existing.efforts }
372 : declaration.efforts?.length
373 ? { efforts: declaration.efforts }
374 : {}),
375 }
376 if (JSON.stringify(reasoning) === JSON.stringify(existing)) return model
377 const reasonSource = tagDocsFacts(
378 { reasoning },
379 declaration.url,
380 declaration.hash,
381 )
382 return {
383 ...capable,
384 reasoning,
385 factSources: {
386 ...model.factSources,
387 ...reasonSource,
388 capabilities: {
389 ...capable.factSources?.capabilities,
390 reasoning: model.factSources?.capabilities?.reasoning ?? capSource,
391 },
392 },
393 }
394 })
395}
396
397export async function loadBedrockThinkingGuides(
398 catalog: Array<ModelInfo>,
399 groups: Array<BedrockCardOwnedGroup>,
400 run: DocsRun,
401 kv?: KVNamespace,
402): Promise<Array<ModelInfo>> {
403 const sources = [
404 {
405 url: BEDROCK_EXTENDED_THINKING_URL,
406 parse: (text: string) => {
407 const controls = parseBedrockExtendedThinking(text)
408 return {
409 controls,
410 runtimeNamedControls: Object.fromEntries(
411 [...models(prose(text))].map(([name, id]) => [name, controls[id]!]),
412 ),
413 }
414 },
415 },
416 {
417 url: BEDROCK_ADAPTIVE_THINKING_URL,
418 parse: (text: string) => {
419 const controls = parseBedrockAdaptiveThinking(text)
420 return {
421 controls,
422 runtimeNamedControls: Object.fromEntries(
423 [...models(prose(text))].map(([name, id]) => [name, controls[id]!]),
424 ),
425 }
426 },
427 },
428 {
429 url: BEDROCK_NOVA_THINKING_URL,
430 parse: (text: string) => {
431 const declaration = parseBedrockNovaThinking(text)
432 return {
433 controls: {},
434 namedControls: { [declaration.modelName]: declaration.reasoning },
435 }
436 },
437 },
438 ]
439 const guides = await Promise.all(
440 sources.map((source) =>
441 tryDocs(run, source.url, (cached) =>
442 cached(kv, source.url, async () => {
443 const text = await fetchText(source.url, {
444 signal: AbortSignal.timeout(20_000),
445 headers: {
446 'User-Agent':
447 'modelschemas (+https://modelschemas.openstory.workers.dev)',
448 },
449 })
450 return {
451 ...source.parse(text),
452 url: source.url,
453 hash: await sha256Text(text),
454 }
455 }),
456 ),
457 ),
458 )
459 let enriched = catalog
460 const failedSources = new Set(
461 sources
462 .filter((_, index) => guides[index] == null)
463 .map((source) => source.url),
464 )
465 // Apply adaptive first: it is the recommendation for overlapping IDs.
466 for (const index of [1, 0, 2]) {
467 const guide = guides[index]
468 if (!guide) continue
469 const result = await tryDocs(run, guide.url, async () =>
470 applyBedrockThinkingGuides(enriched, groups, [guide]),
471 )
472 if (result) enriched = result
473 else failedSources.add(guide.url)
474 }
475 if (!failedSources.size) return enriched
476 // A failed guide cannot clear missing controls that it may have supplied.
477 // Existing populated card facts remain intact; failures are public.
478 const claude = new Set(
479 groups
480 .filter((group) =>
481 group.baseIds.some((id) => id.startsWith('anthropic.')),
482 )
483 .flatMap((group) => group.rowIds),
484 )
485 const nova = new Set(
486 groups
487 .filter((group) =>
488 group.baseIds.some((id) => id.startsWith('amazon.nova-')),
489 )
490 .flatMap((group) => group.rowIds),
491 )
492 return enriched.map((model) => {
493 const missingMode = model.reasoning == null
494 const missingAdaptiveEfforts =
495 model.reasoning?.mode === 'adaptive' && !model.reasoning.efforts?.length
496 const missingNovaEfforts =
497 model.reasoning?.mode === 'effort' && !model.reasoning.efforts?.length
498 const affected =
499 (claude.has(model.rawId) &&
500 ((failedSources.has(BEDROCK_EXTENDED_THINKING_URL) && missingMode) ||
501 (failedSources.has(BEDROCK_ADAPTIVE_THINKING_URL) &&
502 (missingMode || missingAdaptiveEfforts)))) ||
503 (nova.has(model.rawId) &&
504 failedSources.has(BEDROCK_NOVA_THINKING_URL) &&
505 (missingMode || missingNovaEfforts))
506 return affected
507 ? {
508 ...model,
509 absent: { ...model.absent, ...unavailable('reasoning').absent },
510 }
511 : model
512 })
513}