@alexwkleung/reika 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/config.js CHANGED
@@ -28,7 +28,8 @@ export function isDeniedFromProjectEnv(key) {
28
28
  export function applyProjectEnv(text, env) {
29
29
  const ignored = [];
30
30
  for (const [key, value] of Object.entries(dotenv.parse(text))) {
31
- if (!key.startsWith('REIKA_') || key in env)
31
+ // An empty line sets nothing, but would still claim the key ahead of ~/.config/reika/.env.
32
+ if (!key.startsWith('REIKA_') || key in env || value.trim() === '')
32
33
  continue;
33
34
  if (isDeniedFromProjectEnv(key))
34
35
  ignored.push(key);
@@ -116,7 +117,7 @@ export function loadConfig() {
116
117
  // A termination backstop for the spiral shapes the loop detectors miss, not a cost cap: a
117
118
  // cached round is nearly free on both local and API, so it is sized where a healthy complex
118
119
  // turn never lands and a spiral in headless (no ctrl-c) still ends in hours, not days.
119
- maxTurns: parseInt(process.env.REIKA_MAX_TURNS ?? '200', 10),
120
+ maxTurns: parseInt(process.env.REIKA_MAX_TURNS ?? '400', 10),
120
121
  repoMapBudget: parseIntOrUndef(process.env.REIKA_REPO_MAP_BUDGET),
121
122
  autoApprove: parseAutoApprove(process.env.REIKA_AUTO_APPROVE),
122
123
  autoApproveExplicit: (process.env.REIKA_AUTO_APPROVE ?? '').trim() !== '',
@@ -125,7 +126,7 @@ export function loadConfig() {
125
126
  subagentBaseURL: emptyToUndefined(process.env.REIKA_SUBAGENT_BASE_URL),
126
127
  subagentApiKey: emptyToUndefined(process.env.REIKA_SUBAGENT_API_KEY),
127
128
  // Not a backstop: the last round IS the report round (#340), so this stays tight.
128
- subagentMaxTurns: parseInt(process.env.REIKA_SUBAGENT_MAX_TURNS ?? '8', 10),
129
+ subagentMaxTurns: parseInt(process.env.REIKA_SUBAGENT_MAX_TURNS ?? '10', 10),
129
130
  visionModel: emptyToUndefined(process.env.REIKA_VISION_MODEL),
130
131
  visionBaseURL,
131
132
  visionApiKey: emptyToUndefined(process.env.REIKA_VISION_API_KEY),
@@ -119,6 +119,31 @@ export async function loadModelCatalog(path = MODEL_CATALOG_CACHE_PATH) {
119
119
  }
120
120
  return fetchCatalog(path);
121
121
  }
122
+ // Catalog bases on the same host as `baseURL`, other than itself. A provider that moves its API
123
+ // path (models.dev's opencode-go went from /zen/go/v1 to /inference/go/v1) leaves a profile on the
124
+ // old base with no entry, and the new base is what the user needs to see. Named, never used: two
125
+ // bases on one host can be two products, so picking one would be a guess.
126
+ export function sameHostBases(index, baseURL) {
127
+ let host;
128
+ try {
129
+ host = new URL(baseURL).host.toLowerCase();
130
+ }
131
+ catch {
132
+ return [];
133
+ }
134
+ const own = normalizeApiBase(baseURL);
135
+ return Object.keys(index)
136
+ .filter(base => base !== own && hostOf(base) === host)
137
+ .sort();
138
+ }
139
+ function hostOf(base) {
140
+ try {
141
+ return new URL(base).host.toLowerCase();
142
+ }
143
+ catch {
144
+ return undefined;
145
+ }
146
+ }
122
147
  // What startup and a /model switch need to ask about. An explicit window still leaves the output
123
148
  // limit open — the case the catalog exists for — but only a catalog-eligible host can answer it,
124
149
  // so a local server with REIKA_CONTEXT_WINDOW set sees no request at all.
@@ -143,6 +168,12 @@ export async function probeModelLimits(profile, catalog = loadModelCatalog) {
143
168
  return probe;
144
169
  const index = await catalog();
145
170
  const found = index && lookupModelLimits(index, profile.baseURL, profile.model);
171
+ if (index && wantWindow && !found?.window) {
172
+ probe.catalogMiss = {
173
+ baseListed: index[normalizeApiBase(profile.baseURL)] !== undefined,
174
+ sameHost: sameHostBases(index, profile.baseURL),
175
+ };
176
+ }
146
177
  if (!found)
147
178
  return probe;
148
179
  if (wantWindow && found.window) {
package/dist/session.js CHANGED
@@ -95,7 +95,7 @@ export async function createSession(opts) {
95
95
  changed();
96
96
  notices.push({ role: 'system', content: notice });
97
97
  }
98
- const warn = noWindowNotice(probe, before);
98
+ const warn = noWindowNotice(probe, before, name);
99
99
  if (warn)
100
100
  notices.push({ role: 'system', content: warn, tone: 'warn' });
101
101
  return notices;
@@ -286,7 +286,7 @@ export async function createSession(opts) {
286
286
  offline,
287
287
  searchNotice: offline ? undefined : searchPrecedenceNotice(chooseSearchBackend(cfg)),
288
288
  limitsNotice: probed && probedLimitsNotice(probed),
289
- windowNotice: probed && noWindowNotice(probed, startProfile),
289
+ windowNotice: probed && noWindowNotice(probed, startProfile, profile),
290
290
  mcp,
291
291
  // Config errors come first: they explain a server that never even started.
292
292
  mcpNotices: [...(cfg.mcpErrors ?? []), ...mcp.notices],
@@ -361,12 +361,28 @@ export function probedLimitsNotice(probe) {
361
361
  }
362
362
  // A server that answered without a window (Ollama, a router the catalog does not list) leaves the
363
363
  // session with no compaction and per-round payload aging, and nothing on screen would say why.
364
- // Not while the probe is unreached: the retry at the next submit may still find one.
365
- export function noWindowNotice(probe, before) {
364
+ // Not while the probe is unreached: the retry at the next submit may still find one. A hosted
365
+ // endpoint gets the catalog's side of it too: a provider that moved its URL on models.dev reads
366
+ // as "no window" with nothing pointing at the move, and the keys named are this profile's own.
367
+ export function noWindowNotice(probe, before, name = 'default') {
366
368
  if (before.contextWindow != null || !probe.reached || probe.window)
367
369
  return undefined;
368
- return [
369
- `No context window known for ${before.model}, so there is no compaction and older tool output`,
370
- "is dropped from every request. Set REIKA_CONTEXT_WINDOW to the server's context size.",
371
- ].join(' ');
370
+ const lead = `No context window known for ${before.model}, so there is no compaction and older tool output is dropped from every request.`;
371
+ const miss = probe.catalogMiss;
372
+ if (!miss) {
373
+ return `${lead} Set REIKA_CONTEXT_WINDOW to the server's context size.`;
374
+ }
375
+ const group = before.group ?? name;
376
+ const prefix = group === 'default' ? 'REIKA' : `REIKA_${group.toUpperCase()}`;
377
+ const parts = [
378
+ lead,
379
+ miss.baseListed
380
+ ? `models.dev lists ${before.baseURL} but not ${before.model} under it.`
381
+ : `models.dev has no entry for ${before.baseURL}.`,
382
+ ];
383
+ if (!miss.baseListed && miss.sameHost.length > 0) {
384
+ parts.push(`It lists this host at ${miss.sameHost.join(', ')} — if the provider moved, update ${prefix}_BASE_URL.`);
385
+ }
386
+ parts.push(`Or set ${prefix}_CONTEXT_WINDOW to the model's context size.`);
387
+ return parts.join(' ');
372
388
  }
@@ -1,6 +1,7 @@
1
- import { realpathSync } from 'node:fs';
1
+ import { lstatSync, readlinkSync, realpathSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
- import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { execFileSync } from 'node:child_process';
4
5
  // Resolve a model-supplied path against cwd. Models routinely emit `~/...`
5
6
  // paths, which node's resolve() treats as a literal directory named "~".
6
7
  export function resolveUserPath(cwd, path) {
@@ -66,3 +67,105 @@ export function escapesProject(cwd, full) {
66
67
  // No path in the text: the modal prints the subject directly above it, and repeating it there only
67
68
  // pushed the line past the dialog width and wrapped it.
68
69
  export const OUTSIDE_PROJECT_WARNING = 'Writes outside the project directory';
70
+ // The approval warning for a write that lands in git's metadata. Same shape and mechanism as
71
+ // `OUTSIDE_PROJECT_WARNING`: under `safe` the warning pierces auto-approve and the user sees a
72
+ // modal; under `bypass` (no `requestApproval`) the write is refused outright. The sandbox half of
73
+ // this class refuses the same paths for every sandboxed command (#706); here a deliberately
74
+ // approved write is allowed, exactly as a user-approved bash command runs unsandboxed — the "user
75
+ // asks the agent to repair a hook" case the sandbox's hard deny would otherwise force into bash.
76
+ export const GIT_METADATA_WARNING = 'Writes to git config or hooks (runs code at your next git command)';
77
+ // The names the sandbox profile refuses (src/tools/_sandbox.ts): any entry named `.git`, the
78
+ // metadata files at its top level and under `modules/`/`worktrees/<x>/`, and the `hooks` subtree.
79
+ // Unanchored, so a repo nested anywhere in the project is covered. Paths are normalized to `/` so
80
+ // a Windows separator cannot dodge the `/`-spelled rules. Case-insensitive because macOS's default
81
+ // volume is: `.git/Config` and `.GIT/hooks/x` write the real files, and on a case-sensitive volume
82
+ // the extra matches are only a prompt.
83
+ const GIT_METADATA_NAME_RE = /\/\.git$|\.git\/((modules\/.+\/|worktrees\/[^/]+\/)?(config|config\.worktree|commondir|gitdir))$|\.git\/(modules\/.+\/)?hooks(\/|$)/i;
84
+ // A common git dir NOT named `.git` (`git init --separate-git-dir`, a dotfiles bare repo) escapes
85
+ // the name rules, the same hole the sandbox's GITDIR param exists for. Protected places are the
86
+ // profile's `GITDIR` deny lines, written against the resolved common dir of the session cwd. This
87
+ // is the cwd's repo only — a git dir a target's OWN tree would resolve to is a separate repo whose
88
+ // paths the name rules still cover when it is a plain `.git` entry. The path is regex-escaped: a
89
+ // cwd may itself contain `.`, `+` or `(` (a dotted project name), and an unescaped one would match
90
+ // broader than the git dir.
91
+ const GIT_DIR_DENY_RE = (g) => {
92
+ const dir = g.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
93
+ return new RegExp(`^${dir}$|^${dir}/(config|config\\.worktree|commondir|gitdir)$|^${dir}/hooks(/|$)|^${dir}/worktrees/[^/]+/(config|config\\.worktree|commondir|gitdir)$|^${dir}/modules/.+/(config|config\\.worktree|commondir|gitdir)$|^${dir}/modules/.+/hooks(/|$)`, 'i');
94
+ };
95
+ const commonGitDirs = new Map();
96
+ // The session cwd's common git dir, normalized, or null when there is none. Mirrors the sandbox's
97
+ // `gitDirToBind` (src/tools/_sandbox.ts) minus its "cwd's own `.git`" skip:
98
+ // for the file tools the name rules already cover a `.git`-named dir, and protecting it again here
99
+ // changes nothing, so the skip is a comparison that cannot differ in outcome. A found dir is cached
100
+ // per cwd; a null is not, so a `--separate-git-dir`/bare repo the user creates mid-session is still
101
+ // probed for on the next write.
102
+ function commonGitDir(cwd) {
103
+ const cached = commonGitDirs.get(cwd);
104
+ if (cached !== undefined)
105
+ return cached;
106
+ let dir = null;
107
+ try {
108
+ const out = execFileSync('git', ['rev-parse', '--git-common-dir'], {
109
+ cwd,
110
+ encoding: 'utf8',
111
+ stdio: ['ignore', 'pipe', 'ignore'],
112
+ timeout: 5_000,
113
+ }).trim();
114
+ if (out) {
115
+ // Real path, as the sandbox binds it: git prints a separate git dir already resolved, so a
116
+ // cwd behind a symlink (`/tmp`, `os.tmpdir()`) would otherwise never match it.
117
+ dir = realTarget(resolve(isAbsolute(out) ? out : resolve(cwd, out)));
118
+ }
119
+ }
120
+ catch {
121
+ // not a repo, or no git — nothing to protect beyond the name rules
122
+ }
123
+ if (dir !== null)
124
+ commonGitDirs.set(cwd, dir);
125
+ return dir;
126
+ }
127
+ // Where a write to `full` actually lands: the real path of its deepest existing ancestor plus the
128
+ // rest, with a dangling symlink followed by hand (writeFile creates its target). The sandbox gets
129
+ // this from the kernel; a string check does not, and a sandboxed `ln -s .git/hooks h` is an
130
+ // ordinary in-project write that would turn `write h/pre-commit` into a hook.
131
+ function realTarget(full) {
132
+ let head = full;
133
+ const tail = [];
134
+ for (let hops = 0; hops < 40; hops++) {
135
+ try {
136
+ return join(realpathSync.native(head), ...tail);
137
+ }
138
+ catch {
139
+ // does not exist (yet), or a dangling link — handled below
140
+ }
141
+ try {
142
+ if (lstatSync(head).isSymbolicLink()) {
143
+ head = resolve(dirname(head), readlinkSync(head));
144
+ continue;
145
+ }
146
+ }
147
+ catch {
148
+ // nothing there
149
+ }
150
+ const parent = dirname(head);
151
+ if (parent === head)
152
+ return full;
153
+ tail.unshift(basename(head));
154
+ head = parent;
155
+ }
156
+ return full;
157
+ }
158
+ // Whether a resolved path is git metadata that names a program, and the warning to raise when it
159
+ // is. Undefined for anything else, so the tools' `warnings` arrays stay absent for a normal write.
160
+ // Both the path as written and where it really lands are checked: either one naming git metadata
161
+ // is enough.
162
+ export function gitMetadataWarning(cwd, full) {
163
+ const targets = [...new Set([full, realTarget(full)])].map(p => p.replaceAll('\\', '/'));
164
+ if (targets.some(f => GIT_METADATA_NAME_RE.test(f)))
165
+ return GIT_METADATA_WARNING;
166
+ const g = commonGitDir(cwd);
167
+ if (!g)
168
+ return undefined;
169
+ const deny = GIT_DIR_DENY_RE(g.replaceAll('\\', '/'));
170
+ return targets.some(f => deny.test(f)) ? GIT_METADATA_WARNING : undefined;
171
+ }
@@ -1,6 +1,6 @@
1
1
  import { realpathSync } from 'node:fs';
2
2
  import { homedir, tmpdir } from 'node:os';
3
- import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
3
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
4
4
  import { execFileSync, spawnSync } from 'node:child_process';
5
5
  import { expandingHeredocBodies, stripHeredocs } from './_heredoc.js';
6
6
  import { dropCarriers, hasExecutableSubstitution, hasRawSubstitution, maskQuoted, splitSegments, words, INSPECTION_COMMANDS, } from './_readonly.js';
@@ -52,12 +52,10 @@ export function sandboxProfile(opts) {
52
52
  // typecheck`). That is a very common shape, and losing to it makes the sandbox unusable.
53
53
  '(deny file-write*)',
54
54
  '(allow file-write* (subpath (param "WORKDIR")))',
55
- // The repo's git dir, when it sits ABOVE cwd: a monorepo package (`packages/web/`), a worktree
56
- // (`.git` is a file pointing into `main/.git/worktrees/x`) or a submodule. Without it every git
57
- // write there — `add`, `stash`, `checkout`, even `fetch` (writes FETCH_HEAD) — fails on
58
- // `.git/index.lock: Operation not permitted`, which reads as a stale lock and whose natural next
59
- // move is `rm -f .git/index.lock` (measured). Bound to WORKDIR when the git dir is inside it or
60
- // there is no repo, since an unbound param exits 65.
55
+ // The repo's git dir when it isn't cwd's own `.git` — usually above cwd (monorepo package,
56
+ // worktree, submodule). Without it `git add` fails on `.git/index.lock: Operation not
57
+ // permitted`, which reads as a stale lock and invites `rm -f` (measured). Never bound to
58
+ // WORKDIR: the denies below derive `config`/`hooks` from it and would hit the project's own.
61
59
  '(allow file-write* (subpath (param "GITDIR")))',
62
60
  // Temp is writable: `mktemp -d`, `cd /tmp && …` and `tempfile` are how a model scratches, and
63
61
  // denying them did worse than fail — python's `tempfile.mkdtemp()` fell through TMPDIR and /tmp
@@ -76,6 +74,28 @@ export function sandboxProfile(opts) {
76
74
  '(allow file-write* (subpath (param "USERCACHE")))',
77
75
  '(allow file-write* (subpath (param "XDGCACHE")))',
78
76
  '(allow file-write* (subpath "/dev"))',
77
+ // Git config and hooks name programs something else runs, so they stay unwritable (#706).
78
+ // Matched by name, not under an anchored dir: renaming `.git`, writing `commondir`, or
79
+ // repointing a worktree's `.git` file each redirected git to a planted config (measured). Temp
80
+ // is covered too, since a repo built there and `mv`'d in is one git status recurses into. The
81
+ // config pattern names only metadata dirs, so a branch called `config` still works.
82
+ '(deny file-write* (regex #"/\\.git$"))',
83
+ '(deny file-write* (regex #"/\\.git/((modules/.+|worktrees/[^/]+)/)?(config|config\\.worktree|commondir|gitdir)$"))',
84
+ '(deny file-write* (regex #"/\\.git/(modules/.+/)?hooks(/|$)"))',
85
+ // Deleting stays allowed, or `rm -rf vendor` with a nested repo in it fails on that repo's
86
+ // metadata. Removing one plants nothing, and the file can't be created again. The project's
87
+ // own `.git` and GITDIR are excluded here, because renaming one away counts as an unlink, and a
88
+ // later deny does not win over this unlink allow (measured).
89
+ '(allow file-write-unlink (require-all (regex #"/\\.git(/|$)") (require-any (subpath (param "WORKDIR")) (subpath "/private/tmp") (subpath "/private/var/tmp") (subpath (param "TMPDIR")) (subpath (param "USERCACHE")) (subpath (param "XDGCACHE"))) (require-not (subpath (string-append (param "WORKDIR") "/.git"))) (require-not (subpath (param "GITDIR")))))',
90
+ // A common dir not named `.git` has no name to match, so its places are spelled out from the
91
+ // param.
92
+ '(deny file-write* (literal (param "GITDIR")))',
93
+ '(deny file-write* (subpath (string-append (param "GITDIR") "/config")))',
94
+ '(deny file-write* (subpath (string-append (param "GITDIR") "/config.worktree")))',
95
+ '(deny file-write* (subpath (string-append (param "GITDIR") "/commondir")))',
96
+ '(deny file-write* (subpath (string-append (param "GITDIR") "/hooks")))',
97
+ '(deny file-write* (require-all (subpath (string-append (param "GITDIR") "/worktrees")) (regex #"/worktrees/[^/]+/(config|config\\.worktree|commondir|gitdir)$")))',
98
+ '(deny file-write* (require-all (subpath (string-append (param "GITDIR") "/modules")) (regex #"/(config|config\\.worktree|commondir|gitdir)$|/hooks(/|$)")))',
79
99
  ];
80
100
  if (!opts.network) {
81
101
  lines.push('(deny network*)',
@@ -507,19 +527,27 @@ export function sandboxPlan(cwd, opts) {
507
527
  // Same realpath rule for every other allowed dir: `os.tmpdir()` is `/var/folders/…/T`, a symlink
508
528
  // hop away from the `/private/var/…` the kernel matches. Each falls back to a path the profile
509
529
  // already covers, so an unresolvable dir costs nothing rather than an unbound param (exit 65).
530
+ const params = sandboxParams(cwd, resolved);
531
+ const args = ['-p', sandboxProfile(opts)];
532
+ for (const [k, v] of Object.entries(params))
533
+ args.push('-D', `${k}=${v}`);
534
+ return { args };
535
+ }
536
+ /** The `-D` bindings for the profile's params. Exported so tests can prove every param is bound
537
+ * even where `sandboxPlan` refuses (nested seatbelt exits 71, but still parses the profile). */
538
+ export function sandboxParams(cwd, resolved) {
510
539
  const home = homedir();
511
- const params = {
540
+ return {
512
541
  WORKDIR: resolved,
513
- GITDIR: gitDirOutside(cwd, resolved) ?? resolved,
542
+ GITDIR: gitDirToBind(cwd, resolved) ?? NO_GITDIR,
514
543
  TMPDIR: realOr(tmpdir(), '/private/tmp'),
515
544
  USERCACHE: realOr(join(home, 'Library', 'Caches'), resolved),
516
545
  XDGCACHE: realOr(process.env.XDG_CACHE_HOME || join(home, '.cache'), resolved),
517
546
  };
518
- const args = ['-p', sandboxProfile(opts)];
519
- for (const [k, v] of Object.entries(params))
520
- args.push('-D', `${k}=${v}`);
521
- return { args };
522
547
  }
548
+ /** GITDIR when there is none to bind: an unbound param exits 65, and nothing can exist under the
549
+ * `/dev/null` device, so every rule naming it matches nothing. */
550
+ export const NO_GITDIR = '/dev/null/reika-no-gitdir';
523
551
  function realOr(path, fallback) {
524
552
  try {
525
553
  return realpathSync.native(path);
@@ -529,9 +557,9 @@ function realOr(path, fallback) {
529
557
  }
530
558
  }
531
559
  const gitDirs = new Map();
532
- /** The repo's common git dir when it lies outside cwd, resolved; null inside cwd or without a repo.
533
- * Cached per cwd — a property of the checkout, and `git rev-parse` per command is a process. */
534
- function gitDirOutside(cwd, resolvedCwd) {
560
+ /** The repo's common git dir unless it is cwd's own `.git`: one inside cwd under another name
561
+ * (`--separate-git-dir`, a dotfiles repo) escapes the name-based denies. Cached per cwd. */
562
+ function gitDirToBind(cwd, resolvedCwd) {
535
563
  const cached = gitDirs.get(cwd);
536
564
  if (cached !== undefined)
537
565
  return cached;
@@ -544,7 +572,7 @@ function gitDirOutside(cwd, resolvedCwd) {
544
572
  timeout: 5_000,
545
573
  }).trim();
546
574
  const abs = realOr(isAbsolute(out) ? out : resolve(cwd, out), '');
547
- if (abs && abs !== resolvedCwd && !abs.startsWith(resolvedCwd + sep))
575
+ if (abs && abs !== join(resolvedCwd, '.git'))
548
576
  dir = abs;
549
577
  }
550
578
  catch {
@@ -589,11 +617,149 @@ export function sandboxNotice(cwd, home = homedir()) {
589
617
  // Python's `[Errno 1] Operation not permitted` is a network denial only WITHOUT a trailing quoted
590
618
  // path — with one (`PermissionError: [Errno 1] Operation not permitted: '/Users/x/f'`) it is a write.
591
619
  const NET_DENIAL_RE = /couldn.t connect to server|connect EPERM|code EPERM|\[Errno 1\] Operation not permitted(?!: ')|connect(?: to host \S+ port \d+)?: operation not permitted|could ?n.t resolve host|unable to resolve host|ENOTFOUND|EAI_AGAIN|EAI_NONAME|getaddrinfo|nodename nor servname|no such host|name resolution|network is unreachable/i;
592
- // A write outside the allowed dirs, as the shell (`/bin/sh: /Users/x/f: Operation not permitted`),
593
- // mkdir/cp/… (`mkdir: /Users/x/d: Operation not permitted`), node (`EPERM: operation not permitted,
594
- // mkdir '/Users/x/d'`) and python (`Operation not permitted: '/Users/x/f'`) each print it — a PATH
595
- // next to the message is what tells it apart from the network and exec shapes above.
596
- const FS_DENIAL_RE = /\/[^\s:'"]+: operation not permitted|EPERM: operation not permitted, \w+ '|operation not permitted: '\//i;
620
+ // A write the profile refused: `<prog>: <path>: Operation not permitted` from the shell and
621
+ // coreutils (behind any `<runner>: ` prefixes — turbo, pnpm -r, a go error chain — or indentation),
622
+ // go's `open <path>: …` with no colon after the verb, git's bare absolute `<path>: …`, node's and
623
+ // python's mid-line shapes, and (#723) two forms the slash requirement dropped:
624
+ //
625
+ // - a SLASHLESS path, which only a file verb may introduce: `rm -rf .git` prints `rm: .git:
626
+ // Operation not permitted`, `mv .git .g` prints `mv: rename .git to .g: …` and `tee config` from
627
+ // inside `.git` prints `tee: config: …`; `sed -i` names no path at all (`sed: rename(): …`,
628
+ // measured on macOS sed). Since #706 these are among the refusals a model is likeliest to cause,
629
+ // and the slash dropped them. Making the slash
630
+ // optional after ANY `<prog>: ` instead would match `docker: connect: operation not permitted`, a
631
+ // network denial, and the write line would then point the model at the wrong thing.
632
+ // - a quoted path before the phrase, which is git's form for the same refusals: `fatal: cannot copy
633
+ // '…/templates/hooks/commit-msg.sample' to '…/.git/hooks/commit-msg.sample': Operation not
634
+ // permitted`, what `git init` prints now that #706 denies the hook copy. The quotes and spaces put
635
+ // it out of reach of the path forms above, and the tail is the only part of git's line that does
636
+ // not change with the message. It must sit behind git's own `fatal:`/`error:`, so a test title
637
+ // quoting a path is not one, and a quoted URL is not a path: `fatal: unable to access
638
+ // 'https://…/': Operation not permitted` is a network shape.
639
+ // - git's config refusal, `error: could not write config file .git/config: Operation not
640
+ // permitted` — what `git config` prints since #706 (measured; `lock` is the same message when the
641
+ // lock file is the refused one), with no verb or slash in front of the path.
642
+ //
643
+ // Python's `[Errno 1] Operation not permitted: '<path>'` takes a relative path too (`'.git/config'`);
644
+ // the `[Errno 1]` is what keeps a quoted test name or host from reading as one.
645
+ //
646
+ // All but node's must END the line (#720): quoted text — a comment, a fixture string, a grep hit —
647
+ // carries text after the phrase, and prose before the path must end in `: ` or be a single verb, so a
648
+ // sentence that quotes the error is not a refusal. A denial line quoted whole at column 0 and node's
649
+ // mid-line shape still read as one.
650
+ //
651
+ // The prefix in front of every form below is an ALLOWLIST of what runners print (#726). #720 allowed
652
+ // any `.*: ` here so that a runner's column reached a shape added for the shell's own output, and
653
+ // that is what let a line which only QUOTES a refusal read as one whenever the quote sat behind a
654
+ // colon column of its own — the assertion header a failing test prints over the fixture it compared
655
+ // (`Expected: rm: .git: Operation not permitted`, and `AssertionError: /bin/sh: /Users/x/f: Operation
656
+ // not permitted`, which is not a hypothetical: it is reika's own `_sandbox.test.ts` failing under the
657
+ // `| grep -E "AssertionError|expected"` a model wraps it in), a diff's added/removed line (`+ mkdir:
658
+ // /Users/x: …`, what `gh pr diff` of such a fixture prints), and git's own quoted form behind either
659
+ // (`Expected: fatal: cannot copy '…' to '….git/hooks/…': Operation not permitted`). Each produced the
660
+ // write footer and the once-per-cwd `REIKA_SANDBOX=0` receipt for a write that never happened — the
661
+ // #720 class, which #725 widened the exposure of by scanning a run's 4MB tail, not just its 64KB
662
+ // head. So the prefix is these five shapes, one source for all the forms below, and a runner nobody
663
+ // listed loses its footer rather than the rest of the class getting through: a miss costs one
664
+ // footer, a false hit costs a footer AND that receipt.
665
+ //
666
+ // `name: ` / `name build: ` turbo's `web:build: `, pnpm -r's `packages/web build: `
667
+ // `[n] ` a job or worker number, padded or not (`[0] `, `[1] `)
668
+ // `name | ` concurrently's column (`web:build | `)
669
+ // indentation a test runner printing an indented line
670
+ // `go: <prose>: ` go's error chain, whose middle segment is prose and cannot be a name
671
+ //
672
+ // What may NOT be one is assertion vocabulary, refused BY NAME because it is name-shaped: a
673
+ // capitalized header (`Expected: `/`Received: `/`Actual: `/`AssertionError: `, the last measured, the
674
+ // rest the issue's, and the bare `Error: ` a test prints over a thrown fixture string) is a value being compared, never a runner — and a runner's own column in front
675
+ // does not make it one: `web:build: Expected: …` is the issue's red suite under turbo, the word can
676
+ // end a column as its trailing token (`run: Expected: `), and the go chain's prose segment can carry
677
+ // it (`go: x: Expected: `). So the vocabulary is checked where a name starts AND at the `:` that ends
678
+ // a column (the `(?<!…)` before each terminator), and a go chain stops at the first segment that
679
+ // ends in it, not only at the line's first token. A diff's
680
+ // `+ `/`- ` marker needs no
681
+ // rule of its own — a column cannot start with one, which is also why a column-0 `-bash: /x: …` (a
682
+ // login shell naming itself) is dropped: at column 0 the marker and the shell's name are the same
683
+ // character. A line number is not a column either, so a name must carry a letter somewhere — that is
684
+ // what keeps `668: mkdir: /x: Operation not permitted`, a `grep -n` hit on an indented denial, out;
685
+ // a runner that numbers its lines brackets the number (`[0] `), form or not.
686
+ //
687
+ // What is left is one-directional and stated: a runner whose column is one of the shapes above keeps
688
+ // its footer, and adding one belongs on the list rather than back in the open form. Replayed over the
689
+ // 7,335 `bash` outputs saved in a session history (32,418 distinct lines, `evals/sandboxdenial-replay.ts`),
690
+ // this changed one verdict — the `AssertionError: ` line above — and lost no runner shape.
691
+ // `error` is the generic header a test prints over a thrown fixture string (`Error: rm: .git: …`); no
692
+ // runner is named for it, and git's own `error: … '…': …` form is matched as a form, not a column.
693
+ const RUNNER_VOCABULARY = String.raw `(?:expected|received|actual|assertionerror|error)`;
694
+ const RUNNER_NAME = String.raw `(?=[^\s|]*[A-Za-z])[^\s|+-][^\s|]*`;
695
+ // One column, anchored at the start of what is left of the line. Matched one at a time by
696
+ // `isRefusalBehindRunnerColumns` rather than repeated inside one regex: a name may contain `:`
697
+ // (`web:build`), so `a: b: ` splits into columns more than one way, and a quantified group over
698
+ // those overlapping readings backtracks exponentially on a line of repeated `x: ` segments — over
699
+ // a run's 4MB tail, on the main thread. Alternation order is the tie-break the regex no longer gets
700
+ // from backtracking: `name: ` before `name build: `, or `/bin/sh: /x/f: ` reads as one column.
701
+ const RUNNER_COLUMN_RE = new RegExp(String.raw `^(?:\[[^\]\r\n]*\][ \t]+|(?!${RUNNER_VOCABULARY}\b)${RUNNER_NAME}[ \t]+\|[ \t]+|(?!${RUNNER_VOCABULARY}\b)${RUNNER_NAME}(?<!\b${RUNNER_VOCABULARY}\b):[ \t]+|(?!${RUNNER_VOCABULARY}\b)${RUNNER_NAME}[ \t]+[^\s:]+(?<!\b${RUNNER_VOCABULARY}\b):[ \t]+)`, 'i');
702
+ // go's chain is `go: <prose>: <prose>: <error>`, so its segments are cut at every `: ` in turn.
703
+ const GO_CHAIN_RE = /^go:[ \t]+/i;
704
+ const GO_SEGMENT_END_RE = new RegExp(String.raw `\b${RUNNER_VOCABULARY}$`, 'i');
705
+ // Deeper than any runner nests its columns or go its chain; it bounds the walk on a line that is
706
+ // nothing but `x: x: x: …`.
707
+ const MAX_RUNNER_COLUMNS = 8;
708
+ // A path may carry one token in front of its first slash — `~/x`, `./x`, `../x`, and the `~` a shell
709
+ // prints unexpanded when the command was quoted. It cannot start with `+`/`-` for the diff marker's
710
+ // reason: with the column above optional, an unconstrained token here would read `+/Users/x/.git:
711
+ // Operation not permitted` (the added-line form of a fixture) as a path.
712
+ const PATH_LEAD = String.raw `(?:[^\s:'"+-][^\s:'"]*)?`;
713
+ // The forms a refusal takes once the runner's columns are off the front of its line.
714
+ const FS_DENIAL_FORM_RE = new RegExp([
715
+ // `<prog>: <abs path>: …`, go's `open <abs path>: …`, git's bare `<abs path>: …`.
716
+ String.raw `^(?:[a-z]+ )?${PATH_LEAD}\/[^:'"\r\n]*: operation not permitted[ \t]*$`,
717
+ // A slashless path, which only a file verb may introduce.
718
+ String.raw `^(?:rm|mv|cp|mkdir|touch|ln|tee): [^:'"\r\n]*: operation not permitted[ \t]*$`,
719
+ String.raw `^sed: rename\(\): operation not permitted[ \t]*$`,
720
+ // git's quoted-path form, behind its own `fatal:`/`error:` so a test title quoting a path is not one.
721
+ String.raw `^(?:fatal|error): [^\r\n]*'(?![a-z][a-z0-9+.-]*:\/\/)[^'\r\n]*\/[^'\r\n]*': operation not permitted[ \t]*$`,
722
+ ].join('|'), 'i');
723
+ // Shapes printed mid-line, so no column rule applies to them.
724
+ const FS_DENIAL_ANYWHERE_RE = new RegExp([
725
+ String.raw `could not (?:lock|write) config file [^\r\n]*: operation not permitted[ \t]*$`,
726
+ String.raw `EPERM: operation not permitted, \w+ '`,
727
+ String.raw `\[Errno 1\] operation not permitted: '[^'\r\n]+'[ \t]*$`,
728
+ ].join('|'), 'i');
729
+ function isRefusalForm(rest) {
730
+ return FS_DENIAL_FORM_RE.test(rest.replace(/^[ \t]+/, ''));
731
+ }
732
+ // A go chain carrying assertion vocabulary is a quote (`go: x: Expected: …`), so the walk stops at the
733
+ // first segment that ends in it rather than cutting past it.
734
+ function isRefusalBehindGoChain(rest) {
735
+ let from = rest.match(GO_CHAIN_RE)[0].length;
736
+ if (isRefusalForm(rest.slice(from)))
737
+ return true;
738
+ for (let i = 0; i < MAX_RUNNER_COLUMNS; i++) {
739
+ const cut = rest.indexOf(': ', from);
740
+ if (cut === -1 || GO_SEGMENT_END_RE.test(rest.slice(from, cut)))
741
+ return false;
742
+ from = cut + 2;
743
+ if (isRefusalForm(rest.slice(from)))
744
+ return true;
745
+ }
746
+ return false;
747
+ }
748
+ function isRefusalBehindRunnerColumns(line) {
749
+ let rest = line;
750
+ for (let i = 0; i <= MAX_RUNNER_COLUMNS; i++) {
751
+ rest = rest.replace(/^[ \t]+/, '');
752
+ if (isRefusalForm(rest))
753
+ return true;
754
+ if (GO_CHAIN_RE.test(rest))
755
+ return isRefusalBehindGoChain(rest);
756
+ const column = RUNNER_COLUMN_RE.exec(rest);
757
+ if (!column)
758
+ return false;
759
+ rest = rest.slice(column[0].length);
760
+ }
761
+ return false;
762
+ }
597
763
  // Where to send the model for the page it wanted. Keyed on the turn's tool list (the #377 rule: a
598
764
  // result must not point at a tool the model does not have): minimal mode is bash alone, and an
599
765
  // offline session registers neither web tool, so "use fetch_url" there is a phantom pointer the
@@ -611,15 +777,63 @@ function webRoute(toolNames) {
611
777
  parts.push('the search tool instead of scraping');
612
778
  return `For a web page, ${parts.join(', and ')}.`;
613
779
  }
614
- // The exec refusal the setuid note at the top of the file is about, as the shell prints it.
615
- const PS_DENIAL_RE = /\b(?:ps|top): Operation not permitted/;
780
+ // The exec refusal the setuid note at the top of the file is about, as the shell prints it: bare
781
+ // (`ps: …`), behind the shell (`/bin/sh: /bin/ps: …`, and `/bin/sh: line 1: /bin/ps: …` for a
782
+ // multi-line command) or behind a wrapper (`env: ps: …`, `xargs: ps: …`). `ps`/`top` must follow a
783
+ // line start or `: ` directly, with only `/bin/` or `/usr/bin/` allowed between, so a refused write to
784
+ // a path ending in `/top` (`mkdir: /Users/x/top: …`) is not mistaken for it.
785
+ const PS_DENIAL_RE = /(?:^|: )(?:\/(?:usr\/)?bin\/)?(?:ps|top): Operation not permitted/m;
786
+ const PS_DENIAL_LINE_RE = /^.*?(?:^|: )(?:\/(?:usr\/)?bin\/)?(?:ps|top): Operation not permitted.*$/gm;
787
+ // One output can carry both a ps refusal and a refused write — `ps aux | grep node; mkdir ~/x` —
788
+ // and `!ps` on the whole output dropped the write line for exactly the command that shows both
789
+ // (#723). Only the ps/top lines are blanked out of the write check: `/bin/ps: Operation not
790
+ // permitted` is a path by shape and is already explained by the ps note. One replace rather than a
791
+ // split and join, since this runs over up to 4MB of a run's tail.
792
+ function withoutPsDenials(output) {
793
+ return output.replace(PS_DENIAL_LINE_RE, '');
794
+ }
616
795
  // `curl -s` prints nothing on a denial and exits 6 (could not resolve) or 7 (could not connect) —
617
796
  // the one shape the output gate cannot see, so the exit status has to carry it.
618
797
  const CURL_RE = /(?:^|[|;&(]\s*)(?:[A-Za-z_]\w*=\S*\s+)*curl(?![\w./-])/;
619
- /** True when a sandboxed command's output shows a write the profile refused. The user-facing half:
620
- * the footer tells the model not to fight it, this tells the user the flag exists (`bash.ts`). */
621
- export function sandboxRefusedWrite(output) {
622
- return FS_DENIAL_RE.test(output) && !PS_DENIAL_RE.test(output);
798
+ function lineEndFrom(text, from) {
799
+ const lf = text.indexOf('\n', from);
800
+ const cr = text.indexOf('\r', from);
801
+ if (lf === -1)
802
+ return cr === -1 ? text.length : cr;
803
+ return cr === -1 ? lf : Math.min(lf, cr);
804
+ }
805
+ /** The line of a sandboxed command's output that shows a write the profile refused, or null. The
806
+ * user-facing half: the footer tells the model not to fight it, the notice tells the user the flag
807
+ * exists (`bash.ts`). Returned whole so the footer can quote it when it is not in the payload. */
808
+ export function refusedWriteLine(output) {
809
+ const scanned = withoutPsDenials(output);
810
+ // Every form carries the phrase, so only the lines that do are read — linear in the output.
811
+ const phrase = /operation not permitted/gi;
812
+ for (let found = phrase.exec(scanned); found; found = phrase.exec(scanned)) {
813
+ const at = found.index;
814
+ // A `\r` starts a line as a `\n` does (a progress bar redrawn over), as `^`/`$` read it under
815
+ // the `m` flag; the quote is the whole `\n` line around it.
816
+ const segStart = Math.max(scanned.lastIndexOf('\n', at), scanned.lastIndexOf('\r', at)) + 1;
817
+ const segEnd = lineEndFrom(scanned, at);
818
+ const segment = scanned.slice(segStart, segEnd);
819
+ if (FS_DENIAL_ANYWHERE_RE.test(segment) || isRefusalBehindRunnerColumns(segment)) {
820
+ const start = scanned.lastIndexOf('\n', at) + 1;
821
+ const end = scanned.indexOf('\n', at);
822
+ return scanned.slice(start, end === -1 ? undefined : end).trim();
823
+ }
824
+ phrase.lastIndex = segEnd;
825
+ }
826
+ return null;
827
+ }
828
+ // A quoted line is the model's only pointer to WHICH write failed when it sat past the payload head;
829
+ // a pathological one (a minified log on one line) must not become a 4MB footer.
830
+ const QUOTED_DENIAL_MAX_CHARS = 300;
831
+ // The line is the command's output, so a backtick in it would close the code span it is quoted in.
832
+ function quoteDenial(line) {
833
+ const safe = line.replaceAll('`', "'");
834
+ return safe.length > QUOTED_DENIAL_MAX_CHARS
835
+ ? `${safe.slice(0, QUOTED_DENIAL_MAX_CHARS)}…`
836
+ : safe;
623
837
  }
624
838
  /**
625
839
  * What the model is told when a sandboxed command exits non-zero.
@@ -670,13 +884,23 @@ export function sandboxFooter(command, code, output, opts) {
670
884
  webRoute(opts.toolNames) +
671
885
  ' If the command genuinely needs the network, say so and ask the user to run it.');
672
886
  }
673
- // `/bin/ps: Operation not permitted` is a path too, and already explained above.
674
- if (!ps && FS_DENIAL_RE.test(output)) {
675
- lines.push('A write outside the working directory, temp and cache dirs was refused by the sandbox — not ' +
676
- 'a permissions problem, so do not reach for sudo or chmod. If the command must write there, ' +
677
- 'say so and ask the user to run it.');
887
+ // `/bin/ps: Operation not permitted` is a path too, and already explained above, so the ps lines
888
+ // are taken out before this test rather than the write check being skipped for the whole output.
889
+ // The line says "a path it does not allow", not "outside the working directory": since #706 the
890
+ // denied paths include `.git/config` and `.git/hooks`, which are INSIDE the working directory.
891
+ const refused = opts.refusedWrite === undefined ? refusedWriteLine(output) : opts.refusedWrite;
892
+ if (refused !== null) {
893
+ // Past the payload head the model sees no refusal at all, so the line is quoted: without it the
894
+ // model guesses which write failed or re-runs the whole command to find out.
895
+ const quoted = output.includes(refused)
896
+ ? ''
897
+ : ` It was printed after the output shown above: \`${quoteDenial(refused)}\`.`;
898
+ lines.push('The sandbox refused a write to a path it does not allow — not a permissions problem, so do ' +
899
+ 'not reach for sudo or chmod.' +
900
+ quoted +
901
+ ' If the command must write there, say so and ask the user to run it.');
678
902
  }
679
903
  if (lines.length === 0)
680
904
  return '';
681
- return `\n\n(reika: this command ran in a local sandbox, so the failure above may be the sandbox rather than your command. ${lines.join(' ')} Writes are confined to the working directory, temp and cache dirs.)`;
905
+ return `\n\n(reika: this command ran in a local sandbox, so the failure above may be the sandbox rather than your command. ${lines.join(' ')} Writes are confined to the working directory, temp and cache dirs, and git's config and hooks are not writable even there.)`;
682
906
  }
@@ -44,9 +44,10 @@ const CONTEXT_LINES = 3;
44
44
  // Capture the state a diff will be taken against. `null` when git is present but can't answer
45
45
  // (slow, or too much untracked to read), which callers treat as "no diff" rather than an error.
46
46
  export async function snapshotTree(cwd, command) {
47
- const [root, head] = await Promise.all([
47
+ const [root, head, guard] = await Promise.all([
48
48
  git(['rev-parse', '--show-toplevel'], cwd),
49
49
  git(['rev-parse', 'HEAD'], cwd),
50
+ repoFilterGuard(cwd),
50
51
  ]);
51
52
  // git reports the resolved root; the cwd must be resolved the same way or a project under a
52
53
  // symlinked dir (macOS /tmp → /private/tmp) gets every path as a long `../` chain.
@@ -63,7 +64,9 @@ export async function snapshotTree(cwd, command) {
63
64
  paths = writeTargets(command, realCwd);
64
65
  }
65
66
  else {
66
- const listed = await dirtyPaths(snap.root);
67
+ if (guard === null)
68
+ return null;
69
+ const listed = await dirtyPaths(snap.root, guard);
67
70
  if (listed === null || listed.size > MAX_DIRTY_ENTRIES)
68
71
  return null;
69
72
  paths = [...listed.keys()];
@@ -87,7 +90,13 @@ export async function changesSince(snap) {
87
90
  if (snap.root === null)
88
91
  return namedChanges(snap);
89
92
  const root = snap.root;
90
- const [listed, head] = await Promise.all([dirtyPaths(root), git(['rev-parse', 'HEAD'], root)]);
93
+ const [guard, head] = await Promise.all([
94
+ repoFilterGuard(root),
95
+ git(['rev-parse', 'HEAD'], root),
96
+ ]);
97
+ if (guard === null)
98
+ return null;
99
+ const listed = await dirtyPaths(root, guard);
91
100
  if (listed === null)
92
101
  return null;
93
102
  const moved = snap.head !== null && head !== null && head.trim() !== snap.head;
@@ -132,11 +141,10 @@ export async function changesSince(snap) {
132
141
  }
133
142
  else {
134
143
  // The old head's bytes, fetched only for files that get rendered — a formatter sweeping 200
135
- // files must not cost 200 git processes. `--filters` applies the same eol/smudge conversion
136
- // the worktree copy went through, so a CRLF checkout doesn't diff as a full-file rewrite. A
137
- // miss (no commit had the path, yet it wasn't listed before) or a mode-only change has
138
- // nothing to draw.
139
- const old = await git(['cat-file', '--filters', `${snap.head ?? 'HEAD'}:${c.path}`], root, 'buffer');
144
+ // files must not cost 200 git processes. `--filters` applies eol and LFS conversion so a CRLF or
145
+ // LFS file doesn't diff as a rewrite; the guard stops repo-defined drivers. A miss or a
146
+ // mode-only change has nothing to draw.
147
+ const old = await git([...guard, 'cat-file', '--filters', `${snap.head ?? 'HEAD'}:${c.path}`], root, 'buffer');
140
148
  if (old === null)
141
149
  continue;
142
150
  before = decode(old);
@@ -243,8 +251,18 @@ function splitLines(text) {
243
251
  // `git status` lists tracked files that differ from HEAD or the index, plus untracked ones. Ignored
244
252
  // files are deliberately absent: a build writing into `dist/` is not an edit the user wants a diff
245
253
  // of, and it's the same rule the file index and the read tools already apply.
246
- async function dirtyPaths(root) {
247
- const out = await git(['status', '--porcelain=v1', '-z', '--untracked-files=all'], root);
254
+ async function dirtyPaths(root, guard) {
255
+ const out = await git(
256
+ // A submodule's status runs git inside it under that repo's own filter drivers, which the
257
+ // guard never names (measured), and its changes can't be drawn as a file diff anyway.
258
+ [
259
+ ...guard,
260
+ 'status',
261
+ '--porcelain=v1',
262
+ '-z',
263
+ '--untracked-files=all',
264
+ '--ignore-submodules=all',
265
+ ], root);
248
266
  if (out === null)
249
267
  return null;
250
268
  const paths = new Map();
@@ -274,6 +292,26 @@ async function commitDiff(root, from, to) {
274
292
  paths.set(tokens[i + 1], tokens[i][0]);
275
293
  return paths;
276
294
  }
295
+ // `-c` overrides blanking every filter driver from the repo's own config, which a model can write
296
+ // (#719); global ones like git-lfs are the user's and keep running. Null when that can't be
297
+ // decided (git < 2.26, an `=` in a name): callers skip the diff rather than run git unguarded.
298
+ async function repoFilterGuard(cwd) {
299
+ const out = await git(['config', '--show-scope', '--list', '-z'], cwd);
300
+ if (out === null)
301
+ return null;
302
+ const names = new Set();
303
+ const tokens = out.split('\0');
304
+ for (let i = 0; i + 1 < tokens.length; i += 2) {
305
+ const key = tokens[i + 1].split('\n', 1)[0];
306
+ if (!key.startsWith('filter.') || (tokens[i] !== 'local' && tokens[i] !== 'worktree'))
307
+ continue;
308
+ const name = key.slice('filter.'.length, key.lastIndexOf('.'));
309
+ if (name.includes('='))
310
+ return null;
311
+ names.add(name);
312
+ }
313
+ return [...names].flatMap(n => ['smudge=', 'clean=', 'process=', 'required=false'].flatMap(v => ['-c', `filter.${n}.${v}`]));
314
+ }
277
315
  async function readBounded(path) {
278
316
  try {
279
317
  const buf = await readFile(path);
@@ -294,8 +332,15 @@ function decode(buf) {
294
332
  }
295
333
  function git(args, cwd, as) {
296
334
  return new Promise(resolve => {
297
- execFile('git', args, {
335
+ execFile('git',
336
+ // Unsandboxed git on a repo the model can write: `status` ran a planted fsmonitor and a
337
+ // `post-index-change` hook (measured), so both are off on the command line (#706). Filter
338
+ // drivers are per-repo and blanked by `repoFilterGuard`.
339
+ ['-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null', ...args], {
298
340
  cwd,
341
+ // git-lfs is a global driver, so `--filters` runs it here, unsandboxed, and a missing
342
+ // object is a download. A `.gitattributes` the model wrote must not start one.
343
+ env: { ...process.env, GIT_LFS_SKIP_SMUDGE: '1' },
299
344
  timeout: GIT_TIMEOUT_MS,
300
345
  windowsHide: true,
301
346
  maxBuffer: 64 * 1024 * 1024,
@@ -4,7 +4,7 @@ import { detectDangerousPatterns } from './_danger.js';
4
4
  import { scanHeredocs } from './_heredoc.js';
5
5
  import { remoteUrlRisk } from './_exfil.js';
6
6
  import { declineSummary } from '../approval.js';
7
- import { SANDBOX_EXEC_ERROR_PREFIX, SANDBOX_PROFILE_ERROR_CODE, broadWorkdirNotice, isBroadWorkdir, networkAllowedFor, sandboxArgv, sandboxFooter, sandboxNotice, sandboxPlan, sandboxRefusedWrite, } from './_sandbox.js';
7
+ import { SANDBOX_EXEC_ERROR_PREFIX, SANDBOX_PROFILE_ERROR_CODE, broadWorkdirNotice, isBroadWorkdir, networkAllowedFor, sandboxArgv, sandboxFooter, sandboxNotice, sandboxPlan, refusedWriteLine, } from './_sandbox.js';
8
8
  import { recordCapped } from './_spillstats.js';
9
9
  import { GH_PLAN_READ_LIST, READ_ONLY_COMMAND_LIST, isProvablyReadOnly } from './_readonly.js';
10
10
  import { changesSince, snapshotTree } from './_treediff.js';
@@ -260,8 +260,8 @@ export const sandboxNoticed = new Set();
260
260
  // fight it"; this line is where the user learns the flag exists — once, since a Go or Gradle build
261
261
  // that needs a home-dir path will refuse on every command until they act on it.
262
262
  const sandboxDenialNoticed = new Set();
263
- const SANDBOX_DENIAL_NOTICE = 'The sandbox refused a write outside the working directory, temp and cache dirs (see the ' +
264
- 'command output). If this project needs it, REIKA_SANDBOX=0 turns the sandbox off.';
263
+ const SANDBOX_DENIAL_NOTICE = 'The sandbox refused a write to a path it does not allow (see the command output). If this ' +
264
+ 'project needs it, REIKA_SANDBOX=0 turns the sandbox off.';
265
265
  export function execStream(command, ctx, sandbox) {
266
266
  const timeoutMs = ctx.bashTimeoutMs ?? DEFAULT_TIMEOUT_MS;
267
267
  const idleMs = ctx.bashIdleMs ?? DEFAULT_IDLE_MS;
@@ -396,7 +396,24 @@ export function execStream(command, ctx, sandbox) {
396
396
  proc.on('close', (code, signal) => {
397
397
  cleanup();
398
398
  const rawOutput = buffer.join('');
399
- const truncated = totalBytes >= MAX_PAYLOAD_BYTES ? '\n…(truncated)' : '';
399
+ const capped = totalBytes >= MAX_PAYLOAD_BYTES;
400
+ const truncated = capped ? '\n…(truncated)' : '';
401
+ // #723: a denial printed after the 64KB head is still a denial. The spill window holds the last
402
+ // 4MB, so a refusal in one package of a `pnpm -r build` followed by 20KB of the others' logs is
403
+ // still seen; with spill off only the 4KB `uiTail` is retained. Only the refused-write check
404
+ // reads past the head: the ps and network notes stay on the output the model was shown, since
405
+ // loose words like `ENOTFOUND` in 4MB of a red test suite would blame the sandbox for a
406
+ // genuine failure. Joined once and reused by the spill below.
407
+ const retained = spilling ? tail : uiTail;
408
+ const tailText = capped ? retained.text() : '';
409
+ // The window is chunk-granular, so its first line may be the back half of one: cut off, a prose
410
+ // line (`we tried to open /x/y: operation not permitted`) reads as a refusal.
411
+ const scanned = !capped
412
+ ? rawOutput
413
+ : retained.bytes >= rawBytes
414
+ ? tailText
415
+ : `${rawOutput}\n${tailText.slice(tailText.indexOf('\n') + 1)}`;
416
+ const refusedWrite = argv ? refusedWriteLine(scanned) : null;
400
417
  // The sandbox-aware half (#163). Seatbelt's network denials never say "permission" — curl
401
418
  // reports a DNS failure, git/npm report credentials or proxy problems — so a headerless failure
402
419
  // reads to a model as a bug in its own command and sets up the classic spiral. Keyed on the
@@ -406,7 +423,11 @@ export function execStream(command, ctx, sandbox) {
406
423
  searchHint(command, rawOutput) +
407
424
  heredocSubstitutionHint(command, code, rawOutput) +
408
425
  (argv && sandbox
409
- ? sandboxFooter(command, code, rawOutput, { ...sandbox, toolNames: ctx.toolNames })
426
+ ? sandboxFooter(command, code, rawOutput, {
427
+ ...sandbox,
428
+ toolNames: ctx.toolNames,
429
+ refusedWrite,
430
+ })
410
431
  : '');
411
432
  // Built from the retained tail, not the payload head: the chip is the user's answer to "how
412
433
  // did it end?", which the head cannot give once a run passes the cap.
@@ -415,7 +436,7 @@ export function execStream(command, ctx, sandbox) {
415
436
  sandboxNoticed.add(ctx.cwd);
416
437
  // On the output's shape, not the exit status: `mkdir ~/x; echo ok` exits 0 with the denial in
417
438
  // its output, and the user would otherwise never learn the flag exists.
418
- if (argv && sandboxRefusedWrite(rawOutput) && !sandboxDenialNoticed.has(ctx.cwd)) {
439
+ if (refusedWrite !== null && !sandboxDenialNoticed.has(ctx.cwd)) {
419
440
  sandboxDenialNoticed.add(ctx.cwd);
420
441
  notice = {
421
442
  tone: 'warn',
@@ -497,7 +518,7 @@ export function execStream(command, ctx, sandbox) {
497
518
  }
498
519
  void (async () => {
499
520
  const complete = tail.bytes >= rawBytes;
500
- const ref = await spillResult('bash', tail.text());
521
+ const ref = await spillResult('bash', tailText);
501
522
  recordCapped({
502
523
  tool: 'bash',
503
524
  total: rawBytes,
@@ -1,6 +1,6 @@
1
1
  import { readFile, writeFile } from 'node:fs/promises';
2
2
  import { relative } from 'node:path';
3
- import { escapesProject, OUTSIDE_PROJECT_WARNING, resolveUserPath } from './_paths.js';
3
+ import { escapesProject, gitMetadataWarning, OUTSIDE_PROJECT_WARNING, resolveUserPath, } from './_paths.js';
4
4
  import { buildEditDiff, editDiffStartLine } from './_diff.js';
5
5
  import { surfaceImportedDeps } from './_deps.js';
6
6
  import { groundUrls } from './_urls.js';
@@ -26,6 +26,12 @@ export const editTool = {
26
26
  const newStr = String(args.new_string ?? '');
27
27
  const full = resolveUserPath(ctx.cwd, path);
28
28
  const outside = escapesProject(ctx.cwd, full);
29
+ // Git config and hooks name programs something else runs, so they carry a warning the same way
30
+ // an out-of-project path does (#719). Combined into one `warnings` list so a path that is both
31
+ // (an outside repo's `.git/config`) raises each flag once, in one modal.
32
+ const gitMeta = gitMetadataWarning(ctx.cwd, full);
33
+ const gated = outside || gitMeta !== undefined;
34
+ const warnings = [...(outside ? [OUTSIDE_PROJECT_WARNING] : []), ...(gitMeta ? [gitMeta] : [])];
29
35
  // See write.ts for why these are two names. `rel` stays project-relative because it rides
30
36
  // `diff.path`, which App.tsx hands to addFileToIndex -> ignore (a RangeError on an absolute
31
37
  // path); `display` is what the user and the model see.
@@ -33,10 +39,17 @@ export const editTool = {
33
39
  const display = outside ? full : rel;
34
40
  // See write.ts — the same gap, the same gate. Checked before the file is read so the boundary is
35
41
  // reported instead of an incidental read error on a path we would refuse anyway.
36
- if (outside && !ctx.requestApproval) {
42
+ if (gated && !ctx.requestApproval) {
43
+ if (outside) {
44
+ return {
45
+ summary: `Edit refused: ${full} is outside the project directory (${ctx.cwd}), and approvals ` +
46
+ 'are bypassed so it cannot be confirmed with the user. Edit inside the project instead.',
47
+ };
48
+ }
37
49
  return {
38
- summary: `Edit refused: ${full} is outside the project directory (${ctx.cwd}), and approvals ` +
39
- 'are bypassed so it cannot be confirmed with the user. Edit inside the project instead.',
50
+ summary: `Edit refused: ${display} is git config or a hook, which runs code at the user's next ` +
51
+ 'git command. Approvals are bypassed so it cannot be confirmed with the user; edit a ' +
52
+ 'project file instead, or leave the change for the user.',
40
53
  };
41
54
  }
42
55
  if (oldStr === '') {
@@ -58,12 +71,12 @@ export const editTool = {
58
71
  // below, which no longer re-raises the warning — the boundary was consented to here, so under
59
72
  // `safe` that second one auto-approves and this stays a single modal.
60
73
  let approvedOutside = false;
61
- if (outside && ctx.requestApproval) {
74
+ if (gated && ctx.requestApproval) {
62
75
  const ok = await ctx.requestApproval({
63
76
  tool: 'edit',
64
77
  subject: display,
65
78
  preview: intentDiff(oldStr, newStr),
66
- warnings: [OUTSIDE_PROJECT_WARNING],
79
+ warnings,
67
80
  });
68
81
  if (!ok)
69
82
  return { summary: declineSummary('Edit', ` for ${display}`, ctx) };
@@ -1,6 +1,6 @@
1
1
  import { mkdir, stat, writeFile } from 'node:fs/promises';
2
2
  import { dirname, relative } from 'node:path';
3
- import { escapesProject, OUTSIDE_PROJECT_WARNING, resolveUserPath } from './_paths.js';
3
+ import { escapesProject, gitMetadataWarning, OUTSIDE_PROJECT_WARNING, resolveUserPath, } from './_paths.js';
4
4
  import { buildWriteDiff } from './_diff.js';
5
5
  import { surfaceImportedDeps } from './_deps.js';
6
6
  import { groundUrls } from './_urls.js';
@@ -21,6 +21,12 @@ export const writeTool = {
21
21
  const content = String(args.content ?? '');
22
22
  const full = resolveUserPath(ctx.cwd, path);
23
23
  const outside = escapesProject(ctx.cwd, full);
24
+ // Git config and hooks name programs something else runs, so they carry a warning the same way
25
+ // an out-of-project path does (#719). Combined into one `warnings` list so a path that is both
26
+ // (an outside repo's `.git/config`) raises each flag once, in one modal.
27
+ const gitMeta = gitMetadataWarning(ctx.cwd, full);
28
+ const gated = outside || gitMeta !== undefined;
29
+ const warnings = [...(outside ? [OUTSIDE_PROJECT_WARNING] : []), ...(gitMeta ? [gitMeta] : [])];
24
30
  // Two names for the same file, deliberately. `rel` stays project-relative because it is what
25
31
  // rides `diff.path`, and App.tsx feeds that straight to addFileToIndex -> ignore, which throws
26
32
  // a RangeError on an absolute path. `display` is the human- and model-facing string: an
@@ -32,10 +38,19 @@ export const writeTool = {
32
38
  // passed `warnings`, so under `safe` every write auto-approved to any path `resolveUserPath`
33
39
  // would produce — `~/.zshrc` included. Under `bypass` there is no modal to fall through to, so
34
40
  // the only honest answer is no; the model is told why, and that the project is where to write.
35
- if (outside && !ctx.requestApproval) {
41
+ // Git metadata gets the same treatment: bypassed, there is nobody to clear a hook write, so it
42
+ // is refused rather than landed (#719).
43
+ if (gated && !ctx.requestApproval) {
44
+ if (outside) {
45
+ return {
46
+ summary: `Write refused: ${full} is outside the project directory (${ctx.cwd}), and approvals ` +
47
+ 'are bypassed so it cannot be confirmed with the user. Write inside the project instead.',
48
+ };
49
+ }
36
50
  return {
37
- summary: `Write refused: ${full} is outside the project directory (${ctx.cwd}), and approvals ` +
38
- 'are bypassed so it cannot be confirmed with the user. Write inside the project instead.',
51
+ summary: `Write refused: ${display} is git config or a hook, which runs code at the user's next ` +
52
+ 'git command. Approvals are bypassed so it cannot be confirmed with the user; write a ' +
53
+ 'project file instead, or leave the change for the user.',
39
54
  };
40
55
  }
41
56
  const diffText = buildWriteDiff(content);
@@ -45,13 +60,13 @@ export const writeTool = {
45
60
  // model's own content, not the file's, so gating early loses no information. Inside the
46
61
  // project the order is unchanged.
47
62
  let approved = false;
48
- if (outside && ctx.requestApproval) {
63
+ if (gated && ctx.requestApproval) {
49
64
  const ok = await ctx.requestApproval({
50
65
  tool: 'write',
51
66
  subject: display,
52
67
  preview: diffText,
53
68
  startLine: 1,
54
- warnings: [OUTSIDE_PROJECT_WARNING],
69
+ warnings,
55
70
  });
56
71
  if (!ok)
57
72
  return { summary: declineSummary('Write', ` for ${display}`, ctx) };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexwkleung/reika",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Coding agent CLI for local and hosted models, designed around small local models first.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Alex Leung",