api

package
v0.1.29 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultCPUs                   = 1
	DefaultMemoryMB               = 512
	DefaultDiskSizeMB             = 5120
	DefaultTimeoutSeconds         = 300
	DefaultNetworkMTU             = 1500
	DefaultGracefulShutdownPeriod = 0
)
View Source
const (
	MountTypeMemory  = "memory"
	MountTypeHostFS  = "host_fs"
	MountTypeOverlay = "overlay"

	MountOptionReadonlyShort = "ro"
	MountOptionReadonly      = "readonly"
)
View Source
const DefaultWorkspace = "/workspace"

DefaultWorkspace is the conventional mount point for the VFS in the guest. VFS is now opt-in and this path is used only when explicitly configured.

Variables

View Source
var (
	ErrBlocked        = errors.New("request blocked by policy")
	ErrHostNotAllowed = errors.New("host not in allowlist")
	ErrSecretLeak     = errors.New("secret placeholder sent to unauthorized host")
	ErrVMNotRunning   = errors.New("VM is not running")
	ErrVMNotFound     = errors.New("VM not found")
	ErrTimeout        = errors.New("operation timed out")
	ErrInvalidConfig  = errors.New("invalid configuration")

	ErrInvalidVolumeFormat = errors.New("expected format host:guest or host:guest:" + MountOptionReadonlyShort)
	ErrResolvePath         = errors.New("failed to resolve path")
	ErrHostPathNotExist    = errors.New("host path does not exist")
	ErrUnknownMountOption  = errors.New("unknown option")
	ErrGuestPathNotAbs     = errors.New("guest path must be absolute")
	ErrGuestPathOutside    = errors.New("guest path must be within workspace")

	ErrEnvNameEmpty   = errors.New("environment variable name cannot be empty")
	ErrEnvNameInvalid = errors.New("environment variable name is invalid")
	ErrEnvVarNotSet   = errors.New("environment variable is not set")
	ErrReadEnvFile    = errors.New("read env file")
	ErrEnvFileLine    = errors.New("parse env file line")

	ErrPortForwardSpecFormat = errors.New("invalid port-forward spec format")
	ErrPortForwardPort       = errors.New("invalid port")

	ErrAddHostSpecFormat = errors.New("invalid add-host format")
	ErrAddHostHost       = errors.New("invalid add-host hostname")
	ErrAddHostIP         = errors.New("invalid add-host ip")
)
View Source
var DefaultDNSServers = []string{"8.8.8.8", "8.8.4.4"}

DefaultDNSServers are used when no custom DNS servers are configured.

Functions

func IsValidCPUCount added in v0.1.29

func IsValidCPUCount(cpus float64) bool

IsValidCPUCount reports whether cpus is finite and greater than zero.

func ParseEnvFile added in v0.1.19

func ParseEnvFile(path string) (map[string]string, error)

ParseEnvFile parses an env file with one variable per line using the same semantics as ParseEnvVar. Blank lines and lines starting with '#' are ignored.

func ParseEnvVar added in v0.1.19

func ParseEnvVar(spec string) (string, string, error)

ParseEnvVar parses an environment variable in Docker-style format: "KEY=VALUE" (inline value) or "KEY" (read from host environment).

func ParseEnvs added in v0.1.19

func ParseEnvs(envSpecs []string, envFiles []string) (map[string]string, error)

ParseEnvs merges env files and explicit env flags into one map. Later values override earlier ones: 1) env files in provided order, then 2) explicit env specs in provided order.

func ParseVolumeMount

func ParseVolumeMount(vol string, workspace string) (hostPath, guestPath string, readonly bool, err error)

ParseVolumeMount parses a volume mount string in format: - "host:guest" - "host:guest:ro" - "host:guest:overlay" - "host:guest:host_fs"

This is kept for backward compatibility with existing callers that only need host/guest/readonly. Use ParseVolumeMountSpec for mount type aware parsing.

Guest paths are resolved within workspace; absolute guest paths must already be under workspace.

func ShellQuoteArgs added in v0.1.1

func ShellQuoteArgs(args []string) string

ShellQuoteArgs joins command arguments into a single shell-safe string using POSIX shell quoting rules.

func VCPUCount added in v0.1.29

func VCPUCount(cpus float64) (int, bool)

VCPUCount rounds a valid CPU value up to a whole vCPU count. The second return value is false when cpus is invalid or overflows int.

func ValidateAddHost added in v0.1.20

func ValidateAddHost(mapping HostIPMapping) error

func ValidateGuestMount added in v0.1.6

func ValidateGuestMount(path string) error

ValidateGuestMount checks that a guest mount path is safe for use in kernel cmdline args and shell scripts.

func ValidateGuestPathWithinWorkspace added in v0.1.19

func ValidateGuestPathWithinWorkspace(guestPath string, workspace string) error

ValidateGuestPathWithinWorkspace checks that guestPath is absolute and inside workspace.

func ValidateVFSMountsWithinWorkspace added in v0.1.19

func ValidateVFSMountsWithinWorkspace(mounts map[string]MountConfig, workspace string) error

ValidateVFSMountsWithinWorkspace checks that all VFS mount paths are valid guest paths under the configured workspace.

Types

type Config

type Config struct {
	ID         string `json:"id,omitempty"`
	Image      string `json:"image,omitempty"`
	Privileged bool   `json:"privileged,omitempty"`
	// LaunchEntrypoint starts image ENTRYPOINT/CMD in detached mode during create.
	// This is used by SDK `launch` convenience helpers.
	LaunchEntrypoint bool              `json:"launch_entrypoint,omitempty"`
	Resources        *Resources        `json:"resources,omitempty"`
	Network          *NetworkConfig    `json:"network,omitempty"`
	VFS              *VFSConfig        `json:"vfs,omitempty"`
	Env              map[string]string `json:"env,omitempty"`
	ExtraDisks       []DiskMount       `json:"extra_disks,omitempty"`
	ImageCfg         *ImageConfig      `json:"image_config,omitempty"`
}

func DefaultConfig

func DefaultConfig() *Config

func ParseConfig

func ParseConfig(data []byte) (*Config, error)

func (*Config) GetHostname added in v0.1.20

func (c *Config) GetHostname() string

GetHostname returns hostname from config or default to ID if not set

func (*Config) GetID added in v0.1.20

func (c *Config) GetID() string

GetID returns the VM ID from config. Creates a new random ID if not set.

func (*Config) GetWorkspace

func (c *Config) GetWorkspace() string

GetWorkspace returns the workspace path from config, or empty when unset.

func (*Config) HasVFSMounts added in v0.1.24

func (c *Config) HasVFSMounts() bool

HasVFSMounts reports whether VFS is enabled with at least one mount.

func (*Config) Merge

func (c *Config) Merge(other *Config) *Config

func (*Config) ValidateVFS added in v0.1.24

func (c *Config) ValidateVFS() error

ValidateVFS checks VFS config invariants.

Rules: - vfs.workspace requires at least one vfs.mounts entry - vfs.mounts requires a non-empty vfs.workspace - vfs.interception requires at least one vfs.mounts entry - vfs.workspace must be a safe absolute guest path - every vfs.mounts key must be under vfs.workspace

type DirectMount

type DirectMount struct {
	HostPath string `json:"host_path"`
	Readonly bool   `json:"readonly,omitempty"`
}

type DiskMount added in v0.1.6

type DiskMount struct {
	HostPath   string `json:"host_path"`
	GuestMount string `json:"guest_mount"`
	ReadOnly   bool   `json:"readonly,omitempty"`
}

DiskMount describes a persistent ext4 disk image to attach as a block device.

type Event

type Event struct {
	Type      string        `json:"type"`
	Timestamp int64         `json:"timestamp"`
	Network   *NetworkEvent `json:"network,omitempty"`
	File      *FileEvent    `json:"file,omitempty"`
	Exec      *ExecEvent    `json:"exec,omitempty"`
}

type ExecEvent

type ExecEvent struct {
	Command  string `json:"command"`
	ExitCode int    `json:"exit_code"`
}

type ExecOptions

type ExecOptions struct {
	WorkingDir string
	Env        map[string]string
	Stdin      io.Reader
	Stdout     io.Writer
	Stderr     io.Writer
	User       string // "uid", "uid:gid", or username — resolved in guest
}

type ExecResult

type ExecResult struct {
	ExitCode   int           `json:"exit_code"`
	Stdout     []byte        `json:"stdout,omitempty"`
	Stderr     []byte        `json:"stderr,omitempty"`
	DurationMS int64         `json:"duration_ms"`
	Duration   time.Duration `json:"-"`
}

type FileEvent

type FileEvent struct {
	Op   string `json:"op"`
	Path string `json:"path"`
	Size int64  `json:"size"`
	Mode uint32 `json:"mode,omitempty"`
	UID  int    `json:"uid,omitempty"`
	GID  int    `json:"gid,omitempty"`
}

type FileInfo

type FileInfo struct {
	Name    string    `json:"name"`
	Size    int64     `json:"size"`
	Mode    uint32    `json:"mode"`
	ModTime time.Time `json:"mod_time"`
	IsDir   bool      `json:"is_dir"`
}

type HTTPHooks

type HTTPHooks struct {
	OnRequest  func(req *http.Request) (*http.Request, error)
	OnResponse func(resp *http.Response, req *http.Request) (*http.Response, error)
}

type HostIPMapping added in v0.1.20

type HostIPMapping struct {
	Host string `json:"host"`
	IP   string `json:"ip"`
}

func ParseAddHost added in v0.1.20

func ParseAddHost(spec string) (HostIPMapping, error)

func ParseAddHosts added in v0.1.20

func ParseAddHosts(specs []string) ([]HostIPMapping, error)

type ImageConfig added in v0.1.10

type ImageConfig struct {
	User       string            `json:"user,omitempty"`
	WorkingDir string            `json:"working_dir,omitempty"`
	Entrypoint []string          `json:"entrypoint,omitempty"`
	Cmd        []string          `json:"cmd,omitempty"`
	Env        map[string]string `json:"env,omitempty"`
}

func (*ImageConfig) ComposeCommand added in v0.1.10

func (ic *ImageConfig) ComposeCommand(userArgs []string) []string

ComposeCommand builds a shell command from image ENTRYPOINT/CMD and user-provided args. Follows Docker semantics: if user provides args, they replace CMD; ENTRYPOINT is always prepended.

type MountConfig

type MountConfig struct {
	Type     string       `json:"type"`
	HostPath string       `json:"host_path,omitempty"`
	Readonly bool         `json:"readonly,omitempty"`
	Upper    *MountConfig `json:"upper,omitempty"`
	Lower    *MountConfig `json:"lower,omitempty"`
}

type NetworkBodyTransform added in v0.1.24

type NetworkBodyTransform struct {
	Find    string `json:"find"`
	Replace string `json:"replace,omitempty"`
}

NetworkBodyTransform applies a literal replacement. For text/event-stream, replacements are applied to each SSE data line payload.

type NetworkConfig

type NetworkConfig struct {
	AllowedHosts    []string                   `json:"allowed_hosts,omitempty"`
	AddHosts        []HostIPMapping            `json:"add_hosts,omitempty"`
	BlockPrivateIPs bool                       `json:"block_private_ips,omitempty"`
	NoNetwork       bool                       `json:"no_network,omitempty"`
	Intercept       bool                       `json:"intercept,omitempty"`
	Interception    *NetworkInterceptionConfig `json:"interception,omitempty"`
	Secrets         map[string]Secret          `json:"secrets,omitempty"`
	PolicyScript    string                     `json:"policy_script,omitempty"`
	DNSServers      []string                   `json:"dns_servers,omitempty"`
	Hostname        string                     `json:"hostname,omitempty"`
	MTU             int                        `json:"mtu,omitempty"`
}

func (*NetworkConfig) GetDNSServers added in v0.1.7

func (n *NetworkConfig) GetDNSServers() []string

GetDNSServers returns the configured DNS servers or defaults.

func (*NetworkConfig) GetMTU added in v0.1.20

func (n *NetworkConfig) GetMTU() int

GetMTU returns the configured network MTU or the default.

func (*NetworkConfig) Validate added in v0.1.24

func (n *NetworkConfig) Validate() error

Validate checks network config invariants.

type NetworkEvent

type NetworkEvent struct {
	Method        string `json:"method"`
	URL           string `json:"url"`
	Host          string `json:"host"`
	StatusCode    int    `json:"status_code"`
	RequestBytes  int64  `json:"request_bytes"`
	ResponseBytes int64  `json:"response_bytes"`
	DurationMS    int64  `json:"duration_ms"`
	Blocked       bool   `json:"blocked"`
	BlockReason   string `json:"block_reason,omitempty"`
}

type NetworkHookCallbackRequest added in v0.1.24

type NetworkHookCallbackRequest struct {
	CallbackID string `json:"callback_id"`
	Phase      string `json:"phase"`
	Host       string `json:"host,omitempty"`
	Method     string `json:"method,omitempty"`
	Path       string `json:"path,omitempty"`

	Query          map[string]string   `json:"query,omitempty"`
	RequestHeaders map[string][]string `json:"request_headers,omitempty"`

	StatusCode      int                 `json:"status_code,omitempty"`
	ResponseHeaders map[string][]string `json:"response_headers,omitempty"`
	IsSSE           bool                `json:"is_sse,omitempty"`
}

NetworkHookCallbackRequest is sent from host interception logic to an SDK-local callback server when a matching callback rule is triggered.

type NetworkHookCallbackResponse added in v0.1.24

type NetworkHookCallbackResponse struct {
	Action string `json:"action,omitempty"` // allow, block, mutate

	Request  *NetworkHookRequestMutation  `json:"request,omitempty"`
	Response *NetworkHookResponseMutation `json:"response,omitempty"`

	Error string `json:"error,omitempty"`
}

NetworkHookCallbackResponse is returned by an SDK-local callback server.

type NetworkHookRequestMutation added in v0.1.24

type NetworkHookRequestMutation struct {
	// Headers replaces the full outbound request header map when non-nil.
	Headers map[string][]string `json:"headers"`
	// Query replaces the full outbound query map when non-nil.
	Query map[string]string `json:"query"`
	// Path rewrites the outbound request path when non-empty.
	Path string `json:"path,omitempty"`
}

NetworkHookRequestMutation describes request-shaping changes returned by an SDK-local callback.

type NetworkHookResponseMutation added in v0.1.24

type NetworkHookResponseMutation struct {
	// Headers replaces the full inbound response header map when non-nil.
	Headers          map[string][]string    `json:"headers"`
	BodyReplacements []NetworkBodyTransform `json:"body_replacements,omitempty"`
	// SetBodyBase64 replaces the entire response body when non-nil.
	SetBodyBase64 *string `json:"set_body_base64,omitempty"`
}

NetworkHookResponseMutation describes response-shaping changes returned by an SDK-local callback.

type NetworkHookRule added in v0.1.24

type NetworkHookRule struct {
	Name  string `json:"name,omitempty"`
	Phase string `json:"phase,omitempty"` // before, after

	Hosts   []string `json:"hosts,omitempty"`   // glob patterns; empty matches all hosts
	Methods []string `json:"methods,omitempty"` // HTTP methods; empty matches all methods
	Path    string   `json:"path,omitempty"`    // URL path glob; empty matches all paths

	Action string `json:"action,omitempty"` // allow, block, mutate
	// CallbackID identifies an SDK-local callback hook for this rule.
	// This is intended for SDK-internal use.
	CallbackID string `json:"callback_id,omitempty"`
	// TimeoutMS applies to SDK-local callback execution.
	TimeoutMS int `json:"timeout_ms,omitempty"`

	// Before-phase request mutations.
	SetHeaders    map[string]string `json:"set_headers,omitempty"`
	DeleteHeaders []string          `json:"delete_headers,omitempty"`
	SetQuery      map[string]string `json:"set_query,omitempty"`
	DeleteQuery   []string          `json:"delete_query,omitempty"`
	RewritePath   string            `json:"rewrite_path,omitempty"`

	// After-phase response mutations.
	SetResponseHeaders    map[string]string      `json:"set_response_headers,omitempty"`
	DeleteResponseHeaders []string               `json:"delete_response_headers,omitempty"`
	BodyReplacements      []NetworkBodyTransform `json:"body_replacements,omitempty"`
}

NetworkHookRule describes one network interception rule.

type NetworkInterceptionConfig added in v0.1.24

type NetworkInterceptionConfig struct {
	Rules []NetworkHookRule `json:"rules,omitempty"`
	// CallbackSocket enables SDK-local callback hooks over a Unix domain socket.
	// This is intended for SDK-internal use.
	CallbackSocket string `json:"callback_socket,omitempty"`
}

NetworkInterceptionConfig configures host-side HTTP(S) interception hooks.

type PortForward added in v0.1.20

type PortForward struct {
	LocalPort  int `json:"local_port"`
	RemotePort int `json:"remote_port"`
}

PortForward maps a local host port to a remote guest port.

func ParsePortForward added in v0.1.20

func ParsePortForward(spec string) (PortForward, error)

ParsePortForward parses a single spec in the form [LOCAL_PORT:]REMOTE_PORT.

func ParsePortForwards added in v0.1.20

func ParsePortForwards(specs []string) ([]PortForward, error)

ParsePortForwards parses specs in the form [LOCAL_PORT:]REMOTE_PORT.

type PortForwardBinding added in v0.1.20

type PortForwardBinding struct {
	Address    string `json:"address"`
	LocalPort  int    `json:"local_port"`
	RemotePort int    `json:"remote_port"`
}

PortForwardBinding is a realized local listener binding.

type Resources

type Resources struct {
	CPUs           float64       `json:"cpus,omitempty"`
	MemoryMB       int           `json:"memory_mb,omitempty"`
	DiskSizeMB     int           `json:"disk_size_mb,omitempty"`
	TimeoutSeconds int           `json:"timeout_seconds,omitempty"`
	Timeout        time.Duration `json:"-"`
}

type Secret

type Secret struct {
	Value       string   `json:"value"`
	Placeholder string   `json:"placeholder,omitempty"`
	Hosts       []string `json:"hosts"`
}

func ParseSecret added in v0.1.1

func ParseSecret(s string) (string, Secret, error)

ParseSecret parses a secret string in the format "NAME=VALUE@host1,host2" or "NAME@host1,host2". When no inline value is provided, the value is read from the environment variable $NAME.

type VFSConfig

type VFSConfig struct {
	Workspace    string                 `json:"workspace,omitempty"`
	DirectMounts map[string]DirectMount `json:"direct_mounts,omitempty"`
	Mounts       map[string]MountConfig `json:"mounts,omitempty"`
	Interception *VFSInterceptionConfig `json:"interception,omitempty"`
}

func (*VFSConfig) GetWorkspace

func (v *VFSConfig) GetWorkspace() string

GetWorkspace returns the configured workspace path, or empty when unset.

type VFSHookRule added in v0.1.19

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

	// Phase is either "before" or "after".
	// Empty defaults to "before".
	Phase string `json:"phase,omitempty"`

	// Ops filters operations (for example: read, write, create, open).
	// Empty matches all operations.
	Ops []string `json:"ops,omitempty"`

	// Path is a filepath-style glob pattern (for example: /workspace/*).
	// Empty matches all paths.
	Path string `json:"path,omitempty"`

	// Action is one of: allow, block.
	Action string `json:"action"`

	// TimeoutMS is interpreted by SDK-local callback execution and ignored by
	// host wire rules.
	TimeoutMS int `json:"timeout_ms,omitempty"`
}

VFSHookRule describes a single interception rule.

type VFSHooks

type VFSHooks struct {
	BeforeOpen  func(path string, flags int) error
	AfterRead   func(path string, n int)
	AfterWrite  func(path string, n int)
	BeforeClose func(path string)
}

type VFSInterceptionConfig added in v0.1.19

type VFSInterceptionConfig struct {
	// EmitEvents enables file-operation event notifications.
	EmitEvents bool `json:"emit_events,omitempty"`

	Rules []VFSHookRule `json:"rules,omitempty"`
}

VFSInterceptionConfig configures host-side VFS interception rules.

type VM

type VM interface {
	ID() string
	Config() *Config
	Start(ctx context.Context) error
	Stop(ctx context.Context) error
	Exec(ctx context.Context, command string, opts *ExecOptions) (*ExecResult, error)
	WriteFile(ctx context.Context, path string, content []byte, mode uint32) error
	ReadFile(ctx context.Context, path string) ([]byte, error)
	ListFiles(ctx context.Context, path string) ([]FileInfo, error)
	Events() <-chan Event
	Close() error
}

type VolumeMountSpec added in v0.1.21

type VolumeMountSpec struct {
	HostPath  string
	GuestPath string
	Type      string
	Readonly  bool
}

VolumeMountSpec is a parsed -v/--volume specification.

func ParseVolumeMountSpec added in v0.1.21

func ParseVolumeMountSpec(vol string, workspace string) (VolumeMountSpec, error)

ParseVolumeMountSpec parses a volume mount string and returns a typed spec.

Jump to

Keyboard shortcuts

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