Solari

Sandboxes

solari-sandbox: classes SandboxClient and Sandbox. A sandbox is a headless microVM for commands, code, files, and git. See the Python SDK hub for install and configuration.

pip install solari-sandbox
Sandbox is the shared base of Desktop
Every Sandbox method below is inherited from SessionHandle and is also available on Desktop. A Desktop is a Sandbox plus the GUI surface.

Contents

Result dataclasses keep camelCase fields
Method arguments are idiomatic snake_case (mem_mb, from_snapshot), but the dataclasses they return mirror the wire and stay camelCase: result.exitCode, view.sandboxId, stat.modTimeMs.

SandboxClient

The sandbox entry point. Talks the gateway HTTP API.

Properties

  • volumes VolumeClient: persistent volume CRUD. Attach one at create time via create(volumes=...).

Constructors

SandboxClient()

SandboxClient(
    *,
    api_key: str,
    base_url: str = "https://api.getsolari.com",
    http: httpx.AsyncClient | None = None,
    call_timeout_ms: int | None = None,
    kind: "sandbox" | "desktop" = "sandbox",
) -> SandboxClient

Creates a client. Does not open any connection. All arguments are keyword-only.

Parameters:

  • api_key str: required.
  • base_url str: optional. Defaults to https://api.getsolari.com; pass https://api-sta.getsolari.com for staging.
  • http httpx.AsyncClient | None: reuse an existing client.
  • call_timeout_ms int | None: per-RPC timeout for handles this client creates. Default 300_000.
  • kind "sandbox" | "desktop": the flavour create() makes. Default "sandbox".

Returns: SandboxClient

Raises: SolariError if api_key is empty.

Example:

from solari_sandbox import SandboxClient

client = SandboxClient(api_key="slr_live_...")  # production gateway
A synchronous flavour exists
SyncSandboxClient takes the same arguments (minus http) and drives a private event loop. Its list_all() and list_all_snapshots() return plain lists rather than async generators, and the Sandbox handle it returns is synchronous too: no await, and with client.create() as sbx: releases the machine on exit.

Methods

create()

async create(
    *,
    template: str | None = None,
    cpu: int | None = None,
    mem_mb: int | None = None,
    disk_gb: int | None = None,
    envs: dict[str, str] | None = None,
    metadata: dict[str, str] | None = None,
    timeout_ms: int | None = None,
    idle_timeout_ms: int | None = None,
    ttl_seconds: int | None = None,
    from_snapshot: str | None = None,
    isolation: "shared" | "dedicated" | "hardened" | None = None,
    lifecycle: dict | None = None,
    idle_policy: str | dict | None = None,
    volumes: list[dict[str, str]] | None = None,
    user: str | None = None,
    cwd: str | None = None,
) -> Sandbox

Creates a sandbox and returns a live handle. The call sends an idempotency key, so retrying is safe. The control channel opens on your first call on the handle.

Parameters:

  • template str | None: "base" (the only built-in sandbox template, and the default), or a custom template id (tpl_…) from TemplateClient or promote_snapshot(). Any other name is refused with a 400 naming the valid ones. Desktop templates such as "code" or "workstation" belong to create_desktop(); there is no "python-kernel" template.
  • cpu, mem_mb, disk_gb int | None: vCPUs, memory in MiB, disk in GiB. The host clamps cpu/mem_mb to slot capacity. disk_gb (integer 1–20, default 4 GB) sets the overlay disk on a fresh create; it is grown and the guest filesystem resized at boot, so the space is usable immediately. A from_snapshot machine keeps the snapshot's disk. Mount a volume for storage that outlives the VM.
  • envs dict[str, str] | None: per-session env.
  • metadata dict[str, str] | None: opaque labels, filterable on list().
  • idle_timeout_ms int | None: the rolling idle window in milliseconds; the session auto-releases after this long with no use. A negative, fractional, boolean or non-int value raises SolariError before any request. timeout_ms is the older name for the same window; idle_timeout_ms wins when both are set.
  • ttl_seconds int | None: deprecated. A legacy idle window in seconds, used only when neither millisecond option is set, and it emits a DeprecationWarning. Use idle_timeout_ms.
  • from_snapshot str | None: boot from a snapshot instead of the template.
  • isolation str | None: "dedicated" (the default), "shared" or "hardened". See Isolation tiers for what each one changes.
  • lifecycle dict | None: idle policy with camelCase wire keys, e.g. {"onTimeout": "pause", "autoResume": True}. Also accepts parkAfterMs, parkMaxMs, hibernateAfterParkedMs and checkpointEveryMs (positive milliseconds); any other key is a 400.
  • idle_policy str | dict | None: the staged idle policy, one setting for what happens as the sandbox sits idle, e.g. "park@30s,hibernate@2m,pause@5m,delete@1d", a dict of stages, or format_idle_policy(pause="5m", delete="1d"). Offsets are measured from the last activity and must increase. park freezes the vCPUs (wakes in milliseconds, free), hibernate checkpoints to disk and frees the slot (needs park), pause snapshots and frees the slot (resume with connect()), and delete destroys it. Do not combine it with idle_timeout_ms, timeout_ms, ttl_seconds or the idle keys of lifecycle; the gateway answers 400 naming the field. The sandbox view’s idlePolicy shows the policy as applied.
  • volumes list[dict[str, str]] | None: each {"volumeId": ..., "path": ...}, mounted before the session starts. path is an absolute in-guest path on dedicated and hardened, and a short name on shared; see Isolation tiers.
  • user str | None, cwd str | None: the default unix user for commands, code and files (created at first boot with passwordless sudo if the image lacks it; a lower-case name of at most 32 characters, or root) and the default working directory (absolute, defaults to /home/<user>). Not available with isolation="shared"; an older gateway ignores them or answers 400.

The TypeScript client also takes secrets; the Python clients have no such option, so pass values with envs.

Returns: Sandbox

Raises: AuthError, PlanError, ConcurrencyLimitError, NoCapacityError, ValidationError (a bad field, named in the message), NotFoundError (unknown volume or snapshot), SnapshotNotRestorableError (from_snapshot was taken on a different template build), or GatewayError. See Errors.

Example:

sbx = await client.create(
    template="base",
    cpu=2,
    mem_mb=4096,
    envs={"NODE_ENV": "test"},
    idle_timeout_ms=10 * 60_000,
)

# release on exit, on every path
async with await client.create() as sbx:
    await sbx.commands.run("echo", args=["hi"])
Release what you create
async with (or with on a sync handle) calls kill() when the block ends. A process that exits without kill() or close() prints a one-line warning to stderr: the machine keeps running and billing until its idle timeout.

Isolation tiers

isolation picks how the sandbox is separated from your other sandboxes. Create accepts it on create() and create_desktop().

ValueWhat you getRestrictions
"dedicated" (default)Its own microVM.None.
"shared"A context inside a VM shared with your org’s other shared sandboxes (cheaper; siblings are separated by namespaces and a cgroup, not a hypervisor).Sandboxes only (refused for desktops). cpu at most 4 and mem_mb at most 2048 (the shared machine’s size); user and cwd are refused. Control-channel calls are limited to run_code(), create_code_context() and metrics(): files.*, commands.start() and pty.* fail with an ActionError whose code is NotAvailableOnSharedIsolation. commands.run() and git.* work: they go over REST (solari-sandbox 0.6.4 and later), so git credentials are not supported there and only public remotes work. download_url() / upload_url() only address /tmp, /home and /work. Manual pause() answers 400; use park(). A volume path is a short name matching [A-Za-z0-9_-]{1,64}, not an absolute path.
"hardened"Its own microVM and no outbound network at all.Refused with 409 HostCapabilityMissing on a host that does not advertise it. Volumes are not available with it: create answers 400 naming volumes.

create_desktop()

async create_desktop(
    *,
    template: str | None = None,
    cpu: int | None = None,
    mem_mb: int | None = None,
    disk_gb: int | None = None,
    envs: dict[str, str] | None = None,
    metadata: dict[str, str] | None = None,
    timeout_ms: int | None = None,
    idle_timeout_ms: int | None = None,
    ttl_seconds: int | None = None,
    from_snapshot: str | None = None,
    isolation: "dedicated" | "hardened" | None = None,
    resolution: str | None = None,
    record: bool | None = None,
    lifecycle: dict | None = None,
    idle_policy: str | dict | None = None,
    volumes: list[dict[str, str]] | None = None,
) -> Desktop

Creates a GUI session over the same /sandboxes route and returns a Desktop handle. Adds resolution and record to the sandbox options.

Parameters:

  • All of create() except user and cwd (a desktop runs as its own fixed user) and isolation="shared" (a desktop’s display is per VM), plus resolution str | None and record bool | None. Template names are the desktop ones: "default", "workstation", "office", "code", or a tpl_… id. With record=True the returned handle’s recordingUrl is the presigned playback URL.

Returns: Desktop

Example:

vm = await client.create_desktop(template="workstation", resolution="1280x720")

connect()

async connect(sandbox_id: str) -> Sandbox

Re-attaches to a running sandbox by id and returns a handle. The control channel opens on your first call on it.

Parameters:

  • sandbox_id str: the sandbox id.

Returns: Sandbox

Raises: GatewayError if the id is unknown.

Example:

sbx = await client.connect("sbx_abc123")
await sbx.commands.run("uptime")
connect() does not resume a paused sandbox
Unlike DesktopClient.connect(), this only rebuilds a handle. Call resume() on it if the sandbox is paused.

start()

async start(sandbox_id: str) -> Sandbox

Boots a stopped sandbox (one whose guest powered itself off; the host kept its disk) and returns a live handle on the fresh control URL. A cold boot, not a resume: files on disk are kept, processes and memory are gone. Idempotent: an already-running sandbox answers 200 and you get a handle to it. The handle method start() does the same for a handle you already hold. The call is not retried automatically.

Parameters:

  • sandbox_id str: the sandbox id.

Returns: Sandbox

Raises: SandboxNotStoppedError (409 NotStopped: the sandbox is in another state, use resume() for a paused one; 409 StartInProgress: poll get() until running; its state attribute is the current state), GatewayError with code StoppedDiskMissing, StoppedDiskUnsafe, GoldenMismatch, DiskPlatformMismatch, DiskShaMismatch, DiskExceedsSpec or DiskOwnerMismatch (the host cannot start this disk), HostCapabilityMissing (the pool is not armed for start; not retryable), StartFailed (500; the sandbox stays stopped with its disk, calling again is safe) or StartHostError (502, retryable), NoCapacityError, ConcurrencyLimitError, PlanError.

Example:

view = await client.get("sbx_abc123")
if view.state == "stopped":
    sbx = await client.start("sbx_abc123")

get()

async get(sandbox_id: str) -> SandboxView

Fetches a sandbox’s current record: state, kind, metadata, resources. Does not return a handle.

Parameters:

  • sandbox_id str: the sandbox id.

Returns: SandboxView

Example:

view = await client.get("sbx_abc123")
print(view.state)  # "running" | "paused" | ...

list()

async list(
    *,
    metadata: dict[str, str] | None = None,
    state: SandboxState | None = None,
    kind: SandboxKind | None = None,
    limit: int | None = None,
    cursor: str | None = None,
) -> dict

Lists sandboxes with optional filters. One page. Follow nextCursor, or use list_all().

Parameters:

  • metadata dict[str, str] | None: match on caller-set metadata.
  • state SandboxState | None: starting, running, paused, stopped, archived, releasing, gone.
  • kind SandboxKind | None: sandbox or desktop.
  • limit int | None, cursor str | None: page size and cursor.

Returns: dict, a plain dict, not a dataclass: {"sandboxes": list[SandboxView], "nextCursor": str | None}.

Example:

page = await client.list(state="running", limit=50)
print(len(page["sandboxes"]), page["nextCursor"])

list_all()

list_all(
    *,
    metadata: dict[str, str] | None = None,
    state: SandboxState | None = None,
    kind: SandboxKind | None = None,
    limit: int | None = None,
) -> AsyncIterator[SandboxView]

Auto-paginates list(), following nextCursor until exhausted. An async generator. Iterate it, do not await it.

Parameters:

  • Same filters as list(), minus cursor.

Returns: AsyncIterator[SandboxView]

Example:

async for s in client.list_all(state="running"):
    print(s.sandboxId, s.cpu, s.memMb)

kill()

async kill(sandbox_id: str) -> None

Destroys a sandbox. Idempotent: killing one that is already gone (404) is not an error.

Parameters:

  • sandbox_id str: the sandbox id.

Returns: None

Example:

await client.kill("sbx_abc123")

list_snapshots()

async list_snapshots(
    *,
    template: str | None = None,
    kind: SandboxKind | None = None,
    limit: int | None = None,
    cursor: str | None = None,
) -> list[SnapshotView]

Lists snapshots, newest first, optionally filtered by template or kind. The gateway pages the list, so this is one page, not necessarily every snapshot. Use list_snapshots_page(...) (returns {"snapshots", "nextCursor"}; pass nextCursor back as cursor) or the async generator list_all_snapshots(...) to walk them all.

Parameters:

  • template str | None, kind SandboxKind | None, limit int | None.

Returns: list[SnapshotView], the list directly, not wrapped in a dict.

Example:

for snap in await client.list_snapshots(template="base"):
    print(snap.id, snap.sizeBytes)

get_snapshot()

async get_snapshot(snapshot_id: str) -> SnapshotView

Fetches one snapshot record.

Parameters:

  • snapshot_id str: e.g. snap_abc123.

Returns: SnapshotView

Example:

snap = await client.get_snapshot("snap_abc123")
print(snap.sizeBytes, snap.parent)

delete_snapshot()

async delete_snapshot(snapshot_id: str) -> None

Deletes a snapshot.

Parameters:

  • snapshot_id str: the snapshot id.

Returns: None

Raises: GatewayError if the snapshot has live children.

Example:

await client.delete_snapshot("snap_abc123")

promote_snapshot()

async promote_snapshot(snapshot_id: str, name: str) -> dict

Promotes a snapshot to a reusable template you can pass as template on future creates.

Parameters:

  • snapshot_id str: the snapshot id.
  • name str: template name.

Returns: dict, the raw body, with templateId and name.

Example:

snap_id = await sbx.snapshot("deps-installed")
tpl = await client.promote_snapshot(snap_id, "my-stack")
fresh = await client.create(template=tpl["templateId"])

aclose()

async aclose() -> None

Closes the underlying HTTP clients, if this client owns them. Does not touch live sandboxes.

Returns: None

Example:

await client.aclose()
Volumes are live (Beta)

Volumes work on sandboxes (shared and dedicated isolation) and on desktops. Volumes are not available with hardened isolation (no network egress, and a volume is network storage): create answers 400 naming volumes; use dedicated. Attach volumes at create time with volumes=[{"volumeId": ..., "path": ...}]. The mount path is an absolute in-guest path, except on shared, where it is a short name ([A-Za-z0-9_-]{1,64}). A volume can be attached to one session at a time (a second attach is 409 VolumeAlreadyAttached). If the host pool cannot mount, the create is refused with 409 HostCapabilityMissing rather than handing back a session with nothing mounted. See Volumes for the full explanation.

volumes.create()

async volumes.create(
    *,
    name: str | None = None,
    size_mb: int | None = None,
    metadata: dict[str, str] | None = None,
) -> dict

Creates a persistent, S3-backed volume your org owns. It outlives any session.

Parameters:

  • name str | None: server default "volume".
  • size_mb int | None: advisory hint; storage is elastic, not a hard cap.
  • metadata dict[str, str] | None: opaque labels.

Returns: dict, the raw volume body, with volumeId and name. The volume calls return plain dicts, not dataclasses.

Example:

vol = await client.volumes.create(name="datasets")
sbx = await client.create(
    volumes=[{"volumeId": vol["volumeId"], "path": "/data"}],
)

volumes.list()

async volumes.list() -> list[dict]

Lists the org’s volumes, newest first.

Returns: list[dict]

Example:

for v in await client.volumes.list():
    print(v["volumeId"], v["name"])

volumes.get()

async volumes.get(volume_id: str) -> dict

Fetches one volume’s metadata.

Parameters:

  • volume_id str: e.g. vol_abc123.

Returns: dict

Example:

vol = await client.volumes.get("vol_abc123")

volumes.delete()

async volumes.delete(volume_id: str) -> None

Deletes a volume’s metadata. Idempotent.

Parameters:

  • volume_id str: the volume id.

Returns: None

Example:

await client.volumes.delete("vol_abc123")

Templates: TemplateClient and Image

A template is a reusable starting point for a machine. Describe one with the declarative Image builder, build it with TemplateClient, and pass the resulting tpl_… id as template to create(). Both classes live in solari-core and are re-exported by solari-sandbox and solari-desktop. The built-in names are base for sandboxes and default, workstation, office and code for desktops. See Templates for the concepts.

Custom templates require a paid plan
On the free plan a build is refused before anything runs, with a PlanError (402 FeatureRequiresPlan).
import os
from solari_sandbox import SandboxClient, TemplateClient, Image

key = os.environ["SOLARI_API_KEY"]
templates = TemplateClient(api_key=key, base_url="https://api.getsolari.com")
client = SandboxClient(api_key=key)

image = (
    Image.base("ubuntu:22.04")
    .kind("sandbox")                          # "sandbox" (headless) or "desktop"
    .apt_install(["ffmpeg", "poppler-utils"])
    .pip_install(["pandas", "pdfplumber"])
    .run_commands("mkdir -p /work")
    .env({"HF_HOME": "/work/.hf"})
    .workdir("/work")
)

tpl = await templates.build(image, name="media-tools")   # waits until ready
sbx = await client.create(template=tpl["templateId"])

Image

A fluent builder; every method returns the same Image. compile() is offline and returns a CompiledImage.

  • Image.base(image: str): start from a base image name. Image.from_template(name: str): start from an existing template, e.g. "workstation".
  • kind("sandbox" | "desktop"): the template kind (default "sandbox").
  • apt_install(pkgs: list[str]): installed first, in one step.
  • pip_install(pkgs), run_commands(*cmds), env(vars), workdir(dir), entrypoint(cmd: list[str]), cmd(cmd: list[str]): recipe steps that run in the order you chain them.
  • add_local_file(src, dest) / add_local_dir(src, dest): not supported yet. A recipe that uses them is refused when you build.

TemplateClient

TemplateClient(*, api_key: str, base_url: str, http: httpx.AsyncClient | None = None)
SyncTemplateClient(*, api_key: str, base_url: str)   # blocking flavour

async build(image, *, name: str, kind=None, cpu=None, mem_mb=None,
            timeout_ms=900_000, poll_interval_ms=3_000) -> dict
async build_raw(image, *, name, kind=None, cpu=None, mem_mb=None) -> dict
async list() -> list[dict]
async get(template_id: str) -> dict
async delete(template_id: str) -> None
async wait_until_ready(template_id, *, timeout_ms=900_000, poll_interval_ms=3_000) -> dict
async aclose() -> None
  • Unlike the sandbox and desktop clients, base_url is required here. image is an Image, a CompiledImage or a plain dict (the wire recipe); name is required.
  • build() starts the build (POST /templates, sent with an idempotency key) and polls until the status is ready. It raises SolariError if the status becomes failed (with the build error) or timeout_ms (default 15 minutes) passes. It returns the template view dict: templateId, name, kind, status (building, ready or failed).
  • build_raw() starts a build without waiting and returns the ids; poll with get() or wait_until_ready().
  • list() returns the built-in templates plus your team’s custom ones. delete() removes a custom template; a template still building and the built-in ones cannot be deleted. Machines already created from a deleted template keep running.
  • A sandbox template only works with create(), and a desktop template only with create_desktop(); mixing them is refused.

Sandbox

A live headless session. Construct via SandboxClient.create().

Properties

  • id str: the session id.
  • sandboxId str: alias of id.
  • controlUrl str: wss:// JSON-RPC control channel.
  • expiresAt str: ISO 8601 expiry.
  • connected bool: whether the control channel is currently open. It is informational: you never need to check it before a call.
  • commands, pty, files, volumes, git: the grouped namespaces below.

Channel

connect()

async connect() -> None

Opens the control WebSocket now. Idempotent, and optional: commands, code, files, git and the other control-channel calls open the channel on first use, and open it again if it dropped, so you can skip this call. Use it to pay the connect cost up front or to fail fast on a connection problem. Concurrent first calls share one socket; a fast-failing connect is retried a couple of times before it raises SolariConnectionError.

Returns: None

Example:

await sbx.connect()

reconnect()

async reconnect() -> None

Replaces the control socket with a fresh one and fails any call in flight on the old one. Rarely needed, because calls reconnect automatically after a drop; commands.connect() is an alias.

Returns: None

Example:

await sbx.reconnect()  # normally unnecessary: the next call reconnects itself

close()

async close() -> None

Closes the control channel locally. Does not release the remote session. Use kill() for that. Unlike the TypeScript SDK this is a coroutine and must be awaited. A later call on the handle opens a new channel. The handle is also an async context manager: async with calls kill() on exit (on a sync handle, with).

Returns: None

Example:

await sbx.close()  # session keeps running until its timeout

Commands

commands.run()

async commands.run(
    cmd: str,
    *,
    args: list[str] | None = None,
    cwd: str | None = None,
    env: dict[str, str] | None = None,
    user: str | None = None,
    timeout_ms: int | None = None,
    background: bool = False,
    on_stdout: Callable[[str], None] | None = None,
    on_stderr: Callable[[str], None] | None = None,
    cancellable: bool = False,
) -> CommandResult

Runs a command to completion and returns its exit code and captured output. Cancelling the awaiting task does not stop the process by default: closing the HTTP connection of the plain one-shot route leaves the command running in the sandbox until it finishes or reaches timeout_ms. Pass cancellable=True if the task may be cancelled. On isolation="shared" it works over REST (solari-sandbox 0.6.4 and later), except when you pass env, user or output callbacks, which need a command stream and fail with NotAvailableOnSharedIsolation (see Isolation tiers).

Parameters:

  • cmd str: the program to run; the only positional argument.
  • args list[str] | None: arguments; no shell expansion.
  • cwd, user str | None, env dict[str, str] | None: per-command context.
  • timeout_ms int | None: a client-side deadline in milliseconds. Default 600_000 (the longest the gateway accepts); 0 means no deadline. When it passes, the command is killed and the result has exitCode == -1 and timedOut == True, with the output so far.
  • background bool: return immediately with an empty result; output still reaches the callbacks.
  • on_stdout, on_stderr Callable[[str], None] | None: streamed output.
  • cancellable bool: default False. With True the command runs over the live connection, and cancelling the awaiting task sends the process SIGTERM and closes its stdin, then SIGKILL after 2 seconds if it is still running. Set timeout_ms to the longest you will wait.

Returns: CommandResult: exitCode, stdout, stderr, timedOut. A non-zero exit returns normally; it does not raise.

Example:

r = await sbx.commands.run("ls", args=["-la", "/tmp"])
print(r.exitCode, r.stdout)

# stream output as it arrives
import sys
await sbx.commands.run(
    "npm",
    args=["install"],
    cwd="/app",
    on_stdout=sys.stdout.write,
)
No shell by default
cmd is executed directly with args, not through a shell. Pipes, globs, and && will not expand. For shell syntax use run("sh", args=["-c", "…"]).
timeout_ms is a deadline, not an idle timeout
The deadline covers the whole command. A timed-out command does not raise: check result.timedOut. Pass timeout_ms=0 to wait for as long as the command runs. A timeout_ms over 600000 raises ValidationError before anything is sent (solari-sandbox 0.6.15 and later).

commands.start()

async commands.start(
    cmd: str,
    *,
    args: list[str] | None = None,
    cwd: str | None = None,
    env: dict[str, str] | None = None,
    user: str | None = None,
    timeout_ms: int | None = None,
    on_stdout: Callable[[str], None] | None = None,
    on_stderr: Callable[[str], None] | None = None,
) -> _CommandHandle

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.
  • Others as commands.run(); there is no background. timeout_ms here is optional with no default: when set and it passes, the command is killed, wait() returns -1 and the handle’s timedOut is True.

Returns: _CommandHandle: cmdId, stdin(), on_data(), wait(), kill().

Example:

proc = await sbx.commands.start("python3", args=["-u", "worker.py"])
proc.on_data(lambda stream, data: print(stream, data))
await proc.stdin("input\n")
exit_code = await proc.wait()

pty.create()

async pty.create(
    *,
    cols: int,
    rows: int,
    cmd: str | None = None,
    cwd: str | None = None,
    env: dict[str, str] | None = None,
) -> _PtyHandle

Opens a pseudo-terminal, a real TTY, so interactive programs and curses UIs behave normally.

Parameters:

  • cols, rows int: required terminal size; keyword-only.
  • cmd str | None: program to run; defaults to the guest shell.
  • cwd str | None, env dict[str, str] | None.

Returns: _PtyHandle: ptyId, write(), resize(), on_data(), kill().

Example:

pty = await sbx.pty.create(cols=80, rows=24)
pty.on_data(lambda b: print(b.decode("utf-8", "replace"), end=""))
await pty.write("ls -la\n")
await pty.kill()

Code

run_code()

async run_code(
    code: str,
    *,
    language: CodeLanguage | None = None,
    context_id: str | None = None,
    on_stdout: Callable[[str], None] | None = None,
    on_stderr: Callable[[str], None] | None = None,
) -> RunCodeResult

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

Python is the only supported language
The guest kernel runs Python only. The CodeLanguage type also lists javascript, typescript, bash and r, but any of those fails with unsupported language (only python). To run another language, start its interpreter with commands.run(), for example commands.run("node", args=["-e", "…"]) or commands.run("sh", args=["-c", "…"]).

Parameters:

  • code str: source to execute.
  • language CodeLanguage | None: only python works (also the default); the other values in the type are refused by the guest.
  • context_id str | None: kernel context to reuse; see create_code_context().
  • on_stdout, on_stderr Callable[[str], None] | None: invoked per matching result item.

Returns: RunCodeResult: results, charts, error. A runtime error in the code lands in error; it does not raise.

Example:

r = await sbx.run_code("""
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.title("demo")
plt.show()
""")

png = next((i.png for i in r.results if i.png), None)  # base64 PNG, always present

# r.charts can be empty (it is on the default "base" template): check first
if r.charts:
    print(r.charts[0].type)   # "line"
    print(r.charts[0].title)  # "demo"
Structured charts may be empty
Every matplotlib figure comes back as a base64 PNG on results[i].png. The structured charts list is extracted by the guest and is empty on the default base template, so check it before indexing r.charts[0] (an IndexError otherwise) and fall back to the PNG.
on_stdout fires on completion, not live
Unlike commands.run(), these callbacks are invoked while the final reply is parsed. They are a convenience for splitting results by stream, not a live feed.

create_code_context()

async create_code_context(language: CodeLanguage = "python") -> str

Creates a fresh kernel context so state persists across run_code() calls, like a REPL.

Parameters:

  • language CodeLanguage: default "python".

Returns: str, the context id.

Example:

ctx = await sbx.create_code_context("python")
await sbx.run_code("x = 41", context_id=ctx)
r = await sbx.run_code("print(x + 1)", context_id=ctx)  # 42

Files

files.* moves bytes over the control channel. For large files prefer download_url() / upload_url(). files.* is refused on isolation="shared"; there, use the signed URLs for paths under /tmp, /home and /work (see Isolation tiers).

File size limits

  • Single call (files.write): the whole file travels as one message, so write() refuses a file over 32 MiB before sending anything, with a SolariError (“file too large for a single call”). The control channel stays up. Use files.upload() or the signed URLs for larger files.
  • Chunked (files.upload, read, download): moved in chunks, so size is not limited by the control channel.
  • Signed upload (upload_url()): the body is streamed into the sandbox and capped at 2 GiB per file; a larger body is refused with 413 Payload Too Large. Use it for anything over 32 MiB.
  • files.download() fetches the file in 1 MiB chunks and refuses a file larger than 2 GiB.

files.read() / files.read_text()

async files.read(path: str) -> bytes
async files.read_text(path: str) -> str

Reads a file’s bytes, or its UTF-8 decoded text.

Parameters:

  • path str: absolute in-guest path.

Returns: bytes / str

Example:

text = await sbx.files.read_text("/etc/hostname")
data = await sbx.files.read("/tmp/out.bin")

files.write()

async files.write(path: str, data: bytes | str, mode: int | None = None) -> None

Writes a file, creating or truncating it.

Parameters:

  • path str: absolute in-guest path.
  • data bytes | str: content; str is UTF-8 encoded.
  • mode int | None: permission bits, e.g. 0o755.

Returns: None

Example:

await sbx.files.write("/app/run.sh", "#!/bin/sh\necho hi\n", 0o755)

files.list()

async files.list(path: str) -> list[FsEntry]

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

Parameters:

  • path str: directory path.

Returns: list[FsEntry], each with name, dir, size.

Example:

for e in await sbx.files.list("/app"):
    print("d" if e.dir else "-", e.name, e.size)

files.stat()

async files.stat(path: str) -> FsStat

Returns one entry’s metadata.

Parameters:

  • path str: file or directory path.

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

Example:

st = await sbx.files.stat("/app/run.sh")
print(st.size, oct(st.mode), st.modTimeMs)

files.rename()

async files.rename(frm: str, to: str) -> None

Renames or moves a path. The first parameter is spelled frm, because from is a Python keyword.

Parameters:

  • frm, to str: source and destination paths.

Returns: None

Example:

await sbx.files.rename("/tmp/a.txt", "/tmp/b.txt")

files.remove()

async files.remove(path: str, recursive: bool = False) -> None

Deletes a file or directory.

Parameters:

  • path str: path to delete.
  • recursive bool: default False; required for non-empty directories.

Returns: None

Example:

await sbx.files.remove("/tmp/build", True)

files.mkdir()

async files.mkdir(path: str) -> None

Creates a directory.

Parameters:

  • path str: directory to create.

Returns: None

Example:

await sbx.files.mkdir("/app/data")
async files.search(path: str, query: str, max_results: int | None = None) -> list[FsSearchMatch]

Recursively greps for query under path.

Parameters:

  • path str: root to search.
  • query str: the pattern.
  • max_results int | None: cap on matches.

Returns: list[FsSearchMatch], each with path, line, text.

Example:

for m in await sbx.files.search("/app", "TODO", 20):
    print(f"{m.path}:{m.line}: {m.text}")

files.watch()

async files.watch(
    path: str,
    cb: Callable[[FsWatchEvent], None],
    recursive: bool = False,
) -> Callable[[], Awaitable[None]]

Watches a path for changes. Returns an async unwatch callable. Await it to stop.

Parameters:

  • path str: path to watch.
  • cb Callable[[FsWatchEvent], None]: invoked per event with type (the kind of change: create, write, remove, rename or chmod) and path.
  • recursive bool: default False.

Returns: Callable[[], Awaitable[None]]: the unwatch function.

Example:

unwatch = await sbx.files.watch(
    "/app",
    lambda ev: print(ev.type, ev.path),
    True,
)

await unwatch()

files.upload() / files.download()

async files.upload(path: str, data: bytes | str) -> None
async files.download(path: str) -> bytes

Transfer a file over the control channel. Same bytes as write() / read().

Parameters:

  • path str: in-guest path.
  • data bytes | str: upload content.

Returns: None / bytes

Example:

await sbx.files.upload("/app/data.csv", csv_string)
out = await sbx.files.download("/app/result.json")

download_url()

async download_url(path: str) -> dict

Signed, time-limited URL to download an in-guest file directly over HTTP, bypassing the control channel. Use for files too big for files.read().

Parameters:

  • path str: in-guest file path.

Returns: dict, with url and usually expiresAt.

Raises: RuntimeError if the handle was not created by a client.

Example:

import httpx

dl = await sbx.download_url("/app/big.tar.gz")
async with httpx.AsyncClient() as http:
    res = await http.get(dl["url"])

upload_url()

async upload_url(path: str | None = None) -> dict

Signed, time-limited URL to upload a file into the guest directly over HTTP. The body is streamed and capped at 2 GiB; see file size limits.

Parameters:

  • path str | None: destination path; optional, some backends return a prefix.

Returns: dict, with url and usually expiresAt.

Raises: RuntimeError if the handle was not created by a client.

Example:

up = await sbx.upload_url("/app/big.zip")
async with httpx.AsyncClient() as http:
    await http.put(up["url"], content=data)

Git

Every git.* call is a non-shell git invocation in the guest, so there is no injection surface. Requires git on PATH, which the base template ships.

git.clone()

async git.clone(
    url: str,
    *,
    path: str | None = None,
    branch: str | None = None,
    depth: int | None = None,
    username: str | None = None,
    password: str | None = None,
    cwd: str | None = None,
) -> None

Clones a repository into the guest.

Parameters:

  • url str: remote URL.
  • path str | None: destination dir.
  • branch str | None: branch or tag.
  • depth int | None: shallow-clone depth.
  • username, password str | None: basic auth for private HTTPS remotes; injected into the URL for this invocation only.
  • cwd str | None: working directory.

Returns: None

Raises: RuntimeError with git’s stderr on a non-zero exit.

Example:

await sbx.git.clone(
    "https://github.com/org/repo.git",
    path="/app/repo",
    branch="main",
    depth=1,
)

git.status()

async git.status(cwd: str | None = None) -> GitStatus

Parsed working-tree status.

Parameters:

  • cwd str | None: repository directory.

Returns: GitStatus

Raises: RuntimeError on a non-zero exit.

Example:

st = await sbx.git.status("/app/repo")
print(st.branch, st.clean, st.ahead, st.modified)

git.add()

async git.add(paths: list[str], cwd: str | None = None) -> None

Stages paths. An empty list is a no-op.

Parameters:

  • paths list[str]: use ["."] for everything.
  • cwd str | None: repository directory.

Returns: None

Example:

await sbx.git.add(["."], "/app/repo")

git.commit()

async git.commit(
    message: str,
    *,
    cwd: str | None = None,
    author: str | None = None,
    email: str | None = None,
    all: bool = False,
) -> dict

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

Parameters:

  • message str: commit message.
  • cwd str | None: repository directory.
  • author, email str | None: identity, scoped to this commit only.
  • all bool: stage all tracked modifications first.

Returns: dict: {"hash": str}.

Raises: RuntimeError on a non-zero exit.

Example:

c = await sbx.git.commit(
    "add feature",
    cwd="/app/repo",
    author="CI Bot",
    email="ci@example.com",
)
print(c["hash"])

git.push() / git.pull()

async git.push(
    *,
    cwd: str | None = None,
    remote: str | None = None,
    branch: str | None = None,
    username: str | None = None,
    password: str | None = None,
) -> None
async git.pull(...)  # identical signature

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.6.4 or later.

Parameters:

  • cwd str | None: repository directory.
  • remote str | None: default "origin".
  • branch str | None: defaults to the current branch’s upstream.
  • username, password str | None: one-off HTTPS auth.

Returns: None

Raises: RuntimeError on a non-zero exit.

Example:

import os

await sbx.git.push(
    cwd="/app/repo",
    username="x-access-token",
    password=os.environ["GITHUB_TOKEN"],
)

git.checkout()

async git.checkout(ref: str, *, cwd: str | None = None, create: bool = False) -> None

Checks out an existing ref, or creates a branch.

Parameters:

  • ref str: branch, tag, or commit.
  • cwd str | None: repository directory.
  • create bool: create the branch (-b).

Returns: None

Example:

await sbx.git.checkout("feature/x", cwd="/app/repo", create=True)

git.branches()

async git.branches(cwd: str | None = None) -> list[GitBranch]

Lists local branches.

Parameters:

  • cwd str | None: repository directory.

Returns: list[GitBranch], each with name, commit, current.

Example:

for b in await sbx.git.branches("/app/repo"):
    print("*" if b.current else " ", b.name, b.commit)

git.log()

async git.log(*, cwd: str | None = None, max_count: int | None = None) -> list[GitCommit]

Recent commits, newest first.

Parameters:

  • cwd str | None: repository directory.
  • max_count int | None: cap the number returned.

Returns: list[GitCommit], each with hash, author, email, date, message.

Example:

commits = await sbx.git.log(cwd="/app/repo", max_count=10)

Lifecycle & admin

These need a client-created handle
metrics(), snapshot(), revert(), pause(), resume(), start(), park(), unpark(), set_timeout(), download_url(), upload_url(), and preview_url() reach the gateway through hooks the client installs. On a hand-built handle they raise RuntimeError.

env()

async env(vars: dict[str, str]) -> None

Injects or replaces per-session environment variables in the guest.

Parameters:

  • vars dict[str, str]: the variables to set.

Returns: None

Example:

await sbx.env({"API_URL": "https://staging.example.com"})

volumes.mount()

async volumes.mount(vol_id: str, path: str) -> None

Not available on a running sandbox: it raises at once.

mount() is not supported; mount at create time
A volume is mounted host-side when the sandbox is created or resumed, because the guest cannot fetch the storage credentials itself. volumes.mount() raises a SolariError saying volumes.mount() is not supported on a running sandbox (solari-core 0.7.4 and later; before that it failed with volume.mount: bucket is required). Pass create(volumes=[{"volumeId": ..., "path": ...}]) instead.

Parameters:

  • vol_id str: volume id.
  • path str: absolute in-guest mount point.

Returns: None

Example:

# Not working today; use create(volumes=...) instead:
sbx = await client.create(volumes=[{"volumeId": "vol_abc123", "path": "/data"}])

metrics()

async metrics() -> MetricsResult

Live resource usage for this session.

Returns: MetricsResult: cpuPct, memBytes, memTotalBytes, diskBytes.

Raises: RuntimeError if the handle was not created by a client.

Example:

m = await sbx.metrics()
print(m.cpuPct, m.memBytes / m.memTotalBytes)

snapshot()

async snapshot(name: str | None = None) -> str

Checkpoints this running session and returns the snapshot id. The session keeps running.

Parameters:

  • name str | None: optional label.

Returns: str, the snapshot id.

Raises: RuntimeError if the handle was not created by a client.

Example:

await sbx.commands.run("pip", args=["install", "pandas"])
snap_id = await sbx.snapshot("deps-installed")

# boot future sandboxes from it
fast = await client.create(from_snapshot=snap_id)

revert()

async revert(snapshot_id: str) -> None

Restores this session in place from a snapshot. The session id stays stable.

Parameters:

  • snapshot_id str: snapshot to restore.

Returns: None

Raises: RuntimeError if the handle was not created by a client.

Example:

await sbx.revert(snap_id)  # back to a known-good state

pause()

async pause() -> None

Saves full RAM + disk state and closes the control channel. Resume later with resume(). Not available on isolation="shared": the gateway answers 400 (a manual pause would hibernate the whole shared VM and destroy every sibling). Use park() there.

Returns: None

Raises: RuntimeError if the handle was not created by a client.

Example:

await sbx.pause()   # stops billing for compute
await sbx.resume()  # full state restored

resume()

async resume() -> None

Resumes a paused session and re-points the control channel at the fresh slot.

Returns: None

Raises: RuntimeError if the handle was not created by a client.

Example:

await sbx.resume()
r = await sbx.commands.run("cat", args=["/tmp/state"])

park()

async park() -> None

Parks (deschedules) the session: the guest’s vCPUs freeze while its RAM stays resident on the same host. Takes milliseconds to park and to wake. Unlike pause(), it does not close the control channel or free the slot: the session keeps its host, ports and routing. You do not need to call unpark() first, because commands, code, the control and stream channels, port preview and signed file reads wake a parked session on their own. Use it around a long LLM or tool call to stop paying for vCPU you are not using. For hands-off behaviour set lifecycle={"parkAfterMs": ...} or an idle_policy at create time and the gateway parks on an idle timer.

Returns: None

Raises: RuntimeError if the handle was not created by a client.

Example:

await sbx.park()                       # while the agent thinks
plan = await call_llm(...)
r = await sbx.commands.run("sh", args=["-c", plan])   # wakes it automatically

unpark()

async unpark() -> None

Wakes a parked session explicitly. Rarely needed, since every normal request unparks on touch; it lets you pay the millisecond wake up front.

Returns: None

Raises: RuntimeError if the handle was not created by a client.

Example:

await sbx.unpark()

start()

async start() -> None

Boots a stopped sandbox (one that powered itself off) from its kept disk and re-points the control channel at the fresh slot. This is a cold boot: files are kept, running processes and memory are not. Use resume() for a paused sandbox. Idempotent: starting a running sandbox succeeds. Sandboxes only: a Desktop handle has no start hook. The same call from the client, given just an id, is start(sandbox_id).

Returns: None

Raises: RuntimeError if the handle was not created by a client; SandboxNotStoppedError on 409 NotStopped / StartInProgress; otherwise the same errors as client.start(): 409 HostCapabilityMissing or a host disk code, 429, 502/503 (retryable), or 500 StartFailed (the sandbox stays stopped).

Example:

await sbx.start()
r = await sbx.commands.run("ls", args=["/work"])

set_timeout()

async set_timeout(timeout_ms: int) -> dict

Extends the rolling idle window. Every use of the session resets it.

Parameters:

  • timeout_ms int: new idle window in ms.

Returns: dict, the raw body, carrying expiresAt.

Raises: RuntimeError if the handle was not created by a client.

Example:

r = await sbx.set_timeout(30 * 60_000)  # 30 min
print(r["expiresAt"])

preview_url()

async preview_url(port: int) -> dict

Resolves a public URL for a port listening inside the guest, e.g. a dev server.

Parameters:

  • port int: the in-guest port.

Returns: dict, with url, and token when the gateway signs one.

Raises: RuntimeError if the handle was not created by a client.

Example:

await sbx.commands.start("python3", args=["-m", "http.server", "3000"])
p = await sbx.preview_url(3000)
print(p["url"])

kill()

async kill() -> None

Destroys the remote session and closes the channel. Idempotent.

Returns: None

Example:

try:
    await sbx.commands.run("./build.sh")
finally:
    await sbx.kill()

Types

CreateSandboxResponse

  • sandboxId str, kind SandboxKind.
  • controlUrl str, expiresAt str.
  • streamUrl str | None: present only when kind == "desktop".
  • recordingUrl str | None: presigned playback URL, for a desktop created with record=True.
  • template str | None, golden GoldenInfo | None: the template and the exact image build (imageKey, rootfsSha256, kernelSha256, chVersion) it runs on.

SandboxView

  • sandboxId str, kind SandboxKind, state SandboxState.
  • metadata dict, expiresAt str.
  • cpu int, memMb int, diskGb int.
  • recordingUrl str | None, template str | None, golden GoldenInfo | None.
  • stoppedAtMs, stoppedExit int | None: set when state == "stopped" (when the guest powered off, in epoch ms, and its exit status).

CommandResult

  • exitCode int, stdout str, stderr str, timedOut bool: True when the timeout_ms deadline cut the command off (then exitCode is -1).

_CommandHandle

Returned by commands.start(); not constructed directly.

  • cmdId str: the command id.
  • on_data(cb): subscribe to (stream, data) chunks. Synchronous. Chunks that arrive before the first subscriber are buffered and replayed, so early output is never lost.
  • await stdin(data): write to the command’s stdin.
  • await wait(): int, the exit code (-1 after a timeout_ms kill; then timedOut is True). Raises if the control channel drops before the process exits.
  • await kill(signal=None): signal the process.

_PtyHandle

  • ptyId str: the PTY id.
  • on_data(cb): subscribe to raw bytes. Synchronous.
  • await write(data), await resize(cols, rows), await kill().

RunCodeResult / CodeResultItem

  • results list[CodeResultItem]: each has type (stdout/stderr/result) plus any of text, png, jpeg, svg, html, latex, json, markdown, chart.
  • charts list[Chart]: every chart across results, flattened.
  • error Any: the raw error object when the code raised.

Chart

  • type ChartType: line, scatter, bar, pie, box_and_whisker, composite, unknown.
  • title, xLabel, yLabel str | None.
  • x, y ChartAxis | None: label, ticks, scale.
  • elements list | None: per-type data (points, bars, slices).

FsEntry / FsStat / FsSearchMatch / FsWatchEvent

  • FsEntry: name str, dir bool, size int.
  • FsStat: FsEntry’s fields plus mode int (permission bits) and modTimeMs int (unix millis).
  • FsSearchMatch: path str, line int, text str.
  • FsWatchEvent: type str, path str.

GitStatus / GitBranch / GitCommit

  • GitStatus.branch str: empty on a detached HEAD.
  • GitStatus.detached, clean bool.
  • GitStatus.ahead, behind int: relative to the upstream, when set.
  • GitStatus.staged, modified, untracked list[str].
  • GitBranch: name, commit str, current bool.
  • GitCommit: hash, author, email, date, message str.

MetricsResult

  • cpuPct float, memBytes int, memTotalBytes int, diskBytes int.

SnapshotView

  • id str, parent str | None, name str | None.
  • sizeBytes int, createdAt str, kind SandboxKind, template str.

Errors

All extend SolariError. Every gateway error (everything except ActionError, SolariTimeoutError and SolariConnectionError) also carries status, code, body, retryable (the gateway’s hint), request_id (the x-request-id; quote it in a support request), error_type (on a 429: "rate_limited" or "quota_exceeded") and retry_after_ms (set only on retryable errors). Errors are picked by the gateway’s code first, then by status.

ClassStatusMeaning
ValidationError400The request was refused as invalid (a bad field, a limit exceeded); code and the message say which.
AuthError401API key missing, malformed, or rejected.
PlanError402, 403The plan does not allow this: FeatureRequiresPlan, InsufficientCredit (402) or NotEntitled (403). status is what the gateway sent.
NotFoundError404The sandbox, desktop, snapshot, template or volume does not exist (or is not yours).
SandboxNotStoppedError409From start(): NotStopped (another state; use resume() for a paused sandbox) or StartInProgress (poll until running). Carries state.
SnapshotNotRestorableError409A restore (create from a snapshot, resume, revert) the platform knows cannot succeed. Never retryable. reason is golden_mismatch when the snapshot was taken on a different template build (see snapshot_image_key and host_image_key): take a fresh snapshot from a new sandbox.
ConcurrencyLimitError429Your org is at its cap of live sessions (ConcurrencyLimitExceeded). Not retried. Other 429s (for example TooManyExecutions) are plain GatewayError.
NoCapacityError503NoCapacity / StartTimeout: no host available right now. Other 503s (such as SandboxUnavailable) are plain GatewayError.
GatewayErrorotherAny other non-2xx response.
ActionErrorNoneA control-channel RPC returned ok: false. Carries method and code (for example NotAvailableOnSharedIsolation).
SolariTimeoutErrorNoneNo reply within the per-call timeout. Carries method, timeoutMs.
SolariConnectionErrorNoneThe control channel could not be opened or was closed, or an HTTP request failed at the transport level.
TimeoutError and ConnectionError are aliases
The old names TimeoutError and ConnectionError still import (from solari_sandbox import TimeoutError) but shadow the Python builtins, so they are no longer in the star-import list. Prefer SolariTimeoutError and SolariConnectionError.
from solari_sandbox import (
    ConcurrencyLimitError, NoCapacityError, NotFoundError, ValidationError,
)

try:
    sbx = await client.create(template="base")
except NoCapacityError:
    await retry_later()
except ConcurrencyLimitError:
    await wait_for_slot()
except ValidationError as e:
    print(e.code, e.message)      # which field was refused
except NotFoundError:
    ...                           # unknown volume or snapshot id