eryx.run API

eryx.run runs untrusted Python in a sandbox: CPython 3.14 compiled to WebAssembly. Code can't touch your systems or files, and can only reach the hosts you allow, but it can await functions that you provide, and those run in your own systems.

There are two ways to run code:

  • POST /v1/execute runs some code and returns its output. Use it when the code doesn't need to call you back.
  • /v1/stream is a WebSocket. Use it when the code calls functions (callbacks) that your app handles while the code runs.

AI agents can also use eryx.run as an MCP server.

The base URL is https://api.eryx.run. Requests and responses are JSON.

Quick start

  1. Sign in with GitHub and create an API key.
  2. Run some code:
export ERYX_API_KEY=<your key>
curl https://api.eryx.run/v1/execute \
  -H "Authorization: Bearer $ERYX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"code": "print(1 + 1)"}'
{"stdout": "2\n", "stderr": "", "compute_units": 372479, "duration_ms": 12, "peak_memory_bytes": 14286848, "status": "success"}

To try code without a key, use the playground on the dashboard. It runs as your org, with its environments, sessions, connections and limits.

Client libraries

The client libraries speak this API for you, including callbacks, mounts and sessions, and turn its errors into exceptions:

  • Python: pip install eryx-run (eryx-run), with the same API as pyeryx, which runs sandboxes locally.
  • TypeScript and JavaScript: npm install @eryx-org/eryx-run (@eryx-org/eryx-run), for Node.js 22+ and Bun, and for other runtimes with a WebSocket that can send headers.
import eryx_run as eryx

sandbox = eryx.Sandbox(callbacks=[{"name": "get_user", "fn": lambda id: {"id": id, "name": "Ada"}}])
print(sandbox.execute('print((await get_user(id=1))["name"])').stdout_text)  # Ada
import { Sandbox } from "@eryx-org/eryx-run";

const sandbox = new Sandbox({ callbacks: { get_user: ({ id }) => ({ id, name: "Ada" }) } });
console.log((await sandbox.execute('print((await get_user(id=1))["name"])')).stdout); // Ada

Both read your key from ERYX_API_KEY. Their source is in eryx's sdk/ directory.

Authentication

Send your API key as a Bearer token on every request, including the WebSocket upgrade:

Authorization: Bearer eryx_...

Create and revoke keys in the dashboard. Each key is shown once, when you create it. An org can have up to 10 active keys. A revoked key can keep working for up to a minute.

Keys belong to your org, and so do the limits and usage: every key in an org shares them.

Run code

POST /v1/execute runs the code and responds when it has finished.

Request

FieldType
codestringRequired. The Python code to run. Top-level await works.
environmentstringWhat the code runs in: "python" (the default, just the standard library), "javascript" (QuickJS), "shell" (a bash-like shell with coreutils) or one of your environments. In a session, it can be left out.
timeout_secsintegerStop the run after this many seconds. Defaults to, and is capped at, your org's limit.
fuel_limitintegerStop the run after this many compute units. Defaults to, and is capped at, your org's limit.
connectionsarray of stringsLimit the run to these of your connections. Without it, the code can call all of them.
network_policiesarray of stringsThe network policies the run gets. Without it, it gets your default ones; [] means no network.
{"code": "import math\nprint(math.factorial(20))"}

Response

A run that finishes returns 200, even if the code failed. Check status.

FieldType
stdoutstringWhat the code printed, even if it raised. Empty if the run was stopped (timeout, resource_limit) or failed for another reason.
stderrstringWhat the code wrote to stderr. If the code raised, it ends with the traceback. Empty when stdout is.
compute_unitsintegerThe compute units the run used.
network_bytesintegerBytes the run sent and received over the network. Only there when it used the network.
statusstringHow the run ended: see below.
errorstringWhy the run didn't succeed. Only there when status isn't success.
unsaved_variablesarraySessions only: variables that couldn't be saved. Only there when there are some.
duration_msintegerHow long the code ran, in milliseconds. Not there if it didn't get to run.
callback_invocationsintegerHow many callbacks the code called. Only there when it called some.
peak_memory_bytesintegerThe most memory the code used. Not there if it wasn't measured.
resultanyThe value of the code's result variable, as JSON (as Python's json writes it, so big integers are exact). Only there when the code set one.
result_errorstringWhy result couldn't be returned, such as a value JSON can't hold. Only there when that happened.
{"stdout": "2432902008176640000\n", "stderr": "", "compute_units": 477034, "duration_ms": 17, "peak_memory_bytes": 14286848, "status": "success"}
statusMeaning
successThe code ran to the end.
errorThe code raised an exception. error has the traceback.
timeoutThe run took longer than its time limit.
resource_limitThe run used up its compute units or memory.

Code that raises keeps what it printed before it failed:

{"code": "print('loading data')\nraise ValueError('bad input')"}
{
  "stdout": "loading data\n",
  "stderr": "Traceback (most recent call last):\n  ...\nValueError: bad input\n",
  "compute_units": 1981661,
  "duration_ms": 21,
  "peak_memory_bytes": 14286848,
  "status": "error",
  "error": "Traceback (most recent call last):\n  ...\nValueError: bad input\n"
}

To return a value rather than printing it, set result to anything JSON can hold:

{"code": "import math\nresult = {'factorial': math.factorial(10), 'primes': [2, 3, 5, 7]}"}
{
  "stdout": "",
  "stderr": "",
  "compute_units": 452311,
  "duration_ms": 16,
  "peak_memory_bytes": 14286848,
  "status": "success",
  "result": {"factorial": 3628800, "primes": [2, 3, 5, 7]}
}

A run that's stopped by its time limit or compute units has no output, nor does one that fails before the code runs, such as in a session that can't be restored. A session run whose changes can't be saved keeps its output.

Callbacks

Callbacks are functions that sandboxed code can await, and that your app runs. Run code over the /v1/stream WebSocket, list the callbacks it may use, and answer each call as it comes in:

# This runs in the sandbox
user = await get_user(id=123)
await send_email(to=user["email"], subject="Hi")

Connect

Open a WebSocket to wss://api.eryx.run/v1/stream with the Authorization header set. Browsers can't set headers on a WebSocket, so connect from your server, not from a web page.

Set Sec-WebSocket-Protocol: eryx.v1 to say which version of the protocol your client speaks. The server answers with the version it picked, so a client that offers several (eryx.v2, eryx.v1) gets the newest both sides know. Without the header you get eryx.v1, the protocol below. Offering only versions the server doesn't speak gets a 400 with invalid_request, before the upgrade.

New message types and fields can be added to a version, so ignore ones you don't know. Changing what an existing message means needs a new version.

One connection runs one piece of code at a time. Wait for completed before sending the next execute; any other message sent mid-run, apart from a callback_response or an fs_response, is ignored. A connection can run many pieces of code, one after another.

Messages

Every message is a JSON object with a type.

execute (you send) starts a run. code, timeout_secs, fuel_limit and connections are the same as for POST /v1/execute, callbacks lists the functions the code can call, mounts lists directories you serve to the code, session_id, if set, runs the code in that session, and traceparent, if set, puts the run in that trace instead of the connection's:

{
  "type": "execute",
  "code": "user = await get_user(id=123)\nprint(user['name'])",
  "callbacks": [{"name": "get_user", "description": "Look up a user by id"}]
}

callback (you receive) means the code called one of your callbacks. args holds the keyword arguments it was called with:

{"type": "callback", "call_id": "9f0c...", "name": "get_user", "args": {"id": 123}}

callback_response (you send) answers a call. Send its call_id back with either a result, which can be any JSON and is what await returns in Python, or an error, which raises a RuntimeError in Python:

{"type": "callback_response", "call_id": "9f0c...", "result": {"name": "Ada", "email": "ada@example.com"}}
{"type": "callback_response", "call_id": "9f0c...", "error": "No such user"}

completed (you receive) ends the run. It has the same fields as a POST /v1/execute response:

{"type": "completed", "stdout": "Ada\n", "stderr": "", "compute_units": 4297143, "duration_ms": 31, "callback_invocations": 1, "peak_memory_bytes": 15204352, "status": "success"}

It also has a trace_id when the run was traced.

error (you receive) means the run didn't start, for example because a limit was reached or the message wasn't valid. code is the same as in an error response (invalid_key if the key has been revoked since you connected). The connection stays open:

{"type": "error", "code": "concurrency_limit", "message": "Too many concurrent executions (limit: 5)"}

Rules for callbacks

  • Use keyword arguments. await get_user(id=123) sends {"id": 123}. Positional arguments raise a TypeError in Python, and you get no callback for that call: await get_user(123) fails with get_user() takes 0 positional arguments but 1 was given.
  • Code can run callbacks concurrently, for example with asyncio.gather. You get a callback for each, and you can answer them in any order: call_id says which call an answer is for.
  • Answer each call within 30 seconds, or it fails in Python.
  • A run can make up to 100 callback calls.
  • Calling a function that isn't in callbacks raises a NameError.
  • If you disconnect mid-run, the run carries on until it finishes or hits a limit, and its compute units still count.

Example client

A complete client in Python, using the websockets package:

import asyncio
import json
import os

import websockets

CODE = """
user = await get_user(id=123)
print(f"Hello, {user['name']}")
"""

USERS = {123: {"name": "Ada"}}


async def handle(name, args):
    """Run a callback for the sandbox; raise to send it an error"""
    if name == "get_user":
        return USERS[args["id"]]
    raise ValueError(f"Unknown callback {name}")


async def main():
    headers = {"Authorization": f"Bearer {os.environ['ERYX_API_KEY']}"}
    async with websockets.connect("wss://api.eryx.run/v1/stream", additional_headers=headers) as ws:
        await ws.send(json.dumps({
            "type": "execute",
            "code": CODE,
            "callbacks": [{"name": "get_user", "description": "Look up a user by id"}],
        }))
        async for raw in ws:
            msg = json.loads(raw)
            if msg["type"] == "callback":
                reply = {"type": "callback_response", "call_id": msg["call_id"]}
                try:
                    reply["result"] = await handle(msg["name"], msg["args"])
                except Exception as e:
                    reply["error"] = str(e)
                await ws.send(json.dumps(reply))
            elif msg["type"] == "completed":
                print(msg["status"], msg["stdout"], msg.get("error", ""))
                break
            elif msg["type"] == "error":
                raise RuntimeError(f"{msg['code']}: {msg['message']}")


asyncio.run(main())

Mounts

A run on /v1/stream can read directories from your machine, read-only, without uploading them first. List them in execute's mounts, each at a path under /mnt/, and the code sees them there:

{
  "type": "execute",
  "code": "import os\nprint(os.listdir('/mnt/repo'))\nprint(open('/mnt/repo/README.md').read())",
  "mounts": [{"path": "/mnt/repo"}]
}

As the code uses a mount, you get fs messages asking for what's in it, and answer each with an fs_response carrying its op_id. mount is the mount's path and path is relative to it ("" for the mount itself). A run can have up to 8 mounts, which can't overlap.

You decide what each path serves: the code can ask for any path, and it may be untrusted. Refuse .., don't follow symlinks out of the directory, and don't serve files such as .env or .git/config unless you mean to. The client libraries do this for you with volumes.

stat asks for a file's or directory's metadata. modified is seconds since the Unix epoch, and is optional:

{"type": "fs", "op_id": "4e1a...", "op": "stat", "mount": "/mnt/repo", "path": "README.md"}
{"type": "fs_response", "op_id": "4e1a...", "stat": {"is_dir": false, "size": 1534, "modified": 1762862400.0}}

list asks for a directory's entries, each with its metadata. Set inline on files up to 64 KB and put their contents, one after another in the entries' order, in a binary frame straight after the fs_response; data is that frame's length. Code that walks a directory and reads small files then costs one round trip per directory:

{"type": "fs", "op_id": "77c2...", "op": "list", "mount": "/mnt/repo", "path": ""}
{"type": "fs_response", "op_id": "77c2...", "data": 1534, "entries": [{"name": "README.md", "is_dir": false, "size": 1534, "inline": true}, {"name": "src", "is_dir": true}]}

read asks for up to len bytes of a file from offset. Send them in a binary frame straight after the fs_response, with data set to their length (fewer than len at the end of the file):

{"type": "fs", "op_id": "a90b...", "op": "read", "mount": "/mnt/repo", "path": "data.csv", "offset": 0, "len": 262144}
{"type": "fs_response", "op_id": "a90b...", "data": 262144}

If an operation fails, send an error instead: not_found, not_a_directory, is_a_directory or permission_denied raise the matching OSError in Python, and anything else an OSError with EIO. message is optional:

{"type": "fs_response", "op_id": "4e1a...", "error": "not_found"}

Messages from the server can arrive while you're still answering earlier ones, and you can answer them in any order, but each binary frame must come straight after its fs_response.

Rules for mounts

  • Mounts are read-only: writing, creating or deleting files in them raises PermissionError.
  • What the run learns is kept for the rest of the run, so it asks for each thing once: a file changed on your side mid-run may be seen as it was, and reads stop at the size the file had when the code first looked at it. Reads fetch 256 KB at a time, and up to 16 MB of files and 16 MB of listings are kept. A read reply longer than len fails the read.
  • A run can make up to 1000 fs requests, and you can send it up to 256 MB. Past either, the code's file operations raise OSError.
  • Waiting for you counts towards the run's timeout_secs, but uses no compute units.
  • Mounts only work on /v1/stream. In a session, they're mounted for each run that lists them, and never saved with its state.

Sessions

A session keeps Python state between runs: variables, functions, classes and imports from one run are there in the next, like cells in a notebook. Files under /data are kept too (but not /tmp).

curl -X POST https://api.eryx.run/v1/sessions -H "Authorization: Bearer $ERYX_API_KEY"
{"id": "0b7f5c1e-...", "environment": "python", "ttl_secs": 3600, "expires_at": "2026-11-02T22:00:00Z"}

Then run code in it with POST /v1/sessions/{id}/execute, which takes the same request and gives the same response as POST /v1/execute:

curl -X POST https://api.eryx.run/v1/sessions/$SESSION_ID/execute \
  -H "Authorization: Bearer $ERYX_API_KEY" -H "Content-Type: application/json" \
  -d '{"code": "x = 21"}'
curl -X POST https://api.eryx.run/v1/sessions/$SESSION_ID/execute \
  -H "Authorization: Bearer $ERYX_API_KEY" -H "Content-Type: application/json" \
  -d '{"code": "print(x * 2)"}'

To use callbacks in a session, add its session_id to a WebSocket execute message.

  • Environment. A session runs in the environment it was created with ({"environment": ...}, default "python"). A run in it can leave environment out; naming a different one is a 422.
  • Expiry. A session expires ttl_secs after its last run: an hour, unless you create it with {"ttl_secs": ...} (at most 86400, a day). End one sooner with DELETE /v1/sessions/{id}.
  • One run at a time. A run sent while another is going in the same session gets 409 with session_busy.
  • Failed runs. If the code raises an exception, the changes it made before the exception are kept, files included. A run that stops on a limit (timeout or resource_limit) keeps none of its changes.
  • What's kept. State is saved between runs, so only values that can be saved are kept: most data, functions, classes and their instances, and imported modules. Open files, generators and other live objects aren't; the response lists them in unsaved_variables, and later runs won't see them. Saved state can be up to 1 MB. A run that leaves more keeps none of its changes and ends with resource_limit, though you still get its output. Files under /data have their own limit, the same 16 MB as any run.
  • State that can't be restored. If a session's saved state ever can't be loaded again, for example after we upgrade the Python runtime, every run in that session ends with status: "error" and an error starting Failed to restore session state. Delete the session and start a new one.

Runs in a session use compute units like any other run. Saving and restoring the state and files is free.

Environments

An environment is the sandbox plus Python packages: ones you name from PyPI, and ones you upload. Run code in one by naming it in environment.

curl -X POST https://api.eryx.run/v1/environments -H "Authorization: Bearer $ERYX_API_KEY" \
  -F name=http -F imports=httpx -F requirements='httpx==0.28.1'

The upload is a multipart form:

Field
nameRequired. Up to 63 lowercase letters, digits and dashes, unique in your org. python and names starting python- are taken.
languagepython (the default), or javascript for npm packages.
importsModules to import when the environment is built, separated by spaces or commas, so runs don't spend time importing them. A module that fails to import fails the build.
requirementsPackages from PyPI, one a line, as a name, optional [extras] and version specifiers (httpx==0.28.1, jinja2>=3,<4); blank lines and # comments are skipped. Their dependencies come too. No URLs, paths, markers or - options. Up to 50.
packageA .whl, .tar.gz or .tgz file to upload; repeat the field for each. Nothing is fetched for an upload, so include its dependencies (as files or requirements). An upload replaces a requirement's files where they overlap. Up to 50 MB in all. A package field with an empty file name, as a browser sends for an empty file input, is skipped.

It returns 202 and the environment in "status": "building":

{"id": "5c0e...", "name": "http", "language": "python", "status": "building", "imports": ["httpx"], "packages": [], "requirements": ["httpx==0.28.1"], "created_at": "...", "updated_at": "..."}

Building takes a minute or so. GET /v1/environments/{name} shows its status: ready once you can run code in it, or failed with an error that says why (for example the traceback of an import that failed). Once the requirements are resolved, resolved lists the version of each package they brought in, e.g. [{"name": "httpx", "version": "0.28.1"}, {"name": "idna", "version": "3.10"}, ...]. They're resolved once, when the environment is created: to pick up newer versions, create it again. GET /v1/environments lists them all, and DELETE /v1/environments/{name} deletes one.

curl -X POST https://api.eryx.run/v1/execute -H "Authorization: Bearer $ERYX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"code": "import httpx\nprint(httpx.__version__)", "environment": "http"}'

Packages must be pure Python, or built for WebAssembly (wasm32-wasi): wheels with native code for Linux or macOS won't load. So requirements take each package's pure-Python wheel from PyPI. For packages with native code, we build WebAssembly versions ourselves: such a package, or one that needs it, gets our build, at the version we built (markupsafe 3.0.3, for example). For a package with neither (such as numpy, for now), the environment's status is waiting, with waiting_for naming the builds it needs (["numpy==2.3.4"]) and error saying so: we're asked to build them, and the environment builds by itself once they're published (if that takes over 14 days, it fails instead). To use it sooner, delete it and pin a version that doesn't need them, or upload a WASI build. Pure Python can still use what the sandbox lacks, such as threads or subprocesses, and fail when it runs. Code in an environment can only reach the hosts its network policies allow, as in any sandbox.

While an environment is building, waiting or has failed, runs in it get 409 with environment_not_ready. After we upgrade the sandbox, an environment is rebuilt the next time you use it, which takes a minute; meanwhile its runs get the same 409.

JavaScript environments

An environment can be the JavaScript sandbox plus npm packages instead:

curl -X POST https://api.eryx.run/v1/environments -H "Authorization: Bearer $ERYX_API_KEY" \
  -F name=tools -F language=javascript -F requirements=$'zod@^3\ndate-fns' \
  -F imports=date-fns/format
  • requirements are npm packages, one a line: a name and an optional version, range or tag (zod@^3, @scope/pkg@next, date-fns for the latest). Their dependencies come too. Only the public npm registry is used, and no install scripts run. No aliases (npm:), git, URLs or paths. At least one, and up to 50.
  • imports are what to make importable beyond each package's own name, such as date-fns/format. A package's name always is.
  • There are no uploads.

Versions published in the last 3 days aren't installed, so a just-published (possibly malicious) release can't reach your environment before it's noticed. resolved lists every package installed, and as for Python they're resolved once, when the environment is created. Code imports them as usual:

import { z } from "zod";
console.log(z.string().parse("hi"));

A JavaScript environment runs JavaScript: name it in /v1/execute, /v1/stream or a session, or in MCP's execute_javascript.

MCP

https://api.eryx.run/mcp is an MCP server (Streamable HTTP), so an agent can run code, keep a session and manage environments itself.

Clients that support MCP's OAuth, such as Claude Code, claude.ai and Cursor, only need the URL: they open a page where you sign in and allow them. Each client you allow gets an API key named after it, such as “Claude Code (MCP)”, which you can revoke on the dashboard.

claude mcp add --transport http eryx https://api.eryx.run/mcp

Otherwise, send an API key as a Bearer token, as with the rest of the API:

claude mcp add --transport http eryx https://api.eryx.run/mcp \
  --header "Authorization: Bearer $ERYX_API_KEY"

Its tools:

Tool
execute_pythonRuns code, like POST /v1/execute, or in a session given session_id. Takes environment, timeout_secs, fuel_limit, connections and network_policies too, and returns the same response. Code can call your connections' tools. It only runs Python: another language's environment or session is a 422.
execute_javascript, execute_shellLike execute_python: run JavaScript (in a JavaScript environment given environment) or a shell script (no environment), in a session of that language given session_id. A failed shell script's response has exit_code.
list_network_policiesLists your network policies: the hosts each allows, its secrets' names, and whether runs get it by default.
list_connectionsLists your connections (or just connection) with their tools: the name code calls each by and a one-line summary.
describe_toolOne tool's full description and arguments, given the name code calls it by (call), e.g. mcp.tracker.list_issues.
create_sessionCreates a session; takes environment and ttl_secs.
list_sessionsLists your unexpired sessions.
delete_sessionDeletes the session with this id.
list_environmentsLists your environments.
create_environmentCreates an environment from requirements (a list, e.g. ["httpx==0.28.1"]), with name, imports and language (javascript takes npm packages, e.g. ["zod@^3"]), and returns it building. Upload packages with the API or the dashboard.
delete_environmentDeletes the environment with this name.

A call that the API would reject, such as an unknown environment, is a tool error whose text is the API's error body. Each MCP request, including initialize and listing tools, counts towards your rate limit, and runs use compute units as they do through the API.

Connections

A connection is an MCP server your org adds, whose tools your sandboxed code can call. Add them on the dashboard or with the API. For a server that uses OAuth, pick OAuth under Authentication on the dashboard: you sign in to it once, and we keep its tokens encrypted and refresh them.

curl -X POST https://api.eryx.run/v1/connections -H "Authorization: Bearer $ERYX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "tracker", "url": "https://mcp.example.com/mcp", "headers": {"Authorization": "Bearer <token>"}}'
Field
nameRequired. A lowercase letter, then up to 31 lowercase letters, digits or underscores, unique in your org.
urlRequired. The server's Streamable HTTP URL. It must be https:// and on the public internet.
headersHeaders to send it, such as Authorization. They're stored encrypted and never shown again.

We connect to the server and list its tools before saving the connection, so a wrong URL or credential is a 422 now rather than an error in a run. It returns 201 with the tool names:

{"name": "tracker", "url": "https://mcp.example.com/mcp", "has_headers": true, "created_at": "...", "tools": ["list_issues", "create_issue"]}

GET /v1/connections lists them (without headers or tools), and DELETE /v1/connections/{name} deletes one. An org can have 10.

Code can await any connection's tools as mcp.<connection>.<tool>, passing the tool's arguments by keyword or by position, in the order the tool declares them:

{"code": "issues = await mcp.tracker.list_issues(state=\"open\")\nprint(len(issues))"}

A connection is only connected to when code first calls one of its tools, so connections the code doesn't use cost nothing, and one that's down only affects code that calls it: the call raises an exception saying why. To limit a run to some connections, list them in connections (an unknown name is a 404).

A tool returns its structured content if it has some, else its text, parsed if it's JSON. A tool that fails, or doesn't exist, raises an exception in the code. Use mcp.tracker["list-issues"](...) for names that aren't Python names. Calling a connection that isn't there raises an error that says which are. A run can make up to 100 tool calls, each up to 10 seconds; time spent waiting for a tool uses no compute units.

Network access

Code has no network unless a network policy lets it reach some hosts. A policy is a list of hosts, and secrets to send them. Runs get your org's default policies, or the ones they name in network_policies. Add them on the dashboard or with the API:

{"name": "github", "allowed_hosts": ["api.github.com", "*.githubusercontent.com"], "default": true, "secrets": [{"name": "GITHUB_TOKEN", "value": "ghp_...", "header": "Authorization"}]}
curl -X POST https://api.eryx.run/v1/network-policies -H "Authorization: Bearer $ERYX_API_KEY" \
  -H "Content-Type: application/json" -d @policy.json
Field
nameRequired. A lowercase letter, then up to 31 lowercase letters, digits or underscores, unique in your org.
allowed_hostsRequired. Up to 100 hosts code may connect to, on any port: a name such as api.github.com, or *. and a name for any of its subdomains (*.example.com matches a.example.com and a.b.example.com, but not example.com).
defaultWhether runs that don't set network_policies get it. Default false.
secretsUp to 20 secrets (below).

It returns 201 with the policy. Secret values are stored encrypted and never shown again:

{"name": "github", "allowed_hosts": ["api.github.com", "*.githubusercontent.com"], "default": true, "secrets": [{"name": "GITHUB_TOKEN", "hosts": [], "header": "Authorization"}], "created_at": "...", "updated_at": "..."}

GET /v1/network-policies lists them, PUT /v1/network-policies/{name} replaces one's settings (the same fields but name), and DELETE /v1/network-policies/{name} deletes one. An org can have 20.

A run with several policies can reach the hosts of all of them. Addresses that aren't on the public internet (such as 127.0.0.1, 10.0.0.0/8 or cloud metadata endpoints) are always blocked, even if a host name resolves to one. A run can have 10 connections open at once, and send and receive 16 MB in all (your org's limit on the dashboard): past that, reading and writing fail, which an HTTP client may report as an incomplete read. The response's network_bytes says how much a run moved. urllib.request works, as do packages such as requests in an environment. Time spent waiting for the network uses no compute units, but counts towards the run's timeout.

{"code": "import json, os, urllib.request\nrequest = urllib.request.Request('https://api.github.com/user', headers={'Authorization': 'Bearer ' + os.environ['GITHUB_TOKEN']})\nprint(json.load(urllib.request.urlopen(request))['login'])", "network_policies": ["github"]}

Secrets

Code never sees a secret's value. os.environ[name] holds a placeholder, and we replace it with the real value in the headers of requests to the secret's hosts, over HTTPS. The real value never reaches the sandbox: if a response contains it, the code sees the placeholder, and placeholders in the run's output show as [REDACTED].

Field
nameRequired. The environment variable: uppercase letters, digits and underscores, not starting with a digit, PYTHON or ERYX_, and not one Python uses, such as PATH.
valueRequired when creating. When replacing a policy, leave it out to keep the value stored for this name.
hostsThe hosts it may be sent to, from the policy's allowed_hosts. Default: all of them.
headerThe only header it may be sent in, such as Authorization.

A request with a placeholder to any other host, or in another header when header is set, fails, so the secret can't be sent anywhere else. It's only replaced in headers, not in a request's URL or body. In a session, a secret's placeholder is the same in every run, so a variable that holds one keeps working.

The sandbox

Code runs in CPython 3.14 with the standard library, including asyncio, json, re, datetime, decimal and sqlite3. Each run starts fresh: nothing is kept between runs, unless you use a session. Modules that are slow to import, such as datetime, decimal, statistics and urllib, are imported ahead of time, so importing them costs almost no compute units.

Code can write files under /data and /tmp, up to 16 MB in all. They're gone when the run ends, except in a session, which keeps /data. Past 16 MB, writing raises OSError.

{"code": "with open('/data/notes.txt', 'w') as f:\n    f.write('hello')\nprint(open('/data/notes.txt').read())"}
{"stdout": "hello\n", "stderr": "", "compute_units": 967231, "duration_ms": 14, "peak_memory_bytes": 14286848, "status": "success"}

tempfile works too, and uses /tmp:

{"code": "import tempfile\nwith tempfile.TemporaryFile() as f:\n    f.write(b'hello')\n    f.seek(0)\n    print(f.read())"}
{"stdout": "b'hello'\n", "stderr": "", "compute_units": 1410622, "duration_ms": 15, "peak_memory_bytes": 14286848, "status": "success"}

It can't:

  • Reach hosts its network policies don't allow. Without any, it has no network:

    {"code": "import urllib.request\ntry:\n    urllib.request.urlopen('https://example.com')\nexcept OSError as e:\n    print(type(e).__name__, e.reason)"}
    
    {"stdout": "URLError [Errno 2] not-permitted: networking not enabled for this sandbox\n", "stderr": "", "compute_units": 6298695, "duration_ms": 40, "peak_memory_bytes": 16384000, "status": "success"}
    
  • Write files outside /data and /tmp.

  • Install packages. Only the standard library is available, so import numpy raises ModuleNotFoundError, unless you upload them to an environment.

  • Use more than 64 MB of memory. Past that, Python raises MemoryError.

Limits

Your org's limits are on the dashboard. They apply across all of the org's keys:

LimitWhat happens when you reach it
Requests per minute429 with rate_limit_exceeded. Each API request, each WebSocket connection, each WebSocket execute and each MCP request counts as one.
Concurrent executions429 with concurrency_limit, straight away: requests don't queue.
Compute units per runThe run stops with status: "resource_limit".
Time per runThe run stops with status: "timeout".
Network traffic per runSending and receiving more fails in the code: see Network access.
Mounts per run1000 fs requests and 256 MB, then the code's file operations fail.
Sessions429 with session_limit when creating a 51st unexpired session.
Environments429 with environment_limit when creating an 11th environment.
Connections429 with connection_limit when creating an 11th connection.
Network policies429 with network_policy_limit when creating a 21st network policy.

A request can set a lower fuel_limit or timeout_secs for itself, but not a higher one. A 429 for the rate limit has a Retry-After header with the number of seconds to wait.

Requests without a valid key are rate limited per IP address instead.

Compute units

A compute unit is one WebAssembly instruction. The same code always uses the same number of them, so costs are predictable: print(1 + 1) uses about 370,000 and a typical small script a few million. Time spent waiting for a callback uses none.

compute_units counts runs that fail as well as runs that succeed. For a run that times out it's accurate to within a few million.

Tracing

Send a W3C traceparent header (and tracestate, if you use it) and the run joins your trace, so its spans have your span as their parent. On /v1/stream, runs join the trace in the connection's traceparent header, or the one in an execute message's traceparent field.

When we trace a request, the response has an X-Trace-Id header naming its trace (yours, if you sent one), and a WebSocket run's completed message has a trace_id. Include it when you ask us about a request. Spans never include your code, its arguments or its output.

Errors

When a request is rejected, the response has an error status and this body:

{"error": {"code": "missing_auth", "message": "Missing Authorization header"}}
StatuscodeMeaning
400, 415, 422invalid_requestThe body isn't JSON, isn't sent as application/json, or is missing code.
401missing_authNo Authorization header.
401invalid_authThe header doesn't use the Bearer scheme.
401invalid_keyThe key is wrong or has been revoked.
404not_foundNo such session in your org (or it has expired), environment, connection or network policy.
409conflictYou already have an environment with this name.
409environment_not_readyThe environment is building, waiting for builds of native packages, failed to build, or is being rebuilt.
413invalid_requestAn environment's packages are over 50 MB (Packages can be up to 50 MB in all).
409session_busyAnother run is going in this session.
429rate_limit_exceededOver your org's requests per minute. Wait for Retry-After seconds.
429concurrency_limitYour org already has its maximum number of runs going.
429session_limitYour org already has 50 unexpired sessions.
429environment_limitYour org already has 10 environments.
429network_policy_limitYour org already has 20 network policies.
500internal_errorSomething went wrong on our side.
503unavailableWe're at capacity. Retry after a short wait.

Code that fails isn't an error response: it's a 200 with a status that says what happened (see Response).