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-sandboxSandbox method below is inherited from SessionHandle and is also available on Desktop. A Desktop is a Sandbox plus the GUI surface.Contents
SandboxClient: SandboxClient(), create(), create_desktop(), connect(), start(), get(), list(), list_all(), kill(), list_snapshots(), get_snapshot(), delete_snapshot(), isolation tiers, promote_snapshot(), aclose(), volumes.create(), volumes.list(), volumes.get(), volumes.delete()- Templates:
TemplateClient,Image Sandbox: connect(), reconnect(), close(), commands.run(), commands.start(), pty.create(), run_code(), create_code_context(), files.*, file size limits, git.*, env(), download_url(), upload_url(), volumes.mount(), metrics(), snapshot(), revert(), pause(), resume(), start(), park(), unpark(), set_timeout(), preview_url(), kill()- Types:
CreateSandboxResponse,SandboxView,CommandResult,_CommandHandle,_PtyHandle,RunCodeResult,CodeResultItem,Chart,FsEntry,FsStat,FsSearchMatch,FsWatchEvent,GitStatus,GitBranch,GitCommit,MetricsResult,SnapshotView, errors
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
volumesVolumeClient: persistent volume CRUD. Attach one at create time viacreate(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",
) -> SandboxClientCreates a client. Does not open any connection. All arguments are keyword-only.
Parameters:
api_keystr: required.base_urlstr: optional. Defaults tohttps://api.getsolari.com; passhttps://api-sta.getsolari.comfor staging.httphttpx.AsyncClient | None: reuse an existing client.call_timeout_msint | None: per-RPC timeout for handles this client creates. Default300_000.kind"sandbox" | "desktop": the flavourcreate()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 gatewaySyncSandboxClient 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,
) -> SandboxCreates 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:
templatestr | 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 a400naming the valid ones. Desktop templates such as"code"or"workstation"belong to create_desktop(); there is no"python-kernel"template.cpu,mem_mb,disk_gbint | None: vCPUs, memory in MiB, disk in GiB. The host clampscpu/mem_mbto 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. Afrom_snapshotmachine keeps the snapshot's disk. Mount a volume for storage that outlives the VM.envsdict[str, str] | None: per-session env.metadatadict[str, str] | None: opaque labels, filterable on list().idle_timeout_msint | 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 raisesSolariErrorbefore any request.timeout_msis the older name for the same window;idle_timeout_mswins when both are set.ttl_secondsint | None: deprecated. A legacy idle window in seconds, used only when neither millisecond option is set, and it emits aDeprecationWarning. Useidle_timeout_ms.from_snapshotstr | None: boot from a snapshot instead of the template.isolationstr | None:"dedicated"(the default),"shared"or"hardened". See Isolation tiers for what each one changes.lifecycledict | None: idle policy with camelCase wire keys, e.g.{"onTimeout": "pause", "autoResume": True}. Also acceptsparkAfterMs,parkMaxMs,hibernateAfterParkedMsandcheckpointEveryMs(positive milliseconds); any other key is a400.idle_policystr | 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, orformat_idle_policy(pause="5m", delete="1d"). Offsets are measured from the last activity and must increase.parkfreezes the vCPUs (wakes in milliseconds, free),hibernatecheckpoints to disk and frees the slot (needspark),pausesnapshots and frees the slot (resume with connect()), anddeletedestroys it. Do not combine it withidle_timeout_ms,timeout_ms,ttl_secondsor the idle keys oflifecycle; the gateway answers400naming the field. The sandbox view’sidlePolicyshows the policy as applied.volumeslist[dict[str, str]] | None: each{"volumeId": ..., "path": ...}, mounted before the session starts.pathis an absolute in-guest path ondedicatedandhardened, and a short name onshared; see Isolation tiers.userstr | None,cwdstr | 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, orroot) and the default working directory (absolute, defaults to/home/<user>). Not available withisolation="shared"; an older gateway ignores them or answers400.
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"])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().
| Value | What you get | Restrictions |
|---|---|---|
"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,
) -> DesktopCreates 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
userandcwd(a desktop runs as its own fixed user) andisolation="shared"(a desktop’s display is per VM), plusresolutionstr | None andrecordbool | None. Template names are the desktop ones:"default","workstation","office","code", or atpl_…id. Withrecord=Truethe returned handle’srecordingUrlis the presigned playback URL.
Returns: Desktop
Example:
vm = await client.create_desktop(template="workstation", resolution="1280x720")connect()
async connect(sandbox_id: str) -> SandboxRe-attaches to a running sandbox by id and returns a handle. The control channel opens on your first call on it.
Parameters:
sandbox_idstr: the sandbox id.
Returns: Sandbox
Raises: GatewayError if the id is unknown.
Example:
sbx = await client.connect("sbx_abc123")
await sbx.commands.run("uptime")DesktopClient.connect(), this only rebuilds a handle. Call resume() on it if the sandbox is paused.start()
async start(sandbox_id: str) -> SandboxBoots 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_idstr: 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) -> SandboxViewFetches a sandbox’s current record: state, kind, metadata, resources. Does not return a handle.
Parameters:
sandbox_idstr: 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,
) -> dictLists sandboxes with optional filters. One page. Follow nextCursor, or use list_all().
Parameters:
metadatadict[str, str] | None: match on caller-set metadata.stateSandboxState | None:starting,running,paused,stopped,archived,releasing,gone.kindSandboxKind | None:sandboxordesktop.limitint | None,cursorstr | 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(), minuscursor.
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) -> NoneDestroys a sandbox. Idempotent: killing one that is already gone (404) is not an error.
Parameters:
sandbox_idstr: 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:
templatestr | None,kindSandboxKind | None,limitint | 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) -> SnapshotViewFetches one snapshot record.
Parameters:
snapshot_idstr: 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) -> NoneDeletes a snapshot.
Parameters:
snapshot_idstr: 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) -> dictPromotes a snapshot to a reusable template you can pass as template on future creates.
Parameters:
snapshot_idstr: the snapshot id.namestr: 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() -> NoneCloses the underlying HTTP clients, if this client owns them. Does not touch live sandboxes.
Returns: None
Example:
await client.aclose()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,
) -> dictCreates a persistent, S3-backed volume your org owns. It outlives any session.
Parameters:
namestr | None: server default"volume".size_mbint | None: advisory hint; storage is elastic, not a hard cap.metadatadict[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) -> dictFetches one volume’s metadata.
Parameters:
volume_idstr: e.g.vol_abc123.
Returns: dict
Example:
vol = await client.volumes.get("vol_abc123")volumes.delete()
async volumes.delete(volume_id: str) -> NoneDeletes a volume’s metadata. Idempotent.
Parameters:
volume_idstr: 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.
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_urlis required here.imageis anImage, aCompiledImageor a plain dict (the wire recipe);nameis required. build()starts the build (POST /templates, sent with an idempotency key) and polls until the status isready. It raisesSolariErrorif the status becomesfailed(with the build error) ortimeout_ms(default 15 minutes) passes. It returns the template view dict:templateId,name,kind,status(building,readyorfailed).build_raw()starts a build without waiting and returns the ids; poll withget()orwait_until_ready().list()returns the built-in templates plus your team’s custom ones.delete()removes a custom template; a template stillbuildingand the built-in ones cannot be deleted. Machines already created from a deleted template keep running.- A
sandboxtemplate only works with create(), and adesktoptemplate only with create_desktop(); mixing them is refused.
Sandbox
A live headless session. Construct via SandboxClient.create().
Properties
idstr: the session id.sandboxIdstr: alias ofid.controlUrlstr:wss://JSON-RPC control channel.expiresAtstr: ISO 8601 expiry.connectedbool: 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() -> NoneOpens 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() -> NoneReplaces 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 itselfclose()
async close() -> NoneCloses 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 timeoutCommands
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,
) -> CommandResultRuns 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:
cmdstr: the program to run; the only positional argument.argslist[str] | None: arguments; no shell expansion.cwd,userstr | None,envdict[str, str] | None: per-command context.timeout_msint | None: a client-side deadline in milliseconds. Default600_000(the longest the gateway accepts);0means no deadline. When it passes, the command is killed and the result hasexitCode == -1andtimedOut == True, with the output so far.backgroundbool: return immediately with an empty result; output still reaches the callbacks.on_stdout,on_stderrCallable[[str], None] | None: streamed output.cancellablebool: defaultFalse. WithTruethe 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. Settimeout_msto 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,
)cmd is executed directly with args, not through a shell. Pipes, globs, and && will not expand. For shell syntax use run("sh", args=["-c", "…"]).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,
) -> _CommandHandleStarts a command and returns a handle immediately, without waiting for exit. Use it for interactive or long-running processes.
Parameters:
cmdstr: the program to run.- Others as commands.run(); there is no
background.timeout_mshere is optional with no default: when set and it passes, the command is killed,wait()returns-1and the handle’stimedOutisTrue.
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,
) -> _PtyHandleOpens a pseudo-terminal, a real TTY, so interactive programs and curses UIs behave normally.
Parameters:
cols,rowsint: required terminal size; keyword-only.cmdstr | None: program to run; defaults to the guest shell.cwdstr | None,envdict[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,
) -> RunCodeResultRuns code in a stateful kernel. Rich outputs (PNG, HTML, JSON, structured charts) come back as results items.
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:
codestr: source to execute.languageCodeLanguage | None: onlypythonworks (also the default); the other values in the type are refused by the guest.context_idstr | None: kernel context to reuse; see create_code_context().on_stdout,on_stderrCallable[[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"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.results by stream, not a live feed.create_code_context()
async create_code_context(language: CodeLanguage = "python") -> strCreates a fresh kernel context so state persists across run_code() calls, like a REPL.
Parameters:
languageCodeLanguage: 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) # 42Files
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, sowrite()refuses a file over 32 MiB before sending anything, with aSolariError(“file too large for a single call”). The control channel stays up. Usefiles.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) -> strReads a file’s bytes, or its UTF-8 decoded text.
Parameters:
pathstr: 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) -> NoneWrites a file, creating or truncating it.
Parameters:
pathstr: absolute in-guest path.databytes | str: content;stris UTF-8 encoded.modeint | 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:
pathstr: 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) -> FsStatReturns one entry’s metadata.
Parameters:
pathstr: 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) -> NoneRenames or moves a path. The first parameter is spelled frm, because from is a Python keyword.
Parameters:
frm,tostr: 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) -> NoneDeletes a file or directory.
Parameters:
pathstr: path to delete.recursivebool: defaultFalse; required for non-empty directories.
Returns: None
Example:
await sbx.files.remove("/tmp/build", True)files.mkdir()
async files.mkdir(path: str) -> NoneCreates a directory.
Parameters:
pathstr: directory to create.
Returns: None
Example:
await sbx.files.mkdir("/app/data")files.search()
async files.search(path: str, query: str, max_results: int | None = None) -> list[FsSearchMatch]Recursively greps for query under path.
Parameters:
pathstr: root to search.querystr: the pattern.max_resultsint | 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:
pathstr: path to watch.cbCallable[[FsWatchEvent], None]: invoked per event withtype(the kind of change:create,write,remove,renameorchmod) andpath.recursivebool: defaultFalse.
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) -> bytesTransfer a file over the control channel. Same bytes as write() / read().
Parameters:
pathstr: in-guest path.databytes | 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) -> dictSigned, 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:
pathstr: 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) -> dictSigned, 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:
pathstr | 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,
) -> NoneClones a repository into the guest.
Parameters:
urlstr: remote URL.pathstr | None: destination dir.branchstr | None: branch or tag.depthint | None: shallow-clone depth.username,passwordstr | None: basic auth for private HTTPS remotes; injected into the URL for this invocation only.cwdstr | 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) -> GitStatusParsed working-tree status.
Parameters:
cwdstr | 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) -> NoneStages paths. An empty list is a no-op.
Parameters:
pathslist[str]: use["."]for everything.cwdstr | 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,
) -> dictCommits staged changes and returns the new hash. Set author/email, because an ephemeral session has no git identity.
Parameters:
messagestr: commit message.cwdstr | None: repository directory.author,emailstr | None: identity, scoped to this commit only.allbool: 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 signaturePushes 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:
cwdstr | None: repository directory.remotestr | None: default"origin".branchstr | None: defaults to the current branch’s upstream.username,passwordstr | 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) -> NoneChecks out an existing ref, or creates a branch.
Parameters:
refstr: branch, tag, or commit.cwdstr | None: repository directory.createbool: 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:
cwdstr | 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:
cwdstr | None: repository directory.max_countint | 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
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]) -> NoneInjects or replaces per-session environment variables in the guest.
Parameters:
varsdict[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) -> NoneNot available on a running sandbox: it raises at once.
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_idstr: volume id.pathstr: 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() -> MetricsResultLive 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) -> strCheckpoints this running session and returns the snapshot id. The session keeps running.
Parameters:
namestr | 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) -> NoneRestores this session in place from a snapshot. The session id stays stable.
Parameters:
snapshot_idstr: 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 statepause()
async pause() -> NoneSaves 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 restoredresume()
async resume() -> NoneResumes 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() -> NoneParks (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 automaticallyunpark()
async unpark() -> NoneWakes 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() -> NoneBoots 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) -> dictExtends the rolling idle window. Every use of the session resets it.
Parameters:
timeout_msint: 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) -> dictResolves a public URL for a port listening inside the guest, e.g. a dev server.
Parameters:
portint: 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() -> NoneDestroys the remote session and closes the channel. Idempotent.
Returns: None
Example:
try:
await sbx.commands.run("./build.sh")
finally:
await sbx.kill()Types
CreateSandboxResponse
sandboxIdstr,kindSandboxKind.controlUrlstr,expiresAtstr.streamUrlstr | None: present only whenkind == "desktop".recordingUrlstr | None: presigned playback URL, for a desktop created withrecord=True.templatestr | None,goldenGoldenInfo | None: the template and the exact image build (imageKey,rootfsSha256,kernelSha256,chVersion) it runs on.
SandboxView
sandboxIdstr,kindSandboxKind,stateSandboxState.metadatadict,expiresAtstr.cpuint,memMbint,diskGbint.recordingUrlstr | None,templatestr | None,goldenGoldenInfo | None.stoppedAtMs,stoppedExitint | None: set whenstate == "stopped"(when the guest powered off, in epoch ms, and its exit status).
CommandResult
exitCodeint,stdoutstr,stderrstr,timedOutbool:Truewhen thetimeout_msdeadline cut the command off (thenexitCodeis-1).
_CommandHandle
Returned by commands.start(); not constructed directly.
cmdIdstr: 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 (-1after atimeout_mskill; thentimedOutisTrue). Raises if the control channel drops before the process exits.await kill(signal=None): signal the process.
_PtyHandle
ptyIdstr: the PTY id.on_data(cb): subscribe to rawbytes. Synchronous.await write(data),await resize(cols, rows),await kill().
RunCodeResult / CodeResultItem
resultslist[CodeResultItem]: each hastype(stdout/stderr/result) plus any oftext,png,jpeg,svg,html,latex,json,markdown,chart.chartslist[Chart]: every chart acrossresults, flattened.errorAny: the raw error object when the code raised.
Chart
typeChartType:line,scatter,bar,pie,box_and_whisker,composite,unknown.title,xLabel,yLabelstr | None.x,yChartAxis | None:label,ticks,scale.elementslist | None: per-type data (points, bars, slices).
FsEntry / FsStat / FsSearchMatch / FsWatchEvent
FsEntry:namestr,dirbool,sizeint.FsStat:FsEntry’s fields plusmodeint (permission bits) andmodTimeMsint (unix millis).FsSearchMatch:pathstr,lineint,textstr.FsWatchEvent:typestr,pathstr.
GitStatus / GitBranch / GitCommit
GitStatus.branchstr: empty on a detached HEAD.GitStatus.detached,cleanbool.GitStatus.ahead,behindint: relative to the upstream, when set.GitStatus.staged,modified,untrackedlist[str].GitBranch:name,commitstr,currentbool.GitCommit:hash,author,email,date,messagestr.
MetricsResult
cpuPctfloat,memBytesint,memTotalBytesint,diskBytesint.
SnapshotView
idstr,parentstr | None,namestr | None.sizeBytesint,createdAtstr,kindSandboxKind,templatestr.
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.
| Class | Status | Meaning |
|---|---|---|
ValidationError | 400 | The request was refused as invalid (a bad field, a limit exceeded); code and the message say which. |
AuthError | 401 | API key missing, malformed, or rejected. |
PlanError | 402, 403 | The plan does not allow this: FeatureRequiresPlan, InsufficientCredit (402) or NotEntitled (403). status is what the gateway sent. |
NotFoundError | 404 | The sandbox, desktop, snapshot, template or volume does not exist (or is not yours). |
SandboxNotStoppedError | 409 | From start(): NotStopped (another state; use resume() for a paused sandbox) or StartInProgress (poll until running). Carries state. |
SnapshotNotRestorableError | 409 | A 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. |
ConcurrencyLimitError | 429 | Your org is at its cap of live sessions (ConcurrencyLimitExceeded). Not retried. Other 429s (for example TooManyExecutions) are plain GatewayError. |
NoCapacityError | 503 | NoCapacity / StartTimeout: no host available right now. Other 503s (such as SandboxUnavailable) are plain GatewayError. |
GatewayError | other | Any other non-2xx response. |
ActionError | None | A control-channel RPC returned ok: false. Carries method and code (for example NotAvailableOnSharedIsolation). |
SolariTimeoutError | None | No reply within the per-call timeout. Carries method, timeoutMs. |
SolariConnectionError | None | The control channel could not be opened or was closed, or an HTTP request failed at the transport level. |
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
