Перейти к содержимому

Основной SDK

Сигнатуры и описания сгенерированы из GoDoc опубликованного модуля и оставлены на английском.

go
import "github.com/abox-dev/sdk/packages/go-sdk"

Package agentbox provides the official Go client for AgentBox sandboxes.

Create a client, start a sandbox, and run a command:

go
client, err := agentbox.NewClient()
if err != nil {
	log.Fatal(err)
}
sandbox, err := client.Sandboxes.Create(ctx, nil)
if err != nil {
	log.Fatal(err)
}
defer sandbox.Kill(context.Background())
result, err := sandbox.Commands.Run(ctx, "echo", &agentbox.CommandOptions{
	Args: []string{"Hello from AgentBox"},
})

Index

Constants

Version is the AgentBox SDK release version.

go
const Version = "0.1.4"

func IAMTokenPlaceholder

go
func IAMTokenPlaceholder(name string) (string, error)

IAMTokenPlaceholder returns the value the egress proxy replaces with a freshly minted workload token.

func IAMTokenPlaceholders

go
func IAMTokenPlaceholders(names ...string) (map[string]string, error)

IAMTokenPlaceholders returns placeholders for the supplied registered names.

func ValidateIAMTokenName

go
func ValidateIAMTokenName(name string) error

ValidateIAMTokenName verifies that name can be embedded in the workload-token placeholder grammar understood by the AgentBox egress proxy.

func WaitForFile

go
func WaitForFile(path string) string

WaitForFile returns a readiness command that waits for a filesystem path.

func WaitForPort

go
func WaitForPort(port int) string

WaitForPort returns a readiness command that waits for a listening port.

func WaitForProcess

go
func WaitForProcess(process string) string

WaitForProcess returns a readiness command that waits for a named process.

func WaitForTimeout

go
func WaitForTimeout(timeout time.Duration) string

WaitForTimeout waits a fixed duration before marking a service ready.

func WaitForURL

go
func WaitForURL(value string, status int) string

WaitForURL returns a readiness command that waits for an HTTP status.

type APIError

APIError describes a non-successful HTTP or Connect response.

go
type APIError struct {
    StatusCode int
    Code       string
    Message    string
    Cause      error
}

func (*APIError) Error

go
func (e *APIError) Error() string

Error formats the AgentBox API failure.

func (*APIError) Unwrap

go
func (e *APIError) Unwrap() error

Unwrap returns the underlying request error, if any.

type AptInstallOptions

AptInstallOptions configures apt-get.

go
type AptInstallOptions struct{ NoInstallRecommends, FixMissing bool }

type AuthenticationError

AuthenticationError reports missing or invalid credentials.

go
type AuthenticationError struct{ APIError }

func (*AuthenticationError) Error

go
func (e *AuthenticationError) Error() string

Error formats the authentication failure.

func (*AuthenticationError) Unwrap

go
func (e *AuthenticationError) Unwrap() error

Unwrap returns the underlying authentication error, if any.

type BuildError

BuildError reports a failed template build.

go
type BuildError struct{ APIError }

func (*BuildError) Error

go
func (e *BuildError) Error() string

Error formats the template build failure.

func (*BuildError) Unwrap

go
func (e *BuildError) Unwrap() error

Unwrap returns the underlying template build error, if any.

type BuildLogEntry

BuildLogEntry is one structured template build log record.

go
type BuildLogEntry struct {
    ID        *string   `json:"id,omitzero"`
    Level     string    `json:"level"`
    Message   string    `json:"message"`
    Step      *string   `json:"step,omitzero"`
    Timestamp time.Time `json:"timestamp"`
}

type BuildStatusReason

BuildStatusReason explains a terminal template build status.

go
type BuildStatusReason struct {
    LogEntries *[]BuildLogEntry `json:"logEntries,omitzero"`
    Message    string           `json:"message"`
    Step       *string          `json:"step,omitzero"`
}

type Client

Client is an AgentBox control-plane client.

go
type Client struct {
    Sandboxes *SandboxService
    Templates *TemplateService
    // contains filtered or unexported fields
}
Example
go
client, err := agentbox.NewClient()
if err != nil {
	log.Fatal(err)
}
sandbox, err := client.Sandboxes.Create(context.Background(), nil)
if err != nil {
	log.Fatal(err)
}
defer sandbox.Kill(context.Background())
_, _ = sandbox.Commands.Run(context.Background(), "echo", &agentbox.CommandOptions{Args: []string{"hello"}})

func NewClient

go
func NewClient(options ...ClientOption) (*Client, error)

NewClient creates a client. Configuration defaults to AGENTBOX_* environment variables and can be overridden with options.

type ClientOption

ClientOption configures a Client.

go
type ClientOption func(*clientConfig) error

func WithAPIKey

go
func WithAPIKey(apiKey string) ClientOption

WithAPIKey sets the AgentBox API key. By default AGENTBOX_API_KEY is used.

func WithAPIURL

go
func WithAPIURL(value string) ClientOption

WithAPIURL overrides the control-plane API URL.

func WithDebug

go
func WithDebug(enabled bool) ClientOption

WithDebug enables local envd routing.

func WithDomain

go
func WithDomain(domain string) ClientOption

WithDomain sets the AgentBox runtime domain.

func WithHTTPClient

go
func WithHTTPClient(client *http.Client) ClientOption

WithHTTPClient supplies the HTTP client used for every request. Its Timeout applies to complete streaming requests as well as unary requests; leave it at zero and use contexts or operation options for long-lived streams.

func WithHeaders

go
func WithHeaders(headers http.Header) ClientOption

WithHeaders adds headers to control-plane requests.

func WithLogger

go
func WithLogger(logger *slog.Logger) ClientOption

WithLogger enables structured request and lifecycle logging.

func WithProxy

go
func WithProxy(value string) ClientOption

WithProxy sets an HTTP or HTTPS proxy for SDK requests.

func WithRequestTimeout

go
func WithRequestTimeout(timeout time.Duration) ClientOption

WithRequestTimeout sets the default unary request timeout. Zero disables it.

func WithSandboxURL

go
func WithSandboxURL(value string) ClientOption

WithSandboxURL overrides the sandbox proxy URL.

type CommandExitError

CommandExitError reports a process that completed with a non-zero exit code.

go
type CommandExitError struct {
    Result  CommandResult
    Message string
}

func (*CommandExitError) Error

go
func (e *CommandExitError) Error() string

Error describes the non-zero command exit code.

type CommandHandle

CommandHandle represents a streaming process. Wait can be called without draining the output channels and always returns the complete collected output.

go
type CommandHandle struct {
    Stdout <-chan []byte
    Stderr <-chan []byte
    PTY    <-chan []byte
    Done   <-chan struct{}
    // contains filtered or unexported fields
}

func (*CommandHandle) CloseStdin

go
func (handle *CommandHandle) CloseStdin(ctx context.Context) error

CloseStdin signals EOF to a non-PTY process.

func (*CommandHandle) Kill

go
func (handle *CommandHandle) Kill(ctx context.Context) error

Kill sends SIGKILL to this process.

func (*CommandHandle) PID

go
func (handle *CommandHandle) PID(ctx context.Context) (uint32, error)

PID waits for and returns the process identifier.

func (*CommandHandle) Wait

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

Wait waits for completion and returns collected output.

func (*CommandHandle) Write

go
func (handle *CommandHandle) Write(ctx context.Context, data []byte) (int, error)

Write writes bytes to process stdin.

type CommandOptions

CommandOptions configures a command process.

go
type CommandOptions struct {
    Args     []string
    Env      map[string]string
    Cwd      string
    Tag      string
    Stdin    bool
    OnStdout func([]byte)
    OnStderr func([]byte)
}

type CommandResult

CommandResult contains collected process output.

go
type CommandResult struct {
    PID      uint32
    ExitCode int
    Stdout   []byte
    Stderr   []byte
    Status   string
}

type CommandService

CommandService executes and manages sandbox processes.

go
type CommandService struct {
    // contains filtered or unexported fields
}

func (*CommandService) Connect

go
func (service *CommandService) Connect(ctx context.Context, pid uint32, tag string) (*CommandHandle, error)

Connect attaches to an existing process by PID or tag.

func (*CommandService) Kill

go
func (service *CommandService) Kill(ctx context.Context, pid uint32, tag string) error

Kill sends SIGKILL to a process.

func (*CommandService) List

go
func (service *CommandService) List(ctx context.Context) ([]ProcessInfo, error)

List returns currently running processes.

func (*CommandService) Run

go
func (service *CommandService) Run(ctx context.Context, command string, options *CommandOptions) (CommandResult, error)

Run executes a foreground command and collects its output.

func (*CommandService) Start

go
func (service *CommandService) Start(ctx context.Context, command string, options *CommandOptions) (*CommandHandle, error)

Start starts a process and streams output through the returned handle.

func (*CommandService) Terminate

go
func (service *CommandService) Terminate(ctx context.Context, pid uint32, tag string) error

Terminate sends SIGTERM to a process.

type ConnectSandboxOptions

ConnectSandboxOptions configures connecting or resuming a sandbox.

go
type ConnectSandboxOptions struct{ Timeout time.Duration }

type CopyOptions

CopyOptions configures a COPY template layer.

go
type CopyOptions struct {
    User            string
    Mode            os.FileMode
    ForceUpload     bool
    ResolveSymlinks bool
    Gzip            *bool
}

type CreateSandboxOptions

CreateSandboxOptions configures a new sandbox.

go
type CreateSandboxOptions struct {
    Template            string
    Timeout             time.Duration
    AutoPause           *bool
    AutoPauseMemory     *bool
    AutoResume          *bool
    Secure              *bool
    AllowInternetAccess *bool
    Env                 map[string]string
    Metadata            map[string]string
    Network             *SandboxNetworkConfig
    IAM                 *SandboxIAM
}

type EntryInfo

EntryInfo describes a sandbox filesystem entry.

go
type EntryInfo struct {
    Name          string
    Type          FileType
    Path          string
    Size          int64
    Mode          uint32
    Permissions   string
    Owner         string
    Group         string
    ModifiedAt    time.Time
    SymlinkTarget string
    Metadata      map[string]string
}

type FileEvent

FileEvent describes a filesystem change.

go
type FileEvent struct {
    Name  string
    Type  string
    Entry *EntryInfo
}

type FileNotFoundError

FileNotFoundError reports a missing sandbox file.

go
type FileNotFoundError struct{ APIError }

func (*FileNotFoundError) Error

go
func (e *FileNotFoundError) Error() string

Error formats the missing-file failure.

func (*FileNotFoundError) Unwrap

go
func (e *FileNotFoundError) Unwrap() error

Unwrap returns the underlying missing-file error, if any.

type FileService

FileService reads and mutates sandbox files.

go
type FileService struct {
    // contains filtered or unexported fields
}

func (*FileService) Exists

go
func (service *FileService) Exists(ctx context.Context, path string) (bool, error)

Exists reports whether path exists.

func (*FileService) List

go
func (service *FileService) List(ctx context.Context, path string, depth uint32) ([]EntryInfo, error)

List lists path recursively up to depth.

func (*FileService) MakeDir

go
func (service *FileService) MakeDir(ctx context.Context, path string) (*EntryInfo, error)

MakeDir creates a directory.

func (*FileService) Read

go
func (service *FileService) Read(ctx context.Context, path, user string) (io.ReadCloser, error)

Read opens a streaming file response. The caller must close it.

func (*FileService) ReadBytes

go
func (service *FileService) ReadBytes(ctx context.Context, path, user string) ([]byte, error)

ReadBytes reads a complete file.

func (*FileService) ReadText

go
func (service *FileService) ReadText(ctx context.Context, path, user string) (string, error)

ReadText reads a UTF-8 file as a string.

func (*FileService) ReadTo

go
func (service *FileService) ReadTo(ctx context.Context, path, user string, writer io.Writer) (int64, error)

ReadTo streams a file into writer.

func (*FileService) Remove

go
func (service *FileService) Remove(ctx context.Context, path string) error

Remove recursively removes a filesystem entry.

func (*FileService) Rename

go
func (service *FileService) Rename(ctx context.Context, source, destination string) (*EntryInfo, error)

Rename moves a filesystem entry.

func (*FileService) SignedReadURL

go
func (service *FileService) SignedReadURL(path, user string, expiration time.Time) (string, error)

SignedReadURL creates a directly usable download URL.

func (*FileService) SignedWriteURL

go
func (service *FileService) SignedWriteURL(path, user string, expiration time.Time) (string, error)

SignedWriteURL creates a directly usable upload URL.

func (*FileService) Stat

go
func (service *FileService) Stat(ctx context.Context, path string) (*EntryInfo, error)

Stat returns information about a path.

func (*FileService) Watch

go
func (service *FileService) Watch(ctx context.Context, path string, options *WatchOptions) (*WatchHandle, error)

Watch watches a directory until context cancellation or Close.

func (*FileService) Write

go
func (service *FileService) Write(ctx context.Context, path string, reader io.Reader, options *WriteFileOptions) (*EntryInfo, error)

Write uploads a file from reader.

func (*FileService) WriteBatch

go
func (service *FileService) WriteBatch(ctx context.Context, files []WriteFile, user string) ([]EntryInfo, error)

WriteBatch writes files in order and stops at the first failure.

func (*FileService) WriteBytes

go
func (service *FileService) WriteBytes(ctx context.Context, path string, data []byte, options *WriteFileOptions) (*EntryInfo, error)

WriteBytes uploads bytes.

func (*FileService) WriteText

go
func (service *FileService) WriteText(ctx context.Context, path, text string, options *WriteFileOptions) (*EntryInfo, error)

WriteText uploads a string.

type FileType

FileType identifies a filesystem entry kind.

go
type FileType string

go
const (
    // FileTypeFile identifies a regular file.
    FileTypeFile FileType = "file"
    // FileTypeDirectory identifies a directory.
    FileTypeDirectory FileType = "dir"
    // FileTypeSymlink identifies a symbolic link.
    FileTypeSymlink FileType = "symlink"
)

type FileUploadError

FileUploadError reports a failed template file upload.

go
type FileUploadError struct{ APIError }

func (*FileUploadError) Error

go
func (e *FileUploadError) Error() string

Error formats the file upload failure.

func (*FileUploadError) Unwrap

go
func (e *FileUploadError) Unwrap() error

Unwrap returns the underlying file upload error, if any.

type ForkOptions

ForkOptions configures sandbox forks.

go
type ForkOptions struct {
    Count   int
    Timeout time.Duration
}

type ForkResult

ForkResult is one ordered fork outcome. Exactly one of Sandbox or Err is set.

go
type ForkResult struct {
    Sandbox *Sandbox
    Err     error
}

type GitCloneOptions

GitCloneOptions configures a git clone layer.

go
type GitCloneOptions struct {
    Path, Branch, User string
    Depth              int
}

type InvalidArgumentError

InvalidArgumentError reports invalid SDK input.

go
type InvalidArgumentError struct {
    Message string
    Cause   error
}

func (*InvalidArgumentError) Error

go
func (e *InvalidArgumentError) Error() string

Error formats the invalid argument failure.

func (*InvalidArgumentError) Unwrap

go
func (e *InvalidArgumentError) Unwrap() error

Unwrap returns the underlying validation error, if any.

type ListSandboxOptions

ListSandboxOptions filters one sandbox list page.

go
type ListSandboxOptions struct {
    Metadata  map[string]string
    States    []SandboxState
    NextToken string
    Limit     int
}

type ListedSandbox

ListedSandbox is a compact sandbox list entry.

go
type ListedSandbox struct {
    Alias       *string          `json:"alias,omitzero"`
    CPUCount    int32            `json:"cpuCount"`
    DiskSizeMB  int32            `json:"diskSizeMB"`
    EndAt       time.Time        `json:"endAt"`
    EnvdVersion string           `json:"envdVersion"`
    MemoryMB    int32            `json:"memoryMB"`
    Metadata    *SandboxMetadata `json:"metadata,omitzero"`
    SandboxID   string           `json:"sandboxID"`
    StartedAt   time.Time        `json:"startedAt"`
    State       SandboxState     `json:"state"`
    TemplateID  string           `json:"templateID"`
}

type MetricsOptions

MetricsOptions selects a metrics interval.

go
type MetricsOptions struct{ Start, End time.Time }

type NotEnoughSpaceError

NotEnoughSpaceError reports exhausted sandbox storage.

go
type NotEnoughSpaceError struct{ APIError }

func (*NotEnoughSpaceError) Error

go
func (e *NotEnoughSpaceError) Error() string

Error formats the storage-capacity failure.

func (*NotEnoughSpaceError) Unwrap

go
func (e *NotEnoughSpaceError) Unwrap() error

Unwrap returns the underlying storage error, if any.

type PTYOptions

PTYOptions configures an interactive terminal.

go
type PTYOptions struct {
    Args  []string
    Env   map[string]string
    Cwd   string
    Tag   string
    Cols  uint32
    Rows  uint32
    OnPTY func([]byte)
}

type PTYService

PTYService manages pseudo-terminal processes.

go
type PTYService struct {
    // contains filtered or unexported fields
}

func (*PTYService) Connect

go
func (service *PTYService) Connect(ctx context.Context, pid uint32, tag string) (*CommandHandle, error)

Connect attaches to an existing PTY process.

func (*PTYService) Create

go
func (service *PTYService) Create(ctx context.Context, command string, options *PTYOptions) (*CommandHandle, error)

Create starts a process attached to a pseudo-terminal.

func (*PTYService) Input

go
func (service *PTYService) Input(ctx context.Context, handle *CommandHandle, data []byte) error

Input sends terminal input.

func (*PTYService) Kill

go
func (service *PTYService) Kill(ctx context.Context, handle *CommandHandle) error

Kill stops the terminal process.

func (*PTYService) Resize

go
func (service *PTYService) Resize(ctx context.Context, handle *CommandHandle, cols, rows uint32) error

Resize changes terminal dimensions.

type PackageInstallOptions

PackageInstallOptions configures npm/bun installs.

go
type PackageInstallOptions struct{ Global, Dev bool }

type Page

Page contains one page and an optional opaque continuation token.

go
type Page[T any] struct {
    Items     []T
    NextToken string
}

type PauseOptions

PauseOptions configures snapshot behavior while pausing.

go
type PauseOptions struct{ Memory *bool }

type ProcessInfo

ProcessInfo describes a running envd process.

go
type ProcessInfo struct {
    PID     uint32
    Tag     string
    Command string
    Args    []string
    Env     map[string]string
    Cwd     string
}

type RateLimitError

RateLimitError reports an exhausted API quota.

go
type RateLimitError struct{ APIError }

func (*RateLimitError) Error

go
func (e *RateLimitError) Error() string

Error formats the rate-limit failure.

func (*RateLimitError) Unwrap

go
func (e *RateLimitError) Unwrap() error

Unwrap returns the underlying rate-limit error, if any.

type Sandbox

Sandbox is a connected AgentBox sandbox.

go
type Sandbox struct {
    ID          string
    TemplateID  string
    Alias       string
    Domain      string
    EnvdVersion string

    Commands *CommandService
    PTY      *PTYService
    Files    *FileService
    // contains filtered or unexported fields
}

func (*Sandbox) CreateSnapshot

go
func (sandbox *Sandbox) CreateSnapshot(ctx context.Context, name string) (*SnapshotInfo, error)

CreateSnapshot stores this sandbox as a template snapshot.

func (*Sandbox) Fork

go
func (sandbox *Sandbox) Fork(ctx context.Context, options *ForkOptions) ([]ForkResult, error)

Fork creates one or more sandboxes from this sandbox's current state.

func (Sandbox) GoString

go
func (sandbox Sandbox) GoString() string

GoString returns a credential-free sandbox description for %#v formatting.

func (*Sandbox) Host

go
func (sandbox *Sandbox) Host(port int) string

Host returns the public hostname for a port exposed by the sandbox.

func (*Sandbox) Info

go
func (sandbox *Sandbox) Info(ctx context.Context) (*SandboxInfo, error)

Info returns information about this sandbox.

func (*Sandbox) IsRunning

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

IsRunning reports whether envd is reachable. A 502 response means the sandbox is no longer running.

func (*Sandbox) KeepAlive

go
func (sandbox *Sandbox) KeepAlive(ctx context.Context, duration time.Duration) error

KeepAlive extends the sandbox lifetime. A zero duration uses the server default.

func (*Sandbox) Kill

go
func (sandbox *Sandbox) Kill(ctx context.Context) (bool, error)

Kill permanently stops this sandbox. It returns false when it was not found.

func (*Sandbox) Logs

go
func (sandbox *Sandbox) Logs(ctx context.Context, options *SandboxLogOptions) (Page[SandboxLogEntry], error)

Logs returns one page of sandbox logs.

func (*Sandbox) Metrics

go
func (sandbox *Sandbox) Metrics(ctx context.Context, options *MetricsOptions) ([]SandboxMetric, error)

Metrics returns sandbox metrics for the requested interval.

func (*Sandbox) Pause

go
func (sandbox *Sandbox) Pause(ctx context.Context, options *PauseOptions) error

Pause pauses the sandbox, optionally retaining memory.

func (*Sandbox) Request

go
func (sandbox *Sandbox) Request(ctx context.Context, port int, method, path string, body io.Reader, direct bool) (*http.Response, error)

Request performs an authenticated request against a service inside the sandbox. Direct bypasses the stable proxy hostname while retaining AgentBox routing headers.

func (*Sandbox) RequestTimeout

go
func (sandbox *Sandbox) RequestTimeout() time.Duration

RequestTimeout returns the default unary request timeout configured on the client.

func (*Sandbox) RequestWithOptions

go
func (sandbox *Sandbox) RequestWithOptions(ctx context.Context, port int, method, path string, body io.Reader, options *SandboxRequestOptions) (*http.Response, error)

RequestWithOptions performs an authenticated request with custom headers.

func (*Sandbox) SetTimeout

go
func (sandbox *Sandbox) SetTimeout(ctx context.Context, timeout time.Duration) error

SetTimeout changes the sandbox expiration timeout from now.

func (Sandbox) String

go
func (sandbox Sandbox) String() string

String returns a credential-free sandbox description.

func (*Sandbox) UpdateNetwork

go
func (sandbox *Sandbox) UpdateNetwork(ctx context.Context, config SandboxNetworkConfig, allowInternetAccess *bool) error

UpdateNetwork atomically replaces sandbox egress rules.

type SandboxError

SandboxError is the base error for sandbox operations.

go
type SandboxError struct{ APIError }

func (*SandboxError) Error

go
func (e *SandboxError) Error() string

Error formats the sandbox operation failure.

func (*SandboxError) Unwrap

go
func (e *SandboxError) Unwrap() error

Unwrap returns the underlying sandbox operation error, if any.

type SandboxIAM

SandboxIAM configures workload identity tokens.

go
type SandboxIAM struct {
    Tokens *SandboxIAMTokens `json:"tokens,omitzero"`
}

type SandboxIAMToken

SandboxIAMToken configures one workload identity token.

go
type SandboxIAMToken struct {
    Audience  string `json:"audience"`
    TokenType string `json:"tokenType"`
}

type SandboxIAMTokens

SandboxIAMTokens contains named workload identity token definitions.

go
type SandboxIAMTokens map[string]SandboxIAMToken

type SandboxInfo

SandboxInfo contains current sandbox state and configuration.

go
type SandboxInfo struct {
    Alias               *string               `json:"alias,omitzero"`
    AllowInternetAccess *bool                 `json:"allowInternetAccess,omitzero"`
    CPUCount            int32                 `json:"cpuCount"`
    DiskSizeMB          int32                 `json:"diskSizeMB"`
    Domain              *string               `json:"domain,omitzero"`
    EndAt               time.Time             `json:"endAt"`
    EnvdVersion         string                `json:"envdVersion"`
    Lifecycle           *SandboxLifecycle     `json:"lifecycle,omitzero"`
    MemoryMB            int32                 `json:"memoryMB"`
    Metadata            *SandboxMetadata      `json:"metadata,omitzero"`
    Network             *SandboxNetworkConfig `json:"network,omitzero"`
    SandboxID           string                `json:"sandboxID"`
    StartedAt           time.Time             `json:"startedAt"`
    State               SandboxState          `json:"state"`
    TemplateID          string                `json:"templateID"`
}

type SandboxLifecycle

SandboxLifecycle describes timeout and auto-resume behavior.

go
type SandboxLifecycle struct {
    AutoResume bool   `json:"autoResume"`
    OnTimeout  string `json:"onTimeout"`
}

type SandboxLogEntry

SandboxLogEntry is one structured sandbox log record.

go
type SandboxLogEntry struct {
    Fields    map[string]string `json:"fields"`
    ID        *string           `json:"id,omitzero"`
    Level     string            `json:"level"`
    Message   string            `json:"message"`
    Timestamp time.Time         `json:"timestamp"`
}

type SandboxLogOptions

SandboxLogOptions filters one page of sandbox logs.

go
type SandboxLogOptions struct {
    Cursor    string
    Timestamp int64
    Limit     int
    Direction string
    Level     string
    Search    string
}

type SandboxMetadata

SandboxMetadata contains user-defined sandbox metadata.

go
type SandboxMetadata map[string]string

type SandboxMetric

SandboxMetric is one timestamped resource-usage sample.

go
type SandboxMetric struct {
    CPUCount      int32   `json:"cpuCount"`
    CPUUsedPct    float32 `json:"cpuUsedPct"`
    DiskTotal     int64   `json:"diskTotal"`
    DiskUsed      int64   `json:"diskUsed"`
    MemCache      int64   `json:"memCache"`
    MemTotal      int64   `json:"memTotal"`
    MemUsed       int64   `json:"memUsed"`
    TimestampUnix int64   `json:"timestampUnix"`
}

type SandboxNetworkConfig

SandboxNetworkConfig configures sandbox egress and public traffic.

go
type SandboxNetworkConfig struct {
    AllowOut           *[]string                        `json:"allowOut,omitzero"`
    AllowPublicTraffic *bool                            `json:"allowPublicTraffic,omitzero"`
    DenyOut            *[]string                        `json:"denyOut,omitzero"`
    MaskRequestHost    *string                          `json:"maskRequestHost,omitzero"`
    Rules              *map[string][]SandboxNetworkRule `json:"rules,omitzero"`
}

type SandboxNetworkRule

SandboxNetworkRule applies request transformations to matching traffic.

go
type SandboxNetworkRule struct {
    Transform *SandboxNetworkTransform `json:"transform,omitzero"`
}

type SandboxNetworkTransform

SandboxNetworkTransform describes headers injected into matching requests.

go
type SandboxNetworkTransform struct {
    Headers *map[string]string `json:"headers,omitzero"`
}

type SandboxNotFoundError

SandboxNotFoundError reports a missing or expired sandbox.

go
type SandboxNotFoundError struct{ APIError }

func (*SandboxNotFoundError) Error

go
func (e *SandboxNotFoundError) Error() string

Error formats the missing-sandbox failure.

func (*SandboxNotFoundError) Unwrap

go
func (e *SandboxNotFoundError) Unwrap() error

Unwrap returns the underlying missing-sandbox error, if any.

type SandboxRequestOptions

SandboxRequestOptions configures a request to a service inside a sandbox.

go
type SandboxRequestOptions struct {
    Direct      bool
    Headers     http.Header
    ContentType string
}

type SandboxService

SandboxService manages sandboxes owned by a client.

go
type SandboxService struct {
    // contains filtered or unexported fields
}

func (*SandboxService) Connect

go
func (service *SandboxService) Connect(ctx context.Context, id string, options *ConnectSandboxOptions) (*Sandbox, error)

Connect connects to or resumes a sandbox.

func (*SandboxService) Create

go
func (service *SandboxService) Create(ctx context.Context, options *CreateSandboxOptions) (*Sandbox, error)

Create starts and connects to a sandbox.

func (*SandboxService) DeleteSnapshot

go
func (service *SandboxService) DeleteSnapshot(ctx context.Context, snapshotID string) (bool, error)

DeleteSnapshot deletes a snapshot. It returns false when it did not exist.

func (*SandboxService) Info

go
func (service *SandboxService) Info(ctx context.Context, id string) (*SandboxInfo, error)

Info returns current sandbox state and configuration.

func (*SandboxService) Kill

go
func (service *SandboxService) Kill(ctx context.Context, id string) (bool, error)

Kill permanently stops a sandbox. It returns false when it did not exist.

func (*SandboxService) List

go
func (service *SandboxService) List(ctx context.Context, options *ListSandboxOptions) (Page[ListedSandbox], error)

List returns one list page. The continuation token is read from X-Next-Token.

func (*SandboxService) Logs

go
func (service *SandboxService) Logs(ctx context.Context, id string, options *SandboxLogOptions) (Page[SandboxLogEntry], error)

Logs returns one page of structured sandbox logs.

func (*SandboxService) Metrics

go
func (service *SandboxService) Metrics(ctx context.Context, sandboxIDs ...string) (map[string]SandboxMetric, error)

Metrics returns the latest metrics for the requested sandbox IDs.

func (*SandboxService) Snapshots

go
func (service *SandboxService) Snapshots(ctx context.Context, options *SnapshotListOptions) (Page[SnapshotInfo], error)

Snapshots returns one page of snapshots.

type SandboxState

SandboxState is the lifecycle state of a sandbox.

go
type SandboxState string

go
const (
    // SandboxRunning indicates that a sandbox accepts requests.
    SandboxRunning SandboxState = "running"
    // SandboxPaused indicates that a sandbox is suspended.
    SandboxPaused SandboxState = "paused"
)

type SnapshotInfo

SnapshotInfo identifies a saved sandbox snapshot.

go
type SnapshotInfo struct {
    Names      []string `json:"names"`
    SnapshotID string   `json:"snapshotID"`
}

type SnapshotListOptions

SnapshotListOptions filters and paginates snapshots.

go
type SnapshotListOptions struct {
    SandboxID string
    Name      string
    NextToken string
    Limit     int
}

type TeamUser

TeamUser identifies the user who created a template.

go
type TeamUser struct {
    ID string `json:"id"`
}

type TemplateBuild

TemplateBuild describes one historical template build.

go
type TemplateBuild struct {
    BuildID     string              `json:"buildID"`
    CPUCount    int32               `json:"cpuCount"`
    CreatedAt   time.Time           `json:"createdAt"`
    DiskSizeMB  *int32              `json:"diskSizeMB,omitzero"`
    EnvdVersion *string             `json:"envdVersion,omitzero"`
    FinishedAt  *time.Time          `json:"finishedAt,omitzero"`
    MemoryMB    int32               `json:"memoryMB"`
    Status      TemplateBuildStatus `json:"status"`
    UpdatedAt   time.Time           `json:"updatedAt"`
}

type TemplateBuildInfo

TemplateBuildInfo contains the latest status and logs for a build.

go
type TemplateBuildInfo struct {
    BuildID    string              `json:"buildID"`
    LogEntries []BuildLogEntry     `json:"logEntries"`
    Logs       []string            `json:"logs"`
    Reason     *BuildStatusReason  `json:"reason,omitzero"`
    Status     TemplateBuildStatus `json:"status"`
    TemplateID string              `json:"templateID"`
}

type TemplateBuildOptions

TemplateBuildOptions configures resources, tags, caching, and build polling.

go
type TemplateBuildOptions struct {
    Tags               []string
    CPUCount, MemoryMB int
    SkipCache          bool
    PollInterval       time.Duration
    OnLog              func(BuildLogEntry)
}

type TemplateBuildRef

TemplateBuildRef identifies a started template build.

go
type TemplateBuildRef struct {
    Name                string
    Tags                []string
    TemplateID, BuildID string
}

type TemplateBuildStatus

TemplateBuildStatus is a template build state.

go
type TemplateBuildStatus string

go
const (
    // BuildWaiting indicates that a template build is queued.
    BuildWaiting TemplateBuildStatus = "waiting"
    // BuildBuilding indicates that a template build is in progress.
    BuildBuilding TemplateBuildStatus = "building"
    // BuildReady indicates that a template build completed successfully.
    BuildReady TemplateBuildStatus = "ready"
    // BuildFailed indicates that a template build failed.
    BuildFailed TemplateBuildStatus = "error"
)

type TemplateBuilder

TemplateBuilder builds a declarative template definition.

go
type TemplateBuilder struct {
    // contains filtered or unexported fields
}
Example
go
template := agentbox.NewTemplate(".").FromPython("3.13").Copy("requirements.txt", "/app/", nil).PipInstall().Workdir("/app")
_, _ = template.JSON()

func NewTemplate

go
func NewTemplate(contextPath string, ignore ...string) *TemplateBuilder

NewTemplate starts a template definition. Empty contextPath uses the current directory.

func (*TemplateBuilder) AptInstall

go
func (builder *TemplateBuilder) AptInstall(options AptInstallOptions, packages ...string) *TemplateBuilder

AptInstall installs Debian packages as root.

func (*TemplateBuilder) BunInstall

go
func (builder *TemplateBuilder) BunInstall(options PackageInstallOptions, packages ...string) *TemplateBuilder

BunInstall installs Bun packages with the requested scope.

func (*TemplateBuilder) Copy

go
func (builder *TemplateBuilder) Copy(source, destination string, options *CopyOptions) *TemplateBuilder

Copy adds a file or directory from the context.

func (*TemplateBuilder) Dockerfile

go
func (builder *TemplateBuilder) Dockerfile() string

Dockerfile returns a human-readable equivalent definition.

func (*TemplateBuilder) Env

go
func (builder *TemplateBuilder) Env(values map[string]string) *TemplateBuilder

Env sets environment variables for subsequent template steps.

func (*TemplateBuilder) FromAWSRegistry

go
func (builder *TemplateBuilder) FromAWSRegistry(image, accessKeyID, secretAccessKey, region string) *TemplateBuilder

FromAWSRegistry selects an AWS ECR image.

func (*TemplateBuilder) FromAlpine

go
func (builder *TemplateBuilder) FromAlpine(variant string) *TemplateBuilder

FromAlpine selects an official Alpine image, defaulting to version 3.24.

func (*TemplateBuilder) FromArch

go
func (builder *TemplateBuilder) FromArch(variant string) *TemplateBuilder

FromArch selects an official Arch Linux image.

func (*TemplateBuilder) FromBase

go
func (builder *TemplateBuilder) FromBase() *TemplateBuilder

FromBase selects the default AgentBox base image.

func (*TemplateBuilder) FromBun

go
func (builder *TemplateBuilder) FromBun(variant string) *TemplateBuilder

FromBun selects an official Bun image.

func (*TemplateBuilder) FromDebian

go
func (builder *TemplateBuilder) FromDebian(variant string) *TemplateBuilder

FromDebian selects an official Debian image, defaulting to stable.

func (*TemplateBuilder) FromDockerfile

go
func (builder *TemplateBuilder) FromDockerfile(contentOrPath string) *TemplateBuilder

FromDockerfile parses common FROM/RUN/COPY/ENV/WORKDIR/USER directives.

func (*TemplateBuilder) FromFedora

go
func (builder *TemplateBuilder) FromFedora(variant string) *TemplateBuilder

FromFedora selects an official Fedora image, defaulting to version 44.

func (*TemplateBuilder) FromGCPRegistry

go
func (builder *TemplateBuilder) FromGCPRegistry(image, serviceAccountJSON string) *TemplateBuilder

FromGCPRegistry selects a GCP Artifact Registry image.

func (*TemplateBuilder) FromImage

go
func (builder *TemplateBuilder) FromImage(image string) *TemplateBuilder

FromImage selects an OCI image.

func (*TemplateBuilder) FromNode

go
func (builder *TemplateBuilder) FromNode(variant string) *TemplateBuilder

FromNode selects an official Node.js image, defaulting to the LTS variant.

func (*TemplateBuilder) FromPython

go
func (builder *TemplateBuilder) FromPython(version string) *TemplateBuilder

FromPython selects an official Python image.

func (*TemplateBuilder) FromRegistry

go
func (builder *TemplateBuilder) FromRegistry(image, username, password string) *TemplateBuilder

FromRegistry selects a password-authenticated OCI registry image.

func (*TemplateBuilder) FromTemplate

go
func (builder *TemplateBuilder) FromTemplate(template string) *TemplateBuilder

FromTemplate selects another AgentBox template.

func (*TemplateBuilder) FromUbuntu

go
func (builder *TemplateBuilder) FromUbuntu(variant string) *TemplateBuilder

FromUbuntu selects an official Ubuntu image, defaulting to latest.

func (*TemplateBuilder) GitClone

go
func (builder *TemplateBuilder) GitClone(repository string, options *GitCloneOptions) *TemplateBuilder

GitClone clones a Git repository into the template filesystem.

func (*TemplateBuilder) JSON

go
func (builder *TemplateBuilder) JSON() ([]byte, error)

JSON returns the build request representation without computed copy hashes.

func (*TemplateBuilder) MakeDir

go
func (builder *TemplateBuilder) MakeDir(paths ...string) *TemplateBuilder

MakeDir creates directories and their missing parents.

func (*TemplateBuilder) NPMInstall

go
func (builder *TemplateBuilder) NPMInstall(options PackageInstallOptions, packages ...string) *TemplateBuilder

NPMInstall installs npm packages with the requested scope.

func (*TemplateBuilder) PipInstall

go
func (builder *TemplateBuilder) PipInstall(packages ...string) *TemplateBuilder

PipInstall installs Python packages as root.

func (*TemplateBuilder) Ready

go
func (builder *TemplateBuilder) Ready(command string) *TemplateBuilder

Ready replaces the readiness command for the template.

func (*TemplateBuilder) Remove

go
func (builder *TemplateBuilder) Remove(paths ...string) *TemplateBuilder

Remove recursively removes paths from the template filesystem.

func (*TemplateBuilder) Rename

go
func (builder *TemplateBuilder) Rename(source, destination string) *TemplateBuilder

Rename moves a path in the template filesystem.

func (*TemplateBuilder) Run

go
func (builder *TemplateBuilder) Run(commands ...string) *TemplateBuilder

Run adds shell commands executed as the current build user.

func (*TemplateBuilder) RunAs

go
func (builder *TemplateBuilder) RunAs(user string, commands ...string) *TemplateBuilder

RunAs adds shell commands executed as user. An empty user inherits the current build user, as Run does.

func (*TemplateBuilder) SkipCache

go
func (builder *TemplateBuilder) SkipCache() *TemplateBuilder

SkipCache forces this and all subsequent layers.

func (*TemplateBuilder) Start

go
func (builder *TemplateBuilder) Start(command, readyCommand string) *TemplateBuilder

Start configures the sandbox start command and readiness command.

go
func (builder *TemplateBuilder) Symlink(source, destination string) *TemplateBuilder

Symlink creates a symbolic link.

func (*TemplateBuilder) User

go
func (builder *TemplateBuilder) User(user string) *TemplateBuilder

User sets the user for subsequent template steps.

func (*TemplateBuilder) Workdir

go
func (builder *TemplateBuilder) Workdir(path string) *TemplateBuilder

Workdir sets the working directory for subsequent template steps.

type TemplateError

TemplateError reports an invalid or incompatible template.

go
type TemplateError struct{ APIError }

func (*TemplateError) Error

go
func (e *TemplateError) Error() string

Error formats the template operation failure.

func (*TemplateError) Unwrap

go
func (e *TemplateError) Unwrap() error

Unwrap returns the underlying template operation error, if any.

type TemplateInfo

TemplateInfo is a compact template list entry.

go
type TemplateInfo struct {
    BuildCount    int32               `json:"buildCount"`
    BuildID       string              `json:"buildID"`
    BuildStatus   TemplateBuildStatus `json:"buildStatus"`
    CPUCount      int32               `json:"cpuCount"`
    CreatedAt     time.Time           `json:"createdAt"`
    CreatedBy     *TeamUser           `json:"createdBy,omitzero"`
    DiskSizeMB    int32               `json:"diskSizeMB"`
    EnvdVersion   string              `json:"envdVersion"`
    LastSpawnedAt *time.Time          `json:"lastSpawnedAt,omitzero"`
    MemoryMB      int32               `json:"memoryMB"`
    Names         []string            `json:"names"`
    Public        bool                `json:"public"`
    SpawnCount    int64               `json:"spawnCount"`
    TemplateID    string              `json:"templateID"`
    UpdatedAt     time.Time           `json:"updatedAt"`
}

type TemplateInfoOptions

TemplateInfoOptions paginates a template's build history.

go
type TemplateInfoOptions struct {
    NextToken string
    Limit     int
}

type TemplateListOptions

TemplateListOptions configures template pagination and team filtering.

go
type TemplateListOptions struct {
    TeamID, NextToken string
    Limit             int
}

type TemplateLogOptions

TemplateLogOptions configures template log pagination and filtering.

go
type TemplateLogOptions struct {
    Cursor                   string
    Timestamp                int64
    Limit                    int
    Direction, Level, Source string
}

type TemplateService

TemplateService manages AgentBox templates.

go
type TemplateService struct {
    // contains filtered or unexported fields
}

func (*TemplateService) AssignTags

go
func (service *TemplateService) AssignTags(ctx context.Context, target string, tags []string) (string, error)

AssignTags assigns tags to a template target and returns the selected build ID.

func (*TemplateService) Build

go
func (service *TemplateService) Build(ctx context.Context, builder *TemplateBuilder, name string, options *TemplateBuildOptions) (*TemplateBuildRef, error)

Build starts a build and waits for a terminal state.

func (*TemplateService) BuildInBackground

go
func (service *TemplateService) BuildInBackground(ctx context.Context, builder *TemplateBuilder, name string, options *TemplateBuildOptions) (*TemplateBuildRef, error)

BuildInBackground uploads COPY contexts and starts a build.

func (*TemplateService) BuildLogs

go
func (service *TemplateService) BuildLogs(ctx context.Context, templateID, buildID string, options *TemplateLogOptions) (Page[BuildLogEntry], error)

BuildLogs returns one page of structured build logs.

func (*TemplateService) BuildStatus

go
func (service *TemplateService) BuildStatus(ctx context.Context, templateID, buildID string, logsOffset int) (*TemplateBuildInfo, error)

BuildStatus returns the current build state and logs after logsOffset.

func (*TemplateService) Delete

go
func (service *TemplateService) Delete(ctx context.Context, templateID string) error

Delete removes a template.

func (*TemplateService) Exists

go
func (service *TemplateService) Exists(ctx context.Context, alias string) (bool, error)

Exists reports whether a template alias exists or is reserved.

func (*TemplateService) Info

go
func (service *TemplateService) Info(ctx context.Context, templateID string, options *TemplateInfoOptions) (*TemplateWithBuilds, error)

Info returns a template and its build history.

func (*TemplateService) List

go
func (service *TemplateService) List(ctx context.Context, options *TemplateListOptions) (Page[TemplateInfo], error)

List returns one template page.

func (*TemplateService) RemoveTags

go
func (service *TemplateService) RemoveTags(ctx context.Context, name string, tags []string) error

RemoveTags removes tags from a named template.

func (*TemplateService) SetPublic

go
func (service *TemplateService) SetPublic(ctx context.Context, templateID string, public bool) ([]string, error)

SetPublic changes template visibility and returns its names.

func (*TemplateService) Tags

go
func (service *TemplateService) Tags(ctx context.Context, templateID string) ([]TemplateTag, error)

Tags lists tags assigned to a template.

type TemplateStep

TemplateStep is one layer in a template build.

go
type TemplateStep struct {
    Type            string   `json:"type"`
    Args            []string `json:"args"`
    Force           bool     `json:"force"`
    FilesHash       string   `json:"filesHash,omitempty"`
    ForceUpload     bool     `json:"forceUpload,omitempty"`
    ResolveSymlinks bool     `json:"resolveSymlinks,omitempty"`
    Gzip            bool     `json:"gzip,omitempty"`
}

type TemplateTag

TemplateTag associates a template tag with a build.

go
type TemplateTag struct {
    Tag, BuildID string
    CreatedAt    time.Time
}

type TemplateWithBuilds

TemplateWithBuilds contains a template and its build history.

go
type TemplateWithBuilds struct {
    Builds        []TemplateBuild `json:"builds"`
    CreatedAt     time.Time       `json:"createdAt"`
    LastSpawnedAt *time.Time      `json:"lastSpawnedAt,omitzero"`
    Names         []string        `json:"names"`
    Public        bool            `json:"public"`
    SpawnCount    int64           `json:"spawnCount"`
    TemplateID    string          `json:"templateID"`
    UpdatedAt     time.Time       `json:"updatedAt"`
}

type TimeoutError

TimeoutError reports a request, execution, or sandbox timeout.

go
type TimeoutError struct{ APIError }

func (*TimeoutError) Error

go
func (e *TimeoutError) Error() string

Error formats the timeout failure.

func (*TimeoutError) Unwrap

go
func (e *TimeoutError) Unwrap() error

Unwrap returns the underlying timeout error, if any.

type WatchHandle

WatchHandle owns a directory watch stream.

go
type WatchHandle struct {
    Events <-chan FileEvent
    // contains filtered or unexported fields
}

func (*WatchHandle) Close

go
func (handle *WatchHandle) Close() error

Close stops the watcher.

type WatchOptions

WatchOptions configures recursive and enriched filesystem events.

go
type WatchOptions struct{ Recursive, IncludeEntry, AllowNetworkMounts bool }

type WriteFile

WriteFile describes one batch upload.

go
type WriteFile struct {
    Path     string
    Data     io.Reader
    Metadata map[string]string
}

type WriteFileOptions

WriteFileOptions configures file ownership, metadata, and upload timeout.

go
type WriteFileOptions struct {
    User     string
    Metadata map[string]string
    // RequestTimeout limits the complete streaming upload. Zero leaves the
    // upload bounded only by ctx and a custom HTTP client timeout.
    RequestTimeout time.Duration
}

Generated by gomarkdoc