xonecas.io
64875
Mc

mini-coder / files

mini-coder / src / tui / tui.ts

27.9 KB
1import process from "node:process";
2import {
3  clampThinkingLevel,
4  contentText,
5  type Api,
6  type AssistantMessage,
7  type AuthEvent,
8  type AuthPrompt,
9  type JsonObject,
10  type Message,
11  type Model,
12  type ModelThinkingLevel,
13  type UserMessage,
14} from "@earendil-works/pi-ai";
15import { runAgentTurn, type AgentEvent, type AgentOptions, type Phase } from "../agent.ts";
16import { acceptsImages, toolSchemas, type FileDiff } from "../tools/index.ts";
17import { Terminal, expandTabs, sanitize, wrapLine, type Key } from "./term.ts";
18import { Editor } from "./editor.ts";
19import { completeCommand, findCommand, type Command, type CommandContext } from "./commands.ts";
20import { completePath } from "./complete.ts";
21import { MarkdownStream, TailStream, type BodyLine, type StreamRenderer } from "./stream.ts";
22import { blue, cyan, dim, green, red, teal } from "./styles.ts";
23import { DIFF_ADD, DIFF_DELETE, NORMAL_BG, sgrBg, sgrPlain } from "./theme.ts";
24import { contextUsageLine, estimateContextTokens } from "./usage.ts";
25
26/** Status-row spinner frames; the only animation in the TUI. */
27const SPINNER = [..."⠀⠁⠂⠃⠄⠅⠆⠇⡀⡁⡂⡃⡄⡅⡆⡇⠈⠉⠊⠋⠌⠍⠎⠏⡈⡉⡊⡋⡌⡍⡎⡏⠐⠑⠒⠓⠔⠕⠖⠗⡐⡑⡒⡓⡔⡕⡖⡗⠘⠙⠚⠛⠜⠝⠞⠟⡘⡙⡚⡛⡜⡝⡞⡟⠠⠡⠢⠣⠤⠥⠦⠧⡠⡡⡢⡣⡤⡥⡦⡧⠨⠩⠪⠫⠬⠭⠮⠯⡨⡩⡪⡫⡬⡭⡮⡯⠰⠱⠲⠳⠴⠵⠶⠷⡰⡱⡲⡳⡴⡵⡶⡷⠸⠹⠺⠻⠼⠽⠾⠿⡸⡹⡺⡻⡼⡽⡾⡿⢀⢁⢂⢃⢄⢅⢆⢇⣀⣁⣂⣃⣄⣅⣆⣇⢈⢉⢊⢋⢌⢍⢎⢏⣈⣉⣊⣋⣌⣍⣎⣏⢐⢑⢒⢓⢔⢕⢖⢗⣐⣑⣒⣓⣔⣕⣖⣗⢘⢙⢚⢛⢜⢝⢞⢟⣘⣙⣚⣛⣜⣝⣞⣟⢠⢡⢢⢣⢤⢥⢦⢧⣠⣡⣢⣣⣤⣥⣦⣧⢨⢩⢪⢫⢬⢭⢮⢯⣨⣩⣪⣫⣬⣭⣮⣯⢰⢱⢲⢳⢴⢵⢶⢷⣰⣱⣲⣳⣴⣵⣶⣷⢸⢹⢺⢻⢼⢽⢾⢿⣸⣹⣺⣻⣼⣽⣾⣿"];
28const SPINNER_MS = 120;
29
30/**
31 * Display-only elision for tool bodies, deliberately worded differently from
32 * the model-facing `... output truncated ...` marker in `tools/bash.ts`.
33 * `edit` is exempt: its diffs are always shown in full.
34 */
35const MAX_BODY_ROWS = 12;
36const ELIDED_HEAD = 4;
37const ELIDED_TAIL = 4;
38
39const BODY_PREFIX = " | ";
40const ERROR_PREFIX = " ! ";
41/** The chrome prefix, styled: dim for output, red for errors; text stays `Normal`. */
42const BODY_CHROME = dim(BODY_PREFIX);
43const ERROR_CHROME = red(ERROR_PREFIX);
44const EXIT_LINE = /^exit code: (.+)$/;
45const EDIT_HEADER = /^(Index: |={3,}$|--- |\+\+\+ )/;
46
47/** The `-> <name>` head of a call line, in the tool accent; the args stay `Normal`. */
48function callHead(name: string): string {
49  return teal(`-> ${name}`);
50}
51
52function callSummary(name: string, args: JsonObject): string {
53  if (name === "bash" && typeof args.command === "string") return args.command.replace(/\s*\n\s*/g, " ");
54  if ((name === "edit" || name === "read") && typeof args.path === "string") return args.path;
55  return JSON.stringify(args);
56}
57
58/**
59 * Unified-diff styling for one `edit` body line; file headers are stripped.
60 * Additions and deletions carry the `DiffAdd`/`DiffDelete` background, so every
61 * cell of the line — the trailing ones `paintRow` erases included — is tinted.
62 */
63function diffLine(line: string): BodyLine {
64  if (line.startsWith("@@")) return { text: line, style: cyan };
65  if (line.startsWith("+")) return { text: line, style: green, bg: DIFF_ADD };
66  if (line.startsWith("-")) return { text: line, style: red, bg: DIFF_DELETE };
67  if (line.startsWith("\\ No newline")) return { text: line, style: dim };
68  if (line.startsWith(" ")) return { text: line, style: dim };
69  return { text: line };
70}
71
72/** Display rewrite of a tool result, by tool name. */
73function resultLines(name: string, text: string, isError: boolean): BodyLine[] {
74  const lines = text.trimEnd().split("\n");
75  let diff = false;
76  if (name === "bash") {
77    const exit = EXIT_LINE.exec(lines[lines.length - 1]);
78    if (exit !== null) {
79      lines.pop();
80      if (isError) lines.push(red(`exit ${exit[1]}`));
81    }
82  } else if (name === "edit" && /^(edited|created) /.test(lines[0])) {
83    lines.shift();
84    // The call line already names the path; drop the repeated diff file header.
85    while (lines.length > 0 && EDIT_HEADER.test(lines[0])) lines.shift();
86    diff = true;
87  }
88  return lines.map((line) => (diff ? diffLine(line) : { text: line }));
89}
90
91/**
92 * Styled lines for a `bash` call's changed files: one label per file, then its
93 * patch body with the file headers stripped, or a note when no patch exists.
94 * Shown in full, like `edit`.
95 */
96function diffRows(diffs: FileDiff[]): BodyLine[] {
97  const out: BodyLine[] = [];
98  for (const d of diffs) {
99    out.push({ text: d.path, style: cyan });
100    if (d.patch !== undefined) {
101      const lines = d.patch.trimEnd().split("\n");
102      while (lines.length > 0 && EDIT_HEADER.test(lines[0])) lines.shift();
103      for (const line of lines) out.push(diffLine(line));
104    } else if (d.note !== undefined) {
105      out.push({ text: d.note, style: dim });
106    }
107  }
108  return out;
109}
110
111/**
112 * Wraps plain text, then styles each row: styling after the break is what lets a
113 * continuation row inherit its source line's style. A continuation row carries
114 * no marker; empty rows stay unstyled.
115 */
116function renderRows(lines: BodyLine[], width: number): string[] {
117  return lines.flatMap((line) => {
118    const { style, bg } = line;
119    const wrapped = wrapLine(expandTabs(sanitize(line.text)), width);
120    return wrapped.map((row) => {
121      if (row === "") return row;
122      const styled = style === undefined ? row : style(row);
123      // The row's own background opens and closes it. A markdown span that
124      // carries a background (a heading tint, inline code) can still be open
125      // where the row ends, and `paintRow`'s trailing erase fills with whatever
126      // background is current — so the row has to hand it back its own.
127      const rowBg = sgrBg(bg ?? NORMAL_BG);
128      return `${rowBg}${styled}${rowBg}`;
129    });
130  });
131}
132
133/**
134 * Paints one written row: the palette's pair, the row's own styling, then
135 * `ESC[K` — erase to the end of the line, which the terminal does *with the
136 * row's current background*. The row's trailing cells take the row's own
137 * background (the diff tints included) without a glyph being written for them,
138 * so a short row has no cell left to the host. Padding with spaces would look
139 * the same, but a terminal that reflows on a narrower resize would then wrap
140 * every row and lose the live region's anchor.
141 */
142function paintRow(line: string): string {
143  return `${sgrPlain()}${line}\x1b[K`;
144}
145
146/** `renderRows` plus the display-only elision applied to long tool bodies. */
147function bodyRows(lines: BodyLine[], width: number): string[] {
148  const rows = renderRows(lines, width);
149  if (rows.length > MAX_BODY_ROWS) {
150    const hidden = rows.length - ELIDED_HEAD - ELIDED_TAIL;
151    return [
152      ...rows.slice(0, ELIDED_HEAD),
153      dim(`... ${hidden} lines not shown ...`),
154      ...rows.slice(rows.length - ELIDED_TAIL),
155    ];
156  }
157  return rows;
158}
159
160class LiveRegion {
161  private rows = 0;
162  private cursorUp = 0;
163
164  /** Rows the region currently occupies on screen. */
165  get height(): number {
166    return this.rows;
167  }
168
169  clear(): string {
170    if (this.rows === 0) return "";
171    let out = "";
172    if (this.cursorUp > 0) out += `\x1b[${this.cursorUp}B`;
173    if (this.rows > 1) out += `\x1b[${this.rows - 1}A`;
174    // `ESC[J` erases with the *current* background, so the palette's is set
175    // first: without it the erase bites host-coloured holes and the region
176    // flashes the terminal's background while typing.
177    out += `\r${sgrPlain()}\x1b[J`;
178    this.rows = 0;
179    this.cursorUp = 0;
180    return out;
181  }
182
183  /**
184   * `lines` are already styled; the live region adds no attributes of its own.
185   * `above` is written between the clear and the body, so scrollback lands
186   * where the region was.
187   */
188  draw(lines: string[], cursorRow: number, cursorCol: number, above: string): string {
189    let out = this.clear();
190    out += above;
191    for (let i = 0; i < lines.length; i++) {
192      if (i > 0) out += "\r\n";
193      out += lines[i];
194    }
195    const up = lines.length - 1 - cursorRow;
196    if (up > 0) out += `\x1b[${up}A`;
197    out += "\r";
198    if (cursorCol > 0) out += `\x1b[${cursorCol + 1}G`;
199    this.rows = lines.length;
200    this.cursorUp = up;
201    return out;
202  }
203}
204
205class Tui {
206  private readonly opts: AgentOptions;
207  private readonly term: Terminal;
208  private readonly editor = new Editor();
209  private readonly live = new LiveRegion();
210  private readonly messages: Message[] = [];
211  readonly done: Promise<void>;
212
213  /** A running command's cancellation, and its one pending prompt. */
214  private commandAbort: AbortController | null = null;
215  private pendingPrompt: {
216    prompt: AuthPrompt;
217    resolve: (value: string) => void;
218    reject: (error: Error) => void;
219  } | null = null;
220
221  private resolveExit: () => void = () => {};
222  private phase: Phase = "idle";
223  private detail: string | undefined;
224  private writingTool: string | undefined;
225  private active = false;
226  private paused = false;
227  private pauseRequested = false;
228  private steeringResolve: ((text: string) => void) | null = null;
229  private abort: AbortController | null = null;
230  private renderScheduled = false;
231  private closed = false;
232
233  // Scrollback: lines accumulate here and are written above the live region.
234  private scroll = "";
235  private wrote = false;
236  private lastBlank = false;
237  private separator = false;
238
239  // In-flight stream state, never persisted: all display-only.
240  private readonly reply: StreamRenderer = new MarkdownStream();
241  private readonly activity: StreamRenderer = new TailStream();
242  private pendingCalls: BodyLine[] = [];
243  private streamed = "";
244  private turnStart = 0;
245  private frame = 0;
246  private spinner: NodeJS.Timeout | undefined;
247
248  constructor(opts: AgentOptions) {
249    this.opts = opts;
250    this.term = new Terminal({
251      onKey: (key) => this.handleKey(key),
252      // A reflow moves the region but leaves the cursor on the line it was on,
253      // so the region's top is still `cursorUp` rows above it. Redraw over the
254      // old region instead of dropping the anchor, which would leave it behind.
255      onResize: () => this.render(),
256    });
257    this.done = new Promise((resolve) => {
258      this.resolveExit = resolve;
259    });
260  }
261
262  start(): void {
263    this.term.start();
264    process.on("SIGINT", this.onSignal);
265    process.on("SIGTERM", this.onSignal);
266    this.pushBanner();
267    this.render();
268  }
269
270  private onSignal = (): void => this.exit();
271
272  private handleKey(key: Key): void {
273    if (key.type === "eof") {
274      if (!this.active && this.commandAbort === null && this.editor.text() === "") this.exit();
275      return;
276    }
277    if (key.type === "interrupt") {
278      if (this.active) this.cancel();
279      else if (this.commandAbort !== null) this.commandAbort.abort();
280      else if (this.editor.text() !== "") {
281        this.editor.clear();
282        this.render();
283      }
284      return;
285    }
286    if (key.type === "escape") {
287      if (this.active && !this.paused) {
288        this.pauseRequested = true;
289        this.render();
290      }
291      return;
292    }
293    if (key.type === "tab") {
294      const completed = completeCommand(this.editor.text());
295      if (completed !== null) {
296        this.editor.setText(completed);
297      } else {
298        this.editor.completeWord((word) => completePath(word, process.cwd()));
299      }
300      this.render();
301      return;
302    }
303    const result = this.editor.handle(key);
304    if (result === "submit") this.submit();
305    else if (result === "changed") this.render();
306  }
307
308  private submit(): void {
309    const text = this.editor.text();
310    if (this.active) {
311      if (this.paused && this.steeringResolve !== null) {
312        this.editor.clear();
313        if (text.length > 0) this.commitUser(text);
314        this.resolveSteering(text);
315      }
316      return;
317    }
318    if (this.pendingPrompt !== null) {
319      this.editor.clear();
320      this.render();
321      this.answerPrompt(text);
322      return;
323    }
324    if (this.commandAbort !== null) return;
325    if (text.trim() === "") return;
326    const found = findCommand(text);
327    if (found !== null) {
328      this.editor.clear();
329      this.runCommand(found.command, found.args);
330      this.render();
331      return;
332    }
333    this.editor.clear();
334    const message: UserMessage = { role: "user", content: text, timestamp: Date.now() };
335    this.messages.push(message);
336    this.opts.session.appendMessage(message);
337    this.commitUser(text);
338    this.startTurn();
339  }
340
341  /**
342   * Runs one command with a fresh context. Lines submitted while it runs route
343   * to a pending prompt; Ctrl+C aborts its signal. No agent turn may start
344   * until it settles. Errors surface as an error line.
345   */
346  private runCommand(command: Command, args: string): void {
347    const abort = new AbortController();
348    this.commandAbort = abort;
349    const ctx: CommandContext = {
350      models: this.opts.models,
351      model: this.opts.model,
352      select: (model) => this.select(model),
353      setThinking: (level) => this.setThinking(level),
354      signal: abort.signal,
355      write: (lines) => {
356        this.separator = true;
357        this.commitLines(lines.map((text) => ({ text })));
358        this.separator = true;
359      },
360      prompt: (prompt) => this.ask(prompt),
361      notify: (event) => this.notify(event),
362    };
363    void (async () => {
364      try {
365        await command.run(ctx, args);
366      } catch (error) {
367        this.separator = true;
368        this.push(red(`! ${(error as Error).message}`));
369        this.separator = true;
370      } finally {
371        this.commandAbort = null;
372        this.pendingPrompt = null;
373        this.editor.setMasked(false);
374        this.render();
375      }
376    })();
377  }
378
379  /** The startup and selection banner: provider, model, and thinking effort. */
380  private pushBanner(): void {
381    this.separator = true;
382    const model = this.opts.model;
383    this.push(
384      model === null
385        ? "mini-coder · no model configured"
386        : `mini-coder · ${model.provider}/${model.id} · ${this.opts.thinkingEffort}`,
387    );
388    this.separator = true;
389  }
390
391  /**
392   * Switches the running session to `model`: derived state follows — the
393   * thinking effort is re-clamped, and `read`'s image behaviour is rebuilt for
394   * the new model. The status line and context readout read `opts.model`, so
395   * they update on the next render.
396   */
397  private select(model: Model<Api>): void {
398    this.opts.model = model;
399    this.opts.thinkingEffort = clampThinkingLevel(model, this.opts.thinkingEffort);
400    this.opts.tools = toolSchemas(this.opts.toolNames, acceptsImages(model));
401    this.pushBanner();
402    this.render();
403  }
404
405  /** Sets the running session's thinking level, clamped to the current model. */
406  private setThinking(level: ModelThinkingLevel): void {
407    const model = this.opts.model;
408    if (model === null) return;
409    this.opts.thinkingEffort = clampThinkingLevel(model, level);
410    this.pushBanner();
411    this.render();
412  }
413
414  /** Commits a prompt and returns a promise resolving with the next submitted line. */
415  private ask(prompt: AuthPrompt): Promise<string> {
416    if (this.pendingPrompt !== null) return Promise.reject(new Error("a prompt is already pending"));
417    this.separator = true;
418    this.push(prompt.message);
419    if (prompt.type === "select") {
420      for (let i = 0; i < prompt.options.length; i++) this.push(`  ${i + 1}. ${prompt.options[i].label}`);
421    } else if (prompt.placeholder !== undefined) {
422      this.push(`  (${prompt.placeholder})`);
423    }
424    this.separator = true;
425    this.editor.setMasked(prompt.type === "secret");
426    this.render();
427
428    return new Promise<string>((resolve, reject) => {
429      const flow = this.commandAbort?.signal;
430      const onAbort = (): void => {
431        settle(() => reject(new Error("cancelled")));
432      };
433      const settle = (fn: () => void): void => {
434        prompt.signal?.removeEventListener("abort", onAbort);
435        flow?.removeEventListener("abort", onAbort);
436        this.editor.setMasked(false);
437        this.pendingPrompt = null;
438        this.render();
439        fn();
440      };
441      if (prompt.signal?.aborted === true || flow?.aborted === true) {
442        onAbort();
443        return;
444      }
445      prompt.signal?.addEventListener("abort", onAbort);
446      flow?.addEventListener("abort", onAbort);
447      this.pendingPrompt = {
448        prompt,
449        resolve: (value) => settle(() => resolve(value)),
450        reject: (error) => settle(() => reject(error)),
451      };
452    });
453  }
454
455  /** Turns the submitted line into the answer: a `select` maps to its option id. */
456  private answerPrompt(text: string): void {
457    const pending = this.pendingPrompt;
458    if (pending === null) return;
459    if (pending.prompt.type !== "select") {
460      pending.resolve(text);
461      return;
462    }
463    const trimmed = text.trim();
464    const index = Number.parseInt(trimmed, 10);
465    const byIndex = String(index) === trimmed ? pending.prompt.options[index - 1] : undefined;
466    const chosen = byIndex ?? pending.prompt.options.find((option) => option.id === trimmed || option.label === trimmed);
467    if (chosen === undefined) pending.reject(new Error(`invalid selection: ${trimmed}`));
468    else pending.resolve(chosen.id);
469  }
470
471  private notify(event: AuthEvent): void {
472    this.separator = true;
473    switch (event.type) {
474      case "info":
475        this.push(event.message);
476        for (const link of event.links ?? []) this.push(link.label === undefined ? link.url : `${link.label}: ${link.url}`);
477        break;
478      case "auth_url":
479        this.push(event.url);
480        if (event.instructions !== undefined) this.push(event.instructions);
481        break;
482      case "device_code":
483        this.push(event.verificationUri);
484        this.push(`code: ${event.userCode}`);
485        if (event.expiresInSeconds !== undefined) this.push(`expires in ${event.expiresInSeconds}s`);
486        break;
487      case "progress":
488        this.push(event.message);
489        break;
490    }
491    this.separator = true;
492  }
493
494  private startTurn(): void {
495    this.active = true;
496    this.abort = new AbortController();
497    this.phase = "preparing";
498    this.detail = undefined;
499    this.turnStart = Date.now();
500    this.frame = 0;
501    this.spinner = setInterval(() => {
502      this.frame++;
503      this.render();
504    }, SPINNER_MS);
505    void this.runTurn();
506    this.render();
507  }
508
509  private async runTurn(): Promise<void> {
510    try {
511      await runAgentTurn({
512        ...this.opts,
513        messages: this.messages,
514        signal: this.abort!.signal,
515        interaction: {
516          isPauseRequested: () => this.pauseRequested,
517          clearPause: () => {
518            this.pauseRequested = false;
519          },
520          requestSteering: () =>
521            new Promise<string>((resolve) => {
522              this.paused = true;
523              this.steeringResolve = resolve;
524              this.render();
525            }),
526        },
527        onEvent: (event) => this.handleAgentEvent(event),
528      });
529    } catch (error) {
530      this.separator = true;
531      this.push(red(`! ${(error as Error).message}`));
532    } finally {
533      this.active = false;
534      this.abort = null;
535      this.pauseRequested = false;
536      this.resolveSteering("");
537      this.paused = false;
538      if (this.spinner) clearInterval(this.spinner);
539      this.spinner = undefined;
540      this.render();
541    }
542  }
543
544  private cancel(): void {
545    this.resolveSteering("");
546    this.abort?.abort();
547    this.render();
548  }
549
550  /** Answers a pending steering prompt; "" leaves the turn ending. */
551  private resolveSteering(text: string): void {
552    const resolve = this.steeringResolve;
553    if (resolve === null) return;
554    this.steeringResolve = null;
555    this.paused = false;
556    resolve(text);
557  }
558
559  private handleAgentEvent(event: AgentEvent): void {
560    if (this.closed) return;
561    switch (event.type) {
562      case "phase":
563        this.phase = event.phase;
564        this.detail = event.detail;
565        if (event.phase === "pausing") this.paused = true;
566        break;
567      case "text":
568        this.activity.reset();
569        this.streamed += event.delta;
570        this.commitLines(this.reply.feed(event.delta));
571        break;
572      case "reasoning":
573        if (this.reply.pending().length === 0) this.activity.feed(event.delta);
574        break;
575      case "toolCall":
576        // Hold the call line until its result arrives: a message may carry
577        // several calls, all announced before any of them runs, and each call
578        // line pairs with its own output in execution order.
579        this.writingTool = undefined;
580        this.commitLines(this.reply.flush());
581        this.activity.reset();
582        this.pendingCalls.push({ text: `${callHead(event.name)}  ${callSummary(event.name, event.arguments)}` });
583        break;
584      case "toolCallStart":
585        this.writingTool = event.name;
586        break;
587      case "toolOutput":
588        this.activity.feed(event.chunk);
589        break;
590      case "message":
591        this.commitMessage(event.message);
592        break;
593      case "toolResult":
594        this.activity.reset();
595        this.commitToolResult(event.name, event.text, event.isError, event.diffs);
596        break;
597      case "error":
598        this.endTurn(red(`! ${event.message}`));
599        break;
600      case "noModel":
601        this.endTurn(red("! no model configured"));
602        break;
603      case "cancelled":
604        this.endTurn(red("! cancelled"));
605        break;
606      case "complete":
607        this.endTurn(dim(`[complete · ${this.elapsed()}s]`));
608        break;
609    }
610    this.render();
611  }
612
613  /** A terminal state: clears the status row and any in-flight preview, then commits. */
614  private endTurn(line: string): void {
615    this.phase = "idle";
616    this.detail = undefined;
617    this.writingTool = undefined;
618    this.paused = false;
619    this.activity.reset();
620    this.commitLines(this.reply.flush());
621    this.flushCalls();
622    this.separator = true;
623    this.push(line);
624  }
625
626  private elapsed(): number {
627    return Math.max(0, Math.floor((Date.now() - this.turnStart) / 1000));
628  }
629
630  private commitUser(text: string): void {
631    this.separator = true;
632    this.commitLines(text.split("\n").map((line) => ({ text: line, style: blue })));
633    this.separator = true;
634  }
635
636  /** Commits a line the model emitted without streaming it, plus the in-flight tail. */
637  private commitMessage(message: AssistantMessage): void {
638    this.activity.reset();
639    this.commitLines(this.reply.flush());
640    const text = contentText(message.content, "");
641    if (text.trim() !== "" && !this.streamed.includes(text)) {
642      this.commitLines([...this.reply.feed(text.trimEnd()), ...this.reply.flush()]);
643    }
644    this.streamed = "";
645  }
646
647  private commitToolResult(name: string, text: string, isError: boolean, diffs?: FileDiff[]): void {
648    const call = this.pendingCalls.shift();
649    this.separator = true;
650    if (call !== undefined) this.commitLines([call]);
651    const width = Math.max(1, this.term.width - BODY_PREFIX.length);
652    const lines = resultLines(name, text, isError);
653    // Diffs are shown in full; other tool bodies stay elided.
654    const rows = name === "edit" ? renderRows(lines, width) : bodyRows(lines, width);
655    for (let i = 0; i < rows.length; i++) {
656      const prefix = isError && i === rows.length - 1 ? ERROR_CHROME : BODY_CHROME;
657      this.push(prefix + rows[i]);
658    }
659    if (diffs !== undefined && diffs.length > 0) {
660      for (const row of renderRows(diffRows(diffs), width)) this.push(BODY_CHROME + row);
661    }
662    this.separator = true;
663  }
664
665  /** Commits logical lines through the same wrap-and-style step tool bodies use. */
666  private commitLines(lines: BodyLine[]): void {
667    for (const row of renderRows(lines, Math.max(1, this.term.width))) this.push(row);
668  }
669
670  /** Commits any call line whose result never arrived, e.g. after a cancel. */
671  private flushCalls(): void {
672    for (const call of this.pendingCalls) {
673      this.separator = true;
674      this.commitLines([call]);
675    }
676    this.pendingCalls = [];
677  }
678
679  /**
680   * Appends one scrollback line. A block boundary owes exactly one blank line,
681   * and two blank lines never appear in a row.
682   */
683  private push(line: string): void {
684    line = sanitize(line);
685    const blank = line === "" || (this.separator && this.wrote);
686    this.separator = false;
687    if (blank && this.wrote && !this.lastBlank) {
688      // A separator is a row the app occupies, so it is painted like any other:
689      // a bare newline would leave the host terminal showing through it.
690      this.scroll += `${paintRow("")}\r\n`;
691      this.lastBlank = true;
692    }
693    if (line !== "") {
694      this.scroll += `${paintRow(line)}\r\n`;
695      this.wrote = true;
696      this.lastBlank = false;
697    }
698    this.render();
699  }
700
701  private render(): void {
702    if (this.closed || this.renderScheduled) return;
703    this.renderScheduled = true;
704    setTimeout(() => {
705      this.renderScheduled = false;
706      this.draw();
707    }, 16);
708  }
709
710  /**
711   * The one row between the in-flight lines and the editor: the phase while a
712   * turn is active, and the context readout always. The readout carries its own
713   * emphasis, so only the phase half is dimmed.
714   */
715  private statusLine(): string {
716    const model = this.opts.model;
717    if (model === null) return dim("no model configured");
718    const usage = contextUsageLine(
719      estimateContextTokens(this.messages, this.opts.systemPrompt, this.opts.tools),
720      model,
721    );
722    if (this.paused || this.phase === "pausing") {
723      return `${dim("paused - type steering, Enter to submit")} · ${usage}`;
724    }
725    if (!this.active || this.phase === "idle") return usage;
726    const label =
727      this.phase === "preparing"
728        ? "preparing"
729        : this.phase === "waitingModel"
730          ? "waiting for provider"
731          : this.phase === "streaming"
732            ? this.writingTool !== undefined
733              ? `writing ${this.writingTool}`
734              : "streaming"
735            : `running ${this.detail ?? "tool"}`;
736    return `${dim(`${SPINNER[this.frame % SPINNER.length]} ${label} · ${this.elapsed()}s`)} · ${usage}`;
737  }
738
739  private draw(): void {
740    if (this.closed) return;
741    const width = Math.max(1, this.term.width);
742    const height = Math.max(1, this.term.height - 1);
743
744    const status = wrapLine(this.statusLine(), width);
745
746    let inflight = this.reply.pending();
747    if (inflight.length === 0) inflight = this.activity.pending();
748    const rows = renderRows(inflight, width);
749
750    // Short on space: clip the in-flight rows first, then the editor viewport,
751    // which never drops below one row. The status rows are always kept.
752    const keep = Math.max(0, Math.min(rows.length, height - status.length - 1));
753    const body = rows.slice(rows.length - keep);
754    const editor = this.editor.render(width, Math.max(1, height - status.length - body.length));
755
756    const lines = [...body, ...status, ...editor.rows].map(paintRow);
757    let cursorRow = status.length + body.length + editor.cursorRow;
758    if (cursorRow >= lines.length) cursorRow = lines.length - 1;
759
760    // Scrollback and the live region are written as one frame. Clearing the
761    // region and restoring it in separate writes leaves it blank in between.
762    // A commit on a region filling every row above the last scrolls the
763    // terminal; the re-anchor newline goes after the scrollback, not before the
764    // erase, because `clear()` measures from the previous frame's cursor and
765    // moving the cursor down first lands the erase one row below the region.
766    const scroll = this.scroll;
767    this.scroll = "";
768    const reanchor = scroll !== "" && this.live.height >= this.term.height - 1;
769    this.term.write(this.live.draw(lines, cursorRow, editor.cursorCol, scroll + (reanchor ? "\r\n" : "")));
770  }
771
772  private exit(): void {
773    if (this.closed) return;
774    this.closed = true;
775    this.abort?.abort();
776    this.commandAbort?.abort();
777    if (this.spinner) clearInterval(this.spinner);
778    this.spinner = undefined;
779    // Draws are deferred, so anything pushed since the last frame is still here.
780    this.term.write(this.live.clear() + this.scroll);
781    this.scroll = "";
782    this.term.stop();
783    this.opts.session.close();
784    process.off("SIGINT", this.onSignal);
785    process.off("SIGTERM", this.onSignal);
786    this.resolveExit();
787  }
788}
789
790export async function runTui(opts: AgentOptions): Promise<void> {
791  const tui = new Tui(opts);
792  tui.start();
793  return tui.done;
794}