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

modelSelection.ts

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