@mumbrane/arrakis 0.4.0 → 0.6.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 +54 -1
- package/package.json +1 -1
- package/src/agent.js +49 -7
- package/src/checkpoints.js +83 -0
- package/src/cli.js +346 -11
- package/src/config.js +11 -0
- package/src/hooks.js +114 -0
- package/src/input.js +71 -1
- package/src/jobs.js +97 -0
- package/src/mcp.js +343 -0
- package/src/permissions.js +5 -1
- package/src/session.js +1 -1
- package/src/tools.js +29 -5
- package/src/tui.js +812 -0
- package/src/ui.js +33 -7
- package/src/update.js +33 -0
package/src/tui.js
ADDED
|
@@ -0,0 +1,812 @@
|
|
|
1
|
+
// Full terminal UI for interactive sessions in a real terminal.
|
|
2
|
+
//
|
|
3
|
+
// The bottom of the screen is a "live region" that arrakis 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 { spawnSync } from 'node:child_process';
|
|
12
|
+
import { UI, truncate } from './ui.js';
|
|
13
|
+
import { MarkdownStream, visibleLength } from './markdown.js';
|
|
14
|
+
|
|
15
|
+
const SPIN = ['·', '✢', '✳', '✶', '✻', '✽', '✻', '✶', '✳', '✢'];
|
|
16
|
+
const VERBS = ['Thinking', 'Reading the sands', 'Harvesting spice', 'Folding space', 'Charting the dunes', 'Working', 'Considering', 'Tracing', 'Mapping'];
|
|
17
|
+
const fmtTokens = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
|
|
18
|
+
|
|
19
|
+
export class FancyUI extends UI {
|
|
20
|
+
constructor() {
|
|
21
|
+
super({ print: false });
|
|
22
|
+
this.fancy = true;
|
|
23
|
+
this.markdown = true;
|
|
24
|
+
this.buffer = '';
|
|
25
|
+
this.cursor = 0;
|
|
26
|
+
this.historyList = [];
|
|
27
|
+
this.histIdx = -1;
|
|
28
|
+
this.draft = '';
|
|
29
|
+
this.queued = [];
|
|
30
|
+
this.regionRows = 0;
|
|
31
|
+
this.regionCursorRow = 0;
|
|
32
|
+
this.active = false;
|
|
33
|
+
this.pending = null; // { resolve, label }
|
|
34
|
+
this.menu = null;
|
|
35
|
+
this.partial = '';
|
|
36
|
+
this.suggest = null;
|
|
37
|
+
this.showHelp = false;
|
|
38
|
+
this.exitArmed = false;
|
|
39
|
+
this.escArmed = false;
|
|
40
|
+
this.pasting = false;
|
|
41
|
+
this.tokens = 0;
|
|
42
|
+
this.modeLabel = () => '';
|
|
43
|
+
this.onCycleMode = null;
|
|
44
|
+
this.commandList = () => [];
|
|
45
|
+
this.cwd = process.cwd();
|
|
46
|
+
this.fileCache = null;
|
|
47
|
+
this.onKey = (str, key) => this.handleKey(str, key ?? {});
|
|
48
|
+
this.onResize = () => this.render();
|
|
49
|
+
process.once('exit', () => this.cleanup());
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// ---- lifecycle ---------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
start() {
|
|
55
|
+
if (this.active) return;
|
|
56
|
+
const stdin = process.stdin;
|
|
57
|
+
readline.emitKeypressEvents(stdin);
|
|
58
|
+
stdin.setRawMode(true);
|
|
59
|
+
stdin.resume();
|
|
60
|
+
stdin.on('keypress', this.onKey);
|
|
61
|
+
this.out.on('resize', this.onResize);
|
|
62
|
+
this.out.write('\x1b[?2004h'); // bracketed paste: pasted newlines don't submit
|
|
63
|
+
this.active = true;
|
|
64
|
+
if (!this.historyLoaded && this.historyFile) {
|
|
65
|
+
this.historyLoaded = true;
|
|
66
|
+
try {
|
|
67
|
+
this.historyList = fs.readFileSync(this.historyFile, 'utf8').split('\n').filter(Boolean).slice(-1000);
|
|
68
|
+
} catch {}
|
|
69
|
+
}
|
|
70
|
+
this.render();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
suspend() {
|
|
74
|
+
if (!this.active) return;
|
|
75
|
+
this.eraseRegion();
|
|
76
|
+
process.stdin.off('keypress', this.onKey);
|
|
77
|
+
this.out.off('resize', this.onResize);
|
|
78
|
+
this.out.write('\x1b[?2004l');
|
|
79
|
+
process.stdin.setRawMode(false);
|
|
80
|
+
this.active = false;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
resume() {
|
|
84
|
+
this.start();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
close() {
|
|
88
|
+
this.stopSpinner();
|
|
89
|
+
this.flushPartial();
|
|
90
|
+
this.suspend();
|
|
91
|
+
process.stdin.pause();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
cleanup() {
|
|
95
|
+
if (this.active) {
|
|
96
|
+
this.eraseRegion();
|
|
97
|
+
this.out.write('\x1b[?2004l\x1b[?25h');
|
|
98
|
+
try {
|
|
99
|
+
process.stdin.setRawMode(false);
|
|
100
|
+
} catch {}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
setBusy(busy) {
|
|
105
|
+
this.busy = busy;
|
|
106
|
+
if (busy) this.tokens = 0;
|
|
107
|
+
this.render();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
addTokens(n) {
|
|
111
|
+
this.tokens += n;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ---- input -------------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
prompt() {
|
|
117
|
+
return this.readLine(null);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
readLine(label) {
|
|
121
|
+
this.start();
|
|
122
|
+
if (!label && this.queued.length) {
|
|
123
|
+
const text = this.queued.shift();
|
|
124
|
+
this.echoUser(text);
|
|
125
|
+
this.render();
|
|
126
|
+
return Promise.resolve(text);
|
|
127
|
+
}
|
|
128
|
+
return new Promise((resolve) => {
|
|
129
|
+
this.pending = { resolve, label };
|
|
130
|
+
this.render();
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
cancelRead() {
|
|
135
|
+
if (this.pending?.label) {
|
|
136
|
+
const p = this.pending;
|
|
137
|
+
this.pending = null;
|
|
138
|
+
p.resolve(null);
|
|
139
|
+
}
|
|
140
|
+
if (this.menu) this.finishMenu(this.menu.options.length - 1);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
submit() {
|
|
144
|
+
let text = this.buffer;
|
|
145
|
+
this.buffer = '';
|
|
146
|
+
this.cursor = 0;
|
|
147
|
+
this.histIdx = -1;
|
|
148
|
+
this.suggest = null;
|
|
149
|
+
this.showHelp = false;
|
|
150
|
+
if (this.pending) {
|
|
151
|
+
const p = this.pending;
|
|
152
|
+
this.pending = null;
|
|
153
|
+
if (!p.label) {
|
|
154
|
+
if (text.trim()) this.remember(text);
|
|
155
|
+
this.echoUser(text);
|
|
156
|
+
} else {
|
|
157
|
+
this.eraseRegion();
|
|
158
|
+
this.out.write(`${p.label}${p.secret ? '' : text}\n`);
|
|
159
|
+
}
|
|
160
|
+
this.render();
|
|
161
|
+
p.resolve(text);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if (!text.trim()) return this.render();
|
|
165
|
+
this.remember(text);
|
|
166
|
+
this.queued.push(text);
|
|
167
|
+
this.render();
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
remember(text) {
|
|
171
|
+
if (this.historyList.at(-1) !== text) this.historyList.push(text);
|
|
172
|
+
if (this.historyFile) {
|
|
173
|
+
try {
|
|
174
|
+
fs.appendFileSync(this.historyFile, text.replace(/\n/g, ' ') + '\n', { mode: 0o600 });
|
|
175
|
+
} catch {}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
echoUser(text) {
|
|
180
|
+
const c = this.c;
|
|
181
|
+
const lines = text.split('\n');
|
|
182
|
+
this.printAbove(lines.map((l, i) => c.gray(`${i === 0 ? '>' : ' '} ${l}`)).join('\n') + '\n\n');
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
insert(s) {
|
|
186
|
+
this.buffer = this.buffer.slice(0, this.cursor) + s + this.buffer.slice(this.cursor);
|
|
187
|
+
this.cursor += s.length;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
handleKey(str, key) {
|
|
191
|
+
if (this.menu) return this.menuKey(str, key);
|
|
192
|
+
if (key.name === 'paste-start') return (this.pasting = true);
|
|
193
|
+
if (key.name === 'paste-end') {
|
|
194
|
+
this.pasting = false;
|
|
195
|
+
return this.afterEdit();
|
|
196
|
+
}
|
|
197
|
+
if (this.pasting) {
|
|
198
|
+
if (str) this.insert(str === '\r' ? '\n' : str);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
const name = key.name;
|
|
202
|
+
if (key.ctrl && name === 'c') {
|
|
203
|
+
if (this.busy) return this.onEscape?.();
|
|
204
|
+
if (this.buffer) {
|
|
205
|
+
this.buffer = '';
|
|
206
|
+
this.cursor = 0;
|
|
207
|
+
return this.afterEdit();
|
|
208
|
+
}
|
|
209
|
+
if (this.exitArmed) {
|
|
210
|
+
if (this.pending) {
|
|
211
|
+
const p = this.pending;
|
|
212
|
+
this.pending = null;
|
|
213
|
+
p.resolve(null);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
this.cleanup();
|
|
217
|
+
process.exit(0);
|
|
218
|
+
}
|
|
219
|
+
this.exitArmed = true;
|
|
220
|
+
setTimeout(() => {
|
|
221
|
+
this.exitArmed = false;
|
|
222
|
+
this.render();
|
|
223
|
+
}, 2000).unref?.();
|
|
224
|
+
return this.render();
|
|
225
|
+
}
|
|
226
|
+
this.exitArmed = false;
|
|
227
|
+
if (key.ctrl && name === 'd') {
|
|
228
|
+
if (!this.buffer && this.pending) {
|
|
229
|
+
const p = this.pending;
|
|
230
|
+
this.pending = null;
|
|
231
|
+
p.resolve(null);
|
|
232
|
+
}
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
if (name === 'escape') {
|
|
236
|
+
if (this.busy) return this.onEscape?.();
|
|
237
|
+
if (this.suggest) {
|
|
238
|
+
this.suggest = null;
|
|
239
|
+
this.suggestDismissed = this.buffer;
|
|
240
|
+
return this.render();
|
|
241
|
+
}
|
|
242
|
+
if (this.showHelp) {
|
|
243
|
+
this.showHelp = false;
|
|
244
|
+
return this.render();
|
|
245
|
+
}
|
|
246
|
+
if (this.buffer) {
|
|
247
|
+
if (this.escArmed) {
|
|
248
|
+
this.buffer = '';
|
|
249
|
+
this.cursor = 0;
|
|
250
|
+
this.escArmed = false;
|
|
251
|
+
return this.afterEdit();
|
|
252
|
+
}
|
|
253
|
+
this.escArmed = true;
|
|
254
|
+
setTimeout(() => (this.escArmed = false), 800).unref?.();
|
|
255
|
+
}
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
if (name === 'tab' && key.shift) {
|
|
259
|
+
this.onCycleMode?.();
|
|
260
|
+
return this.render();
|
|
261
|
+
}
|
|
262
|
+
if (name === 'tab') {
|
|
263
|
+
if (this.suggest) this.applySuggestion();
|
|
264
|
+
return this.afterEdit();
|
|
265
|
+
}
|
|
266
|
+
if (name === 'return' || name === 'enter') {
|
|
267
|
+
if (key.meta || key.shift) {
|
|
268
|
+
this.insert('\n');
|
|
269
|
+
return this.afterEdit();
|
|
270
|
+
}
|
|
271
|
+
if (this.buffer.slice(0, this.cursor).endsWith('\\')) {
|
|
272
|
+
this.buffer = this.buffer.slice(0, this.cursor - 1) + '\n' + this.buffer.slice(this.cursor);
|
|
273
|
+
return this.afterEdit();
|
|
274
|
+
}
|
|
275
|
+
if (this.suggest?.kind === 'command') {
|
|
276
|
+
const item = this.suggest.items[this.suggest.selected];
|
|
277
|
+
this.buffer = `/${item.value}`;
|
|
278
|
+
this.cursor = this.buffer.length;
|
|
279
|
+
} else if (this.suggest?.kind === 'file') {
|
|
280
|
+
this.applySuggestion();
|
|
281
|
+
return this.afterEdit();
|
|
282
|
+
}
|
|
283
|
+
return this.submit();
|
|
284
|
+
}
|
|
285
|
+
if (name === 'up' || name === 'down') {
|
|
286
|
+
if (this.suggest) {
|
|
287
|
+
const n = this.suggest.items.length;
|
|
288
|
+
this.suggest.selected = (this.suggest.selected + (name === 'up' ? n - 1 : 1)) % n;
|
|
289
|
+
return this.render();
|
|
290
|
+
}
|
|
291
|
+
const lines = this.buffer.slice(0, this.cursor).split('\n');
|
|
292
|
+
const totalLines = this.buffer.split('\n').length;
|
|
293
|
+
if (name === 'up' && lines.length > 1) return this.moveLine(-1);
|
|
294
|
+
if (name === 'down' && lines.length < totalLines) return this.moveLine(1);
|
|
295
|
+
return this.historyStep(name === 'up' ? 1 : -1);
|
|
296
|
+
}
|
|
297
|
+
if (name === 'left') this.cursor = Math.max(0, key.meta ? this.wordStart() : this.cursor - 1);
|
|
298
|
+
else if (name === 'right') this.cursor = Math.min(this.buffer.length, key.meta ? this.wordEnd() : this.cursor + 1);
|
|
299
|
+
else if (name === 'home' || (key.ctrl && name === 'a')) this.cursor = this.buffer.lastIndexOf('\n', this.cursor - 1) + 1;
|
|
300
|
+
else if (name === 'end' || (key.ctrl && name === 'e')) {
|
|
301
|
+
const nl = this.buffer.indexOf('\n', this.cursor);
|
|
302
|
+
this.cursor = nl < 0 ? this.buffer.length : nl;
|
|
303
|
+
} else if (name === 'backspace') {
|
|
304
|
+
if (key.meta || (key.ctrl && name === 'w')) this.deleteTo(this.wordStart());
|
|
305
|
+
else if (this.cursor > 0) this.deleteTo(this.cursor - 1);
|
|
306
|
+
} else if (key.ctrl && name === 'w') this.deleteTo(this.wordStart());
|
|
307
|
+
else if (name === 'delete') {
|
|
308
|
+
this.buffer = this.buffer.slice(0, this.cursor) + this.buffer.slice(this.cursor + 1);
|
|
309
|
+
} else if (key.ctrl && name === 'u') this.deleteTo(this.buffer.lastIndexOf('\n', this.cursor - 1) + 1);
|
|
310
|
+
else if (key.ctrl && name === 'k') {
|
|
311
|
+
const nl = this.buffer.indexOf('\n', this.cursor);
|
|
312
|
+
this.buffer = this.buffer.slice(0, this.cursor) + (nl < 0 ? '' : this.buffer.slice(nl));
|
|
313
|
+
} else if (key.ctrl && name === 'l') {
|
|
314
|
+
this.out.write('\x1b[2J\x1b[H');
|
|
315
|
+
this.regionRows = 0;
|
|
316
|
+
} else if (str === '?' && !this.buffer) {
|
|
317
|
+
this.showHelp = !this.showHelp;
|
|
318
|
+
return this.render();
|
|
319
|
+
} else if (str && !key.ctrl && !key.meta && !/[\x00-\x08\x0e-\x1f\x7f]/.test(str)) {
|
|
320
|
+
this.insert(str === '\r' ? '\n' : str);
|
|
321
|
+
} else return;
|
|
322
|
+
this.afterEdit();
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
deleteTo(pos) {
|
|
326
|
+
this.buffer = this.buffer.slice(0, pos) + this.buffer.slice(this.cursor);
|
|
327
|
+
this.cursor = pos;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
wordStart() {
|
|
331
|
+
let i = this.cursor;
|
|
332
|
+
while (i > 0 && /\s/.test(this.buffer[i - 1])) i--;
|
|
333
|
+
while (i > 0 && !/\s/.test(this.buffer[i - 1])) i--;
|
|
334
|
+
return i;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
wordEnd() {
|
|
338
|
+
let i = this.cursor;
|
|
339
|
+
while (i < this.buffer.length && /\s/.test(this.buffer[i])) i++;
|
|
340
|
+
while (i < this.buffer.length && !/\s/.test(this.buffer[i])) i++;
|
|
341
|
+
return i;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
moveLine(dir) {
|
|
345
|
+
const before = this.buffer.slice(0, this.cursor);
|
|
346
|
+
const lineStart = before.lastIndexOf('\n') + 1;
|
|
347
|
+
const col = this.cursor - lineStart;
|
|
348
|
+
if (dir < 0) {
|
|
349
|
+
const prevStart = this.buffer.lastIndexOf('\n', lineStart - 2) + 1;
|
|
350
|
+
this.cursor = Math.min(prevStart + col, lineStart - 1);
|
|
351
|
+
} else {
|
|
352
|
+
const nextStart = this.buffer.indexOf('\n', this.cursor) + 1;
|
|
353
|
+
const nextEnd = this.buffer.indexOf('\n', nextStart);
|
|
354
|
+
this.cursor = Math.min(nextStart + col, nextEnd < 0 ? this.buffer.length : nextEnd);
|
|
355
|
+
}
|
|
356
|
+
this.render();
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
historyStep(dir) {
|
|
360
|
+
const n = this.historyList.length;
|
|
361
|
+
if (!n) return;
|
|
362
|
+
if (this.histIdx === -1) this.draft = this.buffer;
|
|
363
|
+
const next = Math.max(-1, Math.min(n - 1, this.histIdx + dir));
|
|
364
|
+
this.histIdx = next;
|
|
365
|
+
this.buffer = next === -1 ? this.draft : this.historyList[n - 1 - next];
|
|
366
|
+
this.cursor = this.buffer.length;
|
|
367
|
+
this.render();
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
afterEdit() {
|
|
371
|
+
this.updateSuggestions();
|
|
372
|
+
this.render();
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// ---- suggestions -------------------------------------------------------
|
|
376
|
+
|
|
377
|
+
files() {
|
|
378
|
+
if (this.fileCache && Date.now() - this.fileCache.time < 30000) return this.fileCache.list;
|
|
379
|
+
let list = [];
|
|
380
|
+
const git = spawnSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], { cwd: this.cwd, encoding: 'utf8', maxBuffer: 20e6 });
|
|
381
|
+
if (git.status === 0) list = git.stdout.split('\n').filter(Boolean);
|
|
382
|
+
else {
|
|
383
|
+
const walk = (dir, rel) => {
|
|
384
|
+
if (list.length > 5000) return;
|
|
385
|
+
let entries = [];
|
|
386
|
+
try {
|
|
387
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
388
|
+
} catch {
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
for (const e of entries) {
|
|
392
|
+
if (e.name === 'node_modules' || e.name === '.git' || e.name.startsWith('.')) continue;
|
|
393
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
394
|
+
if (e.isDirectory()) walk(path.join(dir, e.name), r);
|
|
395
|
+
else list.push(r);
|
|
396
|
+
}
|
|
397
|
+
};
|
|
398
|
+
walk(this.cwd, '');
|
|
399
|
+
}
|
|
400
|
+
const dirs = new Set();
|
|
401
|
+
for (const f of list) {
|
|
402
|
+
const parts = f.split('/');
|
|
403
|
+
for (let i = 1; i < parts.length; i++) dirs.add(parts.slice(0, i).join('/') + '/');
|
|
404
|
+
}
|
|
405
|
+
list = [...dirs, ...list];
|
|
406
|
+
this.fileCache = { time: Date.now(), list };
|
|
407
|
+
return list;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
updateSuggestions() {
|
|
411
|
+
const prev = this.suggest;
|
|
412
|
+
this.suggest = null;
|
|
413
|
+
if (this.suggestDismissed === this.buffer) return;
|
|
414
|
+
this.suggestDismissed = null;
|
|
415
|
+
const before = this.buffer.slice(0, this.cursor);
|
|
416
|
+
let m;
|
|
417
|
+
if (/^\/[\w-]*$/.test(this.buffer)) {
|
|
418
|
+
const q = this.buffer.slice(1).toLowerCase();
|
|
419
|
+
const items = this.commandList()
|
|
420
|
+
.filter((c) => c.name.startsWith(q) || (q.length > 1 && c.name.includes(q)))
|
|
421
|
+
.sort((a, b) => Number(b.name.startsWith(q)) - Number(a.name.startsWith(q)))
|
|
422
|
+
.map((c) => ({ label: `/${c.name}`, value: c.name, hint: c.description }));
|
|
423
|
+
if (items.length) this.suggest = { kind: 'command', items, selected: 0 };
|
|
424
|
+
} else if ((m = before.match(/(?:^|\s)@([^\s]*)$/))) {
|
|
425
|
+
const q = m[1].toLowerCase();
|
|
426
|
+
const scored = [];
|
|
427
|
+
for (const f of this.files()) {
|
|
428
|
+
const lower = f.toLowerCase();
|
|
429
|
+
const i = lower.indexOf(q);
|
|
430
|
+
if (q && i < 0) continue;
|
|
431
|
+
const base = lower.slice(lower.lastIndexOf('/', lower.length - 2) + 1);
|
|
432
|
+
scored.push({ f, score: (base.startsWith(q) ? 0 : 2) + (i === 0 ? 0 : 1) + f.length / 1000 });
|
|
433
|
+
if (scored.length > 2000) break;
|
|
434
|
+
}
|
|
435
|
+
scored.sort((a, b) => a.score - b.score);
|
|
436
|
+
const items = scored.slice(0, 8).map(({ f }) => ({ label: `@${f}`, value: f }));
|
|
437
|
+
if (items.length) this.suggest = { kind: 'file', items, selected: 0, start: this.cursor - m[1].length - 1 };
|
|
438
|
+
}
|
|
439
|
+
if (this.suggest && prev?.kind === this.suggest.kind) {
|
|
440
|
+
this.suggest.selected = Math.min(prev.selected, this.suggest.items.length - 1);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
applySuggestion() {
|
|
445
|
+
const s = this.suggest;
|
|
446
|
+
if (!s) return;
|
|
447
|
+
const item = s.items[s.selected];
|
|
448
|
+
if (s.kind === 'command') {
|
|
449
|
+
this.buffer = `/${item.value} `;
|
|
450
|
+
this.cursor = this.buffer.length;
|
|
451
|
+
} else {
|
|
452
|
+
const insert = `@${item.value}${item.value.endsWith('/') ? '' : ' '}`;
|
|
453
|
+
this.buffer = this.buffer.slice(0, s.start) + insert + this.buffer.slice(this.cursor);
|
|
454
|
+
this.cursor = s.start + insert.length;
|
|
455
|
+
}
|
|
456
|
+
this.suggest = null;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// ---- permission menu ---------------------------------------------------
|
|
460
|
+
|
|
461
|
+
confirm(preview, toolName) {
|
|
462
|
+
return new Promise((resolve) => {
|
|
463
|
+
this.stopSpinnerTimer();
|
|
464
|
+
const what = { edit_file: 'edits', write_file: 'file writes', bash: 'commands', web_fetch: 'web fetches' }[toolName] ?? `"${toolName}"`;
|
|
465
|
+
this.menu = {
|
|
466
|
+
preview,
|
|
467
|
+
options: [
|
|
468
|
+
{ label: 'Yes', value: 'yes' },
|
|
469
|
+
{ label: `Yes, and don't ask again for ${what} this session`, value: 'always' },
|
|
470
|
+
{ label: 'No, and tell arrakis what to do differently', hint: 'esc', value: 'no' },
|
|
471
|
+
],
|
|
472
|
+
selected: 0,
|
|
473
|
+
resolve,
|
|
474
|
+
};
|
|
475
|
+
this.render();
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
menuKey(str, key) {
|
|
480
|
+
const m = this.menu;
|
|
481
|
+
const n = m.options.length;
|
|
482
|
+
if (key.name === 'up') m.selected = (m.selected + n - 1) % n;
|
|
483
|
+
else if (key.name === 'down' || (key.name === 'tab' && !key.shift)) m.selected = (m.selected + 1) % n;
|
|
484
|
+
else if (key.name === 'return' || key.name === 'enter') return this.finishMenu(m.selected);
|
|
485
|
+
else if (key.name === 'escape' || (key.ctrl && key.name === 'c')) return this.finishMenu(n - 1);
|
|
486
|
+
else if (/^[1-9]$/.test(str ?? '') && Number(str) <= n) return this.finishMenu(Number(str) - 1);
|
|
487
|
+
else if (str === 'y') return this.finishMenu(0);
|
|
488
|
+
else if (str === 'n') return this.finishMenu(n - 1);
|
|
489
|
+
this.render();
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
finishMenu(index) {
|
|
493
|
+
const m = this.menu;
|
|
494
|
+
if (!m) return;
|
|
495
|
+
this.menu = null;
|
|
496
|
+
const choice = m.options[index];
|
|
497
|
+
if (choice.value === 'no') this.printAbove(` ${this.c.gray('⎿')} ${this.c.red('Declined')}\n`);
|
|
498
|
+
this.resumeSpinnerTimer();
|
|
499
|
+
this.render();
|
|
500
|
+
m.resolve(choice.value);
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// ---- output ------------------------------------------------------------
|
|
504
|
+
|
|
505
|
+
// Print complete lines above the live region.
|
|
506
|
+
printAbove(s) {
|
|
507
|
+
if (!this.active) {
|
|
508
|
+
this.out.write(s);
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
this.eraseRegion();
|
|
512
|
+
this.out.write(s);
|
|
513
|
+
this.drawRegion();
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
write(stream, s) {
|
|
517
|
+
if (!s) return;
|
|
518
|
+
this.partial += s;
|
|
519
|
+
const nl = this.partial.lastIndexOf('\n');
|
|
520
|
+
this.atLineStart = this.partial === '' || this.partial.endsWith('\n');
|
|
521
|
+
if (nl < 0) return;
|
|
522
|
+
const chunk = this.partial.slice(0, nl + 1);
|
|
523
|
+
this.partial = this.partial.slice(nl + 1);
|
|
524
|
+
this.atLineStart = this.partial === '';
|
|
525
|
+
this.printAbove(chunk);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
flushPartial() {
|
|
529
|
+
if (this.partial) {
|
|
530
|
+
const p = this.partial;
|
|
531
|
+
this.partial = '';
|
|
532
|
+
this.printAbove(p + '\n');
|
|
533
|
+
}
|
|
534
|
+
this.atLineStart = true;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
newlineIfNeeded() {
|
|
538
|
+
if (this.partial) this.flushPartial();
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
text(s) {
|
|
542
|
+
this.addTokens(s.length / 4);
|
|
543
|
+
if (this.mode === 'thinking') this.flushPartial();
|
|
544
|
+
if (this.mode !== 'text') {
|
|
545
|
+
this.md = new MarkdownStream(this.c, { width: this.width - 2 });
|
|
546
|
+
this.firstLine = true;
|
|
547
|
+
this.mode = 'text';
|
|
548
|
+
}
|
|
549
|
+
this.emitText(this.md.push(s));
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
emitText(rendered) {
|
|
553
|
+
if (!rendered) return;
|
|
554
|
+
const lines = rendered.split('\n');
|
|
555
|
+
lines.pop();
|
|
556
|
+
const out = lines.map((l) => {
|
|
557
|
+
const prefix = this.firstLine ? `${this.c.bold('⏺')} ` : ' ';
|
|
558
|
+
this.firstLine = false;
|
|
559
|
+
return prefix + l;
|
|
560
|
+
});
|
|
561
|
+
this.write(this.out, out.join('\n') + '\n');
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
thinking(s) {
|
|
565
|
+
this.addTokens(s.length / 4);
|
|
566
|
+
if (this.spinner) this.spinner.label = 'Thinking';
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
endText() {
|
|
570
|
+
if (this.md) {
|
|
571
|
+
this.emitText(this.md.flush());
|
|
572
|
+
this.md = null;
|
|
573
|
+
this.write(this.out, '\n');
|
|
574
|
+
}
|
|
575
|
+
this.flushPartial();
|
|
576
|
+
this.mode = null;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
toolStart(name, summary, opts) {
|
|
580
|
+
this.endText();
|
|
581
|
+
super.toolStart(name, summary, opts);
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// ---- spinner -----------------------------------------------------------
|
|
585
|
+
|
|
586
|
+
startSpinner(label) {
|
|
587
|
+
if (this.spinner) {
|
|
588
|
+
if (label) this.spinner.label = label;
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
this.spinner = { label: label ?? VERBS[Math.floor(Math.random() * VERBS.length)], started: Date.now(), frame: 0, detail: '' };
|
|
592
|
+
this.resumeSpinnerTimer();
|
|
593
|
+
this.render();
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
resumeSpinnerTimer() {
|
|
597
|
+
if (!this.spinner || this.spinnerTimer) return;
|
|
598
|
+
this.spinnerTimer = setInterval(() => {
|
|
599
|
+
if (this.spinner) this.spinner.frame++;
|
|
600
|
+
this.render();
|
|
601
|
+
}, 120);
|
|
602
|
+
this.spinnerTimer.unref?.();
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
stopSpinnerTimer() {
|
|
606
|
+
clearInterval(this.spinnerTimer);
|
|
607
|
+
this.spinnerTimer = null;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
stopSpinner() {
|
|
611
|
+
this.stopSpinnerTimer();
|
|
612
|
+
if (this.spinner) {
|
|
613
|
+
this.spinner = null;
|
|
614
|
+
this.render();
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
spinnerDetail(text) {
|
|
619
|
+
if (this.spinner) this.spinner.detail = String(text).replace(/\x1b\[[0-9;]*[A-Za-z]/g, '').slice(0, 200);
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
clearSpinnerLine() {}
|
|
623
|
+
|
|
624
|
+
// ---- live region ---------------------------------------------------------
|
|
625
|
+
|
|
626
|
+
eraseRegion() {
|
|
627
|
+
if (!this.regionRows) return;
|
|
628
|
+
if (this.regionCursorRow) this.out.write(`\x1b[${this.regionCursorRow}A`);
|
|
629
|
+
this.out.write('\r\x1b[J');
|
|
630
|
+
this.regionRows = 0;
|
|
631
|
+
this.regionCursorRow = 0;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
render() {
|
|
635
|
+
if (!this.active) return;
|
|
636
|
+
const { lines, cursorRow, cursorCol } = this.layout();
|
|
637
|
+
let s = '\x1b[?25l';
|
|
638
|
+
if (this.regionRows && this.regionCursorRow) s += `\x1b[${this.regionCursorRow}A`;
|
|
639
|
+
s += '\r';
|
|
640
|
+
s += lines.map((l) => `\x1b[2K${l}`).join('\n') + '\x1b[J';
|
|
641
|
+
const up = lines.length - 1 - cursorRow;
|
|
642
|
+
if (up > 0) s += `\x1b[${up}A`;
|
|
643
|
+
s += `\r${cursorCol > 0 ? `\x1b[${cursorCol}C` : ''}`;
|
|
644
|
+
if (cursorRow !== null && !this.menu) s += '\x1b[?25h';
|
|
645
|
+
this.out.write(s);
|
|
646
|
+
this.regionRows = lines.length;
|
|
647
|
+
this.regionCursorRow = cursorRow ?? lines.length - 1;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
drawRegion() {
|
|
651
|
+
this.regionRows = 0;
|
|
652
|
+
this.regionCursorRow = 0;
|
|
653
|
+
this.render();
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
layout() {
|
|
657
|
+
const c = this.c;
|
|
658
|
+
const cols = Math.max(30, this.out.columns || 100);
|
|
659
|
+
const lines = [];
|
|
660
|
+
if (this.spinner) {
|
|
661
|
+
const s = this.spinner;
|
|
662
|
+
const secs = Math.floor((Date.now() - s.started) / 1000);
|
|
663
|
+
const meta = [`${secs}s`];
|
|
664
|
+
if (this.tokens >= 1) meta.push(`↓ ${fmtTokens(Math.round(this.tokens))} tokens`);
|
|
665
|
+
meta.push('esc to interrupt');
|
|
666
|
+
let line = `${c.accent(SPIN[s.frame % SPIN.length])} ${c.accent(s.label + '…')} ${c.gray(`(${meta.join(' · ')})`)}`;
|
|
667
|
+
if (s.detail) line += c.gray(` ⎿ ${s.detail}`);
|
|
668
|
+
lines.push(truncate(line, cols - 1), '');
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
if (this.menu) return this.menuLayout(lines, cols);
|
|
672
|
+
|
|
673
|
+
for (const q of this.queued) lines.push(truncate(c.gray(` ⎿ queued: ${q.replace(/\n/g, ' ')}`), cols - 1));
|
|
674
|
+
if (this.queued.length) lines.push('');
|
|
675
|
+
if (this.pending?.label) lines.push(truncate(this.pending.label.trimEnd(), cols - 1));
|
|
676
|
+
|
|
677
|
+
// Input box
|
|
678
|
+
const inner = cols - 4;
|
|
679
|
+
const width = Math.max(10, inner - 2);
|
|
680
|
+
const shown = this.pending?.secret ? '•'.repeat(this.buffer.length) : this.buffer;
|
|
681
|
+
const rows = wrap(shown, width);
|
|
682
|
+
const boxTop = lines.length;
|
|
683
|
+
const border = this.busy && !this.pending ? c.gray : (s) => c.gray(s);
|
|
684
|
+
lines.push(border(`╭${'─'.repeat(cols - 2)}╮`));
|
|
685
|
+
let cursorRow = null;
|
|
686
|
+
let cursorCol = 0;
|
|
687
|
+
const placeholder = !this.buffer && !this.pending?.label ? (this.busy ? 'Type to queue a message…' : 'Ask arrakis anything, / for commands, @ for files') : '';
|
|
688
|
+
rows.forEach((r, i) => {
|
|
689
|
+
const prefix = i === 0 ? c.accent('> ') : ' ';
|
|
690
|
+
const body = placeholder && i === 0 ? c.gray(placeholder) : r.text;
|
|
691
|
+
const pad = Math.max(0, width - visibleLength(body));
|
|
692
|
+
lines.push(`${border('│')} ${prefix}${body}${' '.repeat(pad)} ${border('│')}`);
|
|
693
|
+
if (this.cursor >= r.start && this.cursor <= r.end && cursorRow === null) {
|
|
694
|
+
if (this.cursor === r.end && r.full && i < rows.length - 1) return;
|
|
695
|
+
cursorRow = lines.length - 1;
|
|
696
|
+
cursorCol = 4 + (this.cursor - r.start);
|
|
697
|
+
}
|
|
698
|
+
});
|
|
699
|
+
if (cursorRow === null) {
|
|
700
|
+
cursorRow = boxTop + rows.length;
|
|
701
|
+
cursorCol = 4 + (rows.at(-1)?.text.length ?? 0);
|
|
702
|
+
}
|
|
703
|
+
lines.push(border(`╰${'─'.repeat(cols - 2)}╯`));
|
|
704
|
+
|
|
705
|
+
// Below the box: suggestions, shortcuts, or the hint line.
|
|
706
|
+
if (this.suggest) {
|
|
707
|
+
for (const [i, item] of this.suggest.items.slice(0, 8).entries()) {
|
|
708
|
+
const sel = i === this.suggest.selected;
|
|
709
|
+
const label = sel ? c.accent(item.label) : item.label;
|
|
710
|
+
const hint = item.hint ? ` ${c.gray(item.hint)}` : '';
|
|
711
|
+
lines.push(truncate(` ${label.padEnd ? label : label}${' '.repeat(Math.max(1, 22 - item.label.length))}${hint}`, cols - 1));
|
|
712
|
+
}
|
|
713
|
+
} else if (this.showHelp) {
|
|
714
|
+
const help = [
|
|
715
|
+
['/ for commands', '@ for file paths', '\\⏎ or shift+⏎ for newline'],
|
|
716
|
+
['shift+tab to cycle modes', 'esc to interrupt', '↑↓ for history'],
|
|
717
|
+
['ctrl+c to clear / exit', 'tab to complete', 'esc esc to clear input'],
|
|
718
|
+
];
|
|
719
|
+
for (const row of help) lines.push(c.gray(' ' + row.map((x) => x.padEnd(28)).join('')));
|
|
720
|
+
} else {
|
|
721
|
+
const left = this.exitArmed ? c.yellow('Press Ctrl-C again to exit') : this.modeLabel() || c.gray('? for shortcuts');
|
|
722
|
+
const right = c.gray(this.statusLine());
|
|
723
|
+
const gap = Math.max(2, cols - 2 - visibleLength(left) - visibleLength(right));
|
|
724
|
+
lines.push(truncate(` ${left}${' '.repeat(gap)}${right}`, cols - 1));
|
|
725
|
+
}
|
|
726
|
+
return { lines, cursorRow, cursorCol };
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
menuLayout(lines, cols) {
|
|
730
|
+
const c = this.c;
|
|
731
|
+
const m = this.menu;
|
|
732
|
+
const inner = cols - 4;
|
|
733
|
+
const row = (s = '') => `${c.accent('│')} ${truncate(s, inner)}${' '.repeat(Math.max(0, inner - visibleLength(truncate(s, inner))))} ${c.accent('│')}`;
|
|
734
|
+
lines.push(c.accent(`╭${'─'.repeat(cols - 2)}╮`));
|
|
735
|
+
lines.push(row(c.bold(m.preview?.title ?? 'Allow this action?')));
|
|
736
|
+
const body = m.preview?.lines ?? [];
|
|
737
|
+
if (body.length) {
|
|
738
|
+
lines.push(row());
|
|
739
|
+
for (const { sign, text, n } of body.slice(0, 18)) {
|
|
740
|
+
const num = n !== undefined ? c.gray(String(n).padStart(4) + ' ') : ' ';
|
|
741
|
+
const t = `${sign} ${text}`;
|
|
742
|
+
lines.push(row(`${num}${sign === '+' ? c.green(t) : sign === '-' ? c.red(t) : c.gray(t)}`));
|
|
743
|
+
}
|
|
744
|
+
if (body.length > 18) lines.push(row(c.gray(` … ${body.length - 18} more lines`)));
|
|
745
|
+
}
|
|
746
|
+
lines.push(row());
|
|
747
|
+
lines.push(row('Do you want to proceed?'));
|
|
748
|
+
m.options.forEach((o, i) => {
|
|
749
|
+
const sel = i === m.selected;
|
|
750
|
+
const text = `${i + 1}. ${o.label}${o.hint ? c.gray(` (${o.hint})`) : ''}`;
|
|
751
|
+
lines.push(row(sel ? `${c.accent('❯')} ${c.accent(text)}` : ` ${text}`));
|
|
752
|
+
});
|
|
753
|
+
lines.push(c.accent(`╰${'─'.repeat(cols - 2)}╯`));
|
|
754
|
+
return { lines, cursorRow: lines.length - 1, cursorCol: 0 };
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// ---- welcome -----------------------------------------------------------
|
|
758
|
+
|
|
759
|
+
banner({ version, model, provider, cwd, instructions = [], resumed, mcp = [], hooks = 0, update }) {
|
|
760
|
+
const c = this.c;
|
|
761
|
+
const home = process.env.HOME ?? '';
|
|
762
|
+
const tild = (p) => (home && p.startsWith(home) ? '~' + p.slice(home.length) : p);
|
|
763
|
+
const rows = [
|
|
764
|
+
`${c.accent('◆')} Welcome to ${c.bold('Arrakis')}!`,
|
|
765
|
+
'',
|
|
766
|
+
c.gray(' /help for commands, /status for your current setup'),
|
|
767
|
+
'',
|
|
768
|
+
c.gray(` cwd: ${tild(cwd)}`),
|
|
769
|
+
c.gray(` model: ${model} · ${provider}`),
|
|
770
|
+
];
|
|
771
|
+
if (resumed) rows.push(c.gray(` session: ${resumed}`));
|
|
772
|
+
if (mcp.length) rows.push(c.gray(` mcp: ${mcp.map((s) => (s.status === 'connected' ? `${s.name} (${s.tools.length} tools)` : `${s.name} (failed)`)).join(', ')}`));
|
|
773
|
+
if (hooks) rows.push(c.gray(` hooks: ${hooks} active`));
|
|
774
|
+
const cols = Math.max(30, this.out.columns || 100);
|
|
775
|
+
const inner = Math.min(cols - 4, Math.max(46, ...rows.map(visibleLength)));
|
|
776
|
+
const line = (s) => `${c.accent('│')} ${truncate(s, inner)}${' '.repeat(Math.max(0, inner - visibleLength(truncate(s, inner))))} ${c.accent('│')}`;
|
|
777
|
+
let out = `\n${c.accent(`╭${'─'.repeat(inner + 2)}╮`)}\n${rows.map(line).join('\n')}\n${c.accent(`╰${'─'.repeat(inner + 2)}╯`)}\n`;
|
|
778
|
+
if (update) out += `\n ${c.accent('↑')} ${c.bold(`Arrakis ${update} is available.`)} ${c.gray('Run: npm install -g @mumbrane/arrakis')}\n`;
|
|
779
|
+
if (!resumed) {
|
|
780
|
+
out += `\n ${c.gray('Tips for getting started:')}\n`;
|
|
781
|
+
const tips = [
|
|
782
|
+
instructions.length ? null : 'Run /init to write an ARRAKIS.md with notes about this project',
|
|
783
|
+
'Ask about the code, or ask for a change, a fix or a new feature',
|
|
784
|
+
'Use /plan for big changes, so arrakis proposes a plan before editing',
|
|
785
|
+
'Mention files with @, and press shift+tab to let it edit without asking',
|
|
786
|
+
].filter(Boolean);
|
|
787
|
+
tips.forEach((t, i) => (out += ` ${c.gray(`${i + 1}. ${t}`)}\n`));
|
|
788
|
+
}
|
|
789
|
+
this.printAbove(out + '\n');
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
info(msg) {
|
|
793
|
+
this.endText();
|
|
794
|
+
this.write(this.out, this.c.gray(msg) + '\n');
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
// Wrap text into rows of at most `width` characters, tracking source offsets.
|
|
799
|
+
function wrap(text, width) {
|
|
800
|
+
const rows = [];
|
|
801
|
+
let offset = 0;
|
|
802
|
+
for (const line of text.split('\n')) {
|
|
803
|
+
if (!line.length) rows.push({ text: '', start: offset, end: offset, full: false });
|
|
804
|
+
for (let i = 0; i < line.length; i += width) {
|
|
805
|
+
const part = line.slice(i, i + width);
|
|
806
|
+
rows.push({ text: part, start: offset + i, end: offset + i + part.length, full: part.length === width });
|
|
807
|
+
}
|
|
808
|
+
offset += line.length + 1;
|
|
809
|
+
}
|
|
810
|
+
if (!rows.length) rows.push({ text: '', start: 0, end: 0, full: false });
|
|
811
|
+
return rows;
|
|
812
|
+
}
|