> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Sandbox

> Main synchronous sandbox class for creating and managing cloud sandboxes in Python. Complete reference for the HopX Python SDK Sandbox class including methods for creating sandboxes, executing code, managing files, controlling desktop automation, and monitoring resources. Includes code examples for all methods.

**Version:** 0.3.0\
**Last Verified:** 2025-01-27\
**Package:** `hopx-ai` on [PyPI](https://pypi.org/project/hopx-ai/)

## Overview

The `Sandbox` class is the main entry point for the HopX Python SDK. It provides a synchronous interface for creating, managing, and interacting with cloud sandboxes (microVMs). Use this class when you're building synchronous Python applications or scripts.

The `Sandbox` class handles authentication, request formatting, error translation, and response parsing automatically, giving you a clean, Pythonic API for sandbox management.

### When to Use Sandbox vs AsyncSandbox

* **Use `Sandbox`** when:
  * Building synchronous Python applications
  * Writing scripts or simple automation
  * You prefer blocking operations
  * You don't need async/await patterns

* **Use `AsyncSandbox`** when:
  * Building async Python applications (FastAPI, aiohttp, etc.)
  * You need to manage multiple sandboxes concurrently
  * You want non-blocking operations
  * You're already using async/await in your codebase

## Import

```python theme={null}
from hopx_ai import Sandbox
```

## Class Methods

### `create`

Create a new sandbox from a template.

```python theme={null}
Sandbox.create(
    template=None,
    *,
    template_id=None,
    region=None,
    timeout_seconds=None,
    internet_access=None,
    env_vars=None,
    api_key=None,
    base_url='https://api.hopx.dev'
) -> Sandbox
```

**Parameters:**

* `template` (`str`, optional): Template name (e.g., `"code-interpreter"`)
* `template_id` (`str`, optional): Template ID (alternative to template name)
* `region` (`str`, optional): Preferred region (auto-selected if not specified)
* `timeout_seconds` (`int`, optional): Auto-kill timeout in seconds (default: no timeout)
* `internet_access` (`bool`, optional): Enable internet access (default: `True`)
* `env_vars` (`Dict[str, str]`, optional): Environment variables to set in the sandbox
* `api_key` (`str`, optional): API key (or use `HOPX_API_KEY` env var)
* `base_url` (`str`, optional): API base URL (default: production)

**Returns:** `Sandbox` - New sandbox instance

**Raises:**

* `ValidationError`: Invalid parameters
* `ResourceLimitError`: Insufficient resources
* `APIError`: API request failed

**Example:**

```python theme={null}
# Create from template name
sandbox = Sandbox.create(template="code-interpreter")
print(sandbox.get_info().public_host)

# Create with timeout and environment variables
sandbox = Sandbox.create(
    template="code-interpreter",
    timeout_seconds=300,
    env_vars={"DEBUG": "true", "API_KEY": "secret"}
)
```

**Expected Output:**

```
https://sandbox_abc123xyz.hopx.dev
```

**See Also:**

* [API: Create Sandbox](/api/control-plane/create-sandbox)

***

### `connect`

Connect to an existing sandbox by ID.

```python theme={null}
Sandbox.connect(
    sandbox_id,
    *,
    api_key=None,
    base_url='https://api.hopx.dev'
) -> Sandbox
```

**Parameters:**

* `sandbox_id` (`str`): Existing sandbox ID
* `api_key` (`str`, optional): API key (or use `HOPX_API_KEY` env var)
* `base_url` (`str`, optional): API base URL

**Returns:** `Sandbox` - Connected sandbox instance

**Raises:**

* `NotFoundError`: Sandbox not found
* `APIError`: API request failed

**Example:**

```python theme={null}
sandbox = Sandbox.connect("sandbox-abc123")
info = sandbox.get_info()
print(f"Status: {info.status}")
```

**Expected Output:**

```
Status: running
```

**See Also:**

* [API: Get Sandbox](/api/control-plane/get-sandbox)

***

### `list`

List all sandboxes (loads all into memory).

```python theme={null}
Sandbox.list(
    *,
    status=None,
    region=None,
    limit=100,
    api_key=None,
    base_url='https://api.hopx.dev'
) -> List[Sandbox]
```

**Parameters:**

* `status` (`str`, optional): Filter by status (`"running"`, `"stopped"`, `"paused"`, `"creating"`)
* `region` (`str`, optional): Filter by region
* `limit` (`int`, optional): Maximum number of sandboxes to return (default: `100`)
* `api_key` (`str`, optional): API key
* `base_url` (`str`, optional): API base URL

**Returns:** `List[Sandbox]` - List of sandbox instances

**Example:**

```python theme={null}
# List all running sandboxes
running = Sandbox.list(status="running")
for sb in running:
    print(f"{sb.sandbox_id}: {sb.get_info().status}")

# List sandboxes in specific region
sandboxes = Sandbox.list(region="us-east", limit=50)
```

**Expected Output:**

```
sandbox_abc123xyz: running
sandbox_def456uvw: running
sandbox_ghi789rst: paused
```

**See Also:**

* [API: List Sandboxes](/api/control-plane/list-sandboxes)

***

### `iter`

Lazy iterator for sandboxes (memory-efficient).

```python theme={null}
Sandbox.iter(
    *,
    status=None,
    region=None,
    api_key=None,
    base_url='https://api.hopx.dev'
) -> Iterator[Sandbox]
```

**Parameters:**

* `status` (`str`, optional): Filter by status
* `region` (`str`, optional): Filter by region
* `api_key` (`str`, optional): API key
* `base_url` (`str`, optional): API base URL

**Returns:** `Iterator[Sandbox]` - Iterator of sandbox instances

**Example:**

```python theme={null}
# Iterate over all sandboxes (memory-efficient)
for sandbox in Sandbox.iter(status="running"):
    info = sandbox.get_info()
    print(f"{info.sandbox_id}: {info.status}")
```

**Expected Output:**

```
sandbox_abc123xyz: running
sandbox_def456uvw: running
```

**See Also:**

* [API: List Sandboxes](/api/control-plane/list-sandboxes)

***

### `list_templates`

List available templates.

```python theme={null}
Sandbox.list_templates(
    *,
    category=None,
    language=None,
    api_key=None,
    base_url='https://api.hopx.dev'
) -> List[Template]
```

**Parameters:**

* `category` (`str`, optional): Filter by category
* `language` (`str`, optional): Filter by language
* `api_key` (`str`, optional): API key
* `base_url` (`str`, optional): API base URL

**Returns:** `List[Template]` - List of template objects

**Example:**

```python theme={null}
# List all Python templates
python_templates = Sandbox.list_templates(language="python")
for template in python_templates:
    print(f"{template.name}: {template.description}")
```

**Expected Output:**

```
code-interpreter: Python environment with data science libraries
python-basic: Minimal Python 3.11 environment
```

**See Also:**

* [API: List Templates](/api/control-plane/list-templates)

***

### `get_template`

Get template details by name.

```python theme={null}
Sandbox.get_template(
    name,
    *,
    api_key=None,
    base_url='https://api.hopx.dev'
) -> Template
```

**Parameters:**

* `name` (`str`): Template name
* `api_key` (`str`, optional): API key
* `base_url` (`str`, optional): API base URL

**Returns:** `Template` - Template object with details

**Raises:**

* `NotFoundError`: Template not found

**Example:**

```python theme={null}
template = Sandbox.get_template("code-interpreter")
print(f"Resources: {template.resources.vcpu} vCPU, {template.resources.memory_mb}MB RAM")
```

**Expected Output:**

```
Resources: 2 vCPU, 4096MB RAM
```

**See Also:**

* [API: Get Template](/api/control-plane/get-template)

***

### `health_check`

Check API health status (does not require authentication).

```python theme={null}
Sandbox.health_check(
    *,
    base_url='https://api.hopx.dev'
) -> Dict[str, Any]
```

**Parameters:**

* `base_url` (`str`, optional): API base URL

**Returns:** `Dict[str, Any]` - Health status information

**Example:**

```python theme={null}
health = Sandbox.health_check()
print(f"API Status: {health.get('status')}")
```

**Expected Output:**

```
API Status: healthy
```

***

## Instance Methods

### Lifecycle Methods

#### `get_info`

Get current sandbox information.

```python theme={null}
sandbox.get_info() -> SandboxInfo
```

**Returns:** `SandboxInfo` - Sandbox information object

**Example:**

```python theme={null}
info = sandbox.get_info()
print(f"ID: {info.sandbox_id}")
print(f"Status: {info.status}")
print(f"Host: {info.public_host}")
```

**Expected Output:**

```
ID: sandbox_abc123xyz
Status: running
Host: https://sandbox_abc123xyz.hopx.dev
```

**See Also:**

* [API: Get Sandbox](/api/control-plane/get-sandbox)

***

#### `start`

Start a stopped sandbox.

```python theme={null}
sandbox.start() -> None
```

**Raises:**

* `APIError`: Failed to start sandbox

**Example:**

```python theme={null}
sandbox.start()
print("Sandbox started")
```

**Expected Output:**

```
Sandbox started
```

**See Also:**

* [API: Start Sandbox](/api/control-plane/start-sandbox)

***

#### `stop`

Stop the sandbox.

```python theme={null}
sandbox.stop() -> None
```

**Example:**

```python theme={null}
sandbox.stop()
print("Sandbox stopped")
```

**Expected Output:**

```
Sandbox stopped
```

**See Also:**

* [API: Stop Sandbox](/api/control-plane/stop-sandbox)

***

#### `pause`

Pause the sandbox.

```python theme={null}
sandbox.pause() -> None
```

**Example:**

```python theme={null}
sandbox.pause()
print("Sandbox paused")
```

**Expected Output:**

```
Sandbox paused
```

**See Also:**

* [API: Pause Sandbox](/api/control-plane/pause-sandbox)

***

#### `resume`

Resume a paused sandbox.

```python theme={null}
sandbox.resume() -> None
```

**Example:**

```python theme={null}
sandbox.resume()
print("Sandbox resumed")
```

**Expected Output:**

```
Sandbox resumed
```

**See Also:**

* [API: Resume Sandbox](/api/control-plane/resume-sandbox)

***

#### `kill`

Destroy the sandbox immediately.

```python theme={null}
sandbox.kill() -> None
```

<Warning>
  This action is irreversible. The sandbox and all its data will be permanently deleted.
</Warning>

**Example:**

```python theme={null}
sandbox.kill()
print("Sandbox destroyed")
```

**Expected Output:**

```
Sandbox destroyed
```

**See Also:**

* [API: Delete Sandbox](/api/control-plane/delete-sandbox)

***

### Execution Methods

#### `run_code`

Execute code with rich output capture.

```python theme={null}
sandbox.run_code(
    code,
    *,
    language='python',
    timeout=60,
    env=None,
    working_dir='/workspace'
) -> ExecutionResult
```

**Parameters:**

* `code` (`str`): Code to execute
* `language` (`str`, optional): Language (`"python"`, `"javascript"`, `"bash"`, `"go"`) (default: `"python"`)
* `timeout` (`int`, optional): Execution timeout in seconds (default: `60`)
* `env` (`Dict[str, str]`, optional): Environment variables for execution
* `working_dir` (`str`, optional): Working directory (default: `"/workspace"`)

**Returns:** `ExecutionResult` - Execution result with `stdout`, `stderr`, `exit_code`, and `rich_outputs`

**Example:**

```python theme={null}
result = sandbox.run_code("print('Hello, HopX!')")
print(result.stdout)  # "Hello, HopX!\n"
print(result.exit_code)  # 0
```

**Expected Output:**

```
Hello, HopX!
0
```

**See Also:**

* [API: Execute Code](/api/vm-agent/execute)

***

#### `run_code_background`

Execute code in background and return immediately.

```python theme={null}
sandbox.run_code_background(
    code,
    *,
    language='python',
    timeout=300,
    env=None,
    working_dir='/workspace',
    name=None
) -> Dict[str, Any]
```

**Parameters:**

* `code` (`str`): Code to execute
* `language` (`str`, optional): Language (default: `"python"`)
* `timeout` (`int`, optional): Max execution time in seconds (default: `300`)
* `env` (`Dict[str, str]`, optional): Environment variables
* `working_dir` (`str`, optional): Working directory
* `name` (`str`, optional): Process name for identification

**Returns:** `Dict[str, Any]` - Dict with `process_id`, `execution_id`, and `status`

**Example:**

```python theme={null}
proc = sandbox.run_code_background(
    "import time; time.sleep(300); print('Done')",
    name="long-task"
)
print(f"Process ID: {proc['process_id']}")

# Check status later
processes = sandbox.list_processes()
```

**Expected Output:**

```
Process ID: proc-abc123xyz
```

**See Also:**

* [API: Execute Code (Background)](/api/vm-agent/execute-background)

***

#### `list_processes`

List all background execution processes.

```python theme={null}
sandbox.list_processes() -> List[Dict[str, Any]]
```

**Returns:** `List[Dict[str, Any]]` - List of process dictionaries

**Example:**

```python theme={null}
processes = sandbox.list_processes()
for proc in processes:
    print(f"{proc['process_id']}: {proc['status']}")
```

**Expected Output:**

```
proc_abc123: running
proc_def456: completed
```

**See Also:**

* [API: List Processes](/api/vm-agent/list-processes)

***

#### `kill_process`

Kill a background execution process.

```python theme={null}
sandbox.kill_process(process_id) -> Dict[str, Any]
```

**Parameters:**

* `process_id` (`str`): Process ID from `run_code_background()` or `list_processes()`

**Returns:** `Dict[str, Any]` - Confirmation message

**Example:**

```python theme={null}
sandbox.kill_process("proc-abc123")
```

**Expected Output:**

```
Process killed successfully
```

**See Also:**

* [API: Kill Process](/api/vm-agent/kill-process)

***

### Information Methods

#### `get_agent_metrics`

Get real-time agent metrics.

```python theme={null}
sandbox.get_agent_metrics() -> Dict[str, Any]
```

**Returns:** `Dict[str, Any]` - Metrics dictionary with `total_executions`, `active_executions`, `error_count`, etc.

**Example:**

```python theme={null}
metrics = sandbox.get_agent_metrics()
print(f"Total executions: {metrics['total_executions']}")
print(f"Active: {metrics['active_executions']}")
```

**Expected Output:**

```
Total executions: 42
Active: 2
```

**See Also:**

* [API: Get System Metrics](/api/vm-agent/get-system-metrics)

***

#### `get_agent_info`

Get VM agent information (version, OS, architecture, endpoints, features).

```python theme={null}
sandbox.get_agent_info() -> Dict[str, Any]
```

**Returns:** `Dict[str, Any]` - Agent information dictionary

<Note>
  Requires Agent v3.1.0+. Uses GET /info endpoint.
</Note>

**Example:**

```python theme={null}
info = sandbox.get_agent_info()
print(f"Agent version: {info['version']}")
print(f"OS: {info['os']}")
```

**Expected Output:**

```
Agent version: 3.1.0
OS: linux
```

***

#### `get_preview_url`

Get preview URL for accessing a service running on a specific port.

```python theme={null}
sandbox.get_preview_url(port=7777) -> str
```

**Parameters:**

* `port` (`int`, optional): Port number (default: `7777`)

**Returns:** `str` - Preview URL

<Note>
  HopX automatically exposes all ports. Use this to get the public URL for any port.
</Note>

**Example:**

```python theme={null}
# Start a web server
sandbox.run_code("python -m http.server 8000", background=True)

# Get preview URL
url = sandbox.get_preview_url(port=8000)
print(f"Access at: {url}")
```

**Expected Output:**

```
Access at: https://8000-sandbox_abc123xyz.hopx.dev
```

***

#### `get_metrics_snapshot`

Get current system metrics snapshot.

```python theme={null}
sandbox.get_metrics_snapshot() -> Dict[str, Any]
```

**Returns:** `Dict[str, Any]` - System metrics dictionary

**Example:**

```python theme={null}
metrics = sandbox.get_metrics_snapshot()
print(f"CPU: {metrics.get('cpu_percent')}%")
print(f"Memory: {metrics.get('memory_percent')}%")
```

**Expected Output:**

```
CPU: 15.3%
Memory: 42.1%
```

***

### Utility Methods

#### `set_timeout`

Extend sandbox timeout.

```python theme={null}
sandbox.set_timeout(seconds) -> None
```

**Parameters:**

* `seconds` (`int`): New timeout in seconds

**Example:**

```python theme={null}
sandbox.set_timeout(3600)  # Extend to 1 hour
```

**See Also:**

* [API: Set Sandbox Timeout](/api/control-plane/set-timeout)

***

#### `refresh_token`

Refresh JWT token for agent authentication.

```python theme={null}
sandbox.refresh_token() -> None
```

**Example:**

```python theme={null}
sandbox.refresh_token()
```

**Expected Output:**

```
Token refreshed successfully
```

***

#### `get_token`

Get current JWT token.

```python theme={null}
sandbox.get_token() -> str
```

**Returns:** `str` - JWT token string

**Example:**

```python theme={null}
token = sandbox.get_token()
print(f"Token: {token[:20]}...")
```

**Expected Output:**

```
Token: eyJhbGciOiJIUzI1NiIs...
```

***

## Properties

### `files`

File operations resource (lazy-loaded).

**Type:** `Files`

**Example:**

```python theme={null}
# Read a file
content = sandbox.files.read("/workspace/script.py")

# Write a file
sandbox.files.write("/workspace/data.txt", "Hello, World!")
```

**Expected Output:**

```
File written successfully
```

See [Files Resource](/sdk/python/files) for complete documentation.

***

### `commands`

Command execution resource (lazy-loaded).

**Type:** `Commands`

**Example:**

```python theme={null}
result = sandbox.commands.run("ls -la /workspace")
print(result.stdout)
```

**Expected Output:**

```
total 8
drwxr-xr-x 2 root root 4096 Jan 27 10:30 .
drwxr-xr-x 3 root root 4096 Jan 27 10:30 ..
-rw-r--r-- 1 root root   42 Jan 27 10:30 data.txt
```

See [Commands Resource](/sdk/python/commands) for complete documentation.

***

### `env`

Environment variables resource (lazy-loaded).

**Type:** `EnvironmentVariables`

**Example:**

```python theme={null}
# Set environment variable
sandbox.env.set("API_KEY", "secret123")

# Get all environment variables
all_vars = sandbox.env.get_all()
```

**Expected Output:**

```
Environment variable set successfully
```

See [Environment Variables Resource](/sdk/python/environment-variables) for complete documentation.

***

### `desktop`

Desktop automation resource (lazy-loaded).

**Type:** `Desktop`

**Example:**

```python theme={null}
# Take a screenshot
screenshot = sandbox.desktop.screenshot()

# Click at position
sandbox.desktop.click(100, 200)
```

**Expected Output:**

```
Screenshot captured (PNG bytes)
Click executed at (100, 200)
```

See [Desktop Resource](/sdk/python/desktop) for complete documentation.

***

### `cache`

Cache management resource (lazy-loaded).

**Type:** `Cache`

**Example:**

```python theme={null}
# Get cache statistics
stats = sandbox.cache.stats()
print(f"Cache size: {stats['cache']['size']}")

# Clear cache
sandbox.cache.clear()
```

**Expected Output:**

```
Cache size: 5
Cache cleared successfully
```

See [Cache Resource](/sdk/python/cache) for complete documentation.

***

### `terminal`

Interactive terminal resource via WebSocket (lazy-loaded).

**Type:** `Terminal`

<Note>
  Requires `websockets` library: `pip install websockets`
</Note>

**Example:**

```python theme={null}
import asyncio

async def use_terminal():
    ws = await sandbox.terminal.connect()
    await sandbox.terminal.send_input(ws, "echo 'Hello'\n")
    # ... handle output
    await ws.close()

asyncio.run(use_terminal())
```

**Expected Output:**

```
Terminal connected
Hello
Terminal closed
```

See [Terminal Resource](/sdk/python/terminal) for complete documentation.

***

### `agent_url`

Get the sandbox agent URL (port 7777) - convenience property.

**Type:** `str` (read-only)

**Example:**

```python theme={null}
url = sandbox.agent_url
print(f"Agent URL: {url}")
```

**Expected Output:**

```
Agent URL: https://sandbox_abc123xyz.hopx.dev
```

***

## Context Manager

The `Sandbox` class supports context manager protocol for automatic cleanup.

**Example:**

```python theme={null}
# Automatically calls kill() when exiting context
with Sandbox.create(template="code-interpreter") as sandbox:
    result = sandbox.run_code("print('Hello')")
    print(result.stdout)
# Sandbox is automatically destroyed here
```

**Expected Output:**

```
Hello
```

***

## Examples

### Example 1: Basic Usage

```python theme={null}
from hopx_ai import Sandbox

# Create sandbox
sandbox = Sandbox.create(template="code-interpreter")

# Execute code
result = sandbox.run_code("print('Hello, HopX!')")
print(result.stdout)

# Cleanup
sandbox.kill()
```

**Expected Output:**

```
Hello, HopX!
```

### Example 2: Using Context Manager

```python theme={null}
from hopx_ai import Sandbox

with Sandbox.create(template="code-interpreter") as sandbox:
    # Work with sandbox
    result = sandbox.run_code("import sys; print(sys.version)")
    print(result.stdout)
# Automatically cleaned up
```

**Expected Output:**

```
3.11.5 (main, Jan 27 2025, 10:30:00) [GCC 11.2.0]
```

### Example 3: File Operations

```python theme={null}
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Write a file
sandbox.files.write("/workspace/script.py", "print('Hello')")

# Execute it
result = sandbox.run_code("exec(open('/workspace/script.py').read())")
print(result.stdout)

sandbox.kill()
```

**Expected Output:**

```
Hello
```

### Example 4: Background Execution

```python theme={null}
from hopx_ai import Sandbox
import time

sandbox = Sandbox.create(template="code-interpreter")

# Start long-running task
proc = sandbox.run_code_background(
    "import time; time.sleep(60); print('Done')",
    name="long-task"
)

# Do other work
time.sleep(5)

# Check status
processes = sandbox.list_processes()
for p in processes:
    if p['process_id'] == proc['process_id']:
        print(f"Status: {p['status']}")

sandbox.kill()
```

**Expected Output:**

```
Status: running
```

***

## Related Classes

* **[AsyncSandbox](/sdk/python/async-sandbox)** - Async version of Sandbox for async/await workflows
* **[Files](/sdk/python/files)** - File operations resource
* **[Commands](/sdk/python/commands)** - Command execution resource
* **[Environment Variables](/sdk/python/environment-variables)** - Environment variable management
* **[Desktop](/sdk/python/desktop)** - Desktop automation resource
* **[Cache](/sdk/python/cache)** - Cache management resource
* **[Terminal](/sdk/python/terminal)** - Interactive terminal resource

## See Also

* [Quickstart Guide](/sdk/python/quickstart) - Get started with the SDK
* [Installation](/sdk/python/installation) - Install and configure the SDK
* [Core Concepts](/core-concepts/sandboxes/creating) - Learn about sandboxes

## Next Steps

* Learn about [AsyncSandbox](/sdk/python/async-sandbox) for async/await workflows
* Explore [Creating Sandboxes](/core-concepts/sandboxes/creating) with different templates
* Review [Code Execution](/core-concepts/code-execution/synchronous) to run code in sandboxes
* Check out [File Operations](/sdk/python/files) for managing files
* See [API Reference](/api/control-plane/create-sandbox) for direct API access
* **[CLI Reference](/cli/introduction)** - Use HopX from the command line
* [API Reference](/api/introduction) - Raw REST API documentation
