"""Command execution for the agent's shell tool. `bwrap` (bubblewrap): no network (protocol ยง4: no public internet), a read-only system, the toolchain bound read-only, the workspace at /work read-write, local documentation at /docs read-only, a fresh /tmp and HOME, and a clean environment. `none` runs on the host and is for harness development only; it is recorded in the run record. """ import os import shutil import subprocess SYSTEM_RO = ["/usr", "/etc"] LINKS = [("usr/lib", "/lib"), ("usr/lib64", "/lib64"), ("usr/bin", "/bin"), ("usr/sbin", "/sbin")] class Sandbox: def __init__(self, kind, workspace, toolchain_binds, path_dirs, docs=(), env=None): if kind == "bwrap" and shutil.which("bwrap") is None: raise SystemExit("sandbox bwrap requested but bubblewrap is not installed") self.kind = kind self.workspace = os.path.realpath(workspace) self.binds = toolchain_binds self.path = ":".join(path_dirs + ["/usr/bin", "/bin"]) self.docs = [(name, os.path.realpath(p)) for name, p in docs] self.env = dict(env or {}) def describe(self): return {"kind": self.kind, "network": self.kind != "bwrap", "toolchain_binds": self.binds, "docs": [{"mount": "/docs/" + n, "path": p} for n, p in self.docs]} def argv(self, command): if self.kind == "none": return ["sh", "-c", command] a = ["bwrap", "--unshare-all", "--die-with-parent", "--new-session"] for d in SYSTEM_RO: if os.path.exists(d): a += ["--ro-bind", d, d] for src, dst in LINKS: if os.path.exists("/" + src): a += ["--symlink", src, dst] a += ["--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp"] for d in self.binds: a += ["--ro-bind", d, d] if self.docs: # A tmpfs mount point, remounted read-only after the binds, keeps # /docs read-only as a whole. a += ["--tmpfs", "/docs"] for name, p in self.docs: a += ["--ro-bind", p, "/docs/" + name if name else "/docs"] a += ["--remount-ro", "/docs"] a += ["--bind", self.workspace, "/work", "--chdir", "/work", "--clearenv"] env = {"PATH": self.path, "HOME": "/tmp", "TMPDIR": "/tmp", "LANG": "C.UTF-8"} env.update(self.env) for k, v in sorted(env.items()): a += ["--setenv", k, v] return a + ["sh", "-c", command] def run(self, command, timeout, output_limit): """Runs `command`; returns (exit code or None on timeout, output, truncated).""" env = None cwd = self.workspace if self.kind == "none": env = {"PATH": self.path + ":" + os.environ.get("PATH", ""), "HOME": os.environ.get("HOME", "/tmp"), "LANG": "C.UTF-8"} env.update(self.env) try: p = subprocess.run(self.argv(command), cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout) code = p.returncode out = p.stdout except subprocess.TimeoutExpired as e: code, out = None, (e.stdout or b"") text = out.decode("utf-8", errors="replace") truncated = len(text) > output_limit if truncated: half = output_limit // 2 text = text[:half] + f"\n... [{len(text) - output_limit} characters omitted] ...\n" + text[-half:] return code, text, truncated