Skip to content

Sandbox API Reference

Secure sandbox for agent code execution. Provides a zero-configuration sandbox environment for agents to safely execute arbitrary commands and code using container technology with multiple security layers.

SandboxConfig

promptise.sandbox.config.SandboxConfig

Bases: BaseModel

Configuration for sandbox environment.

Attributes:

Name Type Description
backend Literal['docker', 'gvisor']

Container backend to use (docker, gvisor)

image str

Base container image (default: python:3.11-slim)

cpu_limit int

Maximum CPU cores (default: 2)

memory_limit str

Maximum memory (default: "4G")

disk_limit str

Maximum disk space (default: "10G")

network NetworkMode

Network isolation mode (default: "restricted")

persistent bool

Keep workspace between runs (default: False)

timeout int

Max execution time in seconds (default: 300)

tools list[str]

Pre-installed tools to include (default: ["python"])

workdir str

Working directory inside container (default: "/workspace")

env dict[str, str]

Additional environment variables

allow_sudo bool

Allow sudo access in container (default: False)

Examples:

>>> # Minimal config
>>> config = SandboxConfig()
>>>
>>> # Custom config
>>> config = SandboxConfig(
...     backend="gvisor",
...     cpu_limit=4,
...     memory_limit="8G",
...     network=NetworkMode.FULL,
...     tools=["python", "node", "rust"]
... )

from_dict(data) classmethod

Create config from dictionary.

Parameters:

Name Type Description Default
data dict

Configuration dictionary

required

Returns:

Type Description
SandboxConfig

SandboxConfig instance

from_simple(enabled=True) classmethod

Create config from simple boolean flag.

Parameters:

Name Type Description Default
enabled bool

If True, use default config

True

Returns:

Type Description
SandboxConfig

SandboxConfig with defaults

validate_size(v) classmethod

Validate memory/disk size format.

NetworkMode

promptise.sandbox.config.NetworkMode

Bases: str, Enum

Network isolation modes for sandbox.

SandboxManager

promptise.sandbox.manager.SandboxManager

Manages sandbox lifecycle and provides integration with agents.

The SandboxManager handles: - Backend selection and initialization - Container lifecycle management - Session creation and cleanup - Health monitoring

Example

config = SandboxConfig() manager = SandboxManager(config)

async with await manager.create_session() as session: ... result = await session.execute("python --version") ... print(result.stdout)

__aenter__() async

Async context manager entry.

__aexit__(exc_type, exc_val, exc_tb) async

Async context manager exit.

__init__(config)

Initialize sandbox manager.

Parameters:

Name Type Description Default
config SandboxConfig | dict[str, Any] | bool

Sandbox configuration (SandboxConfig, dict, or bool)

required

Raises:

Type Description
ValueError

If config is invalid

cleanup_all() async

Clean up all active sessions.

create_session() async

Create a new sandbox session.

Returns:

Type Description
SandboxSession

SandboxSession for command execution

Raises:

Type Description
RuntimeError

If backend is not healthy or container creation fails

SandboxSession

promptise.sandbox.session.SandboxSession

Manages a persistent sandbox session for command execution.

This class provides a high-level interface for executing commands in a sandbox container, handling timeouts, and managing the session lifecycle.

Attributes:

Name Type Description
container_id

ID of the running container

backend

Backend instance managing the container

config

Sandbox configuration

_running

Whether session is active

__aenter__() async

Async context manager entry.

__aexit__(exc_type, exc_val, exc_tb) async

Async context manager exit.

__init__(container_id, backend, config)

Initialize sandbox session.

Parameters:

Name Type Description Default
container_id str

ID of running container

required
backend Any

Backend instance

required
config Any

Sandbox configuration

required

cleanup() async

Clean up the sandbox session.

Stops and removes the container unless persistent mode is enabled.

execute(command, timeout=None, workdir=None) async

Execute a command in the sandbox.

Parameters:

Name Type Description Default
command str

Shell command to execute

required
timeout int | None

Optional timeout in seconds (uses config.timeout if None)

None
workdir str | None

Optional working directory (uses config.workdir if None)

None

Returns:

Type Description
CommandResult

CommandResult with execution details

Raises:

Type Description
RuntimeError

If session is not running

install_package(package, tool='python') async

Install a package in the sandbox.

Parameters:

Name Type Description Default
package str

Package name to install (shell-escaped internally).

required
tool str

Tool ecosystem ("python", "node", "rust", "go").

'python'

Returns:

Type Description
CommandResult

CommandResult from installation.

Raises:

Type Description
RuntimeError

If session is not running.

ValueError

If tool is not supported.

list_files(directory='/workspace') async

List files in a directory.

Parameters:

Name Type Description Default
directory str

Directory path inside sandbox.

'/workspace'

Returns:

Type Description
list[str]

List of file/directory names.

Raises:

Type Description
ValueError

If directory is outside allowed directories.

RuntimeError

If session is not running.

read_file(file_path) async

Read a file from the sandbox.

Parameters:

Name Type Description Default
file_path str

Path to file inside sandbox (must be within /workspace, /tmp, or /home).

required

Returns:

Type Description
str

File contents as string.

Raises:

Type Description
FileNotFoundError

If file doesn't exist.

ValueError

If path is outside allowed directories.

RuntimeError

If session is not running.

write_file(file_path, content) async

Write a file to the sandbox.

Parameters:

Name Type Description Default
file_path str

Path to file inside sandbox (must be within /workspace, /tmp, or /home).

required
content str

File contents to write.

required

Raises:

Type Description
ValueError

If path is outside allowed directories.

RuntimeError

If session is not running.

CommandResult

promptise.sandbox.session.CommandResult dataclass

Result of a command execution in the sandbox.

Attributes:

Name Type Description
exit_code int

Process exit code (0 = success)

stdout str

Standard output from command

stderr str

Standard error from command

timeout bool

Whether command timed out

duration float

Execution time in seconds

success property

Check if command succeeded.

SandboxBackend

promptise.sandbox.backends.SandboxBackend

Bases: ABC

Abstract base class for sandbox backends.

Defines the interface that all backend implementations must provide.

__init__(config)

Initialize backend with configuration.

Parameters:

Name Type Description Default
config SandboxConfig

Sandbox configuration

required

create_container() abstractmethod async

Create and start a new container.

Returns:

Type Description
str

Container ID

execute_command(container_id, command, timeout, workdir) abstractmethod async

Execute a command in the container.

Parameters:

Name Type Description Default
container_id str

Container ID

required
command str

Shell command to execute

required
timeout int

Timeout in seconds

required
workdir str

Working directory

required

Returns:

Type Description
CommandResult

CommandResult with execution details

health_check() abstractmethod async

Check if backend is available and working.

Returns:

Type Description
bool

True if backend is healthy

read_file(container_id, file_path) abstractmethod async

Read a file from the container.

Parameters:

Name Type Description Default
container_id str

Container ID

required
file_path str

Path to file inside container

required

Returns:

Type Description
str

File contents

remove_container(container_id) abstractmethod async

Remove a container.

Parameters:

Name Type Description Default
container_id str

Container ID

required

stop_container(container_id) abstractmethod async

Stop a running container.

Parameters:

Name Type Description Default
container_id str

Container ID

required

write_file(container_id, file_path, content) abstractmethod async

Write a file to the container.

Parameters:

Name Type Description Default
container_id str

Container ID

required
file_path str

Path to file inside container

required
content str

File contents

required

DockerBackend

promptise.sandbox.backends.DockerBackend

Bases: SandboxBackend

Docker-based sandbox backend with gVisor support.

This backend uses Docker as the container runtime, with optional gVisor for enhanced security through user-space kernel implementation.

__init__(config)

Initialize Docker backend.

Parameters:

Name Type Description Default
config SandboxConfig

Sandbox configuration

required

Raises:

Type Description
ImportError

If the docker package is not installed.

create_container() async

Create and start a new Docker container.

Returns:

Type Description
str

Container ID

Raises:

Type Description
RuntimeError

If container creation fails

execute_command(container_id, command, timeout, workdir) async

Execute a command in Docker container with proper timeout enforcement.

Parameters:

Name Type Description Default
container_id str

Container ID

required
command str

Shell command to execute

required
timeout int

Timeout in seconds (actually enforced)

required
workdir str

Working directory

required

Returns:

Type Description
CommandResult

CommandResult with execution details

health_check() async

Check if Docker is available and gVisor runtime is configured if requested.

Returns:

Type Description
bool

True if Docker is healthy (and gVisor is available if requested)

read_file(container_id, file_path) async

Read a file from Docker container.

Parameters:

Name Type Description Default
container_id str

Container ID

required
file_path str

Path to file

required

Returns:

Type Description
str

File contents

Raises:

Type Description
FileNotFoundError

If file doesn't exist

remove_container(container_id) async

Remove Docker container.

Parameters:

Name Type Description Default
container_id str

Container ID

required

stop_container(container_id) async

Stop Docker container.

Parameters:

Name Type Description Default
container_id str

Container ID

required

write_file(container_id, file_path, content) async

Write a file to Docker container using Docker API.

Uses Docker's put_archive API to safely write files without shell injection risks.

Parameters:

Name Type Description Default
container_id str

Container ID

required
file_path str

Path to file

required
content str

File contents

required

Sandbox Tools

LangChain-compatible tools that agents use to interact with the sandbox environment.

SandboxExecTool

promptise.sandbox.tools.SandboxExecTool

Bases: BaseTool

Execute command in sandbox environment.

This tool allows the agent to run any shell command in the secure sandbox. The sandbox provides full CLI access with isolation from the host system.

__init__(session, **kwargs)

Initialize tool with sandbox session.

SandboxReadFileTool

promptise.sandbox.tools.SandboxReadFileTool

Bases: BaseTool

Read file from sandbox environment.

__init__(session, **kwargs)

Initialize tool with sandbox session.

SandboxWriteFileTool

promptise.sandbox.tools.SandboxWriteFileTool

Bases: BaseTool

Write file to sandbox environment.

__init__(session, **kwargs)

Initialize tool with sandbox session.

SandboxListFilesTool

promptise.sandbox.tools.SandboxListFilesTool

Bases: BaseTool

List files in sandbox directory.

__init__(session, **kwargs)

Initialize tool with sandbox session.

SandboxInstallPackageTool

promptise.sandbox.tools.SandboxInstallPackageTool

Bases: BaseTool

Install package in sandbox environment.

__init__(session, **kwargs)

Initialize tool with sandbox session.

create_sandbox_tools

promptise.sandbox.tools.create_sandbox_tools(session)

Create all sandbox tools for a session.

Parameters:

Name Type Description Default
session SandboxSession

Active sandbox session

required

Returns:

Type Description
list[BaseTool]

List of sandbox tools

Utilities

SandboxContainerManager

promptise.sandbox.utils.SandboxContainerManager

Utility for managing and monitoring sandbox containers.

Provides tools to: - List all sandbox containers (running and stopped) - Clean up orphaned containers - Monitor resource usage - Force cleanup of stuck containers

__init__()

Initialize container manager.

cleanup_all(force=False)

Clean up all sandbox containers.

Parameters:

Name Type Description Default
force bool

If True, force remove running containers

False

Returns:

Type Description
int

Number of containers cleaned up

cleanup_old(max_age_hours=24)

Clean up containers older than specified age.

Parameters:

Name Type Description Default
max_age_hours int

Maximum age in hours

24

Returns:

Type Description
int

Number of containers cleaned up

get_stats(container_id)

Get detailed stats for a container.

Parameters:

Name Type Description Default
container_id str

Container ID (short or full)

required

Returns:

Type Description
dict[str, Any]

Dictionary with container statistics

Raises:

Type Description
NotFound

If container doesn't exist

list_containers(all=False)

List all sandbox containers.

Parameters:

Name Type Description Default
all bool

If True, include stopped containers

False

Returns:

Type Description
list[dict[str, Any]]

List of container info dictionaries

cleanup_on_exit

promptise.sandbox.utils.cleanup_on_exit(session) async

Ensure session is cleaned up on process exit.

Parameters:

Name Type Description Default
session Any

SandboxSession to clean up

required