> ## 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 sandbox class for creating and managing cloud sandboxes in JavaScript/TypeScript. Complete reference for the HopX JavaScript SDK Sandbox class including async/await methods for creating sandboxes, executing code, managing files, controlling desktop automation, and monitoring resources. Includes TypeScript examples for all methods.

**Version:** 0.1.22\
**Last Verified:** 2025-01-27\
**Package:** `@hopx-ai/sdk` on [npm](https://www.npmjs.com/package/@hopx-ai/sdk)

## Overview

The `Sandbox` class is the main entry point for the HopX JavaScript/TypeScript SDK. It provides an async/await interface for creating, managing, and interacting with cloud sandboxes (microVMs). All methods are async and must be called with `await`.

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

## Import

```typescript theme={null}
import { Sandbox } from '@hopx-ai/sdk';
```

Or with CommonJS:

```javascript theme={null}
const { Sandbox } = require('@hopx-ai/sdk');
```

## Static Methods

### `create`

Create a new sandbox from a template.

```typescript theme={null}
static async Sandbox.create(options: SandboxCreateOptions): Promise<Sandbox>
```

**Parameters:**

* `options.template` (`string`, optional): Template name
* `options.templateId` (`string`, optional): Template ID (alternative to template)
* `options.region` (`string`, optional): Preferred region
* `options.timeoutSeconds` (`number`, optional): Auto-kill timeout in seconds
* `options.internetAccess` (`boolean`, optional): Enable internet (default: `true`)
* `options.envVars` (`Record<string, string>`, optional): Environment variables
* `options.apiKey` (`string`, optional): API key (or use `HOPX_API_KEY` env var)
* `options.baseURL` (`string`, optional): API base URL

**Returns:** `Promise<Sandbox>` - New sandbox instance

**Example:**

```typescript theme={null}
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
const info = await sandbox.getInfo();
console.log(info.publicHost);
```

**Expected Output:**

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

***

### `connect`

Connect to an existing sandbox by ID.

```typescript theme={null}
static async Sandbox.connect(
    sandboxId: string,
    options?: { apiKey?: string; baseURL?: string }
): Promise<Sandbox>
```

**Parameters:**

* `sandboxId` (`string`): Existing sandbox ID
* `options.apiKey` (`string`, optional): API key
* `options.baseURL` (`string`, optional): API base URL

**Returns:** `Promise<Sandbox>` - Connected sandbox instance

<Note>
  If VM is paused, resumes it and refreshes JWT token. If stopped, throws error.
</Note>

**Example:**

```typescript theme={null}
const sandbox = await Sandbox.connect('sandbox-abc123');
const info = await sandbox.getInfo();
console.log(`Status: ${info.status}`);
```

**Expected Output:**

```
Status: running
```

***

### `list`

List all sandboxes.

```typescript theme={null}
static async Sandbox.list(options?: {
    apiKey?: string;
    baseURL?: string;
    limit?: number;
    status?: 'running' | 'stopped' | 'paused' | 'creating';
    region?: string;
}): Promise<SandboxInfo[]>
```

**Returns:** `Promise<SandboxInfo[]>` - Array of sandbox information objects

**Example:**

```typescript theme={null}
const sandboxes = await Sandbox.list({ status: 'running', limit: 50 });
for (const sb of sandboxes) {
    console.log(`${sb.sandboxId}: ${sb.status}`);
}
```

**Expected Output:**

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

***

### `listTemplates`

List available templates.

```typescript theme={null}
static async Sandbox.listTemplates(options?: {
    category?: string;
    language?: string;
    apiKey?: string;
    baseURL?: string;
}): Promise<TemplateInfo[]>
```

**Returns:** `Promise<TemplateInfo[]>` - Array of template information objects

**Example:**

```typescript theme={null}
const templates = await Sandbox.listTemplates({ language: 'python' });
for (const template of templates) {
    console.log(`${template.name}: ${template.description}`);
}
```

**Expected Output:**

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

***

### `getTemplate`

Get template details by name.

```typescript theme={null}
static async Sandbox.getTemplate(
    name: string,
    options?: { apiKey?: string; baseURL?: string }
): Promise<TemplateInfo>
```

**Returns:** `Promise<TemplateInfo>` - Template information object

**Example:**

```typescript theme={null}
const template = await Sandbox.getTemplate('code-interpreter');
console.log(`Resources: ${template.defaultResources.vcpu} vCPU`);
```

**Expected Output:**

```
Resources: 2 vCPU
```

***

## Instance Methods

### Lifecycle Methods

#### `getInfo`

Get current sandbox information.

```typescript theme={null}
async sandbox.getInfo(): Promise<SandboxInfo>
```

**Returns:** `Promise<SandboxInfo>` - Sandbox information object

***

#### `kill`

Destroy the sandbox immediately.

```typescript theme={null}
async sandbox.kill(): Promise<void>
```

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

***

#### `start`

Start a stopped sandbox.

```typescript theme={null}
async sandbox.start(): Promise<void>
```

***

#### `stop`

Stop a running sandbox.

```typescript theme={null}
async sandbox.stop(): Promise<void>
```

***

#### `pause`

Pause a running sandbox.

```typescript theme={null}
async sandbox.pause(): Promise<void>
```

***

#### `resume`

Resume a paused sandbox.

```typescript theme={null}
async sandbox.resume(): Promise<void>
```

***

### Execution Methods

#### `runCode`

Execute code synchronously with rich output capture.

```typescript theme={null}
async sandbox.runCode(
    code: string,
    options?: CodeExecutionOptions
): Promise<ExecutionResult>
```

**Parameters:**

* `code` (`string`): Code to execute
* `options.language` (`string`, optional): Language (default: `'python'`)
* `options.timeout` (`number`, optional): Timeout in seconds (default: `60`)
* `options.workingDir` (`string`, optional): Working directory (default: `'/workspace'`)
* `options.env` (`Record<string, string>`, optional): Environment variables

**Returns:** `Promise<ExecutionResult>` - Execution result

**Example:**

```typescript theme={null}
const result = await sandbox.runCode("print('Hello, HopX!')");
console.log(result.stdout); // "Hello, HopX!\n"
console.log(result.exitCode); // 0
```

**Expected Output:**

```
Hello, HopX!
0
```

***

#### `runCodeAsync`

Execute code asynchronously with webhook callback.

```typescript theme={null}
async sandbox.runCodeAsync(
    code: string,
    options: AsyncExecutionOptions
): Promise<AsyncExecuteResponse>
```

**Parameters:**

* `code` (`string`): Code to execute
* `options.callbackUrl` (`string`): URL to POST results to
* `options.language` (`string`, optional): Language
* `options.timeout` (`number`, optional): Timeout in seconds
* `options.workingDir` (`string`, optional): Working directory
* `options.env` (`Record<string, string>`, optional): Environment variables
* `options.callbackHeaders` (`Record<string, string>`, optional): Callback headers
* `options.callbackSignatureSecret` (`string`, optional): Signature secret

**Returns:** `Promise<AsyncExecuteResponse>` - Response with `executionId` and `status`

***

#### `runCodeBackground`

Execute code in background and return immediately.

```typescript theme={null}
async sandbox.runCodeBackground(
    code: string,
    options?: BackgroundExecutionOptions
): Promise<BackgroundExecuteResponse>
```

**Returns:** `Promise<BackgroundExecuteResponse>` - Response with `processId` and `executionId`

***

#### `runCodeStream`

Execute code with real-time output streaming via WebSocket.

```typescript theme={null}
async *sandbox.runCodeStream(
    code: string,
    options?: CodeExecutionOptions
): AsyncIterableIterator<StreamMessage>
```

**Returns:** `AsyncIterableIterator<StreamMessage>` - Async generator of stream messages

**Example:**

```typescript theme={null}
for await (const message of sandbox.runCodeStream("print('Hello')")) {
    if (message.type === 'stdout') {
        console.log(message.data);
    }
}
```

**Expected Output:**

```
Hello
```

***

#### `listProcesses`

List all background execution processes.

```typescript theme={null}
async sandbox.listProcesses(): Promise<ProcessInfo[]>
```

**Returns:** `Promise<ProcessInfo[]>` - Array of process information objects

***

#### `killProcess`

Kill a background execution process.

```typescript theme={null}
async sandbox.killProcess(processId: string): Promise<void>
```

***

### Information Methods

#### `getMetricsSnapshot`

Get current system metrics snapshot.

```typescript theme={null}
async sandbox.getMetricsSnapshot(): Promise<MetricsSnapshot>
```

***

#### `getAgentInfo`

Get agent information and capabilities.

```typescript theme={null}
async sandbox.getAgentInfo(): Promise<InfoResponse>
```

***

#### `refreshToken`

Refresh JWT token for agent authentication.

```typescript theme={null}
async sandbox.refreshToken(): Promise<void>
```

***

#### `getToken`

Get current JWT token.

```typescript theme={null}
async sandbox.getToken(): Promise<string>
```

***

## Properties

### `files`

File operations resource (lazy-loaded).

**Type:** `Files`

**Example:**

```typescript theme={null}
const content = await sandbox.files.read('/workspace/script.py');
await sandbox.files.write('/workspace/data.txt', 'Hello, World!');
```

**Expected Output:**

```
File written successfully
```

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

***

### `commands`

Command execution resource (lazy-loaded).

**Type:** `Commands`

**Example:**

```typescript theme={null}
const result = await sandbox.commands.run('ls -la /workspace');
console.log(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
```

***

### `env`

Environment variables resource (lazy-loaded).

**Type:** `EnvironmentVariables`

**Example:**

```typescript theme={null}
await sandbox.env.set('API_KEY', 'secret123');
const allVars = await sandbox.env.getAll();
```

**Expected Output:**

```
Environment variable set successfully
```

***

### `cache`

Cache management resource (lazy-loaded).

**Type:** `Cache`

**Example:**

```typescript theme={null}
const stats = await sandbox.cache.stats();
console.log(`Cache size: ${stats.cache.size}`);
```

**Expected Output:**

```
Cache size: 5
```

***

### `desktop`

Desktop automation resource (lazy-loaded).

**Type:** `Desktop`

**Example:**

```typescript theme={null}
const screenshot = await sandbox.desktop.screenshot();
```

**Expected Output:**

```
Screenshot captured (PNG bytes)
```

***

### `terminal`

Interactive terminal resource via WebSocket (lazy-loaded).

**Type:** `Terminal`

***

### `sandboxId`

Read-only sandbox ID.

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

***

## Examples

### Example 1: Basic Usage

```typescript theme={null}
import { Sandbox } from '@hopx-ai/sdk';

async function main() {
    const sandbox = await Sandbox.create({ template: 'code-interpreter' });
    
    const result = await sandbox.runCode("print('Hello, HopX!')");
    console.log(result.stdout);
    
    await sandbox.kill();
}

main();
```

**Expected Output:**

```
Hello, HopX!
```

### Example 2: File Operations

```typescript theme={null}
import { Sandbox } from '@hopx-ai/sdk';

async function main() {
    const sandbox = await Sandbox.create({ template: 'code-interpreter' });
    
    // Write a file
    await sandbox.files.write('/workspace/script.py', "print('Hello')");
    
    // Execute it
    const result = await sandbox.runCode(
        "exec(open('/workspace/script.py').read())"
    );
    console.log(result.stdout);
    
    await sandbox.kill();
}
```

**Expected Output:**

```
Hello
```

### Example 3: Streaming Output

```typescript theme={null}
import { Sandbox } from '@hopx-ai/sdk';

async function main() {
    const sandbox = await Sandbox.create({ template: 'code-interpreter' });
    
    for await (const message of sandbox.runCodeStream(
        "for i in range(5):\n    print(f'Count: {i}')\n    import time\n    time.sleep(1)"
    )) {
        if (message.type === 'stdout') {
            process.stdout.write(message.data);
        }
    }
    
    await sandbox.kill();
}
```

**Expected Output:**

```
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
```

***

## Related Classes

* **[Files](/sdk/javascript/files)** - File operations resource
* **[Commands](/sdk/javascript/commands)** - Command execution resource
* **[Environment Variables](/sdk/javascript/environment-variables)** - Environment variable management
* **[Types](/sdk/javascript/types)** - TypeScript type definitions

## See Also

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

## Next Steps

* Learn about [Creating Sandboxes](/core-concepts/sandboxes/creating) with different templates
* Explore [Code Execution](/core-concepts/code-execution/synchronous) to run code in sandboxes
* Review [File Operations](/sdk/javascript/files) for managing files
* Check out [API Reference](/api/vm-agent/overview) for direct API access
* **[CLI Sandbox Commands](/cli/commands/sandbox)** - Manage sandboxes from CLI
