SandboxCreate, stop and delete

Create, stop, resume and delete sandboxes

A sandbox is a Linux machine you create, pause, wake and delete from code or the terminal. This page covers every step of that life: the create options, waiting, the timers that stop a sandbox for you, and cleanup.

Create a sandbox and delete it

import { Sandbox } from "@tangle-network/sandbox";
 
const client = new Sandbox({
  apiKey: process.env.TANGLE_API_KEY!,
  baseUrl: "https://sandbox.tangle.tools",
});
 
// create() resolves once the sandbox is running.
const box = await client.create({ name: "my-project" });
try {
  const { stdout } = await box.exec("uname -a");
  console.log(box.id, box.status, stdout);
} finally {
  await box.delete();
}

tangle sandbox create waits until the sandbox runs and prints its id, SSH line and URLs. It has no --no-wait flag. Its --timeout flag is the HTTP request timeout in milliseconds, not the sandbox lifetime.

Choose the image, isolation and size

OptionWhat it sets
nameA label you can use in place of the id in the CLI.
metadataYour own key-value tags. Filter and bulk-delete by them.
environmentThe image: a catalog environment, a template, or an image reference. See Templates and images.
runtime"docker" runs a container on a shared kernel; "firecracker" runs a microVM with its own kernel. Omit it for the platform default.
resources{ cpuCores, memoryMB, diskGB }. Omit it for the default shape.
baretrue gives command execution and lifecycle only, without the agent runtime.
agentfalse keeps files, terminals and processes but provisions no coding agent, model credentials or startup scripts. An enabled startup script that applies to the create makes it fail.
import assert from "node:assert/strict";
import { Sandbox } from "@tangle-network/sandbox";
 
const client = new Sandbox({
  apiKey: process.env.TANGLE_API_KEY!,
  baseUrl: "https://sandbox.tangle.tools",
});
 
const { presets, ceiling } = await client.shapes();
assert(presets.length > 0);
const box = await client.create({ agent: false, name: "build-runner", runtime: "firecracker", resources: { cpuCores: 4, memoryMB: 8192, diskGB: 20 }, metadata: { project: "checkout", ci: "true" }, maxLifetimeSeconds: 300 });
try {
  assert.equal(box.name, "build-runner");
  assert.equal(box.metadata?.project, "checkout");
  const result = await box.exec("uname -s");
  assert.equal(result.exitCode, 0, result.stderr);
  assert.equal(result.stdout.trim(), "Linux");
  console.log(presets.map((preset) => preset.name), ceiling, box.resources);
} finally {
  await box.delete();
}

The CLI takes the same choices as flags: --environment, --runtime, --cpu, --memory (MB), --disk (GB) and --metadata KEY=VALUE. tangle sandbox shapes lists the presets your account can use. The size ceiling for your plan is on Limits.

Retry a create safely

Pass an idempotencyKey when your code may retry. A second create with the same key joins the first provision instead of starting another sandbox.

import assert from "node:assert/strict";
import { Sandbox } from "@tangle-network/sandbox";
 
const client = new Sandbox({
  apiKey: process.env.TANGLE_API_KEY!,
  baseUrl: "https://sandbox.tangle.tools",
});
 
const idempotencyKey = `nightly-eval-${crypto.randomUUID()}`;
const box = await client.create({ agent: false, name: "nightly-eval", maxLifetimeSeconds: 300, idempotencyKey });
try {
  const same = await client.create({ agent: false, name: "nightly-eval", maxLifetimeSeconds: 300, idempotencyKey });
  assert.equal(same.id, box.id);
  console.log("Both requests returned", box.id);
} finally {
  await box.delete();
}

Both SDKs retry capacity and rate-limit refusals inside the create’s time budget. When the budget runs out, the timeout error names the key to retry with: retry create() with idempotencyKey="..." to join it in TypeScript, idempotency_key="..." in Python. Pass retry: { capacity: false } in TypeScript to get CAPACITY_EXHAUSTED at once and schedule the retry yourself.

Timers that stop or delete a sandbox

OptionWhat happens
maxLifetimeSecondsThe sandbox stops when the interval ends. Create and each resume start a new interval; activity does not extend it. The workspace is kept.
idleTimeoutSecondsThe sandbox stops after this much inactivity. The workspace is kept.
deleteAfterStoppedSecondsA stopped sandbox is deleted after this long. Omit it for the platform default.
import assert from "node:assert/strict";
import { Sandbox } from "@tangle-network/sandbox";
 
const client = new Sandbox({
  apiKey: process.env.TANGLE_API_KEY!,
  baseUrl: "https://sandbox.tangle.tools",
});
 
const box = await client.create({ agent: false, maxLifetimeSeconds: 300, idleTimeoutSeconds: 120, deleteAfterStoppedSeconds: 600 });
try {
  await box.refresh();
  assert.equal(box.status, "running");
  // The interval began before this point, so the lifetime stop comes no later than this.
  // Idle timeout or a stop can end it sooner.
  const stopsNoLaterThan = new Date(Date.now() + 300_000);
  const result = await box.exec("printf 'bounded lifetime\\n'");
  assert.equal(result.exitCode, 0, result.stderr);
  assert.equal(result.stdout.trim(), "bounded lifetime");
  // expiresAt is not reported yet; keep the deadline yourself.
  console.log("expiresAt", box.expiresAt ?? "not reported");
  console.log("stops no later than", stopsNoLaterThan.toISOString());
} finally {
  await box.delete();
}

The sandbox does not report its stop deadline yet: expiresAt stays empty even when you set maxLifetimeSeconds. To know the latest time it can run, note when create or resume returns and add the interval. maxLifetimeSeconds is a ceiling, not guaranteed uptime: the idle timeout or a stop can end the sandbox earlier.

The CLI flags are --lifetime and --idle-timeout, both in seconds. Defaults and allowed ranges are on Limits.

A stopped sandbox keeps its disk without charge and does not bill compute until you resume it. See Pricing.

Stop and resume

import { Sandbox } from "@tangle-network/sandbox";
 
const client = new Sandbox({
  apiKey: process.env.TANGLE_API_KEY!,
  baseUrl: "https://sandbox.tangle.tools",
});
 
// Stopped: the disk stays. Resumed: every file is there.
const box = await client.create();
try {
  await box.exec("echo 'first draft' > notes.md");
  await box.stop();
  await box.resume();
  const { stdout } = await box.exec("cat notes.md");
  console.log(stdout.trim());
} finally {
  await box.delete();
}

In TypeScript, stop() waits until the sandbox has stopped. stop({ wait: false }) returns a SandboxOperation once the stop is accepted; call await op.wait() or read it later with box.getOperation(op.id). stop({ retain: { paths: ["reports"] } }) seals the coding agent’s sessions and the listed workspace paths before it answers, and needs the default wait: true.

The SDK does not resume for you: a command on a stopped sandbox throws INVALID_STATE, so call resume() first. The CLI does: tangle exec, ssh, fs, git, process, run and agent prompt resume a stopped sandbox before they run. tangle sandbox stop --no-wait prints the operation id and its status URL.

After a resume

A coding agent’s credential does not survive a stop. Pass backend again on the first prompt after resume():

const again = await client.get(boxId);
if (!again) throw new Error("sandbox not found");
await again.resume();
const run = await again.prompt("Implement step 1 of your plan.", {
  sessionId: "oauth",
  backend,
});

A resume can also be refused because the platform did not keep some environment values. Branch on the error code and pass the values back:

import { SandboxError } from "@tangle-network/sandbox";
 
try {
  await box.resume();
} catch (error) {
  if (error instanceof SandboxError && error.code === "RESUME_ENV_REQUIRED") {
    const env = Object.fromEntries(
      (error.missingEnvKeys ?? []).map((key) => [key, process.env[key] ?? ""]),
    );
    await box.resume({ env });
  } else {
    throw error;
  }
}

box.rebuild() takes the same options as resume() and provisions the sandbox again from its stored config.

Find sandboxes

import assert from "node:assert/strict";
import { Sandbox } from "@tangle-network/sandbox";
 
const client = new Sandbox({
  apiKey: process.env.TANGLE_API_KEY!,
  baseUrl: "https://sandbox.tangle.tools",
});
 
const box = await client.create({ agent: false, maxLifetimeSeconds: 300 });
try {
  const again = await client.get(box.id);
  assert(again, "The created sandbox was missing from get()");
  assert.equal(again.id, box.id);
  const running = await client.list({ status: "running", limit: 20 });
  assert(running.some((item) => item.id === box.id));
  console.log(again.id, running.map((item) => item.id));
} finally {
  await box.delete();
}

list() filters by status (one or several), scope ("personal", "team", "all" or `team:${id}`), limit, offset and run. In the CLI, tangle sandbox list and tangle sandbox get <id-or-name>.

Delete

import assert from "node:assert/strict";
import { Sandbox } from "@tangle-network/sandbox";
 
const client = new Sandbox({
  apiKey: process.env.TANGLE_API_KEY!,
  baseUrl: "https://sandbox.tangle.tools",
});
 
const box = await client.create({ agent: false, maxLifetimeSeconds: 300 });
try {
  const ack = await box.delete();
  assert(["destroyed", "already_absent"].includes(ack.outcome));
  const removed = await box.delete({ until: "removed" });
  assert(["destroyed", "already_absent"].includes(removed.outcome));
  console.log(ack.outcome, removed.outcome);
} finally {
  await box.delete();
}

delete() resolves when the sandbox is gone and billing has stopped; removal reads "pending" until its storage is reclaimed. until: "removed" waits for that too.

A sandbox with live branch children is refused with 409 CHILDREN_EXIST. Delete the children first, or delete the whole lineage with cascade. box.delete() and tangle sandbox delete have no cascade option; use deleteMatching or the REST route:

import assert from "node:assert/strict";
import { Sandbox } from "@tangle-network/sandbox";
 
const client = new Sandbox({
  apiKey: process.env.TANGLE_API_KEY!,
  baseUrl: "https://sandbox.tangle.tools",
});
 
const runKey = `docs-${crypto.randomUUID()}`;
const box = await client.create({ agent: false, maxLifetimeSeconds: 300, metadata: { project: runKey } });
try {
  const result = await client.deleteMatching({ metadataPrefix: { project: runKey } }, { cascade: true });
  assert.equal(result.complete, true);
  assert.equal(result.sandboxes.length, 1);
  assert.equal(result.sandboxes[0].id, box.id);
  assert.equal(result.sandboxes[0].confirmed, true);
  console.log(result.complete, result.sandboxes[0].outcome);
} finally {
  await box.delete();
}
curl -X DELETE "https://sandbox.tangle.tools/v1/sandboxes/$SANDBOX_ID?cascade=true" \
  -H "Authorization: Bearer $TANGLE_API_KEY"

tangle sandbox delete asks for confirmation; pass --force in scripts. Deleting a sandbox does not remove its snapshots: ones in your own storage stay until you delete them, and ones the platform keeps for you stay for about 30 days and can be restored by the account owner. See What a delete keeps.

Python and REST

The Python SDK covers create, wait_for, get, list(ListSandboxOptions(status=...)), stop, resume and delete. It has no rebuild, lifecycle operations, env recovery or delete_matching, and its list has no scope or run filter. Its create options do not include delete_after_stopped_seconds, cold_timeout_seconds, retain or cwd. Send those through the REST API with client.fetch, which returns the raw response and does not raise on an error status:

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:
    created = client.fetch("POST", "/v1/sandboxes", json={"agent": False, "name": "nightly", "maxLifetimeSeconds": 300, "deleteAfterStoppedSeconds": 600})
    created.raise_for_status()
    sandbox_id = created.json()["id"]
    try:
        box = client.get(sandbox_id)
        assert box is not None
        box.wait_for(SandboxStatus.RUNNING)
        assert box.name == "nightly"
        print(created.status_code, box.id)
    finally:
        removed = client.fetch("DELETE", f"/v1/sandboxes/{sandbox_id}", params={"cascade": "true"})
        removed.raise_for_status()

The states a sandbox moves through are drawn in How sandboxes work.

Next