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

modelOptions.ts

256 lines7.9 KB

1import type { MenuAction } from "@react-native-menu/menu";
2import type {
3 ModelCapabilities,
4 ModelSelection,
5 ServerConfig as T3ServerConfig,
6} from "@t3tools/contracts";
7import {
8 buildProviderOptionSelectionsFromDescriptors,
9 getProviderOptionDescriptors,
10} from "@t3tools/shared/model";
11​
12export type ModelOption = {
13 readonly key: string;
14 readonly label: string;
15 readonly subtitle: string;
16 readonly providerKey: string;
17 readonly providerLabel: string;
18 readonly providerDriver: string;
19 readonly isDefault: boolean;
20 readonly isLegacy: boolean;
21 readonly capabilities: ModelCapabilities | null;
22 readonly selection: ModelSelection;
23};
24​
25export type ProviderGroup = {
26 readonly providerKey: string;
27 readonly providerLabel: string;
28 readonly models: ReadonlyArray<ModelOption>;
29};
30​
31function providerDisplayLabel(provider: {
32 readonly displayName?: string | undefined;
33 readonly driver: string;
34 readonly instanceId: string;
35}): string {
36 if (provider.displayName) return provider.displayName;
37 if (provider.driver === "codex") return "Codex";
38 if (provider.driver === "claudeAgent") return "Claude";
39 return provider.instanceId;
41​
42function normalizeSelectionOptions(
43 selection: ModelSelection,
44 capabilities: ModelCapabilities | null,
45): ModelSelection {
46 if (!capabilities) {
47 return selection;
48 }
49 const options = buildProviderOptionSelectionsFromDescriptors(
50 getProviderOptionDescriptors({
51 caps: capabilities,
52 selections: selection.options,
53 }),
54 );
55 return options
56 ? { ...selection, options }
57 : {
58 instanceId: selection.instanceId,
59 model: selection.model,
60 };
62​
63/**
64 * A stored model selection is only usable when its provider instance is
65 * currently enabled, installed, and authenticated on the server. Returns the
66 * selection unchanged when usable, otherwise `null` so callers fall through to
67 * the server's default model. A missing config (environment offline) cannot be
68 * validated, so stored selections pass through untouched.
69 */
70export function resolveSelectableModelSelection(
71 config: T3ServerConfig | null | undefined,
72 selection: ModelSelection | null,
73): ModelSelection | null {
74 if (!selection || !config) {
75 return selection;
76 }
77 const provider = config.providers.find(
78 (candidate) => candidate.instanceId === selection.instanceId,
79 );
80 return provider &&
81 provider.enabled &&
82 provider.installed &&
83 provider.auth.status !== "unauthenticated"
84 ? selection
85 : null;
87​
88/**
89 * Like resolveSelectableModelSelection, but additionally rejects legacy
90 * models. Used for implicit defaults (stored draft, project last-used): a
91 * new thread should never quietly start on a legacy model, so those fall
92 * through to the provider's default instead. Explicit picks in the settings
93 * sheet are unaffected.
94 */
95export function resolveDefaultableModelSelection(
96 config: T3ServerConfig | null | undefined,
97 selection: ModelSelection | null,
98): ModelSelection | null {
99 const usable = resolveSelectableModelSelection(config, selection);
100 if (!usable || !config) {
101 return usable;
102 }
103 const provider = config.providers.find((candidate) => candidate.instanceId === usable.instanceId);
104 const model = provider?.models.find((candidate) => candidate.slug === usable.model);
105 return model?.isLegacy === true ? null : usable;
107​
108export function resolveNewTaskModelSelection(input: {
109 readonly draftSelection: ModelSelection | null;
110 readonly projectDefaultSelection: ModelSelection | null;
111 readonly stickySelection: ModelSelection | null;
112 readonly modelOptions: ReadonlyArray<ModelOption>;
113}): ModelSelection | null {
114 return (
115 input.draftSelection ??
116 input.projectDefaultSelection ??
117 input.stickySelection ??
118 input.modelOptions.find((option) => option.isDefault)?.selection ??
119 input.modelOptions[0]?.selection ??
120 null
121 );
123​
124export function buildModelOptions(
125 config: T3ServerConfig | null | undefined,
126 fallbackModelSelection: ModelSelection | null,
127): ReadonlyArray<ModelOption> {
128 const options = new Map<string, ModelOption>();
129​
130 for (const provider of config?.providers ?? []) {
131 if (!provider.enabled || !provider.installed || provider.auth.status === "unauthenticated") {
132 continue;
133 }
134​
135 const providerLabel = providerDisplayLabel(provider);
136 for (const model of provider.models) {
137 const key = `${provider.instanceId}:${model.slug}`;
138 options.set(key, {
139 key,
140 label: model.name,
141 subtitle: model.subProvider ?? "",
142 providerKey: provider.instanceId,
143 providerLabel,
144 providerDriver: provider.driver,
145 isDefault: model.isDefault === true,
146 isLegacy: model.isLegacy === true,
147 capabilities: model.capabilities,
148 selection: normalizeSelectionOptions(
149 {
150 instanceId: provider.instanceId,
151 model: model.slug,
152 },
153 model.capabilities,
154 ),
155 });
156 }
157 }
158​
159 if (fallbackModelSelection) {
160 const key = `${fallbackModelSelection.instanceId}:${fallbackModelSelection.model}`;
161 const existing = options.get(key);
162 if (existing) {
163 options.set(key, {
164 ...existing,
165 selection: normalizeSelectionOptions(fallbackModelSelection, existing.capabilities),
166 });
167 } else {
168 const providerLabel = fallbackModelSelection.instanceId;
169 options.set(key, {
170 key,
171 label: fallbackModelSelection.model,
172 subtitle: "",
173 providerKey: fallbackModelSelection.instanceId,
174 providerLabel,
175 providerDriver: fallbackModelSelection.instanceId,
176 isDefault: false,
177 isLegacy: false,
178 capabilities: null,
179 selection: fallbackModelSelection,
180 });
181 }
182 }
183​
184 return [...options.values()];
186​
187export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyArray<ProviderGroup> {
188 const groups = new Map<string, { providerLabel: string; models: ModelOption[] }>();
189 for (const option of options) {
190 const existing = groups.get(option.providerKey);
191 if (existing) {
192 existing.models.push(option);
193 } else {
194 groups.set(option.providerKey, {
195 providerLabel: option.providerLabel,
196 models: [option],
197 });
198 }
199 }
200​
201 return [...groups.entries()].map(([providerKey, group]) => ({
202 providerKey,
203 providerLabel: group.providerLabel,
204 models: group.models,
205 }));
207​
208function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction {
209 return {
210 id: `model:${option.key}`,
211 title: option.label,
212 state:
213 option.selection.instanceId === selectedModel?.instanceId &&
214 option.selection.model === selectedModel.model
215 ? "on"
216 : undefined,
217 };
219​
220export function buildModelMenuActions(
221 groups: ReadonlyArray<ProviderGroup>,
222 selectedModel: ModelSelection | null,
223): MenuAction[] {
224 return groups.flatMap((group) => {
225 const currentModels = group.models.filter((model) => !model.isLegacy);
226 const legacyModels = group.models.filter((model) => model.isLegacy);
227 const selected = group.models.find(
228 (model) =>
229 model.selection.instanceId === selectedModel?.instanceId &&
230 model.selection.model === selectedModel.model,
231 );
232​
233 return [
234 ...(currentModels.length > 0
235 ? [
236 {
237 id: `provider:${group.providerKey}`,
238 title: group.providerLabel,
239 subtitle: selected && !selected.isLegacy ? selected.label : undefined,
240 subactions: currentModels.map((option) => modelMenuAction(option, selectedModel)),
241 },
242 ]
243 : []),
244 ...(legacyModels.length > 0
245 ? [
246 {
247 id: `legacy-models:${group.providerKey}`,
248 title: `${group.providerLabel} legacy models`,
249 subtitle: selected?.isLegacy ? selected.label : undefined,
250 subactions: legacyModels.map((option) => modelMenuAction(option, selectedModel)),
251 },
252 ]
253 : []),
254 ];
255 });