Open History to see the last commit
1import {
2 type CustomModelSetting,
3 MODEL_SLUG_ALIASES_BY_PROVIDER,
4 ModelCapabilities,
5 type ModelSelection,
6 ProviderDriverKind,
7 ProviderInstanceId,
8 type ProviderOptionDescriptor,
9 type ProviderOptionSelection,
10} from "@t3tools/contracts";
11import * as Option from "effect/Option";
12import * as Schema from "effect/Schema";
13import { copySorted } from "./Array.ts";
14
15const DEFAULT_PROVIDER_DRIVER_KIND = ProviderDriverKind.make("codex");
16
17export interface SelectableModelOption {
18 slug: string;
19 name: string;
20 aliases?: ReadonlyArray<string> | undefined;
21}
22
23export function createModelCapabilities(input: {
24 optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
25}): ModelCapabilities {
26 return {
27 optionDescriptors: input.optionDescriptors.map(cloneDescriptor),
28 };
29}
30
31function getRawSelectionValueById(
32 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
33 id: string,
34): string | boolean | undefined {
35 const selection = selections?.find((candidate) => candidate.id === id);
36 return selection?.value;
37}
38
39export function getProviderOptionSelectionValue(
40 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
41 id: string,
42): string | boolean | undefined {
43 return getRawSelectionValueById(selections, id);
44}
45
46export function getProviderOptionStringSelectionValue(
47 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
48 id: string,
49): string | undefined {
50 const value = getProviderOptionSelectionValue(selections, id);
51 return typeof value === "string" ? value : undefined;
52}
53
54export function getProviderOptionBooleanSelectionValue(
55 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
56 id: string,
57): boolean | undefined {
58 const value = getProviderOptionSelectionValue(selections, id);
59 return typeof value === "boolean" ? value : undefined;
60}
61
62export function getModelSelectionStringOptionValue(
63 modelSelection: ModelSelection | null | undefined,
64 id: string,
65): string | undefined {
66 return getProviderOptionStringSelectionValue(modelSelection?.options, id);
67}
68
69export function getModelSelectionBooleanOptionValue(
70 modelSelection: ModelSelection | null | undefined,
71 id: string,
72): boolean | undefined {
73 return getProviderOptionBooleanSelectionValue(modelSelection?.options, id);
74}
75
76function canonicalModelSelectionOptions(
77 modelSelection: ModelSelection,
78): ReadonlyArray<readonly [id: string, value: string | boolean]> {
79 return copySorted(
80 (modelSelection.options ?? []).map(
81 (selection): readonly [id: string, value: string | boolean] => [
82 selection.id,
83 selection.value,
84 ],
85 ),
86 (
87 [leftId, leftValue]: readonly [id: string, value: string | boolean],
88 [rightId, rightValue]: readonly [id: string, value: string | boolean],
89 ) => {
90 const idOrder = leftId.localeCompare(rightId);
91 return idOrder !== 0 ? idOrder : String(leftValue).localeCompare(String(rightValue));
92 },
93 );
94}
95
96/**
97 * Compares the complete provider selection while treating option ordering and
98 * an omitted empty option list as presentation details.
99 */
100export function modelSelectionsEqual(left: ModelSelection, right: ModelSelection): boolean {
101 if (left.instanceId !== right.instanceId || left.model !== right.model) {
102 return false;
103 }
104 const leftOptions = canonicalModelSelectionOptions(left);
105 const rightOptions = canonicalModelSelectionOptions(right);
106 return (
107 leftOptions.length === rightOptions.length &&
108 leftOptions.every(
109 ([id, value], index) => id === rightOptions[index]?.[0] && value === rightOptions[index]?.[1],
110 )
111 );
112}
113
114function resolveDescriptorChoiceValue(
115 descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>,
116 raw: string | null | undefined,
117): string | undefined {
118 const trimmed = trimOrNull(raw);
119 if (!trimmed) {
120 return descriptor.currentValue ?? descriptor.options.find((option) => option.isDefault)?.id;
121 }
122 if (descriptor.options.length === 0) {
123 return trimmed;
124 }
125 if (
126 descriptor.promptInjectedValues?.includes(trimmed) &&
127 descriptor.options.some((option) => option.id === trimmed)
128 ) {
129 return descriptor.options.find((option) => option.isDefault)?.id;
130 }
131 if (descriptor.options.some((option) => option.id === trimmed)) {
132 return trimmed;
133 }
134 return descriptor.currentValue ?? descriptor.options.find((option) => option.isDefault)?.id;
135}
136
137function cloneDescriptor(descriptor: ProviderOptionDescriptor): ProviderOptionDescriptor {
138 return descriptor.type === "select"
139 ? {
140 ...descriptor,
141 options: [...descriptor.options],
142 ...(descriptor.promptInjectedValues
143 ? { promptInjectedValues: [...descriptor.promptInjectedValues] }
144 : {}),
145 }
146 : { ...descriptor };
147}
148
149function cloneSelection(selection: ProviderOptionSelection): ProviderOptionSelection {
150 return { ...selection };
151}
152
153function withDescriptorCurrentValue(
154 descriptor: ProviderOptionDescriptor,
155 rawCurrentValue: string | boolean | undefined,
156): ProviderOptionDescriptor {
157 if (descriptor.type === "boolean") {
158 if (typeof rawCurrentValue === "boolean") {
159 return {
160 ...descriptor,
161 currentValue: rawCurrentValue,
162 };
163 }
164 return descriptor;
165 }
166 const currentValue =
167 typeof rawCurrentValue === "string"
168 ? resolveDescriptorChoiceValue(descriptor, rawCurrentValue)
169 : resolveDescriptorChoiceValue(descriptor, descriptor.currentValue);
170 if (!currentValue) {
171 const { currentValue: _unusedCurrentValue, ...rest } = descriptor;
172 return rest;
173 }
174 return {
175 ...descriptor,
176 currentValue,
177 };
178}
179
180export function getProviderOptionDescriptors(input: {
181 caps: ModelCapabilities;
182 selections?: ReadonlyArray<ProviderOptionSelection> | null | undefined;
183}): ReadonlyArray<ProviderOptionDescriptor> {
184 const { caps, selections } = input;
185 const baseDescriptors = (caps.optionDescriptors ?? []).map(cloneDescriptor);
186
187 return baseDescriptors.map((descriptor) =>
188 withDescriptorCurrentValue(
189 descriptor,
190 getRawSelectionValueById(selections, descriptor.id) ?? descriptor.currentValue,
191 ),
192 );
193}
194
195export function getProviderOptionCurrentValue(
196 descriptor: ProviderOptionDescriptor | null | undefined,
197): string | boolean | undefined {
198 if (!descriptor) {
199 return undefined;
200 }
201 if (descriptor.type === "boolean") {
202 return descriptor.currentValue;
203 }
204 if (descriptor.currentValue) {
205 return descriptor.currentValue;
206 }
207 return descriptor.options.find((option) => option.isDefault)?.id;
208}
209
210export function getProviderOptionCurrentLabel(
211 descriptor: ProviderOptionDescriptor | null | undefined,
212): string | undefined {
213 if (!descriptor) {
214 return undefined;
215 }
216 if (descriptor.type === "boolean") {
217 return typeof descriptor.currentValue === "boolean"
218 ? descriptor.currentValue
219 ? "On"
220 : "Off"
221 : undefined;
222 }
223 const currentValue = getProviderOptionCurrentValue(descriptor);
224 if (typeof currentValue !== "string") {
225 return undefined;
226 }
227 return descriptor.options.find((option) => option.id === currentValue)?.label;
228}
229
230export function buildProviderOptionSelectionsFromDescriptors(
231 descriptors: ReadonlyArray<ProviderOptionDescriptor> | null | undefined,
232): Array<ProviderOptionSelection> | undefined {
233 if (!descriptors || descriptors.length === 0) {
234 return undefined;
235 }
236
237 const nextSelections: Array<ProviderOptionSelection> = [];
238
239 for (const descriptor of descriptors) {
240 const value = getProviderOptionCurrentValue(descriptor);
241 if (typeof value === "string" || typeof value === "boolean") {
242 nextSelections.push({ id: descriptor.id, value });
243 }
244 }
245
246 return nextSelections.length > 0 ? nextSelections : undefined;
247}
248
249export function buildExplicitProviderOptionSelectionsFromDescriptors(
250 descriptors: ReadonlyArray<ProviderOptionDescriptor> | null | undefined,
251 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
252): Array<ProviderOptionSelection> | undefined {
253 if (!selections || selections.length === 0) {
254 return undefined;
255 }
256 const explicitIds = new Set(selections.map((selection) => selection.id));
257 const normalized = buildProviderOptionSelectionsFromDescriptors(descriptors)?.filter(
258 (selection) => explicitIds.has(selection.id),
259 );
260 return normalized && normalized.length > 0 ? normalized : undefined;
261}
262
263export function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean {
264 return typeof text === "string" && /\bultrathink\b/i.test(text);
265}
266
267export function normalizeModelSlug(
268 model: string | null | undefined,
269 provider: ProviderDriverKind = DEFAULT_PROVIDER_DRIVER_KIND,
270): string | null {
271 const trimmed = normalizeCustomModelSlug(model);
272 if (!trimmed) {
273 return null;
274 }
275
276 const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] ?? {};
277 const aliased = Object.prototype.hasOwnProperty.call(aliases, trimmed)
278 ? aliases[trimmed]
279 : undefined;
280 return typeof aliased === "string" ? aliased : trimmed;
281}
282
283/** Custom model identifiers are provider-owned, so only trim them; never expand aliases. */
284export function normalizeCustomModelSlug(model: string | null | undefined): string | null {
285 if (typeof model !== "string") {
286 return null;
287 }
288
289 return model.trim() || null;
290}
291
292/** A custom model setting with its optional fields resolved. */
293export interface CustomModelDefinition {
294 readonly slug: string;
295 readonly name: string;
296 readonly capabilities: ModelCapabilities | null;
297}
298
299const decodeCustomModelCapabilities = Schema.decodeUnknownOption(ModelCapabilities);
300
301/**
302 * Read a `customModels` setting into resolved definitions. Accepts the typed
303 * union as well as the opaque `providerInstances[id].config` blob clients see,
304 * so it tolerates bare slugs, malformed rows, and unparseable capabilities
305 * (dropped rather than failing the whole list). Slugs are trimmed and
306 * deduplicated, first occurrence wins; `name` falls back to the slug.
307 */
308export function readCustomModelEntries(value: unknown): CustomModelDefinition[] {
309 if (!Array.isArray(value)) return [];
310 const entries: CustomModelDefinition[] = [];
311 const seen = new Set<string>();
312 for (const raw of value) {
313 const record =
314 typeof raw === "string"
315 ? { slug: raw }
316 : raw !== null && typeof raw === "object"
317 ? (raw as { slug?: unknown; name?: unknown; capabilities?: unknown })
318 : null;
319 if (!record) continue;
320 const slug = normalizeCustomModelSlug(typeof record.slug === "string" ? record.slug : null);
321 if (!slug || seen.has(slug)) continue;
322 seen.add(slug);
323 const name =
324 (typeof record.name === "string" ? normalizeCustomModelSlug(record.name) : null) ?? slug;
325 const capabilities =
326 record.capabilities === undefined || record.capabilities === null
327 ? null
328 : Option.getOrNull(decodeCustomModelCapabilities(record.capabilities));
329 entries.push({
330 slug,
331 name,
332 capabilities: capabilities
333 ? createModelCapabilities({ optionDescriptors: capabilities.optionDescriptors ?? [] })
334 : null,
335 });
336 }
337 return entries;
338}
339
340/** Slugs of a `customModels` setting, in stored order. */
341export function readCustomModelSlugs(value: unknown): string[] {
342 return readCustomModelEntries(value).map((entry) => entry.slug);
343}
344
345/**
346 * Write a definition back to the compact stored shape: a bare slug when it
347 * carries nothing custom, otherwise an entry with only the set fields.
348 */
349export function toCustomModelSetting(entry: CustomModelDefinition): CustomModelSetting {
350 const descriptors = entry.capabilities?.optionDescriptors ?? [];
351 const name = entry.name !== entry.slug ? entry.name : undefined;
352 if (!name && descriptors.length === 0) return entry.slug;
353 return {
354 slug: entry.slug,
355 ...(name ? { name } : {}),
356 ...(descriptors.length > 0
357 ? { capabilities: createModelCapabilities({ optionDescriptors: descriptors }) }
358 : {}),
359 };
360}
361
362export function resolveSelectableModel(
363 provider: ProviderDriverKind,
364 value: string | null | undefined,
365 options: ReadonlyArray<SelectableModelOption>,
366): string | null {
367 if (typeof value !== "string") {
368 return null;
369 }
370
371 const trimmed = value.trim();
372 if (!trimmed) {
373 return null;
374 }
375
376 const direct = options.find((option) => option.slug === trimmed);
377 if (direct) {
378 return direct.slug;
379 }
380
381 const byName = options.find((option) => option.name.toLowerCase() === trimmed.toLowerCase());
382 if (byName) {
383 return byName.slug;
384 }
385
386 const byAlias = options.find((option) =>
387 option.aliases?.some((alias) => alias.toLowerCase() === trimmed.toLowerCase()),
388 );
389 if (byAlias) {
390 return byAlias.slug;
391 }
392
393 const normalized = normalizeModelSlug(trimmed, provider);
394 if (!normalized) {
395 return null;
396 }
397
398 const resolved = options.find((option) => option.slug === normalized);
399 return resolved ? resolved.slug : null;
400}
401
402/** Trim a string, returning null for empty/missing values. */
403export function trimOrNull<T extends string>(value: T | null | undefined): T | null {
404 if (typeof value !== "string") return null;
405 const trimmed = value.trim() as T;
406 return trimmed || null;
407}
408
409function cloneSelections(
410 selections: ReadonlyArray<ProviderOptionSelection>,
411): Array<ProviderOptionSelection> {
412 return selections.map(cloneSelection);
413}
414
415export function createModelSelection(
416 instanceId: ProviderInstanceId,
417 model: string,
418 options?: ReadonlyArray<ProviderOptionSelection> | null,
419): ModelSelection {
420 const selections = options ? cloneSelections(options) : [];
421 const base: ModelSelection = {
422 instanceId,
423 model,
424 };
425 return selections.length > 0 ? { ...base, options: selections } : base;
426}
427
428/**
429 * Returns the effort value if it is a prompt-injected value according to
430 * any select descriptor in the given capabilities, or null otherwise.
431 *
432 * Unlike a single `find`, this checks every descriptor so that the
433 * correct descriptor's `promptInjectedValues` list is consulted even when
434 * multiple select descriptors exist.
435 */
436export function resolvePromptInjectedEffort(
437 caps: ModelCapabilities,
438 rawEffort: string | null | undefined,
439): string | null {
440 const trimmed = trimOrNull(rawEffort);
441 if (!trimmed) return null;
442 const descriptors = getProviderOptionDescriptors({ caps });
443 for (const descriptor of descriptors) {
444 if (descriptor.type === "select" && descriptor.promptInjectedValues?.includes(trimmed)) {
445 return trimmed;
446 }
447 }
448 return null;
449}
450
451export function applyClaudePromptEffortPrefix(
452 text: string,
453 effort: string | null | undefined,
454): string {
455 const trimmed = text.trim();
456 if (!trimmed) {
457 return trimmed;
458 }
459 // Prefixing a slash command turns it into plain prose, so Claude never
460 // runs it. Command names come from arbitrary file names ("/deploy.prod",
461 // "/plugin:skill"), so accept any first token without a second slash;
462 // absolute paths like "/home/theo/app.ts" keep the prefix.
463 if (effort !== "ultrathink" || /^\/[^\s/]+(?:\s|$)/u.test(trimmed)) {
464 return trimmed;
465 }
466 if (trimmed.startsWith("Ultrathink:")) {
467 return trimmed;
468 }
469 return `Ultrathink:\n${trimmed}`;
470}