Open History to see the last commit
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}
36
37export interface ClaudeModelCatalog {
38 readonly models: ReadonlyArray<ClaudeCatalogModel>;
39}
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 models.push({
52 model: ModelCatalog.catalogServerModel(resolved, entry),
53 runtime: profile.value.claudeCode ?? {},
54 compatibility: adapter.value.claudeCode ?? {},
55 });
56 }
57
58 return {
59 models,
60 };
61}
62
63/** Resolve the fallback on each read so its new-model badges can expire. */
64export function resolveClaudeModelCatalog(
65 catalog: ModelCatalog.ProviderCatalog | undefined,
66): ClaudeModelCatalog {
67 return (
68 tryResolveClaudeModelCatalog(catalog) ??
69 tryResolveClaudeModelCatalog(
70 resolveProviderCatalog(BUNDLED_MODEL_MANIFEST, CLAUDE) ?? undefined,
71 ) ?? {
72 models: [],
73 }
74 );
75}
76
77export const BUNDLED_CLAUDE_MODEL_CATALOG = resolveClaudeModelCatalog(undefined);
78
79export function scopeClaudeModelCatalog(
80 catalog: ClaudeModelCatalog,
81 customModels: ReadonlyArray<CustomModelSetting>,
82): ClaudeModelCatalog {
83 const customEntries = readCustomModelEntries(customModels);
84 if (customEntries.length === 0) return catalog;
85 const customAliases = new Set(customEntries.map((entry) => entry.slug.toLowerCase()));
86
87 const builtInModels = catalog.models.map((entry) => {
88 if (!entry.model.aliases?.some((alias) => customAliases.has(alias.toLowerCase()))) {
89 return entry;
90 }
91 return {
92 ...entry,
93 model: {
94 ...entry.model,
95 aliases: entry.model.aliases.filter((alias) => !customAliases.has(alias.toLowerCase())),
96 },
97 };
98 });
99 const builtInSlugs = new Set(builtInModels.map((entry) => entry.model.slug));
100 const customCatalogModels: Array<ClaudeCatalogModel> = [];
101 for (const entry of customEntries) {
102 if (!entry.capabilities || builtInSlugs.has(entry.slug)) continue;
103 customCatalogModels.push({
104 model: {
105 slug: entry.slug,
106 name: entry.name,
107 isCustom: true,
108 capabilities: entry.capabilities,
109 },
110 runtime: {},
111 compatibility: {},
112 });
113 }
114
115 return { models: [...builtInModels, ...customCatalogModels] };
116}
117
118const CLAUDE_EFFORT_LABELS: Readonly<Record<string, string>> = {
119 low: "Low",
120 medium: "Medium",
121 high: "High",
122 xhigh: "Extra High",
123 max: "Max",
124};
125
126function stripClaudeContextWindowSuffix(value: string): string {
127 return value.replace(/\[[^\]]*\]$/, "").trim();
128}
129
130export function claudeReportedModels(
131 catalog: ClaudeModelCatalog,
132 customModels: ReadonlyArray<CustomModelSetting>,
133 reported: ReadonlyArray<ClaudeModelInfo> | undefined,
134): ReadonlyArray<ServerProviderModel> {
135 if (!reported?.length) return [];
136 const known = new Set(
137 [
138 ...catalog.models.flatMap(({ model }) => [model.slug, ...(model.aliases ?? [])]),
139 ...readCustomModelEntries(customModels).map((entry) => entry.slug),
140 ].map((id) => stripClaudeContextWindowSuffix(id).toLowerCase()),
141 );
142 const models: Array<ServerProviderModel> = [];
143 for (const info of reported) {
144 const slug = info.value.trim();
145 // `default` is Claude Code's pointer at its own default model, not a model.
146 if (!slug || slug === "default") continue;
147 const ids = [slug, info.resolvedModel ?? ""]
148 .map((id) => stripClaudeContextWindowSuffix(id).toLowerCase())
149 .filter((id) => id.length > 0);
150 if (ids.some((id) => known.has(id))) continue;
151 for (const id of ids) known.add(id);
152 const efforts = info.supportsEffort ? (info.supportedEffortLevels ?? []) : [];
153 models.push({
154 slug,
155 name: info.displayName.trim() || slug,
156 isCustom: false,
157 capabilities: {
158 optionDescriptors: efforts.length
159 ? [
160 {
161 id: "effort",
162 label: "Reasoning",
163 type: "select",
164 // `default` is not an effort, so choosing it sends none and Claude Code picks.
165 options: [
166 { id: "default", label: "Default", isDefault: true },
167 ...efforts.map((id) => ({ id, label: CLAUDE_EFFORT_LABELS[id] ?? id })),
168 ],
169 },
170 ]
171 : [],
172 },
173 });
174 }
175 return models;
176}
177
178function resolveClaudeCatalogModel(
179 catalog: ClaudeModelCatalog,
180 slugOrAlias: string | null | undefined,
181): ClaudeCatalogModel | undefined {
182 const value = slugOrAlias?.trim();
183 if (!value) return undefined;
184 return (
185 catalog.models.find((entry) => entry.model.slug === value) ??
186 catalog.models.find((entry) =>
187 entry.model.aliases?.some((alias) => alias.toLowerCase() === value.toLowerCase()),
188 )
189 );
190}
191
192export function resolveClaudeModelSlug(catalog: ClaudeModelCatalog, slugOrAlias: string): string {
193 return resolveClaudeCatalogModel(catalog, slugOrAlias)?.model.slug ?? slugOrAlias;
194}
195
196export function getClaudeCatalogModelCapabilities(
197 catalog: ClaudeModelCatalog,
198 slugOrAlias: string | null | undefined,
199): ModelCapabilities {
200 return resolveClaudeCatalogModel(catalog, slugOrAlias)?.model.capabilities ?? EMPTY_CAPABILITIES;
201}
202
203function isVersionSupported(
204 compatibility: ClaudeCodeCompatibility,
205 version: string | null | undefined,
206): boolean {
207 if (!compatibility.minVersion && !compatibility.maxVersionExclusive) return true;
208 if (!version) return false;
209 if (compatibility.minVersion && compareSemverVersions(version, compatibility.minVersion) < 0) {
210 return false;
211 }
212 return !(
213 compatibility.maxVersionExclusive &&
214 compareSemverVersions(version, compatibility.maxVersionExclusive) >= 0
215 );
216}
217
218export function resolveClaudeModelsForVersion(
219 catalog: ClaudeModelCatalog,
220 version: string | null | undefined,
221): ReadonlyArray<ClaudeCatalogModel["model"]> {
222 return catalog.models
223 .filter((entry) => isVersionSupported(entry.compatibility, version))
224 .map((entry) => entry.model);
225}
226
227export function resolveClaudeUpdateRequiredModels(
228 catalog: ClaudeModelCatalog,
229 version: string | null | undefined,
230): ReadonlyArray<ServerProviderUpdateRequiredModel> {
231 if (!version) return [];
232 return catalog.models.flatMap(({ model, compatibility }) => {
233 const minVersion = compatibility.minVersion;
234 if (model.isLegacy || !minVersion || compareSemverVersions(version, minVersion) >= 0) {
235 return [];
236 }
237 return [
238 {
239 slug: model.slug,
240 name: model.name,
241 ...(model.badge ? { badge: model.badge } : {}),
242 minVersion,
243 },
244 ];
245 });
246}
247
248export function formatClaudeVersionUpgradeMessage(
249 catalog: ClaudeModelCatalog,
250 version: string | null,
251): string | undefined {
252 const unavailable = catalog.models
253 .filter(
254 (entry) =>
255 entry.compatibility.minVersion &&
256 (!version || compareSemverVersions(version, entry.compatibility.minVersion) < 0),
257 )
258 .toSorted((left, right) =>
259 compareSemverVersions(left.compatibility.minVersion!, right.compatibility.minVersion!),
260 )[0];
261 if (!unavailable?.compatibility.minVersion) return undefined;
262 const versionLabel = version ? `v${version}` : "the installed version";
263 return `Claude Code ${versionLabel} is too old for ${unavailable.model.name}. Upgrade to v${unavailable.compatibility.minVersion} or newer to access it.`;
264}
265
266export function resolveClaudeCatalogEffort(
267 catalog: ClaudeModelCatalog,
268 model: string | null | undefined,
269 raw: string | null | undefined,
270): string | undefined {
271 if (!resolveClaudeCatalogModel(catalog, model)) {
272 const effort = raw?.trim();
273 return effort && ["low", "medium", "high", "xhigh", "max"].includes(effort)
274 ? effort
275 : undefined;
276 }
277
278 const caps = getClaudeCatalogModelCapabilities(catalog, model);
279 const descriptors = getProviderOptionDescriptors({
280 caps,
281 ...(raw ? { selections: [{ id: "effort", value: raw }] } : {}),
282 });
283 const descriptor = descriptors.find((candidate) => candidate.id === "effort");
284 const value = getProviderOptionCurrentValue(descriptor);
285 return typeof value === "string" ? value : undefined;
286}
287
288export function normalizeClaudeCatalogEffort(
289 catalog: ClaudeModelCatalog,
290 effort: string | null | undefined,
291 model: string | null | undefined,
292): string | undefined {
293 if (!effort) return undefined;
294 const effortMap = resolveClaudeCatalogModel(catalog, model)?.runtime.effortMap;
295 if (!effortMap || !Object.prototype.hasOwnProperty.call(effortMap, effort)) return effort;
296 return effortMap[effort] ?? undefined;
297}
298
299export function isClaudeCatalogUltracodeEffort(effort: string | null | undefined): boolean {
300 return effort === "ultracode";
301}
302
303function resolveClaudeCatalogContextWindow(
304 catalog: ClaudeModelCatalog,
305 modelSelection: ModelSelection | undefined,
306): string | undefined {
307 const caps = getClaudeCatalogModelCapabilities(catalog, modelSelection?.model);
308 const raw = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
309 const descriptors = getProviderOptionDescriptors({
310 caps,
311 ...(raw ? { selections: [{ id: "contextWindow", value: raw }] } : {}),
312 });
313 const descriptor = descriptors.find((candidate) => candidate.id === "contextWindow");
314 const value = getProviderOptionCurrentValue(descriptor);
315 return typeof value === "string" ? value : undefined;
316}
317
318export function resolveClaudeCatalogApiModelId(
319 catalog: ClaudeModelCatalog,
320 modelSelection: ModelSelection,
321): string {
322 const entry = resolveClaudeCatalogModel(catalog, modelSelection.model);
323 const slug = entry?.model.slug ?? modelSelection.model;
324 const descriptors = getProviderOptionDescriptors({
325 caps: entry?.model.capabilities ?? EMPTY_CAPABILITIES,
326 selections: modelSelection.options,
327 });
328 for (const [optionId, suffixes] of Object.entries(entry?.runtime.modelSuffixes ?? {})) {
329 const value = getProviderOptionCurrentValue(
330 descriptors.find((descriptor) => descriptor.id === optionId),
331 );
332 if (typeof value === "string" && suffixes[value]) return `${slug}${suffixes[value]}`;
333 }
334 return slug;
335}
336
337export function resolveClaudeCatalogContextWindowTokens(
338 catalog: ClaudeModelCatalog,
339 modelSelection: ModelSelection | undefined,
340): number | undefined {
341 const entry = resolveClaudeCatalogModel(catalog, modelSelection?.model);
342 if (!entry) return undefined;
343 if (entry.runtime.fixedContextWindowTokens) return entry.runtime.fixedContextWindowTokens;
344 const contextWindow = resolveClaudeCatalogContextWindow(catalog, modelSelection);
345 return contextWindow ? entry.runtime.contextWindowTokens?.[contextWindow] : undefined;
346}