Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ClaudeModelCatalog.ts

626 lines23.5 KB

1import {
2 type CustomModelSetting,
3 type ModelCapabilities,
4 type ModelSelection,
5 ProviderDriverKind,
6 type ServerProviderModel,
7 type ServerProviderUpdateRequiredModel,
8} from "@t3tools/contracts";
9import type { ModelInfo as ClaudeModelInfo } from "@anthropic-ai/claude-agent-sdk";
10import * as Option from "effect/Option";
11import {
12 getModelSelectionStringOptionValue,
13 getProviderOptionCurrentValue,
14 getProviderOptionDescriptors,
15 readCustomModelEntries,
16} from "@t3tools/shared/model";
17import { compareSemverVersions } from "@t3tools/shared/semver";
18​
19import {
20 type ClaudeCodeCompatibility,
21 type ClaudeCodeProfile,
22 decodeClaudeModelAdapter,
23 decodeClaudeProfileAdapter,
24} from "./ClaudeModelManifest.ts";
25import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
26import { BUNDLED_MODEL_MANIFEST, resolveProviderCatalog } from "./ModelManifest.ts";
27​
28const CLAUDE = ProviderDriverKind.make("claudeAgent");
29const EMPTY_CAPABILITIES: ModelCapabilities = { optionDescriptors: [] };
30​
31export interface ClaudeCatalogModel {
32 readonly model: ServerProviderModel;
33 readonly runtime: ClaudeCodeProfile;
34 readonly compatibility: ClaudeCodeCompatibility;
35 /** What to send Claude Code instead of the slug, from its own model list. */
36 readonly apiModel?: string;
38​
39export interface ClaudeModelCatalog {
40 readonly models: ReadonlyArray<ClaudeCatalogModel>;
42​
43function tryResolveClaudeModelCatalog(
44 resolved: ModelCatalog.ProviderCatalog | undefined,
45): ClaudeModelCatalog | null {
46 if (!resolved) return null;
47​
48 const models: Array<ClaudeCatalogModel> = [];
49 for (const entry of resolved.models) {
50 const profile = decodeClaudeProfileAdapter(entry.profileAdapter ?? {});
51 const adapter = decodeClaudeModelAdapter(entry.adapter ?? {});
52 if (Option.isNone(profile) || Option.isNone(adapter)) return null;
53 const model = ModelCatalog.catalogServerModel(resolved, entry);
54 models.push({
55 model: { ...model, capabilities: withUltracodeToggle(model.capabilities) },
56 runtime: profile.value.claudeCode ?? {},
57 compatibility: adapter.value.claudeCode ?? {},
58 });
59 }
60​
61 return {
62 models,
63 };
65​
66// The manifest keeps Ultracode as an effort level because released servers read it from main.
67export function withUltracodeToggle(
68 capabilities: ModelCapabilities | null,
69): ModelCapabilities | null {
70 const descriptors = capabilities?.optionDescriptors ?? [];
71 const effortIndex = descriptors.findIndex(
72 (descriptor) =>
73 descriptor.id === "effort" &&
74 descriptor.type === "select" &&
75 descriptor.options.some((option) => option.id === "ultracode"),
76 );
77 const effort = descriptors[effortIndex];
78 if (effort?.type !== "select") return capabilities;
79 const ultracodeByDefault =
80 (effort.currentValue ?? effort.options.find((option) => option.isDefault)?.id) === "ultracode";
81 const hasXhigh = effort.options.some((option) => option.id === "xhigh");
82 // Ultracode ran at xhigh, so a model that offered it keeps xhigh, and its default moves there.
83 const options = effort.options.flatMap(({ isDefault, ...option }) => {
84 if (option.id === "ultracode") {
85 return hasXhigh
86 ? []
87 : [{ id: "xhigh", label: "Extra High", ...(isDefault ? { isDefault } : {}) }];
88 }
89 if (ultracodeByDefault && option.id === "xhigh") return [{ ...option, isDefault: true }];
90 return [isDefault && !ultracodeByDefault ? { ...option, isDefault } : option];
91 });
92 return {
93 optionDescriptors: descriptors.toSpliced(
94 effortIndex,
95 1,
96 {
97 ...effort,
98 ...(effort.currentValue === "ultracode" ? { currentValue: "xhigh" } : {}),
99 options,
100 },
101 {
102 id: "ultracode",
103 label: "Ultracode",
104 type: "boolean",
105 ...(ultracodeByDefault ? { currentValue: true } : {}),
106 },
107 ),
108 };
110​
111/** Resolve the fallback on each read so its new-model badges can expire. */
112export function resolveClaudeModelCatalog(
113 catalog: ModelCatalog.ProviderCatalog | undefined,
114): ClaudeModelCatalog {
115 return (
116 tryResolveClaudeModelCatalog(catalog) ??
117 tryResolveClaudeModelCatalog(
118 resolveProviderCatalog(BUNDLED_MODEL_MANIFEST, CLAUDE) ?? undefined,
119 ) ?? {
120 models: [],
121 }
122 );
124​
125export const BUNDLED_CLAUDE_MODEL_CATALOG = resolveClaudeModelCatalog(undefined);
126​
127export function scopeClaudeModelCatalog(
128 catalog: ClaudeModelCatalog,
129 customModels: ReadonlyArray<CustomModelSetting>,
130): ClaudeModelCatalog {
131 const customEntries = readCustomModelEntries(customModels);
132 if (customEntries.length === 0) return catalog;
133 const customAliases = new Set(customEntries.map((entry) => entry.slug.toLowerCase()));
134​
135 const builtInModels = catalog.models.map((entry) => {
136 if (!entry.model.aliases?.some((alias) => customAliases.has(alias.toLowerCase()))) {
137 return entry;
138 }
139 return {
140 ...entry,
141 model: {
142 ...entry.model,
143 aliases: entry.model.aliases.filter((alias) => !customAliases.has(alias.toLowerCase())),
144 },
145 };
146 });
147 const builtInSlugs = new Set(builtInModels.map((entry) => entry.model.slug));
148 const customCatalogModels: Array<ClaudeCatalogModel> = [];
149 for (const entry of customEntries) {
150 if (!entry.capabilities || builtInSlugs.has(entry.slug)) continue;
151 customCatalogModels.push({
152 model: {
153 slug: entry.slug,
154 name: entry.name,
155 isCustom: true,
156 capabilities: withUltracodeToggle(entry.capabilities),
157 },
158 runtime: {},
159 compatibility: {},
160 });
161 }
162​
163 return { models: [...builtInModels, ...customCatalogModels] };
165​
166const CLAUDE_EFFORT_LABELS: Readonly<Record<string, string>> = {
167 low: "Low",
168 medium: "Medium",
169 high: "High",
170 xhigh: "Extra High",
171 max: "Max",
172};
173​
174function stripClaudeContextWindowSuffix(value: string): string {
175 return value.replace(/\[[^\]]*\]$/, "").trim();
177​
178export function claudeReportedModels(
179 catalog: ClaudeModelCatalog,
180 customModels: ReadonlyArray<CustomModelSetting>,
181 reported: ReadonlyArray<ClaudeModelInfo> | undefined,
182): { models: ReadonlyArray<ServerProviderModel>; hasNonCatalogModels: boolean } {
183 if (!reported?.length) return { models: [], hasNonCatalogModels: false };
184 const catalogIds = new Set(
185 catalog.models
186 .flatMap(({ model }) => [model.slug, ...(model.aliases ?? [])])
187 .map((id) => stripClaudeContextWindowSuffix(id).toLowerCase()),
188 );
189 const customIds = new Set(
190 readCustomModelEntries(customModels).map((entry) =>
191 stripClaudeContextWindowSuffix(entry.slug).toLowerCase(),
192 ),
193 );
194 const known = new Set([...catalogIds, ...customIds]);
195 let hasNonCatalogModels = false;
196 const models: Array<ServerProviderModel> = [];
197 for (const info of reported) {
198 const slug = info.value.trim();
199 // `default` is Claude Code's pointer at its own default model, not a model.
200 if (!slug || slug === "default") continue;
201 const valueId = stripClaudeContextWindowSuffix(slug).toLowerCase();
202 const resolvedId = stripClaudeContextWindowSuffix(info.resolvedModel ?? "").toLowerCase();
203 const ids = [valueId, resolvedId].filter((id) => id.length > 0);
204 const gatewayValue = !catalogIds.has(valueId);
205 // Claude Code can report family routes from environment settings even on a gateway cache miss.
206 const reportsGatewayModel = gatewayValue
207 ? customIds.has(valueId) || !catalogIds.has(resolvedId)
208 : resolvedId !== "" &&
209 (customIds.has(valueId) || customIds.has(resolvedId)) &&
210 !catalogIds.has(resolvedId) &&
211 !catalogIds.has(stripClaudeBackendDecoration(resolvedId));
212 if (reportsGatewayModel && !CLAUDE_CODE_FAMILY_ALIASES.has(valueId)) {
213 hasNonCatalogModels = true;
214 }
215 if (ids.some((id) => known.has(id))) continue;
216 for (const id of ids) known.add(id);
217 const efforts = info.supportsEffort ? (info.supportedEffortLevels ?? []) : [];
218 models.push({
219 slug,
220 name: info.displayName.trim() || slug,
221 isCustom: false,
222 capabilities: {
223 optionDescriptors: efforts.length
224 ? [
225 {
226 id: "effort",
227 label: "Reasoning",
228 type: "select",
229 // `default` is not an effort, so choosing it sends none and Claude Code picks.
230 options: [
231 { id: "default", label: "Default", isDefault: true },
232 ...efforts.map((id) => ({ id, label: CLAUDE_EFFORT_LABELS[id] ?? id })),
233 ],
234 },
235 ]
236 : [],
237 },
238 });
239 }
240 return { models, hasNonCatalogModels };
242​
243export function resolveClaudeCatalogModel(
244 catalog: ClaudeModelCatalog,
245 slugOrAlias: string | null | undefined,
246): ClaudeCatalogModel | undefined {
247 const value = slugOrAlias?.trim();
248 if (!value) return undefined;
249 return (
250 catalog.models.find((entry) => entry.model.slug === value) ??
251 catalog.models.find((entry) =>
252 entry.model.aliases?.some((alias) => alias.toLowerCase() === value.toLowerCase()),
253 )
254 );
256​
257// Cloud backends decorate first-party ids: Bedrock adds a region prefix and a
258// version ("us.anthropic.claude-opus-4-6-v1"), Vertex adds "@<date>".
259function stripClaudeBackendDecoration(wireModel: string): string {
260 return wireModel
261 .replace(/^(?:[a-z-]+\.)?anthropic\./, "")
262 .replace(/-v\d+(?::\d+)?$/, "")
263 .replace(/@[^@]*$/, "");
265​
266/**
267 * On Bedrock, Vertex and similar backends Claude Code does not accept the first-party slug: it
268 * either sends it verbatim or, when `availableModels` excludes it, silently runs the default
269 * model instead. Its model list names the id that does work, often a family alias that
270 * `ANTHROPIC_DEFAULT_*_MODEL` points at a backend id.
271 */
272export function withClaudeCodeModelRoutes(
273 catalog: ClaudeModelCatalog,
274 reportedModels: ReadonlyArray<Pick<ClaudeModelInfo, "value" | "resolvedModel">>,
275): ClaudeModelCatalog {
276 const apiModels = new Map<string, string>();
277 for (const reported of reportedModels) {
278 if (reported.value === "default") continue;
279 const wireModel = stripClaudeContextWindowSuffix(reported.resolvedModel ?? reported.value);
280 const firstPartyModel = stripClaudeBackendDecoration(wireModel);
281 if (firstPartyModel === wireModel) continue;
282 const entry = resolveClaudeCatalogModel(catalog, firstPartyModel);
283 if (!entry || apiModels.has(entry.model.slug)) continue;
284 apiModels.set(entry.model.slug, stripClaudeContextWindowSuffix(reported.value));
285 }
286 if (apiModels.size === 0) return catalog;
287 return {
288 models: catalog.models.map((entry) => {
289 const apiModel = apiModels.get(entry.model.slug);
290 return apiModel ? { ...entry, apiModel } : entry;
291 }),
292 };
294​
295export function resolveClaudeModelSlug(catalog: ClaudeModelCatalog, slugOrAlias: string): string {
296 return resolveClaudeCatalogModel(catalog, slugOrAlias)?.model.slug ?? slugOrAlias;
298​
299/** Claude reports dated IDs, such as `claude-opus-4-5-20251101`, that the catalog may not list. */
300export function resolveClaudeReportedModelSlug(
301 catalog: ClaudeModelCatalog,
302 reported: string,
303): string {
304 return (
305 (
306 resolveClaudeCatalogModel(catalog, reported) ??
307 resolveClaudeCatalogModel(catalog, reported.replace(/-\d{8}$/, ""))
308 )?.model.slug ?? reported
309 );
311​
312export function getClaudeCatalogModelCapabilities(
313 catalog: ClaudeModelCatalog,
314 slugOrAlias: string | null | undefined,
315): ModelCapabilities {
316 return resolveClaudeCatalogModel(catalog, slugOrAlias)?.model.capabilities ?? EMPTY_CAPABILITIES;
318​
319function isVersionSupported(
320 compatibility: ClaudeCodeCompatibility,
321 version: string | null | undefined,
322): boolean {
323 if (!compatibility.minVersion && !compatibility.maxVersionExclusive) return true;
324 if (!version) return false;
325 if (compatibility.minVersion && compareSemverVersions(version, compatibility.minVersion) < 0) {
326 return false;
327 }
328 return !(
329 compatibility.maxVersionExclusive &&
330 compareSemverVersions(version, compatibility.maxVersionExclusive) >= 0
331 );
333​
334export function resolveClaudeModelsForVersion(
335 catalog: ClaudeModelCatalog,
336 version: string | null | undefined,
337): ReadonlyArray<ClaudeCatalogModel["model"]> {
338 return catalog.models
339 .filter((entry) => isVersionSupported(entry.compatibility, version))
340 .map((entry) => entry.model);
342​
343export function resolveClaudeUpdateRequiredModels(
344 catalog: ClaudeModelCatalog,
345 version: string | null | undefined,
346): ReadonlyArray<ServerProviderUpdateRequiredModel> {
347 if (!version) return [];
348 return catalog.models.flatMap(({ model, compatibility }) => {
349 const minVersion = compatibility.minVersion;
350 if (model.isLegacy || !minVersion || compareSemverVersions(version, minVersion) >= 0) {
351 return [];
352 }
353 return [
354 {
355 slug: model.slug,
356 name: model.name,
357 ...(model.badge ? { badge: model.badge } : {}),
358 minVersion,
359 },
360 ];
361 });
363​
364// The two casks conflict, so moving to the faster channel means replacing the install.
365const HOMEBREW_STABLE_CASK_UPDATE_COMMAND = "brew upgrade --cask claude-code";
366const HOMEBREW_LATEST_CASK_SWITCH_COMMAND =
367 "brew uninstall --cask claude-code && brew install --cask claude-code@latest";
368​
369export function formatClaudeVersionUpgradeMessage(
370 catalog: ClaudeModelCatalog,
371 version: string | null,
372 channel?: { readonly latestVersion: string | null; readonly updateCommand: string | null },
373): string | undefined {
374 const unavailable = catalog.models
375 .filter(
376 (entry) =>
377 entry.compatibility.minVersion &&
378 (!version || compareSemverVersions(version, entry.compatibility.minVersion) < 0),
379 )
380 .toSorted((left, right) =>
381 compareSemverVersions(left.compatibility.minVersion!, right.compatibility.minVersion!),
382 )[0];
383 if (!unavailable?.compatibility.minVersion) return undefined;
384 const versionLabel = version ? `v${version}` : "the installed version";
385 const minVersion = unavailable.compatibility.minVersion;
386 const latestVersion = channel?.latestVersion;
387 if (latestVersion && compareSemverVersions(latestVersion, minVersion) < 0) {
388 const tooOld = `Claude Code ${versionLabel} is too old for ${unavailable.model.name}, which needs v${minVersion} or newer`;
389 if (channel?.updateCommand === HOMEBREW_STABLE_CASK_UPDATE_COMMAND) {
390 return `${tooOld}, but the claude-code Homebrew cask only has v${latestVersion}. Switch to the claude-code@latest cask: ${HOMEBREW_LATEST_CASK_SWITCH_COMMAND}`;
391 }
392 return `${tooOld}, but the newest version this install can update to is v${latestVersion}. Install Claude Code another way or wait for a newer release.`;
393 }
394 return `Claude Code ${versionLabel} is too old for ${unavailable.model.name}. Upgrade to v${minVersion} or newer to access it.`;
396​
397/** The status check words the upgrade before the install channel reports its newest version. */
398export function scopeClaudeUpgradeMessageToChannel<
399 P extends {
400 readonly message?: string | undefined;
401 readonly version: string | null;
402 readonly versionAdvisory?:
403 | { readonly latestVersion: string | null; readonly updateCommand: string | null }
404 | undefined;
405 },
406>(catalog: ClaudeModelCatalog, provider: P): P {
407 const channel = provider.versionAdvisory;
408 if (
409 !channel?.latestVersion ||
410 provider.message === undefined ||
411 provider.message !== formatClaudeVersionUpgradeMessage(catalog, provider.version)
412 ) {
413 return provider;
414 }
415 const message = formatClaudeVersionUpgradeMessage(catalog, provider.version, channel);
416 return message === undefined ? provider : { ...provider, message };
418​
419/** Claude Code's effort levels, lowest first. */
420export const CLAUDE_EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"] as const;
421export type ClaudeEffortLevel = (typeof CLAUDE_EFFORT_LEVELS)[number];
422​
423function claudeEffortRank(level: string | undefined): number {
424 return CLAUDE_EFFORT_LEVELS.indexOf(level as ClaudeEffortLevel);
426​
427/** One settings source's effort caps, with `modelSettings` keys as the user wrote them. */
428export interface ClaudeEffortCapSource {
429 readonly maxEffortLevel?: ClaudeEffortLevel;
430 readonly modelMaxEffortLevels?: ReadonlyMap<string, ClaudeEffortLevel>;
432​
433const CLAUDE_1M_SUFFIX = "[1m]";
434const CLAUDE_CODE_FAMILY_ALIASES: ReadonlySet<string> = new Set([
435 "opus",
436 "sonnet",
437 "haiku",
438 "fable",
439]);
440​
441/**
442 * Names the model a `modelSettings` key caps the way Claude Code does, which is narrower than the
443 * catalog's aliases: only a family alias (optionally `[1m]`) resolves as an alias, and any other key
444 * names the most specific model id it contains, so `claude-opus-5-5-20260101` and Bedrock ids match
445 * while `claude-opus-5.5` matches nothing.
446 */
447function resolveClaudeModelSettingsKey(
448 catalog: ClaudeModelCatalog,
449 key: string,
450): string | undefined {
451 const lowered = key.trim().toLowerCase();
452 const unsuffixed = lowered.endsWith(CLAUDE_1M_SUFFIX)
453 ? lowered.slice(0, -CLAUDE_1M_SUFFIX.length)
454 : lowered;
455 if (CLAUDE_CODE_FAMILY_ALIASES.has(unsuffixed)) {
456 return catalog.models.find(
457 (entry) => !entry.model.isCustom && entry.model.aliases?.includes(unsuffixed),
458 )?.model.slug;
459 }
460 let match: string | undefined;
461 for (const { model } of catalog.models) {
462 if (!model.isCustom && lowered.includes(model.slug) && model.slug.length > (match?.length ?? 0))
463 match = model.slug;
464 }
465 return match;
467​
468/** Keys `modelSettings` caps by canonical slug, keeping the lowest cap when several keys name one model. */
469function resolveClaudeModelMaxEffortLevels(
470 catalog: ClaudeModelCatalog,
471 levels: ReadonlyMap<string, ClaudeEffortLevel> | undefined,
472): ReadonlyMap<string, ClaudeEffortLevel> {
473 const resolved = new Map<string, ClaudeEffortLevel>();
474 for (const [key, level] of levels ?? []) {
475 const slug = resolveClaudeModelSettingsKey(catalog, key);
476 if (!slug) continue;
477 const current = resolved.get(slug);
478 if (!current || claudeEffortRank(level) < claudeEffortRank(current)) resolved.set(slug, level);
479 }
480 return resolved;
482​
483/**
484 * Claude Code clamps efforts above `maxEffortLevel` to the model's highest level under it, so
485 * such options are relabelled, not removed, keeping stored selections valid. Per-model caps
486 * replace their own source's top-level cap and `max` means none; across sources the lowest wins.
487 */
488export function capClaudeCatalogEffort(
489 catalog: ClaudeModelCatalog,
490 models: ReadonlyArray<ServerProviderModel>,
491 sources: ReadonlyArray<ClaudeEffortCapSource>,
492): ReadonlyArray<ServerProviderModel> {
493 if (sources.length === 0) return models;
494 const resolvedSources = sources.map((source) => ({
495 maxEffortLevel: source.maxEffortLevel,
496 modelMaxEffortLevels: resolveClaudeModelMaxEffortLevels(catalog, source.modelMaxEffortLevels),
497 }));
498 return models.map((model) => {
499 // Custom model labels are user-authored, so they are left alone.
500 if (model.isCustom || !model.capabilities?.optionDescriptors) return model;
501 const modelMaxEffortLevel = resolvedSources.reduce<ClaudeEffortLevel | undefined>(
502 (lowest, source) => {
503 const level = source.modelMaxEffortLevels.get(model.slug) ?? source.maxEffortLevel;
504 return level &&
505 level !== "max" &&
506 (!lowest || claudeEffortRank(level) < claudeEffortRank(lowest))
507 ? level
508 : lowest;
509 },
510 undefined,
511 );
512 if (!modelMaxEffortLevel) return model;
513 const capRank = claudeEffortRank(modelMaxEffortLevel);
514 return {
515 ...model,
516 capabilities: {
517 ...model.capabilities,
518 optionDescriptors: model.capabilities.optionDescriptors.map((descriptor) => {
519 if (descriptor.id !== "effort" || descriptor.type !== "select") return descriptor;
520 const cap = descriptor.options.reduce<{ rank: number; label: string } | undefined>(
521 (best, option) => {
522 const rank = claudeEffortRank(option.id);
523 return rank >= 0 && rank <= capRank && rank > (best?.rank ?? -1)
524 ? { rank, label: option.label }
525 : best;
526 },
527 undefined,
528 );
529 if (!cap) return descriptor;
530 return {
531 ...descriptor,
532 options: descriptor.options.map((option) => {
533 const idRank = claudeEffortRank(option.id);
534 const sentRank = claudeEffortRank(
535 normalizeClaudeCatalogEffort(catalog, option.id, model.slug),
536 );
537 const displayedRank = idRank >= 0 ? idRank : sentRank;
538 const runsRank = sentRank >= 0 ? sentRank : idRank;
539 return displayedRank > cap.rank && runsRank > cap.rank
540 ? { ...option, label: `${option.label} (capped to ${cap.label})` }
541 : option;
542 }),
543 };
544 }),
545 },
546 };
547 });
549​
550export function resolveClaudeCatalogEffort(
551 catalog: ClaudeModelCatalog,
552 model: string | null | undefined,
553 raw: string | null | undefined,
554): string | undefined {
555 if (!resolveClaudeCatalogModel(catalog, model)) {
556 const effort = raw?.trim();
557 return effort && (CLAUDE_EFFORT_LEVELS as ReadonlyArray<string>).includes(effort)
558 ? effort
559 : undefined;
560 }
561​
562 const caps = getClaudeCatalogModelCapabilities(catalog, model);
563 const descriptors = getProviderOptionDescriptors({
564 caps,
565 ...(raw ? { selections: [{ id: "effort", value: raw }] } : {}),
566 });
567 const descriptor = descriptors.find((candidate) => candidate.id === "effort");
568 const value = getProviderOptionCurrentValue(descriptor);
569 return typeof value === "string" ? value : undefined;
571​
572export function normalizeClaudeCatalogEffort(
573 catalog: ClaudeModelCatalog,
574 effort: string | null | undefined,
575 model: string | null | undefined,
576): string | undefined {
577 if (!effort) return undefined;
578 const effortMap = resolveClaudeCatalogModel(catalog, model)?.runtime.effortMap;
579 if (!effortMap || !Object.prototype.hasOwnProperty.call(effortMap, effort)) return effort;
580 return effortMap[effort] ?? undefined;
582​
583function resolveClaudeCatalogContextWindow(
584 catalog: ClaudeModelCatalog,
585 modelSelection: ModelSelection | undefined,
586): string | undefined {
587 const caps = getClaudeCatalogModelCapabilities(catalog, modelSelection?.model);
588 const raw = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
589 const descriptors = getProviderOptionDescriptors({
590 caps,
591 ...(raw ? { selections: [{ id: "contextWindow", value: raw }] } : {}),
592 });
593 const descriptor = descriptors.find((candidate) => candidate.id === "contextWindow");
594 const value = getProviderOptionCurrentValue(descriptor);
595 return typeof value === "string" ? value : undefined;
597​
598export function resolveClaudeCatalogApiModelId(
599 catalog: ClaudeModelCatalog,
600 modelSelection: ModelSelection,
601): string {
602 const entry = resolveClaudeCatalogModel(catalog, modelSelection.model);
603 const slug = entry?.apiModel ?? entry?.model.slug ?? modelSelection.model;
604 const descriptors = getProviderOptionDescriptors({
605 caps: entry?.model.capabilities ?? EMPTY_CAPABILITIES,
606 selections: modelSelection.options,
607 });
608 for (const [optionId, suffixes] of Object.entries(entry?.runtime.modelSuffixes ?? {})) {
609 const value = getProviderOptionCurrentValue(
610 descriptors.find((descriptor) => descriptor.id === optionId),
611 );
612 if (typeof value === "string" && suffixes[value]) return `${slug}${suffixes[value]}`;
613 }
614 return slug;
616​
617export function resolveClaudeCatalogContextWindowTokens(
618 catalog: ClaudeModelCatalog,
619 modelSelection: ModelSelection | undefined,
620): number | undefined {
621 const entry = resolveClaudeCatalogModel(catalog, modelSelection?.model);
622 if (!entry) return undefined;
623 if (entry.runtime.fixedContextWindowTokens) return entry.runtime.fixedContextWindowTokens;
624 const contextWindow = resolveClaudeCatalogContextWindow(catalog, modelSelection);
625 return contextWindow ? entry.runtime.contextWindowTokens?.[contextWindow] : undefined;