ucode-agent 1.43.0 → 1.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/ui/screen.js CHANGED
@@ -1,1692 +1,1699 @@
1
- /**
2
- * screen.js — the full-screen interface.
3
- *
4
- * Used whenever stdout is a real terminal. Everything else — piped input, CI,
5
- * `echo ... | ucode` — falls back to plain.js, which is why both exist.
6
- *
7
- * The layout, top to bottom:
8
- *
9
- * ╭──────────────────────────────────────────────────╮
10
- * │ UCODE wordmark dir / keys │
11
- * ╰──────────────────────────────────────────────────╯
12
- *
13
- * the conversation, scrolling with the wheel or PgUp
14
- *
15
- * ╭──────────────────────────────────────────────────╮
16
- * │ › what you are typing, growing downward as it │
17
- * │ │
18
- * │ ◆ Build · Nemotron 3 Ultra 4% │
19
- * ╰──────────────────────────────────────────────────╯
20
- *
21
- * Both boxes are drawn rather than ruled off, because a box says "this is a
22
- * thing you use" where a horizontal rule only says "something changes here".
23
- *
24
- * The status sits inside the input box rather than under it: it describes the
25
- * thing you are typing into, so it belongs within the same border. It carries
26
- * three facts and no more — which mode is live, which model is answering, and
27
- * how full the window is. Anything else down there competes with what the user
28
- * is actually looking at, which is what they just typed.
29
- *
30
- * The transcript is a buffer of pre-rendered lines and the whole frame is
31
- * repainted whenever anything changes. At terminal sizes that is cheap, and
32
- * it rules out every partial-update bug at once.
33
- */
34
-
35
- import { appendFile } from 'node:fs/promises';
36
- import { homedir } from 'node:os';
37
- import path from 'node:path';
38
- import chalk from 'chalk';
39
- import {
40
- theme, blue, sky, deep, dim, edge, ADDED, REMOVED, BANNER, BANNER_WIDTH, SPINNER,
41
- boxTop, boxBottom, boxRow, visLen, padVis, clip, wrapAnsi,
42
- shortenPath, asLabel, ensureColour, planLine, bare, narration, narrationMark, groupKind, groupLabel, groupTarget, runLine, planRows, tidyReply, trimAnswer,
43
- bannerPaint, RAIL, modeChip } from './theme.js';
44
- import { FRAME_MS, spinnerGlyph, formatDuration, doneLine, workingLine, bannerSweep, SWEEP_MS } from './activity.js';
45
- import { gitBranch } from '../core/git.js';
46
- import { renderer, render, polish } from './markdown.js';
47
- import { VERSION } from '../core/version.js';
48
-
49
- /**
50
- * One line of narration, in the model's own words: "Reading screen.js".
51
- * Anything longer than this is prose, and prose belongs in the answer.
52
- */
53
- export const MAX_LABEL = 120;
54
-
55
- export function isLabel(text) {
56
- const t = String(text ?? '').trim();
57
- return t.length > 0 && t.length <= MAX_LABEL && !t.includes('\n');
58
- }
59
-
60
- export const COMMANDS = [
61
- '/help', '/model', '/models', '/session', '/sessions', '/resume',
62
- '/new', '/remember', '/skills', '/clear', '/search', '/copy', '/exit',
63
- '/stats', '/doctor', '/deploy', '/look', '/undo',
64
- ];
65
-
66
- // ANSI ----------------------------------------------------------------------
67
- const ESC = '\x1b';
68
- const ALT_ON = `${ESC}[?1049h`;
69
- const ALT_OFF = `${ESC}[?1049l`;
70
-
71
- /**
72
- * Mouse setup, decided by measurement rather than by documentation.
73
- *
74
- * 1007 is alternate scroll: inside the alternate screen the terminal turns
75
- * wheel events into arrow keys. On Windows that is the only way a wheel ever
76
- * reaches the program, because ConPTY forwards no mouse input at all — a probe
77
- * that enabled every tracking mode received nothing from a scroll.
78
- *
79
- * And mouse tracking suppresses alternate scroll. So on Windows tracking is
80
- * deliberately not requested: it delivers nothing there, and asking for it
81
- * would cost the wheel. Elsewhere tracking works, so the mode chip is
82
- * clickable on those platforms.
83
- */
84
- const TRACK = process.platform === 'win32'
85
- ? '' : `${ESC}[?1000h${ESC}[?1002h${ESC}[?1015h${ESC}[?1006h`;
86
- const UNTRACK = process.platform === 'win32'
87
- ? '' : `${ESC}[?1006l${ESC}[?1015l${ESC}[?1002l${ESC}[?1000l`;
88
-
89
- const PASTE_ON = `${ESC}[?2004h`;
90
- const PASTE_OFF = `${ESC}[?2004l`;
91
- const MOUSE_ON = `${ESC}[?1007h${TRACK}`;
92
- const MOUSE_OFF = `${UNTRACK}${ESC}[?1007l`;
93
- const HIDE = `${ESC}[?25l`;
94
- const SHOW = `${ESC}[?25h`;
95
- const HOME = `${ESC}[H`;
96
- const CLEAR_LINE = `${ESC}[K`;
97
- /** Written out rather than inline, so no edit can turn it into a real break. */
98
- const NEWLINE = String.fromCharCode(10);
99
- const at = (row, col) => `${ESC}[${row};${col}H`;
100
- const title = (t) => `${ESC}]0;${t}\x07`;
101
-
102
- /**
103
- * Fixed rows below the header: the gap under it, the gap above the input box,
104
- * the input box's two borders, the blank row inside it, and the status row.
105
- */
106
- const CHROME_BELOW = 6;
107
-
108
- /** How long one sentence of reasoning holds the line before the next takes it. */
109
- const THOUGHT_HOLD_MS = 1100;
110
-
111
- /** Reasoning that is about the request rather than about the work. */
112
- const RESTATEMENT = /^(?:the user|they|so the user|user)|^(?:i (?:need|should|will need) to (?:understand|figure|work out|check what))|^(?:let me (?:understand|re-?read|look at the (?:request|prompt)))|^(?:the (?:request|prompt|task) (?:is|asks|says))/i;
113
-
114
- /** The wordmark only earns its place with room for the facts column beside it. */
115
- const WORDMARK_NEEDS = BANNER_WIDTH + 30;
116
-
117
- /** What the empty input box says before anything is typed. */
118
- const PLACEHOLDER = 'Ask anything…';
119
-
120
- /**
121
- * What it says instead while the agent has the turn.
122
- *
123
- * The status row beside it already says "esc to stop", so this carries the
124
- * half nothing else on screen does: that the box is still live, and a line
125
- * typed into it now is kept and sent when the turn ends rather than lost. The
126
- * short form is for a terminal too narrow to hold the sentence, where a cut
127
- * one would read as a glitch.
128
- */
129
- const WORKING_HINT = 'Working… type to queue your next message';
130
- const WORKING_HINT_SHORT = 'Working…';
131
- const WORKING_HINT_NEEDS = WORKING_HINT.length + 8;
132
-
133
- /**
134
- * Three things to try, under the box, on a screen with nothing on it yet.
135
- *
136
- * A wordmark over an empty field is handsome and tells you nothing you can act
137
- * on — the first thing a new user has to do is guess what this accepts. Three
138
- * greyed lines answer that in one glance, and they say something about the
139
- * range of it too: build something new, understand something that exists,
140
- * change something small. They are dim, and they are gone the moment anything
141
- * is on the screen.
142
- */
143
- const SUGGESTIONS = [
144
- 'build me a landing page for a coffee shop',
145
- 'explain what this project does and how it fits together',
146
- 'add a dark mode toggle that remembers the choice',
147
- ];
148
-
149
- /** The width of the `try` label, so the three lines share one left edge. */
150
- const SUGGEST_LABEL = 6;
151
-
152
- /** Rows the suggestions occupy under the box: one of air, then the three. */
153
- const SUGGEST_ROWS = SUGGESTIONS.length + 1;
154
-
155
- export class Screen {
156
- constructor({ cwd, input = process.stdin, output = process.stdout } = {}) {
157
- this.cwd = cwd;
158
- this.input = input;
159
- this.output = output;
160
-
161
- this.lines = []; // the rendered transcript
162
- this.scroll = 0; // rows scrolled up from the bottom
163
- this.buffer = ''; // what is being typed
164
- this.cursor = 0;
165
- this.history = [];
166
- this.historyIndex = -1;
167
-
168
- this.status = { busy: false, text: '', frame: 0, since: 0 };
169
- this.facts = {};
170
- this.model = '';
171
-
172
- this.waiters = [];
173
- this.queue = [];
174
- this.closed = false;
175
-
176
- // 'build' may edit and run; 'plan' is read-only. Ctrl+B swaps them, and
177
- // the chip is clickable wherever the terminal forwards clicks.
178
- this.mode = 'build';
179
- this.chipTo = 0;
180
- this.onInterrupt = null;
181
- this.onModeChange = null;
182
- this.spinTimer = null;
183
- this.paintedBusy = false; // whose turn the frame on screen was drawn for
184
- this.activity = null; // the turn in flight: when it began, how many steps
185
- this.tick = 0; // animation frames painted, for the spinner
186
- this.intro = 0; // when the launch sweep began, 0 once it is over
187
- this.introTimer = null;
188
- this.pendingPrompt = null;
189
- this.lastPrompt = ''; // the last thing the user said, for the echo check
190
- this.facts.branch = gitBranch(cwd);
191
-
192
- this.cols = output.columns || 80;
193
- this.rows = output.rows || 24;
194
- this.md = renderer(this.width());
195
- }
196
-
197
- // -- lifecycle -----------------------------------------------------------
198
-
199
- async start() {
200
- ensureColour(this.output);
201
- this.output.write(ALT_ON + MOUSE_ON + PASTE_ON + HIDE + title(`ucode — ${path.basename(this.cwd)}`));
202
- this.input.setRawMode?.(true);
203
- this.input.resume();
204
- this.input.setEncoding('utf8');
205
- this.input.on('data', (chunk) => this.onData(chunk));
206
-
207
- this.onResize = () => {
208
- this.cols = this.output.columns || 80;
209
- this.rows = this.output.rows || 24;
210
- this.md = renderer(this.width());
211
- this.render();
212
- };
213
- this.output.on('resize', this.onResize);
214
-
215
- this.render();
216
- this.startIntro();
217
- }
218
-
219
- /**
220
- * The light that crosses the wordmark once, at launch.
221
- *
222
- * Half a second, on the start screen only, and abandoned the instant there is
223
- * anything else to look at. Below 256 colours there are no shades to fade
224
- * through, so it is skipped rather than flickered.
225
- */
226
- startIntro() {
227
- if (!this.output.isTTY || chalk.level < 2 || !this.welcoming()) return;
228
- this.intro = Date.now();
229
- this.introTimer = setInterval(() => {
230
- if (this.closed || !this.welcoming() || Date.now() - this.intro >= SWEEP_MS) this.stopIntro();
231
- else this.render();
232
- }, FRAME_MS);
233
- this.introTimer.unref?.();
234
- }
235
-
236
- stopIntro() {
237
- if (this.introTimer) clearInterval(this.introTimer);
238
- this.introTimer = null;
239
- if (!this.intro) return;
240
- this.intro = 0;
241
- if (!this.closed) this.render();
242
- }
243
-
244
- stop() {
245
- this.activity = null;
246
- if (this.introTimer) clearInterval(this.introTimer);
247
- this.introTimer = null;
248
- this.intro = 0;
249
- this.stopSpinner();
250
- this.stopTimer();
251
- this.output.off?.('resize', this.onResize);
252
- this.input.setRawMode?.(false);
253
- this.input.pause();
254
- this.output.write(PASTE_OFF + MOUSE_OFF + ALT_OFF + SHOW);
255
- }
256
-
257
- close() {
258
- if (this.closed) return;
259
- this.closed = true;
260
- this.stop();
261
- while (this.waiters.length) this.waiters.shift()(null);
262
- }
263
-
264
- /**
265
- * Every column the terminal has.
266
- *
267
- * Capped at 100 for a release, and it was wrong: on a wide monitor the frame
268
- * sat in the left half of the screen with the rest of it empty, which reads
269
- * as the window having failed to open rather than as a measured column. The
270
- * interface fills what it is given. Prose inside it is still held to 100 by
271
- * the markdown renderer, which is where that limit belongs — the boxes are
272
- * the shape of the window, not of a paragraph.
273
- */
274
- width() {
275
- return Math.max(30, this.cols);
276
- }
277
-
278
- /** Usable width inside a box: two borders and a space of padding each side. */
279
- inner() {
280
- return Math.max(8, this.width() - 4);
281
- }
282
-
283
- // -- transcript ----------------------------------------------------------
284
-
285
- /**
286
- * Append without painting.
287
- *
288
- * Anything replacing a region of the transcript has to build the whole
289
- * region and then render once. Painting between the delete and the re-add
290
- * puts a frame on screen with the text missing, and at streaming speed that
291
- * reads as flicker.
292
- */
293
- add(text = '') {
294
- const width = this.width();
295
- for (const raw of String(text).split('\n')) {
296
- if (visLen(raw) <= width) this.lines.push(raw);
297
- else for (const wrapped of wrapAnsi(raw, width)) this.lines.push(wrapped);
298
- }
299
- this.scroll = 0; // new output snaps back to the bottom
300
- }
301
-
302
- push(text = '') {
303
- this.add(text);
304
- this.soon();
305
- }
306
-
307
- /**
308
- * Collapse a burst of pushes into one frame.
309
- *
310
- * Printing a list one line at a time repaints the screen per line — a model
311
- * list of fifty entries drew a hundred frames back to back, which is visible
312
- * as a cascade. A microtask runs before any I/O, so everything pushed in one
313
- * synchronous stretch becomes a single render, while a push after an await
314
- * still paints immediately.
315
- */
316
- soon() {
317
- if (this.queued) return;
318
- this.queued = true;
319
- queueMicrotask(() => {
320
- this.queued = false;
321
- this.render();
322
- });
323
- }
324
-
325
- write(text = '') { this.push(text); }
326
- blank() { this.push(''); }
327
- note(text) { this.push(dim(` ${text}`)); }
328
-
329
- clearScreen() {
330
- this.lines = [];
331
- this.scroll = 0;
332
- this.render();
333
- }
334
-
335
- /**
336
- * The reply, at full strength, with room either side.
337
- *
338
- * `closing` says this is the last thing the turn will say. It is then also
339
- * the last thing left on screen, and what the whole session reads like
340
- * afterwards, so it is cut to eight lines — see trimAnswer.
341
- */
342
- assistant(text, { closing = false } = {}) {
343
- if (!text?.trim()) return;
344
- const tidy = tidyReply(text, 4, this.lastPrompt);
345
- const body = closing ? trimAnswer(tidy) : tidy;
346
- if (!body.trim()) return;
347
- this.endRun();
348
- this.add('');
349
-
350
- // No bullet, and no indent. A mark on every reply made the answer read as
351
- // one more step in the list above it, and on "Hey! How can I help you
352
- // today?" it was a bullet on a greeting. The answer already wins the page
353
- // by being the only thing on it at full strength; it does not also need to
354
- // be labelled.
355
- this.add(render(this.md, body));
356
-
357
- this.add('');
358
- this.render();
359
- }
360
-
361
- /**
362
- * Something the user said, marked down its left edge in the same blue as the
363
- * box it was typed into.
364
- *
365
- * A long session is mostly the agent's output — tool calls, diffs, answers.
366
- * Your own messages are the landmarks you scroll back looking for, so they
367
- * get a mark of their own. It was a full box, and forty turns of that is a
368
- * ladder of rules across the page: two horizontal lines per message, each as
369
- * loud as the input box, none of them saying anything the rail does not.
370
- */
371
- userMessage(text) {
372
- // Kept so the reply can be checked against it: an answer that opens by
373
- // saying the request back is repeating the line directly above it.
374
- this.lastPrompt = String(text ?? '');
375
- const room = Math.max(8, this.width() - 2); // the rail and the space after it
376
-
377
- const rows = [];
378
- for (const paragraph of String(text).replace(/\r/g, '').split('\n')) {
379
- for (const line of wrapAnsi(paragraph, room)) rows.push(line);
380
- }
381
-
382
- // Room between what you asked for and what came back: without it the reply
383
- // starts against your own message and the two read as one block of text.
384
- this.add('');
385
- for (const row of rows) this.add(`${blue(RAIL)} ${chalk.white(row)}`);
386
- this.add('');
387
- this.add('');
388
- this.render();
389
- }
390
-
391
- /**
392
- * A tool call, as it happens: "● Listing src".
393
- *
394
- * This lives in the transcript rather than only on the status line. The
395
- * status line overwrites itself and is empty by the end of the turn, so work
396
- * announced only there scrolls past unseen — and the diff underneath ends up
397
- * with nothing above it explaining where it came from.
398
- */
399
- toolCall(label) {
400
- // U+25CF, not U+23FA: the latter carries emoji presentation, which Windows
401
- // Terminal draws as a white circle on a blue tile.
402
- // Trimmed here rather than at paint time: runLine hands back a coloured
403
- // string, and asLabel's regexes run off the end of one of those into the
404
- // escape sequence instead of the last word.
405
- const clean = asLabel(label);
406
- const kind = groupKind(clean);
407
- // One line per kind of work for as long as the model is working on one
408
- // thing. Reading, writing and reading again used to draw six lines that
409
- // said three things; now the "Reading files" line it already has is the
410
- // one that counts up, wherever it sits.
411
- const run = (this.segment ??= new Map()).get(kind);
412
-
413
- if (run && this.lines[run.at] !== undefined) {
414
- run.count++;
415
- run.label = clean;
416
- run.targets.push(groupTarget(clean));
417
- this.run = run;
418
- this.paintRun();
419
- } else {
420
- const fresh = {
421
- kind, count: 1, at: 0, label: clean,
422
- targets: [groupTarget(clean)], added: 0, removed: 0,
423
- };
424
- this.push(`${narrationMark(kind)} ${runLine(fresh)}`);
425
- fresh.at = this.lines.length - 1;
426
- this.run = fresh;
427
- this.segment.set(kind, fresh);
428
- }
429
- this.updateSpinner(label);
430
- }
431
-
432
- /**
433
- * The model speaking — or a plan, or a failure — ends the segment.
434
- *
435
- * Up to that point a kind of work keeps one line and counts up on it. After
436
- * it, the next read is a new piece of work and deserves its own line, which
437
- * is what makes the transcript read as a sequence of things done rather
438
- * than a set of running totals.
439
- */
440
- /**
441
- * Stop adding to the current run, but keep the lines already on screen.
442
- *
443
- * A kind of work gets one line for the whole turn. Starting a fresh set
444
- * whenever the model spoke meant "Creating Tide from the HTML starter" five
445
- * times down the page and "Reading files" four, each saying the same thing
446
- * about a different moment. One line that counts up says all of it and
447
- * costs one row.
448
- */
449
- endRun() { this.run = null; }
450
-
451
- /** A new turn starts with a clean page's worth of lines. */
452
- newSegment() { this.run = null; this.segment = new Map(); }
453
-
454
- /** Redraw the run's single line from what it has accumulated. */
455
- /**
456
- * Redraw the run's single line from what it has accumulated.
457
- *
458
- * While its step is still running the text shimmers, which is the only
459
- * thing on screen saying "this is happening now" once the per-step result
460
- * lines are gone. It settles to plain dim the moment the step finishes, so
461
- * the finished ones above stay quiet.
462
- */
463
- paintRun() {
464
- if (!this.run) return;
465
- this.lines[this.run.at] = `${narrationMark(this.run.kind)} ${runLine(this.run)}`;
466
- this.render();
467
- }
468
-
469
- /**
470
- * A change, as its two numbers.
471
- *
472
- * The diff itself used to go into the transcript. A 539-line file printed
473
- * there buries the answer under a copy of something already on disk, so
474
- * what is kept is the shape of the change: how much arrived, how much left.
475
- */
476
- /**
477
- * A one-word verdict on the step that just ran — "clean", "3 to fix".
478
- *
479
- * Same rule as diffStat: it goes on the line that named the step. Nothing
480
- * goes underneath a bullet, and a result line per tool doubles the height of
481
- * the transcript to say "ok".
482
- */
483
- runStat(text) {
484
- if (!this.run || !text) return;
485
- this.run.stat = text;
486
- this.paintRun();
487
- }
488
-
489
- diffStat({ added = 0, removed = 0 } = {}) {
490
- if (!this.run) return;
491
- this.run.added += added;
492
- this.run.removed += removed;
493
- this.paintRun();
494
- }
495
-
496
- /** The checklist, when the model updates it. One line, wrapped if it must. */
497
- plan(items) {
498
- const rows = planRows(items);
499
- if (!rows.length) return;
500
- this.endRun(); // a plan is not another step of whatever came before
501
- for (const row of rows) this.push(row);
502
- }
503
-
504
- /**
505
- * What came of a step.
506
- *
507
- * Nothing goes underneath the bullet any more: a line of its own for every
508
- * result doubles the height of the transcript to say "ok". The bullet
509
- * already names the step, and a change adds its numbers to that same line.
510
- * Only a failure earns a line of its own.
511
- */
512
- toolResult() {}
513
-
514
- /**
515
- * Something went wrong, and the model is the one who can do anything about it.
516
- *
517
- * A red line of machinery — a failed edit, a command that exited non-zero —
518
- * reads as the tool being broken, when almost always it is a step the model
519
- * corrects on its own a second later. It goes to the model; the screen stays
520
- * for what is being built. Whatever is genuinely unrecoverable surfaces as
521
- * the model saying so in words, which is the form worth reading.
522
- */
523
- toolFailed() {
524
- this.endRun();
525
- }
526
-
527
- /**
528
- * The change itself, under the result.
529
- *
530
- * A line-number gutter, then the sign and the code tinted right across the
531
- * row. The numbers are the point: a diff you cannot navigate from is a
532
- * picture of a change rather than a record of one.
533
- */
534
- diff(lines) {
535
- const gutter = 6;
536
- // Two spaces of indent, the gutter, one space, then the tint fills the
537
- // rest. One column over and every row wraps, splitting the whole diff.
538
- const room = Math.max(12, this.width() - gutter - 3);
539
-
540
- for (const line of lines) {
541
- // A file heading in a multi-file write.
542
- if (line.startsWith('~')) {
543
- this.add(` ${dim(' '.repeat(gutter))} ${sky(line.slice(1))}`);
544
- continue;
545
- }
546
-
547
- const added = line.startsWith('+');
548
- const rest = line.slice(1);
549
- // Tools emit "<line>| <text>". A row with no number is the "12 more
550
- // lines" note, which is not part of the change, so it stays dim.
551
- const parsed = /^(\d+)\|\s?([\s\S]*)$/.exec(rest);
552
- if (!parsed) {
553
- this.add(` ${dim(' '.repeat(gutter))} ${dim(rest)}`);
554
- continue;
555
- }
556
-
557
- const [, number, body] = parsed;
558
- const tint = added ? ADDED : REMOVED;
559
- this.add(
560
- ` ${dim(number.padStart(gutter))} ` +
561
- // Tabs would leave the tint ending short of the row, so they widen.
562
- tint(padVis(clip(`${added ? '+' : '-'} ${body.replace(/\t/g, ' ')}`, room), room))
563
- );
564
- }
565
- this.render(); // a sixteen-line diff is one frame, not sixteen
566
- }
567
-
568
- /** Captured output under a command, dimmed so it reads as evidence. */
569
- commandOutput(lines) {
570
- for (const line of lines) this.add(` ${dim(line)}`);
571
- this.render();
572
- }
573
-
574
- /**
575
- * A running command's output, live — on the status line and nowhere else.
576
- *
577
- * Only the newest line, gone as soon as the next arrives. Appending each one
578
- * instead would mean a test run leaving sixty lines of "ok" in the
579
- * conversation permanently, which is noise the moment it scrolls. What
580
- * survives a command is decided when it ends: nothing if it worked, the tail
581
- * if it did not.
582
- */
583
- progress(lines) {
584
- const last = lines[lines.length - 1]?.trim();
585
- if (last) this.updateSpinner(last);
586
- }
587
-
588
- /**
589
- * The model's own account of the step it is taking, before it takes it.
590
- *
591
- * Not called status(): `this.status` holds the spinner state, and a method
592
- * of the same name would be shadowed by it on every instance.
593
- */
594
- narrate(text) {
595
- const line = asLabel(text);
596
- if (!line) return;
597
- this.push(`${dim('⋮')} ${dim(clip(line, this.width() - 4))}`);
598
- this.updateSpinner(line);
599
- }
600
-
601
- // -- streaming -----------------------------------------------------------
602
- // Deltas appear as plain text as they arrive, then get replaced in place by
603
- // properly rendered markdown once the reply is complete.
604
-
605
- streamBegin() {
606
- this.stopSpinner();
607
- this.streamAt = this.lines.length;
608
- this.streamBuf = '';
609
- this.streamPainted = 0;
610
- }
611
-
612
- streamDelta(delta) {
613
- if (this.streamAt === undefined) this.streamBegin();
614
- this.streamBuf += delta;
615
- const now = Date.now();
616
- if (now - this.streamPainted < 60) return; // about 16fps is plenty
617
- this.streamPainted = now;
618
- this.repaintStream();
619
- }
620
-
621
- /**
622
- * Repaint the partial reply.
623
- *
624
- * polish() runs on the partial text so bold, inline code and bullets are
625
- * already styled while it streams. Without it the text arrives raw and then
626
- * visibly re-renders at the end, which reads as a glitch.
627
- */
628
- repaintStream() {
629
- this.lines.length = this.streamAt;
630
- this.add('');
631
- this.add(polish(this.streamBuf));
632
- this.render(); // one frame, and never one without the reply in it
633
- }
634
-
635
- /**
636
- * Finish a streamed reply.
637
- *
638
- * `asLabel` says the text turned out to be narration ahead of a tool call
639
- * rather than an answer, in which case one short line folds down into the
640
- * status line it was always meant to be.
641
- */
642
- streamEnd({ asNarration = false, closing = false } = {}) {
643
- if (this.streamAt === undefined) return '';
644
- const text = this.streamBuf;
645
- this.lines.length = this.streamAt;
646
- this.streamAt = undefined;
647
- this.streamBuf = '';
648
-
649
- if (asNarration && isLabel(text)) this.narrate(text);
650
- else if (text.trim()) this.assistant(text, { closing });
651
- else this.render();
652
- return text;
653
- }
654
-
655
- // -- thinking ------------------------------------------------------------
656
- // A reasoning model does all its working before it says anything. None of it
657
- // is printed: it is long, repetitive, and guesses drawn from it read worse
658
- // than silence. The spinner counts the seconds so the wait is visibly alive,
659
- // and the transcript gets one line afterwards saying how long it took.
660
-
661
- /**
662
- * The model's reasoning does not go on screen.
663
- *
664
- * It was surfaced here to fill the wait before the first tool call, and what
665
- * it actually filled it with was the model talking to itself: "I need to
666
- * build this", "The user wants a tasks app". Nobody needs their own request
667
- * read back to them, and half-formed working-out is not something to publish.
668
- * What the model *says* is its reply, and that is the only thing shown.
669
- */
670
- thinkingDelta() {}
671
-
672
- thinkingEnd() {}
673
-
674
- error(err, { debug = false } = {}) {
675
- const known = err && typeof err === 'object' && err.attempted;
676
- this.push('');
677
- if (known) {
678
- this.push(`${theme.error('✗')} ${chalk.white(`Failed while ${err.attempted}.`)}`);
679
- this.push(` ${err.failed}`);
680
- if (err.fix) this.push(` ${blue('→')} ${err.fix}`);
681
- if (err.kind) this.push(dim(` (${err.kind})`));
682
- } else {
683
- this.push(`${theme.error('✗')} ${chalk.white('Something broke inside ucode.')}`);
684
- this.push(` ${err?.message ?? String(err)}`);
685
- this.push(` ${blue('→')} That is a bug in ucode rather than in your project. Re-run with --debug.`);
686
- }
687
- if (debug) {
688
- const stack = (known && err.cause?.stack) || err?.stack;
689
- if (stack) this.push(dim(stack));
690
- }
691
- this.push('');
692
- }
693
-
694
- // -- header --------------------------------------------------------------
695
-
696
- setFacts(facts) {
697
- this.facts = { ...this.facts, ...facts };
698
- if (facts.model) this.model = facts.model;
699
- this.render();
700
- }
701
-
702
- /** Same shape as the plain UI's header(), so the loop needs no branch. */
703
- header({ cwd, model, used, limit, title: sessionTitle }) {
704
- if (cwd && cwd !== this.facts.cwd) this.facts.branch = gitBranch(cwd);
705
- this.setFacts({
706
- cwd,
707
- model,
708
- title: sessionTitle,
709
- percent: limit > 0 ? Math.min(100, Math.round((used / limit) * 100)) : 0,
710
- });
711
- }
712
-
713
- /**
714
- * How many rows the header box occupies.
715
- *
716
- * The frame has to be exactly as tall as the terminal or every row below the
717
- * shortfall is off by that much — including the one the caret is parked on.
718
- * So this is derived, never assumed.
719
- */
720
- headerHeight() {
721
- return this.width() >= WORDMARK_NEEDS ? BANNER.length + 2 : 5;
722
- }
723
-
724
- headerLines() {
725
- const width = this.width();
726
- const inner = width - 2; // between the borders
727
-
728
- if (width < WORDMARK_NEEDS) {
729
- // Too narrow for the wordmark: stack it rather than wrap it into noise.
730
- const rows = [
731
- ` ${blue.bold('U C O D E')} ${dim('terminal coding agent')}`,
732
- ` ${dim('dir'.padEnd(8))}${chalk.white(clip(shortenPath(this.facts.cwd ?? this.cwd, inner - 12), inner - 12))}`,
733
- ];
734
- return [boxTop(width), ...rows.map((r) => boxRow(r, width)), boxBottom(width)];
735
- }
736
-
737
- // Two spaces of padding, the wordmark, a gap, then the facts column.
738
- //
739
- // Only what you cannot work out by looking, and never what the status row
740
- // already carries: the model and how full the window is live down there,
741
- // next to each other, and a second copy up here would be a second place to
742
- // keep in sync for no reader who needed it. What is left is where you are,
743
- // which branch that is on, which build you are running, and the two keys
744
- // worth knowing before you have typed anything.
745
- //
746
- // Every row has something on it. Three blank rows and a credit floating
747
- // under them read as a column that was meant to be filled and was not.
748
- const room = Math.max(8, inner - BANNER_WIDTH - 6);
749
- const value = (v) => clip(String(v), Math.max(4, room - 10));
750
- const branch = this.facts.branch;
751
-
752
- // The facts run together from the top with nothing between them, the credit
753
- // sits on the last row, and whatever is left over is the gap between the
754
- // two. Holding a row empty in the middle of the list — which is what a
755
- // fixed six-row layout did when a fact was missing — reads as a line that
756
- // failed to draw rather than as spacing.
757
- const facts = [
758
- ['dir', value(shortenPath(this.facts.cwd ?? this.cwd, room - 10))],
759
- branch && ['branch', value(branch)],
760
- VERSION && ['version', value(this.facts.update ? `${VERSION} → ${this.facts.update} next start` : VERSION)],
761
- ['keys', value('/help · esc interrupts · ctrl+b plan')],
762
- ].filter(Boolean).slice(0, BANNER.length - 1);
763
-
764
- while (facts.length < BANNER.length - 1) facts.push(['', '']);
765
- facts.push(['', 'made with ❤️ by om dixit']);
766
-
767
- const rows = BANNER.map((art, i) => {
768
- const [label, text] = facts[i] ?? ['', ''];
769
- const right = label
770
- ? `${dim(label.padEnd(10))}${chalk.white(text)}`
771
- : (text ? dim(text) : '');
772
- return ` ${bannerPaint(i)(art)} ${right}`;
773
- });
774
-
775
- // The frame is lit the way the wordmark inside it is: brightest along the
776
- // top rule, settling to deep at the bottom. Eight rows of box for six of
777
- // banner, so the borders take the two ends of the same ramp and the box
778
- // reads as one object with a light above it rather than as a rule someone
779
- // drew around a picture.
780
- const depth = BANNER.length + 2;
781
- return [
782
- boxTop(width, bannerPaint(0, depth)),
783
- ...rows.map((r, i) => boxRow(r, width, bannerPaint(i + 1, depth))),
784
- boxBottom(width, bannerPaint(depth - 1, depth)),
785
- ];
786
- }
787
-
788
- // -- input box -----------------------------------------------------------
789
-
790
- /** The typed line, wrapped to the inside of a box `width` characters across. */
791
- /**
792
- * The typed text, laid out as rows inside the box.
793
- *
794
- * A line break in the buffer is a row of its own before any wrapping is
795
- * considered. Slicing the text into fixed widths without looking for one
796
- * put the newline into the frame instead, and the terminal obeyed it — the
797
- * pasted text walked out of the box and over the transcript beside it.
798
- *
799
- * `starts` records where each row begins in the text, so the caret can be
800
- * placed by looking up rather than by counting characters a second way and
801
- * hoping the two agree.
802
- */
803
- inputLines(width = this.inner()) {
804
- const prefix = this.pendingPrompt ? `${this.pendingPrompt} ` : '› ';
805
- const full = prefix + this.buffer;
806
-
807
- const rows = [];
808
- const starts = [];
809
- let at = 0;
810
-
811
- for (const para of full.split(NEWLINE)) {
812
- let i = 0;
813
- do {
814
- rows.push(para.slice(i, i + width));
815
- starts.push(at + i);
816
- i += width;
817
- } while (i < para.length);
818
- at += para.length + 1; // the newline itself
819
- }
820
-
821
- if (rows.length === 0) { rows.push(prefix); starts.push(0); }
822
- return { rows, prefix, width, starts };
823
- }
824
-
825
- /** Which row the caret sits on, and how far along it. */
826
- caretAt(width) {
827
- const { rows, prefix, starts } = this.inputLines(width);
828
- const index = prefix.length + this.cursor;
829
- let row = 0;
830
- while (row + 1 < starts.length && starts[row + 1] <= index) row++;
831
- return { row, col: Math.min(index - starts[row], rows[row].length), rows };
832
- }
833
-
834
- viewportHeight() {
835
- return Math.max(
836
- 3,
837
- this.rows - this.headerHeight() - CHROME_BELOW - this.inputLines().rows.length
838
- );
839
- }
840
-
841
- /**
842
- * The input box: what you are typing, and directly under it, inside the same
843
- * border, the three things worth knowing while you type.
844
- *
845
- * The status used to sit outside the box on the last row of the screen,
846
- * which made it a separate object floating under the input. Inside the
847
- * border it reads as part of the thing you are using — the box says "this is
848
- * where you work", and the row underneath says what you are working with.
849
- */
850
- inputBox(width = this.width()) {
851
- const { rows } = this.inputLines(width - 4);
852
- const border = this.borderPaint();
853
- const busy = this.busy();
854
- // Nothing typed yet: a quiet prompt where the text will go. The caret sits
855
- // on its first letter and typing replaces it.
856
- const empty = !this.buffer && !this.pendingPrompt;
857
- const hint = !busy ? PLACEHOLDER
858
- : (width >= WORKING_HINT_NEEDS ? WORKING_HINT : WORKING_HINT_SHORT);
859
- const painted = rows.map((row, i) =>
860
- i === 0
861
- ? boxRow(` ${border('›')}${empty ? ` ${dim(hint)}` : row.slice(1)}`, width, border)
862
- : boxRow(` ${row}`, width, border)
863
- );
864
- return [
865
- boxTop(width, border),
866
- ...painted,
867
- // A blank row between the two. Sitting directly under the caret, the
868
- // status read as a second line of the thing being typed; one row of air
869
- // separates what you are writing from what you are writing it with.
870
- boxRow('', width, border),
871
- boxRow(this.statusRow(width), width, border),
872
- boxBottom(width, border),
873
- ];
874
- }
875
-
876
- /** Is the agent holding the turn? */
877
- busy() {
878
- return this.status.busy || !!this.activity;
879
- }
880
-
881
- /**
882
- * The input box's edge, which says whose turn it is.
883
- *
884
- * Bold blue while the box is yours, quiet while the agent has it. The status
885
- * row inside the same box already carries the words; this is the half you
886
- * catch without reading, from the corner of your eye, in the one place on
887
- * screen you were already looking.
888
- */
889
- borderPaint() {
890
- return this.busy() ? deep : edge;
891
- }
892
-
893
- /**
894
- * Repaint after something that may have changed whose turn it is.
895
- *
896
- * The cheap path redraws one row, which is right twelve times a second for a
897
- * spinner and wrong at a turn boundary: the border above and below would
898
- * still be the old weight while the status row had the new one, and the box
899
- * would be drawn in two colours. A whole frame costs nothing twice a turn.
900
- */
901
- paintBusy() {
902
- if (this.busy() === this.paintedBusy) this.paintStatus();
903
- else this.render();
904
- }
905
-
906
- // -- status row ----------------------------------------------------------
907
-
908
- modeChip() {
909
- return modeChip(this.mode);
910
- }
911
-
912
- /**
913
- * How full the context window is, as a bare number.
914
- *
915
- * It turns amber at 75% because that is where turns start being folded away
916
- * into a summary — the one moment the number predicts something you would
917
- * want to know before it happens.
918
- */
919
- percentChip() {
920
- const percent = Math.round(this.facts.percent ?? 0);
921
- return percent >= 75 ? theme.warn(`${percent}%`) : dim(`${percent}%`);
922
- }
923
-
924
- /**
925
- * Which mode is live, which model is answering, and how full the window is.
926
- *
927
- * Nothing else earns a place. The provider name was there and was cut: it is
928
- * the same on every line of every session, so it was decoration that had to
929
- * be read past to reach the two things that do change.
930
- *
931
- * The spinner used to borrow the middle of this row while something ran. It
932
- * has a row of its own outside the box now, so the only thing that ever
933
- * appears between the model and the percentage is a flash — a reply to
934
- * something you just pressed, gone a moment later.
935
- */
936
- statusRow(width = this.width()) {
937
- const inner = width - 2; // the space between the two borders
938
- const chip = this.modeChip();
939
- const left = ` ${chip} ${chalk.white(this.model || '—')}`;
940
-
941
- // How long the turn has taken, back in the box beside the other two facts
942
- // about the session. It is not on the live line: that line says what is
943
- // being done, and a clock ticking in the middle of it competes with the
944
- // words for no reason. Under a second there is no number worth reading.
945
- const now = Date.now();
946
- const since = this.activity?.start ?? this.status.since ?? 0;
947
- const running = this.busy() && since && now - since >= 1000;
948
- const right = `${running ? `${dim(formatDuration(now - since))} ` : ''}${this.percentChip()} `;
949
-
950
- // Where a click on the bottom row still counts as hitting the mode chip.
951
- this.chipTo = 2 + visLen(chip);
952
-
953
- const between = Math.max(1, inner - visLen(left) - visLen(right));
954
- const middle = this.flashText ? dim(clip(this.flashText, between - 2)) : '';
955
-
956
- const tail = middle ? `${middle} ` : '';
957
- const pad = Math.max(1, inner - visLen(left) - visLen(tail) - visLen(right));
958
- return padVis(left + ' '.repeat(pad) + tail + right, inner);
959
- }
960
-
961
- /**
962
- * What is happening right now: the spinner, what it is doing, how long it has
963
- * been doing it, and the way out.
964
- *
965
- * It used to live in whatever space the status row had spare between the
966
- * model name and the percentage — inside the box you type into, which is the
967
- * one place on screen that is about you rather than about the agent. Out
968
- * here it sits directly under the steps it belongs to, in the same column,
969
- * and has room for a bar instead of a shimmer.
970
- */
971
- activityLine(width = this.width()) {
972
- if (!this.busy()) return '';
973
- const now = Date.now();
974
- return workingLine({
975
- glyph: spinnerGlyph(this.tick, now),
976
- label: this.status.busy ? this.status.text : 'working',
977
- hint: 'esc to stop',
978
- room: Math.max(4, width),
979
- t: now,
980
- });
981
- }
982
-
983
- /**
984
- * Which row the live line is painted on, 1-based, or 0 when it is not shown.
985
- *
986
- * It is the last line of the conversation, so its row moves as the
987
- * conversation grows and stops moving once the viewport is full. Scrolled
988
- * back, or with the picker open, it is not on screen at all and the cheap
989
- * repaint has nothing to do.
990
- */
991
- activityRowAt() {
992
- if (this.scroll > 0 || this.picker) return 0;
993
- const index = Math.min(this.lines.length + 1, this.viewportHeight()) - 1;
994
- return index < 0 ? 0 : this.headerHeight() + 2 + index;
995
- }
996
-
997
- /**
998
- * Repaint only the moving rows, leaving the caret where the user left it.
999
- *
1000
- * It is the second row from the bottom now — the box's own border is below
1001
- * it — so the row is written with its borders rather than as a bare line.
1002
- */
1003
- paintStatus() {
1004
- if (this.closed) return;
1005
- // On the start screen the status row is mid-screen, not second from the
1006
- // bottom, so the cheap single-row repaint would draw it in the wrong place.
1007
- if (this.welcoming()) {
1008
- this.render();
1009
- return;
1010
- }
1011
- const [row, col] = this.caret();
1012
- const width = this.width();
1013
- const liveAt = this.activityRowAt();
1014
- this.output.write(
1015
- HIDE +
1016
- (liveAt ? at(liveAt, 1) + CLEAR_LINE + padVis(this.activityLine(width), width) : '') +
1017
- at(this.rows - 1, 1) + CLEAR_LINE + boxRow(this.statusRow(width), width, this.borderPaint()) +
1018
- at(row, col) + SHOW
1019
- );
1020
- }
1021
-
1022
- toggleMode() {
1023
- this.mode = this.mode === 'plan' ? 'build' : 'plan';
1024
- this.flash(this.mode === 'plan'
1025
- ? 'plan mode — reads and researches, changes nothing'
1026
- : 'build mode — free to edit files and run commands');
1027
- this.onModeChange?.(this.mode);
1028
- this.render();
1029
- }
1030
-
1031
- /** A message on the status line that fades on its own. */
1032
- flash(text) {
1033
- this.flashText = text;
1034
- clearTimeout(this.flashTimer);
1035
- this.flashTimer = setTimeout(() => {
1036
- this.flashText = null;
1037
- this.paintStatus();
1038
- }, 2500);
1039
- this.flashTimer.unref?.();
1040
- this.paintStatus();
1041
- }
1042
-
1043
- // -- spinner -------------------------------------------------------------
1044
-
1045
- startSpinner(text = 'thinking') {
1046
- // `since` is what makes a long think legible: the label may not change for
1047
- // a minute, so the seconds beside it are the proof it is still alive.
1048
- this.status = { busy: true, text: asLabel(text), frame: 0, since: Date.now() };
1049
- this.startTimer();
1050
- this.paintBusy();
1051
- }
1052
-
1053
- updateSpinner(text) {
1054
- if (!this.status.busy) return;
1055
- this.status.text = asLabel(text);
1056
- this.paintStatus();
1057
- }
1058
-
1059
- stopSpinner() {
1060
- if (!this.activity) this.stopTimer();
1061
- if (this.status.busy) {
1062
- this.status = { busy: false, text: '', frame: 0, since: 0 };
1063
- this.paintBusy();
1064
- }
1065
- }
1066
-
1067
- // -- the turn in flight ----------------------------------------------------
1068
-
1069
- /** A turn begins: the timer and step count run until turnEnd(). */
1070
- turnStart() {
1071
- this.newSegment();
1072
- this.activity = { start: Date.now(), steps: 0, movedAt: 0 };
1073
- this.startTimer();
1074
- this.paintBusy();
1075
- }
1076
-
1077
- /** One more model step in this turn. */
1078
- step() {
1079
- if (!this.activity) return;
1080
- this.activity.steps++;
1081
- this.activity.movedAt = Date.now();
1082
- }
1083
-
1084
- /** The turn is over: leave "✓ Done in 6m 12s · 25 steps" under the answer. */
1085
- turnEnd({ ok = true } = {}) {
1086
- const a = this.activity;
1087
- this.activity = null;
1088
- if (!this.status.busy) this.stopTimer();
1089
- // Nothing is written when a turn finishes. The reply is the end of the
1090
- // turn, and a timing line under it is bookkeeping the reader did not ask
1091
- // for. A turn that stopped *without* finishing still says so, because
1092
- // silence there is indistinguishable from a crash.
1093
- if (a && !ok && Date.now() - a.start >= 2000) {
1094
- this.push(` ${doneLine(Date.now() - a.start, a.steps, { ok })}`);
1095
- }
1096
- this.paintBusy();
1097
- }
1098
-
1099
- /** The animation clock: only the status row repaints, about twelve times a second. */
1100
- startTimer() {
1101
- if (this.spinTimer) return;
1102
- this.spinTimer = setInterval(() => {
1103
- // Only the status row repaints on a tick. Animating a transcript line
1104
- // meant redrawing the whole frame twelve times a second, and the input
1105
- // box was being rebuilt under the user's cursor as they typed.
1106
- this.tick++;
1107
- this.paintStatus();
1108
- }, FRAME_MS);
1109
- this.spinTimer.unref?.();
1110
- }
1111
-
1112
- stopTimer() {
1113
- if (!this.spinTimer) return;
1114
- clearInterval(this.spinTimer);
1115
- this.spinTimer = null;
1116
- }
1117
-
1118
- // -- input ---------------------------------------------------------------
1119
-
1120
- nextLine() {
1121
- if (this.queue.length) return Promise.resolve(this.queue.shift());
1122
- if (this.closed) return Promise.resolve(null);
1123
- return new Promise((resolve) => this.waiters.push(resolve));
1124
- }
1125
-
1126
- ask() {
1127
- return this.nextLine();
1128
- }
1129
-
1130
- submit(text) {
1131
- const waiter = this.waiters.shift();
1132
- if (waiter) waiter(text);
1133
- else this.queue.push(text);
1134
- }
1135
-
1136
- /** y/n, answered on the input line. */
1137
- confirm({ action, detail, risk }) {
1138
- this.push('');
1139
- this.push(`${chalk.inverse(theme.warn(risk === 'command' ? ' shell ' : ' outside project '))} ${chalk.white(action)}`);
1140
- for (const line of String(detail ?? '').split('\n')) {
1141
- if (line) this.push(dim(` ${line}`));
1142
- }
1143
-
1144
- this.pendingPrompt = 'go ahead? [y/N]';
1145
- this.render();
1146
-
1147
- return this.nextLine().then((answer) => {
1148
- this.pendingPrompt = null;
1149
- // End of input counts as no. Never run something nobody approved.
1150
- const yes = /^(y|yes)$/i.test(String(answer ?? '').trim());
1151
- this.push(dim(yes ? ' approved' : ' declined'));
1152
- this.push('');
1153
- return yes;
1154
- });
1155
- }
1156
-
1157
- /**
1158
- * A modal list: arrows move, Enter picks, Esc cancels.
1159
- *
1160
- * Only while this is open do the arrows stop scrolling the transcript. They
1161
- * cannot be given up permanently, because under alternate scroll the mouse
1162
- * wheel arrives as arrow keys.
1163
- */
1164
- pick(items, { active = 0, hint = 'enter to choose · esc to cancel', deletable = false } = {}) {
1165
- this.picker = {
1166
- items,
1167
- index: Math.min(Math.max(0, active), Math.max(0, items.length - 1)),
1168
- hint,
1169
- // With deletable, `d` twice on a row resolves { delete: index }. Twice,
1170
- // because a single stray keypress should never cost a conversation.
1171
- deletable,
1172
- armed: null,
1173
- };
1174
- this.render();
1175
- return new Promise((resolve) => { this.pickerResolve = resolve; });
1176
- }
1177
-
1178
- closePicker(value) {
1179
- const resolve = this.pickerResolve;
1180
- this.picker = null;
1181
- this.pickerResolve = null;
1182
- this.render();
1183
- resolve?.(value);
1184
- }
1185
-
1186
- /**
1187
- * Rows for an open picker, windowed so a long list still fits.
1188
- *
1189
- * An item may carry a `sub` line — a second, dimmer row underneath it. That
1190
- * is what lets a list of saved conversations show what each one was actually
1191
- * about instead of a column of near-identical titles.
1192
- */
1193
- pickerLines(height) {
1194
- const { items, index, hint, armed } = this.picker;
1195
- const room = Math.max(1, height - 2);
1196
-
1197
- // Rows per item, so the window can be sized in rows rather than in items.
1198
- const rowsFor = (item) => (typeof item !== 'string' && item.sub ? 2 : 1);
1199
- const perItem = items.map(rowsFor);
1200
-
1201
- // Walk outward from the selection until the window is full. Starting from
1202
- // the selection guarantees it is on screen however long the list is.
1203
- let first = index;
1204
- let last = index;
1205
- let used = perItem[index] ?? 1;
1206
- while (used < room && (first > 0 || last < items.length - 1)) {
1207
- if (first > 0 && used + perItem[first - 1] <= room) { first--; used += perItem[first]; }
1208
- else if (last < items.length - 1 && used + perItem[last + 1] <= room) { last++; used += perItem[last]; }
1209
- else break;
1210
- }
1211
-
1212
- const out = [];
1213
- for (let i = first; i <= last; i++) {
1214
- const item = items[i];
1215
- const body = typeof item === 'string' ? item : item.label;
1216
- if (i === armed) out.push(`${theme.warn('✗')} ${theme.warn(bare(body))}`);
1217
- else out.push(i === index ? `${blue('❯')} ${chalk.bold.white(body)}` : ` ${dim(body)}`);
1218
- if (typeof item !== 'string' && item.sub) out.push(` ${item.sub}`);
1219
- }
1220
-
1221
- out.push('');
1222
- out.push(armed !== null && armed !== undefined
1223
- ? theme.warn(' press d again to delete this conversation · any other key keeps it')
1224
- : dim(` ${hint}`));
1225
- return out;
1226
- }
1227
-
1228
- /** A numbered list, answered on the input line. */
1229
- async choose(prompt, items, { allowNone = true } = {}) {
1230
- items.forEach((item, i) => this.push(` ${blue(String(i + 1).padStart(2))}. ${item}`));
1231
- if (allowNone) this.push(dim(' 0. none — start fresh'));
1232
- this.push('');
1233
-
1234
- this.pendingPrompt = prompt;
1235
- this.render();
1236
-
1237
- const answer = await this.nextLine();
1238
- this.pendingPrompt = null;
1239
-
1240
- const trimmed = String(answer ?? '').trim();
1241
- if (trimmed === '' || trimmed === '0') return null;
1242
-
1243
- const index = Number(trimmed);
1244
- if (!Number.isInteger(index) || index < 1 || index > items.length) {
1245
- this.push(theme.warn(` "${trimmed}" is not one of 1-${items.length}.`));
1246
- return null;
1247
- }
1248
- return index - 1;
1249
- }
1250
-
1251
- // -- keyboard and mouse --------------------------------------------------
1252
-
1253
- /**
1254
- * Scroll the transcript, clamped at both ends.
1255
- *
1256
- * When there is nothing above the fold, say so. Silence is indistinguishable
1257
- * from broken input, and the difference matters: one means the conversation
1258
- * simply fits, the other means the terminal is not forwarding keys at all.
1259
- */
1260
- scrollBy(delta) {
1261
- const max = Math.max(0, this.lines.length - this.viewportHeight());
1262
- if (max === 0) {
1263
- this.flash('nothing above — it all fits on screen');
1264
- return;
1265
- }
1266
- const before = this.scroll;
1267
- this.scroll = Math.min(Math.max(0, this.scroll + delta), max);
1268
- if (this.scroll === before && delta > 0) this.flash('already at the top');
1269
- this.render();
1270
- }
1271
-
1272
- /**
1273
- * Text arriving as a paste rather than as typing.
1274
- *
1275
- * A terminal in bracketed-paste mode wraps pasted text in markers, which is
1276
- * the only way to tell forty lines pasted at once from forty lines typed
1277
- * very fast. Without it every newline in the paste reads as Enter, so a
1278
- * pasted block submits itself a line at a time and arrives as forty
1279
- * messages. Inside the markers a newline is just a character.
1280
- */
1281
- onPaste(text) {
1282
- const clean = String(text).replace(/\r\n?/g, '\n');
1283
- this.buffer = this.buffer.slice(0, this.cursor) + clean + this.buffer.slice(this.cursor);
1284
- this.cursor += clean.length;
1285
- this.render();
1286
- }
1287
-
1288
- onData(chunk) {
1289
- // Pasted text first: it is wrapped in markers and must not be read as
1290
- // keys, or its newlines submit it in pieces.
1291
- const paste = /\[200~([\s\S]*?)\[201~/g;
1292
- if (paste.test(chunk)) {
1293
- paste.lastIndex = 0;
1294
- let at = 0;
1295
- let m;
1296
- while ((m = paste.exec(chunk))) {
1297
- if (m.index > at) this.onData(chunk.slice(at, m.index));
1298
- this.onPaste(m[1]);
1299
- at = m.index + m[0].length;
1300
- }
1301
- if (at < chunk.length) this.onData(chunk.slice(at));
1302
- return;
1303
- }
1304
- // An unterminated paste: hold what has arrived and wait for the rest.
1305
- const open = chunk.indexOf('[200~');
1306
- if (open !== -1) {
1307
- if (open > 0) this.onData(chunk.slice(0, open));
1308
- this.pasting = chunk.slice(open + 6);
1309
- return;
1310
- }
1311
- if (this.pasting !== undefined && this.pasting !== null) {
1312
- const close = chunk.indexOf('[201~');
1313
- if (close === -1) { this.pasting += chunk; return; }
1314
- this.onPaste(this.pasting + chunk.slice(0, close));
1315
- this.pasting = null;
1316
- const after = chunk.slice(close + 6);
1317
- if (after) this.onData(after);
1318
- return;
1319
- }
1320
-
1321
- // UCODE_DEBUG_KEYS=1 logs every byte the terminal sends to
1322
- // ~/.ucode/keys.log. Whether mouse reporting works at all depends on the
1323
- // terminal forwarding it; this is how to find out.
1324
- if (process.env.UCODE_DEBUG_KEYS) {
1325
- appendFile(path.join(homedir(), '.ucode', 'keys.log'), `${JSON.stringify(chunk)}\n`).catch(() => {});
1326
- }
1327
-
1328
- // Pull mouse reports out of the chunk wherever they sit. Anchoring the
1329
- // match to the whole chunk meant a wheel event arriving alongside any
1330
- // other byte was silently treated as typing.
1331
- let rest = '';
1332
- let index = 0;
1333
- // Two encodings: SGR (ESC [ < b ; x ; y M|m), and the legacy form
1334
- // (ESC [ M then three bytes offset by 32) for terminals that ignore 1006.
1335
- const mouse = /\x1b\[<(\d+);(\d+);(\d+)([Mm])|\x1b\[M([\s\S])([\s\S])([\s\S])/g;
1336
- let match;
1337
-
1338
- while ((match = mouse.exec(chunk)) !== null) {
1339
- rest += chunk.slice(index, match.index);
1340
- index = match.index + match[0].length;
1341
- if (match[1] !== undefined) {
1342
- this.onMouse(Number(match[1]), Number(match[2]), Number(match[3]), match[4]);
1343
- } else {
1344
- this.onMouse(
1345
- match[5].charCodeAt(0) - 32,
1346
- match[6].charCodeAt(0) - 32,
1347
- match[7].charCodeAt(0) - 32,
1348
- 'M'
1349
- );
1350
- }
1351
- }
1352
- rest += chunk.slice(index);
1353
-
1354
- // A chunk carrying a line break *and* other text did not come from a
1355
- // keyboard: nobody types a newline in the middle of a burst. Many
1356
- // terminals, Windows ones especially, send a paste with no markers at
1357
- // all, so without this every newline in it reads as Enter and the paste
1358
- // submits itself a line at a time.
1359
- if (looksPasted(rest)) { this.onPaste(rest); return; }
1360
-
1361
- for (const key of splitKeys(rest)) this.onKey(key);
1362
- }
1363
-
1364
- onMouse(button, col, row, press) {
1365
- // Wheel reports set bit 6; bit 0 says which way.
1366
- if (button >= 64) {
1367
- this.scrollBy(button % 2 === 0 ? 3 : -3);
1368
- return;
1369
- }
1370
- if (press !== 'M' || button !== 0) return;
1371
- if (this.welcoming()) {
1372
- const g = this.welcomeGeometry();
1373
- const statusRow = g.boxTop + g.inputRows + 3; // 1-based
1374
- if (row === statusRow && col > g.left + 1 && col <= g.left + this.chipTo) this.toggleMode();
1375
- return;
1376
- }
1377
- // The mode chip, at the left of the bottom row.
1378
- if (row === this.rows - 1 && col >= 2 && col <= this.chipTo) this.toggleMode();
1379
- }
1380
-
1381
- onKey(key) {
1382
- // An open picker owns the keyboard until it closes.
1383
- if (this.picker) {
1384
- const last = this.picker.items.length - 1;
1385
- if (this.picker.deletable && (key === 'd' || key === 'D' || key === `${ESC}[3~`)) {
1386
- if (this.picker.armed === this.picker.index) { this.closePicker({ delete: this.picker.index }); return; }
1387
- this.picker.armed = this.picker.index;
1388
- this.render();
1389
- return;
1390
- }
1391
- this.picker.armed = null; // any other key takes the delete back
1392
- if (key === `${ESC}[A`) { this.picker.index = Math.max(0, this.picker.index - 1); this.render(); return; }
1393
- if (key === `${ESC}[B`) { this.picker.index = Math.min(last, this.picker.index + 1); this.render(); return; }
1394
- if (key === '\r' || key === '\n') { this.closePicker(this.picker.index); return; }
1395
- if (key === ESC || key === '\x03') { this.closePicker(null); return; }
1396
- return;
1397
- }
1398
-
1399
- switch (key) {
1400
- case '\r':
1401
- case '\n': {
1402
- const text = this.buffer;
1403
- this.buffer = '';
1404
- this.cursor = 0;
1405
- this.historyIndex = -1;
1406
- if (text.trim()) {
1407
- this.history.unshift(text);
1408
- // Answers to a y/N or a numbered pick are not messages, so they are
1409
- // not echoed: the prompt reports its own outcome.
1410
- if (!this.pendingPrompt) this.userMessage(text);
1411
- }
1412
- this.render();
1413
- this.submit(text);
1414
- return;
1415
- }
1416
-
1417
- case '\x7f': // backspace
1418
- case '\b':
1419
- if (this.cursor > 0) {
1420
- this.buffer = this.buffer.slice(0, this.cursor - 1) + this.buffer.slice(this.cursor);
1421
- this.cursor--;
1422
- }
1423
- break;
1424
-
1425
- case '\x03': // ctrl+c
1426
- if (this.status.busy && this.onInterrupt) this.onInterrupt();
1427
- else { this.buffer = ''; this.cursor = 0; }
1428
- break;
1429
-
1430
- case '\x04': // ctrl+d
1431
- this.close();
1432
- return;
1433
-
1434
- case '\x02': // ctrl+b — swap plan and build
1435
- this.toggleMode();
1436
- return;
1437
-
1438
- case '\x15': // ctrl+u — clear the line
1439
- this.buffer = this.buffer.slice(this.cursor);
1440
- this.cursor = 0;
1441
- break;
1442
-
1443
- case ESC: // esc — stop the turn in flight
1444
- if (this.onInterrupt) this.onInterrupt();
1445
- return;
1446
-
1447
- case '\t': {
1448
- const hit = COMMANDS.find((c) => c.startsWith(this.buffer));
1449
- if (hit) { this.buffer = hit; this.cursor = hit.length; }
1450
- break;
1451
- }
1452
-
1453
- // With an empty line the arrows scroll the conversation; once there is
1454
- // something typed they walk history. Terminals often swallow PgUp and
1455
- // PgDn for their own scrollback, so this is the path that always works.
1456
- case `${ESC}[A`:
1457
- if (!this.buffer) { this.scrollBy(2); return; }
1458
- if (this.history.length) {
1459
- this.historyIndex = Math.min(this.historyIndex + 1, this.history.length - 1);
1460
- this.buffer = this.history[this.historyIndex] ?? '';
1461
- this.cursor = this.buffer.length;
1462
- }
1463
- break;
1464
-
1465
- case `${ESC}[B`:
1466
- if (!this.buffer) { this.scrollBy(-2); return; }
1467
- this.historyIndex = Math.max(this.historyIndex - 1, -1);
1468
- this.buffer = this.historyIndex === -1 ? '' : (this.history[this.historyIndex] ?? '');
1469
- this.cursor = this.buffer.length;
1470
- break;
1471
-
1472
- case `${ESC}[1;5A`: this.scrollBy(2); return; // ctrl+up
1473
- case `${ESC}[1;5B`: this.scrollBy(-2); return; // ctrl+down
1474
- case `${ESC}[5~`: this.scrollBy(this.viewportHeight()); return;
1475
- case `${ESC}[6~`: this.scrollBy(-this.viewportHeight()); return;
1476
-
1477
- case `${ESC}[H`: this.scrollBy(this.lines.length); return;
1478
- case `${ESC}[F`: this.scroll = 0; this.render(); return;
1479
-
1480
- case `${ESC}[C`: this.cursor = Math.min(this.cursor + 1, this.buffer.length); break;
1481
- case `${ESC}[D`: this.cursor = Math.max(this.cursor - 1, 0); break;
1482
-
1483
- default:
1484
- if (key >= ' ' && !key.startsWith(ESC)) {
1485
- this.buffer = this.buffer.slice(0, this.cursor) + key + this.buffer.slice(this.cursor);
1486
- this.cursor += key.length;
1487
- } else {
1488
- return;
1489
- }
1490
- }
1491
-
1492
- this.render();
1493
- }
1494
-
1495
- // -- painting ------------------------------------------------------------
1496
-
1497
- render() {
1498
- if (this.closed) return;
1499
- if (this.welcoming()) {
1500
- this.renderWelcome();
1501
- return;
1502
- }
1503
-
1504
- const width = this.width();
1505
- const height = this.viewportHeight();
1506
-
1507
- // The live line is the last line of the conversation, not a fixture above
1508
- // the input box. Pinned down there it sat at the bottom of the screen while
1509
- // the message that started it was at the top, with the empty middle of the
1510
- // viewport between them — so the thing being done looked unrelated to the
1511
- // thing that had been asked. On the end of the transcript it arrives
1512
- // directly under the prompt, which is where the eye already is.
1513
- const live = this.activityLine(width);
1514
- const said = live ? [...this.lines, live] : this.lines;
1515
-
1516
- const end = Math.max(0, said.length - this.scroll);
1517
- const start = Math.max(0, end - height);
1518
- const window = this.picker ? this.pickerLines(height) : said.slice(start, end);
1519
- while (window.length < height) window.push('');
1520
-
1521
- const frame = [
1522
- ...this.headerLines(),
1523
- '',
1524
- ...window,
1525
- // Always one clear row between the last thing said and the box you type
1526
- // in. Without it the newest line of output sits against the border and
1527
- // reads as part of the input rather than as the answer above it.
1528
- '',
1529
- ...this.inputBox(),
1530
- ];
1531
-
1532
- // The cursor is hidden for the duration of the paint. Without this it is
1533
- // dragged through every line as the frame is written, which shows up as a
1534
- // dot flickering above the input box on every keystroke.
1535
- const out = [HIDE, HOME];
1536
- for (let i = 0; i < this.rows; i++) {
1537
- out.push(CLEAR_LINE + padVis(frame[i] ?? '', width) + (i === this.rows - 1 ? '' : '\n'));
1538
- }
1539
-
1540
- const [row, col] = this.caret();
1541
- out.push(at(row, col) + SHOW);
1542
- this.paintedBusy = this.busy();
1543
- this.output.write(out.join(''));
1544
- }
1545
-
1546
- /**
1547
- * Where the typing caret belongs, 1-based.
1548
- *
1549
- * Column three is the first character inside the box: border, a space of
1550
- * padding, then the text.
1551
- */
1552
- caret() {
1553
- if (this.welcoming()) {
1554
- const g = this.welcomeGeometry();
1555
- const { row, col } = this.caretAt(g.boxWidth - 4);
1556
- // g.boxTop is 0-based and the typed lines start one below the border.
1557
- return [g.boxTop + 2 + row, g.left + 3 + col];
1558
- }
1559
-
1560
- const { row, col: at, rows } = this.caretAt();
1561
- const col = 3 + at;
1562
- // Counting up from the bottom: the box border is the last row, the status
1563
- // row is above it, then the blank row, then the typed lines.
1564
- const firstRow = this.rows - 2 - rows.length;
1565
- return [firstRow + row, col];
1566
- }
1567
-
1568
- // -- start screen ----------------------------------------------------------
1569
-
1570
- /**
1571
- * Nothing has been said yet, so there is nothing to scroll: the screen is the
1572
- * wordmark and the place to type, centred, and nothing else.
1573
- *
1574
- * It comes back after /clear and /new too, since those empty the transcript —
1575
- * a fresh conversation starts from the same quiet screen as a fresh launch.
1576
- */
1577
- welcoming() {
1578
- return this.lines.length === 0 && !this.picker;
1579
- }
1580
-
1581
- /** Where everything on the start screen goes, 0-based rows. */
1582
- welcomeGeometry() {
1583
- const cols = this.width();
1584
- const boxWidth = Math.max(30, Math.min(cols - 4, 84));
1585
- const left = Math.max(0, Math.floor((cols - boxWidth) / 2));
1586
- const big = cols >= BANNER_WIDTH + 4 && this.rows >= 18;
1587
- const art = big ? BANNER : ['u c o d e'];
1588
- const inputRows = this.inputLines(boxWidth - 4).rows.length;
1589
- const boxRows = inputRows + 4; // borders, typed rows, gap, status
1590
- const suggest = this.rows >= boxRows + art.length + SUGGEST_ROWS + 6;
1591
- const block = art.length + 2 + boxRows + (suggest ? SUGGEST_ROWS : 0);
1592
- // A touch above true centre reads as centred; exact centre looks low.
1593
- const top = Math.max(0, Math.floor((this.rows - block) / 2) - 1);
1594
- return { cols, boxWidth, left, big, art, inputRows, boxRows, suggest, top, boxTop: top + art.length + 2 };
1595
- }
1596
-
1597
- renderWelcome() {
1598
- const g = this.welcomeGeometry();
1599
- const frame = new Array(this.rows).fill('');
1600
-
1601
- // The wordmark lit from the top: sky at the crown, deep in the shadow
1602
- // rows. Across the rows rather than along them — a name split down its
1603
- // middle reads as two words, where a name that fades downward reads as
1604
- // one object with a light on it.
1605
- const elapsed = this.intro ? Date.now() - this.intro : Infinity;
1606
- g.art.forEach((line, i) => {
1607
- const pad = ' '.repeat(Math.max(0, Math.floor((g.cols - line.length) / 2)));
1608
- frame[g.top + i] = pad + (g.big
1609
- ? bannerSweep(line, i, g.art.length, elapsed)
1610
- : blue.bold(line));
1611
- });
1612
-
1613
- const indent = ' '.repeat(g.left);
1614
- this.inputBox(g.boxWidth).forEach((row, i) => {
1615
- frame[g.boxTop + i] = indent + row;
1616
- });
1617
-
1618
- // Three things to try, aligned with the text inside the box above them.
1619
- if (g.suggest) {
1620
- const at = g.boxTop + g.boxRows + 1;
1621
- SUGGESTIONS.forEach((text, i) => {
1622
- const label = i === 0 ? 'try'.padEnd(SUGGEST_LABEL) : ' '.repeat(SUGGEST_LABEL);
1623
- frame[at + i] = `${indent} ${dim(sky(label))}${dim(clip(text, Math.max(8, g.boxWidth - SUGGEST_LABEL - 2)))}`;
1624
- });
1625
- }
1626
-
1627
- // The version, in the corner, and nothing else on the screen.
1628
- if (VERSION) {
1629
- const tag = dim(this.facts.update ? `v${VERSION} · v${this.facts.update} installed, starts next time` : `v${VERSION}`);
1630
- frame[this.rows - 1] = ' '.repeat(Math.max(0, g.cols - visLen(tag) - 2)) + tag;
1631
- }
1632
-
1633
- const out = [HIDE, HOME];
1634
- for (let i = 0; i < this.rows; i++) {
1635
- out.push(CLEAR_LINE + padVis(frame[i], g.cols) + (i === this.rows - 1 ? '' : '\n'));
1636
- }
1637
- const [row, col] = this.caret();
1638
- out.push(at(row, col) + SHOW);
1639
- this.paintedBusy = this.busy();
1640
- this.output.write(out.join(''));
1641
- }
1642
- }
1643
-
1644
- /**
1645
- * Split a raw stdin chunk into keys, keeping escape sequences whole.
1646
- *
1647
- * Application cursor key mode (DECCKM) makes a terminal send ESC O A for the
1648
- * up arrow rather than ESC [ A. Both are normalised to the bracket form here
1649
- * so the key handler only ever sees one of them.
1650
- */
1651
- /**
1652
- * Did this arrive as a paste, judged by shape rather than by markers?
1653
- *
1654
- * Someone pressing Enter sends one carriage return on its own. A paste sends
1655
- * a line break with text around it, in a single read. That difference is all
1656
- * there is to go on when a terminal does not implement bracketed paste, and
1657
- * it is enough.
1658
- *
1659
- * Anything carrying an escape sequence is left alone: that is a key or a
1660
- * mouse report, and reading one as text would put gibberish in the input.
1661
- */
1662
- export function looksPasted(chunk) {
1663
- const text = String(chunk ?? '');
1664
- if (text.length < 2 || text.includes(ESC)) return false;
1665
- const breaks = (text.match(/[\r\n]/g) ?? []).length;
1666
- if (breaks === 0) return false;
1667
- // One trailing break is someone finishing a line, not pasting one.
1668
- if (breaks === 1 && /[\r\n]$/.test(text)) return false;
1669
- return true;
1670
- }
1671
-
1672
- export function splitKeys(chunk) {
1673
- const keys = [];
1674
- let i = 0;
1675
-
1676
- while (i < chunk.length) {
1677
- const c = chunk[i];
1678
- if (c !== ESC) { keys.push(c); i++; continue; }
1679
-
1680
- const rest = chunk.slice(i);
1681
- const csi = /^\x1b\[[0-9;?]*[A-Za-z~]/.exec(rest);
1682
- if (csi) { keys.push(csi[0]); i += csi[0].length; continue; }
1683
-
1684
- const ss3 = /^\x1bO([A-Za-z])/.exec(rest);
1685
- if (ss3) { keys.push(`${ESC}[${ss3[1]}`); i += ss3[0].length; continue; }
1686
-
1687
- keys.push(ESC);
1688
- i++;
1689
- }
1690
-
1691
- return keys;
1692
- }
1
+ /**
2
+ * screen.js — the full-screen interface.
3
+ *
4
+ * Used whenever stdout is a real terminal. Everything else — piped input, CI,
5
+ * `echo ... | ucode` — falls back to plain.js, which is why both exist.
6
+ *
7
+ * The layout, top to bottom:
8
+ *
9
+ * ╭──────────────────────────────────────────────────╮
10
+ * │ UCODE wordmark dir / keys │
11
+ * ╰──────────────────────────────────────────────────╯
12
+ *
13
+ * the conversation, scrolling with the wheel or PgUp
14
+ *
15
+ * ╭──────────────────────────────────────────────────╮
16
+ * │ › what you are typing, growing downward as it │
17
+ * │ │
18
+ * │ ◆ Build · Nemotron 3 Ultra 4% │
19
+ * ╰──────────────────────────────────────────────────╯
20
+ *
21
+ * Both boxes are drawn rather than ruled off, because a box says "this is a
22
+ * thing you use" where a horizontal rule only says "something changes here".
23
+ *
24
+ * The status sits inside the input box rather than under it: it describes the
25
+ * thing you are typing into, so it belongs within the same border. It carries
26
+ * three facts and no more — which mode is live, which model is answering, and
27
+ * how full the window is. Anything else down there competes with what the user
28
+ * is actually looking at, which is what they just typed.
29
+ *
30
+ * The transcript is a buffer of pre-rendered lines and the whole frame is
31
+ * repainted whenever anything changes. At terminal sizes that is cheap, and
32
+ * it rules out every partial-update bug at once.
33
+ */
34
+
35
+ import { appendFile } from 'node:fs/promises';
36
+ import { homedir } from 'node:os';
37
+ import path from 'node:path';
38
+ import chalk from 'chalk';
39
+ import {
40
+ theme, blue, sky, deep, dim, edge, ADDED, REMOVED, BANNER, BANNER_WIDTH, SPINNER,
41
+ boxTop, boxBottom, boxRow, visLen, padVis, clip, wrapAnsi,
42
+ shortenPath, asLabel, ensureColour, planLine, bare, narration, narrationMark, groupKind, groupLabel, groupTarget, runLine, planRows, tidyReply, trimAnswer,
43
+ bannerPaint, RAIL, modeChip, asNarrationLine } from './theme.js';
44
+ import { FRAME_MS, spinnerGlyph, formatDuration, doneLine, workingLine, bannerSweep, SWEEP_MS } from './activity.js';
45
+ import { gitBranch } from '../core/git.js';
46
+ import { renderer, render, polish } from './markdown.js';
47
+ import { VERSION } from '../core/version.js';
48
+
49
+ /**
50
+ * One line of narration, in the model's own words: "Reading screen.js".
51
+ * Anything longer than this is prose, and prose belongs in the answer.
52
+ */
53
+ export const MAX_LABEL = 120;
54
+
55
+ export function isLabel(text) {
56
+ const t = String(text ?? '').trim();
57
+ return t.length > 0 && t.length <= MAX_LABEL && !t.includes('\n');
58
+ }
59
+
60
+ export const COMMANDS = [
61
+ '/help', '/model', '/models', '/session', '/sessions', '/resume',
62
+ '/new', '/remember', '/skills', '/clear', '/search', '/copy', '/exit',
63
+ '/stats', '/doctor', '/deploy', '/look', '/undo',
64
+ ];
65
+
66
+ // ANSI ----------------------------------------------------------------------
67
+ const ESC = '\x1b';
68
+ const ALT_ON = `${ESC}[?1049h`;
69
+ const ALT_OFF = `${ESC}[?1049l`;
70
+
71
+ /**
72
+ * Mouse setup, decided by measurement rather than by documentation.
73
+ *
74
+ * 1007 is alternate scroll: inside the alternate screen the terminal turns
75
+ * wheel events into arrow keys. On Windows that is the only way a wheel ever
76
+ * reaches the program, because ConPTY forwards no mouse input at all — a probe
77
+ * that enabled every tracking mode received nothing from a scroll.
78
+ *
79
+ * And mouse tracking suppresses alternate scroll. So on Windows tracking is
80
+ * deliberately not requested: it delivers nothing there, and asking for it
81
+ * would cost the wheel. Elsewhere tracking works, so the mode chip is
82
+ * clickable on those platforms.
83
+ */
84
+ const TRACK = process.platform === 'win32'
85
+ ? '' : `${ESC}[?1000h${ESC}[?1002h${ESC}[?1015h${ESC}[?1006h`;
86
+ const UNTRACK = process.platform === 'win32'
87
+ ? '' : `${ESC}[?1006l${ESC}[?1015l${ESC}[?1002l${ESC}[?1000l`;
88
+
89
+ const PASTE_ON = `${ESC}[?2004h`;
90
+ const PASTE_OFF = `${ESC}[?2004l`;
91
+ const MOUSE_ON = `${ESC}[?1007h${TRACK}`;
92
+ const MOUSE_OFF = `${UNTRACK}${ESC}[?1007l`;
93
+ const HIDE = `${ESC}[?25l`;
94
+ const SHOW = `${ESC}[?25h`;
95
+ const HOME = `${ESC}[H`;
96
+ const CLEAR_LINE = `${ESC}[K`;
97
+ /** Written out rather than inline, so no edit can turn it into a real break. */
98
+ const NEWLINE = String.fromCharCode(10);
99
+ const at = (row, col) => `${ESC}[${row};${col}H`;
100
+ const title = (t) => `${ESC}]0;${t}\x07`;
101
+
102
+ /**
103
+ * Fixed rows below the header: the gap under it, the gap above the input box,
104
+ * the input box's two borders, the blank row inside it, and the status row.
105
+ */
106
+ const CHROME_BELOW = 6;
107
+
108
+ /** How long one sentence of reasoning holds the line before the next takes it. */
109
+ const THOUGHT_HOLD_MS = 1100;
110
+
111
+ /** Reasoning that is about the request rather than about the work. */
112
+ const RESTATEMENT = /^(?:the user|they|so the user|user)|^(?:i (?:need|should|will need) to (?:understand|figure|work out|check what))|^(?:let me (?:understand|re-?read|look at the (?:request|prompt)))|^(?:the (?:request|prompt|task) (?:is|asks|says))/i;
113
+
114
+ /** The wordmark only earns its place with room for the facts column beside it. */
115
+ const WORDMARK_NEEDS = BANNER_WIDTH + 30;
116
+
117
+ /** What the empty input box says before anything is typed. */
118
+ const PLACEHOLDER = 'Ask anything…';
119
+
120
+ /**
121
+ * What it says instead while the agent has the turn.
122
+ *
123
+ * The status row beside it already says "esc to stop", so this carries the
124
+ * half nothing else on screen does: that the box is still live, and a line
125
+ * typed into it now is kept and sent when the turn ends rather than lost. The
126
+ * short form is for a terminal too narrow to hold the sentence, where a cut
127
+ * one would read as a glitch.
128
+ */
129
+ const WORKING_HINT = 'Working… type to queue your next message';
130
+ const WORKING_HINT_SHORT = 'Working…';
131
+ const WORKING_HINT_NEEDS = WORKING_HINT.length + 8;
132
+
133
+ /**
134
+ * Three things to try, under the box, on a screen with nothing on it yet.
135
+ *
136
+ * A wordmark over an empty field is handsome and tells you nothing you can act
137
+ * on — the first thing a new user has to do is guess what this accepts. Three
138
+ * greyed lines answer that in one glance, and they say something about the
139
+ * range of it too: build something new, understand something that exists,
140
+ * change something small. They are dim, and they are gone the moment anything
141
+ * is on the screen.
142
+ */
143
+ const SUGGESTIONS = [
144
+ 'build me a landing page for a coffee shop',
145
+ 'explain what this project does and how it fits together',
146
+ 'add a dark mode toggle that remembers the choice',
147
+ ];
148
+
149
+ /** The width of the `try` label, so the three lines share one left edge. */
150
+ const SUGGEST_LABEL = 6;
151
+
152
+ /** Rows the suggestions occupy under the box: one of air, then the three. */
153
+ const SUGGEST_ROWS = SUGGESTIONS.length + 1;
154
+
155
+ export class Screen {
156
+ constructor({ cwd, input = process.stdin, output = process.stdout } = {}) {
157
+ this.cwd = cwd;
158
+ this.input = input;
159
+ this.output = output;
160
+
161
+ this.lines = []; // the rendered transcript
162
+ this.scroll = 0; // rows scrolled up from the bottom
163
+ this.buffer = ''; // what is being typed
164
+ this.cursor = 0;
165
+ this.history = [];
166
+ this.historyIndex = -1;
167
+
168
+ this.status = { busy: false, text: '', frame: 0, since: 0 };
169
+ this.facts = {};
170
+ this.model = '';
171
+
172
+ this.waiters = [];
173
+ this.queue = [];
174
+ this.closed = false;
175
+
176
+ // 'build' may edit and run; 'plan' is read-only. Ctrl+B swaps them, and
177
+ // the chip is clickable wherever the terminal forwards clicks.
178
+ this.mode = 'build';
179
+ this.chipTo = 0;
180
+ this.onInterrupt = null;
181
+ this.onModeChange = null;
182
+ this.spinTimer = null;
183
+ this.paintedBusy = false; // whose turn the frame on screen was drawn for
184
+ this.activity = null; // the turn in flight: when it began, how many steps
185
+ this.tick = 0; // animation frames painted, for the spinner
186
+ this.intro = 0; // when the launch sweep began, 0 once it is over
187
+ this.introTimer = null;
188
+ this.pendingPrompt = null;
189
+ this.lastPrompt = ''; // the last thing the user said, for the echo check
190
+ this.facts.branch = gitBranch(cwd);
191
+
192
+ this.cols = output.columns || 80;
193
+ this.rows = output.rows || 24;
194
+ this.md = renderer(this.width());
195
+ }
196
+
197
+ // -- lifecycle -----------------------------------------------------------
198
+
199
+ async start() {
200
+ ensureColour(this.output);
201
+ this.output.write(ALT_ON + MOUSE_ON + PASTE_ON + HIDE + title(`ucode — ${path.basename(this.cwd)}`));
202
+ this.input.setRawMode?.(true);
203
+ this.input.resume();
204
+ this.input.setEncoding('utf8');
205
+ this.input.on('data', (chunk) => this.onData(chunk));
206
+
207
+ this.onResize = () => {
208
+ this.cols = this.output.columns || 80;
209
+ this.rows = this.output.rows || 24;
210
+ this.md = renderer(this.width());
211
+ this.render();
212
+ };
213
+ this.output.on('resize', this.onResize);
214
+
215
+ this.render();
216
+ this.startIntro();
217
+ }
218
+
219
+ /**
220
+ * The light that crosses the wordmark once, at launch.
221
+ *
222
+ * Half a second, on the start screen only, and abandoned the instant there is
223
+ * anything else to look at. Below 256 colours there are no shades to fade
224
+ * through, so it is skipped rather than flickered.
225
+ */
226
+ startIntro() {
227
+ if (!this.output.isTTY || chalk.level < 2 || !this.welcoming()) return;
228
+ this.intro = Date.now();
229
+ this.introTimer = setInterval(() => {
230
+ if (this.closed || !this.welcoming() || Date.now() - this.intro >= SWEEP_MS) this.stopIntro();
231
+ else this.render();
232
+ }, FRAME_MS);
233
+ this.introTimer.unref?.();
234
+ }
235
+
236
+ stopIntro() {
237
+ if (this.introTimer) clearInterval(this.introTimer);
238
+ this.introTimer = null;
239
+ if (!this.intro) return;
240
+ this.intro = 0;
241
+ if (!this.closed) this.render();
242
+ }
243
+
244
+ stop() {
245
+ this.activity = null;
246
+ if (this.introTimer) clearInterval(this.introTimer);
247
+ this.introTimer = null;
248
+ this.intro = 0;
249
+ this.stopSpinner();
250
+ this.stopTimer();
251
+ this.output.off?.('resize', this.onResize);
252
+ this.input.setRawMode?.(false);
253
+ this.input.pause();
254
+ this.output.write(PASTE_OFF + MOUSE_OFF + ALT_OFF + SHOW);
255
+ }
256
+
257
+ close() {
258
+ if (this.closed) return;
259
+ this.closed = true;
260
+ this.stop();
261
+ while (this.waiters.length) this.waiters.shift()(null);
262
+ }
263
+
264
+ /**
265
+ * Every column the terminal has.
266
+ *
267
+ * Capped at 100 for a release, and it was wrong: on a wide monitor the frame
268
+ * sat in the left half of the screen with the rest of it empty, which reads
269
+ * as the window having failed to open rather than as a measured column. The
270
+ * interface fills what it is given. Prose inside it is still held to 100 by
271
+ * the markdown renderer, which is where that limit belongs — the boxes are
272
+ * the shape of the window, not of a paragraph.
273
+ */
274
+ width() {
275
+ return Math.max(30, this.cols);
276
+ }
277
+
278
+ /** Usable width inside a box: two borders and a space of padding each side. */
279
+ inner() {
280
+ return Math.max(8, this.width() - 4);
281
+ }
282
+
283
+ // -- transcript ----------------------------------------------------------
284
+
285
+ /**
286
+ * Append without painting.
287
+ *
288
+ * Anything replacing a region of the transcript has to build the whole
289
+ * region and then render once. Painting between the delete and the re-add
290
+ * puts a frame on screen with the text missing, and at streaming speed that
291
+ * reads as flicker.
292
+ */
293
+ add(text = '') {
294
+ const width = this.width();
295
+ for (const raw of String(text).split('\n')) {
296
+ if (visLen(raw) <= width) this.lines.push(raw);
297
+ else for (const wrapped of wrapAnsi(raw, width)) this.lines.push(wrapped);
298
+ }
299
+ this.scroll = 0; // new output snaps back to the bottom
300
+ }
301
+
302
+ push(text = '') {
303
+ this.add(text);
304
+ this.soon();
305
+ }
306
+
307
+ /**
308
+ * Collapse a burst of pushes into one frame.
309
+ *
310
+ * Printing a list one line at a time repaints the screen per line — a model
311
+ * list of fifty entries drew a hundred frames back to back, which is visible
312
+ * as a cascade. A microtask runs before any I/O, so everything pushed in one
313
+ * synchronous stretch becomes a single render, while a push after an await
314
+ * still paints immediately.
315
+ */
316
+ soon() {
317
+ if (this.queued) return;
318
+ this.queued = true;
319
+ queueMicrotask(() => {
320
+ this.queued = false;
321
+ this.render();
322
+ });
323
+ }
324
+
325
+ write(text = '') { this.push(text); }
326
+ blank() { this.push(''); }
327
+ note(text) { this.push(dim(` ${text}`)); }
328
+
329
+ clearScreen() {
330
+ this.lines = [];
331
+ this.scroll = 0;
332
+ this.render();
333
+ }
334
+
335
+ /**
336
+ * The reply, at full strength, with room either side.
337
+ *
338
+ * `closing` says this is the last thing the turn will say. It is then also
339
+ * the last thing left on screen, and what the whole session reads like
340
+ * afterwards, so it is cut to eight lines — see trimAnswer.
341
+ */
342
+ assistant(text, { closing = false } = {}) {
343
+ if (!text?.trim()) return;
344
+ const tidy = tidyReply(text, 4, this.lastPrompt);
345
+ const body = closing ? trimAnswer(tidy) : tidy;
346
+ if (!body.trim()) return;
347
+ this.endRun();
348
+ this.add('');
349
+
350
+ // No bullet, and no indent. A mark on every reply made the answer read as
351
+ // one more step in the list above it, and on "Hey! How can I help you
352
+ // today?" it was a bullet on a greeting. The answer already wins the page
353
+ // by being the only thing on it at full strength; it does not also need to
354
+ // be labelled.
355
+ this.add(render(this.md, body));
356
+
357
+ this.add('');
358
+ this.render();
359
+ }
360
+
361
+ /**
362
+ * Something the user said, marked down its left edge in the same blue as the
363
+ * box it was typed into.
364
+ *
365
+ * A long session is mostly the agent's output — tool calls, diffs, answers.
366
+ * Your own messages are the landmarks you scroll back looking for, so they
367
+ * get a mark of their own. It was a full box, and forty turns of that is a
368
+ * ladder of rules across the page: two horizontal lines per message, each as
369
+ * loud as the input box, none of them saying anything the rail does not.
370
+ */
371
+ userMessage(text) {
372
+ // Kept so the reply can be checked against it: an answer that opens by
373
+ // saying the request back is repeating the line directly above it.
374
+ this.lastPrompt = String(text ?? '');
375
+ const room = Math.max(8, this.width() - 2); // the rail and the space after it
376
+
377
+ const rows = [];
378
+ for (const paragraph of String(text).replace(/\r/g, '').split('\n')) {
379
+ for (const line of wrapAnsi(paragraph, room)) rows.push(line);
380
+ }
381
+
382
+ // Room between what you asked for and what came back: without it the reply
383
+ // starts against your own message and the two read as one block of text.
384
+ this.add('');
385
+ for (const row of rows) this.add(`${blue(RAIL)} ${chalk.white(row)}`);
386
+ this.add('');
387
+ this.add('');
388
+ this.render();
389
+ }
390
+
391
+ /**
392
+ * A tool call, as it happens: "● Listing src".
393
+ *
394
+ * This lives in the transcript rather than only on the status line. The
395
+ * status line overwrites itself and is empty by the end of the turn, so work
396
+ * announced only there scrolls past unseen — and the diff underneath ends up
397
+ * with nothing above it explaining where it came from.
398
+ */
399
+ toolCall(label) {
400
+ // U+25CF, not U+23FA: the latter carries emoji presentation, which Windows
401
+ // Terminal draws as a white circle on a blue tile.
402
+ // Trimmed here rather than at paint time: runLine hands back a coloured
403
+ // string, and asLabel's regexes run off the end of one of those into the
404
+ // escape sequence instead of the last word.
405
+ const clean = asLabel(label);
406
+ const kind = groupKind(clean);
407
+ // One line per kind of work for as long as the model is working on one
408
+ // thing. Reading, writing and reading again used to draw six lines that
409
+ // said three things; now the "Reading files" line it already has is the
410
+ // one that counts up, wherever it sits.
411
+ const run = (this.segment ??= new Map()).get(kind);
412
+
413
+ if (run && this.lines[run.at] !== undefined) {
414
+ run.count++;
415
+ run.label = clean;
416
+ run.targets.push(groupTarget(clean));
417
+ this.run = run;
418
+ this.paintRun();
419
+ } else {
420
+ const fresh = {
421
+ kind, count: 1, at: 0, label: clean,
422
+ targets: [groupTarget(clean)], added: 0, removed: 0,
423
+ };
424
+ this.push(`${narrationMark(kind)} ${runLine(fresh)}`);
425
+ fresh.at = this.lines.length - 1;
426
+ this.run = fresh;
427
+ this.segment.set(kind, fresh);
428
+ }
429
+ this.updateSpinner(label);
430
+ }
431
+
432
+ /**
433
+ * The model speaking — or a plan, or a failure — ends the segment.
434
+ *
435
+ * Up to that point a kind of work keeps one line and counts up on it. After
436
+ * it, the next read is a new piece of work and deserves its own line, which
437
+ * is what makes the transcript read as a sequence of things done rather
438
+ * than a set of running totals.
439
+ */
440
+ /**
441
+ * Stop adding to the current run, but keep the lines already on screen.
442
+ *
443
+ * A kind of work gets one line for the whole turn. Starting a fresh set
444
+ * whenever the model spoke meant "Creating Tide from the HTML starter" five
445
+ * times down the page and "Reading files" four, each saying the same thing
446
+ * about a different moment. One line that counts up says all of it and
447
+ * costs one row.
448
+ */
449
+ endRun() { this.run = null; }
450
+
451
+ /** A new turn starts with a clean page's worth of lines. */
452
+ newSegment() { this.run = null; this.segment = new Map(); }
453
+
454
+ /** Redraw the run's single line from what it has accumulated. */
455
+ /**
456
+ * Redraw the run's single line from what it has accumulated.
457
+ *
458
+ * While its step is still running the text shimmers, which is the only
459
+ * thing on screen saying "this is happening now" once the per-step result
460
+ * lines are gone. It settles to plain dim the moment the step finishes, so
461
+ * the finished ones above stay quiet.
462
+ */
463
+ paintRun() {
464
+ if (!this.run) return;
465
+ this.lines[this.run.at] = `${narrationMark(this.run.kind)} ${runLine(this.run)}`;
466
+ this.render();
467
+ }
468
+
469
+ /**
470
+ * A change, as its two numbers.
471
+ *
472
+ * The diff itself used to go into the transcript. A 539-line file printed
473
+ * there buries the answer under a copy of something already on disk, so
474
+ * what is kept is the shape of the change: how much arrived, how much left.
475
+ */
476
+ /**
477
+ * A one-word verdict on the step that just ran — "clean", "3 to fix".
478
+ *
479
+ * Same rule as diffStat: it goes on the line that named the step. Nothing
480
+ * goes underneath a bullet, and a result line per tool doubles the height of
481
+ * the transcript to say "ok".
482
+ */
483
+ runStat(text) {
484
+ if (!this.run || !text) return;
485
+ this.run.stat = text;
486
+ this.paintRun();
487
+ }
488
+
489
+ diffStat({ added = 0, removed = 0 } = {}) {
490
+ if (!this.run) return;
491
+ this.run.added += added;
492
+ this.run.removed += removed;
493
+ this.paintRun();
494
+ }
495
+
496
+ /** The checklist, when the model updates it. One line, wrapped if it must. */
497
+ plan(items) {
498
+ const rows = planRows(items);
499
+ if (!rows.length) return;
500
+ this.endRun(); // a plan is not another step of whatever came before
501
+ for (const row of rows) this.push(row);
502
+ }
503
+
504
+ /**
505
+ * What came of a step.
506
+ *
507
+ * Nothing goes underneath the bullet any more: a line of its own for every
508
+ * result doubles the height of the transcript to say "ok". The bullet
509
+ * already names the step, and a change adds its numbers to that same line.
510
+ * Only a failure earns a line of its own.
511
+ */
512
+ toolResult() {}
513
+
514
+ /**
515
+ * Something went wrong, and the model is the one who can do anything about it.
516
+ *
517
+ * A red line of machinery — a failed edit, a command that exited non-zero —
518
+ * reads as the tool being broken, when almost always it is a step the model
519
+ * corrects on its own a second later. It goes to the model; the screen stays
520
+ * for what is being built. Whatever is genuinely unrecoverable surfaces as
521
+ * the model saying so in words, which is the form worth reading.
522
+ */
523
+ toolFailed() {
524
+ this.endRun();
525
+ }
526
+
527
+ /**
528
+ * The change itself, under the result.
529
+ *
530
+ * A line-number gutter, then the sign and the code tinted right across the
531
+ * row. The numbers are the point: a diff you cannot navigate from is a
532
+ * picture of a change rather than a record of one.
533
+ */
534
+ diff(lines) {
535
+ const gutter = 6;
536
+ // Two spaces of indent, the gutter, one space, then the tint fills the
537
+ // rest. One column over and every row wraps, splitting the whole diff.
538
+ const room = Math.max(12, this.width() - gutter - 3);
539
+
540
+ for (const line of lines) {
541
+ // A file heading in a multi-file write.
542
+ if (line.startsWith('~')) {
543
+ this.add(` ${dim(' '.repeat(gutter))} ${sky(line.slice(1))}`);
544
+ continue;
545
+ }
546
+
547
+ const added = line.startsWith('+');
548
+ const rest = line.slice(1);
549
+ // Tools emit "<line>| <text>". A row with no number is the "12 more
550
+ // lines" note, which is not part of the change, so it stays dim.
551
+ const parsed = /^(\d+)\|\s?([\s\S]*)$/.exec(rest);
552
+ if (!parsed) {
553
+ this.add(` ${dim(' '.repeat(gutter))} ${dim(rest)}`);
554
+ continue;
555
+ }
556
+
557
+ const [, number, body] = parsed;
558
+ const tint = added ? ADDED : REMOVED;
559
+ this.add(
560
+ ` ${dim(number.padStart(gutter))} ` +
561
+ // Tabs would leave the tint ending short of the row, so they widen.
562
+ tint(padVis(clip(`${added ? '+' : '-'} ${body.replace(/\t/g, ' ')}`, room), room))
563
+ );
564
+ }
565
+ this.render(); // a sixteen-line diff is one frame, not sixteen
566
+ }
567
+
568
+ /** Captured output under a command, dimmed so it reads as evidence. */
569
+ commandOutput(lines) {
570
+ for (const line of lines) this.add(` ${dim(line)}`);
571
+ this.render();
572
+ }
573
+
574
+ /**
575
+ * A running command's output, live — on the status line and nowhere else.
576
+ *
577
+ * Only the newest line, gone as soon as the next arrives. Appending each one
578
+ * instead would mean a test run leaving sixty lines of "ok" in the
579
+ * conversation permanently, which is noise the moment it scrolls. What
580
+ * survives a command is decided when it ends: nothing if it worked, the tail
581
+ * if it did not.
582
+ */
583
+ progress(lines) {
584
+ const last = lines[lines.length - 1]?.trim();
585
+ if (last) this.updateSpinner(last);
586
+ }
587
+
588
+ /**
589
+ * The model's own account of the step it is taking, before it takes it.
590
+ *
591
+ * Not called status(): `this.status` holds the spinner state, and a method
592
+ * of the same name would be shadowed by it on every instance.
593
+ */
594
+ narrate(text) {
595
+ const line = asLabel(text);
596
+ if (!line) return;
597
+ this.push(`${dim('⋮')} ${dim(clip(line, this.width() - 4))}`);
598
+ this.updateSpinner(line);
599
+ }
600
+
601
+ // -- streaming -----------------------------------------------------------
602
+ // Deltas appear as plain text as they arrive, then get replaced in place by
603
+ // properly rendered markdown once the reply is complete.
604
+
605
+ streamBegin() {
606
+ this.stopSpinner();
607
+ this.streamAt = this.lines.length;
608
+ this.streamBuf = '';
609
+ this.streamPainted = 0;
610
+ }
611
+
612
+ streamDelta(delta) {
613
+ if (this.streamAt === undefined) this.streamBegin();
614
+ this.streamBuf += delta;
615
+ const now = Date.now();
616
+ if (now - this.streamPainted < 60) return; // about 16fps is plenty
617
+ this.streamPainted = now;
618
+ this.repaintStream();
619
+ }
620
+
621
+ /**
622
+ * Repaint the partial reply.
623
+ *
624
+ * polish() runs on the partial text so bold, inline code and bullets are
625
+ * already styled while it streams. Without it the text arrives raw and then
626
+ * visibly re-renders at the end, which reads as a glitch.
627
+ */
628
+ repaintStream() {
629
+ this.lines.length = this.streamAt;
630
+ this.add('');
631
+ this.add(polish(this.streamBuf));
632
+ this.render(); // one frame, and never one without the reply in it
633
+ }
634
+
635
+ /**
636
+ * Finish a streamed reply.
637
+ *
638
+ * `asLabel` says the text turned out to be narration ahead of a tool call
639
+ * rather than an answer, in which case one short line folds down into the
640
+ * status line it was always meant to be.
641
+ */
642
+ streamEnd({ asNarration = false, closing = false } = {}) {
643
+ if (this.streamAt === undefined) return '';
644
+ const text = this.streamBuf;
645
+ this.lines.length = this.streamAt;
646
+ this.streamAt = undefined;
647
+ this.streamBuf = '';
648
+
649
+ // Mid-build the model's prose is commentary on work that has not happened
650
+ // yet, so it is condensed to one line rather than printed whole — long or
651
+ // short, it never becomes a block of text above the file being written.
652
+ if (asNarration) {
653
+ const line = asNarrationLine(text);
654
+ if (line) this.narrate(line);
655
+ else this.render();
656
+ }
657
+ else if (text.trim()) this.assistant(text, { closing });
658
+ else this.render();
659
+ return text;
660
+ }
661
+
662
+ // -- thinking ------------------------------------------------------------
663
+ // A reasoning model does all its working before it says anything. None of it
664
+ // is printed: it is long, repetitive, and guesses drawn from it read worse
665
+ // than silence. The spinner counts the seconds so the wait is visibly alive,
666
+ // and the transcript gets one line afterwards saying how long it took.
667
+
668
+ /**
669
+ * The model's reasoning does not go on screen.
670
+ *
671
+ * It was surfaced here to fill the wait before the first tool call, and what
672
+ * it actually filled it with was the model talking to itself: "I need to
673
+ * build this", "The user wants a tasks app". Nobody needs their own request
674
+ * read back to them, and half-formed working-out is not something to publish.
675
+ * What the model *says* is its reply, and that is the only thing shown.
676
+ */
677
+ thinkingDelta() {}
678
+
679
+ thinkingEnd() {}
680
+
681
+ error(err, { debug = false } = {}) {
682
+ const known = err && typeof err === 'object' && err.attempted;
683
+ this.push('');
684
+ if (known) {
685
+ this.push(`${theme.error('✗')} ${chalk.white(`Failed while ${err.attempted}.`)}`);
686
+ this.push(` ${err.failed}`);
687
+ if (err.fix) this.push(` ${blue('→')} ${err.fix}`);
688
+ if (err.kind) this.push(dim(` (${err.kind})`));
689
+ } else {
690
+ this.push(`${theme.error('✗')} ${chalk.white('Something broke inside ucode.')}`);
691
+ this.push(` ${err?.message ?? String(err)}`);
692
+ this.push(` ${blue('→')} That is a bug in ucode rather than in your project. Re-run with --debug.`);
693
+ }
694
+ if (debug) {
695
+ const stack = (known && err.cause?.stack) || err?.stack;
696
+ if (stack) this.push(dim(stack));
697
+ }
698
+ this.push('');
699
+ }
700
+
701
+ // -- header --------------------------------------------------------------
702
+
703
+ setFacts(facts) {
704
+ this.facts = { ...this.facts, ...facts };
705
+ if (facts.model) this.model = facts.model;
706
+ this.render();
707
+ }
708
+
709
+ /** Same shape as the plain UI's header(), so the loop needs no branch. */
710
+ header({ cwd, model, used, limit, title: sessionTitle }) {
711
+ if (cwd && cwd !== this.facts.cwd) this.facts.branch = gitBranch(cwd);
712
+ this.setFacts({
713
+ cwd,
714
+ model,
715
+ title: sessionTitle,
716
+ percent: limit > 0 ? Math.min(100, Math.round((used / limit) * 100)) : 0,
717
+ });
718
+ }
719
+
720
+ /**
721
+ * How many rows the header box occupies.
722
+ *
723
+ * The frame has to be exactly as tall as the terminal or every row below the
724
+ * shortfall is off by that much — including the one the caret is parked on.
725
+ * So this is derived, never assumed.
726
+ */
727
+ headerHeight() {
728
+ return this.width() >= WORDMARK_NEEDS ? BANNER.length + 2 : 5;
729
+ }
730
+
731
+ headerLines() {
732
+ const width = this.width();
733
+ const inner = width - 2; // between the borders
734
+
735
+ if (width < WORDMARK_NEEDS) {
736
+ // Too narrow for the wordmark: stack it rather than wrap it into noise.
737
+ const rows = [
738
+ ` ${blue.bold('U C O D E')} ${dim('terminal coding agent')}`,
739
+ ` ${dim('dir'.padEnd(8))}${chalk.white(clip(shortenPath(this.facts.cwd ?? this.cwd, inner - 12), inner - 12))}`,
740
+ ];
741
+ return [boxTop(width), ...rows.map((r) => boxRow(r, width)), boxBottom(width)];
742
+ }
743
+
744
+ // Two spaces of padding, the wordmark, a gap, then the facts column.
745
+ //
746
+ // Only what you cannot work out by looking, and never what the status row
747
+ // already carries: the model and how full the window is live down there,
748
+ // next to each other, and a second copy up here would be a second place to
749
+ // keep in sync for no reader who needed it. What is left is where you are,
750
+ // which branch that is on, which build you are running, and the two keys
751
+ // worth knowing before you have typed anything.
752
+ //
753
+ // Every row has something on it. Three blank rows and a credit floating
754
+ // under them read as a column that was meant to be filled and was not.
755
+ const room = Math.max(8, inner - BANNER_WIDTH - 6);
756
+ const value = (v) => clip(String(v), Math.max(4, room - 10));
757
+ const branch = this.facts.branch;
758
+
759
+ // The facts run together from the top with nothing between them, the credit
760
+ // sits on the last row, and whatever is left over is the gap between the
761
+ // two. Holding a row empty in the middle of the list — which is what a
762
+ // fixed six-row layout did when a fact was missing — reads as a line that
763
+ // failed to draw rather than as spacing.
764
+ const facts = [
765
+ ['dir', value(shortenPath(this.facts.cwd ?? this.cwd, room - 10))],
766
+ branch && ['branch', value(branch)],
767
+ VERSION && ['version', value(this.facts.update ? `${VERSION} → ${this.facts.update} next start` : VERSION)],
768
+ ['keys', value('/help · esc interrupts · ctrl+b plan')],
769
+ ].filter(Boolean).slice(0, BANNER.length - 1);
770
+
771
+ while (facts.length < BANNER.length - 1) facts.push(['', '']);
772
+ facts.push(['', 'made with ❤️ by om dixit']);
773
+
774
+ const rows = BANNER.map((art, i) => {
775
+ const [label, text] = facts[i] ?? ['', ''];
776
+ const right = label
777
+ ? `${dim(label.padEnd(10))}${chalk.white(text)}`
778
+ : (text ? dim(text) : '');
779
+ return ` ${bannerPaint(i)(art)} ${right}`;
780
+ });
781
+
782
+ // The frame is lit the way the wordmark inside it is: brightest along the
783
+ // top rule, settling to deep at the bottom. Eight rows of box for six of
784
+ // banner, so the borders take the two ends of the same ramp and the box
785
+ // reads as one object with a light above it rather than as a rule someone
786
+ // drew around a picture.
787
+ const depth = BANNER.length + 2;
788
+ return [
789
+ boxTop(width, bannerPaint(0, depth)),
790
+ ...rows.map((r, i) => boxRow(r, width, bannerPaint(i + 1, depth))),
791
+ boxBottom(width, bannerPaint(depth - 1, depth)),
792
+ ];
793
+ }
794
+
795
+ // -- input box -----------------------------------------------------------
796
+
797
+ /** The typed line, wrapped to the inside of a box `width` characters across. */
798
+ /**
799
+ * The typed text, laid out as rows inside the box.
800
+ *
801
+ * A line break in the buffer is a row of its own before any wrapping is
802
+ * considered. Slicing the text into fixed widths without looking for one
803
+ * put the newline into the frame instead, and the terminal obeyed it — the
804
+ * pasted text walked out of the box and over the transcript beside it.
805
+ *
806
+ * `starts` records where each row begins in the text, so the caret can be
807
+ * placed by looking up rather than by counting characters a second way and
808
+ * hoping the two agree.
809
+ */
810
+ inputLines(width = this.inner()) {
811
+ const prefix = this.pendingPrompt ? `${this.pendingPrompt} ` : '› ';
812
+ const full = prefix + this.buffer;
813
+
814
+ const rows = [];
815
+ const starts = [];
816
+ let at = 0;
817
+
818
+ for (const para of full.split(NEWLINE)) {
819
+ let i = 0;
820
+ do {
821
+ rows.push(para.slice(i, i + width));
822
+ starts.push(at + i);
823
+ i += width;
824
+ } while (i < para.length);
825
+ at += para.length + 1; // the newline itself
826
+ }
827
+
828
+ if (rows.length === 0) { rows.push(prefix); starts.push(0); }
829
+ return { rows, prefix, width, starts };
830
+ }
831
+
832
+ /** Which row the caret sits on, and how far along it. */
833
+ caretAt(width) {
834
+ const { rows, prefix, starts } = this.inputLines(width);
835
+ const index = prefix.length + this.cursor;
836
+ let row = 0;
837
+ while (row + 1 < starts.length && starts[row + 1] <= index) row++;
838
+ return { row, col: Math.min(index - starts[row], rows[row].length), rows };
839
+ }
840
+
841
+ viewportHeight() {
842
+ return Math.max(
843
+ 3,
844
+ this.rows - this.headerHeight() - CHROME_BELOW - this.inputLines().rows.length
845
+ );
846
+ }
847
+
848
+ /**
849
+ * The input box: what you are typing, and directly under it, inside the same
850
+ * border, the three things worth knowing while you type.
851
+ *
852
+ * The status used to sit outside the box on the last row of the screen,
853
+ * which made it a separate object floating under the input. Inside the
854
+ * border it reads as part of the thing you are using — the box says "this is
855
+ * where you work", and the row underneath says what you are working with.
856
+ */
857
+ inputBox(width = this.width()) {
858
+ const { rows } = this.inputLines(width - 4);
859
+ const border = this.borderPaint();
860
+ const busy = this.busy();
861
+ // Nothing typed yet: a quiet prompt where the text will go. The caret sits
862
+ // on its first letter and typing replaces it.
863
+ const empty = !this.buffer && !this.pendingPrompt;
864
+ const hint = !busy ? PLACEHOLDER
865
+ : (width >= WORKING_HINT_NEEDS ? WORKING_HINT : WORKING_HINT_SHORT);
866
+ const painted = rows.map((row, i) =>
867
+ i === 0
868
+ ? boxRow(` ${border('›')}${empty ? ` ${dim(hint)}` : row.slice(1)}`, width, border)
869
+ : boxRow(` ${row}`, width, border)
870
+ );
871
+ return [
872
+ boxTop(width, border),
873
+ ...painted,
874
+ // A blank row between the two. Sitting directly under the caret, the
875
+ // status read as a second line of the thing being typed; one row of air
876
+ // separates what you are writing from what you are writing it with.
877
+ boxRow('', width, border),
878
+ boxRow(this.statusRow(width), width, border),
879
+ boxBottom(width, border),
880
+ ];
881
+ }
882
+
883
+ /** Is the agent holding the turn? */
884
+ busy() {
885
+ return this.status.busy || !!this.activity;
886
+ }
887
+
888
+ /**
889
+ * The input box's edge, which says whose turn it is.
890
+ *
891
+ * Bold blue while the box is yours, quiet while the agent has it. The status
892
+ * row inside the same box already carries the words; this is the half you
893
+ * catch without reading, from the corner of your eye, in the one place on
894
+ * screen you were already looking.
895
+ */
896
+ borderPaint() {
897
+ return this.busy() ? deep : edge;
898
+ }
899
+
900
+ /**
901
+ * Repaint after something that may have changed whose turn it is.
902
+ *
903
+ * The cheap path redraws one row, which is right twelve times a second for a
904
+ * spinner and wrong at a turn boundary: the border above and below would
905
+ * still be the old weight while the status row had the new one, and the box
906
+ * would be drawn in two colours. A whole frame costs nothing twice a turn.
907
+ */
908
+ paintBusy() {
909
+ if (this.busy() === this.paintedBusy) this.paintStatus();
910
+ else this.render();
911
+ }
912
+
913
+ // -- status row ----------------------------------------------------------
914
+
915
+ modeChip() {
916
+ return modeChip(this.mode);
917
+ }
918
+
919
+ /**
920
+ * How full the context window is, as a bare number.
921
+ *
922
+ * It turns amber at 75% because that is where turns start being folded away
923
+ * into a summary — the one moment the number predicts something you would
924
+ * want to know before it happens.
925
+ */
926
+ percentChip() {
927
+ const percent = Math.round(this.facts.percent ?? 0);
928
+ return percent >= 75 ? theme.warn(`${percent}%`) : dim(`${percent}%`);
929
+ }
930
+
931
+ /**
932
+ * Which mode is live, which model is answering, and how full the window is.
933
+ *
934
+ * Nothing else earns a place. The provider name was there and was cut: it is
935
+ * the same on every line of every session, so it was decoration that had to
936
+ * be read past to reach the two things that do change.
937
+ *
938
+ * The spinner used to borrow the middle of this row while something ran. It
939
+ * has a row of its own outside the box now, so the only thing that ever
940
+ * appears between the model and the percentage is a flash — a reply to
941
+ * something you just pressed, gone a moment later.
942
+ */
943
+ statusRow(width = this.width()) {
944
+ const inner = width - 2; // the space between the two borders
945
+ const chip = this.modeChip();
946
+ const left = ` ${chip} ${chalk.white(this.model || '—')}`;
947
+
948
+ // How long the turn has taken, back in the box beside the other two facts
949
+ // about the session. It is not on the live line: that line says what is
950
+ // being done, and a clock ticking in the middle of it competes with the
951
+ // words for no reason. Under a second there is no number worth reading.
952
+ const now = Date.now();
953
+ const since = this.activity?.start ?? this.status.since ?? 0;
954
+ const running = this.busy() && since && now - since >= 1000;
955
+ const right = `${running ? `${dim(formatDuration(now - since))} ` : ''}${this.percentChip()} `;
956
+
957
+ // Where a click on the bottom row still counts as hitting the mode chip.
958
+ this.chipTo = 2 + visLen(chip);
959
+
960
+ const between = Math.max(1, inner - visLen(left) - visLen(right));
961
+ const middle = this.flashText ? dim(clip(this.flashText, between - 2)) : '';
962
+
963
+ const tail = middle ? `${middle} ` : '';
964
+ const pad = Math.max(1, inner - visLen(left) - visLen(tail) - visLen(right));
965
+ return padVis(left + ' '.repeat(pad) + tail + right, inner);
966
+ }
967
+
968
+ /**
969
+ * What is happening right now: the spinner, what it is doing, how long it has
970
+ * been doing it, and the way out.
971
+ *
972
+ * It used to live in whatever space the status row had spare between the
973
+ * model name and the percentage — inside the box you type into, which is the
974
+ * one place on screen that is about you rather than about the agent. Out
975
+ * here it sits directly under the steps it belongs to, in the same column,
976
+ * and has room for a bar instead of a shimmer.
977
+ */
978
+ activityLine(width = this.width()) {
979
+ if (!this.busy()) return '';
980
+ const now = Date.now();
981
+ return workingLine({
982
+ glyph: spinnerGlyph(this.tick, now),
983
+ label: this.status.busy ? this.status.text : 'working',
984
+ hint: 'esc to stop',
985
+ room: Math.max(4, width),
986
+ t: now,
987
+ });
988
+ }
989
+
990
+ /**
991
+ * Which row the live line is painted on, 1-based, or 0 when it is not shown.
992
+ *
993
+ * It is the last line of the conversation, so its row moves as the
994
+ * conversation grows and stops moving once the viewport is full. Scrolled
995
+ * back, or with the picker open, it is not on screen at all and the cheap
996
+ * repaint has nothing to do.
997
+ */
998
+ activityRowAt() {
999
+ if (this.scroll > 0 || this.picker) return 0;
1000
+ const index = Math.min(this.lines.length + 1, this.viewportHeight()) - 1;
1001
+ return index < 0 ? 0 : this.headerHeight() + 2 + index;
1002
+ }
1003
+
1004
+ /**
1005
+ * Repaint only the moving rows, leaving the caret where the user left it.
1006
+ *
1007
+ * It is the second row from the bottom now — the box's own border is below
1008
+ * it — so the row is written with its borders rather than as a bare line.
1009
+ */
1010
+ paintStatus() {
1011
+ if (this.closed) return;
1012
+ // On the start screen the status row is mid-screen, not second from the
1013
+ // bottom, so the cheap single-row repaint would draw it in the wrong place.
1014
+ if (this.welcoming()) {
1015
+ this.render();
1016
+ return;
1017
+ }
1018
+ const [row, col] = this.caret();
1019
+ const width = this.width();
1020
+ const liveAt = this.activityRowAt();
1021
+ this.output.write(
1022
+ HIDE +
1023
+ (liveAt ? at(liveAt, 1) + CLEAR_LINE + padVis(this.activityLine(width), width) : '') +
1024
+ at(this.rows - 1, 1) + CLEAR_LINE + boxRow(this.statusRow(width), width, this.borderPaint()) +
1025
+ at(row, col) + SHOW
1026
+ );
1027
+ }
1028
+
1029
+ toggleMode() {
1030
+ this.mode = this.mode === 'plan' ? 'build' : 'plan';
1031
+ this.flash(this.mode === 'plan'
1032
+ ? 'plan mode — reads and researches, changes nothing'
1033
+ : 'build mode — free to edit files and run commands');
1034
+ this.onModeChange?.(this.mode);
1035
+ this.render();
1036
+ }
1037
+
1038
+ /** A message on the status line that fades on its own. */
1039
+ flash(text) {
1040
+ this.flashText = text;
1041
+ clearTimeout(this.flashTimer);
1042
+ this.flashTimer = setTimeout(() => {
1043
+ this.flashText = null;
1044
+ this.paintStatus();
1045
+ }, 2500);
1046
+ this.flashTimer.unref?.();
1047
+ this.paintStatus();
1048
+ }
1049
+
1050
+ // -- spinner -------------------------------------------------------------
1051
+
1052
+ startSpinner(text = 'thinking') {
1053
+ // `since` is what makes a long think legible: the label may not change for
1054
+ // a minute, so the seconds beside it are the proof it is still alive.
1055
+ this.status = { busy: true, text: asLabel(text), frame: 0, since: Date.now() };
1056
+ this.startTimer();
1057
+ this.paintBusy();
1058
+ }
1059
+
1060
+ updateSpinner(text) {
1061
+ if (!this.status.busy) return;
1062
+ this.status.text = asLabel(text);
1063
+ this.paintStatus();
1064
+ }
1065
+
1066
+ stopSpinner() {
1067
+ if (!this.activity) this.stopTimer();
1068
+ if (this.status.busy) {
1069
+ this.status = { busy: false, text: '', frame: 0, since: 0 };
1070
+ this.paintBusy();
1071
+ }
1072
+ }
1073
+
1074
+ // -- the turn in flight ----------------------------------------------------
1075
+
1076
+ /** A turn begins: the timer and step count run until turnEnd(). */
1077
+ turnStart() {
1078
+ this.newSegment();
1079
+ this.activity = { start: Date.now(), steps: 0, movedAt: 0 };
1080
+ this.startTimer();
1081
+ this.paintBusy();
1082
+ }
1083
+
1084
+ /** One more model step in this turn. */
1085
+ step() {
1086
+ if (!this.activity) return;
1087
+ this.activity.steps++;
1088
+ this.activity.movedAt = Date.now();
1089
+ }
1090
+
1091
+ /** The turn is over: leave "✓ Done in 6m 12s · 25 steps" under the answer. */
1092
+ turnEnd({ ok = true } = {}) {
1093
+ const a = this.activity;
1094
+ this.activity = null;
1095
+ if (!this.status.busy) this.stopTimer();
1096
+ // Nothing is written when a turn finishes. The reply is the end of the
1097
+ // turn, and a timing line under it is bookkeeping the reader did not ask
1098
+ // for. A turn that stopped *without* finishing still says so, because
1099
+ // silence there is indistinguishable from a crash.
1100
+ if (a && !ok && Date.now() - a.start >= 2000) {
1101
+ this.push(` ${doneLine(Date.now() - a.start, a.steps, { ok })}`);
1102
+ }
1103
+ this.paintBusy();
1104
+ }
1105
+
1106
+ /** The animation clock: only the status row repaints, about twelve times a second. */
1107
+ startTimer() {
1108
+ if (this.spinTimer) return;
1109
+ this.spinTimer = setInterval(() => {
1110
+ // Only the status row repaints on a tick. Animating a transcript line
1111
+ // meant redrawing the whole frame twelve times a second, and the input
1112
+ // box was being rebuilt under the user's cursor as they typed.
1113
+ this.tick++;
1114
+ this.paintStatus();
1115
+ }, FRAME_MS);
1116
+ this.spinTimer.unref?.();
1117
+ }
1118
+
1119
+ stopTimer() {
1120
+ if (!this.spinTimer) return;
1121
+ clearInterval(this.spinTimer);
1122
+ this.spinTimer = null;
1123
+ }
1124
+
1125
+ // -- input ---------------------------------------------------------------
1126
+
1127
+ nextLine() {
1128
+ if (this.queue.length) return Promise.resolve(this.queue.shift());
1129
+ if (this.closed) return Promise.resolve(null);
1130
+ return new Promise((resolve) => this.waiters.push(resolve));
1131
+ }
1132
+
1133
+ ask() {
1134
+ return this.nextLine();
1135
+ }
1136
+
1137
+ submit(text) {
1138
+ const waiter = this.waiters.shift();
1139
+ if (waiter) waiter(text);
1140
+ else this.queue.push(text);
1141
+ }
1142
+
1143
+ /** y/n, answered on the input line. */
1144
+ confirm({ action, detail, risk }) {
1145
+ this.push('');
1146
+ this.push(`${chalk.inverse(theme.warn(risk === 'command' ? ' shell ' : ' outside project '))} ${chalk.white(action)}`);
1147
+ for (const line of String(detail ?? '').split('\n')) {
1148
+ if (line) this.push(dim(` ${line}`));
1149
+ }
1150
+
1151
+ this.pendingPrompt = 'go ahead? [y/N]';
1152
+ this.render();
1153
+
1154
+ return this.nextLine().then((answer) => {
1155
+ this.pendingPrompt = null;
1156
+ // End of input counts as no. Never run something nobody approved.
1157
+ const yes = /^(y|yes)$/i.test(String(answer ?? '').trim());
1158
+ this.push(dim(yes ? ' approved' : ' declined'));
1159
+ this.push('');
1160
+ return yes;
1161
+ });
1162
+ }
1163
+
1164
+ /**
1165
+ * A modal list: arrows move, Enter picks, Esc cancels.
1166
+ *
1167
+ * Only while this is open do the arrows stop scrolling the transcript. They
1168
+ * cannot be given up permanently, because under alternate scroll the mouse
1169
+ * wheel arrives as arrow keys.
1170
+ */
1171
+ pick(items, { active = 0, hint = 'enter to choose · esc to cancel', deletable = false } = {}) {
1172
+ this.picker = {
1173
+ items,
1174
+ index: Math.min(Math.max(0, active), Math.max(0, items.length - 1)),
1175
+ hint,
1176
+ // With deletable, `d` twice on a row resolves { delete: index }. Twice,
1177
+ // because a single stray keypress should never cost a conversation.
1178
+ deletable,
1179
+ armed: null,
1180
+ };
1181
+ this.render();
1182
+ return new Promise((resolve) => { this.pickerResolve = resolve; });
1183
+ }
1184
+
1185
+ closePicker(value) {
1186
+ const resolve = this.pickerResolve;
1187
+ this.picker = null;
1188
+ this.pickerResolve = null;
1189
+ this.render();
1190
+ resolve?.(value);
1191
+ }
1192
+
1193
+ /**
1194
+ * Rows for an open picker, windowed so a long list still fits.
1195
+ *
1196
+ * An item may carry a `sub` line — a second, dimmer row underneath it. That
1197
+ * is what lets a list of saved conversations show what each one was actually
1198
+ * about instead of a column of near-identical titles.
1199
+ */
1200
+ pickerLines(height) {
1201
+ const { items, index, hint, armed } = this.picker;
1202
+ const room = Math.max(1, height - 2);
1203
+
1204
+ // Rows per item, so the window can be sized in rows rather than in items.
1205
+ const rowsFor = (item) => (typeof item !== 'string' && item.sub ? 2 : 1);
1206
+ const perItem = items.map(rowsFor);
1207
+
1208
+ // Walk outward from the selection until the window is full. Starting from
1209
+ // the selection guarantees it is on screen however long the list is.
1210
+ let first = index;
1211
+ let last = index;
1212
+ let used = perItem[index] ?? 1;
1213
+ while (used < room && (first > 0 || last < items.length - 1)) {
1214
+ if (first > 0 && used + perItem[first - 1] <= room) { first--; used += perItem[first]; }
1215
+ else if (last < items.length - 1 && used + perItem[last + 1] <= room) { last++; used += perItem[last]; }
1216
+ else break;
1217
+ }
1218
+
1219
+ const out = [];
1220
+ for (let i = first; i <= last; i++) {
1221
+ const item = items[i];
1222
+ const body = typeof item === 'string' ? item : item.label;
1223
+ if (i === armed) out.push(`${theme.warn('✗')} ${theme.warn(bare(body))}`);
1224
+ else out.push(i === index ? `${blue('❯')} ${chalk.bold.white(body)}` : ` ${dim(body)}`);
1225
+ if (typeof item !== 'string' && item.sub) out.push(` ${item.sub}`);
1226
+ }
1227
+
1228
+ out.push('');
1229
+ out.push(armed !== null && armed !== undefined
1230
+ ? theme.warn(' press d again to delete this conversation · any other key keeps it')
1231
+ : dim(` ${hint}`));
1232
+ return out;
1233
+ }
1234
+
1235
+ /** A numbered list, answered on the input line. */
1236
+ async choose(prompt, items, { allowNone = true } = {}) {
1237
+ items.forEach((item, i) => this.push(` ${blue(String(i + 1).padStart(2))}. ${item}`));
1238
+ if (allowNone) this.push(dim(' 0. none — start fresh'));
1239
+ this.push('');
1240
+
1241
+ this.pendingPrompt = prompt;
1242
+ this.render();
1243
+
1244
+ const answer = await this.nextLine();
1245
+ this.pendingPrompt = null;
1246
+
1247
+ const trimmed = String(answer ?? '').trim();
1248
+ if (trimmed === '' || trimmed === '0') return null;
1249
+
1250
+ const index = Number(trimmed);
1251
+ if (!Number.isInteger(index) || index < 1 || index > items.length) {
1252
+ this.push(theme.warn(` "${trimmed}" is not one of 1-${items.length}.`));
1253
+ return null;
1254
+ }
1255
+ return index - 1;
1256
+ }
1257
+
1258
+ // -- keyboard and mouse --------------------------------------------------
1259
+
1260
+ /**
1261
+ * Scroll the transcript, clamped at both ends.
1262
+ *
1263
+ * When there is nothing above the fold, say so. Silence is indistinguishable
1264
+ * from broken input, and the difference matters: one means the conversation
1265
+ * simply fits, the other means the terminal is not forwarding keys at all.
1266
+ */
1267
+ scrollBy(delta) {
1268
+ const max = Math.max(0, this.lines.length - this.viewportHeight());
1269
+ if (max === 0) {
1270
+ this.flash('nothing above — it all fits on screen');
1271
+ return;
1272
+ }
1273
+ const before = this.scroll;
1274
+ this.scroll = Math.min(Math.max(0, this.scroll + delta), max);
1275
+ if (this.scroll === before && delta > 0) this.flash('already at the top');
1276
+ this.render();
1277
+ }
1278
+
1279
+ /**
1280
+ * Text arriving as a paste rather than as typing.
1281
+ *
1282
+ * A terminal in bracketed-paste mode wraps pasted text in markers, which is
1283
+ * the only way to tell forty lines pasted at once from forty lines typed
1284
+ * very fast. Without it every newline in the paste reads as Enter, so a
1285
+ * pasted block submits itself a line at a time and arrives as forty
1286
+ * messages. Inside the markers a newline is just a character.
1287
+ */
1288
+ onPaste(text) {
1289
+ const clean = String(text).replace(/\r\n?/g, '\n');
1290
+ this.buffer = this.buffer.slice(0, this.cursor) + clean + this.buffer.slice(this.cursor);
1291
+ this.cursor += clean.length;
1292
+ this.render();
1293
+ }
1294
+
1295
+ onData(chunk) {
1296
+ // Pasted text first: it is wrapped in markers and must not be read as
1297
+ // keys, or its newlines submit it in pieces.
1298
+ const paste = /\[200~([\s\S]*?)\[201~/g;
1299
+ if (paste.test(chunk)) {
1300
+ paste.lastIndex = 0;
1301
+ let at = 0;
1302
+ let m;
1303
+ while ((m = paste.exec(chunk))) {
1304
+ if (m.index > at) this.onData(chunk.slice(at, m.index));
1305
+ this.onPaste(m[1]);
1306
+ at = m.index + m[0].length;
1307
+ }
1308
+ if (at < chunk.length) this.onData(chunk.slice(at));
1309
+ return;
1310
+ }
1311
+ // An unterminated paste: hold what has arrived and wait for the rest.
1312
+ const open = chunk.indexOf('[200~');
1313
+ if (open !== -1) {
1314
+ if (open > 0) this.onData(chunk.slice(0, open));
1315
+ this.pasting = chunk.slice(open + 6);
1316
+ return;
1317
+ }
1318
+ if (this.pasting !== undefined && this.pasting !== null) {
1319
+ const close = chunk.indexOf('[201~');
1320
+ if (close === -1) { this.pasting += chunk; return; }
1321
+ this.onPaste(this.pasting + chunk.slice(0, close));
1322
+ this.pasting = null;
1323
+ const after = chunk.slice(close + 6);
1324
+ if (after) this.onData(after);
1325
+ return;
1326
+ }
1327
+
1328
+ // UCODE_DEBUG_KEYS=1 logs every byte the terminal sends to
1329
+ // ~/.ucode/keys.log. Whether mouse reporting works at all depends on the
1330
+ // terminal forwarding it; this is how to find out.
1331
+ if (process.env.UCODE_DEBUG_KEYS) {
1332
+ appendFile(path.join(homedir(), '.ucode', 'keys.log'), `${JSON.stringify(chunk)}\n`).catch(() => {});
1333
+ }
1334
+
1335
+ // Pull mouse reports out of the chunk wherever they sit. Anchoring the
1336
+ // match to the whole chunk meant a wheel event arriving alongside any
1337
+ // other byte was silently treated as typing.
1338
+ let rest = '';
1339
+ let index = 0;
1340
+ // Two encodings: SGR (ESC [ < b ; x ; y M|m), and the legacy form
1341
+ // (ESC [ M then three bytes offset by 32) for terminals that ignore 1006.
1342
+ const mouse = /\x1b\[<(\d+);(\d+);(\d+)([Mm])|\x1b\[M([\s\S])([\s\S])([\s\S])/g;
1343
+ let match;
1344
+
1345
+ while ((match = mouse.exec(chunk)) !== null) {
1346
+ rest += chunk.slice(index, match.index);
1347
+ index = match.index + match[0].length;
1348
+ if (match[1] !== undefined) {
1349
+ this.onMouse(Number(match[1]), Number(match[2]), Number(match[3]), match[4]);
1350
+ } else {
1351
+ this.onMouse(
1352
+ match[5].charCodeAt(0) - 32,
1353
+ match[6].charCodeAt(0) - 32,
1354
+ match[7].charCodeAt(0) - 32,
1355
+ 'M'
1356
+ );
1357
+ }
1358
+ }
1359
+ rest += chunk.slice(index);
1360
+
1361
+ // A chunk carrying a line break *and* other text did not come from a
1362
+ // keyboard: nobody types a newline in the middle of a burst. Many
1363
+ // terminals, Windows ones especially, send a paste with no markers at
1364
+ // all, so without this every newline in it reads as Enter and the paste
1365
+ // submits itself a line at a time.
1366
+ if (looksPasted(rest)) { this.onPaste(rest); return; }
1367
+
1368
+ for (const key of splitKeys(rest)) this.onKey(key);
1369
+ }
1370
+
1371
+ onMouse(button, col, row, press) {
1372
+ // Wheel reports set bit 6; bit 0 says which way.
1373
+ if (button >= 64) {
1374
+ this.scrollBy(button % 2 === 0 ? 3 : -3);
1375
+ return;
1376
+ }
1377
+ if (press !== 'M' || button !== 0) return;
1378
+ if (this.welcoming()) {
1379
+ const g = this.welcomeGeometry();
1380
+ const statusRow = g.boxTop + g.inputRows + 3; // 1-based
1381
+ if (row === statusRow && col > g.left + 1 && col <= g.left + this.chipTo) this.toggleMode();
1382
+ return;
1383
+ }
1384
+ // The mode chip, at the left of the bottom row.
1385
+ if (row === this.rows - 1 && col >= 2 && col <= this.chipTo) this.toggleMode();
1386
+ }
1387
+
1388
+ onKey(key) {
1389
+ // An open picker owns the keyboard until it closes.
1390
+ if (this.picker) {
1391
+ const last = this.picker.items.length - 1;
1392
+ if (this.picker.deletable && (key === 'd' || key === 'D' || key === `${ESC}[3~`)) {
1393
+ if (this.picker.armed === this.picker.index) { this.closePicker({ delete: this.picker.index }); return; }
1394
+ this.picker.armed = this.picker.index;
1395
+ this.render();
1396
+ return;
1397
+ }
1398
+ this.picker.armed = null; // any other key takes the delete back
1399
+ if (key === `${ESC}[A`) { this.picker.index = Math.max(0, this.picker.index - 1); this.render(); return; }
1400
+ if (key === `${ESC}[B`) { this.picker.index = Math.min(last, this.picker.index + 1); this.render(); return; }
1401
+ if (key === '\r' || key === '\n') { this.closePicker(this.picker.index); return; }
1402
+ if (key === ESC || key === '\x03') { this.closePicker(null); return; }
1403
+ return;
1404
+ }
1405
+
1406
+ switch (key) {
1407
+ case '\r':
1408
+ case '\n': {
1409
+ const text = this.buffer;
1410
+ this.buffer = '';
1411
+ this.cursor = 0;
1412
+ this.historyIndex = -1;
1413
+ if (text.trim()) {
1414
+ this.history.unshift(text);
1415
+ // Answers to a y/N or a numbered pick are not messages, so they are
1416
+ // not echoed: the prompt reports its own outcome.
1417
+ if (!this.pendingPrompt) this.userMessage(text);
1418
+ }
1419
+ this.render();
1420
+ this.submit(text);
1421
+ return;
1422
+ }
1423
+
1424
+ case '\x7f': // backspace
1425
+ case '\b':
1426
+ if (this.cursor > 0) {
1427
+ this.buffer = this.buffer.slice(0, this.cursor - 1) + this.buffer.slice(this.cursor);
1428
+ this.cursor--;
1429
+ }
1430
+ break;
1431
+
1432
+ case '\x03': // ctrl+c
1433
+ if (this.status.busy && this.onInterrupt) this.onInterrupt();
1434
+ else { this.buffer = ''; this.cursor = 0; }
1435
+ break;
1436
+
1437
+ case '\x04': // ctrl+d
1438
+ this.close();
1439
+ return;
1440
+
1441
+ case '\x02': // ctrl+b — swap plan and build
1442
+ this.toggleMode();
1443
+ return;
1444
+
1445
+ case '\x15': // ctrl+u — clear the line
1446
+ this.buffer = this.buffer.slice(this.cursor);
1447
+ this.cursor = 0;
1448
+ break;
1449
+
1450
+ case ESC: // esc — stop the turn in flight
1451
+ if (this.onInterrupt) this.onInterrupt();
1452
+ return;
1453
+
1454
+ case '\t': {
1455
+ const hit = COMMANDS.find((c) => c.startsWith(this.buffer));
1456
+ if (hit) { this.buffer = hit; this.cursor = hit.length; }
1457
+ break;
1458
+ }
1459
+
1460
+ // With an empty line the arrows scroll the conversation; once there is
1461
+ // something typed they walk history. Terminals often swallow PgUp and
1462
+ // PgDn for their own scrollback, so this is the path that always works.
1463
+ case `${ESC}[A`:
1464
+ if (!this.buffer) { this.scrollBy(2); return; }
1465
+ if (this.history.length) {
1466
+ this.historyIndex = Math.min(this.historyIndex + 1, this.history.length - 1);
1467
+ this.buffer = this.history[this.historyIndex] ?? '';
1468
+ this.cursor = this.buffer.length;
1469
+ }
1470
+ break;
1471
+
1472
+ case `${ESC}[B`:
1473
+ if (!this.buffer) { this.scrollBy(-2); return; }
1474
+ this.historyIndex = Math.max(this.historyIndex - 1, -1);
1475
+ this.buffer = this.historyIndex === -1 ? '' : (this.history[this.historyIndex] ?? '');
1476
+ this.cursor = this.buffer.length;
1477
+ break;
1478
+
1479
+ case `${ESC}[1;5A`: this.scrollBy(2); return; // ctrl+up
1480
+ case `${ESC}[1;5B`: this.scrollBy(-2); return; // ctrl+down
1481
+ case `${ESC}[5~`: this.scrollBy(this.viewportHeight()); return;
1482
+ case `${ESC}[6~`: this.scrollBy(-this.viewportHeight()); return;
1483
+
1484
+ case `${ESC}[H`: this.scrollBy(this.lines.length); return;
1485
+ case `${ESC}[F`: this.scroll = 0; this.render(); return;
1486
+
1487
+ case `${ESC}[C`: this.cursor = Math.min(this.cursor + 1, this.buffer.length); break;
1488
+ case `${ESC}[D`: this.cursor = Math.max(this.cursor - 1, 0); break;
1489
+
1490
+ default:
1491
+ if (key >= ' ' && !key.startsWith(ESC)) {
1492
+ this.buffer = this.buffer.slice(0, this.cursor) + key + this.buffer.slice(this.cursor);
1493
+ this.cursor += key.length;
1494
+ } else {
1495
+ return;
1496
+ }
1497
+ }
1498
+
1499
+ this.render();
1500
+ }
1501
+
1502
+ // -- painting ------------------------------------------------------------
1503
+
1504
+ render() {
1505
+ if (this.closed) return;
1506
+ if (this.welcoming()) {
1507
+ this.renderWelcome();
1508
+ return;
1509
+ }
1510
+
1511
+ const width = this.width();
1512
+ const height = this.viewportHeight();
1513
+
1514
+ // The live line is the last line of the conversation, not a fixture above
1515
+ // the input box. Pinned down there it sat at the bottom of the screen while
1516
+ // the message that started it was at the top, with the empty middle of the
1517
+ // viewport between them — so the thing being done looked unrelated to the
1518
+ // thing that had been asked. On the end of the transcript it arrives
1519
+ // directly under the prompt, which is where the eye already is.
1520
+ const live = this.activityLine(width);
1521
+ const said = live ? [...this.lines, live] : this.lines;
1522
+
1523
+ const end = Math.max(0, said.length - this.scroll);
1524
+ const start = Math.max(0, end - height);
1525
+ const window = this.picker ? this.pickerLines(height) : said.slice(start, end);
1526
+ while (window.length < height) window.push('');
1527
+
1528
+ const frame = [
1529
+ ...this.headerLines(),
1530
+ '',
1531
+ ...window,
1532
+ // Always one clear row between the last thing said and the box you type
1533
+ // in. Without it the newest line of output sits against the border and
1534
+ // reads as part of the input rather than as the answer above it.
1535
+ '',
1536
+ ...this.inputBox(),
1537
+ ];
1538
+
1539
+ // The cursor is hidden for the duration of the paint. Without this it is
1540
+ // dragged through every line as the frame is written, which shows up as a
1541
+ // dot flickering above the input box on every keystroke.
1542
+ const out = [HIDE, HOME];
1543
+ for (let i = 0; i < this.rows; i++) {
1544
+ out.push(CLEAR_LINE + padVis(frame[i] ?? '', width) + (i === this.rows - 1 ? '' : '\n'));
1545
+ }
1546
+
1547
+ const [row, col] = this.caret();
1548
+ out.push(at(row, col) + SHOW);
1549
+ this.paintedBusy = this.busy();
1550
+ this.output.write(out.join(''));
1551
+ }
1552
+
1553
+ /**
1554
+ * Where the typing caret belongs, 1-based.
1555
+ *
1556
+ * Column three is the first character inside the box: border, a space of
1557
+ * padding, then the text.
1558
+ */
1559
+ caret() {
1560
+ if (this.welcoming()) {
1561
+ const g = this.welcomeGeometry();
1562
+ const { row, col } = this.caretAt(g.boxWidth - 4);
1563
+ // g.boxTop is 0-based and the typed lines start one below the border.
1564
+ return [g.boxTop + 2 + row, g.left + 3 + col];
1565
+ }
1566
+
1567
+ const { row, col: at, rows } = this.caretAt();
1568
+ const col = 3 + at;
1569
+ // Counting up from the bottom: the box border is the last row, the status
1570
+ // row is above it, then the blank row, then the typed lines.
1571
+ const firstRow = this.rows - 2 - rows.length;
1572
+ return [firstRow + row, col];
1573
+ }
1574
+
1575
+ // -- start screen ----------------------------------------------------------
1576
+
1577
+ /**
1578
+ * Nothing has been said yet, so there is nothing to scroll: the screen is the
1579
+ * wordmark and the place to type, centred, and nothing else.
1580
+ *
1581
+ * It comes back after /clear and /new too, since those empty the transcript —
1582
+ * a fresh conversation starts from the same quiet screen as a fresh launch.
1583
+ */
1584
+ welcoming() {
1585
+ return this.lines.length === 0 && !this.picker;
1586
+ }
1587
+
1588
+ /** Where everything on the start screen goes, 0-based rows. */
1589
+ welcomeGeometry() {
1590
+ const cols = this.width();
1591
+ const boxWidth = Math.max(30, Math.min(cols - 4, 84));
1592
+ const left = Math.max(0, Math.floor((cols - boxWidth) / 2));
1593
+ const big = cols >= BANNER_WIDTH + 4 && this.rows >= 18;
1594
+ const art = big ? BANNER : ['u c o d e'];
1595
+ const inputRows = this.inputLines(boxWidth - 4).rows.length;
1596
+ const boxRows = inputRows + 4; // borders, typed rows, gap, status
1597
+ const suggest = this.rows >= boxRows + art.length + SUGGEST_ROWS + 6;
1598
+ const block = art.length + 2 + boxRows + (suggest ? SUGGEST_ROWS : 0);
1599
+ // A touch above true centre reads as centred; exact centre looks low.
1600
+ const top = Math.max(0, Math.floor((this.rows - block) / 2) - 1);
1601
+ return { cols, boxWidth, left, big, art, inputRows, boxRows, suggest, top, boxTop: top + art.length + 2 };
1602
+ }
1603
+
1604
+ renderWelcome() {
1605
+ const g = this.welcomeGeometry();
1606
+ const frame = new Array(this.rows).fill('');
1607
+
1608
+ // The wordmark lit from the top: sky at the crown, deep in the shadow
1609
+ // rows. Across the rows rather than along them — a name split down its
1610
+ // middle reads as two words, where a name that fades downward reads as
1611
+ // one object with a light on it.
1612
+ const elapsed = this.intro ? Date.now() - this.intro : Infinity;
1613
+ g.art.forEach((line, i) => {
1614
+ const pad = ' '.repeat(Math.max(0, Math.floor((g.cols - line.length) / 2)));
1615
+ frame[g.top + i] = pad + (g.big
1616
+ ? bannerSweep(line, i, g.art.length, elapsed)
1617
+ : blue.bold(line));
1618
+ });
1619
+
1620
+ const indent = ' '.repeat(g.left);
1621
+ this.inputBox(g.boxWidth).forEach((row, i) => {
1622
+ frame[g.boxTop + i] = indent + row;
1623
+ });
1624
+
1625
+ // Three things to try, aligned with the text inside the box above them.
1626
+ if (g.suggest) {
1627
+ const at = g.boxTop + g.boxRows + 1;
1628
+ SUGGESTIONS.forEach((text, i) => {
1629
+ const label = i === 0 ? 'try'.padEnd(SUGGEST_LABEL) : ' '.repeat(SUGGEST_LABEL);
1630
+ frame[at + i] = `${indent} ${dim(sky(label))}${dim(clip(text, Math.max(8, g.boxWidth - SUGGEST_LABEL - 2)))}`;
1631
+ });
1632
+ }
1633
+
1634
+ // The version, in the corner, and nothing else on the screen.
1635
+ if (VERSION) {
1636
+ const tag = dim(this.facts.update ? `v${VERSION} · v${this.facts.update} installed, starts next time` : `v${VERSION}`);
1637
+ frame[this.rows - 1] = ' '.repeat(Math.max(0, g.cols - visLen(tag) - 2)) + tag;
1638
+ }
1639
+
1640
+ const out = [HIDE, HOME];
1641
+ for (let i = 0; i < this.rows; i++) {
1642
+ out.push(CLEAR_LINE + padVis(frame[i], g.cols) + (i === this.rows - 1 ? '' : '\n'));
1643
+ }
1644
+ const [row, col] = this.caret();
1645
+ out.push(at(row, col) + SHOW);
1646
+ this.paintedBusy = this.busy();
1647
+ this.output.write(out.join(''));
1648
+ }
1649
+ }
1650
+
1651
+ /**
1652
+ * Split a raw stdin chunk into keys, keeping escape sequences whole.
1653
+ *
1654
+ * Application cursor key mode (DECCKM) makes a terminal send ESC O A for the
1655
+ * up arrow rather than ESC [ A. Both are normalised to the bracket form here
1656
+ * so the key handler only ever sees one of them.
1657
+ */
1658
+ /**
1659
+ * Did this arrive as a paste, judged by shape rather than by markers?
1660
+ *
1661
+ * Someone pressing Enter sends one carriage return on its own. A paste sends
1662
+ * a line break with text around it, in a single read. That difference is all
1663
+ * there is to go on when a terminal does not implement bracketed paste, and
1664
+ * it is enough.
1665
+ *
1666
+ * Anything carrying an escape sequence is left alone: that is a key or a
1667
+ * mouse report, and reading one as text would put gibberish in the input.
1668
+ */
1669
+ export function looksPasted(chunk) {
1670
+ const text = String(chunk ?? '');
1671
+ if (text.length < 2 || text.includes(ESC)) return false;
1672
+ const breaks = (text.match(/[\r\n]/g) ?? []).length;
1673
+ if (breaks === 0) return false;
1674
+ // One trailing break is someone finishing a line, not pasting one.
1675
+ if (breaks === 1 && /[\r\n]$/.test(text)) return false;
1676
+ return true;
1677
+ }
1678
+
1679
+ export function splitKeys(chunk) {
1680
+ const keys = [];
1681
+ let i = 0;
1682
+
1683
+ while (i < chunk.length) {
1684
+ const c = chunk[i];
1685
+ if (c !== ESC) { keys.push(c); i++; continue; }
1686
+
1687
+ const rest = chunk.slice(i);
1688
+ const csi = /^\x1b\[[0-9;?]*[A-Za-z~]/.exec(rest);
1689
+ if (csi) { keys.push(csi[0]); i += csi[0].length; continue; }
1690
+
1691
+ const ss3 = /^\x1bO([A-Za-z])/.exec(rest);
1692
+ if (ss3) { keys.push(`${ESC}[${ss3[1]}`); i += ss3[0].length; continue; }
1693
+
1694
+ keys.push(ESC);
1695
+ i++;
1696
+ }
1697
+
1698
+ return keys;
1699
+ }