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

modelSelection.ts

366 lines12.2 KB

1import {
2 ANTIGRAVITY_DEFAULT_MODEL,
3 DEFAULT_TEXT_GENERATION_MODEL,
4 DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER,
5 defaultInstanceIdForDriver,
6 type ModelSelection,
7 ProviderDriverKind,
8 ProviderInstanceId,
9 type ServerProvider,
10} from "@t3tools/contracts";
11import {
12 type CustomModelDefinition,
13 createModelSelection,
14 normalizeCustomModelSlug,
15 readCustomModelEntries,
16 resolveSelectableModel,
17} from "@t3tools/shared/model";
18import { getComposerProviderState } from "./components/chat/composerProviderState";
19import { UnifiedSettings } from "@t3tools/contracts/settings";
20import * as Arr from "effect/Array";
21import * as Result from "effect/Result";
22import {
23 getDefaultServerModel,
24 getProviderModels,
25 resolveSelectableProvider,
26} from "./providerModels";
27import { ModelEsque } from "./components/chat/providerIconUtils";
28import {
29 type ProviderInstanceEntry,
30 deriveProviderInstanceEntries,
31 NO_PROVIDER_MODEL_SELECTION,
32} from "./providerInstances";
33import { sortModelsForProviderInstance } from "./modelOrdering";
34​
35const MAX_CUSTOM_MODEL_COUNT = 32;
36export const MAX_CUSTOM_MODEL_LENGTH = 256;
37const DEFAULT_TEXT_GENERATION_INSTANCE_ID = ProviderInstanceId.make("codex");
38​
39/**
40 * Custom instances intentionally do not read the legacy per-driver bucket;
41 * otherwise one custom model added to `claude_openrouter` can appear on the
42 * stock `claudeAgent` instance.
43 */
44function readInstanceCustomModels(
45 settings: UnifiedSettings,
46 instanceId: ProviderInstanceId,
47 driverKind: ProviderDriverKind,
48): ReadonlyArray<CustomModelDefinition> {
49 if (driverKind === "antigravity") return [];
50 const instance = settings.providerInstances?.[instanceId];
51 const config = instance?.config;
52 if (config !== null && typeof config === "object") {
53 const value = (config as Record<string, unknown>).customModels;
54 if (Array.isArray(value)) {
55 return readCustomModelEntries(value);
56 }
57 }
58 return [];
60​
61export interface AppModelOption {
62 slug: string;
63 name: string;
64 shortName?: string;
65 subProvider?: string;
66 aliases?: ReadonlyArray<string>;
67 badge?: "new";
68 isCustom: boolean;
69 isDefault?: boolean;
70 isLegacy?: boolean;
71 isUnavailable?: boolean;
73​
74function appendUnavailableDynamicModelSelection(
75 options: AppModelOption[],
76 rawModels: ReadonlyArray<ServerProvider["models"][number]>,
77 provider: ProviderDriverKind,
78 selectedModel: string | null | undefined,
79 hiddenModels: ReadonlyArray<string>,
80): AppModelOption[] {
81 if (provider !== "opencode" && provider !== "antigravity") return options;
82 const slug = normalizeCustomModelSlug(selectedModel);
83 if (!slug) return options;
84 if (provider === "antigravity" && slug === ANTIGRAVITY_DEFAULT_MODEL) return options;
85​
86 if (resolveSelectableModel(provider, slug, rawModels) !== null) return options;
87 if (hiddenModels.includes(slug)) return options;
88 if (options.some((option) => option.slug === slug)) return options;
89​
90 return [...options, { slug, name: slug, isCustom: false, isUnavailable: true }];
92​
93function toAppModelOption(model: ServerProvider["models"][number]): AppModelOption {
94 const option: AppModelOption = {
95 slug: model.slug,
96 name: model.name,
97 isCustom: model.isCustom,
98 };
99 if (model.shortName) option.shortName = model.shortName;
100 if (model.subProvider) option.subProvider = model.subProvider;
101 if (model.aliases) option.aliases = model.aliases;
102 if (model.badge) option.badge = model.badge;
103 if (model.isDefault) option.isDefault = true;
104 if (model.isLegacy) option.isLegacy = true;
105 return option;
107​
108function readInstanceModelPreferences(
109 settings: UnifiedSettings,
110 instanceId: ProviderInstanceId,
111): { readonly hiddenModels: ReadonlyArray<string>; readonly modelOrder: ReadonlyArray<string> } {
112 return (
113 settings.providerModelPreferences?.[instanceId] ?? {
114 hiddenModels: [],
115 modelOrder: [],
116 }
117 );
119​
120function applyInstanceModelPreferences(
121 options: ReadonlyArray<AppModelOption>,
122 preferences: {
123 readonly hiddenModels: ReadonlyArray<string>;
124 readonly modelOrder: ReadonlyArray<string>;
125 },
126): AppModelOption[] {
127 const hiddenModels = new Set(preferences.hiddenModels);
128 return sortModelsForProviderInstance(
129 options.filter((option) => option.isCustom || !hiddenModels.has(option.slug)),
130 { modelOrder: preferences.modelOrder },
131 );
133​
134function normalizeCustomModelEntries(
135 models: ReadonlyArray<CustomModelDefinition>,
136 builtInModelSlugs: ReadonlySet<string>,
137): CustomModelDefinition[] {
138 const normalizedModels: CustomModelDefinition[] = [];
139 const seen = new Set<string>();
140​
141 for (const candidate of models) {
142 if (
143 candidate.slug.length > MAX_CUSTOM_MODEL_LENGTH ||
144 builtInModelSlugs.has(candidate.slug) ||
145 seen.has(candidate.slug)
146 ) {
147 continue;
148 }
149​
150 seen.add(candidate.slug);
151 normalizedModels.push(candidate);
152 if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
153 break;
154 }
155 }
156​
157 return normalizedModels;
159​
160function getAppModelOptions(
161 settings: UnifiedSettings,
162 providers: ReadonlyArray<ServerProvider>,
163 provider: ProviderDriverKind,
164 selectedModel?: string | null,
165): AppModelOption[] {
166 const rawModels = getProviderModels(providers, provider);
167 // Server-reported custom rows mirror settings and can lag a removal, so
168 // only built-ins are taken from the snapshot; custom rows are rebuilt from
169 // settings below.
170 const options: AppModelOption[] = rawModels
171 .filter((model) => !model.isCustom)
172 .map(toAppModelOption);
173 const seen = new Set(options.map((option) => option.slug));
174 const builtInModelSlugs = new Set(
175 Arr.filterMap(getProviderModels(providers, provider), (model) =>
176 model.isCustom ? Result.failVoid : Result.succeed(model.slug),
177 ),
178 );
179​
180 const defaultInstanceId = defaultInstanceIdForDriver(provider);
181 const customModels = readInstanceCustomModels(settings, defaultInstanceId, provider);
182 for (const entry of normalizeCustomModelEntries(customModels, builtInModelSlugs)) {
183 if (seen.has(entry.slug)) {
184 continue;
185 }
186​
187 seen.add(entry.slug);
188 options.push({ slug: entry.slug, name: entry.name, isCustom: true });
189 }
190​
191 const preferences = readInstanceModelPreferences(settings, defaultInstanceId);
192 return appendUnavailableDynamicModelSelection(
193 applyInstanceModelPreferences(options, preferences),
194 rawModels,
195 provider,
196 selectedModel,
197 preferences.hiddenModels,
198 );
200​
201export function getAppModelOptionsForInstance(
202 settings: UnifiedSettings,
203 entry: ProviderInstanceEntry,
204 selectedModel?: string | null,
205): AppModelOption[] {
206 const options: AppModelOption[] = entry.models
207 .filter((model) => !model.isCustom)
208 .map(toAppModelOption);
209 const seen = new Set(options.map((option) => option.slug));
210 const builtInModelSlugs = new Set(
211 Arr.filterMap(entry.models, (model) =>
212 model.isCustom ? Result.failVoid : Result.succeed(model.slug),
213 ),
214 );
215​
216 const customModels = readInstanceCustomModels(settings, entry.instanceId, entry.driverKind);
217 for (const custom of normalizeCustomModelEntries(customModels, builtInModelSlugs)) {
218 if (seen.has(custom.slug)) {
219 continue;
220 }
221​
222 seen.add(custom.slug);
223 options.push({ slug: custom.slug, name: custom.name, isCustom: true });
224 }
225​
226 const preferences = readInstanceModelPreferences(settings, entry.instanceId);
227 return appendUnavailableDynamicModelSelection(
228 applyInstanceModelPreferences(options, preferences),
229 entry.models,
230 entry.driverKind,
231 selectedModel,
232 preferences.hiddenModels,
233 );
235​
236export function resolveAppModelSelection(
237 provider: ProviderDriverKind,
238 settings: UnifiedSettings,
239 providers: ReadonlyArray<ServerProvider>,
240 selectedModel: string | null | undefined,
241): string {
242 const resolvedProvider = resolveSelectableProvider(providers, provider);
243 const options = getAppModelOptions(settings, providers, resolvedProvider, selectedModel);
244 return (
245 resolveSelectableModel(resolvedProvider, selectedModel, options) ??
246 getDefaultServerModel(providers, resolvedProvider)
247 );
249​
250export function resolveAppModelSelectionForInstance(
251 instanceId: ProviderInstanceId,
252 settings: UnifiedSettings,
253 providers: ReadonlyArray<ServerProvider>,
254 selectedModel: string | null | undefined,
255 resolutionOptions?: { readonly preserveUnavailableSelection?: boolean },
256): string | null {
257 const entry = deriveProviderInstanceEntries(providers).find(
258 (candidate) => candidate.instanceId === instanceId,
259 );
260 if (!entry) return null;
261 const options = getAppModelOptionsForInstance(
262 settings,
263 entry,
264 resolutionOptions?.preserveUnavailableSelection ? selectedModel : null,
265 );
266 const resolvedSelection = resolveSelectableModel(entry.driverKind, selectedModel, options);
267 if (resolvedSelection) {
268 return resolvedSelection;
269 }
270 if (
271 resolutionOptions?.preserveUnavailableSelection &&
272 (entry.driverKind === "opencode" || entry.driverKind === "antigravity")
273 ) {
274 const unavailableSelection = normalizeCustomModelSlug(selectedModel);
275 const hiddenModels = readInstanceModelPreferences(settings, entry.instanceId).hiddenModels;
276 if (
277 unavailableSelection &&
278 !hiddenModels.includes(unavailableSelection) &&
279 resolveSelectableModel(entry.driverKind, selectedModel, entry.models) === null &&
280 (entry.driverKind !== "antigravity" || unavailableSelection !== ANTIGRAVITY_DEFAULT_MODEL)
281 ) {
282 return unavailableSelection;
283 }
284 }
285 return options.find((option) => option.isDefault)?.slug ?? options[0]?.slug ?? null;
287​
288export function getCustomModelOptionsByInstance(
289 settings: UnifiedSettings,
290 providers: ReadonlyArray<ServerProvider>,
291 selectedInstanceId?: ProviderInstanceId | null,
292 selectedModel?: string | null,
293): ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>> {
294 const out = new Map<ProviderInstanceId, ReadonlyArray<ModelEsque>>();
295 for (const entry of deriveProviderInstanceEntries(providers)) {
296 out.set(
297 entry.instanceId,
298 getAppModelOptionsForInstance(
299 settings,
300 entry,
301 entry.instanceId === selectedInstanceId ? selectedModel : null,
302 ),
303 );
304 }
305 return out;
307​
308export function selectsPlanAgent(options: ModelSelection["options"]): boolean {
309 return options?.some((option) => option.id === "agent" && option.value === "plan") ?? false;
311​
312export function resolveAppModelSelectionState(
313 settings: UnifiedSettings,
314 providers: ReadonlyArray<ServerProvider>,
315): ModelSelection {
316 const selection = settings.textGenerationModelSelection ?? {
317 instanceId: DEFAULT_TEXT_GENERATION_INSTANCE_ID,
318 model: DEFAULT_TEXT_GENERATION_MODEL,
319 };
320 const supportedProviders = providers.filter(
321 (provider) => provider.supportsTextGeneration !== false,
322 );
323 const entries = deriveProviderInstanceEntries(supportedProviders);
324 const selectedEntry = entries.find(
325 (entry) => entry.instanceId === selection.instanceId && entry.enabled && entry.isAvailable,
326 );
327 const entry =
328 selectedEntry ?? entries.find((candidate) => candidate.enabled && candidate.isAvailable);
329 if (entry) {
330 const selectedModel = selectedEntry ? selection.model : null;
331 // A saved model the catalog no longer lists, or a new fallback instance,
332 // gets the driver's cheap text generation default. The catalog's own
333 // default is the flagship chat model, which is too expensive here.
334 const options = getAppModelOptionsForInstance(settings, entry);
335 const model =
336 resolveSelectableModel(entry.driverKind, selectedModel, options) ??
337 resolveSelectableModel(
338 entry.driverKind,
339 DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[entry.driverKind],
340 options,
341 ) ??
342 resolveAppModelSelectionForInstance(
343 entry.instanceId,
344 settings,
345 supportedProviders,
346 selectedModel,
347 ) ??
348 entry.models[0]?.slug ??
349 DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[entry.driverKind];
350 if (!model) {
351 return createModelSelection(entry.instanceId, "", []);
352 }
353 const provider = entry.driverKind;
354 const { modelOptionsForDispatch } = getComposerProviderState({
355 provider,
356 model,
357 models: entry.models,
358 modelOptions: selectedEntry ? selection.options : undefined,
359 planModeEnabled: settings.planModeEnabled || selectsPlanAgent(selection.options),
360 });
361​
362 return createModelSelection(entry.instanceId, model, modelOptionsForDispatch);
363 }
364​
365 return NO_PROVIDER_MODEL_SELECTION;