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

modelSelection.ts

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