e2b

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 29, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

README

E2B Go SDK

Go Reference test integration License

A Go client for the E2B sandbox platform, ported from the official Python and JavaScript SDKs.

Unofficial, community-maintained port. This module is not published by the E2B team — it tracks the upstream spec but is independent of them. Report SDK issues here; report E2B platform issues upstream.

Install

go get github.com/eric642/e2b-go-sdk

Quick start

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/eric642/e2b-go-sdk"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	defer cancel()

	sbx, err := e2b.Create(ctx, e2b.CreateOptions{
		Template: "base",
		Timeout:  5 * time.Minute,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer sbx.Kill(ctx)

	handle, err := sbx.Commands.Run(ctx, "sh", e2b.RunOptions{
		Args: []string{"-c", "echo hello"},
	})
	if err != nil {
		log.Fatal(err)
	}
	result, err := handle.Wait(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(result.Stdout) // hello
}

Authentication

The SDK reads credentials from the environment:

Variable Purpose
E2B_API_KEY Team API key (X-API-Key header)
E2B_ACCESS_TOKEN User access token (Authorization: Bearer)
E2B_DOMAIN Override the default e2b.app domain
E2B_API_URL Full override of the control-plane URL
E2B_SANDBOX_URL Override the envd URL (used for tunneling/tests)
E2B_DEBUG true targets http://localhost:3000

Pass an explicit e2b.Config to any *Options struct to override.

Packages

Path Description
github.com/eric642/e2b-go-sdk Core Sandbox, Commands, Filesystem, Pty, Git
github.com/eric642/e2b-go-sdk/template Template builder + ReadyCmd helpers
github.com/eric642/e2b-go-sdk/volume Persistent volume client

Architecture

  • Control-plane REST at https://api.<domain> — generated from spec/openapi.yml using oapi-codegen.
  • envd Connect-RPC at https://49983-<sandboxID>.<domain> — generated from spec/envd/**/*.proto using connectrpc.com/connect.
  • envd plain HTTP (/files, /metrics, /envs) — generated from spec/envd/envd.yaml.
  • Volume content REST — generated from spec/openapi-volumecontent.yml.

All generated code lives under internal/ and is not part of the public API.

Versioning & regenerating clients

This SDK will track upstream e2b-dev/E2B e2b@X.Y.Z tags 1:1 once aligned. Pre-alignment (v0.x) releases pin an exact upstream commit instead; see spec/E2B_VERSION and make version for what any given build is compiled against.

make tools                                   # one-time: install buf, oapi-codegen, protoc-gen-*
make sync-spec E2B_TAG=e2b@2.19.0            # pin upstream spec (fetches tags)
make codegen                                 # regenerate internal/ clients

# Convenience: sync + regen in one step. Defaults to the newest e2b@* tag.
make regen
make regen E2B_TAG=e2b@2.19.0

# Inspect what you're currently building against:
make version

sync-spec.sh copies the relevant spec files from the E2B/ submodule into ./spec/ (so the submodule can stay detached at any ref without affecting builds), writes spec/E2B_VERSION and internal/version/upstream.go, and updates the top-level VERSION file.

Pass --skip-fetch to work offline (reuses the submodule's existing local refs). See CHANGELOG.md for the full release workflow.

Examples

Path What it shows
examples/basic Minimal Create / Commands.Run loop
examples/terminal Interactive PTY session
examples/template Programmatic template.Builder (v3 build API)
examples/lifecycle Full template + sandbox lifecycle on the v3 API
examples/lifecycle_v2 Same lifecycle against legacy /v2/templates (self-hosted ≤ 2.1)
examples/selfhosted Running against a self-hosted E2B deployment
examples/desktop VNC desktop template — split noVNC URLs for terminal and browser,
PTY mirrored into tmux, on-demand chromium launch

Run any example with source ./.env && go run ./examples/<name>.

Desktop example

examples/desktop builds the e2b.Dockerfile template and exposes two separate noVNC URLs — one per X display — so the terminal and browser don't share a desktop:

  • :06080 — an xterm attached to the shared tmux -L main session. Any Pty.Create opened through the SDK appears here in real time.
  • :16081 — launched on demand by launchBrowser, which starts chromium with --no-sandbox --disable-dev-shm-usage on the browser display and blocks until the window is mapped.

Set E2B_TEMPLATE_ID to reuse an already-built template (skips build + teardown). Set DESKTOP_BROWSER_URL to override the page chromium opens. The driver blocks after printing both URLs so you can open them; hit Ctrl+C to tear the sandbox + template down.

Testing

go test ./...                    # unit tests (no network)
go test -tags=integration ./...  # integration tests (requires E2B_API_KEY)

CI is split across two workflows:

  • .github/workflows/test.yml — unit tests on every push & PR.
  • .github/workflows/integration.yml — integration tests on pushes to main/master and manual workflow_dispatch. Fork PRs don't get access to secrets.E2B_API_KEY, so this workflow simply isn't scheduled for them (shows as "skipped" in the check UI).

Scope & status

v1 implements the core sandbox surface:

  • Create, Connect, Kill, Pause, CreateSnapshot, GetInfo, GetMetrics, SetTimeout
  • Commands.Run / Start / Connect / List / Kill / SendStdin / CloseStdin
  • Pty.Create / Resize / SendInput / Kill
  • Filesystem Read / Write / List / Stat / Move / Remove / MakeDir / Watch
  • Git Clone / Add / Commit / Push / Pull / Status / Branches / …
  • Volume Create / Connect / List / ReadFile / WriteFile / Remove / MakeDir / Delete
  • template.Builder serialization, server-side build orchestration (v3 Build / BuildStream / BuildInBackground), and legacy v2 counterparts (BuildV2 / BuildStreamV2 / BuildInBackgroundV2)
  • template.Client.List / Get / Delete / SetPublic / GetBuildLogs

License

Apache 2.0, matching upstream E2B.

Documentation

Overview

Package e2b is a Go client for the E2B sandbox platform.

It ports the public surface of the Python (https://github.com/e2b-dev/E2B/tree/main/packages/python-sdk) and JavaScript (https://github.com/e2b-dev/E2B/tree/main/packages/js-sdk) SDKs to idiomatic Go: blocking APIs with context.Context, channels for streaming output, and typed errors.

Quick start

ctx := context.Background()
sbx, err := e2b.Create(ctx, e2b.CreateOptions{
	Template: "base",
	Timeout:  5 * time.Minute,
})
if err != nil {
	log.Fatal(err)
}
defer sbx.Kill(ctx)

handle, err := sbx.Commands.Run(ctx, "echo", e2b.RunOptions{Args: []string{"hello"}})
if err != nil {
	log.Fatal(err)
}
result, _ := handle.Wait(ctx)
fmt.Println(result.Stdout) // hello

Authentication

The SDK reads credentials from the environment by default:

  • E2B_API_KEY: team API key (X-API-Key header)
  • E2B_ACCESS_TOKEN: user access token (Authorization: Bearer)
  • E2B_DOMAIN: defaults to e2b.app
  • E2B_DEBUG: when "true", targets http://localhost:3000

Pass an explicit Config to override.

Sub-packages

  • template: fluent builder for sandbox templates (serialization only in v1)
  • volume: client for persistent volumes

Index

Constants

View Source
const (
	DefaultRequestTimeout    = 60 * time.Second
	KeepAlivePingIntervalSec = 50
	KeepAlivePingHeader      = "Keepalive-Ping-Interval"
	DefaultDomain            = "e2b.app"
)

Default request timeout (matches Python/JS SDK).

View Source
const (
	DefaultSandboxTimeout = 300 * time.Second
	DefaultTemplate       = "base"
)

Defaults mirrored from the Python/JS SDKs.

View Source
const AllTraffic = "0.0.0.0/0"

AllTraffic is the CIDR range representing all IPv4 traffic.

View Source
const SDKVersion = version.SDKVersion

SDKVersion is this SDK's release version. It is kept in lockstep with the upstream python-sdk tag (see spec/E2B_VERSION) and regenerated by scripts/sync-spec.sh.

View Source
const UpstreamTag = version.UpstreamTag

UpstreamTag identifies the E2B git tag whose spec was used to generate the REST/Connect-RPC clients in internal/.

Variables

View Source
var (
	ErrTemplateBuild  = errors.New("template build failed")
	ErrTemplateUpload = errors.New("template file upload failed")
	ErrTemplate       = errors.New("template error")
)
View Source
var ErrNotImplemented = errors.New("e2b: not implemented")

ErrNotImplemented is returned by stubbed features pending future work.

Functions

func Kill

func Kill(ctx context.Context, sandboxID string, opts ConnectOptions) (bool, error)

Kill terminates a sandbox by ID. Returns false (nil error) if the sandbox was already gone.

Types

type AuthenticationError

type AuthenticationError struct {
	Message string
	// contains filtered or unexported fields
}

AuthenticationError reports invalid or missing credentials.

func (*AuthenticationError) Error

func (e *AuthenticationError) Error() string

type BuildError

type BuildError struct {
	Message string
	Cause   error
	// contains filtered or unexported fields
}

BuildError reports a template build failure.

func (*BuildError) Error

func (e *BuildError) Error() string

func (*BuildError) Unwrap

func (e *BuildError) Unwrap() error

type CommandExitError

type CommandExitError struct {
	Result CommandResult
	// contains filtered or unexported fields
}

CommandExitError is returned by CommandHandle.Wait when a command exits non-zero. It embeds CommandResult so callers can inspect output.

func (*CommandExitError) Error

func (e *CommandExitError) Error() string

type CommandHandle

type CommandHandle struct {
	// contains filtered or unexported fields
}

CommandHandle represents a running command. Events arrive on the channels returned by Stdout() and Stderr(); the channels close when the command exits or the stream fails. Call Wait to block and collect the final exit code.

func (*CommandHandle) Kill

func (h *CommandHandle) Kill(ctx context.Context) (bool, error)

Kill signals the running command.

func (*CommandHandle) PID

func (h *CommandHandle) PID() uint32

PID returns the command's process ID once known.

func (*CommandHandle) PtyOutput

func (h *CommandHandle) PtyOutput() <-chan []byte

PtyOutput returns a channel of PTY data. Empty for non-PTY commands.

func (*CommandHandle) SendStdin

func (h *CommandHandle) SendStdin(ctx context.Context, data []byte) error

SendStdin writes data to the command's stdin.

func (*CommandHandle) Stderr

func (h *CommandHandle) Stderr() <-chan []byte

Stderr returns a channel of stderr byte slices.

func (*CommandHandle) Stdout

func (h *CommandHandle) Stdout() <-chan []byte

Stdout returns a channel of stdout byte slices. The channel is closed when the command exits.

func (*CommandHandle) Wait

func (h *CommandHandle) Wait(ctx context.Context) (*CommandResult, error)

Wait blocks until the command finishes, returns a *CommandResult, and wraps non-zero exit codes in a *CommandExitError.

type CommandResult

type CommandResult struct {
	Stdout   string
	Stderr   string
	ExitCode int32
	Error    string
}

CommandResult reports the outcome of a finished command.

type Commands

type Commands struct {
	// contains filtered or unexported fields
}

Commands exposes command-execution endpoints (fully implemented in commands_impl.go).

func (*Commands) CloseStdin

func (c *Commands) CloseStdin(ctx context.Context, pid uint32) error

CloseStdin closes the stdin side of the process.

func (*Commands) Connect

func (c *Commands) Connect(ctx context.Context, pid uint32) (*CommandHandle, error)

Connect attaches to a running process by PID and streams remaining output.

func (*Commands) Kill

func (c *Commands) Kill(ctx context.Context, pid uint32) (bool, error)

Kill signals the command identified by PID.

func (*Commands) List

func (c *Commands) List(ctx context.Context) ([]ProcessInfo, error)

List returns all processes currently running inside the sandbox.

func (*Commands) Run

func (c *Commands) Run(ctx context.Context, cmd string, opts RunOptions) (*CommandHandle, error)

Run executes cmd and blocks until it exits (unless opts.Background is true, in which case Run returns a handle immediately). Callers may observe output through the returned handle's channels or the OnStdout/OnStderr callbacks.

func (*Commands) SendStdin

func (c *Commands) SendStdin(ctx context.Context, pid uint32, data []byte) error

SendStdin writes to the stdin of the running process.

func (*Commands) Start

func (c *Commands) Start(ctx context.Context, cmd string, opts RunOptions) (*CommandHandle, error)

Start launches cmd and returns a live *CommandHandle.

type Config

type Config struct {
	// APIKey authenticates team-scoped requests (X-API-Key header).
	// Defaults to $E2B_API_KEY.
	APIKey string

	// AccessToken authenticates user-scoped requests (Authorization: Bearer).
	// Defaults to $E2B_ACCESS_TOKEN.
	AccessToken string

	// Domain for sandbox URLs and the default API URL. Defaults to $E2B_DOMAIN
	// or "e2b.app".
	Domain string

	// APIURL overrides the control-plane URL. Defaults to https://api.<domain>
	// (or http://localhost:3000 when Debug is true).
	APIURL string

	// SandboxURL overrides the envd URL per-sandbox (testing/tunneling).
	// Defaults to $E2B_SANDBOX_URL.
	SandboxURL string

	// Debug flips the default API URL to localhost and sandbox URLs to http://.
	// Defaults to $E2B_DEBUG == "true".
	Debug bool

	// RequestTimeout bounds a single HTTP request. 0 means "no timeout".
	// When unset (zero Duration) the SDK uses DefaultRequestTimeout; callers
	// can disable it by setting Config.RequestTimeoutDisabled = true.
	RequestTimeout         time.Duration
	RequestTimeoutDisabled bool

	// Headers added to every REST request (additional sandbox headers are
	// applied on envd traffic too).
	Headers map[string]string

	// ExtraSandboxHeaders added only to envd traffic.
	ExtraSandboxHeaders map[string]string

	// HTTPClient optionally overrides the transport. If nil a default client
	// with RequestTimeout is built on demand.
	HTTPClient *http.Client
}

Config holds connection/auth/transport settings shared by all client calls. It mirrors Python's ConnectionConfig and JS's ConnectionOpts.

A zero Config is valid — missing fields fall back to environment variables (E2B_API_KEY, E2B_DOMAIN, E2B_ACCESS_TOKEN, E2B_API_URL, E2B_SANDBOX_URL, E2B_DEBUG) and then to sensible defaults.

func (Config) Resolve

func (c Config) Resolve() Config

Resolve returns a Config copy with environment-variable fallbacks and defaults applied. Safe to call on a zero Config.

func (Config) ResolvedHTTPClient

func (c Config) ResolvedHTTPClient() *http.Client

ResolvedHTTPClient returns the HTTP client this Config would use: the HTTPClient field if set, else a fresh *http.Client with RequestTimeout. Named with the Resolved- prefix because it would otherwise collide with the HTTPClient struct field.

type ConnectOptions

type ConnectOptions struct {
	Config  Config
	Timeout time.Duration
}

ConnectOptions configures (Re)connecting to an existing sandbox.

type CreateOptions

type CreateOptions struct {
	Config Config

	// Template ID or alias to build the sandbox from. Defaults to "base".
	Template string
	// Timeout is the sandbox lifetime. Defaults to 5 minutes.
	Timeout time.Duration

	// Metadata attaches free-form key/value pairs.
	Metadata map[string]string
	// Envs sets environment variables inside the sandbox.
	Envs map[string]string

	// Secure enables authenticated envd access (recommended).
	Secure bool
	// AllowInternetAccess enables outbound internet. Defaults to true.
	// Use AllowInternetAccessSet=true to send a false value.
	AllowInternetAccess    bool
	AllowInternetAccessSet bool

	// Network, Lifecycle, and VolumeMounts pass through to the API.
	Network      *NetworkOptions
	Lifecycle    *LifecycleOptions
	VolumeMounts []VolumeMount

	// Mcp is an opaque MCP configuration object (see upstream docs).
	Mcp map[string]any
}

CreateOptions captures every parameter accepted by e2b.Create. Mirrors the Python Sandbox.create(...) signature. All fields are optional except — implicitly — an API key or access token reachable via Config/env.

type EntryInfo

type EntryInfo struct {
	Name          string
	Path          string
	Type          EntryType
	Size          int64
	Mode          uint32
	Permissions   string
	Owner         string
	Group         string
	ModifiedTime  time.Time
	SymlinkTarget string
}

EntryInfo is the metadata for a file or directory.

type EntryType

type EntryType int

EntryType distinguishes file entries from directories.

const (
	EntryTypeUnspecified EntryType = iota
	EntryTypeFile
	EntryTypeDirectory
)

type Error

type Error interface {
	error
	// contains filtered or unexported methods
}

Error is the base interface implemented by every SDK-specific error. It lets callers switch on a single interface via errors.As:

var sErr e2b.Error
if errors.As(err, &sErr) { ... }

type FileNotFoundError

type FileNotFoundError struct {
	Path    string
	Message string
	// contains filtered or unexported fields
}

FileNotFoundError reports a missing file/directory in the sandbox.

func (*FileNotFoundError) Error

func (e *FileNotFoundError) Error() string

type FileUploadError

type FileUploadError struct {
	Path    string
	Message string
	Cause   error
	// contains filtered or unexported fields
}

FileUploadError reports a file upload failure during template build.

func (*FileUploadError) Error

func (e *FileUploadError) Error() string

func (*FileUploadError) Unwrap

func (e *FileUploadError) Unwrap() error

type Filesystem

type Filesystem struct {
	// contains filtered or unexported fields
}

Filesystem exposes filesystem endpoints (implemented in filesystem_impl.go).

func (*Filesystem) Exists

func (f *Filesystem) Exists(ctx context.Context, path string, opts FsOptions) (bool, error)

Exists reports whether path exists.

func (*Filesystem) IsDir

func (f *Filesystem) IsDir(ctx context.Context, path string, opts FsOptions) (bool, error)

IsDir returns true when path is a directory.

func (*Filesystem) List

func (f *Filesystem) List(ctx context.Context, path string, opts FsOptions) ([]EntryInfo, error)

List returns the entries of a directory.

func (*Filesystem) MakeDir

func (f *Filesystem) MakeDir(ctx context.Context, path string, opts FsOptions) error

MakeDir creates a directory at path (including parents).

func (*Filesystem) Move

func (f *Filesystem) Move(ctx context.Context, from, to string, opts FsOptions) error

Move renames or moves a path.

func (*Filesystem) Read

func (f *Filesystem) Read(ctx context.Context, path string, opts FsOptions) ([]byte, error)

Read returns the entire file content as []byte.

func (*Filesystem) ReadStream

func (f *Filesystem) ReadStream(ctx context.Context, path string, opts FsOptions) (io.ReadCloser, error)

ReadStream returns a streaming reader for path.

func (*Filesystem) Remove

func (f *Filesystem) Remove(ctx context.Context, path string, opts FsOptions) error

Remove deletes a file or directory.

func (*Filesystem) Stat

func (f *Filesystem) Stat(ctx context.Context, path string, opts FsOptions) (*EntryInfo, error)

Stat fetches metadata for path.

func (*Filesystem) Watch

func (f *Filesystem) Watch(ctx context.Context, path string, recursive bool) (*WatchHandle, error)

Watch starts watching a directory for filesystem events. The returned handle fans events onto a channel; Stop() cancels the stream.

func (*Filesystem) Write

func (f *Filesystem) Write(ctx context.Context, path string, r io.Reader, opts FsOptions) (*WriteInfo, error)

Write creates or overwrites a file with the contents of r. Returns the final EntryInfo of the written file.

func (*Filesystem) WriteString

func (f *Filesystem) WriteString(ctx context.Context, path, data string, opts FsOptions) (*WriteInfo, error)

WriteString is a convenience helper for small text payloads.

type FilesystemEvent

type FilesystemEvent struct {
	Name string
	Type FilesystemEventType
}

FilesystemEvent is one event emitted by Filesystem.Watch.

type FilesystemEventType

type FilesystemEventType int

FilesystemEventType enumerates filesystem event kinds.

const (
	FsEventUnspecified FilesystemEventType = iota
	FsEventCreate
	FsEventWrite
	FsEventRemove
	FsEventRename
	FsEventChmod
)

type FsOptions

type FsOptions struct {
	User             string
	RequestTimeoutMs int
}

FsOptions holds per-call tweaks common across filesystem operations.

type Git

type Git struct {
	// contains filtered or unexported fields
}

Git wraps Commands to run git operations inside the sandbox. Method bodies are in git_impl.go.

func (*Git) Add

func (g *Git) Add(ctx context.Context, pattern string, opts GitOptions) (*CommandResult, error)

Add runs `git add` for the given pattern(s).

func (*Git) Branches

func (g *Git) Branches(ctx context.Context, opts GitOptions) (*GitBranches, error)

Branches parses `git branch -a`.

func (*Git) CheckoutBranch

func (g *Git) CheckoutBranch(ctx context.Context, name string, opts GitOptions) (*CommandResult, error)

CheckoutBranch switches to a branch.

func (*Git) Clone

func (g *Git) Clone(ctx context.Context, url string, opts GitCloneOptions) (*CommandResult, error)

Clone clones a repository into the sandbox. When creds are provided they are injected into the URL for a single invocation; pass DangerouslyStoreCredentials to persist them.

func (*Git) Commit

func (g *Git) Commit(ctx context.Context, message string, opts GitOptions) (*CommandResult, error)

Commit runs `git commit -m <message>`.

func (*Git) CreateBranch

func (g *Git) CreateBranch(ctx context.Context, name string, opts GitOptions) (*CommandResult, error)

CreateBranch creates a branch with the given name.

func (*Git) DeleteBranch

func (g *Git) DeleteBranch(ctx context.Context, name string, opts GitOptions) (*CommandResult, error)

DeleteBranch deletes a branch.

func (*Git) GetRemoteURL

func (g *Git) GetRemoteURL(ctx context.Context, name string, opts GitOptions) (string, error)

GetRemoteURL returns the URL of the named remote (default "origin").

func (*Git) Pull

func (g *Git) Pull(ctx context.Context, opts GitOptions) (*CommandResult, error)

Pull runs `git pull`.

func (*Git) Push

func (g *Git) Push(ctx context.Context, opts GitOptions) (*CommandResult, error)

Push runs `git push`.

func (*Git) SetRemoteURL

func (g *Git) SetRemoteURL(ctx context.Context, name, url string, opts GitOptions) (*CommandResult, error)

SetRemoteURL sets the URL of the named remote.

func (*Git) Status

func (g *Git) Status(ctx context.Context, opts GitOptions) (*GitStatus, error)

Status parses the porcelain output of `git status`.

type GitAuthError

type GitAuthError struct {
	Message string
	// contains filtered or unexported fields
}

GitAuthError specializes AuthenticationError for Git credential failures.

func (*GitAuthError) Error

func (e *GitAuthError) Error() string

type GitBranches

type GitBranches struct {
	Current string
	Local   []string
	Remote  []string
}

GitBranches is the parsed output of "git branch".

type GitCloneOptions

type GitCloneOptions struct {
	GitOptions
	Branch   string
	Depth    int
	Username string
	Password string
	// DangerouslyStoreCredentials persists creds in the repo config.
	DangerouslyStoreCredentials bool
}

GitCloneOptions configures Git.Clone.

type GitOptions

type GitOptions struct {
	RepoPath string
	User     string
	Cwd      string
	Envs     map[string]string
}

GitOptions holds optional knobs shared by most Git methods.

type GitStatus

type GitStatus struct {
	Modified  []string
	Staged    []string
	Untracked []string
}

GitStatus is the parsed output of "git status".

type GitUpstreamError

type GitUpstreamError struct {
	Message string
	// contains filtered or unexported fields
}

GitUpstreamError reports a missing upstream branch.

func (*GitUpstreamError) Error

func (e *GitUpstreamError) Error() string

type InvalidArgumentError

type InvalidArgumentError struct {
	Message string
	// contains filtered or unexported fields
}

InvalidArgumentError reports an invalid parameter.

func (*InvalidArgumentError) Error

func (e *InvalidArgumentError) Error() string

type LifecycleOptions

type LifecycleOptions struct {
	// OnTimeout is "pause" or "kill". Empty means server default (kill).
	OnTimeout string
	// AutoResume configures auto-resume for paused sandboxes.
	AutoResume bool
}

LifecycleOptions controls what happens when the sandbox timeout fires.

type NetworkOptions

type NetworkOptions struct {
	// AllowOut is a list of CIDR blocks or IPs permitted for egress.
	AllowOut []string
	// DenyOut is a list of CIDR blocks or IPs blocked for egress.
	DenyOut []string
	// AllowPublicTraffic, when true, makes sandbox URLs reachable without
	// the traffic access token.
	AllowPublicTraffic bool
	// MaskRequestHost customizes the host template on sandbox URLs.
	MaskRequestHost string
}

NetworkOptions configures sandbox egress and public-traffic policy. Mirrors SandboxNetworkConfig in the REST API.

type NotEnoughSpaceError

type NotEnoughSpaceError struct {
	Message string
	// contains filtered or unexported fields
}

NotEnoughSpaceError reports the sandbox has insufficient disk space.

func (*NotEnoughSpaceError) Error

func (e *NotEnoughSpaceError) Error() string

type NotFoundError

type NotFoundError struct {
	Message string
	// contains filtered or unexported fields
}

NotFoundError is deprecated. Prefer FileNotFoundError or SandboxNotFoundError.

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

type ProcessInfo

type ProcessInfo struct {
	PID  uint32
	Cmd  string
	Args []string
	Envs map[string]string
	Cwd  string
	Tag  string
}

ProcessInfo describes a running command or PTY inside the sandbox.

type Pty

type Pty struct {
	// contains filtered or unexported fields
}

Pty exposes PTY endpoints (implemented in pty_impl.go).

func (*Pty) Create

func (p *Pty) Create(ctx context.Context, opts PtyOptions) (*CommandHandle, error)

Create starts an interactive PTY session.

func (*Pty) Kill

func (p *Pty) Kill(ctx context.Context, pid uint32) (bool, error)

Kill terminates the PTY.

func (*Pty) Resize

func (p *Pty) Resize(ctx context.Context, pid uint32, cols, rows uint32) error

Resize changes the PTY terminal size.

func (*Pty) SendInput

func (p *Pty) SendInput(ctx context.Context, pid uint32, data []byte) error

SendInput writes bytes into the PTY.

type PtyOptions

type PtyOptions struct {
	Cmd    string
	Args   []string
	Envs   map[string]string
	Cwd    string
	Cols   uint32
	Rows   uint32
	Tag    string
	OnData func([]byte)
}

PtyOptions configures Pty.Create.

type RateLimitError

type RateLimitError struct {
	Message string
	// contains filtered or unexported fields
}

RateLimitError reports HTTP 429.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

type RunOptions

type RunOptions struct {
	Args       []string
	Cwd        string
	User       string
	Envs       map[string]string
	TimeoutMs  int
	Stdin      io.Reader
	Background bool
	Tag        string
	OnStdout   func([]byte)
	OnStderr   func([]byte)
}

RunOptions configures Commands.Run and Commands.Start.

type Sandbox

type Sandbox struct {
	ID                 string
	Domain             string
	EnvdVersion        string
	EnvdAccessToken    string
	TrafficAccessToken string

	// Per-sandbox sub-clients (non-nil after Create/Connect).
	Commands *Commands
	Pty      *Pty
	Files    *Filesystem
	Git      *Git
	// contains filtered or unexported fields
}

Sandbox is a handle to a running (or paused) E2B sandbox.

It exposes three per-sandbox modules:

  • Commands: exec, PTY, signal
  • Files: read/write/watch
  • Git: git operations running inside the sandbox

A *Sandbox is safe for concurrent use.

func Connect

func Connect(ctx context.Context, sandboxID string, opts ConnectOptions) (*Sandbox, error)

Connect attaches to an existing sandbox (running or paused). If paused, the server resumes it; the call sets the sandbox timeout to opts.Timeout (default 5 minutes).

func Create

func Create(ctx context.Context, opts CreateOptions) (*Sandbox, error)

Create provisions a new sandbox and returns a *Sandbox wired up with all sub-clients. The caller owns the returned sandbox and should call Kill (directly or via defer) to release it.

func (*Sandbox) CreateSnapshot

func (s *Sandbox) CreateSnapshot(ctx context.Context) (*SnapshotInfo, error)

CreateSnapshot persists the sandbox's state as a snapshot.

func (*Sandbox) DownloadURL

func (s *Sandbox) DownloadURL(path string, opts SignatureOptions) (string, error)

DownloadURL returns an HTTP URL the caller can GET a file from.

func (*Sandbox) GetHost

func (s *Sandbox) GetHost(port int) string

GetHost returns the external hostname for the given sandbox port.

func (*Sandbox) GetInfo

func (s *Sandbox) GetInfo(ctx context.Context) (*SandboxInfo, error)

GetInfo fetches the sandbox metadata.

func (*Sandbox) GetMetrics

func (s *Sandbox) GetMetrics(ctx context.Context) ([]SandboxMetric, error)

GetMetrics fetches instantaneous CPU/memory/disk usage.

func (*Sandbox) IsRunning

func (s *Sandbox) IsRunning(ctx context.Context) (bool, error)

IsRunning reports whether the sandbox is still alive (REST GET /sandboxes/{id}).

func (*Sandbox) Kill

func (s *Sandbox) Kill(ctx context.Context) error

Kill terminates this sandbox.

func (*Sandbox) Pause

func (s *Sandbox) Pause(ctx context.Context) (bool, error)

Pause pauses this sandbox. Returns true on success; false if the sandbox was already paused.

func (*Sandbox) SetTimeout

func (s *Sandbox) SetTimeout(ctx context.Context, d time.Duration) error

SetTimeout updates the sandbox's inactivity timeout.

func (*Sandbox) UploadURL

func (s *Sandbox) UploadURL(path string, opts SignatureOptions) (string, error)

UploadURL returns an HTTP URL the caller can POST a file to.

type SandboxError

type SandboxError struct {
	Message string
	Cause   error
	// contains filtered or unexported fields
}

SandboxError wraps arbitrary sandbox/API failures that don't have a more specific type.

func (*SandboxError) Error

func (e *SandboxError) Error() string

func (*SandboxError) Unwrap

func (e *SandboxError) Unwrap() error

type SandboxInfo

type SandboxInfo struct {
	SandboxID           string
	Alias               string
	Domain              string
	TemplateID          string
	State               SandboxState
	CPUCount            int32
	MemoryMB            int32
	DiskSizeMB          int32
	StartedAt           time.Time
	EndAt               time.Time
	Metadata            map[string]string
	EnvdVersion         string
	EnvdAccessToken     string
	AllowInternetAccess *bool
	Network             *NetworkOptions
	Lifecycle           *LifecycleOptions
	VolumeMounts        []VolumeMount
}

SandboxInfo holds REST-reported metadata about a sandbox.

type SandboxMetric

type SandboxMetric struct {
	CPUCount      int32
	CPUUsedPct    float32
	DiskTotal     int64
	DiskUsed      int64
	MemTotal      int64
	MemUsed       int64
	Timestamp     time.Time
	TimestampUnix int64
}

SandboxMetric is one sample of resource usage.

type SandboxNotFoundError

type SandboxNotFoundError struct {
	SandboxID string
	Message   string
	// contains filtered or unexported fields
}

SandboxNotFoundError reports that the sandbox is gone or never existed.

func (*SandboxNotFoundError) Error

func (e *SandboxNotFoundError) Error() string

type SandboxState

type SandboxState string

SandboxState reports whether a sandbox is running or paused.

const (
	SandboxStateRunning SandboxState = "running"
	SandboxStatePaused  SandboxState = "paused"
)

type Signature

type Signature struct {
	Value      string
	Expiration *int64 // Unix seconds; nil → no expiration
}

Signature is an opaque v1 signature usable as a query parameter when hitting envd's file endpoints.

func GetSignature

func GetSignature(path string, operation SignatureOperation, envdAccessToken string, opts SignatureOptions) (Signature, error)

GetSignature produces a v1 signature for an envd /files request. It matches the Python and JS implementations byte-for-byte.

raw = path:operation:user:envdAccessToken[:expiration] signature = "v1_" + base64url(sha256(raw)) // '=' padding stripped

type SignatureOperation

type SignatureOperation string

SignatureOperation is either "read" or "write".

const (
	SignatureRead  SignatureOperation = "read"
	SignatureWrite SignatureOperation = "write"
)

type SignatureOptions

type SignatureOptions struct {
	User                string
	ExpirationInSeconds int
}

SignatureOptions configures GetSignature.

type SnapshotInfo

type SnapshotInfo struct {
	SnapshotID string
	Names      []string
}

SnapshotInfo references a persisted sandbox snapshot.

type TemplateError

type TemplateError struct {
	Message string
	// contains filtered or unexported fields
}

TemplateError reports template/envd incompatibility.

func (*TemplateError) Error

func (e *TemplateError) Error() string

type TimeoutError

type TimeoutError struct {
	Message string
	Cause   error
	// contains filtered or unexported fields
}

TimeoutError is returned when a request or sandbox operation times out. Mirrors Python's TimeoutException / JS TimeoutError.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

func (*TimeoutError) Temporary

func (e *TimeoutError) Temporary() bool

func (*TimeoutError) Timeout

func (e *TimeoutError) Timeout() bool

func (*TimeoutError) Unwrap

func (e *TimeoutError) Unwrap() error

type VolumeError

type VolumeError struct {
	Message string
	Cause   error
	// contains filtered or unexported fields
}

VolumeError reports a volume operation failure.

func (*VolumeError) Error

func (e *VolumeError) Error() string

func (*VolumeError) Unwrap

func (e *VolumeError) Unwrap() error

type VolumeMount

type VolumeMount struct {
	Name string
	Path string
}

VolumeMount attaches a volume to a sandbox path.

type WatchHandle

type WatchHandle struct {
	// contains filtered or unexported fields
}

WatchHandle streams filesystem events from Filesystem.Watch.

func (*WatchHandle) Err

func (w *WatchHandle) Err() error

Err returns the error (if any) that terminated the watch.

func (*WatchHandle) Events

func (w *WatchHandle) Events() <-chan FilesystemEvent

Events returns a receive-only channel that yields filesystem events. The channel is closed when the watch ends; check Err() afterwards.

func (*WatchHandle) Stop

func (w *WatchHandle) Stop(ctx context.Context) error

Stop cancels the watch and waits for the background goroutine to finish.

type WriteInfo

type WriteInfo struct {
	Path string
	Name string
	Type EntryType
}

WriteInfo is returned by Filesystem.Write.

Directories

Path Synopsis
examples
basic command
Basic example: create a sandbox, run a command, read its output.
Basic example: create a sandbox, run a command, read its output.
desktop command
Desktop example: build the local e2b.Dockerfile as a template, launch a sandbox, print the noVNC URL, then prove that SDK PTY sessions are mirrored into the shared tmux that the VNC desktop shows.
Desktop example: build the local e2b.Dockerfile as a template, launch a sandbox, print the noVNC URL, then prove that SDK PTY sessions are mirrored into the shared tmux that the VNC desktop shows.
lifecycle command
Lifecycle example: list templates, build a new one, inspect it, spawn a sandbox from it, read sandbox info, then tear everything down.
Lifecycle example: list templates, build a new one, inspect it, spawn a sandbox from it, read sandbox info, then tear everything down.
lifecycle_v2 command
Lifecycle example for self-hosted E2B control planes that predate the /v3/templates endpoint (≤ 2.1.x).
Lifecycle example for self-hosted E2B control planes that predate the /v3/templates endpoint (≤ 2.1.x).
selfhosted command
Self-hosted example: point the SDK at a self-hosted E2B control plane and show the current sandbox session (ID, template, state, timing, envd info, live metrics).
Self-hosted example: point the SDK at a self-hosted E2B control plane and show the current sandbox session (ID, template, state, timing, envd info, live metrics).
template command
Template example: build a simple Debian-based template and launch a sandbox from it.
Template example: build a simple Debian-based template and launch a sandbox from it.
terminal command
Interactive terminal example: open an E2B sandbox, attach the local TTY to a remote PTY (bash) in raw mode, and close the sandbox when the user exits.
Interactive terminal example: open an E2B sandbox, attach the local TTY to a remote PTY (bash) in raw mode, and close the sandbox when the user exits.
internal
api
Package apiclient provides primitives to interact with the openapi HTTP API.
Package apiclient provides primitives to interact with the openapi HTTP API.
envdapi
Package envdapi provides primitives to interact with the openapi HTTP API.
Package envdapi provides primitives to interact with the openapi HTTP API.
transport
Package transport wires the REST (oapi-codegen) and Connect-RPC clients used by the public e2b package.
Package transport wires the REST (oapi-codegen) and Connect-RPC clients used by the public e2b package.
version
Code generated by scripts/sync-spec.sh.
Code generated by scripts/sync-spec.sh.
volumeapi
Package volumeapi provides primitives to interact with the openapi HTTP API.
Package volumeapi provides primitives to interact with the openapi HTTP API.
Package template provides a fluent builder and a Client for building E2B sandbox templates.
Package template provides a fluent builder and a Client for building E2B sandbox templates.
Package volume provides a client for E2B persistent volumes.
Package volume provides a client for E2B persistent volumes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL