Skip to content

Sandbox ​

The Sandbox gives every project remote, API-driven runtime containers for running code, managing files, opening interactive terminals, and previewing apps. It boots a full Linux container (Python, Node, or a multi-runtime base image) that an agent — or a person — can drive over its whole lifecycle: create, exec, snapshot, fork, persist, and tear down.

It is the execution substrate behind coding agents and any workflow that needs a real shell, a real filesystem, and real packages rather than a sandboxed function.

Enterprise module

Sandbox is part of the enterprise edition. The dashboard pages exist in the community build but say that the installation doesn't include Sandbox; the /api/sandbox/* routes and the runtime only activate for a workspace whose package includes the sandbox module. See Licence packages.

Overview ​

The landing page (Operate → Sandbox) summarises everything provisioned in the active project: counters, a By state chart, a Welcome to Sandbox card with the first three steps, and a table of Recent sandboxes with their state, uptime, container and creation time.

Sandbox overview: counters, sandboxes by state and recent sandboxes

What to read on this screen:

  • The Sandboxes, Running, Longest uptime, Failed, Templates and Volumes tiles describe the active project (templates are shared by the whole workspace). Switch projects from the header pill to change scope.
  • The State column reflects the container's real state as reported by the runner — running, stopped, failed or deleted. Only a running sandbox accepts exec, terminal, and filesystem calls.
  • Sandboxes opens the full list, where New sandbox and Playground are.

Core concepts ​

ConceptWhat it is
Sandbox (instance)A concrete container launched from a template. Tracks a desiredState (what you asked for) versus an actualState (what the runner reports). Can be ephemeral or persistent.
TemplateA reusable recipe — base image, runtime, isolation level, default resources, env, and toolbox port — that new sandboxes are launched from.
VolumePersistent storage mounted at /workspace, backed by object storage (S3 or Azure Blob). Survives instance deletion and can be attached to or detached from a sandbox.
SnapshotA point-in-time image of a sandbox's filesystem (docker commit). A snapshot lives on the runner; a backup is also exported to object storage. Used to resume or fork.
RunnerThe compute node that actually runs containers. Either an external agent (remote/DinD/Kubernetes) the console polls, or the built-in Docker-direct runner that talks to the local Docker daemon in-process.
Terminal sessionAn interactive WebSocket-multiplexed PTY into a running sandbox, auto-closed after a TTL.

The relationships: a project owns runners, templates, volumes, snapshots, and sandboxes. A sandbox references one template, optionally one volume, and may have many snapshots.

Create a sandbox ​

New sandbox (on the Sandboxes list) opens a full-screen form that launches a sandbox from a template. To start one from a snapshot instead, use Resume on the snapshot (see Volumes & snapshots).

New sandbox form

Fields:

  1. Name — a human label. Required.
  2. Template — the base image and runtime to launch (e.g. Python 3.12, Node.js 22, or the multi-runtime Cognipeer Sandbox base).
  3. Volume (optional) — attach a persistent volume mounted at /workspace. None means an ephemeral workspace that disappears when the container is removed.
  4. Resources — vCPU / memory (MB) / disk (MB) for this sandbox. Leave a field blank to inherit the project default, then the platform default (see Resource limits). Values above the operator cap are clamped on launch.
  5. Persistent — when checked, the sandbox keeps its files when it stops. Ephemeral sandboxes are deleted once idle; a persistent sandbox is not deleted but goes to sleep after a period without use and starts again when something uses it (see Idle timeout and sleep).
  6. Stop after idle (minutes) — this sandbox's own idle window, within the range shown in the field; blank uses the default.
  7. Private — only you can run commands, open files, the terminal or the preview. See Private sandboxes.
  8. Block all network access — ticked by default in this form. All outbound traffic from the container is blocked, and preview is disabled with it (a blocked sandbox has no preview). Untick it when the sandbox needs the internet, for example for package installs. The choice is made when the sandbox is created and cannot be changed afterwards; a runtime that cannot cut a sandbox off shows the box disabled. Through the API the default is the opposite: a sandbox created without blockNetwork has full network access.
  9. Enable port preview / Allow public share links — both are off in this form (a sandbox is private unless you opt in); choose public (session-less share links) vs private (login-only). Through the API preview is on unless previewEnabled is false. Both are also editable later from the Preview tab.
  10. Environment variables — per-sandbox env, merged over the template's defaults. Values are write-only: see Environment variables are sealed. Each row can also take its value from Config instead — see Environment variables from Config.

Submitting calls POST /api/sandbox/instances, which records the sandbox in pending, picks a runner, and enqueues a create-sandbox command. The runner pulls/starts the container and reports back; the row flips to running.

Sandboxes list ​

Sandboxes is the full list of running and stopped containers, with All and Running filters, a search box and, per row, Terminal and a ⋯ menu with the other actions (start, stop, snapshot, fork, delete).

Sandboxes list

The CPU and RAM columns show live usage (the line above the table sums them for the page), and Last activity is the most recent command, file operation, terminal or preview request. Badges under the name mark a persistent sandbox and one with network blocked (no-net).

Inspect a sandbox ​

Clicking a row opens the detail screen, organised into tabs: Overview, Terminal, Files, Preview, and Metrics.

Overview ​

Sandbox detail: Overview tab

The overview is the operational summary: live resource use against the limits, listening ports, the lifecycle (running since, last activity, created by), and the properties: isolation, network, auto-stop, visibility, the attached volume (or none), class and container. The header shows the template, image and ID and carries the Terminal, Stop, Snapshot and Fork actions, with the rest (such as delete) under ⋯.

Metrics ​

Sandbox detail: Metrics tab

Live container stats sampled from the runner: uptime, CPU percentage, and memory used against the limit. If the runner cannot report stats, the panel says so rather than showing stale numbers.

Preview ​

The Preview tab reaches a web service you start inside the sandbox — a dev server, a built app, an API — from your browser. This makes the dev-agent loop work end to end: an agent writes code, starts npm run dev (or python -m http.server, vite, …), and you open the result; once it's right, the agent commits and pushes to git (the sandbox has full network egress unless it was created with network blocked, which is the default in the New sandbox form but not in the API).

How it works — and why it needs no ingress, DNS, or subdomain change:

  • Any port works — you (or the agent) choose the port; there is no fixed list. The common dev ports (3000, 5173, 8000, 8080, override with SANDBOX_PREVIEW_PORTS, plus any ports declared on the template) are pre-published to ephemeral host ports when the container starts; a request for any other port transparently provisions a tiny on-demand forwarder, so it reaches the service all the same. (Set SANDBOX_PREVIEW_ALL_PORTS=off to restrict preview back to the pre-published set.)
  • The one requirement: the service must listen on 0.0.0.0, not just 127.0.0.1 — the Preview tab flags loopback-only listeners.
  • The Preview tab also detects listening ports live: every TCP port something is actually listening on inside the sandbox is listed with its state, next to a free-form "open any port" field.
  • A request to /api/sandbox/instances/:id/preview/:port/* is proxied — riding the console's existing origin under a path — to that port inside the sandbox. Open launches it in a new tab (authenticated by your dashboard session).
  • HTML responses get a <base href> injected so a dev server emitting relative asset URLs renders correctly under the sub-path. For apps that hardcode absolute root paths, configure their base path (Vite base, Next basePath, CRA PUBLIC_URL).
  • Share link issues a short-lived, signed, session-less URL (/api/sandbox/preview/<token>/) so you can hand a running app to someone without a dashboard login — for any port. Sharing is enabled by setting SANDBOX_PREVIEW_SECRET; links default to a 24-hour TTL.

Previewing requires the sandbox to be running and network not blocked. WebSocket upgrades (e.g. Vite HMR) are not proxied — the app still renders; only live-reload over WS is unavailable.

Per-sandbox toggles (top of the Preview tab, set at create time or live afterwards):

  • Preview enabled — turn preview on/off for this sandbox. When off, both the authenticated proxy and any share links are refused (applied instantly, no restart).
  • Public access — when on, session-less share links can be issued; when off the preview is private, reachable only through the authenticated proxy (a logged-in project member). Toggling public off immediately revokes already-minted share links. Public links additionally need SANDBOX_PREVIEW_SECRET on the server.

The same controls are on the token API for agents: GET /api/client/v1/sandbox/sandboxes/:id returns preview.{enabled,public,allPorts,ports,sharingEnabled}, GET …/:id/preview-listening lists the ports currently in LISTEN state (with a loopbackOnly flag), PATCH …/:id/preview toggles {enabled,public}, and POST …/:id/preview-tokens mints a share link for any port (only when the sandbox is enabled + public). Both flags are also accepted on create (previewEnabled, previewPublic).

Terminal ​

Open terminal on the Terminal tab (or Terminal in the header) opens an interactive PTY into the running container in a full-screen window. The browser connects to a session over WebSocket while the runner attaches the container side; keystrokes and output stream through the console's terminal session manager.

Sandbox terminal

Sessions auto-close after the configured TTL (default 1 hour). A sandbox must be running to open one.

Files ​

Sandbox detail: Files tab

A live browser of the container filesystem (served through the in-container toolbox). When the sandbox has an attached volume, /workspace is that volume; otherwise it is the container's ephemeral disk. You can navigate directories, upload files, and download or delete entries. When a sandbox is stopped but has a volume, the same tab browses the persisted object store instead.

Templates ​

Templates lists the base images new sandboxes launch from. Each row shows the key, display name, image, runtime, and isolation level.

Templates

  • New template registers a custom recipe — base image, runtime, isolation, default resources, env, entrypoint, and the toolbox port (default 8787).
  • Seed defaults idempotently loads the built-in library (Python, Node, data-science, web, and the multi-runtime cognipeer/sandbox-base image).
  • Each row has Edit (update the recipe in place — the key stays fixed since other config resolves it by it) and Delete.
  • Templates are shared by every project of the workspace, so creating, editing, deleting and seeding them — and Promote to template on a sandbox — needs a workspace owner or admin.

Environment variables are sealed ​

The environment variables of a template and of a sandbox are encrypted at rest and write-only. Use them for secrets the sandbox needs (an API key for a tool the agent runs inside it).

  • The API and the UI never return a value. A read shows each variable as •••••• plus the list of variable names (env_keys).
  • To change variables, send the map you want: a string replaces a value, null deletes the variable, and the mask •••••• (or leaving the key out while env_keys is kept) means unchanged. In the UI, each variable has a Replace action instead of a value you can edit.
  • Names must match ^[A-Za-z_][A-Za-z0-9_]{0,127}$, a value is at most 32 KiB, and a template or sandbox holds at most 100 variables.
  • If the encryption key changed, the stored values cannot be decrypted. A read then marks the template or sandbox envUnreadable: true (the names stay, the values are gone) and the template editor shows a warning. A change that needs the stored values (a mask next to a new value, env_keys, a delete) is refused with 409 sandbox_env_unreadable and leaves the stored ciphertext alone; a change with only masks keeps it, and a value for every variable replaces it. In the UI a row opened with Replace and saved without a value keeps the stored value instead of storing an empty string.
  • Executors decrypt the values only when they start the container. Variables stored in plaintext by earlier versions are sealed the first time they are read.

An agent's own sandbox secrets follow the same rule; see Agent secrets.

The multi-base template uses cognipeer/sandbox-base:latest, which bundles the toolbox/agent so the container stays alive and supports terminals, the filesystem browser, and git operations out of the box.

The web-e2e template (Web app + browser testing) uses cognipeer/sandbox-web-e2e:latest: the base image plus Playwright, Chromium and ffmpeg, so an agent can run an app, drive it in a headless browser and look at the result with read (a screenshot as an image, a recorded video as one contact sheet of frames, a PDF as text plus page images). Launch Chromium with --disable-dev-shm-usage: the sandbox /dev/shm is small. The image is built from docker/sandbox-web-e2e (scripts/build-sandbox-web-e2e.sh). A single Docker host that cannot pull it builds it on first use, on top of the base image, which takes several minutes; Kubernetes runners need it in a registry they can pull from.

The base image includes poppler-utils, which read uses for PDF page images; with an older base image read still returns a PDF's text.

An agent's sandbox ​

Switch on Give this agent a sandbox under Build → Sandbox of an agent and the agent gets an isolated Linux machine it can run commands and code in and read and write files on. It is provisioned only when the agent first uses it. The panel has these blocks:

  • Machine — the Template the sandbox starts from, and CPU cores, Memory (MB) and Disk (MB) (blank = the template or project default, see Resource limits). Block network access is a switch that starts off: a new agent sandbox has network access, so package installs and git pushes work. Switch it on to cut the sandbox off from the network. Preview links do not work while the network is blocked.
  • Lifetime — Session (one sandbox per conversation, kept between messages and deleted once idle or with the conversation), Per message (a fresh sandbox for every message, deleted when the reply is done) or Persistent sandbox (see below). Command timeout (seconds) applies per command, at most 600.
  • Preloaded files, Preview, Tools (which sandbox tools the agent may use), Environment variables, Config groups and Secrets.

Conversation files in /inputs/ ​

Files a person attaches to the conversation (a zip, a project, a spreadsheet) are copied into the agent's sandbox at /inputs/, so the agent can work on them with its shell (ls, grep, unzip) instead of reading only their text through the read tool. The files the agent writes for the person go to /outputs/ (see File outputs).

  • The copy is made whenever the sandbox is provisioned for a turn, so a file attached in a later turn arrives too. A file already there with the same size is not sent again.
  • At most 25 files, 25 MB each; when a conversation holds more, the newest win. A file that is too large or cannot be written is skipped, the turn still runs, and the agent is told which files are missing. Files the agent itself produced are not copied back.
  • When two files have the same name, the later one is written as <file id>_<name>.
  • A shared persistent sandbox gets no copies, because what is written there can be seen by other conversations. The agent's system prompt only mentions /inputs/ when copies are made.

A persistent sandbox for an agent ​

An agent's sandbox (Build → Agents → your agent → Build → Sandbox → Lifetime) is normally its own: one per conversation (Session) or one per message (Per message). Persistent sandbox gives the agent an existing sandbox of the project instead — one created with Persistent on — picked under Machine (config.sandbox.mode: "instance", config.sandbox.instanceId).

  • Shared. Every conversation of the agent, and anyone else with access to the sandbox, works on the same machine: files and installed packages stay until someone deletes them, and what the agent writes can be seen by others. The model is told so.
  • The machine's own settings apply. Its template, resources, network block and environment are its own; the agent's Template, CPU, memory, disk and Block network settings are not used. The agent's plain variables go with each command (like its secrets) instead of onto the machine.
  • Never created, stopped or deleted by the agent. A stopped sandbox is started on first use; nothing is recorded on the conversation, and deleting a conversation leaves the sandbox alone. A preview link keeps working because the machine stays up.
  • Outputs. Only files written to /outputs/ during a reply are delivered as session files — not what the shared machine already held.
  • Who may choose it. Setting or changing the sandbox needs write access to Sandbox in the project (403 sandbox_write_required otherwise); re-saving the agent asks nothing. The sandbox must be a persistent sandbox of the agent's project (400 otherwise). Manifest exports leave the id out; importing over an agent keeps the one it has.

Sandbox over MCP ​

The MCP module can serve sandboxes as an internal service (Build → MCP Servers → New MCP server → Source type → Internal service), with the MCP module's endpoints, tool toggles and renames, guardrail binding, logs and hubs:

  • Sandbox — pick a template. Callers start their own sandboxes with sandbox_create (it returns a sandboxId), pass the id to sandbox_exec, sandbox_run_code, sandbox_read_file, sandbox_write_file and sandbox_list_files, and end them with sandbox_delete. A sandbox is usable only through the MCP server that started it; one left behind is not persistent and is deleted by the idle timeout.
  • Persistent sandbox — pick a persistent sandbox of the project. The same work tools, without a sandboxId, run in that one machine, which is started when it is stopped and never stopped or deleted through MCP. Every caller shares it.

Both run code, so they have no public URL: such a server, and a composite with one as a member, is always called with an API token. Creating one, or pointing one at another template or sandbox, needs write access to Sandbox. Both need the Sandbox module and an Enterprise license (checked on every call), and the values a sandbox's launch carries are masked in their results, as for an agent.

Preloaded files (agent sandbox) ​

An agent's sandbox settings (Build → Agents → your agent → Build → Sandbox → Preloaded files) can carry files that are written into the sandbox automatically when it starts, before the agent works: for example a presentation template (.pptx).

  • Click Add file (or drop files on the list) and type the destination path for each. The suggestion is /workspace/templates/<file name>; parent folders are created for you.
  • Paths must be absolute, include the file name, be normalized (no .., //, ./), and must not be under /proc, /sys, /dev, /etc, /bin, /sbin, /usr or /lib. Two files cannot share a destination.
  • Limits: 25 files, 25 MB each, 100 MB in total. The bytes are stored in the agent's attachments bucket (Build → Files) under agent-assets/<agent key>/, so that bucket must be set up.
  • Works for both session and ephemeral sandboxes. A reused session sandbox only gets files that are missing or whose content changed (checked by SHA-256).
  • The agent's system prompt gets a "Preloaded files" list (path and name). If a file cannot be written the turn still runs: the failure is logged and the first command result carries a notice naming the files that are not available.
  • The files are listed under config.sandbox.seedFiles. They are written without the agent's secrets in the environment (see Environment variables are sealed).

Agent secrets (agent sandbox) ​

Build → Sandbox → Secrets holds API keys, tokens and passwords an agent's sandbox commands need. Each sandbox_exec / sandbox_run_code call gets them as environment variables for that command only; they are not set on the sandbox machine. The agent is told the names, never the values.

  • Write-only. Secrets are sealed on save and shown back as names with a masked value (••••••). Sending a key back with the mask keeps the stored value, a new value replaces it, a key left out is removed. They are never part of version snapshots, publish responses, manifest exports or the agent's other configuration reads.
  • Masked where they could leak. A value (four characters or more) that appears in command output is replaced with •••••• before the model sees it, and so it is in the text files collected from /outputs/ before they become session files. Binary files (a NUL byte or invalid UTF-8) and zip-based formats and PDF are not scrubbed, and neither is a value that was transformed (base64, split, URL-encoded). Masking does not stop a script from sending a value over the network: use short-lived, least-privilege keys.
  • Preloaded files are written without secrets. The commands that write preloaded files at start run with no secrets in their environment; the agent's own commands afterwards get them.
  • When the key changed. Secrets are encrypted with the platform's encryption key. If it changed, the stored secrets cannot be read: the agent reads back with config.sandbox.secretsUnreadable: true and an empty secrets list, and the sandbox panel shows a warning. The agent's sandbox tools keep running without the secrets and say so in their result. A save that mixes masked values with new ones is refused with 409 sandbox_secrets_unreadable (a mask stands for a value that cannot be recovered); a save that sends only masks keeps the stored (unreadable) secrets, and a save that enters every value again, with no masks, replaces them. The 409 body is { error, type, code: "sandbox_secrets_unreadable", field: "config.sandbox.secrets" }, on PATCH /api/client/v1/agents/{agentKey} and on the dashboard save.

Environment variables from Config ​

Wherever you enter environment variables or secrets for a sandbox — a template, New sandbox, and an agent's Build → Sandbox (Environment variables and Secrets) — each row has a Value | Config switch. On Config you pick an item from the project's Config instead of typing the value.

  • One item per variable — pick the item for a row, or use + Add from Config to tick several items at once; each gets a suggested name from its key (cfg-openai-api-key → OPENAI_API_KEY), which you can change.
  • A whole group — bind a config group (Groups tab of + Add from Config, or Config groups on the agent): every item in it, now and later, becomes a variable named from its key.
  • Precedence — a variable you set by name (typed value or a single item) wins over a bound group; between groups the first one wins. For a sandbox: template values < template Config values < sandbox values < sandbox Config values.
  • Secrets on an agent — under Environment variables only non-secret items can be picked; secret items go under Secrets. Secret items of a bound group are passed like Secrets (per command, masked in output); the others are set like environment variables.
  • Masking in agent output — an agent's tool output is masked for its Secrets and for the secret Config items its sandbox takes. Typed environment variables, on the agent or the template, are not masked: they are ordinary settings as often as not. Keep secret values in Secrets or in secret Config items.

Only the reference is stored, never the value. The value is read when it is used — when an agent run starts, or when a sandbox launches — in the project where it is used:

  • A sandbox fails to launch with a clear message when a referenced item was deleted or belongs to another project.
  • An agent run continues without a missing item, and the model is told which variables are unavailable.
  • Templates that use Config values are not kept in the warm pool (warm machines belong to no project).
  • Pointing a variable at a new item or group needs read access to Config in that project; re-saving references that are already stored needs nothing.

On the Config side, an item or group shows Used by — the agents and templates that read it — and deleting one warns about them first.

How a sandbox receives its environment ​

A sandbox's launch values — template and sandbox variables, typed or from Config — reach it in one of two ways. The installation picks one with SANDBOX_ENV_DELIVERY (Helm: sandbox.envDelivery); each sandbox keeps the way it was created with, so a change applies to sandboxes created afterwards.

legacy (default)file
Where the values areOn the container or pod spec, as in earlier versionsIn /run/cognipeer/env, a file in a memory-backed mount (tmpfs on Docker, a Memory emptyDir on Kubernetes), mode 0600, written after the sandbox starts
Container / pod spec and snapshot imagesHold the valuesHold none of them
Secret Config itemsCannot be bound; secret items of a bound group are left outSupported, one by one or through a group
Runtime modesAlldocker and kubernetes (other modes stay legacy)

With file delivery, commands, code runs, terminals and the console's own file and git operations load the file before they run, so programs see the same variables as before. If the sandbox loses the file — the engine restarted, the pod was recreated — the console writes it again before the next command. A volume cannot be mounted at /run/cognipeer. Terminals of these sandboxes do not save shell history.

With legacy delivery, a sandbox that already exists keeps starting when an item it uses is made secret later: the item is left out of its launch and a warning is logged. A new sandbox from the same template is refused until the item is unbound or the installation uses file.

Everything a sandbox receives is readable by the code that runs in it: give a sandbox only the values that code is meant to use.

A snapshot of a file sandbox carries its values (sealed) and Config references, so a restore or fork starts with them. A snapshot of a legacy sandbox restores as legacy, whatever the current setting, because its image holds the values.

On the token API, POST /api/client/v1/sandbox/sandboxes/:id/exec and /code accept env — { "NAME": "value" } for that command only, taking precedence over a launch value of the same name. Numbers and booleans are passed as strings. An env that is not an object, a name that is not a valid variable name, or a value containing a NUL byte, is refused with 400.

Volumes & snapshots ​

Volumes manages persistent storage and the snapshot archive on one page.

Volumes & Snapshots

  • Volumes are object-storage-backed workspaces. Each is created from a file bucket (which supplies the provider, container, and credentials) and shows its provider, container, and isolated prefix. Attaching a volume to a sandbox mounts it at /workspace; detaching recreates the container without it. Volume data survives sandbox deletion.
  • Snapshots are point-in-time images. Use the Snapshot action on a running sandbox to capture one; a snapshot can be restored into a new sandbox or forked (snapshot + copy the volume data + launch an independent clone). A backup snapshot is additionally exported to object storage so it survives a runner restart.

Playground ​

The Playground is an interactive REPL bound to a running sandbox — pick a sandbox, then run code or shell commands and watch the output live.

Playground

Each cell is Python, Node, TS, Bash, Shell or API; press Run on a cell or Run all, and every run keeps its output under the cell. It is the fastest way to confirm a sandbox is healthy and to prototype the exact exec / code calls an agent will make.

Settings ​

Settings holds the project-wide defaults and lifecycle policy.

Sandbox settings

SettingDefaultEffect
Terminal session TTL3600 sHow long an idle terminal session stays open before it is closed.
Idle timeout1800 sHow long an ephemeral sandbox may sit idle before the reaper stops and deletes it. 0 disables idle cleanup.
Persistent sandbox sleep (minutes)10 minHow long a persistent sandbox may sit idle before it is stopped. Its files are kept and it starts again when it is used. Allowed range 1 minute to 4 hours (the upper end is SANDBOX_IDLE_STOP_MAX_SECONDS); blank uses the platform default. A sandbox can set its own window within the same range.
Active sandboxes per project / per userno limitThe most active sandboxes one project, or one user, may have at once. A create, start or wake over the limit is refused with 429 sandbox_quota_reached and the reason. 0 means no limit; blank uses the platform default.
Default isolationruncContainer isolation level applied to new templates (runc, gvisor, …).

The page also shows the Platform limits set by environment variables (read-only), the Project resource defaults card and the Warm pools list.

The reaper scans on a fixed interval and skips any sandbox that has a live terminal session, so an interactive session won't be pulled out from under you.

Idle timeout and sleep ​

Persistent sandboxes are not exempt from idle cleanup. When one has had no activity for its window (its own Stop after idle, else the workspace's Persistent sandbox sleep, else the platform default of 10 minutes) it is stopped, not deleted, and its files are kept. Exec, code, file, git, terminal and preview requests start a stopped persistent sandbox again.

  • There is no "always on" setting: a window set in the dashboard or on a sandbox is between 1 minute and 4 hours (SANDBOX_IDLE_STOP_MAX_SECONDS).
  • A sandbox is not stopped while a long command or an agent turn holds it, nor while it is still using CPU (a build, a training run), up to a grace period.
  • A runtime that cannot keep files across a stop (the Kubernetes runtime with SANDBOX_K8S_PERSIST=off) never puts a persistent sandbox to sleep on the platform's window; only the sandbox's own Stop after idle applies, and stopping it loses its files.
  • With the Enterprise Docker-in-Docker chart the engine's data is kept on emptyDir volumes of the Cognipeer pod: a persistent sandbox survives its own sleep, but not the pod being replaced. For workspaces that outlive the pod use the Kubernetes runtime.

Resource limits ​

New sandboxes default to 0.5 vCPU / 1 GB RAM / 1 GB disk. The effective limit for a launch is resolved in layers — first defined wins per field, then clamped to the operator hard cap:

  1. Per-sandbox — the Resources fields in the create dialog (or resources in the API). For an agent's own sandbox, the CPU cores, Memory (MB) and Disk (MB) fields under Build → Sandbox → Machine (config.sandbox.resources; diskMb accepts 256 to 262144, blank follows the chain below).
  2. Per-project — the Project resource defaults card on the Settings page (stored against the active project).
  3. Platform default — SANDBOX_DEFAULT_CPU / _MEMORY_MB / _DISK_MB / _PIDS (env), falling back to the built-in 0.5 / 1024 / 1024 / 512.
  4. Hard cap — SANDBOX_MAX_CPU / _MEMORY_MB / _DISK_MB / _PIDS (env). Operator-owned; the UI and token API can never exceed it. 0/unset = unbounded.

CPU and memory are always enforced by the container engine. Disk (diskMb) is enforced only when SANDBOX_DISK_QUOTA=on and the Docker storage driver supports --storage-opt size (overlay2 on xfs pquota, or btrfs); otherwise it is tracked and shown but advisory. On the Kubernetes runtime disk is always enforced: it becomes the pod's ephemeral-storage limit, and a sandbox that writes past it is evicted by the kubelet.

Runtime architecture ​

A sandbox is driven by a runner. The console never blocks on container work — it enqueues a command and reconciles state from the events the runner reports back.

┌────────────────────┐   enqueue command    ┌─────────────────────┐
│      Console       │ ───────────────────▶ │       Runner        │
│  (control plane)   │                       │   (data plane)      │
│                    │ ◀─── poll /commands ─ │  - docker run/exec  │
│  command queue     │ ──── events ────────▶ │  - commit / save    │
│  event ingestor    │                       │  - terminal PTY     │
│  reconcile / reaper│                       │  - FUSE volume mount│
└────────────────────┘                       └─────────────────────┘

Two execution models:

  • Agent runner — an external process (remote Docker-in-Docker, a Kubernetes pod, or a fleet-managed host) handshakes with a one-time registration token, then long-polls the console for commands and posts events back. This is how the sandbox scales horizontally.
  • Docker-direct — a synthetic in-console runner (local-docker-direct) that executes commands against the local Docker daemon in-process. Ideal for single-host and self-hosted setups; limited to local docker volumes (no cloud-volume FUSE mount or snapshot export).

Supporting loops keep the system consistent:

  • Reconcile runs once at boot: it re-spawns console-managed runners and re-drives any sandbox that should be running, clearing stuck pending states after a restart.
  • Reaper runs periodically: it deletes ephemeral sandboxes once idle (per-template → tenant → config window) and puts idle persistent ones to sleep, keeping their files (see Idle timeout and sleep).
  • Command queue is FIFO per runner, so dependent operations (e.g. detach-then-recreate for a volume change) always execute in order.

Agent conversation lifecycle ​

When an agent is configured to use the sandbox, the default lifecycle is now one sandbox per active conversation session rather than one fresh sandbox per turn. A follow-up turn in the same conversation reuses the existing sandbox while it is still available, which keeps in-sandbox state such as installed packages, generated files, and working-directory changes available across turns.

That reused sandbox is not permanent: once it goes idle long enough to be reaped, the next turn starts a new sandbox. If your workflow needs state to survive beyond the idle window, use the sandbox's own persistent mechanisms such as volumes or snapshots rather than relying on the conversation session alone.

API surface ​

Every screen above is backed by the /api/sandbox/* admin API (cookie-authenticated, RBAC service sandbox). The most-used endpoints:

Method & pathPurpose
GET /api/sandbox/instancesList sandboxes
POST /api/sandbox/instancesCreate a sandbox
POST /api/sandbox/instances/:id/start · /stopStart / stop
DELETE /api/sandbox/instances/:idDelete
POST /api/sandbox/instances/:id/execRun a shell command, return exit/stdout/stderr
POST /api/sandbox/instances/:id/codeRun a code block (python/javascript/typescript/bash)
POST /api/sandbox/instances/:id/terminalOpen a terminal session (returns a WebSocket path)
GET /api/sandbox/instances/:id/previewPreview state: enabled/public/allPorts + suggested ports
GET /api/sandbox/instances/:id/preview-listeningPorts currently LISTENing inside the sandbox
PATCH /api/sandbox/instances/:id/previewToggle preview {enabled, public}
ALL /api/sandbox/instances/:id/preview/:port/*Proxy to a port inside the sandbox (authenticated)
POST /api/sandbox/instances/:id/preview-tokensMint a session-less share link for a port
ALL /api/sandbox/preview/:token/*Public preview proxy (signed token, no session)
GET PUT /api/sandbox/resource-configRead / set the active project's resource defaults
POST /api/sandbox/instances/:id/snapshot · /forkCapture / clone
POST /api/sandbox/instances/:id/volume · DELETE …Attach / detach a volume
GET POST /api/sandbox/templates · /templates/seedManage templates
PATCH DELETE /api/sandbox/templates/:idEdit / remove a template
GET POST /api/sandbox/volumes · /volumes/:id/filesManage volumes and volume files
GET /api/sandbox/snapshots · /snapshots/:id/restoreList / restore snapshots
GET PUT /api/sandbox/settingsRead / update project settings

Template and sandbox writes (POST /api/sandbox/templates, PATCH /api/sandbox/templates/:id, POST /api/sandbox/instances) take envRefs — { "NAME": { "configId": "…" } } or { "configKey": "…" } — and groupRefs — [{ "groupId": "…" }] or [{ "groupKey": "…" }] — next to env; responses return them as stored ({ configId, key, groupId } / { groupId, key }). On a template PATCH a field that is sent replaces the whole map/list (null, {} or [] clears it) and a field that is left out is kept. A name set both in env and envRefs is refused (400); adding a new item or group without Config read is refused with 403 config_read_required.

A sandbox that takes values from Config needs read access to Config in its project, otherwise 403 config_read_required, on the admin API and the token API alike, for:

  • running commands in it: exec, code, terminal, toolbox and file reads;
  • copying it: snapshot and fork;
  • using its volume: uploading to it, reading or writing its files, attaching it to another sandbox.

A caller without that access sees envRefs and groupRefs with ids only, without item and group names. Template writes, seeding and promote need a workspace owner or admin (403 tenant_admin_required).

A volume created from the dashboard belongs to the active project, and its file bucket and storage provider come from that project. Volumes bound to a project are listed and usable only from that project (another project's volume answers 404); volumes without a project, from earlier versions, stay workspace-wide. Reading volume files needs sandbox admin (403 sandbox_admin_required).

External runners use a separate bearer-token API under /api/sandbox/agent/:tenantSlug/* (handshake, heartbeat, commands, events), and terminals relay over WS /api/sandbox/terminal/:sessionId/browser.

Configuration ​

Beyond the in-app Settings, a few environment variables tune the runtime:

VariableDefaultPurpose
SANDBOX_EXECUTORagentExecution model: agent or docker-direct.
SANDBOX_IDLE_REAP_SECONDS1800Fallback idle window for ephemeral sandboxes.
SANDBOX_SNAPSHOT_CONTAINERcognipeer-sandboxDefault object-storage container for snapshot backups.
SANDBOX_BASE_IMAGE—Override the base image used for the multi-runtime template.
SANDBOX_CONSOLE_URLhttp://localhost:$PORTCallback URL advertised to console-managed runners.
SANDBOX_PREVIEW_PORTS3000,5173,8000,8080Ports published for preview (comma list; a-b ranges allowed).
SANDBOX_PREVIEW_PROXY_HOSTautoHost the published ports are reached at. Auto-derived from DOCKER_HOST (tcp://host:… → host), else 127.0.0.1. Set when the console can't reach the engine host directly.
SANDBOX_PREVIEW_SECRET—HMAC secret enabling session-less share links. Unset = sharing disabled (authenticated preview still works).
SANDBOX_DEFAULT_CPU / _MEMORY_MB / _DISK_MB / _PIDS0.5 / 1024 / 1024 / 512Platform default resource limits for new sandboxes.
SANDBOX_MAX_CPU / _MEMORY_MB / _DISK_MB / _PIDS—Hard upper bound per field (0/unset = unbounded). Clamps every launch.
SANDBOX_DISK_QUOTAoffon enforces diskMb via --storage-opt size (needs xfs-pquota / btrfs); otherwise disk is advisory.
SANDBOX_ENV_DELIVERYlegacyfile gives new sandboxes their launch values through an in-memory file instead of the container spec, and allows secret Config items; see How a sandbox receives its environment.
SANDBOX_WORK_ROOT<tmpdir>/cognipeer-sandboxWorking directory of the Docker runtime (snapshot tarballs). Created owner-only; point it at a dedicated volume in containers.
SANDBOX_NETWORK_MODE—docker run --network for sandboxes (none blocks networking). host and container:<name> are not accepted for new sandboxes; a sandbox that exists keeps the network it was created with.
SANDBOX_RUNTIME_MODEdockerWhere Enterprise sandboxes run: docker (the local engine, also the Docker-in-Docker chart), jail (a sandbox-host) or kubernetes (k8s is accepted); see Sandbox on Kubernetes.
SANDBOX_MAX_CONCURRENT0Most active sandboxes the whole workspace may have; 0 = no limit. A create, start or wake over it is refused with 429 sandbox_quota_reached.
SANDBOX_MAX_ACTIVE_PER_PROJECT / _PER_USER0Platform default of the per-project and per-user limits (0 = no limit). The workspace's Settings values override them.
SANDBOX_MAX_DURATION_SECONDS0Age after which an ephemeral sandbox is deleted, however active it is; 0 = no cap. A hold or CPU use never postpones it.
SANDBOX_REAP_INTERVAL_SECONDS60How often the reaper scans for idle sandboxes.
SANDBOX_PERSISTENT_IDLE_STOP_SECONDS600Default idle window of a persistent sandbox before it sleeps. 0 = never stop; only this platform variable can say so. The workspace's Persistent sandbox sleep overrides it within the allowed range.
SANDBOX_IDLE_STOP_MAX_SECONDS14400Longest idle window a workspace or a sandbox may set (the shortest is 60 s).
SANDBOX_MAX_HOLD_SECONDS3600Longest time one long-running command may keep a sandbox from being stopped.
SANDBOX_IDLE_BUSY_CPU_PERCENT / SANDBOX_IDLE_BUSY_GRACE_SECONDS10 / 14400An idle-looking sandbox using at least this much CPU is left running for up to the grace period past its window.
AGENT_SANDBOX_TURN_HOLD_SECONDS900How long an agent's turn keeps its sandbox from being stopped by the reaper. 0 = no hold.
AGENT_SANDBOX_READY_TIMEOUT_MS90000How long an agent waits for its sandbox to become ready.
MCP_SANDBOX_INSTANCE_READY_TIMEOUT_MS60000How long a sandbox served over MCP is awaited.
MCP_SANDBOX_BRIDGE_PORT8808Port of the MCP bridge inside such a sandbox; it is reserved and cannot be previewed.
SANDBOX_ACCESS_GRANT_SECONDS3600Length of the access a sandbox admin is granted to a private sandbox (at least 60).
SANDBOX_IMAGE_ALLOWLIST—Comma-separated image references or prefix* patterns a template may use on the Docker runtime. Unset = any image.
SANDBOX_WARM_POOL_INTERVAL_SECONDS60How often the warm pool is refilled (at least 10).
SANDBOX_FAILED_RETENTION_SECONDS3600How long a failed sandbox record is kept before it is cleaned up; 0 = keep.
SANDBOX_FILE_DOWNLOAD_MAX_BYTES104857600Largest file the file-download endpoint streams out of a sandbox.
SANDBOX_TOOLBOX_SECRETthe session signing secretSecret the per-sandbox toolbox token is derived from. Set it to keep the tokens independent of the key that signs sessions.
SANDBOX_BACKUP_SNAPSHOTS_RETAIN5Backup snapshots kept per sandbox, newest first.
SANDBOX_API_LICENSE_ENFORCEoffWhether the client sandbox API refuses a workspace without an Enterprise licence; see the licence check.

Security & tenant isolation ​

  • Every request is bound to the calling tenant's database for the full async execution, preventing cross-tenant reads under concurrency.
  • Runner agents authenticate with hashed tokens: a one-time registration token (sbref_…) exchanged at handshake for a long-lived agent token (sbat_…), compared in constant time and rotatable from the UI.
  • Block network access removes outbound connectivity for a sandbox; the isolation level (runc, gvisor, …) governs container-to-host isolation.
  • Preview share links are HMAC-signed capability tokens scoped to a single instance + port with a short TTL — anyone with the link reaches only that one port, and only until it expires. Sharing is off unless SANDBOX_PREVIEW_SECRET is set. The authenticated preview proxy stays bound to the caller's session and project.
  • Launch values stay off the container spec with file delivery — they live in a memory-backed file inside the sandbox and are not written to snapshot images; see How a sandbox receives its environment.
  • Config access carries over to sandboxes. Running commands in, or reading files of, a sandbox that takes values from Config needs Config read access in its project; templates, which every project shares, are changed by workspace owners and admins only.
  • Git credentials are used for one operation. A username and password or token given to clone, pull or push authenticate that operation only, so pass them again on each pull or push. They are not written into the repository's configuration or kept by the console, and they are offered only to the host being cloned from, or to origin's host on pull and push, never to another host a redirect or submodule points at. While they are in use, repository hooks do not run, except Git LFS's pre-push.
  • Agent tool output is masked for the agent's Secrets and the secret Config items its sandbox takes, including their shell-quoted form and, for a value of several lines such as a key, each of its lines.
  • Terminal history is not saved in sandboxes with file delivery: their terminals start with HISTFILE=/dev/null. legacy sandboxes keep their shell history as before.
  • Error messages are cleaned of environment values and URL credentials before the API returns or logs them.
  • Sandbox environment variables are sealed and masked on edit. The edit flows treat them as write-only secrets rather than a readable settings field, so operational procedures should store the source value elsewhere if they need to rotate it later — or keep the value in Config and reference it (Environment variables from Config), so a rotation in Config reaches every sandbox launched after it.

Where to go next ​

  • Sandbox on Kubernetes — the Kubernetes and Kata runtime, private sandboxes, limits and the Helm chart.
  • File Storage — the buckets that back sandbox volumes and snapshot exports.
  • Multi-Tenancy — how the per-request tenant binding the sandbox relies on works.
  • Licensing — enabling enterprise modules.

Studio · Pulse · Console · Agent SDK and more — the Cognipeer documentation hub · Contact Support