Open History to see the last commit
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 ?? [];
70}
71
72export interface AppModelOption {
73 slug: string;
74 name: string;
75 shortName?: string;
76 subProvider?: string;
77 isCustom: boolean;
78 isDefault?: boolean;
79}
80
81function toAppModelOption(model: ServerProvider["models"][number]): AppModelOption {
82 const option: AppModelOption = {
83 slug: model.slug,
84 name: model.name,
85 isCustom: model.isCustom,
86 };
87 if (model.shortName) option.shortName = model.shortName;
88 if (model.subProvider) option.subProvider = model.subProvider;
89 if (model.isDefault) option.isDefault = true;
90 return option;
91}
92
93function readInstanceModelPreferences(
94 settings: UnifiedSettings,
95 instanceId: ProviderInstanceId,
96): { readonly hiddenModels: ReadonlyArray<string>; readonly modelOrder: ReadonlyArray<string> } {
97 return (
98 settings.providerModelPreferences?.[instanceId] ?? {
99 hiddenModels: [],
100 modelOrder: [],
101 }
102 );
103}
104
105function applyInstanceModelPreferences(
106 options: ReadonlyArray<AppModelOption>,
107 preferences: {
108 readonly hiddenModels: ReadonlyArray<string>;
109 readonly modelOrder: ReadonlyArray<string>;
110 },
111): AppModelOption[] {
112 const hiddenModels = new Set(preferences.hiddenModels);
113 return sortModelsForProviderInstance(
114 options.filter((option) => option.isCustom || !hiddenModels.has(option.slug)),
115 { modelOrder: preferences.modelOrder },
116 );
117}
118
119export function normalizeCustomModelSlugs(
120 models: Iterable<string | null | undefined>,
121 builtInModelSlugs: ReadonlySet<string>,
122): string[] {
123 const normalizedModels: string[] = [];
124 const seen = new Set<string>();
125
126 for (const candidate of models) {
127 const normalized = normalizeCustomModelSlug(candidate);
128 if (
129 !normalized ||
130 normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
131 builtInModelSlugs.has(normalized) ||
132 seen.has(normalized)
133 ) {
134 continue;
135 }
136
137 seen.add(normalized);
138 normalizedModels.push(normalized);
139 if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
140 break;
141 }
142 }
143
144 return normalizedModels;
145}
146
147export function getAppModelOptions(
148 settings: UnifiedSettings,
149 providers: ReadonlyArray<ServerProvider>,
150 provider: ProviderDriverKind,
151 _selectedModel?: string | null,
152): AppModelOption[] {
153 const options: AppModelOption[] = getProviderModels(providers, provider).map(toAppModelOption);
154 const seen = new Set(options.map((option) => option.slug));
155 const builtInModelSlugs = new Set(
156 Arr.filterMap(getProviderModels(providers, provider), (model) =>
157 model.isCustom ? Result.failVoid : Result.succeed(model.slug),
158 ),
159 );
160
161 // Read from the default instance's config first (that's where edits
162 // now land), falling back to the legacy per-kind bucket so unmigrated
163 // settings and the initial render before the first write both still
164 // see the user's authored custom models.
165 const defaultInstanceId = defaultInstanceIdForDriver(provider);
166 const customModels = readInstanceCustomModels(settings, defaultInstanceId, provider);
167 for (const slug of normalizeCustomModelSlugs(customModels, builtInModelSlugs)) {
168 if (seen.has(slug)) {
169 continue;
170 }
171
172 seen.add(slug);
173 options.push({
174 slug,
175 name: slug,
176 isCustom: true,
177 });
178 }
179
180 return applyInstanceModelPreferences(
181 options,
182 readInstanceModelPreferences(settings, defaultInstanceId),
183 );
184}
185
186/**
187 * Instance-scoped variant of {@link getAppModelOptions}. Built-in models
188 * come from the instance's own `entry.models` snapshot (rather than the
189 * first-matching-kind fallback in `getProviderModels`), so each custom
190 * instance gets the precise model list its driver reported. Custom model
191 * slugs come from the instance's own `providerInstances[id].config.customModels`
192 * when present, falling back to the legacy per-kind
193 * `settings.providers[driverKind].customModels` bucket for default
194 * instances only. This keeps two instances of the same kind from leaking
195 * custom slugs into each other.
196 */
197export function getAppModelOptionsForInstance(
198 settings: UnifiedSettings,
199 entry: ProviderInstanceEntry,
200): AppModelOption[] {
201 const options: AppModelOption[] = entry.models.map(toAppModelOption);
202 const seen = new Set(options.map((option) => option.slug));
203 const builtInModelSlugs = new Set(
204 Arr.filterMap(entry.models, (model) =>
205 model.isCustom ? Result.failVoid : Result.succeed(model.slug),
206 ),
207 );
208
209 const customModels = readInstanceCustomModels(settings, entry.instanceId, entry.driverKind);
210 for (const slug of normalizeCustomModelSlugs(customModels, builtInModelSlugs)) {
211 if (seen.has(slug)) {
212 continue;
213 }
214
215 seen.add(slug);
216 options.push({ slug, name: slug, isCustom: true });
217 }
218
219 return applyInstanceModelPreferences(
220 options,
221 readInstanceModelPreferences(settings, entry.instanceId),
222 );
223}
224
225export function resolveAppModelSelection(
226 provider: ProviderDriverKind,
227 settings: UnifiedSettings,
228 providers: ReadonlyArray<ServerProvider>,
229 selectedModel: string | null | undefined,
230): string {
231 const resolvedProvider = resolveSelectableProvider(providers, provider);
232 const options = getAppModelOptions(settings, providers, resolvedProvider, selectedModel);
233 return (
234 resolveSelectableModel(resolvedProvider, selectedModel, options) ??
235 getDefaultServerModel(providers, resolvedProvider)
236 );
237}
238
239export function resolveAppModelSelectionForInstance(
240 instanceId: ProviderInstanceId,
241 settings: UnifiedSettings,
242 providers: ReadonlyArray<ServerProvider>,
243 selectedModel: string | null | undefined,
244): string | null {
245 const entry = deriveProviderInstanceEntries(providers).find(
246 (candidate) => candidate.instanceId === instanceId,
247 );
248 if (!entry) return null;
249 const options = getAppModelOptionsForInstance(settings, entry);
250 return (
251 resolveSelectableModel(entry.driverKind, selectedModel, options) ??
252 options.find((option) => option.isDefault)?.slug ??
253 options[0]?.slug ??
254 entry.models.find((model) => model.isDefault)?.slug ??
255 entry.models[0]?.slug ??
256 null
257 );
258}
259
260/**
261 * Instance-keyed model options map. Each configured instance gets its own
262 * option list so the model picker can show the same driver's built-in and
263 * custom instances side by side without collapsing them.
264 */
265export function getCustomModelOptionsByInstance(
266 settings: UnifiedSettings,
267 providers: ReadonlyArray<ServerProvider>,
268 _selectedInstanceId?: ProviderInstanceId | null,
269 _selectedModel?: string | null,
270): ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>> {
271 const out = new Map<ProviderInstanceId, ReadonlyArray<ModelEsque>>();
272 for (const entry of deriveProviderInstanceEntries(providers)) {
273 out.set(entry.instanceId, getAppModelOptionsForInstance(settings, entry));
274 }
275 return out;
276}
277
278export function resolveAppModelSelectionState(
279 settings: UnifiedSettings,
280 providers: ReadonlyArray<ServerProvider>,
281): ModelSelection {
282 const selection = settings.textGenerationModelSelection ?? {
283 instanceId: DEFAULT_TEXT_GENERATION_INSTANCE_ID,
284 model: DEFAULT_TEXT_GENERATION_MODEL,
285 };
286 const entries = deriveProviderInstanceEntries(providers);
287 const selectedEntry = entries.find(
288 (entry) => entry.instanceId === selection.instanceId && entry.enabled && entry.isAvailable,
289 );
290 const entry =
291 selectedEntry ?? entries.find((candidate) => candidate.enabled && candidate.isAvailable);
292 if (entry) {
293 // When the instance changed due to fallback (e.g. selected instance was disabled),
294 // don't carry over the old instance's model — use the fallback instance's default.
295 const selectedModel = selectedEntry ? selection.model : null;
296 const model =
297 resolveAppModelSelectionForInstance(entry.instanceId, settings, providers, selectedModel) ??
298 entry.models[0]?.slug ??
299 DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[entry.driverKind];
300 if (!model) {
301 return createModelSelection(entry.instanceId, "", []);
302 }
303 const provider = entry.driverKind;
304 const { modelOptionsForDispatch } = getComposerProviderState({
305 provider,
306 model,
307 models: entry.models,
308 modelOptions: selectedEntry ? selection.options : undefined,
309 });
310
311 return createModelSelection(entry.instanceId, model, modelOptionsForDispatch);
312 }
313
314 const provider = resolveSelectableProvider(providers, null);
315 const keptSelectedProvider = false;
316
317 // When the provider changed due to fallback (e.g. selected provider was disabled),
318 // don't carry over the old provider's model — use the fallback provider's default.
319 const selectedModel = keptSelectedProvider ? selection.model : null;
320 const model = resolveAppModelSelection(provider, settings, providers, selectedModel);
321 const { modelOptionsForDispatch } = getComposerProviderState({
322 provider,
323 model,
324 models: getProviderModels(providers, provider),
325 modelOptions: keptSelectedProvider ? selection.options : undefined,
326 });
327
328 return createModelSelection(defaultInstanceIdForDriver(provider), model, modelOptionsForDispatch);
329}