"""Run one agent command in the episode workspace. The command runs as nobody when the server is root, so it cannot read the server code, the generators or the answers held in server memory. Output goes to a root-owned file so a runaway writer cannot fill server memory, and every nobody process is killed after each command so nothing lingers between steps or into grading. Network is not blocked; the sandbox is the outer boundary. """ import os import resource import signal import subprocess import tempfile import time WALL_TIMEOUT_S = 20 CPU_SECONDS = 20 MEMORY_BYTES = 2 * 1024**3 FILE_BYTES = 20 * 1024**2 MAX_PROCESSES = 256 # A safety cap only. The operator's wrapper does not cut output; the arena's token budget # ends an episode whose observation no longer fits, and that is the pressure to train under. MAX_OUTPUT_CHARS = 60000 NOBODY = 65534 IS_ROOT = os.geteuid() == 0 def _limits() -> None: resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) resource.setrlimit(resource.RLIMIT_CPU, (CPU_SECONDS, CPU_SECONDS + 1)) resource.setrlimit(resource.RLIMIT_AS, (MEMORY_BYTES, MEMORY_BYTES)) resource.setrlimit(resource.RLIMIT_FSIZE, (FILE_BYTES, FILE_BYTES)) resource.setrlimit(resource.RLIMIT_NOFILE, (256, 256)) if IS_ROOT: resource.setrlimit(resource.RLIMIT_NPROC, (MAX_PROCESSES, MAX_PROCESSES)) os.setgroups([]) os.setgid(NOBODY) os.setuid(NOBODY) def kill_nobody() -> None: """SIGKILL every process owned by nobody (no-op unless root).""" if not IS_ROOT: return for _ in range(3): found = False for pid in os.listdir("/proc"): if not pid.isdigit(): continue try: if os.stat(f"/proc/{pid}").st_uid == NOBODY: os.kill(int(pid), signal.SIGKILL) found = True except (FileNotFoundError, ProcessLookupError, PermissionError): pass if not found: return time.sleep(0.05) def give_to_nobody(path: str) -> None: if not IS_ROOT: return for dirpath, dirnames, filenames in os.walk(path): os.chown(dirpath, NOBODY, NOBODY) for name in filenames: os.chown(os.path.join(dirpath, name), NOBODY, NOBODY) def cut(text: str, limit: int = MAX_OUTPUT_CHARS) -> str: if len(text) <= limit: return text head = int(limit * 0.75) tail = limit - head return f"{text[:head]}\n...[{len(text) - limit} characters cut]...\n{text[-tail:]}" def run(argv: list[str], cwd: str, stdin_text: str | None = None) -> tuple[int, str]: """Run argv as nobody in cwd. Returns (exit code, combined output, uncut).""" env = { "PATH": "/usr/local/bin:/usr/bin:/bin", "HOME": cwd, "LANG": "C.UTF-8", "TERM": "dumb", "PYTHONDONTWRITEBYTECODE": "1", } with tempfile.TemporaryFile() as sink: proc = subprocess.Popen( argv, cwd=cwd, env=env, stdin=subprocess.PIPE if stdin_text is not None else subprocess.DEVNULL, stdout=sink, stderr=subprocess.STDOUT, preexec_fn=_limits, start_new_session=True, ) timed_out = False try: proc.communicate( input=stdin_text.encode() if stdin_text is not None else None, timeout=WALL_TIMEOUT_S, ) except subprocess.TimeoutExpired: timed_out = True finally: try: os.killpg(proc.pid, signal.SIGKILL) except ProcessLookupError: pass proc.wait() kill_nobody() sink.seek(0) raw = sink.read(4 * 1024**2) text = raw.decode("utf-8", errors="replace") code = proc.returncode if timed_out: text += f"\n[stopped: {WALL_TIMEOUT_S} s time limit]" code = 124 elif code == -signal.SIGXCPU: text += f"\n[stopped: {CPU_SECONDS} s CPU limit]" elif code == -signal.SIGXFSZ: text += "\n[stopped: file size limit (20 MB)]" return code, text def run_command(cmd: str, cwd: str) -> tuple[int, str]: code, text = run(["/bin/bash", "-c", cmd], cwd) text = text.rstrip("\n") return code, cut(text) if text else "" def write_file(path: str, content: str, cwd: str) -> tuple[int, str]: """Write content to path (relative to cwd unless absolute) as nobody, creating parents. Running as nobody is the path check: the server tree and system files are not writable.""" script = 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"' return run(["/bin/sh", "-c", script, "sh", path], cwd, stdin_text=content)