sandbox

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 15 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sandbox is the contract between an agent and the place its commands run: a directory on this machine or a container elsewhere.

A Backend creates and reconnects Sandboxes (Exec, ReadFile, WriteFile, List, Stat, Healthy). A Manager owns the lifecycle for a conversation: one sandbox per thread, created on first use, a quota per user, health checks, and the replacement of a dead one. Implement Backend to add a new kind of sandbox and prove it with the conformance suite in package sandboxtest; adapters/sandbox has the local and OpenSandbox implementations.

Index

Constants

View Source
const (
	// OutputsDir holds the final deliverables.
	OutputsDir = Workspace + "/outputs"
	// ScratchDir is scratch space, never saved.
	ScratchDir = Workspace + "/.work"
	// ToolOutputDir receives spilled tool outputs.
	ToolOutputDir = ScratchDir + "/tool-output"
	// RendersDir receives view_file renders.
	RendersDir = ScratchDir + "/renders"
)

The /workspace layout the prompts, tools and skills advertise.

View Source
const PlaceMarker = "# work:place"

PlaceMarker is the first line of the place script (sandboxtest fakes it).

View Source
const ReadFilesMarker = "# work:read-files"

ReadFilesMarker is the first line of the read-files script (sandboxtest fakes it).

View Source
const RealPathMarker = "# work:realpath"

RealPathMarker is the first line of the realpath script (sandboxtest fakes it).

View Source
const StagingDir = ScratchDir + "/.staging"

StagingDir receives the uploads WriteFileNoFollow moves into place.

View Source
const UnstageMarker = "# work:unstage"

UnstageMarker is the first line of the unstage script (sandboxtest fakes it).

View Source
const Workspace = "/workspace"

Workspace is the working directory inside every sandbox.

Variables

View Source
var (
	// ErrNoSandbox means the thread has no live sandbox (Get never creates one).
	ErrNoSandbox = errors.New("no sandbox for this thread")
	// ErrNotFound means the file or directory does not exist.
	ErrNotFound = errors.New("no such file or directory")
	// ErrQuota means the user reached MAX_SANDBOXES_PER_USER.
	ErrQuota = errors.New("sandbox quota reached")
	// ErrUnavailable is a transient failure (unhealthy, timeout, provider error): retry later.
	// The sandbox is kept; only a definitive "not found" forgets it.
	ErrUnavailable = errors.New("the sandbox is temporarily unavailable")
	// ErrDisabled means OPENSANDBOX_URL is not configured.
	ErrDisabled = errors.New("sandbox is disabled")
	// ErrGone means an operation found the sandbox itself gone at the provider
	// (removed, expired): its handle must be invalidated (see IsGone).
	ErrGone = errors.New("the sandbox no longer exists")
)
View Source
var ErrRealPath = errors.New("the sandbox could not resolve the path")

ErrRealPath means the sandbox could not resolve a path (fail closed).

View Source
var ErrSymlinkTarget = errors.New("the target is a symbolic link or inside one")

ErrSymlinkTarget means a write was refused because its target is, or is inside, a symbolic link (a *SymlinkError names the real directory).

View Source
var ErrThreadNotFound = errors.New("sandbox: thread not found")

ErrThreadNotFound is what a Store returns for an unknown or deleted thread.

Layout lists the directories of a fresh /workspace, parents first.

Functions

func IsGone

func IsGone(err error) bool

IsGone reports whether an operation failed because the sandbox itself no longer exists: ErrGone (a 404 the backend attributed to the sandbox) or the provider's SANDBOX_NOT_FOUND code, whatever wrapped it. A missing file (ErrNotFound) is not a gone sandbox.

func KeepAlive

func KeepAlive(ctx context.Context, sb Sandbox) func()

KeepAlive renews a sandbox handed out by a DefaultManager (Acquire, Get) until the returned stop is called or ctx ends — for work that outlives one Exec call (background jobs). Other sandboxes get a no-op.

func NoticeOf

func NoticeOf(sb Sandbox) string

NoticeOf returns the OnCreate notice of a freshly created sandbox ("" otherwise).

func PrepareWorkspace

func PrepareWorkspace(ctx context.Context, sb Sandbox) error

PrepareWorkspace creates the Layout in sb (idempotent). The image ships none of it, and the agent's first `cat > /workspace/.work/x.py` would fail.

func Quiet

func Quiet(ctx context.Context) context.Context

Quiet marks an Acquire made on behalf of the API (an Office preview, a version or workspace restore): when it creates the sandbox, the notice for the model (workspace restored / recreated) is kept for the thread and given to the next Acquire that is not quiet (the agent's next tool call).

func Quieted

func Quieted(ctx context.Context) bool

Quieted reports a Quiet context.

func RealPath

func RealPath(ctx context.Context, sb Sandbox, p string) (string, error)

RealPath is RealPaths for one path.

func RealPaths

func RealPaths(ctx context.Context, sb Sandbox, paths []string) ([]string, error)

RealPaths resolves the symlinks of absolute sandbox paths in sb (review round 1: files/content and the approval work-area check decide on the real path).

func Retry

func Retry(ctx context.Context, mgr Manager, threadID string, acquire func(context.Context) (Sandbox, error), op func(Sandbox) error) error

Retry runs op on the sandbox returned by acquire. When op fails because the sandbox is gone (IsGone), the thread's handle is invalidated and op runs once more on a freshly acquired sandbox (which gets the workspace restore and the recreation notice). acquire's errors are returned as is.

func UserTag

func UserTag(login string) string

UserTag is the hashed login stored in sandbox metadata.

func WasRecreated

func WasRecreated(sb Sandbox) bool

WasRecreated reports whether Acquire had to replace the thread's sandbox.

func WriteFileNoFollow

func WriteFileNoFollow(ctx context.Context, sb Sandbox, p string, data []byte) error

WriteFileNoFollow writes data to p without following a symbolic link at p or in its directory (round 3, N6: the approval gate's realpath and the write are two operations; this one re-checks in the exec that writes). The content is uploaded under StagingDir, then moved into place by one script that checks the target first. A refusal is a *SymlinkError (ErrSymlinkTarget).

func WriteFrom

func WriteFrom(ctx context.Context, sb Sandbox, p string, r io.Reader) error

WriteFrom writes r into the sandbox at p: streamed when the sandbox supports it, else read into memory first.

Types

type AuthKind

type AuthKind string

AuthKind says how a binding presents its credential.

const (
	// AuthBasic sends "Authorization: Basic <value>"; the value must already be base64("user:password").
	AuthBasic AuthKind = "basic"
	// AuthBearer sends "Authorization: Bearer <value>".
	AuthBearer AuthKind = "bearer"
)

type Backend

type Backend interface {
	Create(ctx context.Context, opts CreateOptions) (Instance, error)
	// Connect returns ErrNoSandbox only when the sandbox definitively no longer
	// exists (404, Terminated/Failed); any other error is transient.
	Connect(ctx context.Context, id string) (Instance, error)
	Kill(ctx context.Context, id string) error
}

Backend talks to the sandbox provider.

type Coordinator

type Coordinator interface {
	// SetNX stores key=token for ttl unless the key exists.
	SetNX(ctx context.Context, key, token string, ttl time.Duration) (bool, error)
	// Renew extends key's ttl while it still holds token.
	Renew(ctx context.Context, key, token string, ttl time.Duration) (bool, error)
	// Unlock deletes key while it still holds token.
	Unlock(ctx context.Context, key, token string) error
	Set(ctx context.Context, key, value string, ttl time.Duration) error
	// Del reports whether the key existed.
	Del(ctx context.Context, key string) (bool, error)
	// Take returns the value of key and deletes it ("" when absent).
	Take(ctx context.Context, key string) (string, error)
	// Unhealthy records a failed health check: it returns when the streak
	// started (unix ms, the first call's now) and the number of checks so far.
	Unhealthy(ctx context.Context, key string, nowMs int64, ttl time.Duration) (firstMs, checks int64, err error)
}

Coordinator is the small shared state the manager needs to cooperate across replicas: creation locks, health-streak counters and one-shot markers. redisx.Coordinator (Redis) shares it between processes; LocalCoordinator keeps it in memory (a single process: a TUI, a desktop app or tests).

type CreateOptions

type CreateOptions struct {
	Metadata map[string]string
	// Profile names the environment the sandbox should provide ("coding", "work", ...). The deployment maps a profile
	// to an image (a snapshot, a template, a container image) in its configuration (SANDBOX_IMAGES); a backend that
	// has no image for the name, or none at all, uses its default.
	Profile string
}

CreateOptions are per-sandbox creation options.

type Credential

type Credential struct {
	Name  string
	Value string
}

Credential is a named secret held outside the sandbox.

type CredentialBinding

type CredentialBinding struct {
	Name       string
	Host       string
	Methods    []string
	Paths      []string
	Auth       AuthKind
	Credential string
}

CredentialBinding attaches a credential to the HTTPS requests that match its host, methods and paths. Paths are globs ("/owner/repo.git*"); empty Methods means every method.

type CredentialBroker

type CredentialBroker interface {
	// SetCredentials replaces the broker's credentials and bindings with set (idempotent). It is called again
	// to renew a short-lived token.
	SetCredentials(ctx context.Context, set CredentialSet) error
}

CredentialBroker is implemented by sandboxes that can inject credentials outside the workload.

func BrokerOf

func BrokerOf(sb Sandbox) CredentialBroker

BrokerOf returns the credential broker of sb, looking through the wrappers a Manager puts around a sandbox; nil when the backend has none.

type CredentialSet

type CredentialSet struct {
	Credentials []Credential
	Bindings    []CredentialBinding
}

CredentialSet is the complete desired state: SetCredentials makes the sandbox's broker equal to it.

type DefaultManager

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

DefaultManager implements Manager with a Backend, the thread store and a Redis lock.

func NewManager

func NewManager(backend Backend, st Store, coord Coordinator, opts ManagerOptions) *DefaultManager

NewManager builds a manager over a Coordinator (nil: in-process state, a single process). A nil backend yields a disabled manager.

func (*DefaultManager) Acquire

func (m *DefaultManager) Acquire(ctx context.Context, threadID, login string) (Sandbox, error)

func (*DefaultManager) Enabled

func (m *DefaultManager) Enabled() bool

func (*DefaultManager) Get

func (m *DefaultManager) Get(ctx context.Context, threadID string) (Sandbox, error)

func (*DefaultManager) Invalidate

func (m *DefaultManager) Invalidate(ctx context.Context, threadID, sandboxID string)

Invalidate implements Manager.

func (*DefaultManager) Kill

func (m *DefaultManager) Kill(ctx context.Context, sandboxID string) error

type ExecRequest

type ExecRequest struct {
	Command  string
	Cwd      string
	Timeout  time.Duration
	Env      map[string]string
	OnStdout func(text string)
	OnStderr func(text string)
}

ExecRequest runs a shell command.

type ExecResult

type ExecResult struct {
	ExitCode int
}

ExecResult is the outcome of a command. A non-zero exit is not an error.

type FileInfo

type FileInfo struct {
	Path       string
	Type       string // "file" | "directory"
	Size       int64
	ModifiedAt time.Time
}

FileInfo describes a sandbox file.

type FileRead

type FileRead struct {
	Path string
	// Stamp is "size mtime" (seconds).
	Stamp string
	// Unchanged: the stamp matched the known one; Data is not read.
	Unchanged bool
	Data      []byte
}

FileRead is one file found by ReadRegularFiles.

func ReadRegularFiles

func ReadRegularFiles(ctx context.Context, sb Sandbox, paths, known []string, budget int64) ([]FileRead, error)

ReadRegularFiles reads, with one command, the files among paths (absolute, clean) that are regular files reached without a symlink: symlinks, FIFOs, devices, directories and missing paths are skipped. known[i] is the stamp the caller holds for paths[i] ("size mtime", "size -" for the size only, "" none): a file still matching it is returned Unchanged, without its content. The contents read share budget bytes (a file read past it is cut).

type Instance

type Instance interface {
	Sandbox
	Healthy(ctx context.Context) bool
	// Gone reports a definitive end of life (lifecycle state Terminated/Failed, or 404).
	Gone(ctx context.Context) bool
	Renew(ctx context.Context, d time.Duration) error
}

Instance is a backend sandbox with lifecycle operations.

type JobList

type JobList interface {
	// Add records a running job and returns its start: the first one recorded.
	Add(ctx context.Context, threadID, jobID string) (time.Time, error)
	Remove(ctx context.Context, threadID, jobID string) error
	List(ctx context.Context) ([]ListedJob, error)
	// Claim takes the job's lease for owner, or renews it when owner holds it
	// (false: another process holds it).
	Claim(ctx context.Context, threadID, jobID, owner string, ttl time.Duration) (bool, error)
	// Release drops owner's lease.
	Release(ctx context.Context, threadID, jobID, owner string) error
}

JobList persists the running background jobs so that a restarted runtime process resumes their keep-alives (ResumeJobs), and leases each job to one process at a time.

type ListedJob

type ListedJob struct {
	ThreadID, JobID string
	// Started is when the job started (its keep-alive budget counts from it).
	Started time.Time
}

ListedJob is a running background job of the JobList.

type LocalCoordinator

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

LocalCoordinator is the in-process Coordinator.

func NewLocalCoordinator

func NewLocalCoordinator() *LocalCoordinator

NewLocalCoordinator returns an empty in-memory Coordinator.

func (*LocalCoordinator) Del

func (c *LocalCoordinator) Del(_ context.Context, key string) (bool, error)

func (*LocalCoordinator) Exists

func (c *LocalCoordinator) Exists(_ context.Context, key string) (bool, error)

Exists reports whether key holds a live value.

func (*LocalCoordinator) Renew

func (c *LocalCoordinator) Renew(_ context.Context, key, token string, ttl time.Duration) (bool, error)

func (*LocalCoordinator) Set

func (c *LocalCoordinator) Set(_ context.Context, key, value string, ttl time.Duration) error

func (*LocalCoordinator) SetNX

func (c *LocalCoordinator) SetNX(_ context.Context, key, token string, ttl time.Duration) (bool, error)

func (*LocalCoordinator) Take

func (c *LocalCoordinator) Take(_ context.Context, key string) (string, error)

func (*LocalCoordinator) Unhealthy

func (c *LocalCoordinator) Unhealthy(_ context.Context, key string, nowMs int64, ttl time.Duration) (int64, int64, error)

func (*LocalCoordinator) Unlock

func (c *LocalCoordinator) Unlock(_ context.Context, key, token string) error

type Manager

type Manager interface {
	Enabled() bool
	// Acquire returns the thread's sandbox, creating it when needed.
	Acquire(ctx context.Context, threadID, login string) (Sandbox, error)
	// Get returns the thread's sandbox or ErrNoSandbox; it never creates one.
	Get(ctx context.Context, threadID string) (Sandbox, error)
	// Kill destroys a sandbox (best effort).
	Kill(ctx context.Context, sandboxID string) error
	// Invalidate drops the handle of a sandbox an operation found gone; once the
	// provider confirms it no longer exists (the definitive 404 rule of
	// Backend.Connect), the thread forgets it and the next Acquire creates a
	// new one, flagged as recreated.
	Invalidate(ctx context.Context, threadID, sandboxID string)
}

Manager hands out the sandbox of a thread.

type ManagerOptions

type ManagerOptions struct {
	// Profile is passed to Backend.Create as CreateOptions.Profile: which image the deployment's sandboxes start from.
	Profile    string
	MaxPerUser int
	// Timeout is the idle lifetime given to the provider on each renewal.
	Timeout time.Duration
	// RenewEvery throttles renewals and paces the keep-alive of running
	// commands (default 60 s, at most Timeout/3).
	RenewEvery time.Duration
	// CacheIdle drops cached handles unused for this long (default 10 min).
	CacheIdle time.Duration
	// CacheSize caps cached handles (default 1000).
	CacheSize int
	// LockTTL is the TTL of the creation locks (thread, user quota), renewed
	// every LockTTL/3 while held, so a slow creation never loses them (default 30 s; C-10).
	LockTTL time.Duration
	// LockWait bounds the wait for a creation lock (default 3 min).
	LockWait time.Duration
	// HealthRecheck: a cached handle checked healthy more recently is used without a new check (default 30 s).
	HealthRecheck time.Duration
	// UnhealthyRecreate: a sandbox continuously unhealthy for longer than this,
	// checked at least 3 times (across replicas), is killed and recreated (default 5 min).
	UnhealthyRecreate time.Duration
	// HealthTimeout bounds one connect + health attempt (default 10 s).
	HealthTimeout time.Duration
	// OnCreate runs after a sandbox is created for a thread (workspace restore),
	// before the sandbox is recorded for the thread: nobody else can use it
	// until the restore finished (C-11). The returned notice reaches the model
	// with the next tool result (kept for the next agent Acquire when the
	// creation was Quiet; C-18).
	OnCreate func(ctx context.Context, threadID string, sb Sandbox, recreated bool) string
}

ManagerOptions configures the manager.

type Sandbox

type Sandbox interface {
	ID() string
	Exec(ctx context.Context, req ExecRequest) (ExecResult, error)
	// ReadFile returns at most maxBytes of the file and its full size.
	ReadFile(ctx context.Context, path string, maxBytes int64) (data []byte, size int64, err error)
	// WriteFile creates parent directories and writes the file (mode 0644).
	WriteFile(ctx context.Context, path string, data []byte) error
	MkdirAll(ctx context.Context, path string) error
	List(ctx context.Context, path string, depth int) ([]FileInfo, error)
	Stat(ctx context.Context, path string) (FileInfo, error)
}

Sandbox is a live sandbox usable by tools and the files API.

func MarkRecreated

func MarkRecreated(sb Sandbox) Sandbox

MarkRecreated wraps a sandbox that replaced a gone or unresponsive one (/workspace was reset).

type Store

type Store interface {
	// ThreadSandbox returns the sandbox recorded for the thread ("" when none), or
	// ErrThreadNotFound when the thread is unknown or deleted.
	ThreadSandbox(ctx context.Context, threadID string) (string, error)
	// SetThreadSandbox sets sandbox_id when it currently equals expected.
	SetThreadSandbox(ctx context.Context, threadID, expected, sandboxID string) error
	CountUserSandboxes(ctx context.Context, login string) (int, error)
	// SwapThreadSandbox is SetThreadSandbox reporting whether it changed the row
	// (false: another sandbox was recorded meanwhile, or the thread was deleted).
	SwapThreadSandbox(ctx context.Context, threadID, expected, sandboxID string) (bool, error)
	// UserSandboxes lists the user's live threads with a recorded sandbox.
	UserSandboxes(ctx context.Context, login string) ([]UserSandbox, error)
}

Store is what the manager needs from the thread store: the sandbox id recorded on each thread.

type StreamWriter

type StreamWriter interface {
	WriteFileFrom(ctx context.Context, path string, r io.Reader) error
}

StreamWriter is a sandbox that writes a file from a reader without holding its whole content in memory (uploads).

type SymlinkError

type SymlinkError struct{ RealDir string }

SymlinkError is the refusal of WriteFileNoFollow.

func (*SymlinkError) Error

func (e *SymlinkError) Error() string

func (*SymlinkError) Unwrap

func (e *SymlinkError) Unwrap() error

type UserSandbox

type UserSandbox struct {
	ThreadID  string
	SandboxID string
}

UserSandbox is a live thread of a user with a recorded sandbox.

Directories

Path Synopsis
Package sandboxtest provides an in-memory sandbox backend for tests.
Package sandboxtest provides an in-memory sandbox backend for tests.

Jump to

Keyboard shortcuts

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