Sandbox

Run untrusted code in an isolated session with its own files, packages and quotas.

The Sandbox gives each user an isolated session to run code in: a place for an agent to execute Python, install packages and work with files without touching anything else. Each session is a gVisor container with no network, a read-only root filesystem, and memory and CPU limits.

A session keeps its files and installed packages until you destroy it, so a sequence of calls builds on the last:

session.create() ─▶ write files ─▶ install packages ─▶ exec, exec, exec ─▶ read results ─▶ destroy()

It's Python only for now.

Install

pip install aice-sandbox

Import it as aice_sandbox. It's also on the umbrella as aice.sandbox. It depends on aice-core like every other client, so the transport, errors and acting-user rules are the same.

Create a client

The Sandbox uses the project key like every other service: enable Sandbox on the project (regenerate the key if it was made before), and send the user each call acts for. The session belongs to the key's project; no other project's key can see or touch it.

import os
from aice_sandbox import SandboxClient

sandbox = SandboxClient(
    base_url=os.environ["AICE_SANDBOX_URL"],   # http://localhost:8080
    api_key=os.environ["AICE_API_KEY"],
    user_id=current_user.id,
)
ArgumentDefaultMeaning
base_urlthe service host. No path
api_keythe project key. Its audience must include sandbox
user_idnonesent as X-User-Id. Required: without it every call is a 401. Or use acting_as per call
user_rolenonesent as X-User-Role. admin, owner or service_role is needed for tenant_config
timeout30.0seconds. The floor for ordinary calls; calls that run a command wait longer (see below)
max_retries3retries for calls that are safe to repeat

AsyncSandboxClient offers the same with await (await client.aclose() to close it); the sync client closes with close() or a with block. To act as a different user for one call, wrap it in aice_core.acting_as(user_id).

Sessions

session = sandbox.session.create()
try:
    result = session.exec(["python3", "-c", "print(6 * 7)"])
    print(result.stdout)  # "42\n"

    session.write("data.txt", b"some content")
    print(session.read("data.txt"))        # b"some content"
    print(session.list("*.txt"))           # ["data.txt"]
finally:
    session.destroy()

Always destroy a session when you're done; each one holds quota until it's gone. Sessions you leave behind are destroyed after 30 minutes of inactivity by default, but don't rely on it.

The manifest

session.create(manifest) takes an optional manifest that sets what the session may do. Every value is checked against the service's bounds, and one outside them is rejected before anything is started.

session = sandbox.session.create({
    "network": "install_only",
    "memory_limit_bytes": 1024 * 1024 * 1024,
    "cpu_limit": 2.0,
    "default_timeout_s": 300,
})
KeyDefaultAllowedMeaning
network"none""none", "install_only"install_only lets session.install reach the package index (and only it). Your code never has network access either way
memory_limit_bytes512 MiB32 MiB up to the host's limit (4 GiB by default)memory the session may use
cpu_limit1.00.05 up to the host's limit (4 by default)CPUs
default_timeout_s1201 to the host's limit (3,600 by default)how long a command may run when you don't say

An unknown network value is refused rather than guessed at, and an invalid manifest raises SandboxSDKError (a 400).

Run commands

r = session.exec(["python3", "script.py", "--fast"], timeout_s=30, env={"MODE": "test"})
print(r.exit_code, r.stdout, r.stderr)
if r.timed_out:
    print("killed after the timeout")

cmd is an argument list, not a shell line, so there is no shell to interpret quotes or pipes. To use a shell, run it yourself: ["sh", "-c", "ls | wc -l"].

exec and install return an ExecResult:

FieldMeaning
exit_codethe process's exit code, or None if it didn't exit normally
stdout, stderrwhat it printed (text)
truncatedTrue if output was cut at the cap (256 KB per stream)
timed_outTrue if it was stopped for running past timeout_s
signalthe signal that ended it, if any
errora service-side message when the command couldn't run

A command that fails is not an exception: check exit_code and stderr. Exceptions mean the call itself didn't work (auth, quota, a missing session).

Both calls are sent once and never retried. The service doesn't deduplicate them, and a retry would run your command a second time. To make sure a slow command isn't cut off by your own client, the HTTP wait for these two calls is timeout_s (or the session's default_timeout_s, else 120 s) plus 30 s of service grace and a 5 s margin, never less than the client's timeout.

Install packages

session = sandbox.session.create({"network": "install_only"})
result = session.install(["numpy", "pandas==2.2.2"])
print(result.exit_code, result.stderr)

Needs "network": "install_only" in the manifest; without it, NetworkNotPermittedError. Packages come from the package index only. Like exec, it's sent once, never retried. Installed packages stay for the life of the session.

Files

session.write("reports/q3.csv", b"region,total\nKE,100\n")
data = session.read("reports/q3.csv")      # bytes
names = session.list("reports/*.csv")      # list of file names, default glob "*"

write takes bytes and read returns bytes. File content travels base64-encoded in the request, so very large files are better kept out of the sandbox and processed in place. Paths are relative to the session's own directory; a path that tries to leave it is rejected with SandboxSDKError (400). Reading a file that doesn't exist is a 404, raised as SessionNotFoundError.

Cancel and destroy

  • session.cancel() is not supported by the service yet: it raises SandboxSDKError (501). Destroy the session to stop a running command.
  • session.destroy() ends the session. It is safe to call twice: destroying a session that is already gone is a no-op rather than an error.
  • sandbox.health() checks the service.

Container mode

By default each session gets its own container. A project admin can switch the project to a shared container, which trades some isolation for lower cost and faster starts.

sandbox = SandboxClient(base_url=..., api_key=..., user_id=admin.id, user_role="admin")

sandbox.tenant_config.update(project_id, {
    "container_sharing": "shared",                       # or "dedicated" (the default)
    "shared_container_memory_limit_bytes": 1024 ** 3,
    "shared_container_cpu_limit": 2.0,
})
print(sandbox.tenant_config.get(project_id))

This needs user_role of admin, owner or service_role, and only works on the key's own project. tenant_config.update replaces the whole configuration, so send every field you care about.

Quotas and errors

Sessions are limited per user, per project and across the whole service (5 concurrent sessions per user by default). Creating a session over a limit raises QuotaExceededError, with .scope saying which limit and .limit its value. Free quota by destroying sessions you no longer need.

Every error derives from SandboxSDKError, which is also an AiceError:

ErrorWhen
AuthenticationError401: the key is missing, expired, or wasn't made with Sandbox enabled; or there's no user_id
ForbiddenError403: e.g. changing the container mode without an admin role
QuotaExceededError429. .scope is "user", "tenant" or "global", and .limit is the cap
SessionNotFoundError404 on a session call: it expired, was destroyed, or belongs to another project. Also raised for a missing file
NetworkNotPermittedError403 from install(): the manifest didn't allow network access
SandboxSDKErroranything else, including an invalid manifest (400), the sandbox being unavailable (502) and cancel (501)
from aice_sandbox import QuotaExceededError, SessionNotFoundError

try:
    session = sandbox.session.create()
except QuotaExceededError as err:
    print(f"over the {err.scope} limit of {err.limit}")

session.create is also sent once and never retried, since a retry could start a second session and use more quota. See Errors and retries.

Use it from an agent

An Agent Platform agent can use the Sandbox as a tool: in Agent Studio, add the Sandbox tool to the agent (tool_bindings: ["sandbox"] in code). It gets six tools:

ToolDoes
run_python(code, timeout_s=60)runs Python 3 and returns exit_code, stdout and stderr
run_shell(command, timeout_s=60)runs a shell command
write_file(path, content) / read_file(path)puts and gets a text file
list_files(glob)lists files
install_packages(packages)pip-installs from the package index
  • One sandbox per conversation. The first tool call in a conversation starts a sandbox, and later turns reuse it, so files and installed packages carry over. A new conversation starts empty.
  • It runs as the user the run acts for (the run's X-User-Id), under that user's quota of concurrent sessions.
  • No internet for the code. Only install_packages reaches the package index.
  • A tool call may run for up to 300 seconds.
  • After 30 minutes idle the sandbox is destroyed. The next call starts a fresh one and tells the agent that earlier files are gone.
  • Say in the agent's instructions when to use it, e.g. "run Python for any calculation instead of working it out yourself".

Access

Requests need a project key with Sandbox enabled and an X-User-Id, exactly as for Crawler or Knowledge. Agents reach it through /mcp with the Agent Platform's own signed token, never your key. The service's host-wide diagnostics (/doctor) take the console's internal service token, not a project key. Keep the service on a private network anyway: sessions run code, and your key is what stands between them and everyone else.

Reference

PythonEndpoint
sandbox.session.create(manifest=None)POST /session
session.exec(cmd, timeout_s=None, env=None)POST /session/{id}/exec
session.install(packages)POST /session/{id}/install
session.write(path, content)POST /session/{id}/write
session.read(path)GET /session/{id}/read?path=
session.list(glob="*")GET /session/{id}/list?glob=
session.cancel()POST /session/{id}/cancel (not implemented: 501)
session.destroy()DELETE /session/{id}
sandbox.health()GET /health
sandbox.tenant_config.get(project_id) / update(project_id, config)GET, PUT /admin/tenants/{project_id}/config

On this page