Skip to content

Sandbox SDK

@slicevm/sdk runs code through a local slice mcp child process during development and through https://api.slicevm.com in production. Your code does not change between the two. ESM, no runtime dependencies, Node.js 18 or later.

Terminal window
npm install @slicevm/sdk
npm install --save-dev @slicevm/cli # only needed for local mode
import { createSlice } from "@slicevm/sdk";
const slice = createSlice(); // remote if SLICE_API_KEY is set, else local
const run = await slice.evalSandbox(
`const total = [1, 2, 3].reduce((a, b) => a + b, 0); total`,
{ fuel: 1_000_000 },
);
console.log(slice.mode); // "remote" or "local"
console.log(run.ok, run.result); // true 6
console.log(run.telemetry.vmExecUs); // microseconds
await slice.close();

For remote mode, create a key in the console with Sandbox eval only access (or Full access if you also upload .cas bundles).

Setting Mode
createSlice({ local: true }) Always local, even when a key is set.
createSlice({ apiKey }) or SLICE_API_KEY in the environment Remote.
Neither Local.

slice.mode tells you which one was chosen. All createSlice options:

Option Default Notes
apiKey process.env.SLICE_API_KEY Selects remote mode.
baseUrl https://api.slicevm.com Remote mode origin.
local false Forces local mode.
binaryPath SLICE_BINARY_PATH, then @slicevm/cli Local mode: path to the slice binary.
localArgs [] Local mode: extra slice mcp flags, such as ["--allow-net=api.example.com"].
timeoutMs 30,000 Per request.

The second argument of evalSandbox(code, options):

Option Default Notes
fuel Plan maximum Deterministic budget. In local mode the default is 25,000,000.
memoryKb Plan maximum Heap cage in KB. In local mode the default is 4,096.
timeoutMs Plan maximum Wall-clock limit of the run (SDK 0.14.3 and later). Not to be confused with the client option of the same name, which bounds the whole HTTP call.
allowNet [] Egress allowlist. Empty means deny all.
auditEgress [] Secrets that must never leave the sandbox.
deterministicSeed none Seeds Math.random, Date.now and performance.now.
checkpoints true Allows Slice.checkpoint() and Slice.restore() inside the run.
artifacts true Returns the files the code writes under /artifacts (SDK 0.15.0 and later). false turns it off.
casDigest none Runs a previously uploaded .cas bundle first. Remote mode, Pro and Scale.

What each option does in the sandbox is on Sandbox.

Every call resolves to a SandboxResult plus transport metadata:

interface EvalSandboxResult {
ok: boolean;
stdout: string[];
result: unknown; // last expression value, parsed as JSON when possible
violation: string | null; // set when the sandbox trapped
exitCode?: number; // set when the code called process.exit() or set process.exitCode
telemetry: SandboxTelemetry;
requestId: string | null; // X-Slice-Request-Id (remote) or local_<n> (local)
serverTiming: ServerTimingEntry[]; // parsed Server-Timing header; [] in local mode
}

A sandbox violation (fuel exhausted, egress blocked, capability denied) or an uncaught error in the code is a normal result with ok: false, not an exception.

Files the code writes under /artifacts are in result.artifacts, with the same names, sizes, types and hashes in local and remote mode (SDK and runtime 0.15.0 and later):

import { createSlice, artifactText, saveArtifacts } from "@slicevm/sdk";
const slice = createSlice();
const res = await slice.evalSandbox(`
require("node:fs").writeFileSync("/artifacts/report.csv", "region,total\\nus,42\\n");
"done";
`);
console.log(res.artifacts?.map((a) => `${a.name} ${a.contentType} ${a.size}`)); // ["report.csv text/csv 19"]
console.log(artifactText(res.artifacts![0]));
await saveArtifacts(res, "./out"); // writes ./out/report.csv

artifactBytes(a) returns a Uint8Array, artifactText(a) decodes UTF-8, and saveArtifacts(result, dir) writes every file under dir and refuses a name that would escape it. Files that were not returned are in skippedArtifacts. Caps and rules are on Sandbox; in local mode the runtime’s own caps apply (64 files, 4 MB each, 16 MB in total).

Transport and API failures throw SliceApiError with code, status and requestId:

import { createSlice, SliceApiError } from "@slicevm/sdk";
const slice = createSlice();
try {
const run = await slice.evalSandbox(userCode, { auditEgress: [process.env.STRIPE_SECRET_KEY!] });
if (run.violation) console.warn("sandbox trapped:", run.violation);
} catch (err) {
if (err instanceof SliceApiError && err.code === "quota_exceeded") {
// monthly runs used up
}
throw err;
} finally {
await slice.close();
}

code is one of the API error codes, or a client-side code with status 0: timeout, network_error, local_runtime_error, unsupported.

Remote mode retries 503 overloaded up to 3 times and 429 rate_limited (burst limit, or all runs in flight taken) up to 8 times, with exponential backoff or Retry-After when sent. quota_exceeded and other errors are not retried.

On Pro and Scale you can upload a .cas bundle from slice pack once and reference it by digest, so only your short entry code is compiled per call:

import { readFile } from "node:fs/promises";
const { casDigest } = await slice.uploadCas(await readFile("./bundle.cas"));
const run = await slice.evalSandbox("globalThis.handler({ id: 1 })", { casDigest });

The bundle’s entrypoint runs first; it shares values with your code by assigning them to globalThis. Uploading needs a key with the cas:upload scope (Full access).

Local mode spawns one long-lived slice mcp process per client and needs the slice binary (from @slicevm/cli, binaryPath or SLICE_BINARY_PATH). Differences from the cloud:

Field or option Local behavior
telemetry Measured by the runtime; casMmapUs is 0 and mpkDomain is "none"
serverTiming Always []
allowNet Honored per call, but only for hosts the server also allows: pass localArgs: ["--allow-net=<host>"]
Slice.kv Shared by all calls of one client (the cloud starts every run empty)
artifacts Same fields as the cloud. Needs the slice binary 0.15.0 or later
casDigest, uploadCas Throw SliceApiError with code unsupported

Call close() to stop the child process; it is safe to call twice.

The SDK covers the Sandbox. To call a deployed function, use POST /v1/functions/<name>/invoke with fetch:

const res = await fetch("https://api.slicevm.com/v1/functions/hello/invoke", {
method: "POST",
headers: { authorization: `Bearer ${process.env.SLICE_API_KEY}`, "content-type": "application/json" },
body: JSON.stringify({ input: { name: "Ada" } }),
});
const run = await res.json(); // SandboxResult plus function: { name, version }