Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

modelSelection.ts

444 lines16.0 KB

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