@foldrun/core 24.11.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.
@@ -24,6 +24,8 @@ import fs from "node:fs";
24
24
  import path from "node:path";
25
25
  import { spawn } from "node:child_process";
26
26
  import { Worker } from "node:worker_threads";
27
+ import { randomBytes } from "node:crypto";
28
+ import { LAUNCHER } from "./local-sandbox.ts";
27
29
 
28
30
  export interface ToolContext {
29
31
  /** Relative paths resolve here: the agent's directory. */
@@ -38,6 +40,78 @@ export interface ToolContext {
38
40
  * left something in the background has returned, but what it left is
39
41
  * still the step's: the loop ends every group when the step ends. */
40
42
  groups: Set<number>;
43
+ /** On a person's machine, the walls (local-sandbox.ts): commands run
44
+ * through `wrap`; the file tools refuse what canRead / canWrite refuse. */
45
+ sandbox?: import("./engine-common.ts").SandboxWalls | null;
46
+ }
47
+
48
+ /** A file's contents, read through the descriptor that was checked: inside
49
+ * the walls, the open file must be the very file now at the path the rules
50
+ * allow (same device and inode), so a path swapped between the check and
51
+ * the open is refused, not read. A string is the refusal. */
52
+ async function readChecked(ctx: ToolContext, file: string): Promise<Buffer | string> {
53
+ if (!ctx.sandbox) return fs.readFileSync(file);
54
+ // Inside the walls the read itself runs there (cat), so the OS holds it
55
+ // however the path changes between a check and the read.
56
+ const r = await runInside(ctx, `exec /bin/cat -- ${shq(file)}`, "");
57
+ if (r.code !== 0) return `${file} could not be read: ${r.err || "the sandbox refused it"}`;
58
+ return r.out;
59
+ }
60
+
61
+ /** Run a short helper inside the walls with nothing of the step's
62
+ * environment: its stdout as bytes, the last line of its stderr. */
63
+ async function runInside(ctx: ToolContext, script: string, input: string, ms = 60_000): Promise<{ code: number | null; out: Buffer; err: string }> {
64
+ // A plain PATH inside for the helper's own commands (mkdir, mv…): what
65
+ // they reach is the walls' business, not the PATH's.
66
+ const { line, env } = await ctx.sandbox!.launch(script, { PATH: "/usr/bin:/bin:/usr/sbin:/sbin" });
67
+ return new Promise((resolve) => {
68
+ const child = spawn(LAUNCHER, ["-c", line], { cwd: ctx.cwd, env: env as NodeJS.ProcessEnv, stdio: ["pipe", "pipe", "pipe"], detached: true });
69
+ const chunks: Buffer[] = [];
70
+ let err = "";
71
+ let done = false;
72
+ const end = (code: number | null, why?: string) => {
73
+ if (done) return;
74
+ done = true;
75
+ clearTimeout(timer);
76
+ ctx.signal.removeEventListener("abort", stop);
77
+ resolve({ code, out: Buffer.concat(chunks), err: why ?? (err.trim().split("\n").pop() || (code === 0 ? "" : `exit ${code}`)) });
78
+ };
79
+ const kill = () => {
80
+ try {
81
+ if (child.pid) process.kill(-child.pid, "SIGKILL");
82
+ } catch {
83
+ /* gone */
84
+ }
85
+ };
86
+ const stop = () => {
87
+ kill();
88
+ end(null, "stopped");
89
+ };
90
+ const timer = setTimeout(() => {
91
+ kill();
92
+ end(null, `ran past ${ms / 1000} s`);
93
+ }, ms);
94
+ ctx.signal.addEventListener("abort", stop, { once: true });
95
+ child.stdout!.on("data", (c: Buffer) => chunks.push(c));
96
+ child.stderr!.on("data", (c: Buffer) => {
97
+ if (err.length < 4000) err += c.toString("utf8");
98
+ });
99
+ child.on("error", (e) => end(null, e.message));
100
+ child.on("close", (code) => end(code));
101
+ child.stdin!.on("error", () => undefined);
102
+ child.stdin!.end(input, "utf8");
103
+ });
104
+ }
105
+
106
+ /** The sandbox's answer for a path, as a tool's refusal — null when allowed. */
107
+ function walled(ctx: ToolContext, file: string, write: boolean): ToolOutcome | null {
108
+ if (!ctx.sandbox) return null;
109
+ if (write ? ctx.sandbox.canWrite(file) : ctx.sandbox.canRead(file)) return null;
110
+ return fail(
111
+ write
112
+ ? `${file} is outside what this session may write (the project folder and its temp folder; never git hooks or config, never credentials)`
113
+ : `${file} holds credentials this session may not read`,
114
+ );
41
115
  }
42
116
 
43
117
  /** End everything the session's commands started and left running. */
@@ -125,6 +199,28 @@ function looksBinary(buf: Buffer): boolean {
125
199
  return buf.subarray(0, 8192).includes(0);
126
200
  }
127
201
 
202
+ /** Write a file inside the walls: a small shell helper run there makes the
203
+ * folders, writes a temp file and renames it into place, so the OS holds
204
+ * the write wherever a path has been swapped meanwhile. */
205
+ async function writeInside(file: string, content: string, ctx: ToolContext): Promise<void> {
206
+ // Folders, a temp file and the rename all happen inside the walls.
207
+ let mode = "";
208
+ try {
209
+ mode = (fs.statSync(file).mode & 0o7777).toString(8);
210
+ } catch {
211
+ // a new file takes the default mode
212
+ }
213
+ const d = shq(path.dirname(file));
214
+ const script =
215
+ `mkdir -p -- ${d} && t=$(mktemp ${shq(path.join(path.dirname(file), `.${path.basename(file)}.XXXXXXXX`))}) || exit 1\n` +
216
+ `if cat > "$t"${mode ? ` && chmod ${mode} "$t"` : ""} && mv -f -- "$t" ${shq(file)}; then exit 0; fi\n` +
217
+ `rm -f -- "$t"; exit 1`;
218
+ const r = await runInside(ctx, script, content);
219
+ if (r.code !== 0) throw new Error(r.err || `the sandbox refused the write`);
220
+ }
221
+
222
+ const shq = (s: string) => `'${s.replaceAll("'", `'\\''`)}'`;
223
+
128
224
  function writeWhole(file: string, content: string): void {
129
225
  fs.mkdirSync(path.dirname(file), { recursive: true });
130
226
  let mode: number | undefined;
@@ -133,9 +229,11 @@ function writeWhole(file: string, content: string): void {
133
229
  } catch {
134
230
  // a new file takes the default mode
135
231
  }
136
- const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${Date.now()}.tmp`);
232
+ // A name nobody can have planted (random), created only if it is not
233
+ // there (wx): a link left at a guessable name cannot redirect the write.
234
+ const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${randomBytes(8).toString("hex")}.tmp`);
137
235
  try {
138
- fs.writeFileSync(tmp, content, mode !== undefined ? { mode } : undefined);
236
+ fs.writeFileSync(tmp, content, { flag: "wx", ...(mode !== undefined ? { mode } : {}) });
139
237
  fs.renameSync(tmp, file);
140
238
  } catch (err) {
141
239
  fs.rmSync(tmp, { force: true });
@@ -177,6 +275,8 @@ const read: EngineTool = {
177
275
  const given = str(input, "file_path");
178
276
  if (!given) return fail("Read needs file_path");
179
277
  const file = abs(ctx, given);
278
+ const no = walled(ctx, file, false);
279
+ if (no) return no;
180
280
  let stat: fs.Stats;
181
281
  try {
182
282
  stat = fs.statSync(file);
@@ -184,7 +284,8 @@ const read: EngineTool = {
184
284
  return fail(`${file} does not exist`);
185
285
  }
186
286
  if (stat.isDirectory()) return fail(`${file} is a directory — use Glob to list files`);
187
- const buf = fs.readFileSync(file);
287
+ const buf = await readChecked(ctx, file);
288
+ if (typeof buf === "string") return fail(buf);
188
289
  if (looksBinary(buf)) return fail(`${file} is not a text file`);
189
290
  ctx.reads.set(file, stat.mtimeMs);
190
291
  const text = buf.toString("utf8");
@@ -223,6 +324,8 @@ const write: EngineTool = {
223
324
  const content = str(input, "content");
224
325
  if (!given || content === null) return fail("Write needs file_path and content");
225
326
  const file = abs(ctx, given);
327
+ const no = walled(ctx, file, true);
328
+ if (no) return no;
226
329
  try {
227
330
  if (fs.statSync(file).isDirectory()) return fail(`${file} is a directory`);
228
331
  } catch {
@@ -231,7 +334,12 @@ const write: EngineTool = {
231
334
  const stale = staleReason(ctx, file);
232
335
  if (stale) return fail(stale);
233
336
  const existed = fs.existsSync(file);
234
- writeWhole(file, content);
337
+ try {
338
+ if (ctx.sandbox) await writeInside(file, content, ctx);
339
+ else writeWhole(file, content);
340
+ } catch (err) {
341
+ return fail(`${file} was not written: ${err instanceof Error ? err.message : String(err)}`);
342
+ }
235
343
  ctx.reads.set(file, fs.statSync(file).mtimeMs);
236
344
  return { text: `${existed ? "Wrote" : "Created"} ${file} (${content.length} characters)` };
237
345
  },
@@ -268,13 +376,16 @@ const edit: EngineTool = {
268
376
  const to = str(input, "new_string");
269
377
  if (!given || from === null || to === null) return fail("Edit needs file_path, old_string and new_string");
270
378
  const file = abs(ctx, given);
379
+ const no = walled(ctx, file, true);
380
+ if (no) return no;
271
381
  if (!fs.existsSync(file)) return fail(`${file} does not exist — use Write to create it`);
272
382
  if (fs.statSync(file).isDirectory()) return fail(`${file} is a directory`);
273
383
  const stale = staleReason(ctx, file);
274
384
  if (stale) return fail(stale);
275
385
  if (!from) return fail("old_string is empty — give the exact text to replace, or use Write for a whole file");
276
386
  if (from === to) return fail("old_string and new_string are the same — nothing to change");
277
- const buf = fs.readFileSync(file);
387
+ const buf = await readChecked(ctx, file);
388
+ if (typeof buf === "string") return fail(buf);
278
389
  if (looksBinary(buf)) return fail(`${file} is not a text file`);
279
390
  const before = buf.toString("utf8");
280
391
  const count = occurrences(before, from);
@@ -291,7 +402,12 @@ const edit: EngineTool = {
291
402
  // split/join and slice, never String.replace: `$&` in new_string is text.
292
403
  const at = before.indexOf(from);
293
404
  const after = all ? before.split(from).join(to) : before.slice(0, at) + to + before.slice(at + from.length);
294
- writeWhole(file, after);
405
+ try {
406
+ if (ctx.sandbox) await writeInside(file, after, ctx);
407
+ else writeWhole(file, after);
408
+ } catch (err) {
409
+ return fail(`${file} was not changed: ${err instanceof Error ? err.message : String(err)}`);
410
+ }
295
411
  ctx.reads.set(file, fs.statSync(file).mtimeMs);
296
412
  return { text: `Edited ${file} (${all ? count : 1} replacement${(all ? count : 1) === 1 ? "" : "s"})` };
297
413
  },
@@ -422,7 +538,50 @@ export function globProblem(glob: string): string | null {
422
538
  }
423
539
 
424
540
  /** Every file under `root`, as paths relative to it. Bounded. */
425
- function walk(root: string): { files: string[]; cut: boolean } {
541
+ // The listing half of Glob and Grep, as a node program inside the walls:
542
+ // there the OS, not a check made before, decides which folders it may list.
543
+ const WALK_CHILD = `
544
+ const fs = process.getBuiltinModule("node:fs");
545
+ const path = process.getBuiltinModule("node:path");
546
+ const w = JSON.parse(fs.readFileSync(0, "utf8"));
547
+ const skip = new Set(w.skip);
548
+ const files = [];
549
+ const stack = [""];
550
+ let dirs = 0;
551
+ let cut = false;
552
+ outer: while (stack.length) {
553
+ if (++dirs > w.maxDirs) { cut = true; break; }
554
+ const rel = stack.pop();
555
+ let entries;
556
+ try { entries = fs.readdirSync(path.join(w.root, rel), { withFileTypes: true }); } catch { continue; }
557
+ for (const e of entries) {
558
+ const child = rel ? rel + "/" + e.name : e.name;
559
+ if (e.isDirectory()) { if (!skip.has(e.name)) stack.push(child); }
560
+ else if (e.isFile()) { files.push(child); if (files.length >= w.maxFiles) { cut = true; break outer; } }
561
+ }
562
+ }
563
+ process.stdout.write(JSON.stringify({ files, cut }));
564
+ `;
565
+
566
+ /** walk(), inside the walls when there are walls; what the rules deny is
567
+ * left out again here, as a second net. */
568
+ async function walkAny(root: string, ctx: ToolContext): Promise<{ files: string[]; cut: boolean } | ToolOutcome> {
569
+ if (!ctx.sandbox) return walk(root);
570
+ 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 }));
571
+ if (r.code !== 0) return fail(`the folder could not be listed: ${r.err}`);
572
+ let got: { files: string[]; cut: boolean };
573
+ try {
574
+ got = JSON.parse(r.out.toString("utf8")) as { files: string[]; cut: boolean };
575
+ } catch {
576
+ return fail("the folder listing gave no readable answer");
577
+ }
578
+ return { files: got.files.filter((rel) => ctx.sandbox!.canRead(path.join(root, rel))), cut: got.cut };
579
+ }
580
+
581
+ function walk(root: string, ctx?: ToolContext): { files: string[]; cut: boolean } {
582
+ // Inside the walls, a folder or file the session may not read is neither
583
+ // entered nor listed: a search from the home folder skips ~/.ssh.
584
+ const hidden = ctx?.sandbox ? (rel: string) => !ctx.sandbox!.canRead(path.join(root, rel)) : () => false;
426
585
  const files: string[] = [];
427
586
  const stack = [""];
428
587
  let dirs = 0;
@@ -438,8 +597,9 @@ function walk(root: string): { files: string[]; cut: boolean } {
438
597
  for (const e of entries) {
439
598
  const child = rel ? `${rel}/${e.name}` : e.name;
440
599
  if (e.isDirectory()) {
441
- if (!SKIP_DIRS.has(e.name)) stack.push(child);
600
+ if (!SKIP_DIRS.has(e.name) && !hidden(child)) stack.push(child);
442
601
  } else if (e.isFile()) {
602
+ if (hidden(child)) continue;
443
603
  files.push(child);
444
604
  if (files.length >= WALK_FILES) return { files, cut: true };
445
605
  }
@@ -451,6 +611,8 @@ function walk(root: string): { files: string[]; cut: boolean } {
451
611
  function searchRoot(input: Record<string, unknown>, ctx: ToolContext): { root: string } | ToolOutcome {
452
612
  const given = str(input, "path");
453
613
  const root = given ? abs(ctx, given) : ctx.cwd;
614
+ const no = walled(ctx, root, false);
615
+ if (no) return no;
454
616
  if (!fs.existsSync(root)) return fail(`${root} does not exist`);
455
617
  return { root: fs.realpathSync(root) };
456
618
  }
@@ -486,13 +648,20 @@ const glob: EngineTool = {
486
648
  const rest = segs.slice(fixed.length).join("/");
487
649
  if (fixed.length) {
488
650
  const deeper = path.join(where.root, ...fixed);
651
+ // The deny first, the same answer whether or not the path is there.
652
+ const denied = walled(ctx, deeper, false);
653
+ if (denied) return denied;
489
654
  if (!fs.existsSync(deeper)) return { text: `No files match ${pattern}` };
490
655
  where.root = fs.realpathSync(deeper);
656
+ const no = walled(ctx, where.root, false);
657
+ if (no) return no;
491
658
  }
492
659
  const re = { test: globMatcher(rest) };
493
660
  // A pattern with no folder in it matches at any depth, as people expect of `*.md`.
494
661
  const anyDepth = !pattern.includes("/");
495
- const { files, cut } = walk(where.root);
662
+ const listed = await walkAny(where.root, ctx);
663
+ if ("text" in listed) return listed;
664
+ const { files, cut } = listed;
496
665
  const hits = files
497
666
  .filter((f) => re.test(anyDepth ? path.posix.basename(f) : f))
498
667
  .map((f) => {
@@ -521,11 +690,19 @@ const fs = process.getBuiltinModule("node:fs");
521
690
  const re = new RegExp(w.pattern, w.flags);
522
691
  const out = [];
523
692
  let total = 0;
693
+ const seen = {};
524
694
  for (const full of w.files) {
525
695
  let buf;
526
696
  try {
527
- if (fs.statSync(full).size > w.maxBytes) continue;
528
- buf = fs.readFileSync(full);
697
+ const fd = fs.openSync(full, "r");
698
+ try {
699
+ const st = fs.fstatSync(fd, { bigint: true });
700
+ if (Number(st.size) > w.maxBytes) continue;
701
+ seen[full] = { id: st.dev + ":" + st.ino, n: 0 };
702
+ buf = fs.readFileSync(fd);
703
+ } finally {
704
+ fs.closeSync(fd);
705
+ }
529
706
  } catch {
530
707
  continue;
531
708
  }
@@ -540,15 +717,16 @@ for (const full of w.files) {
540
717
  }
541
718
  }
542
719
  if (!inFile) continue;
720
+ seen[full].n = w.mode === "content" ? inFile : 1;
543
721
  total += w.mode === "content" ? inFile : 1;
544
722
  if (w.mode === "files_with_matches" && out.length < w.limit) out.push(full);
545
723
  if (w.mode === "count" && out.length < w.limit) out.push(full + ":" + inFile);
546
724
  }
547
- parentPort.postMessage({ out, total });
725
+ parentPort.postMessage({ out, total, seen });
548
726
  `;
549
727
 
550
728
  type MatchJob = { pattern: string; flags: string; files: string[]; mode: string; limit: number; maxBytes: number };
551
- type MatchResult = { out: string[]; total: number } | { timedOut: true } | { stopped: true } | { error: string };
729
+ type MatchResult = { out: string[]; total: number; seen?: Record<string, { id: string; n: number }> } | { timedOut: true } | { stopped: true } | { error: string };
552
730
 
553
731
  /** Run MATCH_WORKER over `job.files`; end it at `ms` or when `signal` fires. */
554
732
  export function matchInWorker(job: MatchJob, signal: AbortSignal, ms: number): Promise<MatchResult> {
@@ -567,12 +745,32 @@ export function matchInWorker(job: MatchJob, signal: AbortSignal, ms: number): P
567
745
  const onAbort = () => finish({ stopped: true });
568
746
  const timer = setTimeout(() => finish({ timedOut: true }), ms);
569
747
  signal.addEventListener("abort", onAbort, { once: true });
570
- worker.once("message", (m: { out: string[]; total: number }) => finish(m));
748
+ worker.once("message", (m: { out: string[]; total: number; seen?: Record<string, { id: string; n: number }> }) => finish(m));
571
749
  worker.once("error", (err: unknown) => finish({ error: err instanceof Error ? err.message : String(err) }));
572
750
  worker.once("exit", () => finish({ error: "the search ended without an answer" }));
573
751
  });
574
752
  }
575
753
 
754
+ /** MATCH_WORKER as a node program inside the walls: the job on stdin, the
755
+ * answer on stdout. The OS, not this process, decides what it may read. */
756
+ const MATCH_CHILD = MATCH_WORKER.replace(
757
+ `const { parentPort, workerData: w } = process.getBuiltinModule("node:worker_threads");`,
758
+ `const w = JSON.parse(process.getBuiltinModule("node:fs").readFileSync(0, "utf8"));\nconst parentPort = { postMessage: (m) => process.stdout.write(JSON.stringify(m)) };`,
759
+ );
760
+
761
+ async function matchInside(job: MatchJob, ctx: ToolContext, ms: number): Promise<MatchResult> {
762
+ if (ctx.signal.aborted) return { stopped: true };
763
+ const r = await runInside(ctx, `exec ${shq(process.execPath)} -e ${shq(MATCH_CHILD)}`, JSON.stringify(job), ms);
764
+ if (r.err === "stopped") return { stopped: true };
765
+ if (r.code === null && /ran past/.test(r.err)) return { timedOut: true };
766
+ if (r.code !== 0) return { error: r.err || "the search ended without an answer" };
767
+ try {
768
+ return JSON.parse(r.out.toString("utf8")) as MatchResult;
769
+ } catch {
770
+ return { error: "the search gave no readable answer" };
771
+ }
772
+ }
773
+
576
774
  const grep: EngineTool = {
577
775
  name: "Grep",
578
776
  description:
@@ -611,7 +809,9 @@ const grep: EngineTool = {
611
809
  const filterRe = filter ? { test: globMatcher(filter.replace(/^\.\//, "")) } : null;
612
810
  const filterAnyDepth = filter ? !filter.includes("/") : false;
613
811
  const single = fs.statSync(where.root).isFile();
614
- const { files, cut } = single ? { files: [""], cut: false } : walk(where.root);
812
+ const listed = single ? { files: [""], cut: false } : await walkAny(where.root, ctx);
813
+ if ("text" in listed) return listed;
814
+ const { files, cut } = listed;
615
815
  const chosen: string[] = [];
616
816
  for (const rel of files.sort()) {
617
817
  const full = single ? where.root : path.join(where.root, rel);
@@ -620,16 +820,33 @@ const grep: EngineTool = {
620
820
  if (filterRe && !filterRe.test(single || filterAnyDepth ? path.basename(full) : rel)) continue;
621
821
  chosen.push(full);
622
822
  }
623
- const found = await matchInWorker(
624
- { pattern, flags: re.flags, files: chosen, mode, limit, maxBytes: SEARCH_FILE_BYTES },
625
- ctx.signal,
626
- GREP_MS,
627
- );
823
+ const job = { pattern, flags: re.flags, files: chosen, mode, limit, maxBytes: SEARCH_FILE_BYTES };
824
+ const found = ctx.sandbox ? await matchInside(job, ctx, GREP_MS) : await matchInWorker(job, ctx.signal, GREP_MS);
628
825
  if ("stopped" in found) return fail("the search was stopped");
629
826
  if ("timedOut" in found)
630
827
  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.`);
631
828
  if ("error" in found) return fail(`the search failed: ${found.error}`);
632
- const { out, total } = found;
829
+ let { out, total } = found;
830
+ // Inside the walls the search ran there, so the OS held its reads; as a
831
+ // second net, a file now at a path the rules deny (or swapped since it
832
+ // was read) is left out of the answer, its count too.
833
+ if (ctx.sandbox && found.seen) {
834
+ const bad = new Set<string>();
835
+ for (const [full, { id }] of Object.entries(found.seen)) {
836
+ try {
837
+ const real = fs.realpathSync.native(full);
838
+ const st = fs.statSync(real, { bigint: true });
839
+ if (`${st.dev}:${st.ino}` !== id || !ctx.sandbox.canRead(real)) bad.add(full);
840
+ } catch {
841
+ bad.add(full);
842
+ }
843
+ }
844
+ if (bad.size) {
845
+ // Neither its lines nor its count: the total is over accepted files.
846
+ out = out.filter((line) => ![...bad].some((b) => line === b || line.startsWith(`${b}:`)));
847
+ total = Object.entries(found.seen).reduce((sum, [full, f]) => sum + (bad.has(full) ? 0 : f.n), 0);
848
+ }
849
+ }
633
850
  if (!out.length) return { text: `No matches for ${pattern}${cut ? ` (search stopped at ${WALK_FILES} files)` : ""}` };
634
851
  const more = total > out.length ? `\n\n[${total - out.length} more not shown — narrow the search or raise head_limit]` : "";
635
852
  return { text: capped(out.join("\n")) + more };
@@ -652,17 +869,32 @@ const bash: EngineTool = {
652
869
  required: ["command"],
653
870
  },
654
871
  readOnly: false,
655
- run(input, ctx) {
872
+ async run(input, ctx) {
656
873
  const command = str(input, "command");
657
- if (!command) return Promise.resolve(fail("Bash needs command"));
874
+ if (!command) return fail("Bash needs command");
658
875
  const ms = Math.max(1000, Math.min(BASH_MAX_MS, Number.isInteger(input.timeout) ? (input.timeout as number) : BASH_DEFAULT_MS));
876
+ // Inside the walls on a person's machine: the line that runs is the
877
+ // sandbox's wrapping of it. One that cannot be wrapped does not run.
878
+ let line = command;
879
+ let env: Record<string, string | undefined> = ctx.env;
880
+ if (ctx.sandbox) {
881
+ try {
882
+ // The launcher starts with the walls' own few variables; the
883
+ // command's environment is set again inside.
884
+ ({ line, env } = await ctx.sandbox.launch(command, ctx.env));
885
+ } catch (err) {
886
+ return fail(`the command was not run: the sandbox could not wrap it (${err instanceof Error ? err.message : String(err)})`);
887
+ }
888
+ }
659
889
  return new Promise<ToolOutcome>((resolve) => {
660
890
  if (ctx.signal.aborted) return resolve(fail("the step was stopped before the command ran"));
661
891
  // Its own process group, so a stop or a timeout ends what it started
662
892
  // too — a test runner's children, a server it left in the background.
663
- const child = spawn("bash", ["-c", command], {
893
+ // Inside the walls the walls are put up by a fixed program, from an
894
+ // environment no command could have shaped.
895
+ const child = spawn(ctx.sandbox ? LAUNCHER : "bash", ["-c", line], {
664
896
  cwd: ctx.cwd,
665
- env: ctx.env as NodeJS.ProcessEnv,
897
+ env: env as NodeJS.ProcessEnv,
666
898
  detached: true,
667
899
  stdio: ["ignore", "pipe", "pipe"],
668
900
  });