xonecas.io
64875
Mc

mini-coder / commit f40e83b

feat: /login for provider who need it via pi-ai

xonecas2026-09-26 f40e83bb6791317d243afe42abad367bc060bf52 parent 3ec228b

5 files changed

src/auth.ts+84−0
@@ -0,0 +1,84 @@
1+import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2+import { dirname, join } from "node:path";
3+import type { AuthOperationOptions, Credential, CredentialInfo, CredentialStore } from "@earendil-works/pi-ai";
4+
5+/** The `auth.json` layout: one credential per provider id. */
6+type AuthFile = Record<string, Credential>;
7+
8+function readFile(path: string): AuthFile {
9+ try {
10+ return JSON.parse(readFileSync(path, "utf8")) as AuthFile;
11+ } catch (error) {
12+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
13+ throw error;
14+ }
15+}
16+
17+/** Write the whole file atomically: temp file, then rename over the target. */
18+function writeFile(path: string, data: AuthFile): void {
19+ mkdirSync(dirname(path), { recursive: true });
20+ const temp = join(dirname(path), `.${process.pid}.${Date.now()}.tmp`);
21+ writeFileSync(temp, `${JSON.stringify(data, null, 2)}\n`);
22+ renameSync(temp, path);
23+}
24+
25+/**
26+ * File-backed `CredentialStore` over `auth.json`. Writes are serialized per
27+ * provider through an in-process promise chain, so `modify` and `delete` on
28+ * the same provider never interleave.
29+ */
30+export function createCredentialStore(path: string): CredentialStore {
31+ const chains = new Map<string, Promise<unknown>>();
32+
33+ function enqueue<T>(providerId: string, task: () => Promise<T>, options?: AuthOperationOptions): Promise<T> {
34+ options?.signal?.throwIfAborted();
35+ const previous = chains.get(providerId) ?? Promise.resolve();
36+ const queued = (async () => {
37+ await previous.catch(() => {});
38+ options?.signal?.throwIfAborted();
39+ return await task();
40+ })();
41+ const tail = queued.catch(() => {});
42+ chains.set(providerId, tail);
43+ void tail.then(() => {
44+ if (chains.get(providerId) === tail) chains.delete(providerId);
45+ });
46+ return queued;
47+ }
48+
49+ return {
50+ async read(providerId, options): Promise<Credential | undefined> {
51+ options?.signal?.throwIfAborted();
52+ return readFile(path)[providerId];
53+ },
54+ async list(options): Promise<readonly CredentialInfo[]> {
55+ options?.signal?.throwIfAborted();
56+ return Object.entries(readFile(path)).map(([providerId, credential]) => ({ providerId, type: credential.type }));
57+ },
58+ modify(providerId, fn, options): Promise<Credential | undefined> {
59+ return enqueue(
60+ providerId,
61+ async () => {
62+ const data = readFile(path);
63+ const next = await fn(data[providerId]);
64+ options?.signal?.throwIfAborted();
65+ if (next !== undefined) data[providerId] = next;
66+ writeFile(path, data);
67+ return next ?? data[providerId];
68+ },
69+ options,
70+ );
71+ },
72+ delete(providerId, options): Promise<void> {
73+ return enqueue(
74+ providerId,
75+ async () => {
76+ const data = readFile(path);
77+ delete data[providerId];
78+ writeFile(path, data);
79+ },
80+ options,
81+ );
82+ },
83+ };
84+}
src/config.ts+9−3
@@ -16,6 +16,7 @@ import { anthropicMessagesApi } from "@earendil-works/pi-ai/api/anthropic-messag
1616 import { googleGenerativeAIApi } from "@earendil-works/pi-ai/api/google-generative-ai.lazy";
1717 import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
1818 import { openAIResponsesApi } from "@earendil-works/pi-ai/api/openai-responses.lazy";
19+import { createCredentialStore } from "./auth.ts";
1920
2021 const ToolNameSchema = Type.Union([Type.Literal("edit"), Type.Literal("read"), Type.Literal("bash")]);
2122 export type ToolName = Static<typeof ToolNameSchema>;
@@ -44,6 +45,7 @@ const CustomProviderSchema = Type.Object(
4445 const ConfigSchema = Type.Object(
4546 {
4647 sessionsDir: Type.String({ default: join(process.cwd(), "sessions") }),
48+ authFile: Type.String({ default: join(configDir(), "auth.json") }),
4749 systemPrompt: Type.String({ default: "" }),
4850 discoverAgentFiles: Type.Boolean({ default: true }),
4951 skillsDirs: Type.Array(Type.String(), { default: [] }),
@@ -67,9 +69,13 @@ const ConfigSchema = Type.Object(
6769 );
6870 export type Config = Static<typeof ConfigSchema>;
6971
70-function configPath(): string {
72+function configDir(): string {
7173 const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
72- return join(base, "mini-coder", "config.json");
74+ return join(base, "mini-coder");
75+}
76+
77+function configPath(): string {
78+ return join(configDir(), "config.json");
7379 }
7480
7581 function readJson(path: string): unknown {
@@ -106,7 +112,7 @@ const API_FACTORY: Record<CustomApi, () => ReturnType<typeof openAICompletionsAp
106112 };
107113
108114 export function resolveModel(config: Config): { models: MutableModels; model: Model<Api> } {
109- const models = builtinModels();
115+ const models = builtinModels({ credentials: createCredentialStore(config.authFile) });
110116 for (const provider of config.customProviders) {
111117 const name = provider.name ?? provider.id;
112118 models.setProvider(
src/tui/commands.ts+70−7
@@ -1,15 +1,24 @@
1-import { dim } from "./styles.ts";
1+import type { AuthEvent, AuthPrompt, AuthType, Models } from "@earendil-works/pi-ai";
2+import { dim, red } from "./styles.ts";
23 import { commonPrefix } from "./complete.ts";
34
45 export interface CommandContext {
6+ /** The collection the running command may reach, e.g. to start a login. */
7+ models: Models;
8+ /** Aborts when the running command is cancelled (Ctrl+C). */
9+ signal: AbortSignal;
510 /** Appends already-styled lines to scrollback. */
611 write(lines: string[]): void;
12+ /** Asks the user a question and resolves with the next submitted line. */
13+ prompt(prompt: AuthPrompt): Promise<string>;
14+ /** Reports a login event as styled scrollback lines. */
15+ notify(event: AuthEvent): void;
716 }
817
9-interface Command {
18+export interface Command {
1019 name: string; // no leading slash, lowercase
1120 description: string; // one line, shown by /help
12- run(ctx: CommandContext): void;
21+ run(ctx: CommandContext, args: string): void | Promise<void>;
1322 }
1423
1524 /** The keybindings the TUI accepts, in the order `/help` prints them. */
@@ -37,12 +46,66 @@ const help: Command = {
3746 },
3847 };
3948
40-const COMMANDS: Command[] = [help];
49+const login: Command = {
50+ name: "login",
51+ description: "authenticate a provider",
52+ async run(ctx, args): Promise<void> {
53+ const providers = ctx.models
54+ .getProviders()
55+ .filter((provider) => provider.auth.oauth?.login !== undefined || provider.auth.apiKey?.login !== undefined);
56+ const providerId =
57+ args.trim() ||
58+ (await ctx.prompt({
59+ type: "select",
60+ message: "Select a provider",
61+ options: providers.map((provider) => ({ id: provider.id, label: provider.name })),
62+ }));
63+ const provider = ctx.models.getProvider(providerId);
64+ if (provider === undefined) throw new Error(`unknown provider: ${providerId}`);
65+
66+ const oauth = provider.auth.oauth;
67+ const apiKey = provider.auth.apiKey;
68+ const types: { id: AuthType; label: string }[] = [];
69+ if (oauth?.login !== undefined) {
70+ types.push({ id: "oauth", label: oauth.loginLabel ?? oauth.name });
71+ }
72+ if (apiKey?.login !== undefined) types.push({ id: "api_key", label: apiKey.name });
73+ if (types.length === 0) throw new Error(`provider "${providerId}" has no login flow`);
74+ const type =
75+ types.length === 1
76+ ? types[0].id
77+ : ((await ctx.prompt({
78+ type: "select",
79+ message: `How would you like to authenticate with ${provider.name}?`,
80+ options: types,
81+ })) as AuthType);
82+
83+ try {
84+ await ctx.models.login(providerId, type, {
85+ signal: ctx.signal,
86+ prompt: (prompt) => ctx.prompt(prompt),
87+ notify: (event) => ctx.notify(event),
88+ });
89+ } catch (error) {
90+ if (ctx.signal.aborted) {
91+ ctx.write([red("! cancelled")]);
92+ return;
93+ }
94+ throw error;
95+ }
96+ const source = (await ctx.models.getAuth(providerId))?.source;
97+ ctx.write([`logged in to ${provider.name}${source === undefined ? "" : ` (${source})`}`]);
98+ },
99+};
100+
101+const COMMANDS: Command[] = [help, login];
41102
42103 /** `/name` for a known `name`, else null; unknown slash text stays a message. */
43-export function findCommand(text: string): Command | null {
44- const match = /^\/(\S+)/.exec(text);
45- return match === null ? null : (COMMANDS.find((candidate) => candidate.name === match[1]) ?? null);
104+export function findCommand(text: string): { command: Command; args: string } | null {
105+ const match = /^\/(\S+)(?:\s+([\s\S]*))?$/.exec(text);
106+ if (match === null) return null;
107+ const command = COMMANDS.find((candidate) => candidate.name === match[1]);
108+ return command === undefined ? null : { command, args: match[2] ?? "" };
46109 }
47110
48111 /** Tab completion for a half-typed command name; null leaves the draft alone. */
src/tui/editor.ts+12−2
@@ -39,11 +39,21 @@ export class Editor {
3939 private col = 0;
4040 private scroll = 0;
4141 private width = DEFAULT_WIDTH;
42+ private masked = false;
4243
4344 text(): string {
4445 return this.lines.join("\n");
4546 }
4647
48+ /** Renders each character as `*` without changing the underlying text. */
49+ setMasked(masked: boolean): void {
50+ this.masked = masked;
51+ }
52+
53+ private display(line: string): string {
54+ return this.masked ? "*".repeat(codePoints(line).length) : line;
55+ }
56+
4757 clear(): void {
4858 this.lines = [""];
4959 this.row = 0;
@@ -121,7 +131,7 @@ export class Editor {
121131 let cursorRow = 0;
122132 let cursorCol = 0;
123133 for (let line = 0; line < this.lines.length; line++) {
124- const chunks = wrapLine(expandTabs(this.lines[line], TAB), this.width);
134+ const chunks = wrapLine(expandTabs(this.display(this.lines[line]), TAB), this.width);
125135 if (line === this.row) {
126136 const caret = this.caret();
127137 cursorRow = rows.length + caret.row;
@@ -142,7 +152,7 @@ export class Editor {
142152
143153 /** The caret's display row within its logical line, and its cell column. */
144154 private caret(): { row: number; col: number } {
145- const line = this.lines[this.row];
155+ const line = this.display(this.lines[this.row]);
146156 const chunks = wrapLine(expandTabs(line, TAB), this.width);
147157 const cell = this.cells(line)[this.col];
148158 const row = Math.floor(cell / this.width);
src/tui/tui.ts+137−14
@@ -1,9 +1,9 @@
11 import process from "node:process";
2-import type { AssistantMessage, JsonObject, Message, UserMessage } from "@earendil-works/pi-ai";
2+import type { AssistantMessage, AuthEvent, AuthPrompt, JsonObject, Message, UserMessage } from "@earendil-works/pi-ai";
33 import { assistantText, runAgentTurn, type AgentEvent, type AgentOptions, type Phase } from "../agent.ts";
44 import { Terminal, expandTabs, sanitize, wrapLine, type Key } from "./term.ts";
55 import { Editor } from "./editor.ts";
6-import { completeCommand, findCommand, type CommandContext } from "./commands.ts";
6+import { completeCommand, findCommand, type Command, type CommandContext } from "./commands.ts";
77 import { completePath } from "./complete.ts";
88 import { MarkdownStream, TailStream, type BodyLine, type StreamRenderer } from "./stream.ts";
99 import { blue, cyan, dim, green, red, teal } from "./styles.ts";
@@ -177,14 +177,13 @@ class Tui {
177177 private readonly messages: Message[] = [];
178178 readonly done: Promise<void>;
179179
180- /** The only capability a command gets: styled lines into scrollback. */
181- private readonly commandContext: CommandContext = {
182- write: (lines) => {
183- this.separator = true;
184- this.commitLines(lines.map((text) => ({ text })));
185- this.separator = true;
186- },
187- };
180+ /** A running command's cancellation, and its one pending prompt. */
181+ private commandAbort: AbortController | null = null;
182+ private pendingPrompt: {
183+ prompt: AuthPrompt;
184+ resolve: (value: string) => void;
185+ reject: (error: Error) => void;
186+ } | null = null;
188187
189188 private resolveExit: () => void = () => {};
190189 private phase: Phase = "idle";
@@ -241,11 +240,12 @@ class Tui {
241240
242241 private handleKey(key: Key): void {
243242 if (key.type === "eof") {
244- if (!this.active && this.editor.text() === "") this.exit();
243+ if (!this.active && this.commandAbort === null && this.editor.text() === "") this.exit();
245244 return;
246245 }
247246 if (key.type === "interrupt") {
248247 if (this.active) this.cancel();
248+ else if (this.commandAbort !== null) this.commandAbort.abort();
249249 else if (this.editor.text() !== "") {
250250 this.editor.clear();
251251 this.render();
@@ -284,11 +284,18 @@ class Tui {
284284 }
285285 return;
286286 }
287+ if (this.pendingPrompt !== null) {
288+ this.editor.clear();
289+ this.render();
290+ this.answerPrompt(text);
291+ return;
292+ }
293+ if (this.commandAbort !== null) return;
287294 if (text.trim() === "") return;
288- const command = findCommand(text);
289- if (command !== null) {
295+ const found = findCommand(text);
296+ if (found !== null) {
290297 this.editor.clear();
291- command.run(this.commandContext);
298+ this.runCommand(found.command, found.args);
292299 this.render();
293300 return;
294301 }
@@ -300,6 +307,121 @@ class Tui {
300307 this.startTurn();
301308 }
302309
310+ /**
311+ * Runs one command with a fresh context. Lines submitted while it runs route
312+ * to a pending prompt; Ctrl+C aborts its signal. No agent turn may start
313+ * until it settles. Errors surface as an error line.
314+ */
315+ private runCommand(command: Command, args: string): void {
316+ const abort = new AbortController();
317+ this.commandAbort = abort;
318+ const ctx: CommandContext = {
319+ models: this.opts.models,
320+ signal: abort.signal,
321+ write: (lines) => {
322+ this.separator = true;
323+ this.commitLines(lines.map((text) => ({ text })));
324+ this.separator = true;
325+ },
326+ prompt: (prompt) => this.ask(prompt),
327+ notify: (event) => this.notify(event),
328+ };
329+ void (async () => {
330+ try {
331+ await command.run(ctx, args);
332+ } catch (error) {
333+ this.separator = true;
334+ this.push(red(`! ${(error as Error).message}`));
335+ this.separator = true;
336+ } finally {
337+ this.commandAbort = null;
338+ this.pendingPrompt = null;
339+ this.editor.setMasked(false);
340+ this.render();
341+ }
342+ })();
343+ }
344+
345+ /** Commits a prompt and returns a promise resolving with the next submitted line. */
346+ private ask(prompt: AuthPrompt): Promise<string> {
347+ if (this.pendingPrompt !== null) return Promise.reject(new Error("a prompt is already pending"));
348+ this.separator = true;
349+ this.push(prompt.message);
350+ if (prompt.type === "select") {
351+ for (let i = 0; i < prompt.options.length; i++) this.push(` ${i + 1}. ${prompt.options[i].label}`);
352+ } else if (prompt.placeholder !== undefined) {
353+ this.push(` (${prompt.placeholder})`);
354+ }
355+ this.separator = true;
356+ this.editor.setMasked(prompt.type === "secret");
357+ this.render();
358+
359+ return new Promise<string>((resolve, reject) => {
360+ const flow = this.commandAbort?.signal;
361+ const onAbort = (): void => {
362+ settle(() => reject(new Error("cancelled")));
363+ };
364+ const settle = (fn: () => void): void => {
365+ prompt.signal?.removeEventListener("abort", onAbort);
366+ flow?.removeEventListener("abort", onAbort);
367+ this.editor.setMasked(false);
368+ this.pendingPrompt = null;
369+ this.render();
370+ fn();
371+ };
372+ if (prompt.signal?.aborted === true || flow?.aborted === true) {
373+ onAbort();
374+ return;
375+ }
376+ prompt.signal?.addEventListener("abort", onAbort);
377+ flow?.addEventListener("abort", onAbort);
378+ this.pendingPrompt = {
379+ prompt,
380+ resolve: (value) => settle(() => resolve(value)),
381+ reject: (error) => settle(() => reject(error)),
382+ };
383+ });
384+ }
385+
386+ /** Turns the submitted line into the answer: a `select` maps to its option id. */
387+ private answerPrompt(text: string): void {
388+ const pending = this.pendingPrompt;
389+ if (pending === null) return;
390+ if (pending.prompt.type !== "select") {
391+ pending.resolve(text);
392+ return;
393+ }
394+ const trimmed = text.trim();
395+ const index = Number.parseInt(trimmed, 10);
396+ const byIndex = String(index) === trimmed ? pending.prompt.options[index - 1] : undefined;
397+ const chosen = byIndex ?? pending.prompt.options.find((option) => option.id === trimmed || option.label === trimmed);
398+ if (chosen === undefined) pending.reject(new Error(`invalid selection: ${trimmed}`));
399+ else pending.resolve(chosen.id);
400+ }
401+
402+ private notify(event: AuthEvent): void {
403+ this.separator = true;
404+ switch (event.type) {
405+ case "info":
406+ this.push(event.message);
407+ for (const link of event.links ?? []) this.push(link.label === undefined ? link.url : `${link.label}: ${link.url}`);
408+ break;
409+ case "auth_url":
410+ this.push(event.url);
411+ if (event.instructions !== undefined) this.push(event.instructions);
412+ break;
413+ case "device_code":
414+ this.push(event.verificationUri);
415+ this.push(`code: ${event.userCode}`);
416+ if (event.expiresInSeconds !== undefined) this.push(`expires in ${event.expiresInSeconds}s`);
417+ break;
418+ case "progress":
419+ this.push(event.message);
420+ break;
421+ }
422+ this.separator = true;
423+ }
424+
303425 private startTurn(): void {
304426 this.active = true;
305427 this.abort = new AbortController();
@@ -574,6 +696,7 @@ class Tui {
574696 if (this.closed) return;
575697 this.closed = true;
576698 this.abort?.abort();
699+ this.commandAbort?.abort();
577700 if (this.spinner) clearInterval(this.spinner);
578701 this.spinner = undefined;
579702 // Draws are deferred, so anything pushed since the last frame is still here.