Sandboxes
solari-sandbox (library solari) provides two types: Client and Sandbox. A sandbox is a headless microVM for commands, code, files, and git. See the Rust SDK hub for install and configuration.
solari-sandbox = "0.6"solari-sandbox is published to crates.io (source in the solari-sdk GitHub org).commands, files, code.run, and git. It does not yet port PTYs, snapshot management, volume management, templates, metrics, listing sandboxes, park/unpark, idle_policy, secrets, or create-time user/cwd, preview URLs, signed transfer URLs, or files.search/watch. Use the HTTP API or the TypeScript SDK for those.Contents
Client: Client::new(), create(), connect(), get(), kill(), pause(), resume(), start()Sandbox: accessors, connect(), close(), kill(), pause(), resume(), start(), commands(), files(), code(), git()Commands: run(), start(), CommandHandleFiles: read(), read_text(), write(), list(), stat(), mkdir(), remove(), rename()Code: run()Git: clone(), status(), add(), commit(), push(), pull(), checkout(), branches(), log()- Isolation: tiers and the shared-tier restrictions
- Not in the Rust crate
- Types:
ClientOptions,CreateOptions,Lifecycle,SandboxView,RunOptions,CommandResult,RunCodeOptions,RunCodeResult,Chart,FsEntry,FsStat,GitStatus,GitBranch,GitCommit, SolariError
Client
The sandbox entry point. Talks the gateway REST API.
Constructors
Client::new()
fn new(opts: ClientOptions) -> Result<Client, SolariError>Creates a client. Does not open any connection.
Parameters:
optsClientOptions:api_key,base_url,call_timeout_ms. See ClientOptions.
Returns: Result<Client, SolariError>
Errors: SolariError::Other if api_key is empty. An empty base_url is not an error: it falls back to https://api.getsolari.com.
Example:
use solari::{Client, ClientOptions};
// The hosted API (https://api.getsolari.com).
let client = Client::new(ClientOptions::with_api_key(&api_key))?;
// Or an explicit gateway (staging, self-hosted):
let client = Client::new(ClientOptions::new(&api_key, "https://gw.example.com"))?;Methods
create()
async fn create(&self, opts: CreateOptions) -> Result<Sandbox, SolariError>Creates a sandbox and returns a live handle (POST /sandboxes). Retry-safe, since it sends an idempotency key.
Parameters:
optsCreateOptions: see CreateOptions. It is a plain struct, so use..Default::default().
Returns: Result<Sandbox, SolariError>
Errors: Auth, Plan, ConcurrencyLimit, NoCapacity, or Gateway. See Errors.
Example:
use solari::CreateOptions;
let sbx = client
.create(CreateOptions {
template: Some("base".into()),
cpu: Some(2),
mem_mb: Some(4096),
..Default::default()
})
.await?;connect()
async fn connect(&self, sandbox_id: &str) -> Result<Sandbox, SolariError>Re-attaches to a running sandbox by id. Fetches its view, then derives the control URL from the gateway origin when the view omits one.
Parameters:
sandbox_id&str: the sandbox id.
Returns: Result<Sandbox, SolariError>
Errors: SolariError::Validation if the id is blank; SolariError::Gateway (status 404) if the id is unknown.
Example:
let sbx = client.connect("sbx_abc123").await?;
let out = sbx.commands().run("uptime", RunOptions::new()).await?;get()
async fn get(&self, sandbox_id: &str) -> Result<SandboxView, SolariError>Fetches a sandbox’s current record (state, kind, expiry). Returns the raw view, not a handle.
Parameters:
sandbox_id&str: the sandbox id.
Returns: Result<SandboxView, SolariError>
Errors: SolariError::Gateway on a non-2xx status.
Example:
let view = client.get("sbx_abc123").await?;
println!("{} {}", view.state, view.expires_at); // "running" …kill()
async fn kill(&self, sandbox_id: &str) -> Result<(), SolariError>Destroys a sandbox by id. Killing a sandbox that was already killed succeeds again; an id that never existed (or belongs to another org) returns SolariError::Gateway with status 404.
Parameters:
sandbox_id&str: the sandbox id.
Returns: Result<(), SolariError>
Example:
client.kill("sbx_abc123").await?;pause()
async fn pause(&self, sandbox_id: &str) -> Result<(), SolariError>Pauses a session by id (POST /sandboxes/:id/pause): the host snapshots its RAM and disk and frees the slot. The session keeps its id. Bring it back with resume(). Use the 0.3 line: solari-sandbox 0.1.x sends body-less POSTs without a Content-Length and fails with HTTP 411.
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.
Errors: SolariError::Gateway. A shared sandbox answers 400, because a manual pause would hibernate the whole VM and every sibling on it.
resume()
async fn resume(&self, sandbox_id: &str) -> Result<String, SolariError>Resumes a paused session (POST /sandboxes/:id/resume) on a fresh slot and returns the new control URL. The pre-pause URL is stale. Prefer Sandbox::resume(), which also reconnects the handle.
Errors: SolariError::Gateway, including ConcurrencyLimit if the org filled its cap while the session was paused.
start()
async fn start(&self, sandbox_id: &str) -> Result<String, SolariError>Cold-boots a stopped sandbox (its guest powered itself off) from the disk the host kept (POST /sandboxes/:id/start) and returns the fresh control URL. Processes and memory are gone; files on disk are kept. It takes a concurrency slot, and an already-running sandbox answers 200 with its current URL.
Errors: SolariError::SandboxNotStopped ( v0.4.0 and later; status 409) with code Some("NotStopped") for a paused, parked or other-state sandbox (use resume() for a paused one) or Some("StartInProgress") (poll get() until it is running); its state is the sandbox’s current state when the gateway sends it. Any other 409 stays SolariError::Gateway, for example a code that says the kept disk cannot be started (StoppedDiskMissing, StoppedDiskUnsafe, GoldenMismatch, and others). 503 NoCapacity and StartTimeout map to NoCapacity and are retryable; a 500 StartFailed is not, and leaves the sandbox stopped with its disk.
Sandbox
A live headless session. Construct via Client::create() or Client::connect().
Accessors
fn id(&self) -> &str // the session id
fn kind(&self) -> &str // "sandbox" or "desktop"
fn control_url(&self) -> &str // wss:// JSON-RPC control channel
fn stream_url(&self) -> Option<&str> // live view; Some for desktops only
fn expires_at(&self) -> &str // ISO 8601 expiry
fn connected(&self) -> bool // whether the control channel is openChannel
connect()
async fn connect(&self) -> Result<(), SolariError>Opens the control WebSocket. Idempotent. Every namespace opens it on demand, so calling this is only a latency optimization.
Returns: Result<(), SolariError>
Errors: SolariError::Connection if the socket cannot be opened; SolariError::Timeout if the upgrade exceeds the call timeout.
Example:
sbx.connect().await?;commands().start(), files() and code() open the socket themselves when it is closed, so you never need a connected-check before calling them. Once open, the socket closes itself after ClientOptions::idle_close_ms (None means 3000; Some(0) 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. Only the low-level ControlChannel::call fails with Connection when the socket is not open./exec route instead of the WebSocket when the channel is not already open and the call needs no streaming. For a single command, skipping connect() is faster.close()
fn close(&self)Closes the control channel locally. Does not release the remote session. Use kill() for that.
Returns: ()
Example:
sbx.close(); // the session keeps running until its timeoutkill()
async fn kill(&self) -> Result<(), SolariError>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 SolariError::Gateway with status 404.
Returns: Result<(), SolariError>
Errors: SolariError::Gateway on a non-2xx status.
Example:
let result = sbx.commands().run("./build.sh", RunOptions::new()).await;
sbx.kill().await?;
result?;pause()
async fn pause(&self) -> Result<(), SolariError>Pauses this session (RAM and disk snapshotted, slot freed) and closes the control channel. The session keeps its id. Same errors as Client::pause(). While it is paused, commands().run() fails with a 409 SandboxPaused unless the sandbox was created with lifecycle.auto_resume.
resume()
async fn resume(&mut self) -> Result<(), SolariError>Resumes this paused session, adopts the new control URL and reconnects the channel. It takes &mut self because it replaces the handle’s control_url, so declare the handle let mut sbx.
let mut sbx = client.create(CreateOptions::default()).await?;
sbx.pause().await?;
sbx.resume().await?;
let out = sbx.commands().run("uname", RunOptions::new().args(["-a"])).await?;start()
async fn start(&mut self) -> Result<(), SolariError>Cold-boots this stopped session from its kept disk and reconnects the channel. Files on disk are kept; processes and memory are not. See Client::start() for the refusal codes. It takes &mut self like resume().
Commands
Run processes in the guest. Obtain with sbx.commands().
run()
async fn run(&self, cmd: &str, opts: RunOptions) -> Result<CommandResult, SolariError>Runs a command to completion and returns its exit code and captured output. A non-zero exit is Ok, not an error.
run() (or wrap it in tokio::time::timeout) and the process in the sandbox gets SIGTERM, then SIGKILL after 2 seconds; the whole process tree is stopped. Call sbx.connect().await first: on the one-shot /exec route, dropping the call does not stop the process (the crate CHANGELOG says the same). On a sandbox with shared isolation, which only has the one-shot route, dropping the call does not stop the process.Parameters:
cmd&str: the program to run.optsRunOptions: see RunOptions.
Returns: Result<CommandResult, SolariError> with exit_code, stdout, stderr (and stdout_bytes/stderr_bytes, timed_out, oom_killed: see CommandResult). With background: true it returns immediately with an empty result. A command that outlives its timeout_ms is a result (timed_out true, exit code −1), not an error; a timeout_ms over 600000 (0.6.1 and later) or a user that is not root or a unix user name is a SolariError::Validation before anything is sent.
Errors: SolariError::Connection if the channel drops before the process exits; Action if the guest rejects the RPC.
Example:
use solari::RunOptions;
let r = sbx.commands().run("ls", RunOptions::new().args(["-la", "/tmp"])).await?;
println!("{} {}", r.exit_code, r.stdout);
// Stream output as it arrives.
let opts = RunOptions {
args: Some(vec!["install".into()]),
cwd: Some("/app".into()),
on_stdout: Some(std::sync::Arc::new(|s: &str| print!("{s}"))),
..Default::default()
};
sbx.commands().run("npm", opts).await?;cmd is executed directly with args, not through a shell. Pipes, globs, and && will not expand. For shell syntax use run("sh", RunOptions::new().args(["-c", "…"])).start()
async fn start(&self, cmd: &str, opts: RunOptions) -> Result<CommandHandle, SolariError>Starts a command and returns a handle immediately, without waiting for exit. Use it for interactive or long-running processes.
Parameters:
cmd&str: the program to run.optsRunOptions: see RunOptions.
Returns: Result<CommandHandle, SolariError>
Errors: SolariError::Other if the guest reply carries no cmdId; Connection if the control socket cannot be opened (it is opened on demand, so a closed channel is not an error by itself); Action if the guest or a shared sandbox refuses the RPC.
Example:
let proc = sbx
.commands()
.start("python3", RunOptions::new().args(["-u", "worker.py"]))
.await?;
proc.stdin("input\n").await?;
let out = proc.wait().await?;
println!("exit {}", out.exit_code);CommandHandle
Returned by start(). Field cmd_id String identifies the process.
async fn stdin(&self, data: impl AsRef<[u8]>) -> Result<(), SolariError>
async fn kill(&self, signal: Option<i64>) -> Result<(), SolariError>
fn io(&self) -> CommandIo
async fn wait(self) -> Result<CommandResult, SolariError>stdin(data): writes bytes to the command’s stdin (base64-framed on the wire).kill(signal): signals the process;Nonemeans the guest default (SIGTERM).io(): a cloneableCommandIoon the command’s input side, becausewait()consumes the handle. It hasstdin(data),close_stdin()(an EOF tocator a shell),kill(signal)andcmd_id(), so another task can keep writing or signalling while one waits.wait(): consumes the handle, accumulating stdout/stderr until exit. Errors withConnectionif the channel closes first.
Example:
let proc = sbx.commands().start("sleep", RunOptions::new().args(["60"])).await?;
proc.kill(Some(9)).await?; // SIGKILL
let out = proc.wait().await?;Files
Guest filesystem access over the control channel. Obtain with sbx.files(). Bytes are base64-framed on the wire.
write() sends the whole file in one JSON-RPC message, base64-encoded (about 4/3 of the file size), and refuses more than 32 MiB before sending anything (the error says to use upload()), so one big call fails alone and the control connection 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 (crate 0.3.3 and later; before that a file near 48 MiB closed the control connection). The signed-URL upload route, which this crate does not wrap, streams a body of up to 2 GiB. On a shared sandbox every files() call is refused.read()
async fn read(&self, path: &str) -> Result<Vec<u8>, SolariError>Reads a file’s raw bytes.
Parameters:
path&str: absolute in-guest path.
Returns: Result<Vec<u8>, SolariError>
Errors: SolariError::Action if the guest cannot read it; Other on a bad base64 payload.
Example:
let bytes = sbx.files().read("/tmp/out.bin").await?;read_text()
async fn read_text(&self, path: &str) -> Result<String, SolariError>Reads a file as UTF-8 text. Invalid sequences are replaced, not rejected.
Parameters:
path&str: absolute in-guest path.
Returns: Result<String, SolariError>
Errors: as read().
Example:
let host = sbx.files().read_text("/etc/hostname").await?;write()
async fn write(
&self,
path: &str,
data: impl AsRef<[u8]>,
mode: Option<i64>,
) -> Result<(), SolariError>Writes a file, creating or truncating it.
Parameters:
path&str: absolute in-guest path.dataimpl AsRef<[u8]>: content;&strandVec<u8>both work.modeOption<i64>: unix permission bits, e.g.Some(0o755).
Returns: Result<(), SolariError>
Errors: SolariError::Action on a guest-side failure.
Example:
sbx.files().write("/app/run.sh", "#!/bin/sh\necho hi\n", Some(0o755)).await?;list()
async fn list(&self, path: &str) -> Result<Vec<FsEntry>, SolariError>Lists a directory’s entries (non-recursive).
Parameters:
path&str: directory path.
Returns: Result<Vec<FsEntry>, SolariError>, each with name, dir, size.
Errors: SolariError::Other if the entries do not parse.
Example:
for e in sbx.files().list("/app").await? {
println!("{} {} {}", if e.dir { "d" } else { "-" }, e.name, e.size);
}stat()
async fn stat(&self, path: &str) -> Result<FsStat, SolariError>Returns one entry’s metadata.
Parameters:
path&str: file or directory path.
Returns: Result<FsStat, SolariError> with name, dir, size, mode, mod_time_ms.
Errors: SolariError::Other if the reply does not parse.
Example:
let st = sbx.files().stat("/app/run.sh").await?;
println!("{} {:o} {}", st.size, st.mode, st.mod_time_ms);mkdir()
async fn mkdir(&self, path: &str) -> Result<(), SolariError>Creates a directory, including parents.
Parameters:
path&str: directory to create.
Returns: Result<(), SolariError>
Example:
sbx.files().mkdir("/app/data/nested").await?;remove()
async fn remove(&self, path: &str, recursive: bool) -> Result<(), SolariError>Deletes a file or directory.
Parameters:
path&str: path to delete.recursivebool: required for non-empty directories.
Returns: Result<(), SolariError>
Example:
sbx.files().remove("/tmp/build", true).await?;rename()
async fn rename(&self, from: &str, to: &str) -> Result<(), SolariError>Renames or moves a path.
Parameters:
from,to&str: source and destination.
Returns: Result<(), SolariError>
Example:
sbx.files().rename("/tmp/a.txt", "/tmp/b.txt").await?;Code
Stateful kernel execution. Obtain with sbx.code().
run()
async fn run(&self, code: &str, opts: RunCodeOptions) -> Result<RunCodeResult, SolariError>Runs code in a stateful kernel. Rich outputs (PNG, HTML, JSON, structured charts) come back as results items.
Parameters:
code&str: source to execute.optsRunCodeOptions:language(Python only; see below) andcontext_id.
Returns: Result<RunCodeResult, SolariError> with results, charts, error. A runtime error in the code lands in error; it is not a SolariError.
Errors: SolariError::Action or Connection. Transport failures only, never the code’s own exceptions.
Example:
use solari::RunCodeOptions;
let r = sbx
.code()
.run(
"import matplotlib.pyplot as plt\nplt.plot([1,2,3],[4,5,6])\nplt.title('demo')\nplt.show()",
RunCodeOptions::default(),
)
.await?;
let png = r.results.iter().find_map(|i| i.png.as_ref()); // base64 PNG of the figure
// `charts` is the structured form of each figure the kernel could introspect.
// It is empty when there is no figure (or none it could read), so do not index it blindly.
if let Some(chart) = r.charts.first() {
println!("{:?} {:?}", chart.chart_type, chart.title); // Line, Some("demo")
}language accepts "python" (also "python3", "py", "ipython", or unset). Anything else, such as "javascript", "typescript", "bash" or "r", fails with a SolariError::Action whose message is unsupported language ... (only python). To run other languages, call them as processes with commands().run(), for example run("node", RunOptions::new().args(["-e", "…"])). The base image ships Python 3 with matplotlib, IPython and Node.js 20.RunCodeOptions::context_id reuses a kernel context so state persists across calls, like a REPL. The Rust crate has no create_code_context() to mint one. Obtain the id from the HTTP API or the TypeScript SDK, then pass it here.Git
Obtain with sbx.git(). Every call is a non-shell git invocation in the guest, with no injection surface. Requires git on PATH, which the base template ships.
clone()
async fn clone(&self, url: &str, opts: GitCloneOptions) -> Result<(), SolariError>Clones a repository into the guest.
Parameters:
url&str: remote URL.optsGitCloneOptions:path,branch,depth,username,password,cwd.
Returns: Result<(), SolariError>
Errors: SolariError::Git carrying the subcommand, exit code, and git’s stderr.
Example:
use solari::GitCloneOptions;
sbx.git()
.clone("https://github.com/org/repo.git", GitCloneOptions {
path: Some("/app/repo".into()),
branch: Some("main".into()),
depth: Some(1),
..Default::default()
})
.await?;status()
async fn status(&self, cwd: Option<&str>) -> Result<GitStatus, SolariError>Parsed working-tree status.
Parameters:
cwdOption<&str>: repository directory.
Returns: Result<GitStatus, SolariError>. See GitStatus.
Errors: SolariError::Git on a non-zero exit.
Example:
let st = sbx.git().status(Some("/app/repo")).await?;
println!("{} clean={} +{}/-{}", st.branch, st.clean, st.ahead, st.behind);add()
async fn add(&self, paths: &[String], cwd: Option<&str>) -> Result<(), SolariError>Stages paths. An empty slice is a no-op. Paths are passed after --, so flag-like names are safe.
Parameters:
paths&[String]: use["."]for everything.cwdOption<&str>: repository directory.
Returns: Result<(), SolariError>
Errors: SolariError::Git on a non-zero exit.
Example:
sbx.git().add(&[".".to_string()], Some("/app/repo")).await?;commit()
async fn commit(&self, message: &str, opts: GitCommitOptions) -> Result<String, SolariError>Commits staged changes and returns the new hash. Set author/email, because an ephemeral session has no git identity.
Parameters:
message&str: commit message.optsGitCommitOptions:cwd,author,email(passed as-coverrides, scoped to this commit),all(stage tracked modifications first).
Returns: Result<String, SolariError> carrying the commit hash, read back with rev-parse HEAD.
Errors: SolariError::Git on a non-zero exit.
Example:
use solari::GitCommitOptions;
let hash = sbx
.git()
.commit("add feature", GitCommitOptions {
cwd: Some("/app/repo".into()),
author: Some("CI Bot".into()),
email: Some("ci@example.com".into()),
..Default::default()
})
.await?;push() / pull()
async fn push(&self, opts: GitRemoteOptions) -> Result<(), SolariError>
async fn pull(&self, opts: GitRemoteOptions) -> Result<(), SolariError>Pushes to or pulls from a remote. Credentials (http(s) remotes only) travel as environment variables of that one command through a credential helper bound to the remote’s origin: never in the URL, in .git/config or in the process arguments. On a shared sandbox only public remotes work. Needssolari-sandbox 0.3.2 or later.
Parameters:
optsGitRemoteOptions:cwd,remote(default"origin"),branch(default: the current branch’s upstream),username,password.
Returns: Result<(), SolariError>
Errors: SolariError::Git on a non-zero exit.
Example:
use solari::GitRemoteOptions;
sbx.git()
.push(GitRemoteOptions {
cwd: Some("/app/repo".into()),
username: Some("x-access-token".into()),
password: Some(github_token),
..Default::default()
})
.await?;checkout()
async fn checkout(&self, r#ref: &str, cwd: Option<&str>, create: bool) -> Result<(), SolariError>Checks out an existing ref, or creates a branch. Positional arguments here, not an options struct.
Parameters:
ref&str: branch, tag, or commit.cwdOption<&str>: repository directory.createbool: create the branch (-b).
Returns: Result<(), SolariError>
Errors: SolariError::Git on a non-zero exit.
Example:
sbx.git().checkout("feature/x", Some("/app/repo"), true).await?;branches()
async fn branches(&self, cwd: Option<&str>) -> Result<Vec<GitBranch>, SolariError>Lists local branches.
Parameters:
cwdOption<&str>: repository directory.
Returns: Result<Vec<GitBranch>, SolariError>, each with name, commit, current.
Errors: SolariError::Git on a non-zero exit.
Example:
for b in sbx.git().branches(Some("/app/repo")).await? {
println!("{} {} {}", if b.current { "*" } else { " " }, b.name, b.commit);
}log()
async fn log(&self, opts: GitLogOptions) -> Result<Vec<GitCommit>, SolariError>Recent commits, newest first.
Parameters:
optsGitLogOptions:cwd,max_count(applied only when positive).
Returns: Result<Vec<GitCommit>, SolariError>, each with hash, author, email, date, message.
Errors: SolariError::Git on a non-zero exit.
Example:
use solari::GitLogOptions;
let commits = sbx
.git()
.log(GitLogOptions { cwd: Some("/app/repo".into()), max_count: Some(10) })
.await?;Isolation
CreateOptions::isolation (Option<String>) picks how much machine a sandbox gets. Any other value is a 400 ValidationError on field isolation.
| Value | What you get |
|---|---|
"dedicated" (default) | Its own microVM. |
"shared" | A context (a process tree in its own namespaces and cgroup) inside a VM shared with your org’s other shared sandboxes. Cheap, but separated from its siblings by the kernel, not by a hypervisor. Sandboxes only: a desktop create with shared is refused. |
"hardened" | Its own microVM with no outbound network. May be refused with 409 HostCapabilityMissing where the host pool does not advertise support for it. |
let sbx = client
.create(CreateOptions {
isolation: Some("shared".into()),
cpu: Some(2), // at most 4 on shared
mem_mb: Some(1024), // at most 2048 on shared (512 if unset)
..Default::default()
})
.await?;Shared-tier restrictions
- Size.
cpuabove 4 ormem_mbabove 2048 is refused with a 400 naming the field, not clamped. An unsetmem_mbdefaults to 512 MiB, not 2048. - Control channel allowlist. A shared sandbox can run commands (through the one-shot
/execroute) andcode.run. Every other control call is refused withSolariError::Actioncarrying the codeNotAvailableOnSharedIsolation: all offiles()(fs.*), andcommands().start(), which usescmd.startover the socket. - Commands depend on the channel state.
commands().run()takes the/execroute only while the control channel is closed and the call sets no callbacks,envoruser. Aftercode().run()has opened the socket, the same call goes over the socket and is refused. Call close() first, or run commands before code.git()runs throughcommands().run(), so it follows the same rule. - No manual pause. pause() answers 400, because hibernating the shared VM would destroy every sibling on it. Automatic hibernation after idle still applies.
- Volume paths are names. For a volume on a shared sandbox,
pathmust be a short name matching[A-Za-z0-9_-]{1,64}, mounted inside the context, not an absolute path. On dedicated sandboxes it must be an absolute path such as/data. A duplicate path is a 400. - No create-time
userorcwd. These are refused on shared (see Not in the Rust crate).
Not in the Rust crate
These gateway features exist but CreateOptions and Sandbox have no field or method for them in solari-sandbox 0.3. Use the HTTP API or the TypeScript SDK.
- park / unpark (
POST /sandboxes/:id/park,/unpark). Automatic parking is still available throughLifecycle::park_after_ms. idle_policy: the stagedpark@30s,hibernate@2m,pause@5m,delete@1dstring. Settimeout_msand Lifecycle instead.secretsat create (account secrets the gateway resolves into the sandbox environment). Pass plain values withenvsinstead.- Default
user/cwdat create. Per command,RunOptions::userandRunOptions::cwddo exist. - Listing sandboxes, volume management, templates, snapshot management, PTYs, metrics, preview and transfer URLs,
files.search/watch, and creating code contexts.
Types
ClientOptions
api_keyString: required; empty is rejected.base_urlString: trailing slash stripped. Empty meansDEFAULT_BASE_URL,https://api.getsolari.com. The control-WS origin is derived from it (http→ws).call_timeout_msOption<u64>: per-RPC control-WS timeout.Noneuses the default of300_000.
ClientOptions::with_api_key(&api_key) // https://api.getsolari.com
ClientOptions::new(&api_key, "https://gw.example.com") // explicit gatewayCreateOptions
A plain struct implementing Default, not a builder. Unset fields are omitted from the wire.
templateOption<String>:"base"(the default, and the only built-in sandbox template) or a promoted custom template id (tpl_…). The desktop template names ("code","workstation","office","default") and unknown names are refused with a 400ValidationErroron a sandbox create. There is nopython-kerneltemplate; Python is part ofbase.cpuOption<u32>,mem_mbOption<u32>: the host clamps to slot capacity.disk_gbOption<u32>: overlay disk in GiB (1–20, default 4), honored on a fresh create; a fork keeps the snapshot's disk.isolationOption<String>:"dedicated"(default),"shared"or"hardened". See Isolation.envsOption<HashMap<String, String>>: per-session environment.metadataOption<HashMap<String, String>>: opaque labels.timeout_msOption<u64>: the idle window. It is rolling (activity resets it), not a fixed deadline. When it passes with no activity,lifecycle.on_timeoutapplies: the default is"pause"(resumable), and"kill"destroys the sandbox. Defaults to 2 hours for a sandbox (30 minutes for a desktop), and values above your plan’s maximum are clamped. The gateway acts on an expired window on a sweep, so removal can trail the deadline by minutes.ttl_secondsOption<u64>: the same window in seconds. A fallback used only whentimeout_msis unset; prefertimeout_ms.from_snapshotOption<String>: boot from a snapshot instead of the template.volumesOption<Vec<VolumeAttachment>>: persistent volumes to mount before the guest starts, eachVolumeAttachment { volume_id, path }with avol_…id from your org. The mount survives pause and resume.pathis an absolute in-guest path (a short name on shared). A volume that is already attached elsewhere is refused with 409VolumeAlreadyAttached. Create and delete volumes through the HTTP API or the TypeScript SDK; this crate only attaches them.lifecycleOption<Lifecycle>: see Lifecycle.resolutionOption<String>,recordOption<bool>: desktops only. Arecordon a headless sandbox is refused with 400RecordingRequiresDesktop.
CreateOptions has no kind field: the flavour is chosen by which method you call. create() sends kind: "sandbox" on the wire. For a GUI VM, call create_desktop(), which sends kind: "desktop" and returns the same Sandbox handle plus stream_url(). Driving the GUI is not part of the Rust surface. See VMs.Lifecycle
on_timeoutString:"pause"or"kill", applied when the idle window passes.auto_resumeOption<bool>: wake a paused sandbox on the next request instead of answering 409SandboxPaused(defaultfalse).park_after_msOption<u64>: freeze the vCPUs after this long with no activity. The slot, ports and control channel stay, and the next request wakes it in milliseconds.park_max_msOption<u64>: the longest a session may stay parked before the gateway wakes it.hibernate_after_parked_msOption<u64>: escalate a session parked this long to a durable checkpoint that frees the slot.checkpoint_every_msOption<u64>: take a live checkpoint at most this often while running.
The gateway clamps the millisecond values to its minimums and to the idle window. A non-numeric or non-positive value is a 400 naming the field.
SandboxView
sandbox_idString,kindString,stateString: e.g."running","paused","parked","stopped".expires_atString: ISO 8601.control_urlOption<String>: some gateways include it; otherwise connect() derives it.
RunOptions
Struct + two builder shorthands (.args(), .cwd()). Everything else goes through struct literal syntax.
argsOption<Vec<String>>: argv tail; no shell expansion.cwd,userOption<String>,timeout_msOption<u64>.envOption<HashMap<String, String>>: per-command environment.backgroundbool: return immediately; output still streams via callbacks.on_stdout,on_stderrOption<OutputCallback>:Arc<dyn Fn(&str) + Send + Sync>.
/exec route (skipping the WebSocket entirely) when the channel is closed and the call sets no on_stdout/on_stderr, no env, no user, and background: false. It falls back to the control channel only if the gateway does not serve /exec (404/405/501); any other failure propagates, so a command never double-executes.CommandResult
exit_codei64,stdoutString,stderrString. The text is UTF-8, decoded over the whole stream: each invalid byte becomes U+FFFD.stdout_bytes,stderr_bytesVec<u8>: the exact output bytes, so a command that prints binary data (an image, a tarball) is read from these. Exact on the control channel; on 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.timed_outbool: the command hit itstimeout_msand was killed;exit_codeis −1.oom_killedbool: the guest’s memory watchdog killed the command (exit 137 alone is ambiguous). Always present;falseon every path that does not report it.
RunCodeOptions / RunCodeResult
RunCodeOptions:languageOption<String> (python server-side default),context_idOption<String>.RunCodeResult:resultsVec<CodeResultItem>,errorOption<Value>,chartsVec<Chart>: every chart acrossresults, flattened client-side.CodeResultItem:result_typeString (stdout/stderr/result) plus optionaltext,png,jpeg,svg,html,latex,json,markdown,chart.
Chart
chart_typeChartType:Line,Scatter,Bar,Pie,BoxAndWhisker,Composite,Unknown. Unrecognized wire values deserialize toUnknownrather than failing.title,x_label,y_labelOption<String>.x,yOption<ChartAxis>:label,ticks,scale.elementsOption<Value>: per-type data (points, bars, slices), kept as raw JSON so new chart types do not need an SDK bump.
FsEntry / FsStat
FsEntry:nameString,dirbool,sizei64.FsStat: the above plusmodei64 (permission bits) andmod_time_msi64 (unix millis).
GitStatus / GitBranch / GitCommit
GitStatus:branchString (empty on a detached HEAD or a repo with no commits),detachedbool,cleanbool,ahead/behindi64,staged/modified/untracked/conflictedVec<String>,upstreamOption<String> (the tracking branch), andentriesVec<GitStatusEntry> (path,orig_pathfor a rename, and the two status lettersindexandworktree). Paths are verbatim (never quoted or escaped).GitBranch:name,commitString,currentbool,upstreamOption<String>. Only real branches are listed; on a detached HEAD none iscurrent.GitCommit:hash,author,email,date,messageString (the subject line) andbodyString (the rest).log()on a repository with no commit returns an empty list.
Errors
One SolariError enum covers every failure, flattening the TypeScript error hierarchy so you can match broadly. .status() returns Option<u16> for the gateway variants.
| Variant | Status | Meaning |
|---|---|---|
Auth | 401 | API key missing, malformed, or rejected. |
Plan | 402, 403 | The plan does not allow this: 402 FeatureRequiresPlan or InsufficientCredit, or 403 NotEntitled. Any other 403 is a Gateway error. |
ConcurrencyLimit | 429 | At the session cap (ConcurrencyLimitExceeded, or a 429 with no code). Not retried. Other 429s (such as TooManyExecutions) are Gateway errors. |
NoCapacity | 503 | No host available right now (NoCapacity, StartTimeout, or a 503 with no code). Retryable. Other 503s (SandboxUnavailable, StoreUnavailable, and so on) are Gateway errors. |
SandboxNotStopped | 409 | start() on a sandbox that is not stopped (NotStopped) or is already starting (StartInProgress). Carries code and state, the sandbox’s current state when the gateway sends it. Any other 409 is a Gateway error. |
ExecInterrupted | 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. |
Gateway | other | Any other non-2xx response. Carries status, message and the gateway’s code. See the note below. |
Action | None | An RPC replied ok: false. Carries method. |
Timeout | None | No reply within the call timeout. Carries method, timeout_ms. |
Connection | None | The control WebSocket could not be opened, or dropped before a reply. |
Git | None | A git subcommand exited non-zero, or the SDK refused git input before running anything (a ref, remote or branch starting with -, a credential containing a line break). |
Validation | None | You passed an invalid argument, such as a blank sandbox id to connect(), or a user for commands().run that is not root or a unix user name. Nothing was sent. (A request the gateway rejects with a 400 is a Gateway error instead.) |
Other | None | Bad response body, or an internal invariant. |
The enum is #[non_exhaustive], so keep a wildcard arm. Not-stopped has its own variant, SandboxNotStopped. There are no separate not-found, validation or not-restorable variants. Those arrive as Gateway and are told apart by status and code:
- Not found:
status: 404(for example get() on an unknown id). - Request rejected:
status: 400,code: Some("ValidationError"), with the field named inmessage. - Not stopped:
SandboxNotStopped(status: 409,code: Some("NotStopped")orSome("StartInProgress"), plusstate) from start(). - Snapshot cannot be restored on the current template build:
status: 409,code: Some("SnapshotNotRestorable"). It is permanent, so do not retry.
use solari::SolariError;
match client.create(opts).await {
Ok(sbx) => { /* … */ }
Err(SolariError::NoCapacity { .. }) => retry_later().await,
Err(SolariError::ConcurrencyLimit { .. }) => wait_for_slot().await,
Err(SolariError::Gateway { status: 400, message, .. }) => eprintln!("bad request: {message}"),
Err(e) => return Err(e),
}
match client.start("sbx_abc123").await {
Ok(control_url) => { /* … */ }
Err(SolariError::SandboxNotStopped { code, state, .. }) => {
// code: "NotStopped" or "StartInProgress"; state: its current state, if sent
}
Err(e) => return Err(e),
}
