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

provider-aliases.ts

262 lines8.7 KB

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