Skip to main content
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:
  • Python
  • JavaScript
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

Finding Sandbox IDs

You can find sandbox IDs by listing your sandboxes:
  • Python
  • JavaScript
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

Handling Different States

The connect() method handles different sandbox states automatically:
  • Python
  • JavaScript
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")

Complete Workflow Example

Here’s a complete example showing the connect workflow:
  • Python
  • JavaScript
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}")

Error Handling

Handle connection errors appropriately:
  • Python
  • JavaScript
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}")

Use Cases

Reconnecting After Application Restart

  • Python
  • JavaScript
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

Working with Shared Sandboxes

  • Python
  • JavaScript
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

JWT Token Management

When you connect to a sandbox, the SDK automatically:
  1. Refreshes the JWT token for agent authentication
  2. Stores the token for subsequent agent operations
  3. Handles token expiration automatically
You don’t need to manage tokens manually - the SDK handles this for you.
  • Python
  • JavaScript
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()

Implementation

Next Steps