Skip to main content

sandscale

Python SDK for Sandscale: sandboxes, workspaces and build hosts over the Sandscale API (https://api.sandscale.dev). One dependency (httpx); Python 3.10 or later.

The server decides everything: permissions, plan limits, quotas, entitlements, kill switches and regions. The SDK sends your request as you (your API key or your own sign-in token) and hands back the server's answer, including its error code and message.

pip install sandscale

Quick start

import sys
from sandscale import Sandscale

with Sandscale() as sandscale:  # SANDSCALE_API_KEY from the environment
    box = sandscale.sandboxes.create(template="builtin:python", timeout_seconds=600)
    # BUILTIN_TEMPLATES lists the built-ins: base (default), python, node, go, go_postgres (Go with PostgreSQL 17
    # running on 127.0.0.1:5432, TEST_DATABASE_URL set), minimal. The default image has
    # Python 3 with pip, Node.js with npm, git, curl, a C compiler, jq and unzip (docs/sandbox/images.md).
    try:
        run = sandscale.sandboxes.run(
            box.id,
            'python -c "print(6*7)"',
            region=box.region,
            on_stdout=sys.stdout.write,
            on_stderr=sys.stderr.write,
        )
        print("exit code", run.exit_code)
    finally:
        sandscale.sandboxes.stop(box.id, region=box.region)

Authentication

Argument Environment
api_key SANDSCALE_API_KEY A Sandscale API key.
token The person's own sign-in access token, or a function returning a current one (called before every request, so it can refresh).
org_id SANDSCALE_ORG_ID Sent as X-Org-ID; required by workspace and build host calls, whose routes name the organization.
base_url SANDSCALE_BASE_URL Default https://api.sandscale.dev. https only (plain http only to a loopback host).

Credentials are held in memory and sent only to the configured API origin and the region origins the server lists; redirects are not followed, so a credential never follows one.

Regions

One account works in every Sandscale region. Pass region="us" or region="eu" to the client (the default for every call) or to any call:

Region API
none https://api.sandscale.dev, the front door: it routes to the request's region, US by default
"us" https://api.us.sandscale.dev
"eu" https://api.sandscale.dev with region=eu1: the front door sends the call to the EU region with your own credential. The EU regional host (api.eu.sandscale.dev) does not accept a global API key or sign-in token, so the SDK never calls it directly

A region id such as us1 names the same region. region_urls sets origins explicitly. Against another base_url (a self-hosted Sandscale) a region is looked up in that server's public region list (GET /api/v1/regions).

Models carry the region they were read from; pass it to later calls on them. Lists without a region read every Sandscale region the front door reports live and merge the results; pages says, per region, the next cursor or the error that region answered.

API

Area Methods
sandboxes create, get, list, run (live stdout and stderr, exit code), logs, write_file, read_file, list_files, pause, resume, snapshot, list_snapshots, stop, attach_volume, list_attachments, commit_volume, detach_volume, restore_cache, save_cache
volumes create, get, list, delete
caches list, delete
workspaces list, get, start, stop, connect_info
build_hosts list_pools, list, get, start (take a lease of a pool), stop (release it), connect_info, ssh_certificate
sandboxes create (network, image, runtime, environment_id), get, list, run (live stdout and stderr, exit code), logs, write_file, read_file, list_files, pause, resume, snapshot, list_snapshots, stop, expose_port, list_ports, close_port, create_preview_link, list_preview_links, revoke_preview_link, ssh_info, ssh_certificate
snapshots list (with quota usage), get, delete
templates create, list, get, delete, build_status
policy get, set
webhooks list, create, delete, verify (also verify_webhook_signature)
traces list, get, get_export, set_export, delete_export, test_export
execute, search, tasks, code_policy code mode (below): tasks.get, tasks.wait, code_policy.get, code_policy.set
api the typed API (below): every operation as api.<namespace>.<function>(**args)
objects buckets (create_bucket, list_buckets, get_bucket, update_bucket, delete_bucket), lifecycle, policy, access keys, limits
workspaces list, get, start, stop, connect_info, create, update, delete, rebuild, open_link, list_backups, create_backup, verify_backup, list_apps, share_app
build_hosts list_pools, list, get, start (take a lease of a pool), stop (release it), connect_info, ssh_certificate, renew, kill, list_runs, get_run, list_artifacts, get_artifact, download_artifact, delete_artifact, list_caches, list_pool_caches, purge_pool_cache
lab_hosts list, get, revoke
agent_cloud create_task, list_tasks, get_task, cancel_task
account billing, change_plan, set_overage, cancel_pending_plan_change, checkout, usage, regions, list_api_keys, create_api_key, rotate_api_key, delete_api_key

sandboxes.run waits for the command and returns a RunResult (run_id, exit_code, stdout, stderr, duration_ms, oom_killed, timed_out, streamed). With on_stdout / on_stderr it starts the command without waiting (wait false): the server answers with the run's id, and the output arrives live, in the calling thread, from that run's log stream, after the organization's DLP rules. The server may redact it, or end the stream with dlp_unavailable, raised as a ServerError. The exit code comes from the stream's end. A server that answers with the finished result instead gets the callbacks the final output once.

sandboxes.create(vault_env=[VaultEnvRef("DB_PASSWORD", "secret/data/db", "password")]) puts Sandscale Vault values in the sandbox's environment. The server reads them as you and gives them to the sandbox only.

Persistent volumes keep a directory between sandboxes, in versions. attach_volume(sandbox_id, volume_id, mount_path, mode="rw") mounts one (read-write by one sandbox at a time, else 409 volume_writer_attached; mode="ro" is never written back), commit_volume writes the next version and detach_volume(..., commit=False) drops uncommitted changes (a read-write attachment commits first by default). Dependency caches are keyed by the server from the lockfile it reads in the sandbox and shared within the organization only:

r = sandscale.sandboxes.restore_cache(box.id, ecosystem="pip", lockfile="/workspace/requirements.txt")
if not r.hit:
    sandscale.sandboxes.run(box.id, "pip install -r /workspace/requirements.txt")
    sandscale.sandboxes.save_cache(box.id, ecosystem="pip", lockfile="/workspace/requirements.txt")

More examples

Every call takes region= like the first ones. The server decides what you may do; the SDK only carries the answer.

box = sandscale.sandboxes.create(template="builtin:python", network="allowlist", runtime="firecracker")
port = sandscale.sandboxes.expose_port(box.id, 8080, ttl_seconds=3600, region=box.region)
link = sandscale.sandboxes.create_preview_link(box.id, 8080, visibility="team", region=box.region)
print(link.url)
sandscale.sandboxes.revoke_preview_link(box.id, link.id, region=box.region)
sandscale.sandboxes.close_port(box.id, 8080, region=box.region)

cert = sandscale.sandboxes.ssh_certificate(box.id, open("id_ed25519.pub").read().strip(), region=box.region)
print(cert.known_hosts, cert.key_id)  # the certificate itself is in cert.certificate

Snapshots, templates and policy

snaps = sandscale.snapshots.list()
print(snaps.usage.count, snaps.usage.bytes)

tpl = sandscale.templates.create(name="py-ml", image="registry.example/py-ml@sha256:" + "0" * 64, memory_mb=2048)
print(sandscale.templates.build_status(tpl.id).status)

sandscale.policy.set(egress_allowlist=["pypi.org"], egress_presets=["npm", "pypi"], max_concurrent=10)

policy.set(hibernation="on" | "off" | "default") sets hibernation between tool calls; keep_awake retries a waking sandbox (SandboxWakingError) before raising.

Webhooks

from sandscale import verify_webhook_signature

hook = sandscale.webhooks.create(url="https://example.com/hooks/sandscale", events=["run.completed"])
signing_secret = hook.secret  # shown once: store it in your secret manager, never print it

# In your receiver: pass the raw body exactly as received.
ok = verify_webhook_signature(request.headers.get("X-Sandscale-Signature"), raw_body, signing_secret)

The signature is sha256= and the hex HMAC-SHA256 of the raw body under the secret; the check is constant time. Current signing carries no timestamp. Test, redeliver and the delivery log are not served yet.

Run traces and OpenTelemetry export

for t in sandscale.traces.list(limit=10).data:
    print(t.trace_id, t.status, t.spans)
trace = sandscale.traces.get(t.trace_id)
sandscale.traces.set_export(protocol="otlp_http", endpoint="https://otel.example.com", headers={"x-honeycomb-team": api_key_for_collector})
print(sandscale.traces.test_export().ok)

Object storage

from sandscale import LifecycleRule

sandscale.objects.create_bucket("artifacts", versioning="Enabled")
sandscale.objects.put_lifecycle("artifacts", [LifecycleRule(id="tmp", prefix="tmp/", expiration_days=7)])
created = sandscale.objects.create_access_key(description="ci", buckets=["artifacts"], expires_in_days=30)
key_id = created.access_key.access_key_id
secret = created.secret_access_key  # shown once, not in repr(); store it, never log it

Workspaces, build hosts and lab hosts

ws, build = sandscale.workspaces.create(name="dev", template_id="tpl-1", repository="github.com/acme/app")
print(sandscale.workspaces.open_link(ws.id, "vscode").url)
backup = sandscale.workspaces.create_backup(ws.id)
print(sandscale.workspaces.verify_backup(backup.id).valid)
sandscale.workspaces.share_app(ws.id, "web", "org")

lease = sandscale.build_hosts.renew("lease-1", 3600)
for artifact in sandscale.build_hosts.list_artifacts(lease.id):
    data = sandscale.build_hosts.download_artifact(lease.id, artifact.id)
print(sandscale.build_hosts.list_pool_caches("pool-1").used_bytes)
sandscale.lab_hosts.revoke("host-1", reason="decommissioned")

Agent Cloud tasks

task = sandscale.agent_cloud.create_task(repository="github.com/acme/app", brief="Fix the flaky test", engine="claude_code")
print(sandscale.agent_cloud.get_task(task.id).state)
sandscale.agent_cloud.cancel_task(task.id)

These are Sandscale's lead routes (never the device agent). They need a signed-in person's token; an API key is refused with 403 person_required.

Account

billing = sandscale.account.billing()
print(billing.state.plan, billing.balance.remaining_vcpu_hours)
sandscale.account.set_overage(True)          # the server decides whether the plan allows it
sandscale.account.change_plan(plan="team", interval="month", seats=3)
print(sandscale.account.usage().running_boxes, [r.id for r in sandscale.account.regions()])

from datetime import datetime, timedelta, timezone
key = sandscale.account.create_api_key(name="ci", expires_at=datetime.now(timezone.utc) + timedelta(days=30))
new_key = key.key  # shown once; store it, never print it
sandscale.account.rotate_api_key(key.id, overlap_seconds=300)
sandscale.account.delete_api_key(key.id)

Plan changes, overage and personal API keys need a signed-in person's token. Secrets the server shows once (webhook signing secret, secret_access_key, API key key) are fields excluded from repr and from raw; the SDK never logs or prints them.

Agent frameworks

LangChain. pip install "sandscale[langchain]". SandscaleSandbox is a Deep Agents sandbox backend (its file tools and execute run in the sandbox; paths are absolute), and SandscaleToolkit gives any LangChain agent sandscale_run, sandscale_write_file and sandscale_read_file:

from deepagents import create_deep_agent
from sandscale.integrations.langchain import SandscaleSandbox, SandscaleToolkit

with SandscaleSandbox.create(template="builtin:python", timeout_seconds=900) as backend:
    agent = create_deep_agent(model="anthropic:claude-sonnet-4-6", backend=backend)

with SandscaleToolkit.create(template="builtin:node") as toolkit:
    tools = toolkit.get_tools()

OpenAI Agents SDK. pip install "sandscale[openai-agents]". SandscaleSandboxClient runs a SandboxAgent's workspace in a sandbox (root /workspace; saved workspaces are tar archives; an exposed port is published as a public preview link, Pro and up):

from agents.run import RunConfig
from agents.sandbox import SandboxRunConfig
from sandscale.integrations.openai_agents import SandscaleSandboxClient, SandscaleSandboxClientOptions

config = RunConfig(sandbox=SandboxRunConfig(
    client=SandscaleSandboxClient(),
    options=SandscaleSandboxClientOptions(template="builtin:python", timeout_seconds=900),
))

A sandbox an adapter started is stopped when it closes; one you pass in is left running. Both wait out rate limits (429) and move files as streamed transfers (sandboxes.upload and sandboxes.download, up to 1 GiB). Full scripts: examples/langchain_deep_agent.py, examples/openai_agents_sandbox.py.

For agents

c = sandscale.capabilities()  # plan, limits, templates, regions, vCPU-hour balance and its reset time
box = sandscale.sandboxes.create(template="builtin:base", idempotency_key="job-42")  # a retry never makes a second box
proc = sandscale.sandboxes.start_process(box.id, "python -m http.server 8000")
sandscale.sandboxes.wait_for_port(box.id, 8000)
log = sandscale.sandboxes.process_logs(box.id, proc.process_id, offset=0)  # log.next_offset continues
sandscale.sandboxes.kill_process(box.id, proc.process_id)
text = sandscale.sandboxes.read_text(box.id, "/workspace/out.txt")

A refused call raises an error whose details carry the next step the server names (the templates to start, the plan that lifts a limit, when the allowance renews).

Code mode

execute runs a TypeScript or JavaScript script on the server against your typed API, as you: one request instead of one per call. The script sees sandscale.<namespace>.<fn>(args) and vault.ref("store/name#field"), may await and return, and its return value is task.result.

task = sandscale.execute("""
  const box = await sandscale.sandbox.create({ template: "builtin:python" });
  console.log("started", box.id);
  return box.id;
""")
print(task.state, task.result, [line.text for line in task.console])

The server answers within wait_seconds (at most 30); after a 202 the SDK reads the task again (poll_interval, timeout) until it succeeded or failed. A failed task raises TaskFailedError (its code is the task's: script_error, syntax_error, time_limit and so on; task.error has the script line and column and the api_error that ended it, with its next step); raise_on_failure=False returns it instead. A timeout that passes first raises TaskTimeoutError while the task keeps running on the server.

A call the Organization's ask-first policy names waits for a person: execute returns the task in state awaiting_approval with pending_approval (request_id, operation, seq), unless wait_for_approval=True. Read it later with sandscale.tasks.get(task_id, wait_seconds=30) or sandscale.tasks.wait(task_id); reading an approved task resumes it. Only the person who started a task reads it (anyone else gets NotFoundError).

found = sandscale.search('return api.find("snapshot a sandbox", 5)')  # the typed API as data
print(found.result)
sandscale.code_policy.get().ask_first          # e.g. ["destructive"]
sandscale.code_policy.set(["sandbox_terminate", "writes"])  # needs sandboxes:write

Typed API

sandscale.api.<namespace>.<function>(**args) calls any operation of the typed API (the same functions a code mode script calls) directly from Python. It is built at import from the generated operation table; names work in camelCase and snake_case (api.auditLogs.auditEventsList and api.audit_logs.audit_events_list), and api.call("sandbox_snapshot_create", {...}) takes the operation name.

snap = sandscale.api.sandbox.snapshot_create(id=box.id, label="before", region="us")
events = sandscale.api.audit_logs.audit_events_list(from_="2026-11-01", limit=50)  # from_ for from
sandscale.api.sandbox.instances_ports_delete(id=box.id, port=8080, confirm=True)

Arguments are the operation's parameter names; one the operation does not take, or a missing required one, raises ApiArgumentError before any request. Organization path parameters are filled from the client's org_id. An operation that deletes, ends or changes billing needs confirm=True (never sent); without it the SDK raises SandscaleError with code confirmation_required and sends nothing. A write takes idempotency_key (sent as Idempotency-Key, so it is retried like a read). Answers are the server's JSON as is; refusals are the usual errors below.

Errors

Every API error is a SandscaleError with the server's status, code, message, request_id and details: InvalidRequestError (400, 413, 422), AuthenticationError (401), PermissionDeniedError (403), NotFoundError (404), ConflictError (409), LimitExceededError (402 or a quota or limit code, including lease_duration_limit, lease_vcpu_limit, lease_concurrent_limit, lab_host_limit, vault_secret_limit and vault_store_limit, whose details carry plan and the limit hit) and its RateLimitError (429, with retry_after), EntitlementError (not_entitled, payment_required, entitlement_*, plan_*, *_not_in_plan; lease_not_in_plan now means a misconfigured plan), RegionError (wrong_region with region, region_*), KillSwitchError (kill_switch_*), ServerError (5xx; retryable for 502, 503 and 504) with ServiceUnavailableError (any 503, with retry_after; also entitlement_unavailable) and SandboxWakingError (503 sandbox_waking: the sandbox is resuming, retry after retry_after), and APIConnectionError (no answer). ConfigurationError is raised before any request when the client cannot be configured safely.

Retries

Only safe calls (GET) are retried, at most max_retries times (default 2), after a connection error, 429, 502, 503 or 504, with exponential backoff and full jitter (at most 8 s), or the server's Retry-After (at most 60 s). Kill switch, entitlement and region refusals are never retried. Calls that change something are sent once.

Known gaps

  • Cross-region credentials. Until the global plane syncs API keys and sign-in sessions to every region, a credential of one region is refused in another with wrong_region (RegionError, with region).
  • Vault environment on sandboxes needs a server with vault_env (docs/sandbox/vault-env.md in the Sandscale documentation). A server from before it ignores the field.
  • Synchronous client only; an asyncio client is a follow-up.

Tests

pip install -e ".[dev]" && pytest   # unit tests against a local mock server, route contract
SANDSCALE_API_KEY=... pytest         # also the integration test (starts and stops one sandbox)

tests/test_routes.py fails when the server stops mounting a route this SDK calls (the route inventory of the Sandscale repository) or when the SDK calls a route it does not list.

Metadata

Release files for sandscale 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sandscale 1.0.0
File Size Uploaded Provenance Actions
sandscale-1.0.0.tar.gz 124.7 kB Without provenance Details for sandscale-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sandscale 1.0.0
File Interpreter ABI Platform Actions
sandscale-1.0.0-py3-none-any.whl Python 3 none any Details for sandscale-1.0.0-py3-none-any.whl

Total release size: 228.8 kB

Release files / sandscale-1.0.0.tar.gz

Download URL sandscale-1.0.0.tar.gz
Size 124.7 kB
Tags Source
SHA-256 checksum
How to use checksums
f7fe5c90be07f08cf0da740a251265038a3c15d16d4f46ea4a48bceb45fcef69
BLAKE2b-256 checksum
How to use checksums
39bd7d29f48b2d7d018ecd66285465186b5f6c16d6bd02d1b819cfb04b358fc2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / sandscale-1.0.0-py3-none-any.whl

Download URL sandscale-1.0.0-py3-none-any.whl
Size 104.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0c47e19cb2ac3e2f972a3ea4a80526e88a4bc9276c0076b17b030bc2261163ef
BLAKE2b-256 checksum
How to use checksums
bde878604f3871f04448bfd1b81df11684914619ef221bfeb8f91ae19743dde4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for sandscale 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page