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