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
17export function modelSelectionCommandType(
18 currentInstanceId: ProviderInstanceId,
19 selection: ModelSelection,
20) {
21 return currentInstanceId === selection.instanceId
22 ? ("thread.model-selection.set" as const)
23 : ("provider.switch" as const);
24}
25
26export interface SelectableModelOption {
27 slug: string;
28 name: string;
29 aliases?: ReadonlyArray<string> | undefined;
30}
31
32export function createModelCapabilities(input: {
33 optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
34}): ModelCapabilities {
35 return {
36 optionDescriptors: input.optionDescriptors.map(cloneDescriptor),
37 };
38}
39
40function getRawSelectionValueById(
41 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
42 id: string,
43): string | boolean | undefined {
44 const selection = selections?.find((candidate) => candidate.id === id);
45 return selection?.value;
46}
47
48function getProviderOptionSelectionValue(
49 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
50 id: string,
51): string | boolean | undefined {
52 return getRawSelectionValueById(selections, id);
53}
54
55function getProviderOptionStringSelectionValue(
56 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
57 id: string,
58): string | undefined {
59 const value = getProviderOptionSelectionValue(selections, id);
60 return typeof value === "string" ? value : undefined;
61}
62
63function getProviderOptionBooleanSelectionValue(
64 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
65 id: string,
66): boolean | undefined {
67 const value = getProviderOptionSelectionValue(selections, id);
68 return typeof value === "boolean" ? value : undefined;
69}
70
71export function getModelSelectionStringOptionValue(
72 modelSelection: ModelSelection | null | undefined,
73 id: string,
74): string | undefined {
75 return getProviderOptionStringSelectionValue(modelSelection?.options, id);
76}
77
78export function getModelSelectionBooleanOptionValue(
79 modelSelection: ModelSelection | null | undefined,
80 id: string,
81): boolean | undefined {
82 return getProviderOptionBooleanSelectionValue(modelSelection?.options, id);
83}
84
85function canonicalModelSelectionOptions(
86 modelSelection: ModelSelection,
87): ReadonlyArray<readonly [id: string, value: string | boolean]> {
88 return copySorted(
89 (modelSelection.options ?? []).map(
90 (selection): readonly [id: string, value: string | boolean] => [
91 selection.id,
92 selection.value,
93 ],
94 ),
95 // Stable sort: readers use the first entry for an id, so same-id order must survive.
96 ([leftId], [rightId]) => (leftId < rightId ? -1 : leftId > rightId ? 1 : 0),
97 );
98}
99
100export function modelSelectionsEqual(left: ModelSelection, right: ModelSelection): boolean {
101 if (left.instanceId !== right.instanceId || left.model !== right.model) {
102 return false;
103 }
104 const leftOptions = canonicalModelSelectionOptions(left);
105 const rightOptions = canonicalModelSelectionOptions(right);
106 return (
107 leftOptions.length === rightOptions.length &&
108 leftOptions.every(
109 ([id, value], index) => id === rightOptions[index]?.[0] && value === rightOptions[index]?.[1],
110 )
111 );
112}
113
114/**
115 * Whether a composer's draft model pick is what the thread already runs. Web sends
116 * `fastMode: false` for models with a fast toggle while mobile omits it, so off counts as unset.
117 */
118export function draftModelPickMatchesThread(pick: ModelSelection, thread: ModelSelection): boolean {
119 const withoutFastModeOff = (selection: ModelSelection) => {
120 const fastMode = selection.options?.find((option) => option.id === "fastMode");
121 return createModelSelection(selection.instanceId, selection.model, [
122 ...(selection.options?.filter((option) => option.id !== "fastMode") ?? []),
123 ...(fastMode !== undefined && fastMode.value !== false ? [fastMode] : []),
124 ]);
125 };
126 return modelSelectionsEqual(withoutFastModeOff(pick), withoutFastModeOff(thread));
127}
128
129/** Cursor ACP can default Fast to true; T3 requires a user selection. */
130export function withImplicitFastModeDefault(
131 caps: ModelCapabilities,
132 modelOptions: ReadonlyArray<ProviderOptionSelection> | null | undefined,
133): ReadonlyArray<ProviderOptionSelection> | undefined {
134 const hasExplicitFastMode = modelOptions?.some((selection) => selection.id === "fastMode");
135 if (hasExplicitFastMode) {
136 return modelOptions ?? undefined;
137 }
138 const hasFastModeDescriptor = caps.optionDescriptors?.some(
139 (descriptor) => descriptor.type === "boolean" && descriptor.id === "fastMode",
140 );
141 if (!hasFastModeDescriptor) {
142 return modelOptions ?? undefined;
143 }
144 return [...(modelOptions ?? []), { id: "fastMode", value: false }];
145}
146
147function resolveDescriptorChoiceValue(
148 descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>,
149 raw: string | null | undefined,
150): string | undefined {
151 const trimmed = trimOrNull(raw);
152 if (!trimmed) {
153 return descriptor.currentValue ?? descriptor.options.find((option) => option.isDefault)?.id;
154 }
155 if (descriptor.options.length === 0) {
156 return trimmed;
157 }
158 if (
159 descriptor.promptInjectedValues?.includes(trimmed) &&
160 descriptor.options.some((option) => option.id === trimmed)
161 ) {
162 return descriptor.options.find((option) => option.isDefault)?.id;
163 }
164 if (descriptor.options.some((option) => option.id === trimmed)) {
165 return trimmed;
166 }
167 return descriptor.currentValue ?? descriptor.options.find((option) => option.isDefault)?.id;
168}
169
170function cloneDescriptor(descriptor: ProviderOptionDescriptor): ProviderOptionDescriptor {
171 return descriptor.type === "select"
172 ? {
173 ...descriptor,
174 options: [...descriptor.options],
175 ...(descriptor.promptInjectedValues
176 ? { promptInjectedValues: [...descriptor.promptInjectedValues] }
177 : {}),
178 }
179 : { ...descriptor };
180}
181
182function cloneSelection(selection: ProviderOptionSelection): ProviderOptionSelection {
183 return { ...selection };
184}
185
186function withDescriptorCurrentValue(
187 descriptor: ProviderOptionDescriptor,
188 rawCurrentValue: string | boolean | undefined,
189): ProviderOptionDescriptor {
190 if (descriptor.type === "boolean") {
191 if (typeof rawCurrentValue === "boolean") {
192 return {
193 ...descriptor,
194 currentValue: rawCurrentValue,
195 };
196 }
197 return descriptor;
198 }
199 const currentValue =
200 typeof rawCurrentValue === "string"
201 ? resolveDescriptorChoiceValue(descriptor, rawCurrentValue)
202 : resolveDescriptorChoiceValue(descriptor, descriptor.currentValue);
203 if (!currentValue) {
204 const { currentValue: _unusedCurrentValue, ...rest } = descriptor;
205 return rest;
206 }
207 return {
208 ...descriptor,
209 currentValue,
210 };
211}
212
213// Ultracode was a Claude effort level before it became its own toggle; that level ran at xhigh.
214export function withLegacyUltracodeEffort<
215 Selections extends ReadonlyArray<ProviderOptionSelection> | null | undefined,
216>(
217 descriptors: ReadonlyArray<ProviderOptionDescriptor> | null | undefined,
218 selections: Selections,
219): Selections | Array<ProviderOptionSelection> {
220 if (
221 getRawSelectionValueById(selections, "effort") !== "ultracode" ||
222 !descriptors?.some(
223 (descriptor) => descriptor.id === "ultracode" && descriptor.type === "boolean",
224 )
225 ) {
226 return selections;
227 }
228 return [
229 ...(selections ?? []).map((selection) =>
230 selection.id === "effort" && selection.value === "ultracode"
231 ? { id: "effort", value: "xhigh" }
232 : selection,
233 ),
234 ...(getRawSelectionValueById(selections, "ultracode") === undefined
235 ? [{ id: "ultracode", value: true }]
236 : []),
237 ];
238}
239
240export function getProviderOptionDescriptors(input: {
241 caps: ModelCapabilities;
242 selections?: ReadonlyArray<ProviderOptionSelection> | null | undefined;
243}): ReadonlyArray<ProviderOptionDescriptor> {
244 const { caps } = input;
245 const baseDescriptors = (caps.optionDescriptors ?? []).map(cloneDescriptor);
246 const selections = withLegacyUltracodeEffort(baseDescriptors, input.selections);
247
248 return baseDescriptors.map((descriptor) =>
249 withDescriptorCurrentValue(
250 descriptor,
251 getRawSelectionValueById(selections, descriptor.id) ?? descriptor.currentValue,
252 ),
253 );
254}
255
256function getReportedOptionValue(
257 id: string,
258 selection?: ModelSelection | null,
259 reportedSelection?: ModelSelection | null,
260) {
261 if (
262 !selection ||
263 !reportedSelection ||
264 selection.instanceId !== reportedSelection.instanceId ||
265 selection.model !== reportedSelection.model ||
266 selection.options?.some((option) => option.id === id)
267 )
268 return undefined;
269 return getRawSelectionValueById(reportedSelection.options, id);
270}
271
272export function getProviderOptionStatedValue(
273 id: string,
274 selection?: ModelSelection | null,
275 reportedSelection?: ModelSelection | null,
276) {
277 return (
278 getRawSelectionValueById(selection?.options, id) ??
279 getReportedOptionValue(id, selection, reportedSelection)
280 );
281}
282
283/** The variant choice that sends no variant; distinct from any variant name a provider defines. */
284export const DEFAULT_VARIANT_CHOICE_ID = "t3:default";
285
286export function getProviderOptionCurrentValue(
287 descriptor: ProviderOptionDescriptor | null | undefined,
288 selection?: ModelSelection | null,
289 reportedSelection?: ModelSelection | null,
290): string | boolean | undefined {
291 if (!descriptor) {
292 return undefined;
293 }
294 const hasExplicitOption = selection?.options?.some((option) => option.id === descriptor.id);
295 // Reported values are display-only; callers that build dispatch options omit this context.
296 const reportedValue = getReportedOptionValue(descriptor.id, selection, reportedSelection);
297 if (reportedValue !== undefined) return reportedValue;
298 // Without an explicit variant none is sent, which is exactly the catalog's Default choice.
299 if (
300 descriptor.type === "select" &&
301 descriptor.id === "variant" &&
302 selection &&
303 !hasExplicitOption &&
304 descriptor.options.some((option) => option.id === DEFAULT_VARIANT_CHOICE_ID)
305 ) {
306 return DEFAULT_VARIANT_CHOICE_ID;
307 }
308 if (descriptor.id === "variant" && selection && !hasExplicitOption) return undefined;
309 if (descriptor.type === "boolean") {
310 return descriptor.currentValue;
311 }
312 if (descriptor.currentValue) {
313 return descriptor.currentValue;
314 }
315 return descriptor.options.find((option) => option.isDefault)?.id;
316}
317
318export function getProviderOptionCurrentLabel(
319 descriptor: ProviderOptionDescriptor | null | undefined,
320 selection?: ModelSelection | null,
321 reportedSelection?: ModelSelection | null,
322): string | undefined {
323 if (!descriptor) {
324 return undefined;
325 }
326 if (descriptor.type === "boolean") {
327 return typeof descriptor.currentValue === "boolean"
328 ? descriptor.currentValue
329 ? "On"
330 : "Off"
331 : undefined;
332 }
333 const currentValue = getProviderOptionCurrentValue(descriptor, selection, reportedSelection);
334 return (
335 descriptor.options.find((option) => option.id === currentValue)?.label ??
336 (getReportedOptionValue(descriptor.id, selection, reportedSelection) === "default"
337 ? "Default"
338 : descriptor.id === "variant"
339 ? "Unknown"
340 : undefined)
341 );
342}
343
344export function buildProviderOptionSelectionsFromDescriptors(
345 descriptors: ReadonlyArray<ProviderOptionDescriptor> | null | undefined,
346): Array<ProviderOptionSelection> | undefined {
347 if (!descriptors || descriptors.length === 0) {
348 return undefined;
349 }
350
351 const nextSelections: Array<ProviderOptionSelection> = [];
352
353 for (const descriptor of descriptors) {
354 const value = getProviderOptionCurrentValue(descriptor);
355 if (typeof value === "string" || typeof value === "boolean") {
356 nextSelections.push({ id: descriptor.id, value });
357 }
358 }
359
360 return nextSelections.length > 0 ? nextSelections : undefined;
361}
362
363export function buildExplicitProviderOptionSelectionsFromDescriptors(
364 descriptors: ReadonlyArray<ProviderOptionDescriptor> | null | undefined,
365 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
366): Array<ProviderOptionSelection> | undefined {
367 if (!selections || selections.length === 0) {
368 return undefined;
369 }
370 const explicitIds = new Set(
371 withLegacyUltracodeEffort(descriptors, selections).map(({ id }) => id),
372 );
373 const normalized = buildProviderOptionSelectionsFromDescriptors(descriptors)?.filter(
374 (selection) => explicitIds.has(selection.id),
375 );
376 return normalized && normalized.length > 0 ? normalized : undefined;
377}
378
379export function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean {
380 return typeof text === "string" && /\bultrathink\b/i.test(text);
381}
382
383export function codexModelFamily(slug: string): string {
384 return slug.startsWith("openai.gpt-") ? slug.slice("openai.".length) : slug;
385}
386
387export function formatModelSlugName(slug: string): string {
388 const separator = slug.lastIndexOf("/") + 1;
389 const prefix = slug.slice(0, separator);
390 const name = slug.slice(separator);
391 if (/^gpt-\d/i.test(name)) {
392 return (
393 prefix + name.replace(/^gpt/i, "GPT").replace(/-([a-z])/g, (_, c) => "-" + c.toUpperCase())
394 );
395 }
396 if (!/^(claude-(opus|sonnet|haiku|fable)|gemini|grok|composer)-\d/i.test(name)) return slug;
397 return (
398 prefix +
399 name
400 .replace(/^(claude-[a-z]+-\d+)-(\d{1,2})(?=-|\[|$)/i, "$1.$2")
401 .split("-")
402 .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
403 .join(" ")
404 );
405}
406
407export function normalizeModelSlug(
408 model: string | null | undefined,
409 provider: ProviderDriverKind = DEFAULT_PROVIDER_DRIVER_KIND,
410): string | null {
411 const trimmed = normalizeCustomModelSlug(model);
412 if (!trimmed) {
413 return null;
414 }
415
416 const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] ?? {};
417 const aliased = Object.prototype.hasOwnProperty.call(aliases, trimmed)
418 ? aliases[trimmed]
419 : undefined;
420 return typeof aliased === "string" ? aliased : trimmed;
421}
422
423/** Custom model identifiers are provider-owned, so only trim them; never expand aliases. */
424export function normalizeCustomModelSlug(model: string | null | undefined): string | null {
425 if (typeof model !== "string") {
426 return null;
427 }
428
429 return model.trim() || null;
430}
431
432export interface CustomModelDefinition {
433 readonly slug: string;
434 readonly name: string;
435 readonly capabilities: ModelCapabilities | null;
436}
437
438const decodeCustomModelCapabilities = Schema.decodeUnknownOption(ModelCapabilities);
439
440export function readCustomModelEntries(value: unknown): CustomModelDefinition[] {
441 if (!Array.isArray(value)) return [];
442 const entries: CustomModelDefinition[] = [];
443 const seen = new Set<string>();
444 for (const raw of value) {
445 const record =
446 typeof raw === "string"
447 ? { slug: raw }
448 : raw !== null && typeof raw === "object"
449 ? (raw as { slug?: unknown; name?: unknown; capabilities?: unknown })
450 : null;
451 if (!record) continue;
452 const slug = normalizeCustomModelSlug(typeof record.slug === "string" ? record.slug : null);
453 if (!slug || seen.has(slug)) continue;
454 seen.add(slug);
455 const name =
456 (typeof record.name === "string" ? normalizeCustomModelSlug(record.name) : null) ?? slug;
457 const capabilities =
458 record.capabilities === undefined || record.capabilities === null
459 ? null
460 : Option.getOrNull(decodeCustomModelCapabilities(record.capabilities));
461 entries.push({
462 slug,
463 name,
464 capabilities: capabilities
465 ? createModelCapabilities({ optionDescriptors: capabilities.optionDescriptors ?? [] })
466 : null,
467 });
468 }
469 return entries;
470}
471
472export function toCustomModelSetting(entry: CustomModelDefinition): CustomModelSetting {
473 const descriptors = entry.capabilities?.optionDescriptors ?? [];
474 const name = entry.name !== entry.slug ? entry.name : undefined;
475 if (!name && descriptors.length === 0) return entry.slug;
476 return {
477 slug: entry.slug,
478 ...(name ? { name } : {}),
479 ...(descriptors.length > 0
480 ? { capabilities: createModelCapabilities({ optionDescriptors: descriptors }) }
481 : {}),
482 };
483}
484
485export function resolveSelectableModel(
486 provider: ProviderDriverKind,
487 value: string | null | undefined,
488 options: ReadonlyArray<SelectableModelOption>,
489): string | null {
490 if (typeof value !== "string") {
491 return null;
492 }
493
494 const trimmed = value.trim();
495 if (!trimmed) {
496 return null;
497 }
498
499 const direct = options.find((option) => option.slug === trimmed);
500 if (direct) {
501 return direct.slug;
502 }
503
504 const byName = options.find((option) => option.name.toLowerCase() === trimmed.toLowerCase());
505 if (byName) {
506 return byName.slug;
507 }
508
509 const byAlias = options.find((option) =>
510 option.aliases?.some((alias) => alias.toLowerCase() === trimmed.toLowerCase()),
511 );
512 if (byAlias) {
513 return byAlias.slug;
514 }
515
516 const normalized = normalizeModelSlug(trimmed, provider);
517 if (!normalized) {
518 return null;
519 }
520
521 const resolved = options.find((option) => option.slug === normalized);
522 return resolved ? resolved.slug : null;
523}
524
525function trimOrNull<T extends string>(value: T | null | undefined): T | null {
526 if (typeof value !== "string") return null;
527 const trimmed = value.trim() as T;
528 return trimmed || null;
529}
530
531function cloneSelections(
532 selections: ReadonlyArray<ProviderOptionSelection>,
533): Array<ProviderOptionSelection> {
534 return selections.map(cloneSelection);
535}
536
537export function createModelSelection(
538 instanceId: ProviderInstanceId,
539 model: string,
540 options?: ReadonlyArray<ProviderOptionSelection> | null,
541): ModelSelection {
542 const selections = options ? cloneSelections(options) : [];
543 const base: ModelSelection = {
544 instanceId,
545 model,
546 };
547 return selections.length > 0 ? { ...base, options: selections } : base;
548}
549
550/** A model picker's pick: re-picking the current model keeps its options, another model starts without any. */
551export function pickModelSelection(
552 current: ModelSelection | null | undefined,
553 instanceId: ProviderInstanceId,
554 model: string,
555): ModelSelection {
556 return current?.instanceId === instanceId && current.model === model
557 ? current
558 : createModelSelection(instanceId, model);
559}
560
561export function resolvePromptInjectedEffort(
562 caps: ModelCapabilities,
563 rawEffort: string | null | undefined,
564): string | null {
565 const trimmed = trimOrNull(rawEffort);
566 if (!trimmed) return null;
567 const descriptors = getProviderOptionDescriptors({ caps });
568 for (const descriptor of descriptors) {
569 if (descriptor.type === "select" && descriptor.promptInjectedValues?.includes(trimmed)) {
570 return trimmed;
571 }
572 }
573 return null;
574}
575
576export function applyClaudePromptEffortPrefix(
577 text: string,
578 effort: string | null | undefined,
579): string {
580 const trimmed = text.trim();
581 if (!trimmed) {
582 return trimmed;
583 }
584 // Prefixing slash commands prevents Claude invocation; command names allow any token without a second slash.
585 if (effort !== "ultrathink" || /^\/[^\s/]+(?:\s|$)/u.test(trimmed)) {
586 return trimmed;
587 }
588 if (trimmed.startsWith("Ultrathink:")) {
589 return trimmed;
590 }
591 return `Ultrathink:\n${trimmed}`;
592}