sumo-agents 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/AGENTS.md +8 -6
- package/CHANGELOG.md +155 -0
- package/README.md +82 -19
- 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 +289 -89
- 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 +113 -11
- package/src/export.mjs +105 -7
- package/src/guard.mjs +57 -11
- package/src/guides.mjs +5 -4
- package/src/herdr.mjs +9 -4
- package/src/hooks.mjs +35 -19
- 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 +94 -12
- package/src/redact.mjs +10 -0
- package/src/render.mjs +2 -1
- package/src/route.mjs +39 -25
- package/src/sandbox.mjs +82 -3
- package/src/scan.mjs +35 -1
- package/src/scribe.mjs +10 -22
- package/src/sessions.mjs +49 -13
- package/src/setup.mjs +425 -76
- package/src/text.mjs +100 -1
- package/src/tools.mjs +258 -21
- package/src/tty.mjs +481 -105
- package/src/ui.mjs +1205 -276
- package/src/verify.mjs +17 -1
package/src/tty.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import { isAdvisorTool } from './advisor.mjs';
|
|
|
5
5
|
import { compactInput, isMcpTool, splitMcpName, unlabeled } from './mcp.mjs';
|
|
6
6
|
import { REPO_ROOT } from './paths.mjs';
|
|
7
7
|
import { elapsed } from './text.mjs';
|
|
8
|
-
import { BASH_TOOL, DELEGATE_TOOL, EDITOR_TOOL } from './tools.mjs';
|
|
8
|
+
import { ASK_TOOL, BASH_TOOL, DELEGATE_TOOL, EDITOR_TOOL } from './tools.mjs';
|
|
9
9
|
import { isWebTool, WEB_SEARCH_TOOL } from './web.mjs';
|
|
10
10
|
|
|
11
11
|
/**
|
|
@@ -13,21 +13,67 @@ 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'] };
|
|
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
|
|
|
23
|
-
/**
|
|
24
|
-
|
|
49
|
+
/** A link's ends (OSC 8): the terminal makes the text between them open the address, however the lines it is drawn on are broken. */
|
|
50
|
+
const LINK_OPEN = (url) => `\x1b]8;;${url}\x07`;
|
|
51
|
+
const LINK_CLOSE = '\x1b]8;;\x07';
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The style functions, each a no-op when colour is off. `links` makes `link` an address the terminal opens on a click; a
|
|
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.
|
|
57
|
+
*/
|
|
58
|
+
export function styles(enabled, { links = false, plain = false } = {}) {
|
|
25
59
|
const s = {};
|
|
26
60
|
for (const [name, [on, off]] of Object.entries(CODES)) s[name] = enabled ? (t) => `\x1b[${on}m${t}\x1b[${off}m` : (t) => t;
|
|
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;
|
|
27
64
|
return s;
|
|
28
65
|
}
|
|
29
66
|
|
|
30
|
-
|
|
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';
|
|
31
77
|
|
|
32
78
|
/** Lines no wider than this read comfortably whatever the window is. */
|
|
33
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));
|
|
@@ -39,30 +85,46 @@ const columnsOf = (ch) => (WIDE.test(ch) ? 2 : 1);
|
|
|
39
85
|
|
|
40
86
|
/** The columns text takes on a terminal, colour codes not counted: a wide character is two, so a table around it lines up. */
|
|
41
87
|
const visible = (t) => {
|
|
42
|
-
const plain = t.replace(/\x1b\[[0-9;]*m/g, '');
|
|
88
|
+
const plain = t.replace(/\x1b\[[0-9;]*m|\x1b\]8;[^\x07]*\x07/g, '');
|
|
43
89
|
if (!/[^\x00-\x7e]/.test(plain)) return plain.length;
|
|
44
90
|
let width = 0;
|
|
45
91
|
for (const { segment } of GRAPHEMES.segment(plain)) width += columnsOf(segment);
|
|
46
92
|
return width;
|
|
47
93
|
};
|
|
48
94
|
|
|
49
|
-
/**
|
|
95
|
+
/**
|
|
96
|
+
* Word-wraps styled text to `width`, measuring only what is visible; continuation lines carry `indent`. A word wider than
|
|
97
|
+
* a line — an address, a path — is cut at the edge and goes on under the indent: no line is left for the terminal to break.
|
|
98
|
+
*/
|
|
50
99
|
export function wrap(text, width, indent = '') {
|
|
51
100
|
if (visible(text) <= width) return text;
|
|
52
101
|
const lead = /^\s*/.exec(text)[0];
|
|
102
|
+
// An indent that leaves no room is dropped: a word goes on at the edge rather than not at all.
|
|
103
|
+
const hang = visible(indent) < width - 1 ? indent : '';
|
|
53
104
|
const lines = [];
|
|
54
105
|
let line = lead;
|
|
55
106
|
for (const word of text.slice(lead.length).split(' ')) {
|
|
56
107
|
const next = line === lead ? `${lead}${word}` : `${line} ${word}`;
|
|
57
108
|
if (line !== lead && visible(next) > width) {
|
|
58
109
|
lines.push(line);
|
|
59
|
-
line = `${
|
|
110
|
+
line = `${hang}${word}`;
|
|
60
111
|
} else line = next;
|
|
112
|
+
while (visible(line) > width) {
|
|
113
|
+
const [head, ...rest] = cut(line, width);
|
|
114
|
+
lines.push(head);
|
|
115
|
+
line = `${hang}${rest.join('')}`;
|
|
116
|
+
}
|
|
61
117
|
}
|
|
62
118
|
lines.push(line);
|
|
63
119
|
return lines.join('\n');
|
|
64
120
|
}
|
|
65
121
|
|
|
122
|
+
/** An address in text: up to the space after it, without the stop or bracket a sentence puts after it. */
|
|
123
|
+
const ADDRESS = /\bhttps?:\/\/[^\s<>()[\]`]*[^\s<>()[\]`.,;:!?'"]/g;
|
|
124
|
+
|
|
125
|
+
/** Text with each address in it made a link, for lines that are not markdown: what a tool gave back, a note. */
|
|
126
|
+
export const linked = (text, s) => String(text).replace(ADDRESS, (url) => s.link(url));
|
|
127
|
+
|
|
66
128
|
/** A character after a backslash is meant as itself, not as a mark. */
|
|
67
129
|
const ESCAPED = /\\([\\`*_~[\]()<>#|!])/g;
|
|
68
130
|
/** A piece already drawn stands in the line behind these until the end, so no later mark reads into it or into its colour codes. */
|
|
@@ -78,8 +140,10 @@ export function inline(line, s) {
|
|
|
78
140
|
const out = line
|
|
79
141
|
.replace(/(?<!\\)`([^`]+)`/g, (_, code) => keep(s.cyan(code)))
|
|
80
142
|
.replace(ESCAPED, (_, ch) => keep(ch))
|
|
81
|
-
.replace(/<(https?:\/\/[^>\s]+)>/g, (_, url) => keep(url))
|
|
82
|
-
.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, text, url) => (text === url ? keep(url) : `${text} ${keep(s.dim(`(${url})`))}`))
|
|
143
|
+
.replace(/<(https?:\/\/[^>\s]+)>/g, (_, url) => keep(s.link(url)))
|
|
144
|
+
.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, text, url) => (text === url ? keep(s.link(url)) : `${text} ${keep(s.dim(`(${s.link(url)})`))}`))
|
|
145
|
+
// An address in the words is one link, kept from the marks: its underscores are not italics.
|
|
146
|
+
.replace(ADDRESS, (url) => keep(s.link(url)))
|
|
83
147
|
.replace(/\*\*\*(?!\s)([^*]+?)(?<!\s)\*\*\*/g, (_, t) => s.bold(s.italic(t)))
|
|
84
148
|
.replace(/\*\*(?!\s)([^*]+?)(?<!\s)\*\*/g, (_, t) => s.bold(t))
|
|
85
149
|
.replace(/(?<![\w_])__(?!\s)([^_]+?)(?<!\s)__(?![\w_])/g, (_, t) => s.bold(t))
|
|
@@ -98,30 +162,94 @@ const LIST_ITEM = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/;
|
|
|
98
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
|
|
99
163
|
* line that is no list item.
|
|
100
164
|
*/
|
|
101
|
-
|
|
165
|
+
function hangOf(line) {
|
|
102
166
|
const item = LIST_ITEM.exec(line);
|
|
103
167
|
if (!item) return null;
|
|
104
168
|
return `${item[1]}${' '.repeat(/\d/.test(item[2]) ? item[2].length + 3 : 4)}`;
|
|
105
169
|
}
|
|
106
170
|
|
|
171
|
+
const words = (list) => new Set(list.split(' '));
|
|
172
|
+
const C_LIKE = 'break case continue default do else for goto if return switch while true false null';
|
|
173
|
+
/**
|
|
174
|
+
* The languages a code block is coloured in: how a comment starts, which quotes make a string, and the words the language
|
|
175
|
+
* keeps for itself. Anything else — output, a log, plain text — is left as it came: colour guessed onto it would mislead.
|
|
176
|
+
*/
|
|
177
|
+
const LANGUAGES = (() => {
|
|
178
|
+
const js = { line: '//', block: true, quotes: '"\'`', words: words(`${C_LIKE} as async await catch class const debugger delete export extends finally from function import in instanceof let new of static super this throw try typeof undefined var void with yield interface type enum implements private public protected readonly declare namespace abstract keyof satisfies`) };
|
|
179
|
+
const py = { line: '#', quotes: '"\'', words: words('and as assert async await break class continue def del elif else except False finally for from global if import in is lambda None nonlocal not or pass raise return self True try while with yield match case') };
|
|
180
|
+
const sh = { line: '#', quotes: '"\'', words: words('if then else elif fi for while until do done case esac in function return local export readonly set unset echo exit source alias cd') };
|
|
181
|
+
const go = { line: '//', block: true, quotes: '"\'`', words: words(`${C_LIKE} chan const defer fallthrough func go import interface map package range select struct type var nil iota`) };
|
|
182
|
+
const rust = { line: '//', block: true, quotes: '"', words: words(`${C_LIKE} as async await const crate dyn enum extern fn impl in let loop match mod move mut pub ref self Self static struct super trait type unsafe use where Some None Ok Err`) };
|
|
183
|
+
const c = { line: '//', block: true, quotes: '"\'', words: words(`${C_LIKE} auto char class const double enum extern float int long namespace new private protected public register short signed sizeof static struct template this throw try catch typedef union unsigned using virtual void volatile bool include define nullptr import package final abstract extends implements interface var val fun let func guard struct override`) };
|
|
184
|
+
const ruby = { line: '#', quotes: '"\'', words: words('alias and begin break case class def defined do else elsif end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield require') };
|
|
185
|
+
const sql = { line: '--', block: true, quotes: '\'"', words: words('select from where and or not insert into values update set delete create table index drop alter join left right inner outer on as group by order having limit offset distinct union all null is in like between case when then else end primary key references default exists'), caseless: true };
|
|
186
|
+
const conf = { line: '#', quotes: '"\'', words: words('true false null yes no on off') };
|
|
187
|
+
const named = { js, javascript: js, jsx: js, mjs: js, cjs: js, ts: js, typescript: js, tsx: js, json: { quotes: '"', words: words('true false null') }, py: py, python: py, sh, bash: sh, zsh: sh, shell: sh, go, golang: go, rs: rust, rust, c, h: c, cpp: c, 'c++': c, cc: c, java: c, kotlin: c, kt: c, swift: c, cs: c, csharp: c, rb: ruby, ruby, sql, yaml: conf, yml: conf, toml: conf, ini: conf };
|
|
188
|
+
return named;
|
|
189
|
+
})();
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* A line of code in its language's colours: comments faint, strings green, numbers yellow, the language's own words
|
|
193
|
+
* magenta. `code` carries a block comment over from the line before; a diff is its changes, green and red.
|
|
194
|
+
*/
|
|
195
|
+
export function highlight(line, lang, s, code = null) {
|
|
196
|
+
if (lang === 'diff' || lang === 'patch') return /^\+(?!\+\+ )/.test(line) ? s.green(line) : /^-(?!-- )/.test(line) ? s.red(line) : /^@@/.test(line) ? s.cyan(line) : line;
|
|
197
|
+
const language = LANGUAGES[lang];
|
|
198
|
+
if (!language || !line) return line;
|
|
199
|
+
const state = code ?? { comment: false };
|
|
200
|
+
let out = '';
|
|
201
|
+
let at = 0;
|
|
202
|
+
if (state.comment) {
|
|
203
|
+
const end = line.indexOf('*/');
|
|
204
|
+
if (end === -1) return s.dim(line);
|
|
205
|
+
out = s.dim(line.slice(0, end + 2));
|
|
206
|
+
at = end + 2;
|
|
207
|
+
state.comment = false;
|
|
208
|
+
}
|
|
209
|
+
const quotes = [...language.quotes].map((q) => `${q === '`' ? '`' : `\\${q}`}(?:[^${q === '`' ? '`' : `\\${q}`}\\\\]|\\\\.)*${q === '`' ? '`' : `\\${q}`}`).join('|');
|
|
210
|
+
const comment = language.line === '#' ? '(?:^|(?<=\\s))#.*' : language.line ? `${language.line.replace(/\//g, '\\/')}.*` : '(?!)';
|
|
211
|
+
const pattern = new RegExp(`(${comment})|(${language.block ? '\\/\\*' : '(?!)'})|(${quotes || '(?!)'})|(\\b0x[0-9a-fA-F]+\\b|\\b\\d[\\d_]*(?:\\.\\d+)?(?:[eE][+-]?\\d+)?\\b)|(\\b[A-Za-z_][\\w]*\\b)`, 'g');
|
|
212
|
+
pattern.lastIndex = at;
|
|
213
|
+
for (let m; (m = pattern.exec(line)); ) {
|
|
214
|
+
out += line.slice(at, m.index);
|
|
215
|
+
at = m.index + m[0].length;
|
|
216
|
+
if (m[1] !== undefined) out += s.dim(m[0]);
|
|
217
|
+
else if (m[2] !== undefined) {
|
|
218
|
+
const end = line.indexOf('*/', at);
|
|
219
|
+
if (end === -1) {
|
|
220
|
+
out += s.dim(line.slice(m.index));
|
|
221
|
+
state.comment = true;
|
|
222
|
+
return out;
|
|
223
|
+
}
|
|
224
|
+
out += s.dim(line.slice(m.index, end + 2));
|
|
225
|
+
at = end + 2;
|
|
226
|
+
pattern.lastIndex = at;
|
|
227
|
+
} else if (m[3] !== undefined) out += s.green(m[0]);
|
|
228
|
+
else if (m[4] !== undefined) out += s.yellow(m[0]);
|
|
229
|
+
else out += language.words.has(language.caseless ? m[0].toLowerCase() : m[0]) ? s.magenta(m[0]) : m[0];
|
|
230
|
+
}
|
|
231
|
+
return out + line.slice(at);
|
|
232
|
+
}
|
|
233
|
+
|
|
107
234
|
/**
|
|
108
235
|
* One line of a reply: block-level marks replaced by weight and indent, then wrapped with a hanging indent.
|
|
109
236
|
* `hang` is the indent of the list item a line may go on with: an indented line that is not an item of its own is drawn there.
|
|
110
237
|
*/
|
|
111
|
-
export function renderLine(line, s, { fence = false, width = MAX_WIDTH, hang = null } = {}) {
|
|
238
|
+
export function renderLine(line, s, { fence = false, width = MAX_WIDTH, hang = null, lang = '', code = null } = {}) {
|
|
112
239
|
// Code is what is read most closely: the frame around it is faint, the code is not.
|
|
113
|
-
|
|
240
|
+
// A line too long for the window goes on under itself, at its own indent, so the code keeps its shape.
|
|
241
|
+
if (fence) return wrap(` ${highlight(line, lang, s, code)}`, width, ` ${/^\s*/.exec(line)[0]}`);
|
|
114
242
|
const heading = /^(#{1,6})\s+(.*)$/.exec(line);
|
|
115
243
|
if (heading) return wrap(heading[1].length === 1 ? s.bold(s.underline(inline(heading[2], s))) : s.bold(inline(heading[2], s)), width);
|
|
116
244
|
const item = LIST_ITEM.exec(line);
|
|
117
245
|
if (item && !/\d/.test(item[2])) {
|
|
118
246
|
const task = /^\[([ xX])\]\s+(.*)$/.exec(item[3]);
|
|
119
|
-
const mark = task ? (task[1] === ' ' ? s.dim(
|
|
247
|
+
const mark = task ? (task[1] === ' ' ? s.dim(s.g.todo) : s.green(s.g.done)) : s.dim(s.g.bullet);
|
|
120
248
|
return wrap(`${item[1]} ${mark} ${inline(task ? task[2] : item[3], s)}`, width, `${item[1]} `);
|
|
121
249
|
}
|
|
122
250
|
if (item) return wrap(`${item[1]} ${s.dim(`${item[2].slice(0, -1)}.`)} ${inline(item[3], s)}`, width, hangOf(line));
|
|
123
|
-
if (/^\s*>\s?/.test(line)) return wrap(` ${s.dim(
|
|
124
|
-
if (/^\s*(---|\*\*\*|___)\s*$/.test(line)) return s.dim(
|
|
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)));
|
|
125
253
|
if (hang !== null && /^\s+\S/.test(line)) return wrap(`${hang}${inline(line.trim(), s)}`, width, hang);
|
|
126
254
|
return wrap(inline(line, s), width);
|
|
127
255
|
}
|
|
@@ -135,24 +263,49 @@ const cellsOf = (row) => row.trim().slice(1, -1).split(/(?<!\\)\|/).map((c) => c
|
|
|
135
263
|
|
|
136
264
|
const GRAPHEMES = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
|
|
137
265
|
|
|
138
|
-
/**
|
|
266
|
+
/** What each closing code ends: the opening codes it closes. */
|
|
267
|
+
const CLOSES = { 0: /.*/, 22: /^(1|2)$/, 23: /^3$/, 24: /^4$/, 27: /^7$/, 29: /^9$/, 39: /^(3[0-7]|9[0-7]|38;.*)$/, 49: /^(4[0-7]|10[0-7]|48;.*)$/ };
|
|
268
|
+
/** The styles open after `code`, given the ones open before it. */
|
|
269
|
+
function styledAfter(on, code) {
|
|
270
|
+
const n = code.slice(2, -1) || '0';
|
|
271
|
+
const closes = CLOSES[n];
|
|
272
|
+
return closes ? on.filter((open) => !closes.test(open.slice(2, -1))) : [...on, code];
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* A line cut into pieces no wider than `width`, between characters: an emoji, even one joined from several, stays whole,
|
|
277
|
+
* and a colour code takes no room — it stays with the character after it.
|
|
278
|
+
*/
|
|
139
279
|
function cut(line, width) {
|
|
140
280
|
const pieces = [''];
|
|
141
281
|
let used = 0;
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
282
|
+
// A link cut in two is closed at the end of one piece and opened again at the start of the next: both halves open it.
|
|
283
|
+
// So is a style: the next piece starts in the colour the last one ended in, since each row is drawn on its own.
|
|
284
|
+
let link = null;
|
|
285
|
+
let on = [];
|
|
286
|
+
for (const [token] of line.matchAll(/\x1b\[[0-9;]*m|\x1b\]8;[^\x07]*\x07|[^\x1b]+|\x1b/g)) {
|
|
287
|
+
if (token.length > 1 && token[0] === '\x1b') {
|
|
288
|
+
if (token[1] === ']') link = token === LINK_CLOSE ? null : token;
|
|
289
|
+
else on = styledAfter(on, token);
|
|
290
|
+
pieces[pieces.length - 1] += token;
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
for (const { segment: ch } of GRAPHEMES.segment(token)) {
|
|
294
|
+
if (used > 0 && used + columnsOf(ch) > width) {
|
|
295
|
+
if (link) pieces[pieces.length - 1] += LINK_CLOSE;
|
|
296
|
+
pieces.push(`${on.join('')}${link ?? ''}`);
|
|
297
|
+
used = 0;
|
|
298
|
+
}
|
|
299
|
+
pieces[pieces.length - 1] += ch;
|
|
300
|
+
used += columnsOf(ch);
|
|
146
301
|
}
|
|
147
|
-
pieces[pieces.length - 1] += ch;
|
|
148
|
-
used += columnsOf(ch);
|
|
149
302
|
}
|
|
150
303
|
return pieces;
|
|
151
304
|
}
|
|
152
305
|
|
|
153
|
-
/** A text folded to `width`, as its rows
|
|
154
|
-
export function fold(text, width) {
|
|
155
|
-
return wrap(text, width)
|
|
306
|
+
/** A text folded to `width`, as its rows, the ones after the first at `indent`; a word wider than that is cut, so nothing drawn from them runs past the edge. */
|
|
307
|
+
export function fold(text, width, indent = '') {
|
|
308
|
+
return wrap(text, width, indent)
|
|
156
309
|
.split('\n')
|
|
157
310
|
.flatMap((line) => (visible(line) <= width ? [line] : cut(line, width)));
|
|
158
311
|
}
|
|
@@ -174,18 +327,40 @@ export function renderTable(rows, s, width) {
|
|
|
174
327
|
const columns = head.length;
|
|
175
328
|
const aligns = Array.from({ length: columns }, (_, i) => (/^:-+:$/.test(rule[i] ?? '') ? 'center' : /-:$/.test(rule[i] ?? '') ? 'right' : 'left'));
|
|
176
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();
|
|
177
334
|
const widths = Array.from({ length: columns }, (_, i) => Math.max(1, ...table.map((row) => visible(inline(row[i], s)))));
|
|
178
335
|
const room = width - (3 * columns + 1);
|
|
179
|
-
|
|
336
|
+
const sum = (list) => list.reduce((a, b) => a + b, 0);
|
|
337
|
+
if (sum(widths) > room) {
|
|
338
|
+
// Too wide: each column keeps its longest word whole if it can, and the room left over goes to the columns with the most
|
|
339
|
+
// to say, by how much more they have — so a column of short keys is not padded out to match a column of sentences.
|
|
340
|
+
const least = widths.map((most, i) => Math.min(most, Math.max(MIN_COLUMN, ...table.map((row) => Math.max(0, ...inline(row[i], NO_STYLE).split(/\s+/).map(visible))))));
|
|
341
|
+
const spare = room - sum(least);
|
|
342
|
+
// Three columns or more that cannot keep their words whole would fold into a ladder of word ends: each row is shown as
|
|
343
|
+
// a record instead — the column's name, then the cell — one under the other.
|
|
344
|
+
if (spare < 0 && columns >= 3 && body.length > 0) return records();
|
|
345
|
+
if (spare >= 0) {
|
|
346
|
+
const wants = widths.map((most, i) => most - least[i]);
|
|
347
|
+
const given = least.map((w, i) => w + Math.floor((spare * wants[i]) / Math.max(1, sum(wants))));
|
|
348
|
+
// What rounding left goes to the columns that want the most, one each.
|
|
349
|
+
for (let left = room - sum(given), i = 0; left > 0 && i < columns; i++, left--) given[wants.indexOf(Math.max(...wants.filter((_, k) => given[k] < widths[k])))]++;
|
|
350
|
+
widths.splice(0, columns, ...given.map((w, i) => Math.min(w, widths[i])));
|
|
351
|
+
} else widths.splice(0, columns, ...least);
|
|
352
|
+
while (sum(widths) > room && Math.max(...widths) > MIN_COLUMN) widths[widths.indexOf(Math.max(...widths))]--;
|
|
353
|
+
}
|
|
180
354
|
|
|
181
|
-
const
|
|
182
|
-
const
|
|
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);
|
|
183
358
|
const draw = (row, style) => {
|
|
184
359
|
const cells = row.map((cell, i) => (visible(inline(cell, s)) <= widths[i] ? [inline(cell, s)] : fold(inline(cell, NO_STYLE), widths[i])));
|
|
185
360
|
const height = Math.max(...cells.map((c) => c.length));
|
|
186
361
|
return Array.from({ length: height }, (_, n) => `${bar} ${cells.map((c, i) => style(pad(c[n] ?? '', widths[i], aligns[i]))).join(` ${bar} `)} ${bar}`);
|
|
187
362
|
};
|
|
188
|
-
return [edge(
|
|
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');
|
|
189
364
|
}
|
|
190
365
|
|
|
191
366
|
/**
|
|
@@ -199,21 +374,48 @@ export function renderTable(rows, s, width) {
|
|
|
199
374
|
*/
|
|
200
375
|
export const untab = (text) => text.replaceAll('\t', ' ');
|
|
201
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
|
+
|
|
202
397
|
export function createRenderer(write, s, { width = MAX_WIDTH } = {}) {
|
|
203
398
|
let tail = '';
|
|
204
399
|
let fence = false;
|
|
205
400
|
let rows = [];
|
|
206
401
|
/** The indent of the list item the lines are in, until a line comes out of it. */
|
|
207
402
|
let hang = null;
|
|
403
|
+
/** The language the code block in hand is in, and where its colouring has got to: a comment can run over lines. */
|
|
404
|
+
let lang = '';
|
|
405
|
+
let code = { comment: false };
|
|
208
406
|
const line = (raw) => {
|
|
209
407
|
const marks = /^\s*```\s*(\S*)/.exec(raw);
|
|
210
408
|
if (marks) {
|
|
211
409
|
fence = !fence;
|
|
212
410
|
hang = null;
|
|
213
|
-
|
|
411
|
+
lang = fence ? marks[1].toLowerCase() : '';
|
|
412
|
+
code = { comment: false };
|
|
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}`);
|
|
214
416
|
}
|
|
215
417
|
if (!fence) hang = hangOf(raw) ?? (/^\s+\S/.test(raw) || raw.trim() === '' ? hang : null);
|
|
216
|
-
return renderLine(raw, s, { fence, width, hang: hangOf(raw) === null ? hang : null });
|
|
418
|
+
return renderLine(raw, s, { fence, width, hang: hangOf(raw) === null ? hang : null, lang, code });
|
|
217
419
|
};
|
|
218
420
|
/** The rows held so far: a table once its rule has come, the lines they were otherwise. */
|
|
219
421
|
const held = () => (rows.length >= 2 && TABLE_RULE.test(rows[1]) ? renderTable(rows, s, width) : rows.map((r) => renderLine(r, s, { width })).join('\n'));
|
|
@@ -244,17 +446,28 @@ export function createRenderer(write, s, { width = MAX_WIDTH } = {}) {
|
|
|
244
446
|
rows = [];
|
|
245
447
|
fence = false;
|
|
246
448
|
hang = null;
|
|
449
|
+
lang = '';
|
|
450
|
+
code = { comment: false };
|
|
247
451
|
},
|
|
248
452
|
/** What has not been written yet, rendered as far as it has got: the rows of a table, and the line still arriving. */
|
|
249
453
|
get tail() {
|
|
250
454
|
const going = /^\s+\S/.test(tail) && hangOf(tail) === null ? hang : null;
|
|
251
|
-
return [rows.length > 0 ? held() : '', tail && !/^\s*```/.test(tail) ? renderLine(tail, s, { fence, width, hang: going }) : ''].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');
|
|
252
456
|
},
|
|
253
457
|
};
|
|
254
458
|
}
|
|
255
459
|
|
|
460
|
+
/** This sumo's version, from its package.json; empty where there is none to read, as beside a standalone binary. */
|
|
461
|
+
export const VERSION = (() => {
|
|
462
|
+
try {
|
|
463
|
+
return String(JSON.parse(readFileSync(join(REPO_ROOT, 'package.json'), 'utf8')).version ?? '');
|
|
464
|
+
} catch {
|
|
465
|
+
return '';
|
|
466
|
+
}
|
|
467
|
+
})();
|
|
468
|
+
|
|
256
469
|
/** The words shown while the model works: yours, one a line, in spinner.txt at the top of the repo. */
|
|
257
|
-
|
|
470
|
+
const SPINNER_FILE = join(REPO_ROOT, 'spinner.txt');
|
|
258
471
|
const SPINNER_FALLBACK = ['Working'];
|
|
259
472
|
|
|
260
473
|
/** The working messages: every line of the file that is not blank and not a `#` comment. */
|
|
@@ -276,26 +489,8 @@ const MESSAGE_MS = 5000;
|
|
|
276
489
|
/** The working message `elapsed` ms into work that opened on `first`: the next in the file every five seconds, round and round. */
|
|
277
490
|
export const messageAt = (messages, first, elapsed) => messages[(Math.max(0, messages.indexOf(first)) + Math.floor(elapsed / MESSAGE_MS)) % messages.length];
|
|
278
491
|
|
|
279
|
-
/** The chat's colours: gold, into orange, into crimson. */
|
|
280
|
-
const SUNSET = [[0xff, 0xd1, 0x66], [0xf7, 0x7f, 0x00], [0xd6, 0x28, 0x28]];
|
|
281
|
-
|
|
282
|
-
/** The colour `t` of the way through the sunset, 0 its gold and 1 its crimson. */
|
|
283
|
-
export function sunset(t) {
|
|
284
|
-
const at = Math.min(Math.max(t, 0), 1) * (SUNSET.length - 1);
|
|
285
|
-
const i = Math.min(Math.floor(at), SUNSET.length - 2);
|
|
286
|
-
return `#${SUNSET[i].map((v, k) => Math.round(v + (SUNSET[i + 1][k] - v) * (at - i)).toString(16).padStart(2, '0')).join('')}`;
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
const FLOW_LENGTH = 24;
|
|
290
|
-
|
|
291
|
-
/** 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. */
|
|
292
|
-
export function flow(i, frame) {
|
|
293
|
-
const step = (((i - frame) % FLOW_LENGTH) + FLOW_LENGTH) % FLOW_LENGTH;
|
|
294
|
-
return sunset(1 - Math.abs(1 - (2 * step) / FLOW_LENGTH));
|
|
295
|
-
}
|
|
296
|
-
|
|
297
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. */
|
|
298
|
-
|
|
493
|
+
const LOGO_FILE = join(REPO_ROOT, 'logo.txt');
|
|
299
494
|
|
|
300
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. */
|
|
301
496
|
export function logoLines(file = LOGO_FILE) {
|
|
@@ -314,39 +509,83 @@ export function logoLines(file = LOGO_FILE) {
|
|
|
314
509
|
const SHOWN_REPORT_LINES = 3;
|
|
315
510
|
const SHOWN_HEAD_LINES = 2;
|
|
316
511
|
const SHOWN_TAIL_LINES = 3;
|
|
317
|
-
|
|
512
|
+
/** The rows of the screen an edit's diff takes before the rest is folded away. */
|
|
513
|
+
const SHOWN_DIFF_ROWS = 12;
|
|
318
514
|
const SHOWN_COMMAND_LINES = 3;
|
|
319
515
|
const SHOWN_COMMAND_CHARS = 240;
|
|
516
|
+
const SHOWN_WRITE_LINES = 4;
|
|
320
517
|
|
|
321
518
|
const more = (n) => ({ text: `… +${n} line${n === 1 ? '' : 's'}`, tone: 'dim' });
|
|
322
519
|
|
|
323
|
-
/** The top of a list of lines, and how many more there were. */
|
|
520
|
+
/** The top of a list of lines, and how many more there were. One more line is shown, not folded: its fold would take its row. */
|
|
324
521
|
function top(lines, max) {
|
|
325
|
-
return lines.length > max ? [...lines.slice(0, max), more(lines.length - max)] : lines;
|
|
522
|
+
return lines.length > max + 1 ? [...lines.slice(0, max), more(lines.length - max)] : lines;
|
|
326
523
|
}
|
|
327
524
|
|
|
328
525
|
/** Both ends of what a command printed, and how many lines lie between: a run says how it went in its last lines. */
|
|
329
526
|
function ends(lines, full) {
|
|
330
|
-
if (full || lines.length <= SHOWN_HEAD_LINES + SHOWN_TAIL_LINES) return lines;
|
|
527
|
+
if (full || lines.length <= SHOWN_HEAD_LINES + SHOWN_TAIL_LINES + 1) return lines;
|
|
331
528
|
return [...lines.slice(0, SHOWN_HEAD_LINES), more(lines.length - SHOWN_HEAD_LINES - SHOWN_TAIL_LINES), ...lines.slice(-SHOWN_TAIL_LINES)];
|
|
332
529
|
}
|
|
333
530
|
|
|
334
531
|
/** A path as a person reads it: under the home directory, from `~`. */
|
|
335
532
|
export const tilde = (path, home = homedir()) => (path === home ? '~' : String(path).startsWith(`${home}${sep}`) ? `~${String(path).slice(home.length)}` : String(path));
|
|
336
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
|
+
|
|
337
540
|
/** A path as the work reads it: a file in the project from the project, anything else from the home directory. */
|
|
338
|
-
export const pathFrom = (path, cwd) =>
|
|
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
|
+
};
|
|
339
554
|
|
|
340
555
|
/** How a delegated job ended, for the line that sums it up: its mark, the word for it, and its colour. */
|
|
341
|
-
const JOB_ENDS = { done: ['✓', 'done', 'add'], failed: ['✗', 'failed', 'error'], needs_input: ['?', 'needs your answer', 'ask'], open: ['○', 'never closed', 'dim'] };
|
|
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'] };
|
|
342
557
|
|
|
343
|
-
|
|
558
|
+
/**
|
|
559
|
+
* What a command printed in colour reaches the model with its escapes shown as markers (⟨U+001B⟩[31m); on the screen
|
|
560
|
+
* they are noise in the words, and go. Any other hidden character keeps its marker.
|
|
561
|
+
*/
|
|
562
|
+
export const withoutColourCodes = (text) => String(text).replace(/⟨U\+001B⟩\[[0-?]*[ -/]*[@-~]|⟨U\+001B⟩\][^\n]*?(?:⟨U\+0007⟩|⟨U\+001B⟩\\)/g, '');
|
|
563
|
+
|
|
564
|
+
const toned = (text, tone) => withoutColourCodes(text).split('\n').map((t) => ({ text: t, tone }));
|
|
344
565
|
const count = (text) => [{ text: `${text === '' ? 0 : text.replace(/\n$/, '').split('\n').length} lines`, tone: 'dim' }];
|
|
345
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
|
+
|
|
346
583
|
/**
|
|
347
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
|
|
348
585
|
* what came — each numbered as the file numbers it when `line` says where the old text began, with one line of what
|
|
349
|
-
* stayed on either side.
|
|
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.
|
|
350
589
|
*/
|
|
351
590
|
function diffView(old, now, line, full) {
|
|
352
591
|
const was = old === '' ? [] : old.replace(/\r\n/g, '\n').split('\n');
|
|
@@ -358,20 +597,55 @@ function diffView(old, now, line, full) {
|
|
|
358
597
|
const went = was.slice(head, was.length - tail);
|
|
359
598
|
const came = is.slice(head, is.length - tail);
|
|
360
599
|
const wide = line === null ? 0 : String(line + Math.max(was.length, is.length)).length;
|
|
361
|
-
const row = (n, sign, text, tone
|
|
362
|
-
|
|
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
|
+
}
|
|
363
611
|
return {
|
|
364
612
|
at: line === null ? null : line + head,
|
|
365
613
|
stat: { added: came.length, removed: went.length },
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
...fold(went.map((text, i) => row(head + i, '-', text, 'del'))),
|
|
369
|
-
...fold(came.map((text, i) => row(head + i, '+', text, 'add'))),
|
|
370
|
-
...(tail > 0 ? [row(is.length - tail, ' ', is[is.length - tail], 'dim')] : []),
|
|
371
|
-
],
|
|
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')] : [])],
|
|
372
616
|
};
|
|
373
617
|
}
|
|
374
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
|
+
|
|
622
|
+
/**
|
|
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
|
|
624
|
+
* there. A heading is dropped — or, with `headings: 'keep'`, kept as its words; either way a line of three words or fewer
|
|
625
|
+
* under one ("None.", "Matches.") says nothing without it, and takes it in front.
|
|
626
|
+
*/
|
|
627
|
+
function readable(text, cwd = null, { headings = 'drop' } = {}) {
|
|
628
|
+
const lines = [];
|
|
629
|
+
let heading = null;
|
|
630
|
+
for (const raw of String(text ?? '').split('\n')) {
|
|
631
|
+
if (!raw.trim() || TABLE_RULE.test(raw)) continue;
|
|
632
|
+
const head = /^#{1,6}\s+(.*)$/.exec(raw);
|
|
633
|
+
if (head) {
|
|
634
|
+
heading = inline(head[1], NO_STYLE).replace(/:\s*$/, '');
|
|
635
|
+
if (headings === 'keep') lines.push(heading);
|
|
636
|
+
continue;
|
|
637
|
+
}
|
|
638
|
+
const line = inline(TABLE_ROW.test(raw) ? cellsOf(raw).filter(Boolean).join(' · ') : raw.replace(/^(\s*)[-*+]\s+/, '$1• '), NO_STYLE);
|
|
639
|
+
const named = cwd ? line.replaceAll(`${cwd}${sep}`, '') : line;
|
|
640
|
+
if (heading && named.trim().split(/\s+/).length <= 3) {
|
|
641
|
+
if (headings === 'keep') lines.pop();
|
|
642
|
+
lines.push(`${heading}: ${named.trim()}`);
|
|
643
|
+
} else lines.push(named);
|
|
644
|
+
heading = null;
|
|
645
|
+
}
|
|
646
|
+
return lines;
|
|
647
|
+
}
|
|
648
|
+
|
|
375
649
|
/**
|
|
376
650
|
* A tool call for the screen: what ran, and under it the part of the result
|
|
377
651
|
* worth a glance — both ends of a command's output, an edit as a diff, a read
|
|
@@ -379,12 +653,21 @@ function diffView(old, now, line, full) {
|
|
|
379
653
|
* every line, the command whole, and the file itself for a read or a write.
|
|
380
654
|
* `cwd` is the project the work is in: a file in it is named from there.
|
|
381
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
|
+
|
|
382
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 };
|
|
383
662
|
const input = call.input ?? {};
|
|
384
663
|
// Folded, the empty lines of what came back are not shown: three of five lines spent on nothing say nothing.
|
|
385
664
|
const output = (content = result.content) => {
|
|
386
665
|
const lines = toned(content, result.isError ? 'error' : 'plain');
|
|
666
|
+
// What reads as a diff — `git diff`, a patch — is drawn as one: what went red, what came green.
|
|
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;
|
|
387
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)} …`;
|
|
388
671
|
const said = lines.filter((line) => line.text.trim() !== '');
|
|
389
672
|
return said.length === 0 ? [{ text: '(no output)', tone: 'dim' }] : ends(said, false);
|
|
390
673
|
};
|
|
@@ -396,93 +679,186 @@ export function toolView(call, result = null, { full = false, cwd = null } = {})
|
|
|
396
679
|
const command = (there && whole.replace(there, '')) || whole;
|
|
397
680
|
const start = command.split('\n').slice(0, SHOWN_COMMAND_LINES).join('\n').slice(0, SHOWN_COMMAND_CHARS);
|
|
398
681
|
const detail = full || start.length === command.length ? command : `${start} …`;
|
|
399
|
-
if (!result) return { title: '
|
|
400
|
-
if (result.content === '') return { title: '
|
|
401
|
-
return { title: '
|
|
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() };
|
|
402
685
|
}
|
|
403
686
|
if (call.name === DELEGATE_TOOL.name) {
|
|
404
|
-
|
|
405
|
-
|
|
687
|
+
// A report a job in the background sent back is titled as one, by who sent it; a call is the delegation itself.
|
|
688
|
+
const title = input.report ? 'report' : 'job';
|
|
689
|
+
const detail = input.job !== undefined ? `j${input.job}${input.report && input.agent ? ` ${input.agent} · ${input.title ?? ''}` : ''}` : `${input.agent ?? 'worker'} · ${input.title ?? ''}`;
|
|
690
|
+
if (!result) return { title, detail, lines: [] };
|
|
406
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.
|
|
407
|
-
if (!full && !result.isError && /^j\d+ is running in the background/.test(result.content)) return { title
|
|
408
|
-
if (
|
|
692
|
+
if (!full && !result.isError && /^j\d+ is running in the background/.test(result.content)) return { title, detail, lines: [{ text: 'running in the background — its report comes here when it is done', tone: 'dim' }] };
|
|
693
|
+
if (full) return { title, detail, lines: output() };
|
|
694
|
+
// Several attempts report together, in markdown: shown as it reads, like a single job's report.
|
|
695
|
+
if (!result.job) return { title, detail, lines: output(result.isError ? result.content : readable(result.content, cwd, { headings: 'keep' }).join('\n')) };
|
|
409
696
|
// A job that ran: how it went in one line, then the top of what it reported.
|
|
410
697
|
const { job } = result;
|
|
411
|
-
|
|
698
|
+
// Stopped by the user before it closed itself, it was stopped — not left open.
|
|
699
|
+
const [mark, said, tone] = input.stopped && !['done', 'failed', 'needs_input'].includes(job.status) ? JOB_ENDS.stopped : (JOB_ENDS[job.status] ?? JOB_ENDS.open);
|
|
412
700
|
const route = job.effort && job.effort !== 'none' ? `${job.model}/${job.effort}` : job.model;
|
|
413
701
|
// How long it took comes first: it is what the wait was.
|
|
414
702
|
const summary = `${mark} j${job.id} ${said}${job.seconds === undefined ? '' : ` · ${elapsed(job.seconds * 1000)}`} · ${job.turns} turn${job.turns === 1 ? '' : 's'} · ${job.toolCalls} tool call${job.toolCalls === 1 ? '' : 's'} · $${job.costUsd.toFixed(2)} · ${route}`;
|
|
415
|
-
// The top of the report is its first words, not the heading over them
|
|
416
|
-
|
|
417
|
-
|
|
703
|
+
// The top of the report is its first words, as they read: not the heading over them, not a table's rule, not its marks;
|
|
704
|
+
// a table's row is its cells, and a file in the project is named from there.
|
|
705
|
+
const report = readable(job.report, cwd);
|
|
706
|
+
return { title, detail, lines: [{ text: summary, tone }, ...top(report.map((text) => ({ text, tone: 'plain' })), SHOWN_REPORT_LINES)] };
|
|
418
707
|
}
|
|
419
708
|
if (isMcpTool(call.name)) {
|
|
420
|
-
// A server's tool: the server
|
|
709
|
+
// A server's tool: the server and the tool with its input as the detail, what came back under it.
|
|
421
710
|
const { server, tool } = splitMcpName(call.name);
|
|
422
|
-
const detail = `${tool}(${compactInput(input)})`;
|
|
423
|
-
if (!result) return { title:
|
|
424
|
-
// The line that tells the model whose data this is: here the
|
|
425
|
-
return { title:
|
|
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)) };
|
|
426
715
|
}
|
|
427
716
|
if (isWebTool(call)) {
|
|
428
717
|
// The web: what was searched for or which page was read, and under it the pages found or the page and its size.
|
|
429
718
|
const detail = String(input.query ?? input.url ?? '').slice(0, SHOWN_COMMAND_CHARS);
|
|
430
|
-
return { title: call.name === WEB_SEARCH_TOOL.name ? '
|
|
719
|
+
return { title: call.name === WEB_SEARCH_TOOL.name ? 'search' : 'fetch', detail, lines: result ? output() : [] };
|
|
431
720
|
}
|
|
432
721
|
if (isAdvisorTool(call)) {
|
|
433
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.
|
|
434
|
-
return { title: '
|
|
723
|
+
return { title: 'advise', detail: String(input.asked ?? ''), lines: result ? output() : [] };
|
|
724
|
+
}
|
|
725
|
+
if (call.name === ASK_TOOL.name) {
|
|
726
|
+
// A question put to the user: the question, and under it what they answered.
|
|
727
|
+
const question = String(input.question ?? '').split('\n')[0];
|
|
728
|
+
return { title: 'asked', detail: question, lines: result ? output() : [] };
|
|
435
729
|
}
|
|
436
730
|
if (call.name !== EDITOR_TOOL.name) {
|
|
437
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.
|
|
438
733
|
const given = String(input.status ?? input.query ?? input.question ?? input.text ?? '').split('\n')[0].slice(0, 80);
|
|
439
|
-
|
|
440
|
-
return { title
|
|
734
|
+
const title = String(call.name).split(/[_-]/)[0];
|
|
735
|
+
if (!result) return { title, detail: given, lines: [] };
|
|
736
|
+
return { title, detail: given, lines: output() };
|
|
441
737
|
}
|
|
442
738
|
const range = Array.isArray(input.view_range) ? `:${input.view_range.join('-')}` : '';
|
|
443
|
-
const title = input.command === 'view' ? '
|
|
739
|
+
const title = input.command === 'view' ? 'read' : input.command === 'create' ? 'write' : input.command === 'str_replace' || input.command === 'insert' ? 'edit' : 'editor';
|
|
444
740
|
const detail = `${pathFrom(input.path ?? '', cwd)}${range}`;
|
|
445
741
|
if (!result) return { title, detail, lines: [] };
|
|
446
|
-
|
|
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)) };
|
|
447
744
|
const added = (text) => toned(text, 'add').map((l) => ({ ...l, text: `+ ${l.text}` }));
|
|
448
745
|
if (input.command === 'view') return { title, detail, lines: full ? toned(result.content, 'plain') : count(result.content) };
|
|
449
|
-
|
|
746
|
+
// A new file is shown by its top, as what came: what was written is what is checked first.
|
|
747
|
+
if (input.command === 'create') {
|
|
748
|
+
const text = String(input.file_text ?? '').replace(/\n$/, '');
|
|
749
|
+
if (!text) return { title, detail, lines: [{ text: '(empty)', tone: 'dim' }] };
|
|
750
|
+
return { title, detail, lines: full ? added(text) : top(added(text), SHOWN_WRITE_LINES) };
|
|
751
|
+
}
|
|
450
752
|
// The editor says where the old text began and what the file had there; a result that does not is drawn from what the model sent.
|
|
451
753
|
const came = input.command === 'insert' ? (input.insert_text ?? input.new_str ?? '').replace(/\n$/, '') : (input.new_str ?? '');
|
|
452
754
|
const edit = result.edit ?? { line: null, old: input.command === 'str_replace' ? (input.old_str ?? '') : '', new: came };
|
|
453
755
|
const diff = diffView(edit.old, edit.new, edit.line ?? null, full);
|
|
454
|
-
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 };
|
|
455
757
|
}
|
|
456
758
|
|
|
759
|
+
/** The failures a request meets most, in the words a person acts on: what happened, and what to do about it. */
|
|
760
|
+
const FAILURES = [
|
|
761
|
+
[/overloaded|\b529\b/i, "Anthropic's API is overloaded just now — nothing was lost; send it again in a minute"],
|
|
762
|
+
[/rate.?limit|\b429\b/i, 'rate limited by the API — wait a minute and send it again, or /model to another model'],
|
|
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'],
|
|
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'],
|
|
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'],
|
|
771
|
+
[/\b5\d\d\b|internal server error|api_error/i, 'the API failed on its side — send it again'],
|
|
772
|
+
];
|
|
773
|
+
|
|
774
|
+
/** A failure for the screen: in words when it is one of the known ones, with what came back kept faint under it; as it came otherwise. */
|
|
775
|
+
export function explained(message) {
|
|
776
|
+
const said = String(message ?? '').replace(/\s+/g, ' ').trim();
|
|
777
|
+
const known = FAILURES.find(([pattern]) => pattern.test(said));
|
|
778
|
+
return known ? { text: `error: ${known[1]}`, detail: said.length > 200 ? `${said.slice(0, 199)}…` : said } : { text: `error: ${said}` };
|
|
779
|
+
}
|
|
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
|
+
|
|
457
787
|
/**
|
|
458
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,
|
|
459
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.
|
|
460
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
|
+
|
|
461
794
|
export function transcript(log, s, { width = MAX_WIDTH, cwd = null } = {}) {
|
|
462
795
|
const tones = { plain: (t) => t, dim: s.dim, error: s.red, add: s.green, del: s.red, ask: s.yellow };
|
|
463
|
-
const
|
|
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}`));
|
|
464
808
|
const out = [];
|
|
465
809
|
for (const entry of log) {
|
|
466
|
-
if (entry.kind === 'user') out.push('',
|
|
810
|
+
if (entry.kind === 'user') out.push('', `${at('you', (t) => s.bold(s.cyan(t)))}${words(untab(entry.text))}`);
|
|
467
811
|
else if (entry.kind === 'reply') {
|
|
468
812
|
const drawn = [];
|
|
469
|
-
const reply = createRenderer((
|
|
813
|
+
const reply = createRenderer((t) => drawn.push(t), s, { width: Math.max(MIN_WIDTH, width - TEXT_AT) });
|
|
470
814
|
reply.write(entry.raw);
|
|
471
815
|
reply.flush();
|
|
472
|
-
out.push('', ...drawn.join('').replace(/\n$/, '').split('\n').map((line, i) =>
|
|
816
|
+
out.push('', ...drawn.join('').replace(/\n$/, '').split('\n').map((line, i) => (i === 0 ? `${at('sumo', s.bold)}${line}` : line ? `${' '.repeat(TEXT_AT)}${line}` : '')));
|
|
473
817
|
} else if (entry.kind === 'tool') {
|
|
474
818
|
const view = toolView(entry.call, entry.result, { full: true, cwd });
|
|
475
819
|
const stat = view.stat ? ` ${s.green(`+${view.stat.added}`)} ${s.red(`−${view.stat.removed}`)}` : '';
|
|
476
|
-
|
|
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));
|
|
477
823
|
} else if (entry.kind === 'shell') out.push(...under(toolView({ name: BASH_TOOL.name }, entry.result, { full: true }).lines));
|
|
478
|
-
else if (entry.kind === 'job') out.push('',
|
|
479
|
-
else if (entry.kind === 'error') out.push('', s.red(entry.text));
|
|
480
|
-
else if (entry.kind === '
|
|
481
|
-
else if (entry.kind === '
|
|
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)}`);
|
|
482
830
|
}
|
|
483
831
|
return `${out.join('\n').replace(/^\n/, '')}\n`;
|
|
484
832
|
}
|
|
485
833
|
|
|
834
|
+
/** A fence for text that may hold fences of its own: longer than any run of backticks in it. */
|
|
835
|
+
const fenceFor = (text) => '`'.repeat(Math.max(3, ...[...String(text).matchAll(/`+/g)].map((m) => m[0].length + 1)));
|
|
836
|
+
|
|
837
|
+
/**
|
|
838
|
+
* The conversation as Markdown, for `/export`: what was said quoted, each reply as the model wrote it, each call folded
|
|
839
|
+
* away under its name with all it gave back, the thinking under how long it took. Nothing is coloured; it is a file to keep.
|
|
840
|
+
*/
|
|
841
|
+
export function markdownOf(log, { cwd = null, title = 'Sumo' } = {}) {
|
|
842
|
+
const out = [`# ${title}`];
|
|
843
|
+
const folded = (summary, body) => {
|
|
844
|
+
const fence = fenceFor(body);
|
|
845
|
+
out.push('', `<details><summary>${summary.replace(/</g, '<')}</summary>`, '', fence, body, fence, '', '</details>');
|
|
846
|
+
};
|
|
847
|
+
for (const entry of log) {
|
|
848
|
+
if (entry.kind === 'user') out.push('', '**You**', '', ...entry.text.split('\n').map((line) => `> ${line}`));
|
|
849
|
+
else if (entry.kind === 'reply') out.push('', entry.raw.trim());
|
|
850
|
+
else if (entry.kind === 'tool') {
|
|
851
|
+
const view = toolView(entry.call, entry.result, { full: true, cwd });
|
|
852
|
+
folded(`${view.title} ${view.detail.split('\n')[0]}${entry.result.isError ? ' — failed' : ''}`, view.lines.map((line) => line.text).join('\n'));
|
|
853
|
+
} else if (entry.kind === 'shell') folded('! command', String(entry.result.content));
|
|
854
|
+
else if (entry.kind === 'thought') folded(`Thought for ${elapsed(entry.ms)}`, String(entry.text ?? '').trim());
|
|
855
|
+
else if (entry.kind === 'job') out.push('', `**j${entry.id}** ${entry.agent} · ${entry.route} — ${entry.title}`);
|
|
856
|
+
else if (entry.kind === 'error') out.push('', `**${entry.text}**${entry.detail ? ` — ${entry.detail}` : ''}`);
|
|
857
|
+
else if (entry.kind === 'note' || entry.kind === 'footer') out.push('', ...entry.text.split('\n').map((line) => `_${line}_`));
|
|
858
|
+
}
|
|
859
|
+
return `${out.join('\n')}\n`;
|
|
860
|
+
}
|
|
861
|
+
|
|
486
862
|
const kindOf = (raw) => (/^Ask the user/.test(raw) ? 'ask' : /^Warning/.test(raw) ? 'warning' : /^Left off/.test(raw) ? 'left' : /^- m\d+ /.test(raw) ? 'item' : raw);
|
|
487
863
|
|
|
488
864
|
/**
|
|
@@ -512,13 +888,13 @@ export function renderBlock(block, s, { width = MAX_WIDTH } = {}) {
|
|
|
512
888
|
|
|
513
889
|
/** The line above the memory block: which model is answering, how hard it thinks, where the work is. */
|
|
514
890
|
export function header({ route, cwd }, s) {
|
|
515
|
-
return `${s.bold(s.
|
|
891
|
+
return `${s.bold(s.cyan('sumo'.padStart(GUTTER)))} ${route}${s.dim(`${VERSION ? ` · ${VERSION}` : ''} · ${cwd}`)}`;
|
|
516
892
|
}
|
|
517
893
|
|
|
518
894
|
/** The prompt: the model and effort kept in view, the size of the context once it matters. */
|
|
519
895
|
export function prompt({ route, contextTokens }, s) {
|
|
520
896
|
const k = contextTokens >= 1000 ? ` ${Math.round(contextTokens / 1000)}k` : '';
|
|
521
|
-
return `${s.bold(s.
|
|
897
|
+
return `${s.bold(s.cyan('sumo'))}${s.dim(` ${route}${k}`)}${s.bold('>')} `;
|
|
522
898
|
}
|
|
523
899
|
|
|
524
900
|
/**
|