axernsdk

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2026 License: Apache-2.0 Imports: 37 Imported by: 0

README

Axern Go SDK

The Go SDK is the second language surface for Axern programmable sandboxes. It focuses on the programmable sandbox loop:

  • connect to the control plane
  • create a service-backed sandbox from a template, image, or environment
  • run a command
  • inspect sandbox metadata for logs and diagnostics
  • stream an attached process with stdin/stdout/stderr and lifecycle control
  • discover sandbox capabilities before using optional providers
  • read, write, inspect, mutate, and transfer sandbox files through platform file RPCs
  • open a tunnel from the sandbox to a local upstream, with SDK-owned renewal and cleanup
  • branch on typed error helpers such as IsNotFound, IsTimeout, and IsValidation
  • close and clean up SDK-owned resources

The Go SDK follows the same platform boundaries: sandbox file, process, and tunnel behavior are delegated to Axern control/node/relay APIs instead of SDK shell fallbacks.

Local Context

Add the published module to a Go project:

go get github.com/cofy-x/axern/sdk/go@latest

The public sdk/go/clientconfig package loads the same explicit context schema as the Axern CLI. Repository examples read the active CLI context, so make axern-config-init plus a running compose environment is enough for the examples and smoke target.

Quick Start

package main

import (
	"context"
	"fmt"
	"log"

	axern "github.com/cofy-x/axern/sdk/go"
)

func main() {
	ctx := context.Background()
	client, err := axern.NewClient(ctx, "127.0.0.1:25000")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	sandbox, err := axern.NewSandbox(axern.SandboxOptions{
		Client: client,
		Image:  "docker.io/library/python:3.12-slim",
	})
	if err != nil {
		log.Fatal(err)
	}
	defer sandbox.Close(ctx)

	if err := sandbox.Start(ctx); err != nil {
		log.Fatal(err)
	}

	result, err := sandbox.Exec(ctx, "python -c \"print('hello from go')\"", axern.ExecOptions{Check: true})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(result.StdoutString())

	if err := sandbox.WriteFile(ctx, "/tmp/message.txt", []byte("payload\n"), axern.WriteFileOptions{CreateParents: true}); err != nil {
		log.Fatal(err)
	}
	info, err := sandbox.Stat(ctx, "/tmp/message.txt")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s has %d bytes\n", info.Path, info.Size)

	data, err := sandbox.ReadFile(ctx, "/tmp/message.txt")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(string(data))

	if err := sandbox.Copy(ctx, "/tmp/message.txt", "/tmp/message.copy", axern.CopyOptions{Overwrite: true}); err != nil {
		log.Fatal(err)
	}

	process, err := sandbox.Process(ctx, []string{"python", "-u", "-c", "import sys; print(sys.stdin.read().upper())"}, axern.ProcessOptions{})
	if err != nil {
		log.Fatal(err)
	}
	if err := process.WriteString("streamed input\n"); err != nil {
		log.Fatal(err)
	}
	if err := process.CloseStdin(); err != nil {
		log.Fatal(err)
	}
	output, err := process.Output()
	if err != nil {
		log.Fatal(err)
	}
	if output.ExitCode != 0 {
		log.Fatalf("process exited with %d: %s", output.ExitCode, output.Message)
	}
	fmt.Print(string(output.Stdout))

	capabilities, err := sandbox.CapabilityStatus(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(capabilities.Capabilities)
}

Run a tool from a separate image against a host-backed sandbox workspace with ExecImage or ProcessImage. The image ref may point to an OCI or Nydus image; Axern resolves both through the same runtime image path. When Mounts is nil, the SDK requests a writable /workspace -> /workspace mount. Use an empty slice for an isolated image process. The actor image must contain the mount target path, or the node must be able to create it before launch; official Axern server, desktop, and Claude Code runtime images include /workspace. Use SandboxOptions.Image when the image should be the sandbox rootfs with normal files, exec, process, tunnel, and lifecycle APIs; image-backed processes are temporary side processes attached to an existing sandbox.

result, err := sandbox.ExecImage(ctx,
	"ghcr.io/cofy-x/agent:latest",
	axern.Shell("tool run"),
	axern.ImageExecOptions{
		Check: true,
		Mounts: []axern.ImageProcessMount{
			axern.WorkspaceMount("/workspace"),
		},
	},
)

Mount a reusable read-only image bundle into the primary sandbox with SandboxOptions.ImageMounts when the task image should remain the rootfs and the mounted image only contributes files:

sandbox, err := axern.NewSandbox(axern.SandboxOptions{
	Image: "registry.example.com/task-image:latest",
	ImageMounts: []axern.ImageMount{{
		Image:  "registry.example.com/tool-bundle:latest",
		Target: "/opt/axern/tools/example",
	}},
})

Examples

Runnable examples live under sdk/go/examples:

  • basic: start a sandbox and run a command
  • process: stream stdin/stdout with an attached process
  • files: use file and archive APIs
  • tunnel: expose a local upstream to the sandbox through tunnel mode
  • computer-use: inspect a desktop-capable sandbox and capture a screenshot
  • programmable: combine upload, process control, download, tunnel, and cleanup

Each example defaults to the current Axern context from the local CLI config file. Use --context or AXERN_CONTEXT to select a named context, and --config or AXERN_CONFIG to select a config file. Explicit flags and env vars still take precedence, including AXERN_ENDPOINT, AXERN_TLS_CA_CERT, AXERN_TLS_CERT, AXERN_TLS_KEY, AXERN_TEMPLATE_ID, AXERN_RUNTIME_CLASS, AXERN_PROXY_MODE, and AXERN_TLS_SERVER_NAME. Tunnel traffic reuses the gateway endpoint and TLS identity.

go run ./sdk/go/examples/basic
go run ./sdk/go/examples/process
go run ./sdk/go/examples/files
go run ./sdk/go/examples/tunnel
go run ./sdk/go/examples/computer-use --template-id desktop-base
go run ./sdk/go/examples/programmable

The lightweight examples smoke target runs basic, process, and files against the local compose context:

make sdk-go-examples-smoke

Usage Notes

  • Prefer defer sandbox.Close(ctx) for SDK-owned sandboxes. Closing a sandbox also closes SDK-owned tunnels and attached processes.
  • Use process.Output() when you want collected stdout, stderr, and exit status. Use process.Events() or process.Recv() when output should be handled incrementally.
  • Use client.NodeSandbox(allocationID) when you already have an allocation ID and want the lower-level file/process/exec API without creating a new SDK-owned sandbox.
  • Use sandbox.CapabilityStatus(ctx) to discover baseline and optional provider availability before calling desktop or browser APIs.
  • Use ExecOptions{Check: true} for command-style failures that should return ExecError.
  • Branch on helpers such as IsNotFound, IsTimeout, IsUnavailable, and IsValidation instead of parsing error text.
  • Sandboxd-backed capability failures remain RPCError values. When provider diagnostics are present, RPCError.Capability contains structured capability, provider, provider state, reason, and missing dependency details.
  • Use tunnels when a sandbox must reach a caller-local upstream such as a mock HTTP service or development server. Do not use tunnels for Axrun profile-backed LLM telemetry; that path uses sandboxd managed proxy through exec/process managed-proxy options.
result, err := sandbox.Exec(ctx, axern.Args("python", "-c", "import sys; sys.exit(7)"), axern.ExecOptions{Check: true})
var execErr *axern.ExecError
if errors.As(err, &execErr) {
	fmt.Println("exit", execErr.ExitCode(), result.StderrString())
}

_, statErr := sandbox.Stat(ctx, "/tmp/missing")
if axern.IsNotFound(statErr) {
	fmt.Println("missing")
}

var rpcErr *axern.RPCError
if errors.As(statErr, &rpcErr) && rpcErr.Capability != nil {
	fmt.Println(rpcErr.Capability.Capability, rpcErr.Capability.MissingDependencies)
}

Validation

make sdk-go-verify
make sdk-go-examples-smoke

With local compose running, make local-compose-go-sdk-e2e verifies real sandbox exec, process, files, archives, and tunnels. Set AXERN_GO_SDK_E2E_IMAGE_PROCESS_IMAGE=<image-ref> to additionally verify ExecImage and ProcessImage against a host-backed /workspace service volume, including that image-backed writes and overwrites are visible from the owning sandbox. Set AXERN_GO_SDK_E2E_IMAGE_PROCESS_LOOPBACK=1 to also verify that image-backed actors can reach a service bound to the owning sandbox's 127.0.0.1; this is currently expected to pass for runc and expose the runsc loopback isolation limitation. This loopback probe is a runtime capability check, not an Axrun LLM telemetry requirement. The image must provide /bin/sh, cat, curl, and tr.

Documentation

Overview

Package axernsdk provides the Go client surface for Axern programmable sandboxes.

The package owns the SDK-side lifecycle for service-backed sandboxes, attached processes, platform file APIs, archive directory transfer, and tunnel sessions. Runtime behavior is delegated to Axern control, node, and tunnel APIs; the SDK does not implement shell fallbacks for sandbox files or process control.

Index

Constants

View Source
const (
	// ProxyModeEnv uses gRPC's environment proxy configuration.
	ProxyModeEnv = "env"
	// ProxyModeDirect bypasses environment proxies for all SDK connections.
	ProxyModeDirect = "direct"
)

Variables

View Source
var (
	// ErrSandboxNotStarted indicates a sandbox runtime API was called before Start.
	ErrSandboxNotStarted = errors.New("sandbox is not active")
	// ErrInvalidSource indicates SandboxOptions did not specify exactly one source.
	ErrInvalidSource = errors.New("provide exactly one sandbox source")
	// ErrProcessClosed indicates an attached process stream is already closed.
	ErrProcessClosed = errors.New("sandbox process is closed")
	// ErrProcessExitMissing indicates the process stream ended without exit status.
	ErrProcessExitMissing = errors.New("sandbox process stream ended without exit status")
)

Functions

func ErrorRetryable

func ErrorRetryable(err error) bool

ErrorRetryable reports whether an SDK error represents a transient operation that may be retried within the caller's original deadline.

func IsAlreadyExists

func IsAlreadyExists(err error) bool

IsAlreadyExists reports whether err maps to gRPC AlreadyExists.

func IsCancelled

func IsCancelled(err error) bool

IsCancelled reports whether err was cancelled by the caller or transport.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err maps to gRPC NotFound.

func IsPermissionDenied

func IsPermissionDenied(err error) bool

IsPermissionDenied reports whether err maps to permission or auth failure.

func IsTimeout

func IsTimeout(err error) bool

IsTimeout reports whether err is a local or remote deadline failure.

func IsUnavailable

func IsUnavailable(err error) bool

IsUnavailable reports whether err maps to gRPC Unavailable.

func IsValidation

func IsValidation(err error) bool

IsValidation reports whether err was caused by invalid SDK input.

func PlatformName

func PlatformName() string

PlatformName returns the Axern platform name.

func Version

func Version() string

Version returns the Go SDK version.

Types

type CapabilityDependencyStatus

type CapabilityDependencyStatus struct {
	Name      string
	Available bool
	Reason    string
}

type CapabilityProviderStatus

type CapabilityProviderStatus struct {
	Name         string
	State        string
	Available    bool
	Capabilities []string
	Backend      string
	Reason       string
	Dependencies []CapabilityDependencyStatus
}

type CapabilityProviderSummary

type CapabilityProviderSummary struct {
	Total       int32
	Available   int32
	Degraded    int32
	Unavailable int32
}

type CapabilityStatus

type CapabilityStatus struct {
	Ready           bool
	Capabilities    []string
	Providers       []CapabilityProviderStatus
	ProviderSummary CapabilityProviderSummary
}

type ChmodOptions

type ChmodOptions struct {
	Recursive bool
}

ChmodOptions configures sandbox-side chmod operations.

type Client

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

Client is the root Axern Go SDK client.

func NewClient

func NewClient(ctx context.Context, target string, options ...ClientOption) (*Client, error)

NewClient connects to the Axern control plane at target.

func (*Client) AgentProfileControl

func (c *Client) AgentProfileControl() agentprofilev1.AgentProfileControlClient

func (*Client) ArtifactData

func (c *Client) ArtifactData() artifactv1.ArtifactDataClient

func (*Client) CancelRollout

func (c *Client) CancelRollout(ctx context.Context, id string, options ...grpc.CallOption) (*rolloutv1.Rollout, error)

func (*Client) Close

func (c *Client) Close() error

Close closes the control-plane connection when the client owns it.

func (*Client) CreateEnvironment

func (c *Client) CreateEnvironment(ctx context.Context, options CreateEnvironmentOptions) (*environmentv1.Environment, error)

CreateEnvironment creates an Axern environment from a template or image.

func (*Client) CreateRollout

func (c *Client) CreateRollout(ctx context.Context, request *rolloutv1.CreateRolloutRequest, options ...grpc.CallOption) (*rolloutv1.Rollout, error)

func (*Client) CreateService

func (c *Client) CreateService(ctx context.Context, options CreateServiceOptions) (*servicev1.Service, error)

CreateService creates an Axern service.

func (*Client) CreateTunnelSession

func (c *Client) CreateTunnelSession(ctx context.Context, options CreateTunnelSessionOptions) (CreateTunnelSessionResult, error)

CreateTunnelSession creates a tunnel session through the control plane.

func (*Client) DeleteEnvironment

func (c *Client) DeleteEnvironment(ctx context.Context, environmentID string) error

DeleteEnvironment deletes an environment by id.

func (*Client) DeleteService

func (c *Client) DeleteService(ctx context.Context, serviceID string) error

DeleteService deletes a service by id.

func (*Client) GetRollout

func (c *Client) GetRollout(ctx context.Context, id string, options ...grpc.CallOption) (*rolloutv1.GetRolloutResponse, error)

func (*Client) GetTunnelSession

func (c *Client) GetTunnelSession(ctx context.Context, sessionID string) (*tunnelcontrolv1.TunnelSession, error)

GetTunnelSession fetches a tunnel session by id.

func (*Client) ListServiceReplicas

func (c *Client) ListServiceReplicas(ctx context.Context, serviceID string) ([]*servicev1.ServiceReplica, error)

ListServiceReplicas returns the current replicas for a service.

func (*Client) ListTunnelSessionEvents

func (c *Client) ListTunnelSessionEvents(ctx context.Context, sessionID string, limit int32) ([]*tunnelcontrolv1.TunnelSessionEvent, error)

ListTunnelSessionEvents returns recent tunnel session events.

func (*Client) NodeSandbox

func (c *Client) NodeSandbox(allocationID string) (*NodeSandboxClient, error)

NodeSandbox returns a low-level sandbox client for allocationID.

func (*Client) ReadRunOutput added in v0.4.0

func (c *Client) ReadRunOutput(ctx context.Context, runID string, options RunOutputOptions) (*RunOutput, error)

func (*Client) RenewTunnelSession

func (c *Client) RenewTunnelSession(ctx context.Context, sessionID, clientToken string, ttl time.Duration) (*tunnelcontrolv1.TunnelSession, error)

RenewTunnelSession renews a tunnel session lease.

func (*Client) RetryRollout

func (c *Client) RetryRollout(ctx context.Context, id string, options ...grpc.CallOption) (*rolloutv1.Rollout, error)

func (*Client) RevokeTunnelSession

func (c *Client) RevokeTunnelSession(ctx context.Context, sessionID, reason string) (*tunnelcontrolv1.TunnelSession, error)

RevokeTunnelSession revokes a tunnel session.

func (*Client) RolloutControl

func (c *Client) RolloutControl() rolloutv1.RolloutControlClient

func (*Client) WatchRun added in v0.4.0

func (c *Client) WatchRun(ctx context.Context, runID string, afterVersion int64) (*RunWatch, error)

func (*Client) WatchService

func (c *Client) WatchService(ctx context.Context, serviceID string, afterVersion int64) (ServiceWatch, error)

WatchService watches service snapshots newer than afterVersion.

type ClientOption

type ClientOption func(*clientConfig) error

ClientOption configures a Client.

func WithControlConn

func WithControlConn(conn *grpc.ClientConn) ClientOption

WithControlConn uses an existing control-plane gRPC connection.

func WithDialOptions

func WithDialOptions(options ...grpc.DialOption) ClientOption

WithDialOptions appends gRPC dial options for the control-plane connection.

func WithProxyMode

func WithProxyMode(mode string) ClientOption

WithProxyMode configures proxy handling for both control-plane and tunnel relay connections.

func WithTLS

func WithTLS(caCertPath, certPath, keyPath, serverName string) ClientOption

WithTLS configures mutual TLS for the control-plane connection.

type Command

type Command struct {
	Argv  []string
	Shell string
}

func Args

func Args(argv ...string) Command

Args creates a command executed directly without a shell wrapper.

func Shell

func Shell(command string) Command

Shell creates a command executed through /bin/sh -lc.

type ComputerUseDependencyStatus

type ComputerUseDependencyStatus struct {
	Name      string
	Available bool
	Reason    string
}

type ComputerUseDisplay

type ComputerUseDisplay struct {
	Display string
	Backend string
	Width   int32
	Height  int32
}

type ComputerUseKeyboardOptions

type ComputerUseKeyboardOptions struct {
	Text    string
	Key     string
	Keys    []string
	DelayMS int32
}

type ComputerUseMouseOptions

type ComputerUseMouseOptions struct {
	Action    string
	X         int32
	Y         int32
	ToX       int32
	ToY       int32
	Button    string
	Direction string
	Amount    int32
}

type ComputerUseRegion

type ComputerUseRegion struct {
	X      int32
	Y      int32
	Width  int32
	Height int32
}

type ComputerUseScreenshot

type ComputerUseScreenshot struct {
	Data        []byte
	ContentType string
}

type ComputerUseScreenshotOptions

type ComputerUseScreenshotOptions struct {
	ShowCursor bool
	Region     *ComputerUseRegion
	Format     string
	Quality    int32
	Scale      float64
}

type ComputerUseStatus

type ComputerUseStatus struct {
	Available    bool
	Display      string
	Backend      string
	Reason       string
	Dependencies []ComputerUseDependencyStatus
}

type CopyOptions

type CopyOptions struct {
	Recursive bool
	Overwrite bool
}

CopyOptions configures sandbox-side copy operations.

type CreateEnvironmentOptions

type CreateEnvironmentOptions struct {
	Namespace            string
	TemplateID           string
	Image                string
	RegistryCredentialID string
	RootFSReadonly       bool
	Labels               map[string]string
}

CreateEnvironmentOptions configures a control-plane environment.

type CreateServiceOptions

type CreateServiceOptions struct {
	Namespace               string
	EnvironmentID           string
	Argv                    []string
	Env                     map[string]string
	Cwd                     string
	RuntimeClass            string
	ExtensionCapabilities   []ExtensionCapability
	Volumes                 []VolumeMount
	ImageMounts             []ImageMount
	WorkspaceImage          *WorkspaceImageSource
	RequestCPU              ResourceQuantity
	RequestMemory           ResourceQuantity
	RequestEphemeralStorage ResourceQuantity
	LimitCPU                ResourceQuantity
	LimitMemory             ResourceQuantity
	LimitEphemeralStorage   ResourceQuantity
	Labels                  map[string]string
}

CreateServiceOptions configures a single-replica service for sandbox use.

type CreateTunnelSessionOptions

type CreateTunnelSessionOptions struct {
	AllocationID string
	LocalTarget  string
	RemotePort   int32
	TTL          time.Duration
	WaitReady    bool
	ReadyTimeout time.Duration
}

CreateTunnelSessionOptions configures a control-plane tunnel session.

type CreateTunnelSessionResult

type CreateTunnelSessionResult struct {
	Session     *tunnelcontrolv1.TunnelSession
	ClientToken string
}

CreateTunnelSessionResult contains the created tunnel session and client token.

type DownloadDirOptions

type DownloadDirOptions struct {
	NoOverwrite bool
}

DownloadDirOptions configures directory downloads from a sandbox.

type ExecError

type ExecError struct {
	Argv   []string
	Result ExecResult
}

ExecError is returned when ExecOptions.Check is true and a command exits nonzero.

func (*ExecError) Error

func (e *ExecError) Error() string

func (*ExecError) ExitCode

func (e *ExecError) ExitCode() int32

func (*ExecError) StderrString

func (e *ExecError) StderrString() string

func (*ExecError) StdoutString

func (e *ExecError) StdoutString() string

type ExecOptions

type ExecOptions struct {
	Env          map[string]string
	Cwd          string
	Timeout      time.Duration
	User         string
	TTY          bool
	Check        bool
	ManagedProxy *ManagedProxyOptions
}

ExecOptions configures a collected sandbox command execution.

type ExecResult

type ExecResult struct {
	ExitCode           int32
	Stdout             []byte
	Stderr             []byte
	StdoutTruncated    bool
	StderrTruncated    bool
	ManagedProxyReport *ManagedProxyReport
}

ExecResult contains collected command output and exit status.

func (ExecResult) StderrString

func (r ExecResult) StderrString() string

StderrString returns stderr decoded as a Go string.

func (ExecResult) StdoutString

func (r ExecResult) StdoutString() string

StdoutString returns stdout decoded as a Go string.

type ExtensionCapability added in v0.5.0

type ExtensionCapability struct {
	Name  string
	Value string
}

ExtensionCapability is an exact-match, DNS-qualified node extension fact. Platform capabilities are inferred by Axern and cannot be requested here.

type ImageExecOptions

type ImageExecOptions struct {
	Env          map[string]string
	Cwd          string
	Timeout      time.Duration
	User         string
	TTY          bool
	Check        bool
	Mounts       []ImageProcessMount
	ManagedProxy *ManagedProxyOptions
}

ImageExecOptions configures a collected command from a separate image.

type ImageMount

type ImageMount struct {
	Image    string
	Target   string
	Readonly bool
}

ImageMount describes a read-only OCI image mounted into the workload rootfs.

type ImageProcessMount

type ImageProcessMount struct {
	SandboxPath string
	TargetPath  string
	Readonly    bool
	Options     []string
}

ImageProcessMount shares a host-backed path from the target sandbox into an image-backed process.

func WorkspaceMount

func WorkspaceMount(path string) ImageProcessMount

WorkspaceMount shares path from the target sandbox at the same path inside the image-backed process.

type ImageProcessOptions

type ImageProcessOptions struct {
	Env          map[string]string
	Cwd          string
	Timeout      time.Duration
	User         string
	TTY          bool
	Mounts       []ImageProcessMount
	ManagedProxy *ManagedProxyOptions
}

ImageProcessOptions configures a streaming process from a separate image.

type ManagedProxyOptions

type ManagedProxyOptions struct {
	Provider            string
	UpstreamBaseURL     string
	UpstreamBearerToken string
}

type ManagedProxyReport

type ManagedProxyReport struct {
	Provider      string
	RequestCount  int32
	ResponseCount int32
	ErrorCount    int32
	ReportJSON    []byte
}

type MkdirOptions

type MkdirOptions struct {
	Parents bool
}

MkdirOptions configures sandbox directory creation.

type MoveOptions

type MoveOptions struct {
	Overwrite bool
}

MoveOptions configures sandbox-side move operations.

type NodeSandboxClient

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

NodeSandboxClient provides lower-level operations for an existing allocation.

func (*NodeSandboxClient) CapabilityStatus

func (n *NodeSandboxClient) CapabilityStatus(ctx context.Context) (CapabilityStatus, error)

func (*NodeSandboxClient) Chmod

func (n *NodeSandboxClient) Chmod(ctx context.Context, path string, mode uint32, options ChmodOptions) error

func (*NodeSandboxClient) ComputerUseDisplay

func (n *NodeSandboxClient) ComputerUseDisplay(ctx context.Context) (ComputerUseDisplay, error)

func (*NodeSandboxClient) ComputerUseKeyboard

func (n *NodeSandboxClient) ComputerUseKeyboard(ctx context.Context, options ComputerUseKeyboardOptions) error

func (*NodeSandboxClient) ComputerUseMouse

func (n *NodeSandboxClient) ComputerUseMouse(ctx context.Context, options ComputerUseMouseOptions) error

func (*NodeSandboxClient) ComputerUseScreenshot

func (n *NodeSandboxClient) ComputerUseScreenshot(ctx context.Context, options ...ComputerUseScreenshotOptions) (ComputerUseScreenshot, error)

func (*NodeSandboxClient) ComputerUseStatus

func (n *NodeSandboxClient) ComputerUseStatus(ctx context.Context) (ComputerUseStatus, error)

func (*NodeSandboxClient) Copy

func (n *NodeSandboxClient) Copy(ctx context.Context, srcPath, dstPath string, options CopyOptions) error

func (*NodeSandboxClient) DownloadDir

func (n *NodeSandboxClient) DownloadDir(ctx context.Context, remotePath, localPath string, options DownloadDirOptions) error

func (*NodeSandboxClient) Exec

func (n *NodeSandboxClient) Exec(ctx context.Context, command any, options ExecOptions) (ExecResult, error)

Exec runs a command in the allocation and collects stdout/stderr.

func (*NodeSandboxClient) ExecImage

func (n *NodeSandboxClient) ExecImage(ctx context.Context, image string, command any, options ImageExecOptions) (ExecResult, error)

ExecImage runs a command from image against explicit host-backed paths from the allocation and collects stdout/stderr.

func (*NodeSandboxClient) Exists

func (n *NodeSandboxClient) Exists(ctx context.Context, path string) (bool, error)

func (*NodeSandboxClient) ListDir

func (n *NodeSandboxClient) ListDir(ctx context.Context, path string) ([]SandboxFileInfo, error)

func (*NodeSandboxClient) MaterializeTaskAssets

func (n *NodeSandboxClient) MaterializeTaskAssets(ctx context.Context, sourcePath, target string, kind TaskAssetKind) (int64, error)

func (*NodeSandboxClient) Mkdir

func (n *NodeSandboxClient) Mkdir(ctx context.Context, path string, options MkdirOptions) error

func (*NodeSandboxClient) Move

func (n *NodeSandboxClient) Move(ctx context.Context, srcPath, dstPath string, options MoveOptions) error

func (*NodeSandboxClient) Process

func (n *NodeSandboxClient) Process(ctx context.Context, command any, options ProcessOptions) (*SandboxProcess, error)

Process starts an attached process in the allocation.

func (*NodeSandboxClient) ProcessImage

func (n *NodeSandboxClient) ProcessImage(ctx context.Context, image string, command any, options ImageProcessOptions) (*SandboxProcess, error)

ProcessImage starts a streaming process from image against explicit host-backed paths from the allocation.

func (*NodeSandboxClient) ReadFile

func (n *NodeSandboxClient) ReadFile(ctx context.Context, path string) ([]byte, error)

func (*NodeSandboxClient) Remove

func (n *NodeSandboxClient) Remove(ctx context.Context, path string, options RemoveOptions) error

func (*NodeSandboxClient) Stat

func (*NodeSandboxClient) Touch

func (n *NodeSandboxClient) Touch(ctx context.Context, path string, options TouchOptions) error

func (*NodeSandboxClient) UploadDir

func (n *NodeSandboxClient) UploadDir(ctx context.Context, localPath, remotePath string, options UploadDirOptions) error

func (*NodeSandboxClient) WriteFile

func (n *NodeSandboxClient) WriteFile(ctx context.Context, path string, data []byte, options WriteFileOptions) error

type PathError

type PathError struct {
	Message string
}

PathError describes invalid sandbox path input.

func (*PathError) Error

func (e *PathError) Error() string

type ProcessEvent

type ProcessEvent struct {
	Kind               ProcessEventKind
	Data               []byte
	ExitCode           int32
	Message            string
	ManagedProxyReport *ManagedProxyReport
}

ProcessEvent is a stdout, stderr, or exit event from an attached process.

type ProcessEventKind

type ProcessEventKind string

ProcessEventKind identifies a process stream event.

const (
	ProcessEventStdout ProcessEventKind = "stdout"
	ProcessEventStderr ProcessEventKind = "stderr"
	ProcessEventExit   ProcessEventKind = "exit"
)

type ProcessOptions

type ProcessOptions struct {
	Env          map[string]string
	Cwd          string
	Timeout      time.Duration
	User         string
	TTY          bool
	ManagedProxy *ManagedProxyOptions
}

ProcessOptions configures an attached sandbox process.

type ProcessOutput

type ProcessOutput struct {
	ProcessResult
	Stdout []byte
	Stderr []byte
}

ProcessOutput contains collected stdout, stderr, and exit status.

type ProcessResult

type ProcessResult struct {
	ExitCode           int32
	Message            string
	ManagedProxyReport *ManagedProxyReport
}

ProcessResult is the exit status for a sandbox process.

type RPCError

type RPCError struct {
	Operation    string
	AllocationID string
	Code         codes.Code
	Details      string
	Retryable    bool
	Capability   *SandboxCapabilityErrorInfo
	Err          error
}

RPCError wraps a gRPC status with SDK operation context.

func (*RPCError) Error

func (e *RPCError) Error() string

func (*RPCError) Unwrap

func (e *RPCError) Unwrap() error

type RemoveOptions

type RemoveOptions struct {
	Recursive bool
	Force     bool
}

RemoveOptions configures sandbox file or directory removal.

type ResourceQuantity

type ResourceQuantity string

ResourceQuantity is a user-facing resource quantity. String literals such as "500m", "512Mi", and "512MiB" can be assigned directly; constructors below make numeric quantities explicit without weakening the public API to any.

func CPUCores

func CPUCores(cores int64) ResourceQuantity

CPUCores formats CPU cores as a resource quantity.

func CPUMilli

func CPUMilli(milli int64) ResourceQuantity

CPUMilli formats milli CPU as a resource quantity.

func EphemeralStorageBytes added in v0.5.0

func EphemeralStorageBytes(bytes int64) ResourceQuantity

EphemeralStorageBytes formats node-local ephemeral storage bytes as a resource quantity.

func MemoryBytes

func MemoryBytes(bytes int64) ResourceQuantity

MemoryBytes formats memory bytes as a resource quantity.

type RunOutput added in v0.4.0

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

func (*RunOutput) Recv added in v0.4.0

func (s *RunOutput) Recv() (RunOutputEvent, error)

type RunOutputEvent added in v0.4.0

type RunOutputEvent struct {
	Stream              string
	Data                []byte
	NextCursor          string
	Terminal            bool
	Truncated           bool
	ObservedAtUnixMilli int64
}

type RunOutputOptions added in v0.4.0

type RunOutputOptions struct {
	Cursor string
	Follow bool
}

type RunWatch added in v0.4.0

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

func (*RunWatch) Recv added in v0.4.0

func (s *RunWatch) Recv() (*runv1.Run, error)

type Sandbox

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

Sandbox is an SDK-owned programmable sandbox backed by an Axern service allocation.

func NewSandbox

func NewSandbox(options SandboxOptions) (*Sandbox, error)

NewSandbox constructs a sandbox handle. Call Start before using runtime APIs.

func (*Sandbox) CapabilityStatus

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

func (*Sandbox) Chmod

func (s *Sandbox) Chmod(ctx context.Context, path string, mode uint32, options ChmodOptions) error

Chmod changes sandbox file permissions.

func (*Sandbox) Close

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

Close closes SDK-owned processes and tunnels, then deletes SDK-owned service/environment resources.

func (*Sandbox) ComputerUseDisplay

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

func (*Sandbox) ComputerUseKeyboard

func (s *Sandbox) ComputerUseKeyboard(ctx context.Context, options ComputerUseKeyboardOptions) error

func (*Sandbox) ComputerUseMouse

func (s *Sandbox) ComputerUseMouse(ctx context.Context, options ComputerUseMouseOptions) error

func (*Sandbox) ComputerUseScreenshot

func (s *Sandbox) ComputerUseScreenshot(ctx context.Context, options ...ComputerUseScreenshotOptions) (ComputerUseScreenshot, error)

func (*Sandbox) ComputerUseStatus

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

func (*Sandbox) Copy

func (s *Sandbox) Copy(ctx context.Context, srcPath, dstPath string, options CopyOptions) error

Copy copies a sandbox file or directory.

func (*Sandbox) DownloadDir

func (s *Sandbox) DownloadDir(ctx context.Context, remotePath, localPath string, options DownloadDirOptions) error

DownloadDir downloads the contents of remotePath into localPath.

func (*Sandbox) Exec

func (s *Sandbox) Exec(ctx context.Context, command any, options ExecOptions) (ExecResult, error)

Exec runs a command in the sandbox and collects stdout/stderr.

func (*Sandbox) ExecImage

func (s *Sandbox) ExecImage(ctx context.Context, image string, command any, options ImageExecOptions) (ExecResult, error)

ExecImage runs a command from image against explicit host-backed paths from the sandbox and collects stdout/stderr.

func (*Sandbox) Exists

func (s *Sandbox) Exists(ctx context.Context, path string) (bool, error)

Exists reports whether a sandbox path exists.

func (*Sandbox) ListDir

func (s *Sandbox) ListDir(ctx context.Context, path string) ([]SandboxFileInfo, error)

ListDir returns direct entries for a sandbox directory.

func (*Sandbox) MaterializeTaskAssets

func (s *Sandbox) MaterializeTaskAssets(ctx context.Context, sourcePath, target string, kind TaskAssetKind) error

MaterializeTaskAssets makes protected assets from the allocation's resolved TaskSet payload visible inside its copy-on-write workspace.

func (*Sandbox) Metadata

func (s *Sandbox) Metadata() (SandboxMetadata, error)

Metadata returns diagnostic metadata for a started sandbox.

func (*Sandbox) Mkdir

func (s *Sandbox) Mkdir(ctx context.Context, path string, options MkdirOptions) error

Mkdir creates a sandbox directory.

func (*Sandbox) Move

func (s *Sandbox) Move(ctx context.Context, srcPath, dstPath string, options MoveOptions) error

Move moves a sandbox file or directory.

func (*Sandbox) OpenTunnel

func (s *Sandbox) OpenTunnel(ctx context.Context, options TunnelOptions) (*SandboxTunnel, error)

OpenTunnel exposes a local upstream to the sandbox.

func (*Sandbox) Process

func (s *Sandbox) Process(ctx context.Context, command any, options ProcessOptions) (*SandboxProcess, error)

Process starts an attached process in the sandbox.

func (*Sandbox) ProcessImage

func (s *Sandbox) ProcessImage(ctx context.Context, image string, command any, options ImageProcessOptions) (*SandboxProcess, error)

ProcessImage starts a streaming process from image against explicit host-backed paths from the sandbox.

func (*Sandbox) ReadFile

func (s *Sandbox) ReadFile(ctx context.Context, path string) ([]byte, error)

ReadFile reads a sandbox file as bytes.

func (*Sandbox) Remove

func (s *Sandbox) Remove(ctx context.Context, path string, options RemoveOptions) error

Remove removes a sandbox file or directory.

func (*Sandbox) Start

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

Start creates the backing environment/service when needed and waits for a ready allocation.

func (*Sandbox) Stat

func (s *Sandbox) Stat(ctx context.Context, path string) (SandboxFileInfo, error)

Stat returns metadata for a sandbox path.

func (*Sandbox) State

func (s *Sandbox) State() (SandboxState, error)

State returns the current lightweight state for a started sandbox.

func (*Sandbox) Touch

func (s *Sandbox) Touch(ctx context.Context, path string, options TouchOptions) error

Touch updates sandbox file timestamps, optionally creating the path.

func (*Sandbox) UploadDir

func (s *Sandbox) UploadDir(ctx context.Context, localPath, remotePath string, options UploadDirOptions) error

UploadDir uploads the contents of localPath into remotePath.

func (*Sandbox) WriteFile

func (s *Sandbox) WriteFile(ctx context.Context, path string, data []byte, options WriteFileOptions) error

WriteFile writes bytes to a sandbox file.

type SandboxCapabilityErrorInfo

type SandboxCapabilityErrorInfo struct {
	Capability          string
	Provider            string
	ProviderState       string
	Reason              string
	MissingDependencies []string
}

SandboxCapabilityErrorInfo is structured sandbox capability/provider detail parsed from an RPC error.

func SandboxCapabilityInfo

func SandboxCapabilityInfo(details string) *SandboxCapabilityErrorInfo

SandboxCapabilityInfo returns sandbox capability/provider information from an Axern RPC detail string.

type SandboxFileInfo

type SandboxFileInfo struct {
	Path    string
	Kind    SandboxFileKind
	Size    int64
	Mode    uint32
	MtimeNS int64
}

SandboxFileInfo contains sandbox filesystem metadata.

type SandboxFileKind

type SandboxFileKind string

SandboxFileKind describes the kind of a sandbox filesystem entry.

const (
	SandboxFileKindFile        SandboxFileKind = "file"
	SandboxFileKindDirectory   SandboxFileKind = "directory"
	SandboxFileKindSymlink     SandboxFileKind = "symlink"
	SandboxFileKindOther       SandboxFileKind = "other"
	SandboxFileKindUnspecified SandboxFileKind = "unspecified"
)

type SandboxMetadata

type SandboxMetadata struct {
	EnvironmentID   string
	ServiceID       string
	AllocationID    string
	Attempt         int64
	NodeID          string
	RuntimeClass    string
	StartedAt       time.Time
	TunnelSessionID string
	BoundAddr       string
	Labels          map[string]string
}

SandboxMetadata is a stable diagnostic view of a started sandbox.

type SandboxOptions

type SandboxOptions struct {
	Client                  *Client
	TemplateID              string
	Image                   string
	EnvironmentID           string
	Namespace               string
	Argv                    []string
	Env                     map[string]string
	Cwd                     string
	RuntimeClass            string
	ExtensionCapabilities   []ExtensionCapability
	Volumes                 []VolumeMount
	ImageMounts             []ImageMount
	WorkspaceImage          *WorkspaceImageSource
	RequestCPU              ResourceQuantity
	RequestMemory           ResourceQuantity
	RequestEphemeralStorage ResourceQuantity
	LimitCPU                ResourceQuantity
	LimitMemory             ResourceQuantity
	LimitEphemeralStorage   ResourceQuantity
	ReadyTimeout            time.Duration
	Labels                  map[string]string
	RegistryCredentialID    string
	RootFSReadonly          bool
}

SandboxOptions describes the service-backed sandbox to create or attach to.

type SandboxProcess

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

SandboxProcess is an attached sandbox process with stream controls.

func (*SandboxProcess) Close

func (p *SandboxProcess) Close() error

Close closes the attached process stream.

func (*SandboxProcess) CloseStdin

func (p *SandboxProcess) CloseStdin() error

CloseStdin closes the process stdin stream.

func (*SandboxProcess) Events

func (p *SandboxProcess) Events() iter.Seq2[ProcessEvent, error]

Events returns an iterator over process events until exit or error.

func (*SandboxProcess) Kill

func (p *SandboxProcess) Kill() error

Kill sends SIGKILL to the process.

func (*SandboxProcess) Output

func (p *SandboxProcess) Output() (ProcessOutput, error)

Output collects stdout, stderr, and exit status.

func (*SandboxProcess) Recv

func (p *SandboxProcess) Recv() (ProcessEvent, error)

Recv receives the next process event.

func (*SandboxProcess) Resize

func (p *SandboxProcess) Resize(cols, rows uint32) error

Resize sends a terminal resize event for TTY processes.

func (*SandboxProcess) Signal

func (p *SandboxProcess) Signal(signal string) error

Signal sends a named signal to the process.

func (*SandboxProcess) Terminate

func (p *SandboxProcess) Terminate() error

Terminate sends SIGTERM to the process.

func (*SandboxProcess) Wait

func (p *SandboxProcess) Wait() (ProcessResult, error)

Wait drains events until the process exit status is observed.

func (*SandboxProcess) Write

func (p *SandboxProcess) Write(data []byte) error

Write sends bytes to the process stdin stream.

func (*SandboxProcess) WriteString

func (p *SandboxProcess) WriteString(data string) error

WriteString sends a string to the process stdin stream.

type SandboxState

type SandboxState struct {
	EnvironmentID         string
	ServiceID             string
	AllocationID          string
	NodeID                string
	Attempt               int64
	StartedAt             time.Time
	TunnelSessionID       string
	BoundAddr             string
	WorkspacePreparation  *commonv1.WorkspacePreparationFacts
	VerifierMaterializeMs int64
}

SandboxState is the lightweight runtime identity for a started sandbox.

type SandboxTunnel

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

SandboxTunnel is an SDK-owned tunnel session with renewal and cleanup.

func (*SandboxTunnel) BoundAddr

func (t *SandboxTunnel) BoundAddr() string

BoundAddr returns the sandbox-local address bound by the tunnel.

func (*SandboxTunnel) Close

func (t *SandboxTunnel) Close(ctx context.Context) error

Close revokes the tunnel session and stops SDK-owned renewal/relay work.

func (*SandboxTunnel) Session

Session returns the latest control-plane tunnel session payload.

func (*SandboxTunnel) SessionID

func (t *SandboxTunnel) SessionID() string

SessionID returns the control-plane tunnel session id.

type ServiceWatch

type ServiceWatch interface {
	Recv() (*servicev1.Service, error)
	Close()
}

ServiceWatch is a resumable stream of monotonically newer service snapshots.

type TaskAssetKind

type TaskAssetKind string
const (
	TaskAssetKindVerifier TaskAssetKind = "verifier"
	TaskAssetKindOracle   TaskAssetKind = "oracle"
)

type TouchOptions

type TouchOptions struct {
	NoCreate bool
	MtimeNS  int64
}

TouchOptions configures sandbox-side touch operations.

type TunnelConnectorOptions

type TunnelConnectorOptions struct {
	PingInterval time.Duration
	DialTimeout  time.Duration
	MaxStreams   int
}

TunnelConnectorOptions configures SDK-owned relay connector behavior.

type TunnelOptions

type TunnelOptions struct {
	Upstream     string
	ProxyPort    int32
	TTL          time.Duration
	ReadyTimeout time.Duration
	Connector    TunnelConnectorOptions
}

TunnelOptions configures a sandbox tunnel to a local upstream.

type UploadDirOptions

type UploadDirOptions struct {
	NoCreateParents bool
	NoOverwrite     bool
}

UploadDirOptions configures directory uploads into a sandbox.

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError describes invalid SDK input.

func (*ValidationError) Error

func (e *ValidationError) Error() string

type VolumeMount

type VolumeMount struct {
	Name     string
	Target   string
	Readonly bool
	Options  []string
}

VolumeMount describes a service volume claim mounted into a sandbox.

type WorkspaceImageSource

type WorkspaceImageSource struct {
	Variants   []WorkspaceImageVariant
	SourcePath string
	Target     string
}

WorkspaceImageSource describes an immutable TaskSet payload mounted through an allocation-local copy-on-write view. Variants are ordered by preference.

type WorkspaceImageVariant

type WorkspaceImageVariant struct{ Format, Image string }

type WriteFileOptions

type WriteFileOptions struct {
	CreateParents bool
}

WriteFileOptions configures sandbox file writes.

Jump to

Keyboard shortcuts

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