sumo-agents 0.7.1 → 0.8.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/tools.mjs CHANGED
@@ -1,5 +1,6 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { spawn, spawnSync } from 'node:child_process';
2
- import { accessSync, closeSync, constants, existsSync, fstatSync, ftruncateSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
+ import { accessSync, closeSync, constants, existsSync, fstatSync, ftruncateSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from 'node:fs';
3
4
  import { homedir, tmpdir } from 'node:os';
4
5
  import { delimiter, dirname, extname, join, relative, resolve, sep } from 'node:path';
5
6
  import { CREDENTIAL_NAMES } from './auth.mjs';
@@ -7,7 +8,7 @@ import { guardCommand, guardPath } from './guard.mjs';
7
8
  import { SELF } from './paths.mjs';
8
9
  import { readPlainFile } from './scan.mjs';
9
10
  import { redact } from './redact.mjs';
10
- import { blockedWrite, guardedPlaces, guardedWhy, readOnlyPlaces, sandboxWrap, unsandboxable, writablePlaces } from './sandbox.mjs';
11
+ import { blockedWrite, guardedPlaces, guardedWhy, ownGit, readOnlyPatterns, readOnlyPlaces, sandboxWrap, unsandboxable, writablePlaces } from './sandbox.mjs';
11
12
 
12
13
  /**
13
14
  * The two tools a job gets, and the policy every call passes through before it
@@ -165,7 +166,7 @@ const NO_PROMPTS = { GIT_TERMINAL_PROMPT: '0', GIT_EDITOR: 'true', GIT_PAGER: 'c
165
166
  const sshCommands = new Map();
166
167
  function hasSshCommand(cwd, env) {
167
168
  if (!sshCommands.has(cwd)) {
168
- const asked = spawnSync('git', ['config', '--get', 'core.sshCommand'], { cwd, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: PARSE_TIMEOUT_MS });
169
+ const asked = spawnSync('git', ownGit(['config', '--get', 'core.sshCommand']), { cwd, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: PARSE_TIMEOUT_MS });
169
170
  sshCommands.set(cwd, asked.status === 0 && asked.stdout.trim() !== '');
170
171
  }
171
172
  return sshCommands.get(cwd);
@@ -436,10 +437,11 @@ function jailOf(ctx) {
436
437
  toldUnsandboxed = true;
437
438
  return { wrap: null, writable: [], readOnly: [], note };
438
439
  }
439
- const writable = writablePlaces(ctx.roots, { opened: ctx.opened ?? [] });
440
+ // Every root can be read; only the project (the first) is written, as the editor writes it — a job's own folder holds what judges it.
441
+ const writable = writablePlaces(ctx.roots.slice(0, 1), { opened: ctx.opened ?? [] });
440
442
  const readOnly = [...new Set([...readOnlyPlaces(ctx.roots), ...guardedPlaces(ctx.roots)])];
441
443
  const offline = ctx.network === false;
442
- return { wrap: sandboxWrap(writable, { readOnly, network: !offline }), writable, readOnly, offline, note: '' };
444
+ return { wrap: sandboxWrap(writable, { readOnly, patterns: readOnlyPatterns(ctx.roots), network: !offline }), writable, readOnly, offline, note: '' };
443
445
  }
444
446
 
445
447
  /** What a job's own tools run the project's checks under: the sandbox its shell is in, or nothing where the shell has none. */
@@ -515,7 +517,9 @@ async function runInBackground(command, ctx, { env, jail }) {
515
517
  try {
516
518
  mkdirSync(dir, { recursive: true, mode: 0o700 });
517
519
  log = join(dir, `${Date.now()}-${process.pid}-${spilled++}.log`);
518
- fd = openSync(log, 'a', 0o600);
520
+ // Made new, never through a link: the folder may be the temporary one, which the sandboxed shell writes too, and a
521
+ // link it planted at this name would have sumo — outside the sandbox — append the command's output wherever it leads.
522
+ fd = openSync(log, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_APPEND | constants.O_NOFOLLOW, 0o600);
519
523
  } catch (cause) {
520
524
  return result(`the command could not be started in the background: there is nowhere to write its log (${cause.message})`, true);
521
525
  }
@@ -709,18 +713,20 @@ async function blocked(command, shown, ctx, jail, options) {
709
713
 
710
714
  /** How much of a file is looked at to tell a binary from text: a NUL byte in its first pages is one. */
711
715
  const BINARY_PROBE_BYTES = 8192;
716
+ /** The most a view reads: it shows a few hundred lines, and a file past this is looked at in parts, in the shell. */
717
+ const VIEW_MAX_BYTES = 64 * 1024 * 1024;
712
718
 
713
719
  function view(path, range) {
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
+ // Judged and read through one descriptor that never waits: a FIFO or a device is said to be one, never read.
721
+ const text = readPlainFile(path, VIEW_MAX_BYTES);
722
+ if (text === null) {
723
+ const stat = statSync(path);
724
+ if (stat.isDirectory()) return result(cap(readdirSync(path).join('\n')));
725
+ return result(stat.isFile() ? `${path} is ${stat.size} bytes, too big to view whole — look at a part of it in the shell: sed -n '1,200p', tail or grep` : notPlain(path, stat), true);
720
726
  }
721
727
  // A binary shown as text is pages of nonsense, every page billed: say what it is instead.
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);
723
- const lines = bytes.toString('utf8').split('\n');
728
+ if (text.slice(0, BINARY_PROBE_BYTES).includes('\0')) return result(`${path} is a binary file (${statSync(path).size} bytes) — not shown; use a tool that reads its kind, or \`file\` and \`xxd | head\` for a look`, true);
729
+ const lines = text.split('\n');
724
730
  let [from, to] = Array.isArray(range) && range.length === 2 ? range : [1, lines.length];
725
731
  from = Math.max(1, from);
726
732
  to = to === -1 ? lines.length : Math.min(lines.length, to);
@@ -827,13 +833,14 @@ const PY_PARSE = 'import ast,sys,traceback\ntry: ast.parse(open(sys.argv[1], "rb
827
833
  * or the parser is missing or too slow to say. `.js .mjs .cjs` by `node --check`, `.json` here, `.py` and `.go` by
828
834
  * their own tools when they are on the PATH.
829
835
  */
830
- function parseError(path, ctx) {
836
+ function parseError(path, ctx, text) {
831
837
  const env = ctx.env ?? childEnv();
832
838
  const ext = extname(path);
833
839
  let run;
840
+ // JSON is parsed here, from the text the editor read or wrote: a name looked up again could be anything by now.
834
841
  if (ext === '.json') {
835
842
  try {
836
- JSON.parse(readFileSync(path, 'utf8'));
843
+ JSON.parse(text);
837
844
  return null;
838
845
  } catch (cause) {
839
846
  return cause.message;
@@ -868,23 +875,16 @@ function undoTurns(sessionDir) {
868
875
  /** The folder the coming turn's undo goes in — made only when the editor first changes a file in it. */
869
876
  export const nextUndoTurn = (sessionDir) => join(sessionDir, String((undoTurns(sessionDir).at(-1) ?? 0) + 1));
870
877
 
871
- const readManifest = (turnDir) => {
872
- try {
873
- return JSON.parse(readFileSync(join(turnDir, MANIFEST), 'utf8'));
874
- } catch {
875
- return null;
876
- }
877
- };
878
+ export const digest = (data) => createHash('sha256').update(data).digest('hex');
878
879
 
879
880
  /**
880
- * After the editor's first change to a file in a turn: what the file held before it (`before`, its bytes), or that it
881
- * was not there (null), kept in the turn's folder for /undo, readable by the user alone. A later change to it in the same
882
- * turn keeps nothing — /undo goes back to before the turn. The turn that starts a folder lets go of the oldest beyond
883
- * UNDO_TURNS, and of the undo of sessions long untouched.
881
+ * Keep the original bytes once, and what the file holds after the editor's last write: /undo judges it by that, not by its
882
+ * inode. `landed` is where the write went — the real path the checks settled on, and the descriptor's own stat after it —
883
+ * never the name looked up again: a link put there since would be taken for the file, and /undo would write through it.
884
884
  */
885
- function keepForUndo(turnDir, path, before) {
886
- const manifest = readManifest(turnDir) ?? [];
887
- if (manifest.some((entry) => entry.path === path)) return;
885
+ function keepForUndo(turnDir, path, before, written, { target, stat }) {
886
+ const file = join(turnDir, MANIFEST);
887
+ const manifest = existsSync(turnDir) ? JSON.parse(readFileSync(file, 'utf8')) : [];
888
888
  if (manifest.length === 0) {
889
889
  const sessionDir = dirname(turnDir);
890
890
  mkdirSync(turnDir, { recursive: true, mode: 0o700 });
@@ -895,61 +895,122 @@ function keepForUndo(turnDir, path, before) {
895
895
  if (other !== sessionDir && Date.now() - statSync(other).mtimeMs > UNDO_KEEP_MS) rmSync(other, { recursive: true, force: true });
896
896
  }
897
897
  }
898
- const kept = before === null ? null : String(manifest.length);
899
- if (kept !== null) writeFileSync(join(turnDir, kept), before, { mode: 0o600 });
900
- manifest.push({ path, kept, mode: kept === null ? null : statSync(path).mode & 0o777 });
901
- writeFileSync(join(turnDir, MANIFEST), JSON.stringify(manifest), { mode: 0o600 });
898
+ let entry = manifest.find((item) => item.path === path || item.target === target);
899
+ if (!entry) {
900
+ const kept = before === null ? null : String(manifest.length);
901
+ if (kept !== null) writeFileSync(join(turnDir, kept), before, { mode: 0o600, flag: 'wx' });
902
+ entry = { path, target, kept, original: before === null ? null : digest(before), nlink: stat.nlink };
903
+ manifest.push(entry);
904
+ } else if (before === null || entry.after !== digest(before) || entry.target !== target || entry.nlink !== stat.nlink) {
905
+ entry.conflict = true; // A later editor write cannot claim an intervening change as its own.
906
+ }
907
+ entry.after = digest(written);
908
+ writeFileSync(file + '.tmp', JSON.stringify(manifest), { mode: 0o600 });
909
+ renameSync(file + '.tmp', file);
902
910
  }
903
911
 
912
+ /** A file that no longer holds what the editor left in it: someone's work since, kept as it is. */
913
+ const notAsLeft = (message) => Object.assign(new Error(message), { changed: true });
914
+
904
915
  /**
905
- * /undo: every file the session's last kept turn changed, put back as it was before that turn — a file it created is
906
- * deleted — and the turn let go, so the next /undo reaches the one before. Null when there is none to undo.
916
+ * Check every destination and backup before touching the first file. A file changed since the editor wrote it keeps the
917
+ * whole turn for the user to put back and retry; asked again over the same file, the turn is let go, the file kept as it
918
+ * is, so the turns before it can still be undone.
907
919
  */
908
920
  export function undoLast(sessionDir) {
909
- for (const n of undoTurns(sessionDir).reverse()) {
910
- const turnDir = join(sessionDir, String(n));
911
- const manifest = readManifest(turnDir);
912
- if (!manifest) {
921
+ const n = undoTurns(sessionDir).at(-1);
922
+ if (n === undefined) return null;
923
+ const turnDir = join(sessionDir, String(n));
924
+ const cursor = join(turnDir, 'restoring');
925
+ const refused = join(turnDir, 'refused');
926
+ let manifest, start, plan;
927
+ try {
928
+ manifest = JSON.parse(readFileSync(join(turnDir, MANIFEST), 'utf8'));
929
+ if (!Array.isArray(manifest) || !manifest.length) throw new Error('the undo record is incomplete');
930
+ // The cursor is written before each mutation. After an interruption, recognise a completed
931
+ // write or unlink at the cursor, and leave already restored files alone on the next /undo.
932
+ const resuming = existsSync(cursor);
933
+ start = resuming ? JSON.parse(readFileSync(cursor, 'utf8')) : 0;
934
+ if (!Number.isInteger(start) || start < 0 || start >= manifest.length) throw new Error('invalid undo progress');
935
+ plan = manifest.slice(start).map(({ path, target, kept, original, after, nlink, conflict }, offset) => {
936
+ if (!after || !target) throw new Error(`the saved record for ${path} has no verifiable after-state`);
937
+ if (conflict) throw notAsLeft(`${path} was changed outside the editor during this turn`);
938
+ const atCursor = resuming && offset === 0;
939
+ const stat = statSync(path, { throwIfNoEntry: false });
940
+ // A file the turn made that is gone already is as it was before the turn.
941
+ if (kept === null && original === null && !stat && !lstatSync(target, { throwIfNoEntry: false })) return null;
942
+ if (!stat?.isFile() || realpathSync.native(path) !== target || stat.nlink !== nlink) throw notAsLeft(`${path} was removed or replaced`);
943
+ const content = digest(readFileSync(target));
944
+ if (atCursor && kept !== null && content === original) return null;
945
+ if (content !== after) throw notAsLeft(`${path} changed after the editor wrote it`);
946
+ const remove = kept === null && original === null;
947
+ if (remove) accessSync(dirname(target), constants.W_OK | constants.X_OK);
948
+ else if (kept !== String(start + offset)) throw new Error(`invalid backup for ${path}`);
949
+ else accessSync(target, constants.W_OK);
950
+ const bytes = remove ? null : readFileSync(join(turnDir, kept));
951
+ if (bytes !== null && digest(bytes) !== original) throw new Error(`the backup for ${path} has changed`);
952
+ return { path, target, stat, after, bytes };
953
+ });
954
+ } catch (cause) {
955
+ if (!cause.changed) return { blocked: `undo stopped before changing any files: ${cause.message}. The saved turn is at ${turnDir}.` };
956
+ let refusedBefore = null;
957
+ try {
958
+ refusedBefore = readFileSync(refused, 'utf8');
959
+ } catch {
960
+ // Not refused before: this is the first time.
961
+ }
962
+ if (refusedBefore === cause.message) {
913
963
  rmSync(turnDir, { recursive: true, force: true });
914
- continue;
964
+ return { blocked: `undo let go of the last turn without changing any more files: ${cause.message}, and it is kept as it is. /undo again reaches the turn before.` };
915
965
  }
916
- const done = { restored: [], deleted: [] };
917
- for (const { path, kept, mode } of manifest) {
918
- if (kept === null) {
919
- rmSync(path, { force: true });
920
- done.deleted.push(path);
921
- } else {
922
- mkdirSync(dirname(path), { recursive: true });
923
- writeFileSync(path, readFileSync(join(turnDir, kept)), { mode: mode ?? 0o644 });
924
- done.restored.push(path);
966
+ writeFileSync(refused, cause.message, { mode: 0o600 });
967
+ return { blocked: `undo stopped before changing any files: ${cause.message}. Put it back as the editor left it and /undo again — or /undo again to let that turn go and keep it as it is. The saved turn is at ${turnDir}.` };
968
+ }
969
+ try {
970
+ for (const [offset, entry] of plan.entries()) {
971
+ if (!entry) continue;
972
+ const { path, target, stat, after, bytes } = entry;
973
+ writeFileSync(cursor + '.tmp', String(start + offset), { mode: 0o600 });
974
+ renameSync(cursor + '.tmp', cursor);
975
+ const current = statSync(path);
976
+ if (realpathSync.native(path) !== target || current.dev !== stat.dev || current.ino !== stat.ino || current.nlink !== stat.nlink || digest(readFileSync(target)) !== after) {
977
+ throw new Error(`${path} changed while undo was running`);
925
978
  }
979
+ if (bytes === null) rmSync(target);
980
+ else writeTo(target, bytes, current);
926
981
  }
927
982
  rmSync(turnDir, { recursive: true, force: true });
928
- return done;
983
+ } catch (cause) {
984
+ return { blocked: `undo stopped while restoring files: ${cause.message}. Progress is saved in ${turnDir}. Retry /undo to resume.` };
929
985
  }
930
- return null;
986
+ const done = { restored: [], deleted: [] };
987
+ for (const { path, kept } of manifest) (kept === null ? done.deleted : done.restored).push(path);
988
+ return done;
931
989
  }
932
990
 
933
991
  /**
934
992
  * One change to a file by the editor, and what is owed around it: what the file held is kept for /undo (`ctx.undo`, the
935
993
  * chat's turn folder), a change on disk since the model saw it is said first, and a parse the change broke — one that held
936
- * before it — is said after. `created`: the file was not there, so it parsed before as far as anyone is concerned.
994
+ * before it — is said after. `file`: the descriptor `openChecked` holds, read and written through; with none the file is
995
+ * made at `target`, where the checks found it lands — it was not there, so it parsed before as far as anyone is concerned.
937
996
  */
938
- function change(path, ctx, write, { created = false } = {}) {
997
+ function change(path, ctx, written, { file = null, target = null } = {}) {
998
+ const created = file === null;
939
999
  const stale = created ? null : changedSince(path, ctx);
940
- const before = ctx.undo && !created ? readFileSync(path) : null;
941
- const broken = created ? null : parseError(path, ctx);
942
- write();
1000
+ const before = ctx.undo && !created ? file.bytes : null;
1001
+ const broken = created ? null : parseError(path, ctx, file.bytes.toString('utf8'));
1002
+ const where = created ? (target ?? path) : file.target;
1003
+ const stat = created ? writeTo(where, written) : writeThrough(path, file, written);
943
1004
  // Kept once the write has gone through: a change refused — a create of a file already there — has nothing to undo. A keep
944
1005
  // that fails is said, not thrown: the change is made, and a model told it failed would make it twice.
945
1006
  let unkept = null;
946
1007
  try {
947
- if (ctx.undo) keepForUndo(ctx.undo, path, before);
1008
+ if (ctx.undo) keepForUndo(ctx.undo, path, before, written, { target: where, stat });
948
1009
  } catch (cause) {
949
1010
  unkept = `(this change could not be kept for /undo: ${cause.message})`;
950
1011
  }
951
1012
  if (created || ctx.seen?.has(path)) seenIn(ctx).set(path, stampOf(path));
952
- const now = broken === null ? parseError(path, ctx) : null;
1013
+ const now = broken === null ? parseError(path, ctx, written) : null;
953
1014
  return (said) => [stale, said, unkept, now && `The file no longer parses:\n${now}`].filter(Boolean).join('\n');
954
1015
  }
955
1016
 
@@ -1037,25 +1098,63 @@ function linesOf(text, old) {
1037
1098
  /** Why a file with another name is asked about each time. */
1038
1099
  const HARD_LINK = 'it has another name elsewhere (a hard link), and a change here changes that file too';
1039
1100
 
1101
+ /** What the editor says when the file it checked is not the one at that name any more. */
1102
+ const replaced = (path) => `${path} was replaced while it was being changed; nothing was written — view it again`;
1103
+ /** Why a path that is not a plain file is neither read nor written: a FIFO would wait on a writer for good, a device never ends. */
1104
+ const notPlain = (path, stat) => `${path} is ${stat.isDirectory() ? 'a directory' : 'not a plain file (a FIFO, a device or a socket)'} — not opened; look at it in the shell if it is safe to`;
1105
+
1106
+ /** Bytes put in place of a file's, from its start, through a descriptor already open on it. */
1107
+ function overwrite(fd, data) {
1108
+ const bytes = Buffer.from(data);
1109
+ ftruncateSync(fd, 0);
1110
+ for (let at = 0; at < bytes.length; ) at += writeSync(fd, bytes, at, bytes.length - at, at);
1111
+ }
1112
+
1040
1113
  /**
1041
- * A file the editor writes, written where its checks found it lands: through no link swapped in since — the last name
1042
- * is opened without following one — and only when the file opened is the one that was checked. Nothing is truncated
1043
- * before that. (A folder above it swapped for a link between the check and the open is not caught: Node has no openat.)
1114
+ * A file written at its real path, never looked up again: made new (`expected` null, and never through a link), or
1115
+ * written over only when the file opened there — the last name not followed — is the one `expected` names. Nothing is
1116
+ * truncated before that. (A folder above it swapped for a link between the check and the open is not caught: Node has no openat.)
1117
+ * Returns the stat of what was written, from its descriptor.
1044
1118
  */
1045
- function writeTo(path, data, { create = false } = {}) {
1046
- const target = landsAt(path) ?? path;
1047
- const before = create ? null : statSync(target);
1048
- const fd = openSync(target, constants.O_WRONLY | constants.O_NOFOLLOW | (create ? constants.O_CREAT | constants.O_EXCL : 0), 0o666);
1119
+ function writeTo(target, data, expected = null) {
1120
+ const fd = openSync(target, constants.O_WRONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK | (expected ? 0 : constants.O_CREAT | constants.O_EXCL), 0o666);
1049
1121
  try {
1050
1122
  const opened = fstatSync(fd);
1051
- 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`);
1052
- ftruncateSync(fd, 0);
1053
- writeFileSync(fd, data);
1123
+ if (expected && (!opened.isFile() || opened.ino !== expected.ino || opened.dev !== expected.dev)) throw new Error(replaced(target));
1124
+ overwrite(fd, data);
1125
+ return fstatSync(fd);
1054
1126
  } finally {
1055
1127
  closeSync(fd);
1056
1128
  }
1057
1129
  }
1058
1130
 
1131
+ /**
1132
+ * A file the editor changes, opened once where its checks found it lands (`target`, a real path; `checked`, its lstat
1133
+ * then): read and later written through this one descriptor, so what is written is what was read and judged. The last
1134
+ * name is not followed, nothing but a plain file is opened, and nothing that waits on a writer.
1135
+ */
1136
+ function openChecked(path, target, checked) {
1137
+ if (!checked) throw new Error(`${path} does not exist`);
1138
+ if (!checked.isFile()) throw new Error(notPlain(path, checked));
1139
+ const fd = openSync(target, constants.O_RDWR | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1140
+ try {
1141
+ const stat = fstatSync(fd);
1142
+ if (!stat.isFile() || stat.dev !== checked.dev || stat.ino !== checked.ino) throw new Error(replaced(path));
1143
+ return { fd, target, stat, bytes: readFileSync(fd) };
1144
+ } catch (cause) {
1145
+ closeSync(fd);
1146
+ throw cause;
1147
+ }
1148
+ }
1149
+
1150
+ /** The change written through the descriptor `openChecked` holds — and only while the name still leads to that file: a link or another file put there since is neither written through nor said to be changed. Returns the descriptor's stat after it. */
1151
+ function writeThrough(path, file, data) {
1152
+ const now = lstatSync(file.target, { throwIfNoEntry: false });
1153
+ if (!now?.isFile() || now.dev !== file.stat.dev || now.ino !== file.stat.ino) throw new Error(replaced(path));
1154
+ overwrite(file.fd, data);
1155
+ return fstatSync(file.fd);
1156
+ }
1157
+
1059
1158
  /** The text editor's four commands, each inside the jail; secret files are neither shown nor written. */
1060
1159
  /** 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). */
1061
1160
  function openedIn(ctx, path) {
@@ -1125,16 +1224,28 @@ export function runEditor(input, ctx) {
1125
1224
  return result(`${path} can be read, not changed — only files in the project (${ctx.roots[0]}) are edited`, true);
1126
1225
  }
1127
1226
  }
1227
+ // Where a write lands, decided here once — its real path, and the file there as it is now — and carried to the write,
1228
+ // which opens that and nothing else: a name swapped for a link while the work goes on cannot move it.
1229
+ const target = input.command === 'view' ? null : landsAt(path);
1230
+ const checked = target === null ? null : (lstatSync(target, { throwIfNoEntry: false }) ?? null);
1128
1231
  // What git runs by itself — a hook on the next commit, a command its config names — runs outside the sandbox: the shell cannot write it, nor can this.
1232
+ // Each check is made of the name given, the deepest folder there, and where the write lands: a link in the project to the
1233
+ // project (`ln -s . sub`) makes `sub/.npmrc` a new `.npmrc` at its top, which neither of the first two names.
1129
1234
  if (input.command !== 'view') {
1235
+ if (target === null) return result(`${path} goes through a link to something not there yet — not written: say in your report what it needs`, true);
1130
1236
  const at = realAncestor(path);
1131
- const kept = readOnlyPlaces(ctx.roots).find((place) => path === place || path.startsWith(`${place}${sep}`) || at === place || at.startsWith(`${place}${sep}`));
1237
+ const kept = readOnlyPlaces(ctx.roots).find((place) => [path, at, target].some((p) => p === place || p.startsWith(`${place}${sep}`)));
1132
1238
  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);
1239
+ const hidden = secret ?? guardPath(target);
1240
+ if (hidden) return result(hidden, true);
1133
1241
  // 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.
1134
1242
  const guarded = guardedWhy(path, { roots: ctx.roots }) ?? guardedWhy(at, { roots: ctx.roots });
1135
1243
  if (guarded && ctx.granted !== path) return askFirst(`${path} is changed only when the user says so: ${guarded}`, path, { outside: false, guarded });
1244
+ const lands = guarded ? null : guardedWhy(target, { roots: ctx.roots });
1245
+ if (lands && ctx.granted !== target) return askFirst(`${path} (a link to ${target}) is changed only when the user says so: ${lands}`, target, { outside: false, guarded: lands });
1136
1246
  // A hard link is the same file under another name, perhaps one outside the project or guarded: no path check sees it.
1137
- 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 });
1247
+ // Judged on the file the write lands on, so a link to it is no way round.
1248
+ if (checked?.isFile() && checked.nlink > 1 && ctx.granted !== path) return askFirst(`${path} is changed only when the user says so: ${HARD_LINK}`, path, { outside: false, guarded: HARD_LINK });
1138
1249
  }
1139
1250
  switch (input.command) {
1140
1251
  case 'view': {
@@ -1160,45 +1271,56 @@ export function runEditor(input, ctx) {
1160
1271
  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);
1161
1272
  }
1162
1273
  mkdirSync(dirname(path), { recursive: true });
1163
- const said = change(path, ctx, () => writeTo(path, String(input.file_text ?? ''), { create: true }), { created: true });
1274
+ const said = change(path, ctx, String(input.file_text ?? ''), { target });
1164
1275
  return result(said(`created ${path}`));
1165
1276
  }
1166
1277
  case 'str_replace': {
1167
1278
  if (secret) return result(secret, true);
1168
1279
  if (!input.old_str) return result('str_replace needs old_str', true);
1169
1280
  if (input.new_str !== undefined && input.old_str === input.new_str) return result('old_str and new_str are the same — nothing would change', true);
1170
- const text = readFileSync(path, 'utf8');
1171
- const gap = placeholderIn(path, 'new_str', input.new_str, text);
1172
- if (gap) return result(gap, true);
1173
- const where = locate(text, input.old_str);
1174
- if (!where) return result(`old_str was not found in ${path}`, true);
1175
- 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);
1176
- let replacement = String(input.new_str ?? '');
1177
- if (where.how) {
1178
- if (text.includes('\r\n')) replacement = replacement.replace(/\r?\n/g, '\r\n');
1179
- if (where.reindent) replacement = where.reindent(replacement);
1281
+ const file = openChecked(path, target, checked);
1282
+ try {
1283
+ const text = file.bytes.toString('utf8');
1284
+ const gap = placeholderIn(path, 'new_str', input.new_str, text);
1285
+ if (gap) return result(gap, true);
1286
+ const where = locate(text, input.old_str);
1287
+ if (!where) return result(`old_str was not found in ${path}`, true);
1288
+ 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);
1289
+ let replacement = String(input.new_str ?? '');
1290
+ if (where.how) {
1291
+ if (text.includes('\r\n')) replacement = replacement.replace(/\r?\n/g, '\r\n');
1292
+ if (where.reindent) replacement = where.reindent(replacement);
1293
+ }
1294
+ const said = change(path, ctx, `${text.slice(0, where.start)}${replacement}${text.slice(where.end)}`, { file });
1295
+ return { ...result(said(`edited ${path}${where.how ? ` (old_str matched ${where.how})` : ''}`)), edit: changeOf(text, where, replacement) };
1296
+ } finally {
1297
+ closeSync(file.fd);
1180
1298
  }
1181
- const said = change(path, ctx, () => writeTo(path, `${text.slice(0, where.start)}${replacement}${text.slice(where.end)}`));
1182
- return { ...result(said(`edited ${path}${where.how ? ` (old_str matched ${where.how})` : ''}`)), edit: changeOf(text, where, replacement) };
1183
1299
  }
1184
1300
  case 'insert': {
1185
1301
  if (secret) return result(secret, true);
1186
- const lines = readFileSync(path, 'utf8').split('\n');
1187
- const line = Number(input.insert_line ?? 0);
1188
- if (!Number.isInteger(line)) return result('insert needs insert_line: the number of the line to insert after, 0 for the top of the file', true);
1189
- // The tool sends the text as insert_text, a line with its newline; new_str is what an earlier version of the tool sent.
1190
- const text = input.insert_text ?? input.new_str;
1191
- if (typeof text !== 'string') return result('insert needs insert_text: the text to insert', true);
1192
- const gap = placeholderIn(path, input.insert_text === undefined ? 'new_str' : 'insert_text', text, lines.join('\n'));
1193
- if (gap) return result(gap, true);
1194
- // A file ending in a newline splits to a last empty piece, which is not a line to insert after.
1195
- const at = Math.max(0, Math.min(lines.at(-1) === '' ? lines.length - 1 : lines.length, line));
1196
- lines.splice(at, 0, text.replace(/\n$/, ''));
1197
- const said = change(path, ctx, () => writeTo(path, lines.join('\n')));
1198
- return { ...result(said(`inserted into ${path} after line ${at}`)), edit: { line: at + 1, old: '', new: redact(text.replace(/\n$/, '')).text } };
1302
+ const file = openChecked(path, target, checked);
1303
+ try {
1304
+ const lines = file.bytes.toString('utf8').split('\n');
1305
+ const line = Number(input.insert_line ?? 0);
1306
+ if (!Number.isInteger(line)) return result('insert needs insert_line: the number of the line to insert after, 0 for the top of the file', true);
1307
+ // The tool sends the text as insert_text, a line with its newline; new_str is what an earlier version of the tool sent.
1308
+ const text = input.insert_text ?? input.new_str;
1309
+ if (typeof text !== 'string') return result('insert needs insert_text: the text to insert', true);
1310
+ const gap = placeholderIn(path, input.insert_text === undefined ? 'new_str' : 'insert_text', text, lines.join('\n'));
1311
+ if (gap) return result(gap, true);
1312
+ // A file ending in a newline splits to a last empty piece, which is not a line to insert after.
1313
+ const at = Math.max(0, Math.min(lines.at(-1) === '' ? lines.length - 1 : lines.length, line));
1314
+ lines.splice(at, 0, text.replace(/\n$/, ''));
1315
+ const said = change(path, ctx, lines.join('\n'), { file });
1316
+ return { ...result(said(`inserted into ${path} after line ${at}`)), edit: { line: at + 1, old: '', new: redact(text.replace(/\n$/, '')).text } };
1317
+ } finally {
1318
+ closeSync(file.fd);
1319
+ }
1199
1320
  }
1200
1321
  default:
1201
- return result(`unknown command ${input.command}`, true);
1322
+ // Said with the way out: a model that never saw this tool's own schema (Cursor's) guesses its shape at first.
1323
+ return result(`${input.command === undefined ? 'no command given' : `unknown command ${input.command}`} — command is one of view, create, str_replace, insert`, true);
1202
1324
  }
1203
1325
  } catch (cause) {
1204
1326
  return result(cause.message, true);
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 { ownGit } from './sandbox.mjs';
15
16
  import { keyName, settingsPage, SettingsView } from './settings.mjs';
16
17
  import { elapsed } from './text.mjs';
17
18
  import { cleanPaste, editor, keysOf, matchFiles, menuOf, paste, press, under } from './editor.mjs';
@@ -143,7 +144,7 @@ const inTerminal = (program, file) =>
143
144
  /** The files of the project at `cwd` as git knows them, the untracked ones it does not ignore included; none where there is no repository. */
144
145
  const gitFiles = (cwd) =>
145
146
  new Promise((resolve) => {
146
- execFile('git', ['ls-files', '-co', '--exclude-standard'], { cwd, maxBuffer: 32 * 1024 * 1024 }, (error, out) => resolve(error ? [] : out.split('\n').filter(Boolean)));
147
+ execFile('git', ownGit(['ls-files', '-co', '--exclude-standard']), { cwd, maxBuffer: 32 * 1024 * 1024 }, (error, out) => resolve(error ? [] : out.split('\n').filter(Boolean)));
147
148
  });
148
149
 
149
150
  /**
@@ -1461,9 +1462,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1461
1462
  }
1462
1463
  if (control === 'context') {
1463
1464
  record({ kind: 'user', text: line });
1464
- const turns = state.log.filter((entry) => entry.kind === 'user' && !/^[/!]/.test(entry.text)).length;
1465
- const calls = state.log.filter((entry) => entry.kind === 'tool').length;
1466
- return record({ kind: 'reply', raw: contextReport({ contextTokens: session.contextTokens, rows: session.usage(), turns, calls }), own: true });
1465
+ return record({ kind: 'reply', raw: contextReport({ contextTokens: session.contextTokens, rows: session.usage(), ...session.counts }), own: true });
1467
1466
  }
1468
1467
  if (control === 'thinking') {
1469
1468
  record({ kind: 'user', text: line });
@@ -1494,9 +1493,19 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1494
1493
  if (control === 'config') {
1495
1494
  record({ kind: 'user', text: line });
1496
1495
  const left = () => `${routeLine(session)} ${state.where.name}${state.where.branch ? ` (${state.where.branch})` : ''}`;
1497
- state.settings = settingsPage({ live: { route: (to) => session.route(to), servers: () => session.mcpServers(), left }, cwd: state.where.cwd, onChange: redraw });
1496
+ state.settings = settingsPage({ live: { route: (to) => session.route(to), current: () => ({ model: session.model, effort: session.effort }), servers: () => session.mcpServers(), left }, cwd: state.where.cwd, onChange: redraw });
1498
1497
  return;
1499
1498
  }
1499
+ // Each source as a step of its own, said as it is read; then what was saved, as a table.
1500
+ if (control === 'scorecard') {
1501
+ record({ kind: 'user', text: line });
1502
+ state.working = pickMessage(messages);
1503
+ redraw();
1504
+ const report = await session.scorecard((source) =>
1505
+ record({ kind: 'tool', call: { id: `scorecard-${source.id}`, name: 'Fetch', input: { text: source.name } }, result: { content: source.steps.join('\n'), isError: !source.ok }, took: source.ms }),
1506
+ );
1507
+ return record({ kind: 'reply', raw: report, own: true });
1508
+ }
1500
1509
  if (control === 'memory' || control === 'mcp' || control === 'undo') {
1501
1510
  record({ kind: 'user', text: line });
1502
1511
  const text = control === 'undo' ? session.undo() : control === 'mcp' ? (await session.mcp()).join('\n') : await session.memoryPage();