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