How to Set Up CubeSandbox for AI Agents: Complete Configuration Guide
CubeSandbox is a high-performance sandbox service built on RustVMM, KVM, and eBPF that provides sub-60ms cold starts and E2B-compatible APIs, enabling AI agents to run isolated code with hardware-level security.
CubeSandbox by TencentCloud provides production-grade isolation for AI agents through micro-VM architecture. When you set up CubeSandbox for AI agents, you deploy a distributed system comprising stateless gateways, node daemons, and virtual switches that collectively deliver hardware-level isolation with full E2B SDK compatibility. This guide covers the architecture, deployment options, and code integration necessary to run LLM-driven workloads securely.
Architecture Overview
CubeSandbox orchestrates several tightly-coupled components to deliver sub-60ms cold starts and secure isolation. Understanding these components helps you configure the system correctly for your AI agent workloads.
Core Components
The platform consists of eight primary components:
- CubeAPI: A stateless HTTP gateway written in Rust that accepts sandbox requests and maintains drop-in compatibility with the E2B REST API. Located in
CubeAPI/README.md. - CubeMaster: The global orchestrator that schedules sandbox creation across clusters and stores template metadata. See
cube-master/README.md. - CubeProxy: A reverse-proxy terminating TLS and routing requests to sandbox instances using the
cube.appdomain. Configuration details are inCubeProxy/README.md. - Cubelet: The node-local daemon managing the full lifecycle of sandbox VMs (create, pause, resume, destroy) and handling I/O for the sandbox filesystem. Reference implementation in
Cubelet/README.md. - CubeVS: An eBPF-based virtual switch enforcing network isolation and per-sandbox egress policies. Documented in
CubeVS/README.md. - CubeEgress: An OpenResty (nginx + Lua) L7 gateway implementing domain allow-lists, credential injection, and audit logging. Located in
CubeEgress/README.md. - CubeHypervisor + CubeShim: A thin KVM-based micro-VM layer (Cloud-hypervisor fork) with a containerd shim v2 API for runtime integration. See
hypervisor/README.md. - AgentHub: An optional collection of digital assistants (e.g., OpenClaw) shipping pre-built sandbox images for LLM-driven agents. Found in
agent/README.md.
Why It Works for AI Agents
CubeSandbox addresses three critical requirements for AI agent deployment:
- Fast Startup: Fresh micro-VMs boot in under 60 milliseconds and consume less than 5 MiB of RAM, allowing thousands of agents to share a single node.
- Hardware Isolation: Each sandbox runs its own kernel, ensuring that compromised LLM-generated scripts cannot escape the VM boundary.
- E2B Compatibility: The REST API (
/sandboxes,/execute,/files) mirrors the public E2B API, requiring only theCUBE_API_URLenvironment variable to switch existing agent code.
Deployment Prerequisites
Before running AI agent workloads, you must configure the underlying virtualization layer. CubeSandbox supports two deployment modes depending on your infrastructure.
Bare-Metal or KVM-Enabled Servers
If your host exposes /dev/kvm, proceed with the standard installation:
- Verify KVM availability:
ls /dev/kvm - Run the one-click installer from
docs/guide/quickstart.md - Set environment variables pointing to your CubeAPI endpoint
PVM-Enabled Cloud Servers
When running on cloud VMs without direct KVM access, install the PVM host kernel (a page-table-based nested-virtualisation layer):
- Follow the instructions in
docs/guide/pvm-deploy.mdto install the PVM kernel - Set
CUBE_PVM_ENABLE=1before running the installer - The PVM layer provides nested virtualization without requiring
/dev/kvmexposure
Configuring the Python SDK
The sdk/python directory contains the official Python client. Install the SDK and configure environment variables to connect your AI agents.
Basic SDK Setup
Install the package and configure the API endpoint:
# Install the SDK
# pip install cubesandbox
from cubesandbox import Sandbox
# Required environment variables:
# export CUBE_API_URL=http://<control-node>:3000
# export CUBE_TEMPLATE_ID=tpl-xxxxxxxxxxxxxxx
with Sandbox.create() as sb:
result = sb.run_code("x = 41\nx + 1")
print("Result:", result.text) # Output: 42
# Stream stdout in real time
sb.run_code(
'for i in range(3): print(i)',
on_stdout=lambda msg: print("out:", msg.text),
)
E2B-Compatible Integration
For existing AI agents using the E2B SDK, redirect the API URL to your CubeSandbox deployment:
import os
from e2b_code_interpreter import Sandbox
os.environ["E2B_API_URL"] = "http://127.0.0.1:3000"
os.environ["E2B_API_KEY"] = "any-placeholder"
os.environ["CUBE_TEMPLATE_ID"] = "tpl-xxxxxxxxxxxx"
with Sandbox.create(template=os.getenv("CUBE_TEMPLATE_ID")) as sandbox:
out = sandbox.run_code("print('hello from CubeSandbox')")
print(out)
Implementing Security Policies
AI agents often require external API access while maintaining credential security. CubeSandbox implements network policies through CubeEgress and CubeVS.
Credential Injection and Domain Restrictions
The CubeEgress/README.md documents the L7 gateway that injects secrets without exposing them to sandbox processes:
from cubesandbox import Sandbox, Rule, Match, Action, Inject
rules = [
Rule(
name="secure_api",
match=Match(
scheme="https",
host="api.example.com",
path="/v1/*",
method=["POST"],
),
action=Action(
allow=True,
inject=[
Inject(header="Authorization", format="Bearer ${SECRET}", secret="sk_abcdef")
],
),
)
]
with Sandbox.create(network={"allow_out": ["api.example.com"], "rules": rules}) as sb:
sb.run_code("""import requests
requests.post("https://api.example.com/v1/task", json={"msg":"hi"})""")
Mounting Persistent Storage
For AI agents requiring file persistence, use the copy-on-write (CubeCoW) snapshot engine implemented in Cubelet/storage/* to mount host directories:
import json
from cubesandbox import Sandbox
mounts = json.dumps([{"hostPath": "/data/shared", "mountPath": "/mnt/data"}])
with Sandbox.create(metadata={"host-mount": mounts}) as sb:
sb.run_code('open("/mnt/data/hello.txt").read()')
Summary
Setting up CubeSandbox for AI agents involves deploying a micro-VM architecture that balances speed with security:
- Choose your virtualization mode: Use bare-metal KVM when available, or enable PVM for nested cloud virtualization by following
docs/guide/pvm-deploy.md. - Leverage E2B compatibility: Existing AI agents require only the
CUBE_API_URLenvironment variable to migrate from public E2B to private CubeSandbox instances. - Secure credentials: Implement network policies through
CubeEgressto inject API keys without exposing them to sandbox processes. - Optimize storage: Use the CubeCoW snapshot engine in
Cubelet/storage/*for instant clone and rollback capabilities essential for agent state management.
Frequently Asked Questions
How does CubeSandbox achieve sub-60ms cold starts?
CubeSandbox utilizes a fork of Cloud-hypervisor (documented in hypervisor/README.md) combined with the CubeCoW snapshot engine in Cubelet/storage/* to create lightweight micro-VMs that boot in under 60 milliseconds while consuming less than 5 MiB of RAM. This architecture allows thousands of AI agent sandboxes to coexist on a single node without the overhead of traditional virtualization.
Can I use CubeSandbox without dedicated KVM hardware?
Yes. When deploying on cloud servers without /dev/kvm access, install the PVM host kernel as described in docs/guide/pvm-deploy.md and set CUBE_PVM_ENABLE=1. This page-table-based nested virtualization layer allows CubeSandbox to run on standard cloud VMs while maintaining the same isolation guarantees as bare-metal KVM deployments.
How do I migrate existing E2B-based AI agents to CubeSandbox?
Migration requires only configuration changes, not code modifications. Set the E2B_API_URL or CUBE_API_URL environment variable to point to your CubeAPI endpoint (typically http://<control-node>:3000), as implemented in CubeAPI/README.md. The REST API endpoints (/sandboxes, /execute, /files) mirror the public E2B specification, ensuring full backward compatibility with existing agent codebases.
Where are credentials stored when using network policies?
Credentials are stored in the CubeEgress vault and injected at the L7 gateway layer (OpenResty/nginx + Lua) as documented in CubeEgress/README.md. Secrets never enter the sandbox filesystem or environment variables; instead, the eBPF-based CubeVS component intercepts outbound HTTPS requests and injects authorization headers after the sandbox process initiates the connection, preventing credential exfiltration even if the agent executes malicious code.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →