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
228/** Compare Codex model families without changing provider-owned dispatch identifiers. */
229export function codexModelFamily(slug: string): string {
230 return slug.startsWith("openai.gpt-") ? slug.slice("openai.".length) : slug;
231}
232
233export function normalizeModelSlug(
234 model: string | null | undefined,
235 provider: ProviderDriverKind = DEFAULT_PROVIDER_DRIVER_KIND,
236): string | null {
237 const trimmed = normalizeCustomModelSlug(model);
238 if (!trimmed) {
239 return null;
240 }
241
242 const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] ?? {};
243 const aliased = Object.prototype.hasOwnProperty.call(aliases, trimmed)
244 ? aliases[trimmed]
245 : undefined;
246 return typeof aliased === "string" ? aliased : trimmed;
247}
248
249/** Custom model identifiers are provider-owned, so only trim them; never expand aliases. */
250export function normalizeCustomModelSlug(model: string | null | undefined): string | null {
251 if (typeof model !== "string") {
252 return null;
253 }
254
255 return model.trim() || null;
256}
257
258/** A custom model setting with its optional fields resolved. */
259export interface CustomModelDefinition {
260 readonly slug: string;
261 readonly name: string;
262 readonly capabilities: ModelCapabilities | null;
263}
264
265const decodeCustomModelCapabilities = Schema.decodeUnknownOption(ModelCapabilities);
266
267/**
268 * Read a `customModels` setting into resolved definitions. Accepts the typed
269 * union as well as the opaque `providerInstances[id].config` blob clients see,
270 * so it tolerates bare slugs, malformed rows, and unparseable capabilities
271 * (dropped rather than failing the whole list). Slugs are trimmed and
272 * deduplicated, first occurrence wins; `name` falls back to the slug.
273 */
274export function readCustomModelEntries(value: unknown): CustomModelDefinition[] {
275 if (!Array.isArray(value)) return [];
276 const entries: CustomModelDefinition[] = [];
277 const seen = new Set<string>();
278 for (const raw of value) {
279 const record =
280 typeof raw === "string"
281 ? { slug: raw }
282 : raw !== null && typeof raw === "object"
283 ? (raw as { slug?: unknown; name?: unknown; capabilities?: unknown })
284 : null;
285 if (!record) continue;
286 const slug = normalizeCustomModelSlug(typeof record.slug === "string" ? record.slug : null);
287 if (!slug || seen.has(slug)) continue;
288 seen.add(slug);
289 const name =
290 (typeof record.name === "string" ? normalizeCustomModelSlug(record.name) : null) ?? slug;
291 const capabilities =
292 record.capabilities === undefined || record.capabilities === null
293 ? null
294 : Option.getOrNull(decodeCustomModelCapabilities(record.capabilities));
295 entries.push({
296 slug,
297 name,
298 capabilities: capabilities
299 ? createModelCapabilities({ optionDescriptors: capabilities.optionDescriptors ?? [] })
300 : null,
301 });
302 }
303 return entries;
304}
305
306/**
307 * Write a definition back to the compact stored shape: a bare slug when it
308 * carries nothing custom, otherwise an entry with only the set fields.
309 */
310export function toCustomModelSetting(entry: CustomModelDefinition): CustomModelSetting {
311 const descriptors = entry.capabilities?.optionDescriptors ?? [];
312 const name = entry.name !== entry.slug ? entry.name : undefined;
313 if (!name && descriptors.length === 0) return entry.slug;
314 return {
315 slug: entry.slug,
316 ...(name ? { name } : {}),
317 ...(descriptors.length > 0
318 ? { capabilities: createModelCapabilities({ optionDescriptors: descriptors }) }
319 : {}),
320 };
321}
322
323export function resolveSelectableModel(
324 provider: ProviderDriverKind,
325 value: string | null | undefined,
326 options: ReadonlyArray<SelectableModelOption>,
327): string | null {
328 if (typeof value !== "string") {
329 return null;
330 }
331
332 const trimmed = value.trim();
333 if (!trimmed) {
334 return null;
335 }
336
337 const direct = options.find((option) => option.slug === trimmed);
338 if (direct) {
339 return direct.slug;
340 }
341
342 const byName = options.find((option) => option.name.toLowerCase() === trimmed.toLowerCase());
343 if (byName) {
344 return byName.slug;
345 }
346
347 const byAlias = options.find((option) =>
348 option.aliases?.some((alias) => alias.toLowerCase() === trimmed.toLowerCase()),
349 );
350 if (byAlias) {
351 return byAlias.slug;
352 }
353
354 const normalized = normalizeModelSlug(trimmed, provider);
355 if (!normalized) {
356 return null;
357 }
358
359 const resolved = options.find((option) => option.slug === normalized);
360 return resolved ? resolved.slug : null;
361}
362
363/** Trim a string, returning null for empty/missing values. */
364function trimOrNull<T extends string>(value: T | null | undefined): T | null {
365 if (typeof value !== "string") return null;
366 const trimmed = value.trim() as T;
367 return trimmed || null;
368}
369
370function cloneSelections(
371 selections: ReadonlyArray<ProviderOptionSelection>,
372): Array<ProviderOptionSelection> {
373 return selections.map(cloneSelection);
374}
375
376export function createModelSelection(
377 instanceId: ProviderInstanceId,
378 model: string,
379 options?: ReadonlyArray<ProviderOptionSelection> | null,
380): ModelSelection {
381 const selections = options ? cloneSelections(options) : [];
382 const base: ModelSelection = {
383 instanceId,
384 model,
385 };
386 return selections.length > 0 ? { ...base, options: selections } : base;
387}
388
389/**
390 * Returns the effort value if it is a prompt-injected value according to
391 * any select descriptor in the given capabilities, or null otherwise.
392 *
393 * Unlike a single `find`, this checks every descriptor so that the
394 * correct descriptor's `promptInjectedValues` list is consulted even when
395 * multiple select descriptors exist.
396 */
397export function resolvePromptInjectedEffort(
398 caps: ModelCapabilities,
399 rawEffort: string | null | undefined,
400): string | null {
401 const trimmed = trimOrNull(rawEffort);
402 if (!trimmed) return null;
403 const descriptors = getProviderOptionDescriptors({ caps });
404 for (const descriptor of descriptors) {
405 if (descriptor.type === "select" && descriptor.promptInjectedValues?.includes(trimmed)) {
406 return trimmed;
407 }
408 }
409 return null;
410}
411
412export function applyClaudePromptEffortPrefix(
413 text: string,
414 effort: string | null | undefined,
415): string {
416 const trimmed = text.trim();
417 if (!trimmed) {
418 return trimmed;
419 }
420 // Prefixing a slash command turns it into plain prose, so Claude never
421 // runs it. Command names come from arbitrary file names ("/deploy.prod",
422 // "/plugin:skill"), so accept any first token without a second slash;
423 // absolute paths like "/home/theo/app.ts" keep the prefix.
424 if (effort !== "ultrathink" || /^\/[^\s/]+(?:\s|$)/u.test(trimmed)) {
425 return trimmed;
426 }
427 if (trimmed.startsWith("Ultrathink:")) {
428 return trimmed;
429 }
430 return `Ultrathink:\n${trimmed}`;
431}