opensandbox

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2026 License: Apache-2.0 Imports: 28 Imported by: 0

README

OpenSandbox Go SDK

Go client library for the OpenSandbox API.

Covers all three OpenAPI specs:

  • Lifecycle — Create, manage, and destroy sandbox instances
  • Execd — Execute commands, manage files, monitor metrics inside sandboxes
  • Egress — Inspect and mutate sandbox network policy at runtime

Installation

# go 1.20+
go get github.com/alibaba/OpenSandbox/sdks/sandbox/go

Quick Start

Create and manage a sandbox
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/alibaba/OpenSandbox/sdks/sandbox/go"
)

func main() {
    ctx := context.Background()

    lc := opensandbox.NewLifecycleClient("http://localhost:8080/v1", "your-api-key")

    sbx, err := lc.CreateSandbox(ctx, opensandbox.CreateSandboxRequest{
        Image:      opensandbox.ImageSpec{URI: "python:3.12"},
        Entrypoint: []string{"/bin/sh"},
        ResourceLimits: opensandbox.ResourceLimits{
            "cpu":    "500m",
            "memory": "512Mi",
        },
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Created sandbox: %s (state: %s)\n", sbx.ID, sbx.Status.State)

    sbx, err = lc.GetSandbox(ctx, sbx.ID)
    if err != nil {
        log.Fatal(err)
    }

    list, err := lc.ListSandboxes(ctx, opensandbox.ListOptions{
        States:   []opensandbox.SandboxState{opensandbox.StateRunning},
        PageSize: 10,
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Running sandboxes: %d\n", list.Pagination.TotalItems)

    _ = lc.PauseSandbox(ctx, sbx.ID)
    _ = lc.ResumeSandbox(ctx, sbx.ID)

    _ = lc.DeleteSandbox(ctx, sbx.ID)
}
Run a command with streaming output
exec := opensandbox.NewExecdClient("http://localhost:9090", "your-execd-token")

err := exec.RunCommand(ctx, opensandbox.RunCommandRequest{
    Command: "echo 'Hello from sandbox!'",
    Timeout: 30000,
}, func(event opensandbox.StreamEvent) error {
    switch event.Event {
    case "stdout":
        fmt.Print(event.Data)
    case "stderr":
        fmt.Fprintf(os.Stderr, "%s", event.Data)
    case "execution_complete":
        fmt.Println("\n[done]")
    }
    return nil
})
Check egress policy
egress := opensandbox.NewEgressClient("http://localhost:18080", "your-egress-token")

policy, err := egress.GetPolicy(ctx)
fmt.Printf("Mode: %s, Default: %s\n", policy.Mode, policy.Policy.DefaultAction)

updated, err := egress.PatchPolicy(ctx, []opensandbox.NetworkRule{
    {Action: "allow", Target: "api.example.com"},
})
Use Credential Vault

Credential Vault injects outbound credentials from the egress sidecar while keeping real secrets out of sandbox environment variables, commands, files, and logs. Create the sandbox with CredentialProxy enabled, then write credentials and bindings through the sandbox helpers or EgressClient.

sandbox, err := manager.Create(ctx, opensandbox.SandboxCreateOptions{
    Image: "python:3.11",
    NetworkPolicy: &opensandbox.NetworkPolicy{
        DefaultAction: "deny",
        Egress: []opensandbox.NetworkRule{
            {Action: "allow", Target: "api.example.com"},
        },
    },
    CredentialProxy: &opensandbox.CredentialProxyConfig{Enabled: true},
})
if err != nil {
    return err
}

_, err = sandbox.CreateCredentialVault(ctx, opensandbox.CredentialVaultCreateRequest{
    Credentials: []opensandbox.Credential{
        {
            Name: "api-token",
            Source: opensandbox.InlineCredentialSource{
                Type:  opensandbox.CredentialSourceInline,
                Value: "<token>",
            },
        },
    },
    Bindings: []opensandbox.CredentialBinding{
        {
            Name: "api-token",
            Match: opensandbox.CredentialMatch{
                Schemes: []opensandbox.CredentialScheme{opensandbox.CredentialSchemeHTTPS},
                Ports:   []int{443},
                Hosts:   []string{"api.example.com"},
                Paths:   []string{"/v1/*"},
            },
            Auth: opensandbox.CredentialAuth{
                Type:       opensandbox.CredentialAuthAPIKey,
                Name:       "x-api-key",
                Credential: "api-token",
            },
        },
    },
})

See Credential Vault for auth types, binding guidance, and Git/curl examples.

API Reference

LifecycleClient

Created with NewLifecycleClient(baseURL, apiKey string, opts ...Option).

Method Description
CreateSandbox(ctx, req) Create a new sandbox from a container image
GetSandbox(ctx, id) Get sandbox details by ID
ListSandboxes(ctx, opts) List sandboxes with filtering and pagination
DeleteSandbox(ctx, id) Delete a sandbox
PauseSandbox(ctx, id) Pause a running sandbox
ResumeSandbox(ctx, id) Resume a paused sandbox
RenewExpiration(ctx, id, expiresAt) Extend sandbox expiration time
GetEndpoint(ctx, sandboxID, port, useServerProxy) Get public endpoint for a sandbox port
GetSignedEndpoint(ctx, sandboxID, port, expires) Get signed endpoint URL with OSEP-0011 route token
ExecdClient

Created with NewExecdClient(baseURL, accessToken string, opts ...Option).

Health:

Method Description
Ping(ctx) Check server health

Code Execution:

Method Description
ListContexts(ctx, language) List active code execution contexts
CreateContext(ctx, req) Create a code execution context
GetContext(ctx, contextID) Get context details
DeleteContext(ctx, contextID) Delete a context
DeleteContextsByLanguage(ctx, language) Delete all contexts for a language
ExecuteCode(ctx, req, handler) Execute code with SSE streaming
InterruptCode(ctx, sessionID) Interrupt running code

Command Execution:

Method Description
CreateSession(ctx) Create a bash session
RunInSession(ctx, sessionID, req, handler) Run command in session with SSE
DeleteSession(ctx, sessionID) Delete a bash session
RunCommand(ctx, req, handler) Run a command with SSE streaming
InterruptCommand(ctx, sessionID) Interrupt running command
GetCommandStatus(ctx, commandID) Get command execution status
GetCommandLogs(ctx, commandID, cursor) Get command stdout/stderr

File Operations:

Method Description
GetFileInfo(ctx, path) Get file metadata
DeleteFiles(ctx, paths) Delete files
SetPermissions(ctx, req) Change file permissions
MoveFiles(ctx, req) Move/rename files
SearchFiles(ctx, dir, pattern) Search files by glob pattern
ListDirectory(ctx, path) List immediate directory contents (server-side default depth)
ListDirectoryWithDepth(ctx, path, depth) List directory contents up to the given depth (0 returns empty)
ReplaceInFiles(ctx, req) Text replacement in files
UploadFile(ctx, file, opts) Upload a file to the sandbox
UploadFiles(ctx, entries) Upload multiple files to the sandbox
DownloadFile(ctx, remotePath, rangeHeader) Download a file from the sandbox

Directory Operations:

Method Description
CreateDirectory(ctx, path, mode) Create a directory (mkdir -p)
DeleteDirectory(ctx, path) Delete a directory recursively

Metrics:

Method Description
GetMetrics(ctx) Get system resource metrics
WatchMetrics(ctx, handler) Stream metrics via SSE
EgressClient

Created with NewEgressClient(baseURL, authToken string, opts ...Option).

Method Description
GetPolicy(ctx) Get current egress policy
PatchPolicy(ctx, rules) Merge rules into current policy
CreateCredentialVault(ctx, req) Create sandbox-local Credential Vault state
GetCredentialVault(ctx) Get sanitized Credential Vault state
PatchCredentialVault(ctx, req) Atomically mutate credentials and bindings
DeleteCredentialVault(ctx) Delete sandbox-local Credential Vault state
ListCredentialVaultCredentials(ctx) List sanitized credential metadata
GetCredentialVaultCredential(ctx, name) Get sanitized metadata for one credential
ListCredentialVaultBindings(ctx) List sanitized binding metadata
GetCredentialVaultBinding(ctx, name) Get sanitized metadata for one binding

SSE Streaming

Methods that stream output (RunCommand, ExecuteCode, RunInSession, WatchMetrics) accept an EventHandler callback:

type EventHandler func(event StreamEvent) error

Each StreamEvent contains:

  • Event — the event type (e.g. "stdout", "stderr", "result", "execution_complete"). For NDJSON streams, this is extracted from the JSON type field automatically.
  • Data — the raw event payload (JSON string for NDJSON streams).
  • ID — optional event identifier

Return a non-nil error from the handler to stop processing the stream early.

Client Options

All client constructors accept optional Option functions:

client := opensandbox.NewLifecycleClient(url, key,
    opensandbox.WithHTTPClient(myHTTPClient),
)

client := opensandbox.NewExecdClient(url, token,
    opensandbox.WithTimeout(60 * time.Second),
)

SDK-created HTTP clients enforce NIST 2030 minimum TLS certificate strength by default (RSA >= 2048, EC >= 224, DSA P >= 2048/Q >= 224, hash >= 224). If you must interoperate with legacy endpoints, set AllowWeakServerCertKeyLengths: true in TransportConfig.

Error Handling

Non-2xx responses are returned as *opensandbox.APIError:

_, err := lc.GetSandbox(ctx, "nonexistent")
if apiErr, ok := err.(*opensandbox.APIError); ok {
    fmt.Printf("HTTP %d: %s — %s\n", apiErr.StatusCode, apiErr.Response.Code, apiErr.Response.Message)
}

License

Apache 2.0

Documentation

Overview

Package opensandbox provides Go client libraries for the OpenSandbox Lifecycle, Egress, and Execd APIs.

Index

Constants

View Source
const (
	// DefaultExecdPort is the standard port for the execd service inside a sandbox.
	DefaultExecdPort = 44772

	// DefaultEgressPort is the standard port for the egress sidecar inside a sandbox.
	DefaultEgressPort = 18080

	// DefaultTimeoutSeconds is the default sandbox TTL in seconds.
	DefaultTimeoutSeconds = 600

	// DefaultReadyTimeoutSeconds is the default timeout for WaitUntilReady.
	DefaultReadyTimeoutSeconds = 30

	// DefaultHealthCheckPollingInterval is the default polling interval for WaitUntilReady.
	DefaultHealthCheckPollingInterval = 200 * time.Millisecond

	// DefaultRequestTimeout is the default HTTP request timeout.
	DefaultRequestTimeout = 30 * time.Second

	// DefaultCodeInterpreterTimeoutSeconds is the default TTL for code interpreter sandboxes.
	DefaultCodeInterpreterTimeoutSeconds = 900

	// Version is the SDK version reported in the User-Agent header.
	Version = "1.0.4"

	// APIVersion is the lifecycle API version prefix.
	APIVersion = "v1"

	// DefaultDomain is the default OpenSandbox server address.
	DefaultDomain = "localhost:8080"

	// DefaultProtocol is the default protocol for connecting to the server.
	DefaultProtocol = "http"
)
View Source
const (
	DefaultEndpointCacheTTL  = 600 * time.Second
	DefaultEndpointCacheSize = 1024
)
View Source
const CodeInterpreterImage = "opensandbox/code-interpreter:latest"

CodeInterpreterImage is the default container image for the code interpreter.

View Source
const DefaultIdleTimeout = 24 * time.Hour

DefaultIdleTimeout is the default TTL for idle pool entries (24 hours, per OSEP-0005).

Variables

View Source
var CodeInterpreterEntrypoint = []string{"/opt/code-interpreter/code-interpreter.sh"}

CodeInterpreterEntrypoint is the default entrypoint for the code interpreter.

View Source
var DefaultEntrypoint = []string{"tail", "-f", "/dev/null"}

DefaultEntrypoint keeps the sandbox alive for interactive use.

View Source
var DefaultResourceLimits = ResourceLimits{
	"cpu":    "1",
	"memory": "2Gi",
}

DefaultResourceLimits provides sensible defaults for sandbox resource limits.

Functions

func DefaultTransport

func DefaultTransport() *http.Transport

DefaultTransport creates an *http.Transport with connection pooling tuned for SDK workloads. Use with WithHTTPClient:

client := NewLifecycleClient(url, key,
    WithHTTPClient(&http.Client{Transport: DefaultTransport()}),
)

func OctalMode

func OctalMode(m os.FileMode) int

OctalMode converts a Go os.FileMode to the octal-digits-as-int format expected by the OpenSandbox server (e.g. os.FileMode(0755) -> 755).

Types

type APIError

type APIError struct {
	StatusCode int
	RequestID  string
	Response   ErrorResponse

	// RetryAfter is the server-suggested wait duration from the Retry-After
	// header. Zero means no suggestion was provided.
	RetryAfter time.Duration
}

APIError wraps an ErrorResponse with the HTTP status code and retry metadata.

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface.

func (*APIError) IsTransient

func (e *APIError) IsTransient() bool

IsTransient reports whether the API error represents a transient server condition that may succeed on retry.

type AcquireOptions added in v1.0.4

type AcquireOptions struct {
	SandboxTimeout  time.Duration
	Policy          *AcquirePolicy
	SkipHealthCheck bool
	MinRemainingTTL time.Duration
}

AcquireOptions configures a single Acquire call.

type AcquirePolicy added in v1.0.4

type AcquirePolicy int

AcquirePolicy determines behavior when the pool is empty.

const (
	AcquirePolicyDirectCreate AcquirePolicy = iota
	AcquirePolicyFailFast
)

func (AcquirePolicy) String added in v1.0.4

func (p AcquirePolicy) String() string

type Client

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

Client is the base HTTP client shared by LifecycleClient and EgressClient.

func NewClient

func NewClient(baseURL, apiKey, authHeader string, opts ...Option) *Client

NewClient creates a new base Client. The authHeader parameter specifies which HTTP header carries the API key (e.g. "OPEN-SANDBOX-API-KEY" for lifecycle, "OPENSANDBOX-EGRESS-AUTH" for egress).

type CodeContext

type CodeContext struct {
	ID       string `json:"id,omitempty"`
	Language string `json:"language"`
}

CodeContext represents a code execution context identifier and language.

type CodeInterpreter

type CodeInterpreter struct {
	*Sandbox
}

CodeInterpreter wraps a Sandbox with code execution capabilities. It provides multi-language code execution with persistent contexts.

func CreateCodeInterpreter

func CreateCodeInterpreter(ctx context.Context, config ConnectionConfig, opts CodeInterpreterCreateOptions) (*CodeInterpreter, error)

CreateCodeInterpreter creates a sandbox with the code-interpreter image and returns a CodeInterpreter wrapping it.

func (*CodeInterpreter) Execute

func (ci *CodeInterpreter) Execute(ctx context.Context, language, code string, handlers *ExecutionHandlers) (*Execution, error)

Execute runs code in the specified language and returns the structured result. If language is non-empty, it is sent as CodeContext.Language.

func (*CodeInterpreter) ExecuteInContext

func (ci *CodeInterpreter) ExecuteInContext(ctx context.Context, contextID, language, code string, handlers *ExecutionHandlers) (*Execution, error)

ExecuteInContext runs code in an existing context (for state persistence).

type CodeInterpreterCreateOptions

type CodeInterpreterCreateOptions struct {
	// Image overrides the default code-interpreter image.
	Image string

	// Entrypoint overrides the default code-interpreter entrypoint.
	Entrypoint []string

	// ResourceLimits for the sandbox. Defaults to DefaultResourceLimits.
	ResourceLimits ResourceLimits

	// TimeoutSeconds is the sandbox TTL. Defaults to 900 (15 min).
	TimeoutSeconds *int

	// Env variables injected into the sandbox.
	Env map[string]string

	// Metadata for filtering and tagging.
	Metadata map[string]string

	// SkipHealthCheck skips the WaitUntilReady call.
	SkipHealthCheck bool

	// ReadyTimeout overrides the default ready timeout.
	ReadyTimeout time.Duration

	// HealthCheckInterval overrides the default polling interval.
	HealthCheckInterval time.Duration
}

CodeInterpreterCreateOptions configures code interpreter creation.

type CommandLogsResponse

type CommandLogsResponse struct {
	Output string
	Cursor int64
}

CommandLogsResponse contains the stdout/stderr output and cursor for incremental log polling.

type CommandStatusResponse

type CommandStatusResponse struct {
	ID         string     `json:"id"`
	Content    string     `json:"content"`
	Running    bool       `json:"running"`
	ExitCode   *int32     `json:"exit_code,omitempty"`
	Error      string     `json:"error,omitempty"`
	StartedAt  time.Time  `json:"started_at"`
	FinishedAt *time.Time `json:"finished_at,omitempty"`
}

CommandStatusResponse contains the status of a command execution.

type ConnectionConfig

type ConnectionConfig struct {
	// Domain is the server address (e.g. "localhost:8080").
	// Falls back to OPEN_SANDBOX_DOMAIN env var, then DefaultDomain.
	Domain string

	// Protocol is "http" or "https".
	// Falls back to OPEN_SANDBOX_PROTOCOL env var, then DefaultProtocol.
	Protocol string

	// APIKey is the authentication token.
	// Falls back to OPEN_SANDBOX_API_KEY env var.
	APIKey string

	// UseServerProxy routes execd/egress requests through the sandbox server
	// instead of connecting directly to the sandbox endpoint.
	UseServerProxy bool

	// RequestTimeout is the timeout for non-streaming HTTP requests.
	// Zero means no timeout. Defaults to DefaultRequestTimeout.
	RequestTimeout time.Duration

	// Headers are custom HTTP headers added to all requests.
	Headers map[string]string

	// HTTPClient is an optional custom HTTP client. If nil, a default is created.
	HTTPClient *http.Client

	// AuthHeader overrides the default lifecycle auth header name.
	// Default is "OPEN-SANDBOX-API-KEY". Use "X-API-Key" for proxied deployments.
	AuthHeader string

	// Retry enables automatic retry with exponential backoff for transient
	// errors. Defaults to retrying 429/502/503/504; override
	// RetryConfig.RetryableStatusCodes for custom policies. If nil, requests
	// are not retried.
	// Use DefaultRetryConfig() for sensible defaults.
	Retry *RetryConfig

	// Transport configures HTTP connection pooling. If nil and HTTPClient
	// is also nil, the SDK uses DefaultTransport().
	// Use DefaultTransportConfig() for tuned pool settings.
	Transport *TransportConfig

	// EndpointHostRewrite maps hostnames returned by the server in endpoint
	// URLs to replacement hostnames. This is needed when the server runs
	// inside Docker and returns "host.docker.internal" which is not
	// resolvable from the host machine.
	// Example: map[string]string{"host.docker.internal": "localhost"}
	EndpointHostRewrite map[string]string

	// EndpointCacheTTL is how long a cached endpoint stays valid.
	// Zero means DefaultEndpointCacheTTL (600s).
	EndpointCacheTTL time.Duration

	// EndpointCacheSize is the maximum number of cached endpoints.
	// Zero means DefaultEndpointCacheSize (1024).
	EndpointCacheSize int

	// EndpointCacheDisabled disables endpoint caching entirely.
	EndpointCacheDisabled bool
}

ConnectionConfig holds the configuration for connecting to an OpenSandbox server.

func (*ConnectionConfig) GetAPIKey

func (c *ConnectionConfig) GetAPIKey() string

GetAPIKey returns the configured API key, falling back to env var.

func (*ConnectionConfig) GetAuthHeader

func (c *ConnectionConfig) GetAuthHeader() string

GetAuthHeader returns the auth header name for lifecycle requests.

func (*ConnectionConfig) GetBaseURL

func (c *ConnectionConfig) GetBaseURL() string

GetBaseURL returns the lifecycle API base URL (e.g. "http://localhost:8080"). Note: this does NOT append /v1. lifecycleClient() appends /v1 when creating the lifecycle client.

func (*ConnectionConfig) GetDomain

func (c *ConnectionConfig) GetDomain() string

GetDomain returns the configured domain, falling back to env var and default.

func (*ConnectionConfig) GetProtocol

func (c *ConnectionConfig) GetProtocol() string

GetProtocol returns the configured protocol, falling back to env var and default.

func (*ConnectionConfig) GetRequestTimeout

func (c *ConnectionConfig) GetRequestTimeout() time.Duration

GetRequestTimeout returns the request timeout, defaulting to DefaultRequestTimeout.

func (*ConnectionConfig) RewriteEndpointURL

func (c *ConnectionConfig) RewriteEndpointURL(endpointURL string) string

RewriteEndpointURL applies EndpointHostRewrite rules to an endpoint URL returned by the server. This handles cases like Docker's "host.docker.internal" being unreachable from the host machine.

type CreateContextRequest

type CreateContextRequest struct {
	Language string `json:"language"`
}

CreateContextRequest is the request body for creating a code execution context.

type CreateIsolatedSessionRequest added in v1.0.4

type CreateIsolatedSessionRequest struct {
	Workspace          IsolatedWorkspaceSpec `json:"workspace"`
	Profile            string                `json:"profile,omitempty"`
	ExtraWritable      []string              `json:"extra_writable,omitempty"`
	ShareNet           *bool                 `json:"share_net,omitempty"`
	EnvPassthrough     *EnvPassthroughSpec   `json:"env_passthrough,omitempty"`
	Uid                *uint32               `json:"uid,omitempty"`
	Gid                *uint32               `json:"gid,omitempty"`
	IdleTimeoutSeconds int                   `json:"idle_timeout_seconds,omitempty"`
}

CreateIsolatedSessionRequest is the request body for creating an isolated session.

type CreateSandboxRequest

type CreateSandboxRequest struct {
	Image            *ImageSpec             `json:"image,omitempty"`
	SnapshotID       string                 `json:"snapshotId,omitempty"`
	Timeout          *int                   `json:"timeout,omitempty"`
	ResourceLimits   ResourceLimits         `json:"resourceLimits"`
	ResourceRequests ResourceLimits         `json:"resourceRequests,omitempty"`
	Env              map[string]string      `json:"env,omitempty"`
	SecureAccess     bool                   `json:"secureAccess,omitempty"`
	Metadata         map[string]string      `json:"metadata,omitempty"`
	Entrypoint       []string               `json:"entrypoint,omitempty"`
	NetworkPolicy    *NetworkPolicy         `json:"networkPolicy,omitempty"`
	CredentialProxy  *CredentialProxyConfig `json:"credentialProxy,omitempty"`
	Volumes          []Volume               `json:"volumes,omitempty"`
	Extensions       map[string]string      `json:"extensions,omitempty"`
	Platform         *PlatformSpec          `json:"platform,omitempty"`
}

CreateSandboxRequest is the request body for creating a new sandbox.

type CreateSessionRequest

type CreateSessionRequest struct {
	Cwd string `json:"cwd,omitempty"`
}

CreateSessionRequest is the optional request body for creating a bash session.

type CreateSnapshotRequest added in v1.0.1

type CreateSnapshotRequest struct {
	Name string `json:"name,omitempty"`
}

type Credential added in v1.0.3

type Credential struct {
	Name   string                 `json:"name"`
	Source InlineCredentialSource `json:"source"`
}

Credential is a sandbox-local Credential Vault credential create/update model.

type CredentialAuth added in v1.0.3

type CredentialAuth struct {
	Type       CredentialAuthType  `json:"type"`
	Credential string              `json:"credential,omitempty"`
	Name       string              `json:"name,omitempty"`
	Headers    []CustomHeaderEntry `json:"headers,omitempty"`
}

CredentialAuth configures how a binding injects credential material into matching outbound requests.

type CredentialAuthMetadata added in v1.0.3

type CredentialAuthMetadata struct {
	Type string `json:"type"`
	Name string `json:"name,omitempty"`
}

CredentialAuthMetadata is sanitized auth metadata returned by Credential Vault. It intentionally does not include credential references or values.

type CredentialAuthType added in v1.0.3

type CredentialAuthType string

CredentialAuthType is the Credential Vault auth discriminator.

const (
	CredentialAuthBearer        CredentialAuthType = "bearer"
	CredentialAuthBasic         CredentialAuthType = "basic"
	CredentialAuthAPIKey        CredentialAuthType = "apiKey"
	CredentialAuthCustomHeaders CredentialAuthType = "customHeaders"
)

type CredentialBinding added in v1.0.3

type CredentialBinding struct {
	Name  string          `json:"name"`
	Match CredentialMatch `json:"match"`
	Auth  CredentialAuth  `json:"auth"`
}

CredentialBinding is a sandbox-local Credential Vault binding create/update model.

type CredentialBindingListResponse added in v1.0.3

type CredentialBindingListResponse struct {
	Revision int                         `json:"revision"`
	Bindings []CredentialBindingMetadata `json:"bindings"`
}

CredentialBindingListResponse is the binding metadata list response.

type CredentialBindingMetadata added in v1.0.3

type CredentialBindingMetadata struct {
	Name     string                  `json:"name"`
	Revision int                     `json:"revision"`
	Match    *CredentialMatch        `json:"match,omitempty"`
	Auth     *CredentialAuthMetadata `json:"auth,omitempty"`
}

CredentialBindingMetadata is sanitized binding metadata returned by Credential Vault.

type CredentialBindingMutationSet added in v1.0.3

type CredentialBindingMutationSet struct {
	Add     []CredentialBinding `json:"add,omitempty"`
	Replace []CredentialBinding `json:"replace,omitempty"`
	Delete  []string            `json:"delete,omitempty"`
}

CredentialBindingMutationSet describes atomic binding changes for a vault patch.

type CredentialListResponse added in v1.0.3

type CredentialListResponse struct {
	Revision    int                  `json:"revision"`
	Credentials []CredentialMetadata `json:"credentials"`
}

CredentialListResponse is the credential metadata list response.

type CredentialMatch added in v1.0.3

type CredentialMatch struct {
	Schemes []CredentialScheme `json:"schemes,omitempty"`
	// Deprecated: Ports is ignored; port is derived from Schemes (https→443, http→80).
	Ports   []int    `json:"ports,omitempty"`
	Hosts   []string `json:"hosts"`
	Methods []string `json:"methods,omitempty"`
	Paths   []string `json:"paths,omitempty"`
}

CredentialMatch selects outbound requests where a Credential Vault binding applies.

type CredentialMetadata added in v1.0.3

type CredentialMetadata struct {
	Name       string `json:"name"`
	SourceType string `json:"sourceType"`
	Revision   int    `json:"revision"`
}

CredentialMetadata is sanitized credential metadata returned by Credential Vault. It intentionally does not include source values.

type CredentialMutationSet added in v1.0.3

type CredentialMutationSet struct {
	Add     []Credential `json:"add,omitempty"`
	Replace []Credential `json:"replace,omitempty"`
	Delete  []string     `json:"delete,omitempty"`
}

CredentialMutationSet describes atomic credential changes for a vault patch.

type CredentialProxyConfig added in v1.0.3

type CredentialProxyConfig struct {
	Enabled bool `json:"enabled"`
}

CredentialProxyConfig enables Credential Vault transparent proxy support at sandbox startup.

type CredentialScheme added in v1.0.3

type CredentialScheme string

CredentialScheme is a request scheme matched by a Credential Vault binding.

const (
	CredentialSchemeHTTPS CredentialScheme = "https"
	CredentialSchemeHTTP  CredentialScheme = "http"
)

type CredentialSourceType added in v1.0.3

type CredentialSourceType string

CredentialSourceType is the credential source discriminator.

const (
	// CredentialSourceInline carries write-only inline credential material.
	CredentialSourceInline CredentialSourceType = "inline"
)

type CredentialVaultCreateRequest added in v1.0.3

type CredentialVaultCreateRequest struct {
	Credentials []Credential        `json:"credentials"`
	Bindings    []CredentialBinding `json:"bindings"`
}

CredentialVaultCreateRequest creates the initial sandbox-local Credential Vault revision.

type CredentialVaultPatchRequest added in v1.0.3

type CredentialVaultPatchRequest struct {
	ExpectedRevision *int                          `json:"expectedRevision,omitempty"`
	Credentials      *CredentialMutationSet        `json:"credentials,omitempty"`
	Bindings         *CredentialBindingMutationSet `json:"bindings,omitempty"`
}

CredentialVaultPatchRequest atomically mutates credentials and bindings. If ExpectedRevision is set, the sidecar applies it as an optimistic concurrency guard.

type CredentialVaultState added in v1.0.3

type CredentialVaultState struct {
	Revision    int                         `json:"revision"`
	Credentials []CredentialMetadata        `json:"credentials"`
	Bindings    []CredentialBindingMetadata `json:"bindings"`
}

CredentialVaultState is sanitized Credential Vault state.

type CustomHeaderEntry added in v1.0.3

type CustomHeaderEntry struct {
	Name       string `json:"name"`
	Credential string `json:"credential"`
}

CustomHeaderEntry describes one custom header injection rule.

type DefaultSandboxPool added in v1.0.4

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

DefaultSandboxPool implements SandboxPool.

func (*DefaultSandboxPool) Acquire added in v1.0.4

func (p *DefaultSandboxPool) Acquire(ctx context.Context, opts AcquireOptions) (*Sandbox, error)

Acquire takes or creates a sandbox from the pool.

func (*DefaultSandboxPool) ReleaseAllIdle added in v1.0.4

func (p *DefaultSandboxPool) ReleaseAllIdle(ctx context.Context) (int, error)

ReleaseAllIdle drains all idle sandboxes and kills them.

func (*DefaultSandboxPool) Resize added in v1.0.4

func (p *DefaultSandboxPool) Resize(ctx context.Context, newMaxIdle int) error

Resize dynamically changes the idle target. The new value is persisted to the state store and updated locally so that a subsequent Start() (after stop/restart) uses the latest value.

func (*DefaultSandboxPool) Shutdown added in v1.0.4

func (p *DefaultSandboxPool) Shutdown(ctx context.Context, graceful bool) error

Shutdown stops the pool and releases idle sandboxes.

func (*DefaultSandboxPool) Snapshot added in v1.0.4

func (p *DefaultSandboxPool) Snapshot(ctx context.Context) (*PoolSnapshot, error)

Snapshot returns a point-in-time snapshot of pool state.

func (*DefaultSandboxPool) SnapshotIdleEntries added in v1.0.4

func (p *DefaultSandboxPool) SnapshotIdleEntries(ctx context.Context) ([]IdleEntry, error)

SnapshotIdleEntries returns the current idle entries.

func (*DefaultSandboxPool) Start added in v1.0.4

func (p *DefaultSandboxPool) Start(ctx context.Context) error

Start begins the background reconciliation loop.

type DownloadFileOptions added in v1.0.3

type DownloadFileOptions struct {
	// Offset is the starting line number (1-based). Mutually exclusive with Range header.
	Offset int
	// Limit is the number of lines to return. Mutually exclusive with Range header.
	Limit int
}

DownloadFileOptions configures line-based reading for DownloadFile.

type EgressClient

type EgressClient struct {
	*Client
}

EgressClient provides methods for the OpenSandbox Egress API. It connects to the egress sidecar endpoint running inside a specific sandbox.

func NewEgressClient

func NewEgressClient(baseURL, authToken string, opts ...Option) *EgressClient

NewEgressClient creates a new EgressClient. baseURL is the sandbox-specific egress sidecar endpoint (e.g. "http://localhost:18080"). authToken is the value for the OPENSANDBOX-EGRESS-AUTH header; pass "" if the sidecar does not require authentication.

func (*EgressClient) CreateCredentialVault added in v1.0.3

func (c *EgressClient) CreateCredentialVault(ctx context.Context, req CredentialVaultCreateRequest) (*CredentialVaultState, error)

CreateCredentialVault creates the initial sandbox-local Credential Vault revision and activates it in Credential Proxy.

func (*EgressClient) DeleteCredentialVault added in v1.0.3

func (c *EgressClient) DeleteCredentialVault(ctx context.Context) error

DeleteCredentialVault deletes the sandbox-local Credential Vault.

func (*EgressClient) DeletePolicy added in v1.0.2

func (c *EgressClient) DeletePolicy(ctx context.Context, targets []string) (*PolicyStatusResponse, error)

DeletePolicy removes egress rules matching the given targets from the current policy. Each target is a FQDN or wildcard domain. Targets not present in the policy are silently ignored (idempotent). The current defaultAction is preserved.

func (*EgressClient) GetCredentialVault added in v1.0.3

func (c *EgressClient) GetCredentialVault(ctx context.Context) (*CredentialVaultState, error)

GetCredentialVault returns sanitized Credential Vault state. Plaintext credential values are never part of the returned model.

func (*EgressClient) GetCredentialVaultBinding added in v1.0.3

func (c *EgressClient) GetCredentialVaultBinding(ctx context.Context, name string) (*CredentialBindingMetadata, error)

GetCredentialVaultBinding returns sanitized metadata for one binding.

func (*EgressClient) GetCredentialVaultCredential added in v1.0.3

func (c *EgressClient) GetCredentialVaultCredential(ctx context.Context, name string) (*CredentialMetadata, error)

GetCredentialVaultCredential returns sanitized metadata for one credential.

func (*EgressClient) GetPolicy

func (c *EgressClient) GetPolicy(ctx context.Context) (*PolicyStatusResponse, error)

GetPolicy returns the currently enforced egress policy and sidecar metadata.

func (*EgressClient) ListCredentialVaultBindings added in v1.0.3

func (c *EgressClient) ListCredentialVaultBindings(ctx context.Context) (*CredentialBindingListResponse, error)

ListCredentialVaultBindings returns sanitized binding metadata.

func (*EgressClient) ListCredentialVaultCredentials added in v1.0.3

func (c *EgressClient) ListCredentialVaultCredentials(ctx context.Context) (*CredentialListResponse, error)

ListCredentialVaultCredentials returns sanitized credential metadata.

func (*EgressClient) PatchCredentialVault added in v1.0.3

func (c *EgressClient) PatchCredentialVault(ctx context.Context, req CredentialVaultPatchRequest) (*CredentialVaultState, error)

PatchCredentialVault atomically mutates sandbox-local credentials and bindings.

func (*EgressClient) PatchPolicy

func (c *EgressClient) PatchPolicy(ctx context.Context, rules []NetworkRule) (*PolicyStatusResponse, error)

PatchPolicy merges the given network rules into the current egress policy. Existing rules remain unless overridden. Rule conflict behavior is determined by the server.

type Endpoint

type Endpoint struct {
	Endpoint string            `json:"endpoint"`
	Headers  map[string]string `json:"headers,omitempty"`
}

Endpoint describes a public access endpoint for a service running inside a sandbox.

type EndpointCache added in v1.0.4

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

EndpointCache is a thread-safe LRU+TTL cache for sandbox endpoints.

func NewEndpointCache added in v1.0.4

func NewEndpointCache(maxSize int, ttl time.Duration) *EndpointCache

NewEndpointCache creates a cache with the given max size and TTL. If maxSize <= 0, DefaultEndpointCacheSize is used. If ttl <= 0, DefaultEndpointCacheTTL is used.

func (*EndpointCache) Get added in v1.0.4

func (c *EndpointCache) Get(key endpointCacheKey) (*Endpoint, bool)

Get retrieves a cached endpoint. Returns nil, false on miss or expiry.

func (*EndpointCache) GetOrFetch added in v1.0.4

func (c *EndpointCache) GetOrFetch(ctx context.Context, key endpointCacheKey, fetch func() (*Endpoint, error)) (*Endpoint, error)

GetOrFetch checks cache, deduplicates inflight requests via singleflight, and calls fetch on miss. The caller's context is respected: if ctx is cancelled while waiting for a shared inflight request, the caller returns immediately with the context error (the shared fetch continues for other waiters).

func (*EndpointCache) Invalidate added in v1.0.4

func (c *EndpointCache) Invalidate(sandboxID string)

Invalidate removes all cached and inflight entries for the given sandbox ID.

func (*EndpointCache) Len added in v1.0.4

func (c *EndpointCache) Len() int

Len returns the number of entries in the cache.

func (*EndpointCache) Put added in v1.0.4

func (c *EndpointCache) Put(key endpointCacheKey, ep *Endpoint)

Put stores an endpoint in the cache, evicting LRU entries if at capacity.

type EnvPassthroughSpec added in v1.0.4

type EnvPassthroughSpec struct {
	Mode string   `json:"mode,omitempty"` // "allow" | "deny"
	Keys []string `json:"keys,omitempty"`
}

EnvPassthroughSpec controls environment variable passthrough.

type ErrorResponse

type ErrorResponse struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

ErrorResponse is the standard error response for non-2xx HTTP responses.

type EventHandler

type EventHandler func(event StreamEvent) error

EventHandler is a callback invoked for each SSE event received from the server. Return a non-nil error to stop processing the stream.

type ExecdClient

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

ExecdClient provides access to the OpenSandbox Execd API for code execution, command execution, file operations, and system metrics.

func NewExecdClient

func NewExecdClient(baseURL, accessToken string, opts ...Option) *ExecdClient

NewExecdClient creates a new ExecdClient for the given base URL and access token.

func (*ExecdClient) CreateContext

func (e *ExecdClient) CreateContext(ctx context.Context, req CreateContextRequest) (*CodeContext, error)

CreateContext creates a new code execution context and returns its context ID.

func (*ExecdClient) CreateDirectory

func (e *ExecdClient) CreateDirectory(ctx context.Context, path string, mode int) error

CreateDirectory creates a directory at the given path with the specified mode. Parent directories are created as needed (like mkdir -p). Mode is specified as octal digits in decimal form (e.g. 755 for rwxr-xr-x). Use OctalMode() to convert Go os.FileMode to the expected format.

func (*ExecdClient) CreateSession

func (e *ExecdClient) CreateSession(ctx context.Context) (*Session, error)

CreateSession creates a new bash session and returns it with a session ID.

func (*ExecdClient) DeleteContext

func (e *ExecdClient) DeleteContext(ctx context.Context, contextID string) error

DeleteContext deletes a code execution context by ID.

func (*ExecdClient) DeleteContextsByLanguage

func (e *ExecdClient) DeleteContextsByLanguage(ctx context.Context, language string) error

DeleteContextsByLanguage deletes all code execution contexts for the given language.

func (*ExecdClient) DeleteDirectory

func (e *ExecdClient) DeleteDirectory(ctx context.Context, path string) error

DeleteDirectory deletes a directory and all its contents recursively.

func (*ExecdClient) DeleteFiles

func (e *ExecdClient) DeleteFiles(ctx context.Context, paths []string) error

DeleteFiles deletes one or more files from the sandbox.

func (*ExecdClient) DeleteSession

func (e *ExecdClient) DeleteSession(ctx context.Context, sessionID string) error

DeleteSession deletes a bash session by ID.

func (*ExecdClient) DownloadFile

func (e *ExecdClient) DownloadFile(ctx context.Context, remotePath string, rangeHeader string, opts ...DownloadFileOptions) (io.ReadCloser, error)

DownloadFile downloads a file from the sandbox. The caller must close the returned io.ReadCloser. Pass rangeHeader (e.g. "bytes=0-1023") for partial content, or empty string for the full file. Use opts for line-based reading.

func (*ExecdClient) ExecuteCode

func (e *ExecdClient) ExecuteCode(ctx context.Context, req RunCodeRequest, handler EventHandler) error

ExecuteCode executes code in the specified context and streams output events via SSE. The handler is called for each event received from the server.

func (*ExecdClient) GetCommandLogs

func (e *ExecdClient) GetCommandLogs(ctx context.Context, commandID string, cursor *int64) (*CommandLogsResponse, error)

GetCommandLogs returns stdout/stderr for a background command. Pass cursor=-1 or cursor=0 for the full log. The returned CommandLogsResponse includes the tail cursor for incremental polling.

func (*ExecdClient) GetCommandStatus

func (e *ExecdClient) GetCommandStatus(ctx context.Context, commandID string) (*CommandStatusResponse, error)

GetCommandStatus returns the current status of a command by ID.

func (*ExecdClient) GetContext

func (e *ExecdClient) GetContext(ctx context.Context, contextID string) (*CodeContext, error)

GetContext retrieves the details of an existing code execution context by ID.

func (*ExecdClient) GetFileInfo

func (e *ExecdClient) GetFileInfo(ctx context.Context, path string) (map[string]FileInfo, error)

GetFileInfo retrieves metadata for the file at the given path.

func (*ExecdClient) GetMetrics

func (e *ExecdClient) GetMetrics(ctx context.Context) (*Metrics, error)

GetMetrics retrieves current system resource metrics.

func (*ExecdClient) InterruptCode

func (e *ExecdClient) InterruptCode(ctx context.Context, sessionID string) error

InterruptCode interrupts the currently running code execution.

func (*ExecdClient) InterruptCommand

func (e *ExecdClient) InterruptCommand(ctx context.Context, sessionID string) error

InterruptCommand interrupts the currently running command execution.

func (*ExecdClient) IsolatedCapabilities added in v1.0.4

func (e *ExecdClient) IsolatedCapabilities(ctx context.Context) (*IsolatedCapabilities, error)

IsolatedCapabilities retrieves isolation capabilities.

func (*ExecdClient) IsolatedCreate added in v1.0.4

IsolatedCreate creates an isolated bash session.

func (*ExecdClient) IsolatedDelete added in v1.0.4

func (e *ExecdClient) IsolatedDelete(ctx context.Context, sessionID string) error

IsolatedDelete deletes an isolated session.

func (*ExecdClient) IsolatedGet added in v1.0.4

func (e *ExecdClient) IsolatedGet(ctx context.Context, sessionID string) (*IsolatedSessionState, error)

IsolatedGet retrieves the state of an isolated session.

func (*ExecdClient) IsolatedRun added in v1.0.4

func (e *ExecdClient) IsolatedRun(ctx context.Context, sessionID string, req IsolatedRunRequest, handler EventHandler) error

IsolatedRun runs code in an isolated session, streaming output via SSE.

func (*ExecdClient) ListContexts

func (e *ExecdClient) ListContexts(ctx context.Context, language string) ([]CodeContext, error)

ListContexts returns all active code execution contexts for the given language.

func (*ExecdClient) ListDirectory added in v1.0.3

func (e *ExecdClient) ListDirectory(ctx context.Context, path string) ([]FileInfo, error)

ListDirectory lists the immediate children of the given directory using the server-side default depth (1). Use ListDirectoryWithDepth to override.

func (*ExecdClient) ListDirectoryWithDepth added in v1.0.3

func (e *ExecdClient) ListDirectoryWithDepth(ctx context.Context, path string, depth int) ([]FileInfo, error)

ListDirectoryWithDepth lists directory contents up to the given depth. depth=0 returns an empty slice (the directory itself is not listed). depth=1 returns the immediate children. Larger values include descendants up to that many levels below path. Negative values are rejected by the server.

func (*ExecdClient) MoveFiles

func (e *ExecdClient) MoveFiles(ctx context.Context, req MoveRequest) error

MoveFiles renames or moves files to new paths.

func (*ExecdClient) Ping

func (e *ExecdClient) Ping(ctx context.Context) error

Ping verifies that the Execd server is running and responsive.

func (*ExecdClient) ReplaceInFiles

func (e *ExecdClient) ReplaceInFiles(ctx context.Context, req ReplaceRequest) error

ReplaceInFiles performs text replacement in the specified files.

func (*ExecdClient) ReplaceInFilesDetailed added in v1.0.3

func (e *ExecdClient) ReplaceInFilesDetailed(ctx context.Context, req ReplaceRequest) (ReplaceResponse, error)

ReplaceInFilesDetailed performs text replacement and returns per-file replacement counts.

func (*ExecdClient) RunCommand

func (e *ExecdClient) RunCommand(ctx context.Context, req RunCommandRequest, handler EventHandler) error

RunCommand executes a shell command and streams output events via SSE.

func (*ExecdClient) RunInSession

func (e *ExecdClient) RunInSession(ctx context.Context, sessionID string, req RunInSessionRequest, handler EventHandler) error

RunInSession executes a command in an existing bash session and streams output events via SSE.

func (*ExecdClient) SearchFiles

func (e *ExecdClient) SearchFiles(ctx context.Context, dir string, pattern string) ([]FileInfo, error)

SearchFiles searches for files matching a glob pattern within a directory.

func (*ExecdClient) SetPermissions

func (e *ExecdClient) SetPermissions(ctx context.Context, req PermissionsRequest) error

SetPermissions changes permissions, owner, and group for the specified files.

func (*ExecdClient) UploadFile

func (e *ExecdClient) UploadFile(ctx context.Context, file io.Reader, opts UploadFileOptions) error

UploadFile uploads a single file to the sandbox.

func (*ExecdClient) UploadFiles added in v1.0.1

func (e *ExecdClient) UploadFiles(ctx context.Context, entries []UploadFileEntry) error

UploadFiles uploads one or more files to the sandbox in a single multipart request.

func (*ExecdClient) WatchMetrics

func (e *ExecdClient) WatchMetrics(ctx context.Context, handler EventHandler) error

WatchMetrics streams system metrics in real-time via SSE. The handler receives a new event approximately every second until the context is cancelled or an error occurs.

type Execution

type Execution struct {
	// ID is the execution/command identifier from the init event.
	ID string

	// Stdout contains all stdout messages in order.
	Stdout []OutputMessage

	// Stderr contains all stderr messages in order.
	Stderr []OutputMessage

	// Results contains execution results (for code interpreter).
	Results []ExecutionResult

	// Error is set if the execution failed.
	Error *ExecutionError

	// Complete is set when execution finishes.
	Complete *ExecutionComplete

	// ExitCode is the process exit code. Nil if not available.
	ExitCode *int
}

Execution is the structured result of a command or code execution.

func (*Execution) Text

func (e *Execution) Text() string

Text returns the combined stdout text.

type ExecutionComplete

type ExecutionComplete struct {
	Timestamp     int64 `json:"timestamp"`
	ExecutionTime int64 `json:"execution_time"`
}

ExecutionComplete represents the completion event from the server.

type ExecutionError

type ExecutionError struct {
	Name      string   `json:"name"`
	Value     string   `json:"value"`
	Timestamp int64    `json:"timestamp"`
	Traceback []string `json:"traceback"`
}

ExecutionError represents an error during code/command execution.

type ExecutionHandlers

type ExecutionHandlers struct {
	OnInit     func(ExecutionInit) error
	OnStdout   func(OutputMessage) error
	OnStderr   func(OutputMessage) error
	OnResult   func(ExecutionResult) error
	OnComplete func(ExecutionComplete) error
	OnError    func(ExecutionError) error

	// SkipAccumulation, when true, prevents stdout/stderr messages from being
	// accumulated in the Execution struct. Messages are still delivered to handlers.
	// Use for long-running executions to prevent unbounded memory growth.
	SkipAccumulation bool
}

ExecutionHandlers provides optional callbacks invoked during streaming execution. Return a non-nil error from any handler to abort the stream.

type ExecutionInit

type ExecutionInit struct {
	ID        string `json:"text"`
	Timestamp int64  `json:"timestamp"`
}

ExecutionInit represents the initialization event from the server.

type ExecutionResult

type ExecutionResult struct {
	// Results holds MIME-type keyed outputs (e.g. "text/plain", "text/html").
	Results   map[string]string `json:"results,omitempty"`
	Timestamp int64             `json:"timestamp"`
}

ExecutionResult represents a result output from code execution. Results maps MIME types to their string representations (e.g. "text/plain" → "4").

func (ExecutionResult) Text

func (r ExecutionResult) Text() string

Text returns the text/plain result, or empty string if not present.

type FileInfo

type FileInfo struct {
	Path       string    `json:"path"`
	Type       string    `json:"type,omitempty"`
	Size       int64     `json:"size"`
	ModifiedAt time.Time `json:"modified_at"`
	CreatedAt  time.Time `json:"created_at"`
	Owner      string    `json:"owner"`
	Group      string    `json:"group"`
	Mode       int       `json:"mode"`
}

FileInfo contains file metadata including path and permissions.

type FileMetadata

type FileMetadata struct {
	Path  string `json:"path"`
	Owner string `json:"owner,omitempty"`
	Group string `json:"group,omitempty"`
	Mode  int    `json:"mode,omitempty"`
}

FileMetadata is the metadata sent alongside file uploads.

type Host

type Host struct {
	Path string `json:"path"`
}

Host represents a host path bind mount backend.

type IdleEntry added in v1.0.4

type IdleEntry struct {
	SandboxID string
	ExpiresAt time.Time
}

IdleEntry represents a sandbox in the idle pool.

type ImageAuth

type ImageAuth struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

ImageAuth holds registry authentication credentials for private images.

type ImageSpec

type ImageSpec struct {
	URI  string     `json:"uri"`
	Auth *ImageAuth `json:"auth,omitempty"`
}

ImageSpec describes the container image used to provision a sandbox.

type InMemoryPoolStateStore added in v1.0.4

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

InMemoryPoolStateStore is a pure in-memory implementation of PoolStateStore. It is safe for concurrent use from multiple goroutines and supports real lock tracking with TTL, making it suitable for unit testing pool logic.

func NewInMemoryPoolStateStore added in v1.0.4

func NewInMemoryPoolStateStore() *InMemoryPoolStateStore

NewInMemoryPoolStateStore creates a new InMemoryPoolStateStore.

func (*InMemoryPoolStateStore) GetMaxIdle added in v1.0.4

func (s *InMemoryPoolStateStore) GetMaxIdle(_ context.Context, poolName string) (int, error)

GetMaxIdle returns the stored maxIdle value for the pool.

func (*InMemoryPoolStateStore) PutIdle added in v1.0.4

func (s *InMemoryPoolStateStore) PutIdle(_ context.Context, poolName string, sandboxID string) error

PutIdle adds a sandbox to the idle pool. Idempotent: if already present, no-op.

func (*InMemoryPoolStateStore) ReapExpiredIdle added in v1.0.4

func (s *InMemoryPoolStateStore) ReapExpiredIdle(_ context.Context, poolName string, now time.Time) error

ReapExpiredIdle removes all fully expired idle entries and rebuilds the queue.

func (*InMemoryPoolStateStore) ReapExpiredIdleWithMinTTL added in v1.0.4

func (s *InMemoryPoolStateStore) ReapExpiredIdleWithMinTTL(_ context.Context, poolName string, now time.Time, minRemaining time.Duration) (*ReapResult, error)

ReapExpiredIdleWithMinTTL removes expired and near-expiry idle entries. Returns IDs of entries that were still alive but below the TTL threshold.

func (*InMemoryPoolStateStore) ReleasePrimaryLock added in v1.0.4

func (s *InMemoryPoolStateStore) ReleasePrimaryLock(_ context.Context, poolName string, ownerID string) error

ReleasePrimaryLock releases the primary lock. Only succeeds if caller is the current owner.

func (*InMemoryPoolStateStore) RemoveIdle added in v1.0.4

func (s *InMemoryPoolStateStore) RemoveIdle(_ context.Context, poolName string, sandboxID string) error

RemoveIdle removes a sandbox from the idle pool map. The queue is cleaned up lazily during take operations. Idempotent.

func (*InMemoryPoolStateStore) RenewPrimaryLock added in v1.0.4

func (s *InMemoryPoolStateStore) RenewPrimaryLock(_ context.Context, poolName string, ownerID string, ttl time.Duration) (bool, error)

RenewPrimaryLock extends the lock TTL. Only succeeds if caller is the current owner and the lock has not expired.

func (*InMemoryPoolStateStore) SetIdleEntryTTL added in v1.0.4

func (s *InMemoryPoolStateStore) SetIdleEntryTTL(_ context.Context, poolName string, ttl time.Duration) error

SetIdleEntryTTL persists the idle entry TTL for the pool.

func (*InMemoryPoolStateStore) SetMaxIdle added in v1.0.4

func (s *InMemoryPoolStateStore) SetMaxIdle(_ context.Context, poolName string, maxIdle int) error

SetMaxIdle persists the maxIdle value for the pool.

func (*InMemoryPoolStateStore) SnapshotCounters added in v1.0.4

func (s *InMemoryPoolStateStore) SnapshotCounters(_ context.Context, poolName string) (*StoreCounters, error)

SnapshotCounters returns current pool counters, excluding expired entries.

func (*InMemoryPoolStateStore) SnapshotIdleEntries added in v1.0.4

func (s *InMemoryPoolStateStore) SnapshotIdleEntries(_ context.Context, poolName string) ([]IdleEntry, error)

SnapshotIdleEntries returns all current idle entries in FIFO order, excluding expired entries.

func (*InMemoryPoolStateStore) TryAcquirePrimaryLock added in v1.0.4

func (s *InMemoryPoolStateStore) TryAcquirePrimaryLock(_ context.Context, poolName string, ownerID string, ttl time.Duration) (bool, error)

TryAcquirePrimaryLock attempts to acquire the primary lock for the pool. Succeeds if the lock is unheld or expired.

func (*InMemoryPoolStateStore) TryTakeIdle added in v1.0.4

func (s *InMemoryPoolStateStore) TryTakeIdle(_ context.Context, poolName string) (string, error)

TryTakeIdle atomically takes the oldest idle sandbox from the pool. Expired entries are silently dropped inline.

func (*InMemoryPoolStateStore) TryTakeIdleWithMinTTL added in v1.0.4

func (s *InMemoryPoolStateStore) TryTakeIdleWithMinTTL(_ context.Context, poolName string, minRemaining time.Duration) (*TakeIdleResult, error)

TryTakeIdleWithMinTTL takes the oldest idle sandbox that has at least minRemaining TTL left. Entries alive but below threshold are returned in DiscardedAliveSandboxIDs.

type InlineCredentialSource added in v1.0.3

type InlineCredentialSource struct {
	Type  CredentialSourceType `json:"type"`
	Value string               `json:"value"`
}

InlineCredentialSource contains write-only credential material. Values sent in this model are never returned by Credential Vault state endpoints.

func (InlineCredentialSource) MarshalJSON added in v1.0.3

func (s InlineCredentialSource) MarshalJSON() ([]byte, error)

MarshalJSON defaults the only supported source type so callers can use the natural zero-value form InlineCredentialSource{Value: secret}.

type InvalidArgumentError

type InvalidArgumentError struct {
	Field   string
	Message string
}

InvalidArgumentError is returned for invalid SDK arguments.

func (*InvalidArgumentError) Error

func (e *InvalidArgumentError) Error() string

type IsolatedCapabilities added in v1.0.4

type IsolatedCapabilities struct {
	Available       bool   `json:"available"`
	Isolator        string `json:"isolator,omitempty"`
	Version         string `json:"version,omitempty"`
	Message         string `json:"message,omitempty"`
	CommitSupported bool   `json:"commit_supported"`
	DiffSupported   bool   `json:"diff_supported"`
}

IsolatedCapabilities reports isolation capabilities.

type IsolatedRunRequest added in v1.0.4

type IsolatedRunRequest struct {
	Code           string            `json:"code"`
	Envs           map[string]string `json:"envs,omitempty"`
	TimeoutSeconds int               `json:"timeout_seconds,omitempty"`
}

IsolatedRunRequest is the request body for running code in an isolated session.

type IsolatedSessionInfo added in v1.0.4

type IsolatedSessionInfo struct {
	SessionID string    `json:"session_id"`
	CreatedAt time.Time `json:"created_at"`
}

IsolatedSessionInfo is the response from creating an isolated session.

type IsolatedSessionState added in v1.0.4

type IsolatedSessionState struct {
	Status               string    `json:"status"`
	CreatedAt            time.Time `json:"created_at"`
	LastRunAt            time.Time `json:"last_run_at"`
	IdleRemainingSeconds *int      `json:"idle_remaining_seconds,omitempty"`
}

IsolatedSessionState represents the current state of an isolated session.

type IsolatedWorkspaceSpec added in v1.0.4

type IsolatedWorkspaceSpec struct {
	Path string `json:"path"`
	Mode string `json:"mode,omitempty"` // "rw" | "overlay" | "ro"
}

IsolatedWorkspaceSpec describes the workspace bind configuration.

type IsolationSession added in v1.0.4

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

IsolationSession is a handle to a single isolated bash session.

func (*IsolationSession) Delete added in v1.0.4

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

Delete deletes this isolated session.

func (*IsolationSession) Files added in v1.0.4

func (s *IsolationSession) Files() *ExecdClient

Files returns an ExecdClient scoped to this session's file endpoints. File operations (GetFileInfo, UploadFile, DownloadFile, etc.) are automatically routed to /v1/isolated/session/{id}/files/*.

func (*IsolationSession) Get added in v1.0.4

Get retrieves the current state of this session.

func (*IsolationSession) Info added in v1.0.4

Info returns the session creation info.

func (*IsolationSession) Run added in v1.0.4

Run executes code in this isolated session.

func (*IsolationSession) SessionID added in v1.0.4

func (s *IsolationSession) SessionID() string

SessionID returns the session identifier.

type LifecycleClient

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

LifecycleClient provides methods for the OpenSandbox Lifecycle API.

func NewLifecycleClient

func NewLifecycleClient(baseURL, apiKey string, opts ...Option) *LifecycleClient

NewLifecycleClient creates a new LifecycleClient. baseURL should include the version prefix (e.g. "http://localhost:8080/v1").

func NewLifecycleClientWithCache added in v1.0.4

func NewLifecycleClientWithCache(baseURL, apiKey string, cache *EndpointCache, opts ...Option) *LifecycleClient

NewLifecycleClientWithCache creates a LifecycleClient with custom cache settings.

func (*LifecycleClient) CreateSandbox

func (c *LifecycleClient) CreateSandbox(ctx context.Context, req CreateSandboxRequest) (*SandboxInfo, error)

CreateSandbox creates a new sandbox from a container image.

func (*LifecycleClient) CreateSnapshot added in v1.0.1

func (c *LifecycleClient) CreateSnapshot(ctx context.Context, sandboxID string, req CreateSnapshotRequest) (*SnapshotInfo, error)

CreateSnapshot creates a snapshot from the given sandbox.

func (*LifecycleClient) DeleteSandbox

func (c *LifecycleClient) DeleteSandbox(ctx context.Context, id string) error

DeleteSandbox deletes a sandbox, scheduling it for termination.

func (*LifecycleClient) DeleteSnapshot added in v1.0.1

func (c *LifecycleClient) DeleteSnapshot(ctx context.Context, id string) error

DeleteSnapshot deletes a snapshot by ID.

func (*LifecycleClient) GetEndpoint

func (c *LifecycleClient) GetEndpoint(ctx context.Context, sandboxID string, port int, useServerProxy *bool) (*Endpoint, error)

GetEndpoint retrieves the public access endpoint for a service running on the specified port inside the sandbox. Results are cached with LRU+TTL and deduplicated via singleflight. If useServerProxy is non-nil, the server proxy query parameter is included.

func (*LifecycleClient) GetSandbox

func (c *LifecycleClient) GetSandbox(ctx context.Context, id string) (*SandboxInfo, error)

GetSandbox retrieves the complete sandbox information by ID.

func (*LifecycleClient) GetSignedEndpoint added in v1.0.1

func (c *LifecycleClient) GetSignedEndpoint(ctx context.Context, sandboxID string, port int, expires int64) (*Endpoint, error)

GetSignedEndpoint retrieves a cryptographically signed endpoint URL for a sandbox port. The returned endpoint embeds an OSEP-0011 signed route token that expires at the given Unix epoch timestamp (seconds).

func (*LifecycleClient) GetSnapshot added in v1.0.1

func (c *LifecycleClient) GetSnapshot(ctx context.Context, id string) (*SnapshotInfo, error)

GetSnapshot retrieves snapshot information by ID.

func (*LifecycleClient) ListSandboxes

func (c *LifecycleClient) ListSandboxes(ctx context.Context, opts ListOptions) (*ListSandboxesResponse, error)

ListSandboxes returns a paginated list of sandboxes with optional filtering.

func (*LifecycleClient) ListSnapshots added in v1.0.1

ListSnapshots returns a paginated list of snapshots with optional filtering.

func (*LifecycleClient) PatchSandboxMetadata added in v1.0.1

func (c *LifecycleClient) PatchSandboxMetadata(ctx context.Context, id string, patch MetadataPatch) (*SandboxInfo, error)

PatchSandboxMetadata patches metadata for a sandbox. Non-nil values add or replace keys. Nil values delete keys.

func (*LifecycleClient) PauseSandbox

func (c *LifecycleClient) PauseSandbox(ctx context.Context, id string) error

PauseSandbox pauses a running sandbox while preserving its state.

func (*LifecycleClient) RenewExpiration

func (c *LifecycleClient) RenewExpiration(ctx context.Context, id string, expiresAt time.Time) (*RenewExpirationResponse, error)

RenewExpiration renews the sandbox's absolute expiration time. The caller is responsible for computing the desired expiresAt time.

func (*LifecycleClient) ResumeSandbox

func (c *LifecycleClient) ResumeSandbox(ctx context.Context, id string) error

ResumeSandbox resumes a paused sandbox.

type ListOptions

type ListOptions struct {
	// States filters by lifecycle state. Multiple values use OR logic.
	States []SandboxState
	// Metadata filters by key-value metadata (AND logic).
	Metadata map[string]string
	// Page number (1-based). Defaults to 1.
	Page int
	// PageSize is the number of items per page. Defaults to 20.
	PageSize int
}

ListOptions configures filtering and pagination for ListSandboxes.

type ListSandboxesResponse

type ListSandboxesResponse struct {
	Items      []SandboxInfo  `json:"items"`
	Pagination PaginationInfo `json:"pagination"`
}

ListSandboxesResponse is the paginated response from listing sandboxes.

type ListSnapshotsOptions added in v1.0.1

type ListSnapshotsOptions struct {
	SandboxID string
	States    []SnapshotState
	Page      int
	PageSize  int
}

type ListSnapshotsResponse added in v1.0.1

type ListSnapshotsResponse struct {
	Items      []SnapshotInfo `json:"items"`
	Pagination PaginationInfo `json:"pagination"`
}

type MetadataPatch added in v1.0.1

type MetadataPatch map[string]*string

MetadataPatch is the request body for patching sandbox metadata. Non-nil values add or replace keys. Nil values delete keys.

type Metrics

type Metrics struct {
	CPUCount   float64 `json:"cpu_count"`
	CPUUsedPct float64 `json:"cpu_used_pct"`
	MemTotalMB float64 `json:"mem_total_mib"`
	MemUsedMB  float64 `json:"mem_used_mib"`
	Timestamp  int64   `json:"timestamp"`
}

Metrics contains system resource usage metrics.

type MoveItem

type MoveItem struct {
	Src  string `json:"src"`
	Dest string `json:"dest"`
}

MoveItem defines a single file move/rename operation.

type MoveRequest

type MoveRequest []MoveItem

MoveRequest is a list of file move/rename operations.

type NetworkPolicy

type NetworkPolicy struct {
	DefaultAction string        `json:"defaultAction,omitempty"`
	Egress        []NetworkRule `json:"egress,omitempty"`
}

NetworkPolicy defines the egress network policy for a sandbox.

type NetworkRule

type NetworkRule struct {
	Action string `json:"action"`
	Target string `json:"target"`
}

NetworkRule defines a single egress allow/deny rule.

type OSSFS

type OSSFS struct {
	Bucket          string   `json:"bucket"`
	Endpoint        string   `json:"endpoint"`
	Version         string   `json:"version,omitempty"`
	Options         []string `json:"options,omitempty"`
	AccessKeyID     string   `json:"accessKeyId"`
	AccessKeySecret string   `json:"accessKeySecret"`
}

OSSFS represents an Alibaba Cloud OSS mount backend via ossfs.

type Option

type Option func(*Client)

Option configures a Client.

func WithAuthHeader

func WithAuthHeader(header string) Option

WithAuthHeader overrides the default auth header name. Use this when the server expects a different header (e.g. "X-API-Key" instead of "OPEN-SANDBOX-API-KEY").

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient sets a custom http.Client.

func WithHeaders

func WithHeaders(headers map[string]string) Option

WithHeaders adds custom HTTP headers to all requests. These are applied before the auth and content-type headers, so they cannot override those.

func WithRetry

func WithRetry(cfg RetryConfig) Option

WithRetry enables automatic retry with exponential backoff for transient errors and network failures. By default, transient status codes are 429/502/503/504; override RetryConfig.RetryableStatusCodes to customize.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the HTTP client timeout. The timeout is applied after all options, so it is safe to combine with WithHTTPClient in any order.

type OutputMessage

type OutputMessage struct {
	Text      string `json:"text"`
	Timestamp int64  `json:"timestamp"`
}

OutputMessage represents a single stdout or stderr line from command execution.

type PVC

type PVC struct {
	ClaimName                  string   `json:"claimName"`
	CreateIfNotExists          *bool    `json:"createIfNotExists,omitempty"`
	DeleteOnSandboxTermination *bool    `json:"deleteOnSandboxTermination,omitempty"`
	StorageClass               *string  `json:"storageClass,omitempty"`
	Storage                    *string  `json:"storage,omitempty"`
	AccessModes                []string `json:"accessModes,omitempty"`
}

PVC represents a platform-managed named volume backend.

type PaginationInfo

type PaginationInfo struct {
	Page        int  `json:"page"`
	PageSize    int  `json:"pageSize"`
	TotalItems  int  `json:"totalItems"`
	TotalPages  int  `json:"totalPages"`
	HasNextPage bool `json:"hasNextPage"`
}

PaginationInfo contains pagination metadata for list responses.

type Permission

type Permission struct {
	Owner string `json:"owner,omitempty"`
	Group string `json:"group,omitempty"`
	Mode  int    `json:"mode"`
}

Permission defines file ownership and mode settings.

type PermissionsRequest

type PermissionsRequest map[string]Permission

PermissionsRequest maps file paths to their desired permission settings.

type PlatformArch added in v1.0.2

type PlatformArch string

PlatformArch is the target CPU architecture of a sandbox platform constraint.

const (
	ArchAMD64 PlatformArch = "amd64"
	ArchARM64 PlatformArch = "arm64"
)

type PlatformOS added in v1.0.2

type PlatformOS string

PlatformOS is the target operating system of a sandbox platform constraint. The wire-level enum is enforced server-side; the constants below mirror the spec so Go callers can avoid stringly-typed typos.

const (
	OSLinux   PlatformOS = "linux"
	OSWindows PlatformOS = "windows"
)

type PlatformSpec added in v1.0.2

type PlatformSpec struct {
	OS   PlatformOS   `json:"os"`
	Arch PlatformArch `json:"arch"`
}

PlatformSpec is a runtime platform constraint used for scheduling and provisioning. It is independent from Image and expresses the expected target OS and CPU architecture for sandbox execution.

When omitted, the server applies its own default platform selection behavior. When provided, the runtime must satisfy the constraint or the request fails.

See specs/sandbox-lifecycle.yml#/components/schemas/PlatformSpec.

type PolicyStatusResponse

type PolicyStatusResponse struct {
	Status          string         `json:"status,omitempty"`
	Mode            string         `json:"mode,omitempty"`
	EnforcementMode string         `json:"enforcementMode,omitempty"`
	Reason          string         `json:"reason,omitempty"`
	Policy          *NetworkPolicy `json:"policy,omitempty"`
}

PolicyStatusResponse is the response from the egress policy endpoints.

type PoolAcquireFailedError added in v1.0.4

type PoolAcquireFailedError struct {
	PoolName string
	Cause    error
}

PoolAcquireFailedError is returned when Acquire finds an idle sandbox but fails to connect or health-check it under FAIL_FAST policy.

func (*PoolAcquireFailedError) Error added in v1.0.4

func (e *PoolAcquireFailedError) Error() string

func (*PoolAcquireFailedError) Unwrap added in v1.0.4

func (e *PoolAcquireFailedError) Unwrap() error

type PoolConfig added in v1.0.4

type PoolConfig struct {
	PoolName          string
	OwnerID           string
	MaxIdle           int
	WarmupConcurrency int
	PrimaryLockTTL    time.Duration
	ReconcileInterval time.Duration
	DegradedThreshold int
	EmptyBehavior     AcquirePolicy
	StateStore        PoolStateStore
	ConnectionConfig  ConnectionConfig
	CreationSpec      PoolCreationSpec

	AcquireReadyTimeout               time.Duration
	WarmupReadyTimeout                time.Duration
	AcquireHealthCheckPollingInterval time.Duration
	WarmupHealthCheckPollingInterval  time.Duration

	AcquireHealthCheck    func(ctx context.Context, sb *Sandbox) error
	WarmupHealthCheck     func(ctx context.Context, sb *Sandbox) error
	WarmupSandboxPreparer func(ctx context.Context, sb *Sandbox) error
	SandboxCreator        PooledSandboxCreator

	WarmupSkipHealthCheck  bool
	AcquireMinRemainingTTL time.Duration
	IdleTimeout            time.Duration
	DrainTimeout           time.Duration
	Logger                 PoolLogger
}

PoolConfig holds the configuration for a sandbox pool.

type PoolCreationSpec added in v1.0.4

type PoolCreationSpec struct {
	Image           string
	SnapshotID      string
	Entrypoint      []string
	ResourceLimits  ResourceLimits
	TimeoutSeconds  *int
	Env             map[string]string
	Metadata        map[string]string
	NetworkPolicy   *NetworkPolicy
	Volumes         []Volume
	Extensions      map[string]string
	Platform        *PlatformSpec
	ManualCleanup   bool
	SecureAccess    bool
	CredentialProxy *CredentialProxyConfig
	ImageAuth       *ImageAuth
}

PoolCreationSpec defines the sandbox creation parameters used by the pool.

type PoolEmptyError added in v1.0.4

type PoolEmptyError struct {
	PoolName string
	Policy   AcquirePolicy
}

PoolEmptyError is returned when Acquire is called with FAIL_FAST policy and no idle sandbox is available.

func (*PoolEmptyError) Error added in v1.0.4

func (e *PoolEmptyError) Error() string

type PoolHealthState added in v1.0.4

type PoolHealthState int

PoolHealthState represents the health state of a sandbox pool.

const (
	PoolHealthy PoolHealthState = iota
	PoolDegraded
)

func (PoolHealthState) String added in v1.0.4

func (s PoolHealthState) String() string

type PoolLifecycleState added in v1.0.4

type PoolLifecycleState int

PoolLifecycleState represents the lifecycle state of a sandbox pool.

const (
	PoolLifecycleNotStarted PoolLifecycleState = iota
	PoolLifecycleStarting
	PoolLifecycleRunning
	PoolLifecycleDraining
	PoolLifecycleStopped
)

func (PoolLifecycleState) String added in v1.0.4

func (s PoolLifecycleState) String() string

type PoolLogger added in v1.0.4

type PoolLogger interface {
	Info(msg string, keysAndValues ...interface{})
	Warn(msg string, keysAndValues ...interface{})
	Debug(msg string, keysAndValues ...interface{})
}

PoolLogger is the logging interface for pool operations. The default implementation is a no-op. Users can inject their own implementation (e.g., wrapping log/slog) via the builder.

type PoolNotRunningError added in v1.0.4

type PoolNotRunningError struct {
	PoolName string
	State    PoolLifecycleState
}

PoolNotRunningError is returned when an operation is attempted on a pool that is not in the RUNNING state.

func (*PoolNotRunningError) Error added in v1.0.4

func (e *PoolNotRunningError) Error() string

type PoolSnapshot added in v1.0.4

type PoolSnapshot struct {
	LifecycleState     PoolLifecycleState
	HealthState        PoolHealthState
	IdleCount          int
	MaxIdle            int
	FailureCount       int
	BackoffActive      bool
	LastError          string
	InFlightOperations int
}

PoolSnapshot is a point-in-time snapshot of the pool state.

type PoolStateStore added in v1.0.4

type PoolStateStore interface {
	// TryTakeIdle atomically takes the oldest idle sandbox from the pool.
	// Returns empty string if no idle sandbox is available.
	TryTakeIdle(ctx context.Context, poolName string) (string, error)

	// TryTakeIdleWithMinTTL atomically takes the oldest idle sandbox that has
	// at least minRemaining TTL left. Entries that are alive but below the
	// threshold are returned in DiscardedAliveSandboxIDs for caller cleanup.
	TryTakeIdleWithMinTTL(ctx context.Context, poolName string, minRemaining time.Duration) (*TakeIdleResult, error)

	// PutIdle adds a sandbox to the idle pool. Idempotent.
	PutIdle(ctx context.Context, poolName string, sandboxID string) error

	// RemoveIdle removes a sandbox from the idle pool. Idempotent.
	RemoveIdle(ctx context.Context, poolName string, sandboxID string) error

	// TryAcquirePrimaryLock attempts to acquire the primary (leader) lock.
	TryAcquirePrimaryLock(ctx context.Context, poolName string, ownerID string, ttl time.Duration) (bool, error)

	// RenewPrimaryLock extends the primary lock TTL. Only succeeds if caller is the current owner.
	RenewPrimaryLock(ctx context.Context, poolName string, ownerID string, ttl time.Duration) (bool, error)

	// ReleasePrimaryLock releases the primary lock. Only succeeds if caller is the current owner.
	ReleasePrimaryLock(ctx context.Context, poolName string, ownerID string) error

	// ReapExpiredIdle removes fully expired idle entries.
	// The now parameter is a hint; distributed implementations may use
	// server-side time for consistency (e.g., Redis TIME command).
	ReapExpiredIdle(ctx context.Context, poolName string, now time.Time) error

	// ReapExpiredIdleWithMinTTL removes expired and near-expiry idle entries.
	// Returns IDs of entries that were still alive but below the TTL threshold.
	// The now parameter is a hint; see ReapExpiredIdle.
	ReapExpiredIdleWithMinTTL(ctx context.Context, poolName string, now time.Time, minRemaining time.Duration) (*ReapResult, error)

	// SnapshotCounters returns current pool counters.
	SnapshotCounters(ctx context.Context, poolName string) (*StoreCounters, error)

	// SnapshotIdleEntries returns all current idle entries in FIFO order.
	SnapshotIdleEntries(ctx context.Context, poolName string) ([]IdleEntry, error)

	// GetMaxIdle returns the stored maxIdle value for the pool.
	GetMaxIdle(ctx context.Context, poolName string) (int, error)

	// SetMaxIdle persists the maxIdle value for the pool.
	SetMaxIdle(ctx context.Context, poolName string, maxIdle int) error

	// SetIdleEntryTTL persists the idle entry TTL for the pool.
	SetIdleEntryTTL(ctx context.Context, poolName string, ttl time.Duration) error
}

PoolStateStore is the abstraction for pool state persistence. Implementations must be safe for concurrent use. PutIdle and RemoveIdle must be idempotent.

type PoolStateStoreUnavailableError added in v1.0.4

type PoolStateStoreUnavailableError struct {
	Operation string
	Cause     error
}

PoolStateStoreUnavailableError is returned when the pool state store is unreachable or otherwise unavailable during idle take/put/lock operations.

func (*PoolStateStoreUnavailableError) Error added in v1.0.4

func (*PoolStateStoreUnavailableError) Unwrap added in v1.0.4

type PooledSandboxCreateContext added in v1.0.4

type PooledSandboxCreateContext struct {
	PoolName                   string
	OwnerID                    string
	IdleTimeout                time.Duration
	Reason                     PooledSandboxCreateReason
	ReadyTimeout               time.Duration
	HealthCheckPollingInterval time.Duration
	SkipHealthCheck            bool
	HealthCheck                func(ctx context.Context, sb *Sandbox) error
	ConnectionConfig           ConnectionConfig
	CreationSpec               PoolCreationSpec
}

PooledSandboxCreateContext carries pool metadata and creation parameters to a PooledSandboxCreator.

type PooledSandboxCreateReason added in v1.0.4

type PooledSandboxCreateReason int

PooledSandboxCreateReason indicates why a sandbox is being created.

const (
	CreateReasonWarmup PooledSandboxCreateReason = iota
	CreateReasonAcquire
)

func (PooledSandboxCreateReason) String added in v1.0.4

func (r PooledSandboxCreateReason) String() string

type PooledSandboxCreator added in v1.0.4

type PooledSandboxCreator interface {
	Create(ctx context.Context, createCtx PooledSandboxCreateContext) (*Sandbox, error)
}

PooledSandboxCreator allows custom sandbox creation logic.

type ReadyOptions

type ReadyOptions struct {
	Timeout         time.Duration
	PollingInterval time.Duration
	HealthCheck     func(ctx context.Context, sb *Sandbox) (bool, error)
}

ReadyOptions configures WaitUntilReady behavior.

type ReapResult added in v1.0.4

type ReapResult struct {
	DiscardedAliveSandboxIDs []string
}

ReapResult holds the result of a min-TTL-aware expired idle reap.

type RenewExpirationRequest

type RenewExpirationRequest struct {
	ExpiresAt time.Time `json:"expiresAt"`
}

RenewExpirationRequest is the request body for renewing sandbox expiration.

type RenewExpirationResponse

type RenewExpirationResponse struct {
	ExpiresAt time.Time `json:"expiresAt"`
}

RenewExpirationResponse is the response from renewing sandbox expiration.

type ReplaceItem

type ReplaceItem struct {
	Old string `json:"old"`
	New string `json:"new"`
}

ReplaceItem defines a text replacement operation for a single file.

type ReplaceRequest

type ReplaceRequest map[string]ReplaceItem

ReplaceRequest maps file paths to their replacement operations.

type ReplaceResponse added in v1.0.3

type ReplaceResponse map[string]ReplaceResult

ReplaceResponse maps file paths to their replacement results.

type ReplaceResult added in v1.0.3

type ReplaceResult struct {
	ReplacedCount int `json:"replacedCount"`
}

ReplaceResult holds the result of a content replacement for a single file.

type ResourceLimits

type ResourceLimits map[string]string

ResourceLimits defines runtime resource constraints as key-value pairs. Common keys: "cpu" (e.g. "500m"), "memory" (e.g. "512Mi"), "gpu" (e.g. "1").

type RetryConfig

type RetryConfig struct {
	// MaxRetries is the maximum number of retry attempts after the initial
	// request. 0 means no retries (only the original attempt).
	MaxRetries int

	// InitialBackoff is the delay before the first retry.
	InitialBackoff time.Duration

	// MaxBackoff caps the delay between retries.
	MaxBackoff time.Duration

	// Multiplier scales the backoff after each retry attempt.
	Multiplier float64

	// Jitter adds randomness to avoid thundering herd. Expressed as a
	// fraction of the computed delay: 0.0 = no jitter, 0.25 = +/-25%.
	Jitter float64

	// RetryableStatusCodes optionally overrides which HTTP status codes are
	// treated as transient for retry decisions. When empty, SDK defaults are
	// used (429, 502, 503, 504).
	RetryableStatusCodes []int
}

RetryConfig controls automatic retry behavior for transient errors. A zero-value config disables retries.

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns a retry configuration suitable for most SDK consumers: 3 retries, 500ms initial backoff, 2x multiplier, 30s cap.

type RunCodeRequest

type RunCodeRequest struct {
	Context *CodeContext `json:"context,omitempty"`
	Code    string       `json:"code"`
}

RunCodeRequest is the request body for executing code in a context.

type RunCommandRequest

type RunCommandRequest struct {
	Command    string            `json:"command"`
	Cwd        string            `json:"cwd,omitempty"`
	Background bool              `json:"background,omitempty"`
	Timeout    int64             `json:"timeout,omitempty"`
	UID        *int32            `json:"uid,omitempty"`
	GID        *int32            `json:"gid,omitempty"`
	Envs       map[string]string `json:"envs,omitempty"`
}

RunCommandRequest is the request body for executing a shell command.

type RunInSessionRequest

type RunInSessionRequest struct {
	Command string `json:"command"`
	Cwd     string `json:"cwd,omitempty"`
	Timeout int64  `json:"timeout,omitempty"`
}

RunInSessionRequest is the request body for running a command in an existing bash session.

type Sandbox

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

Sandbox is the high-level object wrapping lifecycle, execd, and egress clients. Use CreateSandbox or ConnectSandbox to obtain an instance.

func ConnectSandbox

func ConnectSandbox(ctx context.Context, config ConnectionConfig, sandboxID string, opts ...ReadyOptions) (*Sandbox, error)

ConnectSandbox connects to an existing running sandbox by ID.

func CreateSandbox

func CreateSandbox(ctx context.Context, config ConnectionConfig, opts SandboxCreateOptions) (*Sandbox, error)

CreateSandbox creates a new sandbox and waits for it to be ready.

func ResumeSandbox

func ResumeSandbox(ctx context.Context, config ConnectionConfig, sandboxID string, opts ...ReadyOptions) (*Sandbox, error)

ResumeSandbox resumes a paused sandbox and reconnects to it.

func (*Sandbox) Close

func (s *Sandbox) Close() error

Close releases local HTTP resources. Does NOT terminate the sandbox.

func (*Sandbox) CreateContext

func (s *Sandbox) CreateContext(ctx context.Context, req CreateContextRequest) (*CodeContext, error)

CreateContext creates a code execution context.

func (*Sandbox) CreateCredentialVault added in v1.0.3

func (s *Sandbox) CreateCredentialVault(ctx context.Context, req CredentialVaultCreateRequest) (*CredentialVaultState, error)

CreateCredentialVault creates the initial sandbox-local Credential Vault.

func (*Sandbox) CreateDirectory

func (s *Sandbox) CreateDirectory(ctx context.Context, path string, mode int) error

CreateDirectory creates a directory in the sandbox. Mode is octal digits as int (e.g. 755 for rwxr-xr-x).

func (*Sandbox) CreateSession

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

CreateSession creates a new bash session.

func (*Sandbox) CreateSnapshot added in v1.0.1

func (s *Sandbox) CreateSnapshot(ctx context.Context, req CreateSnapshotRequest) (*SnapshotInfo, error)

CreateSnapshot creates a persistent snapshot from this sandbox.

func (*Sandbox) CredentialVault added in v1.0.3

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

CredentialVault returns the sandbox-scoped egress client used for Credential Vault operations.

func (*Sandbox) DeleteContext

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

DeleteContext deletes a code execution context.

func (*Sandbox) DeleteCredentialVault added in v1.0.3

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

DeleteCredentialVault deletes the sandbox-local Credential Vault.

func (*Sandbox) DeleteDirectory

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

DeleteDirectory deletes a directory and its contents.

func (*Sandbox) DeleteEgressRules added in v1.0.2

func (s *Sandbox) DeleteEgressRules(ctx context.Context, targets []string) (*PolicyStatusResponse, error)

DeleteEgressRules removes egress rules matching the given targets from the current egress policy. Targets not present in the policy are silently ignored.

func (*Sandbox) DeleteFiles

func (s *Sandbox) DeleteFiles(ctx context.Context, paths []string) error

DeleteFiles deletes one or more files from the sandbox.

func (*Sandbox) DeleteSession

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

DeleteSession deletes a bash session.

func (*Sandbox) DownloadFile

func (s *Sandbox) DownloadFile(ctx context.Context, remotePath, rangeHeader string, opts ...DownloadFileOptions) (io.ReadCloser, error)

DownloadFile downloads a file from the sandbox.

func (*Sandbox) ExecuteCode

func (s *Sandbox) ExecuteCode(ctx context.Context, req RunCodeRequest, handlers *ExecutionHandlers) (*Execution, error)

ExecuteCode executes code in a context and streams output via SSE.

func (*Sandbox) GetCredentialVault added in v1.0.3

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

GetCredentialVault returns sanitized Credential Vault state.

func (*Sandbox) GetCredentialVaultBinding added in v1.0.3

func (s *Sandbox) GetCredentialVaultBinding(ctx context.Context, name string) (*CredentialBindingMetadata, error)

GetCredentialVaultBinding returns sanitized metadata for one binding.

func (*Sandbox) GetCredentialVaultCredential added in v1.0.3

func (s *Sandbox) GetCredentialVaultCredential(ctx context.Context, name string) (*CredentialMetadata, error)

GetCredentialVaultCredential returns sanitized metadata for one credential.

func (*Sandbox) GetEgressPolicy

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

GetEgressPolicy retrieves the current egress network policy.

func (*Sandbox) GetEndpoint

func (s *Sandbox) GetEndpoint(ctx context.Context, port int) (*Endpoint, error)

GetEndpoint retrieves the public access endpoint for a service port.

func (*Sandbox) GetFileInfo

func (s *Sandbox) GetFileInfo(ctx context.Context, path string) (map[string]FileInfo, error)

GetFileInfo retrieves file metadata.

func (*Sandbox) GetInfo

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

GetInfo returns the sandbox's current info (status, metadata, image, etc.).

func (*Sandbox) GetMetrics

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

GetMetrics returns current system resource metrics from the sandbox.

func (*Sandbox) GetSignedEndpoint added in v1.0.1

func (s *Sandbox) GetSignedEndpoint(ctx context.Context, port int, expires int64) (*Endpoint, error)

GetSignedEndpoint retrieves a signed endpoint URL with an OSEP-0011 route token that expires at the given Unix epoch timestamp (seconds).

func (*Sandbox) ID

func (s *Sandbox) ID() string

ID returns the sandbox identifier.

func (*Sandbox) IsHealthy

func (s *Sandbox) IsHealthy(ctx context.Context) bool

IsHealthy checks whether the sandbox's execd service is responsive.

func (*Sandbox) IsolatedCapabilities deprecated added in v1.0.4

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

Deprecated: Use IsolationCapabilities instead.

func (*Sandbox) IsolatedCreate deprecated added in v1.0.4

Deprecated: Use IsolationCreate instead.

func (*Sandbox) IsolatedDelete deprecated added in v1.0.4

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

Deprecated: Use IsolationSession.Delete instead.

func (*Sandbox) IsolatedGet deprecated added in v1.0.4

func (s *Sandbox) IsolatedGet(ctx context.Context, sessionID string) (*IsolatedSessionState, error)

Deprecated: Use IsolationSession.Get instead.

func (*Sandbox) IsolatedRun deprecated added in v1.0.4

func (s *Sandbox) IsolatedRun(ctx context.Context, sessionID string, req IsolatedRunRequest, handlers *ExecutionHandlers) (*Execution, error)

Deprecated: Use IsolationSession.Run instead.

func (*Sandbox) IsolationCapabilities added in v1.0.4

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

IsolationCapabilities retrieves isolation capabilities.

func (*Sandbox) IsolationCreate added in v1.0.4

func (s *Sandbox) IsolationCreate(ctx context.Context, req CreateIsolatedSessionRequest) (*IsolationSession, error)

IsolationCreate creates an isolated bash session and returns a session handle.

func (*Sandbox) IsolationRunOnce added in v1.0.4

func (s *Sandbox) IsolationRunOnce(ctx context.Context, req CreateIsolatedSessionRequest, run IsolatedRunRequest, handlers *ExecutionHandlers) (*Execution, error)

IsolationRunOnce creates an isolated session, runs the given code, and deletes the session. It is a convenience wrapper for the create → run → delete lifecycle.

func (*Sandbox) IsolationWithSession added in v1.0.4

func (s *Sandbox) IsolationWithSession(ctx context.Context, req CreateIsolatedSessionRequest, fn func(*IsolationSession) error) error

IsolationWithSession creates an isolated session, invokes fn, and deletes the session afterwards. The session is always deleted regardless of whether fn returns an error.

func (*Sandbox) Kill

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

Kill terminates the sandbox. This is irreversible.

func (*Sandbox) ListContexts

func (s *Sandbox) ListContexts(ctx context.Context, language string) ([]CodeContext, error)

ListContexts lists active code execution contexts for a language.

func (*Sandbox) ListCredentialVaultBindings added in v1.0.3

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

ListCredentialVaultBindings returns sanitized binding metadata.

func (*Sandbox) ListCredentialVaultCredentials added in v1.0.3

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

ListCredentialVaultCredentials returns sanitized credential metadata.

func (*Sandbox) ListDirectory added in v1.0.3

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

ListDirectory lists the immediate children of the given directory using the server-side default depth (1). Use ListDirectoryWithDepth to override.

func (*Sandbox) ListDirectoryWithDepth added in v1.0.3

func (s *Sandbox) ListDirectoryWithDepth(ctx context.Context, path string, depth int) ([]FileInfo, error)

ListDirectoryWithDepth lists directory contents up to the given depth. depth=0 returns an empty slice; depth=1 lists immediate children; larger values include descendants up to that many levels below path.

func (*Sandbox) MoveFiles

func (s *Sandbox) MoveFiles(ctx context.Context, req MoveRequest) error

MoveFiles renames or moves files.

func (*Sandbox) PatchCredentialVault added in v1.0.3

func (s *Sandbox) PatchCredentialVault(ctx context.Context, req CredentialVaultPatchRequest) (*CredentialVaultState, error)

PatchCredentialVault atomically mutates sandbox-local credentials and bindings.

func (*Sandbox) PatchEgressRules

func (s *Sandbox) PatchEgressRules(ctx context.Context, rules []NetworkRule) (*PolicyStatusResponse, error)

PatchEgressRules merges network rules into the current egress policy.

func (*Sandbox) PatchMetadata added in v1.0.1

func (s *Sandbox) PatchMetadata(ctx context.Context, patch MetadataPatch) (*SandboxInfo, error)

PatchMetadata patches this sandbox's metadata. Non-nil values add or replace keys. Nil values delete keys.

func (*Sandbox) Pause

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

Pause pauses the sandbox while preserving its state. Endpoint cache is invalidated because endpoints may change across pause/resume.

func (*Sandbox) Ping

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

Ping checks if the execd service is responsive.

func (*Sandbox) Renew

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

Renew extends the sandbox's expiration by the given duration from now.

func (*Sandbox) ReplaceInFiles

func (s *Sandbox) ReplaceInFiles(ctx context.Context, req ReplaceRequest) error

ReplaceInFiles performs text replacement in files.

func (*Sandbox) ReplaceInFilesDetailed added in v1.0.3

func (s *Sandbox) ReplaceInFilesDetailed(ctx context.Context, req ReplaceRequest) (ReplaceResponse, error)

ReplaceInFilesDetailed performs text replacement and returns per-file replacement counts.

func (*Sandbox) Resume

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

Resume resumes this sandbox if it was paused and reconnects to it.

func (*Sandbox) RunCommand

func (s *Sandbox) RunCommand(ctx context.Context, command string, handlers *ExecutionHandlers) (*Execution, error)

RunCommand executes a shell command and returns the structured result.

func (*Sandbox) RunCommandWithOpts

func (s *Sandbox) RunCommandWithOpts(ctx context.Context, req RunCommandRequest, handlers *ExecutionHandlers) (*Execution, error)

RunCommandWithOpts executes a command with full options.

func (*Sandbox) RunInSession

func (s *Sandbox) RunInSession(ctx context.Context, sessionID string, req RunInSessionRequest, handlers *ExecutionHandlers) (*Execution, error)

RunInSession executes a command in an existing session with structured output.

func (*Sandbox) SearchFiles

func (s *Sandbox) SearchFiles(ctx context.Context, dir, pattern string) ([]FileInfo, error)

SearchFiles searches for files matching a pattern.

func (*Sandbox) SetPermissions

func (s *Sandbox) SetPermissions(ctx context.Context, req PermissionsRequest) error

SetPermissions changes file permissions.

func (*Sandbox) UploadFile

func (s *Sandbox) UploadFile(ctx context.Context, file io.Reader, opts UploadFileOptions) error

UploadFile uploads a single file to the sandbox.

func (*Sandbox) UploadFiles added in v1.0.1

func (s *Sandbox) UploadFiles(ctx context.Context, entries []UploadFileEntry) error

UploadFiles uploads one or more files to the sandbox in a single multipart request.

func (*Sandbox) WaitUntilReady

func (s *Sandbox) WaitUntilReady(ctx context.Context, opts ReadyOptions) error

WaitUntilReady polls until the sandbox is ready or the timeout expires. By default it checks execd /ping; if HealthCheck is provided, it uses that instead.

type SandboxCreateOptions

type SandboxCreateOptions struct {
	// Image is the container image URI (required).
	Image string
	// SnapshotID restores the sandbox from a previously created snapshot.
	SnapshotID string

	// Entrypoint is the command to run. Defaults to DefaultEntrypoint.
	Entrypoint []string

	// Resource limits (e.g. {"cpu": "500m", "memory": "256Mi"}).
	// Defaults to DefaultResourceLimits.
	ResourceLimits ResourceLimits

	// ResourceRequests sets Kubernetes resource requests (guaranteed minimums).
	// When set, enables Burstable QoS (requests < limits).
	// When nil, limits are used for both limits and requests (Guaranteed QoS).
	ResourceRequests ResourceLimits

	// TimeoutSeconds is the sandbox TTL. Nil means use DefaultTimeoutSeconds.
	TimeoutSeconds *int

	// Env variables injected into the sandbox.
	Env map[string]string

	// SecureAccess enables secured access for sandbox endpoints.
	SecureAccess bool

	// Metadata for filtering and tagging.
	Metadata map[string]string

	// NetworkPolicy for egress control.
	NetworkPolicy *NetworkPolicy

	// CredentialProxy enables Credential Vault transparent proxy support.
	CredentialProxy *CredentialProxyConfig

	// Volumes to mount.
	Volumes []Volume

	// ImageAuth provides registry credentials for private images.
	ImageAuth *ImageAuth

	// ManualCleanup, when true, creates the sandbox with no TTL so it stays
	// alive until explicitly killed. The timeout field is omitted from the
	// request (nil), causing the server to treat it as infinite.
	ManualCleanup bool

	// Extensions for provider-specific parameters.
	Extensions map[string]string

	// Platform selects the target OS/arch for the sandbox (e.g. {"os":
	// "windows", "arch": "amd64"}). When nil the server applies its default.
	Platform *PlatformSpec

	// SkipHealthCheck skips the WaitUntilReady call after creation.
	SkipHealthCheck bool

	// ReadyTimeout overrides DefaultReadyTimeoutSeconds.
	ReadyTimeout time.Duration

	// HealthCheckInterval overrides DefaultHealthCheckPollingInterval.
	HealthCheckInterval time.Duration

	// HealthCheck is a custom health check function. If nil, execd /ping is used.
	HealthCheck func(ctx context.Context, sb *Sandbox) (bool, error)
}

SandboxCreateOptions configures sandbox creation.

type SandboxInfo

type SandboxInfo struct {
	ID         string            `json:"id"`
	Image      *ImageSpec        `json:"image,omitempty"`
	SnapshotID string            `json:"snapshotId,omitempty"`
	Status     SandboxStatus     `json:"status"`
	Metadata   map[string]string `json:"metadata,omitempty"`
	Extensions map[string]string `json:"extensions,omitempty"`
	Entrypoint []string          `json:"entrypoint"`
	ExpiresAt  *time.Time        `json:"expiresAt,omitempty"`
	CreatedAt  time.Time         `json:"createdAt"`
	Platform   *PlatformSpec     `json:"platform,omitempty"`
}

SandboxInfo represents a runtime execution environment provisioned from a container image, as returned by the lifecycle API.

type SandboxManager

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

SandboxManager provides administrative operations on sandboxes without connecting to a specific sandbox.

func NewSandboxManager

func NewSandboxManager(config ConnectionConfig) *SandboxManager

NewSandboxManager creates a SandboxManager from the given connection config.

func (*SandboxManager) Close

func (m *SandboxManager) Close() error

Close releases local resources. Currently a no-op placeholder.

func (*SandboxManager) CreateSnapshot added in v1.0.1

func (m *SandboxManager) CreateSnapshot(ctx context.Context, sandboxID string, req CreateSnapshotRequest) (*SnapshotInfo, error)

CreateSnapshot creates a snapshot for the given sandbox.

func (*SandboxManager) DeleteSnapshot added in v1.0.1

func (m *SandboxManager) DeleteSnapshot(ctx context.Context, snapshotID string) error

DeleteSnapshot deletes a snapshot by ID.

func (*SandboxManager) GetSandboxInfo

func (m *SandboxManager) GetSandboxInfo(ctx context.Context, sandboxID string) (*SandboxInfo, error)

GetSandboxInfo retrieves info for a single sandbox by ID.

func (*SandboxManager) GetSnapshot added in v1.0.1

func (m *SandboxManager) GetSnapshot(ctx context.Context, snapshotID string) (*SnapshotInfo, error)

GetSnapshot retrieves snapshot info by ID.

func (*SandboxManager) KillSandbox

func (m *SandboxManager) KillSandbox(ctx context.Context, sandboxID string) error

KillSandbox terminates a sandbox by ID.

func (*SandboxManager) ListSandboxInfos

func (m *SandboxManager) ListSandboxInfos(ctx context.Context, filter ListOptions) (*ListSandboxesResponse, error)

ListSandboxInfos returns a paginated list of sandboxes with optional filtering.

func (*SandboxManager) ListSnapshots added in v1.0.1

ListSnapshots returns a paginated list of snapshots with optional filtering.

func (*SandboxManager) PatchSandboxMetadata added in v1.0.1

func (m *SandboxManager) PatchSandboxMetadata(ctx context.Context, sandboxID string, patch MetadataPatch) (*SandboxInfo, error)

PatchSandboxMetadata patches metadata for a sandbox by ID.

func (*SandboxManager) PauseSandbox

func (m *SandboxManager) PauseSandbox(ctx context.Context, sandboxID string) error

PauseSandbox pauses a running sandbox by ID.

func (*SandboxManager) RenewSandbox

func (m *SandboxManager) RenewSandbox(ctx context.Context, sandboxID string, duration time.Duration) (*RenewExpirationResponse, error)

RenewSandbox extends a sandbox's expiration by the given duration from now.

func (*SandboxManager) ResumeSandbox

func (m *SandboxManager) ResumeSandbox(ctx context.Context, sandboxID string) error

ResumeSandbox resumes a paused sandbox by ID.

type SandboxPool added in v1.0.4

type SandboxPool interface {
	Start(ctx context.Context) error
	Acquire(ctx context.Context, opts AcquireOptions) (*Sandbox, error)
	ReleaseAllIdle(ctx context.Context) (int, error)
	Resize(ctx context.Context, newMaxIdle int) error
	Snapshot(ctx context.Context) (*PoolSnapshot, error)
	SnapshotIdleEntries(ctx context.Context) ([]IdleEntry, error)
	Shutdown(ctx context.Context, graceful bool) error
}

SandboxPool is the interface for a client-side sandbox pool.

type SandboxPoolBuilder added in v1.0.4

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

SandboxPoolBuilder configures and creates a DefaultSandboxPool.

func NewSandboxPoolBuilder added in v1.0.4

func NewSandboxPoolBuilder() *SandboxPoolBuilder

NewSandboxPoolBuilder creates a new builder with sensible defaults.

func (*SandboxPoolBuilder) AcquireHealthCheck added in v1.0.4

func (b *SandboxPoolBuilder) AcquireHealthCheck(fn func(ctx context.Context, sb *Sandbox) error) *SandboxPoolBuilder

AcquireHealthCheck sets an optional health-check callback during Acquire.

func (*SandboxPoolBuilder) AcquireHealthCheckPollingInterval added in v1.0.4

func (b *SandboxPoolBuilder) AcquireHealthCheckPollingInterval(d time.Duration) *SandboxPoolBuilder

AcquireHealthCheckPollingInterval sets the interval between health check polls during acquire (default: 200ms).

func (*SandboxPoolBuilder) AcquireMinRemainingTTL added in v1.0.4

func (b *SandboxPoolBuilder) AcquireMinRemainingTTL(d time.Duration) *SandboxPoolBuilder

AcquireMinRemainingTTL sets the default minimum remaining TTL for acquire.

func (*SandboxPoolBuilder) AcquireReadyTimeout added in v1.0.4

func (b *SandboxPoolBuilder) AcquireReadyTimeout(d time.Duration) *SandboxPoolBuilder

AcquireReadyTimeout sets the timeout for health checks during Acquire.

func (*SandboxPoolBuilder) Build added in v1.0.4

Build validates configuration and creates a DefaultSandboxPool. The pool is not started; call Start() to begin reconciliation.

func (*SandboxPoolBuilder) ConnectionConfig added in v1.0.4

func (b *SandboxPoolBuilder) ConnectionConfig(c ConnectionConfig) *SandboxPoolBuilder

ConnectionConfig sets the connection configuration (required).

func (*SandboxPoolBuilder) CreationSpec added in v1.0.4

CreationSpec sets the sandbox creation parameters.

func (*SandboxPoolBuilder) DegradedThreshold added in v1.0.4

func (b *SandboxPoolBuilder) DegradedThreshold(n int) *SandboxPoolBuilder

DegradedThreshold sets the number of consecutive failures before the pool is considered degraded.

func (*SandboxPoolBuilder) DrainTimeout added in v1.0.4

func (b *SandboxPoolBuilder) DrainTimeout(d time.Duration) *SandboxPoolBuilder

DrainTimeout sets the maximum time to wait during graceful shutdown.

func (*SandboxPoolBuilder) EmptyBehavior added in v1.0.4

EmptyBehavior sets the default policy when the pool is empty during Acquire.

func (*SandboxPoolBuilder) IdleTimeout added in v1.0.4

IdleTimeout sets the TTL applied to pool-created sandboxes (default: 24h).

func (*SandboxPoolBuilder) MaxIdle added in v1.0.4

func (b *SandboxPoolBuilder) MaxIdle(n int) *SandboxPoolBuilder

MaxIdle sets the target number of idle sandboxes.

func (*SandboxPoolBuilder) OwnerID added in v1.0.4

OwnerID sets the owner identifier for leader election.

func (*SandboxPoolBuilder) PoolLogger added in v1.0.4

PoolLogger sets a custom structured logger for pool operations. Defaults to a no-op logger if not set.

func (*SandboxPoolBuilder) PoolName added in v1.0.4

func (b *SandboxPoolBuilder) PoolName(name string) *SandboxPoolBuilder

PoolName sets the pool name (required).

func (*SandboxPoolBuilder) PrimaryLockTTL added in v1.0.4

func (b *SandboxPoolBuilder) PrimaryLockTTL(d time.Duration) *SandboxPoolBuilder

PrimaryLockTTL sets the TTL for the primary (leader) lock.

func (*SandboxPoolBuilder) ReconcileInterval added in v1.0.4

func (b *SandboxPoolBuilder) ReconcileInterval(d time.Duration) *SandboxPoolBuilder

ReconcileInterval sets the interval between reconciliation ticks.

func (*SandboxPoolBuilder) SandboxCreator added in v1.0.4

func (b *SandboxPoolBuilder) SandboxCreator(creator PooledSandboxCreator) *SandboxPoolBuilder

SandboxCreator sets a custom sandbox creator. If nil, the default CreateSandbox is used.

func (*SandboxPoolBuilder) StateStore added in v1.0.4

StateStore sets a custom PoolStateStore implementation.

func (*SandboxPoolBuilder) WarmupConcurrency added in v1.0.4

func (b *SandboxPoolBuilder) WarmupConcurrency(n int) *SandboxPoolBuilder

WarmupConcurrency sets the maximum number of sandboxes created per reconcile tick.

func (*SandboxPoolBuilder) WarmupHealthCheck added in v1.0.4

func (b *SandboxPoolBuilder) WarmupHealthCheck(fn func(ctx context.Context, sb *Sandbox) error) *SandboxPoolBuilder

WarmupHealthCheck sets an optional health-check callback after warmup creation.

func (*SandboxPoolBuilder) WarmupHealthCheckPollingInterval added in v1.0.4

func (b *SandboxPoolBuilder) WarmupHealthCheckPollingInterval(d time.Duration) *SandboxPoolBuilder

WarmupHealthCheckPollingInterval sets the interval between health check polls during warmup (default: 200ms).

func (*SandboxPoolBuilder) WarmupReadyTimeout added in v1.0.4

func (b *SandboxPoolBuilder) WarmupReadyTimeout(d time.Duration) *SandboxPoolBuilder

WarmupReadyTimeout sets the timeout for health checks during warm-up creation.

func (*SandboxPoolBuilder) WarmupSandboxPreparer added in v1.0.4

func (b *SandboxPoolBuilder) WarmupSandboxPreparer(fn func(ctx context.Context, sb *Sandbox) error) *SandboxPoolBuilder

WarmupSandboxPreparer sets an optional callback to prepare sandboxes after warmup.

func (*SandboxPoolBuilder) WarmupSkipHealthCheck added in v1.0.4

func (b *SandboxPoolBuilder) WarmupSkipHealthCheck(skip bool) *SandboxPoolBuilder

WarmupSkipHealthCheck configures whether to skip health check during warmup.

type SandboxReadyTimeoutError

type SandboxReadyTimeoutError struct {
	SandboxID string
	Elapsed   string
	LastErr   error
}

SandboxReadyTimeoutError is returned when WaitUntilReady exceeds the deadline.

func (*SandboxReadyTimeoutError) Error

func (e *SandboxReadyTimeoutError) Error() string

func (*SandboxReadyTimeoutError) Unwrap

func (e *SandboxReadyTimeoutError) Unwrap() error

type SandboxRunningTimeoutError

type SandboxRunningTimeoutError struct {
	SandboxID string
	Elapsed   string
	LastErr   error
}

SandboxRunningTimeoutError is returned when waiting for a sandbox to enter Running state exceeds the deadline.

func (*SandboxRunningTimeoutError) Error

func (*SandboxRunningTimeoutError) Unwrap

func (e *SandboxRunningTimeoutError) Unwrap() error

type SandboxState

type SandboxState string

SandboxState represents the high-level lifecycle state of a sandbox.

const (
	StatePending    SandboxState = "Pending"
	StateRunning    SandboxState = "Running"
	StatePausing    SandboxState = "Pausing"
	StatePaused     SandboxState = "Paused"
	StateStopping   SandboxState = "Stopping"
	StateTerminated SandboxState = "Terminated"
	StateFailed     SandboxState = "Failed"
)

type SandboxStatus

type SandboxStatus struct {
	State            SandboxState `json:"state"`
	Reason           string       `json:"reason,omitempty"`
	Message          string       `json:"message,omitempty"`
	LastTransitionAt *time.Time   `json:"lastTransitionAt,omitempty"`
}

SandboxStatus provides detailed status information with lifecycle state and transition details.

type SandboxUnhealthyError

type SandboxUnhealthyError struct {
	SandboxID string
	Reason    string
}

SandboxUnhealthyError is returned when a sandbox is determined to be unhealthy.

func (*SandboxUnhealthyError) Error

func (e *SandboxUnhealthyError) Error() string

type Session

type Session struct {
	ID string `json:"session_id"`
}

Session represents a bash session with a unique identifier.

type SnapshotInfo added in v1.0.1

type SnapshotInfo struct {
	ID        string         `json:"id"`
	SandboxID string         `json:"sandboxId"`
	Name      string         `json:"name,omitempty"`
	Status    SnapshotStatus `json:"status"`
	CreatedAt time.Time      `json:"createdAt"`
}

type SnapshotState added in v1.0.1

type SnapshotState string
const (
	SnapshotStateCreating SnapshotState = "Creating"
	SnapshotStateDeleting SnapshotState = "Deleting"
	SnapshotStateReady    SnapshotState = "Ready"
	SnapshotStateFailed   SnapshotState = "Failed"
)

type SnapshotStatus added in v1.0.1

type SnapshotStatus struct {
	State            SnapshotState `json:"state"`
	Reason           string        `json:"reason,omitempty"`
	Message          string        `json:"message,omitempty"`
	LastTransitionAt *time.Time    `json:"lastTransitionAt,omitempty"`
}

type StoreCounters added in v1.0.4

type StoreCounters struct {
	IdleCount int
}

StoreCounters contains pool state store counters for observability.

type StreamEvent

type StreamEvent struct {
	// Event is the event type (e.g. "stdout", "stderr", "result").
	// Empty string means no explicit event type was set.
	Event string

	// Data is the event payload. Multiple data lines are joined with newlines.
	Data string

	// ID is the optional event identifier sent by the server.
	ID string
}

StreamEvent represents a single Server-Sent Event received from the server.

type TakeIdleResult added in v1.0.4

type TakeIdleResult struct {
	SandboxID                string
	DiscardedAliveSandboxIDs []string
}

TakeIdleResult is the result of taking an idle sandbox from the store.

type TransportConfig

type TransportConfig struct {
	// MaxIdleConns is the maximum total idle connections across all hosts.
	MaxIdleConns int

	// MaxIdleConnsPerHost is the maximum idle connections kept per host.
	// Go's default is 2, which is too low for SDKs talking to multiple
	// sandbox endpoints concurrently.
	MaxIdleConnsPerHost int

	// IdleConnTimeout is how long an idle connection stays in the pool
	// before being closed.
	IdleConnTimeout time.Duration

	// TLSHandshakeTimeout limits the TLS handshake duration.
	TLSHandshakeTimeout time.Duration

	// DialTimeout limits TCP connection establishment.
	DialTimeout time.Duration

	// KeepAlive sets the TCP keep-alive probe interval.
	KeepAlive time.Duration

	// AllowWeakServerCertKeyLengths allows server certificates below NIST minimum
	// key/hash lengths. Keep false unless interoperability requires legacy certs.
	AllowWeakServerCertKeyLengths bool
}

TransportConfig controls HTTP connection pooling and keep-alive behavior.

func DefaultTransportConfig

func DefaultTransportConfig() TransportConfig

DefaultTransportConfig returns connection pool settings tuned for SDK workloads: moderate concurrency across multiple sandbox endpoints.

func (TransportConfig) NewTransport

func (tc TransportConfig) NewTransport() *http.Transport

NewTransport creates an *http.Transport from the config.

type UploadFileEntry added in v1.0.1

type UploadFileEntry struct {
	File    io.Reader
	Options UploadFileOptions
}

UploadFileEntry describes one file part in a multi-file upload request.

type UploadFileOptions

type UploadFileOptions struct {
	FileName string
	Metadata FileMetadata
}

UploadFileOptions configures the destination path and multipart filename for an upload.

type Volume

type Volume struct {
	Name      string `json:"name"`
	Host      *Host  `json:"host,omitempty"`
	PVC       *PVC   `json:"pvc,omitempty"`
	OSSFS     *OSSFS `json:"ossfs,omitempty"`
	MountPath string `json:"mountPath"`
	ReadOnly  bool   `json:"readOnly,omitempty"`
	SubPath   string `json:"subPath,omitempty"`
}

Volume defines a storage mount for a sandbox.

Jump to

Keyboard shortcuts

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