sumo-agents 0.5.0 → 0.7.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/text.mjs CHANGED
@@ -25,6 +25,16 @@ export function ftsQuery(text) {
25
25
  /** Han, Hiragana, Katakana and Hangul: scripts whose words run on into the next, or into what is joined to them. */
26
26
  const CJK = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
27
27
 
28
+ /**
29
+ * The same words as an expression that wants every one of them (AND): what a search tries first, `ftsQuery` being what
30
+ * it falls back on. Words in Chinese, Japanese or Korean are left out — the index keeps a run of them as one word, so
31
+ * the caller looks for those in the text itself (`cjkTerms`). Empty when no other word is left.
32
+ */
33
+ export function ftsAllQuery(text) {
34
+ const unique = [...new Set(words(text))].filter((w) => !CJK.test(w));
35
+ return unique.map((w) => `"${w.replaceAll('"', '""')}"`).join(' AND ');
36
+ }
37
+
28
38
  /**
29
39
  * The words of a search in Chinese, Japanese or Korean. The index keeps a run of such characters as one word —
30
40
  * "日本語のテスト" is a single token — so a word inside it is never matched there; these are looked for in the text
@@ -59,6 +69,19 @@ export function overlap(a, b) {
59
69
  return shared / Math.min(sa.size, sb.size);
60
70
  }
61
71
 
72
+ /**
73
+ * Share of `text`'s own stems also found in `source`: 0..1. Not `overlap`, which takes the smaller text's share: a
74
+ * long sentence is not about a three-word one because those three words are in it.
75
+ */
76
+ export function coverage(text, source) {
77
+ const its = new Set(words(text).map(stem));
78
+ const theirs = new Set(words(source).map(stem));
79
+ if (its.size === 0) return 0;
80
+ let shared = 0;
81
+ for (const s of its) if (theirs.has(s)) shared++;
82
+ return shared / its.size;
83
+ }
84
+
62
85
  /** How much of what a memory says must be in the user's own words for it to be theirs. */
63
86
  const SAID_SHARE = 0.8;
64
87
  /**
@@ -68,8 +91,6 @@ const SAID_SHARE = 0.8;
68
91
  const NEGATION = /\b(?:never|not|no|none|avoid|without|cannot|dont|doesnt|didnt|wont|cant|isnt|arent|shouldnt|mustnt)\b|\b\w+n['’]t\b/i;
69
92
  /** A trailing "…, not B" or "…, never B", B a word or three: the alternative a statement is chosen over. */
70
93
  const ALTERNATIVE = /[,;]\s*(?:but\s+)?(?:not|never)\s+([\w.@/+-]+(?:\s+[\w.@/+-]+){0,2})\s*\.?\s*$/i;
71
- /** Whether a text is nothing but such an alternative — "never npm" — with no statement of its own to turn round. */
72
- export const onlyAlternative = (text) => /^\s*(?:but\s+)?(?:not|never)\s+[\w.@/+-]+(?:\s+[\w.@/+-]+){0,2}\s*\.?\s*$/i.test(text);
73
94
  /** Whether a text sets `alt` aside itself: moved "from" it, chose "instead of", "rather than" or "over" it, or said "not" it. */
74
95
  const setsAside = (text, alt) => {
75
96
  const said = alt.replace(/[.*+?^${}()|[\]\\]/g, (c) => `\\${c}`);
@@ -80,12 +101,69 @@ const withoutAlternative = (text, other) => {
80
101
  const m = ALTERNATIVE.exec(text);
81
102
  return m && setsAside(other, m[1].replace(/\.+$/, '')) ? text.slice(0, m.index) : text;
82
103
  };
104
+ /** "on" or "off" as a switch's state — turned on, kept off, "is off" ending its clause — never the "on" of "on fridays". */
105
+ const switched = (state) =>
106
+ new RegExp(`\\b(?:turn(?:ed|s|ing)?|switch(?:ed|es|ing)?)\\s+(?:[\\w-]+\\s+){0,3}?${state}\\b|\\b(?:is|are|be|stays?|left|leave|keeps?|kept)\\s+(?:[\\w-]+\\s+){0,3}?${state}\\b(?=\\s+(?:in|by|for|at|when|while|during|everywhere)\\b|\\s*[,.;!?]|\\s*$)`, 'i');
107
+ /**
108
+ * Words that turn a rule round with no negation between them: "disabled" filed from "enabled" is as much the opposite
109
+ * as "never" from "always" (an independent review, Nov 18 2026, filed each of these from the user's own quote).
110
+ */
111
+ const OPPOSITES = [
112
+ [/\benabl(?:e|es|ed|ing)\b/i, /\bdisabl(?:e|es|ed|ing)\b/i],
113
+ [/\b(?:allow(?:s|ed|ing)?|permit(?:s|ted|ting)?)\b/i, /\b(?:forbid(?:s|den|ding)?|prohibit(?:s|ed|ing)?|disallow(?:s|ed|ing)?|block(?:s|ed|ing)?)\b/i],
114
+ [/\bbefore\b/i, /\bafter\b/i],
115
+ [/\badd(?:s|ed|ing)?\b/i, /\bremov(?:e|es|ed|ing)\b/i],
116
+ [switched('on'), switched('off')],
117
+ ];
118
+ /** Whether one text holds one side of a pair and the other text only the other side: both sides in one text is no turn. */
119
+ const opposite = (a, b) =>
120
+ OPPOSITES.some(([one, other]) => {
121
+ const [a1, a2, b1, b2] = [one.test(a), other.test(a), one.test(b), other.test(b)];
122
+ return (a1 && !a2 && b2 && !b1) || (a2 && !a1 && b1 && !b2);
123
+ });
124
+
125
+ /** A text's words with what a name or a version is written with kept in them: `3.12`, `feature/login`, `node-22`. */
126
+ const named = (text) => (text.toLowerCase().match(/[\p{L}\p{N}_][\p{L}\p{N}_./+-]*/gu) ?? []).map((w) => w.replace(/[./+-]+$/, ''));
127
+ const DETERMINERS = new Set(['the', 'a', 'an', 'our', 'my', 'your', 'their']);
128
+ /**
129
+ * The values a text names where one can be told from prose: the word before "branch", a word with a digit (with the
130
+ * word before it — "node 22"), and what is used ("uses pnpm"). Narrow on purpose: a synonym elsewhere is a paraphrase.
131
+ */
132
+ function valuesNamed(text) {
133
+ const all = named(text);
134
+ const out = { branch: [], version: [], tool: [] };
135
+ all.forEach((w, i) => {
136
+ if (w === 'branch' && i > 0 && !STOPWORDS.has(all[i - 1])) out.branch.push({ value: all[i - 1], after: '' });
137
+ if (/\d/.test(w) && i > 0) out.version.push({ value: w, after: stem(all[i - 1]) });
138
+ if (/^us(?:e|es|ed|ing)$/.test(w)) {
139
+ let next = i + 1;
140
+ while (DETERMINERS.has(all[next])) next++;
141
+ if (all[next] && !STOPWORDS.has(all[next])) out.tool.push({ value: all[next], after: '' });
142
+ }
143
+ });
144
+ return { all: new Set(all.map(stem)), ...out };
145
+ }
146
+ /**
147
+ * Whether `a` names a branch, a version or a tool that `b` nowhere holds, where `b` names another: "the release
148
+ * branch" from "the main branch", "node 20" from "node 22", "uses npm" from "uses pnpm". A value `b` holds anywhere is
149
+ * the user's own — "uses bun" from "we moved from pnpm to bun".
150
+ */
151
+ function namesAnother(a, b) {
152
+ const [its, theirs] = [valuesNamed(a), valuesNamed(b)];
153
+ return ['branch', 'version', 'tool'].some((kind) => its[kind].some((v) => !theirs.all.has(stem(v.value)) && theirs[kind].some((t) => t.after === v.after)));
154
+ }
155
+
83
156
  /**
84
157
  * Whether two texts say a thing the same way round: both negate it, or neither does. "slate uses bun, not pnpm" from "we
85
158
  * moved from pnpm to bun" is not a turn — the "not" sets aside what they moved from; "never force-push" is, from "force-push
86
- * freely", which set nothing aside. `aside` is where `a`'s alternative is looked for, when `b` is only part of what was said.
159
+ * freely", which set nothing aside. Nor is it the same way round when one says the opposite in a word (`OPPOSITES`) or
160
+ * names another value (`namesAnother`). `aside` is the whole of what was said, when `b` is only part of it: where
161
+ * `a`'s alternative and the values it names are looked for.
87
162
  */
88
- export const sameWayRound = (a, b, aside = b) => NEGATION.test(withoutAlternative(a, aside)) === NEGATION.test(withoutAlternative(b, a));
163
+ export const sameWayRound = (a, b, aside = b) => {
164
+ const [said, typed] = [withoutAlternative(a, aside), withoutAlternative(b, a)];
165
+ return NEGATION.test(said) === NEGATION.test(typed) && !opposite(said, typed) && !namesAnother(a, aside);
166
+ };
89
167
 
90
168
  /**
91
169
  * Whether what the user typed says what a memory says: nearly all of the memory's own words are in theirs — not a
@@ -105,6 +183,16 @@ export function sharedStems(a, b) {
105
183
  return [...new Set(words(a).map(stem))].filter((s) => sb.has(s)).length;
106
184
  }
107
185
 
186
+ /**
187
+ * How many of a search's distinct words a text holds: by stem, and for a Chinese, Japanese or Korean word by its
188
+ * characters anywhere in the text, as it is searched.
189
+ */
190
+ export function termsHeld(query, text) {
191
+ const lower = text.toLowerCase();
192
+ const stems = new Set(words(text).map(stem));
193
+ return [...new Set(words(query))].filter((w) => (CJK.test(w) ? lower.includes(w) : stems.has(stem(w)))).length;
194
+ }
195
+
108
196
  /**
109
197
  * Deliberately a heuristic: an exact count needs a tokenizer, and these numbers
110
198
  * only have to keep a generated block under its budget.
@@ -130,10 +218,10 @@ export function clip(text, max) {
130
218
  return flat.length <= max ? flat : `${head(flat, max - 1)}…`;
131
219
  }
132
220
 
133
- /** Words that mark a sentence as a standing instruction, which is worth filing right away rather than in the next batch. */
221
+ /** Words that mark a sentence as a standing instruction: whatever else it does, it is not only a request for work. */
134
222
  const DURABLE = /\b(always|never|from now on|going forward|remember|don'?t ever|i (prefer|like|want(?! to\b)|hate|use)|we (use|moved|switched|decided)|make sure|by default|every time|stop (doing|using))\b/i;
135
223
 
136
- export const looksDurable = (text) => DURABLE.test(text);
224
+ const looksDurable = (text) => DURABLE.test(text);
137
225
 
138
226
  /**
139
227
  * A clause that asks for work or an answer — describe this, fix that, delegate, a question — rather than stating
@@ -177,6 +265,30 @@ export const asksForWork = (text) => {
177
265
  return REQUEST.test(said) || sentences.some((x) => oneChange(x) || ANSWER_OR_SWITCH.test(x.replace(LEADING, '')));
178
266
  };
179
267
 
268
+ /** Words that agree, thank or wave on, and nouns that only stand for something said before: none of them is what a sentence is about. */
269
+ const EMPTY_WORDS = new Set(
270
+ `ok okay yes yeah yep yup sure please pls thanks thank good great fine nice cool perfect right agreed sounds sound looks look seems
271
+ works go ahead just well plan idea approach option suggestion proposal thing way one same lets let`.split(/\s+/),
272
+ );
273
+ /** Words that point at something said elsewhere. */
274
+ const POINTS = /\b(?:it|this|that|these|those|them|so|same)\b/i;
275
+ /** A sentence whose whole statement is approval. */
276
+ const APPROVES = /\b(?:sounds?|looks?|seems?)\s+(?:good|great|fine|right|ok|okay|perfect|nice)\b|\bworks\s+for\s+me\b|\b(?:that|it|this)(?:'s|\s+is)\s+(?:good|great|fine|right|ok|okay|perfect)\b/i;
277
+
278
+ /**
279
+ * Whether a sentence says something by itself, so it can be a memory when stored as typed. "ok that plan sounds
280
+ * good", "yes do that always" and "use it" are the user's words and say nothing: what they agree to or point at was
281
+ * said by someone else. Not so when nothing is left once the words of agreement are taken out, when what is left is
282
+ * under three words beside a pointing word, or when the sentence only approves and gives no rule of its own. A short
283
+ * rule stands: "no emojis", "never push to main".
284
+ */
285
+ export function standsAlone(sentence) {
286
+ const content = new Set(words(sentence).filter((w) => !STOPWORDS.has(w) && !EMPTY_WORDS.has(w)).map(stem));
287
+ if (content.size === 0) return false;
288
+ if (content.size < 3 && POINTS.test(sentence)) return false;
289
+ return !(APPROVES.test(sentence) && !looksDurable(sentence));
290
+ }
291
+
180
292
  /**
181
293
  * The known name a mistyped one was most likely meant to be: two edits away at most, nearer than any other, and with
182
294
  * at least half of what was typed kept — `m` is no guess at `mcp`, nor `xml` at `md`; `serch` is at `search`.
package/src/tools.mjs CHANGED
@@ -5,6 +5,7 @@ import { delimiter, dirname, extname, join, relative, resolve, sep } from 'node:
5
5
  import { CREDENTIAL_NAMES } from './auth.mjs';
6
6
  import { guardCommand, guardPath } from './guard.mjs';
7
7
  import { SELF } from './paths.mjs';
8
+ import { readPlainFile } from './scan.mjs';
8
9
  import { redact } from './redact.mjs';
9
10
  import { blockedWrite, guardedPlaces, guardedWhy, readOnlyPlaces, sandboxWrap, unsandboxable, writablePlaces } from './sandbox.mjs';
10
11
 
@@ -710,8 +711,13 @@ async function blocked(command, shown, ctx, jail, options) {
710
711
  const BINARY_PROBE_BYTES = 8192;
711
712
 
712
713
  function view(path, range) {
713
- if (statSync(path).isDirectory()) return result(cap(readdirSync(path).join('\n')));
714
- const bytes = readFileSync(path);
714
+ let bytes;
715
+ try {
716
+ bytes = readFileSync(path);
717
+ } catch (cause) {
718
+ if (cause.code === 'EISDIR') return result(cap(readdirSync(path).join('\n')));
719
+ throw cause;
720
+ }
715
721
  // A binary shown as text is pages of nonsense, every page billed: say what it is instead.
716
722
  if (bytes.subarray(0, BINARY_PROBE_BYTES).includes(0)) return result(`${path} is a binary file (${bytes.length} bytes) — not shown; use a tool that reads its kind, or \`file\` and \`xxd | head\` for a look`, true);
717
723
  const lines = bytes.toString('utf8').split('\n');
@@ -948,9 +954,9 @@ function change(path, ctx, write, { created = false } = {}) {
948
954
  }
949
955
 
950
956
  /** A whole line that is one comment — `//`, `#`, `/* *\/`, `<!-- -->`, `--`, JSX's `{/* *\/}` — and what it says. */
951
- const COMMENT_LINE = /^(?:\/\/+|#+|\/\*+|<!--|--|\{\/\*+)\s*(.*?)\s*(?:\*+\/\}?|-->)?$/;
952
- /** The block comments that close on their line: only dots in one is a gap left in the code, where `// ...` alone may be a deliberate stub. */
953
- const CLOSED_COMMENT = /(?:\*\/\}?|-->)$/;
957
+ const COMMENT_LINE = /^(?:\/\/+|#+|\/\*+|<!--|--|\{\/\*+)\s*(.*?)\s*(?:\*+\/\}?|--!?>)?$/;
958
+ /** The block comments that close on their line (HTML's closes on `--!>` too): only dots in one is a gap left in the code, where `// ...` alone may be a deliberate stub. */
959
+ const CLOSED_COMMENT = /(?:\*\/\}?|--!?>)$/;
954
960
  const DOTS = /\.{3,}|…/g;
955
961
  /** That what was left out stays as it was: optional after `rest of the code`; needed after `other methods` with no dots around it, which could be a heading. */
956
962
  const STAYS = String.raw`(?:\s+(?:is\s+|are\s+|stays\s+|remains\s+|goes\s+)?(unchanged|the same|as before|as is|omitted|here|goes here|follows|not shown))?`;
@@ -1143,8 +1149,13 @@ export function runEditor(input, ctx) {
1143
1149
  const gap = placeholderIn(path, 'file_text', input.file_text);
1144
1150
  if (gap) return result(gap, true);
1145
1151
  // The write below refuses a file that is there anyway; said here in words that tell the model what to do instead.
1146
- if (existsSync(path) && statSync(path).isFile()) {
1147
- const held = readFileSync(path, 'utf8');
1152
+ let held = null;
1153
+ try {
1154
+ held = readPlainFile(path);
1155
+ } catch {
1156
+ // Not there: made below.
1157
+ }
1158
+ if (held !== null) {
1148
1159
  const lines = held.split('\n').length - (held.endsWith('\n') ? 1 : 0);
1149
1160
  return result(`${path} already exists (${lines} line${lines === 1 ? '' : 's'}): change the lines that change with str_replace or insert — a file is never rewritten whole`, true);
1150
1161
  }
@@ -1,10 +1,10 @@
1
1
  import { closeSync, fstatSync, openSync, readSync } from 'node:fs';
2
- import { redact } from './redact.mjs';
3
2
  import { head } from './text.mjs';
4
3
 
5
4
  /**
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.
5
+ * How much of a reply the memory pass is shown. Generous on purpose: the closing reply of a piece of work is where
6
+ * the traps it hit are mentioned, usually mid-paragraph. At 400 characters a real "tests only pass with SIMBA_TZ set"
7
+ * was cut out.
8
8
  */
9
9
  const REPLY_MAX = 1200;
10
10
 
@@ -60,47 +60,3 @@ export function readBackwards(file, enough) {
60
60
  return null;
61
61
  }
62
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 CHANGED
@@ -20,29 +20,17 @@ const CODES = { bold: ['1', '22'], dim: ['2', '22'], italic: ['3', '23'], underl
20
20
 
21
21
  /**
22
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.
23
+ * reader says as itself: no box drawing, no symbol spelled out by its Unicode name.
25
24
  */
26
25
  const GLYPHS = {
27
- fail: '✗', pick: '›', ask: '?', live: '•', spin: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'], bar: '│', quote: '│', rule: '─', fenceOpen: '┌─', fenceClose: '└─', todo: '☐', done: '☑', bullet: '•',
26
+ tool: '⏺', fail: '✗', pick: '❯', under: '⎿', bar: '┃', quote: '│', rule: '─', fenceOpen: '┌─', fenceClose: '└─', todo: '☐', done: '☑', bullet: '•', warn: '⚠', thought: '✻',
28
27
  box: { h: '─', v: '│', tl: '┌', tm: '┬', tr: '┐', ml: '├', mm: '┼', mr: '┤', bl: '└', bm: '┴', br: '┘' },
29
28
  };
30
29
  const PLAIN_GLYPHS = {
31
- fail: 'x', pick: '>', ask: '?', live: '*', spin: ['*'], bar: '|', quote: '|', rule: '-', fenceOpen: '+-', fenceClose: '+-', todo: '[ ]', done: '[x]', bullet: '-',
30
+ tool: '*', fail: 'x', pick: '>', under: '|', bar: '>', quote: '|', rule: '-', fenceOpen: '+-', fenceClose: '+-', todo: '[ ]', done: '[x]', bullet: '-', warn: '!', thought: '*',
32
31
  box: { h: '-', v: '|', tl: '+', tm: '+', tr: '+', ml: '+', mm: '+', mr: '+', bl: '+', bm: '+', br: '+' },
33
32
  };
34
33
 
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
-
46
34
  const MAX_WIDTH = 100;
47
35
  const MIN_WIDTH = 40;
48
36
 
@@ -207,7 +195,7 @@ export function highlight(line, lang, s, code = null) {
207
195
  state.comment = false;
208
196
  }
209
197
  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, '\\/')}.*` : '(?!)';
198
+ const comment = language.line === '#' ? '(?:^|(?<=\\s))#.*' : language.line ? `${language.line.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')}.*` : '(?!)';
211
199
  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
200
  pattern.lastIndex = at;
213
201
  for (let m; (m = pattern.exec(line)); ) {
@@ -489,6 +477,24 @@ const MESSAGE_MS = 5000;
489
477
  /** The working message `elapsed` ms into work that opened on `first`: the next in the file every five seconds, round and round. */
490
478
  export const messageAt = (messages, first, elapsed) => messages[(Math.max(0, messages.indexOf(first)) + Math.floor(elapsed / MESSAGE_MS)) % messages.length];
491
479
 
480
+ /** The chat's colours: gold, into orange, into crimson. */
481
+ const SUNSET = [[0xff, 0xd1, 0x66], [0xf7, 0x7f, 0x00], [0xd6, 0x28, 0x28]];
482
+
483
+ /** The colour `t` of the way through the sunset, 0 its gold and 1 its crimson. */
484
+ export function sunset(t) {
485
+ const at = Math.min(Math.max(t, 0), 1) * (SUNSET.length - 1);
486
+ const i = Math.min(Math.floor(at), SUNSET.length - 2);
487
+ return `#${SUNSET[i].map((v, k) => Math.round(v + (SUNSET[i + 1][k] - v) * (at - i)).toString(16).padStart(2, '0')).join('')}`;
488
+ }
489
+
490
+ const FLOW_LENGTH = 24;
491
+
492
+ /** 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. */
493
+ export function flow(i, frame) {
494
+ const step = (((i - frame) % FLOW_LENGTH) + FLOW_LENGTH) % FLOW_LENGTH;
495
+ return sunset(1 - Math.abs(1 - (2 * step) / FLOW_LENGTH));
496
+ }
497
+
492
498
  /** What the chat draws faint in the empty room above the box you type in: yours, in logo.txt at the top of the repo. */
493
499
  const LOGO_FILE = join(REPO_ROOT, 'logo.txt');
494
500
 
@@ -646,6 +652,47 @@ function readable(text, cwd = null, { headings = 'drop' } = {}) {
646
652
  return lines;
647
653
  }
648
654
 
655
+ /** The most of a failed command's failing lines a folded result shows. */
656
+ const SHOWN_FAILING_LINES = 4;
657
+ /** The last lines of a failed command, always shown: the exit code, why it was stopped, what the user said declining it. */
658
+ const SHOWN_FAILED_TAIL = 2;
659
+ /** A line that says what failed: a test runner's cross, an assertion, an error, a panic, a rejection. */
660
+ const FAILING = /[✖✗×]|^\s*not ok\b|\bFAIL(?:ED|S)?\b|\b(?:failed|failing|failure|rejected)\b|\b(?:Error|Exception|panic)\b|\berror(?:\[|:)|\bexpected\b.+\bto\b/;
661
+ /** A line a runner marks as passed: never a line that says what failed, whatever the test's name says. */
662
+ const PASSING = /^\s*(?:[✔✓√]|ok\b|PASS\b)/;
663
+ /** A command that runs tests: only its count is read as how a run went — a grep that finds "12 passed" is a grep. */
664
+ const TESTS = /\b(?:test|tests|spec|pytest|jest|vitest|mocha|ava|rspec|phpunit|check)\b/;
665
+ /** How test runners count what passed: node --test, TAP, jest/vitest/pytest/cargo, mocha. */
666
+ const PASSED = [/^ℹ pass (\d+)$/m, /^# pass (\d+)$/m, /\b(\d+) passed\b/, /\b(\d+) passing\b/];
667
+ /** A count of what failed beside it: a run that exits 0 — piped to tail, `|| true` — may still have failed. */
668
+ const FAILED = /^ℹ fail [1-9]|^# fail [1-9]|\b[1-9]\d* (?:failed|failing|errors?)\b|\bFAILED\b/m;
669
+ /** The last lines of what a command printed where a test runner's count is looked for. */
670
+ const COUNT_LINES = 8;
671
+
672
+ /**
673
+ * What a command printed, folded to what says how it went. A failure shows the lines that say what failed — a test's
674
+ * cross, an assertion, an error — and its last lines, not its banner; a test run that passed is its count, one row.
675
+ * A few lines are shown whole, and anything else shows both ends, as it always did.
676
+ */
677
+ function ranLines(said, failed, command) {
678
+ if (failed) {
679
+ if (said.length <= SHOWN_HEAD_LINES + SHOWN_TAIL_LINES + 1) return said;
680
+ const tail = said.length - SHOWN_FAILED_TAIL;
681
+ const failing = said.slice(0, tail).filter((line) => FAILING.test(line.text) && !PASSING.test(line.text)).slice(0, SHOWN_FAILING_LINES);
682
+ if (failing.length === 0) return ends(said, false);
683
+ return [...failing, more(tail - failing.length), ...said.slice(tail)];
684
+ }
685
+ // A runner prints its count at the end: a count further up is something the command printed, not how it went.
686
+ const text = said.slice(-COUNT_LINES).map((line) => line.text).join('\n');
687
+ if (TESTS.test(command) && !FAILED.test(text)) {
688
+ for (const passed of PASSED) {
689
+ const n = Number(passed.exec(text)?.[1] ?? 0);
690
+ if (n > 0) return [{ text: `✓ ${n} passed`, tone: 'add' }];
691
+ }
692
+ }
693
+ return ends(said, false);
694
+ }
695
+
649
696
  /**
650
697
  * A tool call for the screen: what ran, and under it the part of the result
651
698
  * worth a glance — both ends of a command's output, an edit as a diff, a read
@@ -661,7 +708,7 @@ export function toolView(call, result = null, { full = false, cwd = null } = {})
661
708
  if (!full && typeof result?.shown === 'string') result = { ...result, content: result.shown };
662
709
  const input = call.input ?? {};
663
710
  // Folded, the empty lines of what came back are not shown: three of five lines spent on nothing say nothing.
664
- const output = (content = result.content) => {
711
+ const output = (content = result.content, folded = (said) => ends(said, false)) => {
665
712
  const lines = toned(content, result.isError ? 'error' : 'plain');
666
713
  // What reads as a diff — `git diff`, a patch — is drawn as one: what went red, what came green.
667
714
  if (!result.isError && /^(?:diff --git |@@ -\d)/m.test(content)) for (const line of lines) line.tone = /^\+(?!\+\+ )/.test(line.text) ? 'add' : /^-(?!-- )/.test(line.text) ? 'del' : line.tone;
@@ -669,7 +716,7 @@ export function toolView(call, result = null, { full = false, cwd = null } = {})
669
716
  // One very long line — a list of paths, a minified file — is cut to a few rows, not left to fill the window.
670
717
  for (const line of lines) if (line.text.length > LONG_LINE) line.text = `${line.text.slice(0, LONG_LINE - 2)} …`;
671
718
  const said = lines.filter((line) => line.text.trim() !== '');
672
- return said.length === 0 ? [{ text: '(no output)', tone: 'dim' }] : ends(said, false);
719
+ return said.length === 0 ? [{ text: '(no output)', tone: 'dim' }] : folded(said);
673
720
  };
674
721
  if (call.name === BASH_TOOL.name) {
675
722
  // Folded, the command is its first lines; asked for in full, it is all there: nothing else on the screen says what ran.
@@ -679,13 +726,13 @@ export function toolView(call, result = null, { full = false, cwd = null } = {})
679
726
  const command = (there && whole.replace(there, '')) || whole;
680
727
  const start = command.split('\n').slice(0, SHOWN_COMMAND_LINES).join('\n').slice(0, SHOWN_COMMAND_CHARS);
681
728
  const detail = full || start.length === command.length ? command : `${start} …`;
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() };
729
+ if (!result) return { title: 'Bash', detail, lines: [] };
730
+ if (result.content === '') return { title: 'Bash', detail, lines: [{ text: '(no output)', tone: 'dim' }] };
731
+ return { title: 'Bash', detail, lines: output(result.content, (said) => ranLines(said, result.isError, command)) };
685
732
  }
686
733
  if (call.name === DELEGATE_TOOL.name) {
687
734
  // 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';
735
+ const title = input.report ? 'Report' : 'Delegate';
689
736
  const detail = input.job !== undefined ? `j${input.job}${input.report && input.agent ? ` ${input.agent} · ${input.title ?? ''}` : ''}` : `${input.agent ?? 'worker'} · ${input.title ?? ''}`;
690
737
  if (!result) return { title, detail, lines: [] };
691
738
  // 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.
@@ -706,37 +753,35 @@ export function toolView(call, result = null, { full = false, cwd = null } = {})
706
753
  return { title, detail, lines: [{ text: summary, tone }, ...top(report.map((text) => ({ text, tone: 'plain' })), SHOWN_REPORT_LINES)] };
707
754
  }
708
755
  if (isMcpTool(call.name)) {
709
- // A server's tool: the server and the tool with its input as the detail, what came back under it.
756
+ // A server's tool: the server as the title, the tool with its input as the detail, what came back under it.
710
757
  const { server, tool } = splitMcpName(call.name);
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)) };
758
+ const detail = `${tool}(${compactInput(input)})`;
759
+ if (!result) return { title: server, detail, lines: [] };
760
+ // The line that tells the model whose data this is: here the title says it.
761
+ return { title: server, detail, lines: output(unlabeled(result.content)) };
715
762
  }
716
763
  if (isWebTool(call)) {
717
764
  // The web: what was searched for or which page was read, and under it the pages found or the page and its size.
718
765
  const detail = String(input.query ?? input.url ?? '').slice(0, SHOWN_COMMAND_CHARS);
719
- return { title: call.name === WEB_SEARCH_TOOL.name ? 'search' : 'fetch', detail, lines: result ? output() : [] };
766
+ return { title: call.name === WEB_SEARCH_TOOL.name ? 'Search' : 'Fetch', detail, lines: result ? output() : [] };
720
767
  }
721
768
  if (isAdvisorTool(call)) {
722
769
  // 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.
723
- return { title: 'advise', detail: String(input.asked ?? ''), lines: result ? output() : [] };
770
+ return { title: 'Advisor', detail: String(input.asked ?? ''), lines: result ? output() : [] };
724
771
  }
725
772
  if (call.name === ASK_TOOL.name) {
726
773
  // A question put to the user: the question, and under it what they answered.
727
774
  const question = String(input.question ?? '').split('\n')[0];
728
- return { title: 'asked', detail: question, lines: result ? output() : [] };
775
+ return { title: 'Question', detail: question, lines: result ? output() : [] };
729
776
  }
730
777
  if (call.name !== EDITOR_TOOL.name) {
731
778
  // 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.
733
779
  const given = String(input.status ?? input.query ?? input.question ?? input.text ?? '').split('\n')[0].slice(0, 80);
734
- const title = String(call.name).split(/[_-]/)[0];
735
- if (!result) return { title, detail: given, lines: [] };
736
- return { title, detail: given, lines: output() };
780
+ if (!result) return { title: call.name, detail: given, lines: [] };
781
+ return { title: call.name, detail: given, lines: output() };
737
782
  }
738
783
  const range = Array.isArray(input.view_range) ? `:${input.view_range.join('-')}` : '';
739
- const title = input.command === 'view' ? 'read' : input.command === 'create' ? 'write' : input.command === 'str_replace' || input.command === 'insert' ? 'edit' : 'editor';
784
+ const title = input.command === 'view' ? 'Read' : input.command === 'create' ? 'Write' : input.command === 'str_replace' || input.command === 'insert' ? 'Update' : call.name;
740
785
  const detail = `${pathFrom(input.path ?? '', cwd)}${range}`;
741
786
  if (!result) return { title, detail, lines: [] };
742
787
  // Folded, a failure names the file as the title does; in full, it is every word as the model read it.
@@ -788,49 +833,43 @@ const helpLines = (rows, s) => {
788
833
  * The conversation as text for a pager: every entry of the chat's log in full — the whole command, all a tool gave back,
789
834
  * a reply as it is drawn — in the terminal's colours. What the screen folds, this does not; a pager scrolls and searches it.
790
835
  */
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
-
794
836
  export function transcript(log, s, { width = MAX_WIDTH, cwd = null } = {}) {
795
837
  const tones = { plain: (t) => t, dim: s.dim, error: s.red, add: s.green, del: s.red, ask: s.yellow };
796
838
  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}`));
839
+ // Folded here, at the window's width, so a long line goes on under its own words and never back at the edge; each row
840
+ // painted on its own, so a colour never runs on into the margin.
841
+ const under = (lines) =>
842
+ lines
843
+ .flatMap((line) => fold(withSpan(line, s), Math.max(20, width - 6)).map(tones[line.tone] ?? tones.plain))
844
+ .map((row, i) => `${i === 0 ? ` ${g.under} ` : ' '}${row}`);
808
845
  const out = [];
809
846
  for (const entry of log) {
810
- if (entry.kind === 'user') out.push('', `${at('you', (t) => s.bold(s.cyan(t)))}${words(untab(entry.text))}`);
847
+ if (entry.kind === 'user') out.push('', ...untab(entry.text).split('\n').map((line) => `${s.yellow(g.bar)} ${line}`));
811
848
  else if (entry.kind === 'reply') {
812
849
  const drawn = [];
813
- const reply = createRenderer((t) => drawn.push(t), s, { width: Math.max(MIN_WIDTH, width - TEXT_AT) });
850
+ const reply = createRenderer((text) => drawn.push(text), s, { width: Math.max(MIN_WIDTH, width - 3) });
814
851
  reply.write(entry.raw);
815
852
  reply.flush();
816
- out.push('', ...drawn.join('').replace(/\n$/, '').split('\n').map((line, i) => (i === 0 ? `${at('sumo', s.bold)}${line}` : line ? `${' '.repeat(TEXT_AT)}${line}` : '')));
853
+ out.push('', ...drawn.join('').replace(/\n$/, '').split('\n').map((line, i) => `${i === 0 ? `${g.tool} ` : ' '}${line}`));
817
854
  } else if (entry.kind === 'tool') {
818
855
  const view = toolView(entry.call, entry.result, { full: true, cwd });
819
- const stat = view.stat ? ` ${s.green(`+${view.stat.added}`)} ${s.red(`−${view.stat.removed}`)}` : '';
856
+ const stat = statOf(view.stat, s);
820
857
  // 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));
858
+ out.push('', `${entry.result.isError ? s.red(g.fail) : s.green(g.tool)} ${s.bold(view.title)}(${untab(view.detail).split('\n').join('\n ')})${stat}`, ...under(view.lines));
823
859
  } else if (entry.kind === 'shell') out.push(...under(toolView({ name: BASH_TOOL.name }, entry.result, { full: true }).lines));
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)}`);
860
+ else if (entry.kind === 'job') out.push('', `${g.tool} ${s.bold(`j${entry.id}`)} ${entry.agent} · ${entry.route} — ${entry.title}`);
861
+ else if (entry.kind === 'error') out.push('', s.red(`${g.fail} ${entry.text}`), ...(entry.detail ? [s.dim(` ${entry.detail}`)] : []));
862
+ else if (entry.kind === 'thought') out.push('', s.dim(`${g.thought} Thought for ${elapsed(entry.ms)}`), ...String(entry.text ?? '').trim().split('\n').filter(Boolean).map((line) => s.dim(s.italic(` ${line}`))));
863
+ else if (entry.kind === 'footer') out.push('', s.dim(` ${entry.text}`));
828
864
  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)}`);
865
+ else if (entry.kind === 'note') out.push(s.dim(` ${g.under} ${entry.text.split('\n').join('\n ')}`));
830
866
  }
831
867
  return `${out.join('\n').replace(/^\n/, '')}\n`;
832
868
  }
833
869
 
870
+ /** How much an edit added and took away, `+2 −1`: a side that is nothing is not said. */
871
+ export const statOf = (stat, s) => (stat ? [stat.added > 0 ? s.green(`+${stat.added}`) : '', stat.removed > 0 ? s.red(`−${stat.removed}`) : ''].filter(Boolean).map((part) => ` ${part}`).join('') : '');
872
+
834
873
  /** A fence for text that may hold fences of its own: longer than any run of backticks in it. */
835
874
  const fenceFor = (text) => '`'.repeat(Math.max(3, ...[...String(text).matchAll(/`+/g)].map((m) => m[0].length + 1)));
836
875
 
@@ -849,7 +888,7 @@ export function markdownOf(log, { cwd = null, title = 'Sumo' } = {}) {
849
888
  else if (entry.kind === 'reply') out.push('', entry.raw.trim());
850
889
  else if (entry.kind === 'tool') {
851
890
  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'));
891
+ folded(`${view.title}(${view.detail.split('\n')[0]})${entry.result.isError ? ' — failed' : ''}`, view.lines.map((line) => line.text).join('\n'));
853
892
  } else if (entry.kind === 'shell') folded('! command', String(entry.result.content));
854
893
  else if (entry.kind === 'thought') folded(`Thought for ${elapsed(entry.ms)}`, String(entry.text ?? '').trim());
855
894
  else if (entry.kind === 'job') out.push('', `**j${entry.id}** ${entry.agent} · ${entry.route} — ${entry.title}`);
@@ -888,13 +927,13 @@ export function renderBlock(block, s, { width = MAX_WIDTH } = {}) {
888
927
 
889
928
  /** The line above the memory block: which model is answering, how hard it thinks, where the work is. */
890
929
  export function header({ route, cwd }, s) {
891
- return `${s.bold(s.cyan('sumo'.padStart(GUTTER)))} ${route}${s.dim(`${VERSION ? ` · ${VERSION}` : ''} · ${cwd}`)}`;
930
+ return `${s.bold(s.green('sumo'))} ${s.dim('route')} ${route} ${s.dim(cwd)}`;
892
931
  }
893
932
 
894
933
  /** The prompt: the model and effort kept in view, the size of the context once it matters. */
895
934
  export function prompt({ route, contextTokens }, s) {
896
935
  const k = contextTokens >= 1000 ? ` ${Math.round(contextTokens / 1000)}k` : '';
897
- return `${s.bold(s.cyan('sumo'))}${s.dim(` ${route}${k}`)}${s.bold('>')} `;
936
+ return `${s.bold(s.green('sumo'))}${s.dim(` ${route}${k}`)}${s.bold('>')} `;
898
937
  }
899
938
 
900
939
  /**