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

model.ts

363 lines11.0 KB

1import {
2 MODEL_SLUG_ALIASES_BY_PROVIDER,
3 type ModelCapabilities,
4 type ModelSelection,
5 ProviderDriverKind,
6 ProviderInstanceId,
7 type ProviderOptionDescriptor,
8 type ProviderOptionSelection,
9} from "@t3tools/contracts";
10​
11import { sanitizeTerminalValue } from "./stripTerminalEscapes.ts";
12​
13const DEFAULT_PROVIDER_DRIVER_KIND = ProviderDriverKind.make("codex");
14​
15export interface SelectableModelOption {
16 slug: string;
17 name: string;
18 aliases?: ReadonlyArray<string> | undefined;
20​
21export function createModelCapabilities(input: {
22 optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
23}): ModelCapabilities {
24 return {
25 optionDescriptors: input.optionDescriptors.map(cloneDescriptor),
26 };
28​
29function getRawSelectionValueById(
30 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
31 id: string,
32): string | boolean | undefined {
33 const selection = selections?.find((candidate) => candidate.id === id);
34 return selection?.value;
36​
37export function getProviderOptionSelectionValue(
38 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
39 id: string,
40): string | boolean | undefined {
41 return getRawSelectionValueById(selections, id);
43​
44export function getProviderOptionStringSelectionValue(
45 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
46 id: string,
47): string | undefined {
48 const value = getProviderOptionSelectionValue(selections, id);
49 if (typeof value !== "string") return undefined;
50 const sanitized = sanitizeTerminalValue(value);
51 return sanitized.length > 0 ? sanitized : undefined;
53​
54export function getProviderOptionBooleanSelectionValue(
55 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
56 id: string,
57): boolean | undefined {
58 const value = getProviderOptionSelectionValue(selections, id);
59 return typeof value === "boolean" ? value : undefined;
61​
62export function getModelSelectionStringOptionValue(
63 modelSelection: ModelSelection | null | undefined,
64 id: string,
65): string | undefined {
66 return getProviderOptionStringSelectionValue(modelSelection?.options, id);
68​
69export function getModelSelectionBooleanOptionValue(
70 modelSelection: ModelSelection | null | undefined,
71 id: string,
72): boolean | undefined {
73 return getProviderOptionBooleanSelectionValue(modelSelection?.options, id);
75​
76function resolveDescriptorChoiceValue(
77 descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>,
78 raw: string | null | undefined,
79): string | undefined {
80 const trimmed = trimOrNull(raw);
81 if (!trimmed) {
82 return descriptor.currentValue ?? descriptor.options.find((option) => option.isDefault)?.id;
83 }
84 if (descriptor.options.length === 0) {
85 return trimmed;
86 }
87 if (
88 descriptor.promptInjectedValues?.includes(trimmed) &&
89 descriptor.options.some((option) => option.id === trimmed)
90 ) {
91 return descriptor.options.find((option) => option.isDefault)?.id;
92 }
93 if (descriptor.options.some((option) => option.id === trimmed)) {
94 return trimmed;
95 }
96 return descriptor.currentValue ?? descriptor.options.find((option) => option.isDefault)?.id;
98​
99function cloneDescriptor(descriptor: ProviderOptionDescriptor): ProviderOptionDescriptor {
100 return descriptor.type === "select"
101 ? {
102 ...descriptor,
103 options: [...descriptor.options],
104 ...(descriptor.promptInjectedValues
105 ? { promptInjectedValues: [...descriptor.promptInjectedValues] }
106 : {}),
107 }
108 : { ...descriptor };
110​
111function cloneSelection(selection: ProviderOptionSelection): ProviderOptionSelection {
112 return { ...selection };
114​
115function withDescriptorCurrentValue(
116 descriptor: ProviderOptionDescriptor,
117 rawCurrentValue: string | boolean | undefined,
118): ProviderOptionDescriptor {
119 if (descriptor.type === "boolean") {
120 if (typeof rawCurrentValue === "boolean") {
121 return {
122 ...descriptor,
123 currentValue: rawCurrentValue,
124 };
125 }
126 return descriptor;
127 }
128 const currentValue =
129 typeof rawCurrentValue === "string"
130 ? resolveDescriptorChoiceValue(descriptor, rawCurrentValue)
131 : resolveDescriptorChoiceValue(descriptor, descriptor.currentValue);
132 if (!currentValue) {
133 const { currentValue: _unusedCurrentValue, ...rest } = descriptor;
134 return rest;
135 }
136 return {
137 ...descriptor,
138 currentValue,
139 };
141​
142export function getProviderOptionDescriptors(input: {
143 caps: ModelCapabilities;
144 selections?: ReadonlyArray<ProviderOptionSelection> | null | undefined;
145}): ReadonlyArray<ProviderOptionDescriptor> {
146 const { caps, selections } = input;
147 const baseDescriptors = (caps.optionDescriptors ?? []).map(cloneDescriptor);
148​
149 return baseDescriptors.map((descriptor) =>
150 withDescriptorCurrentValue(
151 descriptor,
152 getRawSelectionValueById(selections, descriptor.id) ?? descriptor.currentValue,
153 ),
154 );
156​
157export function getProviderOptionCurrentValue(
158 descriptor: ProviderOptionDescriptor | null | undefined,
159): string | boolean | undefined {
160 if (!descriptor) {
161 return undefined;
162 }
163 if (descriptor.type === "boolean") {
164 return descriptor.currentValue;
165 }
166 if (descriptor.currentValue) {
167 return descriptor.currentValue;
168 }
169 return descriptor.options.find((option) => option.isDefault)?.id;
171​
172export function getProviderOptionCurrentLabel(
173 descriptor: ProviderOptionDescriptor | null | undefined,
174): string | undefined {
175 if (!descriptor) {
176 return undefined;
177 }
178 if (descriptor.type === "boolean") {
179 return typeof descriptor.currentValue === "boolean"
180 ? descriptor.currentValue
181 ? "On"
182 : "Off"
183 : undefined;
184 }
185 const currentValue = getProviderOptionCurrentValue(descriptor);
186 if (typeof currentValue !== "string") {
187 return undefined;
188 }
189 return descriptor.options.find((option) => option.id === currentValue)?.label;
191​
192export function buildProviderOptionSelectionsFromDescriptors(
193 descriptors: ReadonlyArray<ProviderOptionDescriptor> | null | undefined,
194): Array<ProviderOptionSelection> | undefined {
195 if (!descriptors || descriptors.length === 0) {
196 return undefined;
197 }
198​
199 const nextSelections: Array<ProviderOptionSelection> = [];
200​
201 for (const descriptor of descriptors) {
202 const value = getProviderOptionCurrentValue(descriptor);
203 if (typeof value === "string" || typeof value === "boolean") {
204 nextSelections.push({ id: descriptor.id, value });
205 }
206 }
207​
208 return nextSelections.length > 0 ? nextSelections : undefined;
210​
211export function buildExplicitProviderOptionSelectionsFromDescriptors(
212 descriptors: ReadonlyArray<ProviderOptionDescriptor> | null | undefined,
213 selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,
214): Array<ProviderOptionSelection> | undefined {
215 if (!selections || selections.length === 0) {
216 return undefined;
217 }
218 const explicitIds = new Set(selections.map((selection) => selection.id));
219 const normalized = buildProviderOptionSelectionsFromDescriptors(descriptors)?.filter(
220 (selection) => explicitIds.has(selection.id),
221 );
222 return normalized && normalized.length > 0 ? normalized : undefined;
224​
225export function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean {
226 return typeof text === "string" && /\bultrathink\b/i.test(text);
228​
229export function normalizeModelSlug(
230 model: string | null | undefined,
231 provider: ProviderDriverKind = DEFAULT_PROVIDER_DRIVER_KIND,
232): string | null {
233 const trimmed = normalizeCustomModelSlug(model);
234 if (!trimmed) {
235 return null;
236 }
237​
238 const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] ?? {};
239 const aliased = Object.prototype.hasOwnProperty.call(aliases, trimmed)
240 ? aliases[trimmed]
241 : undefined;
242 return typeof aliased === "string" ? aliased : trimmed;
244​
245/** Custom model identifiers are provider-owned, so only trim them; never expand aliases. */
246export function normalizeCustomModelSlug(model: string | null | undefined): string | null {
247 if (typeof model !== "string") {
248 return null;
249 }
250​
251 return sanitizeTerminalValue(model) || null;
253​
254export function resolveSelectableModel(
255 provider: ProviderDriverKind,
256 value: string | null | undefined,
257 options: ReadonlyArray<SelectableModelOption>,
258): string | null {
259 if (typeof value !== "string") {
260 return null;
261 }
262​
263 const trimmed = value.trim();
264 if (!trimmed) {
265 return null;
266 }
267​
268 const direct = options.find((option) => option.slug === trimmed);
269 if (direct) {
270 return direct.slug;
271 }
272​
273 const byName = options.find((option) => option.name.toLowerCase() === trimmed.toLowerCase());
274 if (byName) {
275 return byName.slug;
276 }
277​
278 const byAlias = options.find((option) =>
279 option.aliases?.some((alias) => alias.toLowerCase() === trimmed.toLowerCase()),
280 );
281 if (byAlias) {
282 return byAlias.slug;
283 }
284​
285 const normalized = normalizeModelSlug(trimmed, provider);
286 if (!normalized) {
287 return null;
288 }
289​
290 const resolved = options.find((option) => option.slug === normalized);
291 return resolved ? resolved.slug : null;
293​
294/** Trim a string, returning null for empty/missing values. */
295export function trimOrNull<T extends string>(value: T | null | undefined): T | null {
296 if (typeof value !== "string") return null;
297 const sanitized = sanitizeTerminalValue(value);
298 const trimmed = sanitized.trim() as T;
299 return trimmed || null;
301​
302function cloneSelections(
303 selections: ReadonlyArray<ProviderOptionSelection>,
304): Array<ProviderOptionSelection> {
305 return selections.map(cloneSelection);
307​
308export function createModelSelection(
309 instanceId: ProviderInstanceId,
310 model: string,
311 options?: ReadonlyArray<ProviderOptionSelection> | null,
312): ModelSelection {
313 const selections = options ? cloneSelections(options) : [];
314 const base: ModelSelection = {
315 instanceId,
316 model,
317 };
318 return selections.length > 0 ? { ...base, options: selections } : base;
320​
321/**
322 * Returns the effort value if it is a prompt-injected value according to
323 * any select descriptor in the given capabilities, or null otherwise.
324 *
325 * Unlike a single `find`, this checks every descriptor so that the
326 * correct descriptor's `promptInjectedValues` list is consulted even when
327 * multiple select descriptors exist.
328 */
329export function resolvePromptInjectedEffort(
330 caps: ModelCapabilities,
331 rawEffort: string | null | undefined,
332): string | null {
333 const trimmed = trimOrNull(rawEffort);
334 if (!trimmed) return null;
335 const descriptors = getProviderOptionDescriptors({ caps });
336 for (const descriptor of descriptors) {
337 if (descriptor.type === "select" && descriptor.promptInjectedValues?.includes(trimmed)) {
338 return trimmed;
339 }
340 }
341 return null;
343​
344export function applyClaudePromptEffortPrefix(
345 text: string,
346 effort: string | null | undefined,
347): string {
348 const trimmed = text.trim();
349 if (!trimmed) {
350 return trimmed;
351 }
352 // Prefixing a slash command turns it into plain prose, so Claude never
353 // runs it. Command names come from arbitrary file names ("/deploy.prod",
354 // "/plugin:skill"), so accept any first token without a second slash;
355 // absolute paths like "/home/theo/app.ts" keep the prefix.
356 if (effort !== "ultrathink" || /^\/[^\s/]+(?:\s|$)/u.test(trimmed)) {
357 return trimmed;
358 }
359 if (trimmed.startsWith("Ultrathink:")) {
360 return trimmed;
361 }
362 return `Ultrathink:\n${trimmed}`;