@mumbrane/arrakis 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/ui.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import readline from 'node:readline';
2
+ import os from 'node:os';
3
+ import { MarkdownStream, visibleLength } from './markdown.js';
2
4
 
3
5
  const colorOn = (stream) => stream.isTTY && !process.env.NO_COLOR;
4
6
  const paint = (code, on) => (s) => (on ? `\x1b[${code}m${s}\x1b[0m` : String(s));
@@ -6,15 +8,30 @@ const paint = (code, on) => (s) => (on ? `\x1b[${code}m${s}\x1b[0m` : String(s))
6
8
  export function colors(stream = process.stdout) {
7
9
  const on = colorOn(stream);
8
10
  return {
9
- dim: paint('2', on), bold: paint('1', on), italic: paint('3', on),
11
+ on,
12
+ dim: paint('2', on), bold: paint('1', on), italic: paint('3', on), underline: paint('4', on),
10
13
  red: paint('31', on), green: paint('32', on), yellow: paint('33', on),
11
14
  blue: paint('34', on), magenta: paint('35', on), cyan: paint('36', on),
15
+ gray: paint('90', on),
12
16
  accent: paint('38;5;208', on), // spice orange
17
+ sand: paint('38;5;180', on),
18
+ userBg: paint('48;5;236', on),
13
19
  };
14
20
  }
15
21
 
22
+ const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
23
+ const VERBS = ['Thinking', 'Reading the sands', 'Harvesting spice', 'Folding space', 'Charting the dunes', 'Working', 'Considering'];
24
+
25
+ export const TOOL_LABELS = {
26
+ read_file: 'Read', write_file: 'Write', edit_file: 'Edit', bash: 'Bash', grep: 'Search',
27
+ list_files: 'List', task: 'Agent', todo_write: 'Todos', web_fetch: 'Fetch',
28
+ };
29
+
30
+ const tildify = (p) => (p.startsWith(os.homedir()) ? '~' + p.slice(os.homedir().length) : p);
31
+
16
32
  // Terminal I/O. In print mode (-p) the answer goes to stdout and everything
17
- // else (tool activity, notices) to stderr, so output can be piped.
33
+ // else (tool activity, notices, spinner) to stderr, so output can be piped.
34
+ // "Fancy" mode (a real terminal) adds the spinner, input chrome and Markdown.
18
35
  export class UI {
19
36
  constructor({ print = false } = {}) {
20
37
  this.print = print;
@@ -22,43 +39,100 @@ export class UI {
22
39
  this.log = print ? process.stderr : process.stdout;
23
40
  this.c = colors(this.out);
24
41
  this.lc = colors(this.log);
42
+ this.fancy = !print && Boolean(process.stdout.isTTY && process.stdin.isTTY);
43
+ this.markdown = Boolean(this.out.isTTY);
25
44
  this.rl = null;
26
45
  this.queue = [];
27
46
  this.waiter = null;
28
47
  this.closed = false;
29
48
  this.atLineStart = true;
30
49
  this.mode = null; // 'text' | 'thinking'
50
+ this.md = null;
51
+ this.spinner = null;
52
+ this.muted = false;
53
+ this.statusLine = () => '';
54
+ this.onEscape = null;
31
55
  }
32
56
 
57
+ get width() {
58
+ return Math.max(40, (this.out.columns || 100) - 1);
59
+ }
60
+
61
+ // ---- line input -------------------------------------------------------
62
+
33
63
  start() {
34
- this.rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: !!process.stdin.isTTY, historySize: 200 });
35
- this.rl.on('line', (line) => {
64
+ if (this.rl || this.closed) return;
65
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: !!process.stdin.isTTY, historySize: 500 });
66
+ this.rl = rl;
67
+ if (this.history) rl.history = this.history;
68
+ // While the agent works, typed text is queued but not echoed over its output.
69
+ if (typeof rl._writeToOutput === 'function') {
70
+ const write = rl._writeToOutput.bind(rl);
71
+ rl._writeToOutput = (s) => {
72
+ if (!this.muted) write(s);
73
+ };
74
+ }
75
+ rl.on('line', (line) => {
36
76
  if (this.waiter) {
37
77
  const w = this.waiter;
38
78
  this.waiter = null;
39
79
  w(line);
40
80
  } else this.queue.push(line);
41
81
  });
42
- this.rl.on('close', () => {
82
+ rl.on('close', () => {
83
+ if (rl.suspended) return;
43
84
  this.closed = true;
44
85
  this.cancelRead();
45
86
  });
87
+ if (this.interruptHandler) rl.on('SIGINT', this.interruptHandler);
88
+ if (this.fancy && !this.keypressBound) {
89
+ this.keypressBound = true;
90
+ process.stdin.on('keypress', (_s, key) => {
91
+ if (key?.name === 'escape' && this.onEscape) this.onEscape();
92
+ });
93
+ }
94
+ }
95
+
96
+ // Hand the terminal to a raw-mode prompt (picker, secret input) and back.
97
+ suspend() {
98
+ if (!this.rl) return;
99
+ this.history = this.rl.history;
100
+ this.rl.suspended = true;
101
+ this.rl.close();
102
+ this.rl = null;
103
+ }
104
+
105
+ resume() {
106
+ this.start();
46
107
  }
47
108
 
48
109
  onInterrupt(handler) {
110
+ this.interruptHandler = handler;
49
111
  if (this.rl) this.rl.on('SIGINT', handler);
50
112
  process.on('SIGINT', handler);
51
113
  }
52
114
 
53
115
  close() {
116
+ this.stopSpinner();
54
117
  this.rl?.close();
55
118
  }
56
119
 
120
+ setBusy(busy) {
121
+ this.busy = busy;
122
+ this.muted = busy && this.fancy;
123
+ }
124
+
57
125
  readLine(promptText) {
58
126
  if (!this.rl) return Promise.resolve(null);
59
- // Piped input can close readline while queued lines remain.
127
+ const wasMuted = this.muted;
128
+ this.muted = false;
129
+ this.stopSpinner();
130
+ const restore = (v) => {
131
+ this.muted = wasMuted;
132
+ return v;
133
+ };
60
134
  if (this.closed) {
61
- if (!this.queue.length) return Promise.resolve(null);
135
+ if (!this.queue.length) return Promise.resolve(restore(null));
62
136
  this.out.write(promptText);
63
137
  } else {
64
138
  this.rl.setPrompt(promptText);
@@ -67,13 +141,13 @@ export class UI {
67
141
  if (this.queue.length) {
68
142
  const line = this.queue.shift();
69
143
  if (!process.stdin.isTTY) this.out.write(line + '\n');
70
- return Promise.resolve(line);
144
+ return Promise.resolve(restore(line));
71
145
  }
72
- if (this.closed) return Promise.resolve(null);
146
+ if (this.closed) return Promise.resolve(restore(null));
73
147
  return new Promise((resolve) => {
74
148
  this.waiter = (line) => {
75
149
  if (line !== null && !process.stdin.isTTY) this.out.write(line + '\n');
76
- resolve(line);
150
+ resolve(restore(line));
77
151
  };
78
152
  });
79
153
  }
@@ -86,19 +160,51 @@ export class UI {
86
160
  }
87
161
  }
88
162
 
163
+ // The main "› " prompt, with a rule above and a status line below.
89
164
  async prompt() {
90
- let text = await this.readLine(this.c.accent('› '));
91
- // A trailing backslash continues the message on the next line.
165
+ const c = this.c;
166
+ const queued = this.queue.length > 0;
167
+ if (this.fancy && !queued) {
168
+ this.newlineIfNeeded(this.out);
169
+ // A blank line, then a rule that carries the status, then the input line.
170
+ const status = this.statusLine();
171
+ const label = status ? ` ${status} ` : '';
172
+ const rest = Math.max(4, this.width - 2 - visibleLength(label));
173
+ this.out.write(`\n${c.gray('──' + label + '─'.repeat(rest))}\n`);
174
+ }
175
+ let text = await this.readLine(c.accent('› '));
92
176
  while (text !== null && text.endsWith('\\')) {
93
- const next = await this.readLine(this.c.dim(' '));
177
+ const next = await this.readLine(c.gray(' '));
94
178
  if (next === null) break;
95
179
  text = text.slice(0, -1) + '\n' + next;
96
180
  }
181
+ if (text !== null && this.fancy) this.echoUser(text, queued);
182
+ this.atLineStart = true;
97
183
  return text;
98
184
  }
99
185
 
186
+ // Replace the raw prompt line with a highlighted copy of what was sent.
187
+ echoUser(text, queued) {
188
+ const c = this.c;
189
+ if (!queued) {
190
+ // The cursor is just below the input now. Go back over the input and the rule.
191
+ const rows = text.split('\n').reduce((n, l) => n + Math.max(1, Math.ceil((visibleLength(l) + 2) / (this.width + 1))), 0);
192
+ this.out.write(`\x1b[${rows + 1}A\r\x1b[J`);
193
+ }
194
+ const lines = text.split('\n');
195
+ for (const [i, l] of lines.entries()) {
196
+ const body = `${i === 0 ? '› ' : ' '}${l}`;
197
+ const pad = Math.max(0, this.width - visibleLength(body));
198
+ this.out.write(`${c.userBg(body + ' '.repeat(pad))}\n`);
199
+ }
200
+ this.out.write('\n');
201
+ }
202
+
203
+ // ---- output ----------------------------------------------------------
204
+
100
205
  write(stream, s) {
101
206
  if (!s) return;
207
+ if (this.spinner && stream === this.spinner.stream) this.clearSpinnerLine();
102
208
  stream.write(s);
103
209
  this.atLineStart = s.endsWith('\n');
104
210
  }
@@ -107,67 +213,191 @@ export class UI {
107
213
  if (!this.atLineStart) this.write(stream, '\n');
108
214
  }
109
215
 
216
+ startSpinner(label) {
217
+ const stream = this.log;
218
+ if (!stream.isTTY) return;
219
+ if (this.spinner) {
220
+ if (label) this.spinner.label = label;
221
+ return;
222
+ }
223
+ this.newlineIfNeeded(stream);
224
+ const lc = this.lc;
225
+ const spinner = {
226
+ stream,
227
+ label: label ?? VERBS[Math.floor(Math.random() * VERBS.length)],
228
+ started: Date.now(),
229
+ frame: 0,
230
+ drawn: false,
231
+ };
232
+ const draw = () => {
233
+ const secs = Math.floor((Date.now() - spinner.started) / 1000);
234
+ const line = `${lc.accent(SPINNER[spinner.frame++ % SPINNER.length])} ${lc.sand(spinner.label + '…')} ${lc.gray(`(${secs}s · esc to interrupt)`)}`;
235
+ stream.write(`\r\x1b[2K${line}`);
236
+ spinner.drawn = true;
237
+ };
238
+ spinner.timer = setInterval(draw, 90);
239
+ spinner.timer.unref?.();
240
+ this.spinner = spinner;
241
+ draw();
242
+ }
243
+
244
+ clearSpinnerLine() {
245
+ if (this.spinner?.drawn) {
246
+ this.spinner.stream.write('\r\x1b[2K');
247
+ this.spinner.drawn = false;
248
+ }
249
+ }
250
+
251
+ stopSpinner() {
252
+ if (!this.spinner) return;
253
+ clearInterval(this.spinner.timer);
254
+ this.clearSpinnerLine();
255
+ this.spinner = null;
256
+ }
257
+
110
258
  startResponse() {
111
259
  this.mode = null;
112
260
  }
113
261
 
114
262
  thinking(s) {
263
+ this.stopSpinner();
115
264
  if (this.mode !== 'thinking') {
116
265
  this.newlineIfNeeded(this.log);
117
266
  this.mode = 'thinking';
118
267
  }
119
- this.write(this.log, this.lc.dim(this.lc.italic(s)));
268
+ this.write(this.log, this.lc.gray(this.lc.italic(s)));
120
269
  }
121
270
 
122
271
  text(s) {
272
+ this.stopSpinner();
123
273
  if (this.mode === 'thinking') this.write(this.log, '\n\n');
124
- else if (this.mode !== 'text') this.newlineIfNeeded(this.out);
274
+ else if (this.mode !== 'text') {
275
+ this.newlineIfNeeded(this.out);
276
+ if (this.markdown) this.md = new MarkdownStream(this.c, { width: this.width });
277
+ }
125
278
  this.mode = 'text';
126
- this.write(this.out, s);
279
+ if (this.md) this.write(this.out, this.md.push(s));
280
+ else this.write(this.out, s);
127
281
  }
128
282
 
129
283
  endText() {
284
+ if (this.md) {
285
+ this.write(this.out, this.md.flush());
286
+ this.md = null;
287
+ }
130
288
  if (this.mode) this.newlineIfNeeded(this.mode === 'text' ? this.out : this.log);
131
289
  this.mode = null;
132
290
  }
133
291
 
134
- toolStart(name, summary) {
292
+ toolStart(name, summary, { prefix = '' } = {}) {
135
293
  this.endText();
294
+ const lc = this.lc;
136
295
  const s = String(summary ?? '').split('\n')[0];
137
- this.write(this.log, `${this.lc.accent('●')} ${this.lc.bold(name)}${s ? this.lc.dim(`(${s.length > 100 ? s.slice(0, 100) + '…' : s})`) : ''}\n`);
296
+ const label = TOOL_LABELS[name] ?? name;
297
+ const head = prefix ? ` ${lc.gray('⎿')} ${lc.gray(prefix)} ` : `${this.atLineStart ? '' : '\n'}${lc.accent('●')} `;
298
+ this.write(this.log, truncate(`${head}${lc.bold(label)}${s ? lc.gray(`(${s})`) : ''}`, this.width) + '\n');
138
299
  }
139
300
 
140
- toolResult(result, isError = false) {
141
- const lines = String(result).split('\n');
142
- const shown = lines.slice(0, 4).map((l) => (l.length > 160 ? l.slice(0, 160) + '…' : l));
143
- let body = shown.map((l, i) => `${i === 0 ? ' ⎿ ' : ' '}${l}`).join('\n');
144
- if (lines.length > 4) body += `\n … +${lines.length - 4} lines`;
145
- this.write(this.log, (isError ? this.lc.red(body) : this.lc.dim(body)) + '\n');
301
+ toolResult(result, isError = false, { lines: extra } = {}) {
302
+ const lc = this.lc;
303
+ const all = String(result).split('\n');
304
+ const shown = all.slice(0, 4).map((l) => truncate(l, this.width - 6));
305
+ let body = shown.map((l, i) => `${i === 0 ? ' ⎿ ' : ' '}${l}`).join('\n');
306
+ if (all.length > 4) body += `\n ${lc.gray(`… +${all.length - 4} lines`)}`;
307
+ this.write(this.log, (isError ? lc.red(body) : lc.gray(body)) + '\n');
308
+ if (extra?.length) this.diff(extra);
309
+ }
310
+
311
+ diff(lines) {
312
+ const lc = this.lc;
313
+ for (const { sign, text, n } of lines) {
314
+ const num = n !== undefined ? lc.gray(String(n).padStart(4) + ' ') : ' ';
315
+ const body = truncate(`${sign} ${text}`, this.width - 10);
316
+ this.write(this.log, ` ${num}${sign === '+' ? lc.green(body) : sign === '-' ? lc.red(body) : lc.gray(body)}\n`);
317
+ }
318
+ }
319
+
320
+ todos(list) {
321
+ const lc = this.lc;
322
+ for (const t of list) {
323
+ const mark = t.status === 'completed' ? lc.green('☑') : t.status === 'in_progress' ? lc.accent('◼') : lc.gray('☐');
324
+ const text = t.status === 'completed' ? lc.gray(t.content) : t.status === 'in_progress' ? lc.bold(t.content) : t.content;
325
+ this.write(this.log, ` ${mark} ${text}\n`);
326
+ }
146
327
  }
147
328
 
148
329
  async confirm(preview) {
330
+ this.stopSpinner();
149
331
  const c = this.lc;
150
332
  if (preview) {
151
- this.write(this.log, ` ${c.yellow(preview.title)}\n`);
152
- for (const { sign, text } of preview.lines ?? []) {
153
- const line = ` ${sign} ${text}`;
154
- this.write(this.log, (sign === '+' ? c.green(line) : sign === '-' ? c.red(line) : c.dim(line)) + '\n');
155
- }
333
+ this.write(this.log, ` ${c.yellow('?')} ${c.bold(preview.title)}\n`);
334
+ if (preview.lines?.length) this.diff(preview.lines);
156
335
  }
157
- const answer = await this.readLine(` ${c.bold('Allow?')} ${c.dim('[y]es [a]lways this session [n]o')} `);
336
+ const answer = await this.readLine(` ${c.bold('Allow?')} ${c.gray('[y]es [a]lways this session [n]o')} `);
158
337
  const a = (answer ?? 'n').trim().toLowerCase();
159
338
  if (a === 'a' || a === 'always') return 'always';
160
339
  if (a === 'y' || a === 'yes' || a === '') return 'yes';
161
340
  return 'no';
162
341
  }
163
342
 
343
+ banner({ version, model, provider, cwd, instructions = [], resumed }) {
344
+ const c = this.c;
345
+ if (!this.fancy) {
346
+ this.write(this.out, `\n${c.accent(c.bold(' ◆ arrakis'))} ${c.dim(`v${version}`)}\n`);
347
+ this.write(this.out, c.dim(` ${model} · ${provider} · ${cwd}\n`));
348
+ if (resumed) this.write(this.out, c.dim(` ${resumed}\n`));
349
+ this.write(this.out, c.dim(' /help for commands · Ctrl-C to interrupt · Ctrl-D to quit\n\n'));
350
+ return;
351
+ }
352
+ const rows = [
353
+ `${c.accent(c.bold('◆ arrakis'))} ${c.gray(`v${version}`)}`,
354
+ '',
355
+ `${c.gray('model ')} ${c.bold(model)} ${c.gray(`· ${provider}`)}`,
356
+ `${c.gray('folder ')} ${tildify(cwd)}`,
357
+ ];
358
+ if (instructions.length) rows.push(`${c.gray('notes ')} ${instructions.map((f) => tildify(f)).join(', ')}`);
359
+ if (resumed) rows.push(`${c.gray('session ')} ${resumed}`);
360
+ rows.push('', c.gray('/help commands · @file attach · /plan plan first · esc interrupt'));
361
+ const inner = Math.min(this.width - 4, Math.max(...rows.map(visibleLength)) + 2);
362
+ const line = (s) => `${c.accent('│')} ${truncate(s, inner)}${' '.repeat(Math.max(0, inner - visibleLength(truncate(s, inner))))} ${c.accent('│')}`;
363
+ const out = [c.accent(`╭${'─'.repeat(inner + 2)}╮`), ...rows.map(line), c.accent(`╰${'─'.repeat(inner + 2)}╯`)];
364
+ this.write(this.out, '\n' + out.join('\n') + '\n');
365
+ if (!instructions.length) this.write(this.out, c.gray(' Tip: run /init to have arrakis write project notes (ARRAKIS.md) for this folder.\n'));
366
+ }
367
+
164
368
  info(msg) {
165
369
  this.endText();
166
- this.write(this.log, this.lc.dim(msg) + '\n');
370
+ this.write(this.log, this.lc.gray(msg) + '\n');
371
+ }
372
+
373
+ success(msg) {
374
+ this.endText();
375
+ this.write(this.log, `${this.lc.green('✓')} ${msg}\n`);
167
376
  }
168
377
 
169
378
  error(msg) {
170
379
  this.endText();
171
- this.write(this.log, this.lc.red(`Error: ${msg}`) + '\n');
380
+ this.write(this.log, this.lc.red(`✗ ${msg}`) + '\n');
381
+ }
382
+ }
383
+
384
+ export function truncate(s, width) {
385
+ if (visibleLength(s) <= width) return s;
386
+ // Walk the string keeping ANSI codes, cutting visible characters.
387
+ let out = '';
388
+ let seen = 0;
389
+ for (let i = 0; i < s.length; i++) {
390
+ if (s[i] === '\x1b') {
391
+ const m = s.slice(i).match(/^\x1b\[[0-9;]*m/);
392
+ if (m) {
393
+ out += m[0];
394
+ i += m[0].length - 1;
395
+ continue;
396
+ }
397
+ }
398
+ if (seen >= width - 1) break;
399
+ out += s[i];
400
+ seen++;
172
401
  }
402
+ return out + (s.includes('\x1b') ? '…\x1b[0m' : '…');
173
403
  }