sumo-agents 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/AGENTS.md +8 -6
  2. package/CHANGELOG.md +155 -0
  3. package/README.md +82 -19
  4. package/bin/sumo.mjs +13 -2
  5. package/guides/feature.md +2 -1
  6. package/guides/memory.md +6 -4
  7. package/guides/projects.md +1 -1
  8. package/guides/review.md +1 -1
  9. package/package.json +5 -4
  10. package/prompts/dream.md +6 -0
  11. package/spinner.txt +25 -1
  12. package/src/apply.mjs +146 -18
  13. package/src/auth.mjs +32 -5
  14. package/src/card.mjs +39 -2
  15. package/src/catalog.mjs +6 -3
  16. package/src/chat.mjs +289 -89
  17. package/src/cli.mjs +359 -135
  18. package/src/cost.mjs +67 -8
  19. package/src/db.mjs +106 -3
  20. package/src/dream.mjs +445 -19
  21. package/src/editor.mjs +113 -11
  22. package/src/export.mjs +105 -7
  23. package/src/guard.mjs +57 -11
  24. package/src/guides.mjs +5 -4
  25. package/src/herdr.mjs +9 -4
  26. package/src/hooks.mjs +35 -19
  27. package/src/jobs.mjs +118 -39
  28. package/src/jobtools.mjs +6 -4
  29. package/src/keeper.mjs +77 -0
  30. package/src/local-server.mjs +9 -16
  31. package/src/lock.mjs +2 -1
  32. package/src/logs.mjs +165 -0
  33. package/src/loop.mjs +121 -44
  34. package/src/mcp.mjs +72 -16
  35. package/src/memory.mjs +142 -15
  36. package/src/model.mjs +41 -21
  37. package/src/paths.mjs +38 -0
  38. package/src/prime.mjs +19 -31
  39. package/src/projects.mjs +94 -12
  40. package/src/redact.mjs +10 -0
  41. package/src/render.mjs +2 -1
  42. package/src/route.mjs +39 -25
  43. package/src/sandbox.mjs +82 -3
  44. package/src/scan.mjs +35 -1
  45. package/src/scribe.mjs +10 -22
  46. package/src/sessions.mjs +49 -13
  47. package/src/setup.mjs +425 -76
  48. package/src/text.mjs +100 -1
  49. package/src/tools.mjs +258 -21
  50. package/src/tty.mjs +481 -105
  51. package/src/ui.mjs +1205 -276
  52. package/src/verify.mjs +17 -1
package/src/text.mjs CHANGED
@@ -22,6 +22,19 @@ export function ftsQuery(text) {
22
22
  return unique.map((w) => `"${w.replaceAll('"', '""')}"`).join(' OR ');
23
23
  }
24
24
 
25
+ /** Han, Hiragana, Katakana and Hangul: scripts whose words run on into the next, or into what is joined to them. */
26
+ const CJK = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
27
+
28
+ /**
29
+ * The words of a search in Chinese, Japanese or Korean. The index keeps a run of such characters as one word —
30
+ * "日本語のテスト" is a single token — so a word inside it is never matched there; these are looked for in the text
31
+ * itself. Read alike from what was typed or from `ftsQuery`'s expression, which quotes the same words.
32
+ */
33
+ export const cjkTerms = (text) => [...new Set(words(text))].filter((w) => CJK.test(w));
34
+
35
+ /** A LIKE pattern for `term` anywhere in a text, LIKE's own characters taken as themselves (with ESCAPE '\'). */
36
+ export const containing = (term) => `%${term.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
37
+
25
38
  /**
26
39
  * Crude suffix stripping, for judging whether two short texts are about the
27
40
  * same thing. The index itself uses SQLite's porter stemmer.
@@ -46,6 +59,46 @@ export function overlap(a, b) {
46
59
  return shared / Math.min(sa.size, sb.size);
47
60
  }
48
61
 
62
+ /** How much of what a memory says must be in the user's own words for it to be theirs. */
63
+ const SAID_SHARE = 0.8;
64
+ /**
65
+ * The words that turn a rule round: "never" is not "always", "don't" is not "do". Only a negation counts: an "always"
66
+ * a model adds to what was said changes how firmly, never which way.
67
+ */
68
+ 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
+ /** A trailing "…, not B" or "…, never B", B a word or three: the alternative a statement is chosen over. */
70
+ 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
+ /** Whether a text sets `alt` aside itself: moved "from" it, chose "instead of", "rather than" or "over" it, or said "not" it. */
74
+ const setsAside = (text, alt) => {
75
+ const said = alt.replace(/[.*+?^${}()|[\]\\]/g, (c) => `\\${c}`);
76
+ return new RegExp(`\\b(?:from|instead of|rather than|over|not|never|no)\\s+(?:the\\s+)?${said}\\b`, 'i').test(text);
77
+ };
78
+ /** The text without its trailing alternative, when the other text sets that alternative aside too. */
79
+ const withoutAlternative = (text, other) => {
80
+ const m = ALTERNATIVE.exec(text);
81
+ return m && setsAside(other, m[1].replace(/\.+$/, '')) ? text.slice(0, m.index) : text;
82
+ };
83
+ /**
84
+ * Whether two texts say a thing the same way round: both negate it, or neither does. "slate uses bun, not pnpm" from "we
85
+ * 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.
87
+ */
88
+ export const sameWayRound = (a, b, aside = b) => NEGATION.test(withoutAlternative(a, aside)) === NEGATION.test(withoutAlternative(b, a));
89
+
90
+ /**
91
+ * Whether what the user typed says what a memory says: nearly all of the memory's own words are in theirs — not a
92
+ * few of theirs inside much they never said — and it says it the same way round, never for always, don't for do.
93
+ */
94
+ export function saysAs(memory, typed, share = SAID_SHARE) {
95
+ const theirs = new Set(words(typed).map(stem));
96
+ const its = [...new Set(words(memory).map(stem))];
97
+ if (its.length === 0) return false;
98
+ const covered = its.filter((w) => theirs.has(w)).length / its.length;
99
+ return covered >= share && sameWayRound(memory, typed);
100
+ }
101
+
49
102
  /** How many distinct stems two texts have in common. */
50
103
  export function sharedStems(a, b) {
51
104
  const sb = new Set(words(b).map(stem));
@@ -93,5 +146,51 @@ const VERBS = /describe|explain|delegate|fix|find|investigate|look\s+(?:at|into|
93
146
  const FOR_NOW = /\b(?:not|n't|dont|don't)\b[^.!?\n]*\byet\b|\b(?:lmk|let\s+me\s+know)\b/.source;
94
147
  const REQUEST = new RegExp(`(?:^|[.,:;!?)]\\s+|\\n\\s*)${OPENERS}(?:${VERBS})\\b|\\?\\s*$|${FOR_NOW}`, 'im');
95
148
 
149
+ /** Verbs that change something. Aimed at one thing now, they ask for work; with a condition they are a rule. */
150
+ const CHANGES = new Set(['make', 'change', 'rename', 'update', 'add', 'remove', 'delete', 'move', 'refactor', 'create', 'build', 'run', 'deploy', 'bump', 'revert', 'undo', 'turn', 'fix']);
151
+ /** Verbs that are almost always one change, now: a rule seldom renames, deletes or undoes. */
152
+ const NOW_ONLY = new Set(['rename', 'delete', 'undo', 'revert']);
153
+ const POINTING = new Set(['it', 'this', 'that', 'these', 'those']);
154
+ /** What makes a change a rule: when it happens, or to what, every time. */
155
+ const CONDITION = /\b(?:before|after|when|whenever|each|every|unless|always|never|by default)\b/i;
156
+ /** Asking for an answer, or saying what the work is now — wherever in the sentence it comes. */
157
+ const ANSWER_OR_SWITCH = /\b(?:tell|show|give)\s+me\b|\bcheck\s+(?:if|whether)\b|^(?:switching|switch|moving|going)\s+(?:to|over\s+to)\b|^(?:back|now)\s+(?:on|to)\b|^(?:work|get\s+back)\s+on\b/i;
158
+ const LEADING = /^(?:(?:please|pls|now|then|also|and|so+|ok|okay|yes|yeah|yep|just|actually|lets|let's)[\s,]+)+/i;
159
+
160
+ /**
161
+ * A change to one thing, now — "make the button blue", "deploy it", "rename the config file" — whose result lives in
162
+ * the code, not in memory. Read narrowly, because a rule lost is lost silently: a change verb aimed at it/this/that, a
163
+ * change to "the X" in four words or fewer, or a rename, delete or undo; never with a condition ("run the tests before
164
+ * pushing"), and never a longer "the" sentence, which reads the same as a rule ("make the commit messages imperative").
165
+ */
166
+ function oneChange(sentence) {
167
+ const words = sentence.replace(LEADING, '').replace(/[.!?,;:]+$/, '').trim().toLowerCase().split(/\s+/);
168
+ if (!CHANGES.has(words[0]) || CONDITION.test(sentence)) return false;
169
+ return POINTING.has(words[1]) || NOW_ONLY.has(words[0]) || (words[1] === 'the' && words.length <= 4);
170
+ }
171
+
96
172
  /** Words that ask for work or an answer and state nothing that lasts: nothing in them is a memory. */
97
- export const asksForWork = (text) => REQUEST.test(String(text ?? '')) && !looksDurable(String(text ?? ''));
173
+ export const asksForWork = (text) => {
174
+ const said = String(text ?? '');
175
+ if (looksDurable(said)) return false;
176
+ const sentences = said.split(/(?<=[.!?;])\s+|\n+/).map((x) => x.trim()).filter(Boolean);
177
+ return REQUEST.test(said) || sentences.some((x) => oneChange(x) || ANSWER_OR_SWITCH.test(x.replace(LEADING, '')));
178
+ };
179
+
180
+ /**
181
+ * The known name a mistyped one was most likely meant to be: two edits away at most, nearer than any other, and with
182
+ * at least half of what was typed kept — `m` is no guess at `mcp`, nor `xml` at `md`; `serch` is at `search`.
183
+ */
184
+ export function closest(typed, names) {
185
+ const distance = (a, b) => {
186
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i);
187
+ for (let i = 1; i <= a.length; i++) {
188
+ const next = [i];
189
+ for (let j = 1; j <= b.length; j++) next.push(Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)));
190
+ row = next;
191
+ }
192
+ return row[b.length];
193
+ };
194
+ const ranked = [...new Set(names)].map((name) => ({ name, d: distance(String(typed).toLowerCase(), name) })).sort((x, y) => x.d - y.d);
195
+ return ranked[0] && ranked[0].d <= 2 && ranked[0].d <= Math.floor(String(typed).length / 2) ? ranked[0].name : null;
196
+ }
package/src/tools.mjs CHANGED
@@ -1,11 +1,12 @@
1
1
  import { spawn, spawnSync } from 'node:child_process';
2
- import { accessSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
- import { tmpdir } from 'node:os';
4
- import { delimiter, dirname, extname, join, resolve, sep } from 'node:path';
2
+ import { accessSync, closeSync, constants, existsSync, fstatSync, ftruncateSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
+ import { homedir, tmpdir } from 'node:os';
4
+ import { delimiter, dirname, extname, join, relative, resolve, sep } from 'node:path';
5
5
  import { CREDENTIAL_NAMES } from './auth.mjs';
6
6
  import { guardCommand, guardPath } from './guard.mjs';
7
+ import { SELF } from './paths.mjs';
7
8
  import { redact } from './redact.mjs';
8
- import { blockedWrite, readOnlyPlaces, sandboxWrap, unsandboxable, writablePlaces } from './sandbox.mjs';
9
+ import { blockedWrite, guardedPlaces, guardedWhy, readOnlyPlaces, sandboxWrap, unsandboxable, writablePlaces } from './sandbox.mjs';
9
10
 
10
11
  /**
11
12
  * The two tools a job gets, and the policy every call passes through before it
@@ -140,6 +141,9 @@ export function trackGroup(pid) {
140
141
  // A terminal closed, or a kill: leave as the signal would, after the commands — exit runs the line above.
141
142
  process.on('SIGHUP', () => process.exit(129));
142
143
  process.on('SIGTERM', () => process.exit(143));
144
+ // Ctrl-C too, which a group of its own never hears — unless this process already answers Ctrl-C itself (a job run
145
+ // stops the job and says how it ended). The chat's screen is unchanged: in raw mode Ctrl-C is a key, not a signal.
146
+ if (process.listenerCount('SIGINT') === 0) process.on('SIGINT', () => process.exit(130));
143
147
  }
144
148
 
145
149
  /** What a command's output ends with when the user stopped it. */
@@ -306,7 +310,7 @@ function realAncestor(path, hops = 0) {
306
310
  if (up === probe) return probe;
307
311
  probe = up;
308
312
  }
309
- return realpathSync(probe);
313
+ return realpathSync.native(probe);
310
314
  }
311
315
 
312
316
  const isLink = (path) => {
@@ -323,7 +327,7 @@ export function jailed(path, { cwd, roots }) {
323
327
  // resolve() also tidies an absolute path: a .. after a directory that does not exist yet must not climb past the check.
324
328
  const absolute = resolve(cwd, path);
325
329
  const real = realAncestor(absolute);
326
- const allowed = roots.map((r) => realpathSync(r)).some((r) => real === r || real.startsWith(`${r}/`));
330
+ const allowed = roots.map((r) => realpathSync.native(r)).some((r) => real === r || real.startsWith(`${r}/`));
327
331
  if (!allowed) throw new Error(`${path} is outside the project (${roots[0]}) — work only inside it`);
328
332
  return absolute;
329
333
  }
@@ -431,8 +435,8 @@ function jailOf(ctx) {
431
435
  toldUnsandboxed = true;
432
436
  return { wrap: null, writable: [], readOnly: [], note };
433
437
  }
434
- const writable = writablePlaces(ctx.roots);
435
- const readOnly = readOnlyPlaces(ctx.roots);
438
+ const writable = writablePlaces(ctx.roots, { opened: ctx.opened ?? [] });
439
+ const readOnly = [...new Set([...readOnlyPlaces(ctx.roots), ...guardedPlaces(ctx.roots)])];
436
440
  const offline = ctx.network === false;
437
441
  return { wrap: sandboxWrap(writable, { readOnly, network: !offline }), writable, readOnly, offline, note: '' };
438
442
  }
@@ -539,6 +543,64 @@ async function runInBackground(command, ctx, { env, jail }) {
539
543
  return result(`started in the background (pid ${pid}); its output goes to ${log} — read it with \`tail -n 50 ${log}\`. It is stopped when the job or the chat that started it ends.${jail.note}`);
540
544
  }
541
545
 
546
+ /**
547
+ * The sumo commands the model's shell runs as sumo itself, outside the sandbox — the sandbox keeps sumo's memory,
548
+ * settings and MCP servers read-only, so from inside it they could not be read or written at all. The CLI refuses there
549
+ * what only the user does (settings, MCP servers, models), and a job's shell what only the chat does. Never routed:
550
+ * what installs or starts things — setup, a job's run, a hook, the chat.
551
+ */
552
+ const SUMO_ROUTED = new Set(['search', 'add', 'learn', 'show', 'history', 'gate', 'supersede', 'forget', 'confirm', 'reject', 'prime', 'memory', 'project', 'cost', 'config', 'mcp', 'models', 'export', 'doctor', 'job', 'help', 'version', '--version', '-v', '--help', '-h']);
553
+ /** Of a job's commands, only those that read: verify and finish run the project's checks, which belong in the sandbox. */
554
+ const ROUTED_JOB = new Set(['show', 'list', 'stats']);
555
+
556
+ /**
557
+ * A command's words when it is plain words alone — quoted or not — with nothing the shell would expand, redirect, pipe,
558
+ * glob or run besides; null for anything else. Only such a command is what it looks like before the shell reads it.
559
+ */
560
+ function shellWords(text) {
561
+ const words = [];
562
+ let word = null;
563
+ let quote = null;
564
+ for (const c of String(text).trim()) {
565
+ if (quote === "'") {
566
+ if (c === "'") quote = null;
567
+ else word += c;
568
+ } else if (quote === '"') {
569
+ if (c === '"') quote = null;
570
+ else if ('$`\\'.includes(c)) return null;
571
+ else word += c;
572
+ } else if (c === "'" || c === '"') {
573
+ quote = c;
574
+ word ??= '';
575
+ } else if (c === ' ' || c === '\t') {
576
+ if (word !== null) words.push(word);
577
+ word = null;
578
+ } else if (/[;&|<>$`(){}*?[\]~!#\\\n\r]/.test(c)) {
579
+ return null;
580
+ } else word = (word ?? '') + c;
581
+ }
582
+ if (quote) return null;
583
+ if (word !== null) words.push(word);
584
+ return words;
585
+ }
586
+
587
+ const quoted = (w) => (/^[\w@%+=:,./-]+$/.test(w) ? w : `'${w.replaceAll("'", "'\\''")}'`);
588
+
589
+ /** A plain `sumo …` command, spelled to run this very sumo by its path; null for any other command. */
590
+ function sumoCall(command) {
591
+ // `sumo learn` reads its steps on stdin, written as a here-document: taken as it is when its delimiter is quoted (nothing
592
+ // in it expands) and no line inside it ends it early — bash would run what came after that line, outside the sandbox.
593
+ const heredoc = /^([^\n]*?)\s*<<-?\s*(['"])([A-Za-z_]\w*)\2[ \t]*\n([\s\S]*)\n\3[ \t]*$/.exec(String(command).trim());
594
+ const words = shellWords(heredoc ? heredoc[1] : command);
595
+ if (!words || words[0] !== 'sumo' || !SUMO_ROUTED.has(words[1] ?? 'help')) return null;
596
+ if (words[1] === 'job' && !ROUTED_JOB.has(words[2])) return null;
597
+ const call = [...SELF, ...words.slice(1)].map(quoted).join(' ');
598
+ if (!heredoc) return call;
599
+ const [, , , end, body] = heredoc;
600
+ if (words[1] !== 'learn' || body.split('\n').some((line) => line.replace(/^\t+/, '').replace(/\r$/, '') === end)) return null;
601
+ return `${call} <<'${end}'\n${body}\n${end}`;
602
+ }
603
+
542
604
  /** A limit as it is said: in minutes when it is whole minutes, else in seconds. */
543
605
  const span = (ms) => (ms >= 60_000 && ms % 60_000 === 0 ? `${ms / 60_000} minute${ms === 60_000 ? '' : 's'}` : `${ms / 1000} second${ms === 1000 ? '' : 's'}`);
544
606
 
@@ -554,7 +616,14 @@ export async function runBash({ command, restart }, ctx, { signal = null, timeou
554
616
  const refused = guardCommand(command, { cwd: ctx.cwd });
555
617
  if (refused) return result(refused, true);
556
618
  const env = unprompted(ctx.env ?? childEnv(), ctx.cwd);
557
- const jail = jailOf(ctx);
619
+ let jail = jailOf(ctx);
620
+ // sumo's own files are read-only to the sandbox: a plain sumo command runs as sumo itself, outside it, where the CLI's own
621
+ // rules decide what the model may change — never the settings, the MCP servers or the models.
622
+ const asSumo = jail.wrap ? sumoCall(command) : null;
623
+ if (asSumo) {
624
+ command = asSumo;
625
+ jail = { ...jail, wrap: null, note: '' };
626
+ }
558
627
  const behind = backgrounded(command);
559
628
  if (behind !== null) return runInBackground(behind, ctx, { env, jail });
560
629
  // The commands that run the project's checks give each check its own limit; one limit over all of them would cut a verdict off half-way.
@@ -580,7 +649,36 @@ export async function runBash({ command, restart }, ctx, { signal = null, timeou
580
649
  const kept = ctx.spill && (tidied.capped || tidied.cut > 0) ? spill(ctx.spill, output, run.omitted) : null;
581
650
  const shown = tidied.show(kept) + tail;
582
651
  if (jail.wrap && run.stopped === null && run.status !== 0 && blockedWrite(output)) return blocked(command, shown, ctx, jail, { signal, timeoutMs, idleMs, onOutput });
583
- return result(shown + jail.note, failed);
652
+ return result(shown + changedBy(ctx) + jail.note, failed);
653
+ }
654
+
655
+ /** The most files a command is said to have changed by name. */
656
+ const CHANGED_NAMED = 20;
657
+
658
+ /**
659
+ * The files the model has viewed that this command changed or removed — a formatter, codegen, a checkout — said after
660
+ * it, so the model views those again and not the rest. What it saw of them stays as it was: an edit made without a
661
+ * fresh view is still said to be against what it remembers.
662
+ */
663
+ function changedBy(ctx) {
664
+ const changed = [];
665
+ for (const [path, was] of ctx.seen ?? []) {
666
+ try {
667
+ const now = stampOf(path);
668
+ // Said once for each change: what it was told of is kept beside what it saw, which stays.
669
+ if ((now.mtimeMs !== was.mtimeMs || now.size !== was.size) && (now.mtimeMs !== was.told?.mtimeMs || now.size !== was.told?.size)) {
670
+ was.told = now;
671
+ changed.push(path);
672
+ }
673
+ } catch {
674
+ ctx.seen.delete(path);
675
+ changed.push(`${path} (gone)`);
676
+ }
677
+ }
678
+ if (changed.length === 0) return '';
679
+ const named = changed.slice(0, CHANGED_NAMED);
680
+ const more = changed.length - named.length;
681
+ return `\n(this command changed files you had viewed: ${named.join(', ')}${more > 0 ? ` and ${more} more` : ''} — view one again before editing it)`;
584
682
  }
585
683
 
586
684
  /**
@@ -589,16 +687,21 @@ export async function runBash({ command, restart }, ctx, { signal = null, timeou
589
687
  * the guard has passed it already. With nobody there, the model is told to report it.
590
688
  */
591
689
  async function blocked(command, shown, ctx, jail, options) {
592
- const except = jail.readOnly.length > 0 ? `, except git's hooks and config: ${jail.readOnly.join(', ')}` : '';
690
+ const except = jail.readOnly.length > 0 ? `, except what is read later outside it — git's hooks and config, the shell's and the tools' own files: ${jail.readOnly.join(', ')}` : '';
593
691
  const offline = jail.offline ? ' — and nothing past this machine can be reached: the user turned the network off (shell.network)' : '';
594
692
  const said = `${shown}\n(the sandbox blocked a write outside the project — only these can be written: ${jail.writable.join(', ')}${except}${offline})`;
595
693
  if (!ctx.approve) return result(`${said}\n(nobody is here to allow it outside the sandbox: report it, with the command, so the user can run it themselves)`, true);
596
694
  const { signal } = options;
597
695
  const stopped = new Promise((resolve) => signal?.addEventListener('abort', () => resolve('no'), { once: true }));
598
696
  // Asked as what it is — this one run outside the sandbox, yes or no — never as an MCP call that could be allowed always.
599
- const answer = signal?.aborted ? 'no' : await Promise.race([ctx.approve({ name: BASH_TOOL.name, server: 'bash', tool: 'outside the sandbox', input: { command }, unsandboxed: true, signal }), stopped]);
697
+ // With what the sandbox refused, so the question says why it is asked: the first line that names a refused write.
698
+ const refusal = String(shown).split('\n').find((line) => /operation not permitted|read-only file system|permission denied/i.test(line));
699
+ const blockedLine = refusal ? redact(refusal.trim()).text.slice(0, 300) : null;
700
+ const answer = signal?.aborted ? 'no' : await Promise.race([ctx.approve({ name: BASH_TOOL.name, server: 'bash', tool: 'outside the sandbox', input: { command }, unsandboxed: true, blocked: blockedLine, signal }), stopped]);
600
701
  // Always is once here: what is allowed is this one run, never the sandbox off.
601
- if (answer !== 'once' && answer !== 'always') return result(`${said}\n(the user declined running it outside the sandbox: do not run it again; carry on another way, or ask the user)`, true);
702
+ if (answer !== 'once' && answer !== 'always') {
703
+ return { ...result(`${said}\n(the user declined running it outside the sandbox: do not run it again; carry on another way, or ask the user)${saidWhy(answer)}`, true), shown: redact(`${shown}\n${declinedShown('the sandbox kept it from writing outside the project, and it was not run outside it', answer)}`).text };
704
+ }
602
705
  const again = await runBash({ command }, { ...ctx, sandbox: false }, options);
603
706
  return { ...again, content: `(the sandbox blocked a write outside the project; the user let it run again outside the sandbox)\n${again.content}` };
604
707
  }
@@ -891,18 +994,125 @@ function placeholderIn(path, field, text, had = '') {
891
994
  return gap === undefined ? null : `not written: ${field} has a line that stands for code instead of holding it — ${JSON.stringify(gap.trim())} — and the file would hold that line, not the code. Write the code out in full; to leave code as it is, leave it out of the edit.`;
892
995
  }
893
996
 
997
+ /** The longest reason a refusal carries: a sentence or two, not a document. */
998
+ const REASON_MAX_CHARS = 500;
999
+
1000
+ /**
1001
+ * What the user said when they refused a call — an answer of `{ no: 'their words' }` — as the line the model reads
1002
+ * after the refusal; empty for a plain no. Their words are their direction for what to do instead.
1003
+ */
1004
+ export function saidWhy(answer) {
1005
+ const words = wordsOf(answer);
1006
+ return words ? `\n(the user declined it and said: "${words}" — do what they said instead)` : '';
1007
+ }
1008
+ /** The user's words with a no, redacted, on one line; empty for a plain no. */
1009
+ const wordsOf = (answer) => (answer && typeof answer === 'object' && typeof answer.no === 'string' ? redact(answer.no).text.replace(/\s+/g, ' ').trim().slice(0, REASON_MAX_CHARS) : '');
1010
+ /**
1011
+ * A refusal as the screen says it: what was declined, in a line, and the user's own words — not the paths and the
1012
+ * instructions the model is given. The model's text stays whole in `content`; the full view shows it.
1013
+ */
1014
+ export const declinedShown = (what, answer) => {
1015
+ const words = wordsOf(answer);
1016
+ return `declined: ${what}${words ? ` · you said: "${words}"` : ''}`;
1017
+ };
1018
+
1019
+ /** The most lines an ambiguous old_str is said to start on. */
1020
+ const HITS_NAMED = 10;
1021
+
1022
+ /** Where an old_str found more than once starts, as ` (lines 4, 18, 40)`, so one view of those lines makes it unique; empty when it matched only loosely. */
1023
+ function linesOf(text, old) {
1024
+ const lines = [];
1025
+ for (let at = text.indexOf(old); at !== -1 && lines.length <= HITS_NAMED; at = text.indexOf(old, at + 1)) lines.push(text.slice(0, at).split('\n').length);
1026
+ if (lines.length < 2) return '';
1027
+ const more = lines.length > HITS_NAMED ? ', …' : '';
1028
+ return ` (lines ${lines.slice(0, HITS_NAMED).join(', ')}${more})`;
1029
+ }
1030
+
1031
+ /** Why a file with another name is asked about each time. */
1032
+ const HARD_LINK = 'it has another name elsewhere (a hard link), and a change here changes that file too';
1033
+
1034
+ /**
1035
+ * A file the editor writes, written where its checks found it lands: through no link swapped in since — the last name
1036
+ * is opened without following one — and only when the file opened is the one that was checked. Nothing is truncated
1037
+ * before that. (A folder above it swapped for a link between the check and the open is not caught: Node has no openat.)
1038
+ */
1039
+ function writeTo(path, data, { create = false } = {}) {
1040
+ const target = landsAt(path) ?? path;
1041
+ const before = create ? null : statSync(target);
1042
+ const fd = openSync(target, constants.O_WRONLY | constants.O_NOFOLLOW | (create ? constants.O_CREAT | constants.O_EXCL : 0), 0o666);
1043
+ try {
1044
+ const opened = fstatSync(fd);
1045
+ if (before && (opened.ino !== before.ino || opened.dev !== before.dev)) throw new Error(`${path} was replaced while it was being changed; nothing was written — view it again`);
1046
+ ftruncateSync(fd, 0);
1047
+ writeFileSync(fd, data);
1048
+ } finally {
1049
+ closeSync(fd);
1050
+ }
1051
+ }
1052
+
894
1053
  /** The text editor's four commands, each inside the jail; secret files are neither shown nor written. */
1054
+ /** Whether the user opened a place for the session that holds this path (`ctx.opened`, kept by real path: a file, or a directory with everything under it). */
1055
+ function openedIn(ctx, path) {
1056
+ for (const place of ctx.opened ?? []) if (path === place || path.startsWith(`${place}${sep}`)) return true;
1057
+ return false;
1058
+ }
1059
+
1060
+ /**
1061
+ * Where a write to a path lands, by real path: through every link on the way, to a file not there yet below the deepest
1062
+ * directory that is. Null for a link that points at nothing yet — a write there goes where the link says, which no
1063
+ * question has shown.
1064
+ */
1065
+ function landsAt(path) {
1066
+ if (existsSync(path)) return realpathSync.native(path);
1067
+ let probe = path;
1068
+ while (!existsSync(probe)) {
1069
+ if (isLink(probe)) return null;
1070
+ const up = dirname(probe);
1071
+ if (up === probe) return null;
1072
+ probe = up;
1073
+ }
1074
+ return join(realpathSync.native(probe), relative(probe, path));
1075
+ }
1076
+
1077
+ /** The directory a file's question may open for the session: never the home, what is above it, or the top of the disk — the shell would write there too. */
1078
+ function directoryFor(path) {
1079
+ const dir = dirname(path);
1080
+ const home = landsAt(homedir()) ?? homedir();
1081
+ return dir === home || `${home}${sep}`.startsWith(`${dir}${sep}`) || dirname(dir) === dir ? null : dir;
1082
+ }
1083
+
1084
+ /** A refusal the model reads, with the question for the user on it: where the write lands, whether that is outside the project, why it is guarded, and what directory may be opened. */
1085
+ function askFirst(message, path, { outside, guarded }) {
1086
+ return { ...result(message, true), ask: { path, outside, guarded, directory: outside && !guarded ? directoryFor(path) : null } };
1087
+ }
1088
+
895
1089
  export function runEditor(input, ctx) {
896
1090
  let path;
1091
+ /** Whether the user let this file, outside the project, be changed: for the session, or this once. */
1092
+ let opened = false;
897
1093
  try {
898
1094
  path = jailed(input.path, ctx);
899
1095
  } catch (cause) {
900
- return result(cause.message, true);
1096
+ // Outside the project: read as the shell reads, anywhere; written only where the user has said so — else refused
1097
+ // with the path on it, for whoever runs the tool to put to the user. A guarded file is never opened for the session.
1098
+ // Judged by where the write lands, so a link in an opened directory cannot carry it somewhere else.
1099
+ const absolute = typeof input.path === 'string' && input.path ? resolve(ctx.cwd, input.path) : null;
1100
+ if (absolute === null) return result(cause.message, true);
1101
+ const lands = landsAt(absolute);
1102
+ if (input.command !== 'view') {
1103
+ if (lands === null) return result(`${absolute} is a link to something not there yet, outside the project — not written: say in your report what it needs`, true);
1104
+ const guarded = guardedWhy(absolute, { roots: ctx.roots }) ?? guardedWhy(lands, { roots: ctx.roots });
1105
+ opened = ctx.granted === lands || (!guarded && openedIn(ctx, lands));
1106
+ // macOS's own /var, /tmp and /etc are links into /private: no link worth naming.
1107
+ const shown = lands === absolute || lands === `/private${absolute}` ? absolute : `${absolute} (a link to ${lands})`;
1108
+ if (!opened) return guarded ? askFirst(`${shown} is changed only when the user says so: ${guarded}`, lands, { outside: true, guarded }) : askFirst(`${shown} is outside the project (${ctx.roots[0]})`, lands, { outside: true, guarded: null });
1109
+ }
1110
+ path = lands ?? absolute;
901
1111
  }
902
1112
  try {
903
1113
  const secret = guardPath(path) ?? guardPath(realAncestor(path));
904
1114
  // Every root can be read; only the project (the first) can be written. A job's own folder holds what judges it.
905
- if (input.command !== 'view' && ctx.roots.length > 1) {
1115
+ if (input.command !== 'view' && !opened && ctx.roots.length > 1) {
906
1116
  try {
907
1117
  jailed(input.path, { cwd: ctx.cwd, roots: ctx.roots.slice(0, 1) });
908
1118
  } catch {
@@ -914,6 +1124,11 @@ export function runEditor(input, ctx) {
914
1124
  const at = realAncestor(path);
915
1125
  const kept = readOnlyPlaces(ctx.roots).find((place) => path === place || path.startsWith(`${place}${sep}`) || at === place || at.startsWith(`${place}${sep}`));
916
1126
  if (kept) return result(`${path} is git's own hooks or configuration: not changed here — what git runs by itself would run outside the sandbox. Say in your report what it needs.`, true);
1127
+ // What something else reads later — the shell at its start, a tool before it runs, an editor — is changed only when the user says so, this once.
1128
+ const guarded = guardedWhy(path, { roots: ctx.roots }) ?? guardedWhy(at, { roots: ctx.roots });
1129
+ if (guarded && ctx.granted !== path) return askFirst(`${path} is changed only when the user says so: ${guarded}`, path, { outside: false, guarded });
1130
+ // A hard link is the same file under another name, perhaps one outside the project or guarded: no path check sees it.
1131
+ if (existsSync(path) && lstatSync(path).isFile() && lstatSync(path).nlink > 1 && ctx.granted !== path) return askFirst(`${path} is changed only when the user says so: ${HARD_LINK}`, path, { outside: false, guarded: HARD_LINK });
917
1132
  }
918
1133
  switch (input.command) {
919
1134
  case 'view': {
@@ -934,7 +1149,7 @@ export function runEditor(input, ctx) {
934
1149
  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);
935
1150
  }
936
1151
  mkdirSync(dirname(path), { recursive: true });
937
- const said = change(path, ctx, () => writeFileSync(path, String(input.file_text ?? ''), { flag: 'wx' }), { created: true });
1152
+ const said = change(path, ctx, () => writeTo(path, String(input.file_text ?? ''), { create: true }), { created: true });
938
1153
  return result(said(`created ${path}`));
939
1154
  }
940
1155
  case 'str_replace': {
@@ -946,13 +1161,13 @@ export function runEditor(input, ctx) {
946
1161
  if (gap) return result(gap, true);
947
1162
  const where = locate(text, input.old_str);
948
1163
  if (!where) return result(`old_str was not found in ${path}`, true);
949
- if (where.hits !== 1) return result(`old_str appears ${where.hits} times in ${path} — include more context so it is unique`, true);
1164
+ if (where.hits !== 1) return result(`old_str appears ${where.hits} times in ${path}${linesOf(text, input.old_str)} — include more context so it is unique`, true);
950
1165
  let replacement = String(input.new_str ?? '');
951
1166
  if (where.how) {
952
1167
  if (text.includes('\r\n')) replacement = replacement.replace(/\r?\n/g, '\r\n');
953
1168
  if (where.reindent) replacement = where.reindent(replacement);
954
1169
  }
955
- const said = change(path, ctx, () => writeFileSync(path, `${text.slice(0, where.start)}${replacement}${text.slice(where.end)}`));
1170
+ const said = change(path, ctx, () => writeTo(path, `${text.slice(0, where.start)}${replacement}${text.slice(where.end)}`));
956
1171
  return { ...result(said(`edited ${path}${where.how ? ` (old_str matched ${where.how})` : ''}`)), edit: changeOf(text, where, replacement) };
957
1172
  }
958
1173
  case 'insert': {
@@ -968,7 +1183,7 @@ export function runEditor(input, ctx) {
968
1183
  // A file ending in a newline splits to a last empty piece, which is not a line to insert after.
969
1184
  const at = Math.max(0, Math.min(lines.at(-1) === '' ? lines.length - 1 : lines.length, line));
970
1185
  lines.splice(at, 0, text.replace(/\n$/, ''));
971
- const said = change(path, ctx, () => writeFileSync(path, lines.join('\n')));
1186
+ const said = change(path, ctx, () => writeTo(path, lines.join('\n')));
972
1187
  return { ...result(said(`inserted into ${path} after line ${at}`)), edit: { line: at + 1, old: '', new: redact(text.replace(/\n$/, '')).text } };
973
1188
  }
974
1189
  default:
@@ -979,9 +1194,31 @@ export function runEditor(input, ctx) {
979
1194
  }
980
1195
  }
981
1196
 
1197
+ /**
1198
+ * A change the editor refused — a file outside the project, or a guarded one — put to whoever is there (`ctx.approve`,
1199
+ * the question a blocked command is put with): the file and the change, to make once; or, outside the project and not
1200
+ * guarded, this file or its directory for the rest of the session (`ctx.opened`), which the shell then writes too.
1201
+ * With nobody there, the model is told to report it.
1202
+ */
1203
+ async function askUser(input, refused, ctx, signal) {
1204
+ const { ask } = refused;
1205
+ if (!ctx.approve) return result(`${refused.content}\n(nobody is here to allow it: report it, with the path and the change, so the user can make it themselves)`, true);
1206
+ const stopped = new Promise((resolve) => signal?.addEventListener('abort', () => resolve('no'), { once: true }));
1207
+ const answer = signal?.aborted ? 'no' : await Promise.race([ctx.approve({ name: EDITOR_TOOL.name, server: 'editor', tool: ask.guarded ? 'a guarded file' : 'outside the project', input, ...ask, signal }), stopped]);
1208
+ const session = !ask.guarded && (answer === 'always' || answer === 'directory');
1209
+ if (answer !== 'once' && !session) return { ...result(`${refused.content}\n(the user declined changing it: do not try again; carry on another way, or ask the user)${saidWhy(answer)}`, true), shown: declinedShown('not changed', answer) };
1210
+ if (session) ctx.opened?.add(answer === 'directory' && ask.directory ? ask.directory : ask.path);
1211
+ const again = runEditor(input, { ...ctx, granted: ask.path });
1212
+ const why = ask.guarded ? 'is a guarded file' : 'is outside the project';
1213
+ return { ...again, content: `(${ask.path} ${why}; the user allowed this change)\n${again.content}` };
1214
+ }
1215
+
982
1216
  /** One tool call, whichever tool it names; a name nothing answers to is an error the model can read. */
983
- export function runTool(block, ctx, { signal = null, onOutput = null } = {}) {
1217
+ export async function runTool(block, ctx, { signal = null, onOutput = null } = {}) {
984
1218
  if (block.name === BASH_TOOL.name) return runBash(block.input ?? {}, ctx, { signal, onOutput });
985
- if (block.name === EDITOR_TOOL.name) return runEditor(block.input ?? {}, ctx);
1219
+ if (block.name === EDITOR_TOOL.name) {
1220
+ const out = runEditor(block.input ?? {}, ctx);
1221
+ return out.ask ? askUser(block.input ?? {}, out, ctx, signal) : out;
1222
+ }
986
1223
  return result(`no tool called ${block.name}`, true);
987
1224
  }