import { ThinkingLevel } from "@sayknow-cli/agent-core"; import { getSupportedEfforts, type Model, modelsAreEqual } from "@sayknow-cli/ai"; import { Container, fuzzyFilter, fuzzyMatch, getKeybindings, Input, matchesKey, Spacer, type Tab, TabBar, Text, type TUI, } from "@sayknow-cli/tui"; import { getModelProfilePresentation, groupModelProfilesForPresetLanding, type ModelProfileDefinition, } from "../../config/model-profiles"; import type { ModelRegistry, SkcModelAssignmentTargetId } from "../../config/model-registry"; import { isAuthenticated, kNoAuth, SKC_MODEL_ASSIGNMENT_TARGET_IDS, SKC_MODEL_ASSIGNMENT_TARGETS, } from "../../config/model-registry"; import { formatModelSelectorValue, resolveConfiguredModelPatterns, resolveModelRoleValue, type ScopedModelSelection, } from "../../config/model-resolver"; import { type ModelSelectorValue, normalizeModelSelectorValue, selectorHead } from "../../config/model-selector-value"; import type { ModelProfileConfig } from "../../config/models-config-schema"; import { getProviderAuthHealth } from "../../config/provider-auth-health"; import { compareRankedProviders, type ProviderAuthState } from "../../config/provider-ranking"; import type { Settings } from "../../config/settings"; import { specialtiesForRole, type TaskModelSpecialty } from "../../config/task-model-specialties"; import { t } from "../../i18n"; import { type ThemeColor, theme } from "../../modes/theme/theme"; import { formatModelOnboardingInlineHint } from "../../setup/model-onboarding-guidance"; import { formatClampedModelSelector, getThinkingLevelMetadata, parseThinkingLevel } from "../../thinking"; import { getTabBarTheme } from "../shared"; import { DynamicBorder } from "./dynamic-border"; function makeInvertedBadge(label: string, color: ThemeColor): string { const fgAnsi = theme.getFgAnsi(color); const bgAnsi = fgAnsi.replace(/\x1b\[38;/g, "\x1b[48;"); return `${bgAnsi}\x1b[30m ${label} \x1b[39m\x1b[49m`; } function normalizeSearchText(value: string): string { return value .toLowerCase() .replace(/[^a-z0-9]+/g, " ") .trim(); } function compactSearchText(value: string): string { return value.toLowerCase().replace(/[^a-z0-9]+/g, ""); } function getAlphaSearchTokens(query: string): string[] { return [...normalizeSearchText(query).matchAll(/[a-z]+/g)].map(match => match[0]).filter(token => token.length > 0); } interface SearchableItem { searchText: string; normalizedSearchText: string; compactSearchText: string; } function buildSearchFields(parts: readonly string[]): SearchableItem { const searchText = parts.join(" "); return { searchText, normalizedSearchText: normalizeSearchText(searchText), compactSearchText: compactSearchText(searchText), }; } /** * Punctuation-insensitive search shared by every list view. Users type model * names the way vendors print them ("opus 5.5", "gpt 5.4"), while ids spell * the same thing with dashes ("claude-opus-5-5"). The alpha-token and compact * substring passes bridge that gap; the fuzzy pass only ranks (or, when both * prefilters are empty, rescues typos) over the display text. */ function filterSearchableItems(items: T[], query: string): T[] { const alphaTokens = getAlphaSearchTokens(query); const alphaFiltered = alphaTokens.length === 0 ? items : items.filter(item => alphaTokens.every(token => item.normalizedSearchText.includes(token))); const compactQuery = compactSearchText(query); const substringFiltered = compactQuery.length === 0 ? alphaFiltered : alphaFiltered.filter(item => item.compactSearchText.includes(compactQuery)); const fuzzySource = substringFiltered.length > 0 ? substringFiltered : alphaFiltered.length > 0 ? alphaFiltered : items; return fuzzyFilter(fuzzySource, query, ({ searchText }) => searchText); } function computeModelRank(model: Model, roles: Record): number { return roles.default && modelsAreEqual(roles.default.model, model) ? 0 : 1; } interface ModelItem extends SearchableItem { kind: "provider"; provider: string; id: string; model: Model; selector: string; thinkingLevel?: ThinkingLevel; explicitThinkingLevel?: boolean; /** Tokenized fuzzy match score for the active query; lower is better. */ fuzzyScore?: number; } interface CanonicalModelItem extends SearchableItem { kind: "canonical"; id: string; model: Model; selector: string; variantCount: number; thinkingLevel?: ThinkingLevel; explicitThinkingLevel?: boolean; /** Tokenized fuzzy match score for the active query; lower is better. */ fuzzyScore?: number; } type ModelScoreItem = Pick; type CanonicalScoreItem = Pick; type RankedModelItem = Pick; type RankedCanonicalItem = Pick; /** Sum of per-token fuzzy scores, matching fuzzyFilter's token semantics; undefined on any miss. */ function fuzzyTokensScore(query: string, text: string): number | undefined { const tokens = query .trim() .split(/\s+/) .filter(token => token.length > 0); if (tokens.length === 0) return undefined; let total = 0; for (const token of tokens) { const match = fuzzyMatch(token, text); if (!match.matches) return undefined; total += match.score; } return total; } /** Assign every item its score for `query`, overwriting stale scores from an earlier query. */ export function assignFuzzyScoresToModels(items: ModelScoreItem[], query: string): void { const active = query.trim().length > 0; for (const item of items) { item.fuzzyScore = active ? fuzzyTokensScore(query, `${item.id} ${item.provider}`) : undefined; } } export function assignFuzzyScoresToCanonicalModels(items: CanonicalScoreItem[], query: string): void { const active = query.trim().length > 0; for (const item of items) { item.fuzzyScore = active ? fuzzyTokensScore(query, item.searchText) : undefined; } } export interface RankedModelOrderContext { roles: Record; mruIndex: ReadonlyMap; providerAuthStateById: ReadonlyMap; } const MODEL_DATE_RE = /-(\d{8})$/; const MODEL_LATEST_RE = /-latest$/; /** Match quality first while searching; ties keep default, MRU, provider, then recency order. */ function compareFuzzyScores(a: number | undefined, b: number | undefined): number { if (a === undefined && b === undefined) return 0; return (a ?? Number.MAX_SAFE_INTEGER) - (b ?? Number.MAX_SAFE_INTEGER); } export function compareModelItemsForRanking( a: RankedModelItem, b: RankedModelItem, context: RankedModelOrderContext, ): number { const { roles, mruIndex, providerAuthStateById } = context; const scoreCmp = compareFuzzyScores(a.fuzzyScore, b.fuzzyScore); if (scoreCmp !== 0) return scoreCmp; const aRank = computeModelRank(a.model, roles); const bRank = computeModelRank(b.model, roles); if (aRank !== bRank) return aRank - bRank; // Then MRU order (models in mruIndex come before those not in it) const aMru = mruIndex.get(a.selector) ?? Number.MAX_SAFE_INTEGER; const bMru = mruIndex.get(b.selector) ?? Number.MAX_SAFE_INTEGER; if (aMru !== bMru) return aMru - bMru; const providerCmp = compareRankedProviders( { id: a.provider, label: a.provider, authState: providerAuthStateById.get(a.provider) ?? "none" }, { id: b.provider, label: b.provider, authState: providerAuthStateById.get(b.provider) ?? "none" }, ); if (providerCmp !== 0) return providerCmp; // Priority field (lower = better, e.g. OpenAI code backend priority values) const aPri = a.model.priority ?? Number.MAX_SAFE_INTEGER; const bPri = b.model.priority ?? Number.MAX_SAFE_INTEGER; if (aPri !== bPri) return aPri - bPri; // Version number descending (higher version = better model) const aVer = extractVersionNumber(a.id); const bVer = extractVersionNumber(b.id); if (aVer !== bVer) return bVer - aVer; const aIsLatest = MODEL_LATEST_RE.test(a.id); const bIsLatest = MODEL_LATEST_RE.test(b.id); const aDate = a.id.match(MODEL_DATE_RE)?.[1] ?? ""; const bDate = b.id.match(MODEL_DATE_RE)?.[1] ?? ""; // Models with recency info come before those without; -latest first, then newest date. const aHasRecency = aIsLatest || aDate !== ""; const bHasRecency = bIsLatest || bDate !== ""; if (aHasRecency !== bHasRecency) return aHasRecency ? -1 : 1; if (!aHasRecency) return a.id.localeCompare(b.id); if (aIsLatest !== bIsLatest) return aIsLatest ? -1 : 1; if (aDate && bDate) return bDate.localeCompare(aDate); return aIsLatest ? -1 : bIsLatest ? 1 : a.id.localeCompare(b.id); } export function compareCanonicalModelItemsForRanking( a: RankedCanonicalItem, b: RankedCanonicalItem, context: RankedModelOrderContext, ): number { const { roles, mruIndex, providerAuthStateById } = context; const scoreCmp = compareFuzzyScores(a.fuzzyScore, b.fuzzyScore); if (scoreCmp !== 0) return scoreCmp; const aRank = computeModelRank(a.model, roles); const bRank = computeModelRank(b.model, roles); if (aRank !== bRank) return aRank - bRank; const aMru = mruIndex.get(`${a.model.provider}/${a.model.id}`) ?? Number.MAX_SAFE_INTEGER; const bMru = mruIndex.get(`${b.model.provider}/${b.model.id}`) ?? Number.MAX_SAFE_INTEGER; if (aMru !== bMru) return aMru - bMru; const providerCmp = compareRankedProviders( { id: a.model.provider, label: a.model.provider, authState: providerAuthStateById.get(a.model.provider) ?? "none", }, { id: b.model.provider, label: b.model.provider, authState: providerAuthStateById.get(b.model.provider) ?? "none", }, ); if (providerCmp !== 0) return providerCmp; return a.id.localeCompare(b.id); } type ScopedModelItem = ScopedModelSelection; interface RoleAssignment { model: Model; thinkingLevel: ThinkingLevel; } export type ModelSelectorSelection = | { kind: "assignment"; model: Model; role: SkcModelAssignmentTargetId | null; roles?: readonly SkcModelAssignmentTargetId[]; thinkingLevel?: ThinkingLevel; selector?: string; } | { kind: "profile"; profileName: string; setDefault: boolean; } | { kind: "specialtyAssignment"; model: Model; role: SkcModelAssignmentTargetId; specialty: TaskModelSpecialty; thinkingLevel?: ThinkingLevel; selector?: string; } | { kind: "specialtyReset"; role: SkcModelAssignmentTargetId; } | { kind: "createProfile"; profile: ModelProfileConfig; } | { kind: "login"; providerId: string; }; interface PendingThinkingChoice { item: ModelItem | CanonicalModelItem; role: SkcModelAssignmentTargetId | null; roles?: readonly SkcModelAssignmentTargetId[]; levels: ThinkingLevel[]; } /** Role agents only — the bulk action that deliberately excludes `default`. */ const ROLE_AGENT_TARGET_IDS = ["executor", "architect", "planner", "critic"] as const; /** * A first-level row. Stable descriptors, never positions. * * `scope` distinguishes the two bulk rows rather than a boolean, because the * difference between them is which targets they write, not a degree of anything. */ type ModelSelectorAction = | { kind: "role"; role: SkcModelAssignmentTargetId } | { kind: "bulk"; roles: readonly SkcModelAssignmentTargetId[]; scope: "roleAgents" | "allTargets"; }; /** A second-level row under one canonical role. */ type ModelSelectorDetailAction = | { kind: "roleGeneral"; role: SkcModelAssignmentTargetId } | { kind: "specialty"; role: SkcModelAssignmentTargetId; specialty: TaskModelSpecialty } | { kind: "resetSpecialties"; role: SkcModelAssignmentTargetId }; interface PendingDetailChoice { item: ModelItem | CanonicalModelItem; role: SkcModelAssignmentTargetId; } type RoleSelectCallback = (selection: ModelSelectorSelection) => void | Promise; type CancelCallback = () => void; interface ProviderTabState { id: string; label: string; providerId?: string; } const ALL_TAB = "ALL"; const CANONICAL_TAB = "CANONICAL"; const STATIC_PROVIDER_TABS: ProviderTabState[] = [ { id: ALL_TAB, label: ALL_TAB }, { id: CANONICAL_TAB, label: CANONICAL_TAB }, ]; function formatProviderTabLabel(providerId: string): string { return providerId.replace(/[-_]+/g, " ").toUpperCase(); } function createProviderTab(providerId: string): ProviderTabState { return { id: providerId, label: formatProviderTabLabel(providerId), providerId }; } type ModelSelectorViewMode = "presets" | "models"; interface PresetGroupRow { kind: "group"; groupId: string; profiles: ModelProfileDefinition[]; } interface PresetProfileRow { kind: "profile"; groupId: string; profile: ModelProfileDefinition; } interface PresetCreateRow { kind: "create"; } interface PresetCreateUnavailableRow { kind: "createUnavailable"; label: string; } interface PresetAlreadySavedRow { kind: "alreadySaved"; profileName: string; } interface PresetBrowseRow { kind: "browse"; } type PresetLandingRow = | PresetGroupRow | PresetProfileRow | PresetCreateRow | PresetCreateUnavailableRow | PresetAlreadySavedRow | PresetBrowseRow; // Stable logical identity for a preset landing row, independent of its current // list position. Used to relocate the cursor after the expanded group changes so // navigation does not silently overshoot the destination group header/profiles. function presetRowIdentity(row: PresetLandingRow): string { switch (row.kind) { case "group": return `group:${row.groupId}`; case "profile": return `profile:${row.groupId}:${row.profile.name}`; case "browse": return "browse"; case "create": return "create"; case "createUnavailable": return "createUnavailable"; case "alreadySaved": return `alreadySaved:${row.profileName}`; } } const PROFILE_ROLE_PREVIEW_ORDER: SkcModelAssignmentTargetId[] = [ "default", "executor", "planner", "critic", "architect", ]; const presetScopeLabels = (): readonly string[] => [t("modelSelector.applySession"), t("modelSelector.setDefault")]; function isPrintableCharacter(keyData: string): boolean { return keyData.length === 1 && keyData >= " " && keyData !== "\x7f"; } function profileRequiredProviders(profile: ModelProfileDefinition): string[] { return [...new Set(profile.requiredProviders)].sort((a, b) => a.localeCompare(b)); } function isInheritedRoleSelector(value: string): boolean { return value === "default" || value === "pi/default"; } function getDefaultAliasThinkingLevel(value: string | undefined): ThinkingLevel | undefined { const normalized = value?.trim(); if (!normalized?.startsWith("pi/default:")) return undefined; return parseThinkingLevel(normalized.slice("pi/default:".length)); } function getSelectorProvider(selector: string): string | undefined { const slashIndex = selector.indexOf("/"); return slashIndex > 0 ? selector.slice(0, slashIndex) : undefined; } function deriveRequiredProviders(modelMapping: ModelProfileConfig["model_mapping"]): string[] { const providers = new Set(); for (const selectorValue of Object.values(modelMapping)) { for (const selector of normalizeModelSelectorValue(selectorValue)) { const provider = getSelectorProvider(selector); if (provider) providers.add(provider); } } return [...providers].sort((a, b) => a.localeCompare(b)); } function sameModelSelectorRecord( left: Readonly>, right: Readonly>, ): boolean { const leftEntries = Object.entries(left) .filter((entry): entry is [string, ModelSelectorValue] => entry[1] !== undefined) .sort(([a], [b]) => a.localeCompare(b)); const rightEntries = Object.entries(right) .filter((entry): entry is [string, ModelSelectorValue] => entry[1] !== undefined) .sort(([a], [b]) => a.localeCompare(b)); if (leftEntries.length !== rightEntries.length) return false; for (let i = 0; i < leftEntries.length; i++) { const leftEntry = leftEntries[i]; const rightEntry = rightEntries[i]; if ( !leftEntry || !rightEntry || leftEntry[0] !== rightEntry[0] || !sameStringArray(normalizeModelSelectorValue(leftEntry[1]), normalizeModelSelectorValue(rightEntry[1])) ) { return false; } } return true; } function sameStringArray(left: readonly string[], right: readonly string[]): boolean { if (left.length !== right.length) return false; for (let i = 0; i < left.length; i++) { if (left[i] !== right[i]) return false; } return true; } function hasPersistableProfileSnapshot(snapshot: ModelProfileConfig): boolean { return Object.keys(snapshot.model_mapping).length > 0 && snapshot.required_providers.length > 0; } /** * Component that renders a canonical model selector with provider tabs. * - Preset landing Left/Right: Collapse/expand selected provider * - Model browser Tab/Arrow Left/Right: Switch between provider tabs * - Arrow Up/Down: Navigate rows * - Enter: Open assignment actions for default plus SKC role-agent models * - Escape: Close selector */ export class ModelSelectorComponent extends Container { #searchInput: Input; #headerContainer: Container; #tabBar: TabBar | null = null; #listContainer: Container; #allModels: ModelItem[] = []; #filteredModels: ModelItem[] = []; #canonicalModels: CanonicalModelItem[] = []; #filteredCanonicalModels: CanonicalModelItem[] = []; #selectedIndex: number = 0; #roles = {} as Record; #settings = null as unknown as Settings; #modelRegistry = null as unknown as ModelRegistry; #onSelectCallback = (() => {}) as RoleSelectCallback; #onCancelCallback = (() => {}) as CancelCallback; #errorMessage?: unknown; #catalogRefreshGeneration = 0; #tui: TUI; #scopedModels: ReadonlyArray; #temporaryOnly: boolean; #currentModel?: Model; #currentThinkingLevel?: ThinkingLevel; #activeModelProfile?: string; #configuredDefaultChain?: readonly string[]; #isFastForProvider: (provider?: string) => boolean = () => false; #isFastForSubagentProvider: (provider?: string) => boolean = () => false; #isCurrentModelFastModeActive: () => boolean = () => false; #pendingActionItem?: ModelItem | CanonicalModelItem; #selectedActionIndex: number = 0; #pendingDetailChoice?: PendingDetailChoice; #selectedDetailIndex: number = 0; #pendingThinkingChoice?: PendingThinkingChoice; #selectedThinkingIndex: number = 0; // Preset landing state #viewMode: ModelSelectorViewMode = "presets"; #presetCursor: number = 0; #expandedPresetProviderId?: string; #previewProfileName?: string; #presetScopeMenuOpen: boolean = false; #presetScopeIndex: number = 0; #providerAuthById = new Map(); #providerAuthPending: boolean = false; #presetLoginHint?: string; #authSessionId?: string; // Tab state #providers: ProviderTabState[] = STATIC_PROVIDER_TABS; #activeTabIndex: number = 0; constructor( tui: TUI, _currentModel: Model | undefined, settings: Settings, modelRegistry: ModelRegistry, scopedModels: ReadonlyArray, onSelect: RoleSelectCallback, onCancel: () => void, options?: { temporaryOnly?: boolean; initialSearchInput?: string; sessionId?: string; isFastForProvider?: (provider?: string) => boolean; isFastForSubagentProvider?: (provider?: string) => boolean; isCurrentModelFastModeActive?: () => boolean; currentThinkingLevel?: ThinkingLevel; activeModelProfile?: string; configuredDefaultChain?: readonly string[]; }, ) { super(); this.#tui = tui; this.#settings = settings; this.#modelRegistry = modelRegistry; this.#scopedModels = scopedModels; this.#onSelectCallback = onSelect; this.#onCancelCallback = onCancel; this.#temporaryOnly = options?.temporaryOnly ?? false; this.#authSessionId = options?.sessionId; this.#currentModel = _currentModel; this.#currentThinkingLevel = options?.currentThinkingLevel; this.#activeModelProfile = options?.activeModelProfile; this.#configuredDefaultChain = options?.configuredDefaultChain; this.#isFastForProvider = options?.isFastForProvider ?? (() => false); this.#isFastForSubagentProvider = options?.isFastForSubagentProvider ?? (() => false); // Current-model EFFECTIVE fast state. Defaults to intent for the current // model so existing callers/tests keep prior behavior; production wires the // session's effective predicate so an auto-disabled provider shows no glyph. this.#isCurrentModelFastModeActive = options?.isCurrentModelFastModeActive ?? (() => (this.#currentModel ? this.#isFastForProvider(this.#currentModel.provider) : false)); const initialSearchInput = options?.initialSearchInput; this.#viewMode = this.#temporaryOnly || initialSearchInput || scopedModels.length > 0 ? "models" : "presets"; // Load current role assignments from settings this.#loadRoleModels(); // Add top border this.addChild(new DynamicBorder()); this.addChild(new Spacer(1)); // Add hint about model filtering const hintText = scopedModels.length > 0 ? t("modelSelector.showingScoped") : formatModelOnboardingInlineHint(); this.addChild(new Text(theme.fg("warning", hintText), 0, 0)); this.addChild(new Spacer(1)); // Create header container for tab bar this.#headerContainer = new Container(); this.addChild(this.#headerContainer); this.addChild(new Spacer(1)); // Create search input this.#searchInput = new Input(); if (initialSearchInput) { this.#setSearchInputValue(initialSearchInput); } this.#searchInput.onSubmit = () => { const selectedItem = this.#getSelectedItem(); if (selectedItem) this.#beginActionMenuOrSelect(selectedItem); }; this.addChild(this.#searchInput); this.addChild(new Spacer(1)); // Create list container this.#listContainer = new Container(); this.addChild(this.#listContainer); this.addChild(new Spacer(1)); // Add bottom border this.addChild(new DynamicBorder()); void this.#bootstrapCatalog(); } async #bootstrapCatalog(): Promise { await this.#loadModels(); this.#buildProviderTabs(); if (this.#viewMode === "presets" && (this.#modelRegistry.getModelProfiles?.().size ?? 0) === 0) { this.#viewMode = "models"; } if (this.#viewMode === "presets") { void this.#refreshProviderAuth(); this.#renderPresetLanding(); } else { this.#updateTabBar(); const currentQuery = this.#searchInput.getValue(); if (currentQuery) { this.#filterModels(currentQuery); } else { this.#updateList(); } void this.#refreshLiveCatalog(); } this.#tui.requestRender(); } async #refreshLiveCatalog(): Promise { if (this.#scopedModels.length > 0) return; const generation = ++this.#catalogRefreshGeneration; try { await this.#modelRegistry.refresh("online"); if (generation !== this.#catalogRefreshGeneration) return; await this.#loadModels(); if (generation !== this.#catalogRefreshGeneration) return; this.#buildProviderTabs(); if (this.#viewMode === "models") { this.#updateTabBar(); const currentQuery = this.#searchInput.getValue(); if (currentQuery) { this.#filterModels(currentQuery); } else { this.#updateList(); } } this.#tui.requestRender(); } catch (error) { if (generation !== this.#catalogRefreshGeneration) return; this.#errorMessage = error instanceof Error ? error.message : String(error); this.#updateList(); this.#tui.requestRender(); } } #isActiveDefaultFallback(): boolean { if (!this.#currentModel) return false; const configuredChain = this.#configuredDefaultChain ?? normalizeModelSelectorValue(this.#settings.getModelRole("default")); if (configuredChain.length < 2) return false; const allModels = this.#modelRegistry.getAll(); const matchPreferences = { usageOrder: this.#settings.getStorage()?.getModelUsageOrder() }; return configuredChain.slice(1).some(selector => { const resolved = resolveModelRoleValue(selector, allModels, { settings: this.#settings, matchPreferences, modelRegistry: this.#modelRegistry, }); return resolved.model !== undefined && modelsAreEqual(resolved.model, this.#currentModel); }); } #loadRoleModels(): void { const allModels = this.#modelRegistry.getAll(); const matchPreferences = { usageOrder: this.#settings.getStorage()?.getModelUsageOrder() }; const agentModelOverrides = this.#settings.get("task.agentModelOverrides"); for (const role of SKC_MODEL_ASSIGNMENT_TARGET_IDS) { const target = SKC_MODEL_ASSIGNMENT_TARGETS[role]; const roleValue = target.settingsPath === "modelRoles" ? this.#settings.getModelRole(role) : agentModelOverrides[role]; if (!roleValue) continue; const resolved = resolveModelRoleValue(roleValue, allModels, { settings: this.#settings, matchPreferences, modelRegistry: this.#modelRegistry, }); if (resolved.model) { this.#roles[role] = { model: resolved.model, thinkingLevel: resolved.explicitThinkingLevel && resolved.thinkingLevel !== undefined ? resolved.thinkingLevel : ThinkingLevel.Inherit, }; } } if ( ((this.#configuredDefaultChain?.length ?? 0) > 0 || this.#activeModelProfile || this.#isActiveDefaultFallback()) && this.#currentModel ) { this.#roles.default = { model: this.#currentModel, thinkingLevel: this.#currentThinkingLevel ?? ThinkingLevel.Inherit, }; } } refreshRoleAssignments( options: { currentModel?: Model; currentThinkingLevel?: ThinkingLevel; activeModelProfile?: string } = {}, ): void { if ("currentModel" in options) this.#currentModel = options.currentModel; if ("currentThinkingLevel" in options) this.#currentThinkingLevel = options.currentThinkingLevel; if ("activeModelProfile" in options) this.#activeModelProfile = options.activeModelProfile; this.#roles = {}; this.#loadRoleModels(); this.#applyTabFilter(); } #resolveProviderAuthState(providerId: string): ProviderAuthState { const health = getProviderAuthHealth(this.#modelRegistry.authStorage, providerId); if (health) return health; return this.#modelRegistry.hasConfiguredProviderAuth(providerId) ? "configured" : "none"; } #sortModels(models: ModelItem[]): void { // Sort: default-tagged model first, then MRU, then provider ranking const mruOrder = this.#settings.getStorage()?.getModelUsageOrder() ?? []; const mruIndex = new Map(mruOrder.map((key, i) => [key, i])); const providerAuthStateById = new Map(); for (const item of models) { if (!providerAuthStateById.has(item.provider)) { providerAuthStateById.set(item.provider, this.#resolveProviderAuthState(item.provider)); } } const context: RankedModelOrderContext = { roles: this.#roles, mruIndex, providerAuthStateById }; models.sort((a, b) => compareModelItemsForRanking(a, b, context)); } #sortCanonicalModels(models: CanonicalModelItem[]): void { const mruOrder = this.#settings.getStorage()?.getModelUsageOrder() ?? []; const mruIndex = new Map(mruOrder.map((key, i) => [key, i])); const providerAuthStateById = new Map(); for (const item of models) { if (!providerAuthStateById.has(item.model.provider)) { providerAuthStateById.set(item.model.provider, this.#resolveProviderAuthState(item.model.provider)); } } const context: RankedModelOrderContext = { roles: this.#roles, mruIndex, providerAuthStateById }; models.sort((a, b) => compareCanonicalModelItemsForRanking(a, b, context)); } async #loadModels(): Promise { let models: ModelItem[]; // Use scoped models if provided via --models flag if (this.#scopedModels.length > 0) { models = this.#scopedModels.map(scoped => ({ kind: "provider", provider: scoped.model.provider, id: scoped.model.id, model: scoped.model, selector: `${scoped.model.provider}/${scoped.model.id}`, thinkingLevel: scoped.thinkingLevel, explicitThinkingLevel: scoped.explicitThinkingLevel, ...buildSearchFields([scoped.model.id, scoped.model.provider, scoped.model.name]), })); } else { // Reload config and cached discovery state without blocking on live provider refresh await this.#modelRegistry.refresh("offline"); // Check for models.json errors const loadError = this.#modelRegistry.getError(); if (loadError) { this.#errorMessage = loadError; } else { this.#errorMessage = undefined; } // Load available models (built-in models still work even if models.json failed) try { const availableModels = this.#modelRegistry.getAvailable(); models = availableModels.map((model: Model) => ({ kind: "provider", provider: model.provider, id: model.id, model, selector: `${model.provider}/${model.id}`, ...buildSearchFields([model.id, model.provider, model.name]), })); } catch (error) { this.#allModels = []; this.#filteredModels = []; this.#canonicalModels = []; this.#filteredCanonicalModels = []; this.#errorMessage = error instanceof Error ? error.message : String(error); return; } } const candidateModels = models.map(item => item.model); const canonicalRecords = this.#modelRegistry.getCanonicalModels({ availableOnly: this.#scopedModels.length === 0, candidates: candidateModels, }); const scopedThinkingBySelector = new Map(models.map(item => [item.selector, item.thinkingLevel])); const canonicalModels = canonicalRecords .map((record): CanonicalModelItem | undefined => { const selectedModel = this.#modelRegistry.resolveCanonicalModel(record.id, { availableOnly: this.#scopedModels.length === 0, candidates: candidateModels, }); if (!selectedModel) return undefined; const selectedSelector = `${selectedModel.provider}/${selectedModel.id}`; const item: CanonicalModelItem = { kind: "canonical", id: record.id, model: selectedModel, selector: record.id, variantCount: record.variants.length, ...buildSearchFields([ record.id, record.name, selectedModel.provider, selectedModel.id, selectedModel.name, ...record.variants.flatMap(variant => [variant.selector, variant.model.name]), ]), }; const scopedThinkingLevel = scopedThinkingBySelector.get(selectedSelector); if (scopedThinkingLevel !== undefined) { item.thinkingLevel = scopedThinkingLevel; } const scopedModel = models.find(model => `${model.model.provider}/${model.model.id}` === selectedSelector); if (scopedModel?.explicitThinkingLevel !== undefined) { item.explicitThinkingLevel = scopedModel.explicitThinkingLevel; } return item; }) .filter((item): item is CanonicalModelItem => item !== undefined); this.#sortModels(models); this.#sortCanonicalModels(canonicalModels); this.#allModels = models; this.#filteredModels = models; this.#canonicalModels = canonicalModels; this.#filteredCanonicalModels = canonicalModels; this.#selectedIndex = Math.min(this.#selectedIndex, Math.max(0, models.length - 1)); } #buildProviderTabs(): void { const activeTabId = this.#getActiveTab().id; const providerSet = new Set(); for (const item of this.#allModels) { providerSet.add(item.provider); } for (const provider of this.#modelRegistry.getDiscoverableProviders()) { providerSet.add(provider); } const providerAuthStateById = new Map(); for (const provider of providerSet) { providerAuthStateById.set(provider, this.#resolveProviderAuthState(provider)); } const sortedProviderIds = Array.from(providerSet).sort((left, right) => compareRankedProviders( { id: left, label: formatProviderTabLabel(left), authState: providerAuthStateById.get(left) ?? "none", }, { id: right, label: formatProviderTabLabel(right), authState: providerAuthStateById.get(right) ?? "none", }, ), ); this.#providers = [...STATIC_PROVIDER_TABS, ...sortedProviderIds.map(createProviderTab)]; const activeIndex = this.#providers.findIndex(tab => tab.id === activeTabId); this.#activeTabIndex = activeIndex >= 0 ? activeIndex : Math.min(this.#activeTabIndex, this.#providers.length - 1); } async #refreshSelectedProvider(): Promise { const providerId = this.#getActiveProviderId(); if (this.#scopedModels.length > 0 || !providerId) { return; } await this.#modelRegistry.refreshProvider(providerId); await this.#loadModels(); this.#buildProviderTabs(); this.#updateTabBar(); this.#applyTabFilter(); this.#tui.requestRender(); } #updateTabBar(): void { this.#headerContainer.clear(); const tabs: Tab[] = this.#providers.map(provider => ({ id: provider.id, label: provider.label })); const tabBar = new TabBar(t("modelSelector.modelsTab"), tabs, getTabBarTheme(), this.#activeTabIndex); tabBar.onTabChange = (_tab, index) => { this.#activeTabIndex = index; this.#selectedIndex = 0; this.#applyTabFilter(); void this.#refreshSelectedProvider().catch(error => { this.#errorMessage = error instanceof Error ? error.message : String(error); this.#updateList(); this.#tui.requestRender(); }); }; this.#tabBar = tabBar; this.#headerContainer.addChild(tabBar); } #getActiveTab(): ProviderTabState { return this.#providers[this.#activeTabIndex] ?? STATIC_PROVIDER_TABS[0]!; } #getActiveTabId(): string { return this.#getActiveTab().id; } #getActiveProviderId(): string | undefined { return this.#getActiveTab().providerId; } #isCanonicalTab(): boolean { return this.#getActiveTabId() === CANONICAL_TAB; } #filterModels(query: string): void { const activeTabId = this.#getActiveTabId(); const activeProviderId = this.#getActiveProviderId(); const isCanonicalTab = activeTabId === CANONICAL_TAB; // Start with all models or filter by provider/canonical view let baseModels = this.#allModels; const baseCanonicalModels = this.#canonicalModels; if (activeProviderId) { baseModels = this.#allModels.filter(m => m.provider === activeProviderId); } // Apply fuzzy filter if query is present if (query.trim()) { // If user is searching from a provider tab, auto-switch to ALL to show global provider results. if (activeProviderId && !isCanonicalTab) { this.#activeTabIndex = 0; if (this.#tabBar && this.#tabBar.getActiveIndex() !== 0) { this.#tabBar.setActiveIndex(0); return; } this.#updateTabBar(); baseModels = this.#allModels; } if (isCanonicalTab) { const fuzzyMatches = filterSearchableItems(baseCanonicalModels, query); assignFuzzyScoresToCanonicalModels(fuzzyMatches, query); this.#sortCanonicalModels(fuzzyMatches); this.#filteredCanonicalModels = fuzzyMatches; } else { const fuzzyMatches = filterSearchableItems(baseModels, query); assignFuzzyScoresToModels(fuzzyMatches, query); this.#sortModels(fuzzyMatches); this.#filteredModels = fuzzyMatches; } } else { this.#filteredModels = baseModels; this.#filteredCanonicalModels = baseCanonicalModels; } const visibleCount = isCanonicalTab ? this.#filteredCanonicalModels.length : this.#filteredModels.length; this.#selectedIndex = Math.min(this.#selectedIndex, Math.max(0, visibleCount - 1)); this.#updateList(); } #applyTabFilter(): void { const query = this.#searchInput.getValue(); this.#filterModels(query); } #formatDiscoveryAge(fetchedAt: number | undefined): string | undefined { if (!fetchedAt) { return undefined; } const ageMs = Math.max(0, Date.now() - fetchedAt); if (ageMs < 60_000) { return "less than a minute ago"; } const ageMinutes = Math.round(ageMs / 60_000); return `${ageMinutes}m ago`; } #getPresetGroups(): Map { return groupModelProfilesForPresetLanding(this.#modelRegistry.getModelProfiles?.() ?? new Map()); } #formatCurrentModelSelector( thinkingLevel: ThinkingLevel | undefined = this.#currentThinkingLevel, ): string | undefined { if (!this.#currentModel) return undefined; return formatModelSelectorValue(`${this.#currentModel.provider}/${this.#currentModel.id}`, thinkingLevel); } #resolveProfileModelSelector(value: ModelSelectorValue | undefined): string | string[] | undefined { const resolvedSelectors: string[] = []; for (const configuredSelector of normalizeModelSelectorValue(value)) { if (isInheritedRoleSelector(configuredSelector)) continue; const selectors = resolveConfiguredModelPatterns(configuredSelector, this.#settings); for (const selector of selectors.length > 0 ? selectors : [configuredSelector]) { const resolved = resolveModelRoleValue(selector, this.#modelRegistry.getAll(), { settings: this.#settings, matchPreferences: { usageOrder: this.#settings.getStorage()?.getModelUsageOrder() }, modelRegistry: this.#modelRegistry, }); if (resolved.model) { resolvedSelectors.push( formatModelSelectorValue(`${resolved.model.provider}/${resolved.model.id}`, resolved.thinkingLevel), ); continue; } const inheritedDefaultThinkingLevel = getDefaultAliasThinkingLevel(selector); if (inheritedDefaultThinkingLevel) { const currentSelector = this.#formatCurrentModelSelector(inheritedDefaultThinkingLevel); if (currentSelector) resolvedSelectors.push(currentSelector); continue; } // Preserve unresolved chain members verbatim instead of silently // truncating configured fallback tails. resolvedSelectors.push(selector); } } if (resolvedSelectors.length === 0) return undefined; return resolvedSelectors.length === 1 ? resolvedSelectors[0] : resolvedSelectors; } #buildCustomModelProfileSnapshot(): ModelProfileConfig { const modelMapping: ModelProfileConfig["model_mapping"] = {}; // Prefer the session's configured default chain so fallback tails are // never dropped from the snapshot; the live model only replaces the head. if (this.#configuredDefaultChain && this.#configuredDefaultChain.length > 0) { const head = this.#formatCurrentModelSelector() ?? this.#configuredDefaultChain[0]!; const tail = this.#configuredDefaultChain.slice(1); modelMapping.default = tail.length > 0 ? [head, ...tail] : head; } else { const currentModelSelector = this.#formatCurrentModelSelector(); if (currentModelSelector) { modelMapping.default = currentModelSelector; } else { const defaultRole = this.#settings.getModelRole("default"); const defaultSelector = this.#resolveProfileModelSelector(defaultRole); if (defaultSelector) modelMapping.default = defaultSelector; } } const agentOverrides = this.#settings.get("task.agentModelOverrides"); for (const role of SKC_MODEL_ASSIGNMENT_TARGET_IDS) { if (role === "default") continue; const selector = this.#resolveProfileModelSelector(agentOverrides[role]); if (selector) modelMapping[role] = selector; } return { required_providers: deriveRequiredProviders(modelMapping), model_mapping: modelMapping, }; } #findDuplicateGeneratedProfile(snapshot: ModelProfileConfig): ModelProfileDefinition | undefined { for (const profile of this.#modelRegistry.getModelProfiles?.().values() ?? []) { if ( sameModelSelectorRecord(profile.modelMapping, snapshot.model_mapping) && sameStringArray(profile.requiredProviders, snapshot.required_providers) ) { return profile; } } return undefined; } #getPresetRows(): PresetLandingRow[] { const rows: PresetLandingRow[] = []; for (const [groupId, profiles] of this.#getPresetGroups()) { rows.push({ kind: "group", groupId, profiles }); if (this.#expandedPresetProviderId === groupId) { for (const profile of profiles) rows.push({ kind: "profile", groupId, profile }); } } const snapshot = this.#buildCustomModelProfileSnapshot(); if (hasPersistableProfileSnapshot(snapshot)) { const duplicateProfile = this.#findDuplicateGeneratedProfile(snapshot); rows.push( duplicateProfile ? { kind: "alreadySaved", profileName: duplicateProfile.name } : { kind: "create" }, ); } else { rows.push({ kind: "createUnavailable", label: "Select a model before creating a custom preset" }); } rows.push({ kind: "browse" }); return rows; } #getSelectedPresetRow(): PresetLandingRow | undefined { return this.#getPresetRows()[this.#presetCursor]; } #getProfileByName(name: string | undefined): ModelProfileDefinition | undefined { if (!name) return undefined; return this.#modelRegistry.getModelProfile?.(name) ?? this.#modelRegistry.getModelProfiles?.().get(name); } #isProviderAuthenticated(providerId: string): boolean | undefined { return this.#providerAuthById.get(providerId); } #getMissingProviders(profileOrProfiles: ModelProfileDefinition | ModelProfileDefinition[]): string[] { const profiles = Array.isArray(profileOrProfiles) ? profileOrProfiles : [profileOrProfiles]; const providers = new Set(); for (const profile of profiles) for (const provider of profileRequiredProviders(profile)) providers.add(provider); return ( [...providers] // Only providers we've CONFIRMED are unauthenticated (=== false) count as // missing. An unknown/pending status (undefined, before #refreshProviderAuth // resolves) must NOT count as missing — otherwise selecting an already- // authenticated preset gets hijacked into a login flow. .filter(provider => this.#isProviderAuthenticated(provider) === false) .sort((a, b) => a.localeCompare(b)) ); } #isPresetAuthenticated(profileOrProfiles: ModelProfileDefinition | ModelProfileDefinition[]): boolean { return this.#getMissingProviders(profileOrProfiles).length === 0; } /** * A preset group is a list of alternative presets, not an all-or-nothing * bundle. Treat the group as usable when at least one member preset has all * of its required providers authenticated. */ #isPresetGroupUsable(profiles: ModelProfileDefinition[]): boolean { return profiles.some(profile => this.#isPresetAuthenticated(profile)); } async #refreshProviderAuth(): Promise { const providers = new Set(); for (const profiles of this.#getPresetGroups().values()) { for (const profile of profiles) for (const provider of profileRequiredProviders(profile)) providers.add(provider); } this.#providerAuthPending = providers.size > 0; this.#renderPresetLanding(); const entries = await Promise.all( [...providers].map(async provider => { const apiKey = await this.#modelRegistry.getApiKeyForProvider(provider, this.#authSessionId); // "Usable" — not "has a real API key". getApiKeyForProvider returns the // kNoAuth ("N/A") sentinel for keyless/no-auth providers (local LLMs, // `--auth none` custom providers), which are usable WITHOUT a key. But // isAuthenticated() deliberately rejects kNoAuth, so using it alone would // flag those providers unauthenticated and silently bail their presets // into a login flow instead of applying. Treat kNoAuth as usable here, // matching setModel()/getApiKey() which already accept it. return [provider, isAuthenticated(apiKey) || apiKey === kNoAuth] as const; }), ); this.#providerAuthById = new Map(entries); this.#providerAuthPending = false; this.#renderPresetLanding(); this.#tui.requestRender(); } #clampPresetCursor(): void { const rows = this.#getPresetRows(); this.#presetCursor = Math.min(this.#presetCursor, Math.max(0, rows.length - 1)); } #relocatePresetCursor(targetIdentity: string): boolean { const relocated = this.#getPresetRows().findIndex(row => presetRowIdentity(row) === targetIdentity); if (relocated < 0) return false; this.#presetCursor = relocated; return true; } #expandSelectedPresetProvider(): void { const selected = this.#getSelectedPresetRow(); if ( !selected || selected.kind === "browse" || selected.kind === "create" || selected.kind === "createUnavailable" || selected.kind === "alreadySaved" ) return; if (this.#expandedPresetProviderId === selected.groupId) return; const targetIdentity = presetRowIdentity(selected); this.#expandedPresetProviderId = selected.groupId; if (!this.#relocatePresetCursor(targetIdentity)) this.#clampPresetCursor(); } #collapseSelectedPresetProvider(): void { const selected = this.#getSelectedPresetRow(); if ( !selected || selected.kind === "browse" || selected.kind === "create" || selected.kind === "createUnavailable" || selected.kind === "alreadySaved" ) return; if (this.#expandedPresetProviderId !== selected.groupId) return; const targetIdentity = selected.kind === "profile" ? `group:${selected.groupId}` : presetRowIdentity(selected); this.#expandedPresetProviderId = undefined; if (!this.#relocatePresetCursor(targetIdentity)) this.#clampPresetCursor(); } #setSearchInputValue(value: string): void { this.#searchInput.setValue(value); } #switchToModelMode(seed?: string): void { this.#viewMode = "models"; this.#expandedPresetProviderId = undefined; this.#previewProfileName = undefined; this.#presetScopeMenuOpen = false; this.#presetScopeIndex = 0; this.#presetLoginHint = undefined; this.#activeTabIndex = 0; this.#selectedIndex = 0; this.#setSearchInputValue(seed ?? this.#searchInput.getValue()); this.#updateTabBar(); this.#filterModels(this.#searchInput.getValue()); void this.#refreshLiveCatalog(); } /** * "What is this session running right now" summary for the preset landing * header: active preset (when one is applied), the effective current model * and thinking level, and one line per assigned role (default, executor, * planner, critic, architect). */ #formatCurrentSessionLines(): string[] { const lines: string[] = []; const parts: string[] = []; if (this.#activeModelProfile) { const profile = this.#getProfileByName(this.#activeModelProfile); const displayName = profile ? getModelProfilePresentation(profile).displayName : this.#activeModelProfile; parts.push(`preset ${theme.fg("accent", displayName)}`); } if (this.#currentModel) { parts.push(this.#formatAssignedModelLabel(this.#currentModel, this.#currentThinkingLevel)); } if (parts.length > 0) lines.push(theme.fg("muted", `Current: ${parts.join(" · ")}`)); for (const role of PROFILE_ROLE_PREVIEW_ORDER) { const assigned = this.#roles[role]; if (!assigned) continue; const label = SKC_MODEL_ASSIGNMENT_TARGETS[role].tag ?? role.toUpperCase(); lines.push( theme.fg("dim", ` ${label}: ${this.#formatAssignedModelLabel(assigned.model, assigned.thinkingLevel)}`), ); } return lines; } #formatAssignedModelLabel(model: Model, thinkingLevel: ThinkingLevel | undefined): string { let label = `${model.provider}/${model.id}`; if (thinkingLevel && thinkingLevel !== ThinkingLevel.Inherit) { label += ` (${getThinkingLevelMetadata(thinkingLevel).label})`; } return label; } #renderPresetLanding(): void { this.#headerContainer.clear(); this.#tabBar = null; this.#listContainer.clear(); this.#headerContainer.addChild(new Text(theme.fg("accent", t("modelSelector.presets")), 0, 0)); for (const line of this.#formatCurrentSessionLines()) { this.#headerContainer.addChild(new Text(line, 0, 0)); } const rows = this.#getPresetRows(); for (let i = 0; i < rows.length; i++) { const row = rows[i]; const selected = i === this.#presetCursor; const prefix = selected ? theme.fg("accent", `${theme.nav.cursor} `) : " "; if (row.kind === "create") { const label = t("modelSelector.createCustom"); this.#listContainer.addChild(new Text(`${prefix}${selected ? theme.fg("accent", label) : label}`, 0, 0)); continue; } if (row.kind === "createUnavailable") { const renderedLabel = selected ? theme.fg("accent", row.label) : theme.fg("dim", row.label); this.#listContainer.addChild(new Text(`${prefix}${renderedLabel}`, 0, 0)); continue; } if (row.kind === "alreadySaved") { const label = `Already saved as ${row.profileName}`; const renderedLabel = selected ? theme.fg("accent", label) : theme.fg("dim", label); this.#listContainer.addChild(new Text(`${prefix}${renderedLabel}`, 0, 0)); continue; } if (row.kind === "browse") { const label = t("modelSelector.browseAll"); this.#listContainer.addChild(new Text(`${prefix}${selected ? theme.fg("accent", label) : label}`, 0, 0)); continue; } if (row.kind === "group") { const authenticated = this.#isPresetGroupUsable(row.profiles); const mark = this.#providerAuthPending ? "…" : authenticated ? "✓" : "✗"; const containsActive = this.#activeModelProfile !== undefined && row.profiles.some(profile => profile.name === this.#activeModelProfile); const label = `${mark} ${row.groupId}`; const renderedLabel = selected ? theme.fg("accent", label) : authenticated ? label : theme.fg("dim", label); const activeSuffix = containsActive ? theme.fg("muted", " (current)") : ""; this.#listContainer.addChild(new Text(`${prefix}${renderedLabel}${activeSuffix}`, 0, 0)); continue; } const presentation = getModelProfilePresentation(row.profile); const authenticated = this.#isPresetAuthenticated(row.profile); const mark = this.#providerAuthPending ? "…" : authenticated ? "✓" : "✗"; const isActive = row.profile.name === this.#activeModelProfile; const label = ` ${mark} ${presentation.displayName}`; const renderedLabel = selected ? theme.fg("accent", label) : authenticated ? label : theme.fg("dim", label); const activeSuffix = isActive ? theme.fg("muted", " (current)") : ""; this.#listContainer.addChild(new Text(`${prefix}${renderedLabel}${activeSuffix}`, 0, 0)); } if (this.#presetLoginHint) { this.#listContainer.addChild(new Spacer(1)); this.#listContainer.addChild(new Text(theme.fg("warning", ` ${this.#presetLoginHint}`), 0, 0)); } const previewProfile = this.#getProfileByName(this.#previewProfileName); if (previewProfile) this.#renderPresetPreview(previewProfile); } #renderPresetPreview(profile: ModelProfileDefinition): void { this.#listContainer.addChild(new Spacer(1)); this.#listContainer.addChild( new Text( theme.fg( "muted", ` ${t("modelSelector.presetPreview", { name: getModelProfilePresentation(profile).displayName })}`, ), 0, 0, ), ); for (const role of PROFILE_ROLE_PREVIEW_ORDER) { const selector = profile.modelMapping[role]; if (!selector) continue; const resolved = resolveModelRoleValue(selector, this.#modelRegistry.getAll(), { settings: this.#settings, matchPreferences: { usageOrder: this.#settings.getStorage()?.getModelUsageOrder() }, modelRegistry: this.#modelRegistry, }); const label = SKC_MODEL_ASSIGNMENT_TARGETS[role].tag ?? role.toUpperCase(); this.#listContainer.addChild( new Text(` ${label}: ${formatClampedModelSelector(selectorHead(selector) ?? "", resolved.model)}`, 0, 0), ); } this.#listContainer.addChild(new Spacer(1)); if (this.#presetScopeMenuOpen) { for (let i = 0; i < presetScopeLabels().length; i++) { const label = presetScopeLabels()[i] ?? ""; const prefix = i === this.#presetScopeIndex ? theme.fg("accent", `${theme.nav.cursor} `) : " "; this.#listContainer.addChild( new Text(`${prefix}${i === this.#presetScopeIndex ? theme.fg("accent", label) : label}`, 0, 0), ); } } else { this.#listContainer.addChild(new Text(theme.fg("muted", ` ${t("modelSelector.pressEnterApply")}`), 0, 0)); } } #formatDiscoveryErrorHint(error: string | undefined): string | undefined { if (!error) { return undefined; } const httpMatch = error.match(/^HTTP (\d+) from (.+)$/); if (!httpMatch) { return undefined; } const [, statusCode, url] = httpMatch; if (statusCode === "404") { return ` Discovery endpoint ${url} returned 404. Point baseUrl at the host that serves /models (usually .../v1).`; } return ` Discovery failed: ${error}`; } #getProviderEmptyStateMessage(): string | undefined { const activeProviderId = this.#getActiveProviderId(); if (!activeProviderId || this.#searchInput.getValue().trim()) { return undefined; } const state = this.#modelRegistry.getProviderDiscoveryState(activeProviderId); if (!state) { return undefined; } const age = this.#formatDiscoveryAge(state.fetchedAt); switch (state.status) { case "cached": return age ? ` Using cached model list from ${age}. Live refresh is still pending.` : " Using cached model list. Live refresh is still pending."; case "unavailable": return ( this.#formatDiscoveryErrorHint(state.error) ?? (age ? ` Provider unavailable. Using cached model list from ${age}.` : " Provider unavailable.") ); case "unauthenticated": return " Provider requires authentication before discovery. Use /provider login or /login for OAuth/subscription providers, or /provider add for API-compatible providers."; case "idle": return " Provider has not been refreshed yet."; case "empty": return " Discovery succeeded but returned 0 models. Check that /models returns { data: [{ id }] }."; case "ok": return undefined; } } #updateList(): void { this.#listContainer.clear(); const isCanonicalTab = this.#isCanonicalTab(); const modelSelectedIndex = this.#selectedIndex; const visibleItems = isCanonicalTab ? this.#filteredCanonicalModels : this.#filteredModels; const maxVisible = 10; const startIndex = Math.max( 0, Math.min(modelSelectedIndex - Math.floor(maxVisible / 2), visibleItems.length - maxVisible), ); const endIndex = Math.min(startIndex + maxVisible, visibleItems.length); const showProvider = this.#getActiveTabId() === ALL_TAB; // Show visible slice of filtered models for (let i = startIndex; i < endIndex; i++) { const item = visibleItems[i]; if (!item) continue; const canonicalItem = isCanonicalTab ? (item as CanonicalModelItem) : undefined; const providerItem = isCanonicalTab ? undefined : (item as ModelItem); const isSelected = i === this.#selectedIndex; // Build role badges (inverted: color as background, black text) const roleBadgeTokens: string[] = []; // Whether a non-subagent (modelRoles) badge on the CURRENT model row already // rendered the current-model EFFECTIVE glyph. Only that case should suppress // the standalone current glyph below — a subagent-only match must NOT, since // subagent badges reflect the subagent tier, not the current model. let currentModelEffectiveGlyphRendered = false; for (const role of SKC_MODEL_ASSIGNMENT_TARGET_IDS) { const roleInfo = SKC_MODEL_ASSIGNMENT_TARGETS[role]; const assigned = this.#roles[role]; if (roleInfo.tag && assigned && modelsAreEqual(assigned.model, item.model)) { const badge = makeInvertedBadge(roleInfo.tag, roleInfo.color ?? "muted"); const thinkingLabel = getThinkingLevelMetadata(assigned.thinkingLevel).label; // Subagent roles (task.agentModelOverrides) run under task.serviceTier, // so their ⚡ uses the effective subagent tier. A non-subagent // (modelRoles) badge on the CURRENT model row uses the current-model // effective predicate so a provider auto-disable hides the glyph; // other modelRoles rows show pure intent. const isSubagentRole = roleInfo.settingsPath === "task.agentModelOverrides"; const isCurrentRow = this.#currentModel !== undefined && modelsAreEqual(this.#currentModel, item.model); const roleFast = isSubagentRole ? this.#isFastForSubagentProvider(assigned.model.provider) : isCurrentRow ? this.#isCurrentModelFastModeActive() : this.#isFastForProvider(assigned.model.provider); if (roleFast && isCurrentRow && !isSubagentRole) { currentModelEffectiveGlyphRendered = true; } const fastSuffix = roleFast ? ` ${theme.icon.fast}` : ""; roleBadgeTokens.push(`${badge} ${theme.fg("dim", `(${thinkingLabel})`)}${fastSuffix}`); } } // Active/current non-role row: show the fast glyph on the session's current // model row. Suppress only when a non-subagent current-row badge already // rendered the current-model effective glyph (duplicate-glyph guard) — a // subagent-only match must not hide the current model's own indicator. if ( !currentModelEffectiveGlyphRendered && this.#currentModel !== undefined && modelsAreEqual(this.#currentModel, item.model) && this.#isCurrentModelFastModeActive() ) { roleBadgeTokens.push(theme.icon.fast); } const badgeText = roleBadgeTokens.length > 0 ? ` ${roleBadgeTokens.join(" ")}` : ""; let line = ""; if (isSelected) { const prefix = theme.fg("accent", `${theme.nav.cursor} `); if (isCanonicalTab) { const variants = theme.fg("dim", ` [${canonicalItem?.variantCount ?? 0}]`); const backing = theme.fg("dim", ` -> ${item.model.provider}/${item.model.id}`); line = `${prefix}${theme.fg("accent", item.id)}${variants}${backing}${badgeText}`; } else if (showProvider) { const providerPrefix = theme.fg("dim", `${providerItem?.provider ?? ""}/`); line = `${prefix}${providerPrefix}${theme.fg("accent", providerItem?.id ?? item.id)}${badgeText}`; } else { line = `${prefix}${theme.fg("accent", item.id)}${badgeText}`; } } else { const prefix = " "; if (isCanonicalTab) { const variants = theme.fg("dim", ` [${canonicalItem?.variantCount ?? 0}]`); const backing = theme.fg("dim", ` -> ${item.model.provider}/${item.model.id}`); line = `${prefix}${item.id}${variants}${backing}${badgeText}`; } else if (showProvider) { const providerPrefix = theme.fg("dim", `${providerItem?.provider ?? ""}/`); line = `${prefix}${providerPrefix}${providerItem?.id ?? item.id}${badgeText}`; } else { line = `${prefix}${item.id}${badgeText}`; } } this.#listContainer.addChild(new Text(line, 0, 0)); } // Add scroll indicator if needed if (startIndex > 0 || endIndex < visibleItems.length) { const scrollInfo = theme.fg("muted", ` (${this.#selectedIndex + 1}/${visibleItems.length})`); this.#listContainer.addChild(new Text(scrollInfo, 0, 0)); } // Show error message or "no results" if empty if (this.#errorMessage) { const errorLines = String(this.#errorMessage).split("\n"); for (const line of errorLines) { this.#listContainer.addChild(new Text(theme.fg("error", line), 0, 0)); } } else if (visibleItems.length === 0) { const statusMessage = this.#getProviderEmptyStateMessage(); this.#listContainer.addChild( new Text( theme.fg( "muted", statusMessage ?? ` ${t("modelSelector.noMatching")} ${formatModelOnboardingInlineHint()}`, ), 0, 0, ), ); } else { const selected = visibleItems[modelSelectedIndex]; if (!selected) { return; } this.#listContainer.addChild(new Spacer(1)); const suffix = isCanonicalTab ? ` (${selected.model.provider}/${selected.model.id}, ${(selected as CanonicalModelItem).variantCount} variants)` : ""; this.#listContainer.addChild( new Text( theme.fg("muted", ` ${t("modelSelector.modelName", { value: selected.model.name })}${suffix}`), 0, 0, ), ); if (this.#pendingThinkingChoice) { this.#renderThinkingMenu(this.#pendingThinkingChoice); } else if (this.#pendingDetailChoice) { this.#renderDetailMenu(this.#pendingDetailChoice); } else if (this.#pendingActionItem) { this.#renderActionMenu(this.#pendingActionItem); } } } /** * First-level actions, in a fixed order the tests and muscle memory both rely on. * * Built as descriptors rather than derived from an index so that adding a row * cannot silently renumber the ones below it — the previous index arithmetic * meant every new action was a chance to mis-assign a model to the wrong role. */ #getActions(): ModelSelectorAction[] { const actions: ModelSelectorAction[] = SKC_MODEL_ASSIGNMENT_TARGET_IDS.map(role => ({ kind: "role", role })); actions.push({ kind: "bulk", roles: ROLE_AGENT_TARGET_IDS, scope: "roleAgents" }); actions.push({ kind: "bulk", roles: SKC_MODEL_ASSIGNMENT_TARGET_IDS, scope: "allTargets" }); return actions; } /** * Second-level rows for one canonical role: General, then its specialties, then reset. * * `default` and the bulk actions never reach here. They write canonical role * models only, because a "set everything" action that also rewrote five * specialty overrides would be impossible to undo from this menu. */ #getDetailActions(role: SkcModelAssignmentTargetId): ModelSelectorDetailAction[] { const rows: ModelSelectorDetailAction[] = [{ kind: "roleGeneral", role }]; for (const specialty of specialtiesForRole(role)) rows.push({ kind: "specialty", role, specialty }); if (rows.length > 1) rows.push({ kind: "resetSpecialties", role }); return rows; } #actionLabel(action: ModelSelectorAction): string { if (action.kind === "bulk") { return action.scope === "roleAgents" ? t("modelSelector.setForAllRoleAgents") : t("modelSelector.setForAllTargets"); } const target = SKC_MODEL_ASSIGNMENT_TARGETS[action.role]; const label = t("modelSelector.setAsTarget", { tag: target.tag ?? action.role.toUpperCase(), name: target.name, }); const count = specialtiesForRole(action.role).length; return count > 0 ? `${label} ${theme.fg("muted", t("modelSelector.hasDetailedUses"))}` : label; } #detailActionLabel(action: ModelSelectorDetailAction): string { if (action.kind === "roleGeneral") return t("modelSelector.generalRole"); if (action.kind === "resetSpecialties") return t("modelSelector.resetSpecialties"); // Read through rather than caching: a row that states what it already holds // is worse than useless if it states a stale value. const assigned = this.#settings.get("task.modelRouting.specialtyModels")?.[action.specialty]; const current = selectorHead(assigned); const label = t(`modelSelector.specialty.${action.specialty}`); return current ? `${label} ${theme.fg("muted", `— ${current}`)}` : label; } #renderActionMenu(item: ModelItem | CanonicalModelItem): void { this.#listContainer.addChild(new Spacer(1)); this.#listContainer.addChild( new Text(theme.fg("muted", ` ${t("modelSelector.actionFor", { id: item.model.id })}`), 0, 0), ); this.#listContainer.addChild(new Spacer(1)); const actions = this.#getActions(); for (let i = 0; i < actions.length; i++) { const action = actions[i]; if (!action) continue; const prefix = i === this.#selectedActionIndex ? theme.fg("accent", `${theme.nav.cursor} `) : " "; const label = this.#actionLabel(action); this.#listContainer.addChild( new Text(`${prefix}${i === this.#selectedActionIndex ? theme.fg("accent", label) : label}`, 0, 0), ); } } #renderDetailMenu(choice: PendingDetailChoice): void { this.#listContainer.addChild(new Spacer(1)); this.#listContainer.addChild( new Text( theme.fg( "muted", ` ${t("modelSelector.detailedUseFor", { target: SKC_MODEL_ASSIGNMENT_TARGETS[choice.role].name, id: choice.item.model.id, })}`, ), 0, 0, ), ); this.#listContainer.addChild(new Spacer(1)); const rows = this.#getDetailActions(choice.role); for (let i = 0; i < rows.length; i++) { const action = rows[i]; if (!action) continue; const prefix = i === this.#selectedDetailIndex ? theme.fg("accent", `${theme.nav.cursor} `) : " "; const label = this.#detailActionLabel(action); this.#listContainer.addChild( new Text(`${prefix}${i === this.#selectedDetailIndex ? theme.fg("accent", label) : label}`, 0, 0), ); } } #renderThinkingMenu(choice: PendingThinkingChoice): void { const targetLabel = choice.roles ? choice.roles.includes("default") ? "all targets" : "all role agents" : choice.role === null ? t("modelSelector.temporaryModel") : SKC_MODEL_ASSIGNMENT_TARGETS[choice.role].name; this.#listContainer.addChild(new Spacer(1)); this.#listContainer.addChild( new Text( theme.fg( "muted", ` ${t("modelSelector.reasoningFor", { target: targetLabel, id: choice.item.model.id })}`, ), 0, 0, ), ); this.#listContainer.addChild(new Spacer(1)); for (let i = 0; i < choice.levels.length; i++) { const level = choice.levels[i]; const metadata = getThinkingLevelMetadata(level); const prefix = i === this.#selectedThinkingIndex ? theme.fg("accent", `${theme.nav.cursor} `) : " "; const label = `${metadata.label} — ${metadata.description}`; this.#listContainer.addChild( new Text(`${prefix}${i === this.#selectedThinkingIndex ? theme.fg("accent", label) : label}`, 0, 0), ); } } #getCurrentRoleThinkingLevel(role: string): ThinkingLevel { return this.#roles[role]?.thinkingLevel ?? ThinkingLevel.Inherit; } #getActionCount(_model: Model): number { return this.#getActions().length; } #getSelectedItem(): ModelItem | CanonicalModelItem | undefined { return this.#isCanonicalTab() ? this.#filteredCanonicalModels[this.#selectedIndex] : this.#filteredModels[this.#selectedIndex]; } handleInput(keyData: string): void { if (this.#pendingThinkingChoice) { this.#handleThinkingMenuInput(keyData); return; } if (this.#pendingDetailChoice) { this.#handleDetailMenuInput(keyData); return; } if (this.#pendingActionItem) { this.#handleActionMenuInput(keyData); return; } if (this.#viewMode === "presets") { this.#handlePresetLandingInput(keyData); return; } // Tab bar navigation if (this.#tabBar?.handleInput(keyData)) { return; } // Up arrow - navigate list (wrap to bottom when at top) if (matchesKey(keyData, "up")) { const itemCount = this.#isCanonicalTab() ? this.#filteredCanonicalModels.length : this.#filteredModels.length; if (itemCount === 0) return; this.#selectedIndex = this.#selectedIndex === 0 ? itemCount - 1 : this.#selectedIndex - 1; this.#updateList(); return; } // Down arrow - navigate list (wrap to top when at bottom) if (matchesKey(keyData, "down")) { const itemCount = this.#isCanonicalTab() ? this.#filteredCanonicalModels.length : this.#filteredModels.length; if (itemCount === 0) return; this.#selectedIndex = this.#selectedIndex === itemCount - 1 ? 0 : this.#selectedIndex + 1; this.#updateList(); return; } // Enter opens the persistent assignment menu. Temporary-only mode keeps the // existing non-persistent quick-switch behavior. if (matchesKey(keyData, "enter") || matchesKey(keyData, "return") || keyData === "\n") { const selectedItem = this.#getSelectedItem(); if (selectedItem) this.#beginActionMenuOrSelect(selectedItem); return; } // Escape or Ctrl+C - close selector if (getKeybindings().matches(keyData, "tui.select.cancel")) { this.#onCancelCallback(); return; } // Pass everything else to search input this.#searchInput.handleInput(keyData); this.#filterModels(this.#searchInput.getValue()); } #handlePresetLandingInput(keyData: string): void { if (isPrintableCharacter(keyData)) { this.#switchToModelMode(keyData); return; } if (matchesKey(keyData, "up")) { const rows = this.#getPresetRows(); if (rows.length === 0) return; if (this.#presetScopeMenuOpen) { this.#presetScopeIndex = this.#presetScopeIndex === 0 ? presetScopeLabels().length - 1 : this.#presetScopeIndex - 1; } else { this.#presetCursor = this.#presetCursor === 0 ? rows.length - 1 : this.#presetCursor - 1; this.#previewProfileName = undefined; this.#presetLoginHint = undefined; this.#clampPresetCursor(); } this.#renderPresetLanding(); return; } if (matchesKey(keyData, "down")) { const rows = this.#getPresetRows(); if (rows.length === 0) return; if (this.#presetScopeMenuOpen) { this.#presetScopeIndex = (this.#presetScopeIndex + 1) % presetScopeLabels().length; } else { this.#presetCursor = (this.#presetCursor + 1) % rows.length; this.#previewProfileName = undefined; this.#presetLoginHint = undefined; this.#clampPresetCursor(); } this.#renderPresetLanding(); return; } if (matchesKey(keyData, "right")) { if (!this.#presetScopeMenuOpen) { this.#expandSelectedPresetProvider(); this.#previewProfileName = undefined; this.#presetLoginHint = undefined; this.#renderPresetLanding(); } return; } if (matchesKey(keyData, "left")) { if (!this.#presetScopeMenuOpen) { this.#collapseSelectedPresetProvider(); this.#previewProfileName = undefined; this.#presetLoginHint = undefined; this.#renderPresetLanding(); } return; } if (matchesKey(keyData, "enter") || matchesKey(keyData, "return") || keyData === "\n") { this.#handlePresetEnter(); return; } if (getKeybindings().matches(keyData, "tui.select.cancel")) { if (this.#presetScopeMenuOpen) { this.#presetScopeMenuOpen = false; this.#renderPresetLanding(); return; } if (this.#previewProfileName) { this.#previewProfileName = undefined; this.#renderPresetLanding(); return; } if (this.#expandedPresetProviderId) { this.#expandedPresetProviderId = undefined; this.#clampPresetCursor(); this.#renderPresetLanding(); return; } this.#onCancelCallback(); } } #handlePresetEnter(): void { if (this.#presetScopeMenuOpen && this.#previewProfileName) { this.#onSelectCallback({ kind: "profile", profileName: this.#previewProfileName, setDefault: this.#presetScopeIndex === 1, }); return; } if (this.#previewProfileName) { this.#presetScopeMenuOpen = true; this.#presetScopeIndex = 0; this.#renderPresetLanding(); return; } const row = this.#getSelectedPresetRow(); if (!row) return; if (row.kind === "create") { this.#onSelectCallback({ kind: "createProfile", profile: this.#buildCustomModelProfileSnapshot() }); return; } if (row.kind === "alreadySaved" || row.kind === "createUnavailable") { return; } if (row.kind === "browse") { this.#switchToModelMode(); return; } if (row.kind === "group") { // A group is a list of alternative presets; only surface a login hint // when none of its members are usable. A partially-usable group stays // navigable so the user can drill in and pick a usable member. if (!this.#isPresetGroupUsable(row.profiles)) { const missing = this.#getMissingProviders(row.profiles); if (this.#startLoginForMissing(missing)) return; this.#presetLoginHint = `Run ${missing.map(provider => `/login ${provider}`).join(", ")}`; this.#renderPresetLanding(); return; } // Enter toggles a usable group's expansion so drilling into presets // works without reaching for the arrow keys (right/left still work). if (this.#expandedPresetProviderId === row.groupId) { this.#collapseSelectedPresetProvider(); } else { this.#expandSelectedPresetProvider(); } this.#presetLoginHint = undefined; this.#renderPresetLanding(); return; } const missing = this.#getMissingProviders(row.profile); if (missing.length > 0) { if (this.#startLoginForMissing(missing)) return; this.#presetLoginHint = `Run ${missing.map(provider => `/login ${provider}`).join(", ")}`; this.#renderPresetLanding(); return; } this.#previewProfileName = row.profile.name; this.#presetLoginHint = undefined; this.#renderPresetLanding(); } /** * Ask the host to start OAuth login for the first missing provider. Returns * true if a login request was dispatched (caller should stop). The controller * decides whether the provider is actually OAuth-capable; if not it falls back * to showing the `/login` / `/provider add` hint itself. */ #startLoginForMissing(missing: string[]): boolean { // Never auto-start login while provider auth is still being checked, or in // temporary-only mode. Only dispatch for a provider confirmed unauthenticated. if (this.#temporaryOnly || this.#providerAuthPending) return false; const providerId = missing.find(p => this.#isProviderAuthenticated(p) === false); if (!providerId) return false; void this.#onSelectCallback({ kind: "login", providerId }); return true; } #beginActionMenuOrSelect(item: ModelItem | CanonicalModelItem): void { if (this.#temporaryOnly) { this.#handleSelect(item, null); return; } this.#pendingActionItem = item; this.#selectedActionIndex = 0; this.#updateList(); } #handleActionMenuInput(keyData: string): void { const item = this.#pendingActionItem; if (!item) return; const actionCount = this.#getActionCount(item.model); if (matchesKey(keyData, "up")) { this.#selectedActionIndex = this.#selectedActionIndex === 0 ? actionCount - 1 : this.#selectedActionIndex - 1; this.#updateList(); return; } if (matchesKey(keyData, "down")) { this.#selectedActionIndex = (this.#selectedActionIndex + 1) % actionCount; this.#updateList(); return; } if (matchesKey(keyData, "enter") || matchesKey(keyData, "return") || keyData === "\n") { const action = this.#getActions()[this.#selectedActionIndex]; if (!action) return; if (action.kind === "bulk") { this.#pendingActionItem = undefined; this.#handleSelect(item, "default", undefined, action.roles); return; } // A role with specialties opens the detail level instead of assigning // straight away; a role without any keeps the old one-keystroke path. if (this.#getDetailActions(action.role).length > 1) { this.#pendingActionItem = undefined; this.#pendingDetailChoice = { item, role: action.role }; this.#selectedDetailIndex = 0; this.#updateList(); return; } this.#pendingActionItem = undefined; this.#handleSelect(item, action.role); return; } if (getKeybindings().matches(keyData, "tui.select.cancel")) { this.#pendingActionItem = undefined; this.#updateList(); } } /** * Second level: General, the role's specialties, and reset. * * Cancel steps back to the first level rather than closing outright, so a * wrong turn costs one keystroke instead of restarting the whole selection. */ #handleDetailMenuInput(keyData: string): void { const choice = this.#pendingDetailChoice; if (!choice) return; const rows = this.#getDetailActions(choice.role); if (matchesKey(keyData, "up")) { this.#selectedDetailIndex = this.#selectedDetailIndex === 0 ? rows.length - 1 : this.#selectedDetailIndex - 1; this.#updateList(); return; } if (matchesKey(keyData, "down")) { this.#selectedDetailIndex = (this.#selectedDetailIndex + 1) % rows.length; this.#updateList(); return; } if (matchesKey(keyData, "enter") || matchesKey(keyData, "return") || keyData === "\n") { const action = rows[this.#selectedDetailIndex]; if (!action) return; this.#pendingDetailChoice = undefined; if (action.kind === "roleGeneral") { this.#handleSelect(choice.item, action.role); return; } if (action.kind === "resetSpecialties") { this.#onSelectCallback({ kind: "specialtyReset", role: action.role }); return; } this.#handleSpecialtySelect(choice.item, action.role, action.specialty); return; } if (getKeybindings().matches(keyData, "tui.select.cancel")) { this.#pendingDetailChoice = undefined; this.#pendingActionItem = choice.item; this.#selectedActionIndex = Math.max( 0, this.#getActions().findIndex(action => action.kind === "role" && action.role === choice.role), ); this.#updateList(); } } /** * Assign a model to one specialty. * * Reuses the same explicit-thinking gate as a canonical assignment, because a * specialty override is dispatched exactly like a role model and would hit * the same "which effort?" ambiguity if it skipped it. */ #handleSpecialtySelect( item: ModelItem | CanonicalModelItem, role: SkcModelAssignmentTargetId, specialty: TaskModelSpecialty, ): void { const thinkingLevel = item.thinkingLevel ?? this.#getCurrentRoleThinkingLevel(role); this.#onSelectCallback({ kind: "specialtyAssignment", model: item.model, role, specialty, thinkingLevel, selector: formatModelSelectorValue(item.selector, thinkingLevel), }); } #handleThinkingMenuInput(keyData: string): void { const choice = this.#pendingThinkingChoice; if (!choice) return; if (matchesKey(keyData, "up")) { this.#selectedThinkingIndex = this.#selectedThinkingIndex === 0 ? choice.levels.length - 1 : this.#selectedThinkingIndex - 1; this.#updateList(); return; } if (matchesKey(keyData, "down")) { this.#selectedThinkingIndex = (this.#selectedThinkingIndex + 1) % choice.levels.length; this.#updateList(); return; } if (matchesKey(keyData, "enter") || matchesKey(keyData, "return") || keyData === "\n") { const level = choice.levels[this.#selectedThinkingIndex]; if (!level) return; this.#pendingThinkingChoice = undefined; this.#handleSelect(choice.item, choice.role, level, choice.roles); return; } if (getKeybindings().matches(keyData, "tui.select.cancel")) { this.#pendingThinkingChoice = undefined; if (choice.role !== null) { // Step back one level, landing on the row that got us here. Located by // descriptor rather than computed from lengths, so the two bulk rows // cannot drift apart from the list that renders them. this.#pendingActionItem = choice.item; const actions = this.#getActions(); const bulkRoles = choice.roles; const wanted = bulkRoles ? actions.findIndex( action => action.kind === "bulk" && action.roles.includes("default") === bulkRoles.includes("default"), ) : actions.findIndex(action => action.kind === "role" && action.role === choice.role); this.#selectedActionIndex = Math.max(0, wanted); } this.#updateList(); } } #getInitialThinkingChoiceIndex(item: ModelItem | CanonicalModelItem, levels: ThinkingLevel[]): number { const preferred = this.#getPreferredThinkingLevel(item); if (preferred && preferred !== ThinkingLevel.Inherit) { const index = levels.indexOf(preferred); if (index !== -1) return index; } return 0; } #getPreferredThinkingLevel(item: ModelItem | CanonicalModelItem): ThinkingLevel | undefined { if (item.thinkingLevel && item.thinkingLevel !== ThinkingLevel.Inherit) { return item.thinkingLevel; } return undefined; } #handleSelect( item: ModelItem | CanonicalModelItem, role: SkcModelAssignmentTargetId | null, thinkingLevel?: ThinkingLevel, roles?: readonly SkcModelAssignmentTargetId[], ): void { const itemThinkingLevel = thinkingLevel ?? item.thinkingLevel; const hasExplicitThinkingChoice = thinkingLevel !== undefined || item.explicitThinkingLevel === true; const needsExplicitThinkingChoice = roles ? roles.some(targetRole => requiresExplicitThinkingChoice(item.model, targetRole)) : requiresExplicitThinkingChoice(item.model, role); if (!hasExplicitThinkingChoice && needsExplicitThinkingChoice) { const levels = getSelectableThinkingLevels(item.model); this.#pendingThinkingChoice = { item, role, roles, levels }; this.#selectedThinkingIndex = this.#getInitialThinkingChoiceIndex(item, levels); this.#updateList(); return; } // For temporary role, don't save to settings - just notify caller if (role === null) { this.#onSelectCallback({ kind: "assignment", model: item.model, role: null, thinkingLevel: itemThinkingLevel, selector: item.selector, }); return; } const selectedThinkingLevel = itemThinkingLevel ?? this.#getCurrentRoleThinkingLevel(role); const selectorValue = roles ? formatModelSelectorValue(item.selector, selectedThinkingLevel) : role === "default" ? item.selector : formatModelSelectorValue(item.selector, selectedThinkingLevel); // Update local state for UI for (const targetRole of roles ?? [role]) { this.#roles[targetRole] = { model: item.model, thinkingLevel: selectedThinkingLevel }; } // Notify caller (for updating agent state if needed) this.#onSelectCallback({ kind: "assignment", model: item.model, role, roles, thinkingLevel: selectedThinkingLevel, selector: selectorValue, }); // Update list to show new badges this.#updateList(); } getSearchInput(): Input { return this.#searchInput; } async __testSelectProfile(profileName: string, setDefault: boolean): Promise { await this.#onSelectCallback({ kind: "profile", profileName, setDefault }); } async __testSelectAssignment( selection: Omit, "kind">, ): Promise { await this.#onSelectCallback({ kind: "assignment", ...selection }); } } function requiresExplicitThinkingChoice(model: Model, role: SkcModelAssignmentTargetId | null): boolean { if (model.reasoning !== true) return false; if (model.provider === "openai" || model.provider === "openai-codex") return true; return role !== null && SKC_MODEL_ASSIGNMENT_TARGETS[role].settingsPath === "task.agentModelOverrides"; } function getSelectableThinkingLevels(model: Model): ThinkingLevel[] { const levels: ThinkingLevel[] = [ThinkingLevel.Off]; let efforts: readonly string[]; try { efforts = getSupportedEfforts(model); } catch { return levels; } for (const effort of efforts) { const level = parseThinkingLevel(effort); if (level && !levels.includes(level)) { levels.push(level); } } return levels; } /** Extract the first version number from a model ID (e.g. "gemini-2.5-pro" → 2.5, "Anthropic model-sonnet-4-6" → 4.6). */ function extractVersionNumber(id: string): number { // Dot-separated version: "gemini-2.5-pro" → 2.5 const dotMatch = id.match(/(?:^|[-_])(\d+\.\d+)/); if (dotMatch) return Number.parseFloat(dotMatch[1]); // Dash-separated short segments: "Anthropic model-sonnet-4-6" → 4.6, "llama-3-1-8b" → 3.1 const dashMatch = id.match(/(?:^|[-_])(\d{1,2})-(\d{1,2})(?=-|$)/); if (dashMatch) return Number.parseFloat(`${dashMatch[1]}.${dashMatch[2]}`); // Single number after separator: "gpt-4o" → 4 const singleMatch = id.match(/(?:^|[-_])(\d+)/); if (singleMatch) return Number.parseFloat(singleMatch[1]); return 0; }