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