JS SDK reference
The orkestr npm package is the official client for the sandbox API. TypeScript-first with a flat .d.ts. Ships dual ESM and CJS builds and works on any runtime with native fetch - Node 18+, Bun, Deno, Cloudflare Workers, browser.
npm install orkestr, then enable them in one click from the Sandboxes console and mint a scoped token.Install
npm install orkestr
# or
pnpm add orkestr
# or
yarn add orkestrAuthentication
Every request is authenticated with a Bearer API token. The SDK looks for it in three places, in order:
- The
apiKeyoption onSandbox.create()etc. - A pre-built default client set via
setDefaultClient() - The
ORKESTR_API_KEYenvironment variable
import { Sandbox, OrkestrClient } from "orkestr";
// 1) Implicit: SDK reads ORKESTR_API_KEY from process.env
const sbx = await Sandbox.create({ template: "python-3.12" });
// 2) Explicit: per-call apiKey
const sbx2 = await Sandbox.create({
template: "python-3.12",
apiKey: "ork_...",
});
// 3) Reusable client (good for long-running agents)
import { setDefaultClient } from "orkestr";
setDefaultClient(new OrkestrClient({
apiKey: "ork_...",
baseUrl: "https://api.orkestr.eu",
}));sandboxes:read and sandboxes:write for agent runtimes. A scoped token cannot reach the rest of the orkestr platform if it leaks.Sandbox class
Sandbox is the main public class. Static methods create / fetch / list / resume sandboxes; instance methods drive exec, files, and lifecycle. All async.
Sandbox.create
import { Sandbox } from "orkestr";
const sbx = await Sandbox.create({
template: "python-3.12",
size: "small",
network: "off",
timeoutSeconds: 600,
env: { OPENAI_API_KEY: "sk-..." },
metadata: { agentRun: "r_42" },
region: "fsn1",
});
console.log(sbx.id, sbx.status);Field names are camelCase. The SDK converts to snake_case on the wire so request bodies match the REST schema.
| Parameter | Type | Description |
|---|---|---|
| templaterequired | Template | A built-in - python-3.12, python-3.12-bare, node-22, debian-12 - or a custom template id (tmpl_...) with your dependencies preinstalled. |
| size | SandboxSize | Fixed size: "small" (1 vCPU / 1 GB), "medium" (2 vCPU / 4 GB) or "large" (4 vCPU / 8 GB). Default "small". Tier-capped (free: small; payg and enterprise: small, medium, large). |
| network | NetworkMode | "off" (default), "restricted", or "open". |
| timeoutSeconds | number | Sandbox auto-terminates after this many seconds. Default 600. |
| env | Record<string, string> | Environment variables exposed to processes in the sandbox. |
| metadata | Record<string, string> | Caller-defined tags echoed back on every response. Max 16 keys, 256 chars per value. |
| region | string | Region preference, e.g. "fsn1". The current list is regions from Sandbox.limits(). Omit to let the control plane pick. |
| allowDomains | string[] | For network: "restricted" only (paid plans): a custom egress allowlist that replaces the default set for this sandbox - still HTTPS-only and proxy-mediated. Pass bare hostnames (subdomains matched automatically) and keep any package registries you need. Sandbox.limits() returns the default set. Ignored for off/open. |
| volume | string | Attach a persistent volume by name (or vol_ id), mounted at /persist. Data written there survives terminate and returns when a later sandbox attaches the same volume - unlike /workspace (RAM, lost on terminate). Created on first use (default 10 GB). See Persistent volumes. |
| apiKey | string | Override the API key for this call. Falls back to default client / env var. |
| baseUrl | string | Override the API base URL for this call. |
tmpl_...) to boot from an image with your dependencies baked in - same call, no install at boot. The SDK consumes templates; you build them from the console, REST API, or MCP. See the Custom templates guide.Sandbox.get and Sandbox.list
// Reattach from another process
const sbx = await Sandbox.get("sbx_01HXYZ...");
// List your sandboxes
const running = await Sandbox.list({ status: "running" });
for (const sbx of running) {
console.log(sbx.id, sbx.template, sbx.createdAt);
}Sandbox.limits
const limits = await Sandbox.limits();
limits.plan; // "free"
limits.allowedSizes; // ["small"]
limits.allowedSizes.includes("medium"); // false
limits.maxConcurrent; // 1
limits.usageGbHoursUsed; // 2.5 (memory used of the trial)
limits.usageGbHoursIncluded; // 10.0 (one-time trial allowance)
limits.usageCpuHoursUsed; // 0.42 (CPU used of the trial)
limits.usageCpuHoursIncluded; // 2.0 (one-time trial allowance)
limits.usageResetsAt; // null - the trial does not reset
for (const s of limits.sizes) { // full menu, each with .allowed
console.log(s.size, s.cpu, s.memoryMb, s.allowed);
}Sandbox.limits reports the sizes and caps available to your API key's plan - pick a size up front instead of learning the limit from a rejected create. Useful when the same code runs under keys on different plans.
sbx.exec
Run a shell command and resolve with the buffered result. Throws ExecTimeout if the command exceeds timeoutSeconds.
const result = await sbx.exec("python /workspace/main.py", {
timeoutSeconds: 60,
});
result.stdout; // string
result.stderr; // string
result.exitCode; // number
result.durationMs; // numbersbx.execStream
Async iterable that yields chunks as they arrive. The final chunk carries exitCode and durationMs; chunks before it carry process output. Iterate to completion - breaking early leaves the in-VM process running until its own timeout fires.
for await (const chunk of sbx.execStream("python long_task.py")) {
if (chunk.stream === "stdout") {
process.stdout.write(chunk.data);
} else {
process.stderr.write(chunk.data);
}
if (chunk.exitCode !== undefined) {
console.log(`exit=${chunk.exitCode} duration=${chunk.durationMs}ms`);
}
}Files namespace
sbx.files is the file operations namespace. All methods are async. Writes go to writable roots; reads work anywhere readable inside the sandbox.
// Text I/O
await sbx.files.write("/workspace/script.py", "console.log('hi')");
const content = await sbx.files.read("/workspace/output.txt");
// Binary I/O
await sbx.files.writeBytes(
"/workspace/blob.bin",
new Uint8Array([0, 1, 2]),
);
const raw = await sbx.files.readBytes("/workspace/blob.bin");
// Directory listing
for (const entry of await sbx.files.list("/workspace")) {
console.log(entry.name, entry.isDir, entry.size, entry.mode);
}
// Remove
await sbx.files.delete("/workspace/output.txt");Persistent volumes
/workspace is fast scratch, but it is RAM-backed and gone when the sandbox terminates. To keep data across sandboxes, attach a persistent volume - a named disk mounted at /persist. Anything written there survives terminate and comes back when a later sandbox attaches the same volume. Name a volume in Sandbox.create({ volume }) and it is created on first use (default 10 GB).
import { Sandbox, Volume } from "orkestr";
// Attach a volume by name - created on first use (default 10 GB).
// Anything under /persist survives terminate.
let sbx = await Sandbox.create({ template: "python-3.12", volume: "my-cache" });
await sbx.exec("echo trained-weights-v1 > /persist/model.txt");
await sbx.terminate();
// A brand-new sandbox re-attaches the same volume and sees the data:
sbx = await Sandbox.create({ template: "python-3.12", volume: "my-cache" });
console.log((await sbx.exec("cat /persist/model.txt")).stdout); // trained-weights-v1
// Manage volumes explicitly (custom size, a region pin, listing, cleanup):
const vol = await Volume.create("datasets", { sizeGb: 50, region: "rbx" });
for (const v of await Volume.list()) console.log(v.name, v.sizeMb, v.status, v.region);
await Volume.move(vol.id, "hel1"); // re-home a detached volume to another region
await Volume.delete(vol.id); // rejected while attached to a running sandboxA volume backs one running sandbox at a time (attaching a busy one throws volume_in_use), and attaching one pins the sandbox to the volume's host - pass the same (or no) region.
sbx.metrics
Live CPU and memory for the sandbox - the latest reading, a rolling ~60s sample window for sparklines, and the sandbox's lifetime totals. Use it to watch a workload for saturation or memory pressure without instrumenting the workload itself. cpu.usagePercent is the share of allocated cores; memory.usageBytes is the working set (reclaimable cache excluded).
const m = await sbx.metrics();
m.sandboxStatus; // "running" (usage is null when paused / terminated)
m.cpu.cores; // 1.0
m.cpu.usagePercent; // 94.0 (% of allocated cores; 1-core pegged = 100)
m.cpu.usageCores; // 0.94 (cores in use)
m.memory.usageBytes; // 188743680 (working set, excludes reclaimable cache)
m.memory.usagePercent; // 35.2 (% of m.memory.limitBytes)
m.lifetime.cpuSeconds; // 12.84 (on-CPU seconds since the sandbox started)
for (const s of m.samples) { // rolling ~60s window, oldest first
console.log(s.t, s.cpuPercent, s.memBytes);
}It is telemetry, not a state change: a paused or terminated sandbox resolves with null live usage (check sandboxStatus), not a throw. Pass { since: Date } to fetch only samples newer than your last poll, and poll no faster than sampleIntervalSeconds.
sbx.getHost
Return a public hostname for an HTTP port a process in the sandbox is serving. Build the URL as `https://${await sbx.getHost(3000)}` and open it in a browser or embed it in your app for a live preview of a dev server running inside the sandbox. The URL is public - its only capability is the unguessable sandbox id in the hostname - stable for the sandbox's lifetime, but serves traffic only while the sandbox is running. WebSockets ride through, so dev-server HMR works.
const sbx = await Sandbox.create({ template: "node-22", network: "open" });
// Start a server inside the sandbox (here, in the background):
await sbx.exec("nohup python3 -m http.server 3000 >/tmp/srv.log 2>&1 &");
const host = await sbx.getHost(3000); // "3000-01hxyz....sbx.orkestr.run"
const url = `https://${host}`; // open in a browser or embed it in your appRequires a card on file (paid tier) and a networked sandbox (network: "restricted" or "open"); an off sandbox has no port to expose. See Networking & egress for the URL format and caveats.
sbx.pause and Sandbox.resume
pause() snapshots the sandbox and stops the compute meter. Returns the sandbox id - persist it wherever your agent keeps state and pass to Sandbox.resume() when you want to come back.
// Pause: returns the sandbox id, stops compute meter
const sandboxId = await sbx.pause();
// ... later ...
const resumed = await Sandbox.resume(sandboxId);Sandbox.withTemp
Convenience wrapper that creates a sandbox, runs your callback, and terminates the sandbox - even if the callback throws. Use this for short-lived "do one thing" loops; otherwise call terminate() yourself.
import { Sandbox } from "orkestr";
await Sandbox.withTemp({ template: "python-3.12" }, async (sbx) => {
const result = await sbx.exec("python -c 'print(2+2)'");
console.log(result.stdout);
});
// terminate() is awaited automatically on return, including on thrown errorsResult types
All result types are flat objects. ExecResult has stdout, stderr, exitCode, durationMs. ExecChunk has stream, data, plus exitCode and durationMs on the final chunk only. FileEntry has name, isDir, size, mode, modifiedAt (a Date).
Errors
Every error the SDK throws extends OrkestrError. Use instanceof to dispatch.
import {
Sandbox,
OrkestrError,
AuthError,
ExecTimeout,
SandboxNotFound,
SnapshotCapReached,
} from "orkestr";
try {
const sbx = await Sandbox.create({ template: "python-3.12" });
await sbx.exec("sleep 9999", { timeoutSeconds: 5 });
} catch (err) {
if (err instanceof ExecTimeout) {
console.log("Command timed out; sandbox is still running.");
} else if (err instanceof AuthError) {
console.error(`Auth failed (${err.statusCode}): ${err.detail}`);
} else if (err instanceof OrkestrError) {
console.error(`Other failure: ${err.message} requestId=${err.requestId}`);
} else {
throw err;
}
}| Parameter | Type | Description |
|---|---|---|
| AuthError | OrkestrError | API key missing, invalid, expired, or scope insufficient. 401 / 403. |
| RateLimitError | OrkestrError | Plan rate limit hit. retryAfter attribute carries the recommended wait. |
| PlanLimitError | OrkestrError | Sandbox tier limit hit. |
| SnapshotCapReached | PlanLimitError | pause() blocked because the snapshot retention cap is full. |
| SandboxNotFound | OrkestrError | Sandbox id doesn't exist or doesn't belong to the caller. 404. |
| SandboxNotReady | OrkestrError | Operation called on a sandbox in the wrong state (e.g. exec on paused). 409. |
| ExecTimeout | OrkestrError | exec exceeded timeoutSeconds. |
| ExecKilled | OrkestrError | Exec process exited via a signal. signal attribute carries the signal number. |
| NetworkPolicyError | OrkestrError | In-sandbox code tried to reach a host blocked by the network policy. |
| ConnectionError | OrkestrError | Transport-level failure reaching api.orkestr.eu (DNS, TCP, timeout before bytes). |
Field naming
The REST API uses snake_case; this SDK exposes camelCase to feel native to JS code. The client converts at the boundary - request bodies and query params, response fields, and error details are all rewritten for you. Field names in this reference match what you see in your IDE.
Versioning
SDK versioning follows Semantic Versioning. The SDK targets the v1 sandbox API; non-breaking additions to the API ship as SDK patch / minor bumps. A future v2 API will require an SDK major.