Agent Sandboxing

Run OpenCode agent shell tool commands inside an isolated microVM instead of directly in the Manager container. Sandboxing does not restrict trusted OpenCode configuration or extensions and is not a per-project permission boundary.

Sandboxing is per session. Each sandboxed session gets its own microVM that mounts only that session's repository, so one session cannot see another session's repositories. Sandbox support is switched on for the server once; each session then carries its own sandbox flag.

Turning Sandboxing On

Sandboxing needs a Linux host with /dev/kvm and the sandbox compose overlay. Start the Manager with the overlay:

docker compose -f docker-compose.yml -f docker-compose.sandbox.yml up -d

Then:

  1. Open Settings → OpenCode Config → Server maintenance → Sandbox.
  2. Turn on Sandbox. If the host cannot sandbox, the section shows the reason and the switch stays disabled.
  3. Restart the OpenCode server when prompted.

The switch turns on sandbox support for the server, and it is restart-gated: until the OpenCode server restarts, the running server keeps its previous state. Enabling support does not sandbox existing sessions by itself — see Per-Session Sandboxing.

Docker Desktop on macOS and Windows cannot provide /dev/kvm, so the switch stays disabled there. See Host Requirements for the overlay's devices and capabilities.

Per-Session Sandboxing

Once support is on, every root session has its own sandbox flag:

  • New sessions start sandboxed when Sandbox new sessions by default is on (the default). Turn it off to make new sessions start unsandboxed.
  • Desktop composer — the box icon next to the permission toggle opens a menu with Sandbox commands and, for a sandboxed session, Sandbox resources….
  • Mobile composer — the same items are in the composer options menu, behind the + button.
  • Child sessions inherit their root session's flag and cannot be toggled on their own; the menu shows Inherited from parent session.
  • Scheduled runs — a schedule job's Run in sandbox option sandboxes each run's session and its subagents; see Schedules → Sandbox.
  • Toggling a session, and changing its resources, applies immediately with no restart.

While server support is off, the control is hidden and every session reports unsandboxed.

What Gets Sandboxed

Execution pathSandboxed
Agent shell tool calls in a sandboxed sessionYes
Subagent shell tool callsYes, in their root session's microVM
Agent shell tool calls in an unsandboxed sessionNo; run on the host
WebUI !command shell mode (POST /api/session/:sessionID/shell)No; it is not attributed to a session, so it runs on the host
Shell API (POST /api/shell)No; runs on the host
Slash-command shell templates (!`cmd`)No; OpenCode expands each interpolation with the configured shell, on the host
PTY terminals, including the Terminal panel and project actionsNo; normal OpenCode behavior with the configured shell
OpenCode file tools, plugins, custom tools, local MCP servers, formatters, LSP servers, hooks, and custom provider modulesNo; normal OpenCode behavior

Only the agent shell tool is routed into a microVM. The command the agent wrote is never rewritten, so the recorded tool call, the permission rules, and the model's own context all keep the original command.

Each sandboxed shell call is marked sandbox in its tool metadata, which the WebUI shows as a green badge on the tool call. When another sandbox provider wins the call — for example an opencode-forge loop session — the badge reads sandbox · <provider>. Metadata is not sent to the model.

Sandboxing fails closed: if a sandboxed session's command cannot be prepared, the call fails instead of running on the host.

One microVM per Sandboxed Session

  • Each sandboxed root session gets its own microVM, created on the session's first sandboxed command. Child sessions run in their root session's microVM.
  • The microVM mounts only the session's repository or worktree, at the same path the Manager uses, plus a small set of shared directories. A session cannot see other repositories from inside its sandbox.
  • It also gets its own Docker data volume, so Docker state is private to the session.
  • The Manager verifies the microVM's image, resources, mounts, network policy, and labels before reuse. A stale or mismatched microVM is removed and recreated automatically, keeping its Docker data volume.
  • A command whose working directory is outside the session's mounts is refused rather than run on the host.

Mounts and Secrets

Each session's microVM receives writable bind mounts for:

Host pathWhy it is mounted
The session's repository or worktreeThe git top level of the session's location directory, or that directory itself when it is not in a repository
The repository's git common directoryOnly for a linked worktree, when it lies outside the top level
/workspace/.opencode/state/opencode/tool-outputWhere OpenCode saves the full content of a truncated tool result before handing the agent that absolute path
/workspace/.config/opencode/skillsGlobal skills, including the scripts and reference files a skill bundles and refers to by absolute path
/workspace/.opencode/tmp/opencodeThe temporary directory OpenCode's environment instructions tell agents to prefer for work outside the workspace

Each is mounted at the identical guest path. That is the point: OpenCode hands the model absolute host paths, and the host-side read, write, and glob tools resolve them against the container. A path that is not mounted resolves for those tools but not for a sandboxed shell call, which is how an agent ends up searching for a file it was just told the exact location of.

Only the session's repository or worktree is a valid working directory. The other mounts are readable and writable but are never a valid working directory, so shell calls still have to run inside a repository or a worktree.

A repository's secrets and variables are resolved on the host for the command's directory and forwarded into the microVM as ordinary environment variables, so sandboxed commands see the same mapped values as host commands.

The microVM also mounts a runtime-owned tmpfs at /tmp, sized to one quarter of the microVM memory and clamped to 1–512 MiB, so agent commands get guest-only scratch space that is not backed by a host filesystem.

The agent temporary directory is separate from that tmpfs. The Manager sets TMPDIR=/workspace/.opencode/tmp on the OpenCode child, which puts OpenCode's own temporary directory at /workspace/.opencode/tmp/opencode — the path its environment instructions advertise — so the same files are visible to sandboxed commands and to the host-side file tools. Everything else under TMPDIR (temporary files from host-side git, gh, and MCP servers) stays out of the guest. The Manager empties the mounted directory each time it starts the OpenCode child, matching the lifetime it had in the container's /tmp; it clears the contents rather than the directory itself, because replacing the directory would detach a running microVM's bind mount.

The following remain outside every microVM:

Host pathContents
/workspace/configSSH configuration and known hosts
/workspace/.ssh-keysRepository SSH private keys
/workspace/.config/opencode/plugins, /workspace/.config/ocmGenerated plugins and the shell shim — the enforcement mechanism itself
/workspace/.config/opencode (except skills)OpenCode configuration
/workspace/.opencode/state (except opencode/tool-output, opencode/worktree, and opencode/forge/worktrees)Provider and MCP credentials, the forge database

OpenCode's host process still reads these paths normally. They are omitted only from the agent command environment.

No internal API token exists anywhere under the mounted roots. The token lives in the Manager's database and reaches the generated plugins only through the OCM_INTERNAL_TOKEN environment variable of the Manager's own OpenCode process, which is never part of the guest environment. Because localhost inside the microVM is the guest rather than the Manager, an agent command cannot call the internal API with curl; agents reach the Manager through the ocm tool instead, which executes in the Manager's own OpenCode process.

The configuration directory also holds service.json, where the Manager writes the managed OpenCode server password for service mode. That password grants the full OpenCode API, including unsandboxed PTY terminals, so while sandboxing is enforced the agent's file tools are denied access to service.json, to grep/glob searches rooted at the configuration directory or an ancestor, and to external_directory grants targeting that directory. The denial is specific to service.json: a sibling configuration file such as opencode.json is not denied for read, and a relative grep/glob search path is not matched. Agents should use the ocm tool for configuration reads and changes.

Sandbox Settings

Settings → OpenCode Config → Server maintenance → Sandbox:

SettingEffect
SandboxTurns on sandbox support for the server. Restart-gated.
Git credentials in sandboxForwards git credentials into the microVM so sandboxed git and gh commands can authenticate. Off by default; see Git Credentials in the Sandbox.
Sandbox new sessions by defaultWhether new root sessions start sandboxed. Applies immediately.
Default CPUsDefault CPUs for a session's microVM. Blank uses the server default.
Default memory (GiB)Default memory for a session's microVM. Blank uses the server default.
Remove idle sandbox VMs after (minutes)How long a microVM may sit unused before it is removed. Default 30.
Max running sandbox VMsHow many session microVMs may run at once. Default 4.

Per-session CPU and memory overrides are set from the composer's Sandbox resources… dialog, which has a Use defaults action to clear the override.

Limits and Lifecycle

  • Resources. A session's override is used first, then the Settings default, then the server default (SANDBOX_CPUS 2 CPUs, SANDBOX_MEMORY 4G). CPUs may be 1–64 and memory 1024 MiB–1 TiB; a value above the host's CPU count or memory is rejected. A resource change applies on the session's next sandboxed command and recreates its microVM, keeping its Docker data volume.
  • Idle removal. A microVM and its Docker data volume are removed after the longer of the idle-stop setting (default 30 minutes) and the per-command timeout (SANDBOX_EXEC_TIMEOUT_MS, default 10 minutes) without a sandboxed command. The next sandboxed command creates a fresh microVM, so installed packages and Docker images are lost.
  • Running limit. At most the configured number of session microVMs run at once. Starting another stops the least recently used running microVM that has been idle for at least the per-command timeout; if none qualifies, the command is refused with a reason naming the limit.
  • Removal. Turning a session's sandbox off removes its microVM and Docker data volume in the background, and so does deleting a session. Turning server sandbox support off and Manager shutdown stop every managed microVM.
  • Warm-up. The Manager caches the guest image at startup and whenever support is switched on, but it does not boot a microVM until a session's first sandboxed command.

Host Requirements

Sandboxing requires KVM on a Linux host and access to Linux /proc for process identity attestation. The overlay exposes /dev/kvm, /dev/net/tun, and NET_ADMIN without enabling full container privilege. /dev/net/tun and NET_ADMIN provide guest networking for SANDBOX_NET=public; if msb reports a missing device or capability on a particular host, add that specific entry rather than enabling full privilege. Docker Desktop on macOS and Windows cannot provide /dev/kvm, so the sandbox switch stays unavailable there.

Worktree Placement

  • Scheduled runs use raw git worktrees under /workspace/schedule-worktrees.
  • OpenCode's own worktrees (/workspace/.opencode/state/opencode/worktree, created through its /api/worktree API) and opencode-forge loop worktrees (/workspace/.opencode/state/opencode/forge/worktrees) are project roots, so agent shell calls run inside them without further configuration.
  • A worktree created outside those roots is created normally; only a later agent shell call whose working directory is outside the session's mounts is refused.

Git Credentials in the Sandbox

By default the guest receives no credentials, so a sandboxed git push, git pull, or gh call fails to authenticate. The repo's git identity (GIT_AUTHOR_* / GIT_COMMITTER_*) is always forwarded, so git commit works either way.

Forwarding is opt-in, off by default:

ScopeWhereEffect
GlobalSettings → OpenCode Config → Server maintenance → Sandbox → Git credentials in sandbox (preferences.sandbox.gitCredentials)Default for every repo
Per reporepo_settings.sandboxGitCredentialsOverrides the global default in either direction. The planner honours it when resolving credentials, but nothing writes it yet — there is no UI or API for the per-repo override

The forwarding switch is read per command, so turning it on or off takes effect on the next sandboxed command without restarting the OpenCode server.

When enabled, credentials are resolved on the host and forwarded into the microVM:

  • One http.<host>.extraheader pair per configured host, so a command can authenticate against every host you have a credential for, not just the repo's own remote.
  • Where several credentials share a host, the repo-bound credential wins, then defaultGitCredentialId. Exactly one credential is ever sent per host — git treats http.<url>.extraheader as multi-valued and would otherwise send competing Authorization headers.
  • GH_TOKEN / GITHUB_TOKEN for gh.
  • At most 16 hosts. Beyond that the Manager logs a warning and forwards the first 16 rather than emitting a GIT_CONFIG_COUNT that git would reject.

Understand the trade-off before enabling it. The token is visible in the msb process arguments on the host and in the guest environment for that command's lifetime, and a prompt-injected agent inside the microVM can read and exfiltrate any credential you forward. The global switch is the only exposed control today, so enabling it applies to every repo; leave it off while any agent handles untrusted input.

Sandbox Guest Image

SANDBOX_IMAGE defaults to a digest-pinned reference of docker.io/cstechdev/ocm-sandbox. The Sandbox Image workflow (.github/workflows/sandbox-image.yml) builds Dockerfile.sandbox natively: linux/amd64 on ubuntu-latest and linux/arm64 on ubuntu-24.04-arm. Pull requests from this repository that touch the Dockerfile, the workflow, or scripts/sandbox-dockerd-start.sh run build-time verification without publishing or requiring registry credentials. A manual workflow_dispatch publishes both platforms by digest and merges them into one manifest list, tagged with the commit SHA, package version, and optional tag input (default latest). Publishing requires DOCKERHUB_USERNAME and DOCKERHUB_TOKEN repository secrets. The job summary prints the index digest to pin.

Native runners avoid the x86_64 rustc segmentation fault observed under qemu-user on the arm64 build host. Later uv releases also failed in that environment. Neither platform skips toolchain execution to work around emulation failures. A single-platform local build on an arm64 host is:

docker buildx build --platform linux/arm64 -t ocm-sandbox:local -f Dockerfile.sandbox --load .

After a publish, update the pin in shared/src/config/defaults.ts (SANDBOX.IMAGE) and in the docker-compose.sandbox.yml default to the new @sha256: digest. That bump is what makes deployments adopt a rebuilt guest image, and it is deliberate rather than convenient:

  • msb caches images by reference. msb pull docker.io/cstechdev/ocm-sandbox:latest reports "already cached" without contacting the registry, and pull_policy: IfMissing never re-pulls, so a host that pulled a mutable tag once keeps that content forever.
  • Sandbox attestation compares the image reference string. A floating tag therefore keeps passing attestation while its content drifts, so the running microVM is never recreated either.

A digest reference sidesteps both: it is a cache key no host has seen before, so IfMissing pulls it, and it fails the reference comparison against a microVM created from the old reference, so the Manager removes and recreates that microVM on its own. No manual cleanup is required on deploy; to reclaim the superseded image afterwards, run msb image prune or msb image rm <old reference>.

It is built from the same node:24.21.0-trixie tag as the Manager image (Debian 13, buildpack-deps based), so both track one Node and one Debian release and the compile toolchain is already present. pnpm, Bun, uv, fallow, Rust, Go, and Playwright have build-argument version pins; base-image and apt tools follow their package sources:

ToolSourceNotes
gcc / g++ / make / ld / pkg-configbase imageGCC 14, GNU Make 4.4
glib-2.0base imageWith pkg-config metadata
git, ssh, python3, curl, wget, unzipbase image
pythonapt (python-is-python3)The base image ships only python3; a skill or script invoking python would otherwise fail
ping, ip, ss, netstat, dig, host, nslookup, nc, traceroute, lsof, rsyncaptThe base image ships no network diagnostics at all. The image build fails if any of these is missing
pnpmnpm install -g (PNPM_VERSION)Installed into /usr/local as root. A project packageManager pin of a different version is honoured by pnpm itself, which downloads it into the pnpm store on first use; the build verifies that as an unknown uid
bun, bunxofficial installer (BUN_VERSION)Installed to /opt/bun, world-readable, both symlinked onto PATH
uv, uvxAstral installer (UV_VERSION)Standalone binaries on PATH; uv tool shims land in /opt/agent-tools/bin, which is on PATH. Pinned at 0.12.7
fallownpm install -g (FALLOW_VERSION)Dead-code and unused-export analysis CLI
rustc, cargo, rustuprustup (RUST_VERSION, minimal profile)RUSTUP_HOME=/usr/local/rustup and CARGO_HOME=/usr/local/cargo follow the official rust image layout and are opened to every uid afterwards, so the exec user can cargo install and add toolchains; /usr/local/cargo/bin is on PATH
goofficial tarball (GO_VERSION)Unpacked to /usr/local/go, on PATH. GOBIN=/opt/agent-tools/bin puts go install binaries next to the other agent tools; GOPATH and the module cache default under the writable HOME
npm -g, pnpm -gnpm / pnpmGlobal installs redirect to /opt/agent-tools (npm_config_prefix, PNPM_HOME), so they are writable for the exec user and their binaries are on PATH
sudoaptPasswordless for every guest user via /etc/sudoers.d/ocm-guest; system-wide apt-get install works from the exec user
pip, venvaptpython3-pip and python3-venv on top of the base python3. Debian's externally-managed marker is removed, so pip and uv pip --system are not refused; system-wide writes still need sudo, so use --user or a venv
jq, ripgrep, less, tree, file, procpsaptCommon CLI tools agent workflows expect; Debian 13 carries jq 1.7 and ripgrep 14
ghofficial cli.github.com apt repoCurrent release. Debian's own package is several years stale
Docker Engine, CLI, Buildx, Composeofficial Docker Debian apt repoocm-dockerd-start starts the guest daemon on demand and waits for readiness. The Manager adds the provisioned exec user to the guest's Docker group. No host Docker socket is mounted
ChromiumPlaywright (PLAYWRIGHT_VERSION, default 1.63.0)Installed to PLAYWRIGHT_BROWSERS_PATH=/ms-playwright, world-readable so SANDBOX_EXEC_USER can launch it

NODE_PATH=/usr/local/lib/node_modules is set so agent code can require("playwright") from any working directory. It is only a resolution fallback; a project-local node_modules still wins.

Before using Docker inside the guest, run ocm-dockerd-start. The helper is safe to call repeatedly, serializes concurrent starts, and probes only the guest's Unix socket regardless of DOCKER_HOST or DOCKER_CONTEXT. It supervises dockerd for up to 180 seconds, relaunching it if it exits before docker info succeeds, because a fresh microVM's dockerd can exit with "timeout waiting for containerd to start". Daemon startup logs are in /var/log/dockerd.log. Docker data lives on a per-session 20 GiB disk volume mounted at /var/lib/docker; Docker's overlay storage cannot use the sandbox's overlay root filesystem. The volume is private to the session, survives that microVM's restarts and recreation, and is not shared with the host Docker daemon. Removing the microVM also removes its Docker data volume, so its images, containers, and volumes are lost. Sandbox attestation requires exactly this named mount in addition to the session's project mounts.

The guest runs every command as a numeric host uid that has no /etc/passwd entry in the image, so the uncorrected default HOME is / and anything that writes per-user state — the pnpm store, uv and pip caches, git config, gh config, the cargo registry, the Go module cache — dies with EACCES on the first run. The image therefore sets HOME=/home/ocm-agent (mode 1777), opens the rust homes to every uid, and puts a world-writable /opt/agent-tools/bin on PATH for uv tool, go install and global package-manager installs. Image ENV reaches msb exec commands verbatim, including for unknown uids. The image build verifies the whole toolchain as an unprivileged uid — including a cargo build and a go run — so a root-only regression fails the build instead of the agent.

The pnpm store itself is pinned to a container-internal path with PNPM_CONFIG_STORE_DIR=/home/ocm-agent/.local/share/pnpm/store. The pin goes through pnpm's own config env var because pnpm 11 no longer reads npm_config_* variables; with the store unpinned, pnpm places it on the mounted project filesystem, which pollutes the repository, slows installs over the host bind mount, and can end up committed.

sudo also needs the exec user to exist in the guest, which the image cannot know at build time. The Manager provisions the /etc/passwd, /etc/group, and /etc/shadow entries for the exec uid through an idempotent root exec (verified by getent, so repeats are no-ops) when a microVM is created and when a stopped microVM is started. A freshly created microVM does not accept msb exec until its guest agent is up, so provisioning first waits on msb ping (bounded by SANDBOX_START_TIMEOUT_MS). Without the entries, sudo refuses with "you do not exist in the passwd database" or a PAM "account validation failure". Provisioning is deliberately non-fatal: if it fails, the Manager logs a warning and the sandbox still runs commands — only sudo is unavailable. A microVM created from an older image reference is replaced automatically when the digest pin changes, so it picks up both sudo and the fixed toolchain without manual cleanup.

Chromium launches headless as the non-root exec user without extra flags. If your host kernel restricts user namespaces so Chromium's own sandbox fails, pass --no-sandbox — the microVM is already the isolation boundary.

The image is around 5 GB unpacked against a 1.6 GB base; Chromium with its dependencies (about 1.1 GB) and the Rust and Go toolchains (about 0.8 GB) account for most of the rest. When sandboxing is enabled, the Manager caches the image at startup, and whenever support is switched on, in the background (msb pull, bounded by SANDBOX_START_TIMEOUT_MS; raise it on slow links). It does not boot a microVM until a session's first sandboxed command. The pull is a no-op once cached, docker-compose.sandbox.yml persists the microsandbox store in the microsandbox-data volume so the download survives container replacement, and the shutdown handler stops any running microVM.

Using your own image

Point SANDBOX_IMAGE at any OCI reference the host can pull. It must contain every tool the agent expects to run, and a shell at /bin/sh. Changing the value is safe at runtime: the running microVM fails image attestation and is recreated automatically.

To build it on the server instead of pulling:

docker build -f Dockerfile.sandbox -t my-sandbox:local .
# then set SANDBOX_IMAGE=my-sandbox:local

Pin a concrete tag or digest rather than a floating one. Attestation compares the image reference string, so a mutable tag keeps passing attestation while the underlying image drifts.

Override any tool pin at build time with its ARG, for example --build-arg PLAYWRIGHT_VERSION=1.62.0 or --build-arg RUST_VERSION=1.97.0; the build asserts the installed version, so a typo fails early instead of shipping a stale tool. If your project drives Playwright itself, match this version to the one in your package.json; a mismatched browser revision makes Playwright refuse to launch. Rebuild and republish the guest image, then update the SANDBOX.IMAGE digest, whenever you change a pin.

The Manager image itself carries the same Chromium browser and playwright package, installed by playwright install --with-deps chromium for the same PLAYWRIGHT_VERSION at build time and made world-readable. That is what makes browser automation run in a container with sandboxing off, where the agent has no root or sudo to install them at runtime; NODE_PATH=/usr/local/lib/node_modules lets agent code resolve playwright from any working directory. Both images track one pin, so bumping PLAYWRIGHT_VERSION refreshes the sandbox browser and the Manager's browser together.

Troubleshooting

  • The sandbox switch is disabled and the section shows a reason. The host cannot sandbox: /dev/kvm is missing or not writable, the msb CLI is not available, the configured SANDBOX_EXEC_USER cannot write the workspace, or process identity attestation failed. Start the Manager with the sandbox overlay on a KVM-capable Linux host, and check SANDBOX_EXEC_USER.
  • A command fails with a message naming the session's sandbox. The working directory is outside the session's mounts. Only the session's repository or worktree is a valid working directory.
  • A command fails with a reason naming the running-VM limit. Too many session microVMs are running; wait for one to finish or go idle, or raise Max running sandbox VMs.
  • Packages or Docker images you installed are gone. The microVM was removed after going idle, or the session's sandbox was turned off. The next sandboxed command creates a fresh microVM.
  • sudo fails inside the sandbox. The Manager could not provision the exec user's guest account; the sandbox still runs commands, but sudo is unavailable.
  • dockerd did not become ready. Run ocm-dockerd-start again — it supervises dockerd for up to 180 seconds — and check /var/log/dockerd.log.

Caveats

  • With sandboxing enabled, the guest image is cached at Manager startup, so commands normally do not wait for the pull. A command that runs before the cache completes waits on it, bounded by SANDBOX_START_TIMEOUT_MS.
  • SANDBOX_IMAGE must contain every tool the agent expects to run.
  • SANDBOX_EXEC_USER must match the workspace owner so commands can write mounted files.
  • A shell the user configured does not apply to the agent shell tool in a sandboxed session; PTY terminals and slash-command shell templates still use it.
  • Credentials injected into OpenCode's host shell environment are not forwarded into the microVM unless git credential forwarding is enabled; see Git Credentials in the Sandbox.
  • Message parts recorded by older releases still hold the old msb exec wrapper; the WebUI unwraps them for display and still badges them.
  • Plugins and other configured host-process extensions are trusted and are not isolated by agent shell sandboxing.