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.

Unknown keys are rejected, so a misspelled option (network_mode instead of network) fails loudly instead of being ignored.

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

Size of the writable workspace (a tmpfs mounted at workdir; it counts toward memory_limit) (default: "1G")

pids_limit int

Maximum number of processes and threads (default: 256)

network NetworkMode

Network isolation mode (default: "none")

persistent bool

Keep the container running after the session ends (default: False)

timeout int

Max execution time in seconds (default: 300)

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)

user str

User the container and every command run as, "uid[:gid]" or a user name from the image (default: "65534:65534", nobody). Set "root" to run as root, the 1.5.0 behaviour.

runtime str | None

Docker runtime to run the container with ("runsc" for gVisor)

read_only_rootfs bool

Mount the root filesystem read-only (default: True)

Examples:

>>> # Minimal config
>>> config = SandboxConfig()
>>>
>>> # Custom config
>>> config = SandboxConfig(
...     backend="gvisor",
...     cpu_limit=4,
...     memory_limit="8G",
...     network=NetworkMode.FULL,
... )

runs_as_root property

Whether sandboxed code runs as root (user="root" or uid 0).

from_dict(data) classmethod

Create config from dictionary.

Parameters:

Name Type Description Default
data dict

Configuration dictionary

required

Returns:

Type Description
SandboxConfig

SandboxConfig instance

Raises:

Type Description
ValidationError

If a key is unknown or a value is invalid.

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.

validate_user(v) classmethod

Validate the user[:group] the container runs as.

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 (pydantic.ValidationError, a ValueError subclass, for unknown keys or bad values)

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.

Kills and removes the container unless persistent mode is enabled. The container is removed at once, so it is killed without a grace period (a graceful stop waited its full timeout, 5 s, every time).

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.

Packages are installed into the writable workspace, so this works on the default read-only root filesystem: pip falls back to a user install under $HOME (the workspace), npm installs into <workdir>/node_modules, cargo into <workdir>/.cargo and go into <workdir>/go. Downloading a package needs network access, which the default network="none" does not provide; bake packages into a custom image instead, or enable the network.

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, or the write fails.

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

ensure_available() async

Raise with the reason when the backend cannot run containers.

The default implementation relies on :meth:health_check. Backends that know why they are unavailable override it to say so.

Raises:

Type Description
RuntimeError

If the backend is not available.

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

kill_container(container_id) async

Stop a container at once, without a grace period.

Used when the container is removed right after (a non-persistent session's cleanup). The default stops it with :meth:stop_container; backends override it with a faster kill.

Parameters:

Name Type Description Default
container_id str

Container ID

required

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, or if network="restricted" cannot be enforced (the container is removed and never used).

ensure_available() async

Check that Docker answers and the requested runtime is installed.

Raises:

Type Description
RuntimeError

With the actual reason: the daemon is unreachable, or the configured runtime (runsc for gVisor) is not registered with Docker.

execute_command(container_id, command, timeout, workdir) async

Execute a command in Docker container with proper timeout enforcement.

When the timeout expires, every process the command started is killed inside the container (see :meth:_kill_exec), so a runaway program does not keep burning CPU after the call returns.

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 the requested runtime is configured.

Returns:

Type Description
bool

True if Docker is healthy (and the runtime is available if requested)

kill_container(container_id) async

Kill a Docker container (SIGKILL), without a grace period.

A sandbox container's main process is /bin/bash, which ignores SIGTERM as PID 1, so a graceful docker stop always waited out its whole timeout before killing it.

Parameters:

Name Type Description Default
container_id str

Container ID

required

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 into the container from inside it.

Docker's archive API cannot write to a container with a read-only root filesystem (nor into its tmpfs mounts), so the content is streamed in base64 slices through exec and decoded in the container. Arbitrary content (quotes, newlines, shell metacharacters) is never interpreted by the shell. The file is written to a temporary name and renamed into place, and missing parent directories are created.

Parameters:

Name Type Description Default
container_id str

Container ID

required
file_path str

Absolute path to the file inside the container

required
content str

File contents

required

Raises:

Type Description
RuntimeError

If the file cannot be written.

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