64875
Mc
mini-coder / files
mini-coder / src / tui / commands.ts
7.4 KB
1import { 2 getSupportedThinkingLevels, 3 type Api, 4 type AuthEvent, 5 type AuthPrompt, 6 type AuthType, 7 type Model, 8 type ModelThinkingLevel, 9 type Models, 10} from "@earendil-works/pi-ai"; 11import { saveConfig } from "../config.ts"; 12import { dim, red } from "./styles.ts"; 13import { commonPrefix } from "./complete.ts"; 14 15export interface CommandContext { 16 /** The collection the running command may reach, e.g. to start a login. */ 17 models: Models; 18 /** The model the session is currently running, or null before one is chosen. */ 19 model: Model<Api> | null; 20 /** Switches the running session to `model`. */ 21 select(model: Model<Api>): void; 22 /** Sets the running session's thinking level. */ 23 setThinking(level: ModelThinkingLevel): void; 24 /** Aborts when the running command is cancelled (Ctrl+C). */ 25 signal: AbortSignal; 26 /** Appends already-styled lines to scrollback. */ 27 write(lines: string[]): void; 28 /** Asks the user a question and resolves with the next submitted line. */ 29 prompt(prompt: AuthPrompt): Promise<string>; 30 /** Reports a login event as styled scrollback lines. */ 31 notify(event: AuthEvent): void; 32} 33 34export interface Command { 35 name: string; // no leading slash, lowercase 36 description: string; // one line, shown by /help 37 run(ctx: CommandContext, args: string): void | Promise<void>; 38} 39 40/** The keybindings the TUI accepts, in the order `/help` prints them. */ 41const KEYBINDINGS: [string, string][] = [ 42 ["Enter", "submit"], 43 ["Shift+Enter", "newline (Ctrl+J also works)"], 44 ["Esc", "pause the turn at the next step boundary"], 45 ["Ctrl+C", "cancel the turn"], 46 ["Ctrl+D", "exit on an empty draft"], 47 ["Tab", "complete command or path"], 48]; 49 50/** One aligned `key description` block; the key column is dimmed. */ 51function keyed(rows: [string, string][], width: number): string[] { 52 return rows.map(([key, description]) => ` ${dim(key.padEnd(width))} ${description}`); 53} 54 55const help: Command = { 56 name: "help", 57 description: "list commands and keybindings", 58 run(ctx): void { 59 const names = COMMANDS.map((command): [string, string] => [`/${command.name}`, command.description]); 60 const width = Math.max(...names.map(([key]) => key.length), ...KEYBINDINGS.map(([key]) => key.length)); 61 ctx.write(["commands", ...keyed(names, width), "", "keybindings", ...keyed(KEYBINDINGS, width)]); 62 }, 63}; 64 65const login: Command = { 66 name: "login", 67 description: "authenticate a provider", 68 async run(ctx, args): Promise<void> { 69 const providers = ctx.models 70 .getProviders() 71 .filter((provider) => provider.auth.oauth?.login !== undefined || provider.auth.apiKey?.login !== undefined); 72 const providerId = 73 args.trim() || 74 (await ctx.prompt({ 75 type: "select", 76 message: "Select a provider", 77 options: providers.map((provider) => ({ id: provider.id, label: provider.name })), 78 })); 79 const provider = ctx.models.getProvider(providerId); 80 if (provider === undefined) throw new Error(`unknown provider: ${providerId}`); 81 82 const oauth = provider.auth.oauth; 83 const apiKey = provider.auth.apiKey; 84 const types: { id: AuthType; label: string }[] = []; 85 if (oauth?.login !== undefined) { 86 types.push({ id: "oauth", label: oauth.loginLabel ?? oauth.name }); 87 } 88 if (apiKey?.login !== undefined) types.push({ id: "api_key", label: apiKey.name }); 89 if (types.length === 0) throw new Error(`provider "${providerId}" has no login flow`); 90 const type = 91 types.length === 1 92 ? types[0].id 93 : ((await ctx.prompt({ 94 type: "select", 95 message: `How would you like to authenticate with ${provider.name}?`, 96 options: types, 97 })) as AuthType); 98 99 try { 100 await ctx.models.login(providerId, type, { 101 signal: ctx.signal, 102 prompt: (prompt) => ctx.prompt(prompt), 103 notify: (event) => ctx.notify(event), 104 }); 105 } catch (error) { 106 if (ctx.signal.aborted) { 107 ctx.write([red("! cancelled")]); 108 return; 109 } 110 throw error; 111 } 112 const source = (await ctx.models.getAuth(providerId))?.source; 113 ctx.write([`logged in to ${provider.name}${source === undefined ? "" : ` (${source})`}`]); 114 }, 115}; 116 117/** Prompts for one of `models`, persists the choice, and switches to it. */ 118async function chooseModel(ctx: CommandContext, providerId: string, models: readonly Model<Api>[]): Promise<void> { 119 if (models.length === 0) throw new Error(`no models for provider "${providerId}"`); 120 const name = ctx.models.getProvider(providerId)?.name ?? providerId; 121 const modelId = await ctx.prompt({ 122 type: "select", 123 message: `Select a model for ${name}`, 124 options: models.map((m) => ({ id: m.id, label: m.name ?? m.id })), 125 }); 126 const chosen = models.find((m) => m.id === modelId); 127 if (chosen === undefined) throw new Error(`unknown model: ${modelId}`); 128 saveConfig({ provider: providerId, model: modelId }); 129 ctx.select(chosen); 130} 131 132const provider: Command = { 133 name: "provider", 134 description: "choose the provider and model", 135 async run(ctx): Promise<void> { 136 const available = await ctx.models.getAvailable(undefined, { signal: ctx.signal }); 137 const ids = [...new Set(available.map((m) => m.provider))]; 138 if (ids.length === 0) throw new Error("no authenticated providers"); 139 const providerId = await ctx.prompt({ 140 type: "select", 141 message: "Select a provider", 142 options: ids.map((id) => ({ id, label: ctx.models.getProvider(id)?.name ?? id })), 143 }); 144 await chooseModel(ctx, providerId, available.filter((m) => m.provider === providerId)); 145 }, 146}; 147 148const thinking: Command = { 149 name: "thinking", 150 description: "set the thinking level", 151 async run(ctx): Promise<void> { 152 if (ctx.model === null) throw new Error("no model configured"); 153 const levels = getSupportedThinkingLevels(ctx.model); 154 const level = (await ctx.prompt({ 155 type: "select", 156 message: "Select a thinking level", 157 options: levels.map((l) => ({ id: l, label: l })), 158 })) as ModelThinkingLevel; 159 saveConfig({ thinkingEffort: level }); 160 ctx.setThinking(level); 161 }, 162}; 163 164const model: Command = { 165 name: "model", 166 description: "choose a model for the current provider", 167 async run(ctx): Promise<void> { 168 if (ctx.model === null) throw new Error("no model configured"); 169 const providerId = ctx.model.provider; 170 const models = await ctx.models.getAvailable(providerId, { signal: ctx.signal }); 171 await chooseModel(ctx, providerId, models); 172 }, 173}; 174 175const COMMANDS: Command[] = [help, login, provider, model, thinking]; 176 177/** `/name` for a known `name`, else null; unknown slash text stays a message. */ 178export function findCommand(text: string): { command: Command; args: string } | null { 179 const match = /^\/(\S+)(?:\s+([\s\S]*))?$/.exec(text); 180 if (match === null) return null; 181 const command = COMMANDS.find((candidate) => candidate.name === match[1]); 182 return command === undefined ? null : { command, args: match[2] ?? "" }; 183} 184 185/** Tab completion for a half-typed command name; null leaves the draft alone. */ 186export function completeCommand(draft: string): string | null { 187 if (!draft.startsWith("/") || /\s/.test(draft)) return null; 188 const typed = draft.slice(1); 189 const matches = COMMANDS.filter((command) => command.name.startsWith(typed)); 190 if (matches.length === 0) return null; 191 if (matches.length === 1) return `/${matches[0].name}`; 192 const shared = matches.map((command) => command.name).reduce(commonPrefix); 193 return shared === typed ? null : `/${shared}`; 194} 195