@foldrun/core 24.10.0 → 24.12.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/src/engine-common.d.ts +21 -0
- package/dist/src/engine-common.js +12 -1
- package/dist/src/engine-loop.js +7 -2
- package/dist/src/engine-mcp.d.ts +4 -0
- package/dist/src/engine-mcp.js +62 -2
- package/dist/src/engine-tools.d.ts +7 -0
- package/dist/src/engine-tools.js +275 -19
- package/dist/src/local-sandbox.d.ts +135 -0
- package/dist/src/local-sandbox.js +1289 -0
- package/dist/src/runner.d.ts +7 -1
- package/dist/src/runner.js +27 -4
- package/package.json +9 -2
- package/src/engine-common.ts +29 -1
- package/src/engine-loop.ts +7 -2
- package/src/engine-mcp.ts +60 -3
- package/src/engine-tools.ts +257 -25
- package/src/local-sandbox.ts +1274 -0
- package/src/runner.ts +27 -6
package/dist/src/engine-tools.js
CHANGED
|
@@ -23,6 +23,80 @@ import fs from "node:fs";
|
|
|
23
23
|
import path from "node:path";
|
|
24
24
|
import { spawn } from "node:child_process";
|
|
25
25
|
import { Worker } from "node:worker_threads";
|
|
26
|
+
import { randomBytes } from "node:crypto";
|
|
27
|
+
import { LAUNCHER } from "./local-sandbox.js";
|
|
28
|
+
/** A file's contents, read through the descriptor that was checked: inside
|
|
29
|
+
* the walls, the open file must be the very file now at the path the rules
|
|
30
|
+
* allow (same device and inode), so a path swapped between the check and
|
|
31
|
+
* the open is refused, not read. A string is the refusal. */
|
|
32
|
+
async function readChecked(ctx, file) {
|
|
33
|
+
if (!ctx.sandbox)
|
|
34
|
+
return fs.readFileSync(file);
|
|
35
|
+
// Inside the walls the read itself runs there (cat), so the OS holds it
|
|
36
|
+
// however the path changes between a check and the read.
|
|
37
|
+
const r = await runInside(ctx, `exec /bin/cat -- ${shq(file)}`, "");
|
|
38
|
+
if (r.code !== 0)
|
|
39
|
+
return `${file} could not be read: ${r.err || "the sandbox refused it"}`;
|
|
40
|
+
return r.out;
|
|
41
|
+
}
|
|
42
|
+
/** Run a short helper inside the walls with nothing of the step's
|
|
43
|
+
* environment: its stdout as bytes, the last line of its stderr. */
|
|
44
|
+
async function runInside(ctx, script, input, ms = 60_000) {
|
|
45
|
+
// A plain PATH inside for the helper's own commands (mkdir, mv…): what
|
|
46
|
+
// they reach is the walls' business, not the PATH's.
|
|
47
|
+
const { line, env } = await ctx.sandbox.launch(script, { PATH: "/usr/bin:/bin:/usr/sbin:/sbin" });
|
|
48
|
+
return new Promise((resolve) => {
|
|
49
|
+
const child = spawn(LAUNCHER, ["-c", line], { cwd: ctx.cwd, env: env, stdio: ["pipe", "pipe", "pipe"], detached: true });
|
|
50
|
+
const chunks = [];
|
|
51
|
+
let err = "";
|
|
52
|
+
let done = false;
|
|
53
|
+
const end = (code, why) => {
|
|
54
|
+
if (done)
|
|
55
|
+
return;
|
|
56
|
+
done = true;
|
|
57
|
+
clearTimeout(timer);
|
|
58
|
+
ctx.signal.removeEventListener("abort", stop);
|
|
59
|
+
resolve({ code, out: Buffer.concat(chunks), err: why ?? (err.trim().split("\n").pop() || (code === 0 ? "" : `exit ${code}`)) });
|
|
60
|
+
};
|
|
61
|
+
const kill = () => {
|
|
62
|
+
try {
|
|
63
|
+
if (child.pid)
|
|
64
|
+
process.kill(-child.pid, "SIGKILL");
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
/* gone */
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
const stop = () => {
|
|
71
|
+
kill();
|
|
72
|
+
end(null, "stopped");
|
|
73
|
+
};
|
|
74
|
+
const timer = setTimeout(() => {
|
|
75
|
+
kill();
|
|
76
|
+
end(null, `ran past ${ms / 1000} s`);
|
|
77
|
+
}, ms);
|
|
78
|
+
ctx.signal.addEventListener("abort", stop, { once: true });
|
|
79
|
+
child.stdout.on("data", (c) => chunks.push(c));
|
|
80
|
+
child.stderr.on("data", (c) => {
|
|
81
|
+
if (err.length < 4000)
|
|
82
|
+
err += c.toString("utf8");
|
|
83
|
+
});
|
|
84
|
+
child.on("error", (e) => end(null, e.message));
|
|
85
|
+
child.on("close", (code) => end(code));
|
|
86
|
+
child.stdin.on("error", () => undefined);
|
|
87
|
+
child.stdin.end(input, "utf8");
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
/** The sandbox's answer for a path, as a tool's refusal — null when allowed. */
|
|
91
|
+
function walled(ctx, file, write) {
|
|
92
|
+
if (!ctx.sandbox)
|
|
93
|
+
return null;
|
|
94
|
+
if (write ? ctx.sandbox.canWrite(file) : ctx.sandbox.canRead(file))
|
|
95
|
+
return null;
|
|
96
|
+
return fail(write
|
|
97
|
+
? `${file} is outside what this session may write (the project folder and its temp folder; never git hooks or config, never credentials)`
|
|
98
|
+
: `${file} holds credentials this session may not read`);
|
|
99
|
+
}
|
|
26
100
|
/** End everything the session's commands started and left running. */
|
|
27
101
|
export function killGroups(ctx) {
|
|
28
102
|
for (const pgid of ctx.groups) {
|
|
@@ -87,6 +161,27 @@ function abs(ctx, p) {
|
|
|
87
161
|
function looksBinary(buf) {
|
|
88
162
|
return buf.subarray(0, 8192).includes(0);
|
|
89
163
|
}
|
|
164
|
+
/** Write a file inside the walls: a small shell helper run there makes the
|
|
165
|
+
* folders, writes a temp file and renames it into place, so the OS holds
|
|
166
|
+
* the write wherever a path has been swapped meanwhile. */
|
|
167
|
+
async function writeInside(file, content, ctx) {
|
|
168
|
+
// Folders, a temp file and the rename all happen inside the walls.
|
|
169
|
+
let mode = "";
|
|
170
|
+
try {
|
|
171
|
+
mode = (fs.statSync(file).mode & 0o7777).toString(8);
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
// a new file takes the default mode
|
|
175
|
+
}
|
|
176
|
+
const d = shq(path.dirname(file));
|
|
177
|
+
const script = `mkdir -p -- ${d} && t=$(mktemp ${shq(path.join(path.dirname(file), `.${path.basename(file)}.XXXXXXXX`))}) || exit 1\n` +
|
|
178
|
+
`if cat > "$t"${mode ? ` && chmod ${mode} "$t"` : ""} && mv -f -- "$t" ${shq(file)}; then exit 0; fi\n` +
|
|
179
|
+
`rm -f -- "$t"; exit 1`;
|
|
180
|
+
const r = await runInside(ctx, script, content);
|
|
181
|
+
if (r.code !== 0)
|
|
182
|
+
throw new Error(r.err || `the sandbox refused the write`);
|
|
183
|
+
}
|
|
184
|
+
const shq = (s) => `'${s.replaceAll("'", `'\\''`)}'`;
|
|
90
185
|
function writeWhole(file, content) {
|
|
91
186
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
92
187
|
let mode;
|
|
@@ -96,9 +191,11 @@ function writeWhole(file, content) {
|
|
|
96
191
|
catch {
|
|
97
192
|
// a new file takes the default mode
|
|
98
193
|
}
|
|
99
|
-
|
|
194
|
+
// A name nobody can have planted (random), created only if it is not
|
|
195
|
+
// there (wx): a link left at a guessable name cannot redirect the write.
|
|
196
|
+
const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${randomBytes(8).toString("hex")}.tmp`);
|
|
100
197
|
try {
|
|
101
|
-
fs.writeFileSync(tmp, content, mode !== undefined ? { mode } :
|
|
198
|
+
fs.writeFileSync(tmp, content, { flag: "wx", ...(mode !== undefined ? { mode } : {}) });
|
|
102
199
|
fs.renameSync(tmp, file);
|
|
103
200
|
}
|
|
104
201
|
catch (err) {
|
|
@@ -142,6 +239,9 @@ const read = {
|
|
|
142
239
|
if (!given)
|
|
143
240
|
return fail("Read needs file_path");
|
|
144
241
|
const file = abs(ctx, given);
|
|
242
|
+
const no = walled(ctx, file, false);
|
|
243
|
+
if (no)
|
|
244
|
+
return no;
|
|
145
245
|
let stat;
|
|
146
246
|
try {
|
|
147
247
|
stat = fs.statSync(file);
|
|
@@ -151,7 +251,9 @@ const read = {
|
|
|
151
251
|
}
|
|
152
252
|
if (stat.isDirectory())
|
|
153
253
|
return fail(`${file} is a directory — use Glob to list files`);
|
|
154
|
-
const buf =
|
|
254
|
+
const buf = await readChecked(ctx, file);
|
|
255
|
+
if (typeof buf === "string")
|
|
256
|
+
return fail(buf);
|
|
155
257
|
if (looksBinary(buf))
|
|
156
258
|
return fail(`${file} is not a text file`);
|
|
157
259
|
ctx.reads.set(file, stat.mtimeMs);
|
|
@@ -193,6 +295,9 @@ const write = {
|
|
|
193
295
|
if (!given || content === null)
|
|
194
296
|
return fail("Write needs file_path and content");
|
|
195
297
|
const file = abs(ctx, given);
|
|
298
|
+
const no = walled(ctx, file, true);
|
|
299
|
+
if (no)
|
|
300
|
+
return no;
|
|
196
301
|
try {
|
|
197
302
|
if (fs.statSync(file).isDirectory())
|
|
198
303
|
return fail(`${file} is a directory`);
|
|
@@ -204,7 +309,15 @@ const write = {
|
|
|
204
309
|
if (stale)
|
|
205
310
|
return fail(stale);
|
|
206
311
|
const existed = fs.existsSync(file);
|
|
207
|
-
|
|
312
|
+
try {
|
|
313
|
+
if (ctx.sandbox)
|
|
314
|
+
await writeInside(file, content, ctx);
|
|
315
|
+
else
|
|
316
|
+
writeWhole(file, content);
|
|
317
|
+
}
|
|
318
|
+
catch (err) {
|
|
319
|
+
return fail(`${file} was not written: ${err instanceof Error ? err.message : String(err)}`);
|
|
320
|
+
}
|
|
208
321
|
ctx.reads.set(file, fs.statSync(file).mtimeMs);
|
|
209
322
|
return { text: `${existed ? "Wrote" : "Created"} ${file} (${content.length} characters)` };
|
|
210
323
|
},
|
|
@@ -241,6 +354,9 @@ const edit = {
|
|
|
241
354
|
if (!given || from === null || to === null)
|
|
242
355
|
return fail("Edit needs file_path, old_string and new_string");
|
|
243
356
|
const file = abs(ctx, given);
|
|
357
|
+
const no = walled(ctx, file, true);
|
|
358
|
+
if (no)
|
|
359
|
+
return no;
|
|
244
360
|
if (!fs.existsSync(file))
|
|
245
361
|
return fail(`${file} does not exist — use Write to create it`);
|
|
246
362
|
if (fs.statSync(file).isDirectory())
|
|
@@ -252,7 +368,9 @@ const edit = {
|
|
|
252
368
|
return fail("old_string is empty — give the exact text to replace, or use Write for a whole file");
|
|
253
369
|
if (from === to)
|
|
254
370
|
return fail("old_string and new_string are the same — nothing to change");
|
|
255
|
-
const buf =
|
|
371
|
+
const buf = await readChecked(ctx, file);
|
|
372
|
+
if (typeof buf === "string")
|
|
373
|
+
return fail(buf);
|
|
256
374
|
if (looksBinary(buf))
|
|
257
375
|
return fail(`${file} is not a text file`);
|
|
258
376
|
const before = buf.toString("utf8");
|
|
@@ -270,7 +388,15 @@ const edit = {
|
|
|
270
388
|
// split/join and slice, never String.replace: `$&` in new_string is text.
|
|
271
389
|
const at = before.indexOf(from);
|
|
272
390
|
const after = all ? before.split(from).join(to) : before.slice(0, at) + to + before.slice(at + from.length);
|
|
273
|
-
|
|
391
|
+
try {
|
|
392
|
+
if (ctx.sandbox)
|
|
393
|
+
await writeInside(file, after, ctx);
|
|
394
|
+
else
|
|
395
|
+
writeWhole(file, after);
|
|
396
|
+
}
|
|
397
|
+
catch (err) {
|
|
398
|
+
return fail(`${file} was not changed: ${err instanceof Error ? err.message : String(err)}`);
|
|
399
|
+
}
|
|
274
400
|
ctx.reads.set(file, fs.statSync(file).mtimeMs);
|
|
275
401
|
return { text: `Edited ${file} (${all ? count : 1} replacement${(all ? count : 1) === 1 ? "" : "s"})` };
|
|
276
402
|
},
|
|
@@ -424,7 +550,51 @@ export function globProblem(glob) {
|
|
|
424
550
|
return expandBraces(glob) ? null : `the glob's braces make more than ${GLOB_ALTERNATIVES} patterns — name fewer`;
|
|
425
551
|
}
|
|
426
552
|
/** Every file under `root`, as paths relative to it. Bounded. */
|
|
427
|
-
|
|
553
|
+
// The listing half of Glob and Grep, as a node program inside the walls:
|
|
554
|
+
// there the OS, not a check made before, decides which folders it may list.
|
|
555
|
+
const WALK_CHILD = `
|
|
556
|
+
const fs = process.getBuiltinModule("node:fs");
|
|
557
|
+
const path = process.getBuiltinModule("node:path");
|
|
558
|
+
const w = JSON.parse(fs.readFileSync(0, "utf8"));
|
|
559
|
+
const skip = new Set(w.skip);
|
|
560
|
+
const files = [];
|
|
561
|
+
const stack = [""];
|
|
562
|
+
let dirs = 0;
|
|
563
|
+
let cut = false;
|
|
564
|
+
outer: while (stack.length) {
|
|
565
|
+
if (++dirs > w.maxDirs) { cut = true; break; }
|
|
566
|
+
const rel = stack.pop();
|
|
567
|
+
let entries;
|
|
568
|
+
try { entries = fs.readdirSync(path.join(w.root, rel), { withFileTypes: true }); } catch { continue; }
|
|
569
|
+
for (const e of entries) {
|
|
570
|
+
const child = rel ? rel + "/" + e.name : e.name;
|
|
571
|
+
if (e.isDirectory()) { if (!skip.has(e.name)) stack.push(child); }
|
|
572
|
+
else if (e.isFile()) { files.push(child); if (files.length >= w.maxFiles) { cut = true; break outer; } }
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
process.stdout.write(JSON.stringify({ files, cut }));
|
|
576
|
+
`;
|
|
577
|
+
/** walk(), inside the walls when there are walls; what the rules deny is
|
|
578
|
+
* left out again here, as a second net. */
|
|
579
|
+
async function walkAny(root, ctx) {
|
|
580
|
+
if (!ctx.sandbox)
|
|
581
|
+
return walk(root);
|
|
582
|
+
const r = await runInside(ctx, `exec ${shq(process.execPath)} -e ${shq(WALK_CHILD)}`, JSON.stringify({ root, skip: [...SKIP_DIRS], maxDirs: WALK_DIRS, maxFiles: WALK_FILES }));
|
|
583
|
+
if (r.code !== 0)
|
|
584
|
+
return fail(`the folder could not be listed: ${r.err}`);
|
|
585
|
+
let got;
|
|
586
|
+
try {
|
|
587
|
+
got = JSON.parse(r.out.toString("utf8"));
|
|
588
|
+
}
|
|
589
|
+
catch {
|
|
590
|
+
return fail("the folder listing gave no readable answer");
|
|
591
|
+
}
|
|
592
|
+
return { files: got.files.filter((rel) => ctx.sandbox.canRead(path.join(root, rel))), cut: got.cut };
|
|
593
|
+
}
|
|
594
|
+
function walk(root, ctx) {
|
|
595
|
+
// Inside the walls, a folder or file the session may not read is neither
|
|
596
|
+
// entered nor listed: a search from the home folder skips ~/.ssh.
|
|
597
|
+
const hidden = ctx?.sandbox ? (rel) => !ctx.sandbox.canRead(path.join(root, rel)) : () => false;
|
|
428
598
|
const files = [];
|
|
429
599
|
const stack = [""];
|
|
430
600
|
let dirs = 0;
|
|
@@ -442,10 +612,12 @@ function walk(root) {
|
|
|
442
612
|
for (const e of entries) {
|
|
443
613
|
const child = rel ? `${rel}/${e.name}` : e.name;
|
|
444
614
|
if (e.isDirectory()) {
|
|
445
|
-
if (!SKIP_DIRS.has(e.name))
|
|
615
|
+
if (!SKIP_DIRS.has(e.name) && !hidden(child))
|
|
446
616
|
stack.push(child);
|
|
447
617
|
}
|
|
448
618
|
else if (e.isFile()) {
|
|
619
|
+
if (hidden(child))
|
|
620
|
+
continue;
|
|
449
621
|
files.push(child);
|
|
450
622
|
if (files.length >= WALK_FILES)
|
|
451
623
|
return { files, cut: true };
|
|
@@ -457,6 +629,9 @@ function walk(root) {
|
|
|
457
629
|
function searchRoot(input, ctx) {
|
|
458
630
|
const given = str(input, "path");
|
|
459
631
|
const root = given ? abs(ctx, given) : ctx.cwd;
|
|
632
|
+
const no = walled(ctx, root, false);
|
|
633
|
+
if (no)
|
|
634
|
+
return no;
|
|
460
635
|
if (!fs.existsSync(root))
|
|
461
636
|
return fail(`${root} does not exist`);
|
|
462
637
|
return { root: fs.realpathSync(root) };
|
|
@@ -494,14 +669,24 @@ const glob = {
|
|
|
494
669
|
const rest = segs.slice(fixed.length).join("/");
|
|
495
670
|
if (fixed.length) {
|
|
496
671
|
const deeper = path.join(where.root, ...fixed);
|
|
672
|
+
// The deny first, the same answer whether or not the path is there.
|
|
673
|
+
const denied = walled(ctx, deeper, false);
|
|
674
|
+
if (denied)
|
|
675
|
+
return denied;
|
|
497
676
|
if (!fs.existsSync(deeper))
|
|
498
677
|
return { text: `No files match ${pattern}` };
|
|
499
678
|
where.root = fs.realpathSync(deeper);
|
|
679
|
+
const no = walled(ctx, where.root, false);
|
|
680
|
+
if (no)
|
|
681
|
+
return no;
|
|
500
682
|
}
|
|
501
683
|
const re = { test: globMatcher(rest) };
|
|
502
684
|
// A pattern with no folder in it matches at any depth, as people expect of `*.md`.
|
|
503
685
|
const anyDepth = !pattern.includes("/");
|
|
504
|
-
const
|
|
686
|
+
const listed = await walkAny(where.root, ctx);
|
|
687
|
+
if ("text" in listed)
|
|
688
|
+
return listed;
|
|
689
|
+
const { files, cut } = listed;
|
|
505
690
|
const hits = files
|
|
506
691
|
.filter((f) => re.test(anyDepth ? path.posix.basename(f) : f))
|
|
507
692
|
.map((f) => {
|
|
@@ -531,11 +716,19 @@ const fs = process.getBuiltinModule("node:fs");
|
|
|
531
716
|
const re = new RegExp(w.pattern, w.flags);
|
|
532
717
|
const out = [];
|
|
533
718
|
let total = 0;
|
|
719
|
+
const seen = {};
|
|
534
720
|
for (const full of w.files) {
|
|
535
721
|
let buf;
|
|
536
722
|
try {
|
|
537
|
-
|
|
538
|
-
|
|
723
|
+
const fd = fs.openSync(full, "r");
|
|
724
|
+
try {
|
|
725
|
+
const st = fs.fstatSync(fd, { bigint: true });
|
|
726
|
+
if (Number(st.size) > w.maxBytes) continue;
|
|
727
|
+
seen[full] = { id: st.dev + ":" + st.ino, n: 0 };
|
|
728
|
+
buf = fs.readFileSync(fd);
|
|
729
|
+
} finally {
|
|
730
|
+
fs.closeSync(fd);
|
|
731
|
+
}
|
|
539
732
|
} catch {
|
|
540
733
|
continue;
|
|
541
734
|
}
|
|
@@ -550,11 +743,12 @@ for (const full of w.files) {
|
|
|
550
743
|
}
|
|
551
744
|
}
|
|
552
745
|
if (!inFile) continue;
|
|
746
|
+
seen[full].n = w.mode === "content" ? inFile : 1;
|
|
553
747
|
total += w.mode === "content" ? inFile : 1;
|
|
554
748
|
if (w.mode === "files_with_matches" && out.length < w.limit) out.push(full);
|
|
555
749
|
if (w.mode === "count" && out.length < w.limit) out.push(full + ":" + inFile);
|
|
556
750
|
}
|
|
557
|
-
parentPort.postMessage({ out, total });
|
|
751
|
+
parentPort.postMessage({ out, total, seen });
|
|
558
752
|
`;
|
|
559
753
|
/** Run MATCH_WORKER over `job.files`; end it at `ms` or when `signal` fires. */
|
|
560
754
|
export function matchInWorker(job, signal, ms) {
|
|
@@ -580,6 +774,26 @@ export function matchInWorker(job, signal, ms) {
|
|
|
580
774
|
worker.once("exit", () => finish({ error: "the search ended without an answer" }));
|
|
581
775
|
});
|
|
582
776
|
}
|
|
777
|
+
/** MATCH_WORKER as a node program inside the walls: the job on stdin, the
|
|
778
|
+
* answer on stdout. The OS, not this process, decides what it may read. */
|
|
779
|
+
const MATCH_CHILD = MATCH_WORKER.replace(`const { parentPort, workerData: w } = process.getBuiltinModule("node:worker_threads");`, `const w = JSON.parse(process.getBuiltinModule("node:fs").readFileSync(0, "utf8"));\nconst parentPort = { postMessage: (m) => process.stdout.write(JSON.stringify(m)) };`);
|
|
780
|
+
async function matchInside(job, ctx, ms) {
|
|
781
|
+
if (ctx.signal.aborted)
|
|
782
|
+
return { stopped: true };
|
|
783
|
+
const r = await runInside(ctx, `exec ${shq(process.execPath)} -e ${shq(MATCH_CHILD)}`, JSON.stringify(job), ms);
|
|
784
|
+
if (r.err === "stopped")
|
|
785
|
+
return { stopped: true };
|
|
786
|
+
if (r.code === null && /ran past/.test(r.err))
|
|
787
|
+
return { timedOut: true };
|
|
788
|
+
if (r.code !== 0)
|
|
789
|
+
return { error: r.err || "the search ended without an answer" };
|
|
790
|
+
try {
|
|
791
|
+
return JSON.parse(r.out.toString("utf8"));
|
|
792
|
+
}
|
|
793
|
+
catch {
|
|
794
|
+
return { error: "the search gave no readable answer" };
|
|
795
|
+
}
|
|
796
|
+
}
|
|
583
797
|
const grep = {
|
|
584
798
|
name: "Grep",
|
|
585
799
|
description: "Search file contents with a regular expression. output_mode: `files_with_matches` (default) lists files, " +
|
|
@@ -621,7 +835,10 @@ const grep = {
|
|
|
621
835
|
const filterRe = filter ? { test: globMatcher(filter.replace(/^\.\//, "")) } : null;
|
|
622
836
|
const filterAnyDepth = filter ? !filter.includes("/") : false;
|
|
623
837
|
const single = fs.statSync(where.root).isFile();
|
|
624
|
-
const
|
|
838
|
+
const listed = single ? { files: [""], cut: false } : await walkAny(where.root, ctx);
|
|
839
|
+
if ("text" in listed)
|
|
840
|
+
return listed;
|
|
841
|
+
const { files, cut } = listed;
|
|
625
842
|
const chosen = [];
|
|
626
843
|
for (const rel of files.sort()) {
|
|
627
844
|
const full = single ? where.root : path.join(where.root, rel);
|
|
@@ -631,14 +848,37 @@ const grep = {
|
|
|
631
848
|
continue;
|
|
632
849
|
chosen.push(full);
|
|
633
850
|
}
|
|
634
|
-
const
|
|
851
|
+
const job = { pattern, flags: re.flags, files: chosen, mode, limit, maxBytes: SEARCH_FILE_BYTES };
|
|
852
|
+
const found = ctx.sandbox ? await matchInside(job, ctx, GREP_MS) : await matchInWorker(job, ctx.signal, GREP_MS);
|
|
635
853
|
if ("stopped" in found)
|
|
636
854
|
return fail("the search was stopped");
|
|
637
855
|
if ("timedOut" in found)
|
|
638
856
|
return fail(`the search ran past ${GREP_MS / 1000} s and was ended: the pattern is too costly for this text. Use a simpler pattern or a narrower path or glob.`);
|
|
639
857
|
if ("error" in found)
|
|
640
858
|
return fail(`the search failed: ${found.error}`);
|
|
641
|
-
|
|
859
|
+
let { out, total } = found;
|
|
860
|
+
// Inside the walls the search ran there, so the OS held its reads; as a
|
|
861
|
+
// second net, a file now at a path the rules deny (or swapped since it
|
|
862
|
+
// was read) is left out of the answer, its count too.
|
|
863
|
+
if (ctx.sandbox && found.seen) {
|
|
864
|
+
const bad = new Set();
|
|
865
|
+
for (const [full, { id }] of Object.entries(found.seen)) {
|
|
866
|
+
try {
|
|
867
|
+
const real = fs.realpathSync.native(full);
|
|
868
|
+
const st = fs.statSync(real, { bigint: true });
|
|
869
|
+
if (`${st.dev}:${st.ino}` !== id || !ctx.sandbox.canRead(real))
|
|
870
|
+
bad.add(full);
|
|
871
|
+
}
|
|
872
|
+
catch {
|
|
873
|
+
bad.add(full);
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
if (bad.size) {
|
|
877
|
+
// Neither its lines nor its count: the total is over accepted files.
|
|
878
|
+
out = out.filter((line) => ![...bad].some((b) => line === b || line.startsWith(`${b}:`)));
|
|
879
|
+
total = Object.entries(found.seen).reduce((sum, [full, f]) => sum + (bad.has(full) ? 0 : f.n), 0);
|
|
880
|
+
}
|
|
881
|
+
}
|
|
642
882
|
if (!out.length)
|
|
643
883
|
return { text: `No matches for ${pattern}${cut ? ` (search stopped at ${WALK_FILES} files)` : ""}` };
|
|
644
884
|
const more = total > out.length ? `\n\n[${total - out.length} more not shown — narrow the search or raise head_limit]` : "";
|
|
@@ -660,19 +900,35 @@ const bash = {
|
|
|
660
900
|
required: ["command"],
|
|
661
901
|
},
|
|
662
902
|
readOnly: false,
|
|
663
|
-
run(input, ctx) {
|
|
903
|
+
async run(input, ctx) {
|
|
664
904
|
const command = str(input, "command");
|
|
665
905
|
if (!command)
|
|
666
|
-
return
|
|
906
|
+
return fail("Bash needs command");
|
|
667
907
|
const ms = Math.max(1000, Math.min(BASH_MAX_MS, Number.isInteger(input.timeout) ? input.timeout : BASH_DEFAULT_MS));
|
|
908
|
+
// Inside the walls on a person's machine: the line that runs is the
|
|
909
|
+
// sandbox's wrapping of it. One that cannot be wrapped does not run.
|
|
910
|
+
let line = command;
|
|
911
|
+
let env = ctx.env;
|
|
912
|
+
if (ctx.sandbox) {
|
|
913
|
+
try {
|
|
914
|
+
// The launcher starts with the walls' own few variables; the
|
|
915
|
+
// command's environment is set again inside.
|
|
916
|
+
({ line, env } = await ctx.sandbox.launch(command, ctx.env));
|
|
917
|
+
}
|
|
918
|
+
catch (err) {
|
|
919
|
+
return fail(`the command was not run: the sandbox could not wrap it (${err instanceof Error ? err.message : String(err)})`);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
668
922
|
return new Promise((resolve) => {
|
|
669
923
|
if (ctx.signal.aborted)
|
|
670
924
|
return resolve(fail("the step was stopped before the command ran"));
|
|
671
925
|
// Its own process group, so a stop or a timeout ends what it started
|
|
672
926
|
// too — a test runner's children, a server it left in the background.
|
|
673
|
-
|
|
927
|
+
// Inside the walls the walls are put up by a fixed program, from an
|
|
928
|
+
// environment no command could have shaped.
|
|
929
|
+
const child = spawn(ctx.sandbox ? LAUNCHER : "bash", ["-c", line], {
|
|
674
930
|
cwd: ctx.cwd,
|
|
675
|
-
env:
|
|
931
|
+
env: env,
|
|
676
932
|
detached: true,
|
|
677
933
|
stdio: ["ignore", "pipe", "pipe"],
|
|
678
934
|
});
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/** Where a person's credentials live: never readable from inside. Paths
|
|
2
|
+
* under the home folder are written `~/…`, as the runtime expects. */
|
|
3
|
+
export declare const DENY_READ: readonly string[];
|
|
4
|
+
/** The shell the walls are put up from: a fixed program, never a `bash`
|
|
5
|
+
* found on a PATH the project could have changed. */
|
|
6
|
+
export declare const LAUNCHER: string;
|
|
7
|
+
export type SandboxBackend = "seatbelt" | "bubblewrap";
|
|
8
|
+
export interface LocalSandboxPolicy {
|
|
9
|
+
/** The project folder: readable and writable. */
|
|
10
|
+
cwd: string;
|
|
11
|
+
/** More paths a command may not read, beside DENY_READ. */
|
|
12
|
+
denyRead?: string[];
|
|
13
|
+
/** Sites a command may reach (`api.example.com`, `*.example.com`). */
|
|
14
|
+
sites: string[];
|
|
15
|
+
}
|
|
16
|
+
export interface LocalSandbox {
|
|
17
|
+
backend: SandboxBackend;
|
|
18
|
+
/** The private temp folder: a command's TMPDIR. */
|
|
19
|
+
tmp: string;
|
|
20
|
+
/** How to run `command` inside the walls with `env` as its environment:
|
|
21
|
+
* start LAUNCHER with `-c line` and exactly `env` (the launcher's own).
|
|
22
|
+
* Refuses once this handle is closed. */
|
|
23
|
+
launch(command: string, env: Record<string, string | undefined>): Promise<{
|
|
24
|
+
line: string;
|
|
25
|
+
env: Record<string, string>;
|
|
26
|
+
token: string;
|
|
27
|
+
}>;
|
|
28
|
+
/** Whether a process launched with `token` runs under the protections as
|
|
29
|
+
* they are now: found again, compared. */
|
|
30
|
+
fresh(token: string): boolean;
|
|
31
|
+
/** Told the new token whenever a launch finds the protections changed. */
|
|
32
|
+
onChange(listener: (token: string) => void | Promise<void>): () => void;
|
|
33
|
+
/** Whether the engine's own file tools may read / write this path (false
|
|
34
|
+
* for everything once this handle is closed). */
|
|
35
|
+
canRead(file: string): boolean;
|
|
36
|
+
canWrite(file: string): boolean;
|
|
37
|
+
/** For the session's record and the CLI. */
|
|
38
|
+
describe(): string;
|
|
39
|
+
/** Give this handle back; the walls come down when the last one is. */
|
|
40
|
+
close(): Promise<void>;
|
|
41
|
+
}
|
|
42
|
+
export interface SandboxRefusal {
|
|
43
|
+
refused: string;
|
|
44
|
+
/** What the person can do about it, when there is something. */
|
|
45
|
+
hint?: string;
|
|
46
|
+
}
|
|
47
|
+
export declare const isRefusal: (x: LocalSandbox | SandboxRefusal) => x is SandboxRefusal;
|
|
48
|
+
/** A path as the file system names it — links followed, and in its own
|
|
49
|
+
* case (realpathSync.native: on a case-insensitive Mac volume the plain
|
|
50
|
+
* realpath keeps whatever case it was given, so `~/.SSH` would not look
|
|
51
|
+
* like `~/.ssh`). A file that does not exist yet is judged by where it
|
|
52
|
+
* would land: its nearest existing parent, resolved, joined with the rest. */
|
|
53
|
+
export declare function realish(p: string): string;
|
|
54
|
+
/** `PATH` with every entry a command could have written removed (and every
|
|
55
|
+
* relative one): what the launcher may look programs up in. */
|
|
56
|
+
export declare function trustedPath(pathVar: string | undefined, writable: string[], platform?: NodeJS.Platform): string;
|
|
57
|
+
/** Every link met on the way to `file`, resolved one component at a time
|
|
58
|
+
* (folders on the way too), and where it lands: each one a place a change
|
|
59
|
+
* could redirect it. A dangling end is where it would land. */
|
|
60
|
+
export declare function linkHops(file: string): string[];
|
|
61
|
+
/** Whether every step on the way to `file` — each folder, each link and
|
|
62
|
+
* where it points, resolved one component at a time — lies outside the
|
|
63
|
+
* folders a command may write: any of them inside could be changed later. */
|
|
64
|
+
export declare function chainOutside(file: string, roots: string[], platform?: NodeJS.Platform): boolean;
|
|
65
|
+
/**
|
|
66
|
+
* A folder only this process writes, holding a link to the real file of
|
|
67
|
+
* each helper the person's PATH would run (first found, as exec finds it):
|
|
68
|
+
* while the walls are up it is this process's whole PATH, so no lookup by
|
|
69
|
+
* name ever sees a folder, a link or a file a command could change. A
|
|
70
|
+
* helper whose real file lies in such a folder is a refusal.
|
|
71
|
+
*/
|
|
72
|
+
export declare function helperFolder(pathVar: string | undefined, roots: string[], platform?: NodeJS.Platform): {
|
|
73
|
+
dir: string;
|
|
74
|
+
} | {
|
|
75
|
+
refused: string;
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* The git paths that run code on a later git command: the hooks (or the
|
|
79
|
+
* folder core.hooksPath names) and every config file git reads (config,
|
|
80
|
+
* config.worktree, included files) of the repository the project is in and
|
|
81
|
+
* of every repository nested below it. Asked of git on the host, with a git
|
|
82
|
+
* found on a trusted PATH. A question git cannot answer, a repository with
|
|
83
|
+
* no git to ask, or a project too large to search, is an error, never an
|
|
84
|
+
* empty answer: a hooks folder dropped by a failed lookup would be writable.
|
|
85
|
+
*/
|
|
86
|
+
export declare function gitProtected(cwd: string, pathVar?: string, hostEnv?: NodeJS.ProcessEnv, writeRoots?: string[]): string[];
|
|
87
|
+
/** A shell line's words, as the shell reads them: quotes and backslash
|
|
88
|
+
* escapes taken, `$NAME` / `${NAME}` taken from `env` outside single
|
|
89
|
+
* quotes, split at blanks and the shell's operators. */
|
|
90
|
+
export declare function shellWords(t: string, env?: Record<string, string | undefined>): string[];
|
|
91
|
+
/** The transport a remote setting makes git run git-remote-<it> for, or
|
|
92
|
+
* null: `remote.<n>.vcs`, a `<transport>::address` URL, a scheme git does
|
|
93
|
+
* not speak itself, and the same in a `url.<base>.insteadOf` base. */
|
|
94
|
+
export declare function remoteHelper(key: string, value: string): string | null;
|
|
95
|
+
/** The in-process half of the policy: what the file tools may touch. Pure
|
|
96
|
+
* but for the paths it is given, so it is tested without a sandbox. */
|
|
97
|
+
export declare function fileRules(policy: LocalSandboxPolicy, tmp: string, protectedWrites?: string[], platform?: NodeJS.Platform): {
|
|
98
|
+
canRead: (file: string) => boolean;
|
|
99
|
+
canWrite: (file: string) => boolean;
|
|
100
|
+
};
|
|
101
|
+
/** Ubuntu 24.04+ restricts unprivileged user namespaces through AppArmor,
|
|
102
|
+
* and bubblewrap then cannot start. */
|
|
103
|
+
export declare function appArmorRestrictsUserns(read?: (f: string) => string): boolean;
|
|
104
|
+
/** The fix for that block. Never "turn the restriction off". */
|
|
105
|
+
export declare const APPARMOR_HINT: string;
|
|
106
|
+
/** End a process and every process below it (SIGKILL), found from the
|
|
107
|
+
* process table: a server's children do not outlive it. */
|
|
108
|
+
export declare function killTree(pid: number): void;
|
|
109
|
+
/** One word for a shell, single-quoted. */
|
|
110
|
+
export declare const q: (s: string) => string;
|
|
111
|
+
/** The environment the probe starts from: a program needs these, and none
|
|
112
|
+
* of them is a secret. */
|
|
113
|
+
export declare function bareEnv(from?: NodeJS.ProcessEnv, extra?: Record<string, string>): Record<string, string>;
|
|
114
|
+
type Runtime = typeof import("@anthropic-ai/sandbox-runtime");
|
|
115
|
+
/**
|
|
116
|
+
* A command's environment carried past the launcher: each variable rides
|
|
117
|
+
* as FOLDRUN_IN_<name> (only names are on the line, never values) and is
|
|
118
|
+
* set again inside — PATH always, the rest where the runtime has not set
|
|
119
|
+
* its own (its proxy, its temp folder).
|
|
120
|
+
*/
|
|
121
|
+
export declare function carry(env: Record<string, string | undefined>): {
|
|
122
|
+
inner: string;
|
|
123
|
+
outer: Record<string, string>;
|
|
124
|
+
};
|
|
125
|
+
/**
|
|
126
|
+
* Start the walls for one session, or say why they cannot be had. The
|
|
127
|
+
* runtime is one per process: a second open with the same policy gets a
|
|
128
|
+
* handle of its own on the same walls (they come down when the last handle
|
|
129
|
+
* is closed); one with another policy is refused while they are up.
|
|
130
|
+
*/
|
|
131
|
+
export declare function openLocalSandbox(policy: LocalSandboxPolicy, opts?: {
|
|
132
|
+
platform?: NodeJS.Platform;
|
|
133
|
+
load?: () => Promise<Runtime>;
|
|
134
|
+
}): Promise<LocalSandbox | SandboxRefusal>;
|
|
135
|
+
export {};
|