initial commit heh
This commit is contained in:
78 files changed
+11181
No files matched your search
@@ -0,0 +1,17 @@
|
||||
"""Safe isolated code execution sandbox extension for HomeAgent."""
|
||||
|
||||
from extensions.sandbox.tools import (
|
||||
code_execute,
|
||||
sandbox_file_read,
|
||||
sandbox_file_write,
|
||||
sandbox_reset,
|
||||
sandbox_run_command,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"code_execute",
|
||||
"sandbox_run_command",
|
||||
"sandbox_file_write",
|
||||
"sandbox_file_read",
|
||||
"sandbox_reset",
|
||||
]
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Base classes and data types for the Code Sandbox extension."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExecutionResult:
|
||||
"""Result of sandbox code or command execution."""
|
||||
|
||||
stdout: str
|
||||
stderr: str
|
||||
exit_code: int
|
||||
duration_seconds: float
|
||||
timed_out: bool = False
|
||||
|
||||
@property
|
||||
def success(self) -> bool:
|
||||
return self.exit_code == 0 and not self.timed_out
|
||||
|
||||
|
||||
class BaseSandboxBackend(ABC):
|
||||
"""Abstract interface for a sandbox execution backend."""
|
||||
|
||||
@abstractmethod
|
||||
def is_available(self) -> bool:
|
||||
"""Check if this backend can be used on the current host system."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def execute(
|
||||
self,
|
||||
cmd: list[str],
|
||||
workspace_dir: Path,
|
||||
timeout: int,
|
||||
allow_network: bool = False,
|
||||
env: Optional[dict[str, str]] = None,
|
||||
) -> ExecutionResult:
|
||||
"""Execute a command inside the isolated sandbox."""
|
||||
pass
|
||||
@@ -0,0 +1,135 @@
|
||||
"""Bubblewrap (bwrap) sandbox backend providing Linux namespace isolation."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import signal
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
from extensions.sandbox.base import BaseSandboxBackend, ExecutionResult
|
||||
from homeagent.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BubblewrapBackend(BaseSandboxBackend):
|
||||
"""Executes processes inside an unprivileged Bubblewrap container namespace."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.settings = get_settings()
|
||||
self.bwrap_bin = shutil.which("bwrap")
|
||||
|
||||
def is_available(self) -> bool:
|
||||
return bool(self.bwrap_bin and os.path.exists("/usr"))
|
||||
|
||||
async def execute(
|
||||
self,
|
||||
cmd: list[str],
|
||||
workspace_dir: Path,
|
||||
timeout: int,
|
||||
allow_network: bool = False,
|
||||
env: Optional[dict[str, str]] = None,
|
||||
) -> ExecutionResult:
|
||||
if not self.bwrap_bin:
|
||||
raise RuntimeError("bwrap executable is not installed or not in PATH.")
|
||||
|
||||
workspace_dir.mkdir(parents=True, exist_ok=True)
|
||||
mem_kb = self.settings.SANDBOX_MEMORY_LIMIT_MB * 1024
|
||||
|
||||
bwrap_args: list[str] = [
|
||||
self.bwrap_bin,
|
||||
"--ro-bind", "/usr", "/usr",
|
||||
"--proc", "/proc",
|
||||
"--dev", "/dev",
|
||||
"--tmpfs", "/tmp",
|
||||
"--bind", str(workspace_dir), "/workspace",
|
||||
"--chdir", "/workspace",
|
||||
"--die-with-parent",
|
||||
"--setenv", "PATH", "/usr/bin:/bin",
|
||||
"--setenv", "HOME", "/workspace",
|
||||
"--setenv", "LANG", "C.UTF-8",
|
||||
"--setenv", "LC_ALL", "C.UTF-8",
|
||||
"--setenv", "PYTHONIOENCODING", "utf-8",
|
||||
]
|
||||
|
||||
# Standard symlinks across modern Linux
|
||||
if os.path.exists("/lib64"):
|
||||
bwrap_args.extend(["--symlink", "usr/lib64", "/lib64"])
|
||||
if os.path.exists("/lib"):
|
||||
bwrap_args.extend(["--symlink", "usr/lib", "/lib"])
|
||||
if os.path.exists("/bin"):
|
||||
bwrap_args.extend(["--symlink", "usr/bin", "/bin"])
|
||||
if os.path.exists("/sbin"):
|
||||
bwrap_args.extend(["--symlink", "usr/bin", "/sbin"])
|
||||
|
||||
# Network isolation
|
||||
if not allow_network:
|
||||
bwrap_args.append("--unshare-all")
|
||||
else:
|
||||
bwrap_args.extend(["--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup"])
|
||||
if os.path.exists("/etc/resolv.conf"):
|
||||
bwrap_args.extend(["--ro-bind", "/etc/resolv.conf", "/etc/resolv.conf"])
|
||||
if os.path.exists("/etc/ssl"):
|
||||
bwrap_args.extend(["--ro-bind", "/etc/ssl", "/etc/ssl"])
|
||||
if os.path.exists("/etc/ca-certificates"):
|
||||
bwrap_args.extend(["--ro-bind", "/etc/ca-certificates", "/etc/ca-certificates"])
|
||||
|
||||
# Custom environment variables
|
||||
if env:
|
||||
for k, v in env.items():
|
||||
bwrap_args.extend(["--setenv", k, v])
|
||||
|
||||
# Apply memory ulimit via bash wrapper
|
||||
quoted_cmd = " ".join(f'"{c}"' if " " in c else c for c in cmd)
|
||||
wrapped_script = f"ulimit -v {mem_kb} 2>/dev/null; exec {quoted_cmd}"
|
||||
full_cmd = bwrap_args + ["bash", "-c", wrapped_script]
|
||||
|
||||
start_time = time.monotonic()
|
||||
try:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*full_cmd,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
preexec_fn=os.setsid,
|
||||
)
|
||||
|
||||
try:
|
||||
stdout_data, stderr_data = await asyncio.wait_for(
|
||||
proc.communicate(),
|
||||
timeout=float(timeout),
|
||||
)
|
||||
duration = time.monotonic() - start_time
|
||||
return ExecutionResult(
|
||||
stdout=stdout_data.decode("utf-8", errors="replace"),
|
||||
stderr=stderr_data.decode("utf-8", errors="replace"),
|
||||
exit_code=proc.returncode if proc.returncode is not None else -1,
|
||||
duration_seconds=round(duration, 3),
|
||||
timed_out=False,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
duration = time.monotonic() - start_time
|
||||
logger.warning("Sandbox process timed out after %ds, killing process group", timeout)
|
||||
try:
|
||||
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
return ExecutionResult(
|
||||
stdout="",
|
||||
stderr=f"Ошибка: превышен максимальный таймаут выполнения ({timeout} сек). Процесс принудительно остановлен.",
|
||||
exit_code=-1,
|
||||
duration_seconds=round(duration, 3),
|
||||
timed_out=True,
|
||||
)
|
||||
except Exception as e:
|
||||
duration = time.monotonic() - start_time
|
||||
logger.error("Failed to execute in Bubblewrap sandbox: %s", e)
|
||||
return ExecutionResult(
|
||||
stdout="",
|
||||
stderr=f"Bubblewrap execution error: {type(e).__name__}: {str(e)}",
|
||||
exit_code=-1,
|
||||
duration_seconds=round(duration, 3),
|
||||
timed_out=False,
|
||||
)
|
||||
@@ -0,0 +1,133 @@
|
||||
"""Docker sandbox backend providing container isolation."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
from extensions.sandbox.base import BaseSandboxBackend, ExecutionResult
|
||||
from homeagent.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DockerBackend(BaseSandboxBackend):
|
||||
"""Executes processes inside isolated Docker containers."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.settings = get_settings()
|
||||
self.docker_bin = shutil.which("docker")
|
||||
self._available: Optional[bool] = None
|
||||
|
||||
def is_available(self) -> bool:
|
||||
if self._available is not None:
|
||||
return self._available
|
||||
|
||||
if not self.docker_bin:
|
||||
self._available = False
|
||||
return False
|
||||
|
||||
try:
|
||||
# Check if Docker daemon is running and accessible
|
||||
res = subprocess.run(
|
||||
[self.docker_bin, "info"],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=3.0,
|
||||
)
|
||||
self._available = (res.returncode == 0)
|
||||
except Exception:
|
||||
self._available = False
|
||||
|
||||
return self._available
|
||||
|
||||
async def execute(
|
||||
self,
|
||||
cmd: list[str],
|
||||
workspace_dir: Path,
|
||||
timeout: int,
|
||||
allow_network: bool = False,
|
||||
env: Optional[dict[str, str]] = None,
|
||||
) -> ExecutionResult:
|
||||
if not self.is_available():
|
||||
raise RuntimeError("Docker is not available or daemon is not running.")
|
||||
|
||||
workspace_dir.mkdir(parents=True, exist_ok=True)
|
||||
mem_mb = self.settings.SANDBOX_MEMORY_LIMIT_MB
|
||||
cpus = self.settings.SANDBOX_CPU_LIMIT
|
||||
image = self.settings.SANDBOX_DOCKER_IMAGE
|
||||
|
||||
docker_args: list[str] = [
|
||||
self.docker_bin,
|
||||
"run",
|
||||
"--rm",
|
||||
"-i",
|
||||
"--read-only",
|
||||
"--tmpfs", "/tmp:rw,noexec,nosuid,size=64m",
|
||||
"--memory", f"{mem_mb}m",
|
||||
"--cpus", str(cpus),
|
||||
"-v", f"{workspace_dir}:/workspace:rw",
|
||||
"-w", "/workspace",
|
||||
]
|
||||
|
||||
if not allow_network:
|
||||
docker_args.extend(["--network", "none"])
|
||||
|
||||
if env:
|
||||
for k, v in env.items():
|
||||
docker_args.extend(["-e", f"{k}={v}"])
|
||||
|
||||
docker_args.append(image)
|
||||
docker_args.extend(cmd)
|
||||
|
||||
start_time = time.monotonic()
|
||||
try:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*docker_args,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
preexec_fn=os.setsid,
|
||||
)
|
||||
|
||||
try:
|
||||
stdout_data, stderr_data = await asyncio.wait_for(
|
||||
proc.communicate(),
|
||||
timeout=float(timeout),
|
||||
)
|
||||
duration = time.monotonic() - start_time
|
||||
return ExecutionResult(
|
||||
stdout=stdout_data.decode("utf-8", errors="replace"),
|
||||
stderr=stderr_data.decode("utf-8", errors="replace"),
|
||||
exit_code=proc.returncode if proc.returncode is not None else -1,
|
||||
duration_seconds=round(duration, 3),
|
||||
timed_out=False,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
duration = time.monotonic() - start_time
|
||||
logger.warning("Docker sandbox timed out after %ds, killing container", timeout)
|
||||
try:
|
||||
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
return ExecutionResult(
|
||||
stdout="",
|
||||
stderr=f"Ошибка: превышен максимальный таймаут выполнения ({timeout} сек).",
|
||||
exit_code=-1,
|
||||
duration_seconds=round(duration, 3),
|
||||
timed_out=True,
|
||||
)
|
||||
except Exception as e:
|
||||
duration = time.monotonic() - start_time
|
||||
logger.error("Failed to execute in Docker sandbox: %s", e)
|
||||
return ExecutionResult(
|
||||
stdout="",
|
||||
stderr=f"Docker sandbox error: {type(e).__name__}: {str(e)}",
|
||||
exit_code=-1,
|
||||
duration_seconds=round(duration, 3),
|
||||
timed_out=False,
|
||||
)
|
||||
@@ -0,0 +1,164 @@
|
||||
"""Sandbox Manager for managing workspace files and selecting the active isolation backend."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
from typing import Optional
|
||||
|
||||
from extensions.sandbox.base import BaseSandboxBackend, ExecutionResult
|
||||
from extensions.sandbox.bwrap_backend import BubblewrapBackend
|
||||
from extensions.sandbox.docker_backend import DockerBackend
|
||||
from extensions.sandbox.process_backend import ProcessBackend
|
||||
from homeagent.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SandboxManager:
|
||||
"""Manages the isolated workspace and executes code/commands via the selected sandbox backend."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.settings = get_settings()
|
||||
self.workspace_dir: Path = self.settings.DATA_DIR / "sandbox_workspace"
|
||||
self.workspace_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
self._bwrap = BubblewrapBackend()
|
||||
self._docker = DockerBackend()
|
||||
self._process = ProcessBackend()
|
||||
self._active_backend: Optional[BaseSandboxBackend] = None
|
||||
|
||||
def get_backend(self) -> BaseSandboxBackend:
|
||||
if self._active_backend is not None:
|
||||
return self._active_backend
|
||||
|
||||
choice = self.settings.SANDBOX_BACKEND.lower()
|
||||
|
||||
if choice == "bwrap":
|
||||
if self._bwrap.is_available():
|
||||
self._active_backend = self._bwrap
|
||||
logger.info("Sandbox using Bubblewrap (bwrap) backend.")
|
||||
return self._active_backend
|
||||
logger.warning("Configured backend 'bwrap' unavailable, falling back to process.")
|
||||
|
||||
elif choice == "docker":
|
||||
if self._docker.is_available():
|
||||
self._active_backend = self._docker
|
||||
logger.info("Sandbox using Docker backend.")
|
||||
return self._active_backend
|
||||
logger.warning("Configured backend 'docker' unavailable, falling back to process.")
|
||||
|
||||
elif choice == "process":
|
||||
self._active_backend = self._process
|
||||
logger.info("Sandbox using Process backend.")
|
||||
return self._active_backend
|
||||
|
||||
# Auto detection: bwrap -> docker -> process
|
||||
if self._bwrap.is_available():
|
||||
self._active_backend = self._bwrap
|
||||
logger.info("Sandbox auto-selected Bubblewrap (bwrap) backend.")
|
||||
elif self._docker.is_available():
|
||||
self._active_backend = self._docker
|
||||
logger.info("Sandbox auto-selected Docker backend.")
|
||||
else:
|
||||
self._active_backend = self._process
|
||||
logger.info("Sandbox auto-selected Process backend.")
|
||||
|
||||
return self._active_backend
|
||||
|
||||
def get_backend_name(self) -> str:
|
||||
backend = self.get_backend()
|
||||
if isinstance(backend, BubblewrapBackend):
|
||||
return "Bubblewrap (bwrap, Linux Namespaces)"
|
||||
if isinstance(backend, DockerBackend):
|
||||
return "Docker Container"
|
||||
return "Process Sandbox (Resource Limits)"
|
||||
|
||||
def _resolve_safe_path(self, filename: str) -> Path:
|
||||
"""Resolve path inside workspace and prevent directory traversal outside workspace."""
|
||||
clean_name = filename.strip().lstrip("/\\")
|
||||
target_path = (self.workspace_dir / clean_name).resolve()
|
||||
workspace_resolved = self.workspace_dir.resolve()
|
||||
|
||||
if not str(target_path).startswith(str(workspace_resolved)):
|
||||
raise ValueError(f"Access denied: path '{filename}' points outside the sandbox workspace.")
|
||||
return target_path
|
||||
|
||||
def write_file(self, filename: str, content: str) -> Path:
|
||||
"""Safely write a file to the sandbox workspace."""
|
||||
path = self._resolve_safe_path(filename)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(content, encoding="utf-8")
|
||||
return path
|
||||
|
||||
def read_file(self, filename: str, max_chars: int = 8000) -> str:
|
||||
"""Safely read a file from the sandbox workspace."""
|
||||
path = self._resolve_safe_path(filename)
|
||||
if not path.exists() or not path.is_file():
|
||||
raise FileNotFoundError(f"File '{filename}' does not exist in sandbox workspace.")
|
||||
|
||||
content = path.read_text(encoding="utf-8", errors="replace")
|
||||
if len(content) > max_chars:
|
||||
content = content[:max_chars] + f"\n\n... [Файл обрезан, показано первые {max_chars} символов]"
|
||||
return content
|
||||
|
||||
def clean_workspace(self) -> None:
|
||||
"""Remove all files inside sandbox workspace."""
|
||||
if self.workspace_dir.exists():
|
||||
for item in self.workspace_dir.iterdir():
|
||||
try:
|
||||
if item.is_dir():
|
||||
shutil.rmtree(item)
|
||||
else:
|
||||
item.unlink()
|
||||
except Exception as e:
|
||||
logger.warning("Could not delete workspace item %s: %s", item, e)
|
||||
|
||||
async def run_code(
|
||||
self,
|
||||
code: str,
|
||||
language: str = "python",
|
||||
timeout: Optional[int] = None,
|
||||
) -> ExecutionResult:
|
||||
"""Execute code in the isolated sandbox."""
|
||||
lang = language.lower().strip()
|
||||
effective_timeout = timeout or self.settings.SANDBOX_TIMEOUT_SECONDS
|
||||
backend = self.get_backend()
|
||||
|
||||
if lang in ("python", "py", "python3"):
|
||||
script_path = self.write_file("main.py", code)
|
||||
cmd = ["python3", "main.py"]
|
||||
elif lang in ("bash", "sh"):
|
||||
script_path = self.write_file("script.sh", code)
|
||||
cmd = ["bash", "script.sh"]
|
||||
elif lang in ("javascript", "js", "node"):
|
||||
script_path = self.write_file("index.js", code)
|
||||
cmd = ["node", "index.js"]
|
||||
else:
|
||||
raise ValueError(
|
||||
f"Unsupported language '{language}'. Supported languages: 'python', 'bash', 'javascript'."
|
||||
)
|
||||
|
||||
return await backend.execute(
|
||||
cmd=cmd,
|
||||
workspace_dir=self.workspace_dir,
|
||||
timeout=effective_timeout,
|
||||
allow_network=self.settings.SANDBOX_ALLOW_NETWORK,
|
||||
)
|
||||
|
||||
async def run_command(
|
||||
self,
|
||||
command: str,
|
||||
timeout: Optional[int] = None,
|
||||
) -> ExecutionResult:
|
||||
"""Execute a shell command inside the isolated sandbox."""
|
||||
effective_timeout = timeout or self.settings.SANDBOX_TIMEOUT_SECONDS
|
||||
backend = self.get_backend()
|
||||
cmd = ["bash", "-c", command]
|
||||
|
||||
return await backend.execute(
|
||||
cmd=cmd,
|
||||
workspace_dir=self.workspace_dir,
|
||||
timeout=effective_timeout,
|
||||
allow_network=self.settings.SANDBOX_ALLOW_NETWORK,
|
||||
)
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Process sandbox backend using resource limits and sanitized environment."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import signal
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
from extensions.sandbox.base import BaseSandboxBackend, ExecutionResult
|
||||
from homeagent.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ProcessBackend(BaseSandboxBackend):
|
||||
"""Fallback sandbox running subprocess with resource limits and stripped environment."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.settings = get_settings()
|
||||
|
||||
def is_available(self) -> bool:
|
||||
return True
|
||||
|
||||
async def execute(
|
||||
self,
|
||||
cmd: list[str],
|
||||
workspace_dir: Path,
|
||||
timeout: int,
|
||||
allow_network: bool = False,
|
||||
env: Optional[dict[str, str]] = None,
|
||||
) -> ExecutionResult:
|
||||
workspace_dir.mkdir(parents=True, exist_ok=True)
|
||||
mem_bytes = self.settings.SANDBOX_MEMORY_LIMIT_MB * 1024 * 1024
|
||||
|
||||
def _setup_child_limits() -> None:
|
||||
# Set new process group so we can cleanly kill all children
|
||||
os.setsid()
|
||||
try:
|
||||
# Limit virtual memory
|
||||
resource.setrlimit(resource.RLIMIT_AS, (mem_bytes, mem_bytes))
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
# Limit CPU time
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (timeout + 5, timeout + 5))
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
# Limit max open files
|
||||
resource.setrlimit(resource.RLIMIT_NOFILE, (128, 128))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Completely sanitize environment: do NOT leak host variables or secrets (.env)
|
||||
safe_env = {
|
||||
"PATH": os.environ.get("PATH", "/usr/bin:/bin"),
|
||||
"LANG": "C.UTF-8",
|
||||
"LC_ALL": "C.UTF-8",
|
||||
"HOME": str(workspace_dir),
|
||||
"TMPDIR": str(workspace_dir),
|
||||
"PYTHONIOENCODING": "utf-8",
|
||||
}
|
||||
if env:
|
||||
safe_env.update(env)
|
||||
|
||||
start_time = time.monotonic()
|
||||
try:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
cwd=str(workspace_dir),
|
||||
env=safe_env,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
preexec_fn=_setup_child_limits,
|
||||
)
|
||||
|
||||
try:
|
||||
stdout_data, stderr_data = await asyncio.wait_for(
|
||||
proc.communicate(),
|
||||
timeout=float(timeout),
|
||||
)
|
||||
duration = time.monotonic() - start_time
|
||||
return ExecutionResult(
|
||||
stdout=stdout_data.decode("utf-8", errors="replace"),
|
||||
stderr=stderr_data.decode("utf-8", errors="replace"),
|
||||
exit_code=proc.returncode if proc.returncode is not None else -1,
|
||||
duration_seconds=round(duration, 3),
|
||||
timed_out=False,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
duration = time.monotonic() - start_time
|
||||
logger.warning("Process sandbox timed out after %ds", timeout)
|
||||
try:
|
||||
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
return ExecutionResult(
|
||||
stdout="",
|
||||
stderr=f"Ошибка: превышен максимальный таймаут выполнения ({timeout} сек).",
|
||||
exit_code=-1,
|
||||
duration_seconds=round(duration, 3),
|
||||
timed_out=True,
|
||||
)
|
||||
except Exception as e:
|
||||
duration = time.monotonic() - start_time
|
||||
logger.error("Failed to execute in Process sandbox: %s", e)
|
||||
return ExecutionResult(
|
||||
stdout="",
|
||||
stderr=f"Process execution error: {type(e).__name__}: {str(e)}",
|
||||
exit_code=-1,
|
||||
duration_seconds=round(duration, 3),
|
||||
timed_out=False,
|
||||
)
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Sandbox tools exposed to HomeAgent, Gemini, DeepSeek, and subagents."""
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from extensions.sandbox.manager import SandboxManager
|
||||
from homeagent.config import get_settings
|
||||
from homeagent.tools.base import tool
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_sandbox_manager: Optional[SandboxManager] = None
|
||||
|
||||
|
||||
def get_sandbox_manager() -> SandboxManager:
|
||||
global _sandbox_manager
|
||||
if _sandbox_manager is None:
|
||||
_sandbox_manager = SandboxManager()
|
||||
return _sandbox_manager
|
||||
|
||||
|
||||
@tool(
|
||||
name="code_execute",
|
||||
description=(
|
||||
"Безопасно выполнить код (Python, Bash, JavaScript) в изолированной песочнице (Sandbox). "
|
||||
"Песочница полностью изолирована от хостовой системы (файлы хоста и секреты .env скрыты, сеть заблокирована, "
|
||||
"лимит RAM 512МБ, строгий таймаут). Используй для математических вычислений, обработки данных, симуляций и проверки алгоритмов."
|
||||
),
|
||||
)
|
||||
async def code_execute(
|
||||
code: str,
|
||||
language: str = "python",
|
||||
timeout: int = 30,
|
||||
) -> str:
|
||||
"""Выполнить код в защищенной песочнице.
|
||||
|
||||
Args:
|
||||
code: Исходный код программы (Python, Bash, JavaScript)
|
||||
language: Язык программирования ('python', 'bash', 'javascript')
|
||||
timeout: Максимальное время выполнения в секундах (по умолчанию 30, максимум 120)
|
||||
"""
|
||||
settings = get_settings()
|
||||
if not settings.SANDBOX_ENABLED:
|
||||
return "Изолированная песочница отключена в настройках (SANDBOX_ENABLED=False)."
|
||||
|
||||
clean_code = code.strip()
|
||||
if not clean_code:
|
||||
return "Ошибка: код для выполнения не может быть пустым."
|
||||
|
||||
mgr = get_sandbox_manager()
|
||||
limit_timeout = max(1, min(timeout, 120))
|
||||
|
||||
try:
|
||||
res = await mgr.run_code(clean_code, language=language, timeout=limit_timeout)
|
||||
backend_name = mgr.get_backend_name()
|
||||
|
||||
lines = [f"⚙️ **[Sandbox: {backend_name}]** Язык: `{language}`, время: `{res.duration_seconds}s`, статус: `{'OK (код 0)' if res.exit_code == 0 else f'Ошибка (код {res.exit_code})'}`"]
|
||||
|
||||
if res.timed_out:
|
||||
lines.append("⚠️ **Превышен лимит времени выполнения!** Процесс был принудительно завершен.")
|
||||
|
||||
if res.stdout.strip():
|
||||
lines.append(f"\n**Вывод (stdout):**\n```\n{res.stdout.strip()}\n```")
|
||||
|
||||
if res.stderr.strip():
|
||||
lines.append(f"\n**Ошибки (stderr):**\n```\n{res.stderr.strip()}\n```")
|
||||
|
||||
if not res.stdout.strip() and not res.stderr.strip():
|
||||
lines.append("\n*(Программа завершилась без вывода в консоль)*")
|
||||
|
||||
return "\n".join(lines)
|
||||
except Exception as e:
|
||||
logger.error("code_execute failed: %s", e)
|
||||
return f"Ошибка выполнения в песочнице: {type(e).__name__}: {str(e)}"
|
||||
|
||||
|
||||
@tool(
|
||||
name="sandbox_run_command",
|
||||
description=(
|
||||
"Выполнить консольную команду (Bash) внутри изолированной песочницы (Sandbox). "
|
||||
"Хостовая файловая система и сеть изолированы, изменения производятся только во временной рабочей директории /workspace."
|
||||
),
|
||||
)
|
||||
async def sandbox_run_command(
|
||||
command: str,
|
||||
timeout: int = 30,
|
||||
) -> str:
|
||||
"""Выполнить команду в песочнице.
|
||||
|
||||
Args:
|
||||
command: Консольная команда для выполнения (например: 'ls -la', 'python3 -V', 'grep ...')
|
||||
timeout: Максимальное время выполнения в секундах (по умолчанию 30)
|
||||
"""
|
||||
settings = get_settings()
|
||||
if not settings.SANDBOX_ENABLED:
|
||||
return "Изолированная песочница отключена в настройках (SANDBOX_ENABLED=False)."
|
||||
|
||||
clean_cmd = command.strip()
|
||||
if not clean_cmd:
|
||||
return "Ошибка: команда не может быть пустой."
|
||||
|
||||
mgr = get_sandbox_manager()
|
||||
limit_timeout = max(1, min(timeout, 120))
|
||||
|
||||
try:
|
||||
res = await mgr.run_command(clean_cmd, timeout=limit_timeout)
|
||||
backend_name = mgr.get_backend_name()
|
||||
|
||||
lines = [f"💻 **[Sandbox: {backend_name}]** Команда: `{clean_cmd}`, время: `{res.duration_seconds}s`"]
|
||||
|
||||
if res.timed_out:
|
||||
lines.append("⚠️ **Превышен лимит времени выполнения!** Команда была принудительно остановлена.")
|
||||
|
||||
if res.stdout.strip():
|
||||
lines.append(f"\n**Вывод (stdout):**\n```\n{res.stdout.strip()}\n```")
|
||||
|
||||
if res.stderr.strip():
|
||||
lines.append(f"\n**Ошибки (stderr):**\n```\n{res.stderr.strip()}\n```")
|
||||
|
||||
if not res.stdout.strip() and not res.stderr.strip():
|
||||
lines.append("\n*(Команда выполнена успешно, вывод пуст)*")
|
||||
|
||||
return "\n".join(lines)
|
||||
except Exception as e:
|
||||
logger.error("sandbox_run_command failed: %s", e)
|
||||
return f"Ошибка выполнения команды в песочнице: {type(e).__name__}: {str(e)}"
|
||||
|
||||
|
||||
@tool(
|
||||
name="sandbox_file_write",
|
||||
description="Создать или перезаписать файл внутри изолированного рабочего пространства песочницы (/workspace).",
|
||||
)
|
||||
async def sandbox_file_write(filename: str, content: str) -> str:
|
||||
"""Записать файл в песочницу.
|
||||
|
||||
Args:
|
||||
filename: Имя файла или относительный путь (например 'data.csv', 'test.py', 'input.json')
|
||||
content: Содержимое файла
|
||||
"""
|
||||
settings = get_settings()
|
||||
if not settings.SANDBOX_ENABLED:
|
||||
return "Изолированная песочница отключена в настройках (SANDBOX_ENABLED=False)."
|
||||
|
||||
mgr = get_sandbox_manager()
|
||||
try:
|
||||
saved_path = mgr.write_file(filename, content)
|
||||
return f"Файл '{filename}' успешно создан в песочнице (размер: {len(content.encode('utf-8'))} байт)."
|
||||
except Exception as e:
|
||||
return f"Ошибка записи файла в песочницу: {type(e).__name__}: {str(e)}"
|
||||
|
||||
|
||||
@tool(
|
||||
name="sandbox_file_read",
|
||||
description="Прочитать содержимое файла, созданного или обработанного внутри песочницы (/workspace).",
|
||||
)
|
||||
async def sandbox_file_read(filename: str, max_chars: int = 8000) -> str:
|
||||
"""Прочитать файл из песочницы.
|
||||
|
||||
Args:
|
||||
filename: Имя файла или относительный путь внутри песочницы
|
||||
max_chars: Максимальное количество символов (по умолчанию 8000)
|
||||
"""
|
||||
settings = get_settings()
|
||||
if not settings.SANDBOX_ENABLED:
|
||||
return "Изолированная песочница отключена в настройках (SANDBOX_ENABLED=False)."
|
||||
|
||||
mgr = get_sandbox_manager()
|
||||
try:
|
||||
content = mgr.read_file(filename, max_chars=max(100, min(max_chars, 32000)))
|
||||
return f"📄 Файл '{filename}' из песочницы:\n```\n{content}\n```"
|
||||
except Exception as e:
|
||||
return f"Ошибка чтения файла из песочницы: {type(e).__name__}: {str(e)}"
|
||||
|
||||
|
||||
@tool(
|
||||
name="sandbox_reset",
|
||||
description="Очистить рабочее пространство песочницы (удалить все временные файлы и скрипты из /workspace).",
|
||||
)
|
||||
async def sandbox_reset() -> str:
|
||||
"""Очистить рабочее пространство песочницы."""
|
||||
settings = get_settings()
|
||||
if not settings.SANDBOX_ENABLED:
|
||||
return "Изолированная песочница отключена в настройках."
|
||||
|
||||
mgr = get_sandbox_manager()
|
||||
try:
|
||||
mgr.clean_workspace()
|
||||
return "Рабочее пространство песочницы успешно очищено."
|
||||
except Exception as e:
|
||||
return f"Ошибка очистки песочницы: {type(e).__name__}: {str(e)}"
|
||||
Reference in new issue
Block a user