@@ -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.