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

ClaudeModelCatalog.ts

401 lines13.8 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;
36​
37export interface ClaudeModelCatalog {
38 readonly models: ReadonlyArray<ClaudeCatalogModel>;
40​
41function tryResolveClaudeModelCatalog(
42 resolved: ModelCatalog.ProviderCatalog | undefined,
43): ClaudeModelCatalog | null {
44 if (!resolved) return null;
45​
46 const models: Array<ClaudeCatalogModel> = [];
47 for (const entry of resolved.models) {
48 const profile = decodeClaudeProfileAdapter(entry.profileAdapter ?? {});
49 const adapter = decodeClaudeModelAdapter(entry.adapter ?? {});
50 if (Option.isNone(profile) || Option.isNone(adapter)) return null;
51 const model = ModelCatalog.catalogServerModel(resolved, entry);
52 models.push({
53 model: { ...model, capabilities: withUltracodeToggle(model.capabilities) },
54 runtime: profile.value.claudeCode ?? {},
55 compatibility: adapter.value.claudeCode ?? {},
56 });
57 }
58​
59 return {
60 models,
61 };
63​
64// The manifest keeps Ultracode as an effort level because released servers read it from main.
65export function withUltracodeToggle(
66 capabilities: ModelCapabilities | null,
67): ModelCapabilities | null {
68 const descriptors = capabilities?.optionDescriptors ?? [];
69 const effortIndex = descriptors.findIndex(
70 (descriptor) =>
71 descriptor.id === "effort" &&
72 descriptor.type === "select" &&
73 descriptor.options.some((option) => option.id === "ultracode"),
74 );
75 const effort = descriptors[effortIndex];
76 if (effort?.type !== "select") return capabilities;
77 const ultracodeByDefault =
78 (effort.currentValue ?? effort.options.find((option) => option.isDefault)?.id) === "ultracode";
79 const hasXhigh = effort.options.some((option) => option.id === "xhigh");
80 // Ultracode ran at xhigh, so a model that offered it keeps xhigh, and its default moves there.
81 const options = effort.options.flatMap(({ isDefault, ...option }) => {
82 if (option.id === "ultracode") {
83 return hasXhigh
84 ? []
85 : [{ id: "xhigh", label: "Extra High", ...(isDefault ? { isDefault } : {}) }];
86 }
87 if (ultracodeByDefault && option.id === "xhigh") return [{ ...option, isDefault: true }];
88 return [isDefault && !ultracodeByDefault ? { ...option, isDefault } : option];
89 });
90 return {
91 optionDescriptors: descriptors.toSpliced(
92 effortIndex,
93 1,
94 {
95 ...effort,
96 ...(effort.currentValue === "ultracode" ? { currentValue: "xhigh" } : {}),
97 options,
98 },
99 {
100 id: "ultracode",
101 label: "Ultracode",
102 type: "boolean",
103 ...(ultracodeByDefault ? { currentValue: true } : {}),
104 },
105 ),
106 };
108​
109/** Resolve the fallback on each read so its new-model badges can expire. */
110export function resolveClaudeModelCatalog(
111 catalog: ModelCatalog.ProviderCatalog | undefined,
112): ClaudeModelCatalog {
113 return (
114 tryResolveClaudeModelCatalog(catalog) ??
115 tryResolveClaudeModelCatalog(
116 resolveProviderCatalog(BUNDLED_MODEL_MANIFEST, CLAUDE) ?? undefined,
117 ) ?? {
118 models: [],
119 }
120 );
122​
123export const BUNDLED_CLAUDE_MODEL_CATALOG = resolveClaudeModelCatalog(undefined);
124​
125export function scopeClaudeModelCatalog(
126 catalog: ClaudeModelCatalog,
127 customModels: ReadonlyArray<CustomModelSetting>,
128): ClaudeModelCatalog {
129 const customEntries = readCustomModelEntries(customModels);
130 if (customEntries.length === 0) return catalog;
131 const customAliases = new Set(customEntries.map((entry) => entry.slug.toLowerCase()));
132​
133 const builtInModels = catalog.models.map((entry) => {
134 if (!entry.model.aliases?.some((alias) => customAliases.has(alias.toLowerCase()))) {
135 return entry;
136 }
137 return {
138 ...entry,
139 model: {
140 ...entry.model,
141 aliases: entry.model.aliases.filter((alias) => !customAliases.has(alias.toLowerCase())),
142 },
143 };
144 });
145 const builtInSlugs = new Set(builtInModels.map((entry) => entry.model.slug));
146 const customCatalogModels: Array<ClaudeCatalogModel> = [];
147 for (const entry of customEntries) {
148 if (!entry.capabilities || builtInSlugs.has(entry.slug)) continue;
149 customCatalogModels.push({
150 model: {
151 slug: entry.slug,
152 name: entry.name,
153 isCustom: true,
154 capabilities: withUltracodeToggle(entry.capabilities),
155 },
156 runtime: {},
157 compatibility: {},
158 });
159 }
160​
161 return { models: [...builtInModels, ...customCatalogModels] };
163​
164const CLAUDE_EFFORT_LABELS: Readonly<Record<string, string>> = {
165 low: "Low",
166 medium: "Medium",
167 high: "High",
168 xhigh: "Extra High",
169 max: "Max",
170};
171​
172function stripClaudeContextWindowSuffix(value: string): string {
173 return value.replace(/\[[^\]]*\]$/, "").trim();
175​
176export function claudeReportedModels(
177 catalog: ClaudeModelCatalog,
178 customModels: ReadonlyArray<CustomModelSetting>,
179 reported: ReadonlyArray<ClaudeModelInfo> | undefined,
180): ReadonlyArray<ServerProviderModel> {
181 if (!reported?.length) return [];
182 const known = new Set(
183 [
184 ...catalog.models.flatMap(({ model }) => [model.slug, ...(model.aliases ?? [])]),
185 ...readCustomModelEntries(customModels).map((entry) => entry.slug),
186 ].map((id) => stripClaudeContextWindowSuffix(id).toLowerCase()),
187 );
188 const models: Array<ServerProviderModel> = [];
189 for (const info of reported) {
190 const slug = info.value.trim();
191 // `default` is Claude Code's pointer at its own default model, not a model.
192 if (!slug || slug === "default") continue;
193 const ids = [slug, info.resolvedModel ?? ""]
194 .map((id) => stripClaudeContextWindowSuffix(id).toLowerCase())
195 .filter((id) => id.length > 0);
196 if (ids.some((id) => known.has(id))) continue;
197 for (const id of ids) known.add(id);
198 const efforts = info.supportsEffort ? (info.supportedEffortLevels ?? []) : [];
199 models.push({
200 slug,
201 name: info.displayName.trim() || slug,
202 isCustom: false,
203 capabilities: {
204 optionDescriptors: efforts.length
205 ? [
206 {
207 id: "effort",
208 label: "Reasoning",
209 type: "select",
210 // `default` is not an effort, so choosing it sends none and Claude Code picks.
211 options: [
212 { id: "default", label: "Default", isDefault: true },
213 ...efforts.map((id) => ({ id, label: CLAUDE_EFFORT_LABELS[id] ?? id })),
214 ],
215 },
216 ]
217 : [],
218 },
219 });
220 }
221 return models;
223​
224function resolveClaudeCatalogModel(
225 catalog: ClaudeModelCatalog,
226 slugOrAlias: string | null | undefined,
227): ClaudeCatalogModel | undefined {
228 const value = slugOrAlias?.trim();
229 if (!value) return undefined;
230 return (
231 catalog.models.find((entry) => entry.model.slug === value) ??
232 catalog.models.find((entry) =>
233 entry.model.aliases?.some((alias) => alias.toLowerCase() === value.toLowerCase()),
234 )
235 );
237​
238export function resolveClaudeModelSlug(catalog: ClaudeModelCatalog, slugOrAlias: string): string {
239 return resolveClaudeCatalogModel(catalog, slugOrAlias)?.model.slug ?? slugOrAlias;
241​
242/** Claude reports dated IDs, such as `claude-opus-4-5-20251101`, that the catalog may not list. */
243export function resolveClaudeReportedModelSlug(
244 catalog: ClaudeModelCatalog,
245 reported: string,
246): string {
247 return (
248 (
249 resolveClaudeCatalogModel(catalog, reported) ??
250 resolveClaudeCatalogModel(catalog, reported.replace(/-\d{8}$/, ""))
251 )?.model.slug ?? reported
252 );
254​
255export function getClaudeCatalogModelCapabilities(
256 catalog: ClaudeModelCatalog,
257 slugOrAlias: string | null | undefined,
258): ModelCapabilities {
259 return resolveClaudeCatalogModel(catalog, slugOrAlias)?.model.capabilities ?? EMPTY_CAPABILITIES;
261​
262function isVersionSupported(
263 compatibility: ClaudeCodeCompatibility,
264 version: string | null | undefined,
265): boolean {
266 if (!compatibility.minVersion && !compatibility.maxVersionExclusive) return true;
267 if (!version) return false;
268 if (compatibility.minVersion && compareSemverVersions(version, compatibility.minVersion) < 0) {
269 return false;
270 }
271 return !(
272 compatibility.maxVersionExclusive &&
273 compareSemverVersions(version, compatibility.maxVersionExclusive) >= 0
274 );
276​
277export function resolveClaudeModelsForVersion(
278 catalog: ClaudeModelCatalog,
279 version: string | null | undefined,
280): ReadonlyArray<ClaudeCatalogModel["model"]> {
281 return catalog.models
282 .filter((entry) => isVersionSupported(entry.compatibility, version))
283 .map((entry) => entry.model);
285​
286export function resolveClaudeUpdateRequiredModels(
287 catalog: ClaudeModelCatalog,
288 version: string | null | undefined,
289): ReadonlyArray<ServerProviderUpdateRequiredModel> {
290 if (!version) return [];
291 return catalog.models.flatMap(({ model, compatibility }) => {
292 const minVersion = compatibility.minVersion;
293 if (model.isLegacy || !minVersion || compareSemverVersions(version, minVersion) >= 0) {
294 return [];
295 }
296 return [
297 {
298 slug: model.slug,
299 name: model.name,
300 ...(model.badge ? { badge: model.badge } : {}),
301 minVersion,
302 },
303 ];
304 });
306​
307export function formatClaudeVersionUpgradeMessage(
308 catalog: ClaudeModelCatalog,
309 version: string | null,
310): string | undefined {
311 const unavailable = catalog.models
312 .filter(
313 (entry) =>
314 entry.compatibility.minVersion &&
315 (!version || compareSemverVersions(version, entry.compatibility.minVersion) < 0),
316 )
317 .toSorted((left, right) =>
318 compareSemverVersions(left.compatibility.minVersion!, right.compatibility.minVersion!),
319 )[0];
320 if (!unavailable?.compatibility.minVersion) return undefined;
321 const versionLabel = version ? `v${version}` : "the installed version";
322 return `Claude Code ${versionLabel} is too old for ${unavailable.model.name}. Upgrade to v${unavailable.compatibility.minVersion} or newer to access it.`;
324​
325export function resolveClaudeCatalogEffort(
326 catalog: ClaudeModelCatalog,
327 model: string | null | undefined,
328 raw: string | null | undefined,
329): string | undefined {
330 if (!resolveClaudeCatalogModel(catalog, model)) {
331 const effort = raw?.trim();
332 return effort && ["low", "medium", "high", "xhigh", "max"].includes(effort)
333 ? effort
334 : undefined;
335 }
336​
337 const caps = getClaudeCatalogModelCapabilities(catalog, model);
338 const descriptors = getProviderOptionDescriptors({
339 caps,
340 ...(raw ? { selections: [{ id: "effort", value: raw }] } : {}),
341 });
342 const descriptor = descriptors.find((candidate) => candidate.id === "effort");
343 const value = getProviderOptionCurrentValue(descriptor);
344 return typeof value === "string" ? value : undefined;
346​
347export function normalizeClaudeCatalogEffort(
348 catalog: ClaudeModelCatalog,
349 effort: string | null | undefined,
350 model: string | null | undefined,
351): string | undefined {
352 if (!effort) return undefined;
353 const effortMap = resolveClaudeCatalogModel(catalog, model)?.runtime.effortMap;
354 if (!effortMap || !Object.prototype.hasOwnProperty.call(effortMap, effort)) return effort;
355 return effortMap[effort] ?? undefined;
357​
358function resolveClaudeCatalogContextWindow(
359 catalog: ClaudeModelCatalog,
360 modelSelection: ModelSelection | undefined,
361): string | undefined {
362 const caps = getClaudeCatalogModelCapabilities(catalog, modelSelection?.model);
363 const raw = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
364 const descriptors = getProviderOptionDescriptors({
365 caps,
366 ...(raw ? { selections: [{ id: "contextWindow", value: raw }] } : {}),
367 });
368 const descriptor = descriptors.find((candidate) => candidate.id === "contextWindow");
369 const value = getProviderOptionCurrentValue(descriptor);
370 return typeof value === "string" ? value : undefined;
372​
373export function resolveClaudeCatalogApiModelId(
374 catalog: ClaudeModelCatalog,
375 modelSelection: ModelSelection,
376): string {
377 const entry = resolveClaudeCatalogModel(catalog, modelSelection.model);
378 const slug = entry?.model.slug ?? modelSelection.model;
379 const descriptors = getProviderOptionDescriptors({
380 caps: entry?.model.capabilities ?? EMPTY_CAPABILITIES,
381 selections: modelSelection.options,
382 });
383 for (const [optionId, suffixes] of Object.entries(entry?.runtime.modelSuffixes ?? {})) {
384 const value = getProviderOptionCurrentValue(
385 descriptors.find((descriptor) => descriptor.id === optionId),
386 );
387 if (typeof value === "string" && suffixes[value]) return `${slug}${suffixes[value]}`;
388 }
389 return slug;
391​
392export function resolveClaudeCatalogContextWindowTokens(
393 catalog: ClaudeModelCatalog,
394 modelSelection: ModelSelection | undefined,
395): number | undefined {
396 const entry = resolveClaudeCatalogModel(catalog, modelSelection?.model);
397 if (!entry) return undefined;
398 if (entry.runtime.fixedContextWindowTokens) return entry.runtime.fixedContextWindowTokens;
399 const contextWindow = resolveClaudeCatalogContextWindow(catalog, modelSelection);
400 return contextWindow ? entry.runtime.contextWindowTokens?.[contextWindow] : undefined;