StrataBox JavaScript / TypeScript SDK (@stratabox/sdk)
Official zero-dependency TypeScript/JavaScript SDK for StrataBox — high-density composable elastic sandboxes for agentic RL and large-scale evaluation.

English | 简体中文
Highlights
- Zero Runtime Dependencies: Built purely on native Node 20+
fetch (including duplex: "half" request streaming), node:zlib, node:fs/promises, and a built-in pure-TypeScript POSIX USTAR + PAX .tar.gz packer & security-hardened two-pass safe extractor.
- Dual ESM + CJS with Full
.d.ts Declarations: Ships native ESM (dist/esm/index.js), CommonJS (dist/cjs/index.cjs), and strict TypeScript declarations (index.d.ts / index.d.cts).
- Zero-Arg Env Resolution & Managed Local Clusters:
new StrataBoxClient() automatically resolves STRATABOX_ENDPOINT (default http://127.0.0.1:18080) and STRATABOX_TOKEN (default "stratabox-root-token"). Use await localCluster() to auto-discover stratabox-daemon / static musl stratabox-agent and spin up a local multi-edge cluster in one line.
- Native Explicit Resource Management (
await using): StrataBoxClient, Sandbox, SandboxGroup, and LocalCluster all implement [Symbol.asyncDispose]() for deterministic automatic teardown in TypeScript 5.2+ and modern Node runtimes.
- 100% StrataBox Wire Protocol Parity:
- Unified
runSandbox plus backend-specific runContainer, runMicroVm, runVm, VM snapshots & cloning (createSnapshot, listSnapshots, getSnapshot, deleteSnapshot, cloneSnapshot), and stateless runFnCall (with env, returnWorkspaceFiles, and decoded outputFiles).
- Full run-arg support:
initDirs, cpuMillicores, scratchQuotaMb, dnsServers, applyOciConfig, idleAutoPauseMs, fromSnapshotId, and snapshotRestoreMode.
- Bounded-concurrency
SandboxGroup rollouts (runContainerGroup, runMicroVmGroup, runVmGroup, runSandboxGroup) with automatic rollback (cleanupOnError: true) and batch runShellAll (forwarding full exec metadata with broadcast or per-sandbox arrays), writeFileAll, refreshAll, updateNetworkRulesAll, listModifiedFilesAll, pauseAll, resumeAll, stopAll / close.
- Composable immutable layer management (
uploadLayer, streaming O(1)-RAM uploadLayerStream, importOciLayer, listLayers, getLayer, layerExists, deleteLayer) with LayerInfo.ociConfig.
- Full sandbox data-plane API: multi-session stateful
runShell with idempotent replay, AsyncGenerator streamShell + streamKill, auto-chunked writeFile / auto-paginated readFile, disk-streaming uploadFilePath / downloadFilePath, writeFiles, uploadTar, Zip-Slip-safe downloadTar / downloadDir, listFiles, statFile, deleteFile, listModifiedFiles, in-sandbox httpRequest, pause/resume, packDiff, and hot updateNetworkRules.
- Hierarchical IAM & fleet control APIs (
createProject, getProject, updateProjectQuotas, issueToken, getFleet / getFleetSnapshot with FnCall & host resource telemetry, registerEdge, selectPlacement).
- Production Resilience: Equal-jitter exponential backoff on
429 / 503 + Retry-After (seconds and HTTP-date) + AbortSignal cancellation + typed StrataBoxError subclasses (including distinct TransportTimeoutError vs server-side TimeoutError, UnsafeArchiveError, and StrataBox*Error aliases).
Installation
npm install @stratabox/sdk
Requires Node.js >= 20.0.0.
Quick Start
1. Run a Stateful Container Sandbox (Zero-Arg Client + await using)
import { StrataBoxClient, QoSClass } from "@stratabox/sdk";
// Automatically reads STRATABOX_ENDPOINT (default http://127.0.0.1:18080)
// and STRATABOX_TOKEN (default "stratabox-root-token")
await using client = new StrataBoxClient();
await using sbx = await client.runContainer({
baseLayer: "base:default",
workspaceLayers: ["ws/swe-repo:v1"],
memoryLimitMb: 512,
cpuMillicores: 1500,
scratchQuotaMb: 2048,
qosClass: QoSClass.LS,
idleAutoPauseMs: 30_000,
initDirs: ["/logs/agent", "/artifacts"],
});
// Multi-session stateful shell execution
await sbx.runShell("cd /workspace && export MODE=eval", { sessionId: "agent" });
const res = await sbx.runShell("pwd && echo $MODE", { sessionId: "agent" });
console.log(res.ok, res.stdout);
// Batch file write + OverlayFS upperdir diff audit
await sbx.writeFiles({
"/workspace/patch.py": "print('patched')\n",
"/logs/agent/run.log": "step 1 ok\n",
});
const modified = await sbx.listModifiedFiles();
console.log(modified); // [{ path: "/workspace/patch.py", change: "added", ... }, ...]
// Download & safely extract directory (strict Zip-Slip / symlink / FIFO protection)
await sbx.downloadDir("/logs/agent", "./local-agent-logs");
// Pause to reclaim memory; next runShell transparently auto-resumes!
await sbx.pause();
const afterPause = await sbx.runShell("python3 /workspace/patch.py");
console.log(afterPause.autoResumed, afterPause.stdout);
// `sbx` is automatically stopped when leaving scope!
2. Zero-Boilerplate Local Cluster (localCluster())
import { localCluster } from "@stratabox/sdk";
// Auto-discovers stratabox-daemon and static musl stratabox-agent, binds an ephemeral port,
// and cleanly terminates the daemon + temp files on scope exit.
await using cluster = await localCluster({ edges: 2 });
await using sbx = await cluster.client.runContainer({ memoryLimitMb: 256, cpuCoresLimit: 1 });
const out = await sbx.runShell("echo hello from local cluster");
console.log(out.stdout.trim());
3. Batch RL Rollouts with SandboxGroup
import { StrataBoxClient } from "@stratabox/sdk";
await using client = new StrataBoxClient();
// Homogeneous group of 16 sandboxes with bounded concurrency & rollback on partial error
await using group = await client.runContainerGroup(
{ baseLayer: "base:default", memoryLimitMb: 256, cpuCoresLimit: 1 },
16,
{ concurrency: 8, cleanupOnError: true },
);
// Broadcast or per-sandbox files, shell exec with rollout metadata, and firewall updates
await group.writeFileAll("/workspace/task.txt", "eval-input", { concurrency: 8 });
const results = await group.runShellAll(
group.map((_, i) => `echo rollout-${i}`),
{
rolloutId: group.map((_, i) => `rollout-${i}`),
stepSeq: 1,
concurrency: 8,
returnExceptions: true,
},
);
await group.updateNetworkRulesAll({ pypi: false, npm: false });
const diffs = await group.listModifiedFilesAll();
await group.pauseAll({ concurrency: 8 });
// `group.stopAll()` / `group.close()` runs automatically on scope exit!
4. Stateless FnCall Fast Path
const out = await client.runFnCall({
language: "python",
code: "import helper, os, sys\nopen('out.txt', 'w').write(os.environ['TAG'])\nprint(helper.mul(int(sys.stdin.read()), 7))",
files: { "helper.py": "def mul(a, b): return a * b\n" },
env: { TAG: "v1" },
stdin: "6\n",
useWarmPython: true,
returnWorkspaceFiles: true,
});
console.log(out.stdout.trim(), out.warmHit, out.outputFiles["out.txt"]);
5. Immutable Layer Streaming Upload & OCI Import
import { LayerKind } from "@stratabox/sdk";
if (!(await client.layerExists("ws/my-repo:v1"))) {
// Packs local directory directly in pure TypeScript (zero dependencies!)
const layer = await client.uploadLayer("ws/my-repo:v1", "./local-repo-dir", {
kind: LayerKind.WORKSPACE,
overwrite: false,
});
console.log(layer.layerId, layer.sha256, layer.sizeBytes);
}
// Stream large `.tar.gz` files, ReadableStreams, or AsyncIterables in O(1) RAM
const streamed = await client.uploadLayerStream("ws/large:v1", "./large-rootfs.tar.gz", {
kind: LayerKind.WORKSPACE,
format: "rootfs_tar",
});
// Import an OCI image directly on edge nodes
const base = await client.importOciLayer("base/python:3.12", "docker:python:3.12-slim");
console.log(base.ociConfig?.workingDir, streamed.sizeBytes);
6. Interactive Streaming Shell (AsyncGenerator) & Cancellation
import { StreamChannel } from "@stratabox/sdk";
for await (const frame of sbx.streamShell("python3 -u script.py", {
stdin: "hello\n",
stdinEof: true,
killOnCancel: true, // automatically calls streamKill() if loop breaks early or times out
})) {
if (frame.channel === StreamChannel.STDOUT) process.stdout.write(frame.text);
if (frame.channel === StreamChannel.STDERR) process.stderr.write(frame.text);
if (frame.channel === StreamChannel.EXIT) console.log("exit:", frame.exitCode);
}
7. CommonJS Usage
const { StrataBoxClient, parseSandboxId } = require("@stratabox/sdk");
async function main() {
const client = new StrataBoxClient(); // http://127.0.0.1:18080 by default
const health = await client.healthz();
console.log(health, parseSandboxId("stratabox-edge-01-ctr-abc123"));
await client.close();
}
main();
Configuration & Error Handling
StrataBoxClient Options
| Option |
Type |
Default |
Description |
endpoint |
string |
STRATABOX_ENDPOINT or "http://127.0.0.1:18080" |
Control-plane ingress base URL |
token |
string |
STRATABOX_TOKEN or "stratabox-root-token" |
Bearer token ("" disables Authorization header) |
timeoutMs |
number |
60000 |
Default HTTP request timeout (ms) |
maxRetries |
number |
4 |
Max retry attempts for retryable statuses / transport errors |
retryBaseDelayMs |
number |
50 |
Equal-jitter exponential backoff base delay (ms) |
retryMaxDelayMs |
number |
2000 |
Equal-jitter exponential backoff max cap (ms) |
retryStatuses |
readonly number[] |
[429, 503] |
HTTP status codes retried automatically (Retry-After honored) |
fetch |
typeof fetch |
globalThis.fetch |
Optional custom fetch implementation |
headers |
Record<string, string> |
{} |
Extra default headers merged into all requests |
Typed StrataBoxError Hierarchy
All error classes also export StrataBox*Error aliases (e.g. StrataBoxTransportTimeoutError, StrataBoxNotFoundError).
| Error Class |
Wire ErrorCode |
HTTP Status |
Notes |
InvalidArgumentError |
INVALID_ARGUMENT |
400 |
Malformed request or argument |
InvalidSandboxIdError |
INVALID_ARGUMENT |
400 |
Subclass of InvalidArgumentError |
UnsafeArchiveError |
INVALID_ARGUMENT |
400 |
Subclass of InvalidArgumentError (Zip-Slip / unsafe tar member) |
UnauthorizedError |
UNAUTHORIZED |
401 |
Missing, invalid, or expired token |
ForbiddenError |
FORBIDDEN |
403 |
Insufficient IAM permission or scope |
NotFoundError |
NOT_FOUND |
404 |
Unknown sandbox, layer, snapshot, project, or path |
AlreadyExistsError |
ALREADY_EXISTS |
409 |
Layer/resource conflict (overwrite: false) |
QuotaExceededError |
QUOTA_EXCEEDED |
429 |
Hierarchical IAM quota exceeded |
InternalError |
INTERNAL |
500 |
Internal server error |
TransportError |
INTERNAL |
503 |
Subclass of InternalError (client network failure) |
TransportTimeoutError |
TIMEOUT |
504 |
Subclass of TransportError (client HTTP timeout; distinct from TimeoutError) |
SandboxFailedError |
SANDBOX_FAILED |
502 |
Sandbox crashed or channel disconnected |
ResourceExhaustedError |
RESOURCE_EXHAUSTED |
503 |
Edge capacity saturated (isPlacementRetryable === true) |
TimeoutError |
TIMEOUT |
504 |
Server-side command/boot/proxy timeout exceeded |
Development & Testing
# Install TypeScript devDependencies
npm install
# Build dual ESM + CJS + .d.ts outputs
npm run build
# Run offline unit, mock-server, tar security, LocalCluster, and CJS smoke tests
npm test
# Run live E2E tests against a running StrataBox cluster
STRATABOX_ENDPOINT=http://127.0.0.1:18080 STRATABOX_TOKEN=stratabox-root-token npm run test:live
License
Dual-licensed under either of:
- MIT License
- Apache License, Version 2.0
at your option. Copyright (c) 2026 veralbor <openstrata@gmail.com>.