Skip to content

Sandbox

The Sandbox runs a piece of TypeScript or JavaScript in a fresh Slice isolate on our servers and returns its output. Each call starts from a clean state and is thrown away when it ends.

  • AI agents and code mode. Let a model write code and run it somewhere that cannot touch your machine, your network or your secrets.
  • User-supplied logic. Pricing formulas, plugins, transforms and rules written by customers.
  • One-off evaluation where deploying a function would be overkill.

If you run the same code many times with different input, deploy it as a function instead. If the code never leaves your machine, the free local runtime (slice run, the local MCP server, the SDK in local mode) does the same job without an account.

Way Use it for Key scope
Hosted MCP (https://api.slicevm.com/mcp) AI agents and editors. The slice_eval_ts tool runs code here. sandbox:eval
Sandbox SDK (@slicevm/sdk) TypeScript and Node.js apps. Retries for you. sandbox:eval
HTTP API (POST /v1/sandbox/eval) Any language. sandbox:eval

All three use an API key from the console and count one run per call.

You send source code. The value of the last expression is the result, and everything printed with console.* is in stdout.

Terminal window
curl https://api.slicevm.com/v1/sandbox/eval \
-H "Authorization: Bearer $SLICE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"code":"const rows = [3, 1, 2]; console.log(rows.length); rows.sort()","options":{"fuel":1000000}}'
{ "ok": true, "stdout": ["3"], "result": [1, 2, 3], "violation": null, "telemetry": { "...": "..." } }

Source is limited to 64 KB per call. The full response shape and every telemetry field are in the HTTP API reference.

Option Default What it does
fuel Plan maximum Deterministic budget: guest steps, function calls and work inside built-ins (sort, string methods, regular expressions, typed arrays, JSON) all count. When it runs out the run traps with CpuFuelExhausted.
memoryKb Plan maximum Heap cage in KB: every object, array, string, Map, Set and buffer (ArrayBuffer, typed arrays, Buffer) counts. Minimum 256. Over it the run traps with MemoryCeilingExceeded.
timeoutMs Plan maximum Wall-clock limit in milliseconds. Over it the run traps with WallClockExceeded.
allowNet [] Hosts the code may reach, as host or host:port. Empty means no network at all.
auditEgress [] Secrets that must never leave the sandbox. Blocked in raw, Base64 and Base64URL form.
deterministicSeed none Seeds Math.random, Date.now and performance.now, so a run can be replayed exactly.
checkpoints true Allows Slice.checkpoint() and Slice.restore() inside the run (at most 1,024 checkpoints). false makes them trap with CheckpointDenied.
artifacts true Returns the files the code writes under /artifacts, and keeps a copy for your plan’s retention (see Artifacts). "inline" never keeps, "store" must keep, false leaves /artifacts unavailable.

Values above your plan cap are clamped to the cap, not rejected. Every result has limits with the fuel, memory and time the run actually got, and a request that was reduced also gets limitsCapped with what you asked for, for example { "memoryKb": 131072 }. The hosted MCP tool accepts fuel, memoryKb, timeoutMs, allowNet and artifacts; the SDK and HTTP API accept all of them.

Compiling your source is usually the largest part of a call. Pack shared dependencies into a .cas bundle once with slice pack, upload it with POST /v1/cas/upload, and pass its casDigest on each eval. The bundle runs first, then your code; share values by assigning them to globalThis.

Free Pro Scale
Runs per month 25,000 2,500,000 50,000,000
Memory cage 8 MB 32 MB 64 MB
Fuel cap 25,000,000 100,000,000 250,000,000
Time per run 10 s 30 s 60 s
Runs in flight 1 4 8
.cas bundles No Yes Yes

A run that asks for nothing gets these maximums. Runs in flight count per account, across all keys. One more returns 429 rate_limited with Retry-After: 1. More on Plans and limits.

As a rough guide, a small object such as { id, value } takes about 112 bytes and a number in an array about 16, so 8 MB holds about 70,000 such objects or 500,000 numbers (32 MB about 280,000 objects). Sorting 100,000 numbers uses about 4,000,000 fuel. telemetry.fuelConsumed and telemetry.peakMemoryKb show how close a run came to limits.

  • Fresh isolate per run. Nothing survives between calls: globals, Slice.kv and the virtual filesystem start empty every time.
  • Fuel, memory and time caps. Every run has a deterministic fuel budget, a hard heap cage and a wall-clock limit, so an infinite loop, a memory bomb or a regular expression that backtracks forever ends as a violation, not an outage. A run whose caller disconnects is stopped.
  • Deny-by-default network. Only hosts in allowNet are reachable. A listed name that resolves to a loopback, private or link-local address is refused when it connects, so DNS cannot point a request back inside, and cloud metadata addresses are always blocked. Both are ordinary refusals your code can catch.
  • Egress secret auditing. A secret in auditEgress that appears in an outgoing request, raw or Base64 encoded, traps the run before it is sent.
  • No self-granted permissions. Only your request options set capabilities and limits; // @slice-* comments inside the code have no effect.
  • Hardware memory domains. On hosts with Intel MPK each run gets its own protection key; telemetry.mpkDomain reports it ("none" elsewhere).

The runtime side of this is described in Security model.

Code can write files under /artifacts with plain node:fs, and they come back with the result: a chart it drew, a CSV it built, a log of what it did. Libraries that write files work unchanged.

const fs = require("node:fs");
fs.mkdirSync("/artifacts/charts", { recursive: true });
fs.writeFileSync("/artifacts/charts/revenue.png", png); // a Uint8Array
fs.writeFileSync("/artifacts/summary.csv", "region,total\nus,42\n");
"done";

The result lists each file, sorted by name, with its bytes in Base64:

"artifacts": [
{ "name": "charts/revenue.png", "size": 18342, "contentType": "image/png", "sha256": "9f2c...", "data": "iVBORw0KGgo..." },
{ "name": "summary.csv", "size": 19, "contentType": "text/csv", "sha256": "41ab...", "data": "cmVnaW9u..." }
]
  • /artifacts starts empty in every run and holds only what that run wrote there. It is never a real directory on the machine, and every other path stays refused.

  • Files come back whatever the outcome, so a log written before a run ran out of fuel or time is still there.

  • contentType is read from the bytes first (PNG, JPEG, GIF, WebP, PDF, ZIP, gzip), then from the extension, and is application/octet-stream when unknown. Treat the files as untrusted output: an .svg or .html file can contain script.

  • Caps per run:

    Plan Files Per file Total
    Free 20 2 MB 4 MB
    Pro 50 8 MB 16 MB
    Scale 200 16 MB 32 MB

    Files also count against the run’s memory while it runs.

  • A file that misses a cap, a symlink (never followed), or a file that contains one of your auditEgress secrets is not returned. It is listed in skippedArtifacts with a reason (tooMany, tooLarge, overTotal, pathTooLong, symlink, auditedSecret), and the run still succeeds. A secret hit is also named in deniedCapabilities as artifact:<name>.

  • options.artifacts: false turns it off for a run; /artifacts is then refused like any other path.

  • Over MCP the agent sees images as images and text files as text. The SDK returns the same fields in local mode, and has helpers to decode and save them.

Runs made with a console key also keep each file for a while, and each entry gets an id, a download url and an expiresAt. The bytes stay in data as well.

Plan Kept for Storage
Free 24 hours 1 GB
Pro 7 days 25 GB
Scale 30 days 250 GB

The playground and keys bought before the console return files inline only.

  • The link is signed and works for 15 minutes; get a fresh one from GET /v1/artifacts/{id}. Images, plain text, JSON and CSV open in the browser; everything else, SVG and HTML included, downloads.
  • List, download and delete them in the console (Artifacts) or with the API, by run or one at a time. Files are deleted when they expire.
  • When the account’s storage is full, files still come back in the result but are not kept, and the result says "artifactsNotKept": "quota".
  • options.artifacts: "inline" returns the files without keeping them; "store" refuses to run (403) when the key or plan cannot keep them.

A run that reaches the sandbox always returns HTTP 200. Check ok:

Outcome ok violation result
Completed true null Last expression value
Uncaught exception or rejected promise false null Uncaught Error: ...
process.exit(n) with n not 0 false null Value at exit; exitCode is n
Sandbox trap (fuel, memory, time, egress, SSRF, checkpoint cap) false e.g. CpuFuelExhausted: ... null
Refused capability the code did not catch false e.g. NetAccessDenied: ... null

A refused fetch, file, subprocess or environment call throws an error your code can catch, so you can probe for access and fall back:

try {
return await (await fetch("https://api.example.com/")).json();
} catch (e) {
if (e.code === "ERR_SLICE_NET_DENIED") return { offline: true };
throw e;
}

The codes are ERR_SLICE_NET_DENIED, ERR_SLICE_FS_DENIED, ERR_SLICE_EXEC_DENIED, ERR_SLICE_ENV_DENIED, ERR_SLICE_CHECKPOINT_DENIED and ERR_SLICE_EXT_DENIED (a Slice.ext.<name> host extension; Slice Cloud grants none). Messages share one format, OCap Violation: lacks <kind> authority for <target>, for example OCap Violation: lacks outbound network authority for host 'example.com:443'; branch on e.code, not on the message. Every refused attempt, caught or not, is listed in deniedCapabilities. Fuel, memory, time and security traps cannot be caught.

Of the Deno namespace only Deno.serve exists. Other Deno.* calls such as Deno.readTextFile or Deno.env.get are not refusals: they throw a plain TypeError without an err.code and are not listed in deniedCapabilities. Use node:fs, process.env and fetch instead.

Lines printed before a trap are kept in stdout. The API itself can refuse a call with an error body; the common ones:

Status Code What to do
400 bad_request Fix the JSON or send non-empty code.
401 unauthorized Check the key; it may be revoked or expired.
403 forbidden The key lacks sandbox:eval, or the feature (such as casDigest) is not in your plan.
413 payload_too_large Keep code under 64 KB, or move dependencies into a .cas bundle.
429 rate_limited Wait and retry; the SDK does this for you.
429 quota_exceeded Monthly runs used up. Upgrade or wait for the refill.
503 overloaded Retry with backoff; the SDK does this for you.

The full table is in the HTTP API reference.