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

modelSelection.ts

443 lines15.9 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 if (driverKind === "antigravity") return [];
62 const instance = settings.providerInstances?.[instanceId];
63 const config = instance?.config;
64 if (config !== null && typeof config === "object") {
65 const value = (config as Record<string, unknown>).customModels;
66 if (Array.isArray(value)) {
67 return readCustomModelEntries(value);
68 }
69 }
70 const defaultInstanceId = defaultInstanceIdForDriver(driverKind);
71 if (instanceId !== defaultInstanceId) {
72 return [];
73 }
74 const legacyProviders = settings.providers as Record<
75 string,
76 { readonly customModels: ReadonlyArray<unknown> } | undefined
77 >;
78 return readCustomModelEntries(legacyProviders[driverKind]?.customModels ?? []);
80​
81export interface AppModelOption {
82 slug: string;
83 name: string;
84 shortName?: string;
85 subProvider?: string;
86 aliases?: ReadonlyArray<string>;
87 badge?: "new";
88 isCustom: boolean;
89 isDefault?: boolean;
90 isLegacy?: boolean;
91 isUnavailable?: boolean;
93​
94function appendUnavailableDynamicModelSelection(
95 options: AppModelOption[],
96 rawModels: ReadonlyArray<ServerProvider["models"][number]>,
97 provider: ProviderDriverKind,
98 selectedModel: string | null | undefined,
99 hiddenModels: ReadonlyArray<string>,
100): AppModelOption[] {
101 if (provider !== "opencode" && provider !== "antigravity") return options;
102 const slug = normalizeCustomModelSlug(selectedModel);
103 if (!slug) return options;
104 if (provider === "antigravity" && slug === ANTIGRAVITY_DEFAULT_MODEL) return options;
105​
106 // A model that exists in the raw catalog can be absent from `options`
107 // because the user hid it. Keep that preference authoritative.
108 if (resolveSelectableModel(provider, slug, rawModels) !== null) return options;
109 if (hiddenModels.includes(slug)) return options;
110 if (options.some((option) => option.slug === slug)) return options;
111​
112 return [...options, { slug, name: slug, isCustom: false, isUnavailable: true }];
114​
115function toAppModelOption(model: ServerProvider["models"][number]): AppModelOption {
116 const option: AppModelOption = {
117 slug: model.slug,
118 name: model.name,
119 isCustom: model.isCustom,
120 };
121 if (model.shortName) option.shortName = model.shortName;
122 if (model.subProvider) option.subProvider = model.subProvider;
123 if (model.aliases) option.aliases = model.aliases;
124 if (model.badge) option.badge = model.badge;
125 if (model.isDefault) option.isDefault = true;
126 if (model.isLegacy) option.isLegacy = true;
127 return option;
129​
130function readInstanceModelPreferences(
131 settings: UnifiedSettings,
132 instanceId: ProviderInstanceId,
133): { readonly hiddenModels: ReadonlyArray<string>; readonly modelOrder: ReadonlyArray<string> } {
134 return (
135 settings.providerModelPreferences?.[instanceId] ?? {
136 hiddenModels: [],
137 modelOrder: [],
138 }
139 );
141​
142function applyInstanceModelPreferences(
143 options: ReadonlyArray<AppModelOption>,
144 preferences: {
145 readonly hiddenModels: ReadonlyArray<string>;
146 readonly modelOrder: ReadonlyArray<string>;
147 },
148): AppModelOption[] {
149 const hiddenModels = new Set(preferences.hiddenModels);
150 return sortModelsForProviderInstance(
151 options.filter((option) => option.isCustom || !hiddenModels.has(option.slug)),
152 { modelOrder: preferences.modelOrder },
153 );
155​
156function normalizeCustomModelEntries(
157 models: ReadonlyArray<CustomModelDefinition>,
158 builtInModelSlugs: ReadonlySet<string>,
159): CustomModelDefinition[] {
160 const normalizedModels: CustomModelDefinition[] = [];
161 const seen = new Set<string>();
162​
163 for (const candidate of models) {
164 if (
165 candidate.slug.length > MAX_CUSTOM_MODEL_LENGTH ||
166 builtInModelSlugs.has(candidate.slug) ||
167 seen.has(candidate.slug)
168 ) {
169 continue;
170 }
171​
172 seen.add(candidate.slug);
173 normalizedModels.push(candidate);
174 if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
175 break;
176 }
177 }
178​
179 return normalizedModels;
181​
182function 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 entry of normalizeCustomModelEntries(customModels, builtInModelSlugs)) {
209 if (seen.has(entry.slug)) {
210 continue;
211 }
212​
213 seen.add(entry.slug);
214 options.push({ slug: entry.slug, name: entry.name, isCustom: true });
215 }
216​
217 const preferences = readInstanceModelPreferences(settings, defaultInstanceId);
218 return appendUnavailableDynamicModelSelection(
219 applyInstanceModelPreferences(options, preferences),
220 rawModels,
221 provider,
222 selectedModel,
223 preferences.hiddenModels,
224 );
226​
227/**
228 * Instance-scoped variant of {@link getAppModelOptions}. Built-in models
229 * come from the instance's own `entry.models` snapshot (rather than the
230 * first-matching-kind fallback in `getProviderModels`), so each custom
231 * instance gets the precise model list its driver reported. Custom model
232 * slugs come from the instance's own `providerInstances[id].config.customModels`
233 * when present, falling back to the legacy per-kind
234 * `settings.providers[driverKind].customModels` bucket for default
235 * instances only. This keeps two instances of the same kind from leaking
236 * custom slugs into each other. Custom rows reported by the server are
237 * ignored so a slug removed in Settings disappears without waiting for the
238 * next provider probe.
239 */
240export function getAppModelOptionsForInstance(
241 settings: UnifiedSettings,
242 entry: ProviderInstanceEntry,
243 selectedModel?: string | null,
244): AppModelOption[] {
245 const options: AppModelOption[] = entry.models
246 .filter((model) => !model.isCustom)
247 .map(toAppModelOption);
248 const seen = new Set(options.map((option) => option.slug));
249 const builtInModelSlugs = new Set(
250 Arr.filterMap(entry.models, (model) =>
251 model.isCustom ? Result.failVoid : Result.succeed(model.slug),
252 ),
253 );
254​
255 const customModels = readInstanceCustomModels(settings, entry.instanceId, entry.driverKind);
256 for (const custom of normalizeCustomModelEntries(customModels, builtInModelSlugs)) {
257 if (seen.has(custom.slug)) {
258 continue;
259 }
260​
261 seen.add(custom.slug);
262 options.push({ slug: custom.slug, name: custom.name, isCustom: true });
263 }
264​
265 const preferences = readInstanceModelPreferences(settings, entry.instanceId);
266 return appendUnavailableDynamicModelSelection(
267 applyInstanceModelPreferences(options, preferences),
268 entry.models,
269 entry.driverKind,
270 selectedModel,
271 preferences.hiddenModels,
272 );
274​
275export function resolveAppModelSelection(
276 provider: ProviderDriverKind,
277 settings: UnifiedSettings,
278 providers: ReadonlyArray<ServerProvider>,
279 selectedModel: string | null | undefined,
280): string {
281 const resolvedProvider = resolveSelectableProvider(providers, provider);
282 const options = getAppModelOptions(settings, providers, resolvedProvider, selectedModel);
283 return (
284 resolveSelectableModel(resolvedProvider, selectedModel, options) ??
285 getDefaultServerModel(providers, resolvedProvider)
286 );
288​
289export function resolveAppModelSelectionForInstance(
290 instanceId: ProviderInstanceId,
291 settings: UnifiedSettings,
292 providers: ReadonlyArray<ServerProvider>,
293 selectedModel: string | null | undefined,
294 resolutionOptions?: { readonly preserveUnavailableSelection?: boolean },
295): string | null {
296 const entry = deriveProviderInstanceEntries(providers).find(
297 (candidate) => candidate.instanceId === instanceId,
298 );
299 if (!entry) return null;
300 const options = getAppModelOptionsForInstance(
301 settings,
302 entry,
303 resolutionOptions?.preserveUnavailableSelection ? selectedModel : null,
304 );
305 const resolvedSelection = resolveSelectableModel(entry.driverKind, selectedModel, options);
306 if (resolvedSelection) {
307 return resolvedSelection;
308 }
309 if (
310 resolutionOptions?.preserveUnavailableSelection &&
311 (entry.driverKind === "opencode" || entry.driverKind === "antigravity")
312 ) {
313 const unavailableSelection = normalizeCustomModelSlug(selectedModel);
314 const hiddenModels = readInstanceModelPreferences(settings, entry.instanceId).hiddenModels;
315 if (
316 unavailableSelection &&
317 !hiddenModels.includes(unavailableSelection) &&
318 resolveSelectableModel(entry.driverKind, selectedModel, entry.models) === null &&
319 (entry.driverKind !== "antigravity" || unavailableSelection !== ANTIGRAVITY_DEFAULT_MODEL)
320 ) {
321 return unavailableSelection;
322 }
323 }
324 return options.find((option) => option.isDefault)?.slug ?? options[0]?.slug ?? null;
326​
327/**
328 * Instance-keyed model options map. Each configured instance gets its own
329 * option list so the model picker can show the same driver's built-in and
330 * custom instances side by side without collapsing them.
331 */
332export function getCustomModelOptionsByInstance(
333 settings: UnifiedSettings,
334 providers: ReadonlyArray<ServerProvider>,
335 selectedInstanceId?: ProviderInstanceId | null,
336 selectedModel?: string | null,
337): ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>> {
338 const out = new Map<ProviderInstanceId, ReadonlyArray<ModelEsque>>();
339 for (const entry of deriveProviderInstanceEntries(providers)) {
340 out.set(
341 entry.instanceId,
342 getAppModelOptionsForInstance(
343 settings,
344 entry,
345 entry.instanceId === selectedInstanceId ? selectedModel : null,
346 ),
347 );
348 }
349 return out;
351​
352/**
353 * Drop the opencode "plan" agent option from a stored model selection.
354 * Used when legacy plan mode is turned off so server-side text-generation
355 * tasks (title, branch, PR) cannot keep dispatching the plan agent.
356 */
357export function withoutPlanAgentSelection(
358 selection: ModelSelection | null | undefined,
359): ModelSelection | null | undefined {
360 if (!selection?.options) {
361 return selection;
362 }
363 const options = selection.options.filter(
364 (option) => !(option.id === "agent" && option.value === "plan"),
365 );
366 if (options.length === selection.options.length) {
367 return selection;
368 }
369 return createModelSelection(selection.instanceId, selection.model, options);
371​
372// The dropdown hides the opencode "plan" agent while legacy plan mode is off,
373// but the persisted text-generation selections are only healed when the toggle
374// flips. Users who already have plan mode off and a stored "plan" selection
375// never trip the toggle handler, so resolve the heal once per settings load.
376export function resolvePlanAgentHealPatch(input: {
377 readonly planModeEnabled: boolean;
378 readonly textGenerationModelSelection: ModelSelection | null | undefined;
379 readonly sourceControlWriterModelSelection: ModelSelection | null | undefined;
380}): ServerSettingsPatch | null {
381 if (input.planModeEnabled) {
382 return null;
383 }
384 const healedText = withoutPlanAgentSelection(input.textGenerationModelSelection);
385 const healedSourceControl = withoutPlanAgentSelection(input.sourceControlWriterModelSelection);
386 const patch: ServerSettingsPatch = {
387 ...(healedText && healedText !== input.textGenerationModelSelection
388 ? { textGenerationModelSelection: healedText }
389 : {}),
390 ...(healedSourceControl && healedSourceControl !== input.sourceControlWriterModelSelection
391 ? { sourceControlWriterModelSelection: healedSourceControl }
392 : {}),
393 };
394 return Object.keys(patch).length > 0 ? patch : null;
396​
397export function resolveAppModelSelectionState(
398 settings: UnifiedSettings,
399 providers: ReadonlyArray<ServerProvider>,
400): ModelSelection {
401 const selection = settings.textGenerationModelSelection ?? {
402 instanceId: DEFAULT_TEXT_GENERATION_INSTANCE_ID,
403 model: DEFAULT_TEXT_GENERATION_MODEL,
404 };
405 const supportedProviders = providers.filter(
406 (provider) => provider.supportsTextGeneration !== false,
407 );
408 const entries = deriveProviderInstanceEntries(supportedProviders);
409 const selectedEntry = entries.find(
410 (entry) => entry.instanceId === selection.instanceId && entry.enabled && entry.isAvailable,
411 );
412 const entry =
413 selectedEntry ?? entries.find((candidate) => candidate.enabled && candidate.isAvailable);
414 if (entry) {
415 // When the instance changed due to fallback (e.g. selected instance was disabled),
416 // don't carry over the old instance's model — use the fallback instance's default.
417 const selectedModel = selectedEntry ? selection.model : null;
418 const model =
419 resolveAppModelSelectionForInstance(
420 entry.instanceId,
421 settings,
422 supportedProviders,
423 selectedModel,
424 ) ??
425 entry.models[0]?.slug ??
426 DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[entry.driverKind];
427 if (!model) {
428 return createModelSelection(entry.instanceId, "", []);
429 }
430 const provider = entry.driverKind;
431 const { modelOptionsForDispatch } = getComposerProviderState({
432 provider,
433 model,
434 models: entry.models,
435 modelOptions: selectedEntry ? selection.options : undefined,
436 planModeEnabled: settings.planModeEnabled,
437 });
438​
439 return createModelSelection(entry.instanceId, model, modelOptionsForDispatch);
440 }
441​
442 return NO_PROVIDER_MODEL_SELECTION;