sumo-agents 0.6.1 → 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
@@ -195,7 +195,7 @@ export function highlight(line, lang, s, code = null) {
195
195
  state.comment = false;
196
196
  }
197
197
  const quotes = [...language.quotes].map((q) => `${q === '`' ? '`' : `\\${q}`}(?:[^${q === '`' ? '`' : `\\${q}`}\\\\]|\\\\.)*${q === '`' ? '`' : `\\${q}`}`).join('|');
198
- const comment = language.line === '#' ? '(?:^|(?<=\\s))#.*' : language.line ? `${language.line.replace(/\//g, '\\/')}.*` : '(?!)';
198
+ const comment = language.line === '#' ? '(?:^|(?<=\\s))#.*' : language.line ? `${language.line.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')}.*` : '(?!)';
199
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');
200
200
  pattern.lastIndex = at;
201
201
  for (let m; (m = pattern.exec(line)); ) {
package/src/ui.mjs CHANGED
@@ -12,6 +12,7 @@ import { INPUT_SHOWN } from './mcp.mjs';
12
12
  import { paths } from './paths.mjs';
13
13
  import { scratchDir } from './projects.mjs';
14
14
  import { redact } from './redact.mjs';
15
+ import { keyName, settingsPage, SettingsView } from './settings.mjs';
15
16
  import { elapsed } from './text.mjs';
16
17
  import { cleanPaste, editor, keysOf, matchFiles, menuOf, paste, press, under } from './editor.mjs';
17
18
  import { clipboardImage, copyText, droppedImages } from './images.mjs';
@@ -990,8 +991,7 @@ const HELP_KEYS = [
990
991
  ['enter', 'send; while the model works, it reads it next'],
991
992
  ['\\ enter', 'a new line (shift-enter and ctrl-j too)'],
992
993
  ['esc', 'interrupt the turn, or close a menu'],
993
- ['↑ ↓', 'what you sent before'],
994
- ['ctrl-r', 'search what you sent'],
994
+ ['↑ ↓ · ctrl-r', 'what you sent before · a search through it'],
995
995
  ['ctrl-c', 'clear the box; twice on an empty one to leave'],
996
996
  ['ctrl-o', 'the whole conversation in your pager'],
997
997
  ['ctrl-g', 'write the message in your editor'],
@@ -1054,8 +1054,9 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1054
1054
  const st = useRef(null);
1055
1055
  // `live` is what each running command has printed so far and since when; `heard`, when the model last said or did anything;
1056
1056
  // `turn`, what the turn in hand has done; `talking`, that the model — not a `!` command — is what the screen is working on;
1057
- // `pick`, the job under the box that Down has stepped onto; `open`, the one whose record is shown.
1058
- st.current ??= { log: [], items: [], unmeasured: [], used: 0, next: 0, epoch: 0, raw: '', ed: editor(readHistory()), images: [], pastes: [], keys: false, notice: null, queue: [], started: new Map(), known: new Map(), working: null, talking: false, tokens: 0, thought: '', thinking: null, showThinking: true, heard: 0, running: new Map(), live: new Map(), drawSoon: null, jobs: new Map(), pick: null, open: null, asks: [], why: null, reply: null, fresh: true, leaving: null, gone: false, title: null, turn: null, where: session.where(), spent: session.spent(), files: { cwd: null, at: 0, list: [] }, away: false };
1057
+ // `pick`, the job under the box that Down has stepped onto; `open`, the one whose record is shown; `settings`, the
1058
+ // settings page while /config has it open.
1059
+ st.current ??= { log: [], items: [], unmeasured: [], used: 0, next: 0, epoch: 0, raw: '', ed: editor(readHistory()), images: [], pastes: [], keys: false, notice: null, queue: [], started: new Map(), known: new Map(), working: null, talking: false, tokens: 0, thought: '', thinking: null, showThinking: true, heard: 0, running: new Map(), live: new Map(), drawSoon: null, jobs: new Map(), pick: null, open: null, asks: [], why: null, reply: null, fresh: true, leaving: null, gone: false, title: null, turn: null, where: session.where(), spent: session.spent(), files: { cwd: null, at: 0, list: [] }, away: false, settings: null };
1059
1060
  const state = st.current;
1060
1061
  state.columns = columns;
1061
1062
  state.rows = rows;
@@ -1480,6 +1481,13 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1480
1481
  session.route(args);
1481
1482
  return record({ kind: 'note', text: args ? `${routeLine(session)} from the next message` : `${routeLine(session)} · /model <model> <effort> changes it` });
1482
1483
  }
1484
+ // The settings page, in the box's place until Esc: what it changes is saved as it changes, and said once when it closes.
1485
+ if (control === 'config') {
1486
+ record({ kind: 'user', text: line });
1487
+ const left = () => `${routeLine(session)} ${state.where.name}${state.where.branch ? ` (${state.where.branch})` : ''}`;
1488
+ state.settings = settingsPage({ live: { route: (to) => session.route(to), servers: () => session.mcpServers(), left }, cwd: state.where.cwd, onChange: redraw });
1489
+ return;
1490
+ }
1483
1491
  if (control === 'memory' || control === 'mcp' || control === 'undo') {
1484
1492
  record({ kind: 'user', text: line });
1485
1493
  const text = control === 'undo' ? session.undo() : control === 'mcp' ? (await session.mcp()).join('\n') : await session.memoryPage();
@@ -1981,6 +1989,15 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1981
1989
  // The terminal's answer to Ink's keyboard-protocol query, when it comes after Ink stopped waiting for it.
1982
1990
  if (/^\[\?\d+u$/.test(input)) return;
1983
1991
  for (const [one, oneKey] of keysOf(input, key)) {
1992
+ // The settings page takes every key while it is open — Esc and Ctrl-C close it — unless a question waits: that comes first.
1993
+ if (state.settings && state.asks.length === 0) {
1994
+ if (state.settings.key(keyName(one, oneKey))) {
1995
+ const changed = state.settings.summary();
1996
+ state.settings = null;
1997
+ if (changed.length > 0) record({ kind: 'note', text: `settings: ${changed.join(' · ')}` });
1998
+ }
1999
+ continue;
2000
+ }
1984
2001
  // Ctrl-R looking back through what was sent takes every key, Esc and Ctrl-C too: they put the draft back, and stop nothing.
1985
2002
  if (state.ed.search) {
1986
2003
  state.ed = press(state.ed, one, oneKey, session.commands, files).state;
@@ -2115,6 +2132,12 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
2115
2132
  });
2116
2133
  // A file dropped on the terminal arrives pasted as its path: an image's path becomes the image.
2117
2134
  usePaste((text) => {
2135
+ // On the settings page a paste is a field's: a server's command or address, mostly.
2136
+ if (state.settings && state.asks.length === 0) {
2137
+ state.settings.paste(cleanPaste(text).text);
2138
+ redraw();
2139
+ return;
2140
+ }
2118
2141
  // Saying why a call is refused, a paste is part of the reason — on one line — and never lands in the box behind it.
2119
2142
  if (state.why && state.why.ask === state.asks[0]) {
2120
2143
  state.why.text += cleanPaste(text).text.replace(/\s+/g, ' ');
@@ -2173,6 +2196,8 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
2173
2196
  : 0;
2174
2197
  const under = approving ? (state.open !== null ? 2 + Math.min(Math.max(1, recorded), openRows(rows)) + (recorded > openRows(rows) ? 1 : 0) : 0) + (said ? 0 : STARTER_ROWS - 1) + 2 + state.queue.length + rowsUnderBox().length : 0;
2175
2198
  const asked = approving ? rows - 1 - over - under : null;
2199
+ // A question waiting comes before the settings page: it is drawn, and answered, while the page waits behind it.
2200
+ const paging = state.settings !== null && state.asks.length === 0;
2176
2201
  return h(
2177
2202
  Box,
2178
2203
  { flexDirection: 'column', minHeight: room },
@@ -2188,18 +2213,21 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
2188
2213
  state.open !== null ? h(JobOpen, { id: state.open, job: state.jobs.get(state.open), rows }) : null,
2189
2214
  // The logo and what to try are the empty room's: once something has been said, the room is the conversation's.
2190
2215
  h(Room, { logo: said ? [] : logo, rows, from: state.used, starter: !said }),
2191
- h(
2192
- Box,
2193
- { flexDirection: 'column', marginTop: 1 },
2194
- // A message for the model is read with its next request — which, while it waits on a delegated job, is when that job reports.
2195
- ...state.queue.map(({ line, steer }, i) => h(Text, { key: i, dimColor: true, wrap: 'truncate' }, ` ${steer ? reading : 'queued'}: ${line.split('\n')[0]}${line.includes('\n') ? ' …' : ''}`)),
2196
- // While a call waits on the user's word every key is the answer's: no box stands there to type into.
2197
- state.asks.length > 0 && !state.asks[0].options ? null : h(Input, { state: state.ed, width: columns, rows, placeholder: said ? '' : 'Ask anything' }),
2198
- // The jobs at work in the background, under the box, and the chat over them: they go on whether or not there is a turn.
2199
- ...rowsUnderBox().map((id) => (id === MAIN ? h(MainAtWork, { key: MAIN, working: Boolean(state.working), picked: state.pick === MAIN, shown: state.open === null }) : h(JobAtWork, { key: `j${id}`, id, job: state.jobs.get(id), alone: true, picked: id === state.pick, open: id === state.open }))),
2200
- // While a call waits on the user's word there is no box, and so nothing of the box's under it: the status row alone.
2201
- menu.length > 0 && !approving ? h(Menu, { menu, pick: state.ed.pick, columns }) : state.ed.search && !approving ? h(Search, { search: state.ed.search }) : state.keys && !approving ? h(Keys, { columns }) : h(Status, { session, leaving: Boolean(state.leaving), notice: state.notice?.text, jobs: [...state.jobs.keys()], aside: session.running(), pick: state.pick, open: state.open, where: state.where, spent: state.spent, overBudget: state.overBudget, waiting: state.queue.length > 0, columns }),
2202
- ),
2216
+ // The settings page stands where the box and the rows under it were, one row short of the window so it never fills it.
2217
+ paging
2218
+ ? h(Box, { marginTop: 1 }, h(SettingsView, { page: state.settings, columns, rows: Math.max(8, rows - 2), plain }))
2219
+ : h(
2220
+ Box,
2221
+ { flexDirection: 'column', marginTop: 1 },
2222
+ // A message for the model is read with its next request — which, while it waits on a delegated job, is when that job reports.
2223
+ ...state.queue.map(({ line, steer }, i) => h(Text, { key: i, dimColor: true, wrap: 'truncate' }, ` ${steer ? reading : 'queued'}: ${line.split('\n')[0]}${line.includes('\n') ? ' …' : ''}`)),
2224
+ // While a call waits on the user's word every key is the answer's: no box stands there to type into.
2225
+ state.asks.length > 0 && !state.asks[0].options ? null : h(Input, { state: state.ed, width: columns, rows, placeholder: said ? '' : 'Ask anything' }),
2226
+ // The jobs at work in the background, under the box, and the chat over them: they go on whether or not there is a turn.
2227
+ ...rowsUnderBox().map((id) => (id === MAIN ? h(MainAtWork, { key: MAIN, working: Boolean(state.working), picked: state.pick === MAIN, shown: state.open === null }) : h(JobAtWork, { key: `j${id}`, id, job: state.jobs.get(id), alone: true, picked: id === state.pick, open: id === state.open }))),
2228
+ // While a call waits on the user's word there is no box, and so nothing of the box's under it: the status row alone.
2229
+ menu.length > 0 && !approving ? h(Menu, { menu, pick: state.ed.pick, columns }) : state.ed.search && !approving ? h(Search, { search: state.ed.search }) : state.keys && !approving ? h(Keys, { columns }) : h(Status, { session, leaving: Boolean(state.leaving), notice: state.notice?.text, jobs: [...state.jobs.keys()], aside: session.running(), pick: state.pick, open: state.open, where: state.where, spent: state.spent, overBudget: state.overBudget, waiting: state.queue.length > 0, columns }),
2230
+ ),
2203
2231
  );
2204
2232
  }
2205
2233
 
package/src/verify.mjs CHANGED
@@ -1,11 +1,11 @@
1
1
  import { execFileSync, spawnSync } from 'node:child_process';
2
2
  import { createHash } from 'node:crypto';
3
- import { closeSync, existsSync, fstatSync, openSync, readFileSync, readSync, renameSync, statSync, writeFileSync } from 'node:fs';
3
+ import { closeSync, existsSync, fstatSync, ftruncateSync, openSync, readFileSync, readSync, renameSync, writeFileSync, writeSync } from 'node:fs';
4
4
  import { join } from 'node:path';
5
5
  import { isSecretPath } from './guard.mjs';
6
6
  import { UsageError } from './memory.mjs';
7
7
  import { secretShape } from './redact.mjs';
8
- import { verifyCommands } from './scan.mjs';
8
+ import { readPlainFile, verifyCommands } from './scan.mjs';
9
9
  import { killGroup } from './tools.mjs';
10
10
 
11
11
  /**
@@ -129,19 +129,14 @@ function timeoutMs() {
129
129
  }
130
130
 
131
131
  /** The last lines of a check's log, read from its end rather than whole. */
132
- function tailOf(file) {
133
- const fd = openSync(file, 'r');
134
- try {
135
- const size = fstatSync(fd).size;
136
- const start = Math.max(0, size - OUTPUT_TAIL_BYTES);
137
- const bytes = Buffer.alloc(size - start);
138
- const lines = bytes.subarray(0, readSync(fd, bytes, 0, bytes.length, start)).toString('utf8').trimEnd().split('\n');
139
- // Read from inside a line, the first piece is half of one.
140
- if (start > 0 && lines.length > 1) lines.shift();
141
- return lines.slice(-OUTPUT_TAIL_LINES).join('\n');
142
- } finally {
143
- closeSync(fd);
144
- }
132
+ function tailOf(fd) {
133
+ const size = fstatSync(fd).size;
134
+ const start = Math.max(0, size - OUTPUT_TAIL_BYTES);
135
+ const bytes = Buffer.alloc(size - start);
136
+ const lines = bytes.subarray(0, readSync(fd, bytes, 0, bytes.length, start)).toString('utf8').trimEnd().split('\n');
137
+ // Read from inside a line, the first piece is half of one.
138
+ if (start > 0 && lines.length > 1) lines.shift();
139
+ return lines.slice(-OUTPUT_TAIL_LINES).join('\n');
145
140
  }
146
141
 
147
142
  /** The sandbox a job's process hands down for its checks: the wrap's words, or null — none given, or one that is not a list of words. */
@@ -167,25 +162,26 @@ function runChecks(root, commands, dir, prefix) {
167
162
  named.set(name, nth);
168
163
  const file = join(dir, `${prefix}-${name}${nth > 1 ? `-${nth}` : ''}.txt`);
169
164
  // Printed into the file, not a pipe: a pipe stays open while anything the check left running holds it, and would be waited on to the time limit.
170
- const into = openSync(file, 'w', 0o600);
171
- let run;
165
+ // Its end is read and written back through the same descriptor, so the file kept is the file the check printed into.
166
+ const into = openSync(file, 'w+', 0o600);
172
167
  try {
173
168
  // A job's checks run the project's code, perhaps tests the model wrote: in the sandbox its shell is in, handed down by the
174
169
  // job's own process (SUMO_CHECKS_WRAP), while this process — which records the verdict in sumo's memory — stays outside it.
175
170
  const wrap = checksWrapOf(process.env);
176
171
  const script = `${watcher}${command}`;
177
- run = wrap
172
+ const run = wrap
178
173
  ? spawnSync(wrap[0], [...wrap.slice(1), '/bin/sh', '-c', script], { cwd: root, detached: true, stdio: ['ignore', into, into], timeout: timeoutMs(), killSignal: 'SIGKILL' })
179
174
  : spawnSync(script, { cwd: root, shell: true, detached: true, stdio: ['ignore', into, into], timeout: timeoutMs(), killSignal: 'SIGKILL' });
175
+ const timedOut = run.error?.code === 'ETIMEDOUT';
176
+ // Whatever it left running goes with it, so nothing writes to the file once it is read.
177
+ killGroup(run.pid);
178
+ const output = tailOf(into);
179
+ ftruncateSync(into);
180
+ writeSync(into, `$ ${command}\n${output}\n${timedOut ? '\n(stopped: it ran past the time limit)\n' : ''}`, 0);
181
+ return { name, command, ok: run.status === 0, status: run.status, timedOut, ms: Date.now() - started, file };
180
182
  } finally {
181
183
  closeSync(into);
182
184
  }
183
- const timedOut = run.error?.code === 'ETIMEDOUT';
184
- // Whatever it left running goes with it, so nothing writes to the file once it is read.
185
- killGroup(run.pid);
186
- const output = tailOf(file);
187
- writeFileSync(file, `$ ${command}\n${output}\n${timedOut ? '\n(stopped: it ran past the time limit)\n' : ''}`, { mode: 0o600 });
188
- return { name, command, ok: run.status === 0, status: run.status, timedOut, ms: Date.now() - started, file };
189
185
  });
190
186
  }
191
187
 
@@ -253,9 +249,9 @@ function scanAdded(root, snap, changes) {
253
249
  // A new file is read whole, and so is one that git never tracked: there is no diff to take its added lines from.
254
250
  for (const created of [...changes.created, ...changes.tracked.filter((c) => c.untracked && c.status === 'M').map((c) => c.path)]) {
255
251
  try {
256
- const full = join(root, created);
257
- if (statSync(full).size > MAX_SCANNED_FILE_BYTES) continue;
258
- readFileSync(full, 'utf8').split('\n').forEach((l, i) => look(`${created}:${i + 1}`, l));
252
+ const text = readPlainFile(join(root, created), MAX_SCANNED_FILE_BYTES);
253
+ if (text === null) continue;
254
+ text.split('\n').forEach((l, i) => look(`${created}:${i + 1}`, l));
259
255
  } catch {
260
256
  // unreadable or binary: nothing to say about it
261
257
  }