sandbox

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2026 License: MIT Imports: 23 Imported by: 0

README

Sandbox Go SDK

Go SDK for Sandbox control-plane, build-plane, and nano-executor CMD APIs.

Install

go get github.com/SeaArt-Infra/sandbox-go

Entrypoints

Preferred public API:

  • initialize once: sandbox.NewClient(baseURL, apiKey, opts...)
  • sandbox lifecycle through the root client: client.Create, client.Connect, client.List
  • sandbox runtime modules from the returned object: created.Commands(), created.Files(), created.Git(), created.Pty()
  • template builder through the root client: sandbox.NewTemplate() plus client.BuildTemplate(...)
  • low-level build plane via client.Build
  • raw runtime helper: createdSandbox.Runtime() or client.RuntimeFromSandbox(createdSandbox)

control and build both talk to the same gateway. Runtime access is derived from sandbox create/detail/connect responses; callers should not hardcode runtime endpoints or tokens. On the public production gateway, tenant and project identity are derived from the authenticated production key; caller-supplied project headers do not select another tenant.

E2B Alignment

  • Supported alignment target: sandbox lifecycle, files, commands, git, PTY, and the high-level template DSL are designed to follow the same public workflow as e2b-docs/sdk.
  • Known unsupported area: snapshot APIs are not exposed because the underlying platform does not support them yet.
  • Go-specific note: the SDK aims for semantic equivalence rather than identical hand feel. Method names, context.Context, and (..., error) returns stay Go-native on purpose.
  • Runtime compatibility note: the SDK normalizes a few runtime-specific quirks so the high-level behavior stays E2B-like, such as missing-process Kill() results and PTY reconnect output framing.

Environment

Use environment variables for gateway configuration in all examples and quick starts:

  • SEAINFRA_BASE_URL: SeaInfra gateway entrypoint
  • SEAINFRA_API_KEY: API key used for gateway routing and authentication
  • SEAINFRA_TEMPLATE_ID: sandbox template identifier or official template type for your target environment

Set them once in your shell:

export SEAINFRA_BASE_URL="https://openresty-gateway.api.seaart.ai/agent-v2"
export SEAINFRA_API_KEY="..."
export SEAINFRA_TEMPLATE_ID="tpl-..."

Default production gateway:

https://openresty-gateway.api.seaart.ai/agent-v2

Use SEAINFRA_TEMPLATE_ID for production integrations. It can be either a concrete template ID such as tpl-... or a stable official template type such as base, claude, or codex when your environment publishes those official templates.

Production Readiness

  • Initialize exactly one root client per process and reuse it.
  • Treat every quick start as creating billable or quota-bound resources unless it explicitly cleans them up.
  • Prefer explicit template references from configuration over hardcoded example values.
  • In SeaInfra environments, prefer official template types such as base, claude, or codex when you want a stable platform-managed entrypoint.
  • Use longer client timeouts for waitReady flows and image builds.
  • Derive runtime access from sandbox responses instead of storing runtime endpoints or tokens in config.

Compatibility

  • Go: see go.mod for the supported toolchain version used by this SDK.
  • API model: this SDK targets the unified SeaInfra sandbox gateway and keeps public template APIs limited to user-facing fields.
  • Stability: operator/admin routes may exist on the gateway, but they are not part of the public SDK workflow described in this README.
  • Retry model: treat create/delete/build operations as remote control-plane actions; add idempotency and retry policy in your application layer according to your workload.

Quick Start

Control Plane
package main

import (
	"context"
	"log"
	"os"
	"time"

	"github.com/SeaArt-Infra/sandbox-go"
	"github.com/SeaArt-Infra/sandbox-go/core"
)

func main() {
	client, err := sandbox.NewClient(
		os.Getenv("SEAINFRA_BASE_URL"),
		os.Getenv("SEAINFRA_API_KEY"),
		core.WithTimeout(180*time.Second),
	)
	if err != nil {
		log.Fatal(err)
	}

	ready := true
	timeout := int32(1800)
	createdSandbox, err := client.Create(context.Background(), os.Getenv("SEAINFRA_TEMPLATE_ID"), &sandbox.CreateOptions{
		WaitReady: &ready,
		Timeout:   &timeout,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer createdSandbox.Delete(context.Background())

	log.Printf("sandbox=%s envd=%v", createdSandbox.SandboxID, createdSandbox.EnvdURL)
	if createdSandbox.EnvdURL != nil {
		runtime, err := createdSandbox.Runtime()
		if err != nil {
			log.Fatal(err)
		}
		log.Printf("runtime=%s", runtime.BaseURL())
	}
}
Bound Sandbox Workflow
client, err := sandbox.NewClient(os.Getenv("SEAINFRA_BASE_URL"), os.Getenv("SEAINFRA_API_KEY"))
if err != nil {
	log.Fatal(err)
}

listed, err := client.List(context.Background(), nil)
if err != nil {
	log.Fatal(err)
}

for _, sandbox := range listed {
	detail, err := sandbox.Reload(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("sandbox=%s status=%s", detail.SandboxID, detail.Status)
}
Template Build
client, err := sandbox.NewClient(os.Getenv("SEAINFRA_BASE_URL"), os.Getenv("SEAINFRA_API_KEY"))
if err != nil {
	log.Fatal(err)
}

ctx := context.Background()
base, err := client.Build.ResolveTemplateRef(ctx, "node")
if err != nil {
	log.Fatal(err)
}

template := sandbox.NewTemplate().
	FromTemplate(base.TemplateID).
	SetWorkdir("/app").
	Copy("./app", "/app", nil)

built, err := client.BuildTemplate(ctx, template, "demo:v1", &sandbox.TemplateBuildOptions{
	BaseTemplateID: base.TemplateID,
	Workdir:        "/app",
})
if err != nil {
	log.Fatal(err)
}

log.Printf("template=%s build=%s status=%s", built.TemplateID, built.BuildID, built.Status)

High-level template helpers currently include:

  • lifecycle and status: client.BuildTemplate, client.BuildTemplateInBackground, client.TemplateExists, client.TemplateAliasExists, client.GetTemplateBuildStatus, client.ListTemplates, client.GetTemplate, client.DeleteTemplate
  • serialization: sandbox.TemplateToJSON, sandbox.TemplateToDockerfile
  • base images and registries: FromDockerfile, FromBaseImage, FromNodeImage, FromPythonImage, FromBunImage, FromUbuntuImage, FromDebianImage, FromAWSRegistry, FromGCPRegistry
  • build-step helpers: Copy, CopyItems, SkipCache, AptInstall, GitClone, MakeDir, MakeSymlink, NpmInstall, PipInstall, BunInstall, Remove, Rename, RunCmd, RunCmds
  • execution and config helpers: SetEnvs, SetWorkdir, SetUser, SetStartCmd, SetReadyCmd
  • supported local copy options: ForceUpload, Mode, ResolveSymlinks
  • supported command and path options: RunCmd(..., &sandbox.TemplateCommandOptions{User: ...}), GitClone(..., &sandbox.TemplateGitCloneOptions{User: ...}), MakeDir(..., &sandbox.TemplateMakeDirOptions{User: ...}), MakeSymlink(..., &sandbox.TemplateMakeSymlinkOptions{User: ...}), Remove(..., &sandbox.TemplateRemoveOptions{...User: ...}), Rename(..., &sandbox.TemplateRenameOptions{...User: ...})
  • intentionally not exposed yet: Copy(..., user=...), MCP server helpers, and devcontainer helpers
Raw Build Plane Through Root Client
package main

import (
	"context"
	"log"
	"os"

	"github.com/SeaArt-Infra/sandbox-go"
	"github.com/SeaArt-Infra/sandbox-go/build"
)

func main() {
	client, err := sandbox.NewClient(
		os.Getenv("SEAINFRA_BASE_URL"),
		os.Getenv("SEAINFRA_API_KEY"),
	)
	if err != nil {
		log.Fatal(err)
	}

	resp, err := client.Build.CreateTemplate(context.Background(), &build.TemplateCreateRequest{
		Name: "demo",
	})
	if err != nil {
		log.Fatal(err)
	}
	defer client.Build.DeleteTemplate(context.Background(), resp.TemplateID)

	buildID := "build-demo"
	_, err = client.Build.CreateBuild(
		context.Background(),
		resp.TemplateID,
		buildID,
		build.NewTemplateBuildBuilder().
			FromImage("docker.io/library/alpine:3.20").
			Run("echo hello-from-go >/tmp/hello.txt", nil).
			Request(),
	)
	if err != nil {
		log.Fatal(err)
	}

	log.Printf("template=%s build=%s", resp.TemplateID, buildID)
}
Runtime Modules
package main

import (
	"context"
	"log"
	"os"

	"github.com/SeaArt-Infra/sandbox-go"
)

func main() {
	client, err := sandbox.NewClient(os.Getenv("SEAINFRA_BASE_URL"), os.Getenv("SEAINFRA_API_KEY"))
	if err != nil {
		log.Fatal(err)
	}

	ready := true
	createdSandbox, err := client.Create(context.Background(), os.Getenv("SEAINFRA_TEMPLATE_ID"), &sandbox.CreateOptions{
		WaitReady: &ready,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer createdSandbox.Delete(context.Background())

	files, err := createdSandbox.Files()
	if err != nil {
		log.Fatal(err)
	}
	if _, err := files.Write(context.Background(), "/root/workspace/hello.txt", []byte("hello from go")); err != nil {
		log.Fatal(err)
	}

	body, err := files.Read(context.Background(), "/root/workspace/hello.txt")
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("%s", body)
}

Bound sandbox helpers currently include:

  • lifecycle: Reload, Connect, Resume, GetInfo, Logs, Pause, Kill, Delete, Refresh, SetTimeout, IsRunning
  • runtime conveniences: GetMetrics, GetHost, Proxy
  • commands module: Run, Exec, Start, Wait, List, Connect, Kill, SendStdin
  • filesystem module: Exists, GetInfo, List, MakeDir, Read, Write, WriteFiles, Remove, Rename, WatchDir
  • git module: Clone, Pull, Checkout, Status
  • pty module: Create, Connect, Kill, SendStdin, Resize

For most integrations, prefer one root client per process:

  • initialize once with sandbox.NewClient(baseURL, apiKey, opts...)
  • create sandboxes with client.Create(...)
  • continue through Commands()/Files()/Git()/Pty()
  • build templates with sandbox.NewTemplate() plus client.BuildTemplate(...)

Low-level methods remain available when you need tighter request control:

  • use CreateSandbox, ListSandboxes, GetSandbox, ConnectSandbox
  • continue from the returned sandbox object with Reload(), Connect(), Resume(), GetInfo(), GetMetrics(), GetHost(), Logs(), Pause(), Refresh(), SetTimeout(), Kill(), Delete(), and IsRunning()
  • only switch to runtime with Runtime() when you need file/process/stream operations
  • use BuildTemplate, BuildTemplateInBackground, TemplateExists, GetTemplateBuildStatus, ListTemplates, GetTemplate, and DeleteTemplate on the root client for bound template workflows
  • use client.Build only for raw template/build workflows
  • use build.NewTemplateBuildBuilder() when you want a small fluent helper that expands into BuildRequest

Low-level domain packages remain available when you need direct request/response models or tighter transport control.

API Surface

Control Plane APIs

sandbox.Client exposes control-plane methods directly:

  • system: Metrics, Shutdown
  • sandboxes: CreateSandbox, ListSandboxes, GetSandbox, DeleteSandbox
  • sandbox operations: GetSandboxLogs, PauseSandbox, ConnectSandbox, SetSandboxTimeout, RefreshSandbox, SendHeartbeat

Recommended root-client path:

  • high-level lifecycle: Create, Connect, List, Get
  • template helpers: BuildTemplate, BuildTemplateInBackground, TemplateExists, TemplateAliasExists, GetTemplateBuildStatus, ListTemplates, GetTemplate, DeleteTemplate
  • low-level lifecycle: CreateSandbox, ListSandboxes, GetSandbox, ConnectSandbox
  • follow-up control actions from the returned object: Reload(), Connect(), Resume(), GetInfo(), GetMetrics(), GetHost(), Logs(), Pause(), Refresh(), SetTimeout(), Kill(), Delete(), IsRunning()
  • runtime actions from objects that include EnvdURL: Runtime()

Low-level direct methods like DeleteSandbox and GetSandboxLogs remain available on the root client when you want explicit control-plane requests.

Operator APIs

The root client also includes operator-oriented methods such as GetPoolStatus, StartRollingUpdate, GetRollingUpdateStatus, and CancelRollingUpdate.

These routes are intended for trusted internal deployments connected directly to an operator endpoint. The public production-key gateway does not expose them. A production key cannot use them and cannot access Admin, namespace, metrics, shutdown, heartbeat, or quota-override routes.

Template Facade

Preferred template path:

  • sandbox.NewTemplate() for build DSL
  • client.BuildTemplate(...) for create + build + optional polling
  • client.BuildTemplateInBackground(...) for fire-and-poll-later workflows
  • client.ListTemplates(...), client.GetTemplate(...), client.DeleteTemplate(...), client.TemplateExists(...), client.TemplateAliasExists(...), client.GetTemplateBuildStatus(...) for bound lifecycle and status
  • sandbox.TemplateToJSON(...), sandbox.TemplateToDockerfile(...) for export helpers

Template builder conveniences include:

  • base images and registries: FromDockerfile (returns (*Template, error)), FromBaseImage, FromNodeImage, FromPythonImage, FromBunImage, FromUbuntuImage, FromDebianImage, FromAWSRegistry, FromGCPRegistry
  • file and command helpers: Copy, CopyItems, SkipCache, AptInstall, GitClone, MakeDir, MakeSymlink, NpmInstall, PipInstall, BunInstall, Remove, Rename, RunCmd, RunCmds
  • execution and config helpers: SetEnvs, SetWorkdir, SetUser, SetStartCmd, SetReadyCmd
  • supported local copy options: ForceUpload, Mode, ResolveSymlinks
  • supported command and path options: RunCmd(..., &sandbox.TemplateCommandOptions{User: ...}), GitClone(..., &sandbox.TemplateGitCloneOptions{User: ...}), MakeDir(..., &sandbox.TemplateMakeDirOptions{User: ...}), MakeSymlink(..., &sandbox.TemplateMakeSymlinkOptions{User: ...}), Remove(..., &sandbox.TemplateRemoveOptions{...User: ...}), Rename(..., &sandbox.TemplateRenameOptions{...User: ...})
  • intentionally not exposed yet: Copy(..., user=...), MCP server helpers, and devcontainer helpers
Build Plane Through client.Build

Low-level client.Build contains:

  • internal/operator-only helpers: Metrics, DirectBuild (not exposed by the public production-key gateway)
  • templates: CreateTemplate, ListTemplates, GetTemplateByAlias, ResolveTemplateRef, GetTemplate, UpdateTemplate, DeleteTemplate
  • builds: CreateBuild, GetBuildFile, RollbackTemplate, ListBuilds, GetBuild, GetBuildStatus, GetBuildLogs

The public template contract is split into three layers: top-level create fields (Name, Tags, CPUCount, MemoryMB), flat SeaInfra template extensions (BaseTemplateID, Visibility, Envs, VolumeMounts, Workdir), and build-only fields on CreateBuild (FromImage, FromTemplate, Steps, StartCmd, ReadyCmd, and registry credentials). COPY content hashes belong to each COPY step as BuildStep.FilesHash; the public Builder does not accept a top-level filesHash. Public create calls reject legacy top-level write fields such as Alias and TeamID. Public update only changes the Public visibility flag.

For Go callers, TemplateCreateRequest uses PublicTemplateExtensions and TemplateUpdateRequest only changes Public. Public read responses follow the Builder's E2B-facing list/detail shapes; Admin template metadata is not available through this route.

CreateTemplate rejects Extensions.Visibility == "official" on public routes.

CreateBuild follows the wire contract directly and returns the raw 202 {} trigger response without adding helper fields. Local files are packed and uploaded by Template.Copy/BuildTemplate, which places the resulting hash on the COPY step.

GetTemplateByAlias is a pure alias lookup endpoint. It should only be used with an actual published alias value.

ResolveTemplateRef is the SeaInfra stable-ref lookup endpoint. It resolves a template by templateID, official template type, or visible alias.

Runtime Helper

Low-level runtime objects returned by createdSandbox.Runtime() or client.RuntimeFromSandbox(...) expose:

  • system: Metrics, Envs, Configure, Ports
  • proxy and file transfer: Proxy, Download, FilesContent, UploadBytes, UploadJSON, UploadMultipart, WriteBatch, ComposeFiles, ReadFile, WriteFile
  • filesystem RPC: ListDir, Stat, MakeDir, Remove, Move, Edit
  • watchers: WatchDir, CreateWatcher, GetWatcherEvents, RemoveWatcher
  • process RPC: Start, Connect, ListProcesses, SendInput, SendSignal, CloseStdin, Update, StreamInput, GetResult, Run

cmd.RequestOptions supports:

  • Username: basic-auth username for envd operations that need it
  • Signature and SignatureExpiration: signed file access parameters
  • Range: partial download support
  • Headers: custom header injection

Streaming APIs return ProcessStream, FilesystemWatchStream, and ConnectFrame.

Resource Safety

  • The quick starts are written for disposable resources and should be adapted before copy-pasting into production jobs.
  • Prefer explicit cleanup with defer createdSandbox.Delete(...) and defer client.Build.DeleteTemplate(...) when running probes, smoke tests, or CI.
  • For long-lived workloads, move cleanup and timeout policy into your own lifecycle manager instead of relying on sample code defaults.

Package Layout

  • github.com/SeaArt-Infra/sandbox-go: root client and recommended entrypoint
  • github.com/SeaArt-Infra/sandbox-go/control: control-plane models and low-level APIs
  • github.com/SeaArt-Infra/sandbox-go/build: build-plane models and low-level APIs
  • github.com/SeaArt-Infra/sandbox-go/cmd: runtime models and low-level APIs
  • github.com/SeaArt-Infra/sandbox-go/core: shared transport and error primitives

Notes

  • The gateway entrypoint always needs baseURL + apiKey to initialize.
  • core.WithProjectID(...) is retained for direct/private Hermes deployments. The public Agent Gateway ignores caller-supplied project identity and derives the canonical project from the authenticated production-line key.
  • Runtime access should be derived from sandbox response objects with Runtime() or RuntimeFromSandbox(...).
  • CreateSandbox and GetSandbox responses include EnvdURL and EnvdAccessToken when the target sandbox supports CMD access.
  • Runtime file/process APIs require a template image that starts nano-executor and returns runtime access fields; if runtime APIs return 404, verify the selected template supports CMD runtime routes.
  • High-level Create converts waitReady=true into a short create followed by cancellable client polling, so the sandbox ID is available even when readiness times out. Configure WaitTimeout and PollInterval when needed.
  • CreateOptions.AutoPause maps to the public autoPause lifecycle flag. The default is disposable (lifecycle.onTimeout=kill); set it to true only when a stopped sandbox should retain held capacity.
  • API errors expose Kind and Retryable() for retry logic and alert routing.
  • High-level Kill() helpers send SIGNAL_SIGKILL and return false when the runtime reports a missing process through either 404 or ESRCH.
  • PTY handles normalize reconnect output into PTY even when the runtime emits the bytes through Stdout / Stderr.
  • Sandbox timeout values are validated to 0..86400; refresh duration to 0..3600.
  • Build request validation accepts E2B-style COPY / ENV / RUN / WORKDIR / USER steps, force, and structured fromImageRegistry credentials (registry / aws / gcp).
  • Some gateways do not expose /admin/* or /build; integration tests skip those cases on 404.
  • Some filesystem layouts reject watcher APIs entirely; the integration suite skips watcher coverage when the runtime reports that limitation.

Security

  • Do not commit SEAINFRA_API_KEY, envdAccessToken, or sandbox access tokens.
  • Treat runtime tokens as sandbox-scoped secrets. Prefer createdSandbox.Runtime() or client.RuntimeFromSandbox(...) so response-scoped runtime access is not copied into configuration.
  • Do not log raw API keys or runtime tokens. SDK errors may include response bodies, so avoid logging full error payloads in shared systems.
  • Do not rely on core.WithProjectID(...) for public tenant selection. Agent Gateway overwrites it with the project derived from the authenticated production-line key.

Integration Tests

SANDBOX_RUN_INTEGRATION=1 \
SANDBOX_TEST_BASE_URL="${SEAINFRA_BASE_URL}" \
SANDBOX_TEST_API_KEY="${SEAINFRA_API_KEY}" \
SANDBOX_TEST_TEMPLATE_ID=... \
go test ./tests/... -count=1 -v

Use a runtime-enabled template for CMD integration coverage. For SeaInfra production smoke tests, tpl-base-dc11799b9f9f4f9e is a known-good runtime template. The same smoke suite is available as a manual GitHub Actions dispatch in .github/workflows/integration-smoke.yml.

Release

  • See CHANGELOG.md for release notes.
  • See RELEASE_CHECKLIST.md before tagging or publishing a new version.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func TemplateToDockerfile

func TemplateToDockerfile(template *Template) (string, error)

TemplateToDockerfile converts the currently supported template subset into a Dockerfile string.

func TemplateToJSON

func TemplateToJSON(template *Template, computeHashes bool) (string, error)

TemplateToJSON serializes the currently supported template subset into build-request JSON.

Types

type Client

type Client struct {
	*control.Service
	Build *build.Service
}

func NewClient

func NewClient(baseURL, apiKey string, opts ...core.TransportOption) (*Client, error)

func (*Client) BuildTemplate

func (c *Client) BuildTemplate(ctx context.Context, template *Template, name string, opts *TemplateBuildOptions) (*TemplateBuildInfo, error)

func (*Client) BuildTemplateInBackground

func (c *Client) BuildTemplateInBackground(ctx context.Context, template *Template, name string, opts *TemplateBuildOptions) (*TemplateBuildInfo, error)

func (*Client) Connect

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

func (*Client) ConnectSandbox

func (c *Client) ConnectSandbox(
	ctx context.Context,
	sandboxID string,
	req *control.ConnectSandboxRequest,
) (*ConnectSandboxResponse, error)

func (*Client) Create

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

func (*Client) CreateSandbox

func (c *Client) CreateSandbox(ctx context.Context, req *control.NewSandboxRequest) (*Sandbox, error)

func (*Client) DeleteTemplate

func (c *Client) DeleteTemplate(ctx context.Context, ref string) error

func (*Client) Get

func (c *Client) Get(ctx context.Context, sandboxID string) (*SandboxDetail, error)

func (*Client) GetSandbox

func (c *Client) GetSandbox(ctx context.Context, sandboxID string) (*SandboxDetail, error)

func (*Client) GetTemplate

func (c *Client) GetTemplate(ctx context.Context, ref string, opts *TemplateGetOptions) (*build.TemplateResponse, error)

func (*Client) GetTemplateBuildStatus

func (c *Client) GetTemplateBuildStatus(ctx context.Context, templateID, buildID string, opts *TemplateBuildStatusOptions) (*build.BuildStatusResponse, error)

func (*Client) List

func (c *Client) List(ctx context.Context, opts *ListOptions) ([]*SandboxHandle, error)

func (*Client) ListSandboxes

func (c *Client) ListSandboxes(
	ctx context.Context,
	params *control.ListSandboxesParams,
) ([]*SandboxHandle, error)

func (*Client) ListTemplates

func (c *Client) ListTemplates(ctx context.Context, opts *TemplateListOptions) ([]build.ListedTemplate, error)

func (*Client) NewCMD

func (c *Client) NewCMD(baseURL, accessToken string) (*cmd.Service, error)

func (*Client) Runtime

func (c *Client) Runtime(baseURL, accessToken string) (*Runtime, error)

func (*Client) RuntimeFromDetail

func (c *Client) RuntimeFromDetail(sandbox *control.SandboxDetail) (*Runtime, error)

func (*Client) RuntimeFromSandbox

func (c *Client) RuntimeFromSandbox(sandbox *control.Sandbox) (*Runtime, error)

func (*Client) TemplateAliasExists

func (c *Client) TemplateAliasExists(ctx context.Context, alias string) (bool, error)

func (*Client) TemplateExists

func (c *Client) TemplateExists(ctx context.Context, ref string) (bool, error)

type CommandHandle

type CommandHandle struct {
	PID   int
	CmdID string
	PTY   bool
	// contains filtered or unexported fields
}

func (*CommandHandle) Close

func (h *CommandHandle) Close() error

func (*CommandHandle) CloseStdin

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

func (*CommandHandle) Kill

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

func (*CommandHandle) SendStdin

func (h *CommandHandle) SendStdin(ctx context.Context, data string) error

func (*CommandHandle) Wait

type CommandResult

type CommandResult struct {
	Stdout     string
	Stderr     string
	ExitCode   int
	DurationMS int64
	Error      string
}

type CommandRunOptions

type CommandRunOptions struct {
	Args    []string
	Envs    map[string]string
	CWD     string
	Timeout *int
	Stdin   *string
}

type CommandWaitResult

type CommandWaitResult struct {
	Stdout   string
	Stderr   string
	PTY      string
	ExitCode int
}

type CommandsModule

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

func (*CommandsModule) Connect

func (m *CommandsModule) Connect(ctx context.Context, pid int) (*CommandHandle, error)

func (*CommandsModule) Exec

func (m *CommandsModule) Exec(ctx context.Context, command string, opts *CommandRunOptions) (*CommandResult, error)

func (*CommandsModule) Kill

func (m *CommandsModule) Kill(ctx context.Context, pid int) (bool, error)

func (*CommandsModule) List

func (m *CommandsModule) List(ctx context.Context) ([]cmd.ProcessInfo, error)

func (*CommandsModule) Run

func (m *CommandsModule) Run(ctx context.Context, command string, opts *CommandRunOptions) (*CommandResult, error)

func (*CommandsModule) SendStdin

func (m *CommandsModule) SendStdin(ctx context.Context, pid int, data string) error

func (*CommandsModule) Start

func (m *CommandsModule) Start(ctx context.Context, command string, opts *CommandRunOptions) (*CommandHandle, error)

type ConnectOptions

type ConnectOptions struct {
	GatewayConfig
	Timeout int32
}

type ConnectSandboxResponse

type ConnectSandboxResponse struct {
	StatusCode int
	Sandbox    *Sandbox
}

type CreateOptions

type CreateOptions struct {
	GatewayConfig
	TemplateID   string
	WorkspaceID  string
	Timeout      *int32
	Metadata     map[string]string
	EnvVars      map[string]string
	VolumeMounts []control.VolumeMount
	WaitReady    *bool
	AutoPause    *bool
	WaitTimeout  time.Duration
	PollInterval time.Duration
}

type FilesystemModule

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

func (*FilesystemModule) Exists

func (m *FilesystemModule) Exists(ctx context.Context, path string) (bool, error)

func (*FilesystemModule) GetInfo

func (m *FilesystemModule) GetInfo(ctx context.Context, path string) (*cmd.EntryInfo, error)

func (*FilesystemModule) List

func (m *FilesystemModule) List(ctx context.Context, path string, depth *int) ([]cmd.EntryInfo, error)

func (*FilesystemModule) MakeDir

func (m *FilesystemModule) MakeDir(ctx context.Context, path string) (bool, error)

func (*FilesystemModule) Read

func (m *FilesystemModule) Read(ctx context.Context, path string) (string, error)

func (*FilesystemModule) Remove

func (m *FilesystemModule) Remove(ctx context.Context, path string) error

func (*FilesystemModule) Rename

func (m *FilesystemModule) Rename(ctx context.Context, oldPath, newPath string) (*cmd.EntryInfo, error)

func (*FilesystemModule) WatchDir

func (m *FilesystemModule) WatchDir(ctx context.Context, path string, recursive *bool) (*cmd.FilesystemWatchStream, error)

func (*FilesystemModule) Write

func (m *FilesystemModule) Write(ctx context.Context, path string, data []byte) (*WriteInfo, error)

func (*FilesystemModule) WriteFiles

func (m *FilesystemModule) WriteFiles(ctx context.Context, files []cmd.WriteFileEntry) ([]WriteInfo, error)

type GatewayConfig

type GatewayConfig struct {
	BaseURL   string
	APIKey    string
	ProjectID string
	Timeout   time.Duration
}

type GitCloneOptions

type GitCloneOptions struct {
	GitCommandOptions
	Branch string
	Depth  int
}

type GitCommandOptions

type GitCommandOptions struct {
	Envs    map[string]string
	CWD     string
	Timeout *int
	User    string
}

type GitModule

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

func (*GitModule) Checkout

func (m *GitModule) Checkout(ctx context.Context, ref, path string, opts *GitCommandOptions) (*CommandResult, error)

func (*GitModule) Clone

func (m *GitModule) Clone(ctx context.Context, repoURL, path string, opts *GitCloneOptions) (*CommandResult, error)

func (*GitModule) Pull

func (m *GitModule) Pull(ctx context.Context, path string, opts *GitCommandOptions) (*CommandResult, error)

func (*GitModule) Status

func (m *GitModule) Status(ctx context.Context, path string, opts *GitCommandOptions) (*CommandResult, error)

type ListOptions

type ListOptions struct {
	GatewayConfig
	Metadata  map[string]string
	State     []string
	Limit     int
	NextToken string
}

type LogEntry

type LogEntry struct {
	Timestamp time.Time
	Level     string
	Message   string
}

func (LogEntry) String

func (l LogEntry) String() string

type PtyCreateOptions

type PtyCreateOptions struct {
	Args    []string
	Envs    map[string]string
	CWD     string
	Timeout *int
	Size    *cmd.PtySize
}

type PtyModule

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

func (*PtyModule) Connect

func (m *PtyModule) Connect(ctx context.Context, pid int) (*CommandHandle, error)

func (*PtyModule) Create

func (m *PtyModule) Create(ctx context.Context, command string, opts *PtyCreateOptions) (*CommandHandle, error)

func (*PtyModule) Kill

func (m *PtyModule) Kill(ctx context.Context, pid int) (bool, error)

func (*PtyModule) Resize

func (m *PtyModule) Resize(ctx context.Context, pid int, size cmd.PtySize) error

func (*PtyModule) SendStdin

func (m *PtyModule) SendStdin(ctx context.Context, pid int, data string) error

type ReadyCmd

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

func WaitForCommand

func WaitForCommand(command string) ReadyCmd

WaitForCommand uses a caller-provided command as the template readiness probe.

func WaitForFile

func WaitForFile(filename string) ReadyCmd

func WaitForPort

func WaitForPort(port int) ReadyCmd

func WaitForProcess

func WaitForProcess(processName string) ReadyCmd

func WaitForTimeout

func WaitForTimeout(timeout time.Duration) ReadyCmd

func WaitForURL

func WaitForURL(rawURL string, statusCode int) ReadyCmd

func (ReadyCmd) Command

func (r ReadyCmd) Command() string

type ResourceOperationError

type ResourceOperationError struct {
	Operation        string
	ResourceType     string
	ResourceID       string
	RelatedID        string
	CleanupAttempted bool
	CleanupErr       error
	Err              error
}

ResourceOperationError preserves resource identity after a partially successful operation.

func (*ResourceOperationError) Error

func (e *ResourceOperationError) Error() string

func (*ResourceOperationError) Unwrap

func (e *ResourceOperationError) Unwrap() error

type Runtime

type Runtime struct {
	*cmd.Service
}

type Sandbox

type Sandbox struct {
	*control.Sandbox
	// contains filtered or unexported fields
}

func (*Sandbox) Commands

func (s *Sandbox) Commands() (*CommandsModule, error)

func (*Sandbox) Connect

func (*Sandbox) Delete

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

func (*Sandbox) Files

func (s *Sandbox) Files() (*FilesystemModule, error)

func (*Sandbox) GetHost

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

func (*Sandbox) GetInfo

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

GetInfo fetches the latest sandbox detail for this sandbox ID.

func (*Sandbox) GetMetrics

func (s *Sandbox) GetMetrics(ctx context.Context) (*cmd.MetricsResponse, error)

GetMetrics reads runtime metrics for sandboxes that expose nano-executor access.

func (*Sandbox) Git

func (s *Sandbox) Git() (*GitModule, error)

func (*Sandbox) IsRunning

func (s *Sandbox) IsRunning() bool

IsRunning reports whether the sandbox is in an active state.

func (*Sandbox) Kill

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

Kill deletes the sandbox.

func (*Sandbox) Logs

func (*Sandbox) Pause

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

func (*Sandbox) Proxy

func (s *Sandbox) Proxy(ctx context.Context, req *cmd.ProxyRequest) (*http.Response, error)

func (*Sandbox) Pty

func (s *Sandbox) Pty() (*PtyModule, error)

func (*Sandbox) Refresh

func (s *Sandbox) Refresh(ctx context.Context, req *control.RefreshSandboxRequest) error

func (*Sandbox) Reload

func (s *Sandbox) Reload(ctx context.Context) (*SandboxDetail, error)

func (*Sandbox) Resume

func (s *Sandbox) Resume(ctx context.Context, timeout int32) (*Sandbox, error)

Resume reconnects to a paused sandbox and returns the running sandbox handle.

func (*Sandbox) Runtime

func (s *Sandbox) Runtime() (*Runtime, error)

func (*Sandbox) SetTimeout

func (s *Sandbox) SetTimeout(ctx context.Context, req *control.TimeoutRequest) error

type SandboxDetail

type SandboxDetail struct {
	*control.SandboxDetail
	// contains filtered or unexported fields
}

func (*SandboxDetail) Commands

func (s *SandboxDetail) Commands() (*CommandsModule, error)

func (*SandboxDetail) Connect

func (*SandboxDetail) Delete

func (s *SandboxDetail) Delete(ctx context.Context) error

func (*SandboxDetail) Files

func (s *SandboxDetail) Files() (*FilesystemModule, error)

func (*SandboxDetail) GetHost

func (s *SandboxDetail) GetHost(port int) (string, error)

func (*SandboxDetail) GetInfo

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

GetInfo refreshes the sandbox detail for this sandbox ID.

func (*SandboxDetail) GetMetrics

func (s *SandboxDetail) GetMetrics(ctx context.Context) (*cmd.MetricsResponse, error)

GetMetrics reads runtime metrics for sandboxes that expose nano-executor access.

func (*SandboxDetail) Git

func (s *SandboxDetail) Git() (*GitModule, error)

func (*SandboxDetail) IsRunning

func (s *SandboxDetail) IsRunning() bool

IsRunning reports whether the sandbox is in an active state.

func (*SandboxDetail) Kill

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

Kill deletes the sandbox.

func (*SandboxDetail) Logs

func (*SandboxDetail) Pause

func (s *SandboxDetail) Pause(ctx context.Context) error

func (*SandboxDetail) Proxy

func (s *SandboxDetail) Proxy(ctx context.Context, req *cmd.ProxyRequest) (*http.Response, error)

func (*SandboxDetail) Pty

func (s *SandboxDetail) Pty() (*PtyModule, error)

func (*SandboxDetail) Refresh

func (*SandboxDetail) Reload

func (s *SandboxDetail) Reload(ctx context.Context) (*SandboxDetail, error)

func (*SandboxDetail) Resume

func (s *SandboxDetail) Resume(ctx context.Context, timeout int32) (*Sandbox, error)

Resume reconnects to a paused sandbox detail and returns a running sandbox handle.

func (*SandboxDetail) Runtime

func (s *SandboxDetail) Runtime() (*Runtime, error)

func (*SandboxDetail) SetTimeout

func (s *SandboxDetail) SetTimeout(ctx context.Context, req *control.TimeoutRequest) error

type SandboxHandle

type SandboxHandle struct {
	*control.ListedSandbox
	// contains filtered or unexported fields
}

func (*SandboxHandle) Connect

func (*SandboxHandle) Delete

func (s *SandboxHandle) Delete(ctx context.Context) error

func (*SandboxHandle) GetInfo

func (s *SandboxHandle) GetInfo(ctx context.Context) (*SandboxDetail, error)

GetInfo fetches the latest sandbox detail for this sandbox ID.

func (*SandboxHandle) IsRunning

func (s *SandboxHandle) IsRunning() bool

IsRunning reports whether the sandbox is in an active state.

func (*SandboxHandle) Kill

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

Kill deletes the sandbox.

func (*SandboxHandle) Logs

func (*SandboxHandle) Pause

func (s *SandboxHandle) Pause(ctx context.Context) error

func (*SandboxHandle) Refresh

func (*SandboxHandle) Reload

func (s *SandboxHandle) Reload(ctx context.Context) (*SandboxDetail, error)

func (*SandboxHandle) Resume

func (s *SandboxHandle) Resume(ctx context.Context, timeout int32) (*Sandbox, error)

Resume reconnects to a paused sandbox handle and returns a running sandbox handle.

func (*SandboxHandle) SetTimeout

func (s *SandboxHandle) SetTimeout(ctx context.Context, req *control.TimeoutRequest) error

type Template

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

func NewTemplate

func NewTemplate() *Template

NewTemplate creates a high-level template builder with E2B-style helpers.

func (*Template) AptInstall

func (t *Template) AptInstall(packages []string, opts *TemplateAptInstallOptions) *Template

func (*Template) BunInstall

func (t *Template) BunInstall(packages []string, opts *TemplateBunInstallOptions) *Template

func (*Template) Copy

func (t *Template) Copy(src, dest string, opts *TemplateCopyOptions) *Template

Copy adds one local source to the template build context.

func (*Template) CopyItems

func (t *Template) CopyItems(items []TemplateCopyItem) *Template

CopyItems adds multiple local sources with per-item copy options.

func (*Template) FromAWSRegistry

func (t *Template) FromAWSRegistry(image, accessKeyID, secretAccessKey, region string) *Template

func (*Template) FromBaseImage

func (t *Template) FromBaseImage() *Template

func (*Template) FromBunImage

func (t *Template) FromBunImage(variant string) *Template

func (*Template) FromDebianImage

func (t *Template) FromDebianImage(variant string) *Template

func (*Template) FromDockerfile

func (t *Template) FromDockerfile(dockerfileContentOrPath string) (*Template, error)

FromDockerfile parses a supported Dockerfile subset into template build steps.

func (*Template) FromGCPRegistry

func (t *Template) FromGCPRegistry(image string, serviceAccountJSON any) *Template

func (*Template) FromImage

func (t *Template) FromImage(image string, registryConfig ...map[string]any) *Template

func (*Template) FromNodeImage

func (t *Template) FromNodeImage(variant string) *Template

func (*Template) FromPythonImage

func (t *Template) FromPythonImage(version string) *Template

func (*Template) FromTemplate

func (t *Template) FromTemplate(templateID string) *Template

func (*Template) FromUbuntuImage

func (t *Template) FromUbuntuImage(variant string) *Template

func (*Template) GitClone

func (t *Template) GitClone(repoURL, path string, opts *TemplateGitCloneOptions) *Template

func (*Template) MakeDir

func (t *Template) MakeDir(paths []string, opts *TemplateMakeDirOptions) *Template
func (t *Template) MakeSymlink(src, dest string, opts *TemplateMakeSymlinkOptions) *Template

func (*Template) NpmInstall

func (t *Template) NpmInstall(packages []string, opts *TemplateNpmInstallOptions) *Template

func (*Template) PipInstall

func (t *Template) PipInstall(packages []string, opts *TemplatePipInstallOptions) *Template

func (*Template) Remove

func (t *Template) Remove(paths []string, opts *TemplateRemoveOptions) *Template

func (*Template) Rename

func (t *Template) Rename(src, dest string, opts *TemplateRenameOptions) *Template

func (*Template) Request

func (t *Template) Request() *build.BuildRequest

func (*Template) RunCmd

func (t *Template) RunCmd(command string, opts *TemplateCommandOptions) *Template

RunCmd adds one RUN step and optionally wraps it to execute as a specific user.

func (*Template) RunCmds

func (t *Template) RunCmds(commands []string, opts *TemplateCommandOptions) *Template

RunCmds adds multiple RUN steps using the same options.

func (*Template) SetEnvs

func (t *Template) SetEnvs(envs map[string]string) *Template

func (*Template) SetReadyCmd

func (t *Template) SetReadyCmd(readyCommand ReadyCmd) *Template

func (*Template) SetStartCmd

func (t *Template) SetStartCmd(startCommand string, readyCommand ReadyCmd) *Template

SetStartCmd records the start command and ready command for the built template.

func (*Template) SetUser

func (t *Template) SetUser(user string) *Template

func (*Template) SetWorkdir

func (t *Template) SetWorkdir(path string) *Template

func (*Template) SkipCache

func (t *Template) SkipCache() *Template

SkipCache forces subsequent helper-generated steps to bypass build cache.

type TemplateAptInstallOptions

type TemplateAptInstallOptions struct {
	NoInstallRecommends bool
	Force               *bool
}

type TemplateBuildInfo

type TemplateBuildInfo struct {
	TemplateID string
	BuildID    string
	Name       string
	Tags       []string
	Status     string
	Template   *build.TemplateResponse
	Build      *build.BuildResponse
}

type TemplateBuildOptions

type TemplateBuildOptions struct {
	GatewayConfig
	Tags           []string
	BaseTemplateID string
	Visibility     string
	Envs           map[string]string
	VolumeMounts   []build.TemplateVolumeMount
	Workdir        string
	CPUCount       *int32
	MemoryMB       *int32
	Wait           *bool
	WaitTimeout    time.Duration
	PollInterval   time.Duration
	OnBuildLog     func(LogEntry)
}

type TemplateBuildStatusOptions

type TemplateBuildStatusOptions struct {
	GatewayConfig
	LogsOffset *int
	Limit      *int
	Level      string
}

type TemplateBunInstallOptions

type TemplateBunInstallOptions struct {
	Dev   bool
	G     bool
	Force *bool
}

type TemplateCommandOptions

type TemplateCommandOptions struct {
	User  string
	Force *bool
}

TemplateCommandOptions configures template RUN helper commands.

type TemplateCopyItem

type TemplateCopyItem struct {
	Src             string
	Srcs            []string
	Dest            string
	FilesHash       string
	ForceUpload     bool
	Mode            *int
	ResolveSymlinks bool
}

TemplateCopyItem describes one COPY helper entry with per-item options.

type TemplateCopyOptions

type TemplateCopyOptions struct {
	FilesHash       string
	ForceUpload     bool
	Mode            *int
	ResolveSymlinks bool
}

TemplateCopyOptions configures local sources copied into a template build.

type TemplateGetOptions

type TemplateGetOptions struct {
	GatewayConfig
	Limit     int
	NextToken string
}

type TemplateGitCloneOptions

type TemplateGitCloneOptions struct {
	Branch string
	Depth  int
	User   string
	Force  *bool
}

type TemplateListOptions

type TemplateListOptions struct {
	GatewayConfig
	Visibility string
	TeamID     string
	Limit      int
	Offset     int
}

type TemplateMakeDirOptions

type TemplateMakeDirOptions struct {
	TemplatePathOptions
	Mode *int
}

type TemplateMakeSymlinkOptions

type TemplateMakeSymlinkOptions struct {
	TemplatePathOptions
}

type TemplateNpmInstallOptions

type TemplateNpmInstallOptions struct {
	Dev   bool
	G     bool
	Force *bool
}

type TemplatePathOptions

type TemplatePathOptions struct {
	User  string
	Force *bool
}

type TemplatePipInstallOptions

type TemplatePipInstallOptions struct {
	G     *bool
	Force *bool
}

type TemplateRemoveOptions

type TemplateRemoveOptions struct {
	TemplatePathOptions
	Recursive bool
}

type TemplateRenameOptions

type TemplateRenameOptions struct {
	TemplatePathOptions
}

type WriteInfo

type WriteInfo struct {
	Path         string
	BytesWritten int64
}

Directories

Path Synopsis
examples
build_template command
cmd_smoke command
control_sandbox command
full_workflow command

Jump to

Keyboard shortcuts

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