@tangle-network/sandbox
ESM TypeScript SDK for sandbox lifecycle, commands, agents, sessions and fleets, with Node.js, edge and browser entrypoints.
Install
npm install @tangle-network/sandbox
Set the customer API key and Sandbox API URL in your server environment.
export TANGLE_API_KEY=sk-tan-...
export SANDBOX_BASE_URL=https://sandbox.tangle.tools
Supported versions
The oldest supported SDK is @tangle-network/sandbox@1.0.151, the first version that accepts a capability or enum value it does not know instead of refusing the whole response.
Older versions fail when the Sandbox API advertises a new value; upgrade to this version or later.
This line is the one place the floor is stated: the production journey (scripts/production-journey.sh) reads it and runs every cell's journey on it.
Every account-authenticated request from the shared raw transport and the Python SDK sends x-sdk-version: <package version>, and the Sandbox Worker's invocation log records it as $workers.event.request.headers.x-sdk-version, so the versions customers run can be counted.
Timeouts and retries
On supported Node runtimes, concurrent HTTPS requests to a Sandbox API origin share HTTP/2 connections when the server negotiates HTTP/2. HTTP/1.1 servers can process long and short requests concurrently. The SDK calls the application’s fetch function and honors an explicit request dispatcher.
Every HTTP request has a default deadline, including direct runtime, Platform, browser control, collaboration and Tangle operator calls. SDK_TIMEOUTS owns the values (milliseconds); import it from @tangle-network/sandbox. SandboxConfig.timeoutMs replaces default; an operation's own timeout replaces that client default. Caller cancellation still applies.
| Calls |
Default policy |
| Calls without an exception below |
default |
create() |
create, or gpuCreate for a GPU lease, including retries; a capacity ETA may extend an omitted timeout within the create recovery window |
exec() |
Execution limit from the operation contract plus margin |
runCode() |
Kernel limit (runCode), plus margin; a zero kernel limit leaves a finite default request deadline |
Fleet dispatchExec / dispatchPrompt |
Larger of the requested duration and fleetDispatch, plus margin |
snapshot, retained stop, snapshot restore, image build |
snapshot; image build accepts timeout |
| Workspace image publication |
workspaceImage |
deleteMatching |
deleteMatching, or deleteMatchingUntilRemoved |
| Operation wait / preview readiness / terminal token / terminal connect |
operationWait / previewReady / interactiveToken / terminalConnect |
| Session gateway status read / attestation signing keys |
Their bounded read limits in the owning modules |
JSON and error bodies remain bounded through consumption. Successful event streams, downloads and batch streams use the request deadline through response headers; their lifetime is controlled by caller cancellation and the operation's stream policy. A timeout ends the client's wait; work already accepted by the server may continue. Rejoin a keyed create or batch using its original key.
Retries require both a replay-safe request and a retryable catalog error. Recovery may first refresh an expired bearer, supply a missing profile or wait for a retained snapshot's copy; these state changes preserve their existing recovery behavior. Transport retries retain shared pacing, Retry-After, caller cancellation and their deadline. x-no-retry disables transport replay. A planned host-agent restart refuses new work before it reaches the sandbox: the host answers 503 SIDECAR_RESTARTING (header-marked; the SDK resends it through the API) and the API answers 503 HOST_AGENT_RESTARTING with Retry-After and retryUntil, after holding the request for part of the restart. Either is safe to resend whatever the method. A turn's first POST is resent under its execution id until retryUntil; any other call the API refuses with HOST_AGENT_RESTARTING is resent whatever its method, within its attempts and deadline, unless x-no-retry is set.
Choose an entrypoint
| Need |
Import |
| Full client, sandboxes, fleets, images, sessions, and trace utilities |
@tangle-network/sandbox |
Edge-safe client without viem |
@tangle-network/sandbox/core |
| Browser or Worker access with a short-lived scoped token |
@tangle-network/sandbox/runtime |
| Browser status, claim, and release control for an interactive session |
@tangle-network/sandbox/interactive-control |
| Direct Tangle chain operations |
@tangle-network/sandbox/tangle |
| Server-side token issuance and validation |
@tangle-network/sandbox/auth |
| Node-only account command transport for seat selection |
@tangle-network/sandbox/select-seat/command |
| Collaborative document clients and file bridging |
@tangle-network/sandbox/collaboration |
| Browser session event streaming through the Sandbox API proxy, with replay |
@tangle-network/sandbox/session-gateway |
| OpenAI-compatible request and event translation |
@tangle-network/sandbox/openai |
| Multiple managed Agents, framework tool packs, and the local MCP bridge |
@tangle-network/sandbox/agent |
| Browser-safe trace reads from Tangle Intelligence |
@tangle-network/sandbox/intelligence |
Browser-safe public template catalog and publication jobs (PublicTemplatesClient) |
@tangle-network/sandbox/public-templates |
Install an optional peer dependency only when the selected integration requires it.
The Tangle quote digest, input-hash, and signature-validation helpers do not need viem at runtime.
Tangle chain operations load the optional peer when called.
The AI SDK tool pack supports the declared AI 6 and AI 7 peer ranges.
The Mastra tool pack validates arguments before it calls a Sandbox operation.
Both tool packs pass the selected session to operations that support sessions.
Credential boundary
TANGLE_API_KEY is an account-level control-plane credential. Keep it in a
trusted server, CI secret store, or CLI configuration. Never ship it, a sandbox
connection token, or provider credentials to browser JavaScript.
Mint a short-lived delegated token on the server:
const scoped = await box.mintScopedToken({
scope: "session-runtime",
sessionId: ownedRuntimeSessionId,
ttlMinutes: 5,
});
Give the browser only scoped.token, scoped.expiresAt, and
scoped.sidecarProxyUrl, then construct the browser-safe client:
import { createSandboxRuntimeClient } from "@tangle-network/sandbox/runtime";
const runtime = createSandboxRuntimeClient({
baseUrl: delegated.sidecarProxyUrl,
token: delegated.token,
});
Use scope: "session-runtime", access: "read-only" and the authorized runtime
session ID for SessionGatewayClient. Give it scoped.runtimeUrl, scoped.token
and runtimeSessionId to stream events and resume after a drop. Use scope: "read-only" for
runtime reads that need no workspace or terminal mutation. The server must
authorize every sandbox and session identifier before minting.
See the public /docs/authentication guide and
examples/browser-streaming-resume.ts.
Quick start
import { Sandbox } from "@tangle-network/sandbox";
const client = new Sandbox({
apiKey: process.env.TANGLE_API_KEY!,
baseUrl: process.env.SANDBOX_BASE_URL!,
});
const box = await client.create({
name: "sdk-quick-start",
resources: {
cpuCores: 2,
memoryMB: 4096,
diskGB: 20,
},
});
try {
await box.waitFor("running");
const result = await box.exec("node --version && npm --version");
if (result.exitCode !== 0) {
throw new Error(result.stderr);
}
console.log(result.stdout);
} finally {
await box.delete();
}
apiKey and baseUrl are required.
Keep delete() in finally unless the sandbox must outlive the process.
delete() answers once the sandbox is dead and billed; its container, volume and network are reclaimed behind the answer, and the acknowledgement reports removal: "pending".
The sandbox is already gone for every read at that point.
Deleted customer snapshot repositories, including their final snapshot when the delete took one, remain until their owner explicitly deletes them. A delete takes a final snapshot of every sandbox, unless the deployment takes delete backups on request: then only of a sandbox created with retain paths or retain.publication, required native session capture or customer storage. A sandbox stopped with retain keeps the snapshot that stop confirmed as its final one. Otherwise the newest snapshot confirmed before the delete, if any, is the last one. Platform-managed repositories of internal-account boxes retire automatically after the deleted-retention window, subject to preservation holds and active exports/restores. The serving window comes from the storage owner; see deleted repository retention.
Pass await box.delete({ until: "removed" }) when you need the reclaim itself, for example before reusing the same host capacity in a test; it reports removal: "complete", or "pending" if the wait runs out.
To remove every sandbox that one job created, tag them with metadata at create time and delete them by prefix:
const result = await client.deleteMatching({
metadataPrefix: { retainedIdempotencyKey: `runtime:${runId}:` },
});
deleteMatching() deletes only your own sandboxes, each through the same delete as box.delete().
result.complete is true only when every match is confirmed gone.
result.sandboxes reports each sandbox as destroyed, already_absent or failed, with the refusal's status and code.
One call attempts every match once, so a refused delete does not hold back the others.
The call is safe to repeat; a confirmed sandbox no longer matches.
Stop creating the job's sandboxes before you call deleteMatching().
result.complete covers only the sandboxes the call listed.
A create that registers after the listing, or retries with the same idempotency key, can leave a match behind, so call again once in-flight creates have settled.
With { until: "removed" }, a destroyed sandbox counts as confirmed only when its removal is proven.
If the removal wait runs out, the sandbox reports removal: "pending" and confirmed: false, and result.complete is false.
That sandbox is already gone for every read, so a later call does not list it again.
Run a profile without choosing where
client.run() runs an AgentProfile on a prompt in the environment its needs require. It returns when the run settles.
const result = await client.run({
profile: { name: "support", prompt: { systemPrompt: "Answer billing questions." } },
prompt: "Which plan includes priority support?",
// placement: "auto" (default) | "inference" | "worker" | "sandbox"
});
console.log(result.placement?.chosen, result.placement?.reason, result.text, result.costUsd);
auto chooses among three placements:
- one Router call, when nothing needs a tool, a file or a session;
- Tangle's sandbox-free agent loop, when the only tools are Hub
connections, owner objects or http reads;
- a sandbox, when the profile needs a harness, files, a shell or MCP servers.
A run that cannot be honoured is refused before anything is spent. client.runs.create(), get(), wait() and cancel() start, follow and stop a run separately; when wait() times out the run keeps executing until it settles or is cancelled. costUsd is the model spend Platform booked (sandbox time is billed separately). Runs are served by Platform at platformUrl.
Create a sandbox
Omit environment to use the server's default image. No image choice is
needed for an ordinary sandbox:
const box = await client.create();
Set environment when the workload needs a custom container image or a
published image ID. For example, this sandbox uses node:22:
const box = await client.create({
name: "repo-review",
environment: "node:22",
git: {
url: "https://github.com/acme/service.git",
ref: "main",
},
env: {
CI: "true",
},
resources: {
cpuCores: 4,
memoryMB: 8192,
diskGB: 40,
},
maxLifetimeSeconds: 3600,
idleTimeoutSeconds: 900,
// Delete the sandbox after one hour parked in the stopped state.
// Omit the field and the platform's default retention applies: the parked
// sweeps keep the sandbox at least 30 days parked and may reclaim it after
// that. An explicit delete, and platform policy, are unaffected.
deleteAfterStoppedSeconds: 3600,
metadata: {
project: "service",
},
});
Runtime and image
runtime chooses the isolation on the platform's hosts and environment what runs inside it.
Omit runtime for the platform default.
| Field |
Meaning |
docker |
firecracker |
runtime |
Isolation on the platform's hosts |
A container on the host kernel |
A microVM with its own kernel |
environment |
A catalog environment, a container image reference, or a built image ID |
Any of the three |
An environment whose runtimes include firecracker, or an image pinned by repository@sha256 that the cell's Firecracker hosts carry |