Skip to main content

Sandbox Class

The Sandbox class is the main entry point for interacting with Hopx sandboxes in JavaScript/TypeScript. It provides methods for creating, connecting to, and managing sandboxes, as well as access to all resources.

Class Definition

import { Sandbox } from '@hopx-ai/sdk';

class Sandbox {
  public readonly sandboxId: string;
  
  // Static methods
  static create(options: SandboxCreateOptions): Promise<Sandbox>;
  static connect(sandboxId: string, options?: ConnectOptions): Promise<Sandbox>;
  static list(options?: ListOptions): Promise<SandboxInfo[]>;
  
  // Instance methods
  async init(): Promise<void>;
  async getInfo(): Promise<SandboxInfo>;
  async kill(): Promise<void>;
  async start(): Promise<void>;
  async stop(): Promise<void>;
  async pause(): Promise<void>;
  async resume(): Promise<void>;
  
  // Resources
  get files(): Files;
  get commands(): Commands;
  get env(): EnvironmentVariables;
  get cache(): Cache;
  get desktop(): Desktop;
  get terminal(): Terminal;
}

Static Methods

Sandbox.create()

Create a new sandbox from a template.
const sandbox = await Sandbox.create({
  template: 'code-interpreter',
  apiKey: process.env.HOPX_API_KEY,
  envVars: {
    API_KEY: 'sk-test-123',
    DEBUG: 'true'
  }
});
Options:
interface SandboxCreateOptions {
  template?: string;           // Template name
  templateId?: string;          // Template ID (alternative)
  region?: string;              // Preferred region
  timeoutSeconds?: number;      // Auto-kill timeout
  internetAccess?: boolean;     // Enable internet (default: true)
  envVars?: Record<string, string>;  // Environment variables
  apiKey?: string;              // API key (or use env var)
  baseURL?: string;             // API base URL
}
Returns: Promise<Sandbox> Example:
// Create from template name
const sandbox = await Sandbox.create({
  template: 'code-interpreter'
});

// Create from template ID with timeout
const sandbox = await Sandbox.create({
  templateId: '291',
  timeoutSeconds: 300,
  internetAccess: true
});

// Create with environment variables
const sandbox = await Sandbox.create({
  template: 'my-python-template',
  envVars: {
    DEBUG: 'true',
    API_KEY: 'sk-123'
  }
});

Sandbox.connect()

Connect to an existing sandbox.
const sandbox = await Sandbox.connect('1761048129dsaqav4n');
const info = await sandbox.getInfo();
console.log(info.status);
Parameters:
  • sandboxId (string): Sandbox ID
  • options (object, optional): Connection options
Returns: Promise<Sandbox> Note: If the sandbox is paused, it will be automatically resumed.

Sandbox.list()

List all sandboxes.
const sandboxes = await Sandbox.list({
  status: 'running',
  limit: 10
});

for (const info of sandboxes) {
  console.log(`${info.sandboxId}: ${info.templateName}`);
}
Options:
interface ListOptions {
  status?: 'running' | 'stopped' | 'paused' | 'creating';
  region?: string;
  limit?: number;
  apiKey?: string;
  baseURL?: string;
}

Instance Methods

Lifecycle Methods

init()

Initialize agent client (required before using resources).
await sandbox.init();
Note: This is automatically called when accessing resources, but you can call it explicitly.

getInfo()

Get sandbox information.
const info = await sandbox.getInfo();
console.log(`ID: ${info.sandboxId}`);
console.log(`Status: ${info.status}`);
console.log(`Template: ${info.templateName}`);
console.log(`Host: ${info.publicHost}`);
Returns: Promise<SandboxInfo>

kill()

Delete the sandbox.
await sandbox.kill();

start()

Start a stopped sandbox.
await sandbox.start();

stop()

Stop a running sandbox.
await sandbox.stop();

pause()

Pause a running sandbox.
await sandbox.pause();

resume()

Resume a paused sandbox.
await sandbox.resume();

Code Execution

runCode()

Execute code synchronously.
const result = await sandbox.runCode('print("Hello, World!")');
console.log(result.stdout);
Method Signature:
async runCode(
  code: string,
  options?: CodeExecutionOptions
): Promise<ExecutionResult>
Options:
interface CodeExecutionOptions {
  language?: string;        // 'python', 'javascript', 'bash', 'go'
  timeout?: number;        // Timeout in seconds
  workingDir?: string;     // Working directory
  env?: Record<string, string>;  // Environment variables
  rich?: boolean;          // Capture rich outputs
}
Example:
// Simple execution
const result = await sandbox.runCode('console.log("Hello!")');
console.log(result.stdout);

// With rich outputs
const result = await sandbox.runCode(
  `
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
plt.savefig('/workspace/plot.png')
`,
  { rich: true }
);

// With environment variables
const result = await sandbox.runCode(
  'console.log(process.env.API_KEY)',
  { env: { API_KEY: 'sk-test-123' } }
);

Resources

files

File operations resource (lazy-loaded).
// Read file
const content = await sandbox.files.read('/workspace/data.txt');

// Write file
await sandbox.files.write('/workspace/output.txt', 'Hello!');

// List directory
const files = await sandbox.files.list('/workspace');
See File Operations for complete reference.

commands

Command execution resource (lazy-loaded).
// Run command
const result = await sandbox.commands.run('ls -la /workspace');
console.log(result.stdout);
See Commands for complete reference.

env

Environment variables resource (lazy-loaded).
// Get all env vars
const env = await sandbox.env.getAll();

// Set env var
await sandbox.env.set('API_KEY', 'sk-prod-xyz');

// Update multiple
await sandbox.env.update({
  NODE_ENV: 'production',
  DEBUG: 'false'
});
See Environment Variables for complete reference.

desktop

Desktop automation resource (lazy-loaded).
// Start VNC
const vncInfo = await sandbox.desktop.startVnc();
console.log(`VNC URL: ${vncInfo.url}`);

// Screenshot
const screenshot = await sandbox.desktop.screenshot();
See Desktop for complete reference.

cache

Cache management resource (lazy-loaded).
// Get cache stats
const stats = await sandbox.cache.stats();
console.log(`Cache size: ${stats.cache.size} MB`);

// Clear cache
await sandbox.cache.clear();

terminal

Interactive terminal resource (lazy-loaded).
const ws = await sandbox.terminal.connect();
await sandbox.terminal.sendInput(ws, 'ls -la\n');
for await (const message of sandbox.terminal.iterOutput(ws)) {
  if (message.type === 'output') {
    process.stdout.write(message.data);
  }
}

Complete Example

import { Sandbox } from '@hopx-ai/sdk';

async function main() {
  // Create sandbox
  const sandbox = await Sandbox.create({
    template: 'code-interpreter',
    envVars: {
      API_KEY: 'sk-test-123'
    }
  });

  // Initialize agent
  await sandbox.init();

  // Get info
  const info = await sandbox.getInfo();
  console.log(`Sandbox: ${info.sandboxId}`);

  // Execute code
  const result = await sandbox.runCode('print("Hello!")');
  console.log(result.stdout);

  // File operations
  await sandbox.files.write('/workspace/test.txt', 'Hello');
  const content = await sandbox.files.read('/workspace/test.txt');

  // Cleanup
  await sandbox.kill();
}

main().catch(console.error);