Solari

Sandboxes

solari (target solari) has four classes: Client, Sandbox, CommandHandle, and GitOps. A sandbox is a headless microVM for commands, files, code, and git. Blocking and synchronous; async output arrives on the control channel’s receive thread. See the C++ SDK hub for install and configuration.

#include <solari/solari.hpp>  // umbrella header
This is the core surface, not the full TypeScript one
The C++ binding covers the core: commands, files, code, git, plus session lifecycle (pause()/resume()/start()), create-time isolation and idle lifecycle options, and create-time volume attachment. It does not bind the TypeScript SDK’s volume CRUD (client.volumes.create/list/get/delete; C++ can only attach a volume created elsewhere, by id), named snapshot management, PTYs, file watch/search, presigned transfer URLs, metrics(), env(), or previewUrl(). It also has no field for account secrets or the staged idlePolicy string at create, no create-time default user/cwd (user and cwd are per-command options), and no park()/unpark() wrappers (see Idle lifecycle). Reach those through client.http() or a TypeScript process.

Contents

Client

The sandbox entry point. Talks the gateway’s /sandboxes REST API and hands back Sandbox handles.

Constructors

Client()

explicit Client(const ClientOptions& options)

Creates a client. Opens no connection.

Parameters:

  • options.apiKey std::string: required.
  • options.baseUrl std::string: required, e.g. https://api.getsolari.com. There is no default.
  • options.callTimeoutMs long: per-RPC timeout for handles this client creates. Default 300000.

Throws: solari::Error if apiKey or baseUrl is empty.

Example:

solari::ClientOptions opts;
opts.apiKey = "slr_live_...";
opts.baseUrl = "https://api.getsolari.com";
solari::Client client(opts);

Methods

create()

std::shared_ptr<Sandbox> create(const CreateSandboxOptions& opts = {})

POST /sandboxes: creates a sandbox and returns a handle. Retry-safe: it sends a fresh idempotency key.

Parameters:

Returns: std::shared_ptr<Sandbox>, not connected; call connect() before any RPC.

Throws: AuthError, PlanError, ConcurrencyLimitError, NoCapacityError, or GatewayError.

Example:

solari::CreateSandboxOptions o;
o.template_ = "base";   // trailing underscore: "template" is a C++ keyword
o.cpu = 2;
o.memMb = 4096;

auto sbx = client.create(o);
sbx->connect();
create() always makes a sandbox
create() sends SandboxKind::Sandbox. For a GUI VM, call createDesktop(), which sends SandboxKind::Desktop and returns the same Sandbox handle plus streamUrl(). Driving the GUI is not part of the C++ surface. See VMs.

connect()

std::shared_ptr<Sandbox> connect(const std::string& sandboxId)

Re-attaches to a running sandbox by id. Fetches the view, then derives the control URL when the view omits one.

Parameters:

  • sandboxId std::string: the sandbox id.

Returns: std::shared_ptr<Sandbox>, also not connected; call connect() on the handle.

Throws: GatewayError if the id is unknown.

Example:

auto sbx = client.connect("sbx_abc123");
sbx->connect();  // Client::connect() re-attaches; Sandbox::connect() opens the socket
Two different connect()s
Client::connect(id) is a REST re-attach that builds a handle. Sandbox::connect() opens that handle’s control WebSocket. You need both. Unlike the TypeScript SDK, this one does not resume a paused session for you.

get()

SandboxView get(const std::string& sandboxId)

GET /sandboxes/:id: the current record. Returns a view, not a handle.

Parameters:

  • sandboxId std::string: the sandbox id.

Returns: SandboxView (sandboxId, kind, state, expiresAt, optional controlUrl).

Throws: GatewayError on a non-2xx response.

Example:

auto v = client.get("sbx_abc123");
std::cout << v.state << " " << v.expiresAt << "\n";

kill()

void kill(const std::string& sandboxId)

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

Parameters:

  • sandboxId std::string: the sandbox id.

Example:

client.kill("sbx_abc123");

pause()

void pause(const std::string& sandboxId)

POST /sandboxes/:id/pause: snapshots the session’s RAM+disk and frees its host slot, by id (no handle needed). Prefer Sandbox::pause() when you hold one.

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:

  • sandboxId std::string: the sandbox id.

Throws: GatewayError on a non-2xx response.

Example:

client.pause("sbx_abc123");

resume()

std::string resume(const std::string& sandboxId)

POST /sandboxes/:id/resume: brings a paused session back on a fresh host slot, by id.

Parameters:

  • sandboxId std::string: the sandbox id.

Returns: std::string, the control URL to re-attach to (the pre-pause one is stale; the session comes back on a different slot).

Throws: GatewayError on a non-2xx response.

Example:

std::string controlUrl = client.resume("sbx_abc123");

start()

std::string start(const std::string& sandboxId)

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

Parameters:

  • sandboxId std::string: the sandbox id.

Returns: std::string, the fresh control URL to re-attach to.

Throws: GatewayError. A 409 NotStopped (the sandbox is paused, parked or in another state; use resume() for a paused one) or StartInProgress (poll until it is running) arrives as SandboxNotStoppedError (v0.4.0 and later), a subclass of GatewayError whose state is the sandbox’s current state when the gateway sends it. Any other 409 carries a code such as StoppedDiskMissing, StoppedDiskUnsafe, GoldenMismatch, DiskPlatformMismatch, DiskShaMismatch, DiskExceedsSpec, DiskOwnerMismatch, or HostCapabilityMissing (host pool not armed; not retryable). A 503 NoCapacity/StartTimeout arrives as NoCapacityError and a 502 StartHostError is retryable. A 500 StartFailed is not retried and leaves the sandbox stopped with its disk, so a later start is safe.

Example:

try {
  std::string controlUrl = client.start("sbx_abc123");
} catch (const solari::SandboxNotStoppedError& e) {
  // *e.code is "NotStopped" or "StartInProgress"; e.state (std::optional) is its current state
}

http()

HttpTransport& http()

The underlying transport, for endpoints this binding does not wrap (snapshots, volumes, preview URLs). Applies auth, retries, and timeouts.

Returns: HttpTransport&, whose request() returns parsed nlohmann::json and throws the mapped typed error on failure.

Example:

auto snaps = client.http().request("GET", "/snapshots");
std::cout << snaps.dump(2) << "\n";

Sandbox

A live session handle. Construct via Client::create() or Client::connect(); never directly. Not copyable.

Properties

  • id() const std::string&: the sandbox id.
  • controlUrl() const std::string&: the wss:// JSON-RPC control channel.
  • expiresAt() const std::string&: ISO 8601 expiry.
  • commands Commands, files Files, code Code, git GitOps: member objects, not methods.
  • channel() ControlChannel&: direct channel access, for the WS adapter and unit tests.

Channel

connect()

void connect()

Opens the control WebSocket. Idempotent. Files, code, git and PTY calls need this first: on a handle that was never connected they throw ConnectionError. Commands open it themselves when they need it (env, user, output callbacks, a cancel token, or a background start), and a plain commands.run() goes over REST while the channel is closed.

Once open, the channel closes itself after 3 s with nothing using it (no call in flight, no running command, no open PTY or watch), because an open control socket counts as activity at the gateway and would keep an idle sandbox from pausing or expiring on time. The next call reopens it by itself; connected() is false meanwhile. A Client handle always uses 3 s; a hand-built Sandbox takes SandboxConfig::idleCloseMs (0 or less turns it off). If the socket drops (network, gateway, pause()), the in-flight calls fail with ConnectionError, connected() turns false and the next call throws until you call connect() again.

Throws: ConnectionError when built without SOLARI_WITH_WS, or if the socket cannot be opened.

Example:

auto sbx = client.create();
sbx->connect();

close()

void close()

Closes the control channel locally. Does not release the remote session. It keeps running until its timeout.

Example:

sbx->close();  // session survives; reattach later with client.connect(id)

connected()

bool connected() const

Whether the control channel is open.

Returns: bool

Example:

if (!sbx->connected()) sbx->connect();

kill()

void kill()

Destroys the remote session and closes the channel. Killing a sandbox that was already killed succeeds again; an id the gateway does not know throws a GatewayError with status 404.

Throws: GatewayError if the delete fails.

Example:

sbx->kill();

pause()

void pause()

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

Throws: solari::Error if this handle was not created by a Client (e.g. hand-built in a test).

Example:

sbx->pause();  // channel closes; sbx->connected() is now false

resume()

void resume()

Resumes a paused session, adopts the control URL of the fresh slot it came back on, and reopens the control channel.

Throws: solari::Error if this handle was not created by a Client; whatever connect() throws if the reopen fails.

Example:

sbx->resume();  // controlUrl() is updated; sbx->connected() is true again
auto r = sbx->commands.run("echo", [] { solari::CommandOptions o; o.args = {"back"}; return o; }());
Not exposed on GitOps' CommandRunner; this is Sandbox-level
pause()/resume() exist on both Sandbox (needs a live handle) and Client (by id, no handle needed). Unlike the TypeScript SDK, Sandbox::connect() does not auto-resume a paused session; call resume() explicitly.

start()

void start()

Cold-boots this stopped session from the disk the host kept, adopts the fresh control URL, and reopens the control channel. Processes and memory are gone; files are kept. See Client::start() for the 409 codes.

Throws: GatewayError (409 with a code) when the sandbox is not stopped or its disk cannot be started; solari::Error if the handle was not created by a Client.

Example:

auto sbx = client.connect("sbx_abc123");
sbx->start();  // controlUrl() is updated; sbx->connected() is true

Commands

commands.run()

CommandResult run(const std::string& cmd, const CommandOptions& opts = {})

Runs a command to completion and returns its result. Equivalent to Sandbox::runCommand().

Cancelling a command
Set CommandOptions::cancel to a std::shared_ptr<solari::CancelToken> and call token->cancel() from another thread: run() then throws solari::CancelledError and the whole process tree in the sandbox is stopped. A cancellable run connects on its own. Without a token, a plain run() goes over the one-shot REST route, which cannot stop the process. On a sandbox with shared isolation, which only has the REST route, cancelling does not stop the process.

Parameters:

  • cmd std::string: the program. Not a shell line.
  • opts CommandOptions: args, cwd, env, user, timeoutMs, background, onStdout, onStderr.

Returns: CommandResult, with exitCode, stdout_, stderr_ (the trailing underscores dodge the <cstdio> macros), plus stdoutBytes, stderrBytes, timedOut and oomKilled: see CommandResult. A command that outlives its timeoutMs is a result (timedOut true, exitCode −1), not an error. A negative timeoutMs, one over 600000 (v0.5.5 and later), or a user that is not root or a unix user name, throws ValidationError before anything is sent.

Throws: ActionError, TimeoutError, or ConnectionError; a GatewayError on the REST path below. A non-zero exit is not an error. Check exitCode.

Two paths: REST while closed, channel once connected
A plain run (no env, user, background, onStdout or onStderr) on a handle whose channel is not connected is sent as a one-shot POST /sandboxes/:id/exec, so it works without connect(). Anything else, or any run once the channel is open, goes over the control channel and needs connect(). With timeoutMs, a command that overruns is killed and the result is exit code -1 with the output so far.

Example:

solari::CommandOptions o;
o.args = {"-la", "/tmp"};
auto r = sbx->commands.run("ls", o);
if (r.exitCode != 0) std::cerr << r.stderr_;
std::cout << r.stdout_;
No shell by default
cmd is executed directly, so pipes, globs, and && do not work. For a shell line, run it explicitly:
o.args = {"-c", "ls /tmp | wc -l"}; sbx->commands.run("sh", o);

commands.start()

CommandHandle start(const std::string& cmd, const CommandOptions& opts = {})

Starts a command and returns a CommandHandle without waiting. Use it for long-running processes, streaming output, or stdin.

Parameters:

Returns: CommandHandle

Throws: ActionError or ConnectionError.

Example:

solari::CommandOptions o;
o.args = {"-u", "worker.py"};
auto proc = sbx->commands.start("python3", o);

proc.onData([](const std::string& stream, const std::string& data) {
  (stream == "stderr" ? std::cerr : std::cout) << data;
});
int code = proc.wait();

Code

code.run()

RunCodeResult run(const std::string& code, const RunCodeOptions& opts = {})

Executes a snippet in a stateful kernel and returns rich results. Equivalent to Sandbox::runCode().

Parameters:

  • code std::string: the source to run.
  • opts.language std::optional<std::string>: only Python is supported. Leave it unset or pass python (also accepted: python3, py, ipython). Any other value, including javascript, typescript, bash and r, fails with an ActionError (“unsupported language … (only python)”). To run other languages, start the interpreter with commands.run(), for example node or sh -c.
  • opts.contextId std::optional<std::string>: reuse a kernel so variables persist across calls.
  • opts.onStdout / opts.onStderr std::function<void(const std::string&)>: called per text item as results are parsed.

Returns: RunCodeResult (results, charts, error). A runtime error in the snippet lands in error; it does not throw.

Throws: ActionError, TimeoutError, or ConnectionError.

Example:

solari::RunCodeOptions o;
o.language = "python";
auto r = sbx->code.run(R"(
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.title("demo")
plt.show()
)", o);

if (r.error) std::cerr << r.error->dump() << "\n";
for (const auto& c : r.charts)
  std::cout << c.type << " " << c.title.value_or("") << "\n";  // "line demo"
charts can be empty: don't index it blindly
charts holds a structured chart only when a figure was introspected into one; it can be empty even when a plot was drawn (the figure then arrives as a png item in results). Loop over it, or check r.charts.empty(), instead of writing r.charts[0].
Charts are flattened for you
Every results[i].chart is lifted into the top-level charts array by flattenCodeResult(), so a matplotlib figure is structured data (type, title, axes, elements) rather than only a PNG. Chart::elements stays raw nlohmann::json so a new chart type never forces an SDK bump.

Files

Large files: use upload() and download(); not on shared isolation
files.write sends the whole file in one base64 message 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. files.upload and files.download move a file in 4 MiB chunks and have no such ceiling, and files.read reads through the same chunked loop (v0.3.2 and later; before that a file near 48 MiB closed the channel and failed every in-flight call with ConnectionError). files.* are also refused on isolation "shared". See Limits.

files.read() / files.readText()

std::string read(const std::string& path)
std::string readText(const std::string& path)

Reads a file. The two are the same call. readText() exists for parity with the other SDKs; C++ has no separate bytes type here.

Parameters:

  • path std::string: absolute in-guest path.

Returns: std::string, the raw bytes.

Throws: ActionError if the path does not exist.

Example:

auto text = sbx->files.readText("/etc/hostname");

files.write()

void write(const std::string& path, const std::string& data,
           std::optional<int> mode = std::nullopt)

Writes a file, creating or truncating it.

Parameters:

  • path std::string: absolute in-guest path.
  • data std::string: the bytes.
  • mode std::optional<int>: unix permission bits, e.g. 0755.

Throws: ActionError if the guest rejects the write (for example a permission error). A missing parent directory is not an error: it is created.

Example:

sbx->files.write("/app/run.sh", "#!/bin/sh\necho hi\n", 0755);

files.list()

std::vector<FsEntry> list(const std::string& path)

Lists a directory’s immediate children. Not recursive.

Parameters:

  • path std::string: absolute directory path.

Returns: std::vector<FsEntry>, each with name, dir, size.

Throws: ActionError if the path is not a directory.

Example:

for (const auto& e : sbx->files.list("/app"))
  std::cout << (e.dir ? "d " : "- ") << e.name << " " << e.size << "\n";

files.stat()

FsStat stat(const std::string& path)

Metadata for one path.

Parameters:

  • path std::string: absolute in-guest path.

Returns: FsStat (name, dir, size, mode, modTimeMs).

Throws: ActionError if the path does not exist.

Example:

auto st = sbx->files.stat("/app/run.sh");
std::cout << st.size << " bytes, mode " << std::oct << st.mode << "\n";

files.mkdir()

void mkdir(const std::string& path)

Creates a directory.

Parameters:

  • path std::string: absolute directory path.

Example:

sbx->files.mkdir("/app/data");

files.remove()

void remove(const std::string& path, bool recursive = false)

Deletes a file or directory. Named remove(), since delete is a C++ keyword.

Parameters:

  • path std::string: absolute in-guest path.
  • recursive bool: required to delete a non-empty directory. Default false.

Example:

sbx->files.remove("/tmp/build", true);

files.rename()

void rename(const std::string& from, const std::string& to)

Moves or renames a path.

Parameters:

  • from, to std::string: absolute paths.

Example:

sbx->files.rename("/tmp/a.txt", "/tmp/b.txt");

CommandHandle

A started command. Returned by commands.start(); not constructed directly.

Properties

  • cmdId() const std::string&: the server-side command id.

Methods

onData()

void onData(std::function<void(const std::string& stream,
                               const std::string& data)> cb)

Subscribes to output chunks. Replays anything buffered before you subscribed, so no output is lost to a late registration.

Parameters:

  • cb: called with stream ("stdout" or "stderr") and data. Runs on the channel’s receive thread.

Example:

proc.onData([](const std::string& stream, const std::string& data) {
  (stream == "stderr" ? std::cerr : std::cout) << data;
});

wait()

int wait()

Blocks until the command exits and returns its exit code.

Returns: int, the exit code.

Throws: if the channel drops before the command exits.

Example:

int code = proc.wait();

stdin_write()

void stdin_write(const std::string& data)

Writes bytes to the command’s stdin. Named stdin_write, since stdin is a <cstdio> macro.

Parameters:

  • data std::string: bytes to write. Include your own newline.

Example:

auto proc = sbx->commands.start("cat");
proc.stdin_write("hello\n");
proc.kill();

closeStdin()

void closeStdin()

Closes the command’s stdin (an EOF to cat, a shell, or anything reading it). Without it a command that reads to the end of its input waits for ever.

auto proc = sbx->commands.start("cat");
proc.stdin_write("hello\n");
proc.closeStdin();
proc.wait();

kill()

void kill(int signal = 0)

Signals the command.

Parameters:

  • signal int: signal number. 0 means the server default.

Example:

proc.kill();     // server default
proc.kill(9);    // SIGKILL

GitOps

sbx->git: safe, non-shell git invocations over the command RPC, plus client-side parsing. Arguments are passed as an argv vector, never interpolated into a shell line.

Methods

clone()

void clone(const std::string& url, const GitCloneOptions& opts = {})

Clones a repository into the guest.

Parameters:

  • url std::string: the remote.
  • opts GitCloneOptions: path, branch, depth, username, password, cwd.

Throws: ActionError if git exits non-zero.

Example:

solari::GitCloneOptions o;
o.path = "/app/repo";
o.branch = "main";
o.depth = 1;
sbx->git.clone("https://github.com/org/repo.git", o);
Credentials travel as environment variables
username + password are passed as environment variables of that one command and read back by a credential helper bound to the remote’s origin (GitOps::authFor()): never in the URL, in .git/config or in the process arguments. Only http(s) remotes take credentials, and on a shared sandbox only public remotes work. Use a PAT as the password. Needs v0.3.1 or later.

status()

GitStatus status(std::optional<std::string> cwd = std::nullopt)

Parses git status --porcelain=v1 --branch into a struct.

Parameters:

  • cwd std::optional<std::string>: the repo directory.

Returns: GitStatus (branch, upstream (std::optional, the tracking branch), detached, ahead, behind, staged, modified, untracked, conflicted, entries (a GitStatusEntry per path: path, origPath for a rename, the two status letters index and worktree), clean). Paths are verbatim (never quoted or escaped).

Example:

auto st = sbx->git.status("/app/repo");
std::cout << st.branch << " ahead " << st.ahead << " clean " << st.clean << "\n";

add()

void add(const std::vector<std::string>& paths,
         std::optional<std::string> cwd = std::nullopt)

Stages paths.

Parameters:

  • paths std::vector<std::string>: pathspecs, e.g. {"."}.
  • cwd std::optional<std::string>: the repo directory.

Example:

sbx->git.add({"."}, "/app/repo");

commit()

GitCommitResult commit(const std::string& message, const GitCommitOptions& opts = {})

Commits the index.

Parameters:

  • message std::string: the commit message.
  • opts GitCommitOptions: cwd, author, email, all (stage tracked files first).

Returns: GitCommitResult (hash).

Throws: ActionError, e.g. nothing to commit.

Example:

solari::GitCommitOptions o;
o.cwd = "/app/repo";
o.author = "CI Bot";
o.email = "ci@example.com";
o.all = true;
auto c = sbx->git.commit("add feature", o);
std::cout << c.hash << "\n";

push() / pull()

void push(const GitRemoteOptions& opts = {})
void pull(const GitRemoteOptions& opts = {})

Publishes or fetches-and-merges against a remote.

Parameters:

  • opts GitRemoteOptions: cwd, remote, branch, username, password.

Throws: ActionError on a rejected push or a merge conflict.

Example:

solari::GitRemoteOptions o;
o.cwd = "/app/repo";
o.remote = "origin";
o.branch = "main";
o.username = "git";
o.password = std::getenv("GITHUB_TOKEN");
sbx->git.push(o);

checkout()

void checkout(const std::string& ref, const GitCheckoutOptions& opts = {})

Switches to a branch, tag, or commit.

Parameters:

  • ref std::string: the target ref.
  • opts GitCheckoutOptions: cwd, create (-b).

Example:

solari::GitCheckoutOptions o;
o.cwd = "/app/repo";
o.create = true;
sbx->git.checkout("feature/x", o);

branches()

std::vector<GitBranch> branches(std::optional<std::string> cwd = std::nullopt)

Lists local branches.

Parameters:

  • cwd std::optional<std::string>: the repo directory.

Returns: std::vector<GitBranch>, each with name, commit, current and upstream (std::optional, the tracking branch). Only real branches are listed; on a detached HEAD none is current.

Example:

for (const auto& b : sbx->git.branches("/app/repo"))
  std::cout << (b.current ? "* " : "  ") << b.name << " " << b.commit << "\n";

log()

std::vector<GitCommit> log(const GitLogOptions& opts = {})

Reads commit history.

Parameters:

  • opts GitLogOptions: cwd, maxCount.

Returns: std::vector<GitCommit>, each with hash, author, email, date, message (the subject line) and body (the rest of the message). A repository with no commit returns an empty list.

Example:

solari::GitLogOptions o;
o.cwd = "/app/repo";
o.maxCount = 10;
for (const auto& c : sbx->git.log(o))
  std::cout << c.hash.substr(0, 7) << " " << c.message << "\n";

Pure helpers

Builders and parsers are exported so you can assert wire shapes with no network. GitOps itself takes an injected CommandRunner, so the whole git surface is testable against canned CommandResults.

FunctionPurpose
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.
buildCreateBody(opts, kind)The POST /sandboxes body. Unset fields are omitted.
flattenCodeResult(reply, onStdout, onStderr)A raw code.run reply → RunCodeResult, charts flattened out of results.
parseChart(json)One Chart, elements kept raw.
GitOps::authFor(url, username, password)The -c options and environment that carry the credentials for one command (for testing).
HttpTransport::prepare(...)The concrete request bytes (method, url, headers, body) without sending.
newIdempotencyKey() / encodeURIComponent()A fresh UUID v4, and path-segment escaping.
base64Encode() / base64Decode() / trim()solari/util.hpp. The codec behind files.read/write. base64Encode takes std::string or std::vector<std::uint8_t>; base64Decode tolerates missing padding.
using namespace solari;

// GitOps against a canned runner. No gateway, no socket.
std::vector<std::string> seen;
GitOps git([&](const std::string& cmd, const CommandOptions& o) -> CommandResult {
  seen = o.args;
  return {0, "## main...origin/main\n", ""};
});

auto st = git.status("/app/repo");
CHECK(st.branch == "main");
CHECK(seen == std::vector<std::string>{"status", "--porcelain=v1", "--branch"});

Isolation

CreateSandboxOptions::isolation chooses how a sandbox is separated from your other sandboxes. Unset means "dedicated".

TierWhat you get
dedicated (default)Its own microVM.
sharedA context inside a VM shared with your org’s other shared sandboxes. Cheaper, because it is a process tree rather than a machine, and siblings are separated by namespaces and a cgroup rather than a hypervisor. Never shared across orgs. Sandboxes only.
hardenedIts own microVM and no outbound network. Refused with 409 HostCapabilityMissing where the host pool does not support it. Cannot be combined with shared.

Shared-tier restrictions

  • Sandboxes only. createDesktop() with "shared" is a 400 (a desktop’s display is per-VM).
  • Size. cpu must be 4 or less and memMb 2048 or less, or the create is a 400 naming the field. The gateway does not clamp it for you.
  • fs.* and cmd.* are refused. Over the control channel a shared sandbox serves code.run only. files.*, commands.start() and a commands.run() made while the channel is open throw ActionError with code NotAvailableOnSharedIsolation. A plain commands.run() on a handle that is not connected goes over REST and works.
  • Manual pause is a 400. pause() answers GatewayError 400, because hibernating the VM would destroy every sibling context. Use park (see Idle lifecycle), or let automatic hibernation do it.
  • Volume paths are short names, not absolute paths (see volumes).
solari::CreateSandboxOptions o;
o.isolation = "shared";
o.cpu = 2;
o.memMb = 1024;

auto sbx = client.create(o);
sbx->connect();
auto r = sbx->code.run("print(1 + 1)");  // works on shared
// sbx->files.write("/tmp/a", "x");      // ActionError: NotAvailableOnSharedIsolation

Idle lifecycle, park and start

A session that sits idle moves through these states. What happens, and when, is set at create with timeoutMs and lifecycle.

StateMeaningWay back
parkedvCPUs frozen; RAM, host slot and concurrency slot kept. Cheap to hold.Wakes in milliseconds on the next touch (exec, control channel, preview, files), or call unpark.
pausedRAM and disk snapshotted; the host slot is freed.resume()
stoppedThe guest powered itself off. The disk is kept; processes and memory are not.start()

The Lifecycle struct

With no lifecycle, the gateway pauses an idle session (onTimeout = "pause", autoResume = false). Set it to change that.

  • onTimeout std::string: "pause" or "kill" (destroy the session).
  • autoResume std::optional<bool>: re-hydrate a paused session when it is re-attached.
  • parkAfterMs std::optional<long>: auto-park after this many milliseconds with no activity. Floored by the gateway and capped at the session’s idle window.
  • parkMaxMs std::optional<long>: the most a session may stay parked before the gateway wakes it, even with no traffic.
  • hibernateAfterParkedMs std::optional<long>: escalate a session parked this long to a full hibernate (durable checkpoint, slot freed).
  • checkpointEveryMs std::optional<long>: take a live durable checkpoint at most this often. Floored server-side.
solari::Lifecycle lc;
lc.onTimeout = "pause";
lc.autoResume = true;
lc.parkAfterMs = 30000;   // freeze after 30 s idle, wake on the next call

solari::CreateSandboxOptions o;
o.timeoutMs = 600000;     // 10 min idle window
o.lifecycle = lc;
auto sbx = client.create(o);

park and unpark

There is no park() or unpark() method in C++. Call the REST endpoints through client.http(). Parking suits a long tool or model wait, because any later touch wakes the sandbox by itself.

client.http().request("POST", "/sandboxes/sbx_abc123/park");    // {"state":"parked"}
client.http().request("POST", "/sandboxes/sbx_abc123/unpark");  // {"state":"running"}
Not in the C++ SDK
The gateway also takes a staged idlePolicy string at create (for example "park@30s,hibernate@2m,pause@5m,delete@1d") and account secrets. CreateSandboxOptions has no field for either, so use lifecycle above for the same timings, and the envs map for values.

Limits

LimitValue
One files.write()32 MiB; a larger one is refused before anything is sent. Use files.upload() / files.download() (4 MiB chunks, no ceiling); files.read() is chunked too.
timeoutMs at createAt least 1000 ms, and at most your plan’s maximum.
diskGb1 to 20 GiB (default 4).
cpu / memMb on isolation: "shared"4 vCPU / 2048 MiB at most.

Types

ClientOptions

  • apiKey std::string: required.
  • baseUrl std::string: required, no default.
  • callTimeoutMs long: default 300000.

CreateSandboxOptions

Volumes (Beta)

Volumes attach at create on sandboxes and on desktops. Neither is special-cased: the mount needs a host that carries the mount build, and when the host a session lands on does not, the create is refused with 409 HostCapabilityMissing rather than silently handing back a session with nothing mounted. The path format depends on isolation: dedicated takes an absolute mount point (/data); shared takes a short name matching [A-Za-z0-9_-]{1,64} and answers 400 for an absolute path. A volume mounted by another session answers 409. Volumes are not available with hardened isolation (no outbound network, and a volume is network storage): a create with volumes answers 400 naming volumes; use dedicated. See Volumes.

  • template_ std::optional<std::string>: a built-in template of the right kind, or a custom tpl_… id. The built-in sandbox template is "base" (headless Ubuntu, with Python for code.run); the built-in desktop templates are default, workstation, office and code, for createDesktop(). A template of the wrong kind, or an unknown name, is a 400. Trailing underscore: template is a C++ keyword.
  • cpu std::optional<int>: vCPUs.
  • memMb std::optional<int>: RAM in MiB.
  • diskGb std::optional<int>: overlay disk in GiB (1–20, default 4); honored on a fresh create and the guest filesystem is grown to match. A fork keeps the snapshot's disk.
  • envs std::map<std::string, std::string>: environment variables baked in at create.
  • metadata std::map<std::string, std::string>: opaque labels sent at create. SandboxView has no metadata field, so C++ does not read them back from get().
  • timeoutMs std::optional<long>: rolling idle window, in milliseconds (at least 1000). Clamped to your plan’s maximum.
  • ttlSeconds std::optional<long>: legacy idle window in seconds, used only when timeoutMs is unset. Prefer timeoutMs.
  • isolation std::optional<std::string>: "dedicated" (default), "shared" or "hardened". See Isolation.
  • fromSnapshot std::optional<std::string>: restore from a snapshot id.
  • lifecycle std::optional<Lifecycle>: idle policy: onTimeout ("pause" or "kill"), optional autoResume bool, and the park knobs parkAfterMs, parkMaxMs, hibernateAfterParkedMs, checkpointEveryMs. "pause" is what resume() recovers from. See Idle lifecycle.
  • resolution std::optional<std::string>: initial display resolution, e.g. "1280x720". Desktops only; see VMs.
  • record std::optional<bool>: record the session server-side; the create response carries a presigned playback URL. Desktops only; rejected with 400 RecordingRequiresDesktop on a headless sandbox.
  • volumes std::vector<VolumeAttachment>: persistent volumes to mount before the session starts, each a {volumeId, path} pair (a vol_… id and the absolute in-guest mount point). Volumes are created/listed/deleted via client.http() or a TypeScript process; C++ only attaches one that already exists.

CreateSandboxResponse / SandboxView

  • CreateSandboxResponse: sandboxId, kind (default "sandbox"), controlUrl, expiresAt, streamUrl optional: parsed but unused; see VMs.
  • SandboxView: sandboxId, kind, state, expiresAt, controlUrl optional.

CommandOptions / CommandResult

  • args std::vector<std::string>: argv, not a shell line.
  • cwd, user std::optional<std::string>: working directory and run-as user.
  • env std::map<std::string, std::string>: per-command environment.
  • timeoutMs std::optional<long>: per-command cap.
  • background bool: detach instead of waiting.
  • onStdout, onStderr std::function<void(const std::string&)>: streaming callbacks.
  • CommandResult: exitCode int, stdout_, stderr_ std::string: UTF-8 text decoded over the whole stream (each invalid byte becomes U+FFFD).
  • stdoutBytes, stderrBytes std::string: the exact output bytes, so a command that prints binary data is read from these. Exact on the live connection; on 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). oomKilled bool: the guest killed it for exceeding the sandbox’s memory limit (exit 137); only the REST route reports it.

FsEntry / FsStat

  • FsEntry: name std::string, dir bool, size std::int64_t.
  • FsStat: the same, plus mode int and modTimeMs std::int64_t.

RunCodeResult / Chart

  • RunCodeResult: results std::vector<CodeResultItem>, charts std::vector<Chart>, error std::optional<Json>.
  • CodeResultItem: type (stdout | stderr | result), plus optional text, png, jpeg, svg, html, latex, markdown, json_, chart.
  • Chart: type (line | scatter | bar | pie | box_and_whisker | composite | unknown), title, xLabel, yLabel, x / y ChartAxis, elements Json.
  • ChartAxis: label, scale, ticks std::vector<Json>, present bool.

Errors

A typed hierarchy rooted at solari::Error (which extends std::runtime_error). Catch a specific type, or the base.

ClassStatusMeaning
GatewayErroranyBase for HTTP failures, and the type thrown for every status that has no class of its own (see below). Carries status, code, body.
AuthError401Missing or rejected API key.
PlanError402 / 403The plan does not allow this: 402 (FeatureRequiresPlan, InsufficientCredit), or 403 NotEntitled (the plan does not include sandboxes/desktops). status is the one the gateway sent.
ConcurrencyLimitError429At the session cap (ConcurrencyLimitExceeded, or a 429 with no code). Not retried. Any other 429 (TooManyExecutions, a per-sandbox limit, a template cap) is a plain GatewayError.
NoCapacityError503No host available (NoCapacity or StartTimeout, or a 503 with no code). Retryable, and retried for you. Any other 503 (SandboxUnavailable, StoreUnavailable, …) is a plain GatewayError.
SandboxNotStoppedError409start() on a sandbox that is not stopped (NotStopped) or is already starting (StartInProgress). A GatewayError subclass; state is the current state when the gateway sends it. Any other 409 is a plain GatewayError.
ActionErrorNoneA control-WS RPC returned {ok: false}, for example a missing path, a bad language, or NotAvailableOnSharedIsolation. Carries method, code.
TimeoutErrorNoneAn RPC or connect exceeded its timeout. Carries method, timeoutMs.
ConnectionErrorNoneThe control WebSocket is not open: you have not called connect(), or it dropped. Calls do not reconnect on their own.
No NotFoundError class; ValidationError is a GatewayError
ValidationError is a GatewayError (status 400, code ValidationError): the SDK throws it before sending anything for a negative timeoutMs or a user that is not root or a unix user name, and a 400 from the gateway (bad option, wrong template kind) arrives as a plain GatewayError. A 404 (unknown id), and a 409 other than not-stopped (SnapshotNotRestorable, HostCapabilityMissing, a volume already mounted) all arrive as GatewayError. Branch on e.status and e.code, and read e.body for the detail.
try {
  auto sbx = client.create();
  sbx->connect();
} catch (const solari::ConcurrencyLimitError& e) {
  // 429 is NOT retried by the transport. Back off yourself.
  std::this_thread::sleep_for(std::chrono::seconds(2));
} catch (const solari::GatewayError& e) {
  std::cerr << e.status << " " << e.what() << "\n";
} catch (const solari::Error& e) {
  std::cerr << e.what() << "\n";
}
429 needs caller-side backoff
The transport retries idempotent requests (GET, DELETE, or anything carrying an Idempotency-Key) on network errors, the statuses 502, 503, 504 and 507, and bodies flagged retryable: true (a 500 is not retried), with backoff min(150 × 2^n, 8000) + rand(0..250) ms, 5 retries by default. ConcurrencyLimitError (429) is not retried. Handle it yourself.