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 "@v12/contracts";
10import {
11 createModelSelection,
12 normalizeModelSlug,
13 resolveSelectableModel,
14} from "@v12/shared/model";
15import { getComposerProviderState } from "./components/chat/composerProviderState";
16import { UnifiedSettings } from "@v12/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 provider: ProviderDriverKind = ProviderDriverKind.make("codex"),
121): string[] {
122 const normalizedModels: string[] = [];
123 const seen = new Set<string>();
124
125 for (const candidate of models) {
126 const normalized = normalizeModelSlug(candidate, provider);
127 if (
128 !normalized ||
129 normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
130 builtInModelSlugs.has(normalized) ||
131 seen.has(normalized)
132 ) {
133 continue;
134 }
135
136 seen.add(normalized);
137 normalizedModels.push(normalized);
138 if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
139 break;
140 }
141 }
142
143 return normalizedModels;
144}
145
146export function getAppModelOptions(
147 settings: UnifiedSettings,
148 providers: ReadonlyArray<ServerProvider>,
149 provider: ProviderDriverKind,
150 _selectedModel?: string | null,
151): AppModelOption[] {
152 const options: AppModelOption[] = getProviderModels(providers, provider).map(toAppModelOption);
153 const seen = new Set(options.map((option) => option.slug));
154 const builtInModelSlugs = new Set(
155 Arr.filterMap(getProviderModels(providers, provider), (model) =>
156 model.isCustom ? Result.failVoid : Result.succeed(model.slug),
157 ),
158 );
159
160 // Read from the default instance's config first (that's where edits
161 // now land), falling back to the legacy per-kind bucket so unmigrated
162 // settings and the initial render before the first write both still
163 // see the user's authored custom models.
164 const defaultInstanceId = defaultInstanceIdForDriver(provider);
165 const customModels = readInstanceCustomModels(settings, defaultInstanceId, provider);
166 for (const slug of normalizeCustomModelSlugs(customModels, builtInModelSlugs, provider)) {
167 if (seen.has(slug)) {
168 continue;
169 }
170
171 seen.add(slug);
172 options.push({
173 slug,
174 name: slug,
175 isCustom: true,
176 });
177 }
178
179 return applyInstanceModelPreferences(
180 options,
181 readInstanceModelPreferences(settings, defaultInstanceId),
182 );
183}
184
185/**
186 * Instance-scoped variant of {@link getAppModelOptions}. Built-in models
187 * come from the instance's own `entry.models` snapshot (rather than the
188 * first-matching-kind fallback in `getProviderModels`), so each custom
189 * instance gets the precise model list its driver reported. Custom model
190 * slugs come from the instance's own `providerInstances[id].config.customModels`
191 * when present, falling back to the legacy per-kind
192 * `settings.providers[driverKind].customModels` bucket for default
193 * instances only. This keeps two instances of the same kind from leaking
194 * custom slugs into each other.
195 */
196export function getAppModelOptionsForInstance(
197 settings: UnifiedSettings,
198 entry: ProviderInstanceEntry,
199): AppModelOption[] {
200 const options: AppModelOption[] = entry.models.map(toAppModelOption);
201 const seen = new Set(options.map((option) => option.slug));
202 const builtInModelSlugs = new Set(
203 Arr.filterMap(entry.models, (model) =>
204 model.isCustom ? Result.failVoid : Result.succeed(model.slug),
205 ),
206 );
207
208 const customModels = readInstanceCustomModels(settings, entry.instanceId, entry.driverKind);
209 const normalizer = entry.driverKind;
210 for (const slug of normalizeCustomModelSlugs(customModels, builtInModelSlugs, normalizer)) {
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[0]?.slug ??
253 entry.models[0]?.slug ??
254 null
255 );
256}
257
258/**
259 * Instance-keyed model options map. Each configured instance gets its own
260 * option list so the model picker can show the same driver's built-in and
261 * custom instances side by side without collapsing them.
262 */
263export function getCustomModelOptionsByInstance(
264 settings: UnifiedSettings,
265 providers: ReadonlyArray<ServerProvider>,
266 _selectedInstanceId?: ProviderInstanceId | null,
267 _selectedModel?: string | null,
268): ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>> {
269 const out = new Map<ProviderInstanceId, ReadonlyArray<ModelEsque>>();
270 for (const entry of deriveProviderInstanceEntries(providers)) {
271 out.set(entry.instanceId, getAppModelOptionsForInstance(settings, entry));
272 }
273 return out;
274}
275
276export function resolveAppModelSelectionState(
277 settings: UnifiedSettings,
278 providers: ReadonlyArray<ServerProvider>,
279): ModelSelection {
280 const selection = settings.textGenerationModelSelection ?? {
281 instanceId: DEFAULT_TEXT_GENERATION_INSTANCE_ID,
282 model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
283 };
284 const entries = deriveProviderInstanceEntries(providers);
285 const selectedEntry = entries.find(
286 (entry) => entry.instanceId === selection.instanceId && entry.enabled && entry.isAvailable,
287 );
288 const entry =
289 selectedEntry ?? entries.find((candidate) => candidate.enabled && candidate.isAvailable);
290 if (entry) {
291 // When the instance changed due to fallback (e.g. selected instance was disabled),
292 // don't carry over the old instance's model — use the fallback instance's default.
293 const selectedModel = selectedEntry ? selection.model : null;
294 const model =
295 resolveAppModelSelectionForInstance(entry.instanceId, settings, providers, selectedModel) ??
296 entry.models[0]?.slug ??
297 DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[entry.driverKind];
298 if (!model) {
299 return createModelSelection(entry.instanceId, "", []);
300 }
301 const provider = entry.driverKind;
302 const { modelOptionsForDispatch } = getComposerProviderState({
303 provider,
304 model,
305 models: entry.models,
306 modelOptions: selectedEntry ? selection.options : undefined,
307 });
308
309 return createModelSelection(entry.instanceId, model, modelOptionsForDispatch);
310 }
311
312 const provider = resolveSelectableProvider(providers, null);
313 const keptSelectedProvider = false;
314
315 // When the provider changed due to fallback (e.g. selected provider was disabled),
316 // don't carry over the old provider's model — use the fallback provider's default.
317 const selectedModel = keptSelectedProvider ? selection.model : null;
318 const model = resolveAppModelSelection(provider, settings, providers, selectedModel);
319 const { modelOptionsForDispatch } = getComposerProviderState({
320 provider,
321 model,
322 models: getProviderModels(providers, provider),
323 modelOptions: keptSelectedProvider ? selection.options : undefined,
324 });
325
326 return createModelSelection(defaultInstanceIdForDriver(provider), model, modelOptionsForDispatch);
327}