Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ jobs:
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with:
python-version: ${{ matrix.python }}
- run: pip install -e ".[dev]"
# The LangChain and OpenAI Agents integrations need Python 3.11 or later; on 3.10 the SDK is
# tested without them (their tests skip) and the type check runs on the later versions.
- if: matrix.python == '3.10'
run: pip install -e ".[dev]"
- if: matrix.python != '3.10'
run: pip install -e ".[dev,langchain,openai-agents]"
- run: pytest
- run: mypy src tests
- if: matrix.python != '3.10'
run: mypy src tests
17 changes: 12 additions & 5 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
# Copyright 2026 Neural Inverse
# SPDX-License-Identifier: Apache-2.0

# Publishes sandscale to PyPI when a v* tag is pushed, through PyPI trusted publishing (OIDC):
# no PyPI token is stored anywhere. PyPI trusts this repository, this workflow file (release.yml)
# and the environment `pypi`. Attestations (PEP 740) are attached automatically.
# Publishes sandscale to PyPI when a v* tag is pushed. Until a trusted publisher (OIDC) is
# registered on PyPI, the upload uses the project's API token, the secret PYPI_API_TOKEN of the
# environment `pypi` (never printed, never in this repository); attestations (PEP 740) need
# trusted publishing and are off until then.
# See RELEASING.md for the one-time setup.
name: release

Expand All @@ -28,7 +29,7 @@ jobs:
have="$(python -c "import tomllib;print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")"
test "$want" = "$have" || { echo "tag $GITHUB_REF_NAME but pyproject.toml is $have"; exit 1; }
grep -q "VERSION = \"$want\"" src/sandscale/_version.py || { echo "_version.py does not carry $want"; exit 1; }
- run: pip install -e ".[dev]"
- run: pip install -e ".[dev,langchain,openai-agents]"
- run: pytest
- run: mypy src tests
- run: python -m build
Expand All @@ -42,10 +43,16 @@ jobs:
runs-on: ubuntu-latest
environment: pypi
permissions:
id-token: write # PyPI trusted publishing
id-token: write # kept for PyPI trusted publishing once it is set up on PyPI
steps:
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: dist
path: dist/
- uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # release/v1
with:
# An API token of the project (environment secret of `pypi`), until a trusted publisher
# is registered on PyPI. PEP 740 attestations need trusted publishing, so they are off.
password: ${{ secrets.PYPI_API_TOKEN }}
attestations: false
print-hash: true
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

# Changelog

## 1.0.0 - 2026-11-18
## 1.0.0 - 2026-11-29

First public release of sandscale under the Apache-2.0 licence: sandboxes (create, run with live
output, logs, files, pause, resume, snapshot, stop, list), ports, preview links and SSH,
Expand Down
155 changes: 143 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ hands back the server's answer, including its error code and message.
pip install sandscale
```

Documentation: https://sandscale.dev/docs. Source and issues: https://github.com/sandscale/sandscale-python. Licensed under Apache-2.0.

## Quick start

```python
Expand All @@ -24,6 +22,9 @@ 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,
Expand Down Expand Up @@ -58,10 +59,10 @@ One account works in every Sandscale region. Pass `region="us"` or `region="eu"`
|---|---|
| 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.eu.sandscale.dev` (when Sandscale opens in eu1) |
| `"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 Keystone) a region is looked up in that server's
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
Expand All @@ -72,12 +73,19 @@ says, per region, the next cursor or the error that region answered.

| 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` |
Expand All @@ -94,9 +102,24 @@ the organization's DLP rules. The server may redact it, or end the stream with
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
Keystone Vault values in the sandbox's environment. The server reads them as you and gives them
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:

```python
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
Expand Down Expand Up @@ -140,7 +163,7 @@ hook = sandscale.webhooks.create(url="https://example.com/hooks/sandscale", even
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-Keystone-Signature"), raw_body, signing_secret)
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
Expand Down Expand Up @@ -193,7 +216,7 @@ print(sandscale.agent_cloud.get_task(task.id).state)
sandscale.agent_cloud.cancel_task(task.id)
```

These are Keystone's lead routes (never the device agent). They need a signed-in person's
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
Expand All @@ -216,14 +239,121 @@ Plan changes, overage and personal API keys need a signed-in person's token. Sec
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`:

```python
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):

```python
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

```python
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`.

```python
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`).

```python
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.

```python
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) and its `RateLimitError` (429, with
`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`), `RegionError` (`wrong_region` with `region`, `region_*`), `KillSwitchError`
`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).
Expand All @@ -241,7 +371,8 @@ never retried. Calls that change something are sent once.
- **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 that supports `vault_env`. A server from before it ignores the
- **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.

Expand All @@ -252,5 +383,5 @@ pip install -e ".[dev]" && pytest # unit tests against a local mock server, ro
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 (checked against the
server route inventory when the tests run inside the Keystone source tree, skipped elsewhere) or when the SDK calls a route it does not list.
`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.
8 changes: 5 additions & 3 deletions RELEASING.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ tree. Do not commit here directly; changes go through Keystone and are synced on

A release is a `v*` tag on `main`. `.github/workflows/release.yml` checks that the tag equals
`pyproject.toml` and `_version.py`, runs pytest and mypy, builds the sdist and wheel, then the
`publish` job uploads them with `pypa/gh-action-pypi-publish` using **PyPI trusted publishing**:
GitHub's OIDC token is exchanged for a short-lived upload token, so no PyPI token exists in this
repository. PEP 740 attestations are attached automatically.
`publish` job uploads them with `pypa/gh-action-pypi-publish`. Today it uses the project's PyPI API
token, stored only as the secret `PYPI_API_TOKEN` of the GitHub environment `pypi` (never in this
repository, never printed). When a trusted publisher is registered (below), drop the `password`
input and turn `attestations` back on: GitHub's OIDC token is then exchanged for a short-lived
upload token and PEP 740 attestations are attached.

## One-time owner setup

Expand Down
17 changes: 17 additions & 0 deletions examples/langchain_deep_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Copyright 2026 Neural Inverse
# SPDX-License-Identifier: Apache-2.0
"""A LangChain Deep Agent whose file tools and shell run in a Sandscale sandbox.

pip install "sandscale[langchain]" langchain-anthropic
export SANDSCALE_API_KEY=... ANTHROPIC_API_KEY=...
python examples/langchain_deep_agent.py
"""

from deepagents import create_deep_agent

from sandscale.integrations.langchain import SandscaleSandbox

with SandscaleSandbox.create(template="builtin:python", timeout_seconds=900) as backend:
agent = create_deep_agent(model="anthropic:claude-sonnet-4-6", backend=backend)
result = agent.invoke({"messages": [{"role": "user", "content": "Write fib.py printing the first 20 Fibonacci numbers, run it and show the output."}]})
print(result["messages"][-1].content)
Loading
Loading