OpenCode sandbox: isolate your agent and control costs

Choose an execution boundary for OpenCode, configure its network and spending limits, and budget running time separately from retained disk.

•

Published on

•

OpenCode sandbox: isolate your agent and control costs
Do not index
Do not index
An OpenCode sandbox is an isolated environment around the coding agent: OpenCode's own security policy says its permission prompts do not provide security isolation. For hosted work, Agent37 runs OpenCode on standard gVisor instances or full VMs; choose the runtime around your build tools, network controls, and persistence needs. A standard 2 vCPU, 4 GB RAM, 4 GB disk instance costs $4.76 for 730 running hours, excluding model and tool usage.
The useful question is what the agent can reach after it follows a bad instruction. A test suite, dependency installer, or repository script can exercise the same authority as the process running it. Give that process a deliberately limited computer, then decide which approvals still need a person.
This guide covers version-specific permissions, hosted deployment choices, and a reproducible infrastructure budget. Documentation and rates were checked on November 30, 2026; the examples are configuration guidance, not a security certification or performance benchmark.

What an OpenCode sandbox must isolate

OpenCode's published threat model explicitly recommends a container or VM when you need isolation. That statement is stronger evidence than an old feature-request thread or the absence of a configuration field.
Design around four boundaries:
Boundary
What to decide before execution
Files
Which repository, caches, and output directories may the process read or change?
Network
Which model endpoints, registries, and Git remotes can it contact?
Credentials
Which scoped tokens are available, and can a proxy keep them outside the worker?
Lifetime
When does execution stop, and what survives restart or deletion?
A working directory is useful context, but it does not by itself confine a process. A fresh Git worktree helps review changes, but it does not remove access to other files. Likewise, an isolated filesystem does not prevent a process from sending the files it can read to an allowed destination.
For a hosted service, keep the job coordinator outside the worker. Give each trust domain its own environment, collect a diff and test output, and approve publication separately. That makes the authority granted to one job easier to inspect and revoke.

Match permissions to the OpenCode version you run

Run opencode --version inside the worker before changing its configuration. A managed template and your laptop may carry different releases. The migration guide now says V2 reads supported V1 configuration without rewriting it; converting every file is optional. Plugins and clients using the server API need separate migration checks.
Configuration
V1 form
Native V2 form
Permission field
permission object
permissions array
Shell action
bash
shell
Delegation action
task
subagent
For a V2 interactive review worker, this example asks before shell execution and access outside the project, and refuses direct edits to release manifests:
{
  "$schema": "https://opencode.ai/config.json",
  "permissions": [
    { "action": "shell", "resource": "*", "effect": "ask" },
    { "action": "external_directory", "resource": "*", "effect": "ask" },
    { "action": "edit", "resource": "release-manifests/*", "effect": "deny" }
  ]
}
The permission reference documents ordered rules: the final match wins. V2 allows external directories by default. Saved approvals persist per project, while configured denials still apply. Custom subagents use their own permissions, so check each one.
These are tool controls. An approved shell still has the operating-system user's authority and may write files denied to the edit tool. Put sensitive paths outside its accessible filesystem. For unattended jobs, decide how the client handles approval requests before launching a long task.
Use the configuration reference to locate project, global, and system settings. Keep administrator restrictions outside agent-writable files, and use managed policies where appropriate. A JSON file the agent can replace is a poor place to rely on for a lasting boundary.

Choose the execution boundary your build actually needs

For a trusted, interactive project, an OS wrapper can restrict process access without provisioning a remote machine. Check exactly which tools it encloses. The third-party opencode-sandbox plugin, for example, documents OS isolation for shell commands but policy guards for V2 file tools. That is different from enclosing the entire agent process. Review compatibility and enforcement behavior before relying on a plugin; the host still needs to stay available.
A conventional Docker or Podman container packages the whole agent and its dependencies. On a server, mount only the workspace it needs, keep state in an intentional volume, and avoid mounting the host Docker socket. Ordinary Linux containers share their host's kernel; privileged settings and broad mounts can defeat the separation you expected.
Docker Sandboxes is a separate product from running an ordinary container. Its OpenCode guide documents sbx run opencode ~/my-project for the local workflow. Docker's local/cloud comparison explains that cloud mode has separate secrets and network policies, no host-path mounts, and its own lifetime settings. Moving a local recipe to a server requires checking those differences.
For Agent37, standard gVisor instances add an application-kernel boundary and suit ordinary coding tasks that do not need a Docker daemon. Choose a full VM for Docker/Compose or other requirements needing a guest kernel. Our microVM versus container guide explains how to evaluate that tradeoff.

Hosted OpenCode options serve different workflows

Start with the integration you need, then compare costs for its actual lifecycle.
E2B's OpenCode guide provides a prebuilt opencode template for running the whole agent remotely. It distinguishes that approach from keeping OpenCode local and using remote workspaces. Its headless example also injects provider credentials outside the guest through Secret.fill, with SDK version requirements. Decide where the model loop and real credentials live before transferring a repository.
Cloudflare's OpenCode runner follows a repository-to-diff workflow. Its example routes model calls through AI Gateway, adds the gateway token in the Worker, and restricts the sandbox to the gateway and GitHub. That is useful when your application already uses Workers and you want a coordinator around each coding task.
Vercel's OpenCode guide combines a microVM, authenticated agent server, outbound policy, and optional credential brokering. Inspect the network-layer secret handling if keeping provider keys out of the guest is a requirement.
Agent37 offers a persistent instance with a preinstalled OpenCode template, managed-model access, and the same lifecycle API used for other sandbox workloads. This fits a worker that repeatedly returns to its repository and installed tools.
These are deployment differences, not throughput measurements. For other providers, include required plans, current allowances, snapshots or volumes, session limits, and active-CPU versus allocated-resource billing. Multiplying a headline hourly price by 730 can miss most of that invoice.

Create a persistent OpenCode worker on Agent37

The OpenCode template includes the coding agent and its chat gateway, with no browser or desktop. It can use the managed model or your own provider credentials. The instance's software and its model usage are separate from infrastructure charges.
Create from your trusted coordinator, with AGENT37_API_KEY in its environment. This example chooses the standard resources used in the cost table, allows HTTPS to the managed-service endpoint and GitHub, and grants $2 of monthly managed-spend headroom:
curl --fail-with-body https://api.agent37.com/v1/instances \
  -H "Authorization: Bearer $AGENT37_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "template": "agent37-opencode",
    "type": "default",
    "resources": { "cpu": 2, "memory": 4, "disk": 4 },
    "name": "OpenCode review worker",
    "budget": { "monthly_cap_micros": 2000000 },
    "network": { "allow": ["api.agent37.com", "github.com"] }
  }'
The create API returns the instance's id and url. A running status means the computer is up. Poll GET /v1/health on that URL until healthy is true before the first message. The narrow network list above is a starting policy, not a complete dependency-installation allowlist.
Set INSTANCE_URL to the returned URL on your coordinator. Then send a small read-only task to the template's chat endpoint:
curl --fail-with-body "$INSTANCE_URL/v1/responses" \
  -H "X-Agent37-Key: $AGENT37_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"input":"Report the installed OpenCode version and current working directory. Do not modify files."}'
Inspect the response for task errors. Omit session_id on the first turn, then reuse the returned value for follow-up work. The template creates its own session identifiers. Record the template revision and installed binary version so a future update is a deliberate change.
The managed-service budget defaults to zero. Raising its cap grants permission to spend; it does not deposit money. Your workspace wallet still needs funds. The cap covers managed services, not compute, disk, or charges billed to your own model-provider key. An omitted model uses the template's managed default, even when another provider is configured.
The example leaves auto-sleep off. Stop the worker after a bounded job, or configure auto-sleep around the workload. URL inactivity can put a worker to sleep while a background task still matters, so test that behavior before using a short timeout.
For Docker builds, choose a full VM. The VM guide explains that agent37-ubuntu includes Docker and defaults to 12 GB disk. The OpenCode template has different software; selecting a VM does not automatically install Ubuntu's toolset. VM entrypoints have no systemd init, and durable Docker data belongs on the billed disk. Creation requires sufficient wallet balance for the funding check.

Restrict outbound access without breaking the model

Agent37's current network policy accepts domains as well as IPv4 addresses and ranges. Domains cover HTTPS on port 443. A list containing a domain gets DNS resolution without separately listing a resolver. IPv6 entries are not accepted.
To retain managed model and tool access, include api.agent37.com. Under deny-all, those services are unavailable. Add the exact Git, registry, artifact, or provider destinations your task requires; github.com alone does not cover every GitHub subdomain or package download.
A wildcard such as *.github.com includes the apex and subdomains. That can simplify a workflow, but it grants broader access. Plain HTTP and other ports require address entries; listing a domain does not permit SSH to that name. Policies limit outbound traffic, so they do not replace authentication on instance URLs or public services.
Apply a changed policy before the agent begins untrusted execution. A successful 200 confirms enforcement. A 503 try_again means the policy is saved but enforcement still needs confirmation; repeat the same update before starting the job. The documented policy persists through lifecycle operations and also applies to full VMs.
Keep credentials out of the checkout. A repository token should cover only the required repository and operations. A provider key in the guest environment remains readable by processes with that authority. If your design requires the real key to stay outside the guest, evaluate a credential-injecting gateway explicitly rather than assuming an environment variable provides that property.
An allowlisted destination can still receive data the worker can read. Limit files and credentials alongside network access, then test an allowed request and a deliberately disallowed one. Include redirects and dependency downloads in that test; the hostname you begin with may not be the final destination.

Budget running time and retained disk separately

At current Agent37 rates, standard compute costs $0.80 per vCPU plus $0.70 per GB RAM per 730-hour month. Disk costs $0.09 per GB over the same period. Full VM compute is 2.5 times standard compute; disk has no multiplier.
For 2 vCPU and 4 GB RAM, standard compute is $4.40 per 730 hours and VM compute is $11.00. The following examples retain disk for the entire 730-hour accounting period and assume the instance is stopped or sleeping outside the stated running time:
Runtime and allocated disk
60 running hours
730 running hours
No running hours, disk retained
Standard gVisor, 4 GB disk
$0.72
$4.76
$0.36
Full VM, 4 GB disk
$1.26
$11.36
$0.36
Full VM, 12 GB disk
$1.98
$12.08
$1.08
The standard 60-hour calculation is $4.40 × 60 / 730 + $0.09 × 4 = $0.7216, rounded to $0.72. This is an estimate from published rates, not a measured customer bill. Model tokens, paid tools, and any separately purchased services are excluded.
An awake but idle instance still bills compute. Auto-sleep must be enabled and configured appropriately; stopping or sleeping pauses compute while retained disk continues billing. If you delete after 60 hours instead of retaining disk for 730 hours, the same standard 4 GB-disk example is about $0.39, and the full VM example is about $0.93. Export anything you need first: deletion ends the instance meter and removes its working storage. See the billing rules for state transitions and wallet behavior.
Size disk for your checkout, dependencies, caches, and build outputs. The 4 GB example makes the arithmetic comparable, but a Docker-heavy project may need more. Eligible new Cloud accounts receive $5 starter credit after adding a card; this is trial credit, and VM funding requirements still apply.

Validate one job before scaling the worker fleet

Use a disposable copy of a representative repository. Ask OpenCode to make a small change and run its normal tests. Save the diff, exit codes, and relevant logs outside the worker before cleanup.
Then exercise the boundaries deliberately with harmless fixtures. Check that an unmounted private file is unavailable, an unrelated outbound destination is blocked under your chosen policy, and the agent cannot obtain a production credential it was never given. Confirm that expected model calls still work.
Finally, stop and start the worker. Verify that required files survive and the coordinator can recover when a request ends without a response. Check the existing session or job state before repeating a task that could have side effects. Persistent disk does not guarantee that every process or connection survives a lifecycle event.
Keep the first job's evidence: source commit, template revision, effective policy, test exit code, diff, elapsed running time, and model spend. That record lets you compare cost per accepted change instead of price per idle machine. The commands here were checked against current documentation and for syntax; this guide does not claim a provisioned benchmark or a measured security result.
Start with one Agent37 sandbox, measure the resource use of your actual test job, and expand only after the boundaries and recovery behavior match your requirements.

OpenCode sandbox FAQ

Does OpenCode provide isolation by itself?

Its published security policy says no. Permission rules help control tool use, while a separately configured container, VM, or other enforced execution boundary limits the process's authority.

Can I use V1 permission snippets with V2?

V2 supports existing V1 configuration where the migration guide documents compatibility. Native V2 uses permissions and shell. Check plugins and server clients separately, and verify behavior in the actual worker.

Does a gVisor instance support Docker builds?

Agent37's standard gVisor runtime cannot run a Docker daemon. Choose its full VM runtime for Docker/Compose and allocate enough persistent disk for images and build caches.

Is $4.76 the total monthly cost of OpenCode?

It is the standard 2 vCPU, 4 GB RAM, 4 GB disk infrastructure estimate for 730 running hours. Model and tool usage are additional, and different resources or runtime choices change the total.

Why does my managed model fail after network lockdown?

Under deny-all, managed services cannot be reached. With a domain allowlist, include api.agent37.com, confirm the policy is enforced, and check both the workspace balance and the instance's managed-service budget.
Vishnu

Written by

Vishnu

Founder at Agent37, which runs managed hosting for OpenClaw and Hermes agents for 1,000+ users. Writes about what actually breaks when you leave an AI agent running.