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