Open History to see the last commit
1import {
2 ANTIGRAVITY_DEFAULT_MODEL,
3 DEFAULT_TEXT_GENERATION_MODEL,
4 DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER,
5 defaultInstanceIdForDriver,
6 type ModelSelection,
7 ProviderDriverKind,
8 ProviderInstanceId,
9 type ServerProvider,
10} from "@t3tools/contracts";
11import {
12 type CustomModelDefinition,
13 createModelSelection,
14 normalizeCustomModelSlug,
15 readCustomModelEntries,
16 resolveSelectableModel,
17} from "@t3tools/shared/model";
18import { getComposerProviderState } from "./components/chat/composerProviderState";
19import { UnifiedSettings } from "@t3tools/contracts/settings";
20import * as Arr from "effect/Array";
21import * as Result from "effect/Result";
22import {
23 getDefaultServerModel,
24 getProviderModels,
25 resolveSelectableProvider,
26} from "./providerModels";
27import { ModelEsque } from "./components/chat/providerIconUtils";
28import {
29 type ProviderInstanceEntry,
30 deriveProviderInstanceEntries,
31 NO_PROVIDER_MODEL_SELECTION,
32} from "./providerInstances";
33import { sortModelsForProviderInstance } from "./modelOrdering";
34
35const MAX_CUSTOM_MODEL_COUNT = 32;
36export const MAX_CUSTOM_MODEL_LENGTH = 256;
37const DEFAULT_TEXT_GENERATION_INSTANCE_ID = ProviderInstanceId.make("codex");
38
39/**
40 * Resolve the custom-model list for a given instance, preferring the
41 * instance's own `providerInstances[id].config.customModels` blob when
42 * present and falling back to the legacy per-kind
43 * `settings.providers[kind].customModels` bucket for default instances only.
44 *
45 * The Settings UI promotes the legacy bucket into an explicit
46 * `providerInstances[defaultId]` entry on every edit (the "migrate on
47 * first write" scheme documented in
48 * `ProviderInstanceRegistryHydration`), so this helper exists primarily
49 * so readers pick up that promotion immediately — and so first-time
50 * viewers on pre-migration settings still see their legacy list on
51 * default slots. Custom instances intentionally do not read the legacy
52 * per-driver bucket; otherwise one custom model added to `claude_openrouter`
53 * can appear on the stock `claudeAgent` instance.
54 */
55function readInstanceCustomModels(
56 settings: UnifiedSettings,
57 instanceId: ProviderInstanceId,
58 driverKind: ProviderDriverKind,
59): ReadonlyArray<CustomModelDefinition> {
60 if (driverKind === "antigravity") return [];
61 const instance = settings.providerInstances?.[instanceId];
62 const config = instance?.config;
63 if (config !== null && typeof config === "object") {
64 const value = (config as Record<string, unknown>).customModels;
65 if (Array.isArray(value)) {
66 return readCustomModelEntries(value);
67 }
68 }
69 const defaultInstanceId = defaultInstanceIdForDriver(driverKind);
70 if (instanceId !== defaultInstanceId) {
71 return [];
72 }
73 const legacyProviders = settings.providers as Record<
74 string,
75 { readonly customModels: ReadonlyArray<unknown> } | undefined
76 >;
77 return readCustomModelEntries(legacyProviders[driverKind]?.customModels ?? []);
78}
79
80export interface AppModelOption {
81 slug: string;
82 name: string;
83 shortName?: string;
84 subProvider?: string;
85 aliases?: ReadonlyArray<string>;
86 badge?: "new";
87 isCustom: boolean;
88 isDefault?: boolean;
89 isLegacy?: boolean;
90 isUnavailable?: boolean;
91}
92
93function appendUnavailableDynamicModelSelection(
94 options: AppModelOption[],
95 rawModels: ReadonlyArray<ServerProvider["models"][number]>,
96 provider: ProviderDriverKind,
97 selectedModel: string | null | undefined,
98 hiddenModels: ReadonlyArray<string>,
99): AppModelOption[] {
100 if (provider !== "opencode" && provider !== "antigravity") return options;
101 const slug = normalizeCustomModelSlug(selectedModel);
102 if (!slug) return options;
103 if (provider === "antigravity" && slug === ANTIGRAVITY_DEFAULT_MODEL) return options;
104
105 // A model that exists in the raw catalog can be absent from `options`
106 // because the user hid it. Keep that preference authoritative.
107 if (resolveSelectableModel(provider, slug, rawModels) !== null) return options;
108 if (hiddenModels.includes(slug)) return options;
109 if (options.some((option) => option.slug === slug)) return options;
110
111 return [...options, { slug, name: slug, isCustom: false, isUnavailable: true }];
112}
113
114function toAppModelOption(model: ServerProvider["models"][number]): AppModelOption {
115 const option: AppModelOption = {
116 slug: model.slug,
117 name: model.name,
118 isCustom: model.isCustom,
119 };
120 if (model.shortName) option.shortName = model.shortName;
121 if (model.subProvider) option.subProvider = model.subProvider;
122 if (model.aliases) option.aliases = model.aliases;
123 if (model.badge) option.badge = model.badge;
124 if (model.isDefault) option.isDefault = true;
125 if (model.isLegacy) option.isLegacy = true;
126 return option;
127}
128
129function readInstanceModelPreferences(
130 settings: UnifiedSettings,
131 instanceId: ProviderInstanceId,
132): { readonly hiddenModels: ReadonlyArray<string>; readonly modelOrder: ReadonlyArray<string> } {
133 return (
134 settings.providerModelPreferences?.[instanceId] ?? {
135 hiddenModels: [],
136 modelOrder: [],
137 }
138 );
139}
140
141function applyInstanceModelPreferences(
142 options: ReadonlyArray<AppModelOption>,
143 preferences: {
144 readonly hiddenModels: ReadonlyArray<string>;
145 readonly modelOrder: ReadonlyArray<string>;
146 },
147): AppModelOption[] {
148 const hiddenModels = new Set(preferences.hiddenModels);
149 return sortModelsForProviderInstance(
150 options.filter((option) => option.isCustom || !hiddenModels.has(option.slug)),
151 { modelOrder: preferences.modelOrder },
152 );
153}
154
155function normalizeCustomModelEntries(
156 models: ReadonlyArray<CustomModelDefinition>,
157 builtInModelSlugs: ReadonlySet<string>,
158): CustomModelDefinition[] {
159 const normalizedModels: CustomModelDefinition[] = [];
160 const seen = new Set<string>();
161
162 for (const candidate of models) {
163 if (
164 candidate.slug.length > MAX_CUSTOM_MODEL_LENGTH ||
165 builtInModelSlugs.has(candidate.slug) ||
166 seen.has(candidate.slug)
167 ) {
168 continue;
169 }
170
171 seen.add(candidate.slug);
172 normalizedModels.push(candidate);
173 if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
174 break;
175 }
176 }
177
178 return normalizedModels;
179}
180
181function getAppModelOptions(
182 settings: UnifiedSettings,
183 providers: ReadonlyArray<ServerProvider>,
184 provider: ProviderDriverKind,
185 selectedModel?: string | null,
186): AppModelOption[] {
187 const rawModels = getProviderModels(providers, provider);
188 // Server-reported custom rows mirror settings and can lag a removal, so
189 // only built-ins are taken from the snapshot; custom rows are rebuilt from
190 // settings below.
191 const options: AppModelOption[] = rawModels
192 .filter((model) => !model.isCustom)
193 .map(toAppModelOption);
194 const seen = new Set(options.map((option) => option.slug));
195 const builtInModelSlugs = new Set(
196 Arr.filterMap(getProviderModels(providers, provider), (model) =>
197 model.isCustom ? Result.failVoid : Result.succeed(model.slug),
198 ),
199 );
200
201 // Read from the default instance's config first (that's where edits
202 // now land), falling back to the legacy per-kind bucket so unmigrated
203 // settings and the initial render before the first write both still
204 // see the user's authored custom models.
205 const defaultInstanceId = defaultInstanceIdForDriver(provider);
206 const customModels = readInstanceCustomModels(settings, defaultInstanceId, provider);
207 for (const entry of normalizeCustomModelEntries(customModels, builtInModelSlugs)) {
208 if (seen.has(entry.slug)) {
209 continue;
210 }
211
212 seen.add(entry.slug);
213 options.push({ slug: entry.slug, name: entry.name, isCustom: true });
214 }
215
216 const preferences = readInstanceModelPreferences(settings, defaultInstanceId);
217 return appendUnavailableDynamicModelSelection(
218 applyInstanceModelPreferences(options, preferences),
219 rawModels,
220 provider,
221 selectedModel,
222 preferences.hiddenModels,
223 );
224}
225
226/**
227 * Instance-scoped variant of {@link getAppModelOptions}. Built-in models
228 * come from the instance's own `entry.models` snapshot (rather than the
229 * first-matching-kind fallback in `getProviderModels`), so each custom
230 * instance gets the precise model list its driver reported. Custom model
231 * slugs come from the instance's own `providerInstances[id].config.customModels`
232 * when present, falling back to the legacy per-kind
233 * `settings.providers[driverKind].customModels` bucket for default
234 * instances only. This keeps two instances of the same kind from leaking
235 * custom slugs into each other. Custom rows reported by the server are
236 * ignored so a slug removed in Settings disappears without waiting for the
237 * next provider probe.
238 */
239export function getAppModelOptionsForInstance(
240 settings: UnifiedSettings,
241 entry: ProviderInstanceEntry,
242 selectedModel?: string | null,
243): AppModelOption[] {
244 const options: AppModelOption[] = entry.models
245 .filter((model) => !model.isCustom)
246 .map(toAppModelOption);
247 const seen = new Set(options.map((option) => option.slug));
248 const builtInModelSlugs = new Set(
249 Arr.filterMap(entry.models, (model) =>
250 model.isCustom ? Result.failVoid : Result.succeed(model.slug),
251 ),
252 );
253
254 const customModels = readInstanceCustomModels(settings, entry.instanceId, entry.driverKind);
255 for (const custom of normalizeCustomModelEntries(customModels, builtInModelSlugs)) {
256 if (seen.has(custom.slug)) {
257 continue;
258 }
259
260 seen.add(custom.slug);
261 options.push({ slug: custom.slug, name: custom.name, isCustom: true });
262 }
263
264 const preferences = readInstanceModelPreferences(settings, entry.instanceId);
265 return appendUnavailableDynamicModelSelection(
266 applyInstanceModelPreferences(options, preferences),
267 entry.models,
268 entry.driverKind,
269 selectedModel,
270 preferences.hiddenModels,
271 );
272}
273
274export function resolveAppModelSelection(
275 provider: ProviderDriverKind,
276 settings: UnifiedSettings,
277 providers: ReadonlyArray<ServerProvider>,
278 selectedModel: string | null | undefined,
279): string {
280 const resolvedProvider = resolveSelectableProvider(providers, provider);
281 const options = getAppModelOptions(settings, providers, resolvedProvider, selectedModel);
282 return (
283 resolveSelectableModel(resolvedProvider, selectedModel, options) ??
284 getDefaultServerModel(providers, resolvedProvider)
285 );
286}
287
288export function resolveAppModelSelectionForInstance(
289 instanceId: ProviderInstanceId,
290 settings: UnifiedSettings,
291 providers: ReadonlyArray<ServerProvider>,
292 selectedModel: string | null | undefined,
293 resolutionOptions?: { readonly preserveUnavailableSelection?: boolean },
294): string | null {
295 const entry = deriveProviderInstanceEntries(providers).find(
296 (candidate) => candidate.instanceId === instanceId,
297 );
298 if (!entry) return null;
299 const options = getAppModelOptionsForInstance(
300 settings,
301 entry,
302 resolutionOptions?.preserveUnavailableSelection ? selectedModel : null,
303 );
304 const resolvedSelection = resolveSelectableModel(entry.driverKind, selectedModel, options);
305 if (resolvedSelection) {
306 return resolvedSelection;
307 }
308 if (
309 resolutionOptions?.preserveUnavailableSelection &&
310 (entry.driverKind === "opencode" || entry.driverKind === "antigravity")
311 ) {
312 const unavailableSelection = normalizeCustomModelSlug(selectedModel);
313 const hiddenModels = readInstanceModelPreferences(settings, entry.instanceId).hiddenModels;
314 if (
315 unavailableSelection &&
316 !hiddenModels.includes(unavailableSelection) &&
317 resolveSelectableModel(entry.driverKind, selectedModel, entry.models) === null &&
318 (entry.driverKind !== "antigravity" || unavailableSelection !== ANTIGRAVITY_DEFAULT_MODEL)
319 ) {
320 return unavailableSelection;
321 }
322 }
323 return options.find((option) => option.isDefault)?.slug ?? options[0]?.slug ?? null;
324}
325
326/**
327 * Instance-keyed model options map. Each configured instance gets its own
328 * option list so the model picker can show the same driver's built-in and
329 * custom instances side by side without collapsing them.
330 */
331export function getCustomModelOptionsByInstance(
332 settings: UnifiedSettings,
333 providers: ReadonlyArray<ServerProvider>,
334 selectedInstanceId?: ProviderInstanceId | null,
335 selectedModel?: string | null,
336): ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>> {
337 const out = new Map<ProviderInstanceId, ReadonlyArray<ModelEsque>>();
338 for (const entry of deriveProviderInstanceEntries(providers)) {
339 out.set(
340 entry.instanceId,
341 getAppModelOptionsForInstance(
342 settings,
343 entry,
344 entry.instanceId === selectedInstanceId ? selectedModel : null,
345 ),
346 );
347 }
348 return out;
349}
350
351/**
352 * Whether stored model options pick the opencode "plan" agent. Shared settings
353 * pickers keep and show such a value even while this device's legacy plan
354 * mode is off: another device may have chosen it, and this device's filter
355 * only applies to picks made here.
356 */
357export function selectsPlanAgent(options: ModelSelection["options"]): boolean {
358 return options?.some((option) => option.id === "agent" && option.value === "plan") ?? false;
359}
360
361export function resolveAppModelSelectionState(
362 settings: UnifiedSettings,
363 providers: ReadonlyArray<ServerProvider>,
364): ModelSelection {
365 const selection = settings.textGenerationModelSelection ?? {
366 instanceId: DEFAULT_TEXT_GENERATION_INSTANCE_ID,
367 model: DEFAULT_TEXT_GENERATION_MODEL,
368 };
369 const supportedProviders = providers.filter(
370 (provider) => provider.supportsTextGeneration !== false,
371 );
372 const entries = deriveProviderInstanceEntries(supportedProviders);
373 const selectedEntry = entries.find(
374 (entry) => entry.instanceId === selection.instanceId && entry.enabled && entry.isAvailable,
375 );
376 const entry =
377 selectedEntry ?? entries.find((candidate) => candidate.enabled && candidate.isAvailable);
378 if (entry) {
379 // When the instance changed due to fallback (e.g. selected instance was disabled),
380 // don't carry over the old instance's model — use the fallback instance's default.
381 const selectedModel = selectedEntry ? selection.model : null;
382 const model =
383 resolveAppModelSelectionForInstance(
384 entry.instanceId,
385 settings,
386 supportedProviders,
387 selectedModel,
388 ) ??
389 entry.models[0]?.slug ??
390 DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[entry.driverKind];
391 if (!model) {
392 return createModelSelection(entry.instanceId, "", []);
393 }
394 const provider = entry.driverKind;
395 const { modelOptionsForDispatch } = getComposerProviderState({
396 provider,
397 model,
398 models: entry.models,
399 modelOptions: selectedEntry ? selection.options : undefined,
400 planModeEnabled: settings.planModeEnabled || selectsPlanAgent(selection.options),
401 });
402
403 return createModelSelection(entry.instanceId, model, modelOptionsForDispatch);
404 }
405
406 return NO_PROVIDER_MODEL_SELECTION;
407}