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