ucode-agent 1.1.0 → 1.2.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,1094 +1,1187 @@
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 (free) 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, dim, edge, ADDED, REMOVED, BANNER, BANNER_WIDTH, SPINNER,
41
- boxTop, boxBottom, boxRow, visLen, padVis, clip, wrapAnsi,
42
- shortenPath, asLabel, ensureColour,
43
- } from './theme.js';
44
- import { renderer, render, polish } from './markdown.js';
45
-
46
- /**
47
- * One line of narration, in the model's own words: "Reading screen.js".
48
- * Anything longer than this is prose, and prose belongs in the answer.
49
- */
50
- export const MAX_LABEL = 120;
51
-
52
- export function isLabel(text) {
53
- const t = String(text ?? '').trim();
54
- return t.length > 0 && t.length <= MAX_LABEL && !t.includes('\n');
55
- }
56
-
57
- export const COMMANDS = [
58
- '/help', '/model', '/models', '/session', '/sessions', '/resume',
59
- '/new', '/skills', '/clear', '/search', '/copy', '/exit',
60
- ];
61
-
62
- // ANSI ----------------------------------------------------------------------
63
- const ESC = '\x1b';
64
- const ALT_ON = `${ESC}[?1049h`;
65
- const ALT_OFF = `${ESC}[?1049l`;
66
-
67
- /**
68
- * Mouse setup, decided by measurement rather than by documentation.
69
- *
70
- * 1007 is alternate scroll: inside the alternate screen the terminal turns
71
- * wheel events into arrow keys. On Windows that is the only way a wheel ever
72
- * reaches the program, because ConPTY forwards no mouse input at all a probe
73
- * that enabled every tracking mode received nothing from a scroll.
74
- *
75
- * And mouse tracking suppresses alternate scroll. So on Windows tracking is
76
- * deliberately not requested: it delivers nothing there, and asking for it
77
- * would cost the wheel. Elsewhere tracking works, so the mode chip is
78
- * clickable on those platforms.
79
- */
80
- const TRACK = process.platform === 'win32'
81
- ? '' : `${ESC}[?1000h${ESC}[?1002h${ESC}[?1015h${ESC}[?1006h`;
82
- const UNTRACK = process.platform === 'win32'
83
- ? '' : `${ESC}[?1006l${ESC}[?1015l${ESC}[?1002l${ESC}[?1000l`;
84
-
85
- const MOUSE_ON = `${ESC}[?1007h${TRACK}`;
86
- const MOUSE_OFF = `${UNTRACK}${ESC}[?1007l`;
87
- const HIDE = `${ESC}[?25l`;
88
- const SHOW = `${ESC}[?25h`;
89
- const HOME = `${ESC}[H`;
90
- const CLEAR_LINE = `${ESC}[K`;
91
- const at = (row, col) => `${ESC}[${row};${col}H`;
92
- const title = (t) => `${ESC}]0;${t}\x07`;
93
-
94
- /**
95
- * Fixed rows below the header: the gap under it, the gap above the input box,
96
- * the input box's two borders, the blank row inside it, and the status row.
97
- */
98
- const CHROME_BELOW = 6;
99
-
100
- /** The wordmark only earns its place with room for the facts column beside it. */
101
- const WORDMARK_NEEDS = BANNER_WIDTH + 30;
102
-
103
- export class Screen {
104
- constructor({ cwd, input = process.stdin, output = process.stdout } = {}) {
105
- this.cwd = cwd;
106
- this.input = input;
107
- this.output = output;
108
-
109
- this.lines = []; // the rendered transcript
110
- this.scroll = 0; // rows scrolled up from the bottom
111
- this.buffer = ''; // what is being typed
112
- this.cursor = 0;
113
- this.history = [];
114
- this.historyIndex = -1;
115
-
116
- this.status = { busy: false, text: '', frame: 0, since: 0 };
117
- this.facts = {};
118
- this.model = '';
119
-
120
- this.waiters = [];
121
- this.queue = [];
122
- this.closed = false;
123
-
124
- // 'build' may edit and run; 'plan' is read-only. Ctrl+B swaps them, and
125
- // the chip is clickable wherever the terminal forwards clicks.
126
- this.mode = 'build';
127
- this.chipTo = 0;
128
- this.onInterrupt = null;
129
- this.onModeChange = null;
130
- this.spinTimer = null;
131
- this.pendingPrompt = null;
132
-
133
- this.cols = output.columns || 80;
134
- this.rows = output.rows || 24;
135
- this.md = renderer(this.width());
136
- }
137
-
138
- // -- lifecycle -----------------------------------------------------------
139
-
140
- async start() {
141
- ensureColour(this.output);
142
- this.output.write(ALT_ON + MOUSE_ON + HIDE + title(`ucode — ${path.basename(this.cwd)}`));
143
- this.input.setRawMode?.(true);
144
- this.input.resume();
145
- this.input.setEncoding('utf8');
146
- this.input.on('data', (chunk) => this.onData(chunk));
147
-
148
- this.onResize = () => {
149
- this.cols = this.output.columns || 80;
150
- this.rows = this.output.rows || 24;
151
- this.md = renderer(this.width());
152
- this.render();
153
- };
154
- this.output.on('resize', this.onResize);
155
-
156
- this.render();
157
- }
158
-
159
- stop() {
160
- this.stopSpinner();
161
- this.output.off?.('resize', this.onResize);
162
- this.input.setRawMode?.(false);
163
- this.input.pause();
164
- this.output.write(MOUSE_OFF + ALT_OFF + SHOW);
165
- }
166
-
167
- close() {
168
- if (this.closed) return;
169
- this.closed = true;
170
- this.stop();
171
- while (this.waiters.length) this.waiters.shift()(null);
172
- }
173
-
174
- width() {
175
- return Math.max(30, this.cols);
176
- }
177
-
178
- /** Usable width inside a box: two borders and a space of padding each side. */
179
- inner() {
180
- return Math.max(8, this.width() - 4);
181
- }
182
-
183
- // -- transcript ----------------------------------------------------------
184
-
185
- /**
186
- * Append without painting.
187
- *
188
- * Anything replacing a region of the transcript has to build the whole
189
- * region and then render once. Painting between the delete and the re-add
190
- * puts a frame on screen with the text missing, and at streaming speed that
191
- * reads as flicker.
192
- */
193
- add(text = '') {
194
- const width = this.width();
195
- for (const raw of String(text).split('\n')) {
196
- if (visLen(raw) <= width) this.lines.push(raw);
197
- else for (const wrapped of wrapAnsi(raw, width)) this.lines.push(wrapped);
198
- }
199
- this.scroll = 0; // new output snaps back to the bottom
200
- }
201
-
202
- push(text = '') {
203
- this.add(text);
204
- this.soon();
205
- }
206
-
207
- /**
208
- * Collapse a burst of pushes into one frame.
209
- *
210
- * Printing a list one line at a time repaints the screen per line — a model
211
- * list of fifty entries drew a hundred frames back to back, which is visible
212
- * as a cascade. A microtask runs before any I/O, so everything pushed in one
213
- * synchronous stretch becomes a single render, while a push after an await
214
- * still paints immediately.
215
- */
216
- soon() {
217
- if (this.queued) return;
218
- this.queued = true;
219
- queueMicrotask(() => {
220
- this.queued = false;
221
- this.render();
222
- });
223
- }
224
-
225
- write(text = '') { this.push(text); }
226
- blank() { this.push(''); }
227
- note(text) { this.push(dim(` ${text}`)); }
228
-
229
- clearScreen() {
230
- this.lines = [];
231
- this.scroll = 0;
232
- this.render();
233
- }
234
-
235
- assistant(text) {
236
- if (!text?.trim()) return;
237
- this.add('');
238
- this.add(render(this.md, text));
239
- this.add('');
240
- this.render();
241
- }
242
-
243
- /**
244
- * Something the user said, in the conversation, in the same blue box as the
245
- * input it was typed into.
246
- *
247
- * A long session is mostly the agent's output — tool calls, diffs, answers.
248
- * Your own messages are the landmarks you scroll back looking for, so they
249
- * get the frame: every one of them is findable at a glance, and the box
250
- * matches the one below so it is plain where each came from.
251
- */
252
- userMessage(text) {
253
- const width = this.width();
254
- const room = Math.max(8, width - 6); // borders, padding, and the caret column
255
-
256
- const rows = [];
257
- for (const paragraph of String(text).replace(/\r/g, '').split('\n')) {
258
- for (const line of wrapAnsi(paragraph, room)) rows.push(line);
259
- }
260
-
261
- this.add('');
262
- this.add(boxTop(width, edge));
263
- rows.forEach((row, i) => {
264
- const lead = i === 0 ? blue('') : ' ';
265
- this.add(boxRow(` ${lead} ${chalk.white(row)}`, width, edge));
266
- });
267
- this.add(boxBottom(width, edge));
268
- this.render();
269
- }
270
-
271
- /**
272
- * A tool call, as it happens: "● Listing src".
273
- *
274
- * This lives in the transcript rather than only on the status line. The
275
- * status line overwrites itself and is empty by the end of the turn, so work
276
- * announced only there scrolls past unseen — and the diff underneath ends up
277
- * with nothing above it explaining where it came from.
278
- */
279
- toolCall(label) {
280
- // U+25CF, not U+23FA: the latter carries emoji presentation, which Windows
281
- // Terminal draws as a white circle on a blue tile.
282
- this.push(`${blue('●')} ${asLabel(label)}`);
283
- this.updateSpinner(label);
284
- }
285
-
286
- toolResult(summary) {
287
- this.push(dim(` └ ${summary}`));
288
- }
289
-
290
- toolFailed(summary) {
291
- this.push(`${dim(' └ ')}${theme.error(summary)}`);
292
- }
293
-
294
- /**
295
- * The change itself, under the result.
296
- *
297
- * A line-number gutter, then the sign and the code tinted right across the
298
- * row. The numbers are the point: a diff you cannot navigate from is a
299
- * picture of a change rather than a record of one.
300
- */
301
- diff(lines) {
302
- const gutter = 6;
303
- // Two spaces of indent, the gutter, one space, then the tint fills the
304
- // rest. One column over and every row wraps, splitting the whole diff.
305
- const room = Math.max(12, this.width() - gutter - 3);
306
-
307
- for (const line of lines) {
308
- // A file heading in a multi-file write.
309
- if (line.startsWith('~')) {
310
- this.add(` ${dim(' '.repeat(gutter))} ${sky(line.slice(1))}`);
311
- continue;
312
- }
313
-
314
- const added = line.startsWith('+');
315
- const rest = line.slice(1);
316
- // Tools emit "<line>| <text>". A row with no number is the "12 more
317
- // lines" note, which is not part of the change, so it stays dim.
318
- const parsed = /^(\d+)\|\s?([\s\S]*)$/.exec(rest);
319
- if (!parsed) {
320
- this.add(` ${dim(' '.repeat(gutter))} ${dim(rest)}`);
321
- continue;
322
- }
323
-
324
- const [, number, body] = parsed;
325
- const tint = added ? ADDED : REMOVED;
326
- this.add(
327
- ` ${dim(number.padStart(gutter))} ` +
328
- // Tabs would leave the tint ending short of the row, so they widen.
329
- tint(padVis(clip(`${added ? '+' : '-'} ${body.replace(/\t/g, ' ')}`, room), room))
330
- );
331
- }
332
- this.render(); // a sixteen-line diff is one frame, not sixteen
333
- }
334
-
335
- /** Captured output under a command, dimmed so it reads as evidence. */
336
- commandOutput(lines) {
337
- for (const line of lines) this.add(` ${dim(line)}`);
338
- this.render();
339
- }
340
-
341
- /**
342
- * A running command's output, live on the status line and nowhere else.
343
- *
344
- * Only the newest line, gone as soon as the next arrives. Appending each one
345
- * instead would mean a test run leaving sixty lines of "ok" in the
346
- * conversation permanently, which is noise the moment it scrolls. What
347
- * survives a command is decided when it ends: nothing if it worked, the tail
348
- * if it did not.
349
- */
350
- progress(lines) {
351
- const last = lines[lines.length - 1]?.trim();
352
- if (last) this.updateSpinner(last);
353
- }
354
-
355
- /**
356
- * The model's own account of the step it is taking, before it takes it.
357
- *
358
- * Not called status(): `this.status` holds the spinner state, and a method
359
- * of the same name would be shadowed by it on every instance.
360
- */
361
- narrate(text) {
362
- const line = asLabel(text);
363
- if (!line) return;
364
- this.push(dim(` ⋮ ${clip(line, this.width() - 6)}`));
365
- this.updateSpinner(line);
366
- }
367
-
368
- // -- streaming -----------------------------------------------------------
369
- // Deltas appear as plain text as they arrive, then get replaced in place by
370
- // properly rendered markdown once the reply is complete.
371
-
372
- streamBegin() {
373
- this.stopSpinner();
374
- this.streamAt = this.lines.length;
375
- this.streamBuf = '';
376
- this.streamPainted = 0;
377
- }
378
-
379
- streamDelta(delta) {
380
- if (this.streamAt === undefined) this.streamBegin();
381
- this.streamBuf += delta;
382
- const now = Date.now();
383
- if (now - this.streamPainted < 60) return; // about 16fps is plenty
384
- this.streamPainted = now;
385
- this.repaintStream();
386
- }
387
-
388
- /**
389
- * Repaint the partial reply.
390
- *
391
- * polish() runs on the partial text so bold, inline code and bullets are
392
- * already styled while it streams. Without it the text arrives raw and then
393
- * visibly re-renders at the end, which reads as a glitch.
394
- */
395
- repaintStream() {
396
- this.lines.length = this.streamAt;
397
- this.add('');
398
- this.add(polish(this.streamBuf));
399
- this.render(); // one frame, and never one without the reply in it
400
- }
401
-
402
- /**
403
- * Finish a streamed reply.
404
- *
405
- * `asLabel` says the text turned out to be narration ahead of a tool call
406
- * rather than an answer, in which case one short line folds down into the
407
- * status line it was always meant to be.
408
- */
409
- streamEnd({ asNarration = false } = {}) {
410
- if (this.streamAt === undefined) return '';
411
- const text = this.streamBuf;
412
- this.lines.length = this.streamAt;
413
- this.streamAt = undefined;
414
- this.streamBuf = '';
415
-
416
- if (asNarration && isLabel(text)) this.narrate(text);
417
- else if (text.trim()) this.assistant(text);
418
- else this.render();
419
- return text;
420
- }
421
-
422
- // -- thinking ------------------------------------------------------------
423
- // A reasoning model does all its working before it says anything. None of it
424
- // is printed: it is long, repetitive, and guesses drawn from it read worse
425
- // than silence. The spinner counts the seconds so the wait is visibly alive,
426
- // and the transcript gets one line afterwards saying how long it took.
427
-
428
- thinkingDelta() {
429
- if (this.thoughtSince === undefined) this.thoughtSince = Date.now();
430
- }
431
-
432
- thinkingEnd() {
433
- if (this.thoughtSince === undefined) return;
434
- const seconds = Math.round((Date.now() - this.thoughtSince) / 1000);
435
- if (seconds >= 2) this.push(dim(` ⋮ thought for ${seconds}s`));
436
- this.thoughtSince = undefined;
437
- }
438
-
439
- error(err, { debug = false } = {}) {
440
- const known = err && typeof err === 'object' && err.attempted;
441
- this.push('');
442
- if (known) {
443
- this.push(`${theme.error('✗')} ${chalk.white(`Failed while ${err.attempted}.`)}`);
444
- this.push(` ${err.failed}`);
445
- if (err.fix) this.push(` ${blue('→')} ${err.fix}`);
446
- if (err.kind) this.push(dim(` (${err.kind})`));
447
- } else {
448
- this.push(`${theme.error('')} ${chalk.white('Something broke inside ucode.')}`);
449
- this.push(` ${err?.message ?? String(err)}`);
450
- this.push(` ${blue('')} That is a bug in ucode rather than in your project. Re-run with --debug.`);
451
- }
452
- if (debug) {
453
- const stack = (known && err.cause?.stack) || err?.stack;
454
- if (stack) this.push(dim(stack));
455
- }
456
- this.push('');
457
- }
458
-
459
- // -- header --------------------------------------------------------------
460
-
461
- setFacts(facts) {
462
- this.facts = { ...this.facts, ...facts };
463
- if (facts.model) this.model = facts.model;
464
- this.render();
465
- }
466
-
467
- /** Same shape as the plain UI's header(), so the loop needs no branch. */
468
- header({ cwd, model, used, limit, title: sessionTitle }) {
469
- this.setFacts({
470
- cwd,
471
- model,
472
- title: sessionTitle,
473
- percent: limit > 0 ? Math.min(100, Math.round((used / limit) * 100)) : 0,
474
- });
475
- }
476
-
477
- /**
478
- * How many rows the header box occupies.
479
- *
480
- * The frame has to be exactly as tall as the terminal or every row below the
481
- * shortfall is off by that much — including the one the caret is parked on.
482
- * So this is derived, never assumed.
483
- */
484
- headerHeight() {
485
- return this.width() >= WORDMARK_NEEDS ? BANNER.length + 2 : 5;
486
- }
487
-
488
- headerLines() {
489
- const width = this.width();
490
- const inner = width - 2; // between the borders
491
-
492
- if (width < WORDMARK_NEEDS) {
493
- // Too narrow for the wordmark: stack it rather than wrap it into noise.
494
- const rows = [
495
- ` ${blue.bold('U C O D E')} ${dim('terminal coding agent')}`,
496
- ` ${dim('dir'.padEnd(8))}${chalk.white(clip(shortenPath(this.facts.cwd ?? this.cwd, inner - 12), inner - 12))}`,
497
- ];
498
- return [boxTop(width), ...rows.map((r) => boxRow(r, width)), boxBottom(width)];
499
- }
500
-
501
- // Two spaces of padding, the wordmark, a gap, then the facts column.
502
- //
503
- // Only what you cannot work out by looking: where you are, and how to get
504
- // help. How full the window is belongs on the status row next to the model
505
- // it describes, and the session title is already the terminal's own window
506
- // title — repeating either here is a second place to keep in sync for no
507
- // reader who needed it.
508
- const room = Math.max(8, inner - BANNER_WIDTH - 6);
509
- const facts = [
510
- ['dir', shortenPath(this.facts.cwd ?? this.cwd, room - 9)],
511
- ['keys', '/help · esc interrupts'],
512
- ['', ''],
513
- ['', ''],
514
- ['', ''],
515
- ['', 'made with ❤️ by om dixit'],
516
- ];
517
-
518
- const rows = BANNER.map((art, i) => {
519
- const [label, value] = facts[i] ?? ['', ''];
520
- const right = label
521
- ? `${dim(label.padEnd(9))}${chalk.white(clip(value, room - 9))}`
522
- : (value ? dim(value) : '');
523
- return ` ${blue(art)} ${right}`;
524
- });
525
-
526
- return [boxTop(width), ...rows.map((r) => boxRow(r, width)), boxBottom(width)];
527
- }
528
-
529
- // -- input box -----------------------------------------------------------
530
-
531
- /** The typed line, wrapped to the inside of the box. */
532
- inputLines() {
533
- const width = this.inner();
534
- const prefix = this.pendingPrompt ? `${this.pendingPrompt} ` : '› ';
535
- const full = prefix + this.buffer;
536
-
537
- const rows = [];
538
- for (let i = 0; i < full.length; i += width) rows.push(full.slice(i, i + width));
539
- if (rows.length === 0) rows.push(prefix);
540
-
541
- return { rows, prefix, width };
542
- }
543
-
544
- viewportHeight() {
545
- return Math.max(
546
- 3,
547
- this.rows - this.headerHeight() - CHROME_BELOW - this.inputLines().rows.length
548
- );
549
- }
550
-
551
- /**
552
- * The input box: what you are typing, and directly under it, inside the same
553
- * border, the three things worth knowing while you type.
554
- *
555
- * The status used to sit outside the box on the last row of the screen,
556
- * which made it a separate object floating under the input. Inside the
557
- * border it reads as part of the thing you are using — the box says "this is
558
- * where you work", and the row underneath says what you are working with.
559
- */
560
- inputBox() {
561
- const width = this.width();
562
- const { rows } = this.inputLines();
563
- const painted = rows.map((row, i) =>
564
- i === 0
565
- ? boxRow(` ${blue('›')}${row.slice(1)}`, width, edge) // the caret, coloured
566
- : boxRow(` ${row}`, width, edge)
567
- );
568
- return [
569
- boxTop(width, edge),
570
- ...painted,
571
- // A blank row between the two. Sitting directly under the caret, the
572
- // status read as a second line of the thing being typed; one row of air
573
- // separates what you are writing from what you are writing it with.
574
- boxRow('', width, edge),
575
- boxRow(this.statusRow(), width, edge),
576
- boxBottom(width, edge),
577
- ];
578
- }
579
-
580
- // -- status row ----------------------------------------------------------
581
-
582
- modeChip() {
583
- return this.mode === 'plan' ? `${sky('◇')} ${sky('Plan')}` : `${blue('◆')} ${blue('Build')}`;
584
- }
585
-
586
- /**
587
- * How full the context window is, as a bare number.
588
- *
589
- * It turns amber at 75% because that is where turns start being folded away
590
- * into a summary — the one moment the number predicts something you would
591
- * want to know before it happens.
592
- */
593
- percentChip() {
594
- const percent = Math.round(this.facts.percent ?? 0);
595
- return percent >= 75 ? theme.warn(`${percent}%`) : dim(`${percent}%`);
596
- }
597
-
598
- /**
599
- * Which mode is live, which model is answering, and how full the window is.
600
- *
601
- * Nothing else earns a place. The provider name was there and was cut: it is
602
- * the same on every line of every session, so it was decoration that had to
603
- * be read past to reach the two things that do change.
604
- *
605
- * The middle is borrowed while something is running, for the spinner and the
606
- * way out of it, and handed straight back when it finishes.
607
- */
608
- statusRow() {
609
- const inner = this.width() - 2; // the space between the two borders
610
- const chip = this.modeChip();
611
- const left = ` ${chip} ${dim('·')} ${chalk.white(this.model || '—')}`;
612
- const right = `${this.percentChip()} `;
613
-
614
- // Where a click on the bottom row still counts as hitting the mode chip.
615
- this.chipTo = 2 + visLen(chip);
616
-
617
- const between = Math.max(1, inner - visLen(left) - visLen(right));
618
-
619
- let middle = '';
620
- if (this.flashText) {
621
- middle = dim(clip(this.flashText, between - 2));
622
- } else if (this.status.busy) {
623
- const frame = blue(SPINNER[this.status.frame]);
624
- const secs = Math.round((Date.now() - (this.status.since || Date.now())) / 1000);
625
- const elapsed = secs >= 2 ? dim(` ${secs}s`) : '';
626
- const room = between - 20;
627
- middle = room > 8
628
- ? `${frame} ${dim(clip(this.status.text, room))}${elapsed} ${dim('esc to stop')}`
629
- : `${frame}${elapsed}`;
630
- }
631
-
632
- // The percentage is pinned to the right border whatever is in the middle,
633
- // with a gap kept in front of it so a long spinner label cannot run into
634
- // the number and read as part of it.
635
- const tail = middle ? `${middle} ` : '';
636
- const pad = Math.max(1, inner - visLen(left) - visLen(tail) - visLen(right));
637
- return padVis(left + ' '.repeat(pad) + tail + right, inner);
638
- }
639
-
640
- /**
641
- * Repaint only the status row, leaving the caret where the user left it.
642
- *
643
- * It is the second row from the bottom now — the box's own border is below
644
- * it so the row is written with its borders rather than as a bare line.
645
- */
646
- paintStatus() {
647
- if (this.closed) return;
648
- const [row, col] = this.caret();
649
- this.output.write(
650
- HIDE +
651
- at(this.rows - 1, 1) + CLEAR_LINE + boxRow(this.statusRow(), this.width(), edge) +
652
- at(row, col) + SHOW
653
- );
654
- }
655
-
656
- toggleMode() {
657
- this.mode = this.mode === 'plan' ? 'build' : 'plan';
658
- this.flash(this.mode === 'plan'
659
- ? 'plan mode — reads and researches, changes nothing'
660
- : 'build mode — free to edit files and run commands');
661
- this.onModeChange?.(this.mode);
662
- this.render();
663
- }
664
-
665
- /** A message on the status line that fades on its own. */
666
- flash(text) {
667
- this.flashText = text;
668
- clearTimeout(this.flashTimer);
669
- this.flashTimer = setTimeout(() => {
670
- this.flashText = null;
671
- this.paintStatus();
672
- }, 2500);
673
- this.flashTimer.unref?.();
674
- this.paintStatus();
675
- }
676
-
677
- // -- spinner -------------------------------------------------------------
678
-
679
- startSpinner(text = 'thinking') {
680
- // `since` is what makes a long think legible: the label may not change for
681
- // a minute, so the seconds beside it are the proof it is still alive.
682
- this.status = { busy: true, text: asLabel(text), frame: 0, since: Date.now() };
683
- if (!this.spinTimer) {
684
- this.spinTimer = setInterval(() => {
685
- this.status.frame = (this.status.frame + 1) % SPINNER.length;
686
- this.paintStatus();
687
- }, 80);
688
- this.spinTimer.unref?.();
689
- }
690
- this.paintStatus();
691
- }
692
-
693
- updateSpinner(text) {
694
- if (!this.status.busy) return;
695
- this.status.text = asLabel(text);
696
- this.paintStatus();
697
- }
698
-
699
- stopSpinner() {
700
- if (this.spinTimer) {
701
- clearInterval(this.spinTimer);
702
- this.spinTimer = null;
703
- }
704
- if (this.status.busy) {
705
- this.status = { busy: false, text: '', frame: 0, since: 0 };
706
- this.paintStatus();
707
- }
708
- }
709
-
710
- // -- input ---------------------------------------------------------------
711
-
712
- nextLine() {
713
- if (this.queue.length) return Promise.resolve(this.queue.shift());
714
- if (this.closed) return Promise.resolve(null);
715
- return new Promise((resolve) => this.waiters.push(resolve));
716
- }
717
-
718
- ask() {
719
- return this.nextLine();
720
- }
721
-
722
- submit(text) {
723
- const waiter = this.waiters.shift();
724
- if (waiter) waiter(text);
725
- else this.queue.push(text);
726
- }
727
-
728
- /** y/n, answered on the input line. */
729
- confirm({ action, detail, risk }) {
730
- this.push('');
731
- this.push(`${chalk.inverse(theme.warn(risk === 'command' ? ' shell ' : ' outside project '))} ${chalk.white(action)}`);
732
- for (const line of String(detail ?? '').split('\n')) {
733
- if (line) this.push(dim(` ${line}`));
734
- }
735
-
736
- this.pendingPrompt = 'go ahead? [y/N]';
737
- this.render();
738
-
739
- return this.nextLine().then((answer) => {
740
- this.pendingPrompt = null;
741
- // End of input counts as no. Never run something nobody approved.
742
- const yes = /^(y|yes)$/i.test(String(answer ?? '').trim());
743
- this.push(dim(yes ? ' approved' : ' declined'));
744
- this.push('');
745
- return yes;
746
- });
747
- }
748
-
749
- /**
750
- * A modal list: arrows move, Enter picks, Esc cancels.
751
- *
752
- * Only while this is open do the arrows stop scrolling the transcript. They
753
- * cannot be given up permanently, because under alternate scroll the mouse
754
- * wheel arrives as arrow keys.
755
- */
756
- pick(items, { active = 0, hint = 'enter to choose · esc to cancel' } = {}) {
757
- this.picker = {
758
- items,
759
- index: Math.min(Math.max(0, active), Math.max(0, items.length - 1)),
760
- hint,
761
- };
762
- this.render();
763
- return new Promise((resolve) => { this.pickerResolve = resolve; });
764
- }
765
-
766
- closePicker(value) {
767
- const resolve = this.pickerResolve;
768
- this.picker = null;
769
- this.pickerResolve = null;
770
- this.render();
771
- resolve?.(value);
772
- }
773
-
774
- /**
775
- * Rows for an open picker, windowed so a long list still fits.
776
- *
777
- * An item may carry a `sub` line — a second, dimmer row underneath it. That
778
- * is what lets a list of saved conversations show what each one was actually
779
- * about instead of a column of near-identical titles.
780
- */
781
- pickerLines(height) {
782
- const { items, index, hint } = this.picker;
783
- const room = Math.max(1, height - 2);
784
-
785
- // Rows per item, so the window can be sized in rows rather than in items.
786
- const rowsFor = (item) => (typeof item !== 'string' && item.sub ? 2 : 1);
787
- const perItem = items.map(rowsFor);
788
-
789
- // Walk outward from the selection until the window is full. Starting from
790
- // the selection guarantees it is on screen however long the list is.
791
- let first = index;
792
- let last = index;
793
- let used = perItem[index] ?? 1;
794
- while (used < room && (first > 0 || last < items.length - 1)) {
795
- if (first > 0 && used + perItem[first - 1] <= room) { first--; used += perItem[first]; }
796
- else if (last < items.length - 1 && used + perItem[last + 1] <= room) { last++; used += perItem[last]; }
797
- else break;
798
- }
799
-
800
- const out = [];
801
- for (let i = first; i <= last; i++) {
802
- const item = items[i];
803
- const body = typeof item === 'string' ? item : item.label;
804
- out.push(i === index ? `${blue('❯')} ${chalk.bold.white(body)}` : ` ${dim(body)}`);
805
- if (typeof item !== 'string' && item.sub) out.push(` ${item.sub}`);
806
- }
807
-
808
- out.push('');
809
- out.push(dim(` ${hint}`));
810
- return out;
811
- }
812
-
813
- /** A numbered list, answered on the input line. */
814
- async choose(prompt, items, { allowNone = true } = {}) {
815
- items.forEach((item, i) => this.push(` ${blue(String(i + 1).padStart(2))}. ${item}`));
816
- if (allowNone) this.push(dim(' 0. none — start fresh'));
817
- this.push('');
818
-
819
- this.pendingPrompt = prompt;
820
- this.render();
821
-
822
- const answer = await this.nextLine();
823
- this.pendingPrompt = null;
824
-
825
- const trimmed = String(answer ?? '').trim();
826
- if (trimmed === '' || trimmed === '0') return null;
827
-
828
- const index = Number(trimmed);
829
- if (!Number.isInteger(index) || index < 1 || index > items.length) {
830
- this.push(theme.warn(` "${trimmed}" is not one of 1-${items.length}.`));
831
- return null;
832
- }
833
- return index - 1;
834
- }
835
-
836
- // -- keyboard and mouse --------------------------------------------------
837
-
838
- /**
839
- * Scroll the transcript, clamped at both ends.
840
- *
841
- * When there is nothing above the fold, say so. Silence is indistinguishable
842
- * from broken input, and the difference matters: one means the conversation
843
- * simply fits, the other means the terminal is not forwarding keys at all.
844
- */
845
- scrollBy(delta) {
846
- const max = Math.max(0, this.lines.length - this.viewportHeight());
847
- if (max === 0) {
848
- this.flash('nothing above — it all fits on screen');
849
- return;
850
- }
851
- const before = this.scroll;
852
- this.scroll = Math.min(Math.max(0, this.scroll + delta), max);
853
- if (this.scroll === before && delta > 0) this.flash('already at the top');
854
- this.render();
855
- }
856
-
857
- onData(chunk) {
858
- // UCODE_DEBUG_KEYS=1 logs every byte the terminal sends to
859
- // ~/.ucode/keys.log. Whether mouse reporting works at all depends on the
860
- // terminal forwarding it; this is how to find out.
861
- if (process.env.UCODE_DEBUG_KEYS) {
862
- appendFile(path.join(homedir(), '.ucode', 'keys.log'), `${JSON.stringify(chunk)}\n`).catch(() => {});
863
- }
864
-
865
- // Pull mouse reports out of the chunk wherever they sit. Anchoring the
866
- // match to the whole chunk meant a wheel event arriving alongside any
867
- // other byte was silently treated as typing.
868
- let rest = '';
869
- let index = 0;
870
- // Two encodings: SGR (ESC [ < b ; x ; y M|m), and the legacy form
871
- // (ESC [ M then three bytes offset by 32) for terminals that ignore 1006.
872
- const mouse = /\x1b\[<(\d+);(\d+);(\d+)([Mm])|\x1b\[M([\s\S])([\s\S])([\s\S])/g;
873
- let match;
874
-
875
- while ((match = mouse.exec(chunk)) !== null) {
876
- rest += chunk.slice(index, match.index);
877
- index = match.index + match[0].length;
878
- if (match[1] !== undefined) {
879
- this.onMouse(Number(match[1]), Number(match[2]), Number(match[3]), match[4]);
880
- } else {
881
- this.onMouse(
882
- match[5].charCodeAt(0) - 32,
883
- match[6].charCodeAt(0) - 32,
884
- match[7].charCodeAt(0) - 32,
885
- 'M'
886
- );
887
- }
888
- }
889
- rest += chunk.slice(index);
890
-
891
- for (const key of splitKeys(rest)) this.onKey(key);
892
- }
893
-
894
- onMouse(button, col, row, press) {
895
- // Wheel reports set bit 6; bit 0 says which way.
896
- if (button >= 64) {
897
- this.scrollBy(button % 2 === 0 ? 3 : -3);
898
- return;
899
- }
900
- if (press !== 'M' || button !== 0) return;
901
- // The mode chip, at the left of the bottom row.
902
- if (row === this.rows - 1 && col >= 2 && col <= this.chipTo) this.toggleMode();
903
- }
904
-
905
- onKey(key) {
906
- // An open picker owns the keyboard until it closes.
907
- if (this.picker) {
908
- const last = this.picker.items.length - 1;
909
- if (key === `${ESC}[A`) { this.picker.index = Math.max(0, this.picker.index - 1); this.render(); return; }
910
- if (key === `${ESC}[B`) { this.picker.index = Math.min(last, this.picker.index + 1); this.render(); return; }
911
- if (key === '\r' || key === '\n') { this.closePicker(this.picker.index); return; }
912
- if (key === ESC || key === '\x03') { this.closePicker(null); return; }
913
- return;
914
- }
915
-
916
- switch (key) {
917
- case '\r':
918
- case '\n': {
919
- const text = this.buffer;
920
- this.buffer = '';
921
- this.cursor = 0;
922
- this.historyIndex = -1;
923
- if (text.trim()) {
924
- this.history.unshift(text);
925
- // Answers to a y/N or a numbered pick are not messages, so they are
926
- // not echoed: the prompt reports its own outcome.
927
- if (!this.pendingPrompt) this.userMessage(text);
928
- }
929
- this.render();
930
- this.submit(text);
931
- return;
932
- }
933
-
934
- case '\x7f': // backspace
935
- case '\b':
936
- if (this.cursor > 0) {
937
- this.buffer = this.buffer.slice(0, this.cursor - 1) + this.buffer.slice(this.cursor);
938
- this.cursor--;
939
- }
940
- break;
941
-
942
- case '\x03': // ctrl+c
943
- if (this.status.busy && this.onInterrupt) this.onInterrupt();
944
- else { this.buffer = ''; this.cursor = 0; }
945
- break;
946
-
947
- case '\x04': // ctrl+d
948
- this.close();
949
- return;
950
-
951
- case '\x02': // ctrl+b — swap plan and build
952
- this.toggleMode();
953
- return;
954
-
955
- case '\x15': // ctrl+u — clear the line
956
- this.buffer = this.buffer.slice(this.cursor);
957
- this.cursor = 0;
958
- break;
959
-
960
- case ESC: // esc — stop the turn in flight
961
- if (this.onInterrupt) this.onInterrupt();
962
- return;
963
-
964
- case '\t': {
965
- const hit = COMMANDS.find((c) => c.startsWith(this.buffer));
966
- if (hit) { this.buffer = hit; this.cursor = hit.length; }
967
- break;
968
- }
969
-
970
- // With an empty line the arrows scroll the conversation; once there is
971
- // something typed they walk history. Terminals often swallow PgUp and
972
- // PgDn for their own scrollback, so this is the path that always works.
973
- case `${ESC}[A`:
974
- if (!this.buffer) { this.scrollBy(2); return; }
975
- if (this.history.length) {
976
- this.historyIndex = Math.min(this.historyIndex + 1, this.history.length - 1);
977
- this.buffer = this.history[this.historyIndex] ?? '';
978
- this.cursor = this.buffer.length;
979
- }
980
- break;
981
-
982
- case `${ESC}[B`:
983
- if (!this.buffer) { this.scrollBy(-2); return; }
984
- this.historyIndex = Math.max(this.historyIndex - 1, -1);
985
- this.buffer = this.historyIndex === -1 ? '' : (this.history[this.historyIndex] ?? '');
986
- this.cursor = this.buffer.length;
987
- break;
988
-
989
- case `${ESC}[1;5A`: this.scrollBy(2); return; // ctrl+up
990
- case `${ESC}[1;5B`: this.scrollBy(-2); return; // ctrl+down
991
- case `${ESC}[5~`: this.scrollBy(this.viewportHeight()); return;
992
- case `${ESC}[6~`: this.scrollBy(-this.viewportHeight()); return;
993
-
994
- case `${ESC}[H`: this.scrollBy(this.lines.length); return;
995
- case `${ESC}[F`: this.scroll = 0; this.render(); return;
996
-
997
- case `${ESC}[C`: this.cursor = Math.min(this.cursor + 1, this.buffer.length); break;
998
- case `${ESC}[D`: this.cursor = Math.max(this.cursor - 1, 0); break;
999
-
1000
- default:
1001
- if (key >= ' ' && !key.startsWith(ESC)) {
1002
- this.buffer = this.buffer.slice(0, this.cursor) + key + this.buffer.slice(this.cursor);
1003
- this.cursor += key.length;
1004
- } else {
1005
- return;
1006
- }
1007
- }
1008
-
1009
- this.render();
1010
- }
1011
-
1012
- // -- painting ------------------------------------------------------------
1013
-
1014
- render() {
1015
- if (this.closed) return;
1016
-
1017
- const width = this.width();
1018
- const height = this.viewportHeight();
1019
-
1020
- const end = Math.max(0, this.lines.length - this.scroll);
1021
- const start = Math.max(0, end - height);
1022
- const window = this.picker ? this.pickerLines(height) : this.lines.slice(start, end);
1023
- while (window.length < height) window.push('');
1024
-
1025
- const frame = [
1026
- ...this.headerLines(),
1027
- '',
1028
- ...window,
1029
- // Always one clear row between the last thing said and the box you type
1030
- // in. Without it the newest line of output sits against the border and
1031
- // reads as part of the input rather than as the answer above it.
1032
- '',
1033
- ...this.inputBox(),
1034
- ];
1035
-
1036
- // The cursor is hidden for the duration of the paint. Without this it is
1037
- // dragged through every line as the frame is written, which shows up as a
1038
- // dot flickering above the input box on every keystroke.
1039
- const out = [HIDE, HOME];
1040
- for (let i = 0; i < this.rows; i++) {
1041
- out.push(CLEAR_LINE + padVis(frame[i] ?? '', width) + (i === this.rows - 1 ? '' : '\n'));
1042
- }
1043
-
1044
- const [row, col] = this.caret();
1045
- out.push(at(row, col) + SHOW);
1046
- this.output.write(out.join(''));
1047
- }
1048
-
1049
- /**
1050
- * Where the typing caret belongs, 1-based.
1051
- *
1052
- * Column three is the first character inside the box: border, a space of
1053
- * padding, then the text.
1054
- */
1055
- caret() {
1056
- const { rows, prefix, width } = this.inputLines();
1057
- const index = prefix.length + this.cursor;
1058
- const row = Math.min(Math.floor(index / width), rows.length - 1);
1059
- const col = 3 + (index % width);
1060
- // Counting up from the bottom: the box border is the last row, the status
1061
- // row is above it, then the blank row, then the typed lines.
1062
- const firstRow = this.rows - 2 - rows.length;
1063
- return [firstRow + row, col];
1064
- }
1065
- }
1066
-
1067
- /**
1068
- * Split a raw stdin chunk into keys, keeping escape sequences whole.
1069
- *
1070
- * Application cursor key mode (DECCKM) makes a terminal send ESC O A for the
1071
- * up arrow rather than ESC [ A. Both are normalised to the bracket form here
1072
- * so the key handler only ever sees one of them.
1073
- */
1074
- export function splitKeys(chunk) {
1075
- const keys = [];
1076
- let i = 0;
1077
-
1078
- while (i < chunk.length) {
1079
- const c = chunk[i];
1080
- if (c !== ESC) { keys.push(c); i++; continue; }
1081
-
1082
- const rest = chunk.slice(i);
1083
- const csi = /^\x1b\[[0-9;?]*[A-Za-z~]/.exec(rest);
1084
- if (csi) { keys.push(csi[0]); i += csi[0].length; continue; }
1085
-
1086
- const ss3 = /^\x1bO([A-Za-z])/.exec(rest);
1087
- if (ss3) { keys.push(`${ESC}[${ss3[1]}`); i += ss3[0].length; continue; }
1088
-
1089
- keys.push(ESC);
1090
- i++;
1091
- }
1092
-
1093
- return keys;
1094
- }
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,
43
+ } from './theme.js';
44
+ import { renderer, render, polish } from './markdown.js';
45
+ import { VERSION } from '../core/version.js';
46
+
47
+ /**
48
+ * One line of narration, in the model's own words: "Reading screen.js".
49
+ * Anything longer than this is prose, and prose belongs in the answer.
50
+ */
51
+ export const MAX_LABEL = 120;
52
+
53
+ export function isLabel(text) {
54
+ const t = String(text ?? '').trim();
55
+ return t.length > 0 && t.length <= MAX_LABEL && !t.includes('\n');
56
+ }
57
+
58
+ export const COMMANDS = [
59
+ '/help', '/model', '/models', '/session', '/sessions', '/resume',
60
+ '/new', '/skills', '/clear', '/search', '/copy', '/exit',
61
+ ];
62
+
63
+ // ANSI ----------------------------------------------------------------------
64
+ const ESC = '\x1b';
65
+ const ALT_ON = `${ESC}[?1049h`;
66
+ const ALT_OFF = `${ESC}[?1049l`;
67
+
68
+ /**
69
+ * Mouse setup, decided by measurement rather than by documentation.
70
+ *
71
+ * 1007 is alternate scroll: inside the alternate screen the terminal turns
72
+ * wheel events into arrow keys. On Windows that is the only way a wheel ever
73
+ * reaches the program, because ConPTY forwards no mouse input at all — a probe
74
+ * that enabled every tracking mode received nothing from a scroll.
75
+ *
76
+ * And mouse tracking suppresses alternate scroll. So on Windows tracking is
77
+ * deliberately not requested: it delivers nothing there, and asking for it
78
+ * would cost the wheel. Elsewhere tracking works, so the mode chip is
79
+ * clickable on those platforms.
80
+ */
81
+ const TRACK = process.platform === 'win32'
82
+ ? '' : `${ESC}[?1000h${ESC}[?1002h${ESC}[?1015h${ESC}[?1006h`;
83
+ const UNTRACK = process.platform === 'win32'
84
+ ? '' : `${ESC}[?1006l${ESC}[?1015l${ESC}[?1002l${ESC}[?1000l`;
85
+
86
+ const MOUSE_ON = `${ESC}[?1007h${TRACK}`;
87
+ const MOUSE_OFF = `${UNTRACK}${ESC}[?1007l`;
88
+ const HIDE = `${ESC}[?25l`;
89
+ const SHOW = `${ESC}[?25h`;
90
+ const HOME = `${ESC}[H`;
91
+ const CLEAR_LINE = `${ESC}[K`;
92
+ const at = (row, col) => `${ESC}[${row};${col}H`;
93
+ const title = (t) => `${ESC}]0;${t}\x07`;
94
+
95
+ /**
96
+ * Fixed rows below the header: the gap under it, the gap above the input box,
97
+ * the input box's two borders, the blank row inside it, and the status row.
98
+ */
99
+ const CHROME_BELOW = 6;
100
+
101
+ /** The wordmark only earns its place with room for the facts column beside it. */
102
+ const WORDMARK_NEEDS = BANNER_WIDTH + 30;
103
+
104
+ /** Where the U ends and CODE begins in each row of the wordmark. */
105
+ const WORDMARK_SPLIT = 9;
106
+
107
+ /** What the empty input box says before anything is typed. */
108
+ const PLACEHOLDER = 'Ask anything…';
109
+
110
+ export class Screen {
111
+ constructor({ cwd, input = process.stdin, output = process.stdout } = {}) {
112
+ this.cwd = cwd;
113
+ this.input = input;
114
+ this.output = output;
115
+
116
+ this.lines = []; // the rendered transcript
117
+ this.scroll = 0; // rows scrolled up from the bottom
118
+ this.buffer = ''; // what is being typed
119
+ this.cursor = 0;
120
+ this.history = [];
121
+ this.historyIndex = -1;
122
+
123
+ this.status = { busy: false, text: '', frame: 0, since: 0 };
124
+ this.facts = {};
125
+ this.model = '';
126
+
127
+ this.waiters = [];
128
+ this.queue = [];
129
+ this.closed = false;
130
+
131
+ // 'build' may edit and run; 'plan' is read-only. Ctrl+B swaps them, and
132
+ // the chip is clickable wherever the terminal forwards clicks.
133
+ this.mode = 'build';
134
+ this.chipTo = 0;
135
+ this.onInterrupt = null;
136
+ this.onModeChange = null;
137
+ this.spinTimer = null;
138
+ this.pendingPrompt = null;
139
+
140
+ this.cols = output.columns || 80;
141
+ this.rows = output.rows || 24;
142
+ this.md = renderer(this.width());
143
+ }
144
+
145
+ // -- lifecycle -----------------------------------------------------------
146
+
147
+ async start() {
148
+ ensureColour(this.output);
149
+ this.output.write(ALT_ON + MOUSE_ON + HIDE + title(`ucode — ${path.basename(this.cwd)}`));
150
+ this.input.setRawMode?.(true);
151
+ this.input.resume();
152
+ this.input.setEncoding('utf8');
153
+ this.input.on('data', (chunk) => this.onData(chunk));
154
+
155
+ this.onResize = () => {
156
+ this.cols = this.output.columns || 80;
157
+ this.rows = this.output.rows || 24;
158
+ this.md = renderer(this.width());
159
+ this.render();
160
+ };
161
+ this.output.on('resize', this.onResize);
162
+
163
+ this.render();
164
+ }
165
+
166
+ stop() {
167
+ this.stopSpinner();
168
+ this.output.off?.('resize', this.onResize);
169
+ this.input.setRawMode?.(false);
170
+ this.input.pause();
171
+ this.output.write(MOUSE_OFF + ALT_OFF + SHOW);
172
+ }
173
+
174
+ close() {
175
+ if (this.closed) return;
176
+ this.closed = true;
177
+ this.stop();
178
+ while (this.waiters.length) this.waiters.shift()(null);
179
+ }
180
+
181
+ width() {
182
+ return Math.max(30, this.cols);
183
+ }
184
+
185
+ /** Usable width inside a box: two borders and a space of padding each side. */
186
+ inner() {
187
+ return Math.max(8, this.width() - 4);
188
+ }
189
+
190
+ // -- transcript ----------------------------------------------------------
191
+
192
+ /**
193
+ * Append without painting.
194
+ *
195
+ * Anything replacing a region of the transcript has to build the whole
196
+ * region and then render once. Painting between the delete and the re-add
197
+ * puts a frame on screen with the text missing, and at streaming speed that
198
+ * reads as flicker.
199
+ */
200
+ add(text = '') {
201
+ const width = this.width();
202
+ for (const raw of String(text).split('\n')) {
203
+ if (visLen(raw) <= width) this.lines.push(raw);
204
+ else for (const wrapped of wrapAnsi(raw, width)) this.lines.push(wrapped);
205
+ }
206
+ this.scroll = 0; // new output snaps back to the bottom
207
+ }
208
+
209
+ push(text = '') {
210
+ this.add(text);
211
+ this.soon();
212
+ }
213
+
214
+ /**
215
+ * Collapse a burst of pushes into one frame.
216
+ *
217
+ * Printing a list one line at a time repaints the screen per line — a model
218
+ * list of fifty entries drew a hundred frames back to back, which is visible
219
+ * as a cascade. A microtask runs before any I/O, so everything pushed in one
220
+ * synchronous stretch becomes a single render, while a push after an await
221
+ * still paints immediately.
222
+ */
223
+ soon() {
224
+ if (this.queued) return;
225
+ this.queued = true;
226
+ queueMicrotask(() => {
227
+ this.queued = false;
228
+ this.render();
229
+ });
230
+ }
231
+
232
+ write(text = '') { this.push(text); }
233
+ blank() { this.push(''); }
234
+ note(text) { this.push(dim(` ${text}`)); }
235
+
236
+ clearScreen() {
237
+ this.lines = [];
238
+ this.scroll = 0;
239
+ this.render();
240
+ }
241
+
242
+ assistant(text) {
243
+ if (!text?.trim()) return;
244
+ this.add('');
245
+ this.add(render(this.md, text));
246
+ this.add('');
247
+ this.render();
248
+ }
249
+
250
+ /**
251
+ * Something the user said, in the conversation, in the same blue box as the
252
+ * input it was typed into.
253
+ *
254
+ * A long session is mostly the agent's output tool calls, diffs, answers.
255
+ * Your own messages are the landmarks you scroll back looking for, so they
256
+ * get the frame: every one of them is findable at a glance, and the box
257
+ * matches the one below so it is plain where each came from.
258
+ */
259
+ userMessage(text) {
260
+ const width = this.width();
261
+ const room = Math.max(8, width - 6); // borders, padding, and the caret column
262
+
263
+ const rows = [];
264
+ for (const paragraph of String(text).replace(/\r/g, '').split('\n')) {
265
+ for (const line of wrapAnsi(paragraph, room)) rows.push(line);
266
+ }
267
+
268
+ this.add('');
269
+ this.add(boxTop(width, edge));
270
+ rows.forEach((row, i) => {
271
+ const lead = i === 0 ? blue('›') : ' ';
272
+ this.add(boxRow(` ${lead} ${chalk.white(row)}`, width, edge));
273
+ });
274
+ this.add(boxBottom(width, edge));
275
+ this.render();
276
+ }
277
+
278
+ /**
279
+ * A tool call, as it happens: "● Listing src".
280
+ *
281
+ * This lives in the transcript rather than only on the status line. The
282
+ * status line overwrites itself and is empty by the end of the turn, so work
283
+ * announced only there scrolls past unseen — and the diff underneath ends up
284
+ * with nothing above it explaining where it came from.
285
+ */
286
+ toolCall(label) {
287
+ // U+25CF, not U+23FA: the latter carries emoji presentation, which Windows
288
+ // Terminal draws as a white circle on a blue tile.
289
+ this.push(`${blue('●')} ${asLabel(label)}`);
290
+ this.updateSpinner(label);
291
+ }
292
+
293
+ toolResult(summary) {
294
+ this.push(dim(` └ ${summary}`));
295
+ }
296
+
297
+ toolFailed(summary) {
298
+ this.push(`${dim(' └ ')}${theme.error(summary)}`);
299
+ }
300
+
301
+ /**
302
+ * The change itself, under the result.
303
+ *
304
+ * A line-number gutter, then the sign and the code tinted right across the
305
+ * row. The numbers are the point: a diff you cannot navigate from is a
306
+ * picture of a change rather than a record of one.
307
+ */
308
+ diff(lines) {
309
+ const gutter = 6;
310
+ // Two spaces of indent, the gutter, one space, then the tint fills the
311
+ // rest. One column over and every row wraps, splitting the whole diff.
312
+ const room = Math.max(12, this.width() - gutter - 3);
313
+
314
+ for (const line of lines) {
315
+ // A file heading in a multi-file write.
316
+ if (line.startsWith('~')) {
317
+ this.add(` ${dim(' '.repeat(gutter))} ${sky(line.slice(1))}`);
318
+ continue;
319
+ }
320
+
321
+ const added = line.startsWith('+');
322
+ const rest = line.slice(1);
323
+ // Tools emit "<line>| <text>". A row with no number is the "12 more
324
+ // lines" note, which is not part of the change, so it stays dim.
325
+ const parsed = /^(\d+)\|\s?([\s\S]*)$/.exec(rest);
326
+ if (!parsed) {
327
+ this.add(` ${dim(' '.repeat(gutter))} ${dim(rest)}`);
328
+ continue;
329
+ }
330
+
331
+ const [, number, body] = parsed;
332
+ const tint = added ? ADDED : REMOVED;
333
+ this.add(
334
+ ` ${dim(number.padStart(gutter))} ` +
335
+ // Tabs would leave the tint ending short of the row, so they widen.
336
+ tint(padVis(clip(`${added ? '+' : '-'} ${body.replace(/\t/g, ' ')}`, room), room))
337
+ );
338
+ }
339
+ this.render(); // a sixteen-line diff is one frame, not sixteen
340
+ }
341
+
342
+ /** Captured output under a command, dimmed so it reads as evidence. */
343
+ commandOutput(lines) {
344
+ for (const line of lines) this.add(` ${dim(line)}`);
345
+ this.render();
346
+ }
347
+
348
+ /**
349
+ * A running command's output, live — on the status line and nowhere else.
350
+ *
351
+ * Only the newest line, gone as soon as the next arrives. Appending each one
352
+ * instead would mean a test run leaving sixty lines of "ok" in the
353
+ * conversation permanently, which is noise the moment it scrolls. What
354
+ * survives a command is decided when it ends: nothing if it worked, the tail
355
+ * if it did not.
356
+ */
357
+ progress(lines) {
358
+ const last = lines[lines.length - 1]?.trim();
359
+ if (last) this.updateSpinner(last);
360
+ }
361
+
362
+ /**
363
+ * The model's own account of the step it is taking, before it takes it.
364
+ *
365
+ * Not called status(): `this.status` holds the spinner state, and a method
366
+ * of the same name would be shadowed by it on every instance.
367
+ */
368
+ narrate(text) {
369
+ const line = asLabel(text);
370
+ if (!line) return;
371
+ this.push(dim(` ⋮ ${clip(line, this.width() - 6)}`));
372
+ this.updateSpinner(line);
373
+ }
374
+
375
+ // -- streaming -----------------------------------------------------------
376
+ // Deltas appear as plain text as they arrive, then get replaced in place by
377
+ // properly rendered markdown once the reply is complete.
378
+
379
+ streamBegin() {
380
+ this.stopSpinner();
381
+ this.streamAt = this.lines.length;
382
+ this.streamBuf = '';
383
+ this.streamPainted = 0;
384
+ }
385
+
386
+ streamDelta(delta) {
387
+ if (this.streamAt === undefined) this.streamBegin();
388
+ this.streamBuf += delta;
389
+ const now = Date.now();
390
+ if (now - this.streamPainted < 60) return; // about 16fps is plenty
391
+ this.streamPainted = now;
392
+ this.repaintStream();
393
+ }
394
+
395
+ /**
396
+ * Repaint the partial reply.
397
+ *
398
+ * polish() runs on the partial text so bold, inline code and bullets are
399
+ * already styled while it streams. Without it the text arrives raw and then
400
+ * visibly re-renders at the end, which reads as a glitch.
401
+ */
402
+ repaintStream() {
403
+ this.lines.length = this.streamAt;
404
+ this.add('');
405
+ this.add(polish(this.streamBuf));
406
+ this.render(); // one frame, and never one without the reply in it
407
+ }
408
+
409
+ /**
410
+ * Finish a streamed reply.
411
+ *
412
+ * `asLabel` says the text turned out to be narration ahead of a tool call
413
+ * rather than an answer, in which case one short line folds down into the
414
+ * status line it was always meant to be.
415
+ */
416
+ streamEnd({ asNarration = false } = {}) {
417
+ if (this.streamAt === undefined) return '';
418
+ const text = this.streamBuf;
419
+ this.lines.length = this.streamAt;
420
+ this.streamAt = undefined;
421
+ this.streamBuf = '';
422
+
423
+ if (asNarration && isLabel(text)) this.narrate(text);
424
+ else if (text.trim()) this.assistant(text);
425
+ else this.render();
426
+ return text;
427
+ }
428
+
429
+ // -- thinking ------------------------------------------------------------
430
+ // A reasoning model does all its working before it says anything. None of it
431
+ // is printed: it is long, repetitive, and guesses drawn from it read worse
432
+ // than silence. The spinner counts the seconds so the wait is visibly alive,
433
+ // and the transcript gets one line afterwards saying how long it took.
434
+
435
+ thinkingDelta() {
436
+ if (this.thoughtSince === undefined) this.thoughtSince = Date.now();
437
+ }
438
+
439
+ thinkingEnd() {
440
+ if (this.thoughtSince === undefined) return;
441
+ const seconds = Math.round((Date.now() - this.thoughtSince) / 1000);
442
+ if (seconds >= 2) this.push(dim(` ⋮ thought for ${seconds}s`));
443
+ this.thoughtSince = undefined;
444
+ }
445
+
446
+ error(err, { debug = false } = {}) {
447
+ const known = err && typeof err === 'object' && err.attempted;
448
+ this.push('');
449
+ if (known) {
450
+ this.push(`${theme.error('')} ${chalk.white(`Failed while ${err.attempted}.`)}`);
451
+ this.push(` ${err.failed}`);
452
+ if (err.fix) this.push(` ${blue('→')} ${err.fix}`);
453
+ if (err.kind) this.push(dim(` (${err.kind})`));
454
+ } else {
455
+ this.push(`${theme.error('✗')} ${chalk.white('Something broke inside ucode.')}`);
456
+ this.push(` ${err?.message ?? String(err)}`);
457
+ this.push(` ${blue('→')} That is a bug in ucode rather than in your project. Re-run with --debug.`);
458
+ }
459
+ if (debug) {
460
+ const stack = (known && err.cause?.stack) || err?.stack;
461
+ if (stack) this.push(dim(stack));
462
+ }
463
+ this.push('');
464
+ }
465
+
466
+ // -- header --------------------------------------------------------------
467
+
468
+ setFacts(facts) {
469
+ this.facts = { ...this.facts, ...facts };
470
+ if (facts.model) this.model = facts.model;
471
+ this.render();
472
+ }
473
+
474
+ /** Same shape as the plain UI's header(), so the loop needs no branch. */
475
+ header({ cwd, model, used, limit, title: sessionTitle }) {
476
+ this.setFacts({
477
+ cwd,
478
+ model,
479
+ title: sessionTitle,
480
+ percent: limit > 0 ? Math.min(100, Math.round((used / limit) * 100)) : 0,
481
+ });
482
+ }
483
+
484
+ /**
485
+ * How many rows the header box occupies.
486
+ *
487
+ * The frame has to be exactly as tall as the terminal or every row below the
488
+ * shortfall is off by that much — including the one the caret is parked on.
489
+ * So this is derived, never assumed.
490
+ */
491
+ headerHeight() {
492
+ return this.width() >= WORDMARK_NEEDS ? BANNER.length + 2 : 5;
493
+ }
494
+
495
+ headerLines() {
496
+ const width = this.width();
497
+ const inner = width - 2; // between the borders
498
+
499
+ if (width < WORDMARK_NEEDS) {
500
+ // Too narrow for the wordmark: stack it rather than wrap it into noise.
501
+ const rows = [
502
+ ` ${blue.bold('U C O D E')} ${dim('terminal coding agent')}`,
503
+ ` ${dim('dir'.padEnd(8))}${chalk.white(clip(shortenPath(this.facts.cwd ?? this.cwd, inner - 12), inner - 12))}`,
504
+ ];
505
+ return [boxTop(width), ...rows.map((r) => boxRow(r, width)), boxBottom(width)];
506
+ }
507
+
508
+ // Two spaces of padding, the wordmark, a gap, then the facts column.
509
+ //
510
+ // Only what you cannot work out by looking: where you are, and how to get
511
+ // help. How full the window is belongs on the status row next to the model
512
+ // it describes, and the session title is already the terminal's own window
513
+ // title — repeating either here is a second place to keep in sync for no
514
+ // reader who needed it.
515
+ const room = Math.max(8, inner - BANNER_WIDTH - 6);
516
+ const facts = [
517
+ ['dir', shortenPath(this.facts.cwd ?? this.cwd, room - 9)],
518
+ ['keys', '/help · esc interrupts'],
519
+ ['', ''],
520
+ ['', ''],
521
+ ['', ''],
522
+ ['', 'made with ❤️ by om dixit'],
523
+ ];
524
+
525
+ const rows = BANNER.map((art, i) => {
526
+ const [label, value] = facts[i] ?? ['', ''];
527
+ const right = label
528
+ ? `${dim(label.padEnd(9))}${chalk.white(clip(value, room - 9))}`
529
+ : (value ? dim(value) : '');
530
+ return ` ${blue(art)} ${right}`;
531
+ });
532
+
533
+ return [boxTop(width), ...rows.map((r) => boxRow(r, width)), boxBottom(width)];
534
+ }
535
+
536
+ // -- input box -----------------------------------------------------------
537
+
538
+ /** The typed line, wrapped to the inside of a box `width` characters across. */
539
+ inputLines(width = this.inner()) {
540
+ const prefix = this.pendingPrompt ? `${this.pendingPrompt} ` : '› ';
541
+ const full = prefix + this.buffer;
542
+
543
+ const rows = [];
544
+ for (let i = 0; i < full.length; i += width) rows.push(full.slice(i, i + width));
545
+ if (rows.length === 0) rows.push(prefix);
546
+
547
+ return { rows, prefix, width };
548
+ }
549
+
550
+ viewportHeight() {
551
+ return Math.max(
552
+ 3,
553
+ this.rows - this.headerHeight() - CHROME_BELOW - this.inputLines().rows.length
554
+ );
555
+ }
556
+
557
+ /**
558
+ * The input box: what you are typing, and directly under it, inside the same
559
+ * border, the three things worth knowing while you type.
560
+ *
561
+ * The status used to sit outside the box on the last row of the screen,
562
+ * which made it a separate object floating under the input. Inside the
563
+ * border it reads as part of the thing you are using — the box says "this is
564
+ * where you work", and the row underneath says what you are working with.
565
+ */
566
+ inputBox(width = this.width()) {
567
+ const { rows } = this.inputLines(width - 4);
568
+ // Nothing typed yet: a quiet prompt where the text will go. The caret sits
569
+ // on its first letter and typing replaces it.
570
+ const empty = !this.buffer && !this.pendingPrompt;
571
+ const painted = rows.map((row, i) =>
572
+ i === 0
573
+ ? boxRow(` ${blue('›')}${empty ? ` ${dim(PLACEHOLDER)}` : row.slice(1)}`, width, edge)
574
+ : boxRow(` ${row}`, width, edge)
575
+ );
576
+ return [
577
+ boxTop(width, edge),
578
+ ...painted,
579
+ // A blank row between the two. Sitting directly under the caret, the
580
+ // status read as a second line of the thing being typed; one row of air
581
+ // separates what you are writing from what you are writing it with.
582
+ boxRow('', width, edge),
583
+ boxRow(this.statusRow(width), width, edge),
584
+ boxBottom(width, edge),
585
+ ];
586
+ }
587
+
588
+ // -- status row ----------------------------------------------------------
589
+
590
+ modeChip() {
591
+ return this.mode === 'plan' ? `${sky('◇')} ${sky('Plan')}` : `${blue('◆')} ${blue('Build')}`;
592
+ }
593
+
594
+ /**
595
+ * How full the context window is, as a bare number.
596
+ *
597
+ * It turns amber at 75% because that is where turns start being folded away
598
+ * into a summary — the one moment the number predicts something you would
599
+ * want to know before it happens.
600
+ */
601
+ percentChip() {
602
+ const percent = Math.round(this.facts.percent ?? 0);
603
+ return percent >= 75 ? theme.warn(`${percent}%`) : dim(`${percent}%`);
604
+ }
605
+
606
+ /**
607
+ * Which mode is live, which model is answering, and how full the window is.
608
+ *
609
+ * Nothing else earns a place. The provider name was there and was cut: it is
610
+ * the same on every line of every session, so it was decoration that had to
611
+ * be read past to reach the two things that do change.
612
+ *
613
+ * The middle is borrowed while something is running, for the spinner and the
614
+ * way out of it, and handed straight back when it finishes.
615
+ */
616
+ statusRow(width = this.width()) {
617
+ const inner = width - 2; // the space between the two borders
618
+ const chip = this.modeChip();
619
+ const left = ` ${chip} ${dim('·')} ${chalk.white(this.model || '—')}`;
620
+ const right = `${this.percentChip()} `;
621
+
622
+ // Where a click on the bottom row still counts as hitting the mode chip.
623
+ this.chipTo = 2 + visLen(chip);
624
+
625
+ const between = Math.max(1, inner - visLen(left) - visLen(right));
626
+
627
+ let middle = '';
628
+ if (this.flashText) {
629
+ middle = dim(clip(this.flashText, between - 2));
630
+ } else if (this.status.busy) {
631
+ const frame = blue(SPINNER[this.status.frame]);
632
+ const secs = Math.round((Date.now() - (this.status.since || Date.now())) / 1000);
633
+ const elapsed = secs >= 2 ? dim(` ${secs}s`) : '';
634
+ const room = between - 20;
635
+ middle = room > 8
636
+ ? `${frame} ${dim(clip(this.status.text, room))}${elapsed} ${dim('esc to stop')}`
637
+ : `${frame}${elapsed}`;
638
+ }
639
+
640
+ // The percentage is pinned to the right border whatever is in the middle,
641
+ // with a gap kept in front of it so a long spinner label cannot run into
642
+ // the number and read as part of it.
643
+ const tail = middle ? `${middle} ` : '';
644
+ const pad = Math.max(1, inner - visLen(left) - visLen(tail) - visLen(right));
645
+ return padVis(left + ' '.repeat(pad) + tail + right, inner);
646
+ }
647
+
648
+ /**
649
+ * Repaint only the status row, leaving the caret where the user left it.
650
+ *
651
+ * It is the second row from the bottom now — the box's own border is below
652
+ * it — so the row is written with its borders rather than as a bare line.
653
+ */
654
+ paintStatus() {
655
+ if (this.closed) return;
656
+ // On the start screen the status row is mid-screen, not second from the
657
+ // bottom, so the cheap single-row repaint would draw it in the wrong place.
658
+ if (this.welcoming()) {
659
+ this.render();
660
+ return;
661
+ }
662
+ const [row, col] = this.caret();
663
+ this.output.write(
664
+ HIDE +
665
+ at(this.rows - 1, 1) + CLEAR_LINE + boxRow(this.statusRow(), this.width(), edge) +
666
+ at(row, col) + SHOW
667
+ );
668
+ }
669
+
670
+ toggleMode() {
671
+ this.mode = this.mode === 'plan' ? 'build' : 'plan';
672
+ this.flash(this.mode === 'plan'
673
+ ? 'plan mode — reads and researches, changes nothing'
674
+ : 'build mode — free to edit files and run commands');
675
+ this.onModeChange?.(this.mode);
676
+ this.render();
677
+ }
678
+
679
+ /** A message on the status line that fades on its own. */
680
+ flash(text) {
681
+ this.flashText = text;
682
+ clearTimeout(this.flashTimer);
683
+ this.flashTimer = setTimeout(() => {
684
+ this.flashText = null;
685
+ this.paintStatus();
686
+ }, 2500);
687
+ this.flashTimer.unref?.();
688
+ this.paintStatus();
689
+ }
690
+
691
+ // -- spinner -------------------------------------------------------------
692
+
693
+ startSpinner(text = 'thinking') {
694
+ // `since` is what makes a long think legible: the label may not change for
695
+ // a minute, so the seconds beside it are the proof it is still alive.
696
+ this.status = { busy: true, text: asLabel(text), frame: 0, since: Date.now() };
697
+ if (!this.spinTimer) {
698
+ this.spinTimer = setInterval(() => {
699
+ this.status.frame = (this.status.frame + 1) % SPINNER.length;
700
+ this.paintStatus();
701
+ }, 80);
702
+ this.spinTimer.unref?.();
703
+ }
704
+ this.paintStatus();
705
+ }
706
+
707
+ updateSpinner(text) {
708
+ if (!this.status.busy) return;
709
+ this.status.text = asLabel(text);
710
+ this.paintStatus();
711
+ }
712
+
713
+ stopSpinner() {
714
+ if (this.spinTimer) {
715
+ clearInterval(this.spinTimer);
716
+ this.spinTimer = null;
717
+ }
718
+ if (this.status.busy) {
719
+ this.status = { busy: false, text: '', frame: 0, since: 0 };
720
+ this.paintStatus();
721
+ }
722
+ }
723
+
724
+ // -- input ---------------------------------------------------------------
725
+
726
+ nextLine() {
727
+ if (this.queue.length) return Promise.resolve(this.queue.shift());
728
+ if (this.closed) return Promise.resolve(null);
729
+ return new Promise((resolve) => this.waiters.push(resolve));
730
+ }
731
+
732
+ ask() {
733
+ return this.nextLine();
734
+ }
735
+
736
+ submit(text) {
737
+ const waiter = this.waiters.shift();
738
+ if (waiter) waiter(text);
739
+ else this.queue.push(text);
740
+ }
741
+
742
+ /** y/n, answered on the input line. */
743
+ confirm({ action, detail, risk }) {
744
+ this.push('');
745
+ this.push(`${chalk.inverse(theme.warn(risk === 'command' ? ' shell ' : ' outside project '))} ${chalk.white(action)}`);
746
+ for (const line of String(detail ?? '').split('\n')) {
747
+ if (line) this.push(dim(` ${line}`));
748
+ }
749
+
750
+ this.pendingPrompt = 'go ahead? [y/N]';
751
+ this.render();
752
+
753
+ return this.nextLine().then((answer) => {
754
+ this.pendingPrompt = null;
755
+ // End of input counts as no. Never run something nobody approved.
756
+ const yes = /^(y|yes)$/i.test(String(answer ?? '').trim());
757
+ this.push(dim(yes ? ' approved' : ' declined'));
758
+ this.push('');
759
+ return yes;
760
+ });
761
+ }
762
+
763
+ /**
764
+ * A modal list: arrows move, Enter picks, Esc cancels.
765
+ *
766
+ * Only while this is open do the arrows stop scrolling the transcript. They
767
+ * cannot be given up permanently, because under alternate scroll the mouse
768
+ * wheel arrives as arrow keys.
769
+ */
770
+ pick(items, { active = 0, hint = 'enter to choose · esc to cancel' } = {}) {
771
+ this.picker = {
772
+ items,
773
+ index: Math.min(Math.max(0, active), Math.max(0, items.length - 1)),
774
+ hint,
775
+ };
776
+ this.render();
777
+ return new Promise((resolve) => { this.pickerResolve = resolve; });
778
+ }
779
+
780
+ closePicker(value) {
781
+ const resolve = this.pickerResolve;
782
+ this.picker = null;
783
+ this.pickerResolve = null;
784
+ this.render();
785
+ resolve?.(value);
786
+ }
787
+
788
+ /**
789
+ * Rows for an open picker, windowed so a long list still fits.
790
+ *
791
+ * An item may carry a `sub` line — a second, dimmer row underneath it. That
792
+ * is what lets a list of saved conversations show what each one was actually
793
+ * about instead of a column of near-identical titles.
794
+ */
795
+ pickerLines(height) {
796
+ const { items, index, hint } = this.picker;
797
+ const room = Math.max(1, height - 2);
798
+
799
+ // Rows per item, so the window can be sized in rows rather than in items.
800
+ const rowsFor = (item) => (typeof item !== 'string' && item.sub ? 2 : 1);
801
+ const perItem = items.map(rowsFor);
802
+
803
+ // Walk outward from the selection until the window is full. Starting from
804
+ // the selection guarantees it is on screen however long the list is.
805
+ let first = index;
806
+ let last = index;
807
+ let used = perItem[index] ?? 1;
808
+ while (used < room && (first > 0 || last < items.length - 1)) {
809
+ if (first > 0 && used + perItem[first - 1] <= room) { first--; used += perItem[first]; }
810
+ else if (last < items.length - 1 && used + perItem[last + 1] <= room) { last++; used += perItem[last]; }
811
+ else break;
812
+ }
813
+
814
+ const out = [];
815
+ for (let i = first; i <= last; i++) {
816
+ const item = items[i];
817
+ const body = typeof item === 'string' ? item : item.label;
818
+ out.push(i === index ? `${blue('❯')} ${chalk.bold.white(body)}` : ` ${dim(body)}`);
819
+ if (typeof item !== 'string' && item.sub) out.push(` ${item.sub}`);
820
+ }
821
+
822
+ out.push('');
823
+ out.push(dim(` ${hint}`));
824
+ return out;
825
+ }
826
+
827
+ /** A numbered list, answered on the input line. */
828
+ async choose(prompt, items, { allowNone = true } = {}) {
829
+ items.forEach((item, i) => this.push(` ${blue(String(i + 1).padStart(2))}. ${item}`));
830
+ if (allowNone) this.push(dim(' 0. none start fresh'));
831
+ this.push('');
832
+
833
+ this.pendingPrompt = prompt;
834
+ this.render();
835
+
836
+ const answer = await this.nextLine();
837
+ this.pendingPrompt = null;
838
+
839
+ const trimmed = String(answer ?? '').trim();
840
+ if (trimmed === '' || trimmed === '0') return null;
841
+
842
+ const index = Number(trimmed);
843
+ if (!Number.isInteger(index) || index < 1 || index > items.length) {
844
+ this.push(theme.warn(` "${trimmed}" is not one of 1-${items.length}.`));
845
+ return null;
846
+ }
847
+ return index - 1;
848
+ }
849
+
850
+ // -- keyboard and mouse --------------------------------------------------
851
+
852
+ /**
853
+ * Scroll the transcript, clamped at both ends.
854
+ *
855
+ * When there is nothing above the fold, say so. Silence is indistinguishable
856
+ * from broken input, and the difference matters: one means the conversation
857
+ * simply fits, the other means the terminal is not forwarding keys at all.
858
+ */
859
+ scrollBy(delta) {
860
+ const max = Math.max(0, this.lines.length - this.viewportHeight());
861
+ if (max === 0) {
862
+ this.flash('nothing above it all fits on screen');
863
+ return;
864
+ }
865
+ const before = this.scroll;
866
+ this.scroll = Math.min(Math.max(0, this.scroll + delta), max);
867
+ if (this.scroll === before && delta > 0) this.flash('already at the top');
868
+ this.render();
869
+ }
870
+
871
+ onData(chunk) {
872
+ // UCODE_DEBUG_KEYS=1 logs every byte the terminal sends to
873
+ // ~/.ucode/keys.log. Whether mouse reporting works at all depends on the
874
+ // terminal forwarding it; this is how to find out.
875
+ if (process.env.UCODE_DEBUG_KEYS) {
876
+ appendFile(path.join(homedir(), '.ucode', 'keys.log'), `${JSON.stringify(chunk)}\n`).catch(() => {});
877
+ }
878
+
879
+ // Pull mouse reports out of the chunk wherever they sit. Anchoring the
880
+ // match to the whole chunk meant a wheel event arriving alongside any
881
+ // other byte was silently treated as typing.
882
+ let rest = '';
883
+ let index = 0;
884
+ // Two encodings: SGR (ESC [ < b ; x ; y M|m), and the legacy form
885
+ // (ESC [ M then three bytes offset by 32) for terminals that ignore 1006.
886
+ const mouse = /\x1b\[<(\d+);(\d+);(\d+)([Mm])|\x1b\[M([\s\S])([\s\S])([\s\S])/g;
887
+ let match;
888
+
889
+ while ((match = mouse.exec(chunk)) !== null) {
890
+ rest += chunk.slice(index, match.index);
891
+ index = match.index + match[0].length;
892
+ if (match[1] !== undefined) {
893
+ this.onMouse(Number(match[1]), Number(match[2]), Number(match[3]), match[4]);
894
+ } else {
895
+ this.onMouse(
896
+ match[5].charCodeAt(0) - 32,
897
+ match[6].charCodeAt(0) - 32,
898
+ match[7].charCodeAt(0) - 32,
899
+ 'M'
900
+ );
901
+ }
902
+ }
903
+ rest += chunk.slice(index);
904
+
905
+ for (const key of splitKeys(rest)) this.onKey(key);
906
+ }
907
+
908
+ onMouse(button, col, row, press) {
909
+ // Wheel reports set bit 6; bit 0 says which way.
910
+ if (button >= 64) {
911
+ this.scrollBy(button % 2 === 0 ? 3 : -3);
912
+ return;
913
+ }
914
+ if (press !== 'M' || button !== 0) return;
915
+ if (this.welcoming()) {
916
+ const g = this.welcomeGeometry();
917
+ const statusRow = g.boxTop + g.inputRows + 3; // 1-based
918
+ if (row === statusRow && col > g.left + 1 && col <= g.left + this.chipTo) this.toggleMode();
919
+ return;
920
+ }
921
+ // The mode chip, at the left of the bottom row.
922
+ if (row === this.rows - 1 && col >= 2 && col <= this.chipTo) this.toggleMode();
923
+ }
924
+
925
+ onKey(key) {
926
+ // An open picker owns the keyboard until it closes.
927
+ if (this.picker) {
928
+ const last = this.picker.items.length - 1;
929
+ if (key === `${ESC}[A`) { this.picker.index = Math.max(0, this.picker.index - 1); this.render(); return; }
930
+ if (key === `${ESC}[B`) { this.picker.index = Math.min(last, this.picker.index + 1); this.render(); return; }
931
+ if (key === '\r' || key === '\n') { this.closePicker(this.picker.index); return; }
932
+ if (key === ESC || key === '\x03') { this.closePicker(null); return; }
933
+ return;
934
+ }
935
+
936
+ switch (key) {
937
+ case '\r':
938
+ case '\n': {
939
+ const text = this.buffer;
940
+ this.buffer = '';
941
+ this.cursor = 0;
942
+ this.historyIndex = -1;
943
+ if (text.trim()) {
944
+ this.history.unshift(text);
945
+ // Answers to a y/N or a numbered pick are not messages, so they are
946
+ // not echoed: the prompt reports its own outcome.
947
+ if (!this.pendingPrompt) this.userMessage(text);
948
+ }
949
+ this.render();
950
+ this.submit(text);
951
+ return;
952
+ }
953
+
954
+ case '\x7f': // backspace
955
+ case '\b':
956
+ if (this.cursor > 0) {
957
+ this.buffer = this.buffer.slice(0, this.cursor - 1) + this.buffer.slice(this.cursor);
958
+ this.cursor--;
959
+ }
960
+ break;
961
+
962
+ case '\x03': // ctrl+c
963
+ if (this.status.busy && this.onInterrupt) this.onInterrupt();
964
+ else { this.buffer = ''; this.cursor = 0; }
965
+ break;
966
+
967
+ case '\x04': // ctrl+d
968
+ this.close();
969
+ return;
970
+
971
+ case '\x02': // ctrl+b swap plan and build
972
+ this.toggleMode();
973
+ return;
974
+
975
+ case '\x15': // ctrl+u — clear the line
976
+ this.buffer = this.buffer.slice(this.cursor);
977
+ this.cursor = 0;
978
+ break;
979
+
980
+ case ESC: // esc — stop the turn in flight
981
+ if (this.onInterrupt) this.onInterrupt();
982
+ return;
983
+
984
+ case '\t': {
985
+ const hit = COMMANDS.find((c) => c.startsWith(this.buffer));
986
+ if (hit) { this.buffer = hit; this.cursor = hit.length; }
987
+ break;
988
+ }
989
+
990
+ // With an empty line the arrows scroll the conversation; once there is
991
+ // something typed they walk history. Terminals often swallow PgUp and
992
+ // PgDn for their own scrollback, so this is the path that always works.
993
+ case `${ESC}[A`:
994
+ if (!this.buffer) { this.scrollBy(2); return; }
995
+ if (this.history.length) {
996
+ this.historyIndex = Math.min(this.historyIndex + 1, this.history.length - 1);
997
+ this.buffer = this.history[this.historyIndex] ?? '';
998
+ this.cursor = this.buffer.length;
999
+ }
1000
+ break;
1001
+
1002
+ case `${ESC}[B`:
1003
+ if (!this.buffer) { this.scrollBy(-2); return; }
1004
+ this.historyIndex = Math.max(this.historyIndex - 1, -1);
1005
+ this.buffer = this.historyIndex === -1 ? '' : (this.history[this.historyIndex] ?? '');
1006
+ this.cursor = this.buffer.length;
1007
+ break;
1008
+
1009
+ case `${ESC}[1;5A`: this.scrollBy(2); return; // ctrl+up
1010
+ case `${ESC}[1;5B`: this.scrollBy(-2); return; // ctrl+down
1011
+ case `${ESC}[5~`: this.scrollBy(this.viewportHeight()); return;
1012
+ case `${ESC}[6~`: this.scrollBy(-this.viewportHeight()); return;
1013
+
1014
+ case `${ESC}[H`: this.scrollBy(this.lines.length); return;
1015
+ case `${ESC}[F`: this.scroll = 0; this.render(); return;
1016
+
1017
+ case `${ESC}[C`: this.cursor = Math.min(this.cursor + 1, this.buffer.length); break;
1018
+ case `${ESC}[D`: this.cursor = Math.max(this.cursor - 1, 0); break;
1019
+
1020
+ default:
1021
+ if (key >= ' ' && !key.startsWith(ESC)) {
1022
+ this.buffer = this.buffer.slice(0, this.cursor) + key + this.buffer.slice(this.cursor);
1023
+ this.cursor += key.length;
1024
+ } else {
1025
+ return;
1026
+ }
1027
+ }
1028
+
1029
+ this.render();
1030
+ }
1031
+
1032
+ // -- painting ------------------------------------------------------------
1033
+
1034
+ render() {
1035
+ if (this.closed) return;
1036
+ if (this.welcoming()) {
1037
+ this.renderWelcome();
1038
+ return;
1039
+ }
1040
+
1041
+ const width = this.width();
1042
+ const height = this.viewportHeight();
1043
+
1044
+ const end = Math.max(0, this.lines.length - this.scroll);
1045
+ const start = Math.max(0, end - height);
1046
+ const window = this.picker ? this.pickerLines(height) : this.lines.slice(start, end);
1047
+ while (window.length < height) window.push('');
1048
+
1049
+ const frame = [
1050
+ ...this.headerLines(),
1051
+ '',
1052
+ ...window,
1053
+ // Always one clear row between the last thing said and the box you type
1054
+ // in. Without it the newest line of output sits against the border and
1055
+ // reads as part of the input rather than as the answer above it.
1056
+ '',
1057
+ ...this.inputBox(),
1058
+ ];
1059
+
1060
+ // The cursor is hidden for the duration of the paint. Without this it is
1061
+ // dragged through every line as the frame is written, which shows up as a
1062
+ // dot flickering above the input box on every keystroke.
1063
+ const out = [HIDE, HOME];
1064
+ for (let i = 0; i < this.rows; i++) {
1065
+ out.push(CLEAR_LINE + padVis(frame[i] ?? '', width) + (i === this.rows - 1 ? '' : '\n'));
1066
+ }
1067
+
1068
+ const [row, col] = this.caret();
1069
+ out.push(at(row, col) + SHOW);
1070
+ this.output.write(out.join(''));
1071
+ }
1072
+
1073
+ /**
1074
+ * Where the typing caret belongs, 1-based.
1075
+ *
1076
+ * Column three is the first character inside the box: border, a space of
1077
+ * padding, then the text.
1078
+ */
1079
+ caret() {
1080
+ if (this.welcoming()) {
1081
+ const g = this.welcomeGeometry();
1082
+ const { rows, prefix, width } = this.inputLines(g.boxWidth - 4);
1083
+ const index = prefix.length + this.cursor;
1084
+ const row = Math.min(Math.floor(index / width), rows.length - 1);
1085
+ // g.boxTop is 0-based and the typed lines start one below the border.
1086
+ return [g.boxTop + 2 + row, g.left + 3 + (index % width)];
1087
+ }
1088
+
1089
+ const { rows, prefix, width } = this.inputLines();
1090
+ const index = prefix.length + this.cursor;
1091
+ const row = Math.min(Math.floor(index / width), rows.length - 1);
1092
+ const col = 3 + (index % width);
1093
+ // Counting up from the bottom: the box border is the last row, the status
1094
+ // row is above it, then the blank row, then the typed lines.
1095
+ const firstRow = this.rows - 2 - rows.length;
1096
+ return [firstRow + row, col];
1097
+ }
1098
+
1099
+ // -- start screen ----------------------------------------------------------
1100
+
1101
+ /**
1102
+ * Nothing has been said yet, so there is nothing to scroll: the screen is the
1103
+ * wordmark and the place to type, centred, and nothing else.
1104
+ *
1105
+ * It comes back after /clear and /new too, since those empty the transcript —
1106
+ * a fresh conversation starts from the same quiet screen as a fresh launch.
1107
+ */
1108
+ welcoming() {
1109
+ return this.lines.length === 0 && !this.picker;
1110
+ }
1111
+
1112
+ /** Where everything on the start screen goes, 0-based rows. */
1113
+ welcomeGeometry() {
1114
+ const cols = this.width();
1115
+ const boxWidth = Math.max(30, Math.min(cols - 4, 84));
1116
+ const left = Math.max(0, Math.floor((cols - boxWidth) / 2));
1117
+ const big = cols >= BANNER_WIDTH + 4 && this.rows >= 18;
1118
+ const art = big ? BANNER : ['u c o d e'];
1119
+ const inputRows = this.inputLines(boxWidth - 4).rows.length;
1120
+ const block = art.length + 2 + inputRows + 4; // wordmark, gap, box
1121
+ // A touch above true centre reads as centred; exact centre looks low.
1122
+ const top = Math.max(0, Math.floor((this.rows - block) / 2) - 1);
1123
+ return { cols, boxWidth, left, big, art, inputRows, top, boxTop: top + art.length + 2 };
1124
+ }
1125
+
1126
+ renderWelcome() {
1127
+ const g = this.welcomeGeometry();
1128
+ const frame = new Array(this.rows).fill('');
1129
+
1130
+ // The wordmark in two tones of the one blue, the way a name reads in two
1131
+ // halves: the U quieter, CODE brighter.
1132
+ g.art.forEach((line, i) => {
1133
+ const pad = ' '.repeat(Math.max(0, Math.floor((g.cols - line.length) / 2)));
1134
+ frame[g.top + i] = pad + (g.big
1135
+ ? deep(line.slice(0, WORDMARK_SPLIT)) + sky(line.slice(WORDMARK_SPLIT))
1136
+ : blue.bold(line));
1137
+ });
1138
+
1139
+ const indent = ' '.repeat(g.left);
1140
+ this.inputBox(g.boxWidth).forEach((row, i) => {
1141
+ frame[g.boxTop + i] = indent + row;
1142
+ });
1143
+
1144
+ // The version, in the corner, and nothing else on the screen.
1145
+ if (VERSION) {
1146
+ const tag = dim(`v${VERSION}`);
1147
+ frame[this.rows - 1] = ' '.repeat(Math.max(0, g.cols - visLen(tag) - 2)) + tag;
1148
+ }
1149
+
1150
+ const out = [HIDE, HOME];
1151
+ for (let i = 0; i < this.rows; i++) {
1152
+ out.push(CLEAR_LINE + padVis(frame[i], g.cols) + (i === this.rows - 1 ? '' : '\n'));
1153
+ }
1154
+ const [row, col] = this.caret();
1155
+ out.push(at(row, col) + SHOW);
1156
+ this.output.write(out.join(''));
1157
+ }
1158
+ }
1159
+
1160
+ /**
1161
+ * Split a raw stdin chunk into keys, keeping escape sequences whole.
1162
+ *
1163
+ * Application cursor key mode (DECCKM) makes a terminal send ESC O A for the
1164
+ * up arrow rather than ESC [ A. Both are normalised to the bracket form here
1165
+ * so the key handler only ever sees one of them.
1166
+ */
1167
+ export function splitKeys(chunk) {
1168
+ const keys = [];
1169
+ let i = 0;
1170
+
1171
+ while (i < chunk.length) {
1172
+ const c = chunk[i];
1173
+ if (c !== ESC) { keys.push(c); i++; continue; }
1174
+
1175
+ const rest = chunk.slice(i);
1176
+ const csi = /^\x1b\[[0-9;?]*[A-Za-z~]/.exec(rest);
1177
+ if (csi) { keys.push(csi[0]); i += csi[0].length; continue; }
1178
+
1179
+ const ss3 = /^\x1bO([A-Za-z])/.exec(rest);
1180
+ if (ss3) { keys.push(`${ESC}[${ss3[1]}`); i += ss3[0].length; continue; }
1181
+
1182
+ keys.push(ESC);
1183
+ i++;
1184
+ }
1185
+
1186
+ return keys;
1187
+ }