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 normalizeModelSlug(
283 model: string | null | undefined,
284 provider: ProviderDriverKind = DEFAULT_PROVIDER_DRIVER_KIND,
285): string | null {
286 const trimmed = normalizeCustomModelSlug(model);
287 if (!trimmed) {
288 return null;
289 }
290
291 const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] ?? {};
292 const aliased = Object.prototype.hasOwnProperty.call(aliases, trimmed)
293 ? aliases[trimmed]
294 : undefined;
295 return typeof aliased === "string" ? aliased : trimmed;
296}
297
298/** Custom model identifiers are provider-owned, so only trim them; never expand aliases. */
299export function normalizeCustomModelSlug(model: string | null | undefined): string | null {
300 if (typeof model !== "string") {
301 return null;
302 }
303
304 return model.trim() || null;
305}
306
307/** A custom model setting with its optional fields resolved. */
308export interface CustomModelDefinition {
309 readonly slug: string;
310 readonly name: string;
311 readonly capabilities: ModelCapabilities | null;
312}
313
314const decodeCustomModelCapabilities = Schema.decodeUnknownOption(ModelCapabilities);
315
316/**
317 * Read a `customModels` setting into resolved definitions. Accepts the typed
318 * union as well as the opaque `providerInstances[id].config` blob clients see,
319 * so it tolerates bare slugs, malformed rows, and unparseable capabilities
320 * (dropped rather than failing the whole list). Slugs are trimmed and
321 * deduplicated, first occurrence wins; `name` falls back to the slug.
322 */
323export function readCustomModelEntries(value: unknown): CustomModelDefinition[] {
324 if (!Array.isArray(value)) return [];
325 const entries: CustomModelDefinition[] = [];
326 const seen = new Set<string>();
327 for (const raw of value) {
328 const record =
329 typeof raw === "string"
330 ? { slug: raw }
331 : raw !== null && typeof raw === "object"
332 ? (raw as { slug?: unknown; name?: unknown; capabilities?: unknown })
333 : null;
334 if (!record) continue;
335 const slug = normalizeCustomModelSlug(typeof record.slug === "string" ? record.slug : null);
336 if (!slug || seen.has(slug)) continue;
337 seen.add(slug);
338 const name =
339 (typeof record.name === "string" ? normalizeCustomModelSlug(record.name) : null) ?? slug;
340 const capabilities =
341 record.capabilities === undefined || record.capabilities === null
342 ? null
343 : Option.getOrNull(decodeCustomModelCapabilities(record.capabilities));
344 entries.push({
345 slug,
346 name,
347 capabilities: capabilities
348 ? createModelCapabilities({ optionDescriptors: capabilities.optionDescriptors ?? [] })
349 : null,
350 });
351 }
352 return entries;
353}
354
355/**
356 * Write a definition back to the compact stored shape: a bare slug when it
357 * carries nothing custom, otherwise an entry with only the set fields.
358 */
359export function toCustomModelSetting(entry: CustomModelDefinition): CustomModelSetting {
360 const descriptors = entry.capabilities?.optionDescriptors ?? [];
361 const name = entry.name !== entry.slug ? entry.name : undefined;
362 if (!name && descriptors.length === 0) return entry.slug;
363 return {
364 slug: entry.slug,
365 ...(name ? { name } : {}),
366 ...(descriptors.length > 0
367 ? { capabilities: createModelCapabilities({ optionDescriptors: descriptors }) }
368 : {}),
369 };
370}
371
372export function resolveSelectableModel(
373 provider: ProviderDriverKind,
374 value: string | null | undefined,
375 options: ReadonlyArray<SelectableModelOption>,
376): string | null {
377 if (typeof value !== "string") {
378 return null;
379 }
380
381 const trimmed = value.trim();
382 if (!trimmed) {
383 return null;
384 }
385
386 const direct = options.find((option) => option.slug === trimmed);
387 if (direct) {
388 return direct.slug;
389 }
390
391 const byName = options.find((option) => option.name.toLowerCase() === trimmed.toLowerCase());
392 if (byName) {
393 return byName.slug;
394 }
395
396 const byAlias = options.find((option) =>
397 option.aliases?.some((alias) => alias.toLowerCase() === trimmed.toLowerCase()),
398 );
399 if (byAlias) {
400 return byAlias.slug;
401 }
402
403 const normalized = normalizeModelSlug(trimmed, provider);
404 if (!normalized) {
405 return null;
406 }
407
408 const resolved = options.find((option) => option.slug === normalized);
409 return resolved ? resolved.slug : null;
410}
411
412/** Trim a string, returning null for empty/missing values. */
413function trimOrNull<T extends string>(value: T | null | undefined): T | null {
414 if (typeof value !== "string") return null;
415 const trimmed = value.trim() as T;
416 return trimmed || null;
417}
418
419function cloneSelections(
420 selections: ReadonlyArray<ProviderOptionSelection>,
421): Array<ProviderOptionSelection> {
422 return selections.map(cloneSelection);
423}
424
425export function createModelSelection(
426 instanceId: ProviderInstanceId,
427 model: string,
428 options?: ReadonlyArray<ProviderOptionSelection> | null,
429): ModelSelection {
430 const selections = options ? cloneSelections(options) : [];
431 const base: ModelSelection = {
432 instanceId,
433 model,
434 };
435 return selections.length > 0 ? { ...base, options: selections } : base;
436}
437
438/**
439 * Returns the effort value if it is a prompt-injected value according to
440 * any select descriptor in the given capabilities, or null otherwise.
441 *
442 * Unlike a single `find`, this checks every descriptor so that the
443 * correct descriptor's `promptInjectedValues` list is consulted even when
444 * multiple select descriptors exist.
445 */
446export function resolvePromptInjectedEffort(
447 caps: ModelCapabilities,
448 rawEffort: string | null | undefined,
449): string | null {
450 const trimmed = trimOrNull(rawEffort);
451 if (!trimmed) return null;
452 const descriptors = getProviderOptionDescriptors({ caps });
453 for (const descriptor of descriptors) {
454 if (descriptor.type === "select" && descriptor.promptInjectedValues?.includes(trimmed)) {
455 return trimmed;
456 }
457 }
458 return null;
459}
460
461export function applyClaudePromptEffortPrefix(
462 text: string,
463 effort: string | null | undefined,
464): string {
465 const trimmed = text.trim();
466 if (!trimmed) {
467 return trimmed;
468 }
469 // Prefixing a slash command turns it into plain prose, so Claude never
470 // runs it. Command names come from arbitrary file names ("/deploy.prod",
471 // "/plugin:skill"), so accept any first token without a second slash;
472 // absolute paths like "/home/theo/app.ts" keep the prefix.
473 if (effort !== "ultrathink" || /^\/[^\s/]+(?:\s|$)/u.test(trimmed)) {
474 return trimmed;
475 }
476 if (trimmed.startsWith("Ultrathink:")) {
477 return trimmed;
478 }
479 return `Ultrathink:\n${trimmed}`;
480}