SandboxPython SDK

Python SDK

tangle-sandbox drives sandboxes from Python: create one, run commands, read and write text files, give a coding agent a task, snapshot the workspace and delete it. Sandbox is the synchronous client and AsyncSandbox is its asyncio twin with the same methods.

Install

The SDK needs Python 3.10 or newer.

pip install tangle-sandbox
ExtraAddsUnlocks
tangle-sandbox[gateway]websocketstangle_sandbox.session_gateway, a WebSocket client for a session’s live events
tangle-sandbox[tangle]web3, eth-accounttangle_sandbox.tangle, which creates sandboxes on Tangle Network operators
tangle-sandbox[all]bothboth

Everything else, including fleets, batches, secrets, teams and trace export, is in the base install.

Create a client

import os
 
from tangle_sandbox import Sandbox
 
client = Sandbox(
    api_key=os.environ["TANGLE_API_KEY"],
    base_url="https://sandbox.tangle.tools",
)

Pass both arguments. The SDK reads no environment variables and has no default host. Keys start with sk-tan-; create one at id.tangle.tools/app/keys. API keys and tokens covers scopes and budgets.

timeout_ms (default 30000) bounds each request. Use the client as a context manager, or call client.close(), to close its connection pool.

Run your first sandbox

import os
 
from tangle_sandbox import Sandbox, SandboxStatus
 
with Sandbox(
    api_key=os.environ["TANGLE_API_KEY"],
    base_url="https://sandbox.tangle.tools",
) as client:
    box = client.create(name="hello-python")
    try:
        # create() returns before the sandbox runs; runtime calls need RUNNING.
        box.wait_for(SandboxStatus.RUNNING)
 
        result = box.exec("python3 -c 'print(sum(range(1_000_000)))'")
        print(result.exit_code, result.stdout.strip())
 
        box.write("notes.md", "first draft\n")
        print(box.read("notes.md").strip())
 
        turn = box.prompt("Reply with exactly the word OK")
        if not turn.success:
            raise RuntimeError(turn.error)
        print(turn.response)
    finally:
        box.delete()
0 499999500000
first draft
OK

A sandbox created without a backend runs the opencode coding agent. Run a coding agent shows how to pick Claude Code, Codex or another one.

Stop and resume

stop() keeps the disk and stops billing for compute. resume() starts it again; wait for RUNNING before the next runtime call.

box.write("notes.md", "first draft\n")
box.stop()
print(box.status.value)
 
box.resume()
box.wait_for(SandboxStatus.RUNNING)
print(box.read("notes.md").strip())
stopped
first draft

Async client

import asyncio
import os
 
from tangle_sandbox import AsyncSandbox, SandboxStatus
 
 
async def word_count(client: AsyncSandbox, text: str) -> str:
    box = await client.create()
    try:
        await box.wait_for(SandboxStatus.RUNNING)
        await box.write("input.txt", text)
        return (await box.exec("wc -w < input.txt")).stdout.strip()
    finally:
        await box.delete()
 
 
async def main() -> None:
    async with AsyncSandbox(
        api_key=os.environ["TANGLE_API_KEY"],
        base_url="https://sandbox.tangle.tools",
    ) as client:
        texts = ["one two three", "four five", "six"]
        print(await asyncio.gather(*(word_count(client, t) for t in texts)))
 
 
asyncio.run(main())
['3', '2', '1']

Things that catch Python users

  • create() returns while the sandbox is still pending or provisioning. exec, read, write, search, prompt, git and snapshot raise StateError until you call wait_for(SandboxStatus.RUNNING).
  • Pass SandboxStatus members, not strings. wait_for("running") raises AttributeError instead of TimeoutError when it times out, and ListSandboxOptions(status="running") raises at once.
  • exec runs the command with bash and merges stderr into stdout, so ExecResult.stderr is empty. A non-zero exit code is returned, not raised.
  • A cwd that does not exist is ignored: the command runs in the default directory, /home/agent, or the cloned repository when the sandbox was created with git.
  • prompt() returns success=False with error set when the turn fails. Check success.
  • read and write handle UTF-8 text only.
  • health() returns True for any key, because /health needs no key. Make a real call, such as client.list(limit=1), to check a key.
  • tangle_sandbox.TimeoutError is not the built-in TimeoutError. Catch the SDK’s class, or catch SandboxError and read code.
  • confidential and tangle_secrets on CreateSandboxOptions are ignored by Sandbox and AsyncSandbox. Only the [tangle] client sends them.

Timeouts and retries

WhatLimit
Each requesttimeout_ms on the client, default 30000 ms
execExecOptions.timeout_ms (default 30000 ms) plus 15 s for the response
prompt, stream_prompt, stream_batch300 s without an event, or PromptOptions.timeout_ms
wait_forWaitForOptions.timeout_ms, default 120000 ms, polling every 2000 ms
snapshot, restore_pathsup to 600 s for the operation
Fleet dispatchthe larger of timeout_ms and 600 s, plus 15 s

GET, PUT, DELETE, HEAD and OPTIONS requests are retried up to 3 times on a 429, 502, 503 or 504 whose error code is retryable, waiting for Retry-After. create() sends an Idempotency-Key with every attempt. When the service is out of capacity it sends the same request again for up to 150 s or the client timeout, whichever comes first, so a retry joins the first create instead of making a second sandbox. If create() times out, the TimeoutError message names the key. Call create() again with CreateSandboxOptions(idempotency_key=...) set to that key to pick up the same sandbox.

What Python can do, and what to use for the rest

The Python SDK covers the core lifecycle, commands, text files, git, snapshots, network rules, coding agent prompts, batches, secrets, teams and traces. For anything below, use the TypeScript SDK or the CLI, or call the REST route with client.fetch(method, path, json=..., params=...). client.fetch sends your key, returns the raw httpx.Response and does not raise on a 4xx or 5xx status.

TaskTypeScriptCLIREST
Interactive terminalbox.terminalstangle ssh, tangle agent prompt --interactiveWebSocket; see Shells and terminals
List, move, upload and download files; binary filesbox.fs.*, box.uploadDirectorytangle fssee Files
Run code with structured outputbox.runCodetangle runsee Run commands and code
Background processes and logsbox.process.*tangle processsee Run commands and code
Separate stderrbox.exectangle exec
Expose a port or share a preview linkbox.network.exposePort, box.previewLinkstangle sandbox expose, tangle previewsee Ports and preview links
Named agent sessions, answers and historybox.createSession, box.sessionstangle agent prompt --sessionsee Sessions
Branch or fork a running sandboxbox.branch, box.forktangle branch createsee Snapshots and forks
Revert to or delete a snapshotbox.revertToSnapshot, box.deleteSnapshottangle snapshot revert, tangle snapshot deletesee Snapshots and forks
Rebuild a sandbox, poll an operationbox.rebuild, box.getOperation
Resource usage and runtime healthbox.resourceUsage, box.runtimeHealth
MCP endpoint and computer usebox.getMcpEndpointGET /v1/sandboxes/{id}/mcp
TEE sandboxes and attestationconfidential on create, box.getTeeAttestationtangle sandbox create --tee, tangle sandbox attestation
Egress usage and activitybox.egress.usage, box.egress.activityGET /v1/sandboxes/{id}/egress/usage, GET /v1/sandboxes/{id}/egress/activity
GPU leasesbox.gpu.*tangle sandbox gpusee GPU leases
SSH keys, public templates, lines, runsclient.sshKeys, client.publicTemplates, client.lines, client.runstangle ssh-keys, tangle template, tangle lines
Sizes and coding agents on offerclient.shapes(), client.listBackends()tangle sandbox shapesGET /v1/shapes, GET /v1/backends
List team or all sandboxesclient.list({ scope })tangle sandbox list --team, --all-scopesGET /v1/sandboxes?scope=team
Team secrets and templates, ownership transferclient.teams.upsertSecret, createTemplate, transferOwnershiptangle team secret, tangle team templates, tangle team transfersee Teams
Create fields Python lacks: cwd, ephemeral, retain, startupScriptIds, gpuLease, complianceclient.createsome as tangle sandbox create flagsPOST /v1/sandboxes
List every fleetclient.fleetstangle fleet listGET /v1/fleets

For example, list the coding agents the service offers:

response = client.fetch("GET", "/v1/backends")
print(response.status_code, [b["type"] for b in response.json()["backends"]][:3])

Reference

Next