import { readFileSync } from "node:fs"; import { type Api, getSupportedThinkingLevels, type Model } from "@earendil-works/pi-ai"; import type { ExtensionMode, ExtensionUIContext } from "../../core/extensions/types.ts"; import { SelectorComponent, type SelectorResult } from "../pi-subagents/src/slash/selector.ts"; import { emptyRoster, formatRow, globalRosterPath, projectRosterPath, type Effort, type Roster, type RosterRow, SECTION_LABELS, SECTIONS, saveRoster, validateRoster, } from "./roster.ts"; interface PickerContext { ui: Pick & Partial>; modelRegistry: { getAvailable(): Model[] }; mode?: ExtensionMode; } /** TUI: one fuzzy-searchable list of every model. Returns null when the host cannot render components. */ async function searchModel(ctx: PickerContext, models: Model[], current?: RosterRow): Promise | undefined | null> { if (ctx.mode !== "tui" || !ctx.ui.custom) return null; const items = models.map((model) => ({ value: `${model.provider}/${model.id}`, label: `${model.provider}/${model.id}`, current: model.provider === current?.provider && model.id === current?.model, })); const result = await ctx.ui.custom( (tui, theme, kb, done) => new SelectorComponent(tui, theme, kb, { title: "Model", subtitle: "Type to search", items, done }), { overlay: false }, ); return result?.confirmed ? models.find((model) => `${model.provider}/${model.id}` === result.value) : undefined; } async function inputNumber( ctx: PickerContext, title: string, defaultValue: number, valid: (value: number) => boolean, warning: string, ): Promise { while (true) { const input = await ctx.ui.input(title, String(defaultValue)); if (input === undefined) return undefined; const value = input.trim() === "" ? defaultValue : Number(input); if (Number.isFinite(value) && valid(value)) return value; ctx.ui.notify(warning, "warning"); } } async function pickRow(ctx: PickerContext, current?: RosterRow): Promise { const models = [...ctx.modelRegistry.getAvailable()]; if (models.length === 0) { ctx.ui.notify("No models are available.", "error"); return undefined; } const providers = [...new Set(models.map((model) => model.provider))]; // Select dialogs have no default argument; put the current selection first when editing. const providerIndex = providers.findIndex((provider) => provider === current?.provider); if (providerIndex > 0) providers.unshift(...providers.splice(providerIndex, 1)); const providerLabels = providers.map((provider) => `${provider} (${models.filter((model) => model.provider === provider).length})`); const searched = await searchModel(ctx, models, current); if (searched === undefined) return undefined; let model: Model | undefined = searched ?? undefined; // Non-TUI hosts (RPC/ACP) cannot render the search list: provider, then model. while (!model) { const providerLabel = await ctx.ui.select("Provider", providerLabels); if (providerLabel === undefined) return undefined; const provider = providers[providerLabels.indexOf(providerLabel)]; const providerModels = models.filter((candidate) => candidate.provider === provider); const modelIndex = providerModels.findIndex((candidate) => candidate.provider === current?.provider && candidate.id === current?.model); if (modelIndex > 0) providerModels.unshift(...providerModels.splice(modelIndex, 1)); const id = await ctx.ui.select("Model", providerModels.map((candidate) => candidate.id)); if (id === undefined) continue; model = providerModels.find((candidate) => candidate.id === id); } const efforts = model.reasoning ? [...getSupportedThinkingLevels(model)] : ["off" as const]; const effortIndex = efforts.findIndex((effort) => effort === current?.effort); if (effortIndex > 0) efforts.unshift(...efforts.splice(effortIndex, 1)); const effort = await ctx.ui.select("Effort", efforts); if (effort === undefined) return undefined; const difficultyDefault = current?.difficulty ?? 3; const difficulty = await inputNumber(ctx, `Difficulty 1–7 (Enter = ${Number.isInteger(difficultyDefault) ? difficultyDefault.toFixed(1) : difficultyDefault})`, difficultyDefault, (value) => value >= 1 && value <= 7, "Difficulty must be a finite number from 1 to 7."); if (difficulty === undefined) return undefined; const concurrencyDefault = current?.concurrency ?? 3; const concurrency = await inputNumber(ctx, `Concurrency (Enter = ${concurrencyDefault})`, concurrencyDefault, (value) => Number.isInteger(value) && value >= 1, "Concurrency must be an integer of at least 1."); if (concurrency === undefined) return undefined; return { provider: model.provider, model: model.id, effort: effort as Effort, difficulty, concurrency }; } export async function runRosterPicker( ctx: PickerContext, { cwd, trusted, agentDir }: { cwd: string; trusted: boolean; agentDir?: string }, ): Promise<{ roster: Roster; path: string; scope: "global" | "project" } | undefined> { const globalOption = "Global (~/.selesai/agent/implement-models.json)"; const projectOption = "This project (.selesai/implement-models.json)"; const choice = await ctx.ui.select("Save model list to?", trusted ? [globalOption, projectOption] : [globalOption]); if (choice === undefined) return undefined; const scope = trusted && choice === projectOption ? "project" : "global"; const path = scope === "project" ? projectRosterPath(cwd) : globalRosterPath(agentDir); let roster = emptyRoster(); try { const result = validateRoster(JSON.parse(readFileSync(path, "utf8")) as unknown); if (result.ok) roster = result.roster; } catch { // A missing or unreadable/invalid scope file starts a fresh roster. } while (true) { const sectionOptions = SECTIONS.map((section) => `${SECTION_LABELS[section]} (${roster.sections[section].length})`); const selection = await ctx.ui.select("Model list sections", [...sectionOptions, "Save", "Cancel"]); if (selection === undefined || selection === "Cancel") return undefined; if (selection === "Save") { if (!SECTIONS.some((section) => roster.sections[section].length > 0)) { ctx.ui.notify("Add at least one model before saving.", "warning"); continue; } saveRoster(path, roster); return { roster, path, scope }; } const section = SECTIONS[sectionOptions.indexOf(selection)]; if (!section) continue; const rows = roster.sections[section]; while (true) { const rowOptions = rows.map((row, index) => `${index + 1}. ${formatRow(row)}`); const action = await ctx.ui.select(SECTION_LABELS[section], ["+ Add model", ...rowOptions, "Clear section", "Back"]); if (action === undefined || action === "Back") break; if (action === "+ Add model") { const row = await pickRow(ctx); if (row) rows.push(row); } else if (action === "Clear section") { rows.length = 0; } else { const index = rowOptions.indexOf(action); if (index < 0) continue; const rowAction = await ctx.ui.select(formatRow(rows[index]), ["Edit", "Remove", "Back"]); if (rowAction === "Remove") rows.splice(index, 1); if (rowAction === "Edit") { const row = await pickRow(ctx, rows[index]); if (row) rows[index] = row; } } } } }