Open History to see the last commit
1/**
2 * Provider aliases callers send in place of the dated catalog id (issue #112).
3 * Anthropic publishes the alias on the models overview and each model page.
4 * An alias is attached only when that page names it and the dated id is in
5 * the provider listing. Retired ids, and any candidate the listing omits,
6 * stay absent.
7 */
8import type { ModelInfo } from './types.ts'
9import { fetchText, sha256Text } from './types.ts'
10import {
11 assertParsed,
12 cachedDocs,
13 mapConcurrent,
14 markdownSection,
15 markdownTableRows,
16} from './model-facts.ts'
17
18export const ANTHROPIC_MODELS_OVERVIEW_URL =
19 'https://platform.claude.com/docs/en/about-claude/models/overview.md'
20
21const MODEL_PAGE =
22 /https:\/\/platform\.claude\.com\/docs\/en\/models\/([a-z0-9-]+)\/overview(?:\.md)?/g
23
24/**
25 * models.dev ids from issue #112 that are not Anthropic aliases. They are
26 * catalog rows only when the provider listing still contains that exact id.
27 */
28export const UNDOCUMENTED_CANDIDATE_IDS = [
29 'mistral-large-2411',
30 'mistral-medium-2508',
31 'mistral-small-2506',
32 'devstral-latest',
33 'devstral-2512',
34 'pixtral-large-latest',
35 'open-mistral-nemo',
36 'llama-3.3-70b-versatile',
37 'llama-3.1-8b-instant',
38 'groq/compound',
39 'groq/compound-mini',
40 'gpt-5.3-codex-spark',
41] as const
42
43/** Candidates that appear verbatim in the provider's served model listing. */
44export function candidatesStillListed(
45 candidates: readonly string[],
46 listedRawIds: ReadonlySet<string>,
47): Array<string> {
48 return candidates.filter((id) => listedRawIds.has(id))
49}
50
51function plainLabel(cell: string): string {
52 return cell
53 .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
54 .replace(/`/g, '')
55 .trim()
56 .toLowerCase()
57}
58
59function codeId(cell: string | undefined): string | null {
60 const id = cell?.match(/`([^`\s]+)`/)?.[1]
61 return id && id.length > 0 ? id : null
62}
63
64/** `claude-opus-4-5-20251101` → `opus-4-5`. Dateless ids return null. */
65export function claudeModelSlug(apiModelName: string): string | null {
66 const dated = apiModelName.match(/^claude-(.+)-(\d{8})$/)
67 return dated?.[1] ?? null
68}
69
70/**
71 * Model-page URLs from the overview's own links, plus a page per dated id
72 * the deprecations table (linked from the overview) still calls active,
73 * legacy, or deprecated. Retired rows are not fetched.
74 */
75export function claudeModelPageUrls(
76 overviewMarkdown: string,
77 deprecationsMarkdown: string,
78): Array<string> {
79 const urls = new Set<string>()
80 for (const match of overviewMarkdown.matchAll(MODEL_PAGE)) {
81 const slug = match[1]
82 if (slug) {
83 urls.add(`https://platform.claude.com/docs/en/models/${slug}/overview.md`)
84 }
85 }
86 for (const cells of markdownTableRows(
87 markdownSection(deprecationsMarkdown, 'Model status'),
88 )) {
89 const name = plainLabel(cells[0] ?? '')
90 const state = plainLabel(cells[1] ?? '')
91 if (state === 'retired' || state === 'current state') continue
92 const slug = claudeModelSlug(name)
93 if (!slug) continue
94 urls.add(`https://platform.claude.com/docs/en/models/${slug}/overview.md`)
95 }
96 return [...urls]
97}
98
99/** Wide comparison table: "Claude API ID" row vs "Claude API alias" row. */
100export function parseOverviewAliases(markdown: string): Map<string, string> {
101 const out = new Map<string, string>()
102 let ids: Array<string | null> | null = null
103 let aliases: Array<string | null> | null = null
104 for (const cells of markdownTableRows(markdown)) {
105 const label = plainLabel(cells[0] ?? '')
106 if (label === 'claude api id')
107 ids = cells.slice(1).map((cell) => codeId(cell))
108 if (label === 'claude api alias') {
109 aliases = cells.slice(1).map((cell) => codeId(cell))
110 }
111 }
112 if (!ids || !aliases) return out
113 for (let i = 0; i < Math.min(ids.length, aliases.length); i++) {
114 const canonical = ids[i]
115 const alias = aliases[i]
116 if (!canonical || !alias || alias === canonical) continue
117 out.set(alias, canonical)
118 }
119 return out
120}
121
122/** Two-column Model IDs table. Retired pages contribute nothing. */
123export function parseModelAliasPage(markdown: string): {
124 alias: string
125 canonical: string
126} | null {
127 let canonical: string | null = null
128 let alias: string | null = null
129 let retired = false
130 for (const cells of markdownTableRows(markdown)) {
131 if (cells.length < 2) continue
132 const label = plainLabel(cells[0] ?? '')
133 const value = cells[1] ?? ''
134 if (label === 'status' && plainLabel(value).startsWith('retired')) {
135 retired = true
136 }
137 if (label === 'claude api') canonical = codeId(value)
138 if (label === 'claude api alias') alias = codeId(value)
139 }
140 if (retired || !canonical || !alias || alias === canonical) return null
141 return { alias, canonical }
142}
143
144/** Overview rows first; a model page replaces the overview for that alias. */
145export function parseClaudeAliases(pages: Array<string>): Map<string, string> {
146 const out = new Map<string, string>()
147 const pagePairs: Array<{ alias: string; canonical: string }> = []
148 for (const page of pages) {
149 const pair = parseModelAliasPage(page)
150 if (pair) pagePairs.push(pair)
151 else {
152 for (const [alias, canonical] of parseOverviewAliases(page)) {
153 out.set(alias, canonical)
154 }
155 }
156 }
157 for (const pair of pagePairs) out.set(pair.alias, pair.canonical)
158 return out
159}
160
161/**
162 * Copy documented aliases onto the dated listing row. An alias whose dated
163 * id is not listed (retired, or never served) is dropped. An alias that is
164 * itself a listed id is left as its own row.
165 */
166export function applyDocumentedAliases<T extends ModelInfo>(
167 models: Array<T>,
168 aliasToCanonical: ReadonlyMap<string, string>,
169): Array<T> {
170 const listed = new Set(models.map((model) => model.rawId))
171 const byCanonical = new Map<string, Array<string>>()
172 for (const [alias, canonical] of aliasToCanonical) {
173 if (alias === canonical) continue
174 if (!listed.has(canonical) || listed.has(alias)) continue
175 const found = byCanonical.get(canonical) ?? []
176 found.push(alias)
177 byCanonical.set(canonical, found)
178 }
179 return models.map((model) => {
180 const aliases = byCanonical.get(model.rawId)
181 if (!aliases || aliases.length === 0) return model
182 return { ...model, aliases: [...aliases].sort() }
183 })
184}
185
186/**
187 * Resolve a caller id to the catalog row. A listed raw id wins. An alias
188 * resolves only when exactly one listed row carries it. Anything else,
189 * including a retired id, is null.
190 */
191/** JSON column → sorted alias ids, or null when the row has none. */
192export function storedAliases(value: unknown): Array<string> | null {
193 if (!Array.isArray(value)) return null
194 const ids = value.filter((item): item is string => typeof item === 'string')
195 return ids.length > 0 ? [...ids].sort() : null
196}
197
198export function resolveAlias<
199 T extends { rawId: string; aliases?: readonly string[] | null },
200>(requestedId: string, models: readonly T[]): T | null {
201 const direct = models.find((model) => model.rawId === requestedId)
202 if (direct) return direct
203 const via = models.filter((model) =>
204 (model.aliases ?? []).includes(requestedId),
205 )
206 return via.length === 1 ? (via[0] ?? null) : null
207}
208
209function deprecationsUrl(overview: string): string | null {
210 const match = overview.match(
211 /https:\/\/platform\.claude\.com\/docs\/en\/about-claude\/model-deprecations(?:\.md)?/,
212 )
213 if (!match) return null
214 return match[0].endsWith('.md') ? match[0] : `${match[0]}.md`
215}
216
217async function fetchOptional(url: string): Promise<string | null> {
218 const response = await fetch(url)
219 if (response.status === 404) return null
220 if (!response.ok) {
221 throw new Error(
222 `fetch failed: ${url} → ${String(response.status)} ${response.statusText}`,
223 )
224 }
225 return response.text()
226}
227
228/** Alias → dated id, from the models overview and the pages it points at. */
229export async function anthropicAliasMap(
230 kv?: KVNamespace,
231 cached: typeof cachedDocs = cachedDocs,
232): Promise<Map<string, string>> {
233 const doc = await cached(kv, ANTHROPIC_MODELS_OVERVIEW_URL, async () => {
234 const overview = await fetchText(ANTHROPIC_MODELS_OVERVIEW_URL)
235 const depUrl = deprecationsUrl(overview)
236 const deprecations = depUrl ? await fetchText(depUrl) : ''
237 const urls = claudeModelPageUrls(overview, deprecations)
238 const fetched = await mapConcurrent(urls, 4, fetchOptional)
239 const pages = fetched.filter((page): page is string => page !== null)
240 const aliases = parseClaudeAliases([overview, ...pages])
241 assertParsed(aliases, 'anthropic models overview')
242 return {
243 pairs: [...aliases.entries()],
244 hash: await sha256Text(overview),
245 }
246 })
247 return new Map(doc.pairs)
248}