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@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: NewClient(), Create(), Get(), Connect(), Kill(), Pause(), Resume(), Start()Sandbox: Connect(), Reconnect(), Connected(), Close(), Pause(), Resume(), Start(), Kill()Commands: Run(), Start(), CommandHandleFiles: Read(), ReadText(), Write(), List(), Stat(), Mkdir(), Remove(), Rename()Code: Run(), CreateContext()Git: Clone(), Status(), Add(), Commit(), Push(), Pull(), Checkout(), Branches(), Log()- Isolation tiers: dedicated, hardened, and the shared-tier restrictions
- Types:
ClientOptions,CreateOptions,SandboxView,CommandOptions,CommandResult,FsEntry,FsStat,RunCodeOptions,RunCodeResult,Chart,GitStatus,GitBranch,GitCommit, errors
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:
optsClientOptions: see ClientOptions.
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:
ctxcontext.Context.optsCreateOptions: see CreateOptions.Kinddefaults toKindSandbox.
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:
ctxcontext.Context.sandboxIDstring: 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 4096Connect()
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:
ctxcontext.Context.sandboxIDstring: 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) errorDestroys 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:
ctxcontext.Context.sandboxIDstring: the sandbox id.
Returns: error
Example:
err := client.Kill(ctx, "sbx_abc123")Pause()
func (c *Client) Pause(ctx context.Context, sandboxID string) errorSnapshots 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:
ctxcontext.Context.sandboxIDstring: 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:
ctxcontext.Context.sandboxIDstring: 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:
ctxcontext.Context.sandboxIDstring: 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;Statecarries it) orStartInProgress(poll until it is running). - 409 with a disk code (
StoppedDiskMissing,StoppedDiskUnsafe,GoldenMismatch,DiskPlatformMismatch,DiskShaMismatch,DiskExceedsSpec,DiskOwnerMismatch): the stopped disk cannot be started. 409HostCapabilityMissing: the host pool is not armed for start. Retrying will not help with any of these. - 503
NoCapacity/StartTimeoutand 502StartHostErrorare transient: callStartagain (the SDK does not retry this POST for you). 500StartFailedleaves the sandbox stopped with its disk, so a laterStartis 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
IDstring: the session id.ControlURLstring: thewss://JSON-RPC control channel.ExpiresAtstring: ISO 8601 expiry.KindSandboxKind:KindSandboxorKindDesktop.Commands*Commands,Files*Files,Code*Code,Git*Git: the namespaces.
Channel
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) errorOpens the control WebSocket. Idempotent. Only Commands.Run can avoid it. Every other namespace requires the channel, so connect first.
Parameters:
ctxcontext.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) errorRe-opens the control channel after a drop.
Parameters:
ctxcontext.Context.
Returns: error
Example:
if !sbx.Connected() {
err := sbx.Reconnect(ctx)
}Connected()
func (s *Sandbox) Connected() boolReports 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 timeoutPause()
func (s *Sandbox) Pause(ctx context.Context) errorSnapshots 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:
ctxcontext.Context.
Returns: error
Example:
if err := sbx.Pause(ctx); err != nil {
log.Fatal(err)
}Resume()
func (s *Sandbox) Resume(ctx context.Context) errorRe-hydrates this paused session and re-points the control channel at the fresh slot it came back on: updates ControlURL and reconnects.
Parameters:
ctxcontext.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) errorCold-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:
ctxcontext.Context.
Returns: error
Example:
if err := sbx.Start(ctx); err != nil {
log.Fatal(err)
}Kill()
func (s *Sandbox) Kill(ctx context.Context) errorDestroys 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:
ctxcontext.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.
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:
ctxcontext.Context.cmdstring: the program to run.optsCommandOptions: 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) },
})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", "…"}}).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.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:
ctxcontext.Context.cmdstring: the program to run.optsCommandOptions:TimeoutMsandBackgroundare 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.
CmdIDstring: 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) errorOnData: subscribes tostdout/stderrchunks. 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 orctxis cancelled.Stdin: writes bytes to the command’s stdin.CloseStdin: closes the command’s stdin (an EOF tocat, 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.
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:
ctxcontext.Context.pathstring: 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:
ctxcontext.Context.pathstring: 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) errorWrites bytes to an in-guest path, creating or truncating it.
Parameters:
ctxcontext.Context.pathstring: absolute in-guest path.data[]byte: content.modeint: unix permission bits.0means 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:
ctxcontext.Context.pathstring: 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:
ctxcontext.Context.pathstring: 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) errorCreates a directory, and any missing parents.
Parameters:
ctxcontext.Context.pathstring: 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) errorDeletes a file or directory.
Parameters:
ctxcontext.Context.pathstring: path to delete.recursivebool: 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) errorRenames or moves a path.
Parameters:
ctxcontext.Context.from,tostring: 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.
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:
ctxcontext.Context.codestring: source to execute.optsRunCodeOptions: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))
}
}
}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:
ctxcontext.Context.languagestring: 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}) // 42Git
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) errorClones a repository into the guest.
Parameters:
ctxcontext.Context.rawURLstring: remote URL.optsGitCloneOptions: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,
})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:
ctxcontext.Context.cwdstring: 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) errorStages paths. An empty slice is a no-op; a -- separator guards paths that look like flags.
Parameters:
ctxcontext.Context.paths[]string: use[]string{"."}for everything.cwdstring: 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:
ctxcontext.Context.messagestring: commit message.optsGitCommitOptions: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) errorPushes to a remote. Defaults to origin and the current branch.
Parameters:
ctxcontext.Context.optsGitRemoteOptions: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"),
})-c url.<authed>.insteadOf=<plain>. Nothing is persisted.Pull()
func (g *Git) Pull(ctx context.Context, opts GitRemoteOptions) errorPulls from a remote. Same options and credential handling as Push.
Parameters:
ctxcontext.Context.optsGitRemoteOptions: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) errorChecks out an existing ref, or creates a branch.
Parameters:
ctxcontext.Context.refstring: branch, tag, or commit.cwdstring: repository directory.createbool: 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:
ctxcontext.Context.cwdstring: 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:
ctxcontext.Context.optsGitLogOptions: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.
| Missing | TypeScript equivalent | |
|---|---|---|
*ExecInterruptedError | 409 | A 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. |
| PTYs | pty.create() | |
| Listing and filtering sessions | list(), listAll() | |
| Snapshots | snapshot(), revert(), listSnapshots(), promoteSnapshot() | |
| Volume create/list/delete | volumes.* (attach-at-create is ported; see CreateOptions.Volumes) | |
| Park / unpark | park(), unpark() (POST /sandboxes/:id/park and /unpark). Auto-park is ported: set Lifecycle.ParkAfterMs. | |
| Account secrets | secrets: { ENV_VAR: secretName } on create. CreateOptions has no such field; pass values through Envs instead. | |
| Timeout extension | setTimeout() | |
| Signed transfer + preview URLs | downloadUrl(), uploadUrl(), previewUrl() | |
| Metrics, session env, file search/watch | metrics(), env(), files.search(), files.watch() |
Isolation tiers
CreateOptions.Isolation picks how the sandbox is placed. The zero value means IsolationDedicated.
| Constant | Value | What 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-scopedexec, and a few status calls. Every other method is refused, including allfs.*calls behindFilesand thecmd.startbehindCommands.Start. The refusal is an*ActionErrorwhose 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. UseLifecycle.ParkAfterMsfor a context-scoped freeze, or let the automatic hibernation handle it. - Volumes. The
Pathof aVolumeAttachmentis 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
APIKeystring: required. Authenticates REST requests and the control-WS upgrade.BaseURLstring: optional. The gateway origin; defaults tohttps://api.getsolari.com.HTTPClient*http.Client: override for tests.CallTimeoutMsint: per-call control-WS RPC timeout. Default300000.MaxRetriesint: default5.0means “use the default”, not “no retries”. Pass-1to disable retries.RetryDelayMs*int: when non-nil, a fixed delay instead of exponential backoff.0disables the wait.
CreateOptions
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.
Templatestring:"base"(the default, and the only built-in sandbox template) or a customtpl_…id. Desktop templates ("workstation","office","code","default") are forKindDesktop;"code"is not a sandbox template.KindSandboxKind:KindSandbox(default) orKindDesktop.CPUint,MemMbint: the host clamps to slot capacity.DiskGbint: overlay disk in GiB (1–20, default 4), honored on a fresh create; a fork keeps the snapshot's disk.Envsmap[string]string: per-session environment.Metadatamap[string]string: opaque labels.TimeoutMsint: rolling idle window in milliseconds before the session is released (at least 1000).TtlSecondsint: the same idle window in seconds, used only whenTimeoutMsis unset. Legacy: preferTimeoutMs. Values above your plan maximum are clamped, and the effective deadline comes back asExpiresAt.IsolationSandboxIsolation:IsolationDedicated(default),IsolationHardened, orIsolationShared. See isolation tiers.FromSnapshotstring: boot from a snapshot instead of the template.Lifecycle*SandboxLifecycle: what happens when the session goes idle.OnTimeout("pause"or"kill") andAutoResume*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.
Resolutionstring: 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 (400RecordingRequiresDesktop) on a headless sandbox. A pointer so an explicitfalseis distinguishable from unset.Volumes[]VolumeAttachment: persistent volumes to mount before the session starts, each withVolumeID(avol_…id of your org) andPath(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
SandboxIDstring,KindSandboxKind,Statestring.Metadatamap[string]string,ExpiresAtstring.ControlURLstring: may be empty; Connect derives one when it is.CPUint,MemMbint.
CommandOptions
Args[]string: the argv tail. No shell expansion.Cwdstring,Userstring.Envmap[string]string: per-command environment.TimeoutMsint: the command's deadline in milliseconds, on either route (one-shot REST or the live connection);0means the tier maximum, 600000 (10 minutes).Backgroundbool: Run returns immediately with an empty result; output still streams to the callbacks.OnStdout,OnStderrfunc(string): streamed output.
CommandResult
ExitCodeint,Stdoutstring,Stderrstring. 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/execroute 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.TimedOutbool: the command hit itsTimeoutMsand was killed;ExitCodeis −1. A command with noTimeoutMsgets the tier maximum (10 minutes).OOMKilledbool: the guest killed the command for exceeding the sandbox’s memory limit (exit 137). Only the/execroute reports it; a command run over the control channel always hasfalse.
FsEntry / FsStat
FsEntry:Namestring,Dirbool,Sizeint64.FsStat:Name,Dir,Size, plusModeint (permission bits) andModTimeMsint64 (unix millis).
RunCodeOptions / RunCodeResult
RunCodeOptions:Languagestring (only"python"is supported; empty means Python),ContextIDstring,OnStdout,OnStderrfunc(string).RunCodeResult.Results[]CodeResultItem: each hasType(stdout/stderr/result) plus any ofText,PNG,JPEG,SVG,HTML,LaTeX,JSON,Markdown,Chart.RunCodeResult.Charts[]Chart: every present chart acrossResults, flattened client-side.RunCodeResult.Errorinterface{}: a*CodeError(Name,Message,Traceback) or a string; kept raw so both wire shapes round-trip.
Chart
TypeChartType:ChartLine,ChartScatter,ChartBar,ChartPie,ChartBoxAndWhisker,ChartComposite,ChartUnknown.Title,XLabel,YLabelstring.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
Branchstring: empty on a detached HEAD.Detachedbool,Cleanbool.Ahead,Behindint: relative to the upstream, when set.Upstreamstring is the tracking branch.Conflicted[]string: paths with a merge conflict, each listed once.Entries[]GitStatusEntry: one per path withPath,OrigPath(the old path of a rename), and the two status lettersIndexandWorktree. Paths are verbatim (never quoted or escaped).Staged,Modified,Untracked[]string.
GitBranch / GitCommit
GitBranch:Namestring,Commitstring (short),Currentbool,Upstreamstring (the tracking branch, when set). Only real branches are listed; on a detached HEAD none isCurrent.GitCommit:Hash,Author,Email,Date(ISO 8601),Messagestring (the subject line),Bodystring (the rest of the message).Logon 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.
| Type | Status | Meaning |
|---|---|---|
*AuthError | 401, 403 | API key missing, malformed, or rejected. |
*PlanError | 402 | The plan does not allow this. |
*ConcurrencyLimitError | 429 | Too many live sessions. Not retryable. |
*NoCapacityError | 503 | No host available right now. Retryable. |
*SandboxNotStoppedError | 409 | Start on a sandbox that is not stopped (NotStopped) or is already starting (StartInProgress). Carries State, the sandbox’s current state. |
*ValidationError | 400 | A 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. |
*GitError | None | A 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. |
*GatewayError | other | Any other non-2xx response. |
*ActionError | None | An RPC returned ok: false. Carries Method, Code. |
*TimeoutError | None | No reply within the deadline. Carries Method (or "connect") and TimeoutMs. |
*ConnectionError | None | The 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.
| Situation | Status | Code |
|---|---|---|
| Unknown sandbox, snapshot, or volume (or another org’s) | 404 | usually empty |
A create option is invalid (e.g. timeoutMs under 1000) | 400 | ValidationError |
Start on a sandbox that is not stopped | 409 | NotStopped, StartInProgress |
FromSnapshot that cannot be restored on the current fleet. Retrying never helps | 409 | SnapshotNotRestorable |
A fast-path Commands.Run on a paused sandbox | 409 | SandboxPaused (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)
}
