sumo-agents 0.4.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.
Files changed (52) hide show
  1. package/AGENTS.md +8 -6
  2. package/CHANGELOG.md +155 -0
  3. package/README.md +76 -18
  4. package/bin/sumo.mjs +13 -2
  5. package/guides/feature.md +2 -1
  6. package/guides/memory.md +6 -4
  7. package/guides/projects.md +1 -1
  8. package/guides/review.md +1 -1
  9. package/package.json +5 -4
  10. package/prompts/dream.md +6 -0
  11. package/spinner.txt +25 -1
  12. package/src/apply.mjs +146 -18
  13. package/src/auth.mjs +32 -5
  14. package/src/card.mjs +39 -2
  15. package/src/catalog.mjs +6 -3
  16. package/src/chat.mjs +197 -86
  17. package/src/cli.mjs +359 -135
  18. package/src/cost.mjs +67 -8
  19. package/src/db.mjs +106 -3
  20. package/src/dream.mjs +445 -19
  21. package/src/editor.mjs +3 -2
  22. package/src/export.mjs +105 -7
  23. package/src/guard.mjs +57 -11
  24. package/src/guides.mjs +5 -4
  25. package/src/herdr.mjs +4 -2
  26. package/src/hooks.mjs +31 -18
  27. package/src/jobs.mjs +118 -39
  28. package/src/jobtools.mjs +6 -4
  29. package/src/keeper.mjs +77 -0
  30. package/src/local-server.mjs +9 -16
  31. package/src/lock.mjs +2 -1
  32. package/src/logs.mjs +165 -0
  33. package/src/loop.mjs +121 -44
  34. package/src/mcp.mjs +72 -16
  35. package/src/memory.mjs +142 -15
  36. package/src/model.mjs +41 -21
  37. package/src/paths.mjs +38 -0
  38. package/src/prime.mjs +19 -31
  39. package/src/projects.mjs +76 -12
  40. package/src/redact.mjs +10 -0
  41. package/src/render.mjs +2 -1
  42. package/src/route.mjs +16 -22
  43. package/src/sandbox.mjs +82 -3
  44. package/src/scan.mjs +35 -1
  45. package/src/scribe.mjs +10 -22
  46. package/src/sessions.mjs +46 -11
  47. package/src/setup.mjs +423 -78
  48. package/src/text.mjs +100 -1
  49. package/src/tools.mjs +258 -21
  50. package/src/tty.mjs +205 -78
  51. package/src/ui.mjs +869 -293
  52. package/src/verify.mjs +17 -1
package/src/tty.mjs CHANGED
@@ -13,10 +13,36 @@ import { isWebTool, WEB_SEARCH_TOOL } from './web.mjs';
13
13
  * dim and colour as it streams, wrapped to a readable width; the memory block
14
14
  * in spaced sections with its labels standing out; tool lines and errors told
15
15
  * apart from the model's own words. Colour is off when stdout is not a
16
- * terminal or NO_COLOR is set, so a pipe gets plain text.
16
+ * terminal or NO_COLOR is set, so a pipe gets plain text — unless FORCE_COLOR asks for it.
17
17
  */
18
18
 
19
- const CODES = { bold: ['1', '22'], dim: ['2', '22'], italic: ['3', '23'], underline: ['4', '24'], strike: ['9', '29'], cyan: ['36', '39'], yellow: ['33', '39'], red: ['31', '39'], green: ['32', '39'], magenta: ['35', '39'], blue: ['34', '39'] };
19
+ const CODES = { bold: ['1', '22'], dim: ['2', '22'], italic: ['3', '23'], underline: ['4', '24'], inverse: ['7', '27'], strike: ['9', '29'], cyan: ['36', '39'], yellow: ['33', '39'], red: ['31', '39'], green: ['32', '39'], magenta: ['35', '39'], blue: ['34', '39'] };
20
+
21
+ /**
22
+ * The marks the screen draws with. Plain, for a screen reader or a terminal that draws only ASCII, each is a character a
23
+ * reader says as itself: no box drawing, no symbol spelled out by its Unicode name. What a row is, the ledger says in
24
+ * words; these are only its state — failed, at work, picked, waiting on you — and the markdown's own.
25
+ */
26
+ const GLYPHS = {
27
+ fail: '✗', pick: '›', ask: '?', live: '•', spin: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'], bar: '│', quote: '│', rule: '─', fenceOpen: '┌─', fenceClose: '└─', todo: '☐', done: '☑', bullet: '•',
28
+ box: { h: '─', v: '│', tl: '┌', tm: '┬', tr: '┐', ml: '├', mm: '┼', mr: '┤', bl: '└', bm: '┴', br: '┘' },
29
+ };
30
+ const PLAIN_GLYPHS = {
31
+ fail: 'x', pick: '>', ask: '?', live: '*', spin: ['*'], bar: '|', quote: '|', rule: '-', fenceOpen: '+-', fenceClose: '+-', todo: '[ ]', done: '[x]', bullet: '-',
32
+ box: { h: '-', v: '|', tl: '+', tm: '+', tr: '+', ml: '+', mm: '+', mr: '+', bl: '+', bm: '+', br: '+' },
33
+ };
34
+
35
+ /**
36
+ * The ledger the conversation is set in: each row named in a gutter on the left — you, sumo, read, edit, run, ask — in
37
+ * words, so what a row is never rests on a colour or a mark; beside the name a column for the row's state; the words from
38
+ * there on. What came back from a step stands two columns further in, under the words of the step.
39
+ */
40
+ export const GUTTER = 6;
41
+ export const TEXT_AT = GUTTER + 3;
42
+ export const OUT_AT = TEXT_AT + 2;
43
+ /** A row's start, as text: its name set right in the gutter, its state beside it. */
44
+ export const ledger = (label = '', mark = ' ') => `${String(label).slice(0, GUTTER).padStart(GUTTER)} ${mark} `;
45
+
20
46
  const MAX_WIDTH = 100;
21
47
  const MIN_WIDTH = 40;
22
48
 
@@ -27,15 +53,27 @@ const LINK_CLOSE = '\x1b]8;;\x07';
27
53
  /**
28
54
  * The style functions, each a no-op when colour is off. `links` makes `link` an address the terminal opens on a click; a
29
55
  * terminal that does not know them draws the text alone, but a pager does not, so the screen asks for them and nothing else.
56
+ * `plain` draws with ASCII marks (`g`): see GLYPHS.
30
57
  */
31
- export function styles(enabled, { links = false } = {}) {
58
+ export function styles(enabled, { links = false, plain = false } = {}) {
32
59
  const s = {};
33
60
  for (const [name, [on, off]] of Object.entries(CODES)) s[name] = enabled ? (t) => `\x1b[${on}m${t}\x1b[${off}m` : (t) => t;
34
61
  s.link = enabled && links ? (url, text = url) => `${LINK_OPEN(url)}${text}${LINK_CLOSE}` : (_url, text = _url) => text;
62
+ s.plain = plain;
63
+ s.g = plain ? PLAIN_GLYPHS : GLYPHS;
35
64
  return s;
36
65
  }
37
66
 
38
- export const colourEnabled = (stream = process.stdout, env = process.env) => Boolean(stream.isTTY) && !('NO_COLOR' in env) && env.TERM !== 'dumb';
67
+ /** The marks for a screen, plain or not. */
68
+ export const glyphs = (plain = false) => (plain ? PLAIN_GLYPHS : GLYPHS);
69
+
70
+ /**
71
+ * Colour on a terminal unless NO_COLOR holds something (an empty one is not set: no-color.org) or the terminal is dumb.
72
+ * A FORCE_COLOR the user set wins, as it does for chalk on the chat screen: 0 or false is none, anything else is colour,
73
+ * piped too — a CI log can ask for it. Empty is not set, as for NO_COLOR.
74
+ */
75
+ export const colourEnabled = (stream = process.stdout, env = process.env) =>
76
+ env.FORCE_COLOR ? env.FORCE_COLOR !== '0' && env.FORCE_COLOR !== 'false' : Boolean(stream.isTTY) && !env.NO_COLOR && env.TERM !== 'dumb';
39
77
 
40
78
  /** Lines no wider than this read comfortably whatever the window is. */
41
79
  export const widthOf = (stream = process.stdout, env = process.env) => Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, (stream.columns || Number(env.COLUMNS) || 80) - 1));
@@ -124,7 +162,7 @@ const LIST_ITEM = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/;
124
162
  * The indent a line that goes on with a list item is drawn at: under the item's text, not its marker. Null for a
125
163
  * line that is no list item.
126
164
  */
127
- export function hangOf(line) {
165
+ function hangOf(line) {
128
166
  const item = LIST_ITEM.exec(line);
129
167
  if (!item) return null;
130
168
  return `${item[1]}${' '.repeat(/\d/.test(item[2]) ? item[2].length + 3 : 4)}`;
@@ -206,12 +244,12 @@ export function renderLine(line, s, { fence = false, width = MAX_WIDTH, hang = n
206
244
  const item = LIST_ITEM.exec(line);
207
245
  if (item && !/\d/.test(item[2])) {
208
246
  const task = /^\[([ xX])\]\s+(.*)$/.exec(item[3]);
209
- const mark = task ? (task[1] === ' ' ? s.dim('☐') : s.green('☑')) : s.dim('•');
247
+ const mark = task ? (task[1] === ' ' ? s.dim(s.g.todo) : s.green(s.g.done)) : s.dim(s.g.bullet);
210
248
  return wrap(`${item[1]} ${mark} ${inline(task ? task[2] : item[3], s)}`, width, `${item[1]} `);
211
249
  }
212
250
  if (item) return wrap(`${item[1]} ${s.dim(`${item[2].slice(0, -1)}.`)} ${inline(item[3], s)}`, width, hangOf(line));
213
- if (/^\s*>\s?/.test(line)) return wrap(` ${s.dim('│')} ${s.italic(inline(line.replace(/^\s*>\s?/, ''), s))}`, width, ` ${s.dim('│')} `);
214
- if (/^\s*(---|\*\*\*|___)\s*$/.test(line)) return s.dim('─'.repeat(Math.min(40, width)));
251
+ if (/^\s*>\s?/.test(line)) return wrap(` ${s.dim(s.g.quote)} ${s.italic(inline(line.replace(/^\s*>\s?/, ''), s))}`, width, ` ${s.dim(s.g.quote)} `);
252
+ if (/^\s*(---|\*\*\*|___)\s*$/.test(line)) return s.dim(s.g.rule.repeat(Math.min(40, width)));
215
253
  if (hang !== null && /^\s+\S/.test(line)) return wrap(`${hang}${inline(line.trim(), s)}`, width, hang);
216
254
  return wrap(inline(line, s), width);
217
255
  }
@@ -289,6 +327,10 @@ export function renderTable(rows, s, width) {
289
327
  const columns = head.length;
290
328
  const aligns = Array.from({ length: columns }, (_, i) => (/^:-+:$/.test(rule[i] ?? '') ? 'center' : /-:$/.test(rule[i] ?? '') ? 'right' : 'left'));
291
329
  const table = [head, ...body].map((row) => Array.from({ length: columns }, (_, i) => row[i] ?? ''));
330
+ // Each row as a record — the column's name, then the cell — one under the other.
331
+ const records = () => body.map((row) => head.map((name, i) => wrap(`${i === 0 ? s.dim(s.g.bullet) : ' '} ${s.bold(inline(name, s))}: ${inline(row[i] ?? '', s)}`, width, ' ')).join('\n')).join('\n\n');
332
+ // Plain mode is drawn for a screen reader, which would spell a frame out character by character: always records.
333
+ if (s.plain && body.length > 0) return records();
292
334
  const widths = Array.from({ length: columns }, (_, i) => Math.max(1, ...table.map((row) => visible(inline(row[i], s)))));
293
335
  const room = width - (3 * columns + 1);
294
336
  const sum = (list) => list.reduce((a, b) => a + b, 0);
@@ -299,9 +341,7 @@ export function renderTable(rows, s, width) {
299
341
  const spare = room - sum(least);
300
342
  // Three columns or more that cannot keep their words whole would fold into a ladder of word ends: each row is shown as
301
343
  // a record instead — the column's name, then the cell — one under the other.
302
- if (spare < 0 && columns >= 3 && body.length > 0) {
303
- return body.map((row) => head.map((name, i) => wrap(`${i === 0 ? s.dim('•') : ' '} ${s.bold(inline(name, s))}: ${inline(row[i] ?? '', s)}`, width, ' ')).join('\n')).join('\n\n');
304
- }
344
+ if (spare < 0 && columns >= 3 && body.length > 0) return records();
305
345
  if (spare >= 0) {
306
346
  const wants = widths.map((most, i) => most - least[i]);
307
347
  const given = least.map((w, i) => w + Math.floor((spare * wants[i]) / Math.max(1, sum(wants))));
@@ -312,14 +352,15 @@ export function renderTable(rows, s, width) {
312
352
  while (sum(widths) > room && Math.max(...widths) > MIN_COLUMN) widths[widths.indexOf(Math.max(...widths))]--;
313
353
  }
314
354
 
315
- const edge = (left, mid, right) => s.dim(`${left}${widths.map((w) => '─'.repeat(w + 2)).join(mid)}${right}`);
316
- const bar = s.dim('│');
355
+ const box = s.g.box;
356
+ const edge = (left, mid, right) => s.dim(`${left}${widths.map((w) => box.h.repeat(w + 2)).join(mid)}${right}`);
357
+ const bar = s.dim(box.v);
317
358
  const draw = (row, style) => {
318
359
  const cells = row.map((cell, i) => (visible(inline(cell, s)) <= widths[i] ? [inline(cell, s)] : fold(inline(cell, NO_STYLE), widths[i])));
319
360
  const height = Math.max(...cells.map((c) => c.length));
320
361
  return Array.from({ length: height }, (_, n) => `${bar} ${cells.map((c, i) => style(pad(c[n] ?? '', widths[i], aligns[i]))).join(` ${bar} `)} ${bar}`);
321
362
  };
322
- return [edge('┌', '┬', '┐'), ...draw(table[0], s.bold), edge('├', '┼', '┤'), ...table.slice(1).flatMap((row) => draw(row, (t) => t)), edge('└', '┴', '┘')].join('\n');
363
+ return [edge(box.tl, box.tm, box.tr), ...draw(table[0], s.bold), edge(box.ml, box.mm, box.mr), ...table.slice(1).flatMap((row) => draw(row, (t) => t)), edge(box.bl, box.bm, box.br)].join('\n');
323
364
  }
324
365
 
325
366
  /**
@@ -333,6 +374,26 @@ export function renderTable(rows, s, width) {
333
374
  */
334
375
  export const untab = (text) => text.replaceAll('\t', ' ');
335
376
 
377
+ /**
378
+ * The line still arriving, a mark it has opened and not yet closed made whole for now — a code span shut, a link whose
379
+ * address is still coming shown by its words, bold ended — so the live line never shows a mark the finished one will not.
380
+ * A mark with nothing after it yet is held back. Only the live line is drawn from this; the finished one, from what came.
381
+ */
382
+ function closedForNow(line) {
383
+ const ticks = [...line.matchAll(/(?<!\\)`/g)];
384
+ if (ticks.length % 2 === 1) {
385
+ const at = ticks.at(-1).index;
386
+ return line.slice(at + 1).trim() ? `${line}\`` : line.slice(0, at);
387
+ }
388
+ const shown = line.replace(/\[([^\]\n]+)\]\([^)\s]*$/, '$1');
389
+ // Bold counted outside the code spans, where a `**` is only itself.
390
+ const bold = [...shown.replace(/`[^`]*`/g, (span) => ' '.repeat(span.length)).matchAll(/\*\*/g)];
391
+ if (bold.length % 2 === 0) return shown;
392
+ const at = bold.at(-1).index;
393
+ const words = shown.trimEnd();
394
+ return shown.slice(at + 2).trim() ? `${words}**${shown.slice(words.length)}` : shown.slice(0, at);
395
+ }
396
+
336
397
  export function createRenderer(write, s, { width = MAX_WIDTH } = {}) {
337
398
  let tail = '';
338
399
  let fence = false;
@@ -349,7 +410,9 @@ export function createRenderer(write, s, { width = MAX_WIDTH } = {}) {
349
410
  hang = null;
350
411
  lang = fence ? marks[1].toLowerCase() : '';
351
412
  code = { comment: false };
352
- return s.dim(fence ? ` ┌─${marks[1] ? ` ${marks[1]}` : ''}` : ' └─');
413
+ // Plain mode names the block in words, for a reader: no frame corner to spell out.
414
+ if (s.plain) return s.dim(fence ? ` code${marks[1] ? ` (${marks[1]})` : ''}:` : ' end of code');
415
+ return s.dim(fence ? ` ${s.g.fenceOpen}${marks[1] ? ` ${marks[1]}` : ''}` : ` ${s.g.fenceClose}`);
353
416
  }
354
417
  if (!fence) hang = hangOf(raw) ?? (/^\s+\S/.test(raw) || raw.trim() === '' ? hang : null);
355
418
  return renderLine(raw, s, { fence, width, hang: hangOf(raw) === null ? hang : null, lang, code });
@@ -389,7 +452,7 @@ export function createRenderer(write, s, { width = MAX_WIDTH } = {}) {
389
452
  /** What has not been written yet, rendered as far as it has got: the rows of a table, and the line still arriving. */
390
453
  get tail() {
391
454
  const going = /^\s+\S/.test(tail) && hangOf(tail) === null ? hang : null;
392
- return [rows.length > 0 ? held() : '', tail && !/^\s*```/.test(tail) ? renderLine(tail, s, { fence, width, hang: going, lang, code: { ...code } }) : ''].filter(Boolean).join('\n');
455
+ return [rows.length > 0 ? held() : '', tail && !/^\s*```/.test(tail) ? renderLine(fence ? tail : closedForNow(tail), s, { fence, width, hang: going, lang, code: { ...code } }) : ''].filter(Boolean).join('\n');
393
456
  },
394
457
  };
395
458
  }
@@ -404,7 +467,7 @@ export const VERSION = (() => {
404
467
  })();
405
468
 
406
469
  /** The words shown while the model works: yours, one a line, in spinner.txt at the top of the repo. */
407
- export const SPINNER_FILE = join(REPO_ROOT, 'spinner.txt');
470
+ const SPINNER_FILE = join(REPO_ROOT, 'spinner.txt');
408
471
  const SPINNER_FALLBACK = ['Working'];
409
472
 
410
473
  /** The working messages: every line of the file that is not blank and not a `#` comment. */
@@ -426,26 +489,8 @@ const MESSAGE_MS = 5000;
426
489
  /** The working message `elapsed` ms into work that opened on `first`: the next in the file every five seconds, round and round. */
427
490
  export const messageAt = (messages, first, elapsed) => messages[(Math.max(0, messages.indexOf(first)) + Math.floor(elapsed / MESSAGE_MS)) % messages.length];
428
491
 
429
- /** The chat's colours: gold, into orange, into crimson. */
430
- const SUNSET = [[0xff, 0xd1, 0x66], [0xf7, 0x7f, 0x00], [0xd6, 0x28, 0x28]];
431
-
432
- /** The colour `t` of the way through the sunset, 0 its gold and 1 its crimson. */
433
- export function sunset(t) {
434
- const at = Math.min(Math.max(t, 0), 1) * (SUNSET.length - 1);
435
- const i = Math.min(Math.floor(at), SUNSET.length - 2);
436
- return `#${SUNSET[i].map((v, k) => Math.round(v + (SUNSET[i + 1][k] - v) * (at - i)).toString(16).padStart(2, '0')).join('')}`;
437
- }
438
-
439
- const FLOW_LENGTH = 24;
440
-
441
- /** The colour of character `i` at `frame` of a sunset flowing through words: gold to crimson and back, a step a character, moving on a character a frame. */
442
- export function flow(i, frame) {
443
- const step = (((i - frame) % FLOW_LENGTH) + FLOW_LENGTH) % FLOW_LENGTH;
444
- return sunset(1 - Math.abs(1 - (2 * step) / FLOW_LENGTH));
445
- }
446
-
447
492
  /** What the chat draws faint in the empty room above the box you type in: yours, in logo.txt at the top of the repo. */
448
- export const LOGO_FILE = join(REPO_ROOT, 'logo.txt');
493
+ const LOGO_FILE = join(REPO_ROOT, 'logo.txt');
449
494
 
450
495
  /** The logo's rows, as drawn: `#` comments and the blank rows around it dropped, the blank rows inside it kept. No file draws nothing. */
451
496
  export function logoLines(file = LOGO_FILE) {
@@ -464,7 +509,8 @@ export function logoLines(file = LOGO_FILE) {
464
509
  const SHOWN_REPORT_LINES = 3;
465
510
  const SHOWN_HEAD_LINES = 2;
466
511
  const SHOWN_TAIL_LINES = 3;
467
- const SHOWN_DIFF_LINES = 12;
512
+ /** The rows of the screen an edit's diff takes before the rest is folded away. */
513
+ const SHOWN_DIFF_ROWS = 12;
468
514
  const SHOWN_COMMAND_LINES = 3;
469
515
  const SHOWN_COMMAND_CHARS = 240;
470
516
  const SHOWN_WRITE_LINES = 4;
@@ -485,8 +531,26 @@ function ends(lines, full) {
485
531
  /** A path as a person reads it: under the home directory, from `~`. */
486
532
  export const tilde = (path, home = homedir()) => (path === home ? '~' : String(path).startsWith(`${home}${sep}`) ? `~${String(path).slice(home.length)}` : String(path));
487
533
 
534
+ /**
535
+ * A path without the link macOS keeps its own /var, /tmp and /etc behind (`/private/var` is `/var`): one file, one
536
+ * spelling on the screen, however the model or a resolved path named it. Elsewhere `/private` is a folder like any other.
537
+ */
538
+ const unlinked = (path) => (process.platform === 'darwin' ? String(path).replace(/^\/private(?=\/(?:var|tmp|etc)(?:\/|$))/, '') : String(path));
539
+
488
540
  /** A path as the work reads it: a file in the project from the project, anything else from the home directory. */
489
- export const pathFrom = (path, cwd) => (cwd && path === cwd ? '.' : cwd && String(path).startsWith(`${cwd}${sep}`) ? String(path).slice(cwd.length + 1) : tilde(path));
541
+ export const pathFrom = (path, cwd) => {
542
+ const at = unlinked(path);
543
+ const from = cwd ? unlinked(cwd) : null;
544
+ return from && at === from ? '.' : from && at.startsWith(`${from}${sep}`) ? at.slice(from.length + 1) : tilde(at);
545
+ };
546
+
547
+ /** What the work said back, the files in the project in it named from there, as its title names them: the editor's own words. */
548
+ const fromProject = (text, cwd) => {
549
+ if (!cwd) return text;
550
+ const at = unlinked(cwd);
551
+ const places = process.platform === 'darwin' && /^\/(?:var|tmp|etc)(?:\/|$)/.test(at) ? [`/private${at}`, at] : [at];
552
+ return places.reduce((said, place) => said.replaceAll(`${place}${sep}`, ''), String(text));
553
+ };
490
554
 
491
555
  /** How a delegated job ended, for the line that sums it up: its mark, the word for it, and its colour. */
492
556
  const JOB_ENDS = { done: ['✓', 'done', 'add'], failed: ['✗', 'failed', 'error'], needs_input: ['?', 'needs your answer', 'ask'], open: ['○', 'never closed', 'dim'], stopped: ['■', 'stopped by you', 'dim'] };
@@ -500,10 +564,28 @@ export const withoutColourCodes = (text) => String(text).replace(/⟨U\+001B⟩\
500
564
  const toned = (text, tone) => withoutColourCodes(text).split('\n').map((t) => ({ text: t, tone }));
501
565
  const count = (text) => [{ text: `${text === '' ? 0 : text.replace(/\n$/, '').split('\n').length} lines`, tone: 'dim' }];
502
566
 
567
+ /**
568
+ * Where two lines differ: what lies between the start they share and the end they share, in each — null when they share
569
+ * neither, since then the whole line is the change and marking it says nothing.
570
+ */
571
+ function changedSpan(a, b) {
572
+ let start = 0;
573
+ while (start < a.length && start < b.length && a[start] === b[start]) start++;
574
+ let end = 0;
575
+ while (end < a.length - start && end < b.length - start && a.at(-1 - end) === b.at(-1 - end)) end++;
576
+ if (start + end === 0) return null;
577
+ return [
578
+ [start, a.length - end],
579
+ [start, b.length - end],
580
+ ];
581
+ }
582
+
503
583
  /**
504
584
  * An edit as a diff: the lines old and new share at their ends are what stayed, and what lies between is what went and
505
585
  * what came — each numbered as the file numbers it when `line` says where the old text began, with one line of what
506
- * stayed on either side. Folded, a big change keeps the top of each side, so what came is never folded away whole.
586
+ * stayed on either side. A line that went stands over the line that came in its place, the part of each that changed
587
+ * marked (`span`); what is left over on either side follows. Folding is the screen's: by the rows the lines take
588
+ * there (`rows`), so a narrow window does not show a long edit whole.
507
589
  */
508
590
  function diffView(old, now, line, full) {
509
591
  const was = old === '' ? [] : old.replace(/\r\n/g, '\n').split('\n');
@@ -515,20 +597,28 @@ function diffView(old, now, line, full) {
515
597
  const went = was.slice(head, was.length - tail);
516
598
  const came = is.slice(head, is.length - tail);
517
599
  const wide = line === null ? 0 : String(line + Math.max(was.length, is.length)).length;
518
- const row = (n, sign, text, tone) => ({ text: line === null ? `${sign} ${text}` : `${String(line + n).padStart(wide)} ${sign} ${text}`, tone });
519
- const fold = (rows) => (full || went.length + came.length <= SHOWN_DIFF_LINES ? rows : top(rows, SHOWN_DIFF_LINES / 2));
600
+ const row = (n, sign, text, tone, span = null) => {
601
+ const lead = line === null ? `${sign} ` : `${String(line + n).padStart(wide)} ${sign} `;
602
+ return { text: `${lead}${text}`, tone, ...(span && span[1] > span[0] ? { span: [lead.length + span[0], lead.length + span[1]] } : {}) };
603
+ };
604
+ // Pairs go only as far as both sides do: past that, what is left of the longer side, in its own order.
605
+ const lines = [];
606
+ for (let i = 0; i < Math.max(went.length, came.length); i++) {
607
+ const both = i < went.length && i < came.length ? changedSpan(went[i], came[i]) : null;
608
+ if (i < went.length) lines.push(row(head + i, '-', went[i], 'del', both?.[0]));
609
+ if (i < came.length) lines.push(row(head + i, '+', came[i], 'add', both?.[1]));
610
+ }
520
611
  return {
521
612
  at: line === null ? null : line + head,
522
613
  stat: { added: came.length, removed: went.length },
523
- lines: [
524
- ...(head > 0 ? [row(head - 1, ' ', was[head - 1], 'dim')] : []),
525
- ...fold(went.map((text, i) => row(head + i, '-', text, 'del'))),
526
- ...fold(came.map((text, i) => row(head + i, '+', text, 'add'))),
527
- ...(tail > 0 ? [row(is.length - tail, ' ', is[is.length - tail], 'dim')] : []),
528
- ],
614
+ rows: full ? null : SHOWN_DIFF_ROWS,
615
+ lines: [...(head > 0 ? [row(head - 1, ' ', was[head - 1], 'dim')] : []), ...lines, ...(tail > 0 ? [row(is.length - tail, ' ', is[is.length - tail], 'dim')] : [])],
529
616
  };
530
617
  }
531
618
 
619
+ /** A line with the part of it that changed in reverse video, which shows with colour off too where reverse video does. */
620
+ export const withSpan = (line, s) => (line.span ? `${untab(line.text.slice(0, line.span[0]))}${s.inverse(untab(line.text.slice(...line.span)))}${untab(line.text.slice(line.span[1]))}` : untab(line.text));
621
+
532
622
  /**
533
623
  * A report as it reads, a line each: no table rules, a table's row its cells, no marks, a file in the project named from
534
624
  * there. A heading is dropped — or, with `headings: 'keep'`, kept as its words; either way a line of three words or fewer
@@ -563,7 +653,12 @@ function readable(text, cwd = null, { headings = 'drop' } = {}) {
563
653
  * every line, the command whole, and the file itself for a read or a write.
564
654
  * `cwd` is the project the work is in: a file in it is named from there.
565
655
  */
656
+ /** The most of one line a folded result shows: about five rows of a window 80 wide. */
657
+ const LONG_LINE = 400;
658
+
566
659
  export function toolView(call, result = null, { full = false, cwd = null } = {}) {
660
+ // Folded, a result written for the screen as well as for the model says what it means in a line; in full, every word.
661
+ if (!full && typeof result?.shown === 'string') result = { ...result, content: result.shown };
567
662
  const input = call.input ?? {};
568
663
  // Folded, the empty lines of what came back are not shown: three of five lines spent on nothing say nothing.
569
664
  const output = (content = result.content) => {
@@ -571,6 +666,8 @@ export function toolView(call, result = null, { full = false, cwd = null } = {})
571
666
  // What reads as a diff — `git diff`, a patch — is drawn as one: what went red, what came green.
572
667
  if (!result.isError && /^(?:diff --git |@@ -\d)/m.test(content)) for (const line of lines) line.tone = /^\+(?!\+\+ )/.test(line.text) ? 'add' : /^-(?!-- )/.test(line.text) ? 'del' : line.tone;
573
668
  if (full) return lines;
669
+ // One very long line — a list of paths, a minified file — is cut to a few rows, not left to fill the window.
670
+ for (const line of lines) if (line.text.length > LONG_LINE) line.text = `${line.text.slice(0, LONG_LINE - 2)} …`;
574
671
  const said = lines.filter((line) => line.text.trim() !== '');
575
672
  return said.length === 0 ? [{ text: '(no output)', tone: 'dim' }] : ends(said, false);
576
673
  };
@@ -582,13 +679,13 @@ export function toolView(call, result = null, { full = false, cwd = null } = {})
582
679
  const command = (there && whole.replace(there, '')) || whole;
583
680
  const start = command.split('\n').slice(0, SHOWN_COMMAND_LINES).join('\n').slice(0, SHOWN_COMMAND_CHARS);
584
681
  const detail = full || start.length === command.length ? command : `${start} …`;
585
- if (!result) return { title: 'Bash', detail, lines: [] };
586
- if (result.content === '') return { title: 'Bash', detail, lines: [{ text: '(no output)', tone: 'dim' }] };
587
- return { title: 'Bash', detail, lines: output() };
682
+ if (!result) return { title: 'run', detail, lines: [] };
683
+ if (result.content === '') return { title: 'run', detail, lines: [{ text: '(no output)', tone: 'dim' }] };
684
+ return { title: 'run', detail, lines: output() };
588
685
  }
589
686
  if (call.name === DELEGATE_TOOL.name) {
590
687
  // A report a job in the background sent back is titled as one, by who sent it; a call is the delegation itself.
591
- const title = input.report ? 'Report' : 'Delegate';
688
+ const title = input.report ? 'report' : 'job';
592
689
  const detail = input.job !== undefined ? `j${input.job}${input.report && input.agent ? ` ${input.agent} · ${input.title ?? ''}` : ''}` : `${input.agent ?? 'worker'} · ${input.title ?? ''}`;
593
690
  if (!result) return { title, detail, lines: [] };
594
691
  // Started in the background: what the call answered is for the model — how to wait, what not to guess. The screen says the one thing it means.
@@ -609,38 +706,41 @@ export function toolView(call, result = null, { full = false, cwd = null } = {})
609
706
  return { title, detail, lines: [{ text: summary, tone }, ...top(report.map((text) => ({ text, tone: 'plain' })), SHOWN_REPORT_LINES)] };
610
707
  }
611
708
  if (isMcpTool(call.name)) {
612
- // A server's tool: the server as the title, the tool with its input as the detail, what came back under it.
709
+ // A server's tool: the server and the tool with its input as the detail, what came back under it.
613
710
  const { server, tool } = splitMcpName(call.name);
614
- const detail = `${tool}(${compactInput(input)})`;
615
- if (!result) return { title: server, detail, lines: [] };
616
- // The line that tells the model whose data this is: here the title says it.
617
- return { title: server, detail, lines: output(unlabeled(result.content)) };
711
+ const detail = `${server} · ${tool}(${compactInput(input)})`;
712
+ if (!result) return { title: 'mcp', detail, lines: [] };
713
+ // The line that tells the model whose data this is: here the detail says it.
714
+ return { title: 'mcp', detail, lines: output(unlabeled(result.content)) };
618
715
  }
619
716
  if (isWebTool(call)) {
620
717
  // The web: what was searched for or which page was read, and under it the pages found or the page and its size.
621
718
  const detail = String(input.query ?? input.url ?? '').slice(0, SHOWN_COMMAND_CHARS);
622
- return { title: call.name === WEB_SEARCH_TOOL.name ? 'Search' : 'Fetch', detail, lines: result ? output() : [] };
719
+ return { title: call.name === WEB_SEARCH_TOOL.name ? 'search' : 'fetch', detail, lines: result ? output() : [] };
623
720
  }
624
721
  if (isAdvisorTool(call)) {
625
722
  // The advisor: who was asked. The advice is the model's alone to read, so under it only that it came, or why it did not.
626
- return { title: 'Advisor', detail: String(input.asked ?? ''), lines: result ? output() : [] };
723
+ return { title: 'advise', detail: String(input.asked ?? ''), lines: result ? output() : [] };
627
724
  }
628
725
  if (call.name === ASK_TOOL.name) {
629
726
  // A question put to the user: the question, and under it what they answered.
630
727
  const question = String(input.question ?? '').split('\n')[0];
631
- return { title: 'Question', detail: question, lines: result ? output() : [] };
728
+ return { title: 'asked', detail: question, lines: result ? output() : [] };
632
729
  }
633
730
  if (call.name !== EDITOR_TOOL.name) {
634
731
  // A job's own tools: what it was given in a line, what came back under it.
732
+ // Named in the gutter by the first word of the tool's name: `search_memory` is search.
635
733
  const given = String(input.status ?? input.query ?? input.question ?? input.text ?? '').split('\n')[0].slice(0, 80);
636
- if (!result) return { title: call.name, detail: given, lines: [] };
637
- return { title: call.name, detail: given, lines: output() };
734
+ const title = String(call.name).split(/[_-]/)[0];
735
+ if (!result) return { title, detail: given, lines: [] };
736
+ return { title, detail: given, lines: output() };
638
737
  }
639
738
  const range = Array.isArray(input.view_range) ? `:${input.view_range.join('-')}` : '';
640
- const title = input.command === 'view' ? 'Read' : input.command === 'create' ? 'Write' : input.command === 'str_replace' || input.command === 'insert' ? 'Update' : call.name;
739
+ const title = input.command === 'view' ? 'read' : input.command === 'create' ? 'write' : input.command === 'str_replace' || input.command === 'insert' ? 'edit' : 'editor';
641
740
  const detail = `${pathFrom(input.path ?? '', cwd)}${range}`;
642
741
  if (!result) return { title, detail, lines: [] };
643
- if (result.isError) return { title, detail, lines: output() };
742
+ // Folded, a failure names the file as the title does; in full, it is every word as the model read it.
743
+ if (result.isError) return { title, detail, lines: output(full ? result.content : fromProject(result.content, cwd)) };
644
744
  const added = (text) => toned(text, 'add').map((l) => ({ ...l, text: `+ ${l.text}` }));
645
745
  if (input.command === 'view') return { title, detail, lines: full ? toned(result.content, 'plain') : count(result.content) };
646
746
  // A new file is shown by its top, as what came: what was written is what is checked first.
@@ -653,7 +753,7 @@ export function toolView(call, result = null, { full = false, cwd = null } = {})
653
753
  const came = input.command === 'insert' ? (input.insert_text ?? input.new_str ?? '').replace(/\n$/, '') : (input.new_str ?? '');
654
754
  const edit = result.edit ?? { line: null, old: input.command === 'str_replace' ? (input.old_str ?? '') : '', new: came };
655
755
  const diff = diffView(edit.old, edit.new, edit.line ?? null, full);
656
- return { title, detail: diff.at === null ? detail : `${detail}:${diff.at}`, stat: diff.stat, lines: diff.lines };
756
+ return { title, detail: diff.at === null ? detail : `${detail}:${diff.at}`, stat: diff.stat, lines: diff.lines, rows: diff.rows };
657
757
  }
658
758
 
659
759
  /** The failures a request meets most, in the words a person acts on: what happened, and what to do about it. */
@@ -661,8 +761,12 @@ const FAILURES = [
661
761
  [/overloaded|\b529\b/i, "Anthropic's API is overloaded just now — nothing was lost; send it again in a minute"],
662
762
  [/rate.?limit|\b429\b/i, 'rate limited by the API — wait a minute and send it again, or /model to another model'],
663
763
  [/credit balance|billing|payment/i, 'the API account has no credit left — top it up, then send it again'],
764
+ [/prompt is too long|context.{0,20}(window|length|limit)|too many tokens/i, 'the conversation no longer fits the model — /handoff starts a fresh session with a hand-off; /new starts bare; the memory brings the thread back'],
765
+ // Any other request the API turned down — an image too big, a model it does not know — says why in its own words, kept
766
+ // under this. It and the context's go before the credential's: a 400 that says "invalid_request_error … tokens" is no
767
+ // credential refused.
768
+ [/^4(?!01|08|09|29)\d\d\b|\b(?:invalid_request|permission|not_found|request_too_large)_error\b/i, 'the API refused the request — its reason is below; change what it names, or /new to start clean'],
664
769
  [/\b401\b|authentication|x-api-key|invalid.*token|oauth/i, 'the API refused the credential — check ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN, then sumo doctor'],
665
- [/prompt is too long|context.{0,20}(window|length|limit)|too many tokens/i, 'the conversation no longer fits the model — /new starts fresh; the memory brings the thread back'],
666
770
  [/ENOTFOUND|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|fetch failed|socket hang up|network|connection error/i, 'no connection to the API — check the network, then send it again'],
667
771
  [/\b5\d\d\b|internal server error|api_error/i, 'the API failed on its side — send it again'],
668
772
  ];
@@ -674,32 +778,55 @@ export function explained(message) {
674
778
  return known ? { text: `error: ${known[1]}`, detail: said.length > 200 ? `${said.slice(0, 199)}…` : said } : { text: `error: ${said}` };
675
779
  }
676
780
 
781
+ /** /help's rows as text: the command or key, then what it does, in a column of its own; a blank row stays blank. */
782
+ const helpLines = (rows, s) => {
783
+ const wide = Math.max(...rows.filter(Boolean).map((row) => row.key.length)) + 2;
784
+ return rows.map((row) => (row ? ` ${row.key.padEnd(wide)}${s.dim(row.does)}` : ''));
785
+ };
786
+
677
787
  /**
678
788
  * The conversation as text for a pager: every entry of the chat's log in full — the whole command, all a tool gave back,
679
789
  * a reply as it is drawn — in the terminal's colours. What the screen folds, this does not; a pager scrolls and searches it.
680
790
  */
791
+ /** A failure's words as the ledger sets them: the row is already named `error`, and does not say it twice. */
792
+ export const unnamed = (text) => String(text).replace(/^error: /, '');
793
+
681
794
  export function transcript(log, s, { width = MAX_WIDTH, cwd = null } = {}) {
682
795
  const tones = { plain: (t) => t, dim: s.dim, error: s.red, add: s.green, del: s.red, ask: s.yellow };
683
- const under = (lines) => lines.map((line, i) => `${i === 0 ? ' ⎿ ' : ' '}${(tones[line.tone] ?? tones.plain)(untab(line.text))}`);
796
+ const { g } = s;
797
+ // The ledger, as the screen sets it: a row's name in the gutter, coloured as the screen colours it; the words after.
798
+ const at = (label, paint = s.dim, mark = ' ') => `${paint(label.slice(0, GUTTER).padStart(GUTTER))} ${mark} `;
799
+ // Folded here, as the screen folds them, so a long line goes on under its own words and never back at the edge;
800
+ // each row painted on its own, so a colour never runs on into the gutter.
801
+ const rows = (t, from = TEXT_AT, paint = (r) => r) =>
802
+ String(t)
803
+ .split('\n')
804
+ .flatMap((line) => fold(line, Math.max(20, width - from - 1)))
805
+ .map(paint);
806
+ const words = (t, paint) => rows(t, TEXT_AT, paint).join(`\n${' '.repeat(TEXT_AT)}`);
807
+ const under = (lines) => lines.flatMap((line) => rows(withSpan(line, s), OUT_AT, tones[line.tone] ?? tones.plain).map((row) => `${' '.repeat(OUT_AT)}${row}`));
684
808
  const out = [];
685
809
  for (const entry of log) {
686
- if (entry.kind === 'user') out.push('', ...untab(entry.text).split('\n').map((line) => `${s.yellow('┃')} ${line}`));
810
+ if (entry.kind === 'user') out.push('', `${at('you', (t) => s.bold(s.cyan(t)))}${words(untab(entry.text))}`);
687
811
  else if (entry.kind === 'reply') {
688
812
  const drawn = [];
689
- const reply = createRenderer((text) => drawn.push(text), s, { width: Math.max(MIN_WIDTH, width - 3) });
813
+ const reply = createRenderer((t) => drawn.push(t), s, { width: Math.max(MIN_WIDTH, width - TEXT_AT) });
690
814
  reply.write(entry.raw);
691
815
  reply.flush();
692
- out.push('', ...drawn.join('').replace(/\n$/, '').split('\n').map((line, i) => `${i === 0 ? '⏺ ' : ' '}${line}`));
816
+ out.push('', ...drawn.join('').replace(/\n$/, '').split('\n').map((line, i) => (i === 0 ? `${at('sumo', s.bold)}${line}` : line ? `${' '.repeat(TEXT_AT)}${line}` : '')));
693
817
  } else if (entry.kind === 'tool') {
694
818
  const view = toolView(entry.call, entry.result, { full: true, cwd });
695
819
  const stat = view.stat ? ` ${s.green(`+${view.stat.added}`)} ${s.red(`−${view.stat.removed}`)}` : '';
696
- out.push('', `${entry.result.isError ? s.red('⏺') : s.green('⏺')} ${s.bold(view.title)}(${untab(view.detail).split('\n').join('\n ')})${stat}`, ...under(view.lines));
820
+ // A failure has a mark of its own: colour alone does not tell it to someone who cannot see the colour.
821
+ const failed = entry.result.isError;
822
+ out.push('', `${at(view.title, failed ? s.red : s.dim, failed ? s.red(g.fail) : ' ')}${words(`${untab(view.detail)}${stat}`)}`, ...under(view.lines));
697
823
  } else if (entry.kind === 'shell') out.push(...under(toolView({ name: BASH_TOOL.name }, entry.result, { full: true }).lines));
698
- else if (entry.kind === 'job') out.push('', `⏺ ${s.bold(`j${entry.id}`)} ${entry.agent} · ${entry.route} — ${entry.title}`);
699
- else if (entry.kind === 'error') out.push('', s.red(entry.text), ...(entry.detail ? [s.dim(` ${entry.detail}`)] : []));
700
- else if (entry.kind === 'thought') out.push('', s.dim(`✻ Thought for ${elapsed(entry.ms)}`), ...String(entry.text ?? '').trim().split('\n').filter(Boolean).map((line) => s.dim(s.italic(` ${line}`))));
701
- else if (entry.kind === 'footer') out.push('', s.dim(` ${entry.text}`));
702
- else if (entry.kind === 'note') out.push(s.dim(` ⎿ ${entry.text.split('\n').join('\n ')}`));
824
+ else if (entry.kind === 'job') out.push('', `${at(`j${entry.id}`, s.bold)}${words(`${entry.agent} · ${entry.route} — ${entry.title}`)}`);
825
+ else if (entry.kind === 'error') out.push('', `${at('error', s.red, s.red(g.fail))}${words(unnamed(entry.text), s.red)}`, ...(entry.detail ? [`${' '.repeat(TEXT_AT)}${words(entry.detail, s.dim)}`] : []));
826
+ else if (entry.kind === 'thought') out.push('', `${at('think')}${s.dim(`for ${elapsed(entry.ms)}`)}`, ...String(entry.text ?? '').trim().split('\n').filter(Boolean).flatMap((line) => rows(line, OUT_AT, (r) => s.dim(s.italic(r))).map((row) => `${' '.repeat(OUT_AT)}${row}`)));
827
+ else if (entry.kind === 'footer') out.push(`${' '.repeat(TEXT_AT)}${words(entry.text, s.dim)}`);
828
+ else if (entry.kind === 'help') out.push('', ...helpLines(entry.rows, s));
829
+ else if (entry.kind === 'note') out.push(`${' '.repeat(TEXT_AT)}${words(entry.text, s.dim)}`);
703
830
  }
704
831
  return `${out.join('\n').replace(/^\n/, '')}\n`;
705
832
  }
@@ -722,7 +849,7 @@ export function markdownOf(log, { cwd = null, title = 'Sumo' } = {}) {
722
849
  else if (entry.kind === 'reply') out.push('', entry.raw.trim());
723
850
  else if (entry.kind === 'tool') {
724
851
  const view = toolView(entry.call, entry.result, { full: true, cwd });
725
- folded(`${view.title}(${view.detail.split('\n')[0]})${entry.result.isError ? ' — failed' : ''}`, view.lines.map((line) => line.text).join('\n'));
852
+ folded(`${view.title} ${view.detail.split('\n')[0]}${entry.result.isError ? ' — failed' : ''}`, view.lines.map((line) => line.text).join('\n'));
726
853
  } else if (entry.kind === 'shell') folded('! command', String(entry.result.content));
727
854
  else if (entry.kind === 'thought') folded(`Thought for ${elapsed(entry.ms)}`, String(entry.text ?? '').trim());
728
855
  else if (entry.kind === 'job') out.push('', `**j${entry.id}** ${entry.agent} · ${entry.route} — ${entry.title}`);
@@ -761,13 +888,13 @@ export function renderBlock(block, s, { width = MAX_WIDTH } = {}) {
761
888
 
762
889
  /** The line above the memory block: which model is answering, how hard it thinks, where the work is. */
763
890
  export function header({ route, cwd }, s) {
764
- return `${s.bold(s.green('sumo'))} ${s.dim('route')} ${route} ${s.dim(cwd)}`;
891
+ return `${s.bold(s.cyan('sumo'.padStart(GUTTER)))} ${route}${s.dim(`${VERSION ? ` · ${VERSION}` : ''} · ${cwd}`)}`;
765
892
  }
766
893
 
767
894
  /** The prompt: the model and effort kept in view, the size of the context once it matters. */
768
895
  export function prompt({ route, contextTokens }, s) {
769
896
  const k = contextTokens >= 1000 ? ` ${Math.round(contextTokens / 1000)}k` : '';
770
- return `${s.bold(s.green('sumo'))}${s.dim(` ${route}${k}`)}${s.bold('>')} `;
897
+ return `${s.bold(s.cyan('sumo'))}${s.dim(` ${route}${k}`)}${s.bold('>')} `;
771
898
  }
772
899
 
773
900
  /**