File size: 5,220 Bytes
b16b327 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | 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"
|