xonecas.io
64875
Mc

mini-coder / commit 884bdc7

feat: /provider and /model selection, persisted to config

Add two TUI commands. /provider lists authenticated providers then that
provider's models; /model lists the current provider's models. Both query
pi-ai at command time (no startup cost), switch the running session live
(re-clamping thinking effort and rebuilding tools), and persist the pair
to the global config via an atomic write that preserves all other keys.

xonecas2026-09-26 884bdc7d8713b3deeba3c53bef28c7bf5feadabc parent f40e83b

5 files changed

src/agent.ts+3−0
@@ -12,6 +12,7 @@ import {
1212 type UserMessage,
1313 } from "@earendil-works/pi-ai";
1414 import type { Session } from "./session.ts";
15+import type { ToolName } from "./config.ts";
1516 import { acceptsImages, executeTool, type ToolDetails, type ToolResult } from "./tools/index.ts";
1617
1718 export type Phase = "preparing" | "waitingModel" | "streaming" | "runningTool" | "pausing" | "idle";
@@ -47,6 +48,8 @@ export interface AgentOptions {
4748 model: Model<Api>;
4849 systemPrompt: string;
4950 tools: Tool[];
51+ /** The configured tool names, kept so a model switch can rebuild `tools`. */
52+ toolNames: ToolName[];
5053 thinkingEffort: ModelThinkingLevel;
5154 session: Session;
5255 }
src/cli.ts+1−0
@@ -77,6 +77,7 @@ async function main(): Promise<void> {
7777 model,
7878 systemPrompt: buildSystemPrompt(config),
7979 tools: toolSchemas(config.tools, acceptsImages(model)),
80+ toolNames: config.tools,
8081 thinkingEffort: clampThinkingLevel(model, config.thinkingEffort),
8182 session,
8283 };
src/config.ts+19−2
@@ -1,6 +1,6 @@
1-import { readFileSync } from "node:fs";
1+import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
22 import { homedir } from "node:os";
3-import { join } from "node:path";
3+import { dirname, join } from "node:path";
44 import {
55 createProvider,
66 envApiKeyAuth,
@@ -104,6 +104,23 @@ export function loadConfig(): Config {
104104 }
105105 }
106106
107+/**
108+ * Persist the chosen pair to the global config, leaving every other key
109+ * untouched. Written atomically: a temp file, then a rename over the target.
110+ */
111+export function saveSelection(provider: string, model: string): void {
112+ const path = configPath();
113+ const existing = readJson(path);
114+ if (typeof existing !== "object" || existing === null || Array.isArray(existing)) {
115+ throw new Error(`config ${path}: not an object`);
116+ }
117+ const next = { ...existing, provider, model };
118+ mkdirSync(dirname(path), { recursive: true });
119+ const temp = join(dirname(path), `.${process.pid}.${Date.now()}.tmp`);
120+ writeFileSync(temp, `${JSON.stringify(next, null, 2)}\n`);
121+ renameSync(temp, path);
122+}
123+
107124 const API_FACTORY: Record<CustomApi, () => ReturnType<typeof openAICompletionsApi>> = {
108125 "openai-completions": openAICompletionsApi,
109126 "openai-responses": openAIResponsesApi,
src/tui/commands.ts+54−2
@@ -1,10 +1,15 @@
1-import type { AuthEvent, AuthPrompt, AuthType, Models } from "@earendil-works/pi-ai";
1+import type { Api, AuthEvent, AuthPrompt, AuthType, Model, Models } from "@earendil-works/pi-ai";
2+import { saveSelection } from "../config.ts";
23 import { dim, red } from "./styles.ts";
34 import { commonPrefix } from "./complete.ts";
45
56 export interface CommandContext {
67 /** The collection the running command may reach, e.g. to start a login. */
78 models: Models;
9+ /** The model the session is currently running. */
10+ model: Model<Api>;
11+ /** Switches the running session to `model`. */
12+ select(model: Model<Api>): void;
813 /** Aborts when the running command is cancelled (Ctrl+C). */
914 signal: AbortSignal;
1015 /** Appends already-styled lines to scrollback. */
@@ -98,7 +103,54 @@ const login: Command = {
98103 },
99104 };
100105
101-const COMMANDS: Command[] = [help, login];
106+const provider: Command = {
107+ name: "provider",
108+ description: "choose the provider and model",
109+ async run(ctx): Promise<void> {
110+ const available = await ctx.models.getAvailable(undefined, { signal: ctx.signal });
111+ const ids = [...new Set(available.map((m) => m.provider))];
112+ if (ids.length === 0) throw new Error("no authenticated providers");
113+ const providerId = await ctx.prompt({
114+ type: "select",
115+ message: "Select a provider",
116+ options: ids.map((id) => ({ id, label: ctx.models.getProvider(id)?.name ?? id })),
117+ });
118+ const models = available.filter((m) => m.provider === providerId);
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+ saveSelection(providerId, modelId);
129+ ctx.select(chosen);
130+ },
131+};
132+
133+const model: Command = {
134+ name: "model",
135+ description: "choose a model for the current provider",
136+ async run(ctx): Promise<void> {
137+ const providerId = ctx.model.provider;
138+ const models = await ctx.models.getAvailable(providerId, { signal: ctx.signal });
139+ if (models.length === 0) throw new Error(`no models for provider "${providerId}"`);
140+ const name = ctx.models.getProvider(providerId)?.name ?? providerId;
141+ const modelId = await ctx.prompt({
142+ type: "select",
143+ message: `Select a model for ${name}`,
144+ options: models.map((m) => ({ id: m.id, label: m.name ?? m.id })),
145+ });
146+ const chosen = models.find((m) => m.id === modelId);
147+ if (chosen === undefined) throw new Error(`unknown model: ${modelId}`);
148+ saveSelection(providerId, modelId);
149+ ctx.select(chosen);
150+ },
151+};
152+
153+const COMMANDS: Command[] = [help, login, provider, model];
102154
103155 /** `/name` for a known `name`, else null; unknown slash text stays a message. */
104156 export function findCommand(text: string): { command: Command; args: string } | null {
src/tui/tui.ts+30−1
@@ -1,6 +1,17 @@
11 import process from "node:process";
2-import type { AssistantMessage, AuthEvent, AuthPrompt, JsonObject, Message, UserMessage } from "@earendil-works/pi-ai";
2+import {
3+ clampThinkingLevel,
4+ type Api,
5+ type AssistantMessage,
6+ type AuthEvent,
7+ type AuthPrompt,
8+ type JsonObject,
9+ type Message,
10+ type Model,
11+ type UserMessage,
12+} from "@earendil-works/pi-ai";
313 import { assistantText, runAgentTurn, type AgentEvent, type AgentOptions, type Phase } from "../agent.ts";
14+import { acceptsImages, toolSchemas } from "../tools/index.ts";
415 import { Terminal, expandTabs, sanitize, wrapLine, type Key } from "./term.ts";
516 import { Editor } from "./editor.ts";
617 import { completeCommand, findCommand, type Command, type CommandContext } from "./commands.ts";
@@ -317,6 +328,8 @@ class Tui {
317328 this.commandAbort = abort;
318329 const ctx: CommandContext = {
319330 models: this.opts.models,
331+ model: this.opts.model,
332+ select: (model) => this.select(model),
320333 signal: abort.signal,
321334 write: (lines) => {
322335 this.separator = true;
@@ -342,6 +355,22 @@ class Tui {
342355 })();
343356 }
344357
358+ /**
359+ * Switches the running session to `model`: derived state follows — the
360+ * thinking effort is re-clamped, and `read`'s image behaviour is rebuilt for
361+ * the new model. The status line and context readout read `opts.model`, so
362+ * they update on the next render.
363+ */
364+ private select(model: Model<Api>): void {
365+ this.opts.model = model;
366+ this.opts.thinkingEffort = clampThinkingLevel(model, this.opts.thinkingEffort);
367+ this.opts.tools = toolSchemas(this.opts.toolNames, acceptsImages(model));
368+ this.separator = true;
369+ this.push(`${model.provider}/${model.id}`);
370+ this.separator = true;
371+ this.render();
372+ }
373+
345374 /** Commits a prompt and returns a promise resolving with the next submitted line. */
346375 private ask(prompt: AuthPrompt): Promise<string> {
347376 if (this.pendingPrompt !== null) return Promise.reject(new Error("a prompt is already pending"));