@mumbrane/arrakis 0.3.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,19 +39,39 @@ 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
64
  if (this.rl || this.closed) return;
35
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: !!process.stdin.isTTY, historySize: 200 });
65
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: !!process.stdin.isTTY, historySize: 500 });
36
66
  this.rl = rl;
37
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
+ }
38
75
  rl.on('line', (line) => {
39
76
  if (this.waiter) {
40
77
  const w = this.waiter;
@@ -48,6 +85,12 @@ export class UI {
48
85
  this.cancelRead();
49
86
  });
50
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
+ }
51
94
  }
52
95
 
53
96
  // Hand the terminal to a raw-mode prompt (picker, secret input) and back.
@@ -70,14 +113,26 @@ export class UI {
70
113
  }
71
114
 
72
115
  close() {
116
+ this.stopSpinner();
73
117
  this.rl?.close();
74
118
  }
75
119
 
120
+ setBusy(busy) {
121
+ this.busy = busy;
122
+ this.muted = busy && this.fancy;
123
+ }
124
+
76
125
  readLine(promptText) {
77
126
  if (!this.rl) return Promise.resolve(null);
78
- // 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
+ };
79
134
  if (this.closed) {
80
- if (!this.queue.length) return Promise.resolve(null);
135
+ if (!this.queue.length) return Promise.resolve(restore(null));
81
136
  this.out.write(promptText);
82
137
  } else {
83
138
  this.rl.setPrompt(promptText);
@@ -86,13 +141,13 @@ export class UI {
86
141
  if (this.queue.length) {
87
142
  const line = this.queue.shift();
88
143
  if (!process.stdin.isTTY) this.out.write(line + '\n');
89
- return Promise.resolve(line);
144
+ return Promise.resolve(restore(line));
90
145
  }
91
- if (this.closed) return Promise.resolve(null);
146
+ if (this.closed) return Promise.resolve(restore(null));
92
147
  return new Promise((resolve) => {
93
148
  this.waiter = (line) => {
94
149
  if (line !== null && !process.stdin.isTTY) this.out.write(line + '\n');
95
- resolve(line);
150
+ resolve(restore(line));
96
151
  };
97
152
  });
98
153
  }
@@ -105,19 +160,51 @@ export class UI {
105
160
  }
106
161
  }
107
162
 
163
+ // The main "› " prompt, with a rule above and a status line below.
108
164
  async prompt() {
109
- let text = await this.readLine(this.c.accent('› '));
110
- // 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('› '));
111
176
  while (text !== null && text.endsWith('\\')) {
112
- const next = await this.readLine(this.c.dim(' '));
177
+ const next = await this.readLine(c.gray(' '));
113
178
  if (next === null) break;
114
179
  text = text.slice(0, -1) + '\n' + next;
115
180
  }
181
+ if (text !== null && this.fancy) this.echoUser(text, queued);
182
+ this.atLineStart = true;
116
183
  return text;
117
184
  }
118
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
+
119
205
  write(stream, s) {
120
206
  if (!s) return;
207
+ if (this.spinner && stream === this.spinner.stream) this.clearSpinnerLine();
121
208
  stream.write(s);
122
209
  this.atLineStart = s.endsWith('\n');
123
210
  }
@@ -126,67 +213,191 @@ export class UI {
126
213
  if (!this.atLineStart) this.write(stream, '\n');
127
214
  }
128
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
+
129
258
  startResponse() {
130
259
  this.mode = null;
131
260
  }
132
261
 
133
262
  thinking(s) {
263
+ this.stopSpinner();
134
264
  if (this.mode !== 'thinking') {
135
265
  this.newlineIfNeeded(this.log);
136
266
  this.mode = 'thinking';
137
267
  }
138
- this.write(this.log, this.lc.dim(this.lc.italic(s)));
268
+ this.write(this.log, this.lc.gray(this.lc.italic(s)));
139
269
  }
140
270
 
141
271
  text(s) {
272
+ this.stopSpinner();
142
273
  if (this.mode === 'thinking') this.write(this.log, '\n\n');
143
- 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
+ }
144
278
  this.mode = 'text';
145
- this.write(this.out, s);
279
+ if (this.md) this.write(this.out, this.md.push(s));
280
+ else this.write(this.out, s);
146
281
  }
147
282
 
148
283
  endText() {
284
+ if (this.md) {
285
+ this.write(this.out, this.md.flush());
286
+ this.md = null;
287
+ }
149
288
  if (this.mode) this.newlineIfNeeded(this.mode === 'text' ? this.out : this.log);
150
289
  this.mode = null;
151
290
  }
152
291
 
153
- toolStart(name, summary) {
292
+ toolStart(name, summary, { prefix = '' } = {}) {
154
293
  this.endText();
294
+ const lc = this.lc;
155
295
  const s = String(summary ?? '').split('\n')[0];
156
- 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');
299
+ }
300
+
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
+ }
157
318
  }
158
319
 
159
- toolResult(result, isError = false) {
160
- const lines = String(result).split('\n');
161
- const shown = lines.slice(0, 4).map((l) => (l.length > 160 ? l.slice(0, 160) + '…' : l));
162
- let body = shown.map((l, i) => `${i === 0 ? ' ⎿ ' : ' '}${l}`).join('\n');
163
- if (lines.length > 4) body += `\n … +${lines.length - 4} lines`;
164
- this.write(this.log, (isError ? this.lc.red(body) : this.lc.dim(body)) + '\n');
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
+ }
165
327
  }
166
328
 
167
329
  async confirm(preview) {
330
+ this.stopSpinner();
168
331
  const c = this.lc;
169
332
  if (preview) {
170
- this.write(this.log, ` ${c.yellow(preview.title)}\n`);
171
- for (const { sign, text } of preview.lines ?? []) {
172
- const line = ` ${sign} ${text}`;
173
- this.write(this.log, (sign === '+' ? c.green(line) : sign === '-' ? c.red(line) : c.dim(line)) + '\n');
174
- }
333
+ this.write(this.log, ` ${c.yellow('?')} ${c.bold(preview.title)}\n`);
334
+ if (preview.lines?.length) this.diff(preview.lines);
175
335
  }
176
- 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')} `);
177
337
  const a = (answer ?? 'n').trim().toLowerCase();
178
338
  if (a === 'a' || a === 'always') return 'always';
179
339
  if (a === 'y' || a === 'yes' || a === '') return 'yes';
180
340
  return 'no';
181
341
  }
182
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
+
183
368
  info(msg) {
184
369
  this.endText();
185
- 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`);
186
376
  }
187
377
 
188
378
  error(msg) {
189
379
  this.endText();
190
- 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++;
191
401
  }
402
+ return out + (s.includes('\x1b') ? '…\x1b[0m' : '…');
192
403
  }