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

modelSelection.ts

432 lines15.5 KB

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