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

modelSelection.ts

325 lines11.4 KB

1import {
2 DEFAULT_GIT_TEXT_GENERATION_MODEL,
3 DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
4 defaultInstanceIdForDriver,
5 type ModelSelection,
6 ProviderDriverKind,
7 ProviderInstanceId,
8 type ServerProvider,
9} from "@t3tools/contracts";
10import {
11 createModelSelection,
12 normalizeModelSlug,
13 resolveSelectableModel,
14} from "@t3tools/shared/model";
15import { getComposerProviderState } from "./components/chat/composerProviderState";
16import { UnifiedSettings } from "@t3tools/contracts/settings";
17import {
18 getDefaultServerModel,
19 getProviderModels,
20 resolveSelectableProvider,
21} from "./providerModels";
22import { ModelEsque } from "./components/chat/providerIconUtils";
23import { type ProviderInstanceEntry, deriveProviderInstanceEntries } from "./providerInstances";
24import { sortModelsForProviderInstance } from "./modelOrdering";
25​
26const MAX_CUSTOM_MODEL_COUNT = 32;
27export const MAX_CUSTOM_MODEL_LENGTH = 256;
28const DEFAULT_TEXT_GENERATION_INSTANCE_ID = ProviderInstanceId.make("codex");
29​
30/**
31 * Resolve the custom-model list for a given instance, preferring the
32 * instance's own `providerInstances[id].config.customModels` blob when
33 * present and falling back to the legacy per-kind
34 * `settings.providers[kind].customModels` bucket for default instances only.
35 *
36 * The Settings UI promotes the legacy bucket into an explicit
37 * `providerInstances[defaultId]` entry on every edit (the "migrate on
38 * first write" scheme documented in
39 * `ProviderInstanceRegistryHydration`), so this helper exists primarily
40 * so readers pick up that promotion immediately — and so first-time
41 * viewers on pre-migration settings still see their legacy list on
42 * default slots. Custom instances intentionally do not read the legacy
43 * per-driver bucket; otherwise one custom model added to `claude_openrouter`
44 * can appear on the stock `claudeAgent` instance.
45 */
46function readInstanceCustomModels(
47 settings: UnifiedSettings,
48 instanceId: ProviderInstanceId,
49 driverKind: ProviderDriverKind,
50): ReadonlyArray<string> {
51 const instance = settings.providerInstances?.[instanceId];
52 const config = instance?.config;
53 if (config !== null && typeof config === "object") {
54 const value = (config as Record<string, unknown>).customModels;
55 if (Array.isArray(value)) {
56 return value.filter((entry): entry is string => typeof entry === "string");
57 }
58 }
59 const defaultInstanceId = defaultInstanceIdForDriver(driverKind);
60 if (instanceId !== defaultInstanceId) {
61 return [];
62 }
63 const legacyProviders = settings.providers as Record<
64 string,
65 { readonly customModels: ReadonlyArray<string> } | undefined
66 >;
67 return legacyProviders[driverKind]?.customModels ?? [];
69​
70export interface AppModelOption {
71 slug: string;
72 name: string;
73 shortName?: string;
74 subProvider?: string;
75 isCustom: boolean;
77​
78function toAppModelOption(model: ServerProvider["models"][number]): AppModelOption {
79 const option: AppModelOption = {
80 slug: model.slug,
81 name: model.name,
82 isCustom: model.isCustom,
83 };
84 if (model.shortName) option.shortName = model.shortName;
85 if (model.subProvider) option.subProvider = model.subProvider;
86 return option;
88​
89function readInstanceModelPreferences(
90 settings: UnifiedSettings,
91 instanceId: ProviderInstanceId,
92): { readonly hiddenModels: ReadonlyArray<string>; readonly modelOrder: ReadonlyArray<string> } {
93 return (
94 settings.providerModelPreferences?.[instanceId] ?? {
95 hiddenModels: [],
96 modelOrder: [],
97 }
98 );
100​
101function applyInstanceModelPreferences(
102 options: ReadonlyArray<AppModelOption>,
103 preferences: {
104 readonly hiddenModels: ReadonlyArray<string>;
105 readonly modelOrder: ReadonlyArray<string>;
106 },
107): AppModelOption[] {
108 const hiddenModels = new Set(preferences.hiddenModels);
109 return sortModelsForProviderInstance(
110 options.filter((option) => option.isCustom || !hiddenModels.has(option.slug)),
111 { modelOrder: preferences.modelOrder },
112 );
114​
115export function normalizeCustomModelSlugs(
116 models: Iterable<string | null | undefined>,
117 builtInModelSlugs: ReadonlySet<string>,
118 provider: ProviderDriverKind = ProviderDriverKind.make("codex"),
119): string[] {
120 const normalizedModels: string[] = [];
121 const seen = new Set<string>();
122​
123 for (const candidate of models) {
124 const normalized = normalizeModelSlug(candidate, provider);
125 if (
126 !normalized ||
127 normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
128 builtInModelSlugs.has(normalized) ||
129 seen.has(normalized)
130 ) {
131 continue;
132 }
133​
134 seen.add(normalized);
135 normalizedModels.push(normalized);
136 if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
137 break;
138 }
139 }
140​
141 return normalizedModels;
143​
144export function getAppModelOptions(
145 settings: UnifiedSettings,
146 providers: ReadonlyArray<ServerProvider>,
147 provider: ProviderDriverKind,
148 _selectedModel?: string | null,
149): AppModelOption[] {
150 const options: AppModelOption[] = getProviderModels(providers, provider).map(toAppModelOption);
151 const seen = new Set(options.map((option) => option.slug));
152 const builtInModelSlugs = new Set(
153 getProviderModels(providers, provider)
154 .filter((model) => !model.isCustom)
155 .map((model) => model.slug),
156 );
157​
158 // Read from the default instance's config first (that's where edits
159 // now land), falling back to the legacy per-kind bucket so unmigrated
160 // settings and the initial render before the first write both still
161 // see the user's authored custom models.
162 const defaultInstanceId = defaultInstanceIdForDriver(provider);
163 const customModels = readInstanceCustomModels(settings, defaultInstanceId, provider);
164 for (const slug of normalizeCustomModelSlugs(customModels, builtInModelSlugs, provider)) {
165 if (seen.has(slug)) {
166 continue;
167 }
168​
169 seen.add(slug);
170 options.push({
171 slug,
172 name: slug,
173 isCustom: true,
174 });
175 }
176​
177 return applyInstanceModelPreferences(
178 options,
179 readInstanceModelPreferences(settings, defaultInstanceId),
180 );
182​
183/**
184 * Instance-scoped variant of {@link getAppModelOptions}. Built-in models
185 * come from the instance's own `entry.models` snapshot (rather than the
186 * first-matching-kind fallback in `getProviderModels`), so each custom
187 * instance gets the precise model list its driver reported. Custom model
188 * slugs come from the instance's own `providerInstances[id].config.customModels`
189 * when present, falling back to the legacy per-kind
190 * `settings.providers[driverKind].customModels` bucket for default
191 * instances only. This keeps two instances of the same kind from leaking
192 * custom slugs into each other.
193 */
194export function getAppModelOptionsForInstance(
195 settings: UnifiedSettings,
196 entry: ProviderInstanceEntry,
197): AppModelOption[] {
198 const options: AppModelOption[] = entry.models.map(toAppModelOption);
199 const seen = new Set(options.map((option) => option.slug));
200 const builtInModelSlugs = new Set(
201 entry.models.filter((model) => !model.isCustom).map((model) => model.slug),
202 );
203​
204 const customModels = readInstanceCustomModels(settings, entry.instanceId, entry.driverKind);
205 const normalizer = entry.driverKind;
206 for (const slug of normalizeCustomModelSlugs(customModels, builtInModelSlugs, normalizer)) {
207 if (seen.has(slug)) {
208 continue;
209 }
210​
211 seen.add(slug);
212 options.push({ slug, name: slug, isCustom: true });
213 }
214​
215 return applyInstanceModelPreferences(
216 options,
217 readInstanceModelPreferences(settings, entry.instanceId),
218 );
220​
221export function resolveAppModelSelection(
222 provider: ProviderDriverKind,
223 settings: UnifiedSettings,
224 providers: ReadonlyArray<ServerProvider>,
225 selectedModel: string | null | undefined,
226): string {
227 const resolvedProvider = resolveSelectableProvider(providers, provider);
228 const options = getAppModelOptions(settings, providers, resolvedProvider, selectedModel);
229 return (
230 resolveSelectableModel(resolvedProvider, selectedModel, options) ??
231 getDefaultServerModel(providers, resolvedProvider)
232 );
234​
235export function resolveAppModelSelectionForInstance(
236 instanceId: ProviderInstanceId,
237 settings: UnifiedSettings,
238 providers: ReadonlyArray<ServerProvider>,
239 selectedModel: string | null | undefined,
240): string | null {
241 const entry = deriveProviderInstanceEntries(providers).find(
242 (candidate) => candidate.instanceId === instanceId,
243 );
244 if (!entry) return null;
245 const options = getAppModelOptionsForInstance(settings, entry);
246 return (
247 resolveSelectableModel(entry.driverKind, selectedModel, options) ??
248 options[0]?.slug ??
249 entry.models[0]?.slug ??
250 null
251 );
253​
254/**
255 * Instance-keyed model options map. Each configured instance gets its own
256 * option list so the model picker can show the same driver's built-in and
257 * custom instances side by side without collapsing them.
258 */
259export function getCustomModelOptionsByInstance(
260 settings: UnifiedSettings,
261 providers: ReadonlyArray<ServerProvider>,
262 _selectedInstanceId?: ProviderInstanceId | null,
263 _selectedModel?: string | null,
264): ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>> {
265 const out = new Map<ProviderInstanceId, ReadonlyArray<ModelEsque>>();
266 for (const entry of deriveProviderInstanceEntries(providers)) {
267 out.set(entry.instanceId, getAppModelOptionsForInstance(settings, entry));
268 }
269 return out;
271​
272export function resolveAppModelSelectionState(
273 settings: UnifiedSettings,
274 providers: ReadonlyArray<ServerProvider>,
275): ModelSelection {
276 const selection = settings.textGenerationModelSelection ?? {
277 instanceId: DEFAULT_TEXT_GENERATION_INSTANCE_ID,
278 model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
279 };
280 const entries = deriveProviderInstanceEntries(providers);
281 const selectedEntry = entries.find(
282 (entry) => entry.instanceId === selection.instanceId && entry.enabled && entry.isAvailable,
283 );
284 const entry =
285 selectedEntry ?? entries.find((candidate) => candidate.enabled && candidate.isAvailable);
286 if (entry) {
287 // When the instance changed due to fallback (e.g. selected instance was disabled),
288 // don't carry over the old instance's model — use the fallback instance's default.
289 const selectedModel = selectedEntry ? selection.model : null;
290 const model =
291 resolveAppModelSelectionForInstance(entry.instanceId, settings, providers, selectedModel) ??
292 entry.models[0]?.slug ??
293 DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[entry.driverKind];
294 if (!model) {
295 return createModelSelection(entry.instanceId, "", []);
296 }
297 const provider = entry.driverKind;
298 const { modelOptionsForDispatch } = getComposerProviderState({
299 provider,
300 model,
301 models: entry.models,
302 prompt: "",
303 modelOptions: selectedEntry ? selection.options : undefined,
304 });
305​
306 return createModelSelection(entry.instanceId, model, modelOptionsForDispatch);
307 }
308​
309 const provider = resolveSelectableProvider(providers, null);
310 const keptSelectedProvider = false;
311​
312 // When the provider changed due to fallback (e.g. selected provider was disabled),
313 // don't carry over the old provider's model — use the fallback provider's default.
314 const selectedModel = keptSelectedProvider ? selection.model : null;
315 const model = resolveAppModelSelection(provider, settings, providers, selectedModel);
316 const { modelOptionsForDispatch } = getComposerProviderState({
317 provider,
318 model,
319 models: getProviderModels(providers, provider),
320 prompt: "",
321 modelOptions: keptSelectedProvider ? selection.options : undefined,
322 });
323​
324 return createModelSelection(defaultInstanceIdForDriver(provider), model, modelOptionsForDispatch);