sumo-agents 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/setup.mjs CHANGED
@@ -27,10 +27,12 @@ export const CONFIG_DEFAULTS = {
27
27
  'chat.model': 'opus',
28
28
  'chat.effort': 'medium',
29
29
  'chat.notify': 'on',
30
+ 'chat.motion': 'on',
30
31
  'chat.budget': '5',
31
32
  'guides.auto': 'on',
32
33
  'jobs.advisor': 'off',
33
34
  'jobs.budget': '10',
35
+ 'jobs.floor': 'haiku',
34
36
  'jobs.escalate': 'on',
35
37
  'jobs.review': 'risky',
36
38
  'shell.sandbox': 'on',
@@ -480,11 +482,13 @@ export function config(key, value) {
480
482
  // Sent with every chat turn: a word the API does not take would fail each one, not this command.
481
483
  if (key === 'chat.effort' && !CHAT_EFFORTS.includes(value)) throw new UsageError(`no such effort "${value}" — one of: ${CHAT_EFFORTS.join(', ')}`);
482
484
  if (key === 'chat.notify' && value !== 'on' && value !== 'off') throw new UsageError('chat.notify is on or off: the bell and the notification when a long turn ends behind another window');
485
+ if (key === 'chat.motion' && value !== 'on' && value !== 'off') throw new UsageError('chat.motion is on or off: the colours flowing through the working line — off, it stands still');
483
486
  // A word would be no budget at all, and the line it holds back would never be said.
484
487
  if (key === 'chat.budget' && !/^\d+(\.\d+)?$/.test(value)) throw new UsageError('chat.budget is a sum in US dollars, like 5 or 2.50 (0 for never): what a chat session costs before the screen says so, once');
485
488
  if (key === 'guides.auto' && value !== 'on' && value !== 'off') throw new UsageError('guides.auto is on or off: a guide riding in with the message that asks for its kind of work, and a turn held for an edit nothing checked');
486
489
  if (key === 'jobs.advisor' && value !== 'on' && value !== 'off') throw new UsageError('jobs.advisor is on or off: a job asking the next model up for advice, from inside its own request');
487
490
  if (key === 'jobs.escalate' && value !== 'on' && value !== 'off') throw new UsageError('jobs.escalate is on or off: a worker\'s first attempt that fails retried once, one step up, without being asked');
491
+ if (key === 'jobs.floor' && !['haiku', 'sonnet', 'opus', 'fable'].includes(value)) throw new UsageError('jobs.floor is haiku, sonnet, opus or fable: the smallest model a job may run on — haiku holds nothing back');
488
492
  if (key === 'jobs.review' && !['risky', 'all', 'off'].includes(value)) {
489
493
  throw new UsageError('jobs.review is risky, all or off: which workers that finish DONE, verified, are reviewed without being asked — the ones the router called risky, every one, or none');
490
494
  }
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
  /**
@@ -16,14 +16,22 @@ import { isWebTool, WEB_SEARCH_TOOL } from './web.mjs';
16
16
  * terminal or NO_COLOR is set, so a pipe gets plain text.
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'], strike: ['9', '29'], cyan: ['36', '39'], yellow: ['33', '39'], red: ['31', '39'], green: ['32', '39'], magenta: ['35', '39'], blue: ['34', '39'] };
20
20
  const MAX_WIDTH = 100;
21
21
  const MIN_WIDTH = 40;
22
22
 
23
- /** The style functions, each a no-op when colour is off. */
24
- export function styles(enabled) {
23
+ /** 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. */
24
+ const LINK_OPEN = (url) => `\x1b]8;;${url}\x07`;
25
+ const LINK_CLOSE = '\x1b]8;;\x07';
26
+
27
+ /**
28
+ * The style functions, each a no-op when colour is off. `links` makes `link` an address the terminal opens on a click; a
29
+ * terminal that does not know them draws the text alone, but a pager does not, so the screen asks for them and nothing else.
30
+ */
31
+ export function styles(enabled, { links = false } = {}) {
25
32
  const s = {};
26
33
  for (const [name, [on, off]] of Object.entries(CODES)) s[name] = enabled ? (t) => `\x1b[${on}m${t}\x1b[${off}m` : (t) => t;
34
+ s.link = enabled && links ? (url, text = url) => `${LINK_OPEN(url)}${text}${LINK_CLOSE}` : (_url, text = _url) => text;
27
35
  return s;
28
36
  }
29
37
 
@@ -39,30 +47,46 @@ const columnsOf = (ch) => (WIDE.test(ch) ? 2 : 1);
39
47
 
40
48
  /** The columns text takes on a terminal, colour codes not counted: a wide character is two, so a table around it lines up. */
41
49
  const visible = (t) => {
42
- const plain = t.replace(/\x1b\[[0-9;]*m/g, '');
50
+ const plain = t.replace(/\x1b\[[0-9;]*m|\x1b\]8;[^\x07]*\x07/g, '');
43
51
  if (!/[^\x00-\x7e]/.test(plain)) return plain.length;
44
52
  let width = 0;
45
53
  for (const { segment } of GRAPHEMES.segment(plain)) width += columnsOf(segment);
46
54
  return width;
47
55
  };
48
56
 
49
- /** Word-wraps styled text to `width`, measuring only what is visible; continuation lines carry `indent`. */
57
+ /**
58
+ * Word-wraps styled text to `width`, measuring only what is visible; continuation lines carry `indent`. A word wider than
59
+ * 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.
60
+ */
50
61
  export function wrap(text, width, indent = '') {
51
62
  if (visible(text) <= width) return text;
52
63
  const lead = /^\s*/.exec(text)[0];
64
+ // An indent that leaves no room is dropped: a word goes on at the edge rather than not at all.
65
+ const hang = visible(indent) < width - 1 ? indent : '';
53
66
  const lines = [];
54
67
  let line = lead;
55
68
  for (const word of text.slice(lead.length).split(' ')) {
56
69
  const next = line === lead ? `${lead}${word}` : `${line} ${word}`;
57
70
  if (line !== lead && visible(next) > width) {
58
71
  lines.push(line);
59
- line = `${indent}${word}`;
72
+ line = `${hang}${word}`;
60
73
  } else line = next;
74
+ while (visible(line) > width) {
75
+ const [head, ...rest] = cut(line, width);
76
+ lines.push(head);
77
+ line = `${hang}${rest.join('')}`;
78
+ }
61
79
  }
62
80
  lines.push(line);
63
81
  return lines.join('\n');
64
82
  }
65
83
 
84
+ /** An address in text: up to the space after it, without the stop or bracket a sentence puts after it. */
85
+ const ADDRESS = /\bhttps?:\/\/[^\s<>()[\]`]*[^\s<>()[\]`.,;:!?'"]/g;
86
+
87
+ /** Text with each address in it made a link, for lines that are not markdown: what a tool gave back, a note. */
88
+ export const linked = (text, s) => String(text).replace(ADDRESS, (url) => s.link(url));
89
+
66
90
  /** A character after a backslash is meant as itself, not as a mark. */
67
91
  const ESCAPED = /\\([\\`*_~[\]()<>#|!])/g;
68
92
  /** 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 +102,10 @@ export function inline(line, s) {
78
102
  const out = line
79
103
  .replace(/(?<!\\)`([^`]+)`/g, (_, code) => keep(s.cyan(code)))
80
104
  .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})`))}`))
105
+ .replace(/<(https?:\/\/[^>\s]+)>/g, (_, url) => keep(s.link(url)))
106
+ .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, text, url) => (text === url ? keep(s.link(url)) : `${text} ${keep(s.dim(`(${s.link(url)})`))}`))
107
+ // An address in the words is one link, kept from the marks: its underscores are not italics.
108
+ .replace(ADDRESS, (url) => keep(s.link(url)))
83
109
  .replace(/\*\*\*(?!\s)([^*]+?)(?<!\s)\*\*\*/g, (_, t) => s.bold(s.italic(t)))
84
110
  .replace(/\*\*(?!\s)([^*]+?)(?<!\s)\*\*/g, (_, t) => s.bold(t))
85
111
  .replace(/(?<![\w_])__(?!\s)([^_]+?)(?<!\s)__(?![\w_])/g, (_, t) => s.bold(t))
@@ -104,13 +130,77 @@ export function hangOf(line) {
104
130
  return `${item[1]}${' '.repeat(/\d/.test(item[2]) ? item[2].length + 3 : 4)}`;
105
131
  }
106
132
 
133
+ const words = (list) => new Set(list.split(' '));
134
+ const C_LIKE = 'break case continue default do else for goto if return switch while true false null';
135
+ /**
136
+ * The languages a code block is coloured in: how a comment starts, which quotes make a string, and the words the language
137
+ * keeps for itself. Anything else — output, a log, plain text — is left as it came: colour guessed onto it would mislead.
138
+ */
139
+ const LANGUAGES = (() => {
140
+ 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`) };
141
+ 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') };
142
+ 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') };
143
+ 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`) };
144
+ 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`) };
145
+ 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`) };
146
+ 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') };
147
+ 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 };
148
+ const conf = { line: '#', quotes: '"\'', words: words('true false null yes no on off') };
149
+ 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 };
150
+ return named;
151
+ })();
152
+
153
+ /**
154
+ * A line of code in its language's colours: comments faint, strings green, numbers yellow, the language's own words
155
+ * magenta. `code` carries a block comment over from the line before; a diff is its changes, green and red.
156
+ */
157
+ export function highlight(line, lang, s, code = null) {
158
+ if (lang === 'diff' || lang === 'patch') return /^\+(?!\+\+ )/.test(line) ? s.green(line) : /^-(?!-- )/.test(line) ? s.red(line) : /^@@/.test(line) ? s.cyan(line) : line;
159
+ const language = LANGUAGES[lang];
160
+ if (!language || !line) return line;
161
+ const state = code ?? { comment: false };
162
+ let out = '';
163
+ let at = 0;
164
+ if (state.comment) {
165
+ const end = line.indexOf('*/');
166
+ if (end === -1) return s.dim(line);
167
+ out = s.dim(line.slice(0, end + 2));
168
+ at = end + 2;
169
+ state.comment = false;
170
+ }
171
+ const quotes = [...language.quotes].map((q) => `${q === '`' ? '`' : `\\${q}`}(?:[^${q === '`' ? '`' : `\\${q}`}\\\\]|\\\\.)*${q === '`' ? '`' : `\\${q}`}`).join('|');
172
+ const comment = language.line === '#' ? '(?:^|(?<=\\s))#.*' : language.line ? `${language.line.replace(/\//g, '\\/')}.*` : '(?!)';
173
+ 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');
174
+ pattern.lastIndex = at;
175
+ for (let m; (m = pattern.exec(line)); ) {
176
+ out += line.slice(at, m.index);
177
+ at = m.index + m[0].length;
178
+ if (m[1] !== undefined) out += s.dim(m[0]);
179
+ else if (m[2] !== undefined) {
180
+ const end = line.indexOf('*/', at);
181
+ if (end === -1) {
182
+ out += s.dim(line.slice(m.index));
183
+ state.comment = true;
184
+ return out;
185
+ }
186
+ out += s.dim(line.slice(m.index, end + 2));
187
+ at = end + 2;
188
+ pattern.lastIndex = at;
189
+ } else if (m[3] !== undefined) out += s.green(m[0]);
190
+ else if (m[4] !== undefined) out += s.yellow(m[0]);
191
+ else out += language.words.has(language.caseless ? m[0].toLowerCase() : m[0]) ? s.magenta(m[0]) : m[0];
192
+ }
193
+ return out + line.slice(at);
194
+ }
195
+
107
196
  /**
108
197
  * One line of a reply: block-level marks replaced by weight and indent, then wrapped with a hanging indent.
109
198
  * `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
199
  */
111
- export function renderLine(line, s, { fence = false, width = MAX_WIDTH, hang = null } = {}) {
200
+ export function renderLine(line, s, { fence = false, width = MAX_WIDTH, hang = null, lang = '', code = null } = {}) {
112
201
  // Code is what is read most closely: the frame around it is faint, the code is not.
113
- if (fence) return ` ${line}`;
202
+ // A line too long for the window goes on under itself, at its own indent, so the code keeps its shape.
203
+ if (fence) return wrap(` ${highlight(line, lang, s, code)}`, width, ` ${/^\s*/.exec(line)[0]}`);
114
204
  const heading = /^(#{1,6})\s+(.*)$/.exec(line);
115
205
  if (heading) return wrap(heading[1].length === 1 ? s.bold(s.underline(inline(heading[2], s))) : s.bold(inline(heading[2], s)), width);
116
206
  const item = LIST_ITEM.exec(line);
@@ -135,24 +225,49 @@ const cellsOf = (row) => row.trim().slice(1, -1).split(/(?<!\\)\|/).map((c) => c
135
225
 
136
226
  const GRAPHEMES = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
137
227
 
138
- /** A line cut into pieces no wider than `width`, between characters: an emoji, even one joined from several, stays whole. */
228
+ /** What each closing code ends: the opening codes it closes. */
229
+ 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;.*)$/ };
230
+ /** The styles open after `code`, given the ones open before it. */
231
+ function styledAfter(on, code) {
232
+ const n = code.slice(2, -1) || '0';
233
+ const closes = CLOSES[n];
234
+ return closes ? on.filter((open) => !closes.test(open.slice(2, -1))) : [...on, code];
235
+ }
236
+
237
+ /**
238
+ * A line cut into pieces no wider than `width`, between characters: an emoji, even one joined from several, stays whole,
239
+ * and a colour code takes no room — it stays with the character after it.
240
+ */
139
241
  function cut(line, width) {
140
242
  const pieces = [''];
141
243
  let used = 0;
142
- for (const { segment: ch } of GRAPHEMES.segment(line)) {
143
- if (pieces.at(-1) && used + columnsOf(ch) > width) {
144
- pieces.push('');
145
- used = 0;
244
+ // 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.
245
+ // So is a style: the next piece starts in the colour the last one ended in, since each row is drawn on its own.
246
+ let link = null;
247
+ let on = [];
248
+ for (const [token] of line.matchAll(/\x1b\[[0-9;]*m|\x1b\]8;[^\x07]*\x07|[^\x1b]+|\x1b/g)) {
249
+ if (token.length > 1 && token[0] === '\x1b') {
250
+ if (token[1] === ']') link = token === LINK_CLOSE ? null : token;
251
+ else on = styledAfter(on, token);
252
+ pieces[pieces.length - 1] += token;
253
+ continue;
254
+ }
255
+ for (const { segment: ch } of GRAPHEMES.segment(token)) {
256
+ if (used > 0 && used + columnsOf(ch) > width) {
257
+ if (link) pieces[pieces.length - 1] += LINK_CLOSE;
258
+ pieces.push(`${on.join('')}${link ?? ''}`);
259
+ used = 0;
260
+ }
261
+ pieces[pieces.length - 1] += ch;
262
+ used += columnsOf(ch);
146
263
  }
147
- pieces[pieces.length - 1] += ch;
148
- used += columnsOf(ch);
149
264
  }
150
265
  return pieces;
151
266
  }
152
267
 
153
- /** A text folded to `width`, as its rows; a word wider than that is cut, so nothing drawn from them runs past the edge. */
154
- export function fold(text, width) {
155
- return wrap(text, width)
268
+ /** 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. */
269
+ export function fold(text, width, indent = '') {
270
+ return wrap(text, width, indent)
156
271
  .split('\n')
157
272
  .flatMap((line) => (visible(line) <= width ? [line] : cut(line, width)));
158
273
  }
@@ -176,7 +291,26 @@ export function renderTable(rows, s, width) {
176
291
  const table = [head, ...body].map((row) => Array.from({ length: columns }, (_, i) => row[i] ?? ''));
177
292
  const widths = Array.from({ length: columns }, (_, i) => Math.max(1, ...table.map((row) => visible(inline(row[i], s)))));
178
293
  const room = width - (3 * columns + 1);
179
- while (widths.reduce((a, b) => a + b, 0) > room && Math.max(...widths) > MIN_COLUMN) widths[widths.indexOf(Math.max(...widths))]--;
294
+ const sum = (list) => list.reduce((a, b) => a + b, 0);
295
+ if (sum(widths) > room) {
296
+ // Too wide: each column keeps its longest word whole if it can, and the room left over goes to the columns with the most
297
+ // to say, by how much more they have — so a column of short keys is not padded out to match a column of sentences.
298
+ 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))))));
299
+ const spare = room - sum(least);
300
+ // Three columns or more that cannot keep their words whole would fold into a ladder of word ends: each row is shown as
301
+ // 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
+ }
305
+ if (spare >= 0) {
306
+ const wants = widths.map((most, i) => most - least[i]);
307
+ const given = least.map((w, i) => w + Math.floor((spare * wants[i]) / Math.max(1, sum(wants))));
308
+ // What rounding left goes to the columns that want the most, one each.
309
+ 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])))]++;
310
+ widths.splice(0, columns, ...given.map((w, i) => Math.min(w, widths[i])));
311
+ } else widths.splice(0, columns, ...least);
312
+ while (sum(widths) > room && Math.max(...widths) > MIN_COLUMN) widths[widths.indexOf(Math.max(...widths))]--;
313
+ }
180
314
 
181
315
  const edge = (left, mid, right) => s.dim(`${left}${widths.map((w) => '─'.repeat(w + 2)).join(mid)}${right}`);
182
316
  const bar = s.dim('│');
@@ -205,15 +339,20 @@ export function createRenderer(write, s, { width = MAX_WIDTH } = {}) {
205
339
  let rows = [];
206
340
  /** The indent of the list item the lines are in, until a line comes out of it. */
207
341
  let hang = null;
342
+ /** The language the code block in hand is in, and where its colouring has got to: a comment can run over lines. */
343
+ let lang = '';
344
+ let code = { comment: false };
208
345
  const line = (raw) => {
209
346
  const marks = /^\s*```\s*(\S*)/.exec(raw);
210
347
  if (marks) {
211
348
  fence = !fence;
212
349
  hang = null;
350
+ lang = fence ? marks[1].toLowerCase() : '';
351
+ code = { comment: false };
213
352
  return s.dim(fence ? ` ┌─${marks[1] ? ` ${marks[1]}` : ''}` : ' └─');
214
353
  }
215
354
  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 });
355
+ return renderLine(raw, s, { fence, width, hang: hangOf(raw) === null ? hang : null, lang, code });
217
356
  };
218
357
  /** The rows held so far: a table once its rule has come, the lines they were otherwise. */
219
358
  const held = () => (rows.length >= 2 && TABLE_RULE.test(rows[1]) ? renderTable(rows, s, width) : rows.map((r) => renderLine(r, s, { width })).join('\n'));
@@ -244,15 +383,26 @@ export function createRenderer(write, s, { width = MAX_WIDTH } = {}) {
244
383
  rows = [];
245
384
  fence = false;
246
385
  hang = null;
386
+ lang = '';
387
+ code = { comment: false };
247
388
  },
248
389
  /** What has not been written yet, rendered as far as it has got: the rows of a table, and the line still arriving. */
249
390
  get tail() {
250
391
  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');
392
+ return [rows.length > 0 ? held() : '', tail && !/^\s*```/.test(tail) ? renderLine(tail, s, { fence, width, hang: going, lang, code: { ...code } }) : ''].filter(Boolean).join('\n');
252
393
  },
253
394
  };
254
395
  }
255
396
 
397
+ /** This sumo's version, from its package.json; empty where there is none to read, as beside a standalone binary. */
398
+ export const VERSION = (() => {
399
+ try {
400
+ return String(JSON.parse(readFileSync(join(REPO_ROOT, 'package.json'), 'utf8')).version ?? '');
401
+ } catch {
402
+ return '';
403
+ }
404
+ })();
405
+
256
406
  /** The words shown while the model works: yours, one a line, in spinner.txt at the top of the repo. */
257
407
  export const SPINNER_FILE = join(REPO_ROOT, 'spinner.txt');
258
408
  const SPINNER_FALLBACK = ['Working'];
@@ -317,17 +467,18 @@ const SHOWN_TAIL_LINES = 3;
317
467
  const SHOWN_DIFF_LINES = 12;
318
468
  const SHOWN_COMMAND_LINES = 3;
319
469
  const SHOWN_COMMAND_CHARS = 240;
470
+ const SHOWN_WRITE_LINES = 4;
320
471
 
321
472
  const more = (n) => ({ text: `… +${n} line${n === 1 ? '' : 's'}`, tone: 'dim' });
322
473
 
323
- /** The top of a list of lines, and how many more there were. */
474
+ /** 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
475
  function top(lines, max) {
325
- return lines.length > max ? [...lines.slice(0, max), more(lines.length - max)] : lines;
476
+ return lines.length > max + 1 ? [...lines.slice(0, max), more(lines.length - max)] : lines;
326
477
  }
327
478
 
328
479
  /** Both ends of what a command printed, and how many lines lie between: a run says how it went in its last lines. */
329
480
  function ends(lines, full) {
330
- if (full || lines.length <= SHOWN_HEAD_LINES + SHOWN_TAIL_LINES) return lines;
481
+ if (full || lines.length <= SHOWN_HEAD_LINES + SHOWN_TAIL_LINES + 1) return lines;
331
482
  return [...lines.slice(0, SHOWN_HEAD_LINES), more(lines.length - SHOWN_HEAD_LINES - SHOWN_TAIL_LINES), ...lines.slice(-SHOWN_TAIL_LINES)];
332
483
  }
333
484
 
@@ -338,9 +489,15 @@ export const tilde = (path, home = homedir()) => (path === home ? '~' : String(p
338
489
  export const pathFrom = (path, cwd) => (cwd && path === cwd ? '.' : cwd && String(path).startsWith(`${cwd}${sep}`) ? String(path).slice(cwd.length + 1) : tilde(path));
339
490
 
340
491
  /** 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'] };
492
+ 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
493
 
343
- const toned = (text, tone) => String(text).split('\n').map((t) => ({ text: t, tone }));
494
+ /**
495
+ * What a command printed in colour reaches the model with its escapes shown as markers (⟨U+001B⟩[31m); on the screen
496
+ * they are noise in the words, and go. Any other hidden character keeps its marker.
497
+ */
498
+ export const withoutColourCodes = (text) => String(text).replace(/⟨U\+001B⟩\[[0-?]*[ -/]*[@-~]|⟨U\+001B⟩\][^\n]*?(?:⟨U\+0007⟩|⟨U\+001B⟩\\)/g, '');
499
+
500
+ const toned = (text, tone) => withoutColourCodes(text).split('\n').map((t) => ({ text: t, tone }));
344
501
  const count = (text) => [{ text: `${text === '' ? 0 : text.replace(/\n$/, '').split('\n').length} lines`, tone: 'dim' }];
345
502
 
346
503
  /**
@@ -372,6 +529,33 @@ function diffView(old, now, line, full) {
372
529
  };
373
530
  }
374
531
 
532
+ /**
533
+ * 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
+ * there. A heading is dropped — or, with `headings: 'keep'`, kept as its words; either way a line of three words or fewer
535
+ * under one ("None.", "Matches.") says nothing without it, and takes it in front.
536
+ */
537
+ function readable(text, cwd = null, { headings = 'drop' } = {}) {
538
+ const lines = [];
539
+ let heading = null;
540
+ for (const raw of String(text ?? '').split('\n')) {
541
+ if (!raw.trim() || TABLE_RULE.test(raw)) continue;
542
+ const head = /^#{1,6}\s+(.*)$/.exec(raw);
543
+ if (head) {
544
+ heading = inline(head[1], NO_STYLE).replace(/:\s*$/, '');
545
+ if (headings === 'keep') lines.push(heading);
546
+ continue;
547
+ }
548
+ const line = inline(TABLE_ROW.test(raw) ? cellsOf(raw).filter(Boolean).join(' · ') : raw.replace(/^(\s*)[-*+]\s+/, '$1• '), NO_STYLE);
549
+ const named = cwd ? line.replaceAll(`${cwd}${sep}`, '') : line;
550
+ if (heading && named.trim().split(/\s+/).length <= 3) {
551
+ if (headings === 'keep') lines.pop();
552
+ lines.push(`${heading}: ${named.trim()}`);
553
+ } else lines.push(named);
554
+ heading = null;
555
+ }
556
+ return lines;
557
+ }
558
+
375
559
  /**
376
560
  * A tool call for the screen: what ran, and under it the part of the result
377
561
  * worth a glance — both ends of a command's output, an edit as a diff, a read
@@ -384,6 +568,8 @@ export function toolView(call, result = null, { full = false, cwd = null } = {})
384
568
  // Folded, the empty lines of what came back are not shown: three of five lines spent on nothing say nothing.
385
569
  const output = (content = result.content) => {
386
570
  const lines = toned(content, result.isError ? 'error' : 'plain');
571
+ // What reads as a diff — `git diff`, a patch — is drawn as one: what went red, what came green.
572
+ 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
573
  if (full) return lines;
388
574
  const said = lines.filter((line) => line.text.trim() !== '');
389
575
  return said.length === 0 ? [{ text: '(no output)', tone: 'dim' }] : ends(said, false);
@@ -401,20 +587,26 @@ export function toolView(call, result = null, { full = false, cwd = null } = {})
401
587
  return { title: 'Bash', detail, lines: output() };
402
588
  }
403
589
  if (call.name === DELEGATE_TOOL.name) {
404
- const detail = input.job !== undefined ? `j${input.job}` : `${input.agent ?? 'worker'} · ${input.title ?? ''}`;
405
- if (!result) return { title: 'Delegate', detail, lines: [] };
590
+ // A report a job in the background sent back is titled as one, by who sent it; a call is the delegation itself.
591
+ const title = input.report ? 'Report' : 'Delegate';
592
+ const detail = input.job !== undefined ? `j${input.job}${input.report && input.agent ? ` ${input.agent} · ${input.title ?? ''}` : ''}` : `${input.agent ?? 'worker'} · ${input.title ?? ''}`;
593
+ if (!result) return { title, detail, lines: [] };
406
594
  // 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: 'Delegate', detail, lines: [{ text: 'running in the background — its report comes here when it is done', tone: 'dim' }] };
408
- if (!result.job || full) return { title: 'Delegate', detail, lines: output() };
595
+ 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' }] };
596
+ if (full) return { title, detail, lines: output() };
597
+ // Several attempts report together, in markdown: shown as it reads, like a single job's report.
598
+ if (!result.job) return { title, detail, lines: output(result.isError ? result.content : readable(result.content, cwd, { headings: 'keep' }).join('\n')) };
409
599
  // A job that ran: how it went in one line, then the top of what it reported.
410
600
  const { job } = result;
411
- const [mark, said, tone] = JOB_ENDS[job.status] ?? JOB_ENDS.open;
601
+ // Stopped by the user before it closed itself, it was stopped — not left open.
602
+ const [mark, said, tone] = input.stopped && !['done', 'failed', 'needs_input'].includes(job.status) ? JOB_ENDS.stopped : (JOB_ENDS[job.status] ?? JOB_ENDS.open);
412
603
  const route = job.effort && job.effort !== 'none' ? `${job.model}/${job.effort}` : job.model;
413
604
  // How long it took comes first: it is what the wait was.
414
605
  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
- const report = String(job.report ?? '').split('\n').filter((line) => line.trim() && !/^#{1,6}\s/.test(line));
417
- return { title: 'Delegate', detail, lines: [{ text: summary, tone }, ...top(report.map((text) => ({ text, tone: 'plain' })), SHOWN_REPORT_LINES)] };
606
+ // 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;
607
+ // a table's row is its cells, and a file in the project is named from there.
608
+ const report = readable(job.report, cwd);
609
+ return { title, detail, lines: [{ text: summary, tone }, ...top(report.map((text) => ({ text, tone: 'plain' })), SHOWN_REPORT_LINES)] };
418
610
  }
419
611
  if (isMcpTool(call.name)) {
420
612
  // A server's tool: the server as the title, the tool with its input as the detail, what came back under it.
@@ -433,6 +625,11 @@ export function toolView(call, result = null, { full = false, cwd = null } = {})
433
625
  // 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
626
  return { title: 'Advisor', detail: String(input.asked ?? ''), lines: result ? output() : [] };
435
627
  }
628
+ if (call.name === ASK_TOOL.name) {
629
+ // A question put to the user: the question, and under it what they answered.
630
+ const question = String(input.question ?? '').split('\n')[0];
631
+ return { title: 'Question', detail: question, lines: result ? output() : [] };
632
+ }
436
633
  if (call.name !== EDITOR_TOOL.name) {
437
634
  // A job's own tools: what it was given in a line, what came back under it.
438
635
  const given = String(input.status ?? input.query ?? input.question ?? input.text ?? '').split('\n')[0].slice(0, 80);
@@ -446,7 +643,12 @@ export function toolView(call, result = null, { full = false, cwd = null } = {})
446
643
  if (result.isError) return { title, detail, lines: output() };
447
644
  const added = (text) => toned(text, 'add').map((l) => ({ ...l, text: `+ ${l.text}` }));
448
645
  if (input.command === 'view') return { title, detail, lines: full ? toned(result.content, 'plain') : count(result.content) };
449
- if (input.command === 'create') return { title, detail, lines: full ? added(String(input.file_text ?? '').replace(/\n$/, '')) : count(String(input.file_text ?? '')) };
646
+ // A new file is shown by its top, as what came: what was written is what is checked first.
647
+ if (input.command === 'create') {
648
+ const text = String(input.file_text ?? '').replace(/\n$/, '');
649
+ if (!text) return { title, detail, lines: [{ text: '(empty)', tone: 'dim' }] };
650
+ return { title, detail, lines: full ? added(text) : top(added(text), SHOWN_WRITE_LINES) };
651
+ }
450
652
  // 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
653
  const came = input.command === 'insert' ? (input.insert_text ?? input.new_str ?? '').replace(/\n$/, '') : (input.new_str ?? '');
452
654
  const edit = result.edit ?? { line: null, old: input.command === 'str_replace' ? (input.old_str ?? '') : '', new: came };
@@ -454,6 +656,24 @@ export function toolView(call, result = null, { full = false, cwd = null } = {})
454
656
  return { title, detail: diff.at === null ? detail : `${detail}:${diff.at}`, stat: diff.stat, lines: diff.lines };
455
657
  }
456
658
 
659
+ /** The failures a request meets most, in the words a person acts on: what happened, and what to do about it. */
660
+ const FAILURES = [
661
+ [/overloaded|\b529\b/i, "Anthropic's API is overloaded just now — nothing was lost; send it again in a minute"],
662
+ [/rate.?limit|\b429\b/i, 'rate limited by the API — wait a minute and send it again, or /model to another model'],
663
+ [/credit balance|billing|payment/i, 'the API account has no credit left — top it up, then send it again'],
664
+ [/\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
+ [/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
+ [/\b5\d\d\b|internal server error|api_error/i, 'the API failed on its side — send it again'],
668
+ ];
669
+
670
+ /** 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. */
671
+ export function explained(message) {
672
+ const said = String(message ?? '').replace(/\s+/g, ' ').trim();
673
+ const known = FAILURES.find(([pattern]) => pattern.test(said));
674
+ return known ? { text: `error: ${known[1]}`, detail: said.length > 200 ? `${said.slice(0, 199)}…` : said } : { text: `error: ${said}` };
675
+ }
676
+
457
677
  /**
458
678
  * 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
679
  * a reply as it is drawn — in the terminal's colours. What the screen folds, this does not; a pager scrolls and searches it.
@@ -476,13 +696,42 @@ export function transcript(log, s, { width = MAX_WIDTH, cwd = null } = {}) {
476
696
  out.push('', `${entry.result.isError ? s.red('⏺') : s.green('⏺')} ${s.bold(view.title)}(${untab(view.detail).split('\n').join('\n ')})${stat}`, ...under(view.lines));
477
697
  } else if (entry.kind === 'shell') out.push(...under(toolView({ name: BASH_TOOL.name }, entry.result, { full: true }).lines));
478
698
  else if (entry.kind === 'job') out.push('', `⏺ ${s.bold(`j${entry.id}`)} ${entry.agent} · ${entry.route} — ${entry.title}`);
479
- else if (entry.kind === 'error') out.push('', s.red(entry.text));
699
+ else if (entry.kind === 'error') out.push('', s.red(entry.text), ...(entry.detail ? [s.dim(` ${entry.detail}`)] : []));
700
+ else if (entry.kind === 'thought') out.push('', s.dim(`✻ Thought for ${elapsed(entry.ms)}`), ...String(entry.text ?? '').trim().split('\n').filter(Boolean).map((line) => s.dim(s.italic(` ${line}`))));
480
701
  else if (entry.kind === 'footer') out.push('', s.dim(` ${entry.text}`));
481
702
  else if (entry.kind === 'note') out.push(s.dim(` ⎿ ${entry.text.split('\n').join('\n ')}`));
482
703
  }
483
704
  return `${out.join('\n').replace(/^\n/, '')}\n`;
484
705
  }
485
706
 
707
+ /** A fence for text that may hold fences of its own: longer than any run of backticks in it. */
708
+ const fenceFor = (text) => '`'.repeat(Math.max(3, ...[...String(text).matchAll(/`+/g)].map((m) => m[0].length + 1)));
709
+
710
+ /**
711
+ * The conversation as Markdown, for `/export`: what was said quoted, each reply as the model wrote it, each call folded
712
+ * 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.
713
+ */
714
+ export function markdownOf(log, { cwd = null, title = 'Sumo' } = {}) {
715
+ const out = [`# ${title}`];
716
+ const folded = (summary, body) => {
717
+ const fence = fenceFor(body);
718
+ out.push('', `<details><summary>${summary.replace(/</g, '&lt;')}</summary>`, '', fence, body, fence, '', '</details>');
719
+ };
720
+ for (const entry of log) {
721
+ if (entry.kind === 'user') out.push('', '**You**', '', ...entry.text.split('\n').map((line) => `> ${line}`));
722
+ else if (entry.kind === 'reply') out.push('', entry.raw.trim());
723
+ else if (entry.kind === 'tool') {
724
+ const view = toolView(entry.call, entry.result, { full: true, cwd });
725
+ folded(`${view.title}(${view.detail.split('\n')[0]})${entry.result.isError ? ' — failed' : ''}`, view.lines.map((line) => line.text).join('\n'));
726
+ } else if (entry.kind === 'shell') folded('! command', String(entry.result.content));
727
+ else if (entry.kind === 'thought') folded(`Thought for ${elapsed(entry.ms)}`, String(entry.text ?? '').trim());
728
+ else if (entry.kind === 'job') out.push('', `**j${entry.id}** ${entry.agent} · ${entry.route} — ${entry.title}`);
729
+ else if (entry.kind === 'error') out.push('', `**${entry.text}**${entry.detail ? ` — ${entry.detail}` : ''}`);
730
+ else if (entry.kind === 'note' || entry.kind === 'footer') out.push('', ...entry.text.split('\n').map((line) => `_${line}_`));
731
+ }
732
+ return `${out.join('\n')}\n`;
733
+ }
734
+
486
735
  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
736
 
488
737
  /**