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