# Sandbox (/docs/go-sdk/sandbox)

> For AI agents: the complete documentation index is at https://www.daytona.com/llms.txt.

## Sandbox [#sandbox]

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

Sandbox is a concurrency-safe live handle. Obtain one from Client.Get, List,
Search or FindByName. Metadata getters do not perform I/O.

#### Sandbox.AccessToken [#sandboxaccesstoken]

```go
func (s *Sandbox) AccessToken() (token string, expiresAt time.Time)
```

AccessToken returns the sandbox access token the handle currently holds and
when it expires (zero when unknown). The token is a credential for this
sandbox's toolbox: never log or print it. It is empty until the API issued
one or GetSandboxOptions supplied one; the SDK mints and refreshes it as
needed when the handle calls the toolbox.

#### Sandbox.BuildLogs [#sandboxbuildlogs]

```go
func (s *Sandbox) BuildLogs(ctx context.Context) (*BuildLogsSnapshot, error)
```

BuildLogs returns a one-shot text snapshot, bounded to 2 MiB. ErrNotFound
means no image build was found. The client's request timeout bounds the
entire read, including discovery; NoTimeout leaves only the context bound.

**Example**:

```go
client, err := daytona.New()
if err != nil {
	log.Print(err)
	return
}
defer func() {
	if closeErr := client.Close(); closeErr != nil {
		log.Print(closeErr)
	}
}()
ctx := context.Background()
sandbox, err := client.Get(ctx, "sandbox-id", nil)
if err != nil {
	log.Print(err)
	return
}
snapshot, err := sandbox.BuildLogs(ctx)
if err != nil {
	log.Print(err)
	return
}
fmt.Print(snapshot.Text)
```

#### Sandbox.CaptureImage [#sandboxcaptureimage]

```go
func (s *Sandbox) CaptureImage(ctx context.Context, opts *CaptureImageOptions) (*Image, error)
```

CaptureImage captures the sandbox filesystem as an image without waiting
for readiness. Linux sandboxes keep running. macOS requires a stopped,
persistent sandbox; ErrDiskNotReady means the disk is not ready yet.
Combining Name and IdleExpiry returns ErrBadRequest before any request.

#### Sandbox.ComputerUse [#sandboxcomputeruse]

```go
func (s *Sandbox) ComputerUse() *ComputerUse
```

ComputerUse returns a concurrency-safe desktop automation namespace.

**Example**:

```go
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
client, err := daytona.New()
if err != nil {
	log.Fatal(err)
}
defer func() {
	if closeErr := client.Close(); closeErr != nil {
		log.Print(closeErr)
	}
}()
sandbox, err := client.Get(ctx, "sandbox-id", nil)
if err != nil {
	log.Fatal(err)
}
desktop := sandbox.ComputerUse()
if _, startErr := desktop.Start(ctx, nil); startErr != nil {
	log.Fatal(startErr)
}
if _, clickErr := desktop.Mouse().Click(ctx, daytona.ComputerUsePoint{X: 100, Y: 200}, nil); clickErr != nil {
	log.Fatal(clickErr)
}
if typeErr := desktop.Keyboard().Type(ctx, "Hello desktop", nil); typeErr != nil {
	log.Fatal(typeErr)
}
image, err := desktop.Screen().Screenshot(ctx, nil)
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Captured %d bytes\n", len(image.Data))
```

#### Sandbox.CreateAccessToken [#sandboxcreateaccesstoken]

```go
func (s *Sandbox) CreateAccessToken(ctx context.Context, opts *CreateAccessTokenOptions) (*SandboxAccessToken, error)
```

CreateAccessToken mints a delegated credential without changing this handle's
own authentication. Nil options use server defaults. Invalid port numbers or
a fractional or negative TTL return ErrBadRequest before I/O.

#### Sandbox.CreateSnapshot [#sandboxcreatesnapshot]

```go
func (s *Sandbox) CreateSnapshot(ctx context.Context, name string) (*Snapshot, error)
```

CreateSnapshot captures memory and disk without waiting for readiness.
Name must be non-blank, valid UTF-8; otherwise it returns ErrBadRequest
before any request. Both sandbox-write and snapshot-write permissions are
required; use Snapshots.Get with Wait to observe completion.

#### Sandbox.Delete [#sandboxdelete]

```go
func (s *Sandbox) Delete(ctx context.Context, opts *LifecycleWaitOptions) error
```

Delete requests deletion and waits for destroyed or a subsequent 404.
Timeout defaults to 60 seconds; NoWait returns after acceptance. A failed
completion returns ErrRequestTimeout or *SandboxTerminalStateError.

The platform releases the sandbox's image and volumes a few seconds after it
is destroyed: deleting them right away can return ErrConflict for a short
while, so retry such a delete after a moment.

#### Sandbox.Docker [#sandboxdocker]

```go
func (s *Sandbox) Docker() *Docker
```

Docker returns the sandbox's read-only Docker Engine service.

#### Sandbox.EntrypointLogs [#sandboxentrypointlogs]

```go
func (s *Sandbox) EntrypointLogs(ctx context.Context) (string, error)
```

EntrypointLogs returns the sandbox entrypoint's retained plain-text log.
The client's request timeout and buffered response limit apply.

#### Sandbox.Exec [#sandboxexec]

```go
func (s *Sandbox) Exec(ctx context.Context, command string, opts *ExecOptions) (*ProcessResult, error)
```

Exec runs a shell command and collects Stdout, Stderr, interleaved Output and Logs.
A non-zero ExitCode is NOT an error: inspect res.ExitCode (nil means unreported).
err means invalid input, cancellation, a local writer failure, a transport/protocol failure or a server
error; use errors.Is with ErrProcessNotFound, ErrSessionEnded, etc.
Timeout limits observation without killing; ExecutionTimeout stops the tree.
Any failure after creation returns a partial result with ProcessID and unknown Reason.
For untrusted arguments use ExecArgs; for persistent shell state use CreateSession.

**Example**:

```go
ctx := context.Background()
client, err := daytona.New()
if err != nil {
	log.Fatal(err)
}
defer func() {
	if closeErr := client.Close(); closeErr != nil {
		log.Print(closeErr)
	}
}()
sb, err := client.Get(ctx, "sandbox-id", nil)
if err != nil {
	log.Fatal(err)
}
res, err := sb.Exec(ctx, "python3 -c 'print(1)'", nil)
if err != nil {
	log.Fatal(err)
} // API, transport or cancellation failure.
fmt.Print(res.Stdout)
if res.ExitCode != nil && *res.ExitCode != 0 {
	fmt.Fprintf(os.Stderr, "command exited %d: %s", *res.ExitCode, res.Stderr)
}
```

#### Sandbox.ExecArgs [#sandboxexecargs]

```go
func (s *Sandbox) ExecArgs(ctx context.Context, argv []string, opts *ExecOptions) (*ProcessResult, error)
```

ExecArgs runs an argument vector without shell interpolation.
argv must contain a non-empty executable. Results and timeout semantics match Exec.

**Example**:

```go
ctx := context.Background()
client, err := daytona.New()
if err != nil {
	log.Fatal(err)
}
defer func() {
	if closeErr := client.Close(); closeErr != nil {
		log.Print(closeErr)
	}
}()
sb, err := client.Get(ctx, "sandbox-id", nil)
if err != nil {
	log.Fatal(err)
}
// An argument containing shell syntax remains literal.
result, err := sb.ExecArgs(ctx, []string{"printf", "%s", "$(not-a-command)"}, &daytona.ExecOptions{Stdout: os.Stdout})
if err != nil {
	log.Fatal(err)
}
fmt.Println(result.ProcessID)
```

#### Sandbox.FS [#sandboxfs]

```go
func (s *Sandbox) FS() *FileSystem
```

FS returns the sandbox filesystem service without making a request.

**Example**:

```go
client, err := daytona.New()
if err != nil {
	log.Fatal(err)
}
defer func() {
	if closeErr := client.Close(); closeErr != nil {
		log.Print(closeErr)
	}
}()
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
sb, err := client.Get(ctx, "your-sandbox-id", nil)
if err != nil {
	log.Fatal(err)
}
if writeErr := sb.FS().WriteFile(ctx, "/tmp/hello.txt", []byte("hello"), nil); writeErr != nil {
	log.Fatal(writeErr)
}
data, err := sb.FS().ReadFile(ctx, "/tmp/hello.txt", nil)
if err != nil {
	log.Fatal(err)
}
fmt.Println(string(data))
```

#### Sandbox.FollowBuildLogs [#sandboxfollowbuildlogs]

```go
func (s *Sandbox) FollowBuildLogs(ctx context.Context, opts *FollowBuildLogsOptions) iter.Seq2[BuildLogEvent, error]
```

FollowBuildLogs observes this sandbox's build lazily. Unknown events are
skipped. A discovery HTTP error is returned unchanged; subsequent failures
yield BuildLogInterruptedError with the last delivered cursor. Broken streams
reconnect up to five times without progress. Breaking iteration closes the
response immediately. Context cancellation and Client.Close stop observation.

#### Sandbox.Fork [#sandboxfork]

```go
func (s *Sandbox) Fork(ctx context.Context, opts *ForkOptions) (*Sandbox, error)
```

Fork copies this sandbox and returns the fork's last observed handle. A running
source waits for Started; a paused Linux memory fork waits for Paused; all
other forks wait for Stopped. Waiting forks refresh the source before POST.
NoWait skips every GET, including the source refresh. Accepted forks return
their handle with a nil error when the wait times out, fails a read, or ends
in a terminal state; check State() or Info(). If the server accepted the request,
the returned *Sandbox is non-nil even when err is non-nil: delete it or keep it.
Caller cancellation or deadline expiry remains reachable through errors.Is.
If the POST itself is interrupted, the outcome is unknown. Fork has no
idempotency key: inspect existing forks before retrying to avoid duplicates.
The fork never inherits the source's toolbox override or access token.

**Example**:

```go
client, err := daytona.New()
if err != nil {
	log.Print(err)
	return
}
defer func() {
	if closeErr := client.Close(); closeErr != nil {
		log.Print(closeErr)
	}
}()
ctx := context.Background()
source, err := client.Get(ctx, "source-sandbox-id", nil)
if err != nil {
	log.Print(err)
	return
}
fork, err := source.Fork(ctx, nil)
if err != nil {
	log.Print(err)
	return
}
defer func() {
	if deleteErr := fork.Delete(context.WithoutCancel(ctx), nil); deleteErr != nil {
		log.Print(deleteErr)
	}
}()
// Running sources produce started forks; paused memory forks remain paused.
log.Printf("fork %s: %s", fork.ID(), fork.State())
```

#### Sandbox.GetNetworkPolicy [#sandboxgetnetworkpolicy]

```go
func (s *Sandbox) GetNetworkPolicy(ctx context.Context) (*NetworkPolicyInfo, error)
```

GetNetworkPolicy reads desired and applied policy state, including its ETag.

#### Sandbox.GetSecrets [#sandboxgetsecrets]

```go
func (s *Sandbox) GetSecrets(ctx context.Context) (*SandboxSecretsInfo, error)
```

GetSecrets reads attached secret names, revision ETag and apply state.

#### Sandbox.Git [#sandboxgit]

```go
func (s *Sandbox) Git() *Git
```

Git returns this sandbox's concurrency-safe Git service.

#### Sandbox.GoString [#sandboxgostring]

```go
func (s *Sandbox) GoString() string
```

GoString returns a credential-free description.

#### Sandbox.ID [#sandboxid]

```go
func (s *Sandbox) ID() string
```

ID returns the sandbox's stable ID.

#### Sandbox.Info [#sandboxinfo]

```go
func (s *Sandbox) Info() SandboxInfo
```

Info returns an independent copy, including maps, slices and optional values.
It never contains a credential; see AccessToken.

#### Sandbox.Interpreter [#sandboxinterpreter]

```go
func (s *Sandbox) Interpreter() *Interpreter
```

Interpreter returns the sandbox's shared interpreter service.

#### Sandbox.Metrics [#sandboxmetrics]

```go
func (s *Sandbox) Metrics(ctx context.Context) (*SystemMetrics, error)
```

Metrics reads current resource usage from the sandbox. A malformed sample,
including negative byte counts or utilization outside 0..1, returns ErrBadRequest.

#### Sandbox.Name [#sandboxname]

```go
func (s *Sandbox) Name() string
```

Name returns the last observed name, or empty before it was reported.

#### Sandbox.PTY [#sandboxpty]

```go
func (s *Sandbox) PTY() *PTY
```

PTY returns the sandbox's interactive terminal namespace.

#### Sandbox.Pause [#sandboxpause]

```go
func (s *Sandbox) Pause(ctx context.Context, opts *LifecycleWaitOptions) error
```

Pause saves sandbox memory and waits for paused (default 60 seconds).
Returning to started is a *SandboxTerminalStateError. NoWait skips waiting.
The server decides whether the sandbox supports pausing.

#### Sandbox.Ports [#sandboxports]

```go
func (s *Sandbox) Ports() *Ports
```

Ports returns the sandbox's port inspection and preview service.

#### Sandbox.Process [#sandboxprocess]

```go
func (s *Sandbox) Process() *Processes
```

Process returns the sandbox's process namespace.

#### Sandbox.Refresh [#sandboxrefresh]

```go
func (s *Sandbox) Refresh(ctx context.Context) error
```

Refresh reloads metadata. It returns ErrNotFound if the sandbox no longer
exists, or ErrClientClosed after the owning client closes.

#### Sandbox.ReplaceSecrets [#sandboxreplacesecrets]

```go
func (s *Sandbox) ReplaceSecrets(
	ctx context.Context, secrets []string, opts *IfMatchOptions,
) (*SandboxSecretsInfo, error)
```

ReplaceSecrets replaces all attached project secret names; nil removes them
all. IfMatch is required. ErrStaleSecretsRevision identifies a stale ETag;
the SDK does not retry it. The change applies asynchronously, and only
subsequently started processes receive the updated environment.

#### Sandbox.ResetIdleTimer [#sandboxresetidletimer]

```go
func (s *Sandbox) ResetIdleTimer(ctx context.Context) (*LifecyclePolicy, error)
```

ResetIdleTimer records activity without changing the wall-clock timeout and
returns the server's full policy. Older concurrent echoes never move the
cached activity clock backwards. Deleting or deleted sandboxes return ErrConflict.

#### Sandbox.ResetNetworkPolicy [#sandboxresetnetworkpolicy]

```go
func (s *Sandbox) ResetNetworkPolicy(ctx context.Context, opts *IfMatchOptions) (*NetworkPolicyInfo, error)
```

ResetNetworkPolicy removes the sandbox-specific policy using the last read's
ETag. It sends a null body to reset the sandbox to open network access. A stale ETag returns
ErrStaleNetworkPolicyRevision, without retrying.

#### Sandbox.Resume [#sandboxresume]

```go
func (s *Sandbox) Resume(ctx context.Context, opts *LifecycleWaitOptions) error
```

Resume resumes a paused sandbox and waits for started (default 60 seconds).
Returning to stopped is a *SandboxTerminalStateError. NoWait skips waiting.

#### Sandbox.RotateSigningKey [#sandboxrotatesigningkey]

```go
func (s *Sandbox) RotateSigningKey(ctx context.Context) error
```

RotateSigningKey invalidates previously signed file URLs within approximately
30 seconds. The key is never returned. ErrUnsupportedOperation identifies a
caller-supplied direct toolbox URL that is not scoped to this sandbox.
A closed owning client returns ErrClientClosed before scope validation.

#### Sandbox.RunCode [#sandboxruncode]

```go
func (s *Sandbox) RunCode(ctx context.Context, code string, opts *RunCodeOptions) (*RunCodeResult, error)
```

RunCode executes code through Interpreter.Run. Context-free runs share state
per language. Explicit context loss returns ErrSessionNotFound without retry.

**Example**:

```go
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
client, err := daytona.New()
if err != nil {
	log.Print(err)
	return
}
defer func() {
	if closeErr := client.Close(); closeErr != nil {
		log.Print(closeErr)
	}
}()
sandbox, err := client.Get(ctx, "sandbox-id", nil)
if err != nil {
	log.Print(err)
	return
}
result, err := sandbox.RunCode(ctx, "print(40 + 2)", &daytona.RunCodeOptions{
	Stdout: os.Stdout, Timeout: 30 * time.Second,
})
if err != nil {
	log.Print(err)
	return
}
if result.Error != nil {
	fmt.Println(result.Error.Name, result.Error.Value)
}
```

#### Sandbox.SetLabels [#sandboxsetlabels]

```go
func (s *Sandbox) SetLabels(ctx context.Context, labels map[string]string) (map[string]string, error)
```

SetLabels replaces labels and returns the applied map. Nil clears all but the
reserved name label. Unless name is supplied, a detail read preserves its
current value; this read and write are not atomic. Empty keys return
ErrBadRequest before I/O. ErrConflict identifies deleting or deleted sandboxes.

#### Sandbox.Start [#sandboxstart]

```go
func (s *Sandbox) Start(ctx context.Context, opts *LifecycleWaitOptions) error
```

Start reads the current state, starts a stopped sandbox or resumes a paused
sandbox, then waits for started. An in-progress stop/pause first settles under
the same budget (default 60 seconds). Already-started sandboxes need no action.
NoWait skips settling and completion; for an in-progress stop/pause it sends
start immediately and lets the API decide whether it can accept the request.
Timeout returns ErrRequestTimeout; terminal failures return *SandboxTerminalStateError.

#### Sandbox.State [#sandboxstate]

```go
func (s *Sandbox) State() SandboxState
```

State returns the last observed state, or SandboxStateUnknown before a read.

#### Sandbox.Stop [#sandboxstop]

```go
func (s *Sandbox) Stop(ctx context.Context, opts *LifecycleWaitOptions) error
```

Stop stops the sandbox and waits for stopped. The default wait is 60 seconds;
NoWait returns after acceptance. Toolbox calls require Start before reuse.
A failed completion returns ErrRequestTimeout or *SandboxTerminalStateError.

#### Sandbox.String [#sandboxstring]

```go
func (s *Sandbox) String() string
```

String returns a credential-free description.

#### Sandbox.ToJSON [#sandboxtojson]

```go
func (s *Sandbox) ToJSON() SandboxHandleJSON
```

ToJSON returns an independent credential- and URL-free camelCase snapshot.
Marshal it with encoding/json. This is a snapshot, not a way back: resume a
stored sandbox with client.Get(ctx, json.SandboxID, nil).

**Example**:

```go
client, err := daytona.New()
if err != nil {
	fmt.Println(err)
	return
}
defer func() {
	if closeErr := client.Close(); closeErr != nil {
		fmt.Println(closeErr)
	}
}()
ctx := context.Background()
sandbox, err := client.Get(ctx, "sbx", nil)
if err != nil {
	fmt.Println(err)
	return
}
snapshot := sandbox.ToJSON()
encoded, err := json.Marshal(snapshot)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(string(encoded))
// Resume later with client.Get(ctx, snapshot.SandboxID, nil).
```

#### Sandbox.UpdateEnv [#sandboxupdateenv]

```go
func (s *Sandbox) UpdateEnv(ctx context.Context, env map[string]string, opts *UpdateEnvOptions) error
```

UpdateEnv updates the extra environment inherited by subsequently started
processes, PTYs and sessions. Nil env sets nothing; nil options unsets nothing.
Empty names, names containing '=', NUL, CR or LF, and values containing NUL
return ErrBadRequest before I/O. Platform-reserved names are checked server-side.

#### Sandbox.UpdateLifecyclePolicy [#sandboxupdatelifecyclepolicy]

```go
func (s *Sandbox) UpdateLifecyclePolicy(ctx context.Context, opts *LifecyclePolicyOptions) (*LifecyclePolicy, error)
```

UpdateLifecyclePolicy changes supplied policy settings and caches the echoed
policy. Nil or empty options return ErrBadRequest. Unknown classes return
ErrUnsupportedOperation. Deleted sandboxes return ErrConflict. Actions involving
deletion additionally require delete:sandboxes permission.

**Example**:

```go
client, err := daytona.New()
if err != nil {
	log.Fatal(err)
}
defer func() {
	if closeErr := client.Close(); closeErr != nil {
		log.Print(closeErr)
	}
}()
ctx := context.Background()
sandbox, err := client.Get(ctx, "sandbox-id", nil)
if err != nil {
	log.Fatal(err)
}
_, err = sandbox.UpdateLifecyclePolicy(ctx, &daytona.LifecyclePolicyOptions{
	Timeout: time.Hour, IdleExpiry: 10 * time.Minute, OnIdleTimeout: daytona.LifecycleActionDelete,
})
if err != nil {
	log.Fatal(err)
}
```

#### Sandbox.UpdateNetworkPolicy [#sandboxupdatenetworkpolicy]

```go
func (s *Sandbox) UpdateNetworkPolicy(
	ctx context.Context, spec NetworkPolicySpec, opts *IfMatchOptions,
) (*NetworkPolicyInfo, error)
```

UpdateNetworkPolicy replaces the desired policy using the last read's ETag.
Invalid policy combinations return ErrBadRequest before I/O. A stale ETag
returns ErrStaleNetworkPolicyRevision, without retrying the update.

**Example**:

```go
client, err := daytona.New()
if err != nil {
	log.Fatal(err)
}
defer func() {
	if closeErr := client.Close(); closeErr != nil {
		log.Print(closeErr)
	}
}()
ctx := context.Background()
sandbox, err := client.Get(ctx, "sandbox-id", nil)
if err != nil {
	log.Fatal(err)
}
current, err := sandbox.GetNetworkPolicy(ctx)
if err != nil {
	log.Fatal(err)
}
domains := []string{"api.example.com"}
_, err = sandbox.UpdateNetworkPolicy(ctx, daytona.NetworkPolicySpec{
	AllowDomains: &domains,
}, &daytona.IfMatchOptions{IfMatch: current.ETag})
if err != nil {
	log.Fatal(err)
}
```

#### Sandbox.Volumes [#sandboxvolumes]

```go
func (s *Sandbox) Volumes() *SandboxVolumes
```

Volumes returns the sandbox's attached-volume pull service.

#### Sandbox.Wait [#sandboxwait]

```go
func (s *Sandbox) Wait(ctx context.Context, opts *WaitOptions) error
```

Wait observes the server until any requested state is reached (default started).
A spent budget returns ErrRequestTimeout with source SDK; an incompatible
terminal state returns *SandboxTerminalStateError, including its raw status
and any reason read from the server. Unknown server states keep waiting.
A terminal event without a reason borrows only a matching full read's
reason, never an earlier event's explanation.
An event reporting a known sandbox's disappearance returns ErrNotFound with source SDK.
A healthy events socket suppresses early API probes; a quiet socket permits
a probe after about ten seconds (sooner for a short wait with no frames).
A bounded wait reserves up to five seconds for authoritative API reads
regardless of socket activity. Once a target event was observed, failure to
refresh metadata does not undo success. Caller cancellation is never hidden.
With events enabled, nondecisive read failures (including rate limits) retry
within the budget; the last read failure is retained as a timeout cause.
Live probes rearm after a fresh jittered ten seconds. Fallback polling
honors RetryAfter.
Fallback polling stops on HTTP 4xx other than 429; live-event probes stop
only on 401, 403, or 404. Final-reserve failures remain timeout causes.
With events disabled, read failures are returned immediately.

**Example**:

```go
ctx := context.Background()
client, err := daytona.New()
if err != nil {
	fmt.Println(err)
	return
}
defer func() {
	if closeErr := client.Close(); closeErr != nil {
		fmt.Println(closeErr)
	}
}()
sandbox, err := client.Get(ctx, "sandbox-id", nil)
if err != nil {
	fmt.Println(err)
	return
}
err = sandbox.Wait(ctx, &daytona.WaitOptions{
	Until:   []daytona.SandboxState{daytona.SandboxStateStarted},
	Timeout: 30 * time.Second,
})
switch {
case errors.Is(err, daytona.ErrRequestTimeout):
	fmt.Println("Still waiting:", sandbox.State())
case err != nil:
	fmt.Println(err)
default:
	fmt.Println("Ready:", sandbox.ID())
}
```

## CreateAccessTokenOptions [#createaccesstokenoptions]

```go
type CreateAccessTokenOptions struct {
	// Operations is nil for the server default; an empty slice grants none.
	// Unknown operations are rejected by the API, never silently narrowed.
	Operations []string
	// Ports is nil for the server default; an empty slice grants no ports.
	// Each port must be in 1..65535 and not reserved for the sandbox daemon.
	Ports []int
	// TTL is a positive whole-second lifetime. Zero uses the server default.
	// The API enforces its maximum lifetime.
	TTL time.Duration
}
```

CreateAccessTokenOptions selects the scope and lifetime of a delegated token.

## FindByNameOptions [#findbynameoptions]

```go
type FindByNameOptions struct {
	// Region selects a region; empty or "local" uses the default.
	Region string
}
```

FindByNameOptions selects a region. Empty, whitespace or "local" (ignoring
case) uses the default region; other values are sent unchanged.

## ForkOptions [#forkoptions]

```go
type ForkOptions struct {
	// Name is an optional non-blank name; empty uses the server's generated name.
	Name string
	// Memory selects whether to copy memory. Nil uses the platform default:
	// Linux copies memory unless stopped; macOS copies disk only.
	// Explicit true on macOS is refused by the API.
	Memory *bool
	// Wait defaults to 60 seconds. NoWait performs only the POST; WaitForever
	// has no SDK deadline. Positive fractional durations are supported.
	Wait time.Duration
}
```

ForkOptions selects the fork's name, memory copying and observation budget.

## GetSandboxOptions [#getsandboxoptions]

```go
type GetSandboxOptions struct {
	// ToolboxURL overrides the sandbox's tools destination with a trusted HTTP
	// or HTTPS URL, without a query or fragment.
	ToolboxURL string
	// AccessToken is an optional caller-managed sandbox token.
	AccessToken string
}
```

GetSandboxOptions configures a sandbox connection. ToolboxURL is an explicitly
trusted direct URL; \{sandboxId\} and \{sandbox_id\} path placeholders are expanded.
AccessToken is caller-owned and is never automatically replaced.

#### GetSandboxOptions.GoString [#getsandboxoptionsgostring]

```go
func (o GetSandboxOptions) GoString() string
```

GoString prints get options with the same redaction as String.

#### GetSandboxOptions.String [#getsandboxoptionsstring]

```go
func (o GetSandboxOptions) String() string
```

String prints all get options with a non-empty AccessToken redacted.

## ImageRef [#imageref]

```go
type ImageRef struct {
	// ID identifies the image.
	ID string
	// Name is the optional image name.
	Name string
	// contains filtered or unexported fields
}
```

ImageRef identifies the image a sandbox booted.

## LifecyclePolicy [#lifecyclepolicy]

```go
type LifecyclePolicy struct {
	// Timeout is the lifetime budget; nil is absent and zero disables expiry.
	Timeout *time.Duration
	// OnTimeout is the action taken at the lifetime deadline.
	OnTimeout LifecycleAction
	// TimeoutAt is the effective lifetime deadline.
	TimeoutAt time.Time

	// IdleExpiry is the idle budget; nil is absent and zero disables expiry.
	IdleExpiry *time.Duration
	// OnIdleTimeout is the action taken at the idle deadline.
	OnIdleTimeout LifecycleAction
	// IdleTimeoutAt is the effective idle deadline.
	IdleTimeoutAt time.Time

	// LastActivityAt is the activity observation timestamp.
	LastActivityAt time.Time

	// LastActivitySource is the open server activity source.
	LastActivitySource string
	// contains filtered or unexported fields
}
```

LifecyclePolicy is the observed timeout/idle policy. Nil durations mean not
reported; a reported zero disables that expiry. Actions are open strings.

## MacBootMode [#macbootmode]

```go
type MacBootMode string
```

MacBootMode is an open server-defined macOS boot mode.

## PortAssignment [#portassignment]

```go
type PortAssignment struct {
	// HostPort is the host-side port.
	HostPort int
	// VMPort is the sandbox-side port.
	VMPort int
	// Protocol is the open server protocol name.
	Protocol string
}
```

PortAssignment is an observed sandbox port assignment.

## SandboxAccessToken [#sandboxaccesstoken-1]

```go
type SandboxAccessToken struct {
	// AccessToken is sensitive bearer material; do not log or share it publicly.
	AccessToken string
	// TokenType is the server token type, usually Bearer.
	TokenType string
	// ExpiresAt is the credential's expiration timestamp.
	ExpiresAt time.Time
	// Operations contains the granted operations, including future server values.
	Operations []string
	// Ports contains the granted ports; nil means unrestricted ports.
	Ports []int
}
```

SandboxAccessToken is a scoped credential for one sandbox. It cannot refresh
itself or mint further credentials. String and GoString omit its secret.

#### SandboxAccessToken.GoString [#sandboxaccesstokengostring]

```go
func (t SandboxAccessToken) GoString() string
```

GoString returns a credential-free token description.

#### SandboxAccessToken.String [#sandboxaccesstokenstring]

```go
func (t SandboxAccessToken) String() string
```

String returns a credential-free token description.

## SandboxArtifactJSON [#sandboxartifactjson]

```go
type SandboxArtifactJSON struct {
	// ID is the artifact identity.
	ID string `json:"id"`
	// Name is omitted unless reported.
	Name *string `json:"name,omitempty"`
}
```

SandboxArtifactJSON identifies an image or snapshot in SandboxHandleJSON.

## SandboxClass [#sandboxclass]

```go
type SandboxClass string
```

SandboxClass identifies the sandbox operating-system class.

```go
const (
	// SandboxClassUnknown is an unrecognized server class; see RawClass.
	SandboxClassUnknown SandboxClass = "unknown"
	// SandboxClassLinux identifies Linux sandboxes.
	SandboxClassLinux SandboxClass = "linux"
	// SandboxClassMacOS identifies macOS sandboxes.
	SandboxClassMacOS SandboxClass = "macos"
)
```

## SandboxHandleJSON [#sandboxhandlejson]

```go
type SandboxHandleJSON struct {
	// SandboxID is the stable sandbox identity.
	SandboxID string `json:"sandboxId"`
	// Name is the last reported name, including a reported empty name.
	Name *string `json:"name,omitempty"`
	// State is the normalized state, omitted until known.
	State SandboxState `json:"state,omitempty"`
	// RawState is the server's status verbatim.
	RawState string `json:"rawState,omitempty"`
	// Image identifies the boot image.
	Image *SandboxArtifactJSON `json:"image,omitempty"`
	// Snapshot identifies the resumed snapshot.
	Snapshot *SandboxArtifactJSON `json:"snapshot,omitempty"`
	// Region is the explicit or inferred region.
	Region string `json:"region,omitempty"`
	// Labels is omitted until observed; a reported empty map writes {}.
	Labels *map[string]string `json:"labels,omitempty"`
	// CPU is reserved CPU in cores.
	CPU *float64 `json:"cpu,omitempty"`
	// CPUMax is the CPU limit in cores.
	CPUMax *float64 `json:"cpuMax,omitempty"`
	// Memory is reserved memory in GiB.
	Memory *float64 `json:"memory,omitempty"`
	// MemoryMax is the memory limit in GiB.
	MemoryMax *float64 `json:"memoryMax,omitempty"`
	// Disk is writable capacity in GiB.
	Disk *float64 `json:"disk,omitempty"`
	// DiskMax is the disk limit in GiB.
	DiskMax *float64 `json:"diskMax,omitempty"`
	// SandboxClass is the normalized operating-system class.
	SandboxClass SandboxClass `json:"sandboxClass,omitempty"`
	// RawSandboxClass is the server's class verbatim.
	RawSandboxClass string `json:"rawSandboxClass,omitempty"`
	// Persistent reports disk persistence.
	Persistent *bool `json:"persistent,omitempty"`
	// Spot reports interruptible capacity.
	Spot *bool `json:"spot,omitempty"`
	// SpotEvictedAt is the server's RFC 3339 timestamp verbatim.
	SpotEvictedAt string `json:"spotEvictedAt,omitempty"`
	// LifecyclePolicy is the observed automatic expiry policy.
	LifecyclePolicy *SandboxLifecycleJSON `json:"lifecyclePolicy,omitempty"`
	// ForkedFrom identifies the source sandbox.
	ForkedFrom *string `json:"forkedFrom,omitempty"`
	// ReservationID identifies the associated Mac reservation.
	ReservationID *string `json:"reservationId,omitempty"`
	// User is the reported operating-system user.
	User *string `json:"user,omitempty"`
	// Error is the reported failure explanation.
	Error *string `json:"error,omitempty"`
	// ImageBuildID identifies the associated image build.
	ImageBuildID *string `json:"imageBuildId,omitempty"`
}
```

SandboxHandleJSON is a credential- and URL-free camelCase metadata snapshot,
shared with the other SDKs. Nil optional fields are omitted, including unknown
capacity on a create handle. Memory and disk are GiB; CPU is cores.
This is not reconnectable data: resume with client.Get(ctx, json.SandboxID, nil).

## SandboxInfo [#sandboxinfo-1]

```go
type SandboxInfo struct {
	// ID is the stable sandbox ID.
	ID string
	// Name is the last observed name.
	Name string
	// State is the normalized lifecycle state.
	State SandboxState
	// RawState is the server's lifecycle status verbatim.
	RawState string
	// Class is the normalized operating-system class.
	Class SandboxClass
	// RawClass is the server's class verbatim.
	RawClass string
	// Error is the server's failure explanation.
	Error string
	// Image identifies the boot image, if reported.
	Image *ImageRef
	// Snapshot identifies the resumed memory snapshot, if reported.
	Snapshot *SnapshotRef
	// Labels is an independent map; nil means not yet observed.
	Labels map[string]string
	// Resources contains reserved capacity and reported maxima.
	Resources Resources
	// User is the default operating-system user.
	User string
	// Region is the explicit region, or the tag inferred from ID.
	Region string
	// MacBootMode is an open server-defined macOS boot mode.
	MacBootMode MacBootMode
	// Persistent reports disk persistence; nil means not reported.
	Persistent *bool
	// Spot reports interruptible capacity; nil means not reported.
	Spot *bool
	// SpotEvictedAt is zero until an eviction is reported.
	SpotEvictedAt time.Time

	// LifecyclePolicy is the observed automatic expiry policy.
	LifecyclePolicy *LifecyclePolicy
	// ForkedFrom identifies the source sandbox of a fork.
	ForkedFrom string
	// ReservationID identifies the associated Mac reservation.
	ReservationID string
	// ImageBuildID identifies the associated image build.
	ImageBuildID string
	// CreatedAt is the creation timestamp, or zero when absent.
	CreatedAt time.Time
	// UpdatedAt is the update timestamp, or zero when absent.
	UpdatedAt time.Time
	// StartedAt is the last start timestamp, or zero when absent.
	StartedAt time.Time
	// StoppedAt is the last stop timestamp, or zero when absent.
	StoppedAt time.Time
	// LastActivityAt is the last activity timestamp, or zero when absent.
	LastActivityAt time.Time
	// CreateTimeoutAt is the create deadline, or zero when absent.
	CreateTimeoutAt time.Time
	// PortMap contains observed port assignments.
	PortMap []PortAssignment
	// contains filtered or unexported fields
}
```

SandboxInfo is a caller-owned snapshot of a handle's last observation.
Nil optional fields mean not reported. Labels are nil before a detail read.

## SandboxLifecycleJSON [#sandboxlifecyclejson]

```go
type SandboxLifecycleJSON struct {
	// TimeoutSeconds is the lifetime budget; zero disables expiry.
	TimeoutSeconds *int64 `json:"timeoutSeconds,omitempty"`
	// OnTimeout is the open server-defined lifetime action.
	OnTimeout *string `json:"onTimeout,omitempty"`
	// TimeoutAt is the effective lifetime deadline, in RFC 3339.
	TimeoutAt string `json:"timeoutAt,omitempty"`
	// IdleExpirySeconds is the idle budget; zero disables expiry.
	IdleExpirySeconds *int64 `json:"idleExpirySeconds,omitempty"`
	// OnIdleTimeout is the open server-defined idle action.
	OnIdleTimeout *string `json:"onIdleTimeout,omitempty"`
	// IdleTimeoutAt is the effective idle deadline, in RFC 3339.
	IdleTimeoutAt string `json:"idleTimeoutAt,omitempty"`
	// LastActivityAt is the activity observation timestamp, in RFC 3339.
	LastActivityAt string `json:"lastActivityAt,omitempty"`
	// LastActivitySource is the open server-defined activity source.
	LastActivitySource *string `json:"lastActivitySource,omitempty"`
}
```

SandboxLifecycleJSON is the shared camelCase lifecycle snapshot. Durations
are seconds, not nanoseconds. Timestamp strings preserve server formatting.

## SandboxState [#sandboxstate-1]

```go
type SandboxState string
```

SandboxState is the normalized lifecycle state; RawState keeps the wire value.

```go
const (
	// SandboxStateUnknown is an unrecognized or not yet observed state.
	SandboxStateUnknown SandboxState = "unknown"
	// SandboxStateQueued means the sandbox is waiting for placement.
	SandboxStateQueued SandboxState = "queued"
	// SandboxStateCreating means provisioning is in progress.
	SandboxStateCreating SandboxState = "creating"
	// SandboxStateStarting means the sandbox is booting.
	SandboxStateStarting SandboxState = "starting"
	// SandboxStateStarted means the sandbox is running.
	SandboxStateStarted SandboxState = "started"
	// SandboxStatePausing means pause is in progress.
	SandboxStatePausing SandboxState = "pausing"
	// SandboxStatePaused means the sandbox is paused.
	SandboxStatePaused SandboxState = "paused"
	// SandboxStateStopping means stop is in progress.
	SandboxStateStopping SandboxState = "stopping"
	// SandboxStateStopped means the sandbox is stopped.
	SandboxStateStopped SandboxState = "stopped"
	// SandboxStateDestroying means deletion is in progress.
	SandboxStateDestroying SandboxState = "destroying"
	// SandboxStateDestroyed means the sandbox was deleted.
	SandboxStateDestroyed SandboxState = "destroyed"
	// SandboxStateError means the sandbox failed or was lost.
	SandboxStateError SandboxState = "error"
)
```

## SearchSandboxesOptions [#searchsandboxesoptions]

```go
type SearchSandboxesOptions struct {
	// Q is free text or an exact ID.
	Q string
	// NamePrefix filters by name prefix.
	NamePrefix string
	// IDPrefix filters by ID prefix.
	IDPrefix string
	// States accepts known SDK states and expands them to server statuses.
	States []SandboxState
	// Classes selects known operating-system classes.
	Classes []SandboxClass
	// Regions selects region IDs without comma characters.
	Regions []string
	// ImageRef selects an exact image reference.
	ImageRef string
	// ImageRefPrefix selects an image-reference prefix.
	ImageRefPrefix string
	// Labels matches containment of all supplied pairs.
	Labels map[string]string
	// Spot selects interruptible capacity; nil omits the filter.
	Spot *bool
	// ForkedFrom selects forks of a sandbox.
	ForkedFrom string
	// MinCores is the inclusive minimum CPU limit in cores.
	MinCores *float64
	// MaxCores is the inclusive maximum CPU limit in cores.
	MaxCores *float64
	// MinMemoryMiB is an inclusive memory bound in MiB.
	MinMemoryMiB *int64
	// MaxMemoryMiB is an inclusive memory bound in MiB.
	MaxMemoryMiB *int64
	// MinDiskMiB is an inclusive disk bound in MiB.
	MinDiskMiB *int64
	// MaxDiskMiB is an inclusive disk bound in MiB.
	MaxDiskMiB *int64
	// CreatedStartAt is an inclusive creation bound.
	CreatedStartAt time.Time
	// CreatedEndAt is an exclusive creation bound.
	CreatedEndAt time.Time
	// UpdatedStartAt is an inclusive update bound.
	UpdatedStartAt time.Time
	// UpdatedEndAt is an exclusive update bound.
	UpdatedEndAt time.Time
	// LastActivityStartAt is an inclusive activity bound.
	LastActivityStartAt time.Time
	// LastActivityEndAt is an exclusive activity bound.
	LastActivityEndAt time.Time
	// Sort defaults to creation time.
	Sort SearchSort
	// Order defaults to descending.
	Order SortOrder
	// Limit is 1–200; zero uses the server default.
	Limit int
	// Cursor is the opaque continuation cursor.
	Cursor string
}
```

SearchSandboxesOptions filters sandboxes. Filters combine with AND; values within
States, Classes and Regions combine with OR. Nil slices/maps omit filters;
explicit empty ones are invalid. Memory/disk bounds are MiB, CPU bounds cores.
Zero timestamps omit bounds; starts are inclusive and ends exclusive.

## SearchSort [#searchsort]

```go
type SearchSort string
```

SearchSort selects the search ordering field. Zero uses created_at.

```go
const (
	// SearchSortCreatedAt sorts by creation.
	SearchSortCreatedAt SearchSort = "created_at"
	// SearchSortUpdatedAt sorts by last update.
	SearchSortUpdatedAt SearchSort = "updated_at"
	// SearchSortLastActivityAt sorts by last activity.
	SearchSortLastActivityAt SearchSort = "last_activity_at"
	// SearchSortName sorts by name.
	SearchSortName SearchSort = "name"
	// SearchSortCores sorts by CPU limit in cores.
	SearchSortCores SearchSort = "cores"
	// SearchSortMemoryMiB sorts by memory in MiB.
	SearchSortMemoryMiB SearchSort = "memory_mib"
	// SearchSortDiskMiB sorts by disk in MiB.
	SearchSortDiskMiB SearchSort = "disk_mib"
)
```

## SnapshotRef [#snapshotref]

```go
type SnapshotRef struct {
	// ID identifies the snapshot.
	ID string
	// Name is the optional snapshot name.
	Name string
	// contains filtered or unexported fields
}
```

SnapshotRef identifies the memory snapshot a sandbox resumed.

## SortOrder [#sortorder]

```go
type SortOrder string
```

SortOrder selects ascending or descending results. Zero uses descending.

```go
const (
	// SortOrderAscending requests smallest/oldest first.
	SortOrderAscending SortOrder = "asc"
	// SortOrderDescending requests largest/newest first.
	SortOrderDescending SortOrder = "desc"
)
```

## SystemMetrics [#systemmetrics]

```go
type SystemMetrics struct {
	// Timestamp is when the sandbox sampled these metrics.
	Timestamp time.Time
	// CPUCount is the nonnegative number of CPUs, at most 2^31-1.
	CPUCount int64
	// CPUUtilization is the fraction of CPU capacity in use, from zero to one.
	CPUUtilization float64
	// MemoryUsageBytes is used memory in bytes.
	MemoryUsageBytes int64
	// MemoryTotalBytes is total memory in bytes.
	MemoryTotalBytes int64
	// DiskUsageBytes is used disk capacity in bytes.
	DiskUsageBytes int64
	// DiskTotalBytes is total disk capacity in bytes.
	DiskTotalBytes int64
}
```

SystemMetrics is one sandbox CPU, memory and disk usage observation.

## UpdateEnvOptions [#updateenvoptions]

```go
type UpdateEnvOptions struct {
	// Unset removes these SDK-managed entries; image environment is unchanged.
	Unset []string
}
```

UpdateEnvOptions selects SDK-managed environment variables to remove.

## WaitOptions [#waitoptions]

```go
type WaitOptions struct {
	// Until defaults to started when nil. An empty slice is invalid.
	// Valid targets are queued, starting, started, pausing, paused, stopping,
	// stopped, destroying and destroyed. Any one target completes the wait.
	Until []SandboxState
	// Timeout defaults to 60 seconds. NoWait skips observation; WaitForever
	// removes the SDK deadline. The context deadline still applies.
	Timeout time.Duration
}
```

WaitOptions selects the state and budget for Sandbox.Wait.
