aafimalek2032's picture
code ca5ec3214eaa
b16b327 verified
Raw History Blame Contribute Delete
5.22 kB
from __future__ import annotations
import os
import shutil
import subprocess
import sys
import tempfile
import threading
from dataclasses import dataclass
from pathlib import Path
_IS_POSIX = os.name == "posix"
_FSIZE_LIMIT = 16 * 1024 * 1024
_TRACEBACK_TAIL_LINES = 8
_KEEP_ENV = ("PATH", "LANG") if _IS_POSIX else ("PATH", "SYSTEMROOT", "TEMP", "TMP", "LANG")
@dataclass(frozen=True)
class ExecResult:
stdout: str
stderr: str
ok: bool
timed_out: bool
def _scrubbed_env(workdir: str) -> dict[str, str]:
env = {k: os.environ[k] for k in _KEEP_ENV if k in os.environ}
env["HOME"] = workdir
if not _IS_POSIX:
env["TEMP"] = env["TMP"] = workdir
return env
def _limiter(memory_mb: int, timeout: float):
def apply() -> None:
import resource
resource.setrlimit(resource.RLIMIT_AS, (memory_mb << 20, memory_mb << 20))
cpu = max(1, int(timeout) + 1)
resource.setrlimit(resource.RLIMIT_CPU, (cpu, cpu))
resource.setrlimit(resource.RLIMIT_FSIZE, (_FSIZE_LIMIT, _FSIZE_LIMIT))
return apply
class _Capture(threading.Thread):
"""Drains a pipe while keeping only a bounded head and tail, so runaway output cannot exhaust memory."""
def __init__(self, stream, keep: int):
super().__init__(daemon=True)
self._stream = stream
self._keep = keep
self.head = bytearray()
self.tail = bytearray()
self.total = 0
def run(self) -> None:
while chunk := self._stream.read(65536):
self.total += len(chunk)
room = self._keep - len(self.head)
if room > 0:
self.head += chunk[:room]
chunk = chunk[room:]
if chunk:
self.tail += chunk
del self.tail[: max(0, len(self.tail) - self._keep)]
def text(self, max_chars: int) -> str:
dropped = self.total - len(self.head) - len(self.tail)
if dropped > 0:
head = self.head.decode("utf-8", "replace")
tail = self.tail.decode("utf-8", "replace")
return _truncate(head + f"\n[... {dropped} bytes omitted ...]\n" + tail, max_chars, head, tail)
return _truncate((self.head + self.tail).decode("utf-8", "replace"), max_chars)
def _truncate(text: str, max_chars: int, head: str | None = None, tail: str | None = None) -> str:
if head is not None and tail is not None:
if len(text) <= max_chars:
return text
keep_head = max_chars // 2
keep_tail = max_chars - keep_head
return head[:keep_head] + "\n[... output truncated ...]\n" + tail[len(tail) - keep_tail :]
if len(text) <= max_chars:
return text
keep_head = max_chars // 2
keep_tail = max_chars - keep_head
omitted = len(text) - max_chars
return text[:keep_head] + f"\n[... {omitted} chars truncated ...]\n" + text[len(text) - keep_tail :]
def _kill(proc: subprocess.Popen) -> None:
if _IS_POSIX:
import signal
try:
os.killpg(proc.pid, signal.SIGKILL)
except ProcessLookupError:
pass
else:
proc.kill()
def run_python(
code: str, timeout: float = 10.0, memory_mb: int = 2048, max_output_chars: int = 4000
) -> ExecResult:
workdir = tempfile.mkdtemp(prefix="pm_sandbox_")
try:
script = Path(workdir) / "main.py"
script.write_text(code, encoding="utf-8")
kwargs: dict = {}
if _IS_POSIX:
kwargs["start_new_session"] = True
kwargs["preexec_fn"] = _limiter(memory_mb, timeout)
proc = subprocess.Popen(
[sys.executable, "-I", "-X", "utf8", str(script)],
cwd=workdir,
env=_scrubbed_env(workdir),
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
**kwargs,
)
out = _Capture(proc.stdout, max_output_chars)
err = _Capture(proc.stderr, max_output_chars)
out.start()
err.start()
timed_out = False
try:
proc.wait(timeout=timeout)
except subprocess.TimeoutExpired:
timed_out = True
_kill(proc)
proc.wait()
if _IS_POSIX:
_kill(proc)
out.join(timeout=2)
err.join(timeout=2)
return ExecResult(
stdout=out.text(max_output_chars),
stderr=err.text(max_output_chars),
ok=proc.returncode == 0 and not timed_out,
timed_out=timed_out,
)
finally:
shutil.rmtree(workdir, ignore_errors=True)
def format_tool_output(result: ExecResult) -> str:
if result.timed_out:
body = (result.stdout.rstrip() + "\n" if result.stdout.strip() else "") + "Error: execution timed out"
elif result.ok:
body = result.stdout.rstrip()
else:
lines = result.stderr.rstrip().splitlines()
body = "\n".join(lines[-_TRACEBACK_TAIL_LINES:]) if lines else result.stdout.rstrip()
return f"```output\n{body}\n```\n"