@alexwkleung/reika 0.2.0 → 0.4.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/agent/loop.js +1 -0
- package/dist/check/typecheck.js +115 -7
- package/dist/cli.js +3 -0
- package/dist/config.js +4 -3
- package/dist/headless.js +27 -2
- package/dist/headlessargs.js +12 -0
- package/dist/provider/modellimits.js +31 -0
- package/dist/session.js +24 -8
- package/dist/tools/_paths.js +105 -2
- package/dist/tools/_sandbox.js +299 -36
- package/dist/tools/_treediff.js +56 -11
- package/dist/tools/bash.js +38 -33
- package/dist/tools/edit.js +19 -6
- package/dist/tools/write.js +21 -6
- package/package.json +1 -1
- package/skills/review.md +8 -2
package/dist/tools/_sandbox.js
CHANGED
|
@@ -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
|
|
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';
|
|
@@ -32,8 +32,8 @@ import { dropCarriers, hasExecutableSubstitution, hasRawSubstitution, maskQuoted
|
|
|
32
32
|
// affordance fix, which is why `sandboxFooter` exists and why it names `ps` explicitly rather than
|
|
33
33
|
// letting a model read this as a bug in its own pipeline.
|
|
34
34
|
// A malformed profile makes `sandbox-exec` exit 65 *without running the command* — the sandbox
|
|
35
|
-
// fails closed, which is the opposite of what a fail-open feature wants.
|
|
36
|
-
//
|
|
35
|
+
// fails closed, which is the opposite of what a fail-open feature wants. `sandboxPlan` probes for it
|
|
36
|
+
// before any command runs (`profileLoadFailure`); the typecheck gate also reads it off its output.
|
|
37
37
|
export const SANDBOX_PROFILE_ERROR_CODE = 65;
|
|
38
38
|
export const SANDBOX_EXEC_ERROR_PREFIX = 'sandbox-exec:';
|
|
39
39
|
/** Seatbelt profile for one cwd. Pure string in, string out — the unit under test. */
|
|
@@ -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
|
|
56
|
-
//
|
|
57
|
-
//
|
|
58
|
-
//
|
|
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*)',
|
|
@@ -464,6 +484,7 @@ function hasSandboxExec() {
|
|
|
464
484
|
export function resetSandboxCache() {
|
|
465
485
|
execAvailable = undefined;
|
|
466
486
|
gitDirs.clear();
|
|
487
|
+
profileProbes.clear();
|
|
467
488
|
}
|
|
468
489
|
/**
|
|
469
490
|
* How to run a command under the sandbox, or why it can't be sandboxed.
|
|
@@ -507,19 +528,65 @@ export function sandboxPlan(cwd, opts) {
|
|
|
507
528
|
// Same realpath rule for every other allowed dir: `os.tmpdir()` is `/var/folders/…/T`, a symlink
|
|
508
529
|
// hop away from the `/private/var/…` the kernel matches. Each falls back to a path the profile
|
|
509
530
|
// already covers, so an unresolvable dir costs nothing rather than an unbound param (exit 65).
|
|
531
|
+
const params = sandboxParams(cwd, resolved);
|
|
532
|
+
const args = ['-p', sandboxProfile(opts)];
|
|
533
|
+
for (const [k, v] of Object.entries(params))
|
|
534
|
+
args.push('-D', `${k}=${v}`);
|
|
535
|
+
const failure = profileLoadFailure(args);
|
|
536
|
+
return failure ? { reason: failure } : { args };
|
|
537
|
+
}
|
|
538
|
+
const profileProbes = new Map();
|
|
539
|
+
/**
|
|
540
|
+
* Why `sandbox-exec` will not load these exact args, or null when it does. A generator bug (a bad
|
|
541
|
+
* rule, an unbound param) makes it exit 65 having run nothing, so every command would fail. Asking
|
|
542
|
+
* here, against `:`, settles that before a model's command exists (#738): the old check read the
|
|
543
|
+
* refusal off the confined command's own output, and `echo 'sandbox-exec: x' >&2; exit 65` bought
|
|
544
|
+
* itself an unconfined rerun. The probe runs the same bytes the command will get, and loading
|
|
545
|
+
* depends on nothing else, so a pass here means the real run loads too, and its exit 65 is its own.
|
|
546
|
+
*
|
|
547
|
+
* Only a refusal counts. A timeout or spawn error reads as loaded: assuming it failed would let a
|
|
548
|
+
* swapping machine switch the sandbox off, where assuming it loaded costs at worst a command that
|
|
549
|
+
* fails closed, visibly. Cached per argv: at most one per cwd and network setting.
|
|
550
|
+
*/
|
|
551
|
+
export function profileLoadFailure(args) {
|
|
552
|
+
const key = args.join('\0');
|
|
553
|
+
const cached = profileProbes.get(key);
|
|
554
|
+
if (cached !== undefined)
|
|
555
|
+
return cached;
|
|
556
|
+
let failure = null;
|
|
557
|
+
try {
|
|
558
|
+
const r = spawnSync('/usr/bin/sandbox-exec', [...args, '/bin/sh', '-c', ':'], {
|
|
559
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
560
|
+
encoding: 'utf8',
|
|
561
|
+
timeout: 5_000,
|
|
562
|
+
});
|
|
563
|
+
// `:` cannot fail, so any exit but 0 is sandbox-exec's own (65 a parse or bind error, 71 apply).
|
|
564
|
+
if (r.error === undefined && r.status !== null && r.status !== 0) {
|
|
565
|
+
const detail = r.stderr.trim().split('\n')[0] ?? '';
|
|
566
|
+
failure = `the sandbox profile failed to load (sandbox-exec exit ${r.status}${detail ? `: ${detail}` : ''})`;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
catch {
|
|
570
|
+
// Spawn threw: same as a timeout, read as loaded.
|
|
571
|
+
}
|
|
572
|
+
profileProbes.set(key, failure);
|
|
573
|
+
return failure;
|
|
574
|
+
}
|
|
575
|
+
/** The `-D` bindings for the profile's params. Exported so tests can prove every param is bound
|
|
576
|
+
* even where `sandboxPlan` refuses (nested seatbelt exits 71, but still parses the profile). */
|
|
577
|
+
export function sandboxParams(cwd, resolved) {
|
|
510
578
|
const home = homedir();
|
|
511
|
-
|
|
579
|
+
return {
|
|
512
580
|
WORKDIR: resolved,
|
|
513
|
-
GITDIR:
|
|
581
|
+
GITDIR: gitDirToBind(cwd, resolved) ?? NO_GITDIR,
|
|
514
582
|
TMPDIR: realOr(tmpdir(), '/private/tmp'),
|
|
515
583
|
USERCACHE: realOr(join(home, 'Library', 'Caches'), resolved),
|
|
516
584
|
XDGCACHE: realOr(process.env.XDG_CACHE_HOME || join(home, '.cache'), resolved),
|
|
517
585
|
};
|
|
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
586
|
}
|
|
587
|
+
/** GITDIR when there is none to bind: an unbound param exits 65, and nothing can exist under the
|
|
588
|
+
* `/dev/null` device, so every rule naming it matches nothing. */
|
|
589
|
+
export const NO_GITDIR = '/dev/null/reika-no-gitdir';
|
|
523
590
|
function realOr(path, fallback) {
|
|
524
591
|
try {
|
|
525
592
|
return realpathSync.native(path);
|
|
@@ -529,9 +596,9 @@ function realOr(path, fallback) {
|
|
|
529
596
|
}
|
|
530
597
|
}
|
|
531
598
|
const gitDirs = new Map();
|
|
532
|
-
/** The repo's common git dir
|
|
533
|
-
*
|
|
534
|
-
function
|
|
599
|
+
/** The repo's common git dir unless it is cwd's own `.git`: one inside cwd under another name
|
|
600
|
+
* (`--separate-git-dir`, a dotfiles repo) escapes the name-based denies. Cached per cwd. */
|
|
601
|
+
function gitDirToBind(cwd, resolvedCwd) {
|
|
535
602
|
const cached = gitDirs.get(cwd);
|
|
536
603
|
if (cached !== undefined)
|
|
537
604
|
return cached;
|
|
@@ -544,7 +611,7 @@ function gitDirOutside(cwd, resolvedCwd) {
|
|
|
544
611
|
timeout: 5_000,
|
|
545
612
|
}).trim();
|
|
546
613
|
const abs = realOr(isAbsolute(out) ? out : resolve(cwd, out), '');
|
|
547
|
-
if (abs && abs !== resolvedCwd
|
|
614
|
+
if (abs && abs !== join(resolvedCwd, '.git'))
|
|
548
615
|
dir = abs;
|
|
549
616
|
}
|
|
550
617
|
catch {
|
|
@@ -589,11 +656,149 @@ export function sandboxNotice(cwd, home = homedir()) {
|
|
|
589
656
|
// Python's `[Errno 1] Operation not permitted` is a network denial only WITHOUT a trailing quoted
|
|
590
657
|
// path — with one (`PermissionError: [Errno 1] Operation not permitted: '/Users/x/f'`) it is a write.
|
|
591
658
|
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
|
|
593
|
-
//
|
|
594
|
-
//
|
|
595
|
-
//
|
|
596
|
-
|
|
659
|
+
// A write the profile refused: `<prog>: <path>: Operation not permitted` from the shell and
|
|
660
|
+
// coreutils (behind any `<runner>: ` prefixes — turbo, pnpm -r, a go error chain — or indentation),
|
|
661
|
+
// go's `open <path>: …` with no colon after the verb, git's bare absolute `<path>: …`, node's and
|
|
662
|
+
// python's mid-line shapes, and (#723) two forms the slash requirement dropped:
|
|
663
|
+
//
|
|
664
|
+
// - a SLASHLESS path, which only a file verb may introduce: `rm -rf .git` prints `rm: .git:
|
|
665
|
+
// Operation not permitted`, `mv .git .g` prints `mv: rename .git to .g: …` and `tee config` from
|
|
666
|
+
// inside `.git` prints `tee: config: …`; `sed -i` names no path at all (`sed: rename(): …`,
|
|
667
|
+
// measured on macOS sed). Since #706 these are among the refusals a model is likeliest to cause,
|
|
668
|
+
// and the slash dropped them. Making the slash
|
|
669
|
+
// optional after ANY `<prog>: ` instead would match `docker: connect: operation not permitted`, a
|
|
670
|
+
// network denial, and the write line would then point the model at the wrong thing.
|
|
671
|
+
// - a quoted path before the phrase, which is git's form for the same refusals: `fatal: cannot copy
|
|
672
|
+
// '…/templates/hooks/commit-msg.sample' to '…/.git/hooks/commit-msg.sample': Operation not
|
|
673
|
+
// permitted`, what `git init` prints now that #706 denies the hook copy. The quotes and spaces put
|
|
674
|
+
// it out of reach of the path forms above, and the tail is the only part of git's line that does
|
|
675
|
+
// not change with the message. It must sit behind git's own `fatal:`/`error:`, so a test title
|
|
676
|
+
// quoting a path is not one, and a quoted URL is not a path: `fatal: unable to access
|
|
677
|
+
// 'https://…/': Operation not permitted` is a network shape.
|
|
678
|
+
// - git's config refusal, `error: could not write config file .git/config: Operation not
|
|
679
|
+
// permitted` — what `git config` prints since #706 (measured; `lock` is the same message when the
|
|
680
|
+
// lock file is the refused one), with no verb or slash in front of the path.
|
|
681
|
+
//
|
|
682
|
+
// Python's `[Errno 1] Operation not permitted: '<path>'` takes a relative path too (`'.git/config'`);
|
|
683
|
+
// the `[Errno 1]` is what keeps a quoted test name or host from reading as one.
|
|
684
|
+
//
|
|
685
|
+
// All but node's must END the line (#720): quoted text — a comment, a fixture string, a grep hit —
|
|
686
|
+
// carries text after the phrase, and prose before the path must end in `: ` or be a single verb, so a
|
|
687
|
+
// sentence that quotes the error is not a refusal. A denial line quoted whole at column 0 and node's
|
|
688
|
+
// mid-line shape still read as one.
|
|
689
|
+
//
|
|
690
|
+
// The prefix in front of every form below is an ALLOWLIST of what runners print (#726). #720 allowed
|
|
691
|
+
// any `.*: ` here so that a runner's column reached a shape added for the shell's own output, and
|
|
692
|
+
// that is what let a line which only QUOTES a refusal read as one whenever the quote sat behind a
|
|
693
|
+
// colon column of its own — the assertion header a failing test prints over the fixture it compared
|
|
694
|
+
// (`Expected: rm: .git: Operation not permitted`, and `AssertionError: /bin/sh: /Users/x/f: Operation
|
|
695
|
+
// not permitted`, which is not a hypothetical: it is reika's own `_sandbox.test.ts` failing under the
|
|
696
|
+
// `| grep -E "AssertionError|expected"` a model wraps it in), a diff's added/removed line (`+ mkdir:
|
|
697
|
+
// /Users/x: …`, what `gh pr diff` of such a fixture prints), and git's own quoted form behind either
|
|
698
|
+
// (`Expected: fatal: cannot copy '…' to '….git/hooks/…': Operation not permitted`). Each produced the
|
|
699
|
+
// write footer and the once-per-cwd `REIKA_SANDBOX=0` receipt for a write that never happened — the
|
|
700
|
+
// #720 class, which #725 widened the exposure of by scanning a run's 4MB tail, not just its 64KB
|
|
701
|
+
// head. So the prefix is these five shapes, one source for all the forms below, and a runner nobody
|
|
702
|
+
// listed loses its footer rather than the rest of the class getting through: a miss costs one
|
|
703
|
+
// footer, a false hit costs a footer AND that receipt.
|
|
704
|
+
//
|
|
705
|
+
// `name: ` / `name build: ` turbo's `web:build: `, pnpm -r's `packages/web build: `
|
|
706
|
+
// `[n] ` a job or worker number, padded or not (`[0] `, `[1] `)
|
|
707
|
+
// `name | ` concurrently's column (`web:build | `)
|
|
708
|
+
// indentation a test runner printing an indented line
|
|
709
|
+
// `go: <prose>: ` go's error chain, whose middle segment is prose and cannot be a name
|
|
710
|
+
//
|
|
711
|
+
// What may NOT be one is assertion vocabulary, refused BY NAME because it is name-shaped: a
|
|
712
|
+
// capitalized header (`Expected: `/`Received: `/`Actual: `/`AssertionError: `, the last measured, the
|
|
713
|
+
// 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
|
|
714
|
+
// does not make it one: `web:build: Expected: …` is the issue's red suite under turbo, the word can
|
|
715
|
+
// end a column as its trailing token (`run: Expected: `), and the go chain's prose segment can carry
|
|
716
|
+
// it (`go: x: Expected: `). So the vocabulary is checked where a name starts AND at the `:` that ends
|
|
717
|
+
// a column (the `(?<!…)` before each terminator), and a go chain stops at the first segment that
|
|
718
|
+
// ends in it, not only at the line's first token. A diff's
|
|
719
|
+
// `+ `/`- ` marker needs no
|
|
720
|
+
// rule of its own — a column cannot start with one, which is also why a column-0 `-bash: /x: …` (a
|
|
721
|
+
// login shell naming itself) is dropped: at column 0 the marker and the shell's name are the same
|
|
722
|
+
// character. A line number is not a column either, so a name must carry a letter somewhere — that is
|
|
723
|
+
// what keeps `668: mkdir: /x: Operation not permitted`, a `grep -n` hit on an indented denial, out;
|
|
724
|
+
// a runner that numbers its lines brackets the number (`[0] `), form or not.
|
|
725
|
+
//
|
|
726
|
+
// What is left is one-directional and stated: a runner whose column is one of the shapes above keeps
|
|
727
|
+
// its footer, and adding one belongs on the list rather than back in the open form. Replayed over the
|
|
728
|
+
// 7,335 `bash` outputs saved in a session history (32,418 distinct lines, `evals/sandboxdenial-replay.ts`),
|
|
729
|
+
// this changed one verdict — the `AssertionError: ` line above — and lost no runner shape.
|
|
730
|
+
// `error` is the generic header a test prints over a thrown fixture string (`Error: rm: .git: …`); no
|
|
731
|
+
// runner is named for it, and git's own `error: … '…': …` form is matched as a form, not a column.
|
|
732
|
+
const RUNNER_VOCABULARY = String.raw `(?:expected|received|actual|assertionerror|error)`;
|
|
733
|
+
const RUNNER_NAME = String.raw `(?=[^\s|]*[A-Za-z])[^\s|+-][^\s|]*`;
|
|
734
|
+
// One column, anchored at the start of what is left of the line. Matched one at a time by
|
|
735
|
+
// `isRefusalBehindRunnerColumns` rather than repeated inside one regex: a name may contain `:`
|
|
736
|
+
// (`web:build`), so `a: b: ` splits into columns more than one way, and a quantified group over
|
|
737
|
+
// those overlapping readings backtracks exponentially on a line of repeated `x: ` segments — over
|
|
738
|
+
// a run's 4MB tail, on the main thread. Alternation order is the tie-break the regex no longer gets
|
|
739
|
+
// from backtracking: `name: ` before `name build: `, or `/bin/sh: /x/f: ` reads as one column.
|
|
740
|
+
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');
|
|
741
|
+
// go's chain is `go: <prose>: <prose>: <error>`, so its segments are cut at every `: ` in turn.
|
|
742
|
+
const GO_CHAIN_RE = /^go:[ \t]+/i;
|
|
743
|
+
const GO_SEGMENT_END_RE = new RegExp(String.raw `\b${RUNNER_VOCABULARY}$`, 'i');
|
|
744
|
+
// Deeper than any runner nests its columns or go its chain; it bounds the walk on a line that is
|
|
745
|
+
// nothing but `x: x: x: …`.
|
|
746
|
+
const MAX_RUNNER_COLUMNS = 8;
|
|
747
|
+
// A path may carry one token in front of its first slash — `~/x`, `./x`, `../x`, and the `~` a shell
|
|
748
|
+
// prints unexpanded when the command was quoted. It cannot start with `+`/`-` for the diff marker's
|
|
749
|
+
// reason: with the column above optional, an unconstrained token here would read `+/Users/x/.git:
|
|
750
|
+
// Operation not permitted` (the added-line form of a fixture) as a path.
|
|
751
|
+
const PATH_LEAD = String.raw `(?:[^\s:'"+-][^\s:'"]*)?`;
|
|
752
|
+
// The forms a refusal takes once the runner's columns are off the front of its line.
|
|
753
|
+
const FS_DENIAL_FORM_RE = new RegExp([
|
|
754
|
+
// `<prog>: <abs path>: …`, go's `open <abs path>: …`, git's bare `<abs path>: …`.
|
|
755
|
+
String.raw `^(?:[a-z]+ )?${PATH_LEAD}\/[^:'"\r\n]*: operation not permitted[ \t]*$`,
|
|
756
|
+
// A slashless path, which only a file verb may introduce.
|
|
757
|
+
String.raw `^(?:rm|mv|cp|mkdir|touch|ln|tee): [^:'"\r\n]*: operation not permitted[ \t]*$`,
|
|
758
|
+
String.raw `^sed: rename\(\): operation not permitted[ \t]*$`,
|
|
759
|
+
// git's quoted-path form, behind its own `fatal:`/`error:` so a test title quoting a path is not one.
|
|
760
|
+
String.raw `^(?:fatal|error): [^\r\n]*'(?![a-z][a-z0-9+.-]*:\/\/)[^'\r\n]*\/[^'\r\n]*': operation not permitted[ \t]*$`,
|
|
761
|
+
].join('|'), 'i');
|
|
762
|
+
// Shapes printed mid-line, so no column rule applies to them.
|
|
763
|
+
const FS_DENIAL_ANYWHERE_RE = new RegExp([
|
|
764
|
+
String.raw `could not (?:lock|write) config file [^\r\n]*: operation not permitted[ \t]*$`,
|
|
765
|
+
String.raw `EPERM: operation not permitted, \w+ '`,
|
|
766
|
+
String.raw `\[Errno 1\] operation not permitted: '[^'\r\n]+'[ \t]*$`,
|
|
767
|
+
].join('|'), 'i');
|
|
768
|
+
function isRefusalForm(rest) {
|
|
769
|
+
return FS_DENIAL_FORM_RE.test(rest.replace(/^[ \t]+/, ''));
|
|
770
|
+
}
|
|
771
|
+
// A go chain carrying assertion vocabulary is a quote (`go: x: Expected: …`), so the walk stops at the
|
|
772
|
+
// first segment that ends in it rather than cutting past it.
|
|
773
|
+
function isRefusalBehindGoChain(rest) {
|
|
774
|
+
let from = rest.match(GO_CHAIN_RE)[0].length;
|
|
775
|
+
if (isRefusalForm(rest.slice(from)))
|
|
776
|
+
return true;
|
|
777
|
+
for (let i = 0; i < MAX_RUNNER_COLUMNS; i++) {
|
|
778
|
+
const cut = rest.indexOf(': ', from);
|
|
779
|
+
if (cut === -1 || GO_SEGMENT_END_RE.test(rest.slice(from, cut)))
|
|
780
|
+
return false;
|
|
781
|
+
from = cut + 2;
|
|
782
|
+
if (isRefusalForm(rest.slice(from)))
|
|
783
|
+
return true;
|
|
784
|
+
}
|
|
785
|
+
return false;
|
|
786
|
+
}
|
|
787
|
+
function isRefusalBehindRunnerColumns(line) {
|
|
788
|
+
let rest = line;
|
|
789
|
+
for (let i = 0; i <= MAX_RUNNER_COLUMNS; i++) {
|
|
790
|
+
rest = rest.replace(/^[ \t]+/, '');
|
|
791
|
+
if (isRefusalForm(rest))
|
|
792
|
+
return true;
|
|
793
|
+
if (GO_CHAIN_RE.test(rest))
|
|
794
|
+
return isRefusalBehindGoChain(rest);
|
|
795
|
+
const column = RUNNER_COLUMN_RE.exec(rest);
|
|
796
|
+
if (!column)
|
|
797
|
+
return false;
|
|
798
|
+
rest = rest.slice(column[0].length);
|
|
799
|
+
}
|
|
800
|
+
return false;
|
|
801
|
+
}
|
|
597
802
|
// Where to send the model for the page it wanted. Keyed on the turn's tool list (the #377 rule: a
|
|
598
803
|
// result must not point at a tool the model does not have): minimal mode is bash alone, and an
|
|
599
804
|
// offline session registers neither web tool, so "use fetch_url" there is a phantom pointer the
|
|
@@ -611,15 +816,63 @@ function webRoute(toolNames) {
|
|
|
611
816
|
parts.push('the search tool instead of scraping');
|
|
612
817
|
return `For a web page, ${parts.join(', and ')}.`;
|
|
613
818
|
}
|
|
614
|
-
// The exec refusal the setuid note at the top of the file is about, as the shell prints it
|
|
615
|
-
|
|
819
|
+
// The exec refusal the setuid note at the top of the file is about, as the shell prints it: bare
|
|
820
|
+
// (`ps: …`), behind the shell (`/bin/sh: /bin/ps: …`, and `/bin/sh: line 1: /bin/ps: …` for a
|
|
821
|
+
// multi-line command) or behind a wrapper (`env: ps: …`, `xargs: ps: …`). `ps`/`top` must follow a
|
|
822
|
+
// line start or `: ` directly, with only `/bin/` or `/usr/bin/` allowed between, so a refused write to
|
|
823
|
+
// a path ending in `/top` (`mkdir: /Users/x/top: …`) is not mistaken for it.
|
|
824
|
+
const PS_DENIAL_RE = /(?:^|: )(?:\/(?:usr\/)?bin\/)?(?:ps|top): Operation not permitted/m;
|
|
825
|
+
const PS_DENIAL_LINE_RE = /^.*?(?:^|: )(?:\/(?:usr\/)?bin\/)?(?:ps|top): Operation not permitted.*$/gm;
|
|
826
|
+
// One output can carry both a ps refusal and a refused write — `ps aux | grep node; mkdir ~/x` —
|
|
827
|
+
// and `!ps` on the whole output dropped the write line for exactly the command that shows both
|
|
828
|
+
// (#723). Only the ps/top lines are blanked out of the write check: `/bin/ps: Operation not
|
|
829
|
+
// permitted` is a path by shape and is already explained by the ps note. One replace rather than a
|
|
830
|
+
// split and join, since this runs over up to 4MB of a run's tail.
|
|
831
|
+
function withoutPsDenials(output) {
|
|
832
|
+
return output.replace(PS_DENIAL_LINE_RE, '');
|
|
833
|
+
}
|
|
616
834
|
// `curl -s` prints nothing on a denial and exits 6 (could not resolve) or 7 (could not connect) —
|
|
617
835
|
// the one shape the output gate cannot see, so the exit status has to carry it.
|
|
618
836
|
const CURL_RE = /(?:^|[|;&(]\s*)(?:[A-Za-z_]\w*=\S*\s+)*curl(?![\w./-])/;
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
837
|
+
function lineEndFrom(text, from) {
|
|
838
|
+
const lf = text.indexOf('\n', from);
|
|
839
|
+
const cr = text.indexOf('\r', from);
|
|
840
|
+
if (lf === -1)
|
|
841
|
+
return cr === -1 ? text.length : cr;
|
|
842
|
+
return cr === -1 ? lf : Math.min(lf, cr);
|
|
843
|
+
}
|
|
844
|
+
/** The line of a sandboxed command's output that shows a write the profile refused, or null. The
|
|
845
|
+
* user-facing half: the footer tells the model not to fight it, the notice tells the user the flag
|
|
846
|
+
* exists (`bash.ts`). Returned whole so the footer can quote it when it is not in the payload. */
|
|
847
|
+
export function refusedWriteLine(output) {
|
|
848
|
+
const scanned = withoutPsDenials(output);
|
|
849
|
+
// Every form carries the phrase, so only the lines that do are read — linear in the output.
|
|
850
|
+
const phrase = /operation not permitted/gi;
|
|
851
|
+
for (let found = phrase.exec(scanned); found; found = phrase.exec(scanned)) {
|
|
852
|
+
const at = found.index;
|
|
853
|
+
// A `\r` starts a line as a `\n` does (a progress bar redrawn over), as `^`/`$` read it under
|
|
854
|
+
// the `m` flag; the quote is the whole `\n` line around it.
|
|
855
|
+
const segStart = Math.max(scanned.lastIndexOf('\n', at), scanned.lastIndexOf('\r', at)) + 1;
|
|
856
|
+
const segEnd = lineEndFrom(scanned, at);
|
|
857
|
+
const segment = scanned.slice(segStart, segEnd);
|
|
858
|
+
if (FS_DENIAL_ANYWHERE_RE.test(segment) || isRefusalBehindRunnerColumns(segment)) {
|
|
859
|
+
const start = scanned.lastIndexOf('\n', at) + 1;
|
|
860
|
+
const end = scanned.indexOf('\n', at);
|
|
861
|
+
return scanned.slice(start, end === -1 ? undefined : end).trim();
|
|
862
|
+
}
|
|
863
|
+
phrase.lastIndex = segEnd;
|
|
864
|
+
}
|
|
865
|
+
return null;
|
|
866
|
+
}
|
|
867
|
+
// A quoted line is the model's only pointer to WHICH write failed when it sat past the payload head;
|
|
868
|
+
// a pathological one (a minified log on one line) must not become a 4MB footer.
|
|
869
|
+
const QUOTED_DENIAL_MAX_CHARS = 300;
|
|
870
|
+
// The line is the command's output, so a backtick in it would close the code span it is quoted in.
|
|
871
|
+
function quoteDenial(line) {
|
|
872
|
+
const safe = line.replaceAll('`', "'");
|
|
873
|
+
return safe.length > QUOTED_DENIAL_MAX_CHARS
|
|
874
|
+
? `${safe.slice(0, QUOTED_DENIAL_MAX_CHARS)}…`
|
|
875
|
+
: safe;
|
|
623
876
|
}
|
|
624
877
|
/**
|
|
625
878
|
* What the model is told when a sandboxed command exits non-zero.
|
|
@@ -670,13 +923,23 @@ export function sandboxFooter(command, code, output, opts) {
|
|
|
670
923
|
webRoute(opts.toolNames) +
|
|
671
924
|
' If the command genuinely needs the network, say so and ask the user to run it.');
|
|
672
925
|
}
|
|
673
|
-
// `/bin/ps: Operation not permitted` is a path too, and already explained above
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
926
|
+
// `/bin/ps: Operation not permitted` is a path too, and already explained above, so the ps lines
|
|
927
|
+
// are taken out before this test rather than the write check being skipped for the whole output.
|
|
928
|
+
// The line says "a path it does not allow", not "outside the working directory": since #706 the
|
|
929
|
+
// denied paths include `.git/config` and `.git/hooks`, which are INSIDE the working directory.
|
|
930
|
+
const refused = opts.refusedWrite === undefined ? refusedWriteLine(output) : opts.refusedWrite;
|
|
931
|
+
if (refused !== null) {
|
|
932
|
+
// Past the payload head the model sees no refusal at all, so the line is quoted: without it the
|
|
933
|
+
// model guesses which write failed or re-runs the whole command to find out.
|
|
934
|
+
const quoted = output.includes(refused)
|
|
935
|
+
? ''
|
|
936
|
+
: ` It was printed after the output shown above: \`${quoteDenial(refused)}\`.`;
|
|
937
|
+
lines.push('The sandbox refused a write to a path it does not allow — not a permissions problem, so do ' +
|
|
938
|
+
'not reach for sudo or chmod.' +
|
|
939
|
+
quoted +
|
|
940
|
+
' If the command must write there, say so and ask the user to run it.');
|
|
678
941
|
}
|
|
679
942
|
if (lines.length === 0)
|
|
680
943
|
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.)`;
|
|
944
|
+
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
945
|
}
|
package/dist/tools/_treediff.js
CHANGED
|
@@ -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
|
-
|
|
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 [
|
|
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
|
|
136
|
-
//
|
|
137
|
-
//
|
|
138
|
-
|
|
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(
|
|
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',
|
|
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,
|