Python SDK

sandal (private beta): async and blocking Python clients with configuration from the environment, a Sandbox handle and helpers, plus the low-level client for every endpoint.


Install#

Private beta: the package is not on PyPI yet. Install the wheel from your beta bundle (Python 3.11+); you import it as sandal:

python3 -m venv .venv
.venv/bin/pip install ./sdk/python/sandal_sdk-0.1.0b16-py3-none-any.whl

Create the client#

Sandal is async (asyncio, httpx); SandalSync is its blocking twin with the same methods. Close the client when you are done, or use it as a context manager.

import asyncio

from sandal import Sandal, SandalSync, SandboxTarget


async def main() -> None:
    async with Sandal() as sandal:              # SANDAL_API_KEY alone is enough, else the `sandal login` profile
        sb = await sandal.create_sandbox(size="s")
        try:
            print((await sb.exec("echo hi && uname -a")).stdout)
            await sb.write_text("/workspace/notes.txt", "done\n")
            await sb.push("./app")              # git-aware copy to /workspace/app
        finally:
            await sb.delete()


asyncio.run(main())

with SandalSync() as sandal:                    # blocking: same calls without await
    print(sandal.create_sandbox().exec("python3 -c 'print(6*7)'").stdout)

# organization_id and project_id are optional overrides; the key alone is enough.
explicit = Sandal(SandboxTarget(base_url="https://api.sandal.dev", api_token=key,
                                organization_id=org, project_id=project))

The helpers (create_sandbox, exec, stream_command, run_command, files of any size, push, run_job, expose / share, lifetime, usage, saved snapshots, history) are documented once for all three languages on the SDK pages (TypeScript, Python, Go). The rest of this page is the low-level client: one method per endpoint.

Conventions#

  • Idempotency. Every mutation accepts idempotency_key; it is optional (an omitted key is a random UUID, reused by retries).
  • Revisions. expected_sandbox_revision (exec, files, ports, snapshots) and expected_revision (lifecycle) are optional; the SDK reads the current one and retries once on revision_conflict. The examples below pass them explicitly to show the wire contract.
  • Retries. 429, 502, 503, 504 and network failures, 3 retries by default, honouring Retry-After; tune with SandalRetryPolicy.
  • Operations. Create, lifecycle and fork return an object with .sandbox and .operation. Wait with await sandal.sandboxes.wait_for_operation(operation.id, timeout_seconds=300); a failed operation raises SandalOperationFailedError.
  • Errors. API failures raise SandalApiError (also the generated ApiException) with code, status, reason, request_id, retry_after_seconds and retryable, and a subclass per status (SandalNotFoundError, SandalConflictError, ...). See Limits.
import uuid


def key() -> str:
    return str(uuid.uuid4())


async def revision(sandal, sandbox_id: str) -> int:
    return (await sandal.sandboxes.get(sandbox_id)).revision

Templates#

published = await sandal.builds.templates.get_published("<template-id>")
print(published.template_digest, published.profile, published.architecture)

Template ids change when a template is rebuilt: sandal templates list shows the current ones, and omitting the template (the project default) never goes stale. Catalog ids are retired when the image is respun: a retired id answers 404 resource_not_found (“was retired… omit the template to use the project default”). Omit the template to always get the project's default; the templateId of any sandbox you create names the current one.

Sandboxes#

Create#

from datetime import datetime, timedelta, timezone

from sandal.models.sandbox_cpu_architecture import SandboxCpuArchitecture
from sandal.models.sandbox_lifecycle_policy_input import SandboxLifecyclePolicyInput
from sandal.models.sandbox_network_policy_input import SandboxNetworkPolicyInput
from sandal.models.sandbox_size import SandboxSize

created = await sandal.sandboxes.create(
    idempotency_key=key(),
    kind="virtual-machine",
    template_id="<template-id>",
    template_digest="sha256:f311884c8be75a75ada50405624aefff53ebc6611590b7cf9275fe16dc0dee6b",
    size=SandboxSize("s"),  # xs | s | m | l | xl
    architecture=SandboxCpuArchitecture("amd64"),
    name="agent-1",
    lifecycle=SandboxLifecyclePolicyInput(expires_at=datetime.now(timezone.utc) + timedelta(hours=1)),
    network_policy=SandboxNetworkPolicyInput(allow_internet=False),  # optional: block internet egress
)
await sandal.sandboxes.wait_for_operation(created.operation.id, timeout_seconds=300)
sandbox_id = created.sandbox.id

Create takes about 1.5-3.6 s until running at size s (warm pool, median about 2 s); size m and larger boot cold in 12-16 s.

Lifecycle#

async def lifecycle(action: str, sandbox_id: str) -> None:
    admitted = await getattr(sandal.sandboxes, action)(
        sandbox_id, expected_revision=await revision(sandal, sandbox_id), idempotency_key=key()
    )
    await sandal.sandboxes.wait_for_operation(admitted.operation.id, timeout_seconds=300)


await lifecycle("stop", sandbox_id)     # keeps the disk
await lifecycle("start", sandbox_id)
await lifecycle("archive", sandbox_id)  # cold storage; needs a running sandbox
await lifecycle("recover", sandbox_id)  # back to running, files intact
await lifecycle("delete", sandbox_id)   # deletes the sandbox and wipes its disk

pause and resume take the same arguments and keep memory on the same host. get_lifecycle_policy, update_lifecycle_policy and keep_alive manage automatic stop/archive/delete.

Processes#

import base64

started = await sandal.processes.exec(
    sandbox_id,
    command=["sh", "-c", "for i in 1 2 3; do echo tick $i; sleep 1; done; exit 3"],
    expected_sandbox_revision=await revision(sandal, sandbox_id),
    idempotency_key=key(),
)
async for event in sandal.processes.stream_events(sandbox_id, started.process.id, timeout_ms=120_000):
    print(base64.b64decode(event.data_base64).decode("utf-8", "replace"), end="")

process = await sandal.processes.get(sandbox_id, started.process.id)
print(process.exit_code)  # 3 (can be None for a moment after the last event; poll get() briefly)

processes.cancel, processes.signal, processes.write_input and processes.resize_pty manage a running process. A process keeps at most max_output_bytes of output (16 MiB by default, up to 64 MiB); sb.exec(...) raises SandalCommandOutputLimitError (its result holds the output so far) when a command passes it.

On a held handle, repeated sb.exec(...) calls take on the direct exec path about 125 ms median on the default Linux template and about 50 ms on the default container image (from Helsinki, November 29, 2026), and about 250 ms over the API path (one EU vantage point, November 2026). The SDK uses the direct path whenever the sandbox's image offers it (the default Linux template and the default container image do) and falls back to the API by itself. Since 0.1.0-beta.16 a handle keeps one direct-exec stream and runs each command as a channel of it (sandal.exec.v2, on by default), so only the first command pays the connection setup; turn it off with direct_exec_multi=False or SANDAL_DIRECT_EXEC_MULTI=0 (also false, off, no). Where a host or image does not offer it (the default Linux template answers with v1 today), each command opens its own connection as before; a handle you get later (by id, or from a create that did not wait) finds the direct path on its first command. sb.exec(cmd, user="root") runs as root on templates that allow it (always over the API path); the default template refuses it with 422 capability_unavailable. See Root and FUSE (preview).

Files#

await sandal.files.write(
    sandbox_id,
    path="/workspace/hello.txt",
    data_base64=base64.b64encode(b"hello sandal\n").decode(),
    offset=0,
    truncate=True,
    create_parents=True,
    expected_sandbox_revision=await revision(sandal, sandbox_id),
    idempotency_key=key(),
)
read = await sandal.files.download(sandbox_id, "/workspace/hello.txt", offset=0, limit=65_536)
print(base64.b64decode(read.data_base64).decode())

One write carries at most 256 KiB. Large transfers use signed transfer URLs (24 MiB in about 5 s up and 3 s down); where those are switched off the SDK falls back to the much slower chunked API.

Ports#

exposure = (
    await sandal.sandboxes.expose_port(
        sandbox_id,
        expected_sandbox_revision=await revision(sandal, sandbox_id),
        port=8080,
        protocol="http",
        ttl_seconds=600,
        idempotency_key=key(),
    )
).exposure
while exposure.state.value != "ready":
    await asyncio.sleep(0.5)
    exposure = await sandal.sandboxes.get_port_exposure(sandbox_id, exposure.id)
print(exposure.url)  # requests need `Authorization: Bearer <API key>`

To share a preview without a key, use sb.share(port) (a time-bounded, revocable share link; see Share links).

Snapshots and forks#

snapshot = (
    await sandal.sandboxes.create_snapshot(
        sandbox_id, expected_sandbox_revision=await revision(sandal, sandbox_id), idempotency_key=key()
    )
).snapshot
while snapshot.state.value != "ready":
    await asyncio.sleep(0.5)
    snapshot = await sandal.sandboxes.get_snapshot(sandbox_id, snapshot.id)

forked = await sandal.sandboxes.fork(
    sandbox_id,
    expected_revision=await revision(sandal, sandbox_id),
    idempotency_key=key(),
    name="agent-1-fork",
    lifecycle=SandboxLifecyclePolicyInput(expires_at=datetime.now(timezone.utc) + timedelta(hours=1)),
)
await sandal.sandboxes.wait_for_operation(forked.operation.id, timeout_seconds=300)

Code interpreter#

On projects where sandal capabilities lists code-interpreter:

outcome = await sandal.code.run_and_wait(
    sandbox_id,
    idempotency_key=key(),
    language="python",
    code="import math\nprint('hi')\nmath.sqrt(2)",
)
print(outcome.main_result.data["text/plain"] if outcome.main_result else None)

Not yet available on the beta#

The SDK contains clients for a few parts of the API that the beta deployment does not offer yet: file watch, volume snapshots and telemetry export answer capability_unavailable today, the Xcode builds client has no Mac hosts behind it yet, and the macOS client needs a Mac leased to your organisation. Auto-pause (autoResume), bring-your-own egress, browser sessions and template builds are enabled per project during the beta. The current state per feature is on Limits; sandal capabilities shows what your project can do.

Every namespace: sandboxes, processes, files, git, agents, code, language_servers, computer, browsers, devices, builds, events.webhooks, telemetry, keys, audit; sandal.raw holds the generated APIs.