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 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 };
62}
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 };
107}
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 );
121}
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] };
162}
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();
174}
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;
222}
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 );
236}
237
238export function resolveClaudeModelSlug(catalog: ClaudeModelCatalog, slugOrAlias: string): string {
239 return resolveClaudeCatalogModel(catalog, slugOrAlias)?.model.slug ?? slugOrAlias;
240}
241
242export function getClaudeCatalogModelCapabilities(
243 catalog: ClaudeModelCatalog,
244 slugOrAlias: string | null | undefined,
245): ModelCapabilities {
246 return resolveClaudeCatalogModel(catalog, slugOrAlias)?.model.capabilities ?? EMPTY_CAPABILITIES;
247}
248
249function isVersionSupported(
250 compatibility: ClaudeCodeCompatibility,
251 version: string | null | undefined,
252): boolean {
253 if (!compatibility.minVersion && !compatibility.maxVersionExclusive) return true;
254 if (!version) return false;
255 if (compatibility.minVersion && compareSemverVersions(version, compatibility.minVersion) < 0) {
256 return false;
257 }
258 return !(
259 compatibility.maxVersionExclusive &&
260 compareSemverVersions(version, compatibility.maxVersionExclusive) >= 0
261 );
262}
263
264export function resolveClaudeModelsForVersion(
265 catalog: ClaudeModelCatalog,
266 version: string | null | undefined,
267): ReadonlyArray<ClaudeCatalogModel["model"]> {
268 return catalog.models
269 .filter((entry) => isVersionSupported(entry.compatibility, version))
270 .map((entry) => entry.model);
271}
272
273export function resolveClaudeUpdateRequiredModels(
274 catalog: ClaudeModelCatalog,
275 version: string | null | undefined,
276): ReadonlyArray<ServerProviderUpdateRequiredModel> {
277 if (!version) return [];
278 return catalog.models.flatMap(({ model, compatibility }) => {
279 const minVersion = compatibility.minVersion;
280 if (model.isLegacy || !minVersion || compareSemverVersions(version, minVersion) >= 0) {
281 return [];
282 }
283 return [
284 {
285 slug: model.slug,
286 name: model.name,
287 ...(model.badge ? { badge: model.badge } : {}),
288 minVersion,
289 },
290 ];
291 });
292}
293
294export function formatClaudeVersionUpgradeMessage(
295 catalog: ClaudeModelCatalog,
296 version: string | null,
297): string | undefined {
298 const unavailable = catalog.models
299 .filter(
300 (entry) =>
301 entry.compatibility.minVersion &&
302 (!version || compareSemverVersions(version, entry.compatibility.minVersion) < 0),
303 )
304 .toSorted((left, right) =>
305 compareSemverVersions(left.compatibility.minVersion!, right.compatibility.minVersion!),
306 )[0];
307 if (!unavailable?.compatibility.minVersion) return undefined;
308 const versionLabel = version ? `v${version}` : "the installed version";
309 return `Claude Code ${versionLabel} is too old for ${unavailable.model.name}. Upgrade to v${unavailable.compatibility.minVersion} or newer to access it.`;
310}
311
312export function resolveClaudeCatalogEffort(
313 catalog: ClaudeModelCatalog,
314 model: string | null | undefined,
315 raw: string | null | undefined,
316): string | undefined {
317 if (!resolveClaudeCatalogModel(catalog, model)) {
318 const effort = raw?.trim();
319 return effort && ["low", "medium", "high", "xhigh", "max"].includes(effort)
320 ? effort
321 : undefined;
322 }
323
324 const caps = getClaudeCatalogModelCapabilities(catalog, model);
325 const descriptors = getProviderOptionDescriptors({
326 caps,
327 ...(raw ? { selections: [{ id: "effort", value: raw }] } : {}),
328 });
329 const descriptor = descriptors.find((candidate) => candidate.id === "effort");
330 const value = getProviderOptionCurrentValue(descriptor);
331 return typeof value === "string" ? value : undefined;
332}
333
334export function normalizeClaudeCatalogEffort(
335 catalog: ClaudeModelCatalog,
336 effort: string | null | undefined,
337 model: string | null | undefined,
338): string | undefined {
339 if (!effort) return undefined;
340 const effortMap = resolveClaudeCatalogModel(catalog, model)?.runtime.effortMap;
341 if (!effortMap || !Object.prototype.hasOwnProperty.call(effortMap, effort)) return effort;
342 return effortMap[effort] ?? undefined;
343}
344
345function resolveClaudeCatalogContextWindow(
346 catalog: ClaudeModelCatalog,
347 modelSelection: ModelSelection | undefined,
348): string | undefined {
349 const caps = getClaudeCatalogModelCapabilities(catalog, modelSelection?.model);
350 const raw = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
351 const descriptors = getProviderOptionDescriptors({
352 caps,
353 ...(raw ? { selections: [{ id: "contextWindow", value: raw }] } : {}),
354 });
355 const descriptor = descriptors.find((candidate) => candidate.id === "contextWindow");
356 const value = getProviderOptionCurrentValue(descriptor);
357 return typeof value === "string" ? value : undefined;
358}
359
360export function resolveClaudeCatalogApiModelId(
361 catalog: ClaudeModelCatalog,
362 modelSelection: ModelSelection,
363): string {
364 const entry = resolveClaudeCatalogModel(catalog, modelSelection.model);
365 const slug = entry?.model.slug ?? modelSelection.model;
366 const descriptors = getProviderOptionDescriptors({
367 caps: entry?.model.capabilities ?? EMPTY_CAPABILITIES,
368 selections: modelSelection.options,
369 });
370 for (const [optionId, suffixes] of Object.entries(entry?.runtime.modelSuffixes ?? {})) {
371 const value = getProviderOptionCurrentValue(
372 descriptors.find((descriptor) => descriptor.id === optionId),
373 );
374 if (typeof value === "string" && suffixes[value]) return `${slug}${suffixes[value]}`;
375 }
376 return slug;
377}
378
379export function resolveClaudeCatalogContextWindowTokens(
380 catalog: ClaudeModelCatalog,
381 modelSelection: ModelSelection | undefined,
382): number | undefined {
383 const entry = resolveClaudeCatalogModel(catalog, modelSelection?.model);
384 if (!entry) return undefined;
385 if (entry.runtime.fixedContextWindowTokens) return entry.runtime.fixedContextWindowTokens;
386 const contextWindow = resolveClaudeCatalogContextWindow(catalog, modelSelection);
387 return contextWindow ? entry.runtime.contextWindowTokens?.[contextWindow] : undefined;
388}