@mumbrane/leto 0.0.0-stage → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +395 -2
- package/bin/leto.js +8 -0
- package/evals/core/suite.json +249 -0
- package/index.js +12 -0
- package/package.json +43 -4
- package/src/agent.js +572 -0
- package/src/agents.js +68 -0
- package/src/anthropic.js +204 -0
- package/src/browser.js +427 -0
- package/src/btw.js +56 -0
- package/src/checkpoints.js +90 -0
- package/src/ci.js +115 -0
- package/src/cli.js +1926 -0
- package/src/client.js +111 -0
- package/src/config.js +205 -0
- package/src/documents.js +198 -0
- package/src/eval.js +289 -0
- package/src/hooks.js +115 -0
- package/src/ide.js +231 -0
- package/src/input.js +148 -0
- package/src/jobs.js +97 -0
- package/src/legacy.js +41 -0
- package/src/lsp.js +401 -0
- package/src/markdown.js +153 -0
- package/src/mcp.js +346 -0
- package/src/memory.js +136 -0
- package/src/orchestrator.js +141 -0
- package/src/patching.js +185 -0
- package/src/permissions.js +75 -0
- package/src/plugins.js +118 -0
- package/src/policy.js +74 -0
- package/src/pricing.js +67 -0
- package/src/processes.js +139 -0
- package/src/prompt.js +134 -0
- package/src/prompts.js +189 -0
- package/src/providers.js +59 -0
- package/src/repomap.js +211 -0
- package/src/sandbox.js +90 -0
- package/src/sdk.js +220 -0
- package/src/selftool.js +238 -0
- package/src/serve.js +233 -0
- package/src/session.js +168 -0
- package/src/setup.js +157 -0
- package/src/skills.js +125 -0
- package/src/theme.js +185 -0
- package/src/toolcalls.js +257 -0
- package/src/tools.js +976 -0
- package/src/tui.js +1179 -0
- package/src/ui.js +454 -0
- package/src/update.js +33 -0
- package/src/usage.js +83 -0
- package/src/verify.js +131 -0
- package/src/version.js +3 -0
- package/src/worktree.js +87 -0
- package/vscode/extension.js +132 -0
- package/vscode/package.json +21 -0
package/src/tui.js
ADDED
|
@@ -0,0 +1,1179 @@
|
|
|
1
|
+
// Full terminal UI for interactive sessions in a real terminal.
|
|
2
|
+
//
|
|
3
|
+
// The bottom of the screen is a "live region" that leto redraws in place:
|
|
4
|
+
// the spinner, any queued messages, the input box and a hint/suggestion line.
|
|
5
|
+
// Everything else (replies, tool activity) is printed above it and scrolls
|
|
6
|
+
// normally. The input box stays usable while the agent works, so you can type
|
|
7
|
+
// ahead; Enter queues the message for when the current turn ends.
|
|
8
|
+
import readline from 'node:readline';
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
12
|
+
import { UI, truncate } from './ui.js';
|
|
13
|
+
import { MarkdownStream, visibleLength } from './markdown.js';
|
|
14
|
+
import { GLYPH, LOGO, PALETTE } from './theme.js';
|
|
15
|
+
|
|
16
|
+
const SPIN = GLYPH.spinner;
|
|
17
|
+
const VERBS = ['Thinking', 'Reading the sands', 'Harvesting spice', 'Folding space', 'Charting the dunes', 'Working', 'Considering', 'Tracing', 'Mapping'];
|
|
18
|
+
const fmtTokens = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
|
|
19
|
+
|
|
20
|
+
export class FancyUI extends UI {
|
|
21
|
+
constructor() {
|
|
22
|
+
super({ print: false });
|
|
23
|
+
this.fancy = true;
|
|
24
|
+
this.markdown = true;
|
|
25
|
+
this.buffer = '';
|
|
26
|
+
this.cursor = 0;
|
|
27
|
+
this.historyList = [];
|
|
28
|
+
this.histIdx = -1;
|
|
29
|
+
this.draft = '';
|
|
30
|
+
this.queued = [];
|
|
31
|
+
this.regionRows = 0;
|
|
32
|
+
this.regionCursorRow = 0;
|
|
33
|
+
this.active = false;
|
|
34
|
+
this.pending = null; // { resolve, label }
|
|
35
|
+
this.menu = null;
|
|
36
|
+
this.partial = '';
|
|
37
|
+
this.suggest = null;
|
|
38
|
+
this.showHelp = false;
|
|
39
|
+
this.exitArmed = false;
|
|
40
|
+
this.escArmed = false;
|
|
41
|
+
this.pasting = false;
|
|
42
|
+
this.tokens = 0;
|
|
43
|
+
this.modeLabel = () => '';
|
|
44
|
+
this.onCycleMode = null;
|
|
45
|
+
this.commandList = () => [];
|
|
46
|
+
this.cwd = process.cwd();
|
|
47
|
+
this.fileCache = null;
|
|
48
|
+
this.onKey = (str, key) => this.handleKey(str, key ?? {});
|
|
49
|
+
// Everything printed above the input box, so it can be reprinted when the
|
|
50
|
+
// terminal width changes (old lines re-wrap unpredictably otherwise).
|
|
51
|
+
this.transcript = [];
|
|
52
|
+
this.transcriptSize = 0;
|
|
53
|
+
this.lastCols = this.out.columns;
|
|
54
|
+
// Rows of the screen filled by printed output since the last clear. Until
|
|
55
|
+
// the screen is full, blank rows pad the gap so the composer sits at the
|
|
56
|
+
// bottom; after that the conversation scrolls normally.
|
|
57
|
+
this.contentRows = 0;
|
|
58
|
+
this.onResize = () => {
|
|
59
|
+
clearTimeout(this.resizeTimer);
|
|
60
|
+
this.resizeTimer = setTimeout(() => this.handleResize(), 60);
|
|
61
|
+
};
|
|
62
|
+
process.once('exit', () => this.cleanup());
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ---- lifecycle ---------------------------------------------------------
|
|
66
|
+
|
|
67
|
+
start() {
|
|
68
|
+
if (this.active) return;
|
|
69
|
+
const stdin = process.stdin;
|
|
70
|
+
readline.emitKeypressEvents(stdin);
|
|
71
|
+
stdin.setRawMode(true);
|
|
72
|
+
stdin.resume();
|
|
73
|
+
stdin.on('keypress', this.onKey);
|
|
74
|
+
this.out.on('resize', this.onResize);
|
|
75
|
+
this.out.write('\x1b[?2004h'); // bracketed paste: pasted newlines don't submit
|
|
76
|
+
this.active = true;
|
|
77
|
+
if (!this.historyLoaded && this.historyFile) {
|
|
78
|
+
this.historyLoaded = true;
|
|
79
|
+
try {
|
|
80
|
+
this.historyList = fs.readFileSync(this.historyFile, 'utf8').split('\n').filter(Boolean).slice(-1000);
|
|
81
|
+
} catch {}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
suspend() {
|
|
86
|
+
if (!this.active) return;
|
|
87
|
+
this.eraseRegion();
|
|
88
|
+
process.stdin.off('keypress', this.onKey);
|
|
89
|
+
this.out.off('resize', this.onResize);
|
|
90
|
+
this.out.write('\x1b[?2004l');
|
|
91
|
+
process.stdin.setRawMode(false);
|
|
92
|
+
this.active = false;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
resume() {
|
|
96
|
+
this.start();
|
|
97
|
+
this.render();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
close() {
|
|
101
|
+
this.stopSpinner();
|
|
102
|
+
this.flushPartial();
|
|
103
|
+
this.suspend();
|
|
104
|
+
process.stdin.pause();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
cleanup() {
|
|
108
|
+
if (this.active) {
|
|
109
|
+
this.eraseRegion();
|
|
110
|
+
this.out.write('\x1b[?2004l\x1b[?25h');
|
|
111
|
+
try {
|
|
112
|
+
process.stdin.setRawMode(false);
|
|
113
|
+
} catch {}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
setBusy(busy) {
|
|
118
|
+
this.busy = busy;
|
|
119
|
+
if (busy) this.tokens = 0;
|
|
120
|
+
this.render();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// A bell, and on macOS a notification, when a long turn finishes.
|
|
124
|
+
notify(message, secs) {
|
|
125
|
+
if (process.env.LETO_NO_NOTIFY) return;
|
|
126
|
+
this.out.write('\x07');
|
|
127
|
+
if (process.platform === 'darwin' && secs >= 60) {
|
|
128
|
+
const text = message.replace(/["\\]/g, '').slice(0, 120);
|
|
129
|
+
spawn('osascript', ['-e', `display notification "${text}" with title "leto"`], { stdio: 'ignore', detached: true }).unref();
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
addTokens(n) {
|
|
134
|
+
this.tokens += n;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// ---- input -------------------------------------------------------------
|
|
138
|
+
|
|
139
|
+
prompt() {
|
|
140
|
+
return this.readLine(null);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
readLine(label) {
|
|
144
|
+
this.start();
|
|
145
|
+
if (!label && this.queued.length) {
|
|
146
|
+
const text = this.queued.shift();
|
|
147
|
+
this.echoUser(text);
|
|
148
|
+
this.render();
|
|
149
|
+
return Promise.resolve(text);
|
|
150
|
+
}
|
|
151
|
+
return new Promise((resolve) => {
|
|
152
|
+
this.pending = { resolve, label };
|
|
153
|
+
this.render();
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
cancelRead() {
|
|
158
|
+
if (this.pending?.label) {
|
|
159
|
+
const p = this.pending;
|
|
160
|
+
this.pending = null;
|
|
161
|
+
p.resolve(null);
|
|
162
|
+
}
|
|
163
|
+
if (this.menu?.kind === 'ask') {
|
|
164
|
+
const m = this.menu;
|
|
165
|
+
this.menu = null;
|
|
166
|
+
m.resolve(null);
|
|
167
|
+
} else if (this.menu) this.finishMenu(this.menu.options.length - 1);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
submit() {
|
|
171
|
+
let text = this.buffer;
|
|
172
|
+
this.buffer = '';
|
|
173
|
+
this.cursor = 0;
|
|
174
|
+
this.histIdx = -1;
|
|
175
|
+
this.suggest = null;
|
|
176
|
+
this.showHelp = false;
|
|
177
|
+
if (this.pending) {
|
|
178
|
+
const p = this.pending;
|
|
179
|
+
this.pending = null;
|
|
180
|
+
if (!p.label) {
|
|
181
|
+
if (text.trim()) this.remember(text);
|
|
182
|
+
this.echoUser(text);
|
|
183
|
+
} else {
|
|
184
|
+
this.eraseRegion();
|
|
185
|
+
this.out.write(`${p.label}${p.secret ? '' : text}\n`);
|
|
186
|
+
}
|
|
187
|
+
this.render();
|
|
188
|
+
p.resolve(text);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (!text.trim()) return this.render();
|
|
192
|
+
this.remember(text);
|
|
193
|
+
// Side questions are answered right away, even while leto is working.
|
|
194
|
+
if (this.busy && /^\/btw(\s|$)/.test(text.trim()) && this.onImmediate) {
|
|
195
|
+
this.render();
|
|
196
|
+
this.onImmediate(text.trim());
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
this.queued.push(text);
|
|
200
|
+
this.render();
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
remember(text) {
|
|
204
|
+
if (this.historyList.at(-1) !== text) this.historyList.push(text);
|
|
205
|
+
if (this.historyFile) {
|
|
206
|
+
try {
|
|
207
|
+
fs.appendFileSync(this.historyFile, text.replace(/\n/g, ' ') + '\n', { mode: 0o600 });
|
|
208
|
+
} catch {}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Your message: a raised gold-edged panel across the full width, so it stands
|
|
213
|
+
// apart from both the terminal and leto's replies.
|
|
214
|
+
echoUser(text) {
|
|
215
|
+
const c = this.c;
|
|
216
|
+
const cols = Math.max(30, (this.out.columns || 100) - 1);
|
|
217
|
+
const width = cols - 3;
|
|
218
|
+
const rows = [];
|
|
219
|
+
for (const line of text.split('\n')) {
|
|
220
|
+
if (!line) rows.push('');
|
|
221
|
+
for (let i = 0; i < line.length; i += width) rows.push(line.slice(i, i + width));
|
|
222
|
+
}
|
|
223
|
+
const panel = (s, first) => {
|
|
224
|
+
const body = first ? c.bold(c.lilac(s)) : c.lilac(s);
|
|
225
|
+
return c.raiseBg(`${c.violet(GLYPH.user)} ${body}${' '.repeat(Math.max(0, cols - 2 - s.length))}`);
|
|
226
|
+
};
|
|
227
|
+
const lead = this.lastBlank ? '' : '\n';
|
|
228
|
+
this.printAbove(lead + rows.map((r) => panel(r, true)).join('\n') + '\n\n');
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
insert(s) {
|
|
232
|
+
this.buffer = this.buffer.slice(0, this.cursor) + s + this.buffer.slice(this.cursor);
|
|
233
|
+
this.cursor += s.length;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Ctrl+R: search earlier messages. Type to narrow, Ctrl+R for older matches,
|
|
237
|
+
// Enter to keep the match, Esc to go back to what you had.
|
|
238
|
+
searchKey(str, key) {
|
|
239
|
+
const h = this.hsearch;
|
|
240
|
+
const find = () => {
|
|
241
|
+
let skip = h.skip;
|
|
242
|
+
for (let i = this.historyList.length - 1; i >= 0; i--) {
|
|
243
|
+
if (!this.historyList[i].toLowerCase().includes(h.query.toLowerCase())) continue;
|
|
244
|
+
if (skip-- > 0) continue;
|
|
245
|
+
return this.historyList[i];
|
|
246
|
+
}
|
|
247
|
+
return null;
|
|
248
|
+
};
|
|
249
|
+
if (key.ctrl && key.name === 'r') h.skip++;
|
|
250
|
+
else if (key.name === 'escape' || (key.ctrl && (key.name === 'g' || key.name === 'c'))) {
|
|
251
|
+
this.buffer = h.saved;
|
|
252
|
+
this.cursor = this.buffer.length;
|
|
253
|
+
this.hsearch = null;
|
|
254
|
+
return this.render();
|
|
255
|
+
} else if (key.name === 'backspace') {
|
|
256
|
+
h.query = h.query.slice(0, -1);
|
|
257
|
+
h.skip = 0;
|
|
258
|
+
} else if (str && !key.ctrl && !key.meta && str.length === 1 && str >= ' ') {
|
|
259
|
+
h.query += str;
|
|
260
|
+
h.skip = 0;
|
|
261
|
+
} else {
|
|
262
|
+
this.hsearch = null;
|
|
263
|
+
if (key.name === 'return' || key.name === 'enter') return this.render();
|
|
264
|
+
return this.handleKey(str, key);
|
|
265
|
+
}
|
|
266
|
+
const match = find();
|
|
267
|
+
if (match === null && h.skip > 0) h.skip--;
|
|
268
|
+
const found = match ?? find();
|
|
269
|
+
if (found !== null) {
|
|
270
|
+
this.buffer = found;
|
|
271
|
+
this.cursor = found.length;
|
|
272
|
+
}
|
|
273
|
+
h.failed = found === null;
|
|
274
|
+
this.render();
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
setDraft(text) {
|
|
278
|
+
this.buffer = text;
|
|
279
|
+
this.cursor = text.length;
|
|
280
|
+
this.render();
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
handleKey(str, key) {
|
|
284
|
+
if (this.menu) return this.menuKey(str, key);
|
|
285
|
+
if (this.hsearch) return this.searchKey(str, key);
|
|
286
|
+
if (key.ctrl && key.name === 'r' && !this.busy) {
|
|
287
|
+
this.hsearch = { query: '', skip: 0, saved: this.buffer };
|
|
288
|
+
return this.render();
|
|
289
|
+
}
|
|
290
|
+
if (key.name === 'paste-start') return (this.pasting = true);
|
|
291
|
+
if (key.name === 'paste-end') {
|
|
292
|
+
this.pasting = false;
|
|
293
|
+
return this.afterEdit();
|
|
294
|
+
}
|
|
295
|
+
if (this.pasting) {
|
|
296
|
+
if (str) this.insert(str === '\r' ? '\n' : str);
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
const name = key.name;
|
|
300
|
+
if (key.ctrl && name === 'c') {
|
|
301
|
+
if (this.busy) return this.onEscape?.();
|
|
302
|
+
if (this.buffer) {
|
|
303
|
+
this.buffer = '';
|
|
304
|
+
this.cursor = 0;
|
|
305
|
+
return this.afterEdit();
|
|
306
|
+
}
|
|
307
|
+
if (this.exitArmed) {
|
|
308
|
+
if (this.pending) {
|
|
309
|
+
const p = this.pending;
|
|
310
|
+
this.pending = null;
|
|
311
|
+
p.resolve(null);
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
this.cleanup();
|
|
315
|
+
process.exit(0);
|
|
316
|
+
}
|
|
317
|
+
this.exitArmed = true;
|
|
318
|
+
setTimeout(() => {
|
|
319
|
+
this.exitArmed = false;
|
|
320
|
+
this.render();
|
|
321
|
+
}, 2000).unref?.();
|
|
322
|
+
return this.render();
|
|
323
|
+
}
|
|
324
|
+
this.exitArmed = false;
|
|
325
|
+
if (key.ctrl && name === 'd') {
|
|
326
|
+
if (!this.buffer && this.pending) {
|
|
327
|
+
const p = this.pending;
|
|
328
|
+
this.pending = null;
|
|
329
|
+
p.resolve(null);
|
|
330
|
+
}
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
if (name === 'escape') {
|
|
334
|
+
if (this.busy) return this.onEscape?.();
|
|
335
|
+
if (this.suggest) {
|
|
336
|
+
this.suggest = null;
|
|
337
|
+
this.suggestDismissed = this.buffer;
|
|
338
|
+
return this.render();
|
|
339
|
+
}
|
|
340
|
+
if (this.showHelp) {
|
|
341
|
+
this.showHelp = false;
|
|
342
|
+
return this.render();
|
|
343
|
+
}
|
|
344
|
+
// Esc Esc: clear what you typed; on an empty composer, rewind. (Two quick
|
|
345
|
+
// presses arrive as one event with the sequence "\x1b\x1b".)
|
|
346
|
+
if (this.escArmed || key.sequence === '\x1b\x1b') {
|
|
347
|
+
this.escArmed = false;
|
|
348
|
+
if (this.buffer) {
|
|
349
|
+
this.buffer = '';
|
|
350
|
+
this.cursor = 0;
|
|
351
|
+
return this.afterEdit();
|
|
352
|
+
}
|
|
353
|
+
if (this.pending && !this.pending.label) this.onRewind?.();
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
this.escArmed = true;
|
|
357
|
+
setTimeout(() => (this.escArmed = false), 800).unref?.();
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
if (name === 'tab' && key.shift) {
|
|
361
|
+
this.onCycleMode?.();
|
|
362
|
+
return this.render();
|
|
363
|
+
}
|
|
364
|
+
if (name === 'tab') {
|
|
365
|
+
if (this.suggest) this.applySuggestion();
|
|
366
|
+
return this.afterEdit();
|
|
367
|
+
}
|
|
368
|
+
if (name === 'return' || name === 'enter') {
|
|
369
|
+
if (key.meta || key.shift) {
|
|
370
|
+
this.insert('\n');
|
|
371
|
+
return this.afterEdit();
|
|
372
|
+
}
|
|
373
|
+
if (this.buffer.slice(0, this.cursor).endsWith('\\')) {
|
|
374
|
+
this.buffer = this.buffer.slice(0, this.cursor - 1) + '\n' + this.buffer.slice(this.cursor);
|
|
375
|
+
return this.afterEdit();
|
|
376
|
+
}
|
|
377
|
+
if (this.suggest?.kind === 'command') {
|
|
378
|
+
const item = this.suggest.items[this.suggest.selected];
|
|
379
|
+
this.buffer = `/${item.value}`;
|
|
380
|
+
this.cursor = this.buffer.length;
|
|
381
|
+
} else if (this.suggest?.kind === 'file') {
|
|
382
|
+
this.applySuggestion();
|
|
383
|
+
return this.afterEdit();
|
|
384
|
+
}
|
|
385
|
+
return this.submit();
|
|
386
|
+
}
|
|
387
|
+
if (name === 'up' || name === 'down') {
|
|
388
|
+
if (this.suggest) {
|
|
389
|
+
const n = this.suggest.items.length;
|
|
390
|
+
this.suggest.selected = (this.suggest.selected + (name === 'up' ? n - 1 : 1)) % n;
|
|
391
|
+
return this.render();
|
|
392
|
+
}
|
|
393
|
+
const lines = this.buffer.slice(0, this.cursor).split('\n');
|
|
394
|
+
const totalLines = this.buffer.split('\n').length;
|
|
395
|
+
if (name === 'up' && lines.length > 1) return this.moveLine(-1);
|
|
396
|
+
if (name === 'down' && lines.length < totalLines) return this.moveLine(1);
|
|
397
|
+
return this.historyStep(name === 'up' ? 1 : -1);
|
|
398
|
+
}
|
|
399
|
+
if (name === 'left') this.cursor = Math.max(0, key.meta ? this.wordStart() : this.cursor - 1);
|
|
400
|
+
else if (name === 'right') this.cursor = Math.min(this.buffer.length, key.meta ? this.wordEnd() : this.cursor + 1);
|
|
401
|
+
else if (name === 'home' || (key.ctrl && name === 'a')) this.cursor = this.buffer.lastIndexOf('\n', this.cursor - 1) + 1;
|
|
402
|
+
else if (name === 'end' || (key.ctrl && name === 'e')) {
|
|
403
|
+
const nl = this.buffer.indexOf('\n', this.cursor);
|
|
404
|
+
this.cursor = nl < 0 ? this.buffer.length : nl;
|
|
405
|
+
} else if (name === 'backspace') {
|
|
406
|
+
if (key.meta || (key.ctrl && name === 'w')) this.deleteTo(this.wordStart());
|
|
407
|
+
else if (this.cursor > 0) this.deleteTo(this.cursor - 1);
|
|
408
|
+
} else if (key.ctrl && name === 'w') this.deleteTo(this.wordStart());
|
|
409
|
+
else if (name === 'delete') {
|
|
410
|
+
this.buffer = this.buffer.slice(0, this.cursor) + this.buffer.slice(this.cursor + 1);
|
|
411
|
+
} else if (key.ctrl && name === 'u') this.deleteTo(this.buffer.lastIndexOf('\n', this.cursor - 1) + 1);
|
|
412
|
+
else if (key.ctrl && name === 'k') {
|
|
413
|
+
const nl = this.buffer.indexOf('\n', this.cursor);
|
|
414
|
+
this.buffer = this.buffer.slice(0, this.cursor) + (nl < 0 ? '' : this.buffer.slice(nl));
|
|
415
|
+
} else if (key.ctrl && name === 'o') {
|
|
416
|
+
// Show the last tool's full output.
|
|
417
|
+
if (this.lastOutput) {
|
|
418
|
+
const lines = this.lastOutput.split('\n');
|
|
419
|
+
const shown = lines.slice(0, 400).map((l) => ` ${this.c.mist(l)}`).join('\n');
|
|
420
|
+
this.printAbove(`${shown}${lines.length > 400 ? `\n ${this.c.faint(`… ${lines.length - 400} more lines`)}` : ''}\n`);
|
|
421
|
+
}
|
|
422
|
+
return this.render();
|
|
423
|
+
} else if (key.ctrl && name === 'v') {
|
|
424
|
+
this.onPasteImage?.();
|
|
425
|
+
return this.render();
|
|
426
|
+
} else if (key.ctrl && name === 'l') {
|
|
427
|
+
this.clearScreen();
|
|
428
|
+
return this.render();
|
|
429
|
+
} else if (str === '?' && !this.buffer) {
|
|
430
|
+
this.showHelp = !this.showHelp;
|
|
431
|
+
return this.render();
|
|
432
|
+
} else if (str && !key.ctrl && !key.meta && !/[\x00-\x08\x0e-\x1f\x7f]/.test(str)) {
|
|
433
|
+
this.insert(str === '\r' ? '\n' : str);
|
|
434
|
+
} else return;
|
|
435
|
+
this.afterEdit();
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
deleteTo(pos) {
|
|
439
|
+
this.buffer = this.buffer.slice(0, pos) + this.buffer.slice(this.cursor);
|
|
440
|
+
this.cursor = pos;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
wordStart() {
|
|
444
|
+
let i = this.cursor;
|
|
445
|
+
while (i > 0 && /\s/.test(this.buffer[i - 1])) i--;
|
|
446
|
+
while (i > 0 && !/\s/.test(this.buffer[i - 1])) i--;
|
|
447
|
+
return i;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
wordEnd() {
|
|
451
|
+
let i = this.cursor;
|
|
452
|
+
while (i < this.buffer.length && /\s/.test(this.buffer[i])) i++;
|
|
453
|
+
while (i < this.buffer.length && !/\s/.test(this.buffer[i])) i++;
|
|
454
|
+
return i;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
moveLine(dir) {
|
|
458
|
+
const before = this.buffer.slice(0, this.cursor);
|
|
459
|
+
const lineStart = before.lastIndexOf('\n') + 1;
|
|
460
|
+
const col = this.cursor - lineStart;
|
|
461
|
+
if (dir < 0) {
|
|
462
|
+
const prevStart = this.buffer.lastIndexOf('\n', lineStart - 2) + 1;
|
|
463
|
+
this.cursor = Math.min(prevStart + col, lineStart - 1);
|
|
464
|
+
} else {
|
|
465
|
+
const nextStart = this.buffer.indexOf('\n', this.cursor) + 1;
|
|
466
|
+
const nextEnd = this.buffer.indexOf('\n', nextStart);
|
|
467
|
+
this.cursor = Math.min(nextStart + col, nextEnd < 0 ? this.buffer.length : nextEnd);
|
|
468
|
+
}
|
|
469
|
+
this.render();
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
historyStep(dir) {
|
|
473
|
+
const n = this.historyList.length;
|
|
474
|
+
if (!n) return;
|
|
475
|
+
if (this.histIdx === -1) this.draft = this.buffer;
|
|
476
|
+
const next = Math.max(-1, Math.min(n - 1, this.histIdx + dir));
|
|
477
|
+
this.histIdx = next;
|
|
478
|
+
this.buffer = next === -1 ? this.draft : this.historyList[n - 1 - next];
|
|
479
|
+
this.cursor = this.buffer.length;
|
|
480
|
+
this.render();
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
afterEdit() {
|
|
484
|
+
this.updateSuggestions();
|
|
485
|
+
this.render();
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// ---- suggestions -------------------------------------------------------
|
|
489
|
+
|
|
490
|
+
files() {
|
|
491
|
+
if (this.fileCache && Date.now() - this.fileCache.time < 30000) return this.fileCache.list;
|
|
492
|
+
let list = [];
|
|
493
|
+
const git = spawnSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], { cwd: this.cwd, encoding: 'utf8', maxBuffer: 20e6 });
|
|
494
|
+
if (git.status === 0) list = git.stdout.split('\n').filter(Boolean);
|
|
495
|
+
else {
|
|
496
|
+
const walk = (dir, rel) => {
|
|
497
|
+
if (list.length > 5000) return;
|
|
498
|
+
let entries = [];
|
|
499
|
+
try {
|
|
500
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
501
|
+
} catch {
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
for (const e of entries) {
|
|
505
|
+
if (e.name === 'node_modules' || e.name === '.git' || e.name.startsWith('.')) continue;
|
|
506
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
507
|
+
if (e.isDirectory()) walk(path.join(dir, e.name), r);
|
|
508
|
+
else list.push(r);
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
walk(this.cwd, '');
|
|
512
|
+
}
|
|
513
|
+
const dirs = new Set();
|
|
514
|
+
for (const f of list) {
|
|
515
|
+
const parts = f.split('/');
|
|
516
|
+
for (let i = 1; i < parts.length; i++) dirs.add(parts.slice(0, i).join('/') + '/');
|
|
517
|
+
}
|
|
518
|
+
list = [...dirs, ...list];
|
|
519
|
+
this.fileCache = { time: Date.now(), list };
|
|
520
|
+
return list;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
updateSuggestions() {
|
|
524
|
+
const prev = this.suggest;
|
|
525
|
+
this.suggest = null;
|
|
526
|
+
if (this.suggestDismissed === this.buffer) return;
|
|
527
|
+
this.suggestDismissed = null;
|
|
528
|
+
const before = this.buffer.slice(0, this.cursor);
|
|
529
|
+
let m;
|
|
530
|
+
if (/^\/[\w-]*$/.test(this.buffer)) {
|
|
531
|
+
const q = this.buffer.slice(1).toLowerCase();
|
|
532
|
+
const items = this.commandList()
|
|
533
|
+
.filter((c) => c.name.startsWith(q) || (q.length > 1 && c.name.includes(q)))
|
|
534
|
+
.sort((a, b) => Number(b.name.startsWith(q)) - Number(a.name.startsWith(q)))
|
|
535
|
+
.map((c) => ({ label: `/${c.name}`, value: c.name, hint: c.description }));
|
|
536
|
+
if (items.length) this.suggest = { kind: 'command', items, selected: 0 };
|
|
537
|
+
} else if ((m = before.match(/(?:^|\s)@([^\s]*)$/))) {
|
|
538
|
+
const q = m[1].toLowerCase();
|
|
539
|
+
const scored = [];
|
|
540
|
+
for (const f of this.files()) {
|
|
541
|
+
const lower = f.toLowerCase();
|
|
542
|
+
const i = lower.indexOf(q);
|
|
543
|
+
if (q && i < 0) continue;
|
|
544
|
+
const base = lower.slice(lower.lastIndexOf('/', lower.length - 2) + 1);
|
|
545
|
+
scored.push({ f, score: (base.startsWith(q) ? 0 : 2) + (i === 0 ? 0 : 1) + f.length / 1000 });
|
|
546
|
+
if (scored.length > 2000) break;
|
|
547
|
+
}
|
|
548
|
+
scored.sort((a, b) => a.score - b.score);
|
|
549
|
+
const items = scored.slice(0, 8).map(({ f }) => ({ label: `@${f}`, value: f }));
|
|
550
|
+
if (items.length) this.suggest = { kind: 'file', items, selected: 0, start: this.cursor - m[1].length - 1 };
|
|
551
|
+
}
|
|
552
|
+
if (this.suggest && prev?.kind === this.suggest.kind) {
|
|
553
|
+
this.suggest.selected = Math.min(prev.selected, this.suggest.items.length - 1);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
applySuggestion() {
|
|
558
|
+
const s = this.suggest;
|
|
559
|
+
if (!s) return;
|
|
560
|
+
const item = s.items[s.selected];
|
|
561
|
+
if (s.kind === 'command') {
|
|
562
|
+
this.buffer = `/${item.value} `;
|
|
563
|
+
this.cursor = this.buffer.length;
|
|
564
|
+
} else {
|
|
565
|
+
const insert = `@${item.value}${item.value.endsWith('/') ? '' : ' '}`;
|
|
566
|
+
this.buffer = this.buffer.slice(0, s.start) + insert + this.buffer.slice(this.cursor);
|
|
567
|
+
this.cursor = s.start + insert.length;
|
|
568
|
+
}
|
|
569
|
+
this.suggest = null;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// ---- permission menu ---------------------------------------------------
|
|
573
|
+
|
|
574
|
+
confirm(preview, toolName, { prefix } = {}) {
|
|
575
|
+
return new Promise((resolve) => {
|
|
576
|
+
this.stopSpinnerTimer();
|
|
577
|
+
const what = { edit_file: 'edits', write_file: 'file writes', bash: 'commands', web_fetch: 'web fetches', browser: 'browser actions' }[toolName] ?? `"${toolName}"`;
|
|
578
|
+
// Plan approval and leto's own settings are decided one at a time.
|
|
579
|
+
const once = toolName === 'exit_plan_mode' || toolName === 'leto';
|
|
580
|
+
const plan = toolName === 'exit_plan_mode';
|
|
581
|
+
this.menu = {
|
|
582
|
+
preview,
|
|
583
|
+
toolName,
|
|
584
|
+
options: [
|
|
585
|
+
{ label: plan ? 'Yes, start building' : 'Yes', value: 'yes' },
|
|
586
|
+
...(prefix ? [{ label: `Always \`${prefix}\` here`, value: 'prefix' }] : []),
|
|
587
|
+
...(once ? [] : [{ label: prefix ? 'All commands this session' : `Always allow ${what}`, value: 'always' }]),
|
|
588
|
+
{ label: plan ? 'No, keep planning' : 'No, I\'ll explain', value: 'no' },
|
|
589
|
+
],
|
|
590
|
+
selected: 0,
|
|
591
|
+
resolve,
|
|
592
|
+
};
|
|
593
|
+
this.render();
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// ---- questions from the model -----------------------------------------
|
|
598
|
+
|
|
599
|
+
// One question as a card: pick an option (or several), or type an answer.
|
|
600
|
+
// Resolves to { answer } or null when skipped.
|
|
601
|
+
async ask({ question, header, options = [], multiSelect = false, index = 0, total = 1 }) {
|
|
602
|
+
this.stopSpinnerTimer();
|
|
603
|
+
const OTHER = { label: 'Type my own answer', description: '', other: true };
|
|
604
|
+
const picked = await new Promise((resolve) => {
|
|
605
|
+
this.menu = { kind: 'ask', question, header, multiSelect, index, total, options: [...options, OTHER], selected: 0, checked: new Set(), resolve };
|
|
606
|
+
this.render();
|
|
607
|
+
});
|
|
608
|
+
let answer = null;
|
|
609
|
+
if (picked?.other) {
|
|
610
|
+
const typed = await this.readLine(` ${this.c.orchid('✎')} `);
|
|
611
|
+
answer = typed?.trim() ? typed.trim() : null;
|
|
612
|
+
} else if (picked) answer = picked.labels.join(', ');
|
|
613
|
+
const c = this.c;
|
|
614
|
+
this.printAbove(` ${c.orchid('?')} ${c.lilac(question)}
|
|
615
|
+
${c.faint(GLYPH.result)} ${answer ? c.mint(answer) : c.mist('skipped')}
|
|
616
|
+
`);
|
|
617
|
+
this.resumeSpinnerTimer();
|
|
618
|
+
this.render();
|
|
619
|
+
return answer ? { answer } : null;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
askKey(str, key) {
|
|
623
|
+
const m = this.menu;
|
|
624
|
+
const n = m.options.length;
|
|
625
|
+
const done = (value) => {
|
|
626
|
+
this.menu = null;
|
|
627
|
+
this.render();
|
|
628
|
+
m.resolve(value);
|
|
629
|
+
};
|
|
630
|
+
const choose = (i) => {
|
|
631
|
+
const o = m.options[i];
|
|
632
|
+
if (o.other) return done({ other: true });
|
|
633
|
+
if (m.multiSelect) {
|
|
634
|
+
// Enter on an option with nothing ticked picks just that one.
|
|
635
|
+
const labels = m.checked.size ? [...m.checked].sort((a, b) => a - b).map((j) => m.options[j].label) : [o.label];
|
|
636
|
+
return done({ labels });
|
|
637
|
+
}
|
|
638
|
+
return done({ labels: [o.label] });
|
|
639
|
+
};
|
|
640
|
+
if (key.name === 'up') m.selected = (m.selected + n - 1) % n;
|
|
641
|
+
else if (key.name === 'down' || (key.name === 'tab' && !key.shift)) m.selected = (m.selected + 1) % n;
|
|
642
|
+
else if (key.name === 'return' || key.name === 'enter') return choose(m.selected);
|
|
643
|
+
else if (key.name === 'escape' || (key.ctrl && key.name === 'c')) return done(null);
|
|
644
|
+
else if (m.multiSelect && (key.name === 'space' || str === ' ')) {
|
|
645
|
+
if (!m.options[m.selected].other) m.checked.has(m.selected) ? m.checked.delete(m.selected) : m.checked.add(m.selected);
|
|
646
|
+
} else if (/^[1-9]$/.test(str ?? '') && Number(str) <= n) {
|
|
647
|
+
const i = Number(str) - 1;
|
|
648
|
+
if (m.multiSelect && !m.options[i].other) {
|
|
649
|
+
m.checked.has(i) ? m.checked.delete(i) : m.checked.add(i);
|
|
650
|
+
m.selected = i;
|
|
651
|
+
} else return choose(i);
|
|
652
|
+
}
|
|
653
|
+
this.render();
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
askLayout(lines, cols) {
|
|
657
|
+
const c = this.c;
|
|
658
|
+
const m = this.menu;
|
|
659
|
+
const bar = c.orchid(GLYPH.user);
|
|
660
|
+
const inner = cols - 3;
|
|
661
|
+
const row = (s = '') => `${bar} ${truncate(s, inner)}`;
|
|
662
|
+
const head = [m.header ? c.bold(c.lilac(m.header)) : c.bold(c.lilac('Question')), m.total > 1 ? c.faint(`${m.index + 1} of ${m.total}`) : ''].filter(Boolean).join(' ');
|
|
663
|
+
lines.push(row(`${c.orchid('?')} ${head}`));
|
|
664
|
+
for (const l of wrapAnsi(m.question, Math.max(20, inner - 2))) lines.push(row(c.bold(l)));
|
|
665
|
+
lines.push(bar);
|
|
666
|
+
m.options.forEach((o, i) => {
|
|
667
|
+
const sel = i === m.selected;
|
|
668
|
+
const box = m.multiSelect && !o.other ? (m.checked.has(i) ? c.mint('◉ ') : c.faint('○ ')) : '';
|
|
669
|
+
const num = c.faint(`${i + 1}.`);
|
|
670
|
+
const label = o.other ? c.mist(o.label) : sel ? c.bold(c.violet(o.label)) : c.lilac(o.label);
|
|
671
|
+
const text = `${sel ? c.violet('❯') : ' '} ${num} ${box}${label}${o.description ? ` ${c.mist(o.description)}` : ''}`;
|
|
672
|
+
lines.push(row(sel ? c.raiseBg(truncate(text, inner)) : text));
|
|
673
|
+
});
|
|
674
|
+
lines.push(bar);
|
|
675
|
+
lines.push(row(c.faint(m.multiSelect ? '↑↓ move · space or number to tick · enter to send · esc to skip' : '↑↓ move · enter or number to answer · esc to skip')));
|
|
676
|
+
return { lines, cursorRow: lines.length - 1, cursorCol: 0 };
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
menuKey(str, key) {
|
|
680
|
+
const m = this.menu;
|
|
681
|
+
if (m.kind === 'ask') return this.askKey(str, key);
|
|
682
|
+
const n = m.options.length;
|
|
683
|
+
if (key.name === 'up' || key.name === 'left') m.selected = (m.selected + n - 1) % n;
|
|
684
|
+
else if (key.name === 'down' || key.name === 'right' || (key.name === 'tab' && !key.shift)) m.selected = (m.selected + 1) % n;
|
|
685
|
+
else if (key.name === 'return' || key.name === 'enter') return this.finishMenu(m.selected);
|
|
686
|
+
else if (key.name === 'escape' || (key.ctrl && key.name === 'c')) return this.finishMenu(n - 1);
|
|
687
|
+
else if (/^[1-9]$/.test(str ?? '') && Number(str) <= n) return this.finishMenu(Number(str) - 1);
|
|
688
|
+
else if (str === 'y') return this.finishMenu(0);
|
|
689
|
+
else if (str === 'n') return this.finishMenu(n - 1);
|
|
690
|
+
this.render();
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
finishMenu(index) {
|
|
694
|
+
const m = this.menu;
|
|
695
|
+
if (!m) return;
|
|
696
|
+
this.menu = null;
|
|
697
|
+
const choice = m.options[index];
|
|
698
|
+
if (choice.value === 'no') this.printAbove(` ${this.c.faint(GLYPH.result)} ${this.c.rose('declined')} ${this.c.mist('· tell leto what to do instead')}\n`);
|
|
699
|
+
else if (choice.value === 'always') this.printAbove(` ${this.c.faint(GLYPH.result)} ${this.c.mint('allowed for the rest of this session')}\n`);
|
|
700
|
+
else if (choice.value === 'prefix') this.printAbove(` ${this.c.faint(GLYPH.result)} ${this.c.mint(`${choice.label.replace(/^Always /, '').replace(/ here$/, '')} will run without asking in this project`)} ${this.c.mist('· /permissions to change')}\n`);
|
|
701
|
+
this.resumeSpinnerTimer();
|
|
702
|
+
this.render();
|
|
703
|
+
m.resolve(choice.value);
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// ---- output ------------------------------------------------------------
|
|
707
|
+
|
|
708
|
+
// Print complete lines above the live region.
|
|
709
|
+
printAbove(s) {
|
|
710
|
+
this.lastBlank = s.endsWith('\n\n') || (s === '\n' && this.lastEndsNewline);
|
|
711
|
+
this.lastEndsNewline = s.endsWith('\n');
|
|
712
|
+
this.transcript.push(s);
|
|
713
|
+
this.transcriptSize += s.length;
|
|
714
|
+
while (this.transcriptSize > 2_000_000 && this.transcript.length > 1) this.transcriptSize -= this.transcript.shift().length;
|
|
715
|
+
if (!this.active) {
|
|
716
|
+
this.out.write(s);
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
this.eraseRegion();
|
|
720
|
+
this.out.write(s);
|
|
721
|
+
this.contentRows = Math.min(this.out.rows || 24, this.contentRows + this.countRows(s));
|
|
722
|
+
this.drawRegion();
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// Screen rows a chunk of output takes, counting wrapped lines.
|
|
726
|
+
countRows(s) {
|
|
727
|
+
const cols = Math.max(1, this.out.columns || 100);
|
|
728
|
+
const lines = s.split('\n');
|
|
729
|
+
if (lines.at(-1) === '') lines.pop();
|
|
730
|
+
return lines.reduce((n, l) => n + Math.max(1, Math.ceil(visibleLength(l) / cols)), 0);
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
// Clear the screen and scrollback, and forget what was printed, so a resize
|
|
734
|
+
// doesn't bring it back. The input area is redrawn by the next render.
|
|
735
|
+
clearScreen({ keepScrollback = false } = {}) {
|
|
736
|
+
this.thinkBuf = '';
|
|
737
|
+
this.md = null;
|
|
738
|
+
this.mode = null;
|
|
739
|
+
this.partial = '';
|
|
740
|
+
this.transcript = [];
|
|
741
|
+
this.transcriptSize = 0;
|
|
742
|
+
this.out.write(keepScrollback ? '\x1b[2J\x1b[H' : '\x1b[2J\x1b[3J\x1b[H');
|
|
743
|
+
this.regionRows = 0;
|
|
744
|
+
this.regionCursorRow = 0;
|
|
745
|
+
this.regionCursorCol = 0;
|
|
746
|
+
this.regionWidths = [];
|
|
747
|
+
this.contentRows = 0;
|
|
748
|
+
this.lastBlank = true;
|
|
749
|
+
this.atLineStart = true;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
handleResize() {
|
|
753
|
+
const cols = this.out.columns;
|
|
754
|
+
if (cols === this.lastCols || !this.active) return this.render();
|
|
755
|
+
this.lastCols = cols;
|
|
756
|
+
// Clear screen and scrollback, reprint the conversation at the new width.
|
|
757
|
+
const all = this.transcript.join('');
|
|
758
|
+
this.out.write('\x1b[?25l\x1b[2J\x1b[3J\x1b[H' + all);
|
|
759
|
+
this.contentRows = Math.min(this.out.rows || 24, this.countRows(all));
|
|
760
|
+
this.regionRows = 0;
|
|
761
|
+
this.drawRegion();
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
write(stream, s) {
|
|
765
|
+
if (!s) return;
|
|
766
|
+
this.partial += s;
|
|
767
|
+
const nl = this.partial.lastIndexOf('\n');
|
|
768
|
+
this.atLineStart = this.partial === '' || this.partial.endsWith('\n');
|
|
769
|
+
if (nl < 0) return;
|
|
770
|
+
const chunk = this.partial.slice(0, nl + 1);
|
|
771
|
+
this.partial = this.partial.slice(nl + 1);
|
|
772
|
+
this.atLineStart = this.partial === '';
|
|
773
|
+
this.printAbove(chunk);
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
flushPartial() {
|
|
777
|
+
if (this.partial) {
|
|
778
|
+
const p = this.partial;
|
|
779
|
+
this.partial = '';
|
|
780
|
+
this.printAbove(p + '\n');
|
|
781
|
+
}
|
|
782
|
+
this.atLineStart = true;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
newlineIfNeeded() {
|
|
786
|
+
if (this.partial) this.flushPartial();
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
text(s) {
|
|
790
|
+
this.addTokens(s.length / 4);
|
|
791
|
+
if (this.mode === 'thinking') {
|
|
792
|
+
this.flushThinking();
|
|
793
|
+
this.mode = null;
|
|
794
|
+
}
|
|
795
|
+
if (this.mode !== 'text') {
|
|
796
|
+
this.md = new MarkdownStream(this.c, { width: this.width - 2 });
|
|
797
|
+
this.firstLine = true;
|
|
798
|
+
this.mode = 'text';
|
|
799
|
+
}
|
|
800
|
+
this.emitText(this.md.push(s));
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
emitText(rendered) {
|
|
804
|
+
if (!rendered) return;
|
|
805
|
+
const lines = rendered.split('\n');
|
|
806
|
+
lines.pop();
|
|
807
|
+
const width = Math.max(20, (this.out.columns || 100) - 3);
|
|
808
|
+
const out = [];
|
|
809
|
+
for (const l of lines) {
|
|
810
|
+
for (const [i, part] of wrapAnsi(l, width).entries()) {
|
|
811
|
+
const prefix = this.firstLine ? `${this.c.violet(GLYPH.reply)} ` : ' ';
|
|
812
|
+
this.firstLine = false;
|
|
813
|
+
out.push(prefix + (i ? part.replace(/^/, '') : part));
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
this.write(this.out, out.join('\n') + '\n');
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
thinking(s) {
|
|
820
|
+
this.addTokens(s.length / 4);
|
|
821
|
+
if (this.spinner) this.spinner.label = 'Thinking';
|
|
822
|
+
if (this.mode === 'text') this.endText();
|
|
823
|
+
this.mode = 'thinking';
|
|
824
|
+
this.thinkBuf = (this.thinkBuf ?? '') + s;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
// Print the thinking summary, dim, above the reply.
|
|
828
|
+
flushThinking() {
|
|
829
|
+
const text = (this.thinkBuf ?? '').trim();
|
|
830
|
+
this.thinkBuf = '';
|
|
831
|
+
if (!text) return;
|
|
832
|
+
const c = this.c;
|
|
833
|
+
const width = Math.max(20, this.width - 4);
|
|
834
|
+
const rows = [];
|
|
835
|
+
for (const para of text.split('\n')) {
|
|
836
|
+
if (!para.trim()) continue;
|
|
837
|
+
for (let i = 0; i < para.length; i += width) rows.push(para.slice(i, i + width));
|
|
838
|
+
}
|
|
839
|
+
const shown = rows.slice(0, 10);
|
|
840
|
+
const out = shown.map((r, i) => `${i === 0 ? `${c.orchid(GLYPH.thinking)} ` : ' '}${c.mist(c.italic(r))}`);
|
|
841
|
+
if (rows.length > shown.length) out.push(` ${c.faint(`+${rows.length - shown.length} more lines of thinking`)}`);
|
|
842
|
+
this.printAbove((this.lastBlank ? '' : '\n') + out.join('\n') + '\n\n');
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
endText() {
|
|
846
|
+
if (this.thinkBuf) this.flushThinking();
|
|
847
|
+
if (this.md) {
|
|
848
|
+
this.emitText(this.md.flush());
|
|
849
|
+
this.md = null;
|
|
850
|
+
this.write(this.out, '\n');
|
|
851
|
+
}
|
|
852
|
+
this.flushPartial();
|
|
853
|
+
this.mode = null;
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
toolStart(name, summary, opts) {
|
|
857
|
+
this.endText();
|
|
858
|
+
super.toolStart(name, summary, opts);
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
// ---- spinner -----------------------------------------------------------
|
|
862
|
+
|
|
863
|
+
startSpinner(label) {
|
|
864
|
+
if (this.spinner) {
|
|
865
|
+
if (label) this.spinner.label = label;
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
this.spinner = { label: label ?? VERBS[Math.floor(Math.random() * VERBS.length)], started: Date.now(), frame: 0, detail: '' };
|
|
869
|
+
this.resumeSpinnerTimer();
|
|
870
|
+
this.render();
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
resumeSpinnerTimer() {
|
|
874
|
+
if (!this.spinner || this.spinnerTimer) return;
|
|
875
|
+
this.spinnerTimer = setInterval(() => {
|
|
876
|
+
if (this.spinner) this.spinner.frame++;
|
|
877
|
+
this.render();
|
|
878
|
+
}, 120);
|
|
879
|
+
this.spinnerTimer.unref?.();
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
stopSpinnerTimer() {
|
|
883
|
+
clearInterval(this.spinnerTimer);
|
|
884
|
+
this.spinnerTimer = null;
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
stopSpinner() {
|
|
888
|
+
this.stopSpinnerTimer();
|
|
889
|
+
if (this.spinner) {
|
|
890
|
+
this.spinner = null;
|
|
891
|
+
this.render();
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
spinnerDetail(text) {
|
|
896
|
+
if (this.spinner) this.spinner.detail = String(text).replace(/\x1b\[[0-9;]*[A-Za-z]/g, '').slice(0, 200);
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
clearSpinnerLine() {}
|
|
900
|
+
|
|
901
|
+
// ---- live region ---------------------------------------------------------
|
|
902
|
+
|
|
903
|
+
// How many screen rows the cursor is below the top of the drawn region.
|
|
904
|
+
// If the terminal got narrower since we drew, long lines have re-wrapped
|
|
905
|
+
// onto extra rows, so count them at the current width.
|
|
906
|
+
rowsAboveCursor() {
|
|
907
|
+
const cols = Math.max(1, this.out.columns || 100);
|
|
908
|
+
let rows = 0;
|
|
909
|
+
for (let i = 0; i < this.regionCursorRow; i++) rows += Math.max(1, Math.ceil((this.regionWidths[i] ?? 0) / cols));
|
|
910
|
+
return rows + Math.floor((this.regionCursorCol ?? 0) / cols);
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
eraseRegion() {
|
|
914
|
+
if (!this.regionRows) return;
|
|
915
|
+
const up = this.rowsAboveCursor();
|
|
916
|
+
this.out.write(`${up ? `\x1b[${up}A` : ''}\r\x1b[J`);
|
|
917
|
+
this.regionRows = 0;
|
|
918
|
+
this.regionCursorRow = 0;
|
|
919
|
+
this.regionCursorCol = 0;
|
|
920
|
+
this.regionWidths = [];
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
render() {
|
|
924
|
+
if (!this.active) return;
|
|
925
|
+
let { lines, cursorRow, cursorCol } = this.layout();
|
|
926
|
+
const gap = Math.max(0, (this.out.rows || 24) - this.contentRows - lines.length);
|
|
927
|
+
if (gap) {
|
|
928
|
+
lines = [...Array(gap).fill(''), ...lines];
|
|
929
|
+
cursorRow = cursorRow === null ? null : cursorRow + gap;
|
|
930
|
+
}
|
|
931
|
+
let s = '\x1b[?25l';
|
|
932
|
+
if (this.regionRows) {
|
|
933
|
+
const up = this.rowsAboveCursor();
|
|
934
|
+
if (up) s += `\x1b[${up}A`;
|
|
935
|
+
}
|
|
936
|
+
s += '\r';
|
|
937
|
+
const max = Math.max(1, (this.out.columns || 100) - 1);
|
|
938
|
+
s += lines.map((l) => `\x1b[2K${visibleLength(l) > max ? truncate(l, max) : l}`).join('\n') + '\x1b[J';
|
|
939
|
+
const up = lines.length - 1 - cursorRow;
|
|
940
|
+
if (up > 0) s += `\x1b[${up}A`;
|
|
941
|
+
s += `\r${cursorCol > 0 ? `\x1b[${cursorCol}C` : ''}`;
|
|
942
|
+
if (cursorRow !== null && !this.menu) s += '\x1b[?25h';
|
|
943
|
+
this.out.write(s);
|
|
944
|
+
this.regionRows = lines.length;
|
|
945
|
+
this.regionCursorRow = cursorRow ?? lines.length - 1;
|
|
946
|
+
this.regionCursorCol = cursorCol;
|
|
947
|
+
this.regionWidths = lines.map((l) => Math.min(visibleLength(l), max));
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
drawRegion() {
|
|
951
|
+
this.regionRows = 0;
|
|
952
|
+
this.regionCursorRow = 0;
|
|
953
|
+
this.regionCursorCol = 0;
|
|
954
|
+
this.regionWidths = [];
|
|
955
|
+
this.render();
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
layout() {
|
|
959
|
+
const c = this.c;
|
|
960
|
+
const cols = Math.max(30, (this.out.columns || 100) - 1);
|
|
961
|
+
const lines = [];
|
|
962
|
+
if (this.spinner && !this.menu) {
|
|
963
|
+
const s = this.spinner;
|
|
964
|
+
const secs = Math.floor((Date.now() - s.started) / 1000);
|
|
965
|
+
const meta = [`${secs}s`];
|
|
966
|
+
if (this.tokens >= 1) meta.push(`↓ ${fmtTokens(Math.round(this.tokens))}`);
|
|
967
|
+
meta.push('esc to interrupt');
|
|
968
|
+
lines.push(truncate(`${c.orchid(SPIN[s.frame % SPIN.length])} ${c.shimmer(s.label + '…', s.frame)} ${c.faint(meta.join(' · '))}`, cols - 1));
|
|
969
|
+
if (s.detail) lines.push(truncate(` ${c.faint(GLYPH.result)} ${c.mist(s.detail)}`, cols - 1));
|
|
970
|
+
lines.push('');
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
if (this.menu) return this.menuLayout(lines, cols);
|
|
974
|
+
|
|
975
|
+
for (const q of this.queued) lines.push(truncate(`${c.iris(GLYPH.user)} ${c.mist('queued')} ${c.faint('·')} ${c.lilac(q.replace(/\n/g, ' '))}`, cols - 1));
|
|
976
|
+
if (this.queued.length) lines.push('');
|
|
977
|
+
if (this.pending?.label) lines.push(truncate(this.pending.label.trimEnd(), cols - 1));
|
|
978
|
+
|
|
979
|
+
// The input rail: a gradient line (it drifts while leto works), then the prompt.
|
|
980
|
+
const phase = this.busy && this.spinner ? (this.spinner.frame * 0.015) % 1 : 0;
|
|
981
|
+
lines.push(this.busy ? c.gradient('─'.repeat(cols), [PALETTE.iris, PALETTE.violet, PALETTE.dusk, PALETTE.iris], phase) : c.gradient('─'.repeat(cols)));
|
|
982
|
+
const width = Math.max(10, cols - 3);
|
|
983
|
+
const shown = this.pending?.secret ? '•'.repeat(this.buffer.length) : this.buffer;
|
|
984
|
+
const rows = wrap(shown, width);
|
|
985
|
+
const top = lines.length;
|
|
986
|
+
let cursorRow = null;
|
|
987
|
+
let cursorCol = 0;
|
|
988
|
+
const placeholder = !this.buffer && !this.pending?.label ? (this.busy ? 'Type ahead; your message will be sent next' : 'Ask, plan or build something. / commands @ files') : '';
|
|
989
|
+
rows.forEach((r, i) => {
|
|
990
|
+
const prefix = i === 0 ? `${this.busy ? c.iris(GLYPH.prompt) : c.orchid(GLYPH.prompt)} ` : ' ';
|
|
991
|
+
const body = placeholder && i === 0 ? c.faint(c.italic(truncate(placeholder, width))) : c.lilac(r.text);
|
|
992
|
+
lines.push(`${prefix}${body}`);
|
|
993
|
+
if (this.cursor >= r.start && this.cursor <= r.end && cursorRow === null) {
|
|
994
|
+
if (this.cursor === r.end && r.full && i < rows.length - 1) return;
|
|
995
|
+
cursorRow = lines.length - 1;
|
|
996
|
+
cursorCol = 2 + (this.cursor - r.start);
|
|
997
|
+
}
|
|
998
|
+
});
|
|
999
|
+
if (cursorRow === null) {
|
|
1000
|
+
cursorRow = top + rows.length - 1;
|
|
1001
|
+
cursorCol = 2 + (rows.at(-1)?.text.length ?? 0);
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
// Below the input: suggestions, shortcuts, or the hint line.
|
|
1005
|
+
if (this.suggest) {
|
|
1006
|
+
const s = this.suggest;
|
|
1007
|
+
const labelW = Math.min(28, Math.max(...s.items.map((x) => x.label.length)) + 2);
|
|
1008
|
+
// A window of rows that scrolls to keep the selection in view.
|
|
1009
|
+
const VISIBLE = 8;
|
|
1010
|
+
const total = s.items.length;
|
|
1011
|
+
s.top = Math.min(Math.max(0, s.top ?? 0), Math.max(0, total - VISIBLE));
|
|
1012
|
+
if (s.selected < s.top) s.top = s.selected;
|
|
1013
|
+
if (s.selected >= s.top + VISIBLE) s.top = s.selected - VISIBLE + 1;
|
|
1014
|
+
for (const [j, item] of s.items.slice(s.top, s.top + VISIBLE).entries()) {
|
|
1015
|
+
const i = s.top + j;
|
|
1016
|
+
const sel = i === s.selected;
|
|
1017
|
+
const label = item.label.padEnd(labelW);
|
|
1018
|
+
const row = ` ${sel ? c.bold(c.violet(label)) : c.lilac(label)}${item.hint ? (sel ? c.lilac(item.hint) : c.mist(item.hint)) : ''}`;
|
|
1019
|
+
const fit = truncate(row, cols - 1);
|
|
1020
|
+
lines.push(sel ? c.raiseBg(fit + ' '.repeat(Math.max(0, cols - 1 - visibleLength(fit)))) : fit);
|
|
1021
|
+
}
|
|
1022
|
+
if (total > VISIBLE) {
|
|
1023
|
+
const above = s.top;
|
|
1024
|
+
const below = total - s.top - VISIBLE;
|
|
1025
|
+
const parts = [above ? `↑ ${above} more` : '', below ? `↓ ${below} more` : ''].filter(Boolean);
|
|
1026
|
+
lines.push(truncate(` ${c.faint(`${parts.join(' ')} · ${s.selected + 1}/${total}`)}`, cols - 1));
|
|
1027
|
+
}
|
|
1028
|
+
} else if (this.showHelp) {
|
|
1029
|
+
const k = (key, desc) => `${c.violet(key)} ${c.mist(desc)}`;
|
|
1030
|
+
const help = [
|
|
1031
|
+
[k('/', 'commands'), k('@', 'attach files'), k('\\⏎', 'new line')],
|
|
1032
|
+
[k('⇧⇥', 'cycle modes'), k('esc', 'interrupt'), k('↑↓', 'history')],
|
|
1033
|
+
[k('tab', 'complete'), k('esc esc', 'clear input / rewind'), k('ctrl+c', 'clear / exit')],
|
|
1034
|
+
[k('ctrl+r', 'search history'), k('ctrl+o', 'full tool output'), k('ctrl+v', 'paste image')],
|
|
1035
|
+
];
|
|
1036
|
+
for (const row of help) lines.push(' ' + row.map((x) => x + ' '.repeat(Math.max(2, 24 - visibleLength(x)))).join(''));
|
|
1037
|
+
} else {
|
|
1038
|
+
const left = this.hsearch
|
|
1039
|
+
? `${c.violet('search history:')} ${c.lilac(this.hsearch.query)}${c.faint('▏')} ${this.hsearch.failed ? c.rose('no match') : c.faint('ctrl+r older · enter keep · esc cancel')}`
|
|
1040
|
+
: this.exitArmed ? c.amber('press ctrl+c again to exit') : this.escArmed && !this.buffer && this.pending ? c.amber('esc again to rewind the conversation') : this.modeLabel() || c.faint('? shortcuts');
|
|
1041
|
+
const right = c.mist(this.statusLine());
|
|
1042
|
+
const gap = Math.max(2, cols - 3 - visibleLength(left) - visibleLength(right));
|
|
1043
|
+
lines.push(truncate(` ${left}${' '.repeat(gap)}${right}`, cols - 1));
|
|
1044
|
+
}
|
|
1045
|
+
return { lines, cursorRow, cursorCol };
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
// A permission request: a card with an orchid edge, the preview, and choices.
|
|
1049
|
+
menuLayout(lines, cols) {
|
|
1050
|
+
if (this.menu.kind === 'ask') return this.askLayout(lines, cols);
|
|
1051
|
+
const c = this.c;
|
|
1052
|
+
const m = this.menu;
|
|
1053
|
+
const bar = c.orchid(GLYPH.user);
|
|
1054
|
+
const inner = cols - 3;
|
|
1055
|
+
const row = (s = '') => `${bar} ${truncate(s, inner)}`;
|
|
1056
|
+
const label = { edit_file: 'Edit', write_file: 'Write', bash: 'Bash', web_fetch: 'Fetch' }[m.toolName] ?? (m.toolName ?? '').replace(/^mcp__/, '').replace(/__/, ':');
|
|
1057
|
+
let title = m.preview?.title ?? 'wants to run';
|
|
1058
|
+
if (title.toLowerCase().startsWith(label.toLowerCase() + ' ')) title = title.slice(label.length + 1);
|
|
1059
|
+
lines.push(row(`${c.violet(GLYPH.tool)} ${c.bold(c.lilac(label))} ${c.mist(title)}`));
|
|
1060
|
+
const body = m.preview?.lines ?? [];
|
|
1061
|
+
if (body.length) {
|
|
1062
|
+
lines.push(bar);
|
|
1063
|
+
const w = Math.max(20, inner - 8);
|
|
1064
|
+
for (const { sign, text, n } of body.slice(0, 16)) {
|
|
1065
|
+
const num = n !== undefined ? c.faint(String(n).padStart(4)) : ' ';
|
|
1066
|
+
const t = truncate(`${sign} ${text}`, w);
|
|
1067
|
+
const padded = t + ' '.repeat(Math.max(0, w - visibleLength(t)));
|
|
1068
|
+
const styled = sign === '+' ? c.addBg(c.mint(padded)) : sign === '-' ? c.delBg(c.rose(padded)) : sign === '$' ? c.panelBg(c.lilac(padded)) : c.mist(t);
|
|
1069
|
+
lines.push(row(`${num} ${styled}`));
|
|
1070
|
+
}
|
|
1071
|
+
if (body.length > 16) lines.push(row(c.faint(` +${body.length - 16} more lines`)));
|
|
1072
|
+
}
|
|
1073
|
+
lines.push(bar);
|
|
1074
|
+
// Choices as chips side by side, or stacked when the terminal is narrow.
|
|
1075
|
+
const chips = m.options.map((o, i) => {
|
|
1076
|
+
const text = ` ${i + 1} ${o.label} `;
|
|
1077
|
+
return i === m.selected ? c.violetBg(c.ink(c.bold(text))) : c.raiseBg(c.lilac(text));
|
|
1078
|
+
});
|
|
1079
|
+
const together = chips.join(' ');
|
|
1080
|
+
if (visibleLength(together) <= inner - 2) lines.push(row(together));
|
|
1081
|
+
else chips.forEach((chip) => lines.push(row(chip)));
|
|
1082
|
+
lines.push(row(c.faint('←→ choose · enter confirm · esc to say no')));
|
|
1083
|
+
return { lines, cursorRow: lines.length - 1, cursorCol: 0 };
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
// ---- welcome -----------------------------------------------------------
|
|
1087
|
+
|
|
1088
|
+
banner({ version, model, provider, cwd, instructions = [], resumed, mcp = [], hooks = 0, skills = 0, update }) {
|
|
1089
|
+
const c = this.c;
|
|
1090
|
+
const home = process.env.HOME ?? '';
|
|
1091
|
+
const tild = (p) => (home && p.startsWith(home) ? '~' + p.slice(home.length) : p);
|
|
1092
|
+
const side = [`${c.lilac(c.bold('leto'))} ${c.mist(`v${version}`)}`, c.mist('a coding agent by Mumbrane')];
|
|
1093
|
+
let out = '\n';
|
|
1094
|
+
LOGO.forEach((row, i) => (out += ` ${c.bold(c.gradient(row))} ${side[i] ?? ''}\n`));
|
|
1095
|
+
out += '\n';
|
|
1096
|
+
const facts = [
|
|
1097
|
+
['model', `${c.lilac(model)} ${c.faint('·')} ${c.mist(provider)}`],
|
|
1098
|
+
['folder', c.lilac(middle(tild(cwd), Math.max(20, (this.out.columns || 100) - 16)))],
|
|
1099
|
+
];
|
|
1100
|
+
if (instructions.length) facts.push(['notes', c.lilac(instructions.map((f) => tild(f).split('/').pop()).join(', '))]);
|
|
1101
|
+
if (mcp.length) facts.push(['mcp', mcp.map((s) => (s.status === 'connected' ? `${c.lilac(s.name)} ${c.faint(`${s.tools.length} tools`)}` : c.rose(`${s.name} failed`))).join(c.faint(' · '))]);
|
|
1102
|
+
if (hooks) facts.push(['hooks', c.lilac(`${hooks} active`)]);
|
|
1103
|
+
if (skills) facts.push(['skills', c.lilac(`${skills} available`)]);
|
|
1104
|
+
if (resumed) facts.push(['session', c.lilac(resumed)]);
|
|
1105
|
+
for (const [k, v] of facts) out += ` ${c.iris(GLYPH.tool)} ${c.mist(k.padEnd(8))} ${v}\n`;
|
|
1106
|
+
if (update) out += `\n ${c.orchid('↑')} ${c.lilac(`leto ${update} is out`)} ${c.faint('·')} ${c.mist('npm install -g @mumbrane/leto')}\n`;
|
|
1107
|
+
out += `\n ${c.mist(instructions.length || resumed ? 'What are we building?' : 'Ask a question, describe a task, or run /init to map this project.')}\n`;
|
|
1108
|
+
const k = (key, desc) => `${c.violet(key)} ${c.faint(desc)}`;
|
|
1109
|
+
out += ` ${[k('/', 'commands'), k('@', 'files'), k('⇧⇥', 'modes'), k('esc', 'interrupt'), k('?', 'shortcuts')].join(' ')}\n`;
|
|
1110
|
+
this.printAbove(out + '\n');
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
info(msg) {
|
|
1114
|
+
this.endText();
|
|
1115
|
+
this.write(this.out, this.c.mist(msg) + '\n');
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
// Shorten a path in the middle: ~/projects/…/src/app.js
|
|
1120
|
+
function middle(s, max) {
|
|
1121
|
+
if (s.length <= max) return s;
|
|
1122
|
+
const keep = max - 1;
|
|
1123
|
+
return s.slice(0, Math.ceil(keep * 0.35)) + '…' + s.slice(s.length - Math.floor(keep * 0.65));
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
// Word-wrap a styled line to `width` visible columns. Continuation lines get
|
|
1127
|
+
// a hanging indent that lines up with the text after a bullet or number.
|
|
1128
|
+
export function wrapAnsi(line, width) {
|
|
1129
|
+
if (visibleLength(line) <= width) return [line];
|
|
1130
|
+
const plain = line.replace(/\x1b\[[0-9;]*m/g, '');
|
|
1131
|
+
const lead = plain.match(/^(\s*(?:[•◦○●◉┃]|\d+\.)?\s*)/)?.[1] ?? '';
|
|
1132
|
+
const indent = ' '.repeat(Math.min(lead.length, Math.floor(width / 2)));
|
|
1133
|
+
const tokens = line.match(/\x1b\[[0-9;]*m|\s+|[^\s\x1b]+/g) ?? [];
|
|
1134
|
+
const rows = [];
|
|
1135
|
+
let cur = '';
|
|
1136
|
+
let len = 0;
|
|
1137
|
+
for (const t of tokens) {
|
|
1138
|
+
if (t.startsWith('\x1b')) {
|
|
1139
|
+
cur += t;
|
|
1140
|
+
continue;
|
|
1141
|
+
}
|
|
1142
|
+
if (len + t.length > width && len > indent.length) {
|
|
1143
|
+
rows.push(cur);
|
|
1144
|
+
cur = indent;
|
|
1145
|
+
len = indent.length;
|
|
1146
|
+
if (/^\s+$/.test(t)) continue;
|
|
1147
|
+
}
|
|
1148
|
+
// A single word longer than the line: hard-break it.
|
|
1149
|
+
let word = t;
|
|
1150
|
+
while (len + word.length > width) {
|
|
1151
|
+
const room = width - len;
|
|
1152
|
+
cur += word.slice(0, room);
|
|
1153
|
+
rows.push(cur);
|
|
1154
|
+
word = word.slice(room);
|
|
1155
|
+
cur = indent;
|
|
1156
|
+
len = indent.length;
|
|
1157
|
+
}
|
|
1158
|
+
cur += word;
|
|
1159
|
+
len += word.length;
|
|
1160
|
+
}
|
|
1161
|
+
if (cur.trim()) rows.push(cur);
|
|
1162
|
+
return rows;
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
// Wrap text into rows of at most `width` characters, tracking source offsets.
|
|
1166
|
+
function wrap(text, width) {
|
|
1167
|
+
const rows = [];
|
|
1168
|
+
let offset = 0;
|
|
1169
|
+
for (const line of text.split('\n')) {
|
|
1170
|
+
if (!line.length) rows.push({ text: '', start: offset, end: offset, full: false });
|
|
1171
|
+
for (let i = 0; i < line.length; i += width) {
|
|
1172
|
+
const part = line.slice(i, i + width);
|
|
1173
|
+
rows.push({ text: part, start: offset + i, end: offset + i + part.length, full: part.length === width });
|
|
1174
|
+
}
|
|
1175
|
+
offset += line.length + 1;
|
|
1176
|
+
}
|
|
1177
|
+
if (!rows.length) rows.push({ text: '', start: 0, end: 0, full: false });
|
|
1178
|
+
return rows;
|
|
1179
|
+
}
|