Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

model.ts

502 lines15.8 KB

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);
25​
26export interface SelectableModelOption {
27 slug: string;
28 name: string;
29 aliases?: ReadonlyArray<string> | undefined;
31​
32export function createModelCapabilities(input: {
33 optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
34}): ModelCapabilities {
35 return {
36 optionDescriptors: input.optionDescriptors.map(cloneDescriptor),
37 };
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;
47​
48function getProviderOptionSelectionValue(
49 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
50 id: string,
51): string | boolean | undefined {
52 return getRawSelectionValueById(selections, id);
54​
55export function 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;
62​
63export function 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;
70​
71export function getModelSelectionStringOptionValue(
72 modelSelection: ModelSelection | null | undefined,
73 id: string,
74): string | undefined {
75 return getProviderOptionStringSelectionValue(modelSelection?.options, id);
77​
78export function getModelSelectionBooleanOptionValue(
79 modelSelection: ModelSelection | null | undefined,
80 id: string,
81): boolean | undefined {
82 return getProviderOptionBooleanSelectionValue(modelSelection?.options, id);
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 (
96 [leftId, leftValue]: readonly [id: string, value: string | boolean],
97 [rightId, rightValue]: readonly [id: string, value: string | boolean],
98 ) => {
99 const idOrder = leftId.localeCompare(rightId);
100 return idOrder !== 0 ? idOrder : String(leftValue).localeCompare(String(rightValue));
101 },
102 );
104​
105export function modelSelectionsEqual(left: ModelSelection, right: ModelSelection): boolean {
106 if (left.instanceId !== right.instanceId || left.model !== right.model) {
107 return false;
108 }
109 const leftOptions = canonicalModelSelectionOptions(left);
110 const rightOptions = canonicalModelSelectionOptions(right);
111 return (
112 leftOptions.length === rightOptions.length &&
113 leftOptions.every(
114 ([id, value], index) => id === rightOptions[index]?.[0] && value === rightOptions[index]?.[1],
115 )
116 );
118​
119function resolveDescriptorChoiceValue(
120 descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>,
121 raw: string | null | undefined,
122): string | undefined {
123 const trimmed = trimOrNull(raw);
124 if (!trimmed) {
125 return descriptor.currentValue ?? descriptor.options.find((option) => option.isDefault)?.id;
126 }
127 if (descriptor.options.length === 0) {
128 return trimmed;
129 }
130 if (
131 descriptor.promptInjectedValues?.includes(trimmed) &&
132 descriptor.options.some((option) => option.id === trimmed)
133 ) {
134 return descriptor.options.find((option) => option.isDefault)?.id;
135 }
136 if (descriptor.options.some((option) => option.id === trimmed)) {
137 return trimmed;
138 }
139 return descriptor.currentValue ?? descriptor.options.find((option) => option.isDefault)?.id;
141​
142function cloneDescriptor(descriptor: ProviderOptionDescriptor): ProviderOptionDescriptor {
143 return descriptor.type === "select"
144 ? {
145 ...descriptor,
146 options: [...descriptor.options],
147 ...(descriptor.promptInjectedValues
148 ? { promptInjectedValues: [...descriptor.promptInjectedValues] }
149 : {}),
150 }
151 : { ...descriptor };
153​
154function cloneSelection(selection: ProviderOptionSelection): ProviderOptionSelection {
155 return { ...selection };
157​
158function withDescriptorCurrentValue(
159 descriptor: ProviderOptionDescriptor,
160 rawCurrentValue: string | boolean | undefined,
161): ProviderOptionDescriptor {
162 if (descriptor.type === "boolean") {
163 if (typeof rawCurrentValue === "boolean") {
164 return {
165 ...descriptor,
166 currentValue: rawCurrentValue,
167 };
168 }
169 return descriptor;
170 }
171 const currentValue =
172 typeof rawCurrentValue === "string"
173 ? resolveDescriptorChoiceValue(descriptor, rawCurrentValue)
174 : resolveDescriptorChoiceValue(descriptor, descriptor.currentValue);
175 if (!currentValue) {
176 const { currentValue: _unusedCurrentValue, ...rest } = descriptor;
177 return rest;
178 }
179 return {
180 ...descriptor,
181 currentValue,
182 };
184​
185export function getProviderOptionDescriptors(input: {
186 caps: ModelCapabilities;
187 selections?: ReadonlyArray<ProviderOptionSelection> | null | undefined;
188}): ReadonlyArray<ProviderOptionDescriptor> {
189 const { caps, selections } = input;
190 const baseDescriptors = (caps.optionDescriptors ?? []).map(cloneDescriptor);
191​
192 return baseDescriptors.map((descriptor) =>
193 withDescriptorCurrentValue(
194 descriptor,
195 getRawSelectionValueById(selections, descriptor.id) ?? descriptor.currentValue,
196 ),
197 );
199​
200function getReportedOptionValue(
201 id: string,
202 selection?: ModelSelection | null,
203 reportedSelection?: ModelSelection | null,
204) {
205 if (
206 !selection ||
207 !reportedSelection ||
208 selection.instanceId !== reportedSelection.instanceId ||
209 selection.model !== reportedSelection.model ||
210 selection.options?.some((option) => option.id === id)
211 )
212 return undefined;
213 return getRawSelectionValueById(reportedSelection.options, id);
215​
216export function getProviderOptionCurrentValue(
217 descriptor: ProviderOptionDescriptor | null | undefined,
218 selection?: ModelSelection | null,
219 reportedSelection?: ModelSelection | null,
220): string | boolean | undefined {
221 if (!descriptor) {
222 return undefined;
223 }
224 const hasExplicitOption = selection?.options?.some((option) => option.id === descriptor.id);
225 // Reported values are display-only; callers that build dispatch options omit this context.
226 const reportedValue = getReportedOptionValue(descriptor.id, selection, reportedSelection);
227 if (reportedValue !== undefined) return reportedValue;
228 if (descriptor.id === "variant" && selection && !hasExplicitOption) return undefined;
229 if (descriptor.type === "boolean") {
230 return descriptor.currentValue;
231 }
232 if (descriptor.currentValue) {
233 return descriptor.currentValue;
234 }
235 return descriptor.options.find((option) => option.isDefault)?.id;
237​
238export function getProviderOptionCurrentLabel(
239 descriptor: ProviderOptionDescriptor | null | undefined,
240 selection?: ModelSelection | null,
241 reportedSelection?: ModelSelection | null,
242): string | undefined {
243 if (!descriptor) {
244 return undefined;
245 }
246 if (descriptor.type === "boolean") {
247 return typeof descriptor.currentValue === "boolean"
248 ? descriptor.currentValue
249 ? "On"
250 : "Off"
251 : undefined;
252 }
253 const currentValue = getProviderOptionCurrentValue(descriptor, selection, reportedSelection);
254 return (
255 descriptor.options.find((option) => option.id === currentValue)?.label ??
256 (getReportedOptionValue(descriptor.id, selection, reportedSelection) === "default"
257 ? "Default"
258 : descriptor.id === "variant"
259 ? "Unknown"
260 : undefined)
261 );
263​
264export function buildProviderOptionSelectionsFromDescriptors(
265 descriptors: ReadonlyArray<ProviderOptionDescriptor> | null | undefined,
266): Array<ProviderOptionSelection> | undefined {
267 if (!descriptors || descriptors.length === 0) {
268 return undefined;
269 }
270​
271 const nextSelections: Array<ProviderOptionSelection> = [];
272​
273 for (const descriptor of descriptors) {
274 const value = getProviderOptionCurrentValue(descriptor);
275 if (typeof value === "string" || typeof value === "boolean") {
276 nextSelections.push({ id: descriptor.id, value });
277 }
278 }
279​
280 return nextSelections.length > 0 ? nextSelections : undefined;
282​
283export function buildExplicitProviderOptionSelectionsFromDescriptors(
284 descriptors: ReadonlyArray<ProviderOptionDescriptor> | null | undefined,
285 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
286): Array<ProviderOptionSelection> | undefined {
287 if (!selections || selections.length === 0) {
288 return undefined;
289 }
290 const explicitIds = new Set(selections.map((selection) => selection.id));
291 const normalized = buildProviderOptionSelectionsFromDescriptors(descriptors)?.filter(
292 (selection) => explicitIds.has(selection.id),
293 );
294 return normalized && normalized.length > 0 ? normalized : undefined;
296​
297export function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean {
298 return typeof text === "string" && /\bultrathink\b/i.test(text);
300​
301export function codexModelFamily(slug: string): string {
302 return slug.startsWith("openai.gpt-") ? slug.slice("openai.".length) : slug;
304​
305export function formatCodexModelName(name: string): string {
306 return name.replace(/^gpt/i, "GPT").replace(/-([a-z])/g, (_, c) => "-" + c.toUpperCase());
308​
309export function formatModelSlugName(slug: string): string {
310 const separator = slug.lastIndexOf("/") + 1;
311 const prefix = slug.slice(0, separator);
312 const name = slug.slice(separator);
313 if (/^gpt-\d/i.test(name)) return prefix + formatCodexModelName(name);
314 if (!/^(claude-(opus|sonnet|haiku|fable)|gemini|grok|composer)-\d/i.test(name)) return slug;
315 return (
316 prefix +
317 name
318 .replace(/^(claude-[a-z]+-\d+)-(\d{1,2})(?=-|\[|$)/i, "$1.$2")
319 .split("-")
320 .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
321 .join(" ")
322 );
324​
325export function normalizeModelSlug(
326 model: string | null | undefined,
327 provider: ProviderDriverKind = DEFAULT_PROVIDER_DRIVER_KIND,
328): string | null {
329 const trimmed = normalizeCustomModelSlug(model);
330 if (!trimmed) {
331 return null;
332 }
333​
334 const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] ?? {};
335 const aliased = Object.prototype.hasOwnProperty.call(aliases, trimmed)
336 ? aliases[trimmed]
337 : undefined;
338 return typeof aliased === "string" ? aliased : trimmed;
340​
341/** Custom model identifiers are provider-owned, so only trim them; never expand aliases. */
342export function normalizeCustomModelSlug(model: string | null | undefined): string | null {
343 if (typeof model !== "string") {
344 return null;
345 }
346​
347 return model.trim() || null;
349​
350export interface CustomModelDefinition {
351 readonly slug: string;
352 readonly name: string;
353 readonly capabilities: ModelCapabilities | null;
355​
356const decodeCustomModelCapabilities = Schema.decodeUnknownOption(ModelCapabilities);
357​
358export function readCustomModelEntries(value: unknown): CustomModelDefinition[] {
359 if (!Array.isArray(value)) return [];
360 const entries: CustomModelDefinition[] = [];
361 const seen = new Set<string>();
362 for (const raw of value) {
363 const record =
364 typeof raw === "string"
365 ? { slug: raw }
366 : raw !== null && typeof raw === "object"
367 ? (raw as { slug?: unknown; name?: unknown; capabilities?: unknown })
368 : null;
369 if (!record) continue;
370 const slug = normalizeCustomModelSlug(typeof record.slug === "string" ? record.slug : null);
371 if (!slug || seen.has(slug)) continue;
372 seen.add(slug);
373 const name =
374 (typeof record.name === "string" ? normalizeCustomModelSlug(record.name) : null) ?? slug;
375 const capabilities =
376 record.capabilities === undefined || record.capabilities === null
377 ? null
378 : Option.getOrNull(decodeCustomModelCapabilities(record.capabilities));
379 entries.push({
380 slug,
381 name,
382 capabilities: capabilities
383 ? createModelCapabilities({ optionDescriptors: capabilities.optionDescriptors ?? [] })
384 : null,
385 });
386 }
387 return entries;
389​
390export function toCustomModelSetting(entry: CustomModelDefinition): CustomModelSetting {
391 const descriptors = entry.capabilities?.optionDescriptors ?? [];
392 const name = entry.name !== entry.slug ? entry.name : undefined;
393 if (!name && descriptors.length === 0) return entry.slug;
394 return {
395 slug: entry.slug,
396 ...(name ? { name } : {}),
397 ...(descriptors.length > 0
398 ? { capabilities: createModelCapabilities({ optionDescriptors: descriptors }) }
399 : {}),
400 };
402​
403export function resolveSelectableModel(
404 provider: ProviderDriverKind,
405 value: string | null | undefined,
406 options: ReadonlyArray<SelectableModelOption>,
407): string | null {
408 if (typeof value !== "string") {
409 return null;
410 }
411​
412 const trimmed = value.trim();
413 if (!trimmed) {
414 return null;
415 }
416​
417 const direct = options.find((option) => option.slug === trimmed);
418 if (direct) {
419 return direct.slug;
420 }
421​
422 const byName = options.find((option) => option.name.toLowerCase() === trimmed.toLowerCase());
423 if (byName) {
424 return byName.slug;
425 }
426​
427 const byAlias = options.find((option) =>
428 option.aliases?.some((alias) => alias.toLowerCase() === trimmed.toLowerCase()),
429 );
430 if (byAlias) {
431 return byAlias.slug;
432 }
433​
434 const normalized = normalizeModelSlug(trimmed, provider);
435 if (!normalized) {
436 return null;
437 }
438​
439 const resolved = options.find((option) => option.slug === normalized);
440 return resolved ? resolved.slug : null;
442​
443function trimOrNull<T extends string>(value: T | null | undefined): T | null {
444 if (typeof value !== "string") return null;
445 const trimmed = value.trim() as T;
446 return trimmed || null;
448​
449function cloneSelections(
450 selections: ReadonlyArray<ProviderOptionSelection>,
451): Array<ProviderOptionSelection> {
452 return selections.map(cloneSelection);
454​
455export function createModelSelection(
456 instanceId: ProviderInstanceId,
457 model: string,
458 options?: ReadonlyArray<ProviderOptionSelection> | null,
459): ModelSelection {
460 const selections = options ? cloneSelections(options) : [];
461 const base: ModelSelection = {
462 instanceId,
463 model,
464 };
465 return selections.length > 0 ? { ...base, options: selections } : base;
467​
468export function resolvePromptInjectedEffort(
469 caps: ModelCapabilities,
470 rawEffort: string | null | undefined,
471): string | null {
472 const trimmed = trimOrNull(rawEffort);
473 if (!trimmed) return null;
474 const descriptors = getProviderOptionDescriptors({ caps });
475 for (const descriptor of descriptors) {
476 if (descriptor.type === "select" && descriptor.promptInjectedValues?.includes(trimmed)) {
477 return trimmed;
478 }
479 }
480 return null;
482​
483export function applyClaudePromptEffortPrefix(
484 text: string,
485 effort: string | null | undefined,
486): string {
487 const trimmed = text.trim();
488 if (!trimmed) {
489 return trimmed;
490 }
491 // Prefixing a slash command turns it into plain prose, so Claude never
492 // runs it. Command names come from arbitrary file names ("/deploy.prod",
493 // "/plugin:skill"), so accept any first token without a second slash;
494 // absolute paths like "/home/theo/app.ts" keep the prefix.
495 if (effort !== "ultrathink" || /^\/[^\s/]+(?:\s|$)/u.test(trimmed)) {
496 return trimmed;
497 }
498 if (trimmed.startsWith("Ultrathink:")) {
499 return trimmed;
500 }
501 return `Ultrathink:\n${trimmed}`;