Skip to main content
Version: 0.1.22
Last Verified: 2025-01-27
Package: @hopx-ai/sdk on npm

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

import { Sandbox } from '@hopx-ai/sdk';
Or with CommonJS:
const { Sandbox } = require('@hopx-ai/sdk');

Static Methods

create

Create a new sandbox from a template.
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:
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.
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
If VM is paused, resumes it and refreshes JWT token. If stopped, throws error.
Example:
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.
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:
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.
static async Sandbox.listTemplates(options?: {
    category?: string;
    language?: string;
    apiKey?: string;
    baseURL?: string;
}): Promise<TemplateInfo[]>
Returns: Promise<TemplateInfo[]> - Array of template information objects Example:
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.
static async Sandbox.getTemplate(
    name: string,
    options?: { apiKey?: string; baseURL?: string }
): Promise<TemplateInfo>
Returns: Promise<TemplateInfo> - Template information object Example:
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.
async sandbox.getInfo(): Promise<SandboxInfo>
Returns: Promise<SandboxInfo> - Sandbox information object

kill

Destroy the sandbox immediately.
async sandbox.kill(): Promise<void>
This action is irreversible. The sandbox and all its data will be permanently deleted.

start

Start a stopped sandbox.
async sandbox.start(): Promise<void>

stop

Stop a running sandbox.
async sandbox.stop(): Promise<void>

pause

Pause a running sandbox.
async sandbox.pause(): Promise<void>

resume

Resume a paused sandbox.
async sandbox.resume(): Promise<void>

Execution Methods

runCode

Execute code synchronously with rich output capture.
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:
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.
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.
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.
async *sandbox.runCodeStream(
    code: string,
    options?: CodeExecutionOptions
): AsyncIterableIterator<StreamMessage>
Returns: AsyncIterableIterator<StreamMessage> - Async generator of stream messages Example:
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.
async sandbox.listProcesses(): Promise<ProcessInfo[]>
Returns: Promise<ProcessInfo[]> - Array of process information objects

killProcess

Kill a background execution process.
async sandbox.killProcess(processId: string): Promise<void>

Information Methods

getMetricsSnapshot

Get current system metrics snapshot.
async sandbox.getMetricsSnapshot(): Promise<MetricsSnapshot>

getAgentInfo

Get agent information and capabilities.
async sandbox.getAgentInfo(): Promise<InfoResponse>

refreshToken

Refresh JWT token for agent authentication.
async sandbox.refreshToken(): Promise<void>

getToken

Get current JWT token.
async sandbox.getToken(): Promise<string>

Properties

files

File operations resource (lazy-loaded). Type: Files Example:
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 for complete documentation.

commands

Command execution resource (lazy-loaded). Type: Commands Example:
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:
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:
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:
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

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

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

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

See Also

Next Steps