Run OpenCode AI coding agent in E2B sandboxes.
This library allows you to spin up isolated cloud sandboxes with OpenCode running inside, send messages, and interact with an AI coding agent programmatically.
- Run OpenCode in isolated E2B cloud sandboxes
- Interactive CLI for testing your E2B connection
- Stateful conversation sessions
- Upload/download files to the sandbox workspace
- Execute shell commands in the sandbox
- Full access to OpenCode's capabilities (code generation, file editing, etc.)
npm install- E2B API Key: Get from e2b.dev/dashboard
- LLM Provider API Key: Anthropic, OpenAI, or another supported provider
Copy .env.example to .env and add your API keys:
cp .env.example .envEdit .env:
E2B_API_KEY=e2b_***
ANTHROPIC_API_KEY=sk-ant-***
The fastest way to test your E2B connection:
npm run consoleThis starts an interactive terminal session where you can chat with OpenCode running in an E2B sandbox.
Console Commands:
| Command | Description |
|---|---|
/clear |
Start a new session |
/files |
List files in workspace |
/run <cmd> |
Run a shell command |
/upload <file> <text> |
Upload a file |
/download <file> |
Download a file |
/status |
Show sandbox status |
/exit |
Exit the CLI |
CLI Options:
npm run console -- --help # Show all options
npm run console -- --model claude-haiku-4-20250514 # Use a specific model
npm run console -- --template base # Use a specific E2B template
npm run console -- --timeout 600000 # Set timeout (ms)import { createChat } from "./src/index.js";
const chat = createChat({
providerApiKey: process.env.ANTHROPIC_API_KEY,
sandbox: {
envVars: {
ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,
},
},
opencode: {
providerId: "anthropic",
modelId: "claude-sonnet-4-20250514",
},
});
// Initialize (starts the sandbox - takes ~30-60 seconds first time)
await chat.initialize();
// Send messages
const response = await chat.send("Write a Python function to calculate fibonacci numbers");
console.log(response);
// Upload files for OpenCode to work with
await chat.uploadFile("main.py", "print('hello')");
const review = await chat.send("Review the main.py file I uploaded");
// Cleanup
await chat.close();For more control, use OpenCodeRuntime:
import { createRuntime } from "./src/index.js";
const runtime = createRuntime({
providerApiKey: process.env.ANTHROPIC_API_KEY,
sandbox: {
envVars: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY },
},
opencode: {
providerId: "anthropic",
modelId: "claude-sonnet-4-20250514",
},
});
await runtime.start();
// Send messages
const response = await runtime.sendMessage("Hello!");
console.log(runtime.extractText(response.parts));
// File operations
await runtime.uploadFile("test.js", "console.log('hello')");
await runtime.runCommand("node test.js");
await runtime.stop();npm run consolenpm run testnpm run exampleCreates a new chat instance with high-level API.
interface ChatOptions {
sandbox?: {
template?: string; // E2B template ID (default: "opencode-e2b-sandbox")
timeout?: number; // Timeout in ms (default: 300000)
envVars?: Record<string, string>; // Pass API keys here!
metadata?: Record<string, string>;
};
opencode?: {
providerId?: string; // LLM provider (default: "anthropic")
modelId?: string; // Model ID (default: "claude-sonnet-4-20250514")
};
providerApiKey?: string; // API key for the LLM provider
}| Method | Description |
|---|---|
initialize() |
Start the sandbox and OpenCode server (~30-60s) |
send(message) |
Send a message and wait for response |
getHistory() |
Get conversation history |
clear() |
Start a new session |
abort() |
Abort current operation |
uploadFile(name, content) |
Upload a file to the workspace |
downloadFile(name) |
Download a file from the workspace |
runCommand(cmd) |
Run a shell command in the sandbox |
listFiles() |
List files in workspace |
close() |
Stop the sandbox and cleanup |
Creates a runtime instance for lower-level control.
interface RuntimeConfig {
sandbox?: SandboxConfig;
opencode?: OpenCodeConfig;
providerApiKey?: string;
}
interface RuntimeEvents {
onLog?: (message: string) => void;
onServerLog?: (type: "stdout" | "stderr", message: string) => void;
onSandboxStarted?: (sandboxId: string) => void;
onServerReady?: () => void;
onServerCrashed?: () => void;
onSessionCreated?: (sessionId: string) => void;
}| Method | Description |
|---|---|
start() |
Start sandbox, install OpenCode, start server |
stop() |
Stop and cleanup the sandbox |
isRunning() |
Check if runtime is running |
restartServer() |
Restart the OpenCode server |
sendMessage(text) |
Send a message and wait for response |
getMessages() |
Get messages in current session |
createSession(title?) |
Create a new session |
abort() |
Abort current operation |
uploadFile(name, content) |
Upload a file |
downloadFile(name) |
Download a file |
runCommand(cmd) |
Run a shell command |
listFiles() |
List workspace files |
┌──────────────────┐ ┌─────────────────────────────┐
│ Your App │ │ E2B Sandbox │
│ │ HTTP/curl │ │
│ ┌────────────┐ │ ◄────────────────► │ ┌─────────────────────┐ │
│ │ Chat │ │ │ │ OpenCode Server │ │
│ │ or Runtime │ │ │ │ (port 4096) │ │
│ └────────────┘ │ │ └─────────────────────┘ │
│ │ │ │ │ │
│ ▼ │ │ ▼ │
│ ┌────────────┐ │ │ ┌─────────────────────┐ │
│ │ OpenCode │ │ │ │ /home/user/workspace│ │
│ │ Runtime │──│────────────────────│──│ (files) │ │
│ └────────────┘ │ │ └─────────────────────┘ │
└──────────────────┘ └─────────────────────────────┘
- E2B Sandbox starts - A lightweight VM spins up (~150ms)
- OpenCode is installed - npm installs opencode-ai globally (~20-30s)
- OpenCode server starts -
opencode serveruns on port 4096 - Your app sends messages - Via HTTP to the OpenCode server
- OpenCode responds - Can edit files, run commands, generate code
| Variable | Description |
|---|---|
E2B_API_KEY |
Your E2B API key |
ANTHROPIC_API_KEY |
Anthropic API key (for Claude models) |
OPENAI_API_KEY |
OpenAI API key (for GPT models) |
MIT