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