Solari

Sandboxes

github.com/solari-sdk/solari-sandbox-go, package solari. Types Client and Sandbox. A sandbox is a headless microVM for commands, code, files, and git. See the Go SDK hub for install and configuration.

go get github.com/solari-sdk/solari-sandbox-go
This is the core surface only
The Go module ports the @solarisdk/core surface: session lifecycle (including Pause/Resume and Start) plus Commands, Files, Code, and Git. PTYs, full volume CRUD, snapshots, park/unpark, account secrets, metrics, signed transfer URLs, and preview URLs are not ported. See what is not ported.

Contents

Client

The sandbox entry point. Talks the gateway REST API.

Constructor

NewClient()

func NewClient(opts ClientOptions) (*Client, error)

Constructs a client. Opens no connection.

Parameters:

Returns: (*Client, error)

Errors: *SolariError if APIKey is empty. BaseURL is optional and defaults to https://api.getsolari.com.

Example:

import solari "github.com/solari-sdk/solari-sandbox-go"

client, err := solari.NewClient(solari.ClientOptions{
    APIKey:  os.Getenv("SOLARI_API_KEY"),
    BaseURL: "https://api.getsolari.com",
})

Methods

Create()

func (c *Client) Create(ctx context.Context, opts CreateOptions) (*Sandbox, error)

Provisions a sandbox (POST /sandboxes) and returns a handle. Retry-safe, since it sends an idempotency key. The control channel is not opened yet.

Parameters:

  • ctx context.Context.
  • opts CreateOptions: see CreateOptions. Kind defaults to KindSandbox.

Returns: (*Sandbox, error)

Errors: *AuthError, *PlanError, *ConcurrencyLimitError, *NoCapacityError, or *GatewayError. A bad option (400 ValidationError), an unknown template or snapshot (404), and a snapshot that cannot be restored (409 SnapshotNotRestorable) all arrive as a plain *GatewayError; see matching on Status and Code.

Example:

sbx, err := client.Create(ctx, solari.CreateOptions{
    Template: "base",
    CPU:      2,
    MemMb:    4096,
    Envs:     map[string]string{"NODE_ENV": "test"},
})
if err != nil {
    log.Fatal(err)
}
defer sbx.Kill(ctx)

Get()

func (c *Client) Get(ctx context.Context, sandboxID string) (*SandboxView, error)

Fetches a sandbox’s current record (GET /sandboxes/:id). Returns the raw view, not a handle.

Parameters:

  • ctx context.Context.
  • sandboxID string: the sandbox id.

Returns: (*SandboxView, error)

Errors: *GatewayError with Status 404 if the id is unknown (there is no dedicated not-found type).

Example:

view, _ := client.Get(ctx, "sbx_abc123")
fmt.Println(view.State, view.CPU, view.MemMb)  // "running" 2 4096

Connect()

func (c *Client) Connect(ctx context.Context, sandboxID string) (*Sandbox, error)

Re-attaches to a running sandbox by id. When the view carries no ControlURL, one is derived by swapping the base URL scheme to ws/wss and appending /control/<id>.

Parameters:

  • ctx context.Context.
  • sandboxID string: the sandbox id.

Returns: (*Sandbox, error)

Errors: *GatewayError if the id is unknown.

Example:

sbx, err := client.Connect(ctx, "sbx_abc123")
r, _ := sbx.Commands.Run(ctx, "uptime", solari.CommandOptions{})

Kill()

func (c *Client) Kill(ctx context.Context, sandboxID string) error

Destroys a sandbox by id (DELETE /sandboxes/:id). Killing a sandbox that was already killed succeeds again; an id that never existed (or belongs to another org) returns a *GatewayError with status 404. Use Sandbox.Kill when you hold a handle.

Parameters:

  • ctx context.Context.
  • sandboxID string: the sandbox id.

Returns: error

Example:

err := client.Kill(ctx, "sbx_abc123")

Pause()

func (c *Client) Pause(ctx context.Context, sandboxID string) error

Snapshots a session’s RAM+disk and frees its host slot (POST /sandboxes/:id/pause). The session keeps its id and can be brought back with Resume; its control channel is dead until then. Prefer Sandbox.Pause when you hold a handle; it also closes the local channel.

A pause can end in a retryable 503 PauseRetryable (the host cut the pause short and left the sandbox running). Pause sends an Idempotency-Key, so the transport retries that 503 like its other retryable errors: 5 retries, about 5 s in all. If the error still comes back, call Pause again; a sandbox that is already paused answers 200.

Parameters:

  • ctx context.Context.
  • sandboxID string: the sandbox id.

Returns: error

Example:

err := client.Pause(ctx, "sbx_abc123")

Resume()

func (c *Client) Resume(ctx context.Context, sandboxID string) (string, error)

Re-hydrates a paused session (POST /sandboxes/:id/resume) and returns the control URL to re-attach to. The session comes back on a fresh slot, so any control URL from before the pause is stale.

Parameters:

  • ctx context.Context.
  • sandboxID string: the sandbox id.

Returns: (string, error), the fresh control URL.

Example:

controlURL, err := client.Resume(ctx, "sbx_abc123")

Start()

func (c *Client) Start(ctx context.Context, sandboxID string) (string, error)

Cold-boots a stopped sandbox (POST /sandboxes/:id/start) from the disk the host kept and returns the fresh control URL. A sandbox is stopped when its guest powered itself off. This is a cold boot, not a resume: running processes and memory are gone, files on disk are kept. It takes a concurrency slot (429 at the cap) and opens a new billing segment. Idempotent: an already-running sandbox answers 200 with the current control URL. Use Resume for a paused one.

Parameters:

  • ctx context.Context.
  • sandboxID string: the sandbox id.

Returns: (string, error), the fresh control URL.

Errors: a 409 NotStopped or StartInProgress arrives as *SandboxNotStoppedError (v0.4.0 and later; it still matches *GatewayError with errors.As). Every other error arrives as *GatewayError (or *NoCapacityError for a 503); match on Code:

  • 409 NotStopped (the sandbox is in another state; State carries it) or StartInProgress (poll until it is running).
  • 409 with a disk code (StoppedDiskMissing, StoppedDiskUnsafe, GoldenMismatch, DiskPlatformMismatch, DiskShaMismatch, DiskExceedsSpec, DiskOwnerMismatch): the stopped disk cannot be started. 409 HostCapabilityMissing: the host pool is not armed for start. Retrying will not help with any of these.
  • 503 NoCapacity/StartTimeout and 502 StartHostError are transient: call Start again (the SDK does not retry this POST for you). 500 StartFailed leaves the sandbox stopped with its disk, so a later Start is safe.

Example:

controlURL, err := client.Start(ctx, "sbx_abc123")
var ns *solari.SandboxNotStoppedError
if errors.As(err, &ns) {
    switch ns.Code {
    case "StartInProgress":
        // poll client.Get until it is running
    default: // "NotStopped"; ns.State is its current state
        // paused? call client.Resume instead
    }
}

Sandbox

A live session handle. Construct via Client.Create or Client.Connect.

Fields

  • ID string: the session id.
  • ControlURL string: the wss:// JSON-RPC control channel.
  • ExpiresAt string: ISO 8601 expiry.
  • Kind SandboxKind: KindSandbox or KindDesktop.
  • Commands *Commands, Files *Files, Code *Code, Git *Git: the namespaces.

Channel

Go never opens the channel for you the first time
Unlike the other SDKs, the Go namespaces do not open the control channel on demand. Commands.Start, Files, Code, and Git return *ConnectionError (“Not connected”) until you call Connect (or a Resume/Start reconnects for you).

Once open, the channel closes itself after ClientOptions.IdleCloseMs (default 3000; a negative value turns it off) with nothing using it: no call in flight, no running command, no open PTY or watch. An open control socket counts as activity at the gateway, so one left open would keep an idle sandbox from pausing or expiring on time. The next call reopens it by itself; you do not call Connect again, and Connected() reports false while it is closed. Close, Pause, Kill or a network or gateway drop are different: after a real drop the next call returns *ConnectionError, so call Reconnect().

Connect()

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

Opens the control WebSocket. Idempotent. Only Commands.Run can avoid it. Every other namespace requires the channel, so connect first.

Parameters:

  • ctx context.Context: bounds the dial.

Returns: error

Errors: *ConnectionError if the dial fails; *TimeoutError with method "connect" after 15s.

Example:

if err := sbx.Connect(ctx); err != nil {
    log.Fatal(err)
}

Reconnect()

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

Re-opens the control channel after a drop.

Parameters:

  • ctx context.Context.

Returns: error

Example:

if !sbx.Connected() {
    err := sbx.Reconnect(ctx)
}

Connected()

func (s *Sandbox) Connected() bool

Reports whether the control channel is currently open.

Returns: bool

Example:

fmt.Println(sbx.Connected())

Close()

func (s *Sandbox) Close()

Closes the control channel locally. Does not release the remote session. Use Kill for that.

Returns: nothing.

Example:

sbx.Close()  // session keeps running until its timeout

Pause()

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

Snapshots this session’s RAM+disk, frees its host slot, and closes the control channel locally. The session keeps its id; bring it back with Resume.

Parameters:

  • ctx context.Context.

Returns: error

Example:

if err := sbx.Pause(ctx); err != nil {
    log.Fatal(err)
}

Resume()

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

Re-hydrates this paused session and re-points the control channel at the fresh slot it came back on: updates ControlURL and reconnects.

Parameters:

  • ctx context.Context.

Returns: error

Example:

if err := sbx.Resume(ctx); err != nil {
    log.Fatal(err)
}
r, _ := sbx.Commands.Run(ctx, "echo", solari.CommandOptions{Args: []string{"back"}})

Start()

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

Cold-boots this stopped session from its kept disk, then updates ControlURL and reconnects the control channel. Processes and memory are gone, files on disk are kept. See Client.Start for the refusal codes.

Parameters:

  • ctx context.Context.

Returns: error

Example:

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

Kill()

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

Destroys the remote session and closes the channel. Killing a sandbox that was already killed succeeds again; an id the gateway does not know returns a *GatewayError with status 404. The channel is closed even when the delete fails.

Parameters:

  • ctx context.Context.

Returns: error

Example:

sbx, err := client.Create(ctx, solari.CreateOptions{Template: "base"})
if err != nil {
    log.Fatal(err)
}
defer sbx.Kill(ctx)

Commands

The process-execution namespace. Reach it at sandbox.Commands.

Run()

func (c *Commands) Run(ctx context.Context, cmd string, opts CommandOptions) (*CommandResult, error)

Executes a command to completion and returns its exit code and captured output. OnStdout/OnStderr, when set, receive output as it streams.

Cancelling a command
Cancel the ctx you pass to Run: it returns context.Canceled and the whole process tree in the sandbox is stopped. This needs a cancellable ctx (one from context.WithCancel or WithTimeout); it then uses the control connection by itself. context.Background() takes the one-shot REST route, which cannot stop the process: closing that request leaves the command running until it finishes or reaches TimeoutMs. On a sandbox with shared isolation, which only has the REST route, cancelling does not stop the process.

Parameters:

  • ctx context.Context.
  • cmd string: the program to run.
  • opts CommandOptions: see CommandOptions.

Returns: (*CommandResult, error), carrying ExitCode, Stdout, Stderr (and StdoutBytes/StderrBytes, TimedOut, OOMKilled: see CommandResult). A non-zero exit returns a result, not an error, and so does a command that outlives its TimeoutMs (TimedOut true, exit code −1). A negative TimeoutMs, one over 600000 (v0.7.5 and later), or a User that is not root or a unix user name, returns a *ValidationError before anything is sent.

Errors: *ActionError, *TimeoutError, *ConnectionError, or a gateway error from the fast path.

Example:

r, err := sbx.Commands.Run(ctx, "ls", solari.CommandOptions{
    Args: []string{"-la", "/tmp"},
})
fmt.Println(r.ExitCode, r.Stdout)

// stream output as it arrives (needs the control channel)
_, err = sbx.Commands.Run(ctx, "npm", solari.CommandOptions{
    Args:     []string{"install"},
    Cwd:      "/app",
    OnStdout: func(s string) { fmt.Print(s) },
})
No shell by default
cmd runs directly with Args, not through a shell. Pipes, globs, and && will not expand. For shell syntax use Run(ctx, "sh", CommandOptions{Args: []string{"-c", "…"}}).
The first Run takes a warm HTTP fast path
On an unconnected sandbox a plain run-to-completion goes over POST /sandboxes/:id/exec, skipping the cold WS handshake. The fast path is used only when Background is false and OnStdout, OnStderr, Env, and User are all unset. It falls back to the control channel only when the route is unserved (404/405/501). A real command failure propagates, so nothing double-executes.
On isolation: shared, only the fast path works
A shared sandbox refuses cmd.start on the control channel. A plain Run on a not-yet-connected handle succeeds because it takes the HTTP fast path above. Setting Env, User, Background, or a callback, calling Commands.Start, or having the channel already open (after Connect() or a Code call) sends the command over the channel and it fails with *ActionError. Git methods run commands too, so the same applies.

Start()

func (c *Commands) Start(ctx context.Context, cmd string, opts CommandOptions) (*CommandHandle, error)

Launches a command and returns a handle immediately, without waiting for exit. Requires the control channel.

Parameters:

  • ctx context.Context.
  • cmd string: the program to run.
  • opts CommandOptions: TimeoutMs and Background are ignored here.

Returns: (*CommandHandle, error). See CommandHandle.

Errors: *ConnectionError if the channel is not open; *ActionError if the guest rejects the start.

Example:

h, err := sbx.Commands.Start(ctx, "python3", solari.CommandOptions{
    Args: []string{"-u", "worker.py"},
})
h.OnData(func(stream, data string) { fmt.Print(data) })
h.Stdin(ctx, []byte("input\n"))
code, err := h.Wait(ctx)

CommandHandle

A started command from Start.

  • CmdID string: the command id.
func (h *CommandHandle) OnData(cb func(stream, data string))
func (h *CommandHandle) Wait(ctx context.Context) (int, error)
func (h *CommandHandle) Stdin(ctx context.Context, data []byte) error
func (h *CommandHandle) CloseStdin(ctx context.Context) error
func (h *CommandHandle) Kill(ctx context.Context, signal int) error
  • OnData: subscribes to stdout/stderr chunks. Output buffered before the first subscriber is replayed, so early output is never dropped.
  • Wait: blocks until exit and returns the exit code. Also returns when the channel drops or ctx is cancelled.
  • Stdin: writes bytes to the command’s stdin.
  • CloseStdin: closes the command’s stdin (an EOF to cat, a shell, or anything reading it).
  • Kill: signals the process. signal ≤ 0 means SIGTERM.

Files

The filesystem namespace (fs.* RPCs), moving bytes over the control channel. Reach it at sandbox.Files.

File size limits and shared sandboxes
Write sends the whole file in one base64 frame and refuses more than 32 MiB before sending anything (the error says to use Upload), so one big call fails alone and the channel stays up. Upload and Download move a file in 4 MiB chunks and have no such ceiling, and Read reads through the same chunked loop (v0.3.3 and later; before that a file near 48 MiB closed the control channel). The gateway’s signed-URL upload route streams the body and accepts up to 2 GiB. On isolation: "shared" every Files method is refused; see the shared-tier restrictions.

Read()

func (f *Files) Read(ctx context.Context, path string) ([]byte, error)

Returns the raw bytes of an in-guest file.

Parameters:

  • ctx context.Context.
  • path string: absolute in-guest path.

Returns: ([]byte, error)

Errors: *ActionError if the path does not exist; *ConnectionError if the channel is not open.

Example:

b, err := sbx.Files.Read(ctx, "/tmp/out.bin")

ReadText()

func (f *Files) ReadText(ctx context.Context, path string) (string, error)

Read decoded as UTF-8 text.

Parameters:

  • ctx context.Context.
  • path string: absolute in-guest path.

Returns: (string, error)

Example:

host, err := sbx.Files.ReadText(ctx, "/etc/hostname")

Write()

func (f *Files) Write(ctx context.Context, path string, data []byte, mode int) error

Writes bytes to an in-guest path, creating or truncating it.

Parameters:

  • ctx context.Context.
  • path string: absolute in-guest path.
  • data []byte: content.
  • mode int: unix permission bits. 0 means unset and is omitted from the wire.

Returns: error

Example:

err := sbx.Files.Write(ctx, "/app/run.sh", []byte("#!/bin/sh\necho hi\n"), 0o755)

List()

func (f *Files) List(ctx context.Context, path string) ([]FsEntry, error)

Returns a directory’s entries (non-recursive).

Parameters:

  • ctx context.Context.
  • path string: directory path.

Returns: ([]FsEntry, error), each with Name, Dir, Size.

Example:

entries, _ := sbx.Files.List(ctx, "/app")
for _, e := range entries {
    fmt.Println(e.Name, e.Dir, e.Size)
}

Stat()

func (f *Files) Stat(ctx context.Context, path string) (*FsStat, error)

Returns metadata for a single path.

Parameters:

  • ctx context.Context.
  • path string: file or directory path.

Returns: (*FsStat, error), carrying Name, Dir, Size, Mode, ModTimeMs.

Example:

st, _ := sbx.Files.Stat(ctx, "/app/run.sh")
fmt.Println(st.Size, strconv.FormatInt(int64(st.Mode), 8), st.ModTimeMs)

Mkdir()

func (f *Files) Mkdir(ctx context.Context, path string) error

Creates a directory, and any missing parents.

Parameters:

  • ctx context.Context.
  • path string: directory to create.

Returns: error

Example:

err := sbx.Files.Mkdir(ctx, "/app/data")

Remove()

func (f *Files) Remove(ctx context.Context, path string, recursive bool) error

Deletes a file or directory.

Parameters:

  • ctx context.Context.
  • path string: path to delete.
  • recursive bool: required for a non-empty directory.

Returns: error

Example:

err := sbx.Files.Remove(ctx, "/tmp/build", true)

Rename()

func (f *Files) Rename(ctx context.Context, from, to string) error

Renames or moves a path.

Parameters:

  • ctx context.Context.
  • from, to string: source and destination.

Returns: error

Example:

err := sbx.Files.Rename(ctx, "/tmp/a.txt", "/tmp/b.txt")

Code

The stateful-kernel namespace. Reach it at sandbox.Code.

Run()

func (c *Code) Run(ctx context.Context, code string, opts RunCodeOptions) (*RunCodeResult, error)

Executes code in a stateful kernel. Rich outputs (PNG, HTML, JSON, structured charts) come back as Results items.

Python only
The guest runs a Python kernel and nothing else. Any other Language (javascript, typescript, bash, r) fails with an *ActionError reading “unsupported language (only python)”. The empty string and the aliases python3, py, and ipython mean Python. For other languages, run the interpreter with Commands.Run.

Parameters:

  • ctx context.Context.
  • code string: source to execute.
  • opts RunCodeOptions: Language (Python only), ContextID, OnStdout, OnStderr.

Returns: (*RunCodeResult, error), carrying Results, Charts, Error. A runtime error in the executed code lands in Error; it is not returned as a Go error.

Errors: *ActionError, *TimeoutError, *ConnectionError.

Example:

r, err := sbx.Code.Run(ctx, `
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.title("demo")
plt.show()
`, solari.RunCodeOptions{})

// Charts is a convenience view of the structured figures the guest could
// introspect. It can be empty even when a figure was drawn (it has come
// back empty on the default "base" template), so check before indexing.
// The PNG is normally on Results[i].PNG.
if len(r.Charts) > 0 {
    fmt.Println(r.Charts[0].Type)   // "line"
    fmt.Println(r.Charts[0].Title)  // "demo"
} else {
    for _, item := range r.Results {
        if item.PNG != "" {
            fmt.Println("png bytes (base64):", len(item.PNG))
        }
    }
}
Charts may be empty: never index it blind
r.Charts[0] panics with an index out of range when no figure could be introspected. Always test len(r.Charts) first and fall back to the PNG on Results[i].PNG.

CreateContext()

func (c *Code) CreateContext(ctx context.Context, language string) (string, error)

Creates a fresh kernel context so state persists across Run calls, like a REPL.

Parameters:

  • ctx context.Context.
  • language string: empty defaults to "python", which is the only language the guest supports.

Returns: (string, error), the context id.

Example:

cid, _ := sbx.Code.CreateContext(ctx, "python")
sbx.Code.Run(ctx, "x = 41", solari.RunCodeOptions{ContextID: cid})
r, _ := sbx.Code.Run(ctx, "print(x + 1)", solari.RunCodeOptions{ContextID: cid})  // 42

Git

Every method is a safe, non-shell git invocation over the command RPC, with client-side parsing and no injection surface. Reach it at sandbox.Git.

Clone()

func (g *Git) Clone(ctx context.Context, rawURL string, opts GitCloneOptions) error

Clones a repository into the guest.

Parameters:

  • ctx context.Context.
  • rawURL string: remote URL.
  • opts GitCloneOptions: Path, Branch, Depth, Username, Password, Cwd.

Returns: error

Errors: a plain error carrying the subcommand, exit code, and git’s stderr on a non-zero exit.

Example:

err := sbx.Git.Clone(ctx, "https://github.com/org/repo.git", solari.GitCloneOptions{
    Path:   "/app/repo",
    Branch: "main",
    Depth:  1,
})
Credentials travel as environment variables
Username/Password are passed as environment variables of this one command and read back by a credential helper bound to the remote’s origin: never in the URL, in .git/config or in the process arguments. A non-http(s) remote (ssh, scp-style) takes no credentials. On a shared sandbox only public remotes work. Needs v0.3.2 or later.

Status()

func (g *Git) Status(ctx context.Context, cwd string) (*GitStatus, error)

Parsed working-tree status.

Parameters:

  • ctx context.Context.
  • cwd string: repository directory; empty uses the session default.

Returns: (*GitStatus, error). See GitStatus.

Errors: a plain error on a non-zero exit.

Example:

st, _ := sbx.Git.Status(ctx, "/app/repo")
fmt.Println(st.Branch, st.Clean, st.Ahead, st.Modified)

Add()

func (g *Git) Add(ctx context.Context, paths []string, cwd string) error

Stages paths. An empty slice is a no-op; a -- separator guards paths that look like flags.

Parameters:

  • ctx context.Context.
  • paths []string: use []string{"."} for everything.
  • cwd string: repository directory.

Returns: error

Example:

err := sbx.Git.Add(ctx, []string{"."}, "/app/repo")

Commit()

func (g *Git) Commit(ctx context.Context, message string, opts GitCommitOptions) (string, error)

Commits staged changes and returns the new hash. Set Author/Email, because an ephemeral session has no git identity.

Parameters:

  • ctx context.Context.
  • message string: commit message.
  • opts GitCommitOptions: Cwd, Author, Email (scoped to this commit only), All.

Returns: (string, error), the commit hash, read back with rev-parse HEAD.

Errors: a plain error on a non-zero exit.

Example:

hash, err := sbx.Git.Commit(ctx, "add feature", solari.GitCommitOptions{
    Cwd:    "/app/repo",
    Author: "CI Bot",
    Email:  "ci@example.com",
    All:    true,
})

Push()

func (g *Git) Push(ctx context.Context, opts GitRemoteOptions) error

Pushes to a remote. Defaults to origin and the current branch.

Parameters:

  • ctx context.Context.
  • opts GitRemoteOptions: Cwd, Remote, Branch, Username, Password.

Returns: error

Errors: a plain error on a non-zero exit.

Example:

err := sbx.Git.Push(ctx, solari.GitRemoteOptions{
    Cwd:      "/app/repo",
    Username: "x-access-token",
    Password: os.Getenv("GITHUB_TOKEN"),
})
Push/Pull auth never touches the repo config
With credentials set, the SDK reads the remote’s URL and rewrites it for this one invocation via -c url.<authed>.insteadOf=<plain>. Nothing is persisted.

Pull()

func (g *Git) Pull(ctx context.Context, opts GitRemoteOptions) error

Pulls from a remote. Same options and credential handling as Push.

Parameters:

  • ctx context.Context.
  • opts GitRemoteOptions: Cwd, Remote, Branch, Username, Password.

Returns: error

Example:

err := sbx.Git.Pull(ctx, solari.GitRemoteOptions{Cwd: "/app/repo"})

Checkout()

func (g *Git) Checkout(ctx context.Context, ref string, cwd string, create bool) error

Checks out an existing ref, or creates a branch.

Parameters:

  • ctx context.Context.
  • ref string: branch, tag, or commit.
  • cwd string: repository directory.
  • create bool: create the branch (-b).

Returns: error

Example:

err := sbx.Git.Checkout(ctx, "feature/x", "/app/repo", true)

Branches()

func (g *Git) Branches(ctx context.Context, cwd string) ([]GitBranch, error)

Lists local branches.

Parameters:

  • ctx context.Context.
  • cwd string: repository directory.

Returns: ([]GitBranch, error), each with Name, Commit (short), Current.

Example:

branches, _ := sbx.Git.Branches(ctx, "/app/repo")
for _, b := range branches {
    fmt.Println(b.Current, b.Name, b.Commit)
}

Log()

func (g *Git) Log(ctx context.Context, opts GitLogOptions) ([]GitCommit, error)

Recent commits, newest first.

Parameters:

  • ctx context.Context.
  • opts GitLogOptions: Cwd, MaxCount.

Returns: ([]GitCommit, error), each with Hash, Author, Email, Date, Message.

Example:

commits, _ := sbx.Git.Log(ctx, solari.GitLogOptions{Cwd: "/app/repo", MaxCount: 10})

Not ported to Go

These exist in the TypeScript SDK but have no Go equivalent. Reach them over the HTTP API.

MissingTypeScript equivalent
*ExecInterruptedError409A one-shot command (POST /sandboxes/:id/exec) answeredExecInterrupted: the sandbox was parked while the command ran, so it may have partly run. Never retried and never re-run on the live connection; look at the sandbox and decide whether to run it again. A *GatewayError subclass.
PTYspty.create()
Listing and filtering sessionslist(), listAll()
Snapshotssnapshot(), revert(), listSnapshots(), promoteSnapshot()
Volume create/list/deletevolumes.* (attach-at-create is ported; see CreateOptions.Volumes)
Park / unparkpark(), unpark() (POST /sandboxes/:id/park and /unpark). Auto-park is ported: set Lifecycle.ParkAfterMs.
Account secretssecrets: { ENV_VAR: secretName } on create. CreateOptions has no such field; pass values through Envs instead.
Timeout extensionsetTimeout()
Signed transfer + preview URLsdownloadUrl(), uploadUrl(), previewUrl()
Metrics, session env, file search/watchmetrics(), env(), files.search(), files.watch()

Isolation tiers

CreateOptions.Isolation picks how the sandbox is placed. The zero value means IsolationDedicated.

ConstantValueWhat you get
IsolationDedicated"dedicated"Your own VM. The default. Everything on this page works.
IsolationHardened"hardened"Your own VM with outbound network blocked. A create returns 409 HostCapabilityMissing where the host does not advertise it.
IsolationShared"shared"A context inside a VM shared with your other shared sandboxes. Sandbox-only: the gateway refuses it for KindDesktop. Restricted, see below.

Shared-tier restrictions

A shared sandbox is scoped by the gateway to a private context, so siblings cannot see it. The price is that anything that would act on the whole VM is refused:

  • Control channel. The gateway forwards only code execution (code.run, code.context.create), its context-scoped exec, and a few status calls. Every other method is refused, including all fs.* calls behind Files and the cmd.start behind Commands.Start. The refusal is an *ActionError whose message ends “is not available on a shared context”. The HTTP fast path of Commands.Run still works. Named shells, tunnels, and durable executions are refused too.
  • Manual pause. Pause() returns 400, as it would hibernate the whole VM and every sibling on it. Use Lifecycle.ParkAfterMs for a context-scoped freeze, or let the automatic hibernation handle it.
  • Volumes. The Path of a VolumeAttachment is a short name matching [A-Za-z0-9_-]{1,64}, not an absolute path. The volume appears at /volumes/<name> inside the context. An absolute path is a 400.
  • Sizing. A shared context cannot ask for more CPU or memory than the machine it shares; the gateway refuses it.

Types

ClientOptions

  • APIKey string: required. Authenticates REST requests and the control-WS upgrade.
  • BaseURL string: optional. The gateway origin; defaults to https://api.getsolari.com.
  • HTTPClient *http.Client: override for tests.
  • CallTimeoutMs int: per-call control-WS RPC timeout. Default 300000.
  • MaxRetries int: default 5. 0 means “use the default”, not “no retries”. Pass -1 to disable retries.
  • RetryDelayMs *int: when non-nil, a fixed delay instead of exponential backoff. 0 disables the wait.

CreateOptions

Volumes work on sandboxes and desktops (Beta)

Attach-at-create works on both sandboxes and desktops. The mount path depends on the isolation tier: an absolute path (e.g. /data) on dedicated and hardened, but only a short name on shared (see the shared-tier restrictions). If the assigned host cannot mount volumes, the create returns 409 HostCapabilityMissing rather than silently handing back a session with nothing mounted. A volume already attached elsewhere is a 409 VolumeAlreadyAttached. See Volumes for the full explanation.

Zero and nil fields are omitted from the wire body.

  • Template string: "base" (the default, and the only built-in sandbox template) or a custom tpl_… id. Desktop templates ("workstation", "office", "code", "default") are for KindDesktop; "code" is not a sandbox template.
  • Kind SandboxKind: KindSandbox (default) or KindDesktop.
  • CPU int, MemMb int: the host clamps to slot capacity. DiskGb int: overlay disk in GiB (1–20, default 4), honored on a fresh create; a fork keeps the snapshot's disk.
  • Envs map[string]string: per-session environment.
  • Metadata map[string]string: opaque labels.
  • TimeoutMs int: rolling idle window in milliseconds before the session is released (at least 1000).
  • TtlSeconds int: the same idle window in seconds, used only when TimeoutMs is unset. Legacy: prefer TimeoutMs. Values above your plan maximum are clamped, and the effective deadline comes back as ExpiresAt.
  • Isolation SandboxIsolation: IsolationDedicated (default), IsolationHardened, or IsolationShared. See isolation tiers.
  • FromSnapshot string: boot from a snapshot instead of the template.
  • Lifecycle *SandboxLifecycle: what happens when the session goes idle. OnTimeout ("pause" or "kill") and AutoResume *bool, plus four optional millisecond knobs, all floored and capped by the gateway and omitted when zero:
    • ParkAfterMs: freeze the vCPUs after this long with no activity. The slot, ports, and control channel stay resident, so the next request wakes it in milliseconds. Zero means never auto-park.
    • ParkMaxMs: the longest a park may last before the gateway wakes the session regardless of traffic.
    • HibernateAfterParkedMs: escalate a session parked this long to a full hibernate (durable checkpoint, slot freed).
    • CheckpointEveryMs: take a live durable checkpoint at most this often, so a host loss costs at most one interval of progress. Each checkpoint briefly pauses the guest.
  • Resolution string: initial display resolution, e.g. "1280x720". Desktops only (KindDesktop); a headless sandbox has no display.
  • Record *bool: ask the gateway to record the session server-side; the create response carries a presigned playback URL. Desktops only; rejected (400 RecordingRequiresDesktop) on a headless sandbox. A pointer so an explicit false is distinguishable from unset.
  • Volumes []VolumeAttachment: persistent volumes to mount before the session starts, each with VolumeID (a vol_… id of your org) and Path (the absolute in-guest mount point, e.g. "/data"; on shared isolation a short name instead). Paths must be unique within the create. Attaching at create time is ported; creating, listing, and deleting volumes is not (see what is not ported).

SandboxView

  • SandboxID string, Kind SandboxKind, State string.
  • Metadata map[string]string, ExpiresAt string.
  • ControlURL string: may be empty; Connect derives one when it is.
  • CPU int, MemMb int.

CommandOptions

  • Args []string: the argv tail. No shell expansion.
  • Cwd string, User string.
  • Env map[string]string: per-command environment.
  • TimeoutMs int: the command's deadline in milliseconds, on either route (one-shot REST or the live connection); 0 means the tier maximum, 600000 (10 minutes).
  • Background bool: Run returns immediately with an empty result; output still streams to the callbacks.
  • OnStdout, OnStderr func(string): streamed output.

CommandResult

  • ExitCode int, Stdout string, Stderr string. The text is UTF-8, decoded over the whole stream: each invalid byte becomes U+FFFD.
  • StdoutBytes, StderrBytes []byte: the exact output bytes (Go v0.7.0 and later), so a command that prints binary data (an image, a tarball) is read from these. Exact over the control channel; over the one-shot /exec route they are exact when the gateway sends the bytes (it does for output that is not valid UTF-8) and otherwise the bytes of the text.
  • TimedOut bool: the command hit its TimeoutMs and was killed; ExitCode is −1. A command with no TimeoutMs gets the tier maximum (10 minutes).
  • OOMKilled bool: the guest killed the command for exceeding the sandbox’s memory limit (exit 137). Only the /exec route reports it; a command run over the control channel always has false.

FsEntry / FsStat

  • FsEntry: Name string, Dir bool, Size int64.
  • FsStat: Name, Dir, Size, plus Mode int (permission bits) and ModTimeMs int64 (unix millis).

RunCodeOptions / RunCodeResult

  • RunCodeOptions: Language string (only "python" is supported; empty means Python), ContextID string, OnStdout, OnStderr func(string).
  • RunCodeResult.Results []CodeResultItem: each has Type (stdout/stderr/result) plus any of Text, PNG, JPEG, SVG, HTML, LaTeX, JSON, Markdown, Chart.
  • RunCodeResult.Charts []Chart: every present chart across Results, flattened client-side.
  • RunCodeResult.Error interface{}: a *CodeError (Name, Message, Traceback) or a string; kept raw so both wire shapes round-trip.

Chart

  • Type ChartType: ChartLine, ChartScatter, ChartBar, ChartPie, ChartBoxAndWhisker, ChartComposite, ChartUnknown.
  • Title, XLabel, YLabel string.
  • X, Y *ChartAxis: Label, Ticks, Scale.
  • Elements []interface{}: per-type data (points, bars, slices), kept loose so new chart types need no SDK bump.

GitStatus

  • Branch string: empty on a detached HEAD.
  • Detached bool, Clean bool.
  • Ahead, Behind int: relative to the upstream, when set. Upstream string is the tracking branch.
  • Conflicted []string: paths with a merge conflict, each listed once.
  • Entries []GitStatusEntry: one per path with Path, OrigPath (the old path of a rename), and the two status letters Index and Worktree. Paths are verbatim (never quoted or escaped).
  • Staged, Modified, Untracked []string.

GitBranch / GitCommit

  • GitBranch: Name string, Commit string (short), Current bool, Upstream string (the tracking branch, when set). Only real branches are listed; on a detached HEAD none is Current.
  • GitCommit: Hash, Author, Email, Date (ISO 8601), Message string (the subject line), Body string (the rest of the message). Log on a repository with no commit returns an empty list.

Errors

Every error embeds *SolariError directly or transitively. Match broadly on *SolariError or narrowly on a concrete type with errors.As. Gateway errors also carry Status, Code, and Body.

TypeStatusMeaning
*AuthError401, 403API key missing, malformed, or rejected.
*PlanError402The plan does not allow this.
*ConcurrencyLimitError429Too many live sessions. Not retryable.
*NoCapacityError503No host available right now. Retryable.
*SandboxNotStoppedError409Start on a sandbox that is not stopped (NotStopped) or is already starting (StartInProgress). Carries State, the sandbox’s current state.
*ValidationError400A request the gateway refuses as invalid (Code says which). Also returned before anything is sent for a Commands.Run option the gateway would refuse (a negative TimeoutMs, a User that is not root or a unix user name) and for git input that would be read as an option (a ref, remote or branch starting with -) or a credential containing a line break.
*GitErrorNoneA git command the sandbox ran exited non-zero (Go v0.7.0 and later; before, a plain error). Carries Subcommand and ExitCode; the message is git’s own, with any credential masked.
*GatewayErrorotherAny other non-2xx response.
*ActionErrorNoneAn RPC returned ok: false. Carries Method, Code.
*TimeoutErrorNoneNo reply within the deadline. Carries Method (or "connect") and TimeoutMs.
*ConnectionErrorNoneThe control channel is not open, or the dial failed.

Not found, validation, not-stopped, not-restorable

Not-stopped has its own type, *SandboxNotStoppedError (above). The others have no dedicated types: they are plain *GatewayErrors, so match on Status and Code. The human-readable text is in Message; for a validation error it starts with the offending field name.

SituationStatusCode
Unknown sandbox, snapshot, or volume (or another org’s)404usually empty
A create option is invalid (e.g. timeoutMs under 1000)400ValidationError
Start on a sandbox that is not stopped409NotStopped, StartInProgress
FromSnapshot that cannot be restored on the current fleet. Retrying never helps409SnapshotNotRestorable
A fast-path Commands.Run on a paused sandbox409SandboxPaused (call Resume)
var ns *solari.SandboxNotStoppedError
if errors.As(err, &ns) {
    // Start on a sandbox that is not stopped; ns.State says what it is
}

var ge *solari.GatewayError
if errors.As(err, &ge) {
    switch {
    case ge.Status == 404:
        // gone or never existed
    case ge.Status == 409 && ge.Code == "SnapshotNotRestorable":
        // take a fresh snapshot; this one is permanently unusable
    case ge.Code == "ValidationError":
        log.Println(ge.Message)  // "timeoutMs: must be at least 1000 (one second)"
    }
}
_, err := client.Create(ctx, solari.CreateOptions{Template: "base"})

var capErr *solari.ConcurrencyLimitError
var noCap *solari.NoCapacityError
switch {
case errors.As(err, &noCap):
    retryLater()
case errors.As(err, &capErr):
    waitForSlot()
case err != nil:
    log.Fatal(err)
}