Connect to sandboxes that are already running. This is useful when you need to reconnect to a sandbox after your application restarts, or when working with sandboxes created by other processes.
Prerequisites
Before you begin, make sure you have:
- Existing sandbox - A sandbox that was previously created (see Creating Sandboxes)
- Sandbox ID - The ID of the sandbox you want to connect to
- API key - Your HopX API key configured
Overview
The connect() method allows you to reconnect to an existing sandbox by its ID. When connecting:
- If sandbox is paused → Automatically resumes it and refreshes JWT token
- If sandbox is stopped → Raises an error (cannot connect to stopped sandbox)
- If sandbox is running → Refreshes JWT token for agent authentication
- JWT token → Automatically refreshed and stored for agent operations
You cannot connect to a stopped sandbox. Use sandbox.start() first, or create a new sandbox.
Basic Connection
Connect to an existing sandbox by ID:
from hopx_ai import Sandbox
# Connect to existing sandbox
sandbox = Sandbox.connect("1763309903rt5vs4lm")
# Get current information
info = sandbox.get_info()
print(f"Status: {info.status}")
print(f"URL: {info.public_host}")
Expected Output:Status: running
URL: https://1763309903rt5vs4lm.hopx.dev
import { Sandbox } from '@hopx-ai/sdk';
// Connect to existing sandbox
const sandbox = await Sandbox.connect('1763309903rt5vs4lm');
// Get current information
const info = await sandbox.getInfo();
console.log(`Status: ${info.status}`);
console.log(`URL: ${info.publicHost}`);
Expected Output:Status: running
URL: https://1763309903rt5vs4lm.hopx.dev
Finding Sandbox IDs
You can find sandbox IDs by listing your sandboxes:
from hopx_ai import Sandbox
# List sandboxes to find IDs
sandboxes = Sandbox.list(status="running")
for sandbox in sandboxes:
info = sandbox.get_info()
print(f"ID: {sandbox.sandbox_id}, Status: {info.status}")
# Connect to the first one
if sandboxes:
sandbox = Sandbox.connect(sandboxes[0].sandbox_id)
print(f"Connected to: {sandbox.sandbox_id}")
Expected Output:ID: 1763309903rt5vs4lm, Status: running
ID: 1763309904rt5vs4ln, Status: running
Connected to: 1763309903rt5vs4lm
import { Sandbox } from '@hopx-ai/sdk';
// List sandboxes to find IDs
const sandboxes = await Sandbox.list({ status: 'running' });
for (const sandbox of sandboxes) {
const info = await sandbox.getInfo();
console.log(`ID: ${sandbox.sandboxId}, Status: ${info.status}`);
}
// Connect to the first one
if (sandboxes.length > 0) {
const sandbox = await Sandbox.connect(sandboxes[0].sandboxId);
console.log(`Connected to: ${sandbox.sandboxId}`);
}
Handling Different States
The connect() method handles different sandbox states automatically:
from hopx_ai import Sandbox
from hopx_ai.errors import HopxError
try:
sandbox = Sandbox.connect("sandbox_id")
info = sandbox.get_info()
if info.status == "paused":
print("Sandbox was paused - automatically resumed")
elif info.status == "running":
print("Sandbox is running - ready to use")
except HopxError as e:
if "stopped" in str(e).lower():
print("Cannot connect to stopped sandbox")
print("Use sandbox.start() first, or create a new sandbox")
import { Sandbox } from '@hopx-ai/sdk';
try {
const sandbox = await Sandbox.connect('sandbox_id');
const info = await sandbox.getInfo();
if (info.status === 'paused') {
console.log('Sandbox was paused - automatically resumed');
} else if (info.status === 'running') {
console.log('Sandbox is running - ready to use');
}
} catch (error) {
if (error.message.includes('stopped')) {
console.error('Cannot connect to stopped sandbox');
console.error('Use sandbox.start() first, or create a new sandbox');
}
}
Complete Workflow Example
Here’s a complete example showing the connect workflow:
from hopx_ai import Sandbox
# Step 1: List running sandboxes
sandboxes = Sandbox.list(status="running")
print(f"Found {len(sandboxes)} running sandboxes")
# Step 2: Connect to a specific sandbox
if sandboxes:
sandbox_id = sandboxes[0].sandbox_id
print(f"\nConnecting to: {sandbox_id}")
sandbox = Sandbox.connect(sandbox_id)
info = sandbox.get_info()
print(f"✅ Connected successfully")
print(f" Status: {info.status}")
print(f" Template: {info.template_name}")
print(f" URL: {info.public_host}")
# Step 3: Use the sandbox
result = sandbox.run_code('print("Reconnected!")')
print(f" Output: {result.stdout}")
import { Sandbox } from '@hopx-ai/sdk';
// Step 1: List running sandboxes
const sandboxes = await Sandbox.list({ status: 'running' });
console.log(`Found ${sandboxes.length} running sandboxes`);
// Step 2: Connect to a specific sandbox
if (sandboxes.length > 0) {
const sandboxId = sandboxes[0].sandboxId;
console.log(`\nConnecting to: ${sandboxId}`);
const sandbox = await Sandbox.connect(sandboxId);
const info = await sandbox.getInfo();
console.log('✅ Connected successfully');
console.log(` Status: ${info.status}`);
console.log(` Template: ${info.templateName}`);
console.log(` URL: ${info.publicHost}`);
// Step 3: Use the sandbox
const result = await sandbox.runCode('print("Reconnected!")');
console.log(` Output: ${result.stdout}`);
}
Error Handling
Handle connection errors appropriately:
from hopx_ai import Sandbox
from hopx_ai.errors import NotFoundError, HopxError
try:
sandbox = Sandbox.connect("invalid_id")
except NotFoundError:
print("Sandbox not found")
except HopxError as e:
if "stopped" in str(e).lower():
print("Sandbox is stopped - cannot connect")
print("Start it first: sandbox.start()")
else:
print(f"Connection error: {e}")
import { Sandbox } from '@hopx-ai/sdk';
import { NotFoundError, HopxError } from '@hopx-ai/sdk';
try {
const sandbox = await Sandbox.connect('invalid_id');
} catch (error) {
if (error instanceof NotFoundError) {
console.error('Sandbox not found');
} else if (error instanceof HopxError) {
if (error.message.includes('stopped')) {
console.error('Sandbox is stopped - cannot connect');
console.error('Start it first: sandbox.start()');
} else {
console.error(`Connection error: ${error.message}`);
}
}
}
Use Cases
Reconnecting After Application Restart
from hopx_ai import Sandbox
import os
# Store sandbox ID (e.g., in environment variable or database)
sandbox_id = os.getenv("SANDBOX_ID")
if sandbox_id:
# Reconnect to existing sandbox
sandbox = Sandbox.connect(sandbox_id)
print(f"Reconnected to: {sandbox.sandbox_id}")
else:
# Create new sandbox
sandbox = Sandbox.create(template="code-interpreter")
print(f"Created new: {sandbox.sandbox_id}")
# Store ID for later
os.environ["SANDBOX_ID"] = sandbox.sandbox_id
import { Sandbox } from '@hopx-ai/sdk';
// Store sandbox ID (e.g., in environment variable or database)
const sandboxId = process.env.SANDBOX_ID;
if (sandboxId) {
// Reconnect to existing sandbox
const sandbox = await Sandbox.connect(sandboxId);
console.log(`Reconnected to: ${sandbox.sandboxId}`);
} else {
// Create new sandbox
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
console.log(`Created new: ${sandbox.sandboxId}`);
// Store ID for later
process.env.SANDBOX_ID = sandbox.sandboxId;
}
Working with Shared Sandboxes
from hopx_ai import Sandbox
# Multiple processes can connect to the same sandbox
# Process 1: Creates sandbox
sandbox1 = Sandbox.create(template="code-interpreter")
sandbox_id = sandbox1.sandbox_id
print(f"Created: {sandbox_id}")
# Process 2: Connects to same sandbox
sandbox2 = Sandbox.connect(sandbox_id)
print(f"Connected: {sandbox2.sandbox_id}")
# Both can use the same sandbox
result1 = sandbox1.run_code('x = 1')
result2 = sandbox2.run_code('print(x)') # Can access shared state
import { Sandbox } from '@hopx-ai/sdk';
// Multiple processes can connect to the same sandbox
// Process 1: Creates sandbox
const sandbox1 = await Sandbox.create({ template: 'code-interpreter' });
const sandboxId = sandbox1.sandboxId;
console.log(`Created: ${sandboxId}`);
// Process 2: Connects to same sandbox
const sandbox2 = await Sandbox.connect(sandboxId);
console.log(`Connected: ${sandbox2.sandboxId}`);
// Both can use the same sandbox
await sandbox1.runCode('x = 1');
await sandbox2.runCode('print(x)'); // Can access shared state
JWT Token Management
When you connect to a sandbox, the SDK automatically:
- Refreshes the JWT token for agent authentication
- Stores the token for subsequent agent operations
- Handles token expiration automatically
You don’t need to manage tokens manually - the SDK handles this for you.
from hopx_ai import Sandbox
# Connect - token is automatically refreshed
sandbox = Sandbox.connect("sandbox_id")
# Token is stored and used automatically for agent calls
result = sandbox.run_code('print("Hello")') # Uses stored token
# Manually refresh if needed
sandbox.refresh_token()
import { Sandbox } from '@hopx-ai/sdk';
// Connect - token is automatically refreshed
const sandbox = await Sandbox.connect('sandbox_id');
// Token is stored and used automatically for agent calls
const result = await sandbox.runCode('print("Hello")'); // Uses stored token
// Manually refresh if needed
await sandbox.refreshToken();
Implementation
Next Steps