Skip to content

About

Run OpenCode AI coding agent in E2B cloud sandboxes

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

OpenCode E2B

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.

Features

  • 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.)

Installation

npm install

Prerequisites

  1. E2B API Key: Get from e2b.dev/dashboard
  2. LLM Provider API Key: Anthropic, OpenAI, or another supported provider

Setup

Copy .env.example to .env and add your API keys:

cp .env.example .env

Edit .env:

E2B_API_KEY=e2b_***
ANTHROPIC_API_KEY=sk-ant-***

Quick Start

Interactive Console (Recommended for Testing)

The fastest way to test your E2B connection:

npm run console

This 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)

Programmatic Usage

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();

Using the Runtime Directly

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();

Running Examples

Interactive Console

npm run console

Simple Test

npm run test

Programmatic Example

npm run example

API Reference

createChat(options)

Creates 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
}

Chat Methods

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

createRuntime(config, events)

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;
}

Runtime Methods

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

Architecture

┌──────────────────┐                    ┌─────────────────────────────┐
│   Your App       │                    │       E2B Sandbox           │
│                  │     HTTP/curl      │                             │
│  ┌────────────┐  │ ◄────────────────► │  ┌─────────────────────┐    │
│  │ Chat       │  │                    │  │ OpenCode Server     │    │
│  │ or Runtime │  │                    │  │ (port 4096)         │    │
│  └────────────┘  │                    │  └─────────────────────┘    │
│        │         │                    │            │                │
│        ▼         │                    │            ▼                │
│  ┌────────────┐  │                    │  ┌─────────────────────┐    │
│  │ OpenCode   │  │                    │  │ /home/user/workspace│    │
│  │ Runtime    │──│────────────────────│──│ (files)             │    │
│  └────────────┘  │                    │  └─────────────────────┘    │
└──────────────────┘                    └─────────────────────────────┘

How It Works

  1. E2B Sandbox starts - A lightweight VM spins up (~150ms)
  2. OpenCode is installed - npm installs opencode-ai globally (~20-30s)
  3. OpenCode server starts - opencode serve runs on port 4096
  4. Your app sends messages - Via HTTP to the OpenCode server
  5. OpenCode responds - Can edit files, run commands, generate code

Environment Variables

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)

License

MIT

About

Run OpenCode AI coding agent in E2B cloud sandboxes

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages