sumo-agents 0.4.0 → 0.6.1
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/AGENTS.md +8 -6
- package/CHANGELOG.md +187 -0
- package/README.md +76 -18
- package/bin/sumo.mjs +13 -2
- package/guides/feature.md +2 -1
- package/guides/memory.md +6 -4
- package/guides/projects.md +1 -1
- package/guides/review.md +1 -1
- package/package.json +5 -4
- package/prompts/dream.md +6 -0
- package/spinner.txt +25 -1
- package/src/apply.mjs +146 -18
- package/src/auth.mjs +32 -5
- package/src/card.mjs +39 -2
- package/src/catalog.mjs +6 -3
- package/src/chat.mjs +186 -75
- package/src/cli.mjs +359 -135
- package/src/cost.mjs +67 -8
- package/src/db.mjs +106 -3
- package/src/dream.mjs +445 -19
- package/src/editor.mjs +3 -2
- package/src/export.mjs +105 -7
- package/src/guard.mjs +57 -11
- package/src/guides.mjs +5 -4
- package/src/herdr.mjs +1 -1
- package/src/hooks.mjs +31 -18
- package/src/jobs.mjs +118 -39
- package/src/jobtools.mjs +6 -4
- package/src/keeper.mjs +77 -0
- package/src/local-server.mjs +9 -16
- package/src/lock.mjs +2 -1
- package/src/logs.mjs +165 -0
- package/src/loop.mjs +121 -44
- package/src/mcp.mjs +72 -16
- package/src/memory.mjs +142 -15
- package/src/model.mjs +41 -21
- package/src/paths.mjs +38 -0
- package/src/prime.mjs +19 -31
- package/src/projects.mjs +76 -12
- package/src/redact.mjs +10 -0
- package/src/render.mjs +2 -1
- package/src/route.mjs +16 -22
- package/src/sandbox.mjs +82 -3
- package/src/scan.mjs +35 -1
- package/src/scribe.mjs +10 -22
- package/src/sessions.mjs +46 -11
- package/src/setup.mjs +423 -78
- package/src/text.mjs +100 -1
- package/src/tools.mjs +258 -21
- package/src/tty.mjs +210 -44
- package/src/ui.mjs +816 -226
- package/src/verify.mjs +17 -1
package/src/tty.mjs
CHANGED
|
@@ -13,10 +13,24 @@ 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.
|
|
24
|
+
*/
|
|
25
|
+
const GLYPHS = {
|
|
26
|
+
tool: '⏺', fail: '✗', pick: '❯', under: '⎿', bar: '┃', quote: '│', rule: '─', fenceOpen: '┌─', fenceClose: '└─', todo: '☐', done: '☑', bullet: '•', warn: '⚠', thought: '✻',
|
|
27
|
+
box: { h: '─', v: '│', tl: '┌', tm: '┬', tr: '┐', ml: '├', mm: '┼', mr: '┤', bl: '└', bm: '┴', br: '┘' },
|
|
28
|
+
};
|
|
29
|
+
const PLAIN_GLYPHS = {
|
|
30
|
+
tool: '*', fail: 'x', pick: '>', under: '|', bar: '>', quote: '|', rule: '-', fenceOpen: '+-', fenceClose: '+-', todo: '[ ]', done: '[x]', bullet: '-', warn: '!', thought: '*',
|
|
31
|
+
box: { h: '-', v: '|', tl: '+', tm: '+', tr: '+', ml: '+', mm: '+', mr: '+', bl: '+', bm: '+', br: '+' },
|
|
32
|
+
};
|
|
33
|
+
|
|
20
34
|
const MAX_WIDTH = 100;
|
|
21
35
|
const MIN_WIDTH = 40;
|
|
22
36
|
|
|
@@ -27,15 +41,27 @@ const LINK_CLOSE = '\x1b]8;;\x07';
|
|
|
27
41
|
/**
|
|
28
42
|
* The style functions, each a no-op when colour is off. `links` makes `link` an address the terminal opens on a click; a
|
|
29
43
|
* terminal that does not know them draws the text alone, but a pager does not, so the screen asks for them and nothing else.
|
|
44
|
+
* `plain` draws with ASCII marks (`g`): see GLYPHS.
|
|
30
45
|
*/
|
|
31
|
-
export function styles(enabled, { links = false } = {}) {
|
|
46
|
+
export function styles(enabled, { links = false, plain = false } = {}) {
|
|
32
47
|
const s = {};
|
|
33
48
|
for (const [name, [on, off]] of Object.entries(CODES)) s[name] = enabled ? (t) => `\x1b[${on}m${t}\x1b[${off}m` : (t) => t;
|
|
34
49
|
s.link = enabled && links ? (url, text = url) => `${LINK_OPEN(url)}${text}${LINK_CLOSE}` : (_url, text = _url) => text;
|
|
50
|
+
s.plain = plain;
|
|
51
|
+
s.g = plain ? PLAIN_GLYPHS : GLYPHS;
|
|
35
52
|
return s;
|
|
36
53
|
}
|
|
37
54
|
|
|
38
|
-
|
|
55
|
+
/** The marks for a screen, plain or not. */
|
|
56
|
+
export const glyphs = (plain = false) => (plain ? PLAIN_GLYPHS : GLYPHS);
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Colour on a terminal unless NO_COLOR holds something (an empty one is not set: no-color.org) or the terminal is dumb.
|
|
60
|
+
* 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,
|
|
61
|
+
* piped too — a CI log can ask for it. Empty is not set, as for NO_COLOR.
|
|
62
|
+
*/
|
|
63
|
+
export const colourEnabled = (stream = process.stdout, env = process.env) =>
|
|
64
|
+
env.FORCE_COLOR ? env.FORCE_COLOR !== '0' && env.FORCE_COLOR !== 'false' : Boolean(stream.isTTY) && !env.NO_COLOR && env.TERM !== 'dumb';
|
|
39
65
|
|
|
40
66
|
/** Lines no wider than this read comfortably whatever the window is. */
|
|
41
67
|
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 +150,7 @@ const LIST_ITEM = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/;
|
|
|
124
150
|
* 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
151
|
* line that is no list item.
|
|
126
152
|
*/
|
|
127
|
-
|
|
153
|
+
function hangOf(line) {
|
|
128
154
|
const item = LIST_ITEM.exec(line);
|
|
129
155
|
if (!item) return null;
|
|
130
156
|
return `${item[1]}${' '.repeat(/\d/.test(item[2]) ? item[2].length + 3 : 4)}`;
|
|
@@ -206,12 +232,12 @@ export function renderLine(line, s, { fence = false, width = MAX_WIDTH, hang = n
|
|
|
206
232
|
const item = LIST_ITEM.exec(line);
|
|
207
233
|
if (item && !/\d/.test(item[2])) {
|
|
208
234
|
const task = /^\[([ xX])\]\s+(.*)$/.exec(item[3]);
|
|
209
|
-
const mark = task ? (task[1] === ' ' ? s.dim(
|
|
235
|
+
const mark = task ? (task[1] === ' ' ? s.dim(s.g.todo) : s.green(s.g.done)) : s.dim(s.g.bullet);
|
|
210
236
|
return wrap(`${item[1]} ${mark} ${inline(task ? task[2] : item[3], s)}`, width, `${item[1]} `);
|
|
211
237
|
}
|
|
212
238
|
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(
|
|
214
|
-
if (/^\s*(---|\*\*\*|___)\s*$/.test(line)) return s.dim(
|
|
239
|
+
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)} `);
|
|
240
|
+
if (/^\s*(---|\*\*\*|___)\s*$/.test(line)) return s.dim(s.g.rule.repeat(Math.min(40, width)));
|
|
215
241
|
if (hang !== null && /^\s+\S/.test(line)) return wrap(`${hang}${inline(line.trim(), s)}`, width, hang);
|
|
216
242
|
return wrap(inline(line, s), width);
|
|
217
243
|
}
|
|
@@ -289,6 +315,10 @@ export function renderTable(rows, s, width) {
|
|
|
289
315
|
const columns = head.length;
|
|
290
316
|
const aligns = Array.from({ length: columns }, (_, i) => (/^:-+:$/.test(rule[i] ?? '') ? 'center' : /-:$/.test(rule[i] ?? '') ? 'right' : 'left'));
|
|
291
317
|
const table = [head, ...body].map((row) => Array.from({ length: columns }, (_, i) => row[i] ?? ''));
|
|
318
|
+
// Each row as a record — the column's name, then the cell — one under the other.
|
|
319
|
+
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');
|
|
320
|
+
// Plain mode is drawn for a screen reader, which would spell a frame out character by character: always records.
|
|
321
|
+
if (s.plain && body.length > 0) return records();
|
|
292
322
|
const widths = Array.from({ length: columns }, (_, i) => Math.max(1, ...table.map((row) => visible(inline(row[i], s)))));
|
|
293
323
|
const room = width - (3 * columns + 1);
|
|
294
324
|
const sum = (list) => list.reduce((a, b) => a + b, 0);
|
|
@@ -299,9 +329,7 @@ export function renderTable(rows, s, width) {
|
|
|
299
329
|
const spare = room - sum(least);
|
|
300
330
|
// Three columns or more that cannot keep their words whole would fold into a ladder of word ends: each row is shown as
|
|
301
331
|
// 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
|
-
}
|
|
332
|
+
if (spare < 0 && columns >= 3 && body.length > 0) return records();
|
|
305
333
|
if (spare >= 0) {
|
|
306
334
|
const wants = widths.map((most, i) => most - least[i]);
|
|
307
335
|
const given = least.map((w, i) => w + Math.floor((spare * wants[i]) / Math.max(1, sum(wants))));
|
|
@@ -312,14 +340,15 @@ export function renderTable(rows, s, width) {
|
|
|
312
340
|
while (sum(widths) > room && Math.max(...widths) > MIN_COLUMN) widths[widths.indexOf(Math.max(...widths))]--;
|
|
313
341
|
}
|
|
314
342
|
|
|
315
|
-
const
|
|
316
|
-
const
|
|
343
|
+
const box = s.g.box;
|
|
344
|
+
const edge = (left, mid, right) => s.dim(`${left}${widths.map((w) => box.h.repeat(w + 2)).join(mid)}${right}`);
|
|
345
|
+
const bar = s.dim(box.v);
|
|
317
346
|
const draw = (row, style) => {
|
|
318
347
|
const cells = row.map((cell, i) => (visible(inline(cell, s)) <= widths[i] ? [inline(cell, s)] : fold(inline(cell, NO_STYLE), widths[i])));
|
|
319
348
|
const height = Math.max(...cells.map((c) => c.length));
|
|
320
349
|
return Array.from({ length: height }, (_, n) => `${bar} ${cells.map((c, i) => style(pad(c[n] ?? '', widths[i], aligns[i]))).join(` ${bar} `)} ${bar}`);
|
|
321
350
|
};
|
|
322
|
-
return [edge(
|
|
351
|
+
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
352
|
}
|
|
324
353
|
|
|
325
354
|
/**
|
|
@@ -333,6 +362,26 @@ export function renderTable(rows, s, width) {
|
|
|
333
362
|
*/
|
|
334
363
|
export const untab = (text) => text.replaceAll('\t', ' ');
|
|
335
364
|
|
|
365
|
+
/**
|
|
366
|
+
* The line still arriving, a mark it has opened and not yet closed made whole for now — a code span shut, a link whose
|
|
367
|
+
* address is still coming shown by its words, bold ended — so the live line never shows a mark the finished one will not.
|
|
368
|
+
* A mark with nothing after it yet is held back. Only the live line is drawn from this; the finished one, from what came.
|
|
369
|
+
*/
|
|
370
|
+
function closedForNow(line) {
|
|
371
|
+
const ticks = [...line.matchAll(/(?<!\\)`/g)];
|
|
372
|
+
if (ticks.length % 2 === 1) {
|
|
373
|
+
const at = ticks.at(-1).index;
|
|
374
|
+
return line.slice(at + 1).trim() ? `${line}\`` : line.slice(0, at);
|
|
375
|
+
}
|
|
376
|
+
const shown = line.replace(/\[([^\]\n]+)\]\([^)\s]*$/, '$1');
|
|
377
|
+
// Bold counted outside the code spans, where a `**` is only itself.
|
|
378
|
+
const bold = [...shown.replace(/`[^`]*`/g, (span) => ' '.repeat(span.length)).matchAll(/\*\*/g)];
|
|
379
|
+
if (bold.length % 2 === 0) return shown;
|
|
380
|
+
const at = bold.at(-1).index;
|
|
381
|
+
const words = shown.trimEnd();
|
|
382
|
+
return shown.slice(at + 2).trim() ? `${words}**${shown.slice(words.length)}` : shown.slice(0, at);
|
|
383
|
+
}
|
|
384
|
+
|
|
336
385
|
export function createRenderer(write, s, { width = MAX_WIDTH } = {}) {
|
|
337
386
|
let tail = '';
|
|
338
387
|
let fence = false;
|
|
@@ -349,7 +398,9 @@ export function createRenderer(write, s, { width = MAX_WIDTH } = {}) {
|
|
|
349
398
|
hang = null;
|
|
350
399
|
lang = fence ? marks[1].toLowerCase() : '';
|
|
351
400
|
code = { comment: false };
|
|
352
|
-
|
|
401
|
+
// Plain mode names the block in words, for a reader: no frame corner to spell out.
|
|
402
|
+
if (s.plain) return s.dim(fence ? ` code${marks[1] ? ` (${marks[1]})` : ''}:` : ' end of code');
|
|
403
|
+
return s.dim(fence ? ` ${s.g.fenceOpen}${marks[1] ? ` ${marks[1]}` : ''}` : ` ${s.g.fenceClose}`);
|
|
353
404
|
}
|
|
354
405
|
if (!fence) hang = hangOf(raw) ?? (/^\s+\S/.test(raw) || raw.trim() === '' ? hang : null);
|
|
355
406
|
return renderLine(raw, s, { fence, width, hang: hangOf(raw) === null ? hang : null, lang, code });
|
|
@@ -389,7 +440,7 @@ export function createRenderer(write, s, { width = MAX_WIDTH } = {}) {
|
|
|
389
440
|
/** What has not been written yet, rendered as far as it has got: the rows of a table, and the line still arriving. */
|
|
390
441
|
get tail() {
|
|
391
442
|
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');
|
|
443
|
+
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
444
|
},
|
|
394
445
|
};
|
|
395
446
|
}
|
|
@@ -404,7 +455,7 @@ export const VERSION = (() => {
|
|
|
404
455
|
})();
|
|
405
456
|
|
|
406
457
|
/** The words shown while the model works: yours, one a line, in spinner.txt at the top of the repo. */
|
|
407
|
-
|
|
458
|
+
const SPINNER_FILE = join(REPO_ROOT, 'spinner.txt');
|
|
408
459
|
const SPINNER_FALLBACK = ['Working'];
|
|
409
460
|
|
|
410
461
|
/** The working messages: every line of the file that is not blank and not a `#` comment. */
|
|
@@ -445,7 +496,7 @@ export function flow(i, frame) {
|
|
|
445
496
|
}
|
|
446
497
|
|
|
447
498
|
/** 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
|
-
|
|
499
|
+
const LOGO_FILE = join(REPO_ROOT, 'logo.txt');
|
|
449
500
|
|
|
450
501
|
/** 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
502
|
export function logoLines(file = LOGO_FILE) {
|
|
@@ -464,7 +515,8 @@ export function logoLines(file = LOGO_FILE) {
|
|
|
464
515
|
const SHOWN_REPORT_LINES = 3;
|
|
465
516
|
const SHOWN_HEAD_LINES = 2;
|
|
466
517
|
const SHOWN_TAIL_LINES = 3;
|
|
467
|
-
|
|
518
|
+
/** The rows of the screen an edit's diff takes before the rest is folded away. */
|
|
519
|
+
const SHOWN_DIFF_ROWS = 12;
|
|
468
520
|
const SHOWN_COMMAND_LINES = 3;
|
|
469
521
|
const SHOWN_COMMAND_CHARS = 240;
|
|
470
522
|
const SHOWN_WRITE_LINES = 4;
|
|
@@ -485,8 +537,26 @@ function ends(lines, full) {
|
|
|
485
537
|
/** A path as a person reads it: under the home directory, from `~`. */
|
|
486
538
|
export const tilde = (path, home = homedir()) => (path === home ? '~' : String(path).startsWith(`${home}${sep}`) ? `~${String(path).slice(home.length)}` : String(path));
|
|
487
539
|
|
|
540
|
+
/**
|
|
541
|
+
* A path without the link macOS keeps its own /var, /tmp and /etc behind (`/private/var` is `/var`): one file, one
|
|
542
|
+
* spelling on the screen, however the model or a resolved path named it. Elsewhere `/private` is a folder like any other.
|
|
543
|
+
*/
|
|
544
|
+
const unlinked = (path) => (process.platform === 'darwin' ? String(path).replace(/^\/private(?=\/(?:var|tmp|etc)(?:\/|$))/, '') : String(path));
|
|
545
|
+
|
|
488
546
|
/** 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) =>
|
|
547
|
+
export const pathFrom = (path, cwd) => {
|
|
548
|
+
const at = unlinked(path);
|
|
549
|
+
const from = cwd ? unlinked(cwd) : null;
|
|
550
|
+
return from && at === from ? '.' : from && at.startsWith(`${from}${sep}`) ? at.slice(from.length + 1) : tilde(at);
|
|
551
|
+
};
|
|
552
|
+
|
|
553
|
+
/** 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. */
|
|
554
|
+
const fromProject = (text, cwd) => {
|
|
555
|
+
if (!cwd) return text;
|
|
556
|
+
const at = unlinked(cwd);
|
|
557
|
+
const places = process.platform === 'darwin' && /^\/(?:var|tmp|etc)(?:\/|$)/.test(at) ? [`/private${at}`, at] : [at];
|
|
558
|
+
return places.reduce((said, place) => said.replaceAll(`${place}${sep}`, ''), String(text));
|
|
559
|
+
};
|
|
490
560
|
|
|
491
561
|
/** How a delegated job ended, for the line that sums it up: its mark, the word for it, and its colour. */
|
|
492
562
|
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 +570,28 @@ export const withoutColourCodes = (text) => String(text).replace(/⟨U\+001B⟩\
|
|
|
500
570
|
const toned = (text, tone) => withoutColourCodes(text).split('\n').map((t) => ({ text: t, tone }));
|
|
501
571
|
const count = (text) => [{ text: `${text === '' ? 0 : text.replace(/\n$/, '').split('\n').length} lines`, tone: 'dim' }];
|
|
502
572
|
|
|
573
|
+
/**
|
|
574
|
+
* Where two lines differ: what lies between the start they share and the end they share, in each — null when they share
|
|
575
|
+
* neither, since then the whole line is the change and marking it says nothing.
|
|
576
|
+
*/
|
|
577
|
+
function changedSpan(a, b) {
|
|
578
|
+
let start = 0;
|
|
579
|
+
while (start < a.length && start < b.length && a[start] === b[start]) start++;
|
|
580
|
+
let end = 0;
|
|
581
|
+
while (end < a.length - start && end < b.length - start && a.at(-1 - end) === b.at(-1 - end)) end++;
|
|
582
|
+
if (start + end === 0) return null;
|
|
583
|
+
return [
|
|
584
|
+
[start, a.length - end],
|
|
585
|
+
[start, b.length - end],
|
|
586
|
+
];
|
|
587
|
+
}
|
|
588
|
+
|
|
503
589
|
/**
|
|
504
590
|
* 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
591
|
* 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.
|
|
592
|
+
* stayed on either side. A line that went stands over the line that came in its place, the part of each that changed
|
|
593
|
+
* marked (`span`); what is left over on either side follows. Folding is the screen's: by the rows the lines take
|
|
594
|
+
* there (`rows`), so a narrow window does not show a long edit whole.
|
|
507
595
|
*/
|
|
508
596
|
function diffView(old, now, line, full) {
|
|
509
597
|
const was = old === '' ? [] : old.replace(/\r\n/g, '\n').split('\n');
|
|
@@ -515,20 +603,28 @@ function diffView(old, now, line, full) {
|
|
|
515
603
|
const went = was.slice(head, was.length - tail);
|
|
516
604
|
const came = is.slice(head, is.length - tail);
|
|
517
605
|
const wide = line === null ? 0 : String(line + Math.max(was.length, is.length)).length;
|
|
518
|
-
const row = (n, sign, text, tone
|
|
519
|
-
|
|
606
|
+
const row = (n, sign, text, tone, span = null) => {
|
|
607
|
+
const lead = line === null ? `${sign} ` : `${String(line + n).padStart(wide)} ${sign} `;
|
|
608
|
+
return { text: `${lead}${text}`, tone, ...(span && span[1] > span[0] ? { span: [lead.length + span[0], lead.length + span[1]] } : {}) };
|
|
609
|
+
};
|
|
610
|
+
// Pairs go only as far as both sides do: past that, what is left of the longer side, in its own order.
|
|
611
|
+
const lines = [];
|
|
612
|
+
for (let i = 0; i < Math.max(went.length, came.length); i++) {
|
|
613
|
+
const both = i < went.length && i < came.length ? changedSpan(went[i], came[i]) : null;
|
|
614
|
+
if (i < went.length) lines.push(row(head + i, '-', went[i], 'del', both?.[0]));
|
|
615
|
+
if (i < came.length) lines.push(row(head + i, '+', came[i], 'add', both?.[1]));
|
|
616
|
+
}
|
|
520
617
|
return {
|
|
521
618
|
at: line === null ? null : line + head,
|
|
522
619
|
stat: { added: came.length, removed: went.length },
|
|
523
|
-
|
|
524
|
-
|
|
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
|
-
],
|
|
620
|
+
rows: full ? null : SHOWN_DIFF_ROWS,
|
|
621
|
+
lines: [...(head > 0 ? [row(head - 1, ' ', was[head - 1], 'dim')] : []), ...lines, ...(tail > 0 ? [row(is.length - tail, ' ', is[is.length - tail], 'dim')] : [])],
|
|
529
622
|
};
|
|
530
623
|
}
|
|
531
624
|
|
|
625
|
+
/** A line with the part of it that changed in reverse video, which shows with colour off too where reverse video does. */
|
|
626
|
+
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));
|
|
627
|
+
|
|
532
628
|
/**
|
|
533
629
|
* 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
630
|
* there. A heading is dropped — or, with `headings: 'keep'`, kept as its words; either way a line of three words or fewer
|
|
@@ -556,6 +652,47 @@ function readable(text, cwd = null, { headings = 'drop' } = {}) {
|
|
|
556
652
|
return lines;
|
|
557
653
|
}
|
|
558
654
|
|
|
655
|
+
/** The most of a failed command's failing lines a folded result shows. */
|
|
656
|
+
const SHOWN_FAILING_LINES = 4;
|
|
657
|
+
/** The last lines of a failed command, always shown: the exit code, why it was stopped, what the user said declining it. */
|
|
658
|
+
const SHOWN_FAILED_TAIL = 2;
|
|
659
|
+
/** A line that says what failed: a test runner's cross, an assertion, an error, a panic, a rejection. */
|
|
660
|
+
const FAILING = /[✖✗×]|^\s*not ok\b|\bFAIL(?:ED|S)?\b|\b(?:failed|failing|failure|rejected)\b|\b(?:Error|Exception|panic)\b|\berror(?:\[|:)|\bexpected\b.+\bto\b/;
|
|
661
|
+
/** A line a runner marks as passed: never a line that says what failed, whatever the test's name says. */
|
|
662
|
+
const PASSING = /^\s*(?:[✔✓√]|ok\b|PASS\b)/;
|
|
663
|
+
/** A command that runs tests: only its count is read as how a run went — a grep that finds "12 passed" is a grep. */
|
|
664
|
+
const TESTS = /\b(?:test|tests|spec|pytest|jest|vitest|mocha|ava|rspec|phpunit|check)\b/;
|
|
665
|
+
/** How test runners count what passed: node --test, TAP, jest/vitest/pytest/cargo, mocha. */
|
|
666
|
+
const PASSED = [/^ℹ pass (\d+)$/m, /^# pass (\d+)$/m, /\b(\d+) passed\b/, /\b(\d+) passing\b/];
|
|
667
|
+
/** A count of what failed beside it: a run that exits 0 — piped to tail, `|| true` — may still have failed. */
|
|
668
|
+
const FAILED = /^ℹ fail [1-9]|^# fail [1-9]|\b[1-9]\d* (?:failed|failing|errors?)\b|\bFAILED\b/m;
|
|
669
|
+
/** The last lines of what a command printed where a test runner's count is looked for. */
|
|
670
|
+
const COUNT_LINES = 8;
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* What a command printed, folded to what says how it went. A failure shows the lines that say what failed — a test's
|
|
674
|
+
* cross, an assertion, an error — and its last lines, not its banner; a test run that passed is its count, one row.
|
|
675
|
+
* A few lines are shown whole, and anything else shows both ends, as it always did.
|
|
676
|
+
*/
|
|
677
|
+
function ranLines(said, failed, command) {
|
|
678
|
+
if (failed) {
|
|
679
|
+
if (said.length <= SHOWN_HEAD_LINES + SHOWN_TAIL_LINES + 1) return said;
|
|
680
|
+
const tail = said.length - SHOWN_FAILED_TAIL;
|
|
681
|
+
const failing = said.slice(0, tail).filter((line) => FAILING.test(line.text) && !PASSING.test(line.text)).slice(0, SHOWN_FAILING_LINES);
|
|
682
|
+
if (failing.length === 0) return ends(said, false);
|
|
683
|
+
return [...failing, more(tail - failing.length), ...said.slice(tail)];
|
|
684
|
+
}
|
|
685
|
+
// A runner prints its count at the end: a count further up is something the command printed, not how it went.
|
|
686
|
+
const text = said.slice(-COUNT_LINES).map((line) => line.text).join('\n');
|
|
687
|
+
if (TESTS.test(command) && !FAILED.test(text)) {
|
|
688
|
+
for (const passed of PASSED) {
|
|
689
|
+
const n = Number(passed.exec(text)?.[1] ?? 0);
|
|
690
|
+
if (n > 0) return [{ text: `✓ ${n} passed`, tone: 'add' }];
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
return ends(said, false);
|
|
694
|
+
}
|
|
695
|
+
|
|
559
696
|
/**
|
|
560
697
|
* A tool call for the screen: what ran, and under it the part of the result
|
|
561
698
|
* worth a glance — both ends of a command's output, an edit as a diff, a read
|
|
@@ -563,16 +700,23 @@ function readable(text, cwd = null, { headings = 'drop' } = {}) {
|
|
|
563
700
|
* every line, the command whole, and the file itself for a read or a write.
|
|
564
701
|
* `cwd` is the project the work is in: a file in it is named from there.
|
|
565
702
|
*/
|
|
703
|
+
/** The most of one line a folded result shows: about five rows of a window 80 wide. */
|
|
704
|
+
const LONG_LINE = 400;
|
|
705
|
+
|
|
566
706
|
export function toolView(call, result = null, { full = false, cwd = null } = {}) {
|
|
707
|
+
// Folded, a result written for the screen as well as for the model says what it means in a line; in full, every word.
|
|
708
|
+
if (!full && typeof result?.shown === 'string') result = { ...result, content: result.shown };
|
|
567
709
|
const input = call.input ?? {};
|
|
568
710
|
// Folded, the empty lines of what came back are not shown: three of five lines spent on nothing say nothing.
|
|
569
|
-
const output = (content = result.content) => {
|
|
711
|
+
const output = (content = result.content, folded = (said) => ends(said, false)) => {
|
|
570
712
|
const lines = toned(content, result.isError ? 'error' : 'plain');
|
|
571
713
|
// What reads as a diff — `git diff`, a patch — is drawn as one: what went red, what came green.
|
|
572
714
|
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
715
|
if (full) return lines;
|
|
716
|
+
// One very long line — a list of paths, a minified file — is cut to a few rows, not left to fill the window.
|
|
717
|
+
for (const line of lines) if (line.text.length > LONG_LINE) line.text = `${line.text.slice(0, LONG_LINE - 2)} …`;
|
|
574
718
|
const said = lines.filter((line) => line.text.trim() !== '');
|
|
575
|
-
return said.length === 0 ? [{ text: '(no output)', tone: 'dim' }] :
|
|
719
|
+
return said.length === 0 ? [{ text: '(no output)', tone: 'dim' }] : folded(said);
|
|
576
720
|
};
|
|
577
721
|
if (call.name === BASH_TOOL.name) {
|
|
578
722
|
// Folded, the command is its first lines; asked for in full, it is all there: nothing else on the screen says what ran.
|
|
@@ -584,7 +728,7 @@ export function toolView(call, result = null, { full = false, cwd = null } = {})
|
|
|
584
728
|
const detail = full || start.length === command.length ? command : `${start} …`;
|
|
585
729
|
if (!result) return { title: 'Bash', detail, lines: [] };
|
|
586
730
|
if (result.content === '') return { title: 'Bash', detail, lines: [{ text: '(no output)', tone: 'dim' }] };
|
|
587
|
-
return { title: 'Bash', detail, lines: output() };
|
|
731
|
+
return { title: 'Bash', detail, lines: output(result.content, (said) => ranLines(said, result.isError, command)) };
|
|
588
732
|
}
|
|
589
733
|
if (call.name === DELEGATE_TOOL.name) {
|
|
590
734
|
// A report a job in the background sent back is titled as one, by who sent it; a call is the delegation itself.
|
|
@@ -640,7 +784,8 @@ export function toolView(call, result = null, { full = false, cwd = null } = {})
|
|
|
640
784
|
const title = input.command === 'view' ? 'Read' : input.command === 'create' ? 'Write' : input.command === 'str_replace' || input.command === 'insert' ? 'Update' : call.name;
|
|
641
785
|
const detail = `${pathFrom(input.path ?? '', cwd)}${range}`;
|
|
642
786
|
if (!result) return { title, detail, lines: [] };
|
|
643
|
-
|
|
787
|
+
// Folded, a failure names the file as the title does; in full, it is every word as the model read it.
|
|
788
|
+
if (result.isError) return { title, detail, lines: output(full ? result.content : fromProject(result.content, cwd)) };
|
|
644
789
|
const added = (text) => toned(text, 'add').map((l) => ({ ...l, text: `+ ${l.text}` }));
|
|
645
790
|
if (input.command === 'view') return { title, detail, lines: full ? toned(result.content, 'plain') : count(result.content) };
|
|
646
791
|
// A new file is shown by its top, as what came: what was written is what is checked first.
|
|
@@ -653,7 +798,7 @@ export function toolView(call, result = null, { full = false, cwd = null } = {})
|
|
|
653
798
|
const came = input.command === 'insert' ? (input.insert_text ?? input.new_str ?? '').replace(/\n$/, '') : (input.new_str ?? '');
|
|
654
799
|
const edit = result.edit ?? { line: null, old: input.command === 'str_replace' ? (input.old_str ?? '') : '', new: came };
|
|
655
800
|
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 };
|
|
801
|
+
return { title, detail: diff.at === null ? detail : `${detail}:${diff.at}`, stat: diff.stat, lines: diff.lines, rows: diff.rows };
|
|
657
802
|
}
|
|
658
803
|
|
|
659
804
|
/** The failures a request meets most, in the words a person acts on: what happened, and what to do about it. */
|
|
@@ -661,8 +806,12 @@ const FAILURES = [
|
|
|
661
806
|
[/overloaded|\b529\b/i, "Anthropic's API is overloaded just now — nothing was lost; send it again in a minute"],
|
|
662
807
|
[/rate.?limit|\b429\b/i, 'rate limited by the API — wait a minute and send it again, or /model to another model'],
|
|
663
808
|
[/credit balance|billing|payment/i, 'the API account has no credit left — top it up, then send it again'],
|
|
809
|
+
[/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'],
|
|
810
|
+
// Any other request the API turned down — an image too big, a model it does not know — says why in its own words, kept
|
|
811
|
+
// under this. It and the context's go before the credential's: a 400 that says "invalid_request_error … tokens" is no
|
|
812
|
+
// credential refused.
|
|
813
|
+
[/^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
814
|
[/\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
815
|
[/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
816
|
[/\b5\d\d\b|internal server error|api_error/i, 'the API failed on its side — send it again'],
|
|
668
817
|
];
|
|
@@ -674,36 +823,53 @@ export function explained(message) {
|
|
|
674
823
|
return known ? { text: `error: ${known[1]}`, detail: said.length > 200 ? `${said.slice(0, 199)}…` : said } : { text: `error: ${said}` };
|
|
675
824
|
}
|
|
676
825
|
|
|
826
|
+
/** /help's rows as text: the command or key, then what it does, in a column of its own; a blank row stays blank. */
|
|
827
|
+
const helpLines = (rows, s) => {
|
|
828
|
+
const wide = Math.max(...rows.filter(Boolean).map((row) => row.key.length)) + 2;
|
|
829
|
+
return rows.map((row) => (row ? ` ${row.key.padEnd(wide)}${s.dim(row.does)}` : ''));
|
|
830
|
+
};
|
|
831
|
+
|
|
677
832
|
/**
|
|
678
833
|
* 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
834
|
* 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
835
|
*/
|
|
681
836
|
export function transcript(log, s, { width = MAX_WIDTH, cwd = null } = {}) {
|
|
682
837
|
const tones = { plain: (t) => t, dim: s.dim, error: s.red, add: s.green, del: s.red, ask: s.yellow };
|
|
683
|
-
const
|
|
838
|
+
const { g } = s;
|
|
839
|
+
// Folded here, at the window's width, so a long line goes on under its own words and never back at the edge; each row
|
|
840
|
+
// painted on its own, so a colour never runs on into the margin.
|
|
841
|
+
const under = (lines) =>
|
|
842
|
+
lines
|
|
843
|
+
.flatMap((line) => fold(withSpan(line, s), Math.max(20, width - 6)).map(tones[line.tone] ?? tones.plain))
|
|
844
|
+
.map((row, i) => `${i === 0 ? ` ${g.under} ` : ' '}${row}`);
|
|
684
845
|
const out = [];
|
|
685
846
|
for (const entry of log) {
|
|
686
|
-
if (entry.kind === 'user') out.push('', ...untab(entry.text).split('\n').map((line) => `${s.yellow(
|
|
847
|
+
if (entry.kind === 'user') out.push('', ...untab(entry.text).split('\n').map((line) => `${s.yellow(g.bar)} ${line}`));
|
|
687
848
|
else if (entry.kind === 'reply') {
|
|
688
849
|
const drawn = [];
|
|
689
850
|
const reply = createRenderer((text) => drawn.push(text), s, { width: Math.max(MIN_WIDTH, width - 3) });
|
|
690
851
|
reply.write(entry.raw);
|
|
691
852
|
reply.flush();
|
|
692
|
-
out.push('', ...drawn.join('').replace(/\n$/, '').split('\n').map((line, i) => `${i === 0 ?
|
|
853
|
+
out.push('', ...drawn.join('').replace(/\n$/, '').split('\n').map((line, i) => `${i === 0 ? `${g.tool} ` : ' '}${line}`));
|
|
693
854
|
} else if (entry.kind === 'tool') {
|
|
694
855
|
const view = toolView(entry.call, entry.result, { full: true, cwd });
|
|
695
|
-
const stat =
|
|
696
|
-
|
|
856
|
+
const stat = statOf(view.stat, s);
|
|
857
|
+
// A failure has a mark of its own: colour alone does not tell it to someone who cannot see the colour.
|
|
858
|
+
out.push('', `${entry.result.isError ? s.red(g.fail) : s.green(g.tool)} ${s.bold(view.title)}(${untab(view.detail).split('\n').join('\n ')})${stat}`, ...under(view.lines));
|
|
697
859
|
} 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('',
|
|
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(
|
|
860
|
+
else if (entry.kind === 'job') out.push('', `${g.tool} ${s.bold(`j${entry.id}`)} ${entry.agent} · ${entry.route} — ${entry.title}`);
|
|
861
|
+
else if (entry.kind === 'error') out.push('', s.red(`${g.fail} ${entry.text}`), ...(entry.detail ? [s.dim(` ${entry.detail}`)] : []));
|
|
862
|
+
else if (entry.kind === 'thought') out.push('', s.dim(`${g.thought} Thought for ${elapsed(entry.ms)}`), ...String(entry.text ?? '').trim().split('\n').filter(Boolean).map((line) => s.dim(s.italic(` ${line}`))));
|
|
701
863
|
else if (entry.kind === 'footer') out.push('', s.dim(` ${entry.text}`));
|
|
702
|
-
else if (entry.kind === '
|
|
864
|
+
else if (entry.kind === 'help') out.push('', ...helpLines(entry.rows, s));
|
|
865
|
+
else if (entry.kind === 'note') out.push(s.dim(` ${g.under} ${entry.text.split('\n').join('\n ')}`));
|
|
703
866
|
}
|
|
704
867
|
return `${out.join('\n').replace(/^\n/, '')}\n`;
|
|
705
868
|
}
|
|
706
869
|
|
|
870
|
+
/** How much an edit added and took away, `+2 −1`: a side that is nothing is not said. */
|
|
871
|
+
export const statOf = (stat, s) => (stat ? [stat.added > 0 ? s.green(`+${stat.added}`) : '', stat.removed > 0 ? s.red(`−${stat.removed}`) : ''].filter(Boolean).map((part) => ` ${part}`).join('') : '');
|
|
872
|
+
|
|
707
873
|
/** A fence for text that may hold fences of its own: longer than any run of backticks in it. */
|
|
708
874
|
const fenceFor = (text) => '`'.repeat(Math.max(3, ...[...String(text).matchAll(/`+/g)].map((m) => m[0].length + 1)));
|
|
709
875
|
|