ucode-agent 1.0.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.
@@ -0,0 +1,1067 @@
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
+ * A tool call, as it happens: "● Listing src".
245
+ *
246
+ * This lives in the transcript rather than only on the status line. The
247
+ * status line overwrites itself and is empty by the end of the turn, so work
248
+ * announced only there scrolls past unseen — and the diff underneath ends up
249
+ * with nothing above it explaining where it came from.
250
+ */
251
+ toolCall(label) {
252
+ // U+25CF, not U+23FA: the latter carries emoji presentation, which Windows
253
+ // Terminal draws as a white circle on a blue tile.
254
+ this.push(`${blue('●')} ${asLabel(label)}`);
255
+ this.updateSpinner(label);
256
+ }
257
+
258
+ toolResult(summary) {
259
+ this.push(dim(` └ ${summary}`));
260
+ }
261
+
262
+ toolFailed(summary) {
263
+ this.push(`${dim(' └ ')}${theme.error(summary)}`);
264
+ }
265
+
266
+ /**
267
+ * The change itself, under the result.
268
+ *
269
+ * A line-number gutter, then the sign and the code tinted right across the
270
+ * row. The numbers are the point: a diff you cannot navigate from is a
271
+ * picture of a change rather than a record of one.
272
+ */
273
+ diff(lines) {
274
+ const gutter = 6;
275
+ // Two spaces of indent, the gutter, one space, then the tint fills the
276
+ // rest. One column over and every row wraps, splitting the whole diff.
277
+ const room = Math.max(12, this.width() - gutter - 3);
278
+
279
+ for (const line of lines) {
280
+ // A file heading in a multi-file write.
281
+ if (line.startsWith('~')) {
282
+ this.add(` ${dim(' '.repeat(gutter))} ${sky(line.slice(1))}`);
283
+ continue;
284
+ }
285
+
286
+ const added = line.startsWith('+');
287
+ const rest = line.slice(1);
288
+ // Tools emit "<line>| <text>". A row with no number is the "12 more
289
+ // lines" note, which is not part of the change, so it stays dim.
290
+ const parsed = /^(\d+)\|\s?([\s\S]*)$/.exec(rest);
291
+ if (!parsed) {
292
+ this.add(` ${dim(' '.repeat(gutter))} ${dim(rest)}`);
293
+ continue;
294
+ }
295
+
296
+ const [, number, body] = parsed;
297
+ const tint = added ? ADDED : REMOVED;
298
+ this.add(
299
+ ` ${dim(number.padStart(gutter))} ` +
300
+ // Tabs would leave the tint ending short of the row, so they widen.
301
+ tint(padVis(clip(`${added ? '+' : '-'} ${body.replace(/\t/g, ' ')}`, room), room))
302
+ );
303
+ }
304
+ this.render(); // a sixteen-line diff is one frame, not sixteen
305
+ }
306
+
307
+ /** Captured output under a command, dimmed so it reads as evidence. */
308
+ commandOutput(lines) {
309
+ for (const line of lines) this.add(` ${dim(line)}`);
310
+ this.render();
311
+ }
312
+
313
+ /**
314
+ * A running command's output, live — on the status line and nowhere else.
315
+ *
316
+ * Only the newest line, gone as soon as the next arrives. Appending each one
317
+ * instead would mean a test run leaving sixty lines of "ok" in the
318
+ * conversation permanently, which is noise the moment it scrolls. What
319
+ * survives a command is decided when it ends: nothing if it worked, the tail
320
+ * if it did not.
321
+ */
322
+ progress(lines) {
323
+ const last = lines[lines.length - 1]?.trim();
324
+ if (last) this.updateSpinner(last);
325
+ }
326
+
327
+ /**
328
+ * The model's own account of the step it is taking, before it takes it.
329
+ *
330
+ * Not called status(): `this.status` holds the spinner state, and a method
331
+ * of the same name would be shadowed by it on every instance.
332
+ */
333
+ narrate(text) {
334
+ const line = asLabel(text);
335
+ if (!line) return;
336
+ this.push(dim(` ⋮ ${clip(line, this.width() - 6)}`));
337
+ this.updateSpinner(line);
338
+ }
339
+
340
+ // -- streaming -----------------------------------------------------------
341
+ // Deltas appear as plain text as they arrive, then get replaced in place by
342
+ // properly rendered markdown once the reply is complete.
343
+
344
+ streamBegin() {
345
+ this.stopSpinner();
346
+ this.streamAt = this.lines.length;
347
+ this.streamBuf = '';
348
+ this.streamPainted = 0;
349
+ }
350
+
351
+ streamDelta(delta) {
352
+ if (this.streamAt === undefined) this.streamBegin();
353
+ this.streamBuf += delta;
354
+ const now = Date.now();
355
+ if (now - this.streamPainted < 60) return; // about 16fps is plenty
356
+ this.streamPainted = now;
357
+ this.repaintStream();
358
+ }
359
+
360
+ /**
361
+ * Repaint the partial reply.
362
+ *
363
+ * polish() runs on the partial text so bold, inline code and bullets are
364
+ * already styled while it streams. Without it the text arrives raw and then
365
+ * visibly re-renders at the end, which reads as a glitch.
366
+ */
367
+ repaintStream() {
368
+ this.lines.length = this.streamAt;
369
+ this.add('');
370
+ this.add(polish(this.streamBuf));
371
+ this.render(); // one frame, and never one without the reply in it
372
+ }
373
+
374
+ /**
375
+ * Finish a streamed reply.
376
+ *
377
+ * `asLabel` says the text turned out to be narration ahead of a tool call
378
+ * rather than an answer, in which case one short line folds down into the
379
+ * status line it was always meant to be.
380
+ */
381
+ streamEnd({ asNarration = false } = {}) {
382
+ if (this.streamAt === undefined) return '';
383
+ const text = this.streamBuf;
384
+ this.lines.length = this.streamAt;
385
+ this.streamAt = undefined;
386
+ this.streamBuf = '';
387
+
388
+ if (asNarration && isLabel(text)) this.narrate(text);
389
+ else if (text.trim()) this.assistant(text);
390
+ else this.render();
391
+ return text;
392
+ }
393
+
394
+ // -- thinking ------------------------------------------------------------
395
+ // A reasoning model does all its working before it says anything. None of it
396
+ // is printed: it is long, repetitive, and guesses drawn from it read worse
397
+ // than silence. The spinner counts the seconds so the wait is visibly alive,
398
+ // and the transcript gets one line afterwards saying how long it took.
399
+
400
+ thinkingDelta() {
401
+ if (this.thoughtSince === undefined) this.thoughtSince = Date.now();
402
+ }
403
+
404
+ thinkingEnd() {
405
+ if (this.thoughtSince === undefined) return;
406
+ const seconds = Math.round((Date.now() - this.thoughtSince) / 1000);
407
+ if (seconds >= 2) this.push(dim(` ⋮ thought for ${seconds}s`));
408
+ this.thoughtSince = undefined;
409
+ }
410
+
411
+ error(err, { debug = false } = {}) {
412
+ const known = err && typeof err === 'object' && err.attempted;
413
+ this.push('');
414
+ if (known) {
415
+ this.push(`${theme.error('✗')} ${chalk.white(`Failed while ${err.attempted}.`)}`);
416
+ this.push(` ${err.failed}`);
417
+ if (err.fix) this.push(` ${blue('→')} ${err.fix}`);
418
+ if (err.kind) this.push(dim(` (${err.kind})`));
419
+ } else {
420
+ this.push(`${theme.error('✗')} ${chalk.white('Something broke inside ucode.')}`);
421
+ this.push(` ${err?.message ?? String(err)}`);
422
+ this.push(` ${blue('→')} That is a bug in ucode rather than in your project. Re-run with --debug.`);
423
+ }
424
+ if (debug) {
425
+ const stack = (known && err.cause?.stack) || err?.stack;
426
+ if (stack) this.push(dim(stack));
427
+ }
428
+ this.push('');
429
+ }
430
+
431
+ // -- header --------------------------------------------------------------
432
+
433
+ setFacts(facts) {
434
+ this.facts = { ...this.facts, ...facts };
435
+ if (facts.model) this.model = facts.model;
436
+ this.render();
437
+ }
438
+
439
+ /** Same shape as the plain UI's header(), so the loop needs no branch. */
440
+ header({ cwd, model, used, limit, title: sessionTitle }) {
441
+ this.setFacts({
442
+ cwd,
443
+ model,
444
+ title: sessionTitle,
445
+ percent: limit > 0 ? Math.min(100, Math.round((used / limit) * 100)) : 0,
446
+ });
447
+ }
448
+
449
+ /**
450
+ * How many rows the header box occupies.
451
+ *
452
+ * The frame has to be exactly as tall as the terminal or every row below the
453
+ * shortfall is off by that much — including the one the caret is parked on.
454
+ * So this is derived, never assumed.
455
+ */
456
+ headerHeight() {
457
+ return this.width() >= WORDMARK_NEEDS ? BANNER.length + 2 : 5;
458
+ }
459
+
460
+ headerLines() {
461
+ const width = this.width();
462
+ const inner = width - 2; // between the borders
463
+
464
+ if (width < WORDMARK_NEEDS) {
465
+ // Too narrow for the wordmark: stack it rather than wrap it into noise.
466
+ const rows = [
467
+ ` ${blue.bold('U C O D E')} ${dim('terminal coding agent')}`,
468
+ ` ${dim('dir'.padEnd(8))}${chalk.white(clip(shortenPath(this.facts.cwd ?? this.cwd, inner - 12), inner - 12))}`,
469
+ ];
470
+ return [boxTop(width), ...rows.map((r) => boxRow(r, width)), boxBottom(width)];
471
+ }
472
+
473
+ // Two spaces of padding, the wordmark, a gap, then the facts column.
474
+ //
475
+ // Only what you cannot work out by looking: where you are, and how to get
476
+ // help. How full the window is belongs on the status row next to the model
477
+ // it describes, and the session title is already the terminal's own window
478
+ // title — repeating either here is a second place to keep in sync for no
479
+ // reader who needed it.
480
+ const room = Math.max(8, inner - BANNER_WIDTH - 6);
481
+ const facts = [
482
+ ['dir', shortenPath(this.facts.cwd ?? this.cwd, room - 9)],
483
+ ['keys', '/help · esc interrupts'],
484
+ ['', ''],
485
+ ['', ''],
486
+ ['', ''],
487
+ ['', 'made with ❤️ by om dixit'],
488
+ ];
489
+
490
+ const rows = BANNER.map((art, i) => {
491
+ const [label, value] = facts[i] ?? ['', ''];
492
+ const right = label
493
+ ? `${dim(label.padEnd(9))}${chalk.white(clip(value, room - 9))}`
494
+ : (value ? dim(value) : '');
495
+ return ` ${blue(art)} ${right}`;
496
+ });
497
+
498
+ return [boxTop(width), ...rows.map((r) => boxRow(r, width)), boxBottom(width)];
499
+ }
500
+
501
+ // -- input box -----------------------------------------------------------
502
+
503
+ /** The typed line, wrapped to the inside of the box. */
504
+ inputLines() {
505
+ const width = this.inner();
506
+ const prefix = this.pendingPrompt ? `${this.pendingPrompt} ` : '› ';
507
+ const full = prefix + this.buffer;
508
+
509
+ const rows = [];
510
+ for (let i = 0; i < full.length; i += width) rows.push(full.slice(i, i + width));
511
+ if (rows.length === 0) rows.push(prefix);
512
+
513
+ return { rows, prefix, width };
514
+ }
515
+
516
+ viewportHeight() {
517
+ return Math.max(
518
+ 3,
519
+ this.rows - this.headerHeight() - CHROME_BELOW - this.inputLines().rows.length
520
+ );
521
+ }
522
+
523
+ /**
524
+ * The input box: what you are typing, and directly under it, inside the same
525
+ * border, the three things worth knowing while you type.
526
+ *
527
+ * The status used to sit outside the box on the last row of the screen,
528
+ * which made it a separate object floating under the input. Inside the
529
+ * border it reads as part of the thing you are using — the box says "this is
530
+ * where you work", and the row underneath says what you are working with.
531
+ */
532
+ inputBox() {
533
+ const width = this.width();
534
+ const { rows } = this.inputLines();
535
+ const painted = rows.map((row, i) =>
536
+ i === 0
537
+ ? boxRow(` ${blue('›')}${row.slice(1)}`, width, edge) // the caret, coloured
538
+ : boxRow(` ${row}`, width, edge)
539
+ );
540
+ return [
541
+ boxTop(width, edge),
542
+ ...painted,
543
+ // A blank row between the two. Sitting directly under the caret, the
544
+ // status read as a second line of the thing being typed; one row of air
545
+ // separates what you are writing from what you are writing it with.
546
+ boxRow('', width, edge),
547
+ boxRow(this.statusRow(), width, edge),
548
+ boxBottom(width, edge),
549
+ ];
550
+ }
551
+
552
+ // -- status row ----------------------------------------------------------
553
+
554
+ modeChip() {
555
+ return this.mode === 'plan' ? `${sky('◇')} ${sky('Plan')}` : `${blue('◆')} ${blue('Build')}`;
556
+ }
557
+
558
+ /**
559
+ * How full the context window is, as a bare number.
560
+ *
561
+ * It turns amber at 75% because that is where turns start being folded away
562
+ * into a summary — the one moment the number predicts something you would
563
+ * want to know before it happens.
564
+ */
565
+ percentChip() {
566
+ const percent = Math.round(this.facts.percent ?? 0);
567
+ return percent >= 75 ? theme.warn(`${percent}%`) : dim(`${percent}%`);
568
+ }
569
+
570
+ /**
571
+ * Which mode is live, which model is answering, and how full the window is.
572
+ *
573
+ * Nothing else earns a place. The provider name was there and was cut: it is
574
+ * the same on every line of every session, so it was decoration that had to
575
+ * be read past to reach the two things that do change.
576
+ *
577
+ * The middle is borrowed while something is running, for the spinner and the
578
+ * way out of it, and handed straight back when it finishes.
579
+ */
580
+ statusRow() {
581
+ const inner = this.width() - 2; // the space between the two borders
582
+ const chip = this.modeChip();
583
+ const left = ` ${chip} ${dim('·')} ${chalk.white(this.model || '—')}`;
584
+ const right = `${this.percentChip()} `;
585
+
586
+ // Where a click on the bottom row still counts as hitting the mode chip.
587
+ this.chipTo = 2 + visLen(chip);
588
+
589
+ const between = Math.max(1, inner - visLen(left) - visLen(right));
590
+
591
+ let middle = '';
592
+ if (this.flashText) {
593
+ middle = dim(clip(this.flashText, between - 2));
594
+ } else if (this.status.busy) {
595
+ const frame = blue(SPINNER[this.status.frame]);
596
+ const secs = Math.round((Date.now() - (this.status.since || Date.now())) / 1000);
597
+ const elapsed = secs >= 2 ? dim(` ${secs}s`) : '';
598
+ const room = between - 20;
599
+ middle = room > 8
600
+ ? `${frame} ${dim(clip(this.status.text, room))}${elapsed} ${dim('esc to stop')}`
601
+ : `${frame}${elapsed}`;
602
+ }
603
+
604
+ // The percentage is pinned to the right border whatever is in the middle,
605
+ // with a gap kept in front of it so a long spinner label cannot run into
606
+ // the number and read as part of it.
607
+ const tail = middle ? `${middle} ` : '';
608
+ const pad = Math.max(1, inner - visLen(left) - visLen(tail) - visLen(right));
609
+ return padVis(left + ' '.repeat(pad) + tail + right, inner);
610
+ }
611
+
612
+ /**
613
+ * Repaint only the status row, leaving the caret where the user left it.
614
+ *
615
+ * It is the second row from the bottom now — the box's own border is below
616
+ * it — so the row is written with its borders rather than as a bare line.
617
+ */
618
+ paintStatus() {
619
+ if (this.closed) return;
620
+ const [row, col] = this.caret();
621
+ this.output.write(
622
+ HIDE +
623
+ at(this.rows - 1, 1) + CLEAR_LINE + boxRow(this.statusRow(), this.width(), edge) +
624
+ at(row, col) + SHOW
625
+ );
626
+ }
627
+
628
+ toggleMode() {
629
+ this.mode = this.mode === 'plan' ? 'build' : 'plan';
630
+ this.flash(this.mode === 'plan'
631
+ ? 'plan mode — reads and researches, changes nothing'
632
+ : 'build mode — free to edit files and run commands');
633
+ this.onModeChange?.(this.mode);
634
+ this.render();
635
+ }
636
+
637
+ /** A message on the status line that fades on its own. */
638
+ flash(text) {
639
+ this.flashText = text;
640
+ clearTimeout(this.flashTimer);
641
+ this.flashTimer = setTimeout(() => {
642
+ this.flashText = null;
643
+ this.paintStatus();
644
+ }, 2500);
645
+ this.flashTimer.unref?.();
646
+ this.paintStatus();
647
+ }
648
+
649
+ // -- spinner -------------------------------------------------------------
650
+
651
+ startSpinner(text = 'thinking') {
652
+ // `since` is what makes a long think legible: the label may not change for
653
+ // a minute, so the seconds beside it are the proof it is still alive.
654
+ this.status = { busy: true, text: asLabel(text), frame: 0, since: Date.now() };
655
+ if (!this.spinTimer) {
656
+ this.spinTimer = setInterval(() => {
657
+ this.status.frame = (this.status.frame + 1) % SPINNER.length;
658
+ this.paintStatus();
659
+ }, 80);
660
+ this.spinTimer.unref?.();
661
+ }
662
+ this.paintStatus();
663
+ }
664
+
665
+ updateSpinner(text) {
666
+ if (!this.status.busy) return;
667
+ this.status.text = asLabel(text);
668
+ this.paintStatus();
669
+ }
670
+
671
+ stopSpinner() {
672
+ if (this.spinTimer) {
673
+ clearInterval(this.spinTimer);
674
+ this.spinTimer = null;
675
+ }
676
+ if (this.status.busy) {
677
+ this.status = { busy: false, text: '', frame: 0, since: 0 };
678
+ this.paintStatus();
679
+ }
680
+ }
681
+
682
+ // -- input ---------------------------------------------------------------
683
+
684
+ nextLine() {
685
+ if (this.queue.length) return Promise.resolve(this.queue.shift());
686
+ if (this.closed) return Promise.resolve(null);
687
+ return new Promise((resolve) => this.waiters.push(resolve));
688
+ }
689
+
690
+ ask() {
691
+ return this.nextLine();
692
+ }
693
+
694
+ submit(text) {
695
+ const waiter = this.waiters.shift();
696
+ if (waiter) waiter(text);
697
+ else this.queue.push(text);
698
+ }
699
+
700
+ /** y/n, answered on the input line. */
701
+ confirm({ action, detail, risk }) {
702
+ this.push('');
703
+ this.push(`${chalk.inverse(theme.warn(risk === 'command' ? ' shell ' : ' outside project '))} ${chalk.white(action)}`);
704
+ for (const line of String(detail ?? '').split('\n')) {
705
+ if (line) this.push(dim(` ${line}`));
706
+ }
707
+
708
+ this.pendingPrompt = 'go ahead? [y/N]';
709
+ this.render();
710
+
711
+ return this.nextLine().then((answer) => {
712
+ this.pendingPrompt = null;
713
+ // End of input counts as no. Never run something nobody approved.
714
+ const yes = /^(y|yes)$/i.test(String(answer ?? '').trim());
715
+ this.push(dim(yes ? ' approved' : ' declined'));
716
+ this.push('');
717
+ return yes;
718
+ });
719
+ }
720
+
721
+ /**
722
+ * A modal list: arrows move, Enter picks, Esc cancels.
723
+ *
724
+ * Only while this is open do the arrows stop scrolling the transcript. They
725
+ * cannot be given up permanently, because under alternate scroll the mouse
726
+ * wheel arrives as arrow keys.
727
+ */
728
+ pick(items, { active = 0, hint = 'enter to choose · esc to cancel' } = {}) {
729
+ this.picker = {
730
+ items,
731
+ index: Math.min(Math.max(0, active), Math.max(0, items.length - 1)),
732
+ hint,
733
+ };
734
+ this.render();
735
+ return new Promise((resolve) => { this.pickerResolve = resolve; });
736
+ }
737
+
738
+ closePicker(value) {
739
+ const resolve = this.pickerResolve;
740
+ this.picker = null;
741
+ this.pickerResolve = null;
742
+ this.render();
743
+ resolve?.(value);
744
+ }
745
+
746
+ /**
747
+ * Rows for an open picker, windowed so a long list still fits.
748
+ *
749
+ * An item may carry a `sub` line — a second, dimmer row underneath it. That
750
+ * is what lets a list of saved conversations show what each one was actually
751
+ * about instead of a column of near-identical titles.
752
+ */
753
+ pickerLines(height) {
754
+ const { items, index, hint } = this.picker;
755
+ const room = Math.max(1, height - 2);
756
+
757
+ // Rows per item, so the window can be sized in rows rather than in items.
758
+ const rowsFor = (item) => (typeof item !== 'string' && item.sub ? 2 : 1);
759
+ const perItem = items.map(rowsFor);
760
+
761
+ // Walk outward from the selection until the window is full. Starting from
762
+ // the selection guarantees it is on screen however long the list is.
763
+ let first = index;
764
+ let last = index;
765
+ let used = perItem[index] ?? 1;
766
+ while (used < room && (first > 0 || last < items.length - 1)) {
767
+ if (first > 0 && used + perItem[first - 1] <= room) { first--; used += perItem[first]; }
768
+ else if (last < items.length - 1 && used + perItem[last + 1] <= room) { last++; used += perItem[last]; }
769
+ else break;
770
+ }
771
+
772
+ const out = [];
773
+ for (let i = first; i <= last; i++) {
774
+ const item = items[i];
775
+ const body = typeof item === 'string' ? item : item.label;
776
+ out.push(i === index ? `${blue('❯')} ${chalk.bold.white(body)}` : ` ${dim(body)}`);
777
+ if (typeof item !== 'string' && item.sub) out.push(` ${item.sub}`);
778
+ }
779
+
780
+ out.push('');
781
+ out.push(dim(` ${hint}`));
782
+ return out;
783
+ }
784
+
785
+ /** A numbered list, answered on the input line. */
786
+ async choose(prompt, items, { allowNone = true } = {}) {
787
+ items.forEach((item, i) => this.push(` ${blue(String(i + 1).padStart(2))}. ${item}`));
788
+ if (allowNone) this.push(dim(' 0. none — start fresh'));
789
+ this.push('');
790
+
791
+ this.pendingPrompt = prompt;
792
+ this.render();
793
+
794
+ const answer = await this.nextLine();
795
+ this.pendingPrompt = null;
796
+
797
+ const trimmed = String(answer ?? '').trim();
798
+ if (trimmed === '' || trimmed === '0') return null;
799
+
800
+ const index = Number(trimmed);
801
+ if (!Number.isInteger(index) || index < 1 || index > items.length) {
802
+ this.push(theme.warn(` "${trimmed}" is not one of 1-${items.length}.`));
803
+ return null;
804
+ }
805
+ return index - 1;
806
+ }
807
+
808
+ // -- keyboard and mouse --------------------------------------------------
809
+
810
+ /**
811
+ * Scroll the transcript, clamped at both ends.
812
+ *
813
+ * When there is nothing above the fold, say so. Silence is indistinguishable
814
+ * from broken input, and the difference matters: one means the conversation
815
+ * simply fits, the other means the terminal is not forwarding keys at all.
816
+ */
817
+ scrollBy(delta) {
818
+ const max = Math.max(0, this.lines.length - this.viewportHeight());
819
+ if (max === 0) {
820
+ this.flash('nothing above — it all fits on screen');
821
+ return;
822
+ }
823
+ const before = this.scroll;
824
+ this.scroll = Math.min(Math.max(0, this.scroll + delta), max);
825
+ if (this.scroll === before && delta > 0) this.flash('already at the top');
826
+ this.render();
827
+ }
828
+
829
+ onData(chunk) {
830
+ // UCODE_DEBUG_KEYS=1 logs every byte the terminal sends to
831
+ // ~/.ucode/keys.log. Whether mouse reporting works at all depends on the
832
+ // terminal forwarding it; this is how to find out.
833
+ if (process.env.UCODE_DEBUG_KEYS) {
834
+ appendFile(path.join(homedir(), '.ucode', 'keys.log'), `${JSON.stringify(chunk)}\n`).catch(() => {});
835
+ }
836
+
837
+ // Pull mouse reports out of the chunk wherever they sit. Anchoring the
838
+ // match to the whole chunk meant a wheel event arriving alongside any
839
+ // other byte was silently treated as typing.
840
+ let rest = '';
841
+ let index = 0;
842
+ // Two encodings: SGR (ESC [ < b ; x ; y M|m), and the legacy form
843
+ // (ESC [ M then three bytes offset by 32) for terminals that ignore 1006.
844
+ const mouse = /\x1b\[<(\d+);(\d+);(\d+)([Mm])|\x1b\[M([\s\S])([\s\S])([\s\S])/g;
845
+ let match;
846
+
847
+ while ((match = mouse.exec(chunk)) !== null) {
848
+ rest += chunk.slice(index, match.index);
849
+ index = match.index + match[0].length;
850
+ if (match[1] !== undefined) {
851
+ this.onMouse(Number(match[1]), Number(match[2]), Number(match[3]), match[4]);
852
+ } else {
853
+ this.onMouse(
854
+ match[5].charCodeAt(0) - 32,
855
+ match[6].charCodeAt(0) - 32,
856
+ match[7].charCodeAt(0) - 32,
857
+ 'M'
858
+ );
859
+ }
860
+ }
861
+ rest += chunk.slice(index);
862
+
863
+ for (const key of splitKeys(rest)) this.onKey(key);
864
+ }
865
+
866
+ onMouse(button, col, row, press) {
867
+ // Wheel reports set bit 6; bit 0 says which way.
868
+ if (button >= 64) {
869
+ this.scrollBy(button % 2 === 0 ? 3 : -3);
870
+ return;
871
+ }
872
+ if (press !== 'M' || button !== 0) return;
873
+ // The mode chip, at the left of the bottom row.
874
+ if (row === this.rows - 1 && col >= 2 && col <= this.chipTo) this.toggleMode();
875
+ }
876
+
877
+ onKey(key) {
878
+ // An open picker owns the keyboard until it closes.
879
+ if (this.picker) {
880
+ const last = this.picker.items.length - 1;
881
+ if (key === `${ESC}[A`) { this.picker.index = Math.max(0, this.picker.index - 1); this.render(); return; }
882
+ if (key === `${ESC}[B`) { this.picker.index = Math.min(last, this.picker.index + 1); this.render(); return; }
883
+ if (key === '\r' || key === '\n') { this.closePicker(this.picker.index); return; }
884
+ if (key === ESC || key === '\x03') { this.closePicker(null); return; }
885
+ return;
886
+ }
887
+
888
+ switch (key) {
889
+ case '\r':
890
+ case '\n': {
891
+ const text = this.buffer;
892
+ this.buffer = '';
893
+ this.cursor = 0;
894
+ this.historyIndex = -1;
895
+ if (text.trim()) {
896
+ this.history.unshift(text);
897
+ // Echo it so the transcript reads as a conversation rather than as
898
+ // a series of unprompted answers.
899
+ this.push('');
900
+ this.push(`${blue('›')} ${chalk.white(text)}`);
901
+ }
902
+ this.render();
903
+ this.submit(text);
904
+ return;
905
+ }
906
+
907
+ case '\x7f': // backspace
908
+ case '\b':
909
+ if (this.cursor > 0) {
910
+ this.buffer = this.buffer.slice(0, this.cursor - 1) + this.buffer.slice(this.cursor);
911
+ this.cursor--;
912
+ }
913
+ break;
914
+
915
+ case '\x03': // ctrl+c
916
+ if (this.status.busy && this.onInterrupt) this.onInterrupt();
917
+ else { this.buffer = ''; this.cursor = 0; }
918
+ break;
919
+
920
+ case '\x04': // ctrl+d
921
+ this.close();
922
+ return;
923
+
924
+ case '\x02': // ctrl+b — swap plan and build
925
+ this.toggleMode();
926
+ return;
927
+
928
+ case '\x15': // ctrl+u — clear the line
929
+ this.buffer = this.buffer.slice(this.cursor);
930
+ this.cursor = 0;
931
+ break;
932
+
933
+ case ESC: // esc — stop the turn in flight
934
+ if (this.onInterrupt) this.onInterrupt();
935
+ return;
936
+
937
+ case '\t': {
938
+ const hit = COMMANDS.find((c) => c.startsWith(this.buffer));
939
+ if (hit) { this.buffer = hit; this.cursor = hit.length; }
940
+ break;
941
+ }
942
+
943
+ // With an empty line the arrows scroll the conversation; once there is
944
+ // something typed they walk history. Terminals often swallow PgUp and
945
+ // PgDn for their own scrollback, so this is the path that always works.
946
+ case `${ESC}[A`:
947
+ if (!this.buffer) { this.scrollBy(2); return; }
948
+ if (this.history.length) {
949
+ this.historyIndex = Math.min(this.historyIndex + 1, this.history.length - 1);
950
+ this.buffer = this.history[this.historyIndex] ?? '';
951
+ this.cursor = this.buffer.length;
952
+ }
953
+ break;
954
+
955
+ case `${ESC}[B`:
956
+ if (!this.buffer) { this.scrollBy(-2); return; }
957
+ this.historyIndex = Math.max(this.historyIndex - 1, -1);
958
+ this.buffer = this.historyIndex === -1 ? '' : (this.history[this.historyIndex] ?? '');
959
+ this.cursor = this.buffer.length;
960
+ break;
961
+
962
+ case `${ESC}[1;5A`: this.scrollBy(2); return; // ctrl+up
963
+ case `${ESC}[1;5B`: this.scrollBy(-2); return; // ctrl+down
964
+ case `${ESC}[5~`: this.scrollBy(this.viewportHeight()); return;
965
+ case `${ESC}[6~`: this.scrollBy(-this.viewportHeight()); return;
966
+
967
+ case `${ESC}[H`: this.scrollBy(this.lines.length); return;
968
+ case `${ESC}[F`: this.scroll = 0; this.render(); return;
969
+
970
+ case `${ESC}[C`: this.cursor = Math.min(this.cursor + 1, this.buffer.length); break;
971
+ case `${ESC}[D`: this.cursor = Math.max(this.cursor - 1, 0); break;
972
+
973
+ default:
974
+ if (key >= ' ' && !key.startsWith(ESC)) {
975
+ this.buffer = this.buffer.slice(0, this.cursor) + key + this.buffer.slice(this.cursor);
976
+ this.cursor += key.length;
977
+ } else {
978
+ return;
979
+ }
980
+ }
981
+
982
+ this.render();
983
+ }
984
+
985
+ // -- painting ------------------------------------------------------------
986
+
987
+ render() {
988
+ if (this.closed) return;
989
+
990
+ const width = this.width();
991
+ const height = this.viewportHeight();
992
+
993
+ const end = Math.max(0, this.lines.length - this.scroll);
994
+ const start = Math.max(0, end - height);
995
+ const window = this.picker ? this.pickerLines(height) : this.lines.slice(start, end);
996
+ while (window.length < height) window.push('');
997
+
998
+ const frame = [
999
+ ...this.headerLines(),
1000
+ '',
1001
+ ...window,
1002
+ // Always one clear row between the last thing said and the box you type
1003
+ // in. Without it the newest line of output sits against the border and
1004
+ // reads as part of the input rather than as the answer above it.
1005
+ '',
1006
+ ...this.inputBox(),
1007
+ ];
1008
+
1009
+ // The cursor is hidden for the duration of the paint. Without this it is
1010
+ // dragged through every line as the frame is written, which shows up as a
1011
+ // dot flickering above the input box on every keystroke.
1012
+ const out = [HIDE, HOME];
1013
+ for (let i = 0; i < this.rows; i++) {
1014
+ out.push(CLEAR_LINE + padVis(frame[i] ?? '', width) + (i === this.rows - 1 ? '' : '\n'));
1015
+ }
1016
+
1017
+ const [row, col] = this.caret();
1018
+ out.push(at(row, col) + SHOW);
1019
+ this.output.write(out.join(''));
1020
+ }
1021
+
1022
+ /**
1023
+ * Where the typing caret belongs, 1-based.
1024
+ *
1025
+ * Column three is the first character inside the box: border, a space of
1026
+ * padding, then the text.
1027
+ */
1028
+ caret() {
1029
+ const { rows, prefix, width } = this.inputLines();
1030
+ const index = prefix.length + this.cursor;
1031
+ const row = Math.min(Math.floor(index / width), rows.length - 1);
1032
+ const col = 3 + (index % width);
1033
+ // Counting up from the bottom: the box border is the last row, the status
1034
+ // row is above it, then the blank row, then the typed lines.
1035
+ const firstRow = this.rows - 2 - rows.length;
1036
+ return [firstRow + row, col];
1037
+ }
1038
+ }
1039
+
1040
+ /**
1041
+ * Split a raw stdin chunk into keys, keeping escape sequences whole.
1042
+ *
1043
+ * Application cursor key mode (DECCKM) makes a terminal send ESC O A for the
1044
+ * up arrow rather than ESC [ A. Both are normalised to the bracket form here
1045
+ * so the key handler only ever sees one of them.
1046
+ */
1047
+ export function splitKeys(chunk) {
1048
+ const keys = [];
1049
+ let i = 0;
1050
+
1051
+ while (i < chunk.length) {
1052
+ const c = chunk[i];
1053
+ if (c !== ESC) { keys.push(c); i++; continue; }
1054
+
1055
+ const rest = chunk.slice(i);
1056
+ const csi = /^\x1b\[[0-9;?]*[A-Za-z~]/.exec(rest);
1057
+ if (csi) { keys.push(csi[0]); i += csi[0].length; continue; }
1058
+
1059
+ const ss3 = /^\x1bO([A-Za-z])/.exec(rest);
1060
+ if (ss3) { keys.push(`${ESC}[${ss3[1]}`); i += ss3[0].length; continue; }
1061
+
1062
+ keys.push(ESC);
1063
+ i++;
1064
+ }
1065
+
1066
+ return keys;
1067
+ }