Quick Start
Agent Sandbox API
Whensandbox is configured, agents gain powerful execution capabilities:
SandboxMixin API
| Method | Signature | Description |
|---|---|---|
has_sandbox | property -> bool | Whether sandbox is configured |
execute_code | async (code, language="python", check_security=True, **kwargs) -> SandboxResult | Async code execution with optional security pre-check |
execute_code_sync | (code, language="python", check_security=True, **kwargs) -> SandboxResult | Sync wrapper around execute_code |
run_shell_command | async (command: str | list, check_security=True, **kwargs) -> SandboxResult | Run shell command in sandbox |
get_sandbox_status | () -> Dict[str, Any] | Returns {"configured", "config", "available_types", "current_type"} |
sandbox_cleanup | async () -> None | Force cleanup of sandbox resources |
get_sandbox_manager | () -> SandboxManager | None | Get or lazily create the manager |
Auto-Generated Agent Tools
Whensandbox is set on an Agent, two tools are automatically available:
execute_python_code(code: str) -> str— runs Python in the sandbox, returns stdout or errorexecute_shell_command(command: str) -> str— runs shell command in the sandbox, returns output or error
Sandbox Backends
Choose the right backend for your security and performance needs:- Subprocess (Local)
- Docker
- E2B Cloud
- Native OS
- Sandlock
- SSH Remote
- Modal Cloud
- Daytona
Fastest, minimal isolation - development only
| Requirements | None (built-in) |
|---|---|
| Use case | Development, trusted code only |
| Isolation | ⚠️ Limited - NOT for untrusted code |
| Performance | ✅ Fastest |
All backend imports are lazy-loaded. Importing the top-level package will not trigger heavy backend imports.
What SecurityPolicy actually controls in subprocess
| Setting | Effect on subprocess child |
|---|---|
allow_network=False | Strips HTTP_PROXY / HTTPS_PROXY / NO_PROXY from child env |
allow_network=True | Passes proxy vars through from host |
max_output_size | Truncates stdout/stderr; appends [OUTPUT TRUNCATED] |
allow_file_write | Controls file write permissions (implementation varies by backend) |
allow_subprocess | Controls subprocess creation (implementation varies by backend) |
blocked_paths | Prevents access to specified paths |
blocked_commands | Blocks execution of specified shell commands |
blocked_imports | Prevents importing specified Python modules |
Resource limits in practice
- Linux / macOS
- Windows
POSIX When limits are exceeded:
setrlimit mapping enforces hard limits:- Memory: Process is killed by the kernel
- Processes:
fork()fails with EAGAIN - Files:
open()fails with EMFILE - Timeout: Whole process group killed with SIGKILL
Timeout handling
On POSIX the whole process group is killed (killpg(SIGKILL)); on Windows only the leader is killed.
Subprocess execution flow
Security Pre-checks
Static code analysis warns about potentially dangerous patterns before execution:Security API
| Function | Signature | Description |
|---|---|---|
check_code_safety | (code: str, language: str = "python") -> List[SecurityWarning] | Runs regex + AST analysis. Supports python, bash, generic fallback |
format_warnings | (warnings: List[SecurityWarning]) -> str | Pretty-print warnings grouped by severity |
get_security_summary | (warnings) -> Dict | Returns {"total_warnings", "by_severity", "max_severity", "is_safe", "has_critical"} |
| Field | Type | Description |
|---|---|---|
pattern | str | Regex pattern or AST node that triggered |
message | str | Human-readable warning |
severity | str | "low", "medium", "high", "critical" |
line_number | Optional[int] | Line number in code |
context | Optional[str] | Source line text |
Agent Integration
Agents automatically run security checks unless disabled:Path Traversal Protection
DockerSandbox and SubprocessSandbox validate every path passed to
write_file, read_file, and list_files. Paths that resolve outside
the sandbox root — via ../, absolute paths, or symlink escapes — are
rejected:
Path traversal attempt blocked: <path>. This is in addition to the
container/OS isolation the sandbox already provides — defense in depth.
SandboxManager
Factory and async context manager for sandbox backends:SandboxManager API
| Method | Description |
|---|---|
__init__(config: SandboxConfig | None) | Defaults to SandboxConfig.subprocess() |
run_code(code, language="python", **kwargs) -> SandboxResult | One-shot: open, run, cleanup |
__aenter__ / __aexit__ | Async context manager yielding SandboxProtocol |
get_available_types() -> Dict[str, Dict] | Returns availability info per backend |
Configuration Options
Progressive disclosure from simple to advanced:SandboxConfig Options
| Option | Type | Default | Description |
|---|---|---|---|
sandbox_type | str | "subprocess" | Backend: subprocess, docker, e2b, native, sandlock, ssh, modal, daytona |
image | str | "python:3.11-slim" | Docker image (docker backend only) |
working_dir | str | "/workspace" | Working directory within sandbox |
env | Dict[str, str] | {} | Environment variables |
resource_limits | ResourceLimits | ResourceLimits() | CPU, memory, timeout limits |
security_policy | SecurityPolicy | SecurityPolicy() | File and network access rules |
auto_cleanup | bool | True | Auto-cleanup after execution |
persist_files | bool | False | Keep files between runs |
mount_paths | List[str] | [] | Paths to mount (host:container format) |
metadata | Dict[str, Any] | {} | Additional configuration |
ResourceLimits Presets
| Limit | Minimal | Standard | Generous |
|---|---|---|---|
memory_mb | 128 | 512 | 2048 |
timeout_seconds | 30 | 60 | 300 |
cpu_percent | 50 | 100 | 100 |
network_enabled | ❌ | ❌ | ✅ |
SecurityPolicy Presets
Common Patterns
- Data Science Agent
- Secure Code Review
- Batch Processing
Timeout Behavior & Resource Cleanup
Understanding how different backends handle timeouts and resource cleanup ensures your resource limits are properly enforced.| Backend | Local cleanup on timeout | Remote cleanup on timeout |
|---|---|---|
subprocess | Process killed | N/A |
docker | Client process killed and docker kill <container> issued on the named container (praisonai-<execution_id>) | Container stopped — resource limits enforced |
ssh | Local SSH client killed | Remote process terminated via timeout N sh -c ... wrapper; remote temp file cleaned up via finally (even on error) |
e2b, modal, native, sandlock, daytona | Backend-managed | Backend-managed |
Docker Timeout Handling
Docker containers get deterministic names and are properly killed on timeout: Why containers are no longer orphaned: Everydocker run is launched with --name praisonai-<execution_id>. On timeout, the sandbox issues docker kill <name> to stop the actual container — not just detach the client. Your memory_mb and cpu_percent limits are now enforced through the entire execution lifecycle.
SSH Timeout Handling
SSH backend prevents both remote process leaks and temp file accumulation: Remote process cleanup: Commands are wrapped withtimeout N sh -c ... to ensure remote processes terminate even if the SSH connection drops.
Temp file cleanup: File cleanup (rm -f) is now in a finally block. Even if execution raises (timeout, network blip), the remote temp file is removed. Cleanup errors are swallowed so they never mask the real execution result.
Best Practices
Use Docker for untrusted code
Use Docker for untrusted code
Always use Docker sandbox when executing code from untrusted sources. Subprocess isolation is not sufficient for security-critical applications.
Enable security pre-checks
Enable security pre-checks
Keep
check_security=True (default) when calling execute_code(). Review warnings in result.metadata["security_warnings"] for insights.Set appropriate resource limits
Set appropriate resource limits
Configure memory and timeout limits based on expected workload. Start with minimal limits and increase as needed.
Disable network by default
Disable network by default
Keep
allow_network=False unless code specifically needs network access. This prevents data exfiltration.Use context managers for persistence
Use context managers for persistence
For multiple operations on the same sandbox, use
async with SandboxManager(config) as sandbox: to reuse the environment efficiently.File system boundaries are enforced
File system boundaries are enforced
Filesystem boundaries are enforced — write_file/read_file/list_files reject paths that escape the sandbox root, even before the backend’s isolation kicks in.
Related
Sandboxed Agent
Complete agent with built-in sandbox
Tools
Extend agent capabilities

