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

modelSelection.ts

331 lines11.6 KB

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