feat(sandbox): add KVM-backed agent sandboxing via microsandbox

This commit is contained in:
Chris Scott committed 2026-08-13 16:14:16 -04:00
1 parent 1d477bdee4
commit aa3fb48a62
80 files changed
+17304 -204

No files matched your search

+42 -1
View File
@@ -295,6 +295,44 @@ Why the repo mount uses the host path as the container path:
With a fresh Docker volume, first startup imports the host OpenCode config and state, and after you add `${OCM_REPOS_HOST_PATH}` in the Manager UI, previously existing chats appear under the discovered repositories.
## Agent Sandboxing Overlay
Optional KVM-backed agent sandboxing (see [Agent Sandboxing](../features/sandboxing.md)). The sandbox overlay (`docker-compose.sandbox.yml`) grants the container KVM access, passes sandbox tuning through from `.env`, and persists microsandbox state:
```yaml
services:
app:
privileged: true
devices:
- "/dev/kvm:/dev/kvm"
environment:
- SANDBOX_IMAGE=${SANDBOX_IMAGE:-node:24}
- SANDBOX_MEMORY=${SANDBOX_MEMORY:-4G}
- SANDBOX_CPUS=${SANDBOX_CPUS:-2}
- SANDBOX_EXEC_USER=${SANDBOX_EXEC_USER:-${PUID:-1000}}
- SANDBOX_NET=${SANDBOX_NET:-public}
- SANDBOX_START_TIMEOUT_MS=${SANDBOX_START_TIMEOUT_MS:-300000}
- SANDBOX_EXEC_TIMEOUT_MS=${SANDBOX_EXEC_TIMEOUT_MS:-600000}
volumes:
- microsandbox-data:/home/node/.microsandbox
volumes:
microsandbox-data:
driver: local
```
Start the Manager with the overlay:
```bash
docker compose -f docker-compose.yml -f docker-compose.sandbox.yml up -d
```
The overlay requires a Linux host with `/dev/kvm`. Docker Desktop on macOS and Windows cannot provide `/dev/kvm`, so the sandbox toggle in Settings stays disabled there.
`SANDBOX_EXEC_USER` defaults to the numeric `PUID` (falling back to `1000`), and the Manager runs every sandboxed command as that numeric uid (with the Manager's gid). Because the entrypoint realigns the container's `node` account to `PUID`/`PGID` and re-owns `/workspace`, a non-1000 `PUID` (for example `PUID=1001`) writes to the mounted repositories with the same identity as the workspace owner. If a configured `SANDBOX_EXEC_USER` cannot match the workspace owner, the toggle reports enforcement as unavailable instead of running broken commands.
The `microsandbox-data` volume persists microsandbox's own state (downloaded images, firmware cache) across container recreations, alongside the workspace and data volumes.
## Health Checks
The container includes health checks:
@@ -444,6 +482,9 @@ By default, the OpenCode server binds to `127.0.0.1` inside the container and is
You only need to expose the OpenCode server on an external interface if you have a specific use case that requires other services or machines to connect directly to it.
!!! warning "Sandbox enforcement is proxy-scoped"
Part of agent-sandboxing enforcement — the blocked session-shell/PTY/slash-command endpoints and config-mutation sanitization — is applied by the Manager's OpenCode proxy on port 5003, not by the OpenCode server itself. The `bash` tool rewrite, by contrast, runs as a plugin hook inside the OpenCode process, so it still guards direct connections to the OpenCode server. While sandboxing is enforced the Manager forces the OpenCode server to bind loopback, so external clients cannot reach the OpenCode port directly and bypass the proxy-applied endpoint blocking and config sanitization; exposing port `5551:5551` is only effective with sandboxing disabled (see [Agent Sandboxing](../features/sandboxing.md)).
### How to Expose Safely
To expose the OpenCode server on the host network:
@@ -475,4 +516,4 @@ The password can be configured in two ways:
### Startup Guard
If you set `OPENCODE_HOST=0.0.0.0` (or any non-localhost host) without configuring a password (either via env var or UI), the managed OpenCode server will refuse to start with an error message explaining how to fix it. The OpenCode Manager UI/API may remain available so you can configure a password and restart the managed server.
If you set `OPENCODE_HOST=0.0.0.0` (or any non-localhost host) without configuring a password (either via env var or UI), the managed OpenCode server will refuse to start with an error message explaining how to fix it. The OpenCode Manager UI/API may remain available so you can configure a password and restart the managed server. (While agent sandboxing is enforced the server is forced onto a loopback bind regardless of `OPENCODE_HOST`, so this password guard is skipped — the server is not actually reachable externally.)
+16
View File
@@ -108,6 +108,22 @@ When configured, users can enable push notifications in Settings → Notificatio
| `OPENCODE_IMPORT_CONFIG_PATH` | Existing standalone OpenCode `opencode.json` to import on first startup | - |
| `OPENCODE_IMPORT_STATE_PATH` | Existing standalone OpenCode state directory to import on first startup | - |
## Agent Sandboxing
Sandboxed agent commands run inside a microVM managed by `msb` (see [Agent Sandboxing](../features/sandboxing.md)). Requires a Linux host with `/dev/kvm` and the sandbox compose overlay.
| Variable | Description | Default |
|----------|-------------|---------|
| `MSB_PATH` | Path to the `msb` executable | `msb` |
| `MSB_LIBKRUNFW_PATH` | Path to the `libkrunfw` firmware library used by `msb` (set in the container image) | `/opt/microsandbox/lib/libkrunfw.so` |
| `SANDBOX_IMAGE` | OCI image the microVM boots from | `node:24` |
| `SANDBOX_MEMORY` | MicroVM memory (e.g. `4G`) | `4G` |
| `SANDBOX_CPUS` | MicroVM CPU count | `2` |
| `SANDBOX_EXEC_USER` | Guest identity sandboxed commands run as: a numeric `uid`, a numeric `uid:gid`, or a guest username. A numeric uid must match the Manager's effective uid (`PUID`); the compose overlay defaults it to `${PUID:-1000}`. A guest username is resolved to the Manager's effective `uid:gid` so writes to the mounted project roots always succeed. When a configured numeric identity cannot write the workspace, enforcement is reported unavailable | `${PUID:-1000}` via the overlay, otherwise `node` |
| `SANDBOX_NET` | Network mode for the microVM: `public`, `private`, or `host`, or a comma-separated composition (for example `public,host`). Passed to `msb run --net` and attested against the profile's canonical network policy | `public` |
| `SANDBOX_START_TIMEOUT_MS` | Timeout for microVM startup, in milliseconds | `300000` |
| `SANDBOX_EXEC_TIMEOUT_MS` | Timeout for a single sandboxed command, in milliseconds | `600000` |
## Timeouts
| Variable | Description | Default |
+140
View File
@@ -0,0 +1,140 @@
# Agent Sandboxing
Run agent shell commands inside an isolated microVM instead of directly in the Manager container. Sandboxing is a hardening option for untrusted agent code, not a per-project permission boundary.
## Overview
When sandboxing is enabled, every shell command an OpenCode **agent** runs through the `bash` tool is executed inside a microVM managed by [`msb`](https://github.com/superradcompany/microsandbox) instead of in the container that hosts the Manager and the OpenCode server. The agent still works with the same files in the same layout — the microVM sees the repositories through bind mounts — but the process runs under a different kernel and cannot read Manager or provider secrets from the host filesystem. OpenCode also exposes shell surfaces that bypass the `bash` tool hook; those are **blocked** while enforcement is active (see [Host-Shell Surfaces Under Enforcement](#host-shell-surfaces-under-enforcement)).
## What Gets Sandboxed
Sandboxing hooks into the OpenCode `bash` tool, which is how agents execute shell commands. As a result:
| Execution path | Sandboxed |
|----------------|-----------|
| Chat session `bash` tool calls | Yes |
| Scheduled run commands | Yes |
| Subagent `bash` tool calls | Yes |
| WebUI `!command` shell mode (`POST /session/:id/shell`) | Blocked while enforced |
| PTY terminals (`POST /pty`, `/pty/:id/connect`) | Blocked while enforced |
| Custom slash commands (`POST /session/:id/command`) | Blocked while enforced |
| Local MCP server processes (`mcp` config with `type: "local"` / `command`) | Disabled while enforced |
| Dynamically added local MCP servers (`POST /mcp`) | Blocked while enforced |
| Formatter commands (`formatter` config) | Disabled while enforced |
| LSP server processes (`lsp` config, any enabling form) | Disabled while enforced |
| Experimental hook commands (`experimental.hook` config) | Disabled while enforced |
| Global custom tools (`<config>/opencode/tool(s)/`, `$HOME/.opencode/tool(s)/`) | Quarantined while enforced |
| Manager-side git operations (`backend/src/services/repo.ts`) | No |
| OpenCode `read` / `write` / `edit` file tools | No |
Manager-side git operations (clone, fetch, worktree creation, credential setup) run directly in the container so the Manager can manage repositories regardless of the sandbox setting. OpenCode's file tools keep operating on the host filesystem — the same files the microVM sees through its bind mounts — so editing a file and running a command against it behave exactly as they do without sandboxing.
## Host-Shell Surfaces Under Enforcement
The `bash` tool hook is not the only way OpenCode's host process can spawn a shell: the session-shell endpoint that powers the WebUI `!command` mode, PTY creation and connection, and custom slash-command execution all run in the host process without passing through `tool.execute.before`. While enforcement is active the Manager's OpenCode proxy — both the authenticated `/api/opencode/*` surface and the internal-token `/api/opencode-proxy` surface — rejects these endpoints with `403` and an actionable reason, so neither an authenticated user nor an internal-token caller can make the OpenCode host process execute a command outside the microVM. The shared policy strictly canonicalizes request paths before matching: percent-encoded spellings of a blocked route (for example `/session/s1/%73hell`) are blocked, and any path containing malformed, double-encoded, control-character, or encoded-separator sequences is refused as unsafe rather than forwarded. The WebUI disables `!command` shell mode with the same explanation. Custom slash commands (including commands whose templates only prompt the model) are unavailable while enforcement is on because the proxy cannot distinguish a prompt template from a shell template without trusting user configuration; disable sandboxing and restart to use them. The same proxy surfaces refuse to dynamically add a local MCP server to the running process: `POST /mcp` is only forwarded while enforcement is on when the body is a provably remote server (`type: "remote"` with a URL) — a local (`type: "local"`) or otherwise command-bearing config is rejected with `403`, so neither surface can start an MCP process in the OpenCode host process. This boundary is enforced by the shared proxy policy in `backend/src/services/opencode/proxy-policy.ts`, which is covered by route tests that pin the blocked surface list.
!!! warning "Direct OpenCode port exposure bypasses the proxy boundary"
Enforcement is applied in two different places. The `bash` tool rewrite runs as a plugin hook (`ocm-sandbox.js`) inside the OpenCode process itself, so it still guards every `bash` tool call even when clients connect directly to the OpenCode server's own port. The blocked host-shell surfaces and the config-mutation sanitization, by contrast, are applied by the Manager's OpenCode proxy. To keep the proxy authoritative, an enforced OpenCode server is always spawned with a loopback bind: when `OPENCODE_HOST` is not a loopback address, the Manager overrides it with `127.0.0.1` for the child (and logs the override), so callers cannot reach the session-shell, PTY, slash-command, or unsanitized configuration endpoints on the OpenCode port directly — the only external path is the Manager proxy, which applies the enforcement policy. The Manager's own OpenCode client follows the same effective host (loopback while enforced, `OPENCODE_HOST` otherwise), so health checks and every proxied request keep targeting the address the child actually binds, including IPv6 loopback hosts. The override is active only while enforcement is on; with the toggle off, `OPENCODE_HOST` is honored as configured.
## Host Requirements
Sandboxing requires KVM, which means a Linux host:
- The host must expose `/dev/kvm` to the container. Start the Manager with the sandbox overlay:
```bash
docker compose -f docker-compose.yml -f docker-compose.sandbox.yml up -d
```
- Docker Desktop on macOS and Windows cannot provide `/dev/kvm`. On those platforms the sandbox toggle stays disabled and the Settings UI shows the reason.
Because enforcement requires KVM, it is inherently limited to Linux. On non-Linux hosts the enforced code path fails closed, and unenforced production operation tracks the OpenCode server as a direct child instead of relying on `/proc` process identity attestation, so starting the Manager in production mode on macOS keeps working with the sandbox toggle off.
If the host meets the requirements, the Settings UI displays the detected `msb` version; otherwise it shows why sandboxing is unavailable.
## Scope and Lifecycle
All projects share **one** microVM:
- The microVM is named `ocm-workspace` and is created detached (`msb run -d`), booted on the first sandboxed command, and reused for every subsequent command.
- It mounts `/workspace/repos` and `/workspace/schedule-worktrees` at identical guest paths. This covers every repository, every repository worktree, the assistant-mode project (`repos/assistant`), and every schedule worktree.
- The assistant-mode `.opencode` directory (`repos/assistant/.opencode`, which holds the internal API token plus the managed assistant skills and agents) is masked inside the microVM with a guest-memory `tmpfs` overlay. Guest shell processes see an empty directory there and cannot read the token, while OpenCode's host-side config and skill loading keeps operating on the real directory.
- Because the mount roots are the two parent directories, repositories cloned and schedule worktrees created after the microVM booted are visible inside it immediately — there is nothing to remount.
- Each command supplies its own working directory via `msb exec -w`, so `cd`-ing between projects behaves exactly as it does without sandboxing.
- To tear the microVM down, remove it by label:
```bash
msb rm --label ocm.managed=true
```
The next sandboxed command recreates it.
- A graceful Manager shutdown always attempts to stop any `ocm.managed=true` microVM (`msb stop --label ocm.managed=true`, with `ignoreExitCode` and a finite timeout), independent of the current toggle state, so a VM is never left detached after a restart, a toggle change with a pending restart, or an earlier shutdown step failing.
- Disabling sandboxing does not stop the microVM at toggle time: the stop runs when the OpenCode server restarts into the disabled state, so a background guest process cannot outlive an enforced-to-disabled restart. That stop is confirmed — it only completes once the managed microVM is listed as stopped or absent, and the restart fails closed if the VM cannot be confirmed stopped — and it is reversible: re-enabling sandboxing and restarting boots the microVM again.
- Before reusing an existing `ocm-workspace` microVM, the Manager verifies it was created by the Manager: it must carry the `ocm.managed=true` label, boot from the configured `SANDBOX_IMAGE`, run with the configured CPUs/memory/workdir, keep networking enabled, mount exactly `/workspace/repos` and `/workspace/schedule-worktrees` as writable identical-path bind mounts, and carry exactly one tmpfs: the assistant `.opencode` mask. The effective network policy is also attested against the resolved policy of the configured `SANDBOX_NET` profile (`public`, `private`, `host`, or a comma-separated composition): the inspected `default_egress`/`default_ingress` and every rule must match the profile's canonical policy exactly, so a sandbox labelled with the configured profile that actually carries an allow-all rule, a rule broadened to specific protocols or ports, stale rules from another profile, or altered defaults is recreated rather than reused. Any named volume, disk image, extra tmpfs (including one masking a project root), extra bind mount (for example one exposing `/workspace/config`), or missing mask fails the check. An instance that fails any of these checks is force-removed and recreated from the centralized create arguments, so an unmanaged or stale instance is never started or used. The attestation parses the real `msb inspect --format json` contract of the pinned `msb` CLI (`MICROSANDBOX_VERSION`), which is tested against fixtures copied from that contract.
A session rooted outside the two mounted roots (for example `/workspace` itself) is refused with a clear error rather than silently escaping the sandbox.
## What Is Not Mounted
These host paths stay outside the microVM:
| Host path | Contents |
|-----------|----------|
| `/workspace/config` | SSH `known_hosts`, `ssh_config` |
| `/workspace/.ssh-keys` | SSH private keys for repository access |
| `/workspace/.config` | OpenCode configuration and generated plugins |
| `/workspace/.opencode/state` | Provider credentials (`auth.json`) |
| `repos/assistant/.opencode` (masked) | Assistant internal API token — hidden inside the microVM behind a `tmpfs` overlay |
The consequence: sandboxed commands cannot read Manager or provider secrets, and they cannot modify the OpenCode configuration or the installed plugins. The assistant-mode `.opencode` directory is bind-visible on the host for OpenCode's own config and skill loading, but inside the microVM it is replaced by an empty in-memory filesystem, so the internal API bearer token it contains is unreadable by guest shell code.
## Blast Radius
The microVM shares one kernel and one filesystem namespace across all projects. This boundary protects the Manager container and its secrets from agent code; it does **not** isolate one repository from another. Repositories remain mutually accessible inside the sandbox, exactly as they are on the host.
## Enabling and Enforcement Model
Enforcement follows this chain:
1. **Toggle** — Enable **Sandbox** in Settings. If `/dev/kvm` is unavailable the toggle cannot be turned on and the capability reason is shown; if the runtime later becomes unavailable while the preference stays enabled, the toggle remains turned on and every sandboxed command fails closed with the reason instead of running on the host.
2. **Restart** — Changing the preference marks the OpenCode server restart as pending. The new enforcement value is only applied to newly spawned OpenCode processes, so a restart is required. When an enforced server starts, the Manager terminates the previous server's process group — the detached OpenCode child plus every host-process descendant it spawned, including a shell command or MCP process started while enforcement was off — waits for all members to exit, escalates to `SIGKILL` on the group if needed, and refuses to start the enforced server if any member survives, so no unenforced host-executed process can outlive the transition. Non-detached development children are terminated by PID only, preserving the existing hot-reload behavior.
3. **Stamp** — On startup the Manager resolves the preference (not the runtime probe) and stamps every spawned OpenCode child environment with `OCM_SANDBOX_ENFORCED=true` whenever the preference is enabled. A missing or broken sandbox runtime therefore keeps enforcement active and blocks commands with the capability reason rather than silently running them on the host. If the preference itself cannot be read, the Manager fails closed the same way: it treats enforcement as active, terminates any attested predecessor and port-owning server so no unenforced child stays reachable, and aborts startup as non-recoverable with the settings error. User-defined environment variables cannot override this value.
4. **OpenCode build** — Sandbox enforcement rewrites `bash` tool arguments through the plugin `tool.execute.before` hook, a behavior that depends on the OpenCode build. The container image ships a pinned OpenCode build (`1.18.16`), and the Manager refuses to start an enforced server unless the installed build is one of the versions verified by the black-box hook contract test (currently `1.18.16`), failing closed with a clear error instead of trusting an unverified build to run agent commands on the host. While enforcement is active (the persisted preference or a running enforced child), the Settings UI disables the Update action and the unverified rows in the Versions dialog, and the Manager rejects `POST /opencode-upgrade` and any unverified `POST /opencode-install-version` request, so the installed build can never be replaced with an unverified release; installing a verified version remains allowed. The container entrypoint also repairs a missing or below-minimum `opencode` by reinstalling the bundled build rather than the latest release.
5. **Fail closed** — The installed OpenCode plugin rewrites every `bash` tool command through the internal sandbox planning endpoint. If the sandbox cannot be prepared, the command is replaced with an error and exits non-zero instead of running on the host. A session outside the project roots fails with:
```
Sandbox enforcement is on but the sandbox is unavailable: working directory is outside the sandboxed project roots (/workspace/repos, /workspace/schedule-worktrees)
```
Every other fail-closed reason uses the same `Sandbox enforcement is on but the sandbox is unavailable:` prefix followed by its reason — for example, a sandbox that fails to boot reports the underlying `msb` error after the prefix.
The enforcement value is stamped into the OpenCode child process at startup and is authoritative for its lifetime. The plugin reports that stamp to the planning endpoint, so an enforced child can never fall back to host execution — even if the toggle is turned off before the required restart, the running OpenCode server keeps executing sandboxed until it is restarted.
## Plugin Policy Under Enforcement
Plugins run as ordinary JavaScript inside the OpenCode process and can touch the host filesystem and process APIs without going through the `bash` tool, so sandbox enforcement must make sure that **only Manager-owned plugin code** is evaluated in the host process:
- The Manager installs exactly two plugins into the auto-discovery directory (`<workspace>/.config/opencode/plugin`): `ocm-sandbox.js` (the enforcement hook) and `ocm-gh-env.js` (host credential injection for the `shell.env` hook). Both are generated by the Manager and are the only trusted plugin files.
- **Repository plugins are never evaluated.** Enforced OpenCode children are started with `OPENCODE_DISABLE_PROJECT_CONFIG=1`, so OpenCode does not read project `opencode.json` files or scan `.opencode/plugin` / `.opencode/plugins` directories — including plugins planted in a repository by an agent using the host-side `write` tool or by a cloned repository itself.
- **Configured package plugins are disabled.** On an enforced start the Manager removes the `plugin` array from the global OpenCode config file (`<workspace>/.config/opencode/opencode.json`) and writes a backup of the removed sections next to it; the backup is refreshed with the latest configured array whenever the file sanitizer sees new plugins during enforcement, and the entries are merged back when enforcement is turned off and the server restarts. `installConfiguredPlugins` is skipped while enforcement is on. The running process is additionally guarded by stateless enforcement sanitization: config reloads, settings-driven config saves, and mutating `PATCH /config` requests proxied through either Manager OpenCode proxy surface (`/api/opencode/*` or `/api/opencode-proxy/*`) have the `plugin` array stripped from the patch before it reaches the OpenCode server — a body that is not valid JSON or not a JSON object is refused with `403` rather than forwarded — so a persisted config that still contains a plugin array can never re-activate plugins in the running process. Proxied patches are rewritten for that request only: their removed values are discarded rather than backed up, and the proxy never writes to the config file.
- **Config-source environment variables are blocked.** OpenCode reads additional config and plugin sources from `OPENCODE_CONFIG`, `OPENCODE_CONFIG_CONTENT`, `OPENCODE_CONFIG_DIR`, `OPENCODE_AUTH_CONTENT`, `OPENCODE_TEST_HOME`, and `OPENCODE_TEST_MANAGED_CONFIG_DIR`. `OPENCODE_AUTH_CONTENT` replaces the whole auth file and can inject a well-known auth entry that triggers the `.well-known/opencode` remote-config fetch; `OPENCODE_TEST_HOME` redirects the home-based `.opencode` plugin and agent discovery directories; `OPENCODE_TEST_MANAGED_CONFIG_DIR` redirects the system managed-config directory. The Manager blocks all six in user-defined `serverEnvVars`, removes the five overridable ones from the child environment entirely, and stamps `OPENCODE_CONFIG` to the Manager's own global config path, so neither a configured environment variable nor a leaked Manager process environment can introduce a third-party config, plugin, or auth source into a child process. OpenCode also skips external plugin discovery and installation when `OPENCODE_PURE` is truthy, which would silently disable the Manager-owned `ocm-sandbox.js` and `ocm-gh-env.js` hooks; the Manager blocks `OPENCODE_PURE` in user-defined `serverEnvVars`, removes any inherited value from the child environment, and stamps `OPENCODE_PURE=false` after the environment spreads in both modes, so neither a configured entry nor an inherited value can switch pure mode on. Executable-resolution, runtime-loader, and shell-selection variables (`PATH`, `BUN_OPTIONS`, `NODE_OPTIONS`, `LD_PRELOAD`, `LD_LIBRARY_PATH`, `SHELL`, `BASH_ENV`, `ENV`) are reserved in the same contract: the Manager spawns the verified `opencode` executable by its absolute path, removes any inherited `SHELL`, `BASH_ENV`, or `ENV` from the child environment in both modes, and stamps `SHELL` to the Manager-selected absolute `/bin/bash` when enforcement is on — so user environment settings cannot select a repository-controlled shell binary or source repository-controlled startup files (`.bashrc`/`$ENV`/`$BASH_ENV`) before the rewritten `msb exec` command runs.
- **User-dropped global plugins are quarantined.** Any file other than the two Manager-owned plugins found in the global plugin directories (`<workspace>/.config/opencode/plugin`, `<workspace>/.config/opencode/plugins`, `$HOME/.opencode/plugin`, `$HOME/.opencode/plugins`) is moved to a sibling `.ocm-quarantine` directory at an enforced start and restored when enforcement is turned off.
- **Fail closed.** If the plugin directory cannot be quarantined or the config cannot be sanitized, the Manager refuses to start an enforced server.
- **Defense in depth.** In addition, the sandbox plugin locks the rewritten `bash` command argument after planning and verifies the replacement by reading it back; if neither the planned command nor a blocking guard can be installed — for example another plugin froze the argument object — the hook aborts the tool call instead of letting the original command run on the host, and any detected bypass blocks every subsequent sandboxed command.
- **Host-execution config sections are disabled.** OpenCode can spawn host processes outside the `bash` hook from configuration sources, and enforcement disables all of them: local MCP servers (a `mcp` entry with `type: "local"` or a `command`), the whole `formatter` configuration, the `shell` configuration, LSP servers (every enabling `lsp` form, whether a non-empty section or `lsp: true`; only an explicit `lsp: false` survives, since it disables built-in LSP processes), experimental hook commands (`experimental.hook`), and custom provider modules (any `provider` entry carrying an `npm` selector, including a `file://` module, which OpenCode would dynamically import in its host process); remote MCP servers and provider entries without an `npm` selector survive. On an enforced start the Manager removes these sections from the global config file and from every native global config file OpenCode loads (`opencode.json`, `opencode.jsonc`, `config.json` under `<workspace>/.config/opencode`, plus `opencode.json` and `opencode.jsonc` under `$HOME/.opencode`), backs up the removed sections next to each file, and merges them back when enforcement is turned off. The same sections are stripped, without any backup, from every live config reload, every settings-driven config save, and every mutating `/config` request proxied through either Manager OpenCode proxy surface. A proxied `POST /mcp` that would add a local or command-bearing MCP server to the running process is refused with `403`, so only provably remote servers can be added while enforcement is active. Global custom tools — TypeScript/JavaScript modules under `<config>/opencode/tool(s)/` and `$HOME/.opencode/tool(s)/` that run in the OpenCode host process — are quarantined to a sibling `.ocm-quarantine` directory at an enforced start and restored when enforcement is off. Project-level `.opencode/tool(s)/` custom tools are covered by `OPENCODE_DISABLE_PROJECT_CONFIG=1`. The consequence: a configured local MCP server, formatter command, shell, LSP server, hook command, or custom provider module cannot read Manager or provider credentials from the host process during enforcement.
- **System managed configuration is sanitized.** OpenCode reads the platform managed-config directory — `/etc/opencode` on Linux, `/Library/Application Support/opencode` on macOS, `%ProgramData%\opencode` on Windows — with the highest file-based priority. On an enforced start the Manager sanitizes `opencode.json` and `opencode.jsonc` from that directory with the same backup-and-restore contract as the native global files, so an org-managed config cannot supply a plugin, local MCP server, formatter, shell, LSP server, or hook to the host process. A managed config that contains a host-execution section and cannot be rewritten (for example a read-only bind mount) aborts the enforced start instead of running with unsanitized managed configuration.
- **Well-known remote configuration fails closed.** OpenCode fetches organizational default configuration from `${provider}/.well-known/opencode` whenever an authenticated provider entry is a well-known auth entry, and merges the response — including `plugin`, local MCP, formatter, `shell`, LSP, and hook sections — into the running process. That content is fetched by the OpenCode process at startup, so the Manager cannot sanitize it. On an enforced start the Manager inspects the auth file it owns (`<workspace>/.opencode/state/opencode/auth.json`) and refuses to launch whenever it contains a well-known provider entry, with an error naming the provider and the remediation (remove the provider authentication or disable sandboxing). The `OPENCODE_AUTH_CONTENT` environment variable that could inject such an entry is blocked and stripped from the child environment, and both Manager OpenCode proxy surfaces additionally refuse a `PUT /auth/{provider}` write whose body is a well-known auth entry with `403` while enforcement is active — so a well-known entry cannot be added to the running process after the startup check, which would fetch remote host-executed configuration on a later enforced start. Ordinary `api` and `oauth` auth writes continue to pass through.
One documented consequence: because project config files are disabled while enforcement is on, the assistant-mode workspace's project-level `opencode.json`, agents, and skills (under `repos/assistant/.opencode`) are not loaded for assistant sessions during enforcement. The assistant workspace directory and its `AGENTS.md` guidance still load, but its default agent and managed skills are unavailable until sandboxing is disabled and the server restarts.
## Worktree Placement
The Manager only creates agent worktrees under the two mounted roots, so every supported project plans in sandbox mode while the secret-bearing `.opencode/state` directory stays unmounted:
- **Scheduled runs** — OpenCode's experimental workspace API would place run worktrees beneath `.opencode/state`. The schedule runner detects that location, deletes the API workspace, and falls back to a raw git worktree under `/workspace/schedule-worktrees` (`job-<id>-run-<runId>`), which is mounted. A worktree returned by the API that already lives under a mounted root is used as-is.
- **User-created OpenCode worktrees** — the same API creates these outside the mounted roots, so while sandboxing is enforced the Manager refuses the creation with a clear error instead of handing the session a directory that cannot be sandboxed. Disable sandboxing (and restart) to use them.
- **Local repositories outside `/workspace/repos`** — external repositories are symlinked into `repos/`; the link target is not mounted, so an agent session in one of them is refused with the "outside the sandboxed project roots" error. Move the repository under `/workspace/repos` or disable sandboxing.
## Caveats
- **First-command latency** — The first sandboxed command after a container start pays the image pull and microVM boot cost once for all projects. This is bounded by `SANDBOX_START_TIMEOUT_MS` (default 5 minutes).
- **Image contents** — `SANDBOX_IMAGE` is the OCI image the microVM boots from. It must contain the toolchain the agent expects, including `git` if the agent runs git commands.
- **Workspace identity** — Sandboxed commands run as the Manager's effective uid (and gid), which the entrypoint aligns to `PUID`/`PGID`. The overlay defaults `SANDBOX_EXEC_USER` to `PUID`, so a non-1000 `PUID` (for example `1001`) still writes to the mounted repositories as the workspace owner. If a configured numeric `SANDBOX_EXEC_USER` cannot match the workspace owner, the toggle reports enforcement as unavailable with the reason instead of enabling a broken sandbox.
- **Permission patterns** — OpenCode `permission` rules are matched against the rewritten command (`msb exec ...`), not the agent's original text. Command-pattern permission rules must be reviewed when enforcement is on.
- **Plugin lockdown** — While enforcement is on, only the Manager-owned plugins load (see [Plugin Policy Under Enforcement](#plugin-policy-under-enforcement)); repository, project, and user-configured plugins are not evaluated in the host process. As defense in depth, the sandbox plugin also locks the `command` argument after rewriting, so any plugin that did manage to load cannot unwrap a sandboxed `bash` command, and a detected bypass blocks every subsequent sandboxed command.
- **Host credentials** — Credentials injected by the `shell.env` hook (`ocm-gh-env.js`) are not forwarded into the microVM, so agent-run `git push` / `gh` calls that depend on those injected credentials fail inside the sandbox by design. Credentials that are themselves visible inside the microVM remain usable — a token or credential helper stored in a mounted repository, an authenticated remote URL, or a credential supplied directly to the command — because the microVM's networking is enabled.
- **Assistant internal API** — The assistant-mode `.opencode` directory is masked in the microVM, so the internal API token it holds is not readable there. Assistant sessions can still manage repos, schedules, notifications, and settings through the Manager's host-side integrations; agent-run `curl` against the internal API using the masked token fails inside a sandbox by design.