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