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

model.ts

396 lines11.6 KB

1import {
2 DEFAULT_MODEL,
3 DEFAULT_MODEL_BY_PROVIDER,
4 MODEL_SLUG_ALIASES_BY_PROVIDER,
5 type ModelCapabilities,
6 type ModelSelection,
7 ProviderDriverKind,
8 ProviderInstanceId,
9 type ProviderOptionDescriptor,
10 type ProviderOptionSelection,
11} from "@t3tools/contracts";
12​
13const DEFAULT_PROVIDER_DRIVER_KIND = ProviderDriverKind.make("codex");
14​
15export interface SelectableModelOption {
16 slug: string;
17 name: string;
19​
20export function createModelCapabilities(input: {
21 optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
22}): ModelCapabilities {
23 return {
24 optionDescriptors: input.optionDescriptors.map(cloneDescriptor),
25 };
27​
28function getRawSelectionValueById(
29 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
30 id: string,
31): string | boolean | undefined {
32 const selection = selections?.find((candidate) => candidate.id === id);
33 return selection?.value;
35​
36export function getProviderOptionSelectionValue(
37 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
38 id: string,
39): string | boolean | undefined {
40 return getRawSelectionValueById(selections, id);
42​
43export function getProviderOptionStringSelectionValue(
44 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
45 id: string,
46): string | undefined {
47 const value = getProviderOptionSelectionValue(selections, id);
48 return typeof value === "string" ? value : undefined;
50​
51export function getProviderOptionBooleanSelectionValue(
52 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
53 id: string,
54): boolean | undefined {
55 const value = getProviderOptionSelectionValue(selections, id);
56 return typeof value === "boolean" ? value : undefined;
58​
59export function getModelSelectionOptionValue(
60 modelSelection: ModelSelection | null | undefined,
61 id: string,
62): string | boolean | undefined {
63 return getProviderOptionSelectionValue(modelSelection?.options, id);
65​
66export function getModelSelectionStringOptionValue(
67 modelSelection: ModelSelection | null | undefined,
68 id: string,
69): string | undefined {
70 return getProviderOptionStringSelectionValue(modelSelection?.options, id);
72​
73export function getModelSelectionBooleanOptionValue(
74 modelSelection: ModelSelection | null | undefined,
75 id: string,
76): boolean | undefined {
77 return getProviderOptionBooleanSelectionValue(modelSelection?.options, id);
79​
80function canonicalModelSelectionOptions(
81 modelSelection: ModelSelection,
82): ReadonlyArray<readonly [id: string, value: string | boolean]> {
83 return (modelSelection.options ?? [])
84 .map((selection) => [selection.id, selection.value] as const)
85 .toSorted(([leftId, leftValue], [rightId, rightValue]) => {
86 const idOrder = leftId.localeCompare(rightId);
87 return idOrder !== 0 ? idOrder : String(leftValue).localeCompare(String(rightValue));
88 });
90​
91/**
92 * Compares the complete provider selection while treating option ordering and
93 * an omitted empty option list as presentation details.
94 */
95export function modelSelectionsEqual(left: ModelSelection, right: ModelSelection): boolean {
96 if (left.instanceId !== right.instanceId || left.model !== right.model) {
97 return false;
98 }
99 const leftOptions = canonicalModelSelectionOptions(left);
100 const rightOptions = canonicalModelSelectionOptions(right);
101 return (
102 leftOptions.length === rightOptions.length &&
103 leftOptions.every(
104 ([id, value], index) => id === rightOptions[index]?.[0] && value === rightOptions[index]?.[1],
105 )
106 );
108​
109function resolveDescriptorChoiceValue(
110 descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>,
111 raw: string | null | undefined,
112): string | undefined {
113 const trimmed = trimOrNull(raw);
114 if (!trimmed) {
115 return descriptor.currentValue ?? descriptor.options.find((option) => option.isDefault)?.id;
116 }
117 if (descriptor.options.length === 0) {
118 return trimmed;
119 }
120 if (
121 descriptor.promptInjectedValues?.includes(trimmed) &&
122 descriptor.options.some((option) => option.id === trimmed)
123 ) {
124 return descriptor.options.find((option) => option.isDefault)?.id;
125 }
126 if (descriptor.options.some((option) => option.id === trimmed)) {
127 return trimmed;
128 }
129 return descriptor.currentValue ?? descriptor.options.find((option) => option.isDefault)?.id;
131​
132function cloneDescriptor(descriptor: ProviderOptionDescriptor): ProviderOptionDescriptor {
133 return descriptor.type === "select"
134 ? {
135 ...descriptor,
136 options: [...descriptor.options],
137 ...(descriptor.promptInjectedValues
138 ? { promptInjectedValues: [...descriptor.promptInjectedValues] }
139 : {}),
140 }
141 : { ...descriptor };
143​
144function cloneSelection(selection: ProviderOptionSelection): ProviderOptionSelection {
145 return { ...selection };
147​
148function withDescriptorCurrentValue(
149 descriptor: ProviderOptionDescriptor,
150 rawCurrentValue: string | boolean | undefined,
151): ProviderOptionDescriptor {
152 if (descriptor.type === "boolean") {
153 if (typeof rawCurrentValue === "boolean") {
154 return {
155 ...descriptor,
156 currentValue: rawCurrentValue,
157 };
158 }
159 return descriptor;
160 }
161 const currentValue =
162 typeof rawCurrentValue === "string"
163 ? resolveDescriptorChoiceValue(descriptor, rawCurrentValue)
164 : resolveDescriptorChoiceValue(descriptor, descriptor.currentValue);
165 if (!currentValue) {
166 const { currentValue: _unusedCurrentValue, ...rest } = descriptor;
167 return rest;
168 }
169 return {
170 ...descriptor,
171 currentValue,
172 };
174​
175export function getProviderOptionDescriptors(input: {
176 caps: ModelCapabilities;
177 selections?: ReadonlyArray<ProviderOptionSelection> | null | undefined;
178}): ReadonlyArray<ProviderOptionDescriptor> {
179 const { caps, selections } = input;
180 const baseDescriptors = (caps.optionDescriptors ?? []).map(cloneDescriptor);
181​
182 return baseDescriptors.map((descriptor) =>
183 withDescriptorCurrentValue(
184 descriptor,
185 getRawSelectionValueById(selections, descriptor.id) ?? descriptor.currentValue,
186 ),
187 );
189​
190export function getProviderOptionCurrentValue(
191 descriptor: ProviderOptionDescriptor | null | undefined,
192): string | boolean | undefined {
193 if (!descriptor) {
194 return undefined;
195 }
196 if (descriptor.type === "boolean") {
197 return descriptor.currentValue;
198 }
199 if (descriptor.currentValue) {
200 return descriptor.currentValue;
201 }
202 return descriptor.options.find((option) => option.isDefault)?.id;
204​
205export function getProviderOptionCurrentLabel(
206 descriptor: ProviderOptionDescriptor | null | undefined,
207): string | undefined {
208 if (!descriptor) {
209 return undefined;
210 }
211 if (descriptor.type === "boolean") {
212 return typeof descriptor.currentValue === "boolean"
213 ? descriptor.currentValue
214 ? "On"
215 : "Off"
216 : undefined;
217 }
218 const currentValue = getProviderOptionCurrentValue(descriptor);
219 if (typeof currentValue !== "string") {
220 return undefined;
221 }
222 return descriptor.options.find((option) => option.id === currentValue)?.label;
224​
225export function buildProviderOptionSelectionsFromDescriptors(
226 descriptors: ReadonlyArray<ProviderOptionDescriptor> | null | undefined,
227): Array<ProviderOptionSelection> | undefined {
228 if (!descriptors || descriptors.length === 0) {
229 return undefined;
230 }
231​
232 const nextSelections: Array<ProviderOptionSelection> = [];
233​
234 for (const descriptor of descriptors) {
235 const value = getProviderOptionCurrentValue(descriptor);
236 if (typeof value === "string" || typeof value === "boolean") {
237 nextSelections.push({ id: descriptor.id, value });
238 }
239 }
240​
241 return nextSelections.length > 0 ? nextSelections : undefined;
243​
244export function getModelSelectionOptionDescriptors(
245 modelSelection: ModelSelection | null | undefined,
246 caps?: ModelCapabilities | null | undefined,
247): ReadonlyArray<ProviderOptionDescriptor> {
248 if (!modelSelection) {
249 return [];
250 }
251 if (!caps) {
252 return [];
253 }
254 return getProviderOptionDescriptors({
255 caps,
256 selections: modelSelection.options,
257 });
259​
260export function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean {
261 return typeof text === "string" && /\bultrathink\b/i.test(text);
263​
264export function normalizeModelSlug(
265 model: string | null | undefined,
266 provider: ProviderDriverKind = DEFAULT_PROVIDER_DRIVER_KIND,
267): string | null {
268 if (typeof model !== "string") {
269 return null;
270 }
271​
272 const trimmed = model.trim();
273 if (!trimmed) {
274 return null;
275 }
276​
277 const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] ?? {};
278 const aliased = Object.prototype.hasOwnProperty.call(aliases, trimmed)
279 ? aliases[trimmed]
280 : undefined;
281 return typeof aliased === "string" ? aliased : trimmed;
283​
284export function resolveSelectableModel(
285 provider: ProviderDriverKind,
286 value: string | null | undefined,
287 options: ReadonlyArray<SelectableModelOption>,
288): string | null {
289 if (typeof value !== "string") {
290 return null;
291 }
292​
293 const trimmed = value.trim();
294 if (!trimmed) {
295 return null;
296 }
297​
298 const direct = options.find((option) => option.slug === trimmed);
299 if (direct) {
300 return direct.slug;
301 }
302​
303 const byName = options.find((option) => option.name.toLowerCase() === trimmed.toLowerCase());
304 if (byName) {
305 return byName.slug;
306 }
307​
308 const normalized = normalizeModelSlug(trimmed, provider);
309 if (!normalized) {
310 return null;
311 }
312​
313 const resolved = options.find((option) => option.slug === normalized);
314 return resolved ? resolved.slug : null;
316​
317function resolveModelSlug(model: string | null | undefined, provider: ProviderDriverKind): string {
318 const normalized = normalizeModelSlug(model, provider);
319 if (!normalized) {
320 return DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;
321 }
322 return normalized;
324​
325export function resolveModelSlugForProvider(
326 provider: ProviderDriverKind,
327 model: string | null | undefined,
328): string {
329 return resolveModelSlug(model, provider);
331​
332/** Trim a string, returning null for empty/missing values. */
333export function trimOrNull<T extends string>(value: T | null | undefined): T | null {
334 if (typeof value !== "string") return null;
335 const trimmed = value.trim() as T;
336 return trimmed || null;
338​
339function cloneSelections(
340 selections: ReadonlyArray<ProviderOptionSelection>,
341): Array<ProviderOptionSelection> {
342 return selections.map(cloneSelection);
344​
345export function createModelSelection(
346 instanceId: ProviderInstanceId,
347 model: string,
348 options?: ReadonlyArray<ProviderOptionSelection> | null,
349): ModelSelection {
350 const selections = options ? cloneSelections(options) : [];
351 const base: ModelSelection = {
352 instanceId,
353 model,
354 };
355 return selections.length > 0 ? { ...base, options: selections } : base;
357​
358/**
359 * Returns the effort value if it is a prompt-injected value according to
360 * any select descriptor in the given capabilities, or null otherwise.
361 *
362 * Unlike a single `find`, this checks every descriptor so that the
363 * correct descriptor's `promptInjectedValues` list is consulted even when
364 * multiple select descriptors exist.
365 */
366export function resolvePromptInjectedEffort(
367 caps: ModelCapabilities,
368 rawEffort: string | null | undefined,
369): string | null {
370 const trimmed = trimOrNull(rawEffort);
371 if (!trimmed) return null;
372 const descriptors = getProviderOptionDescriptors({ caps });
373 for (const descriptor of descriptors) {
374 if (descriptor.type === "select" && descriptor.promptInjectedValues?.includes(trimmed)) {
375 return trimmed;
376 }
377 }
378 return null;
380​
381export function applyClaudePromptEffortPrefix(
382 text: string,
383 effort: string | null | undefined,
384): string {
385 const trimmed = text.trim();
386 if (!trimmed) {
387 return trimmed;
388 }
389 if (effort !== "ultrathink") {
390 return trimmed;
391 }
392 if (trimmed.startsWith("Ultrathink:")) {
393 return trimmed;
394 }
395 return `Ultrathink:\n${trimmed}`;