e2b

package module
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 34 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

E2B Go SDK

Go Reference test integration License

A Go client for the E2B sandbox platform, staying wire-compatible with the official Python and JavaScript SDKs across both E2B Cloud and self-hosted E2B deployments.

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.

Pinned upstream baselines
Component Baseline Scope
e2b-dev/E2B SDK spec e2b@2.64.0 Vendored OpenAPI & Protobuf specs in ./spec/ (spec/E2B_VERSION)
e2b-dev/runtime 2026.30 (runtime <= 2026.30, tagged 2025.31..2026.30 + pre-2025.31) Self-hosted control-plane, orchestrator, proxy, and belt volume content
envd (in-sandbox daemon) envd-v0.6.13 (v0.1.0..v0.6.13) Guest capabilities gated automatically via Sandbox.EnvdVersion

Install

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

Quick start (E2B Cloud)

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

	client, err := e2b.NewClient(e2b.Config{}) // reads E2B_API_KEY from env
	if err != nil {
		log.Fatal(err)
	}

	sbx, err := client.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
}

Self-hosted E2B note: Self-hosted releases (runtime <= 2026.30) expose POST /sandboxes rather than POST /v2/sandboxes. Call client.CreateV1(ctx, ...) (and ConnectV1 or Resume / sbx.Resume) on self-hosted clusters — see the Server generation selection table and examples/selfhosted.

Unified clients

Hold one e2b.Client (and template.Client / volume.Client when building templates or managing volumes) for the lifetime of your process. Each resolves e2b.Config once and shares pooled HTTP transports — applying control-plane retries and timeouts on REST calls while keeping long-lived envd streams and large file transfers free of client-wide timeout cutoffs:

c, err := e2b.NewClient(e2b.Config{})
if err != nil {
	log.Fatal(err)
}

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

// List all running sandboxes (cursor-paginated via x-next-token).
running, err := c.ListAll(ctx, e2b.SandboxListOptions{
	State: []e2b.SandboxState{e2b.SandboxStateRunning},
})
if err != nil {
	log.Fatal(err)
}
for _, s := range running {
	fmt.Println(s.SandboxID, s.State)
}

Package-level e2b.Create / CreateV1 / Connect / ConnectV1 / Resume / Kill / List / ListAll (and volume.Create / Connect / ConnectByID / List) remain supported for one-shot scripts; prefer NewClient when issuing multiple calls.

Configuration & authentication

e2b.Config{} resolves missing fields from environment variables:

Variable Purpose
E2B_API_KEY Team API key (X-API-Key header; takes precedence if E2B_ACCESS_TOKEN is also set)
E2B_ACCESS_TOKEN User access token (Authorization: Bearer)
E2B_DOMAIN Base domain (defaults to e2b.app)
E2B_API_URL Full override of the control-plane URL (defaults to https://api.<domain>)
E2B_SANDBOX_URL Override the envd base URL (e.g. http://localhost:3002 for E2B Embed or tunnels)
E2B_VOLUME_API_URL Override the volume-content URL (defaults to https://api.<volumeDomain>)
E2B_HTTP_VERSION Force HTTP protocol version: "1.1" (HTTPVersion1) or "2" (HTTPVersion2)
E2B_DEBUG "true" targets local debug servers (localhost:3000 API, localhost:8080 volumes, localhost:49983 envd)

e2b.Config also supports explicit Proxy (http://, https://, socks5://, socks5h://, or host:port), Retries (default 3, honoring Should-Retry and Retry-After), Headers (control-plane only), and ExtraSandboxHeaders (envd only).

Packages

Path Description
github.com/eric642/e2b-go-sdk Core Client, Sandbox, Commands, Filesystem, Pty, Git, Snapshots, Fork, Logs, Network, Secrets
github.com/eric642/e2b-go-sdk/template Fluent template.Builder, ReadyCmd helpers, v3 & legacy v2 build pipelines, template & tag management
github.com/eric642/e2b-go-sdk/volume volume.Client persistent volume lifecycle & streaming volume-content API

Server generation selection table

E2B Cloud is a single hosted service, whereas self-hosted E2B clusters span runtime releases (2025.31..2026.30) as well as older pre-2025.31 deployments. Use this table to pick the right method for your target environment:

Area & operation E2B Cloud Self-Hosted Modern (runtime 2025.44..2026.30) Self-Hosted Legacy (runtime < 2025.44)
Sandbox create Client.Create (POST /v2/sandboxes) Client.CreateV1 (POST /sandboxes, secure: true default) Client.CreateV1 (POST /sandboxes, secure: true default)
Sandbox connect / wake Client.Connect / Sandbox.Connect (POST /v2/sandboxes/{id}/connect) Client.ConnectV1 / Sandbox.ConnectV1 (POST /sandboxes/{id}/connect), or Client.Resume / Sandbox.Resume Client.Resume / Sandbox.Resume / ResumeV1 (POST /sandboxes/{id}/resume)
Sandbox pause / kill Pause (POST /sandboxes/{id}/pause), Kill (DELETE /sandboxes/{id}) Pause, Kill Pause, Kill
Sandbox list Client.List / ListAll (GET /v2/sandboxes) Client.List / ListAll (GET /v2/sandboxes; Order/StartedAfter/Template in runtime 2026.30) Client.List (runtime >= 2025.31) or Client.ListV1 (GET /sandboxes on runtime < 2025.31)
Sandbox timeout / keepalive SetTimeout (POST /sandboxes/{id}/timeout) SetTimeout or monotonic RefreshTimeout (POST /sandboxes/{id}/refreshes) SetTimeout or RefreshTimeout (RefreshTimeoutV1)
Sandbox logs GetLogs (GET /v2/sandboxes/{id}/logs) GetLogs (runtime >= 2026.07) or GetLogsV1 (runtime < 2026.07) GetLogsV1 (GET /sandboxes/{id}/logs)
Sandbox fork Fork (POST /sandboxes/{id}/fork, envd >= v0.5.0) Fork (runtime >= 2026.29, envd >= v0.5.0) Not available
Sandbox network update UpdateNetwork (PUT /sandboxes/{id}/network) UpdateNetwork (runtime >= 2026.12) Not available
Snapshots CreateSnapshot, ListSnapshots, DeleteSnapshot (envd >= v0.5.0) Supported on runtime >= 2026.08 (envd >= v0.5.0) Not available
Template build template.Client.Build / BuildStream / BuildInBackground (POST /v3/templates) Build / BuildStream / BuildInBackground (POST /v3/templates) BuildV2 / BuildStreamV2 / BuildInBackgroundV2 (POST /v2/templates; returns 410 Gone on E2B Cloud)
Template list ListV2 / ListAllV2 (GET /v2/templates) & ListDefault (GET /default-templates) ListV2 / ListAllV2 (runtime >= 2026.26) or List / ListV1 (GET /templates) List / ListV1 (GET /templates)
Template visibility SetPublic (PATCH /v2/templates/{id}) SetPublic (runtime >= 2026.05) or SetPublicV1 (runtime < 2026.05) SetPublicV1 (PATCH /templates/{id})
Template tags AssignTags, RemoveTags, GetTags, CountTags, TagExists, ListTagGroups, GetTagAssignments AssignTags, RemoveTags, GetTags (runtime >= 2026.01..2026.07) Not available
Persistent volumes volume.NewClient (Create, Connect, ConnectWithToken, Stat, List, ReadFileStream, WriteFileStream, …) Supported on runtime >= 2026.07 (BYOC domain when returned, else Config.Domain) Not available
Secrets CreateSecret, UpdateSecret, GetSecret, ListSecrets, DeleteSecret, SecretPlaceholder Supported on runtime 2026.30 Not available
Soft-deprecated OpenAPI routes vs. retired (410 Gone) routes

Upstream OpenAPI marks older routes deprecated: true when a newer endpoint is introduced, which does not mean those routes are removed on self-hosted clusters (or even on E2B Cloud):

  • Soft-deprecated in OpenAPI, still actively served (CreateV1, ConnectV1, Resume, RefreshTimeout, ListV1, GetLogsV1, template.List/ListV1, template.SetPublicV1): All of these remain actively served on E2B Cloud and self-hosted runtime <= 2026.30 (from each route's introduction release), and several are the primary or required endpoints on self-hosted deployments:
    • CreateV1 (POST /sandboxes): primary create endpoint for all self-hosted runtime <= 2026.30 (POST /v2/sandboxes is E2B Cloud-only).
    • ConnectV1 (POST /sandboxes/{id}/connect): primary idempotent connect/wake endpoint for self-hosted runtime 2025.44..2026.30.
    • Resume / ResumeV1 (POST /sandboxes/{id}/resume): soft-deprecated since runtime 2025.44 introduced idempotent /connect (ConnectV1 attaches if running or wakes if paused, whereas /resume returns 409 Conflict if already running). Still served on both E2B Cloud and all self-hosted runtime <= 2026.30; required on runtime < 2025.44 to wake paused sandboxes, and useful anywhere when overriding CPUCount/AutoPause on wake or strictly asserting the sandbox was paused.
    • RefreshTimeout / RefreshTimeoutV1 (POST /sandboxes/{id}/refreshes): monotonic keepalive (allowShorter=false), still served on E2B Cloud and self-hosted runtime <= 2026.30.
    • ListV1 (GET /sandboxes), GetLogsV1 (GET /sandboxes/{id}/logs), template.List/ListV1 (GET /templates), template.SetPublicV1 (PATCH /templates/{id}): required on self-hosted runtimes predating their v2 counterparts (< 2025.31, < 2026.07, < 2026.26, < 2026.05 respectively) and still served on runtime <= 2026.30 and E2B Cloud.
  • Retired (410 Gone) on E2B Cloud (template.BuildV2 / BuildStreamV2 / BuildInBackgroundV2 — POST /v2/templates): The only SDK-exposed route retired on E2B Cloud (where it returns 410 Gone). It remains actively served on self-hosted runtime <= 2026.30 and is required on self-hosted runtime < 2025.44 (where POST /v3/templates does not exist).
Explicit control-plane coexistence vs. adaptive high-level features

The SDK follows a strict two-layer design so multi-generation support stays predictable and debuggable:

  1. 1-to-1 Control-Plane Methods — Zero Hidden Fallback: Versioned control-plane endpoints (Create vs CreateV1, Connect vs ConnectV1 vs Resume / ResumeV1, List vs ListV1, GetLogs vs GetLogsV1, template.Build vs BuildV2, template.ListV2 vs ListV1, template.SetPublic vs SetPublicV1) coexist on the same client and never probe or silently fall back across route versions. If your server returns 404 or 410, the SDK surfaces the exact e2b.Error immediately.
  2. High-Level Composite & Data-Plane Features — Automatic Adaptation: Composite workflows and guest operations adapt transparently across server and envd versions:
    • (*Sandbox).IsRunning & GetInfo: Avoids unintentionally waking paused autoResume sandboxes, probes envd GET /health (200/204 -> true, 502 -> false), falls back to control-plane GetInfo when older self-hosted proxies return 404 on /health, and normalizes legacy pre-2025.31 empty state == "" responses to SandboxStateRunning.
    • MCP Gateway (Create & CreateV1): Defaults Template to "mcp-gateway" when Mcp is configured, generates a random UUID access token, launches mcp-gateway as root (killing the sandbox on failure), and falls back to /etc/mcp-gateway/.token on reconnected sandboxes.
    • Template Layer Uploads & Build Logs: Buffers COPY tarballs with an exact Content-Length (required by AWS S3 presigned PUT) while forwarding TemplateBuildFileUpload.Headers (required by Azure Blob SAS), and synthesizes LogEntry items from legacy logs: []string when logEntries is empty.
    • Volume BYOC Routing: Routes /volumecontent/{id}/* to Config.VolumeAPIURL / $E2B_VOLUME_API_URL (or http://localhost:8080 in Debug mode), otherwise https://api.<VolumeAndToken.domain> when returned by BYOC clusters, falling back to https://api.<Config.Domain> on non-BYOC E2B Cloud and self-hosted runtime 2026.07..2026.30.
    • envd SemVer Gates (versions.go): Gates guest features against Sandbox.EnvdVersion (99.99.99 in Debug):
      • >= v0.1.0: minimum envd floor on sandbox creation
      • >= v0.1.4: recursive Filesystem.Watch / WatchWithOptions
      • >= v0.1.5: Sandbox.GetMetrics
      • >= v0.4.0: omits default username and Authorization header unless User is explicitly provided (< v0.4.0 falls back to "user")
      • >= v0.5.2: Commands.CloseStdin / CommandHandle.CloseStdin
      • >= v0.5.5: Filesystem.Compose (POST /files/compose)
      • >= v0.5.7: Filesystem uploads use application/octet-stream (< v0.5.7 falls back to multipart/form-data)
      • >= v0.6.2: Filesystem extended-attribute Metadata (X-Metadata-*)
      • >= v0.6.3: WatchOptions.IncludeEntry
      • >= v0.6.4: WatchOptions.AllowNetworkMounts

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 (WithProtoJSON()), carrying E2b-Sandbox-Id, E2b-Sandbox-Port: 49983, and Keepalive-Ping-Interval: 50 on streams.
  • envd plain HTTP (/files, /files/compose, /health, /metrics, /envs) — generated from spec/envd/envd.yaml.
  • Volume content REST (belt /volumecontent/{volumeID}/*) — generated from spec/openapi-volumecontent.yml.

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

Versioning & regenerating clients

spec/E2B_VERSION and VERSION track the upstream e2b-dev/E2B SDK spec tag (currently e2b@2.64.0):

make tools                           # one-time: install buf, oapi-codegen, protoc-gen-*
make sync-spec E2B_TAG=e2b@2.64.0    # sync & filter ./spec/, VERSION, internal/version/upstream.go
make codegen                         # regenerate internal/ clients
make regen                           # sync-spec + codegen in one step
make version                         # print current SDK version and pinned upstream spec ref

scripts/sync-spec.sh reads spec files directly from git objects in E2B/ without mutating the submodule checkout and runs scripts/filter_spec.go to strip internal/admin operations before code generation. Pass --skip-fetch to work offline.

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 E2B Cloud (/v3/templates + /v2/sandboxes)
examples/lifecycle_v2 Legacy lifecycle on self-hosted E2B (runtime <= 2026.30: ListV1, BuildStreamV2, SetPublicV1, CreateV1)
examples/selfhosted Connecting to a self-hosted E2B deployment (CreateV1, session info, exec, metrics)
examples/desktop Split dual-display noVNC desktop (:0 tmux terminal + :1 on-demand Chromium)

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:

  • :0 -> 6080 — an xterm attached to the shared tmux -L main session. Any Pty.Create opened through the SDK appears here in real time.
  • :1 -> 6081 — 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.

Testing

go test -mod=readonly -race ./...   # unit tests (no external network)
go test -tags=integration ./...     # live integration tests (requires E2B_API_KEY)

License

Apache 2.0, matching upstream E2B.

Documentation

Overview

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

It tracks the official 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 with idiomatic Go APIs: context-aware calls, typed errors implementing Error, and coexisting control-plane methods for both E2B Cloud and self-hosted E2B clusters.

Pinned upstream baselines:

  • E2B SDK OpenAPI/Protobuf spec pin: e2b@2.64.0
  • Self-hosted E2B runtime: 2026.30 (compatible across runtime <= 2026.30, tagged 2025.31..2026.30 + pre-2025.31)
  • In-sandbox envd daemon: envd-v0.6.13 (v0.1.0..v0.6.13 via SemVer gates)

Quick start

ctx := context.Background()
client, err := e2b.NewClient(e2b.Config{}) // reads E2B_API_KEY from env
if err != nil {
	log.Fatal(err)
}
sbx, err := client.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 and configuration

A zero Config falls back to environment variables:

  • E2B_API_KEY: team API key (X-API-Key header; wins if E2B_ACCESS_TOKEN is also set)
  • E2B_ACCESS_TOKEN: user access token (Authorization: Bearer)
  • E2B_DOMAIN: base domain (defaults to e2b.app)
  • E2B_API_URL: control-plane URL override (defaults to https://api.<domain>)
  • E2B_SANDBOX_URL: envd URL override (e.g. http://localhost:3002 for E2B Embed)
  • E2B_VOLUME_API_URL: volume-content URL override (defaults to https://api.<volumeDomain>)
  • E2B_HTTP_VERSION: HTTP protocol version ("1.1" or "2")
  • E2B_DEBUG: when "true", targets localhost debug ports (3000 API, 8080 volume, 49983 envd)

Unified client

Build one Client via NewClient and reuse it across calls. It resolves Config once and separates control-plane HTTP traffic (retries + request timeout) from long-lived envd data-plane streams and file transfers. Package-level helpers (Create, CreateV1, Connect, ConnectV1, Resume, Kill, List, ListAll) remain available for short scripts.

Multi-generation server selection

Control-plane methods map 1-to-1 to server endpoints with zero hidden fallback probes:

  • E2B Cloud: Create (POST /v2/sandboxes), Connect (POST /v2/sandboxes/{id}/connect), Pause, List / ListAll (GET /v2/sandboxes), GetLogs (GET /v2/sandboxes/{id}/logs), Fork, UpdateNetwork, Snapshots, Secrets, template.Client.Build (/v3/templates), template.Client.ListV2 (/v2/templates), template.Client.SetPublic (/v2/templates/{id}), and volume.NewClient.
  • Self-Hosted Modern (runtime 2025.44..2026.30): CreateV1 (POST /sandboxes), ConnectV1 (POST /sandboxes/{id}/connect), Pause / Resume, List / ListAll, GetLogs (runtime >= 2026.07) or GetLogsV1, template.Client.Build (/v3/templates), template.Client.ListV2 (runtime >= 2026.26) or ListV1, template.Client.SetPublic (runtime >= 2026.05), volume.NewClient (runtime >= 2026.07), Secrets (runtime 2026.30).
  • Self-Hosted Legacy (runtime < 2025.44): CreateV1, Pause / Resume (Client.Resume, Sandbox.Resume, ResumeV1 via POST /sandboxes/{id}/resume), RefreshTimeout, List (runtime >= 2025.31) or ListV1 (runtime < 2025.31), GetLogsV1, template.Client.BuildV2 (/v2/templates), template.Client.ListV1, and template.Client.SetPublicV1.

Soft-deprecated OpenAPI routes (CreateV1, ConnectV1, Resume, RefreshTimeout, ListV1, GetLogsV1, template.Client.ListV1, template.Client.SetPublicV1) remain actively served on both E2B Cloud and self-hosted runtime <= 2026.30; only POST /v2/templates (template.Client.Build*V2) is retired (410 Gone) on E2B Cloud while remaining active on self-hosted runtime <= 2026.30.

High-level composite features (Sandbox.IsRunning, GetInfo empty-state normalization, MCP gateway bootstrap, template S3/Azure layer uploads and build-log fallback, volume BYOC domain routing, and envd SemVer capability gates in versions.go) adapt automatically across versions.

Sub-packages

  • github.com/eric642/e2b-go-sdk/template: fluent template Builder, ReadyCmd helpers, v3 and v2 build pipelines, and template/tag management
  • github.com/eric642/e2b-go-sdk/volume: persistent volume lifecycle client and streaming belt volume-content API

Index

Examples

Constants

View Source
const (
	DefaultRequestTimeout    = 60 * time.Second
	KeepAlivePingIntervalSec = transport.KeepalivePingIntervalSec
	KeepAlivePingHeader      = transport.HeaderKeepalivePing
	DefaultDomain            = "e2b.app"
	// DefaultRetries is the number of control-plane retries applied when
	// Config.Retries is nil.
	DefaultRetries = transport.DefaultRetries
)

Default request timeout (matches Python/JS SDK).

View Source
const (
	HTTPVersion1 = "1.1"
	HTTPVersion2 = "2"
)

HTTP protocol versions accepted by Config.HTTPVersion.

View Source
const (
	ListOrderAsc  = "asc"
	ListOrderDesc = "desc"
)

Sort order constants for SandboxListOptions.Order.

View Source
const (
	SandboxLogLevelDebug = "debug"
	SandboxLogLevelInfo  = "info"
	SandboxLogLevelWarn  = "warn"
	SandboxLogLevelError = "error"
)

Log level constants for SandboxLogsOptions.Level.

View Source
const (
	LogsDirectionForward  = "forward"
	LogsDirectionBackward = "backward"
)

Log direction constants for SandboxLogsOptions.Direction.

View Source
const (
	// DefaultMCPTemplate is the default sandbox template used when
	// CreateOptions.Mcp is non-nil and CreateOptions.Template is unset.
	DefaultMCPTemplate = "mcp-gateway"

	// MCPPort is the in-sandbox port the MCP gateway listens on.
	MCPPort = 50005
)
View Source
const (
	DefaultSandboxTimeout = 300 * time.Second
	DefaultTemplate       = "base"
)

Defaults mirrored from the Python/JS SDKs.

View Source
const (
	SnapshotModeFull       = "full"
	SnapshotModeFilesystem = "filesystem"
)

Snapshot persistence modes for CreateSnapshotOptions.Mode and LifecycleOptions.Mode.

View Source
const AllTraffic = "0.0.0.0/0"

AllTraffic is the CIDR range representing all IPv4 traffic.

View Source
const DefaultUser = defaultUser

DefaultUser is the username the SDK falls back to when none is supplied and the envd build predates server-side default-user inference (envd < 0.4.0).

View Source
const SDKVersion = version.SDKVersion

SDKVersion is this SDK's release version. It is kept in lockstep with the upstream e2b 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 Bool added in v0.1.4

func Bool(v bool) *bool

Bool returns a pointer to v, useful for optional tri-state boolean fields such as NetworkOptions.AllowPublicTraffic (in Go 1.26+, built-in new(true) and new(false) work identically).

func ClassifyAPIError added in v0.1.4

func ClassifyAPIError(status int, code, msg, sandboxID string) error

ClassifyAPIError classifies an HTTP status code, machine-readable error code, and error message into the corresponding e2b.Error type using the same status mapping as DecodeAPIError. It returns nil for a 2xx status.

func DecodeAPIError added in v0.1.4

func DecodeAPIError(resp *http.Response, sandboxID string) error

DecodeAPIError translates a non-2xx control-plane HTTP response into an e2b.Error, decoding the JSON error body ({"code", "message", "error_code"}) into the error message and BaseError.Code / BaseError.StatusCode. It returns nil for a 2xx response. The body is read (up to 1 MiB) but not closed; the caller still owns resp.Body.

Status mapping:

400       -> *InvalidArgumentError
401, 403  -> *AuthenticationError
404       -> *SandboxNotFoundError when sandboxID != "", else *NotFoundError
409       -> *ConflictError
429       -> *RateLimitError
507       -> *NotEnoughSpaceError
408, 504  -> *TimeoutError
otherwise -> *SandboxError (including 5xx such as 500/502/503)

template and volume pass sandboxID "" and may re-wrap *NotFoundError into their own resource-specific types.

func IamTokenPlaceholder added in v0.1.4

func IamTokenPlaceholder(name string) string

IamTokenPlaceholder formats a placeholder ("${e2b.identity.tokens.<name>}") that the host egress proxy replaces with a freshly minted workload identity token registered in CreateOptions.Iam.

func Kill deprecated

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.

Deprecated: prefer NewClient(cfg).Kill (see Create).

Endpoint: DELETE /sandboxes/{sandboxID} Compatibility: E2B Cloud; self-hosted runtime <= 2026.30.

func Pause deprecated added in v0.1.4

func Pause(ctx context.Context, sandboxID string, opts ...PauseOptions) (bool, error)

Pause pauses a sandbox by ID using a one-shot Client built from opts.Config. Returns true on success, or false (nil error) if the sandbox was already paused (HTTP 409).

Deprecated: prefer NewClient(cfg).Pause (see Create).

Endpoint: POST /sandboxes/{sandboxID}/pause Compatibility: E2B Cloud; self-hosted runtime <= 2026.30 (PauseOptions body requires E2B Cloud or runtime >= 2026.25). Envd: >= v0.5.0 when PauseOptions.Memory is false

func SecretPlaceholder added in v0.1.4

func SecretPlaceholder(name string) string

SecretPlaceholder formats a placeholder ("${e2b.secrets.<name>}") that the host egress proxy resolves to the secret's current value in NetworkRule header transforms without exposing the secret inside the sandbox.

Types

type AuthenticationError

type AuthenticationError struct {
	BaseError
	Message string
	Cause   error
}

AuthenticationError reports invalid or missing credentials.

func (*AuthenticationError) Error

func (e *AuthenticationError) Error() string

func (*AuthenticationError) Unwrap added in v0.1.5

func (e *AuthenticationError) Unwrap() error

type BaseError added in v0.1.4

type BaseError struct {
	// StatusCode is the HTTP status of the response this error was decoded
	// from, or 0.
	StatusCode int
	// Code is the server's machine-readable error code (the OpenAPI
	// Error.error_code field), or "".
	Code string
}

BaseError is embedded by every concrete SDK error type so they all satisfy Error automatically. Subpackages (template, volume) embed it too so their error types satisfy e2b.Error.

For errors decoded from a control-plane HTTP response, StatusCode carries the HTTP status and Code the machine-readable `error_code` from the JSON error body (e.g. "sandbox_capacity_unavailable"); both are zero otherwise.

func (BaseError) ErrorCode added in v0.1.4

func (e BaseError) ErrorCode() string

ErrorCode returns the server's machine-readable error code, if any.

func (BaseError) HTTPStatus added in v0.1.4

func (e BaseError) HTTPStatus() int

HTTPStatus returns the HTTP status code the error was decoded from, or 0.

type BuildError

type BuildError struct {
	BaseError
	Message string
	Cause   error
}

BuildError reports a template build failure.

func (*BuildError) Error

func (e *BuildError) Error() string

func (*BuildError) Unwrap

func (e *BuildError) Unwrap() error

type Client added in v0.1.2

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

Client is the unified entry point to the E2B control plane. It resolves a Config once and constructs shared control-plane (with retries and RequestTimeout) and data-plane (no retries, no client-wide timeout) HTTP clients reused across every call and by every Sandbox it creates.

Prefer holding one *Client for the lifetime of your program (or per credential set) over the package-level Create/Connect/Kill helpers, which build a throwaway Client per call and so cannot reuse the REST client across calls.

A *Client is safe for concurrent use.

func NewClient added in v0.1.2

func NewClient(cfg Config) (*Client, error)

NewClient resolves cfg (applying environment-variable fallbacks and defaults) and builds the shared control-plane and data-plane HTTP clients. Every Sandbox created through the returned Client reuses them.

A zero Config is valid; credentials and domain fall back to the environment. It returns *InvalidArgumentError for an unusable Proxy or HTTPVersion.

Example
package main

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

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

func main() {
	ctx := context.Background()
	client, err := e2b.NewClient(e2b.Config{
		APIKey: "e2b_...",
	})
	if err != nil {
		log.Fatal(err)
	}

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

	h, err := sbx.Commands.Run(ctx, "echo hello", e2b.RunOptions{})
	if err != nil {
		log.Fatal(err)
	}
	res, err := h.Wait(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(res.Stdout)
}

func (*Client) Config added in v0.1.2

func (c *Client) Config() Config

Config returns a copy of the resolved Config backing this Client. The map fields (Headers, ExtraSandboxHeaders) and Retries pointer are deep-copied so mutating the returned Config cannot alter this Client's live request headers or race with concurrent requests.

func (*Client) Connect added in v0.1.2

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

Connect attaches to an existing sandbox (running or paused) via POST /v2/sandboxes/{sandboxID}/connect. If paused, the server resumes it. When opts.Timeout == 0, timeout is omitted so the server default applies; negative durations return *InvalidArgumentError. It does not fall back to ConnectV1 or Resume on self-hosted servers.

opts.Config is ignored (see Create).

Endpoint: POST /v2/sandboxes/{sandboxID}/connect Compatibility: E2B Cloud only (not in self-hosted runtime <= 2026.30; use ConnectV1 or Resume). Envd: >= v0.1.0

func (*Client) ConnectV1 added in v0.1.4

func (c *Client) ConnectV1(ctx context.Context, sandboxID string, opts ...ConnectOptions) (*Sandbox, error)

ConnectV1 attaches to an existing sandbox (running or paused) via POST /sandboxes/{sandboxID}/connect, resuming it if paused. If opts.Timeout == 0, DefaultSandboxTimeout (5 minutes) is sent; negative durations return *InvalidArgumentError.

Marked soft-deprecated in newer OpenAPI specs in favor of Connect (POST /v2/sandboxes/{sandboxID}/connect), this endpoint remains actively served (not retired) on both E2B Cloud and self-hosted runtime 2025.44..2026.30. Choose ConnectV1 as the primary idempotent connect/wake endpoint on self-hosted runtime 2025.44..2026.30; prefer Connect on E2B Cloud, and use Resume on self-hosted runtime < 2025.44 (where /connect does not exist).

opts.Config is ignored (see Create).

Endpoint: POST /sandboxes/{sandboxID}/connect Compatibility: E2B Cloud and self-hosted runtime 2025.44..2026.30 (actively served; primary connect/wake endpoint on self-hosted 2025.44..2026.30; use Resume on < 2025.44). Envd: >= v0.1.0

func (*Client) Create added in v0.1.2

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

Create provisions a new sandbox via POST /v2/sandboxes and returns a *Sandbox wired up with all sub-clients, sharing this Client's HTTP and REST clients. It does not fall back to POST /sandboxes on self-hosted servers; use CreateV1 on self-hosted deployments (runtime <= 2026.30).

opts.Config is ignored: the Client already owns the resolved configuration.

Endpoint: POST /v2/sandboxes Compatibility: E2B Cloud only (not in self-hosted runtime <= 2026.30; use CreateV1). Envd: >= v0.1.0

func (*Client) CreateSecret added in v0.1.4

func (c *Client) CreateSecret(ctx context.Context, name, value string, opts ...SecretOptions) (*SecretInfo, error)

CreateSecret creates a new project secret and stores its initial write-only value.

Endpoint: POST /secrets Compatibility: E2B Cloud; self-hosted runtime 2026.30 (not in runtime < 2026.30).

func (*Client) CreateSnapshot added in v0.1.4

func (c *Client) CreateSnapshot(ctx context.Context, sandboxID string, opts ...CreateSnapshotOptions) (*SnapshotInfo, error)

CreateSnapshot persists a sandbox's current state as a reusable snapshot template.

Endpoint: POST /sandboxes/{sandboxID}/snapshots Compatibility: E2B Cloud; self-hosted runtime 2026.08..2026.30 (not in runtime < 2026.08). Envd: >= v0.5.0

func (*Client) CreateV1 added in v0.1.4

func (c *Client) CreateV1(ctx context.Context, opts ...CreateOptions) (*Sandbox, error)

CreateV1 provisions a new sandbox via POST /sandboxes. By default it sends secure=true so self-hosted servers (< 2026.30) mint an EnvdAccessToken; set opts.Insecure = true only for legacy templates (envd < 0.2.0) that predate secured envd access.

Although marked deprecated in newer OpenAPI specs in favor of Create (POST /v2/sandboxes), POST /sandboxes is soft-deprecated (not retired) and remains actively served on both E2B Cloud and all self-hosted runtime <= 2026.30 deployments. Choose CreateV1 on all self-hosted runtime <= 2026.30 clusters (where /v2/sandboxes does not exist); prefer Create on E2B Cloud.

opts.Config and opts.IdempotencyKey are ignored on v1.

Endpoint: POST /sandboxes Compatibility: E2B Cloud and self-hosted runtime <= 2026.30 (actively served; primary create endpoint on self-hosted, soft-deprecated in OpenAPI in favor of Create on E2B Cloud). Envd: >= v0.2.0 with default secure=true (>= v0.1.0 when Insecure is true)

func (*Client) DeleteSecret added in v0.1.4

func (c *Client) DeleteSecret(ctx context.Context, secretIDOrName string) (bool, error)

DeleteSecret revokes a secret by ID or name. Returns false (nil error) if the secret was already absent.

Endpoint: DELETE /secrets/{secretID} Compatibility: E2B Cloud; self-hosted runtime 2026.30 (not in runtime < 2026.30).

func (*Client) DeleteSnapshot added in v0.1.3

func (c *Client) DeleteSnapshot(ctx context.Context, snapshotID string) (bool, error)

DeleteSnapshot deletes a snapshot by its ID (the snapshot template ID, optionally with a tag). Returns false (nil error) if the snapshot was already gone, mirroring Client.Kill.

Endpoint: DELETE /templates/{templateID} Compatibility: E2B Cloud; self-hosted runtime 2026.08..2026.30 (not in runtime < 2026.08).

func (*Client) Fork added in v0.1.4

func (c *Client) Fork(ctx context.Context, sandboxID string, opts ...ForkOptions) ([]ForkResult, error)

Fork checkpoints a running sandbox in place (preserving its ID and expiration) and boots one or more new sandboxes from that checkpoint. Each requested fork succeeds or fails independently in the returned slice.

Endpoint: POST /sandboxes/{sandboxID}/fork Compatibility: E2B Cloud; self-hosted runtime 2026.29..2026.30 (not in runtime < 2026.29). Envd: >= v0.5.0

func (*Client) GetBatchMetrics added in v0.1.4

func (c *Client) GetBatchMetrics(ctx context.Context, sandboxIDs []string) (map[string]SandboxMetric, error)

GetBatchMetrics fetches the latest metric sample for multiple sandboxes in a single control-plane call, keyed by sandbox ID.

Endpoint: GET /sandboxes/metrics Compatibility: E2B Cloud; self-hosted runtime <= 2026.30. Envd: >= v0.1.5

func (*Client) GetInfo added in v0.1.4

func (c *Client) GetInfo(ctx context.Context, sandboxID string) (*SandboxInfo, error)

GetInfo fetches control-plane metadata for a sandbox by ID. Legacy servers (< 2025.31) that return 200 OK with an empty state field are normalized to SandboxStateRunning.

Endpoint: GET /sandboxes/{sandboxID} Compatibility: E2B Cloud; self-hosted runtime <= 2026.30.

func (*Client) GetLogs added in v0.1.4

func (c *Client) GetLogs(ctx context.Context, sandboxID string, opts ...SandboxLogsOptions) ([]SandboxLogEntry, error)

GetLogs fetches structured logs for a sandbox via the v2 logs endpoint. It does not fall back to GetLogsV1 on older self-hosted servers.

Endpoint: GET /v2/sandboxes/{sandboxID}/logs Compatibility: E2B Cloud; self-hosted runtime 2026.07..2026.30 (use GetLogsV1 on < 2026.07).

func (*Client) GetLogsV1 added in v0.1.4

func (c *Client) GetLogsV1(ctx context.Context, sandboxID string, opts ...SandboxLogsV1Options) (*SandboxLogsV1, error)

GetLogsV1 fetches sandbox logs via GET /sandboxes/{sandboxID}/logs, returning both plain-text lines and structured entries when provided by the server.

Soft-deprecated in OpenAPI in favor of GetLogs (GET /v2/sandboxes/{sandboxID}/logs, added in runtime 2026.07 with cursor/direction/level/search filtering), this endpoint remains actively served (not retired) on both E2B Cloud and all self-hosted runtime <= 2026.30 deployments. Choose GetLogsV1 on self-hosted runtime < 2026.07 (where /v2/sandboxes/{sandboxID}/logs does not exist) or when plain-text Logs lines are needed; prefer GetLogs on E2B Cloud and runtime >= 2026.07.

Endpoint: GET /sandboxes/{sandboxID}/logs Compatibility: E2B Cloud and self-hosted runtime <= 2026.30 (actively served; required on < 2026.07; soft-deprecated in OpenAPI in favor of GetLogs).

func (*Client) GetMetrics added in v0.1.4

func (c *Client) GetMetrics(ctx context.Context, sandboxID string, opts ...MetricsOptions) ([]SandboxMetric, error)

GetMetrics fetches CPU, memory (including MemCache), and disk usage samples for a sandbox by ID.

Endpoint: GET /sandboxes/{sandboxID}/metrics Compatibility: E2B Cloud; self-hosted runtime <= 2026.30 (MemCache requires E2B Cloud or runtime >= 2026.14). Envd: >= v0.1.5

func (*Client) GetSecret added in v0.1.4

func (c *Client) GetSecret(ctx context.Context, secretIDOrName string) (*SecretInfo, error)

GetSecret fetches metadata for one secret by ID or name.

Endpoint: GET /secrets/{secretID} Compatibility: E2B Cloud; self-hosted runtime 2026.30 (not in runtime < 2026.30).

func (*Client) HTTPClient added in v0.1.4

func (c *Client) HTTPClient() *http.Client

HTTPClient returns the shared control-plane *http.Client backing this Client (configured with retries and RequestTimeout).

func (*Client) Health added in v0.1.4

func (c *Client) Health(ctx context.Context) error

Health probes the control-plane API readiness endpoint (GET /health), returning nil on any 2xx status or an Error when the service is unhealthy.

Endpoint: GET /health Compatibility: E2B Cloud; self-hosted runtime <= 2026.30.

func (*Client) IsRunning added in v0.1.4

func (c *Client) IsRunning(ctx context.Context, sandboxID string) (bool, error)

IsRunning reports whether the sandbox identified by sandboxID is currently in the running state according to the control plane (GET /sandboxes/{sandboxID}). Returns (false, nil) if the sandbox is paused or no longer exists.

Endpoint: GET /sandboxes/{sandboxID} Compatibility: E2B Cloud; self-hosted runtime <= 2026.30.

func (*Client) Kill added in v0.1.2

func (c *Client) Kill(ctx context.Context, sandboxID string) (bool, error)

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

Endpoint: DELETE /sandboxes/{sandboxID} Compatibility: E2B Cloud; self-hosted runtime <= 2026.30.

func (*Client) List added in v0.1.2

List returns a paginator over the sandboxes visible to this Client. The request is not issued until the first NextItems call. It does not fall back to ListV1 on legacy servers.

Endpoint: GET /v2/sandboxes Compatibility: E2B Cloud; self-hosted runtime 2025.31..2026.30 (use ListV1 on < 2025.31).

func (*Client) ListAll added in v0.1.2

func (c *Client) ListAll(ctx context.Context, opts ...SandboxListOptions) ([]SandboxInfo, error)

ListAll drains every page and returns all matching sandboxes. Prefer List for large result sets where streaming pages avoids buffering everything.

Endpoint: GET /v2/sandboxes Compatibility: E2B Cloud; self-hosted runtime 2025.31..2026.30 (use ListV1 on < 2025.31).

func (*Client) ListAllSecrets added in v0.1.4

func (c *Client) ListAllSecrets(ctx context.Context, opts ...SecretListOptions) ([]SecretInfo, error)

ListAllSecrets drains every page and returns all project secrets.

Endpoint: GET /secrets Compatibility: E2B Cloud; self-hosted runtime 2026.30 (not in runtime < 2026.30).

func (*Client) ListAllSnapshots added in v0.1.3

func (c *Client) ListAllSnapshots(ctx context.Context, opts ...SnapshotListOptions) ([]SnapshotInfo, error)

ListAllSnapshots drains every page and returns all matching snapshots. Prefer ListSnapshots for large result sets where streaming pages avoids buffering everything.

Endpoint: GET /snapshots Compatibility: E2B Cloud; self-hosted runtime 2026.08..2026.30 (not in runtime < 2026.08).

func (*Client) ListSecrets added in v0.1.4

func (c *Client) ListSecrets(_ context.Context, opts ...SecretListOptions) *SecretPaginator

ListSecrets returns a paginator over the project's secrets. No network request is issued until the first NextItems call.

Endpoint: GET /secrets Compatibility: E2B Cloud; self-hosted runtime 2026.30 (not in runtime < 2026.30).

func (*Client) ListSnapshots added in v0.1.3

func (c *Client) ListSnapshots(_ context.Context, opts ...SnapshotListOptions) *SnapshotPaginator

ListSnapshots returns a paginator over the snapshots visible to this Client. The request is not issued until the first NextItems call.

Endpoint: GET /snapshots Compatibility: E2B Cloud; self-hosted runtime 2026.08..2026.30 (not in runtime < 2026.08).

func (*Client) ListV1 added in v0.1.4

func (c *Client) ListV1(ctx context.Context, opts ...SandboxListV1Options) ([]SandboxInfo, error)

ListV1 lists running sandboxes via the unpaginated GET /sandboxes endpoint.

Soft-deprecated in OpenAPI in favor of cursor-paginated List / ListAll (GET /v2/sandboxes, added in runtime 2025.31 with paused-sandbox visibility), GET /sandboxes remains actively served (not retired) on both E2B Cloud and all self-hosted runtime <= 2026.30 deployments (returning HTTP 400 only when more than 5000 running sandboxes match). Choose ListV1 on self-hosted runtime < 2025.31 (where /v2/sandboxes does not exist); prefer List / ListAll on E2B Cloud and runtime >= 2025.31.

Endpoint: GET /sandboxes Compatibility: E2B Cloud and self-hosted runtime <= 2026.30 (actively served; required on < 2025.31; soft-deprecated in OpenAPI in favor of List / ListAll).

func (*Client) Pause added in v0.1.4

func (c *Client) Pause(ctx context.Context, sandboxID string, opts ...PauseOptions) (bool, error)

Pause pauses a sandbox by ID. Returns true on success, or false (nil error) if the sandbox was already paused (HTTP 409). When opts is omitted or zero, no JSON body is sent so older servers (< runtime 2026.25) accept the call.

Endpoint: POST /sandboxes/{sandboxID}/pause Compatibility: E2B Cloud; self-hosted runtime <= 2026.30 (PauseOptions body requires E2B Cloud or runtime >= 2026.25). Envd: >= v0.5.0 when PauseOptions.Memory is false

func (*Client) RefreshTimeout added in v0.1.4

func (c *Client) RefreshTimeout(ctx context.Context, sandboxID string, duration time.Duration) error

RefreshTimeout extends a sandbox's TTL monotonically via POST /sandboxes/{sandboxID}/refreshes: shorter durations never shrink an existing longer expiration, unlike SetTimeout which overwrites the TTL relative to the current server time.

Remains actively served on both E2B Cloud and all self-hosted runtime <= 2026.30 deployments. Choose RefreshTimeout for monotonic keepalive heartbeats; choose SetTimeout when setting an exact new TTL (including shortening it).

Endpoint: POST /sandboxes/{sandboxID}/refreshes Compatibility: E2B Cloud; self-hosted runtime <= 2026.30 (actively served).

func (*Client) RefreshTimeoutV1 added in v0.1.4

func (c *Client) RefreshTimeoutV1(ctx context.Context, sandboxID string, duration time.Duration) error

RefreshTimeoutV1 is a version-suffixed alias for RefreshTimeout (POST /sandboxes/{sandboxID}/refreshes). See RefreshTimeout for details.

Endpoint: POST /sandboxes/{sandboxID}/refreshes Compatibility: E2B Cloud; self-hosted runtime <= 2026.30 (actively served).

func (*Client) Resume added in v0.1.4

func (c *Client) Resume(ctx context.Context, sandboxID string, opts ...ResumeOptions) (*Sandbox, error)

Resume wakes a paused sandbox via POST /sandboxes/{sandboxID}/resume.

  • Why marked deprecated in OpenAPI: Soft-deprecated since runtime 2025.44 introduced idempotent /connect (ConnectV1, which attaches if running or wakes if paused, whereas /resume returns *ConflictError / HTTP 409 if the sandbox is already running).
  • Availability: Remains actively served (not retired) on both E2B Cloud and all self-hosted runtime <= 2026.30 deployments.
  • When to use: Required on self-hosted runtime < 2025.44 (where /connect does not exist) to wake paused sandboxes. On runtime >= 2025.44 or E2B Cloud, prefer ConnectV1 / Connect for general reconnect/wake, and use Resume when overriding CPUCount or AutoPause on wake or asserting that the sandbox was paused (409 Conflict if running).

opts.Config is ignored (see Create).

Endpoint: POST /sandboxes/{sandboxID}/resume Compatibility: E2B Cloud and self-hosted runtime <= 2026.30 (actively served; required on < 2025.44; soft-deprecated in OpenAPI in favor of Connect / ConnectV1). Envd: >= v0.1.0

func (*Client) ResumeV1 added in v0.1.4

func (c *Client) ResumeV1(ctx context.Context, sandboxID string, opts ResumeOptions) (*Sandbox, error)

ResumeV1 is a version-suffixed alias for Resume (POST /sandboxes/{sandboxID}/resume). See Resume for availability across E2B Cloud and self-hosted runtime <= 2026.30, why OpenAPI soft-deprecated it in favor of Connect / ConnectV1, and when to choose it.

Endpoint: POST /sandboxes/{sandboxID}/resume Compatibility: E2B Cloud and self-hosted runtime <= 2026.30 (actively served; required on < 2025.44; soft-deprecated in OpenAPI in favor of Connect / ConnectV1). Envd: >= v0.1.0

func (*Client) SecretExists added in v0.1.4

func (c *Client) SecretExists(ctx context.Context, secretIDOrName string) (bool, error)

SecretExists reports whether a secret with the given ID or name exists.

Endpoint: GET /secrets/{secretID} Compatibility: E2B Cloud; self-hosted runtime 2026.30 (not in runtime < 2026.30).

func (*Client) SetTimeout added in v0.1.4

func (c *Client) SetTimeout(ctx context.Context, sandboxID string, timeout time.Duration) error

SetTimeout updates a sandbox's timeout by ID, overwriting its TTL relative to the current server time.

Endpoint: POST /sandboxes/{sandboxID}/timeout Compatibility: E2B Cloud; self-hosted runtime <= 2026.30.

func (*Client) UpdateNetwork added in v0.1.4

func (c *Client) UpdateNetwork(ctx context.Context, sandboxID string, opts NetworkUpdateOptions) error

UpdateNetwork atomically replaces the egress network configuration of a running sandbox by ID. Omitted fields are cleared or reset on the server.

Endpoint: PUT /sandboxes/{sandboxID}/network Compatibility: E2B Cloud; self-hosted runtime 2026.12..2026.30 (not in runtime < 2026.12). Envd: >= v0.5.13 when Rules is set

func (*Client) UpdateSecret added in v0.1.4

func (c *Client) UpdateSecret(ctx context.Context, secretIDOrName, value string, opts ...SecretOptions) (*SecretInfo, error)

UpdateSecret appends a new write-only secret version (and optionally replaces stored metadata) for the secret identified by ID or name.

Endpoint: POST /secrets/{secretID} Compatibility: E2B Cloud; self-hosted runtime 2026.30 (not in runtime < 2026.30).

type CommandConnectOptions added in v0.1.4

type CommandConnectOptions struct {
	User           string
	TimeoutMs      int
	RequestTimeout time.Duration
	RetainOutput   *bool
	OnStdout       func([]byte)
	OnStderr       func([]byte)
}

CommandConnectOptions configures Commands.Connect.

type CommandExitError

type CommandExitError struct {
	BaseError
	Result CommandResult
}

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 or PTY session. Events arrive on the buffered channels returned by Stdout(), Stderr(), and PtyOutput() (with non-blocking drops on slow consumers; use OnStdout/OnStderr/OnData or Wait for guaranteed delivery); the channels close when the command exits, the stream fails, or Disconnect is called. Call Wait to block and collect the final exit code.

func (*CommandHandle) CloseStdin added in v0.1.4

func (h *CommandHandle) CloseStdin(ctx context.Context, opts ...CommandRequestOptions) error

CloseStdin closes the command's stdin descriptor to signal EOF. Requires envd >= v0.5.2; returns *TemplateError on older envd builds.

Endpoint: process.Process/CloseStdin (envd Connect-RPC) Envd: >= v0.5.2

func (*CommandHandle) Disconnect added in v0.1.4

func (h *CommandHandle) Disconnect()

Disconnect cancels the client event stream locally without killing the remote process inside the sandbox. You can reconnect later via Commands.Connect or Pty.Connect. Calling Disconnect multiple times is safe and idempotent.

Stopping OnStdout/OnStderr/OnData callbacks is best-effort: Disconnect does not hold locks around callback execution or wait for an in-flight callback to return (so callbacks may safely call Disconnect re-entrantly without deadlocking), and a callback already being dispatched concurrently may still complete after Disconnect returns.

func (*CommandHandle) ExitCode added in v0.1.4

func (h *CommandHandle) ExitCode() (int32, bool)

ExitCode returns the command's exit code and true once the process has exited, or (0, false) while the process is still running.

func (*CommandHandle) Kill

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

Kill sends SIGKILL to the running command or PTY session. It returns (false, nil) if the process has already exited (Connect CodeNotFound).

Endpoint: process.Process/SendSignal (envd Connect-RPC) Envd: >= v0.1.0

func (*CommandHandle) PID

func (h *CommandHandle) PID() uint32

PID returns the command's process ID once known (0 until the StartEvent arrives). Use WaitPID to block until the StartEvent has populated the PID.

func (*CommandHandle) PtyOutput

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

PtyOutput returns a buffered channel (capacity 32) of PTY output byte slices (empty for non-PTY commands). Sends are non-blocking: if the channel buffer is full because the consumer is slow or not reading, incoming chunks are dropped without blocking the event stream. Callers that need guaranteed delivery of every chunk should use PtyOptions.OnData or PtyConnectOptions.OnData. The channel is closed when the PTY session exits or the client stream ends.

func (*CommandHandle) ResizePty added in v0.1.4

func (h *CommandHandle) ResizePty(ctx context.Context, cols, rows uint32, opts ...CommandRequestOptions) error

ResizePty changes this PTY session's terminal dimensions (columns and rows).

Endpoint: process.Process/Update (envd Connect-RPC) Envd: >= v0.1.0

func (*CommandHandle) SendPty added in v0.1.4

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

SendPty writes raw terminal bytes into this PTY session.

Endpoint: process.Process/SendInput (envd Connect-RPC) Envd: >= v0.1.0

func (*CommandHandle) SendSignal added in v0.1.4

func (h *CommandHandle) SendSignal(ctx context.Context, sig Signal, opts ...CommandRequestOptions) (bool, error)

SendSignal sends sig (SignalSIGTERM or SignalSIGKILL) to the running command or PTY session. It returns (false, nil) if the process has already exited (Connect CodeNotFound).

Endpoint: process.Process/SendSignal (envd Connect-RPC) Envd: >= v0.1.0

func (*CommandHandle) SendStdin

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

SendStdin writes data to the command's stdin.

Endpoint: process.Process/SendInput (envd Connect-RPC) Envd: >= v0.1.0

func (*CommandHandle) Stderr

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

Stderr returns a buffered channel (capacity 32) of stderr byte slices. Sends are non-blocking: if the channel buffer is full because the consumer is slow or not reading, incoming chunks are dropped without blocking the event stream. Callers that need guaranteed delivery of every chunk should use RunOptions.OnStderr / CommandConnectOptions.OnStderr or inspect CommandResult.Stderr returned by Wait. The channel is closed when the command exits or the client stream ends.

func (*CommandHandle) Stdout

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

Stdout returns a buffered channel (capacity 32) of stdout byte slices. Sends are non-blocking: if the channel buffer is full because the consumer is slow or not reading, incoming chunks are dropped without blocking the event stream. Callers that need guaranteed delivery of every chunk should use RunOptions.OnStdout / CommandConnectOptions.OnStdout or inspect CommandResult.Stdout returned by Wait. The channel is closed when the command exits or the client stream ends.

func (*CommandHandle) StreamInput added in v0.1.4

StreamInput opens a persistent, ordered client-streaming stdin connection to this command.

Endpoint: process.Process/StreamInput (envd Connect-RPC) Envd: >= v0.1.0

func (*CommandHandle) StreamPtyInput added in v0.1.4

func (h *CommandHandle) StreamPtyInput(ctx context.Context, opts ...CommandRequestOptions) (*PtyInputStream, error)

StreamPtyInput opens a persistent, ordered client-streaming PTY input connection to this PTY session.

Endpoint: process.Process/StreamInput (envd Connect-RPC) Envd: >= v0.1.0

func (*CommandHandle) Wait

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

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

func (*CommandHandle) WaitPID added in v0.1.4

func (h *CommandHandle) WaitPID(ctx context.Context) (uint32, error)

WaitPID blocks until the server emits the initial StartEvent (or the stream or ctx terminates) and returns the process ID.

type CommandInputStream added in v0.1.4

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

CommandInputStream is a persistent client-streaming stdin handle opened by Commands.StreamInput. All methods are safe for concurrent use.

func (*CommandInputStream) Close added in v0.1.4

func (cs *CommandInputStream) Close() error

Close ends the client input stream and waits for envd to acknowledge it. Calling Close multiple times is safe and returns the same error.

Endpoint: process.Process/StreamInput (envd Connect-RPC) Envd: >= v0.1.0

func (*CommandInputStream) Send added in v0.1.4

func (cs *CommandInputStream) Send(data []byte) error

Send is an alias for SendData.

Endpoint: process.Process/StreamInput (envd Connect-RPC) Envd: >= v0.1.0

func (*CommandInputStream) SendData added in v0.1.4

func (cs *CommandInputStream) SendData(data []byte) error

SendData sends a chunk of stdin bytes to the command in call order.

Endpoint: process.Process/StreamInput (envd Connect-RPC) Envd: >= v0.1.0

type CommandRequestOptions added in v0.1.4

type CommandRequestOptions struct {
	User           string
	RequestTimeout time.Duration
}

CommandRequestOptions configures per-call user and request timeout for unary and client-streaming command and PTY operations.

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 in-sandbox command execution and process management endpoints over envd's Connect-RPC Process service (implemented in commands_impl.go).

func (*Commands) CloseStdin

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

CloseStdin closes the stdin descriptor of the process identified by PID to signal EOF.

Closing stdin requires envd >= v0.5.2; on an older build this returns *TemplateError up front instead of failing opaquely at the RPC layer.

Endpoint: process.Process/CloseStdin (envd Connect-RPC) Envd: >= v0.5.2

func (*Commands) Connect

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

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

Endpoint: process.Process/Connect (envd Connect-RPC) Envd: >= v0.1.0

func (*Commands) ConnectByTag added in v0.1.4

func (c *Commands) ConnectByTag(ctx context.Context, tag string, opts ...CommandConnectOptions) (*CommandHandle, error)

ConnectByTag attaches to a running process by its custom tag and streams its remaining output.

Endpoint: process.Process/Connect (envd Connect-RPC) Envd: >= v0.1.0

func (*Commands) Kill

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

Kill sends SIGKILL to the command identified by PID. It returns (false, nil) if the process is no longer running (Connect CodeNotFound).

Endpoint: process.Process/SendSignal (envd Connect-RPC) Envd: >= v0.1.0

func (*Commands) KillByTag added in v0.1.4

func (c *Commands) KillByTag(ctx context.Context, tag string, opts ...CommandRequestOptions) (bool, error)

KillByTag sends SIGKILL to the command identified by tag. It returns (false, nil) if the process is no longer running (Connect CodeNotFound).

Endpoint: process.Process/SendSignal (envd Connect-RPC) Envd: >= v0.1.0

func (*Commands) List

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

List returns all commands and PTY sessions currently running inside the sandbox.

Endpoint: process.Process/List (envd Connect-RPC) Envd: >= v0.1.0

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 live handle immediately). Callers may observe output through the returned handle's channels or the OnStdout/OnStderr callbacks. When opts.Shell is non-empty, cmd is executed via `<Shell> -l -c <cmd>`; otherwise cmd is invoked directly with opts.Args.

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Commands) SendSignal added in v0.1.4

func (c *Commands) SendSignal(ctx context.Context, pid uint32, sig Signal, opts ...CommandRequestOptions) (bool, error)

SendSignal sends sig (SignalSIGTERM or SignalSIGKILL) to the command identified by PID. It returns (false, nil) if the process is no longer running (Connect CodeNotFound).

Endpoint: process.Process/SendSignal (envd Connect-RPC) Envd: >= v0.1.0

func (*Commands) SendStdin

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

SendStdin writes bytes to the stdin of the running process identified by PID.

Endpoint: process.Process/SendInput (envd Connect-RPC) Envd: >= v0.1.0

func (*Commands) Start

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

Start launches cmd and returns a live *CommandHandle streaming process events. When opts.Shell is non-empty, cmd is executed via `<Shell> -l -c <cmd>`; otherwise cmd is executed directly with opts.Args.

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Commands) StreamInput added in v0.1.4

func (c *Commands) StreamInput(ctx context.Context, pid uint32, opts ...CommandRequestOptions) (*CommandInputStream, error)

StreamInput opens a persistent, ordered client-streaming stdin connection to the command identified by PID. Call SendData to write ordered chunks and Close to finish the stream and await envd's acknowledgement.

Endpoint: process.Process/StreamInput (envd Connect-RPC) Envd: >= v0.1.0

type Config

type Config struct {
	// APIKey authenticates team-scoped requests (X-API-Key header).
	// Defaults to $E2B_API_KEY. When both APIKey and AccessToken are set,
	// only APIKey is sent.
	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

	// VolumeAPIURL overrides the volume-content API URL. Defaults to
	// $E2B_VOLUME_API_URL, or http://localhost:8080 when Debug is true. When
	// empty the volume package derives https://api.<volume domain> from the
	// domain the control plane returns for each volume.
	VolumeAPIURL 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

	// Retries is the number of control-plane retries for responses marked
	// `Should-Retry: true`, or 429/502/503/504 responses without that header
	// (`Should-Retry: false` is never retried), and for failures to establish
	// the connection. Waits honor Retry-After, otherwise jittered exponential
	// backoff from 100ms to 10s; a retry whose wait would exhaust the request
	// timeout is skipped. nil means DefaultRetries (3); a pointer to 0
	// disables retries; negative values are treated as 0. Retries never apply
	// to envd (data-plane) traffic.
	Retries *int

	// Proxy is an HTTP(S) or SOCKS5 proxy URL used for every SDK request
	// (control plane, envd and volume content); a bare "host:port" means
	// http://host:port. When empty, the standard HTTP_PROXY/HTTPS_PROXY/
	// NO_PROXY environment variables apply. NewClient rejects an unusable
	// value with *InvalidArgumentError, and requests never silently bypass a
	// configured proxy. Ignored when HTTPClient is set.
	Proxy string

	// HTTPVersion selects the HTTP protocol: HTTPVersion1 ("1.1") disables
	// HTTP/2, HTTPVersion2 ("2") enables HTTP/2 over TLS (with HTTP/1.1
	// fallback). Defaults to $E2B_HTTP_VERSION, else Go's default (HTTP/2
	// negotiated over TLS). NewClient rejects any other value with
	// *InvalidArgumentError. Ignored when HTTPClient is set.
	HTTPVersion string

	// Headers added to every control-plane REST request. They are never sent
	// to envd (use ExtraSandboxHeaders for that).
	Headers map[string]string

	// ExtraSandboxHeaders added only to envd traffic. They can never set the
	// envd Authorization header.
	ExtraSandboxHeaders map[string]string

	// HTTPClient optionally overrides the transport. If nil the SDK builds
	// clients on a shared, pooled transport honoring Proxy and HTTPVersion.
	// Control-plane requests wrap its Transport with the retry policy.
	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_VOLUME_API_URL, E2B_HTTP_VERSION, E2B_DEBUG) and then to sensible defaults.

func (Config) Clone added in v0.1.4

func (c Config) Clone() Config

Clone returns a copy of c with Headers, ExtraSandboxHeaders, and Retries deep-copied so mutating the returned Config cannot alias c.

func (Config) ControlPlaneHTTPClient added in v0.1.4

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

ControlPlaneHTTPClient returns the *http.Client for control-plane REST requests (https://api.<domain>): RequestTimeout bounds each call (including retries) and the transport applies the Retries policy. When HTTPClient is set, its Transport (or http.DefaultTransport) is wrapped and its Timeout, Jar and CheckRedirect are preserved.

Call it on a resolved Config (see Resolve).

func (Config) DataPlaneHTTPClient added in v0.1.4

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

DataPlaneHTTPClient returns the *http.Client for envd and volume-content traffic: the shared pooled base transport with no control-plane retry wrapper and no client-wide Timeout, so long-lived envd streams (commands, PTY, watch) and large uploads/downloads are not cut off. Callers bound unary requests with a context deadline (typically RequestTimeout). When HTTPClient is set it is returned unchanged unless its Transport is a control-plane retry wrapper (e.g. from Client.HTTPClient()), in which case a shallow copy is returned with the retry wrapper unwrapped and Timeout cleared so data-plane traffic never inherits control-plane retries.

Call it on a resolved Config (see Resolve).

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. The returned Config never aliases the caller's Headers / ExtraSandboxHeaders maps.

func (Config) ResolvedHTTPClient

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

ResolvedHTTPClient returns the HTTP client this Config would use without control-plane retries: the HTTPClient field if set, else an *http.Client on the shared pooled transport with RequestTimeout. Named with the Resolved- prefix because it would otherwise collide with the HTTPClient struct field.

Call it on a resolved Config (see Resolve).

func (Config) Validate added in v0.1.4

func (c Config) Validate() error

Validate checks that RequestTimeout is non-negative and that Proxy and HTTPVersion (when HTTPClient is nil) are valid, returning *InvalidArgumentError otherwise.

type ConflictError added in v0.1.4

type ConflictError struct {
	BaseError
	Message string
}

ConflictError reports HTTP 409 from the control plane (e.g. a resource that already exists, an operation incompatible with the current state, or an idempotency-key conflict; see Code).

func (*ConflictError) Error added in v0.1.4

func (e *ConflictError) Error() string

type ConnectOptions

type ConnectOptions struct {
	Config Config
	// Timeout sets the sandbox TTL. On Connect (/v2/sandboxes/{id}/connect),
	// 0 omits timeout so the server default (5 minutes) applies; on ConnectV1
	// (/sandboxes/{id}/connect), 0 sends DefaultSandboxTimeout. Sub-second
	// positive durations round up to the next whole second; negative or
	// out-of-range durations return *InvalidArgumentError.
	Timeout time.Duration
	// OnResume controls how a paused sandbox comes back: "restore" (restore
	// memory snapshot, memory=true) or "reboot" (cold-boot from disk,
	// memory=false). Empty omits memory so the server default applies.
	OnResume string
}

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" (or
	// "mcp-gateway" when Mcp is non-nil).
	Template string
	// Timeout is the sandbox lifetime. Defaults to 5 minutes when 0; sub-second
	// positive durations round up to the next whole second, and negative or
	// out-of-range durations return *InvalidArgumentError.
	Timeout time.Duration
	// IdempotencyKey sets the Idempotency-Key header on Create (POST /v2/sandboxes)
	// using 1..255 lowercase ASCII letters, digits, or hyphens.
	IdempotencyKey string
	// CPUCount overrides the initial online vCPU count (1..template maxCpuCount).
	CPUCount *int32

	// 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 on legacy POST /sandboxes.
	//
	// Deprecated: Create (/v2/sandboxes) is always secured, and CreateV1
	// (/sandboxes) defaults to secure=true unless Insecure is true.
	Secure bool
	// Insecure explicitly sends secure=false on CreateV1 (POST /sandboxes) for
	// legacy self-hosted templates (envd < 0.2.0) that do not support envd
	// access tokens. Ignored by Create (/v2/sandboxes).
	Insecure bool

	// AllowInternetAccess enables outbound internet. Defaults to true.
	// Use AllowInternetAccessSet=true to send an explicit value.
	AllowInternetAccess    bool
	AllowInternetAccessSet bool

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

	// Mcp configures and starts the in-sandbox MCP gateway (defaults Template
	// to "mcp-gateway" when Template is empty).
	Mcp map[string]any
}

CreateOptions captures every parameter accepted by Client.Create and Client.CreateV1. All fields are optional except — implicitly — an API key or access token reachable via Config/env.

type CreateSnapshotOptions added in v0.1.4

type CreateSnapshotOptions struct {
	// Name is an optional snapshot template name. If a snapshot template with
	// this name already exists, a new build is assigned to that template.
	Name string
	// Mode controls what the snapshot persists: "full" (memory + filesystem,
	// server default) or "filesystem" (filesystem only; sandboxes started from
	// it cold-boot from disk). Empty omits memory so the server default applies.
	Mode string
	// IdempotencyKey sets the optional Idempotency-Key header for safe retries
	// (supported on E2B Cloud).
	IdempotencyKey string
}

CreateSnapshotOptions configures CreateSnapshot (POST /sandboxes/{sandboxID}/snapshots).

type EgressProxyOptions added in v0.1.4

type EgressProxyOptions struct {
	// Address is the SOCKS5 proxy address in host:port form (e.g.
	// "proxy.example.com:1080").
	Address string
	// Username is the optional SOCKS5 username (RFC 1929).
	Username string
	// Password is the optional SOCKS5 password (RFC 1929; never returned by GetInfo).
	Password string
	// TLS configures optional TLS wrapping on the hop to the SOCKS5 proxy.
	TLS *EgressProxyTLSOptions
}

EgressProxyOptions configures a SOCKS5 proxy ("bring your own proxy") through which outbound sandbox TCP connections are tunneled after allow/deny filtering.

type EgressProxyTLSOptions added in v0.1.4

type EgressProxyTLSOptions struct {
	// Enabled turns on TLS wrapping for the SOCKS5 proxy connection.
	Enabled bool
	// ServerName overrides SNI and certificate hostname verification (defaults
	// to the host part of EgressProxyOptions.Address).
	ServerName string
	// CACert provides PEM-encoded root CA certificate(s) replacing the host
	// system trust store (never returned by GetInfo).
	CACert string
}

EgressProxyTLSOptions configures TLS on the connection to a BYOP SOCKS5 egress proxy.

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
	Metadata      map[string]string
}

EntryInfo is the metadata for a file, directory, or symlink.

type EntryType

type EntryType int

EntryType distinguishes file, directory, and symlink entries.

const (
	EntryTypeUnspecified EntryType = iota
	EntryTypeFile
	EntryTypeDirectory
	EntryTypeSymlink
)

func (EntryType) String added in v0.1.4

func (t EntryType) String() string

String returns the canonical string name of the entry type ("file", "directory", "symlink", or "" when unspecified).

type EnvdMetrics added in v0.1.4

type EnvdMetrics struct {
	TimestampUnix     int64
	Timestamp         time.Time
	CPUCount          int32
	CPUPossible       int32
	CPUTarget         int32
	CPUTargetAttempts int32
	CPUWritePendingMs int64
	CPUUsedPct        float32
	MemTotal          int64
	MemUsed           int64
	MemCache          int64
	DiskUsed          int64
	DiskTotal         int64
	// OOMKills contains up to the latest 32 guest OOM kills since boot, or nil
	// when omitted by envd.
	OOMKills []EnvdOOMKill
}

EnvdMetrics holds live guest resource usage metrics returned directly by the in-sandbox envd daemon (GET /metrics). Unlike control-plane Sandbox.GetMetrics (which returns historical time-series samples), GetEnvdMetrics queries envd directly for an immediate snapshot including CPU hotplug state and OOM kills.

type EnvdOOMKill added in v0.1.4

type EnvdOOMKill struct {
	Process string
	Seq     int64
}

EnvdOOMKill records a process killed by the guest kernel OOM killer, as reported by envd GET /metrics.

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 {
	BaseError
	Path    string
	Message string
	Cause   error
}

FileNotFoundError reports a missing file/directory in the sandbox.

func (*FileNotFoundError) Error

func (e *FileNotFoundError) Error() string

func (*FileNotFoundError) Unwrap added in v0.1.5

func (e *FileNotFoundError) Unwrap() error

type FileUploadError

type FileUploadError struct {
	BaseError
	Path    string
	Message string
	Cause   error
}

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 in-sandbox filesystem metadata, directory watching, and file transfer endpoints over envd's Connect-RPC Filesystem service and HTTP /files endpoints (implemented in filesystem_impl.go).

func (*Filesystem) Compose added in v0.1.4

func (f *Filesystem) Compose(ctx context.Context, sources []string, destination string, opts FsOptions) (*EntryInfo, error)

Compose concatenates multiple existing regular files inside the sandbox into destination using zero-copy kernel file assembly, deleting the source files once composition succeeds.

Requires envd >= v0.5.5; returns *TemplateError on older envd builds.

Endpoint: POST /files/compose (envd) Envd: >= v0.5.5

func (*Filesystem) Exists

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

Exists reports whether filePath exists inside the sandbox.

Endpoint: filesystem.Filesystem/Stat (envd Connect-RPC) Envd: >= v0.1.0

func (*Filesystem) GetInfo added in v0.1.4

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

GetInfo is an alias for Stat, matching the getInfo / get_info naming in the JS and Python SDKs.

Endpoint: filesystem.Filesystem/Stat (envd Connect-RPC) Envd: >= v0.1.0

func (*Filesystem) IsDir

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

IsDir reports whether filePath exists and is a directory.

Endpoint: filesystem.Filesystem/Stat (envd Connect-RPC) Envd: >= v0.1.0

func (*Filesystem) List

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

List returns the entries of a directory. opts.Depth controls how many directory levels to descend; 0 means the default (1, immediate children). A negative depth or a depth exceeding uint32 range is rejected with *InvalidArgumentError, matching the reference SDKs' depth>=1 rule.

Endpoint: filesystem.Filesystem/ListDir (envd Connect-RPC) Envd: >= v0.1.0

func (*Filesystem) MakeDir

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

MakeDir creates a directory at dirPath (including missing parent directories).

Endpoint: filesystem.Filesystem/MakeDir (envd Connect-RPC) Envd: >= v0.1.0

func (*Filesystem) Move

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

Move renames or moves a file or directory from source to destination.

Endpoint: filesystem.Filesystem/Move (envd Connect-RPC) Envd: >= v0.1.0

func (*Filesystem) Read

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

Read downloads and returns the entire file content as []byte.

Because Read buffers the entire decompressed response in memory, prefer ReadStream combined with io.LimitReader when reading untrusted, large, or gzip-compressed files.

Endpoint: GET /files (envd) Envd: >= v0.1.0

func (*Filesystem) ReadBytes added in v0.1.4

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

ReadBytes is an explicit byte-slice alias for Read.

Because ReadBytes buffers the entire decompressed response in memory, prefer ReadStream combined with io.LimitReader when reading untrusted, large, or gzip-compressed files.

Endpoint: GET /files (envd) Envd: >= v0.1.0

func (*Filesystem) ReadStream

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

ReadStream opens a streaming reader for filePath. The caller must Close the returned io.ReadCloser when done. When opts.Gzip is true, Accept-Encoding: gzip is sent and Content-Encoding: gzip responses are transparently gunzipped.

Endpoint: GET /files (envd) Envd: >= v0.1.0

func (*Filesystem) ReadString added in v0.1.4

func (f *Filesystem) ReadString(ctx context.Context, filePath string, opts FsOptions) (string, error)

ReadString downloads and returns the entire file content as a string.

Because ReadString buffers the entire decompressed response in memory, prefer ReadStream combined with io.LimitReader when reading untrusted, large, or gzip-compressed files.

Endpoint: GET /files (envd) Envd: >= v0.1.0

func (*Filesystem) Remove

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

Remove deletes a file or directory recursively.

Endpoint: filesystem.Filesystem/Remove (envd Connect-RPC) Envd: >= v0.1.0

func (*Filesystem) Rename added in v0.1.4

func (f *Filesystem) Rename(ctx context.Context, oldPath, newPath string, opts FsOptions) (*EntryInfo, error)

Rename moves or renames oldPath to newPath and returns the EntryInfo of the moved filesystem entry.

Endpoint: filesystem.Filesystem/Move (envd Connect-RPC) Envd: >= v0.1.0

func (*Filesystem) Stat

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

Stat fetches metadata for filePath.

Endpoint: filesystem.Filesystem/Stat (envd Connect-RPC) Envd: >= v0.1.0

func (*Filesystem) Watch

func (f *Filesystem) Watch(ctx context.Context, dirPath 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.

Recursive watching requires envd >= v0.1.4; requesting it on an older build returns *TemplateError up front instead of failing opaquely at the RPC layer.

Endpoint: filesystem.Filesystem/WatchDir (envd Connect-RPC) Envd: >= v0.1.0 (recursive >= v0.1.4)

func (*Filesystem) WatchWithOptions added in v0.1.4

func (f *Filesystem) WatchWithOptions(ctx context.Context, dirPath string, opts WatchOptions) (*WatchHandle, error)

WatchWithOptions starts watching a directory for filesystem events with extended options (per-call User, RequestTimeout, IncludeEntry, and AllowNetworkMounts).

Version gates:

  • Recursive requires envd >= v0.1.4 (*TemplateError below)
  • IncludeEntry requires envd >= v0.6.3 (*TemplateError below)
  • AllowNetworkMounts requires envd >= v0.6.4 (*TemplateError below)

Endpoint: filesystem.Filesystem/WatchDir (envd Connect-RPC) Envd: >= v0.1.0 (recursive >= v0.1.4; includeEntry >= v0.6.3; allowNetworkMounts >= v0.6.4)

func (*Filesystem) Write

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

Write creates or overwrites a file with the contents of r and returns the resulting WriteInfo.

The upload encoding is gated on the envd version unless opts.ForceMultipart is set: envd >= v0.5.7 accepts a raw application/octet-stream body, while older envd builds use streaming multipart/form-data. On error, r may still be read briefly by a background goroutine (including net/http and multipart pipe streaming); do not reuse r until it returns EOF or is closed.

Endpoint: POST /files (envd) Envd: >= v0.1.0 (octet-stream >= v0.5.7; metadata >= v0.6.2)

func (*Filesystem) WriteBytes added in v0.1.4

func (f *Filesystem) WriteBytes(ctx context.Context, filePath string, data []byte, opts FsOptions) (*WriteInfo, error)

WriteBytes creates or overwrites a file with data.

Endpoint: POST /files (envd) Envd: >= v0.1.0 (octet-stream >= v0.5.7; metadata >= v0.6.2)

func (*Filesystem) WriteFiles added in v0.1.3

func (f *Filesystem) WriteFiles(ctx context.Context, entries []WriteEntry, opts FsOptions) ([]WriteInfo, error)

WriteFiles writes multiple files sequentially, creating parent directories and overwriting existing files as needed. Each entry is uploaded with the envd-version-appropriate encoding (see Write). It returns the WriteInfo for every entry in order; on the first failure it returns the results gathered so far and the error.

Endpoint: POST /files (envd) Envd: >= v0.1.0 (octet-stream >= v0.5.7; metadata >= v0.6.2)

func (*Filesystem) WriteString

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

WriteString creates or overwrites a file with string data.

Endpoint: POST /files (envd) Envd: >= v0.1.0 (octet-stream >= v0.5.7; metadata >= v0.6.2)

type FilesystemEvent

type FilesystemEvent struct {
	Name string
	Type FilesystemEventType
	// Entry carries metadata for the affected path when WatchOptions.IncludeEntry
	// is true (envd >= v0.6.3) and the entry still exists on disk.
	Entry *EntryInfo
}

FilesystemEvent is one event emitted by Filesystem.Watch or Filesystem.WatchWithOptions.

type FilesystemEventType

type FilesystemEventType int

FilesystemEventType enumerates filesystem event kinds.

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

type ForkOptions added in v0.1.4

type ForkOptions struct {
	// Count is the number of forked sandboxes to create (1..20). Zero omits
	// count so the server default (1) applies.
	Count int
	// Timeout sets the lifetime of the forked sandboxes. 0 omits timeout so
	// the server default applies. Sub-second positive durations round up to
	// the next whole second; negative or out-of-range durations return
	// *InvalidArgumentError.
	Timeout time.Duration
	// Metadata attaches optional key/value pairs when supported by the server.
	Metadata map[string]string
	// Envs sets optional environment variables when supported by the server.
	Envs map[string]string
	// Lifecycle sets optional timeout/auto-resume policy when supported by the server.
	Lifecycle *LifecycleOptions
}

ForkOptions configures Fork (POST /sandboxes/{sandboxID}/fork).

type ForkResult added in v0.1.4

type ForkResult struct {
	Sandbox *Sandbox
	Err     error
}

ForkResult holds the outcome of one requested fork. Exactly one of Sandbox or Err is non-nil: Sandbox when that fork started, or Err (implementing e2b.Error) when that fork failed to start.

type FsOptions

type FsOptions struct {
	User           string
	RequestTimeout time.Duration
	// RequestTimeoutMs is preserved for backwards compatibility when
	// RequestTimeout is unset (0).
	RequestTimeoutMs int
	// Depth limits how many directory levels Filesystem.List descends. 0 means
	// the default of 1 (immediate children only). Ignored by other operations.
	Depth int
	// Gzip sends Accept-Encoding: gzip on GET /files and transparently
	// decompresses responses carrying Content-Encoding: gzip.
	Gzip bool
	// Metadata attaches user-defined extended attributes via X-Metadata-<key>
	// headers on file uploads. Requires envd >= v0.6.2; returns *TemplateError
	// on older envd builds.
	Metadata map[string]string
	// ForceMultipart forces multipart/form-data upload encoding even when
	// envd >= v0.5.7 supports application/octet-stream.
	ForceMultipart bool
}

FsOptions holds per-call options 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 (defaulting to "." when empty).

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) AddWithOptions added in v0.1.4

func (g *Git) AddWithOptions(ctx context.Context, opts GitAddOptions) (*CommandResult, error)

AddWithOptions stages multiple files (`git add -- <files...>`) or stages all changes (`git add -A` when opts.All is nil or true; `git add .` when false).

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) Branches

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

Branches parses `git branch -a`.

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) CheckoutBranch

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

CheckoutBranch switches to an existing branch.

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) Clone

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

Clone clones a git repository into the sandbox. When HTTP(S) credentials are provided (via opts.Username/opts.Password or embedded in repoURL) and opts.DangerouslyStoreCredentials is false, Clone automatically scrubs the credentials from `origin` via `git -C <targetDir> remote set-url origin <cleanURL>` so plaintext secrets never remain in .git/config.

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) Commit

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

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

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) CommitWithOptions added in v0.1.4

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

CommitWithOptions runs `git commit` with optional inline author identity and --allow-empty support.

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) ConfigureUser added in v0.1.4

func (g *Git) ConfigureUser(ctx context.Context, name, email string, opts GitConfigOptions) (*CommandResult, error)

ConfigureUser sets user.name and user.email in the requested scope (default "global").

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) CreateBranch

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

CreateBranch creates a branch with the given name.

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) DangerouslyAuthenticate added in v0.1.4

func (g *Git) DangerouslyAuthenticate(ctx context.Context, opts GitDangerouslyAuthenticateOptions) (*CommandResult, error)

DangerouslyAuthenticate configures `git config --global credential.helper store` and approves the given credentials via `git credential approve` over stdin so credentials do not appear in process arguments. Prefer short-lived tokens or per-call Clone/Push/Pull credentials instead.

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) DeleteBranch

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

DeleteBranch force-deletes a branch (`git branch -D <name>`). Use DeleteBranchWithOptions to control `-d` vs `-D`.

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) DeleteBranchWithOptions added in v0.1.4

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

DeleteBranchWithOptions deletes a branch using `-d` by default or `-D` when opts.Force is true.

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) GetConfig added in v0.1.4

func (g *Git) GetConfig(ctx context.Context, key string, opts GitConfigOptions) (string, error)

GetConfig reads a git configuration entry in the requested scope (default "global"; "local" requires opts.RepoPath). Returns ("", nil) when the key is not set.

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

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

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) Init added in v0.1.4

func (g *Git) Init(ctx context.Context, repoPath string, opts GitInitOptions) (*CommandResult, error)

Init initializes a new git repository at repoPath (or opts.RepoPath when repoPath is empty).

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) Pull

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

Pull runs `git pull`. When per-call opts.Username and opts.Password are supplied, credentials are injected into the target remote URL temporarily and scrubbed back to the clean URL in defer before Pull returns.

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) Push

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

Push runs `git push`. When per-call opts.Username and opts.Password are supplied, credentials are injected into the target remote URL temporarily and scrubbed back to the clean URL in defer before Push returns.

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) RemoteAdd added in v0.1.4

func (g *Git) RemoteAdd(ctx context.Context, name, remoteURL string, opts GitRemoteAddOptions) (*CommandResult, error)

RemoteAdd adds a remote (or updates its URL when opts.Overwrite is true).

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) Reset added in v0.1.4

func (g *Git) Reset(ctx context.Context, opts GitResetOptions) (*CommandResult, error)

Reset resets the current HEAD to the specified state (`soft`, `mixed`, `hard`, `merge`, or `keep`).

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) Restore added in v0.1.4

func (g *Git) Restore(ctx context.Context, opts GitRestoreOptions) (*CommandResult, error)

Restore restores working-tree files and/or unstages index changes.

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) SetConfig added in v0.1.4

func (g *Git) SetConfig(ctx context.Context, key, value string, opts GitConfigOptions) (*CommandResult, error)

SetConfig sets a git configuration entry in the requested scope (default "global"; "local" requires opts.RepoPath).

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) SetRemoteURL

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

SetRemoteURL sets the URL of the named remote.

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Git) Status

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

Status parses the porcelain output of `git status --porcelain`.

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

type GitAddOptions added in v0.1.4

type GitAddOptions struct {
	GitOptions
	// Files lists paths to stage; when empty, All controls whether `-A` (true,
	// default) or `.` (false) is passed to `git add`.
	Files []string
	All   *bool
}

GitAddOptions configures Git.AddWithOptions.

type GitAuthError

type GitAuthError struct {
	BaseError
	Message string
}

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 -a`.

type GitCloneOptions

type GitCloneOptions struct {
	GitOptions
	Branch   string
	Depth    int
	Username string
	Password string
	// DangerouslyStoreCredentials persists credentials in .git/config when true.
	// By default (false), inline HTTP(S) credentials are scrubbed from origin
	// immediately after cloning.
	DangerouslyStoreCredentials bool
}

GitCloneOptions configures Git.Clone.

type GitCmdOptions added in v0.1.4

type GitCmdOptions = GitOptions

GitCmdOptions is an alias for GitOptions.

type GitCommitOptions added in v0.1.4

type GitCommitOptions struct {
	GitOptions
	AuthorName  string
	AuthorEmail string
	AllowEmpty  bool
}

GitCommitOptions configures Git.CommitWithOptions.

type GitConfigOptions added in v0.1.4

type GitConfigOptions struct {
	GitOptions
	Scope GitConfigScope
}

GitConfigOptions configures Git.SetConfig, Git.GetConfig, and Git.ConfigureUser.

type GitConfigScope added in v0.1.4

type GitConfigScope string

GitConfigScope enumerates supported configuration scopes for Git.SetConfig and Git.GetConfig.

const (
	GitConfigGlobal GitConfigScope = "global"
	GitConfigLocal  GitConfigScope = "local"
	GitConfigSystem GitConfigScope = "system"
)

type GitDangerouslyAuthenticateOptions added in v0.1.4

type GitDangerouslyAuthenticateOptions struct {
	GitOptions
	Username string
	Password string
	Host     string
	Protocol string
}

GitDangerouslyAuthenticateOptions configures Git.DangerouslyAuthenticate.

type GitDeleteBranchOptions added in v0.1.4

type GitDeleteBranchOptions struct {
	GitOptions
	Force bool
}

GitDeleteBranchOptions configures Git.DeleteBranchWithOptions.

type GitInitOptions added in v0.1.4

type GitInitOptions struct {
	GitOptions
	Bare          bool
	InitialBranch string
}

GitInitOptions configures Git.Init.

type GitOptions

type GitOptions struct {
	RepoPath       string
	User           string
	Cwd            string
	Envs           map[string]string
	TimeoutMs      int
	RequestTimeout time.Duration

	// Remote, Branch, SetUpstream, Username, and Password are optional per-call
	// parameters used by Push and Pull. When Username and Password are supplied
	// on Push or Pull, credentials are injected only for the duration of the
	// operation and scrubbed from the remote URL before returning.
	Remote      string
	Branch      string
	SetUpstream bool
	Username    string
	Password    string
}

GitOptions holds optional configuration shared across Git operations.

type GitRemoteAddOptions added in v0.1.4

type GitRemoteAddOptions struct {
	GitOptions
	Fetch     bool
	Overwrite bool
}

GitRemoteAddOptions configures Git.RemoteAdd.

type GitResetMode added in v0.1.4

type GitResetMode string

GitResetMode enumerates supported modes for Git.Reset.

const (
	GitResetSoft  GitResetMode = "soft"
	GitResetMixed GitResetMode = "mixed"
	GitResetHard  GitResetMode = "hard"
	GitResetMerge GitResetMode = "merge"
	GitResetKeep  GitResetMode = "keep"
)

type GitResetOptions added in v0.1.4

type GitResetOptions struct {
	GitOptions
	Mode   GitResetMode
	Target string
	Paths  []string
}

GitResetOptions configures Git.Reset.

type GitRestoreOptions added in v0.1.4

type GitRestoreOptions struct {
	GitOptions
	Paths    []string
	Staged   *bool
	Worktree *bool
	Source   string
}

GitRestoreOptions configures Git.Restore.

type GitStatus

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

GitStatus is the parsed output of `git status --porcelain`.

type GitUpstreamError

type GitUpstreamError struct {
	BaseError
	Message string
}

GitUpstreamError reports a missing upstream branch.

func (*GitUpstreamError) Error

func (e *GitUpstreamError) Error() string

type IamOptions added in v0.1.4

type IamOptions struct {
	// Tokens maps caller-chosen token names to token definitions. Reference a
	// registered token in NetworkRule header transforms via IamTokenPlaceholder(name).
	Tokens map[string]IamToken
}

IamOptions configures sandbox workload identity tokens on Create / CreateV1.

type IamToken added in v0.1.4

type IamToken struct {
	// Audience of the workload token, stored exactly as provided.
	Audience string
	// TokenType is the workload token type (e.g. "JWT-SVID").
	TokenType string
}

IamToken defines a workload identity token registered on a sandbox.

type InvalidArgumentError

type InvalidArgumentError struct {
	BaseError
	Message string
	Cause   error
}

InvalidArgumentError reports an invalid parameter.

func (*InvalidArgumentError) Error

func (e *InvalidArgumentError) Error() string

func (*InvalidArgumentError) Unwrap added in v0.1.5

func (e *InvalidArgumentError) Unwrap() error

type LifecycleOptions

type LifecycleOptions struct {
	// OnTimeout is "pause" or "kill". Empty means server default (kill).
	OnTimeout string
	// Mode controls what an auto-pause snapshot persists when OnTimeout is
	// "pause": "full" (memory + filesystem, server default) or "filesystem"
	// (filesystem only; cold-boots on resume, incompatible with AutoResume).
	// Empty omits autoPauseMemory so the server default applies.
	Mode string
	// AutoResume configures auto-resume for paused sandboxes.
	AutoResume bool
}

LifecycleOptions controls what happens when the sandbox timeout fires.

type MetricsOptions added in v0.1.3

type MetricsOptions struct {
	// Start, if non-zero, returns only samples at or after this time.
	Start time.Time
	// End, if non-zero, returns only samples at or before this time.
	End time.Time
}

MetricsOptions filters Sandbox.GetMetrics to a time window. Both bounds are optional; a zero time means "unbounded on that side".

type NetworkOptions

type NetworkOptions struct {
	// AllowOut lists CIDR blocks, IPs, or domain names permitted for egress.
	AllowOut []string
	// DenyOut lists CIDR blocks or IPs blocked for egress.
	DenyOut []string
	// AllowPublicTraffic controls whether sandbox URLs accept traffic without
	// the traffic access token. Nil omits the field so the project/server
	// default (true unless overridden on the project) applies; pass Bool(false)
	// or Bool(true) (or Go 1.26 new(false)/new(true)) to set it explicitly.
	AllowPublicTraffic *bool
	// MaskRequestHost customizes the host template on sandbox URLs.
	MaskRequestHost string
	// Rules defines per-domain egress HTTP/HTTPS header transform rules
	// (requires envd >= v0.5.13).
	Rules map[string][]NetworkRule
	// EgressProxy tunnels outbound sandbox TCP through a SOCKS5 proxy.
	EgressProxy *EgressProxyOptions
	// DNSServers lists IPv4 DNS servers reachable when AllowOut contains
	// domains. Nil omits the field (allowing default 8.8.8.8); a non-nil empty
	// slice ([]string{}) allows none.
	DNSServers []string
	// HTTPSPorts lists in-sandbox ports that serve HTTPS rather than plaintext
	// HTTP.
	HTTPSPorts []int32
}

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

type NetworkRule added in v0.1.4

type NetworkRule struct {
	Transform *NetworkTransform
}

NetworkRule configures a per-domain transform applied to matching outbound HTTP/HTTPS requests. Registering a domain in Rules does not permit egress on its own — also include the domain in AllowOut.

type NetworkTransform added in v0.1.4

type NetworkTransform struct {
	// Headers maps HTTP header names to values injected or overridden before
	// forwarding matching egress requests.
	Headers map[string]string
}

NetworkTransform configures HTTP header injection or overrides applied to outbound requests matching a NetworkRule.

type NetworkUpdateOptions added in v0.1.4

type NetworkUpdateOptions struct {
	// AllowOut lists CIDR blocks, IPs, or domain names permitted for egress.
	AllowOut []string
	// DenyOut lists CIDR blocks or IPs blocked for egress.
	DenyOut []string
	// Rules defines per-domain egress HTTP/HTTPS header transform rules
	// (requires envd >= v0.5.13).
	Rules map[string][]NetworkRule
	// EgressProxy tunnels outbound sandbox TCP through a SOCKS5 proxy.
	EgressProxy *EgressProxyOptions
	// DNSServers lists IPv4 DNS servers reachable when AllowOut contains
	// domains. Nil resets to default 8.8.8.8; []string{} allows none.
	DNSServers []string
	// AllowInternetAccess explicitly enables or disables internet access
	// (Bool(false) behaves like DenyOut: []string{AllTraffic}).
	AllowInternetAccess *bool
}

NetworkUpdateOptions configures an atomic replacement of a running sandbox's egress network policy via UpdateNetwork. Omitted fields are cleared or reset to server defaults.

type NotEnoughSpaceError

type NotEnoughSpaceError struct {
	BaseError
	Message string
	Cause   error
}

NotEnoughSpaceError reports the sandbox has insufficient disk space.

func (*NotEnoughSpaceError) Error

func (e *NotEnoughSpaceError) Error() string

func (*NotEnoughSpaceError) Unwrap added in v0.1.5

func (e *NotEnoughSpaceError) Unwrap() error

type NotFoundError

type NotFoundError struct {
	BaseError
	Message string
}

NotFoundError reports a generic HTTP 404 when no resource-specific error type applies. Prefer FileNotFoundError or SandboxNotFoundError for filesystem and sandbox lookups.

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

type PauseOptions added in v0.1.4

type PauseOptions struct {
	Config Config
	// Memory controls whether a full memory snapshot (true, default) or a
	// filesystem-only snapshot (false; requires envd >= v0.5.0) is captured.
	Memory *bool
	// RequireHealthyGuest, when true, refuses the pause with HTTP 503 if envd
	// is not responding instead of taking an unresponsive memory snapshot.
	RequireHealthyGuest *bool
}

PauseOptions configures Pause (POST /sandboxes/{sandboxID}/pause). Leave Memory and RequireHealthyGuest nil to send an empty body compatible with all server versions.

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 pseudo-terminal (PTY) creation, connection, resize, input, and signal endpoints over envd's Connect-RPC Process service (implemented in pty_impl.go).

func (*Pty) Connect added in v0.1.4

func (p *Pty) Connect(ctx context.Context, pid uint32, opts PtyConnectOptions) (*CommandHandle, error)

Connect attaches to an existing PTY session by PID and streams its output.

Endpoint: process.Process/Connect (envd Connect-RPC) Envd: >= v0.1.0

func (*Pty) ConnectByTag added in v0.1.4

func (p *Pty) ConnectByTag(ctx context.Context, tag string, opts PtyConnectOptions) (*CommandHandle, error)

ConnectByTag attaches to an existing PTY session by its custom tag and streams its output.

Endpoint: process.Process/Connect (envd Connect-RPC) Envd: >= v0.1.0

func (*Pty) Create

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

Create starts an interactive PTY session inside the sandbox. When Cmd is empty it defaults to "/bin/bash"; when Cmd is "/bin/bash" and Args is nil, Args defaults to []string{"-i", "-l"}. Default environment variables (TERM=xterm-256color, LANG=C.UTF-8, LC_ALL=C.UTF-8) are injected unless overridden in opts.Envs.

Endpoint: process.Process/Start (envd Connect-RPC) Envd: >= v0.1.0

func (*Pty) Kill

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

Kill sends SIGKILL to the PTY session identified by PID. It returns (false, nil) if the PTY process is no longer running (Connect CodeNotFound).

Endpoint: process.Process/SendSignal (envd Connect-RPC) Envd: >= v0.1.0

func (*Pty) Resize

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

Resize changes the PTY terminal dimensions (columns and rows).

Endpoint: process.Process/Update (envd Connect-RPC) Envd: >= v0.1.0

func (*Pty) SendInput

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

SendInput writes raw terminal bytes into the PTY identified by PID.

Endpoint: process.Process/SendInput (envd Connect-RPC) Envd: >= v0.1.0

func (*Pty) StreamInput added in v0.1.4

func (p *Pty) StreamInput(ctx context.Context, pid uint32, opts ...CommandRequestOptions) (*PtyInputStream, error)

StreamInput opens a persistent, ordered client-streaming PTY input connection to the PTY identified by PID. Call SendPty to write ordered terminal bytes and Close to finish the stream and await envd's acknowledgement.

Endpoint: process.Process/StreamInput (envd Connect-RPC) Envd: >= v0.1.0

type PtyConnectOptions added in v0.1.4

type PtyConnectOptions struct {
	User           string
	TimeoutMs      int
	RequestTimeout time.Duration
	OnData         func([]byte)
}

PtyConnectOptions configures Pty.Connect.

type PtyInputStream added in v0.1.4

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

PtyInputStream is a persistent client-streaming PTY input handle opened by Pty.StreamInput. All methods are safe for concurrent use.

func (*PtyInputStream) Close added in v0.1.4

func (ps *PtyInputStream) Close() error

Close ends the client PTY input stream and waits for envd to acknowledge it. Calling Close multiple times is safe and returns the same error.

Endpoint: process.Process/StreamInput (envd Connect-RPC) Envd: >= v0.1.0

func (*PtyInputStream) Send added in v0.1.4

func (ps *PtyInputStream) Send(data []byte) error

Send is an alias for SendPty.

Endpoint: process.Process/StreamInput (envd Connect-RPC) Envd: >= v0.1.0

func (*PtyInputStream) SendData added in v0.1.4

func (ps *PtyInputStream) SendData(data []byte) error

SendData is an alias for SendPty.

Endpoint: process.Process/StreamInput (envd Connect-RPC) Envd: >= v0.1.0

func (*PtyInputStream) SendPty added in v0.1.4

func (ps *PtyInputStream) SendPty(data []byte) error

SendPty sends a chunk of terminal bytes to the PTY in call order.

Endpoint: process.Process/StreamInput (envd Connect-RPC) Envd: >= v0.1.0

type PtyOptions

type PtyOptions struct {
	Cmd            string
	Args           []string
	User           string
	Envs           map[string]string
	Cwd            string
	Cols           uint32
	Rows           uint32
	TimeoutMs      int
	RequestTimeout time.Duration
	Tag            string
	OnData         func([]byte)
}

PtyOptions configures Pty.Create.

type RateLimitError

type RateLimitError struct {
	BaseError
	Message string
	Cause   error
}

RateLimitError reports HTTP 429.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

func (*RateLimitError) Unwrap added in v0.1.5

func (e *RateLimitError) Unwrap() error

type ResumeOptions added in v0.1.4

type ResumeOptions struct {
	Config Config
	// Timeout sets the resumed sandbox lifetime. 0 omits timeout so the server
	// default applies. Sub-second positive durations round up to the next whole
	// second; negative or out-of-range durations return *InvalidArgumentError.
	Timeout time.Duration
	// AutoPause overrides whether the resumed sandbox auto-pauses on timeout.
	AutoPause *bool
	// OnResume controls how the paused sandbox resumes: "restore" (memory=true)
	// or "reboot" (memory=false). Empty omits memory.
	OnResume string
	// CPUCount overrides the online vCPU target for the resumed sandbox.
	CPUCount *int32
}

ResumeOptions configures Resume and Client.ResumeV1 (POST /sandboxes/{sandboxID}/resume).

type RunOptions

type RunOptions struct {
	Args           []string
	Shell          string
	Cwd            string
	User           string
	Envs           map[string]string
	TimeoutMs      int
	RequestTimeout time.Duration
	Stdin          io.Reader
	// EnableStdin keeps the child's stdin pipe open even when Stdin is nil so
	// callers can write to it later via SendStdin, StreamInput, or CloseStdin.
	EnableStdin bool
	Background  bool
	// RetainOutput controls whether stdout and stderr are accumulated in memory
	// for CommandHandle.Wait(). Nil defaults to true; set to false for high-volume
	// commands consumed via OnStdout/OnStderr or Stdout()/Stderr().
	RetainOutput *bool
	Tag          string
	OnStdout     func([]byte)
	OnStderr     func([]byte)
}

RunOptions configures Commands.Run and Commands.Start.

type Sandbox

type Sandbox struct {
	ID string

	// Exported snapshots refreshed by Sandbox.Connect, ConnectV1, and Resume.
	// Use CurrentDomain, CurrentEnvdVersion, CurrentEnvdAccessToken, and
	// CurrentTrafficAccessToken when reading concurrently with reconnects.
	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 four per-sandbox modules:

  • Commands: exec, signals, streaming stdin/stdout/stderr
  • Pty: interactive pseudo-terminals
  • Files: read/write/watch/compose
  • Git: git operations running inside the sandbox

Methods on *Sandbox are safe for concurrent use. ID is immutable; Domain, EnvdVersion, EnvdAccessToken, and TrafficAccessToken hold the initial snapshot populated by Create/Connect/Resume and are updated in place by Sandbox.Connect, Sandbox.ConnectV1, and Sandbox.Resume. Callers reading those values concurrently with Connect/Resume should use CurrentDomain, CurrentEnvdVersion, CurrentEnvdAccessToken, and CurrentTrafficAccessToken.

func Connect deprecated

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

Connect attaches to an existing sandbox (running or paused) via POST /v2/sandboxes/{sandboxID}/connect. For self-hosted deployments, use ConnectV1 or Resume.

Deprecated: prefer NewClient(cfg).Connect (see Create).

Endpoint: POST /v2/sandboxes/{sandboxID}/connect Compatibility: E2B Cloud only (not in self-hosted runtime <= 2026.30; use ConnectV1 or Resume). Envd: >= v0.1.0

func ConnectV1 deprecated added in v0.1.4

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

ConnectV1 attaches to an existing sandbox (running or paused) via POST /sandboxes/{sandboxID}/connect using a one-shot Client built from opts.Config. Soft-deprecated in OpenAPI in favor of Connect (POST /v2/sandboxes/{sandboxID}/connect), it remains actively served (not retired) on E2B Cloud and self-hosted runtime 2025.44..2026.30 and is the primary connect/wake endpoint on self-hosted 2025.44..2026.30 (use Resume on < 2025.44).

Deprecated: prefer NewClient(cfg).ConnectV1 (see Create).

Endpoint: POST /sandboxes/{sandboxID}/connect Compatibility: E2B Cloud and self-hosted runtime 2025.44..2026.30 (actively served; primary connect/wake endpoint on self-hosted 2025.44..2026.30; use Resume on < 2025.44). Envd: >= v0.1.0

func Create deprecated

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

Create provisions a new sandbox via POST /v2/sandboxes and returns a *Sandbox wired up with all sub-clients. For self-hosted deployments (runtime <= 2026.30), use CreateV1 (or NewClient(cfg).CreateV1).

Deprecated: prefer NewClient(cfg).Create, which reuses one control-plane REST client across calls.

Endpoint: POST /v2/sandboxes Compatibility: E2B Cloud only (not in self-hosted runtime <= 2026.30; use CreateV1). Envd: >= v0.1.0

func CreateV1 deprecated added in v0.1.4

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

CreateV1 provisions a new sandbox via POST /sandboxes using a one-shot Client built from opts.Config. Although soft-deprecated in OpenAPI in favor of Create (POST /v2/sandboxes), POST /sandboxes remains actively served (not retired) on both E2B Cloud and all self-hosted runtime <= 2026.30 deployments, and is the primary create endpoint on self-hosted runtime <= 2026.30.

Deprecated: prefer NewClient(cfg).CreateV1, which reuses one control-plane REST client across calls.

Endpoint: POST /sandboxes Compatibility: E2B Cloud and self-hosted runtime <= 2026.30 (actively served; primary create endpoint on self-hosted, soft-deprecated in OpenAPI in favor of Create on E2B Cloud). Envd: >= v0.2.0 with default secure=true (>= v0.1.0 when Insecure is true)

func Resume deprecated added in v0.1.4

func Resume(ctx context.Context, sandboxID string, opts ...ResumeOptions) (*Sandbox, error)

Resume wakes a paused sandbox via POST /sandboxes/{sandboxID}/resume using a one-shot Client built from opts.Config.

Soft-deprecated in OpenAPI since runtime 2025.44 introduced idempotent /connect (ConnectV1, whereas /resume returns *ConflictError / HTTP 409 if already running), POST /sandboxes/{sandboxID}/resume remains actively served (not retired) on both E2B Cloud and all self-hosted runtime <= 2026.30. It is required on self-hosted runtime < 2025.44 (where /connect does not exist), and useful on newer servers when overriding CPUCount or AutoPause on wake.

Deprecated: prefer NewClient(cfg).Resume (see Create).

Endpoint: POST /sandboxes/{sandboxID}/resume Compatibility: E2B Cloud and self-hosted runtime <= 2026.30 (actively served; required on < 2025.44; soft-deprecated in OpenAPI in favor of Connect / ConnectV1). Envd: >= v0.1.0

func (*Sandbox) Connect added in v0.1.4

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

Connect reconnects to this sandbox (resuming it if paused) via POST /v2/sandboxes/{sandboxID}/connect and refreshes Domain, EnvdAccessToken, TrafficAccessToken, and EnvdVersion when returned by the server.

Endpoint: POST /v2/sandboxes/{sandboxID}/connect Compatibility: E2B Cloud only (not in self-hosted runtime <= 2026.30; use ConnectV1). Envd: >= v0.1.0

func (*Sandbox) ConnectV1 added in v0.1.4

func (s *Sandbox) ConnectV1(ctx context.Context, opts ...ConnectOptions) error

ConnectV1 reconnects to this sandbox (resuming it if paused) via POST /sandboxes/{sandboxID}/connect and refreshes Domain, EnvdAccessToken, TrafficAccessToken, and EnvdVersion when returned by the server.

Marked soft-deprecated in OpenAPI in favor of Connect (POST /v2/sandboxes/{sandboxID}/connect), this endpoint remains actively served (not retired) on both E2B Cloud and self-hosted runtime 2025.44..2026.30. Choose ConnectV1 on self-hosted runtime 2025.44..2026.30; prefer Connect on E2B Cloud, and use Resume on self-hosted runtime < 2025.44.

Endpoint: POST /sandboxes/{sandboxID}/connect Compatibility: E2B Cloud and self-hosted runtime 2025.44..2026.30 (actively served; primary connect/wake endpoint on self-hosted 2025.44..2026.30; use Resume on < 2025.44). Envd: >= v0.1.0

func (*Sandbox) CreateSnapshot

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

CreateSnapshot persists this sandbox's current state as a reusable snapshot template.

Endpoint: POST /sandboxes/{sandboxID}/snapshots Compatibility: E2B Cloud; self-hosted runtime 2026.08..2026.30 (not in runtime < 2026.08). Envd: >= v0.5.0

func (*Sandbox) CurrentDomain added in v0.1.5

func (s *Sandbox) CurrentDomain() string

CurrentDomain returns the sandbox's current domain safely under the sandbox's internal lock. Prefer this over reading Domain directly when Connect, ConnectV1, or Resume may run concurrently.

func (*Sandbox) CurrentEnvdAccessToken added in v0.1.5

func (s *Sandbox) CurrentEnvdAccessToken() string

CurrentEnvdAccessToken returns the sandbox's current envd access token safely under the sandbox's internal lock. Prefer this over reading EnvdAccessToken directly when Connect, ConnectV1, or Resume may run concurrently.

func (*Sandbox) CurrentEnvdVersion added in v0.1.5

func (s *Sandbox) CurrentEnvdVersion() string

CurrentEnvdVersion returns the sandbox's current envd version safely under the sandbox's internal lock. Prefer this over reading EnvdVersion directly when Connect, ConnectV1, or Resume may run concurrently.

func (*Sandbox) CurrentTrafficAccessToken added in v0.1.5

func (s *Sandbox) CurrentTrafficAccessToken() string

CurrentTrafficAccessToken returns the sandbox's current traffic access token safely under the sandbox's internal lock. Prefer this over reading TrafficAccessToken directly when Connect, ConnectV1, or Resume may run concurrently.

func (*Sandbox) DownloadURL

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

DownloadURL builds a local HTTP URL the caller can GET a file from (/files). For envd >= v0.4.0, the default username parameter is omitted unless opts.User is set. Returns *InvalidArgumentError if opts.ExpirationInSeconds > 0 when the sandbox has no EnvdAccessToken.

func (*Sandbox) Fork added in v0.1.4

func (s *Sandbox) Fork(ctx context.Context, opts ...ForkOptions) ([]ForkResult, error)

Fork checkpoints this running sandbox in place (preserving its ID and expiration) and boots one or more new sandboxes from that checkpoint. Each requested fork succeeds or fails independently in the returned slice.

Endpoint: POST /sandboxes/{sandboxID}/fork Compatibility: E2B Cloud; self-hosted runtime 2026.29..2026.30 (not in runtime < 2026.29). Envd: >= v0.5.0

func (*Sandbox) GetEnvdMetrics added in v0.1.4

func (s *Sandbox) GetEnvdMetrics(ctx context.Context, opts ...CommandRequestOptions) (*EnvdMetrics, error)

GetEnvdMetrics fetches an immediate guest resource usage snapshot directly from the in-sandbox envd daemon (including CPU hotplug state and recent OOM kills). Requires envd >= v0.1.5; returns *TemplateError on older builds.

Endpoint: GET /metrics (envd) Envd: >= v0.1.5

func (*Sandbox) GetEnvs added in v0.1.4

func (s *Sandbox) GetEnvs(ctx context.Context, opts ...CommandRequestOptions) (map[string]string, error)

GetEnvs returns the default environment variables configured inside the sandbox's envd daemon.

Endpoint: GET /envs (envd) Envd: >= v0.1.0

func (*Sandbox) GetHost

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

GetHost returns the external hostname (or localhost:<port> in Debug mode) for the given sandbox port.

func (*Sandbox) GetInfo

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

GetInfo fetches the sandbox metadata from the control plane. Legacy servers (< 2025.31) returning 200 OK with an empty state field are normalized to SandboxStateRunning.

Endpoint: GET /sandboxes/{sandboxID} Compatibility: E2B Cloud; self-hosted runtime <= 2026.30.

func (*Sandbox) GetLogs added in v0.1.4

func (s *Sandbox) GetLogs(ctx context.Context, opts ...SandboxLogsOptions) ([]SandboxLogEntry, error)

GetLogs fetches structured logs for this sandbox via the v2 logs endpoint. It does not fall back to GetLogsV1 on older self-hosted servers.

Endpoint: GET /v2/sandboxes/{sandboxID}/logs Compatibility: E2B Cloud; self-hosted runtime 2026.07..2026.30 (use GetLogsV1 on < 2026.07).

func (*Sandbox) GetLogsV1 added in v0.1.4

func (s *Sandbox) GetLogsV1(ctx context.Context, opts ...SandboxLogsV1Options) (*SandboxLogsV1, error)

GetLogsV1 fetches logs for this sandbox via GET /sandboxes/{sandboxID}/logs. Soft-deprecated in OpenAPI in favor of GetLogs, it remains actively served (not retired) on E2B Cloud and all self-hosted runtime <= 2026.30, and is required on self-hosted runtime < 2026.07 (see Client.GetLogsV1).

Endpoint: GET /sandboxes/{sandboxID}/logs Compatibility: E2B Cloud and self-hosted runtime <= 2026.30 (actively served; required on < 2026.07; soft-deprecated in OpenAPI in favor of GetLogs).

func (*Sandbox) GetMcpToken added in v0.1.3

func (s *Sandbox) GetMcpToken(ctx context.Context) (string, error)

GetMcpToken returns the MCP gateway access token for this sandbox. When the sandbox was created in-process with CreateOptions.Mcp, the cached token is returned without extra I/O; on a reconnected sandbox it reads /etc/mcp-gateway/.token as root (matching the reference JS/Python SDKs) and caches the result. Returns *FileNotFoundError if no MCP gateway is configured.

Endpoint: GET /files?path=/etc/mcp-gateway/.token&username=root (envd, when uncached) Envd: >= v0.1.0

func (*Sandbox) GetMcpURL added in v0.1.3

func (s *Sandbox) GetMcpURL() string

GetMcpURL returns the sandbox's MCP gateway URL (https://<host>/mcp, or http://<host>/mcp in Debug mode). It does not verify that an MCP gateway is running; create the sandbox with CreateOptions.Mcp to start one.

func (*Sandbox) GetMetrics

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

GetMetrics fetches CPU, memory (including MemCache), and disk usage samples for the sandbox. With no opts it returns the most recent samples; pass a single MetricsOptions to bound the time window (opts.Start / opts.End). Returns *TemplateError when EnvdVersion is known and below 0.1.5.

Endpoint: GET /sandboxes/{sandboxID}/metrics Compatibility: E2B Cloud; self-hosted runtime <= 2026.30 (MemCache requires E2B Cloud or runtime >= 2026.14). Envd: >= v0.1.5

func (*Sandbox) IsRunning

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

IsRunning reports whether this sandbox is currently alive and running.

It adapts safely across E2B generations:

  • In Debug mode it probes envd GET /health directly (200/204 -> true; 502/404/dial error -> false).
  • When the sandbox was created with Lifecycle.AutoResume = true, it checks control-plane GetInfo first so probing envd /health never wakes a paused auto-resume sandbox.
  • Otherwise it probes envd GET /health (200/204 -> true; 502 -> false), falling back to control-plane GetInfo if a legacy proxy returns 404 or when no envd listener is reachable in a control-plane-only test setup.

Endpoint: GET /health (envd), with GET /sandboxes/{sandboxID} guard/fallback Compatibility: E2B Cloud; self-hosted runtime <= 2026.30. Envd: >= v0.1.0

func (*Sandbox) Kill

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

Kill terminates this sandbox.

Endpoint: DELETE /sandboxes/{sandboxID} Compatibility: E2B Cloud; self-hosted runtime <= 2026.30.

func (*Sandbox) ListAllSnapshots added in v0.1.4

func (s *Sandbox) ListAllSnapshots(ctx context.Context, opts ...SnapshotListOptions) ([]SnapshotInfo, error)

ListAllSnapshots drains every page of snapshots created from this sandbox.

Endpoint: GET /snapshots Compatibility: E2B Cloud; self-hosted runtime 2026.08..2026.30 (not in runtime < 2026.08).

func (*Sandbox) ListSnapshots added in v0.1.4

func (s *Sandbox) ListSnapshots(_ context.Context, opts ...SnapshotListOptions) *SnapshotPaginator

ListSnapshots returns a paginator over snapshots created from this sandbox. Any SandboxID in opts is overridden with s.ID.

Endpoint: GET /snapshots Compatibility: E2B Cloud; self-hosted runtime 2026.08..2026.30 (not in runtime < 2026.08).

func (*Sandbox) Pause

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

Pause pauses this sandbox. Returns true on success; false (nil error) if the sandbox was already paused (HTTP 409). When opts is omitted or zero, no JSON body is sent so legacy servers (< runtime 2026.25) accept the request.

Endpoint: POST /sandboxes/{sandboxID}/pause Compatibility: E2B Cloud; self-hosted runtime <= 2026.30 (PauseOptions body requires E2B Cloud or runtime >= 2026.25). Envd: >= v0.5.0 when PauseOptions.Memory is false

func (*Sandbox) RefreshTimeout added in v0.1.4

func (s *Sandbox) RefreshTimeout(ctx context.Context, duration time.Duration) error

RefreshTimeout extends this sandbox's TTL monotonically via POST /sandboxes/{sandboxID}/refreshes: shorter durations never shrink an existing longer expiration, unlike SetTimeout which overwrites the TTL relative to the current server time.

Remains actively served on both E2B Cloud and all self-hosted runtime <= 2026.30 deployments. Choose RefreshTimeout for monotonic keepalive heartbeats; choose SetTimeout when setting an exact new TTL (including shortening it).

Endpoint: POST /sandboxes/{sandboxID}/refreshes Compatibility: E2B Cloud; self-hosted runtime <= 2026.30 (actively served).

func (*Sandbox) RefreshTimeoutV1 added in v0.1.4

func (s *Sandbox) RefreshTimeoutV1(ctx context.Context, duration time.Duration) error

RefreshTimeoutV1 is a version-suffixed alias for RefreshTimeout (POST /sandboxes/{sandboxID}/refreshes). See RefreshTimeout for details.

Endpoint: POST /sandboxes/{sandboxID}/refreshes Compatibility: E2B Cloud; self-hosted runtime <= 2026.30 (actively served).

func (*Sandbox) Resume added in v0.1.4

func (s *Sandbox) Resume(ctx context.Context, opts ...ResumeOptions) error

Resume wakes this paused sandbox via POST /sandboxes/{sandboxID}/resume and refreshes Domain, EnvdAccessToken, TrafficAccessToken, EnvdVersion, and the internal envd clients thread-safely when returned by the server.

  • Why marked deprecated in OpenAPI: Soft-deprecated since runtime 2025.44 introduced idempotent /connect (ConnectV1, which attaches if running or wakes if paused, whereas /resume returns *ConflictError / HTTP 409 if the sandbox is already running).
  • Availability: Remains actively served (not retired) on both E2B Cloud and all self-hosted runtime <= 2026.30 deployments.
  • When to use: Required on self-hosted runtime < 2025.44 (where /connect does not exist) to wake paused sandboxes. On runtime >= 2025.44 or E2B Cloud, prefer ConnectV1 / Connect for general reconnect/wake, and use Resume when overriding CPUCount or AutoPause on wake or asserting that the sandbox was paused (409 Conflict if running).

Endpoint: POST /sandboxes/{sandboxID}/resume Compatibility: E2B Cloud and self-hosted runtime <= 2026.30 (actively served; required on < 2025.44; soft-deprecated in OpenAPI in favor of Connect / ConnectV1). Envd: >= v0.1.0

func (*Sandbox) SetTimeout

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

SetTimeout updates the sandbox's inactivity timeout.

Endpoint: POST /sandboxes/{sandboxID}/timeout Compatibility: E2B Cloud; self-hosted runtime <= 2026.30.

func (*Sandbox) SignedDownloadURL added in v0.1.4

func (s *Sandbox) SignedDownloadURL(filePath string, opts SignatureOptions) (string, error)

SignedDownloadURL is an explicit alias for DownloadURL returning a pre-signed (when EnvdAccessToken is set) download URL for GET /files.

func (*Sandbox) SignedUploadURL added in v0.1.4

func (s *Sandbox) SignedUploadURL(filePath string, opts SignatureOptions) (string, error)

SignedUploadURL is an explicit alias for UploadURL returning a pre-signed (when EnvdAccessToken is set) upload URL for POST /files.

func (*Sandbox) UpdateNetwork added in v0.1.4

func (s *Sandbox) UpdateNetwork(ctx context.Context, opts NetworkUpdateOptions) error

UpdateNetwork atomically replaces the egress network configuration of this running sandbox. Omitted fields are cleared or reset on the server.

Endpoint: PUT /sandboxes/{sandboxID}/network Compatibility: E2B Cloud; self-hosted runtime 2026.12..2026.30 (not in runtime < 2026.12). Envd: >= v0.5.13 when Rules is set

func (*Sandbox) UploadURL

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

UploadURL builds a local HTTP URL the caller can POST a file to (/files). When filePath is empty, the ?path= query parameter is omitted (for multipart uploads that supply filenames in part headers). For envd >= v0.4.0, the default username parameter is omitted unless opts.User is set. Returns *InvalidArgumentError if opts.ExpirationInSeconds > 0 when the sandbox has no EnvdAccessToken.

type SandboxError

type SandboxError struct {
	BaseError
	Message string
	Cause   error
}

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
	PauseMode               string
	EnvdUnresponsiveAtPause bool
	CPUCount                int32
	MemoryMB                int32
	DiskSizeMB              int32
	StartedAt               time.Time
	EndAt                   time.Time
	Metadata                map[string]string
	EnvdVersion             string
	EnvdAccessToken         string
	AllowInternetAccess     *bool
	Network                 *SandboxNetworkInfo
	Lifecycle               *LifecycleOptions
	VolumeMounts            []VolumeMount
}

SandboxInfo holds REST-reported metadata about a sandbox.

func ListAll deprecated added in v0.1.2

func ListAll(ctx context.Context, cfg Config, opts ...SandboxListOptions) ([]SandboxInfo, error)

ListAll drains every page using a one-shot Client built from cfg.

Deprecated: prefer NewClient(cfg).ListAll (see List).

Endpoint: GET /v2/sandboxes Compatibility: E2B Cloud; self-hosted runtime 2025.31..2026.30 (use ListV1 on < 2025.31).

func ListV1 deprecated added in v0.1.4

func ListV1(ctx context.Context, cfg Config, opts ...SandboxListV1Options) ([]SandboxInfo, error)

ListV1 lists running sandboxes via the unpaginated GET /sandboxes endpoint using a one-shot Client built from cfg. Soft-deprecated in OpenAPI in favor of List / ListAll (GET /v2/sandboxes), it remains actively served (not retired) on E2B Cloud and all self-hosted runtime <= 2026.30, and is required on self-hosted runtime < 2025.31.

Deprecated: prefer NewClient(cfg).ListV1 (see List).

Endpoint: GET /sandboxes Compatibility: E2B Cloud and self-hosted runtime <= 2026.30 (actively served; required on < 2025.31; soft-deprecated in OpenAPI in favor of List / ListAll).

type SandboxListOptions added in v0.1.2

type SandboxListOptions struct {
	// Metadata filters by exact key/value pairs (all must match).
	Metadata map[string]string
	// State filters by one or more states. Empty means all states.
	State []SandboxState
	// StartedAfter filters to sandboxes started at or after this timestamp
	// (supported on E2B Cloud and self-hosted runtime >= 2026.30).
	StartedAfter *time.Time
	// Template filters by template ID or alias (supported on E2B Cloud and
	// self-hosted runtime >= 2026.30).
	Template string
	// Order sorts results by sandbox start time ("asc" or "desc"; default "desc",
	// supported on E2B Cloud and self-hosted runtime >= 2026.30).
	Order string
	// Limit caps the number of items per page. 0 uses the server default.
	Limit int32
	// NextToken resumes from a previous page's cursor. Usually left empty;
	// the paginator manages it internally.
	NextToken string
}

SandboxListOptions filters and paginates a sandbox list (GET /v2/sandboxes). The zero value lists all sandboxes the caller can see, one server-defined page at a time.

type SandboxListV1Options added in v0.1.4

type SandboxListV1Options struct {
	// Metadata filters running sandboxes by exact key/value pairs.
	Metadata map[string]string
}

SandboxListV1Options filters legacy unpaginated running sandbox listings (GET /sandboxes).

type SandboxLogEntry added in v0.1.4

type SandboxLogEntry struct {
	Timestamp time.Time
	Level     string
	Message   string
	Fields    map[string]string
}

SandboxLogEntry is a structured sandbox log record.

type SandboxLogLine added in v0.1.4

type SandboxLogLine struct {
	Timestamp time.Time
	Line      string
}

SandboxLogLine is a plain-text timestamped log line returned by GetLogsV1.

type SandboxLogsOptions added in v0.1.4

type SandboxLogsOptions struct {
	// Cursor is the starting timestamp in Unix milliseconds (nil omits cursor).
	Cursor *int64
	// Limit caps the maximum number of log entries returned (<= 0 uses server default).
	Limit int32
	// Direction is "forward" or "backward".
	Direction string
	// Level is the minimum log level ("debug", "info", "warn", "error").
	Level string
	// Search filters log messages by case-sensitive substring match.
	Search string
}

SandboxLogsOptions filters structured sandbox logs on GetLogs (GET /v2/sandboxes/{sandboxID}/logs).

type SandboxLogsV1 added in v0.1.4

type SandboxLogsV1 struct {
	Logs       []SandboxLogLine
	LogEntries []SandboxLogEntry
}

SandboxLogsV1 holds both plain-text and structured logs returned by legacy GET /sandboxes/{sandboxID}/logs.

type SandboxLogsV1Options added in v0.1.4

type SandboxLogsV1Options struct {
	// Start is the starting timestamp in Unix milliseconds (nil omits start).
	Start *int64
	// Limit caps the maximum number of log entries returned (<= 0 uses server default).
	Limit int32
}

SandboxLogsV1Options filters legacy sandbox logs on GetLogsV1 (GET /sandboxes/{sandboxID}/logs).

type SandboxMetric

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

SandboxMetric is one sample of resource usage.

type SandboxNetworkInfo added in v0.1.4

type SandboxNetworkInfo = NetworkOptions

SandboxNetworkInfo describes the network configuration reported by GetInfo. It aliases NetworkOptions so callers can inspect or reuse network settings uniformly.

type SandboxNotFoundError

type SandboxNotFoundError struct {
	BaseError
	SandboxID string
	Message   string
}

SandboxNotFoundError reports that the sandbox is gone or never existed.

func (*SandboxNotFoundError) Error

func (e *SandboxNotFoundError) Error() string

type SandboxPaginator added in v0.1.2

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

SandboxPaginator iterates sandbox list pages, following the server's cursor (the x-next-token response header). Obtain one from Client.List.

A SandboxPaginator is stateful and not safe for concurrent use.

func List deprecated added in v0.1.2

func List(ctx context.Context, cfg Config, opts ...SandboxListOptions) (*SandboxPaginator, error)

List returns a paginator over sandboxes using a one-shot Client built from cfg.

Deprecated: prefer NewClient(cfg).List, which reuses one control-plane REST client across calls.

Endpoint: GET /v2/sandboxes Compatibility: E2B Cloud; self-hosted runtime 2025.31..2026.30 (use ListV1 on < 2025.31).

func (*SandboxPaginator) HasNext added in v0.1.2

func (p *SandboxPaginator) HasNext() bool

HasNext reports whether another page is available. It is true before the first NextItems call; afterwards it reflects the x-next-token header of the most recent response.

func (*SandboxPaginator) NextItems added in v0.1.2

func (p *SandboxPaginator) NextItems(ctx context.Context) ([]SandboxInfo, error)

NextItems fetches the next page of sandboxes. Call it only while HasNext reports true; once exhausted it returns (nil, nil). After the call HasNext reflects whether further pages remain.

Endpoint: GET /v2/sandboxes Compatibility: E2B Cloud; self-hosted runtime 2025.31..2026.30 (use ListV1 on < 2025.31).

func (*SandboxPaginator) NextToken added in v0.1.2

func (p *SandboxPaginator) NextToken() string

NextToken returns the cursor for the next page, or "" when exhausted. It can be persisted and replayed via SandboxListOptions.NextToken.

func (*SandboxPaginator) TotalRunning added in v0.1.4

func (p *SandboxPaginator) TotalRunning() *int32

TotalRunning returns the X-Total-Running header reported on the most recent NextItems response when provided by the server, or nil when omitted.

type SandboxState

type SandboxState string

SandboxState reports whether a sandbox is running or paused.

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

type SecretInfo added in v0.1.4

type SecretInfo struct {
	SecretID       string
	Name           string
	CurrentVersion int64
	Metadata       map[string]string
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

SecretInfo holds metadata about a project secret. Secret values are write-only and are never returned by the API.

type SecretListOptions added in v0.1.4

type SecretListOptions struct {
	// Limit caps the number of items per page (0 uses server default).
	Limit int32
	// NextToken resumes from a previous page's cursor.
	NextToken string
}

SecretListOptions filters and paginates a secret list.

type SecretOptions added in v0.1.4

type SecretOptions struct {
	// Metadata attaches customer metadata to the secret. On UpdateSecret, a
	// non-nil map replaces the stored metadata.
	Metadata map[string]string
}

SecretOptions configures CreateSecret and UpdateSecret.

type SecretPaginator added in v0.1.4

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

SecretPaginator iterates secret list pages, following the server's x-next-token response header. Obtain one from Client.ListSecrets.

A SecretPaginator is stateful and not safe for concurrent use.

func (*SecretPaginator) HasNext added in v0.1.4

func (p *SecretPaginator) HasNext() bool

HasNext reports whether another page of secrets is available.

func (*SecretPaginator) NextItems added in v0.1.4

func (p *SecretPaginator) NextItems(ctx context.Context) ([]SecretInfo, error)

NextItems fetches the next page of secrets. Once exhausted it returns (nil, nil).

Endpoint: GET /secrets Compatibility: E2B Cloud; self-hosted runtime 2026.30 (not in runtime < 2026.30).

func (*SecretPaginator) NextToken added in v0.1.4

func (p *SecretPaginator) NextToken() string

NextToken returns the cursor for the next page of secrets, or "" when exhausted.

type Signal added in v0.1.4

type Signal int32

Signal enumerates process signals accepted by Commands.SendSignal and CommandHandle.SendSignal.

const (
	SignalSIGTERM Signal = Signal(procpb.Signal_SIGNAL_SIGTERM)
	SignalSIGKILL Signal = Signal(procpb.Signal_SIGNAL_SIGKILL)
)

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 /files endpoints.

func GetSignature

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

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

raw = path:operation:user:envdAccessToken[:expiration]
signature = "v1_" + base64std_nopad(sha256(raw))
Example
package main

import (
	"fmt"
	"log"

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

func main() {
	sig, err := e2b.GetSignature(
		"/home/user/hello.txt",
		e2b.SignatureRead,
		"example-token",
		e2b.SignatureOptions{User: "user"},
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(sig.Value)
}
Output:
v1_1HtEcpQNp2wfdKa9NLF0h0XdOk6H9IiSXhcqCX6siSs

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, Sandbox.UploadURL, and Sandbox.DownloadURL.

type SnapshotInfo

type SnapshotInfo struct {
	SnapshotID string
	Names      []string
}

SnapshotInfo references a persisted sandbox snapshot.

type SnapshotListOptions added in v0.1.3

type SnapshotListOptions struct {
	// SandboxID filters to snapshots created from a specific sandbox. Empty
	// means all sandboxes.
	SandboxID string
	// Name filters snapshots by name or ID, optionally tag-qualified (e.g.
	// "my-snapshot", "my-team/my-snapshot", or "my-snapshot:v1"; supported on
	// E2B Cloud and self-hosted runtime >= 2026.29).
	Name string
	// Limit caps the number of items per page. 0 uses the server default.
	Limit int32
	// NextToken resumes from a previous page's cursor. Usually left empty; the
	// paginator manages it internally.
	NextToken string
}

SnapshotListOptions filters and paginates a snapshot list. The zero value lists every snapshot the caller can see, one server-defined page at a time.

type SnapshotPaginator added in v0.1.3

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

SnapshotPaginator iterates snapshot list pages, following the server's cursor (the x-next-token response header). Obtain one from Client.ListSnapshots or Sandbox.ListSnapshots.

A SnapshotPaginator is stateful and not safe for concurrent use.

func (*SnapshotPaginator) HasNext added in v0.1.3

func (p *SnapshotPaginator) HasNext() bool

HasNext reports whether another page is available. It is true before the first NextItems call; afterwards it reflects the x-next-token header of the most recent response.

func (*SnapshotPaginator) NextItems added in v0.1.3

func (p *SnapshotPaginator) NextItems(ctx context.Context) ([]SnapshotInfo, error)

NextItems fetches the next page of snapshots. Call it only while HasNext reports true; once exhausted it returns (nil, nil). After the call HasNext reflects whether further pages remain.

Endpoint: GET /snapshots Compatibility: E2B Cloud; self-hosted runtime 2026.08..2026.30 (not in runtime < 2026.08).

func (*SnapshotPaginator) NextToken added in v0.1.3

func (p *SnapshotPaginator) NextToken() string

NextToken returns the cursor for the next page, or "" when exhausted. It can be persisted and replayed via SnapshotListOptions.NextToken.

type TemplateError

type TemplateError struct {
	BaseError
	Message string
}

TemplateError reports template/envd incompatibility.

func (*TemplateError) Error

func (e *TemplateError) Error() string

type TimeoutError

type TimeoutError struct {
	BaseError
	Message string
	Cause   error
}

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 {
	BaseError
	Message string
	Cause   error
}

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 WatchEvent added in v0.1.4

type WatchEvent = FilesystemEvent

WatchEvent is an alias for FilesystemEvent emitted by Filesystem.Watch and Filesystem.WatchWithOptions.

type WatchHandle

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

WatchHandle streams filesystem events from Filesystem.Watch and Filesystem.WatchWithOptions.

func (*WatchHandle) Err

func (w *WatchHandle) Err() error

Err returns the error (if any) that terminated the watch. Returns nil after a clean Stop.

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 stream locally and waits for the background goroutine to finish. Calling Stop multiple times is safe.

type WatchOptions added in v0.1.4

type WatchOptions struct {
	Recursive          bool
	IncludeEntry       bool
	AllowNetworkMounts bool
	User               string
	TimeoutMs          int
	// RequestTimeout bounds only the initial WatchDir start handshake (waiting
	// for envd to establish the watch). Once started, the watch stays alive
	// until ctx is canceled, TimeoutMs expires, or WatchHandle.Stop is called.
	RequestTimeout time.Duration
}

WatchOptions configures Filesystem.WatchWithOptions.

type WriteEntry added in v0.1.3

type WriteEntry struct {
	// Path is the destination path inside the sandbox.
	Path string
	// Data is the file content.
	Data []byte
}

WriteEntry is one file to write via Filesystem.WriteFiles.

type WriteInfo

type WriteInfo struct {
	Path     string
	Name     string
	Type     EntryType
	Metadata map[string]string
}

WriteInfo is returned by Filesystem.Write, WriteBytes, WriteString, and WriteFiles.

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 (E2B Cloud): list templates, build a new one via POST /v3/templates, inspect it, spawn a sandbox via POST /v2/sandboxes, read sandbox info, then tear everything down.
Lifecycle example (E2B Cloud): list templates, build a new one via POST /v3/templates, inspect it, spawn a sandbox via POST /v2/sandboxes, read sandbox info, then tear everything down.
lifecycle_v2 command
Lifecycle example for self-hosted E2B control planes (required on runtime < 2025.44 and still actively served across all self-hosted runtime <= 2026.30; note that POST /v2/templates is retired with 410 Gone on E2B Cloud, whereas ListV1, SetPublicV1, and CreateV1 are soft-deprecated in OpenAPI and remain served on both self-hosted and E2B Cloud).
Lifecycle example for self-hosted E2B control planes (required on runtime < 2025.44 and still actively served across all self-hosted runtime <= 2026.30; note that POST /v2/templates is retired with 410 Gone on E2B Cloud, whereas ListV1, SetPublicV1, and CreateV1 are soft-deprecated in OpenAPI and remain served on both self-hosted and E2B Cloud).
selfhosted command
Self-hosted example: point the SDK at a self-hosted E2B control plane (runtime <= 2026.30, including pre-2025.31 deployments) and inspect the sandbox session (ID, template, state, timing, envd info, live metrics).
Self-hosted example: point the SDK at a self-hosted E2B control plane (runtime <= 2026.30, including pre-2025.31 deployments) and inspect the 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.
version
Package version pins the upstream E2B spec this SDK was generated from.
Package version pins the upstream E2B spec this SDK was generated from.
volumeapi
Package volumeapi provides primitives to interact with the openapi HTTP API.
Package volumeapi provides primitives to interact with the openapi HTTP API.
filter_spec trims the upstream E2B OpenAPI specs down to the surface the Go SDK generates clients for.
filter_spec trims the upstream E2B OpenAPI specs down to the surface the Go SDK generates clients for.
Package template provides a fluent builder and a Client for building and managing E2B sandbox templates.
Package template provides a fluent builder and a Client for building and managing 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