Upstash Box

Persistent Linux containers from Upstash that pause when idle and wake on the next request. Streamed exec over live sessions, PTY, native files, public URLs, filesystem snapshots and network policy (plus opt-in SSH), via @upstash/box.

Installation

@upstash/box is an optional peer dependency of sbox-sdk, imported lazily the first time you create or connect to a box. Commands run over WebSocket live sessions, so the adapter is Node-only.

pnpm add sbox-sdk @upstash/box

Usage

import { createSandboxClient } from "sbox-sdk";
import { upstashBox } from "sbox-sdk/upstash-box";

const client = createSandboxClient({
  provider: upstashBox({ apiKey: process.env.UPSTASH_BOX_API_KEY! }),
});

// Boxes can be named, so getOrCreate is native.
const sandbox = await client.getOrCreate({
  name: "agent-42",
  template: "node",
});

for await (const ev of sandbox.commands.run("npm install", {
  cwd: "/workspace/home",
})) {
  if (ev.type === "stdout") process.stdout.write(ev.data);
}

await sandbox.files.write("/workspace/home/state.json", '{"v":1}');
const ref = await sandbox.snapshots!.create({ name: "after-install" });

// Snapshots seed NEW boxes; they are not restored in place.
const copy = await client.create({ fromSnapshot: ref });

create() without a name but with an idempotency key derives a deterministic name (sbox-<hash>) and reuses that box on retry, so a retried create never makes a second box.

Authentication

OptionEnv varRequiredNotes
apiKeyUPSTASH_BOX_API_KEYyesFrom the Upstash Console, Box section
baseUrlUPSTASH_BOX_BASE_URLnoDefaults to https://us-east-1.box.upstash.com

client.verify() lists your account-level Box env vars (values come back masked); it never creates anything.

Options

Prop

Type

Spec mapping

SandboxSpec fieldUpstash Box
namebox name (Box.get resolves ids and names)
templateruntime: node, python, golang, ruby, rust or their -alpine variants
fromSnapshotBox.fromSnapshot
env, secrets (inline value)box env
metadatalabels, encoded as key:value (at most 5, 20 characters each)
resourcessmallest fitting size: small 2 vCPU/4 GB, medium 4/8, large 8/16
networknetwork policy; inject becomes attachHeaders
regionmust be us-east-1
idempotencyKeydeterministic box name when name is omitted
lifecycle.onIdle: "pause" or "stop"accepted: Box pauses idle boxes itself, keeping the disk (rejected with keepAlive)
lifecycle.maxAgeMs, idleTimeoutMs, autoResume: false, onIdle: "destroy", volumes, GPUs, built templates, secrets without a valuerejected with a Validation error

Lifecycle and states

A box pauses itself when idle: the disk persists, running processes stop, and the next request (exec, file call or preview URL hit) wakes it. sandbox.pause() and sandbox.resume() do the same thing explicitly. Set keepAlive: true in the provider options to keep new boxes running (billed at a flat monthly rate by Upstash). Keep-alive boxes can't be paused, so pause() and resume() throw a Validation error on them.

Box statusSandboxState
creatingcreating
idle, runningrunning
pausedpaused
errorerror
deleteddestroyed

Previews and browser auth

ports.expose(port) creates a public URL, https://<box-id>-<port>.preview.box.upstash.com. With { visibility: "private" } the URL requires a bearer token, and the preview carries auth: { type: "header", headers: { Authorization: "Bearer <token>" } }. Browsers can't send that header on a WebSocket, so previewBrowserAuth is false. ports.unexpose(port) deletes the URL.

A sandbox created with previewVisibility: "private" makes every ports.expose() private, since the core can't tell an omitted visibility from an explicit "public".

Box returns a bearer token only when the URL is created, and asking again issues a new token, which breaks anyone using the old one. So the adapter:

  • keeps the private previews a handle created, and returns them from ports.list() and repeat expose() calls without rotating the token;
  • leaves out of ports.list() any protected URL whose token the handle doesn't hold;
  • throws Conflict instead of rotating when asked to privately expose such a port (for example from ports.fetch() on a reconnected handle). Call ports.unexpose(port) first to issue a new token deliberately.

SSH (experimental, opt-in)

SSH is off by default: the ssh capability is unsupported and sandbox.ssh is undefined. Box SSH logs in with your account API key as the password, so the credentials grant access to your whole Box account, not just one box. Turn it on only when the caller owns the key:

const client = createSandboxClient({
  provider: upstashBox({
    apiKey: process.env.UPSTASH_BOX_API_KEY!,
    experimentalSsh: true,
  }),
});
const sandbox = await client.getOrCreate({ name: "agent-42" });
const { command, password } = await sandbox.ssh!.create();
// command: ssh <box-id>@us-east-1.box.upstash.com, password: your API key

To avoid sharing the key, add an SSH key in the Upstash Console and connect with ssh -i.

Capabilities

CapabilityLevelNotes
listnativefirst metadata label filtered server-side, the rest client-side
streaming / stdinnativelive sessions, stdout and stderr kept separate
background / killProcessnativeprocesses spawned from the same handle
ptynativeTTY live session; not reattachable
filesUploadnativebase64 file API, binary-safe
codeInterpreternativestateless exec.code for python, js, ts
exposePort / privatePreviewnativeper-port public URLs; bearer-token auth
egressControlnativeallow-all, deny-all, or domain/CIDR allow-list
sshunsupportedopt-in with experimentalSsh: true; the password is the API key
pausenativedisk kept, processes stopped
snapshotnativefilesystem only; seeds new boxes, not restorable in place
forkemulatedsnapshot, boot N boxes with the source's network policy, then delete the snapshot
stop / setTimeoutunsupporteduse pause
filesWatch / statefulKernelunsupported
templateBuild / volumes / gpu / regionunsupportedfixed runtimes in us-east-1
proxiedFetch / metrics / secretsVaultunsupported

Flags: perCommandEnvCwd: true, exitCodeNative: true, preservesMemoryOnPause: false, preservesDiskOnStop: true, previewModel: "subdomain", previewBrowserAuth: false, templateSources: [].

Known limitations

  • Node-only, because live sessions authenticate on the WebSocket handshake.
  • user in ExecOptions / PtyOptions is rejected; commands run as boxuser, so prefix sudo when you need root.
  • commands.run({ timeoutMs }) is enforced by the core, which kills the session.
  • killProcess and commands.list() only see processes spawned from the current handle; live sessions can't be reattached after a reconnect.
  • Pausing (manual or idle) stops running processes, including PTYs and background commands.
  • snapshots.restore() is not available; boot a new box with fromSnapshot instead.
  • setEgressPolicy cannot change injected headers after creation.
  • fork() copies the filesystem and the network policy, but not box-level env or injected headers (Box never returns them). If any child fails to boot, the others are deleted and the fork throws.
  • A command whose signal is already aborted is never started.

On this page