Documentation
¶
Overview ¶
Package e2b is a Go client for the E2B sandbox platform.
It ports the public surface of the Python (https://github.com/e2b-dev/E2B/tree/main/packages/python-sdk) and JavaScript (https://github.com/e2b-dev/E2B/tree/main/packages/js-sdk) SDKs to idiomatic Go: blocking APIs with context.Context, channels for streaming output, and typed errors.
Quick start ¶
ctx := context.Background()
sbx, err := e2b.Create(ctx, e2b.CreateOptions{
Template: "base",
Timeout: 5 * time.Minute,
})
if err != nil {
log.Fatal(err)
}
defer sbx.Kill(ctx)
handle, err := sbx.Commands.Run(ctx, "echo", e2b.RunOptions{Args: []string{"hello"}})
if err != nil {
log.Fatal(err)
}
result, _ := handle.Wait(ctx)
fmt.Println(result.Stdout) // hello
Authentication ¶
The SDK reads credentials from the environment by default:
- E2B_API_KEY: team API key (X-API-Key header)
- E2B_ACCESS_TOKEN: user access token (Authorization: Bearer)
- E2B_DOMAIN: defaults to e2b.app
- E2B_DEBUG: when "true", targets http://localhost:3000
Pass an explicit Config to override.
Unified client ¶
For programs that create or manage many sandboxes, build one Client and reuse it. It resolves the Config once and shares a single HTTP and control-plane REST client across every call and every Sandbox it creates:
c, err := e2b.NewClient(e2b.Config{}) // reads credentials from the env
if err != nil {
log.Fatal(err)
}
sbx, err := c.Create(ctx, e2b.CreateOptions{Template: "base"})
// ...
running, err := c.ListAll(ctx, e2b.SandboxListOptions{
State: []e2b.SandboxState{e2b.SandboxStateRunning},
})
The package-level Create, Connect, Kill, List and ListAll functions are thin convenience wrappers that build a throwaway Client per call; they are kept for compatibility but NewClient is preferred.
Sub-packages ¶
- template: fluent builder for sandbox templates (serialization only in v1)
- volume: client for persistent volumes
Index ¶
- Constants
- Variables
- func Kill(ctx context.Context, sandboxID string, opts ConnectOptions) (bool, error)deprecated
- type AuthenticationError
- type BuildError
- type Client
- func (c *Client) Config() Config
- func (c *Client) Connect(ctx context.Context, sandboxID string, opts ConnectOptions) (*Sandbox, error)
- func (c *Client) Create(ctx context.Context, opts CreateOptions) (*Sandbox, error)
- func (c *Client) DeleteSnapshot(ctx context.Context, snapshotID string) (bool, error)
- func (c *Client) Kill(ctx context.Context, sandboxID string) (bool, error)
- func (c *Client) List(_ context.Context, opts SandboxListOptions) *SandboxPaginator
- func (c *Client) ListAll(ctx context.Context, opts SandboxListOptions) ([]SandboxInfo, error)
- func (c *Client) ListAllSnapshots(ctx context.Context, opts SnapshotListOptions) ([]SnapshotInfo, error)
- func (c *Client) ListSnapshots(_ context.Context, opts SnapshotListOptions) *SnapshotPaginator
- type CommandExitError
- type CommandHandle
- func (h *CommandHandle) Kill(ctx context.Context) (bool, error)
- func (h *CommandHandle) PID() uint32
- func (h *CommandHandle) PtyOutput() <-chan []byte
- func (h *CommandHandle) SendStdin(ctx context.Context, data []byte) error
- func (h *CommandHandle) Stderr() <-chan []byte
- func (h *CommandHandle) Stdout() <-chan []byte
- func (h *CommandHandle) Wait(ctx context.Context) (*CommandResult, error)
- type CommandResult
- type Commands
- func (c *Commands) CloseStdin(ctx context.Context, pid uint32) error
- func (c *Commands) Connect(ctx context.Context, pid uint32) (*CommandHandle, error)
- func (c *Commands) Kill(ctx context.Context, pid uint32) (bool, error)
- func (c *Commands) List(ctx context.Context) ([]ProcessInfo, error)
- func (c *Commands) Run(ctx context.Context, cmd string, opts RunOptions) (*CommandHandle, error)
- func (c *Commands) SendStdin(ctx context.Context, pid uint32, data []byte) error
- func (c *Commands) Start(ctx context.Context, cmd string, opts RunOptions) (*CommandHandle, error)
- type Config
- type ConnectOptions
- type CreateOptions
- type EntryInfo
- type EntryType
- type Error
- type FileNotFoundError
- type FileUploadError
- type Filesystem
- func (f *Filesystem) Exists(ctx context.Context, path string, opts FsOptions) (bool, error)
- func (f *Filesystem) IsDir(ctx context.Context, path string, opts FsOptions) (bool, error)
- func (f *Filesystem) List(ctx context.Context, path string, opts FsOptions) ([]EntryInfo, error)
- func (f *Filesystem) MakeDir(ctx context.Context, path string, opts FsOptions) error
- func (f *Filesystem) Move(ctx context.Context, from, to string, opts FsOptions) error
- func (f *Filesystem) Read(ctx context.Context, path string, opts FsOptions) ([]byte, error)
- func (f *Filesystem) ReadStream(ctx context.Context, path string, opts FsOptions) (io.ReadCloser, error)
- func (f *Filesystem) Remove(ctx context.Context, path string, opts FsOptions) error
- func (f *Filesystem) Stat(ctx context.Context, path string, opts FsOptions) (*EntryInfo, error)
- func (f *Filesystem) Watch(ctx context.Context, path string, recursive bool) (*WatchHandle, error)
- func (f *Filesystem) Write(ctx context.Context, path string, r io.Reader, opts FsOptions) (*WriteInfo, error)
- func (f *Filesystem) WriteFiles(ctx context.Context, entries []WriteEntry, opts FsOptions) ([]WriteInfo, error)
- func (f *Filesystem) WriteString(ctx context.Context, path, data string, opts FsOptions) (*WriteInfo, error)
- type FilesystemEvent
- type FilesystemEventType
- type FsOptions
- type Git
- func (g *Git) Add(ctx context.Context, pattern string, opts GitOptions) (*CommandResult, error)
- func (g *Git) Branches(ctx context.Context, opts GitOptions) (*GitBranches, error)
- func (g *Git) CheckoutBranch(ctx context.Context, name string, opts GitOptions) (*CommandResult, error)
- func (g *Git) Clone(ctx context.Context, url string, opts GitCloneOptions) (*CommandResult, error)
- func (g *Git) Commit(ctx context.Context, message string, opts GitOptions) (*CommandResult, error)
- func (g *Git) CreateBranch(ctx context.Context, name string, opts GitOptions) (*CommandResult, error)
- func (g *Git) DeleteBranch(ctx context.Context, name string, opts GitOptions) (*CommandResult, error)
- func (g *Git) GetRemoteURL(ctx context.Context, name string, opts GitOptions) (string, error)
- func (g *Git) Pull(ctx context.Context, opts GitOptions) (*CommandResult, error)
- func (g *Git) Push(ctx context.Context, opts GitOptions) (*CommandResult, error)
- func (g *Git) SetRemoteURL(ctx context.Context, name, url string, opts GitOptions) (*CommandResult, error)
- func (g *Git) Status(ctx context.Context, opts GitOptions) (*GitStatus, error)
- type GitAuthError
- type GitBranches
- type GitCloneOptions
- type GitOptions
- type GitStatus
- type GitUpstreamError
- type InvalidArgumentError
- type LifecycleOptions
- type MetricsOptions
- type NetworkOptions
- type NotEnoughSpaceError
- type NotFoundError
- type ProcessInfo
- type Pty
- func (p *Pty) Create(ctx context.Context, opts PtyOptions) (*CommandHandle, error)
- func (p *Pty) Kill(ctx context.Context, pid uint32) (bool, error)
- func (p *Pty) Resize(ctx context.Context, pid uint32, cols, rows uint32) error
- func (p *Pty) SendInput(ctx context.Context, pid uint32, data []byte) error
- type PtyOptions
- type RateLimitError
- type RunOptions
- type Sandbox
- func (s *Sandbox) CreateSnapshot(ctx context.Context) (*SnapshotInfo, error)
- func (s *Sandbox) DownloadURL(path string, opts SignatureOptions) (string, error)
- func (s *Sandbox) GetHost(port int) string
- func (s *Sandbox) GetInfo(ctx context.Context) (*SandboxInfo, error)
- func (s *Sandbox) GetMcpToken(ctx context.Context) (string, error)
- func (s *Sandbox) GetMcpURL() string
- func (s *Sandbox) GetMetrics(ctx context.Context, opts ...MetricsOptions) ([]SandboxMetric, error)
- func (s *Sandbox) IsRunning(ctx context.Context) (bool, error)
- func (s *Sandbox) Kill(ctx context.Context) error
- func (s *Sandbox) Pause(ctx context.Context) (bool, error)
- func (s *Sandbox) SetTimeout(ctx context.Context, d time.Duration) error
- func (s *Sandbox) UploadURL(path string, opts SignatureOptions) (string, error)
- type SandboxError
- type SandboxInfo
- type SandboxListOptions
- type SandboxMetric
- type SandboxNotFoundError
- type SandboxPaginator
- type SandboxState
- type Signature
- type SignatureOperation
- type SignatureOptions
- type SnapshotInfo
- type SnapshotListOptions
- type SnapshotPaginator
- type TemplateError
- type TimeoutError
- type VolumeError
- type VolumeMount
- type WatchHandle
- type WriteEntry
- type WriteInfo
Constants ¶
const ( DefaultRequestTimeout = 60 * time.Second KeepAlivePingIntervalSec = 50 KeepAlivePingHeader = "Keepalive-Ping-Interval" DefaultDomain = "e2b.app" )
Default request timeout (matches Python/JS SDK).
const ( DefaultSandboxTimeout = 300 * time.Second DefaultTemplate = "base" )
Defaults mirrored from the Python/JS SDKs.
const AllTraffic = "0.0.0.0/0"
AllTraffic is the CIDR range representing all IPv4 traffic.
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).
const MCPPort = 50005
MCPPort is the in-sandbox port the MCP gateway listens on.
const SDKVersion = version.SDKVersion
SDKVersion is this SDK's release version. It is kept in lockstep with the upstream python-sdk tag (see spec/E2B_VERSION) and regenerated by scripts/sync-spec.sh.
const UpstreamTag = version.UpstreamTag
UpstreamTag identifies the E2B git tag whose spec was used to generate the REST/Connect-RPC clients in internal/.
Variables ¶
var ( ErrTemplateBuild = errors.New("template build failed") ErrTemplateUpload = errors.New("template file upload failed") ErrTemplate = errors.New("template error") )
var ErrNotImplemented = errors.New("e2b: not implemented")
ErrNotImplemented is returned by stubbed features pending future work.
Functions ¶
Types ¶
type AuthenticationError ¶
type AuthenticationError struct {
Message string
// contains filtered or unexported fields
}
AuthenticationError reports invalid or missing credentials.
func (*AuthenticationError) Error ¶
func (e *AuthenticationError) Error() string
type BuildError ¶
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 a single shared HTTP client and control-plane REST client, both 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
NewClient resolves cfg (applying environment-variable fallbacks and defaults) and builds the shared HTTP and control-plane REST clients. Every Sandbox created through the returned Client reuses them.
A zero Config is valid; credentials and domain fall back to the environment.
func (*Client) Config ¶ added in v0.1.2
Config returns a copy of the resolved Config backing this Client. The map fields (Headers, ExtraSandboxHeaders) 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). If paused, the server resumes it; the call sets the sandbox timeout to opts.Timeout (default 5 minutes).
opts.Config is ignored (see Create).
func (*Client) Create ¶ added in v0.1.2
Create provisions a new sandbox and returns a *Sandbox wired up with all sub-clients, sharing this Client's HTTP and REST clients. The caller owns the returned sandbox and should call Kill (directly or via defer) to release it.
opts.Config is ignored: the Client already owns the resolved configuration. Use a separate Client (via NewClient) for a different credential set.
func (*Client) DeleteSnapshot ¶ added in v0.1.3
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.
func (*Client) Kill ¶ added in v0.1.2
Kill terminates a sandbox by ID. Returns false (nil error) if the sandbox was already gone.
func (*Client) List ¶ added in v0.1.2
func (c *Client) List(_ context.Context, opts SandboxListOptions) *SandboxPaginator
List returns a paginator over the sandboxes visible to this Client. The request is not issued until the first NextItems call.
Example:
p := c.List(ctx, e2b.SandboxListOptions{State: []e2b.SandboxState{e2b.SandboxStateRunning}})
for p.HasNext() {
page, err := p.NextItems(ctx)
if err != nil {
return err
}
for _, s := range page {
fmt.Println(s.SandboxID)
}
}
SandboxInfo records returned here are lighter than Sandbox.GetInfo: see sandboxInfoFromListed.
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.
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.
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.
Example:
p := c.ListSnapshots(ctx, e2b.SnapshotListOptions{})
for p.HasNext() {
page, err := p.NextItems(ctx)
if err != nil {
return err
}
for _, s := range page {
fmt.Println(s.SnapshotID)
}
}
type CommandExitError ¶
type CommandExitError struct {
Result CommandResult
// contains filtered or unexported fields
}
CommandExitError is returned by CommandHandle.Wait when a command exits non-zero. It embeds CommandResult so callers can inspect output.
func (*CommandExitError) Error ¶
func (e *CommandExitError) Error() string
type CommandHandle ¶
type CommandHandle struct {
// contains filtered or unexported fields
}
CommandHandle represents a running command. Events arrive on the channels returned by Stdout() and Stderr(); the channels close when the command exits or the stream fails. Call Wait to block and collect the final exit code.
func (*CommandHandle) Kill ¶
func (h *CommandHandle) Kill(ctx context.Context) (bool, error)
Kill signals the running command.
func (*CommandHandle) PID ¶
func (h *CommandHandle) PID() uint32
PID returns the command's process ID once known.
func (*CommandHandle) PtyOutput ¶
func (h *CommandHandle) PtyOutput() <-chan []byte
PtyOutput returns a channel of PTY data. Empty for non-PTY commands.
func (*CommandHandle) SendStdin ¶
func (h *CommandHandle) SendStdin(ctx context.Context, data []byte) error
SendStdin writes data to the command's stdin.
func (*CommandHandle) Stderr ¶
func (h *CommandHandle) Stderr() <-chan []byte
Stderr returns a channel of stderr byte slices.
func (*CommandHandle) Stdout ¶
func (h *CommandHandle) Stdout() <-chan []byte
Stdout returns a channel of stdout byte slices. The channel is closed when the command exits.
func (*CommandHandle) Wait ¶
func (h *CommandHandle) Wait(ctx context.Context) (*CommandResult, error)
Wait blocks until the command finishes, returns a *CommandResult, and wraps non-zero exit codes in a *CommandExitError.
type CommandResult ¶
CommandResult reports the outcome of a finished command.
type Commands ¶
type Commands struct {
// contains filtered or unexported fields
}
Commands exposes command-execution endpoints (fully implemented in commands_impl.go).
func (*Commands) CloseStdin ¶
CloseStdin closes the stdin side of the process.
Closing stdin requires envd >= 0.5.2; on an older build this returns an error up front instead of failing opaquely at the RPC layer.
func (*Commands) Connect ¶
Connect attaches to a running process by PID and streams remaining output.
func (*Commands) List ¶
func (c *Commands) List(ctx context.Context) ([]ProcessInfo, error)
List returns all processes currently running inside the sandbox.
func (*Commands) Run ¶
func (c *Commands) Run(ctx context.Context, cmd string, opts RunOptions) (*CommandHandle, error)
Run executes cmd and blocks until it exits (unless opts.Background is true, in which case Run returns a handle immediately). Callers may observe output through the returned handle's channels or the OnStdout/OnStderr callbacks.
func (*Commands) Start ¶
func (c *Commands) Start(ctx context.Context, cmd string, opts RunOptions) (*CommandHandle, error)
Start launches cmd and returns a live *CommandHandle.
type Config ¶
type Config struct {
// APIKey authenticates team-scoped requests (X-API-Key header).
// Defaults to $E2B_API_KEY.
APIKey string
// AccessToken authenticates user-scoped requests (Authorization: Bearer).
// Defaults to $E2B_ACCESS_TOKEN.
AccessToken string
// Domain for sandbox URLs and the default API URL. Defaults to $E2B_DOMAIN
// or "e2b.app".
Domain string
// APIURL overrides the control-plane URL. Defaults to https://api.<domain>
// (or http://localhost:3000 when Debug is true).
APIURL string
// SandboxURL overrides the envd URL per-sandbox (testing/tunneling).
// Defaults to $E2B_SANDBOX_URL.
SandboxURL string
// Debug flips the default API URL to localhost and sandbox URLs to http://.
// Defaults to $E2B_DEBUG == "true".
Debug bool
// RequestTimeout bounds a single HTTP request. 0 means "no timeout".
// When unset (zero Duration) the SDK uses DefaultRequestTimeout; callers
// can disable it by setting Config.RequestTimeoutDisabled = true.
RequestTimeout time.Duration
RequestTimeoutDisabled bool
// Headers added to every REST request (additional sandbox headers are
// applied on envd traffic too).
Headers map[string]string
// ExtraSandboxHeaders added only to envd traffic.
ExtraSandboxHeaders map[string]string
// HTTPClient optionally overrides the transport. If nil a default client
// with RequestTimeout is built on demand.
HTTPClient *http.Client
}
Config holds connection/auth/transport settings shared by all client calls. It mirrors Python's ConnectionConfig and JS's ConnectionOpts.
A zero Config is valid — missing fields fall back to environment variables (E2B_API_KEY, E2B_DOMAIN, E2B_ACCESS_TOKEN, E2B_API_URL, E2B_SANDBOX_URL, E2B_DEBUG) and then to sensible defaults.
func (Config) Resolve ¶
Resolve returns a Config copy with environment-variable fallbacks and defaults applied. Safe to call on a zero Config.
func (Config) ResolvedHTTPClient ¶
ResolvedHTTPClient returns the HTTP client this Config would use: the HTTPClient field if set, else a fresh *http.Client with RequestTimeout. Named with the Resolved- prefix because it would otherwise collide with the HTTPClient struct field.
type ConnectOptions ¶
ConnectOptions configures (Re)connecting to an existing sandbox.
type CreateOptions ¶
type CreateOptions struct {
Config Config
// Template ID or alias to build the sandbox from. Defaults to "base".
Template string
// Timeout is the sandbox lifetime. Defaults to 5 minutes.
Timeout time.Duration
// Metadata attaches free-form key/value pairs.
Metadata map[string]string
// Envs sets environment variables inside the sandbox.
Envs map[string]string
// Secure enables authenticated envd access (recommended).
Secure bool
// AllowInternetAccess enables outbound internet. Defaults to true.
// Use AllowInternetAccessSet=true to send a false value.
AllowInternetAccess bool
AllowInternetAccessSet bool
// Network, Lifecycle, and VolumeMounts pass through to the API.
Network *NetworkOptions
Lifecycle *LifecycleOptions
VolumeMounts []VolumeMount
// Mcp is an opaque MCP configuration object (see upstream docs).
Mcp map[string]any
}
CreateOptions captures every parameter accepted by e2b.Create. Mirrors the Python Sandbox.create(...) signature. All fields are optional except — implicitly — an API key or access token reachable via Config/env.
type EntryInfo ¶
type EntryInfo struct {
Name string
Path string
Type EntryType
Size int64
Mode uint32
Permissions string
Owner string
Group string
ModifiedTime time.Time
SymlinkTarget string
}
EntryInfo is the metadata for a file or directory.
type Error ¶
type Error interface {
error
// contains filtered or unexported methods
}
Error is the base interface implemented by every SDK-specific error. It lets callers switch on a single interface via errors.As:
var sErr e2b.Error
if errors.As(err, &sErr) { ... }
type FileNotFoundError ¶
type FileNotFoundError struct {
Path string
Message string
// contains filtered or unexported fields
}
FileNotFoundError reports a missing file/directory in the sandbox.
func (*FileNotFoundError) Error ¶
func (e *FileNotFoundError) Error() string
type FileUploadError ¶
type FileUploadError struct {
Path string
Message string
Cause error
// contains filtered or unexported fields
}
FileUploadError reports a file upload failure during template build.
func (*FileUploadError) Error ¶
func (e *FileUploadError) Error() string
func (*FileUploadError) Unwrap ¶
func (e *FileUploadError) Unwrap() error
type Filesystem ¶
type Filesystem struct {
// contains filtered or unexported fields
}
Filesystem exposes filesystem endpoints (implemented in filesystem_impl.go).
func (*Filesystem) List ¶
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 is rejected, matching the reference SDKs' depth>=1 rule.
func (*Filesystem) ReadStream ¶
func (f *Filesystem) ReadStream(ctx context.Context, path string, opts FsOptions) (io.ReadCloser, error)
ReadStream returns a streaming reader for path.
func (*Filesystem) Watch ¶
func (f *Filesystem) Watch(ctx context.Context, path string, recursive bool) (*WatchHandle, error)
Watch starts watching a directory for filesystem events. The returned handle fans events onto a channel; Stop() cancels the stream.
Recursive watching requires envd >= 0.1.4; requesting it on an older build returns an error up front instead of failing opaquely at the RPC layer.
func (*Filesystem) Write ¶
func (f *Filesystem) Write(ctx context.Context, path string, r io.Reader, opts FsOptions) (*WriteInfo, error)
Write creates or overwrites a file with the contents of r. Returns the final EntryInfo of the written file.
The upload encoding is gated on the envd version: envd >= 0.5.7 accepts a raw application/octet-stream body, while older envd requires multipart/form-data. See uploadOne.
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 in one call, 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.
func (*Filesystem) WriteString ¶
func (f *Filesystem) WriteString(ctx context.Context, path, data string, opts FsOptions) (*WriteInfo, error)
WriteString is a convenience helper for small text payloads.
type FilesystemEvent ¶
type FilesystemEvent struct {
Name string
Type FilesystemEventType
}
FilesystemEvent is one event emitted by Filesystem.Watch.
type FilesystemEventType ¶
type FilesystemEventType int
FilesystemEventType enumerates filesystem event kinds.
const ( FsEventUnspecified FilesystemEventType = iota FsEventCreate FsEventWrite FsEventRemove FsEventRename FsEventChmod )
type FsOptions ¶
type FsOptions struct {
User string
RequestTimeoutMs int
// Depth limits how many directory levels Filesystem.List descends. 0 means
// the default of 1 (immediate children only). Ignored by other operations.
Depth int
}
FsOptions holds per-call tweaks common across filesystem operations.
type Git ¶
type Git struct {
// contains filtered or unexported fields
}
Git wraps Commands to run git operations inside the sandbox. Method bodies are in git_impl.go.
func (*Git) Add ¶
func (g *Git) Add(ctx context.Context, pattern string, opts GitOptions) (*CommandResult, error)
Add runs `git add` for the given pattern(s).
func (*Git) Branches ¶
func (g *Git) Branches(ctx context.Context, opts GitOptions) (*GitBranches, error)
Branches parses `git branch -a`.
func (*Git) CheckoutBranch ¶
func (g *Git) CheckoutBranch(ctx context.Context, name string, opts GitOptions) (*CommandResult, error)
CheckoutBranch switches to a branch.
func (*Git) Clone ¶
func (g *Git) Clone(ctx context.Context, url string, opts GitCloneOptions) (*CommandResult, error)
Clone clones a repository into the sandbox. When creds are provided they are injected into the URL for a single invocation; pass DangerouslyStoreCredentials to persist them.
func (*Git) Commit ¶
func (g *Git) Commit(ctx context.Context, message string, opts GitOptions) (*CommandResult, error)
Commit runs `git commit -m <message>`.
func (*Git) CreateBranch ¶
func (g *Git) CreateBranch(ctx context.Context, name string, opts GitOptions) (*CommandResult, error)
CreateBranch creates a branch with the given name.
func (*Git) DeleteBranch ¶
func (g *Git) DeleteBranch(ctx context.Context, name string, opts GitOptions) (*CommandResult, error)
DeleteBranch deletes a branch.
func (*Git) GetRemoteURL ¶
GetRemoteURL returns the URL of the named remote (default "origin").
func (*Git) Pull ¶
func (g *Git) Pull(ctx context.Context, opts GitOptions) (*CommandResult, error)
Pull runs `git pull`.
func (*Git) Push ¶
func (g *Git) Push(ctx context.Context, opts GitOptions) (*CommandResult, error)
Push runs `git push`.
func (*Git) SetRemoteURL ¶
func (g *Git) SetRemoteURL(ctx context.Context, name, url string, opts GitOptions) (*CommandResult, error)
SetRemoteURL sets the URL of the named remote.
type GitAuthError ¶
type GitAuthError struct {
Message string
// contains filtered or unexported fields
}
GitAuthError specializes AuthenticationError for Git credential failures.
func (*GitAuthError) Error ¶
func (e *GitAuthError) Error() string
type GitBranches ¶
GitBranches is the parsed output of "git branch".
type GitCloneOptions ¶
type GitCloneOptions struct {
GitOptions
Branch string
Depth int
Username string
Password string
// DangerouslyStoreCredentials persists creds in the repo config.
DangerouslyStoreCredentials bool
}
GitCloneOptions configures Git.Clone.
type GitOptions ¶
GitOptions holds optional knobs shared by most Git methods.
type GitUpstreamError ¶
type GitUpstreamError struct {
Message string
// contains filtered or unexported fields
}
GitUpstreamError reports a missing upstream branch.
func (*GitUpstreamError) Error ¶
func (e *GitUpstreamError) Error() string
type InvalidArgumentError ¶
type InvalidArgumentError struct {
Message string
// contains filtered or unexported fields
}
InvalidArgumentError reports an invalid parameter.
func (*InvalidArgumentError) Error ¶
func (e *InvalidArgumentError) Error() string
type LifecycleOptions ¶
type LifecycleOptions struct {
// OnTimeout is "pause" or "kill". Empty means server default (kill).
OnTimeout string
// AutoResume configures auto-resume for paused sandboxes.
AutoResume bool
}
LifecycleOptions controls what happens when the sandbox timeout fires.
type 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 is a list of CIDR blocks or IPs permitted for egress.
AllowOut []string
// DenyOut is a list of CIDR blocks or IPs blocked for egress.
DenyOut []string
// AllowPublicTraffic, when true, makes sandbox URLs reachable without
// the traffic access token.
AllowPublicTraffic bool
// MaskRequestHost customizes the host template on sandbox URLs.
MaskRequestHost string
}
NetworkOptions configures sandbox egress and public-traffic policy. Mirrors SandboxNetworkConfig in the REST API.
type NotEnoughSpaceError ¶
type NotEnoughSpaceError struct {
Message string
// contains filtered or unexported fields
}
NotEnoughSpaceError reports the sandbox has insufficient disk space.
func (*NotEnoughSpaceError) Error ¶
func (e *NotEnoughSpaceError) Error() string
type NotFoundError ¶
type NotFoundError struct {
Message string
// contains filtered or unexported fields
}
NotFoundError is deprecated. Prefer FileNotFoundError or SandboxNotFoundError.
func (*NotFoundError) Error ¶
func (e *NotFoundError) Error() string
type ProcessInfo ¶
type ProcessInfo struct {
PID uint32
Cmd string
Args []string
Envs map[string]string
Cwd string
Tag string
}
ProcessInfo describes a running command or PTY inside the sandbox.
type Pty ¶
type Pty struct {
// contains filtered or unexported fields
}
Pty exposes PTY endpoints (implemented in pty_impl.go).
func (*Pty) Create ¶
func (p *Pty) Create(ctx context.Context, opts PtyOptions) (*CommandHandle, error)
Create starts an interactive PTY session.
type PtyOptions ¶
type PtyOptions struct {
Cmd string
Args []string
Envs map[string]string
Cwd string
Cols uint32
Rows uint32
Tag string
OnData func([]byte)
}
PtyOptions configures Pty.Create.
type RateLimitError ¶
type RateLimitError struct {
Message string
// contains filtered or unexported fields
}
RateLimitError reports HTTP 429.
func (*RateLimitError) Error ¶
func (e *RateLimitError) Error() string
type RunOptions ¶
type RunOptions struct {
Args []string
Cwd string
User string
Envs map[string]string
TimeoutMs int
Stdin io.Reader
Background bool
Tag string
OnStdout func([]byte)
OnStderr func([]byte)
}
RunOptions configures Commands.Run and Commands.Start.
type Sandbox ¶
type Sandbox struct {
ID string
Domain string
EnvdVersion string
EnvdAccessToken string
TrafficAccessToken string
// Per-sandbox sub-clients (non-nil after Create/Connect).
Commands *Commands
Pty *Pty
Files *Filesystem
Git *Git
// contains filtered or unexported fields
}
Sandbox is a handle to a running (or paused) E2B sandbox.
It exposes three per-sandbox modules:
- Commands: exec, PTY, signal
- Files: read/write/watch
- Git: git operations running inside the sandbox
A *Sandbox is safe for concurrent use.
func Connect
deprecated
Connect attaches to an existing sandbox (running or paused). If paused, the server resumes it; the call sets the sandbox timeout to opts.Timeout (default 5 minutes).
Deprecated: prefer NewClient(cfg).Connect (see Create).
func Create
deprecated
func Create(ctx context.Context, opts CreateOptions) (*Sandbox, error)
Create provisions a new sandbox and returns a *Sandbox wired up with all sub-clients. The caller owns the returned sandbox and should call Kill (directly or via defer) to release it.
Deprecated: prefer NewClient(cfg).Create, which reuses one control-plane REST client across calls. This helper builds a throwaway Client from opts.Config on every call.
func (*Sandbox) CreateSnapshot ¶
func (s *Sandbox) CreateSnapshot(ctx context.Context) (*SnapshotInfo, error)
CreateSnapshot persists the sandbox's state as a snapshot.
func (*Sandbox) DownloadURL ¶
func (s *Sandbox) DownloadURL(path string, opts SignatureOptions) (string, error)
DownloadURL returns an HTTP URL the caller can GET a file from.
func (*Sandbox) GetInfo ¶
func (s *Sandbox) GetInfo(ctx context.Context) (*SandboxInfo, error)
GetInfo fetches the sandbox metadata.
func (*Sandbox) GetMcpToken ¶ added in v0.1.3
GetMcpToken reads the MCP gateway access token from inside the sandbox (/etc/mcp-gateway/.token). It returns a FileNotFoundError if no MCP gateway is configured.
The token file is owned by root, so the read is performed as root (matching the reference SDKs); reading it as the default user fails with a permission or not-found error even when the gateway is configured.
func (*Sandbox) GetMcpURL ¶ added in v0.1.3
GetMcpURL returns the sandbox's MCP gateway URL (https://<host>/mcp). It does not verify that an MCP gateway is actually running; create the sandbox with CreateOptions.Mcp to enable one.
func (*Sandbox) GetMetrics ¶
func (s *Sandbox) GetMetrics(ctx context.Context, opts ...MetricsOptions) ([]SandboxMetric, error)
GetMetrics fetches CPU/memory/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).
func (*Sandbox) IsRunning ¶
IsRunning reports whether the sandbox is still alive (REST GET /sandboxes/{id}).
func (*Sandbox) Pause ¶
Pause pauses this sandbox. Returns true on success; false if the sandbox was already paused.
func (*Sandbox) SetTimeout ¶
SetTimeout updates the sandbox's inactivity timeout.
type SandboxError ¶
SandboxError wraps arbitrary sandbox/API failures that don't have a more specific type.
func (*SandboxError) Error ¶
func (e *SandboxError) Error() string
func (*SandboxError) Unwrap ¶
func (e *SandboxError) Unwrap() error
type SandboxInfo ¶
type SandboxInfo struct {
SandboxID string
Alias string
Domain string
TemplateID string
State SandboxState
CPUCount int32
MemoryMB int32
DiskSizeMB int32
StartedAt time.Time
EndAt time.Time
Metadata map[string]string
EnvdVersion string
EnvdAccessToken string
AllowInternetAccess *bool
Network *NetworkOptions
Lifecycle *LifecycleOptions
VolumeMounts []VolumeMount
}
SandboxInfo holds REST-reported metadata about a sandbox.
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).
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
// 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. The zero value lists all sandboxes the caller can see, one server-defined page at a time.
type SandboxMetric ¶
type SandboxMetric struct {
CPUCount int32
CPUUsedPct float32
DiskTotal int64
DiskUsed int64
MemTotal int64
MemUsed int64
Timestamp time.Time
TimestampUnix int64
}
SandboxMetric is one sample of resource usage.
type SandboxNotFoundError ¶
type SandboxNotFoundError struct {
SandboxID string
Message string
// contains filtered or unexported fields
}
SandboxNotFoundError reports that the sandbox is gone or never existed.
func (*SandboxNotFoundError) Error ¶
func (e *SandboxNotFoundError) Error() string
type 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.
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.
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.
type SandboxState ¶
type SandboxState string
SandboxState reports whether a sandbox is running or paused.
const ( SandboxStateRunning SandboxState = "running" SandboxStatePaused SandboxState = "paused" )
type Signature ¶
Signature is an opaque v1 signature usable as a query parameter when hitting envd's file endpoints.
func GetSignature ¶
func GetSignature(path string, operation SignatureOperation, envdAccessToken string, opts SignatureOptions) (Signature, error)
GetSignature produces a v1 signature for an envd /files request. It matches the Python and JS implementations byte-for-byte.
raw = path:operation:user:envdAccessToken[:expiration] signature = "v1_" + base64url(sha256(raw)) // '=' padding stripped
type SignatureOperation ¶
type SignatureOperation string
SignatureOperation is either "read" or "write".
const ( SignatureRead SignatureOperation = "read" SignatureWrite SignatureOperation = "write" )
type SignatureOptions ¶
SignatureOptions configures GetSignature.
type SnapshotInfo ¶
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
// 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.
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.
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 {
Message string
// contains filtered or unexported fields
}
TemplateError reports template/envd incompatibility.
func (*TemplateError) Error ¶
func (e *TemplateError) Error() string
type TimeoutError ¶
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 ¶
VolumeError reports a volume operation failure.
func (*VolumeError) Error ¶
func (e *VolumeError) Error() string
func (*VolumeError) Unwrap ¶
func (e *VolumeError) Unwrap() error
type VolumeMount ¶
VolumeMount attaches a volume to a sandbox path.
type WatchHandle ¶
type WatchHandle struct {
// contains filtered or unexported fields
}
WatchHandle streams filesystem events from Filesystem.Watch.
func (*WatchHandle) Err ¶
func (w *WatchHandle) Err() error
Err returns the error (if any) that terminated the watch.
func (*WatchHandle) Events ¶
func (w *WatchHandle) Events() <-chan FilesystemEvent
Events returns a receive-only channel that yields filesystem events. The channel is closed when the watch ends; check Err() afterwards.
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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic
command
Basic example: create a sandbox, run a command, read its output.
|
Basic example: create a sandbox, run a command, read its output. |
|
desktop
command
Desktop example: build the local e2b.Dockerfile as a template, launch a sandbox, print the noVNC URL, then prove that SDK PTY sessions are mirrored into the shared tmux that the VNC desktop shows.
|
Desktop example: build the local e2b.Dockerfile as a template, launch a sandbox, print the noVNC URL, then prove that SDK PTY sessions are mirrored into the shared tmux that the VNC desktop shows. |
|
lifecycle
command
Lifecycle example: list templates, build a new one, inspect it, spawn a sandbox from it, read sandbox info, then tear everything down.
|
Lifecycle example: list templates, build a new one, inspect it, spawn a sandbox from it, read sandbox info, then tear everything down. |
|
lifecycle_v2
command
Lifecycle example for self-hosted E2B control planes that predate the /v3/templates endpoint (≤ 2.1.x).
|
Lifecycle example for self-hosted E2B control planes that predate the /v3/templates endpoint (≤ 2.1.x). |
|
selfhosted
command
Self-hosted example: point the SDK at a self-hosted E2B control plane and show the current sandbox session (ID, template, state, timing, envd info, live metrics).
|
Self-hosted example: point the SDK at a self-hosted E2B control plane and show the current sandbox session (ID, template, state, timing, envd info, live metrics). |
|
template
command
Template example: build a simple Debian-based template and launch a sandbox from it.
|
Template example: build a simple Debian-based template and launch a sandbox from it. |
|
terminal
command
Interactive terminal example: open an E2B sandbox, attach the local TTY to a remote PTY (bash) in raw mode, and close the sandbox when the user exits.
|
Interactive terminal example: open an E2B sandbox, attach the local TTY to a remote PTY (bash) in raw mode, and close the sandbox when the user exits. |
|
internal
|
|
|
api
Package apiclient provides primitives to interact with the openapi HTTP API.
|
Package apiclient provides primitives to interact with the openapi HTTP API. |
|
envdapi
Package envdapi provides primitives to interact with the openapi HTTP API.
|
Package envdapi provides primitives to interact with the openapi HTTP API. |
|
transport
Package transport wires the REST (oapi-codegen) and Connect-RPC clients used by the public e2b package.
|
Package transport wires the REST (oapi-codegen) and Connect-RPC clients used by the public e2b package. |
|
version
Code generated by scripts/sync-spec.sh.
|
Code generated by scripts/sync-spec.sh. |
|
volumeapi
Package volumeapi provides primitives to interact with the openapi HTTP API.
|
Package volumeapi provides primitives to interact with the openapi HTTP API. |
|
Package template provides a fluent builder and a Client for building E2B sandbox templates.
|
Package template provides a fluent builder and a Client for building E2B sandbox templates. |
|
Package volume provides a client for E2B persistent volumes.
|
Package volume provides a client for E2B persistent volumes. |