sumo-agents 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/AGENTS.md +38 -0
  2. package/LICENSE +21 -0
  3. package/README.md +111 -2
  4. package/bin/sumo.mjs +33 -0
  5. package/guides/delegation.md +33 -0
  6. package/guides/feature.md +14 -0
  7. package/guides/fix.md +14 -0
  8. package/guides/memory.md +23 -0
  9. package/guides/projects.md +27 -0
  10. package/guides/review.md +16 -0
  11. package/guides/workflows.md +26 -0
  12. package/logo.txt +19 -0
  13. package/package.json +42 -4
  14. package/prompts/agent.md +7 -0
  15. package/prompts/dream.md +13 -0
  16. package/prompts/scribe.md +21 -0
  17. package/spinner.txt +90 -0
  18. package/src/advisor.mjs +59 -0
  19. package/src/apply.mjs +368 -0
  20. package/src/auth.mjs +80 -0
  21. package/src/card.mjs +72 -0
  22. package/src/catalog.mjs +167 -0
  23. package/src/chat.mjs +1162 -0
  24. package/src/cli.mjs +815 -0
  25. package/src/cost.mjs +128 -0
  26. package/src/db.mjs +384 -0
  27. package/src/dream.mjs +97 -0
  28. package/src/editor.mjs +198 -0
  29. package/src/export.mjs +132 -0
  30. package/src/guard.mjs +121 -0
  31. package/src/guides.mjs +86 -0
  32. package/src/herdr.mjs +117 -0
  33. package/src/hooks.mjs +270 -0
  34. package/src/images.mjs +89 -0
  35. package/src/jobs.mjs +1184 -0
  36. package/src/jobtools.mjs +82 -0
  37. package/src/local-server.mjs +169 -0
  38. package/src/lock.mjs +45 -0
  39. package/src/loop.mjs +838 -0
  40. package/src/mcp.mjs +604 -0
  41. package/src/memory.mjs +400 -0
  42. package/src/model.mjs +270 -0
  43. package/src/page.html +304 -0
  44. package/src/page.mjs +135 -0
  45. package/src/paths.mjs +33 -0
  46. package/src/prime.mjs +177 -0
  47. package/src/projects.mjs +232 -0
  48. package/src/recall.mjs +45 -0
  49. package/src/redact.mjs +173 -0
  50. package/src/render.mjs +45 -0
  51. package/src/route.mjs +287 -0
  52. package/src/sandbox.mjs +173 -0
  53. package/src/scan.mjs +204 -0
  54. package/src/scribe.mjs +349 -0
  55. package/src/sessions.mjs +371 -0
  56. package/src/setup.mjs +528 -0
  57. package/src/sqlite.mjs +66 -0
  58. package/src/text.mjs +97 -0
  59. package/src/tools.mjs +987 -0
  60. package/src/transcript.mjs +106 -0
  61. package/src/tty.mjs +529 -0
  62. package/src/ui.mjs +1363 -0
  63. package/src/verify.mjs +369 -0
  64. package/src/web.mjs +49 -0
  65. package/src/workflows.mjs +270 -0
  66. package/src/worktree.mjs +128 -0
@@ -0,0 +1,106 @@
1
+ import { closeSync, fstatSync, openSync, readSync } from 'node:fs';
2
+ import { redact } from './redact.mjs';
3
+ import { head } from './text.mjs';
4
+
5
+ /**
6
+ * Generous on purpose: the closing reply of a piece of work is where the traps it hit are mentioned,
7
+ * usually mid-paragraph. At 400 characters a real "tests only pass with SIMBA_TZ set" was cut out.
8
+ */
9
+ const REPLY_MAX = 1200;
10
+
11
+ /**
12
+ * Keeps both ends of a long reply. The head says what was attempted and the
13
+ * tail says what was done; the middle is the part worth losing.
14
+ */
15
+ export function abridge(text, max = REPLY_MAX) {
16
+ const flat = text.replace(/\s+/g, ' ').trim();
17
+ if (flat.length <= max) return flat;
18
+ const half = Math.floor((max - 5) / 2);
19
+ // Either cut can fall inside an emoji; a lone half of one makes the whole request one the API refuses.
20
+ const tail = flat.slice(-half);
21
+ return `${head(flat, half)} […] ${/^[\uDC00-\uDFFF]/.test(tail) ? tail.slice(1) : tail}`;
22
+ }
23
+
24
+ /** How much of a transcript's end is read first; each look that finds too little reads four times as much. */
25
+ const FIRST_LOOK_BYTES = 1024 * 1024;
26
+
27
+ /**
28
+ * A transcript's last lines, `bytes` of them at most, and whether that was the whole file. A session's transcript
29
+ * grows to hundreds of megabytes; what is asked of it lives at its end, and a string past ~512 MB cannot even be built.
30
+ */
31
+ function tailOf(file, bytes) {
32
+ const fd = openSync(file, 'r');
33
+ try {
34
+ const size = fstatSync(fd).size;
35
+ const start = Math.max(0, size - bytes);
36
+ const buffer = Buffer.alloc(size - start);
37
+ readSync(fd, buffer, 0, buffer.length, start);
38
+ const text = buffer.toString('utf8');
39
+ // A window that starts mid-line drops that piece: it is not a line of JSON. One with no line end in it holds no whole line.
40
+ if (start === 0) return { lines: text.split('\n'), whole: true };
41
+ const cut = text.indexOf('\n');
42
+ return { lines: cut === -1 ? [] : text.slice(cut + 1).split('\n'), whole: false };
43
+ } finally {
44
+ closeSync(fd);
45
+ }
46
+ }
47
+
48
+ /**
49
+ * The transcript read from its end, in windows that grow until `enough(lines)` says so or the whole file has been
50
+ * read. Returns what `enough` last returned, or null for a file that cannot be read.
51
+ */
52
+ export function readBackwards(file, enough) {
53
+ try {
54
+ for (let bytes = FIRST_LOOK_BYTES; ; bytes *= 4) {
55
+ const { lines, whole } = tailOf(file, bytes);
56
+ const answer = enough(lines, whole);
57
+ if (answer !== undefined || whole) return answer ?? null;
58
+ }
59
+ } catch {
60
+ return null;
61
+ }
62
+ }
63
+
64
+ /**
65
+ * The assistant's own words from a Claude Code transcript, since a given time.
66
+ *
67
+ * Only `text` blocks of main-thread assistant messages are read. Tool calls,
68
+ * tool results, thinking and sub-agent traffic are skipped on purpose: they are
69
+ * large, and tool output is exactly where instructions injected by a web page
70
+ * or a file would arrive. Nothing from there may ever reach the memory writer.
71
+ *
72
+ * The format is not a stable contract, so anything unexpected is ignored rather
73
+ * than fatal — without this file the writer still has the user's own turns.
74
+ * A secret the assistant repeated is scrubbed like one the user typed, and before
75
+ * the reply is cut: half a token left at the edge of the cut would still be a leak.
76
+ */
77
+ export function assistantReplies(file, sinceIso, wanted = Infinity) {
78
+ // Read from the end: the last `wanted` replies since `sinceIso` are all that is ever asked for.
79
+ return (
80
+ readBackwards(file, (lines, whole) => {
81
+ const replies = [];
82
+ let reachedSince = false;
83
+ for (const line of lines) {
84
+ if (!line.includes('"assistant"')) continue;
85
+ let entry;
86
+ try {
87
+ entry = JSON.parse(line);
88
+ } catch {
89
+ continue;
90
+ }
91
+ if (entry.type !== 'assistant' || entry.isSidechain || !Array.isArray(entry.message?.content)) continue;
92
+ if (sinceIso && entry.timestamp && entry.timestamp < sinceIso) {
93
+ reachedSince = true;
94
+ continue;
95
+ }
96
+ const text = entry.message.content
97
+ .filter((block) => block?.type === 'text' && typeof block.text === 'string')
98
+ .map((block) => block.text)
99
+ .join('\n')
100
+ .trim();
101
+ if (text) replies.push({ ts: entry.timestamp ?? '', text: abridge(redact(text).text) });
102
+ }
103
+ return whole || reachedSince || replies.length >= wanted ? replies : undefined;
104
+ }) ?? []
105
+ );
106
+ }
package/src/tty.mjs ADDED
@@ -0,0 +1,529 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join, sep } from 'node:path';
4
+ import { isAdvisorTool } from './advisor.mjs';
5
+ import { compactInput, isMcpTool, splitMcpName, unlabeled } from './mcp.mjs';
6
+ import { REPO_ROOT } from './paths.mjs';
7
+ import { elapsed } from './text.mjs';
8
+ import { BASH_TOOL, DELEGATE_TOOL, EDITOR_TOOL } from './tools.mjs';
9
+ import { isWebTool, WEB_SEARCH_TOOL } from './web.mjs';
10
+
11
+ /**
12
+ * What the chat terminal looks like: the reply's markdown turned into bold,
13
+ * dim and colour as it streams, wrapped to a readable width; the memory block
14
+ * in spaced sections with its labels standing out; tool lines and errors told
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.
17
+ */
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'] };
20
+ const MAX_WIDTH = 100;
21
+ const MIN_WIDTH = 40;
22
+
23
+ /** The style functions, each a no-op when colour is off. */
24
+ export function styles(enabled) {
25
+ const s = {};
26
+ for (const [name, [on, off]] of Object.entries(CODES)) s[name] = enabled ? (t) => `\x1b[${on}m${t}\x1b[${off}m` : (t) => t;
27
+ return s;
28
+ }
29
+
30
+ export const colourEnabled = (stream = process.stdout, env = process.env) => Boolean(stream.isTTY) && !('NO_COLOR' in env) && env.TERM !== 'dumb';
31
+
32
+ /** Lines no wider than this read comfortably whatever the window is. */
33
+ export const widthOf = (stream = process.stdout, env = process.env) => Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, (stream.columns || Number(env.COLUMNS) || 80) - 1));
34
+
35
+ /** East Asian wide and fullwidth characters, and emoji drawn as pictures: two columns each on a terminal. */
36
+ const WIDE = /[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA000-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6\u{20000}-\u{3FFFD}]|\p{Emoji_Presentation}|\uFE0F/u;
37
+ /** The columns one character takes, an emoji joined from several included. */
38
+ const columnsOf = (ch) => (WIDE.test(ch) ? 2 : 1);
39
+
40
+ /** The columns text takes on a terminal, colour codes not counted: a wide character is two, so a table around it lines up. */
41
+ const visible = (t) => {
42
+ const plain = t.replace(/\x1b\[[0-9;]*m/g, '');
43
+ if (!/[^\x00-\x7e]/.test(plain)) return plain.length;
44
+ let width = 0;
45
+ for (const { segment } of GRAPHEMES.segment(plain)) width += columnsOf(segment);
46
+ return width;
47
+ };
48
+
49
+ /** Word-wraps styled text to `width`, measuring only what is visible; continuation lines carry `indent`. */
50
+ export function wrap(text, width, indent = '') {
51
+ if (visible(text) <= width) return text;
52
+ const lead = /^\s*/.exec(text)[0];
53
+ const lines = [];
54
+ let line = lead;
55
+ for (const word of text.slice(lead.length).split(' ')) {
56
+ const next = line === lead ? `${lead}${word}` : `${line} ${word}`;
57
+ if (line !== lead && visible(next) > width) {
58
+ lines.push(line);
59
+ line = `${indent}${word}`;
60
+ } else line = next;
61
+ }
62
+ lines.push(line);
63
+ return lines.join('\n');
64
+ }
65
+
66
+ /** A character after a backslash is meant as itself, not as a mark. */
67
+ const ESCAPED = /\\([\\`*_~[\]()<>#|!])/g;
68
+ /** 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. */
69
+ const KEPT = /\uE000(\d+)\uE001/g;
70
+
71
+ /**
72
+ * Inline markdown on one line: code, links shown as their text and address, bold, italic, struck through, and
73
+ * a backslash-escaped mark as itself. A mark only counts where markdown would read it: snake_case and 2*3*4 stay.
74
+ */
75
+ export function inline(line, s) {
76
+ const kept = [];
77
+ const keep = (text) => `\uE000${kept.push(text) - 1}\uE001`;
78
+ const out = line
79
+ .replace(/(?<!\\)`([^`]+)`/g, (_, code) => keep(s.cyan(code)))
80
+ .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})`))}`))
83
+ .replace(/\*\*\*(?!\s)([^*]+?)(?<!\s)\*\*\*/g, (_, t) => s.bold(s.italic(t)))
84
+ .replace(/\*\*(?!\s)([^*]+?)(?<!\s)\*\*/g, (_, t) => s.bold(t))
85
+ .replace(/(?<![\w_])__(?!\s)([^_]+?)(?<!\s)__(?![\w_])/g, (_, t) => s.bold(t))
86
+ .replace(/(?<![\w*])\*(?![\s*])([^*]+?)(?<!\s)\*(?![\w*])/g, (_, t) => s.italic(t))
87
+ .replace(/(?<![\w_])_(?![\s_])([^_]+?)(?<!\s)_(?![\w_])/g, (_, t) => s.italic(t))
88
+ .replace(/~~(?!\s)([^~]+?)(?<!\s)~~/g, (_, t) => s.strike(t));
89
+ // A reply that happens to hold the stand-in characters itself keeps them as they were.
90
+ const restore = (text) => text.replace(KEPT, (whole, i) => (kept[Number(i)] === undefined ? whole : restore(kept[Number(i)])));
91
+ return restore(out);
92
+ }
93
+
94
+ /** A list item's marker: a bullet, or a number with its stop. */
95
+ const LIST_ITEM = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/;
96
+
97
+ /**
98
+ * 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
+ * line that is no list item.
100
+ */
101
+ export function hangOf(line) {
102
+ const item = LIST_ITEM.exec(line);
103
+ if (!item) return null;
104
+ return `${item[1]}${' '.repeat(/\d/.test(item[2]) ? item[2].length + 3 : 4)}`;
105
+ }
106
+
107
+ /**
108
+ * One line of a reply: block-level marks replaced by weight and indent, then wrapped with a hanging indent.
109
+ * `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
+ */
111
+ export function renderLine(line, s, { fence = false, width = MAX_WIDTH, hang = null } = {}) {
112
+ // Code is what is read most closely: the frame around it is faint, the code is not.
113
+ if (fence) return ` ${line}`;
114
+ const heading = /^(#{1,6})\s+(.*)$/.exec(line);
115
+ if (heading) return wrap(heading[1].length === 1 ? s.bold(s.underline(inline(heading[2], s))) : s.bold(inline(heading[2], s)), width);
116
+ const item = LIST_ITEM.exec(line);
117
+ if (item && !/\d/.test(item[2])) {
118
+ const task = /^\[([ xX])\]\s+(.*)$/.exec(item[3]);
119
+ const mark = task ? (task[1] === ' ' ? s.dim('☐') : s.green('☑')) : s.dim('•');
120
+ return wrap(`${item[1]} ${mark} ${inline(task ? task[2] : item[3], s)}`, width, `${item[1]} `);
121
+ }
122
+ 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('│')} ${s.italic(inline(line.replace(/^\s*>\s?/, ''), s))}`, width, ` ${s.dim('│')} `);
124
+ if (/^\s*(---|\*\*\*|___)\s*$/.test(line)) return s.dim('─'.repeat(Math.min(40, width)));
125
+ if (hang !== null && /^\s+\S/.test(line)) return wrap(`${hang}${inline(line.trim(), s)}`, width, hang);
126
+ return wrap(inline(line, s), width);
127
+ }
128
+
129
+ const TABLE_ROW = /^\s*\|.*\|\s*$/;
130
+ const TABLE_RULE = /^\s*\|(\s*:?-+:?\s*\|)+\s*$/;
131
+ const MIN_COLUMN = 3;
132
+ const NO_STYLE = styles(false);
133
+
134
+ const cellsOf = (row) => row.trim().slice(1, -1).split(/(?<!\\)\|/).map((c) => c.trim().replace(/\\\|/g, '|'));
135
+
136
+ const GRAPHEMES = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
137
+
138
+ /** A line cut into pieces no wider than `width`, between characters: an emoji, even one joined from several, stays whole. */
139
+ function cut(line, width) {
140
+ const pieces = [''];
141
+ 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;
146
+ }
147
+ pieces[pieces.length - 1] += ch;
148
+ used += columnsOf(ch);
149
+ }
150
+ return pieces;
151
+ }
152
+
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)
156
+ .split('\n')
157
+ .flatMap((line) => (visible(line) <= width ? [line] : cut(line, width)));
158
+ }
159
+
160
+ function pad(text, width, align) {
161
+ const space = Math.max(0, width - visible(text));
162
+ if (align === 'right') return ' '.repeat(space) + text;
163
+ if (align === 'center') return ' '.repeat(Math.floor(space / 2)) + text + ' '.repeat(Math.ceil(space / 2));
164
+ return text + ' '.repeat(space);
165
+ }
166
+
167
+ /**
168
+ * A markdown table as a box with its columns lined up. When the window is too
169
+ * narrow for it, the widest columns give way and their cells fold; a folded
170
+ * cell is plain text, so no style runs across a border.
171
+ */
172
+ export function renderTable(rows, s, width) {
173
+ const [head, rule, ...body] = rows.map(cellsOf);
174
+ const columns = head.length;
175
+ const aligns = Array.from({ length: columns }, (_, i) => (/^:-+:$/.test(rule[i] ?? '') ? 'center' : /-:$/.test(rule[i] ?? '') ? 'right' : 'left'));
176
+ const table = [head, ...body].map((row) => Array.from({ length: columns }, (_, i) => row[i] ?? ''));
177
+ const widths = Array.from({ length: columns }, (_, i) => Math.max(1, ...table.map((row) => visible(inline(row[i], s)))));
178
+ 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))]--;
180
+
181
+ const edge = (left, mid, right) => s.dim(`${left}${widths.map((w) => '─'.repeat(w + 2)).join(mid)}${right}`);
182
+ const bar = s.dim('│');
183
+ const draw = (row, style) => {
184
+ const cells = row.map((cell, i) => (visible(inline(cell, s)) <= widths[i] ? [inline(cell, s)] : fold(inline(cell, NO_STYLE), widths[i])));
185
+ const height = Math.max(...cells.map((c) => c.length));
186
+ return Array.from({ length: height }, (_, n) => `${bar} ${cells.map((c, i) => style(pad(c[n] ?? '', widths[i], aligns[i]))).join(` ${bar} `)} ${bar}`);
187
+ };
188
+ return [edge('┌', '┬', '┐'), ...draw(table[0], s.bold), edge('├', '┼', '┤'), ...table.slice(1).flatMap((row) => draw(row, (t) => t)), edge('└', '┴', '┘')].join('\n');
189
+ }
190
+
191
+ /**
192
+ * A line-buffered renderer for streamed text: each complete line is written
193
+ * rendered as soon as it arrives; the tail is kept until it ends or `flush`.
194
+ * The rows of a table are kept too, until the line after it shows it is whole.
195
+ */
196
+ /**
197
+ * A tab as the spaces it takes. A screen that lays text out counts a tab as one column and the terminal draws up to
198
+ * eight, so a box's border or a wrapped line would land wherever the tab pushed it.
199
+ */
200
+ export const untab = (text) => text.replaceAll('\t', ' ');
201
+
202
+ export function createRenderer(write, s, { width = MAX_WIDTH } = {}) {
203
+ let tail = '';
204
+ let fence = false;
205
+ let rows = [];
206
+ /** The indent of the list item the lines are in, until a line comes out of it. */
207
+ let hang = null;
208
+ const line = (raw) => {
209
+ const marks = /^\s*```\s*(\S*)/.exec(raw);
210
+ if (marks) {
211
+ fence = !fence;
212
+ hang = null;
213
+ return s.dim(fence ? ` ┌─${marks[1] ? ` ${marks[1]}` : ''}` : ' └─');
214
+ }
215
+ 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 });
217
+ };
218
+ /** The rows held so far: a table once its rule has come, the lines they were otherwise. */
219
+ const held = () => (rows.length >= 2 && TABLE_RULE.test(rows[1]) ? renderTable(rows, s, width) : rows.map((r) => renderLine(r, s, { width })).join('\n'));
220
+ return {
221
+ write(chunk) {
222
+ tail += untab(chunk);
223
+ let at;
224
+ while ((at = tail.indexOf('\n')) !== -1) {
225
+ const raw = tail.slice(0, at);
226
+ tail = tail.slice(at + 1);
227
+ if (!fence && TABLE_ROW.test(raw)) {
228
+ rows.push(raw);
229
+ continue;
230
+ }
231
+ if (rows.length > 0) write(`${held()}\n`);
232
+ rows = [];
233
+ write(`${line(raw)}\n`);
234
+ }
235
+ },
236
+ flush() {
237
+ if (!fence && TABLE_ROW.test(tail)) {
238
+ rows.push(tail);
239
+ tail = '';
240
+ }
241
+ if (rows.length > 0) write(`${held()}${tail ? '\n' : ''}`);
242
+ if (tail) write(line(tail));
243
+ tail = '';
244
+ rows = [];
245
+ fence = false;
246
+ hang = null;
247
+ },
248
+ /** What has not been written yet, rendered as far as it has got: the rows of a table, and the line still arriving. */
249
+ get tail() {
250
+ 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');
252
+ },
253
+ };
254
+ }
255
+
256
+ /** The words shown while the model works: yours, one a line, in spinner.txt at the top of the repo. */
257
+ export const SPINNER_FILE = join(REPO_ROOT, 'spinner.txt');
258
+ const SPINNER_FALLBACK = ['Working'];
259
+
260
+ /** The working messages: every line of the file that is not blank and not a `#` comment. */
261
+ export function spinnerMessages(file = SPINNER_FILE) {
262
+ let text;
263
+ try {
264
+ text = readFileSync(file, 'utf8');
265
+ } catch {
266
+ return SPINNER_FALLBACK;
267
+ }
268
+ const messages = text.split('\n').map((l) => l.trim()).filter((l) => l && !l.startsWith('#'));
269
+ return messages.length > 0 ? messages : SPINNER_FALLBACK;
270
+ }
271
+
272
+ export const pickMessage = (messages, random = Math.random) => messages[Math.floor(random() * messages.length)];
273
+
274
+ const MESSAGE_MS = 5000;
275
+
276
+ /** The working message `elapsed` ms into work that opened on `first`: the next in the file every five seconds, round and round. */
277
+ export const messageAt = (messages, first, elapsed) => messages[(Math.max(0, messages.indexOf(first)) + Math.floor(elapsed / MESSAGE_MS)) % messages.length];
278
+
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
+ /** 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
+ export const LOGO_FILE = join(REPO_ROOT, 'logo.txt');
299
+
300
+ /** 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
+ export function logoLines(file = LOGO_FILE) {
302
+ let text;
303
+ try {
304
+ text = readFileSync(file, 'utf8');
305
+ } catch {
306
+ return [];
307
+ }
308
+ const rows = text.split('\n').filter((l) => !l.startsWith('#')).map((l) => l.trimEnd());
309
+ while (rows.length > 0 && !rows[0]) rows.shift();
310
+ while (rows.length > 0 && !rows.at(-1)) rows.pop();
311
+ return rows;
312
+ }
313
+
314
+ const SHOWN_REPORT_LINES = 3;
315
+ const SHOWN_HEAD_LINES = 2;
316
+ const SHOWN_TAIL_LINES = 3;
317
+ const SHOWN_DIFF_LINES = 12;
318
+ const SHOWN_COMMAND_LINES = 3;
319
+ const SHOWN_COMMAND_CHARS = 240;
320
+
321
+ const more = (n) => ({ text: `… +${n} line${n === 1 ? '' : 's'}`, tone: 'dim' });
322
+
323
+ /** The top of a list of lines, and how many more there were. */
324
+ function top(lines, max) {
325
+ return lines.length > max ? [...lines.slice(0, max), more(lines.length - max)] : lines;
326
+ }
327
+
328
+ /** Both ends of what a command printed, and how many lines lie between: a run says how it went in its last lines. */
329
+ function ends(lines, full) {
330
+ if (full || lines.length <= SHOWN_HEAD_LINES + SHOWN_TAIL_LINES) return lines;
331
+ return [...lines.slice(0, SHOWN_HEAD_LINES), more(lines.length - SHOWN_HEAD_LINES - SHOWN_TAIL_LINES), ...lines.slice(-SHOWN_TAIL_LINES)];
332
+ }
333
+
334
+ /** A path as a person reads it: under the home directory, from `~`. */
335
+ export const tilde = (path, home = homedir()) => (path === home ? '~' : String(path).startsWith(`${home}${sep}`) ? `~${String(path).slice(home.length)}` : String(path));
336
+
337
+ /** 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) => (cwd && path === cwd ? '.' : cwd && String(path).startsWith(`${cwd}${sep}`) ? String(path).slice(cwd.length + 1) : tilde(path));
339
+
340
+ /** 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'] };
342
+
343
+ const toned = (text, tone) => String(text).split('\n').map((t) => ({ text: t, tone }));
344
+ const count = (text) => [{ text: `${text === '' ? 0 : text.replace(/\n$/, '').split('\n').length} lines`, tone: 'dim' }];
345
+
346
+ /**
347
+ * 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
+ * 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. Folded, a big change keeps the top of each side, so what came is never folded away whole.
350
+ */
351
+ function diffView(old, now, line, full) {
352
+ const was = old === '' ? [] : old.replace(/\r\n/g, '\n').split('\n');
353
+ const is = now === '' ? [] : now.replace(/\r\n/g, '\n').split('\n');
354
+ let head = 0;
355
+ while (head < was.length && head < is.length && was[head] === is[head]) head++;
356
+ let tail = 0;
357
+ while (tail < was.length - head && tail < is.length - head && was.at(-1 - tail) === is.at(-1 - tail)) tail++;
358
+ const went = was.slice(head, was.length - tail);
359
+ const came = is.slice(head, is.length - tail);
360
+ const wide = line === null ? 0 : String(line + Math.max(was.length, is.length)).length;
361
+ const row = (n, sign, text, tone) => ({ text: line === null ? `${sign} ${text}` : `${String(line + n).padStart(wide)} ${sign} ${text}`, tone });
362
+ const fold = (rows) => (full || went.length + came.length <= SHOWN_DIFF_LINES ? rows : top(rows, SHOWN_DIFF_LINES / 2));
363
+ return {
364
+ at: line === null ? null : line + head,
365
+ stat: { added: came.length, removed: went.length },
366
+ lines: [
367
+ ...(head > 0 ? [row(head - 1, ' ', was[head - 1], 'dim')] : []),
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
+ ],
372
+ };
373
+ }
374
+
375
+ /**
376
+ * A tool call for the screen: what ran, and under it the part of the result
377
+ * worth a glance — both ends of a command's output, an edit as a diff, a read
378
+ * or a write as its size. Without a result it is the call alone; `full` is
379
+ * every line, the command whole, and the file itself for a read or a write.
380
+ * `cwd` is the project the work is in: a file in it is named from there.
381
+ */
382
+ export function toolView(call, result = null, { full = false, cwd = null } = {}) {
383
+ const input = call.input ?? {};
384
+ // Folded, the empty lines of what came back are not shown: three of five lines spent on nothing say nothing.
385
+ const output = (content = result.content) => {
386
+ const lines = toned(content, result.isError ? 'error' : 'plain');
387
+ if (full) return lines;
388
+ const said = lines.filter((line) => line.text.trim() !== '');
389
+ return said.length === 0 ? [{ text: '(no output)', tone: 'dim' }] : ends(said, false);
390
+ };
391
+ if (call.name === BASH_TOOL.name) {
392
+ // Folded, the command is its first lines; asked for in full, it is all there: nothing else on the screen says what ran.
393
+ // A command that begins by going to the project says nothing by it — the shell starts there — and is shown without that.
394
+ const whole = String(input.command ?? '').trim();
395
+ const there = cwd && !full ? new RegExp(`^cd\\s+(["']?)${cwd.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/?\\1\\s*(?:&&|;)\\s*`) : null;
396
+ const command = (there && whole.replace(there, '')) || whole;
397
+ const start = command.split('\n').slice(0, SHOWN_COMMAND_LINES).join('\n').slice(0, SHOWN_COMMAND_CHARS);
398
+ const detail = full || start.length === command.length ? command : `${start} …`;
399
+ if (!result) return { title: 'Bash', detail, lines: [] };
400
+ if (result.content === '') return { title: 'Bash', detail, lines: [{ text: '(no output)', tone: 'dim' }] };
401
+ return { title: 'Bash', detail, lines: output() };
402
+ }
403
+ 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: [] };
406
+ // 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() };
409
+ // A job that ran: how it went in one line, then the top of what it reported.
410
+ const { job } = result;
411
+ const [mark, said, tone] = JOB_ENDS[job.status] ?? JOB_ENDS.open;
412
+ const route = job.effort && job.effort !== 'none' ? `${job.model}/${job.effort}` : job.model;
413
+ // How long it took comes first: it is what the wait was.
414
+ 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)] };
418
+ }
419
+ if (isMcpTool(call.name)) {
420
+ // A server's tool: the server as the title, the tool with its input as the detail, what came back under it.
421
+ const { server, tool } = splitMcpName(call.name);
422
+ const detail = `${tool}(${compactInput(input)})`;
423
+ if (!result) return { title: server, detail, lines: [] };
424
+ // The line that tells the model whose data this is: here the title says it.
425
+ return { title: server, detail, lines: output(unlabeled(result.content)) };
426
+ }
427
+ if (isWebTool(call)) {
428
+ // The web: what was searched for or which page was read, and under it the pages found or the page and its size.
429
+ const detail = String(input.query ?? input.url ?? '').slice(0, SHOWN_COMMAND_CHARS);
430
+ return { title: call.name === WEB_SEARCH_TOOL.name ? 'Search' : 'Fetch', detail, lines: result ? output() : [] };
431
+ }
432
+ if (isAdvisorTool(call)) {
433
+ // 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: 'Advisor', detail: String(input.asked ?? ''), lines: result ? output() : [] };
435
+ }
436
+ if (call.name !== EDITOR_TOOL.name) {
437
+ // A job's own tools: what it was given in a line, what came back under it.
438
+ const given = String(input.status ?? input.query ?? input.question ?? input.text ?? '').split('\n')[0].slice(0, 80);
439
+ if (!result) return { title: call.name, detail: given, lines: [] };
440
+ return { title: call.name, detail: given, lines: output() };
441
+ }
442
+ const range = Array.isArray(input.view_range) ? `:${input.view_range.join('-')}` : '';
443
+ const title = input.command === 'view' ? 'Read' : input.command === 'create' ? 'Write' : input.command === 'str_replace' || input.command === 'insert' ? 'Update' : call.name;
444
+ const detail = `${pathFrom(input.path ?? '', cwd)}${range}`;
445
+ if (!result) return { title, detail, lines: [] };
446
+ if (result.isError) return { title, detail, lines: output() };
447
+ const added = (text) => toned(text, 'add').map((l) => ({ ...l, text: `+ ${l.text}` }));
448
+ 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 ?? '')) };
450
+ // 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
+ const came = input.command === 'insert' ? (input.insert_text ?? input.new_str ?? '').replace(/\n$/, '') : (input.new_str ?? '');
452
+ const edit = result.edit ?? { line: null, old: input.command === 'str_replace' ? (input.old_str ?? '') : '', new: came };
453
+ 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 };
455
+ }
456
+
457
+ /**
458
+ * 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
+ * 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
+ */
461
+ export function transcript(log, s, { width = MAX_WIDTH, cwd = null } = {}) {
462
+ const tones = { plain: (t) => t, dim: s.dim, error: s.red, add: s.green, del: s.red, ask: s.yellow };
463
+ const under = (lines) => lines.map((line, i) => `${i === 0 ? ' ⎿ ' : ' '}${(tones[line.tone] ?? tones.plain)(untab(line.text))}`);
464
+ const out = [];
465
+ for (const entry of log) {
466
+ if (entry.kind === 'user') out.push('', ...untab(entry.text).split('\n').map((line) => `${s.yellow('┃')} ${line}`));
467
+ else if (entry.kind === 'reply') {
468
+ const drawn = [];
469
+ const reply = createRenderer((text) => drawn.push(text), s, { width: Math.max(MIN_WIDTH, width - 3) });
470
+ reply.write(entry.raw);
471
+ reply.flush();
472
+ out.push('', ...drawn.join('').replace(/\n$/, '').split('\n').map((line, i) => `${i === 0 ? '⏺ ' : ' '}${line}`));
473
+ } else if (entry.kind === 'tool') {
474
+ const view = toolView(entry.call, entry.result, { full: true, cwd });
475
+ const stat = view.stat ? ` ${s.green(`+${view.stat.added}`)} ${s.red(`−${view.stat.removed}`)}` : '';
476
+ 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
+ } 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('', `⏺ ${s.bold(`j${entry.id}`)} ${entry.agent} · ${entry.route} — ${entry.title}`);
479
+ else if (entry.kind === 'error') out.push('', s.red(entry.text));
480
+ else if (entry.kind === 'footer') out.push('', s.dim(` ${entry.text}`));
481
+ else if (entry.kind === 'note') out.push(s.dim(` ⎿ ${entry.text.split('\n').join('\n ')}`));
482
+ }
483
+ return `${out.join('\n').replace(/^\n/, '')}\n`;
484
+ }
485
+
486
+ 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
+
488
+ /**
489
+ * The memory block for the user's eyes: tags dropped, labels bold, ids dim,
490
+ * questions yellow, warnings red, a blank line between sections, long lines
491
+ * wrapped under their label.
492
+ */
493
+ export function renderBlock(block, s, { width = MAX_WIDTH } = {}) {
494
+ const out = [];
495
+ let previous = null;
496
+ for (const raw of block.split('\n')) {
497
+ if (/^<\/?sumo-memory/.test(raw) || raw.trim() === '') continue;
498
+ const kind = kindOf(raw);
499
+ // A section is a run of items under their heading; anything else starts one of its own.
500
+ if (previous !== null && kind !== 'item' && !(kind === previous && kind !== raw)) out.push('');
501
+ previous = kind;
502
+ const label = /^([A-Z][a-z]+(?: [a-z]+)*)(\s*\(.*\))?:\s*(.*)$/.exec(raw);
503
+ const item = /^- (m\d+)\s+(.*)$/.exec(raw);
504
+ if (kind === 'ask') out.push(s.yellow(wrap(raw, width, ' ')));
505
+ else if (kind === 'warning') out.push(s.red(wrap(raw, width, ' ')));
506
+ else if (item) out.push(wrap(` ${s.dim(item[1])} ${item[2]}`, width, ' '));
507
+ else if (label) out.push(wrap(`${s.bold(label[1])}${s.dim(`${label[2] ?? ''}:`)}${label[3] ? ` ${label[3]}` : ''}`, width, ' '));
508
+ else out.push(wrap(raw, width, ' '));
509
+ }
510
+ return out.join('\n');
511
+ }
512
+
513
+ /** The line above the memory block: which model is answering, how hard it thinks, where the work is. */
514
+ export function header({ route, cwd }, s) {
515
+ return `${s.bold(s.green('sumo'))} ${s.dim('route')} ${route} ${s.dim(cwd)}`;
516
+ }
517
+
518
+ /** The prompt: the model and effort kept in view, the size of the context once it matters. */
519
+ export function prompt({ route, contextTokens }, s) {
520
+ const k = contextTokens >= 1000 ? ` ${Math.round(contextTokens / 1000)}k` : '';
521
+ return `${s.bold(s.green('sumo'))}${s.dim(` ${route}${k}`)}${s.bold('>')} `;
522
+ }
523
+
524
+ /**
525
+ * Text from a job — what a model wrote, what a command printed — made safe to put on a terminal: colours are kept,
526
+ * every other control character and escape is dropped, so nothing in it can write the clipboard, retitle the window
527
+ * or clear the screen of whoever is watching.
528
+ */
529
+ export const safeForTerminal = (text) => String(text).replace(/\x1b\[[0-9;]*m|[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, (m) => (m.length > 1 ? m : ''));