TypeScript SDK
The TypeScript SDK wraps the REST API. It runs on Node 18 or later and in other runtimes with fetch, and results use
camelCase field names.
Install
Section titled “Install”npm install @vivarium/sdkCreate a client
Section titled “Create a client”import { Vivarium } from "@vivarium/sdk";
const vv = new Vivarium({ apiKey: process.env.VIVARIUM_API_KEY, baseUrl: "https://api.wardcase.com" });| Option | Meaning |
|---|---|
apiKey | Your API key. Defaults to the VIVARIUM_API_KEY environment variable. |
baseUrl | The API to call, https://api.wardcase.com. Defaults to https://api. followed by the VIVARIUM_DOMAIN environment variable. With neither set, the constructor throws. |
maxRetries | Retries for 429, 502, 503, network errors and, on idempotent calls, other 5xx responses. Default 3. |
timeoutMs | Timeout per request in milliseconds. Default 60000. Commands and file transfers get longer ones. |
Keep API keys on servers. A key in browser code is visible to anyone who loads the page.
Create a sandbox
Section titled “Create a sandbox”// Resolves once the sandbox is running.const sbx = await vv.sandboxes.create({ image: "python", size: "small", region: "eu-west", idleTimeoutS: 600,});console.log(sbx.id); // sbx_4f9k2m8q1z7x3c5vcreate resolves once the sandbox is running, and throws if it ends up in any other state. Pass wait: false to get
it back while it is still creating. The options are the fields of POST /v1/sandboxes in camelCase: image,
size, region, idleTimeoutS, hardTimeoutS, egressPolicyId, env, metadata and snapshotId. The SDK sends
an Idempotency-Key on every create, so a retried request never makes two sandboxes. See
Sandboxes for what each option does.
Run commands
Section titled “Run commands”const result = await sbx.run("python -c 'print(sum(range(10)))'", { timeoutS: 60 });console.log(result.exitCode, result.stdout.trim(), result.durationMs); // 0 45 ...A string runs through /bin/sh -c; an array is an argument list with no shell. The result has exitCode, stdout,
stderr, durationMs, truncated (true when the output passed 10 MiB and was cut)
and timedOut. A non-zero exit code is a result, not an error. timeoutS defaults to 300
seconds and can be up to 3600. Commands run in /work unless you
pass cwd.
Pass onStdout and onStderr to receive output while the command runs:
await sbx.run("pip install requests", { timeoutS: 300, onStdout: (chunk) => process.stdout.write(chunk), onStderr: (chunk) => process.stderr.write(chunk),});await sbx.files.write("/work/app.py", "print('hello')\n");const bytes = await sbx.files.read("/work/app.py"); // Uint8Arrayconsole.log(new TextDecoder().decode(bytes));const entries = await sbx.files.list("/work");Paths must be under /work, the sandbox’s writable volume; relative paths are resolved against it. write takes a
string, Uint8Array, ArrayBuffer, Blob or ReadableStream, creates parent directories, and accepts files up to
50 MiB. read returns a Uint8Array. list returns entries with name, path, type,
size, mode and mtime.
Expose a port
Section titled “Expose a port”// Start a server that listens on all interfaces, then expose its port.await sbx.run("nohup python -m http.server 8000 --bind 0.0.0.0 > /tmp/http.log 2>&1 &");const { url } = await sbx.expose(8000, { access: "public" });console.log(url); // https://8000-4f9k2m8q1z7x3c5v.wardcase.com
// Token access (the default) returns the token once.const { url: privateUrl, token } = await sbx.expose(8080);await sbx.unexpose(8080);expose returns the exposure with its url, and with token access its token, which the API shows only once. The
API’s default access is token. See Port exposure.
const ssh = await sbx.sshCommand();console.log(ssh.command); // ssh sbx_4f9k2m8q1z7x3c5v@ssh.wardcase.com// ssh.token is the password. It expires at ssh.expiresAt.sshCommand() mints a short-lived token and returns command, username, host, port, token and expiresAt.
Run the command and use the token as the password. See SSH access.
Snapshots
Section titled “Snapshots”// Resolves once the snapshot is ready.const snap = await sbx.snapshot({ name: "deps-installed" });const copy = await vv.sandboxes.create({ snapshotId: snap.id, region: "eu-west" });const snaps = await vv.snapshots.list({ sandboxId: sbx.id });snapshot() saves /work and resolves once the snapshot is ready, or pass wait: false. Create a new sandbox
from it with snapshotId. vv.snapshots.list() takes an optional sandboxId, and vv.snapshots.get(id) reads one.
Audit trail
Section titled “Audit trail”const page = await sbx.audit.list({ type: "exec." });for (const event of page.data) console.log(event.type, event.payload);
// Resolves once the export is ready.const exported = await vv.audit.export({ sandboxId: sbx.id });console.log(exported.url); // signed JSONL download, valid for one hoursbx.audit.list() returns a page of the sandbox’s events with data and nextCursor. vv.audit.list() does the same
across the organization with sandboxId, type, since and until filters. vv.audit.export() takes sandboxId,
since, until and types, and resolves once the export is ready, or pass wait: false.
Keep alive and refresh
Section titled “Keep alive and refresh”await sbx.keepalive(); // reset the idle timerconst info = await sbx.refresh(); // reload status and timestampsconsole.log(info.status, info.expiresAt);Account and usage
Section titled “Account and usage”const me = await vv.me(); // org, scopes of this keyconst usage = await vv.usage({ groupBy: "sandbox" });console.log(me.org.name, usage.totals.estimatedUsd);Destroy
Section titled “Destroy”await sbx.kill();kill() returns at once. The status moves to stopping, then stopped.
Errors and retries
Section titled “Errors and retries”Failed requests throw VivariumError, which carries the problem document’s status, type, title,
detail and instance, plus code, the problem slug such as free-tier-limit. See Errors. The SDK retries
429, 502, 503, network errors and, on idempotent calls, other 5xx responses on its own, waiting as long as Retry-After says.
import { VivariumError } from "@vivarium/sdk";
try { await vv.sandboxes.create({ image: "python", size: "large", region: "eu-west" });} catch (err) { if (err instanceof VivariumError) { // err.code is the problem slug, for example "free-tier-limit". console.error(err.status, err.code, err.detail); } throw err;}