feat(opencode): migrate OpenCode Manager to OpenCode 2 (#359)

* feat(opencode): migrate OpenCode Manager to OpenCode 2

Port the backend lifecycle, generated plugins, event aggregation,
schedules, worktrees, provider credentials, MCP, config handling, the
frontend chat model, and the ocm CLI to OpenCode 2.

Adopt @opencode/client 2.0.15 as the single typed V2 API contract,
require OpenCode 2.0.0 or newer (pinned 2.0.15), and delete every
V1-only code path.

* refactor(opencode): reload config in place and drop v1 compatibility shims

Route config/skill/AGENTS.md changes through the OpenCode location reload
API instead of a full server restart, stop auto-resuming interrupted
sessions, remove the restart coordinator and v1 MCP/version shims, and pin
support to OpenCode >=2.0.15 <3.0.0. Adds integration-ready retries,
service-mode launch, ocm-cli repo proxy, and new frontend form/MCP helpers.

* refactor(opencode): consolidate v2 migration helpers and harden install, proxy, and session flows

- extract shared semver and model-ref utilities, reuse across version checks
- share the OpenCode release download script across Docker, entrypoint, dev setup
- unify install/upgrade failure recovery and guard externally managed OPENCODE_BIN
- scope the repo proxy location rewrite and surface ocm proxy errors
- rework frontend session projection, permission lookup, and cache invalidation

* fix(schedules): reject unavailable agents before creating a session

* feat(opencode): add ocm install, schedule agent fallback, and session move guards
This commit is contained in:
Chris Scott authored and GitHub committed 2026-09-26 13:16:45 -04:00
1 parent 6c2ebd764b
commit dacde879d6
383 files changed
+29905 -46566

No files matched your search

+13 -9
View File
@@ -19,13 +19,17 @@ The token has two in-product consumers, neither of which is an agent:
| Generated plugins (`ocm-manager.js`, `ocm-sandbox.js`, `ocm-gh-env.js`) | The `OCM_INTERNAL_TOKEN` environment variable, injected into the OpenCode child process |
| External clients such as the `ocm` CLI | Settings -> Manager Token, served by `GET /api/settings/manager-token` |
The generated plugins are OpenCode 2 plugin modules — plain, dependency-free objects that default-export `{ id, setup }` and register their hooks and tools through the `setup` context. The Manager writes them to `<config home>/opencode/plugins/`; the legacy `opencode/plugin/` files are removed on install.
Agents never authenticate against this API themselves. They call the `ocm` tool, which holds the token inside the Manager process.
## The `ocm` Tool
The Manager installs a generated plugin (`ocm-manager.js`) that gives every agent an `ocm` tool. The tool calls this API from inside the Manager's own OpenCode process, so it needs no token, no base URL, and no network access from the agent shell.
That makes it the only path that works everywhere: a scheduled run executes in a throwaway worktree with no token of its own, and a sandboxed `bash` call runs in a microVM where `localhost` is the guest, not the Manager.
That makes it the only path that works everywhere: a scheduled run executes in a throwaway worktree with no token of its own, and a sandboxed `shell` call runs in a microVM where `localhost` is the guest, not the Manager.
OpenCode 2 validates the tool's arguments against a JSON Schema before it calls `execute`, so the `ocm` tool declares its `action` and `params` shape as a JSON Schema derived from the same Zod definitions the tool uses.
The tool has two actions.
@@ -83,7 +87,7 @@ POST /repos/*/schedules/*/runs/*/cancel
- `POST /notifications/send` — use the `send_notification` action instead.
- `GET /git-credentials/gh-env` — returns the GitHub CLI environment (`GH_TOKEN`, `GITHUB_TOKEN`) for the OpenCode host process; it must not be readable by the agent.
- `POST /sandbox/shell` — the sandbox planner's internal route that resolves and pins the shell for a `bash` call; exposing it would let the agent drive shell planning directly.
- `POST /sandbox/shell` — the sandbox planner's internal route that resolves and pins the shell for a `shell` call; exposing it would let the agent drive shell planning directly.
- `/repos/*/mirror/*` — the repo mirror protocol that the `ocm` CLI uses to sync entire repositories; it can create, replace, patch, or delete whole repos, so it stays reserved for the CLI.
Agents should use the `ocm` tool rather than the raw bearer-token endpoints below. Those endpoints remain available to the frontend, generated plugins, and other Manager-internal clients.
@@ -204,7 +208,7 @@ Returns the updated settings object.
### OpenCode Configuration
The global OpenCode configuration files in the workspace `.config/opencode/` directory are the source of truth, and these endpoints are the only supported way to change them. Up to three sources are recognized and merged in OpenCode order — `config.json`, `opencode.json`, `opencode.jsonc` — with later files overriding earlier ones. The endpoint applies the same rules as the Settings UI: any semantic change is written to disk and marks an OpenCode server restart as required; comment-only edits and changes limited to `mcp` do not.
The global OpenCode configuration files in the workspace `.config/opencode/` directory are the source of truth, and these endpoints are the only supported way to change them. The two sources OpenCode 2 reads are merged in order — `opencode.json`, `opencode.jsonc` — with later files overriding earlier ones. A legacy `config.json` is folded into a recognized source and archived; it is never read as a live source. The schema accepts both V1-compatible keys and native OpenCode 2 fields, so a V2-native config passes validation. The endpoint applies the same rules as the Settings UI: any semantic change is written to disk and applied to the running server with an in-place OpenCode location reload, and it is flagged as restart required only when that reload fails; comment-only edits do nothing, and changes limited to `mcp` are saved without a reload.
**GET `/api/internal/opencode-config`**
@@ -217,7 +221,7 @@ Read the merged persisted configuration and its source files. This is not the ru
content: object // Merged configuration across all sources
rawContent: string // Raw content of the preferred write target
sources: Array<{ // Recognized source files, in merge order
name: 'config.json' | 'opencode.json' | 'opencode.jsonc'
name: 'opencode.json' | 'opencode.jsonc'
path: string
rawContent: string
content: object
@@ -240,7 +244,7 @@ Read the merged persisted configuration and its source files. This is not the ru
**GET `/api/internal/opencode-config/effective`**
Read the running server's effective global configuration (OpenCode `GET /global/config`). Never copy this response into a save.
Read the running server's configuration as `entries`: the configuration documents and discovery directories in precedence order, lowest first, each shaped as `{ type: 'document', path, info }` or `{ type: 'directory', path }`. Its `info` values are expanded for the running server, so never copy this response into a save.
**Status Codes:**
- `200`: Effective configuration returned
@@ -250,19 +254,19 @@ Read the running server's effective global configuration (OpenCode `GET /global/
**PUT `/api/internal/opencode-config`**
Read the merged configuration first, change only the keys the user asked for, and send the complete object back with its `revision`. Only changed paths are patched into the preferred existing source (`opencode.jsonc` > `opencode.json` > `config.json`; a new installation gets `opencode.jsonc`); comments, unknown keys, and untouched inherited values are preserved. For a raw edit, send a string as `content` together with the exact `source` name.
Read the merged configuration first, change only the keys the user asked for, and send the complete object back with its `revision`. Only changed paths are patched into the preferred existing source (`opencode.jsonc` > `opencode.json`; a new installation gets `opencode.jsonc`); comments, unknown keys, and untouched inherited values are preserved. For a raw edit, send a string as `content` together with the exact `source` name.
**Request Body:**
```ts
{
content: object | string // Complete merged object, or raw text for one source
expectedRevision?: string // From GET; a stale value is rejected with 409
source?: 'config.json' | 'opencode.json' | 'opencode.jsonc' // Required for raw string edits
source?: 'opencode.json' | 'opencode.jsonc' // Required for raw string edits
}
```
**Response:**
Returns the refreshed `OpenCodeConfigFile`. Adds `restartRequired: true` when the change needs an OpenCode server restart.
Returns the refreshed `OpenCodeConfigFile`. Semantic changes are applied with an OpenCode location reload, without a restart. Adds `restartRequired: true` only when that reload fails.
**Status Codes:**
- `200`: Configuration written
@@ -275,7 +279,7 @@ Returns the refreshed `OpenCodeConfigFile`. Adds `restartRequired: true` when th
**POST `/api/internal/assistant/reload`**
Reload the assistant workspace by disposing the current OpenCode instance. Use this after editing `.opencode/agents/assistant.md` or `opencode.json` so changes take effect on the next message.
Reload the OpenCode server configuration, rebuilding every loaded location. Use this after editing `.opencode/agents/assistant.md` or `opencode.json` so changes take effect on the next message.
**Rate Limiting:** 5 requests per minute per token. Returns `429 Too Many Requests` with `Retry-After` header when exceeded.
+1 -1
View File
@@ -32,7 +32,7 @@ See [Assistant Internal API](assistant-internal-api.md) for the full API referen
The assistant's system prompt, behavior, and durable preferences live solely in `.opencode/agents/assistant.md`. This file is the single source of truth for the assistant agent's personality and self-editing rules. The `opencode.json` configuration no longer duplicates the agent persona — it only stores agent mode and workspace-level settings.
When the assistant self-edits its agent definition (e.g., to refine behavior or add durable preferences), it uses the `manager-settings` skill to call the `POST /assistant/reload` endpoint through the `ocm` `request` action. This disposes the current OpenCode workspace instance so the changes take effect on the next message. The reload endpoint is rate-limited to 5 requests per minute; the assistant always asks the user before reloading.
When the assistant self-edits its agent definition (e.g., to refine behavior or add durable preferences), it uses the `manager-settings` skill to call the `POST /assistant/reload` endpoint through the `ocm` `request` action. This rebuilds every loaded location so the changes take effect on the next message. The reload endpoint is rate-limited to 5 requests per minute; the assistant always asks the user before reloading.
## Getting Started
+82 -30
View File
@@ -25,18 +25,27 @@ Local servers run as processes on your machine:
```json
{
"name": "filesystem",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/workspace"]
"mcp": {
"servers": {
"filesystem": {
"type": "local",
"command": [
"npx",
"-y",
"@modelcontextprotocol/server-filesystem",
"/workspace"
]
}
}
}
}
```
| Field | Description |
|-------|-------------|
| `name` | Unique identifier |
| `command` | Executable to run |
| `args` | Command arguments |
| `env` | Environment variables (optional) |
| Name (key under `mcp.servers`) | Unique identifier |
| `command` | Executable and its arguments, as one array |
| `environment` | Environment variables (optional) |
### Remote Servers (HTTP)
@@ -49,20 +58,26 @@ Remote servers are accessed over HTTP/SSE:
```json
{
"name": "remote-tools",
"url": "https://mcp.example.com/sse"
"mcp": {
"servers": {
"remote-tools": {
"type": "remote",
"url": "https://mcp.example.com/sse"
}
}
}
}
```
| Field | Description |
|-------|-------------|
| `name` | Unique identifier |
| `url` | Server SSE endpoint |
| Name (key under `mcp.servers`) | Unique identifier |
| `url` | Server endpoint |
| `headers` | HTTP headers (optional) |
## Server Templates
Pre-built configurations for common MCP servers:
Pre-built configurations for common MCP servers, in the OpenCode 2 `mcp.servers` shape the Manager writes:
### Filesystem
@@ -70,9 +85,19 @@ Access local files and directories:
```json
{
"name": "filesystem",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"]
"mcp": {
"servers": {
"filesystem": {
"type": "local",
"command": [
"npx",
"-y",
"@modelcontextprotocol/server-filesystem",
"/path/to/dir"
]
}
}
}
}
```
@@ -82,11 +107,20 @@ Interact with GitHub repositories:
```json
{
"name": "github",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "your-token-here"
"mcp": {
"servers": {
"github": {
"type": "local",
"command": [
"npx",
"-y",
"@modelcontextprotocol/server-github"
],
"environment": {
"GITHUB_TOKEN": "your-token-here"
}
}
}
}
}
```
@@ -97,11 +131,20 @@ Query PostgreSQL databases:
```json
{
"name": "postgres",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "postgres://user:pass@host:5432/db"
"mcp": {
"servers": {
"postgres": {
"type": "local",
"command": [
"npx",
"-y",
"@modelcontextprotocol/server-postgres"
],
"environment": {
"DATABASE_URL": "postgres://user:pass@host:5432/db"
}
}
}
}
}
```
@@ -112,11 +155,20 @@ Web search capabilities:
```json
{
"name": "brave-search",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-brave-search"],
"env": {
"BRAVE_API_KEY": "your-api-key"
"mcp": {
"servers": {
"brave-search": {
"type": "local",
"command": [
"npx",
"-y",
"@modelcontextprotocol/server-brave-search"
],
"environment": {
"BRAVE_API_KEY": "your-api-key"
}
}
}
}
}
```
+1 -1
View File
@@ -26,7 +26,7 @@ A notification is suppressed when a visible tab is already viewing the session t
The title is the action (`Run Command`, `Edit File`, `Question`, `Error`, `Session complete`) and the body is `<repo> · <detail>`, for example `oc-manager · pnpm test`. Bodies are truncated to 140 characters. Permission and question notifications stay on screen until dismissed; every notification carries the event timestamp and re-alerts when a newer event for the same session replaces it.
Clicking a notification opens the session that raised it (`/repos/<id>/sessions/<sessionId>`). The service worker prefers a tab already showing that session, then the focused tab, then any visible tab, and only that one tab navigates; with no tab open a new window is opened. Sessions running in OpenCode workspace worktrees or opencode-forge loop worktrees resolve to their parent repository through the shared OpenCode project id, and Assistant sessions open with the `assistant=1` parameter the Assistant view requires.
Clicking a notification opens the session that raised it (`/repos/<id>/sessions/<sessionId>`). The service worker prefers a tab already showing that session, then the focused tab, then any visible tab, and only that one tab navigates; with no tab open a new window is opened. Sessions running in OpenCode worktrees or opencode-forge loop worktrees resolve to their parent repository through the shared OpenCode project id, and Assistant sessions open with the `assistant=1` parameter the Assistant view requires.
## Browser Compatibility
+2 -2
View File
@@ -108,9 +108,9 @@ OpenCode Manager provides a comprehensive web interface for managing OpenCode AI
### OpenCode Server Health
- **Live Status** — Server health indicator in Settings (Healthy/Unhealthy/Starting)
- **Graceful Restart** — Active sessions are aborted and resumed with `continue` after restart
- **Graceful Restart** — Interrupted sessions resume natively after restart
- **Auto-Recovery** — Configurable health monitoring with automatic recovery on failure
- **Version Management** — View current versions and trigger OpenCode upgrades from the UI
- **Version Management** — View current versions and trigger OpenCode 2 upgrades from the UI
[Learn more →](server-health.md)
+42 -32
View File
@@ -1,10 +1,10 @@
# Agent Sandboxing
Run OpenCode agent `bash` 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.
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.
## Overview
When sandboxing is enabled, every command an OpenCode agent runs through the `bash` tool is executed inside a microVM managed by [`msb`](https://github.com/superradcompany/microsandbox). OpenCode itself continues to run in the Manager container and loads the same global and project configuration, providers, models, plugins, tools, MCP servers, formatters, LSP servers, hooks, and shell settings as it does with sandboxing disabled.
When sandboxing is enabled, every command an OpenCode agent runs through the `shell` tool is executed inside a microVM managed by [`msb`](https://github.com/superradcompany/microsandbox). OpenCode itself continues to run in the Manager container and loads the same global and project configuration, providers, models, plugins, tools, MCP servers, formatters, LSP servers, hooks, and shell settings as it does with sandboxing disabled.
The microVM sees repositories through bind mounts at the same paths used by the Manager. Agent commands therefore operate on the same files while running under a separate kernel without access to Manager configuration, provider credentials, or SSH keys.
@@ -12,46 +12,48 @@ The microVM sees repositories through bind mounts at the same paths used by the
| Execution path | Through the microVM |
|----------------|---------------------|
| Chat session `bash` tool calls | Yes |
| Scheduled run `bash` tool calls | Yes |
| Subagent `bash` tool calls | Yes |
| WebUI `!command` shell mode (`POST /session/:id/shell`) | Yes; it carries a tool call id like the `bash` tool, so it is planned and routed into the microVM. It is not badged in the UI because the surface fires no `tool.execute.after` hook |
| Slash-command shell templates (`` !`cmd` ``, `POST /session/:id/command`) | No; normal OpenCode behavior |
| PTY terminals (`POST /pty`, `/pty/:id/connect`) | No; normal OpenCode behavior |
| OpenCode file tools | No |
| Chat session `shell` tool calls | Yes |
| Scheduled run `shell` tool calls | Yes |
| Subagent `shell` tool calls | Yes |
| WebUI `!command` shell mode (`POST /api/session/:sessionID/shell`) | Yes; it spawns through the same `Shell.create` path as the `shell` tool, so it is planned and routed into the microVM. It is not badged in the UI because the surface fires no `tool.execute.after` hook |
| Shell API (`POST /api/shell`) | Yes; it spawns through the same `Shell.create` path as the `shell` tool. It is not badged in the UI because the surface fires no `tool.execute.after` hook |
| Slash-command shell templates (`` !`cmd` ``, `POST /api/session/:sessionID/command`) | No; OpenCode expands each interpolation itself with the configured shell, directly on the host and outside `Shell.create`, so the `create.before` hook never sees it |
| PTY terminals (`POST /api/pty`, `POST /api/pty/:ptyID/connect`) | No; normal OpenCode behavior, with the user's configured shell |
| OpenCode file tools | No; while enforcement is on they are denied the global configuration directory (see [Mounts and Secrets](#mounts-and-secrets)) |
| Manager-side git operations | No |
| Plugins and custom tools | No; normal OpenCode behavior |
| The `ocm` tool (`ocm-manager.js`) | No; runs in the Manager's OpenCode process |
| Local MCP servers | No; normal OpenCode behavior |
| Formatters, LSP servers, and hooks | No; normal OpenCode behavior |
| Custom provider modules | No; normal OpenCode behavior |
| Explicit OpenCode `shell` configuration | Overridden while enforcement is on |
The Manager generates a POSIX shell shim and points OpenCode's `shell` setting at it, so the agent `bash` tool spawns the shim instead of a host shell. The Manager-owned `ocm-sandbox.js` plugin pins that setting and, before each `bash` spawn, asks the Manager for the sandbox working directory and injects it as `OCM_SANDBOX_WORKDIR`. The shim routes the command into the microVM through `msb exec` whenever that variable is set. Both the pinned setting and the injected directory are locked and verified so a later plugin cannot silently restore host execution. If the sandbox cannot be prepared, the tool call fails instead of running on the host.
OpenCode 2 routes the agent `shell` tool, WebUI `!command` shell mode, and the shell API through `Shell.create`, which triggers the `shell` domain `create.before` hook with a mutable `{ command, cwd, timeout, shell, env }` before spawning. The Manager-owned `ocm-sandbox.js` plugin registers that hook: while enforcement is on, it asks the Manager for the sandbox working directory and pins both the generated shim as the shell and that directory as `OCM_SANDBOX_WORKDIR` on the event. The event carries no tool call id, so every `Shell.create` spawn is sandboxed rather than only the ones with a tool call. PTY terminals and slash-command shell templates use separate paths and are not affected.
Both pinned values are locked accessors, and the plugin verifies each lock, so a later plugin cannot silently restore host execution. The shim fails closed as well: without `OCM_SANDBOX_WORKDIR` it prints an error to stderr and exits 126 instead of running the command on the host. If the sandbox cannot be prepared, the spawn fails instead of running on the host.
The command the agent wrote is never rewritten. It reaches `msb exec` as a single argument, so the recorded tool call, the permission rules, and the model's own context all keep the original command.
Each sandboxed `bash` call is marked `sandbox` in its tool metadata, which the WebUI shows as a green badge on the tool call. Metadata is not sent to the model.
Each sandboxed `shell` call is marked `sandbox` in its tool metadata, which the WebUI shows as a green badge on the tool call. Metadata is not sent to the model.
## OpenCode Configuration
Sandbox enforcement does not sanitize, rewrite, filter, or replace OpenCode configuration files. Global and project configuration loads normally, configured plugins are installed normally, and config, MCP, and authentication API requests are forwarded unchanged.
The single exception is the in-memory `shell` setting: while enforcement is on, the sandbox plugin pins it to the generated shim. No configuration file is modified. A shell the user configured is remembered and handed back to the shim for the surfaces that are not the agent `bash` tool.
Enforcement does not change the configured `shell` setting. The plugin pins the shim per spawn instead, so the setting is left as the user configured it and the shell it names still applies to PTY terminals and to slash-command shell templates.
Existing `.ocm-sandbox-backup` and `.ocm-quarantine` artifacts created by older releases are restored during startup and are no longer created.
Configured extensions execute with OpenCode's normal host-process privileges. This includes plugins, custom tools, local MCP servers, formatters, LSP servers, hooks, custom provider modules, and explicit shell configuration. These are trusted configuration outside the agent `bash` isolation boundary.
Configured extensions execute with OpenCode's normal host-process privileges. This includes plugins, custom tools, local MCP servers, formatters, LSP servers, hooks, custom provider modules, explicit shell configuration, and slash-command shell templates. These are trusted configuration outside the agent `shell` isolation boundary.
## Other Shell Surfaces
Slash-command shell templates and PTY terminals follow OpenCode's normal host-process behavior during enforcement. WebUI `!command` shell mode **is** sandboxed: OpenCode builds a synthetic tool part for it and passes that part's call id to `shell.env`, so it is planned and routed into the microVM exactly like an agent `bash` call.
WebUI `!command` shell mode and the shell API (`POST /api/shell`) **are** sandboxed: both spawn through the same `Shell.create` path as the `shell` tool, so they are planned and routed into the microVM.
The unsandboxed surfaces also spawn the shim, because it is the configured shell, but no working directory is injected for them, so the shim passes the command straight through to the host shell. PTY terminals receive the user's configured shell; slash-command shell templates fire no `shell.env` hook at all and fall back to the shell the Manager resolved at startup rather than a login shell.
PTY terminals follow OpenCode's normal host-process behavior during enforcement and use the user's configured shell. Slash-command shell templates are not sandboxed either: when a command template contains a `` !`cmd` `` interpolation, OpenCode resolves the configured shell and runs the command directly on the host before the resulting prompt is sent, without going through `Shell.create` or its `create.before` hook. That interpolation is trusted configuration outside the agent `shell` isolation boundary.
The `shell.env` hook input carries only `{ cwd, sessionID?, callID? }`, so the presence of a call id is the only available discriminator. It separates session-attached shells (the `bash` tool and `!command` mode) from PTY creation, which has no session context. It cannot distinguish the `bash` tool from `!command` mode.
There is no fallback to a host shell in the `Shell.create` path: the shim refuses to run without a pinned sandbox working directory, so a spawn whose plan, shim, or lock is unavailable is refused instead of running on the host.
The OpenCode server binds to the configured `OPENCODE_HOST` regardless of enforcement, so the password guard for non-loopback hosts applies in both modes.
The OpenCode server binds to the configured `OPENCODE_HOST` regardless of enforcement; OpenCode 2 always requires a password, so the managed server always starts with the password resolved by the Manager.
## Host Requirements
@@ -91,15 +93,15 @@ The microVM receives writable bind mounts for:
|-----------|-------------------|
| `/workspace/repos` | Project root |
| `/workspace/schedule-worktrees` | Project root |
| `/workspace/.opencode/state/opencode/worktree` | Project root: worktrees created through OpenCode's workspace API |
| `/workspace/.opencode/state/opencode/worktree` | Project root: worktrees created through OpenCode's worktree API |
| `/workspace/.opencode/state/opencode/forge/worktrees` | Project root: worktrees created by the opencode-forge plugin for its loops |
| `/workspace/.opencode/state/opencode/tool-output` | Where OpenCode saves the full content of a truncated tool result before handing the agent that absolute path |
| `/workspace/.config/opencode/skills` | Global skills, including the scripts and reference files a skill bundles and refers to by absolute path |
| `/workspace/.opencode/tmp/opencode` | The temporary directory the `bash` tool description tells agents to use for work outside the workspace |
| `/workspace/.opencode/tmp/opencode` | The temporary directory the `shell` tool description tells agents to use 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 `bash` call, which is how an agent ends up searching for a file it was just told the exact location of.
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 four project roots are accepted as working directories. The other three mounts are readable and writable but are never a valid working directory, so `bash` calls still have to run inside a repository or a worktree.
Only the four project roots are accepted as working directories. The other three 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.
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.
@@ -107,7 +109,7 @@ Because `localhost` inside the microVM is the guest rather than the Manager, and
The microVM also mounts a runtime-owned tmpfs at `/tmp`. It is sized to one quarter of the microVM memory, 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 `bash` tool description advertises — 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 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 `shell` tool description advertises — 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 the microVM:
@@ -115,20 +117,28 @@ The following remain outside the microVM:
|-----------|----------|
| `/workspace/config` | SSH configuration and known hosts |
| `/workspace/.ssh-keys` | Repository SSH private keys |
| `/workspace/.config/opencode/plugin`, `/workspace/.config/ocm` | Generated plugins and the shell shim — the enforcement mechanism itself |
| `/workspace/.config/opencode/plugins`, `/workspace/.config/ocm` | Generated 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.
The configuration directory also holds `service.json`, where the Manager writes the managed OpenCode server password for service mode. OpenCode's default agent permissions allow the host-side file tools to read the global configuration directory, and that password grants the full OpenCode API, including unsandboxed PTY terminals. While enforcement is on, `ocm-sandbox.js` therefore denies, through OpenCode's permission `evaluate` hook:
- `read` of `service.json` itself;
- `grep` and `glob` whose absolute search path is the configuration directory or one of its ancestors;
- `external_directory` access to the configuration directory or one of its ancestors.
As a consequence, the host-side file tools cannot read the top-level configuration files (`opencode.json`, `opencode.jsonc`, `service.json`) while enforcement is on; agents read and change the OpenCode configuration through the `ocm` tool instead. The `skills` subdirectory is unaffected.
## Enabling and Enforcement
1. Enable **Sandbox** in Settings.
2. Restart the OpenCode server when prompted.
3. The Manager starts the new child with `OCM_SANDBOX_ENFORCED=true`.
4. The Manager writes the shell shim next to the generated plugins and refuses to start an enforced server if it cannot.
5. The sandbox plugin resolves each `bash` tool working directory through the internal planner and pins it for the shim.
6. If capability detection, planning, boot, attestation, or working-directory pinning fails, the tool call fails instead of running on the host.
5. The sandbox plugin resolves the `Shell.create` working directory through the internal planner and pins the shim and that directory for the spawn.
6. If capability detection, planning, boot, attestation, or shell pinning fails, the spawn fails instead of running on the host.
A directory outside the mounted roots fails with:
@@ -140,14 +150,14 @@ The enforcement stamp remains authoritative for the lifetime of the OpenCode chi
## Worktree Placement
- Scheduled runs use worktrees under `/workspace/schedule-worktrees` when OpenCode's workspace API returns a path beneath unmounted state storage.
- OpenCode's own workspace worktrees (`/workspace/.opencode/state/opencode/worktree`) and opencode-forge loop worktrees (`/workspace/.opencode/state/opencode/forge/worktrees`) are project roots, so agent `bash` calls run inside them without further configuration. Both live under OpenCode's data directory because the Manager sets `XDG_DATA_HOME=/workspace/.opencode/state`.
- Any other worktree location outside the mounted roots is created normally; only a later agent `bash` call whose working directory is outside the mounts is refused by the planner.
- 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. Both live under OpenCode's data directory because the Manager sets `XDG_DATA_HOME=/workspace/.opencode/state`.
- Any other worktree location outside the mounted roots is created normally; only a later agent `shell` call whose working directory is outside the mounts is refused by the planner.
- External repositories symlinked into `/workspace/repos` remain outside the microVM because the link target is not mounted.
## Git Credentials in the Sandbox
The guest environment is empty by default, so a sandboxed `git push`, `git pull`, or `gh` call has no credentials and fails to authenticate. This applies to agent `bash` calls and to WebUI `!command` shell mode alike, since both are routed into the microVM.
The guest environment is empty by default, so a sandboxed `git push`, `git pull`, or `gh` call has no credentials and fails to authenticate. This applies to agent `shell` calls, WebUI `!command` shell mode, and the shell API alike, since all three are routed into the microVM.
Forwarding is opt-in, off by default:
@@ -243,7 +253,7 @@ The Manager image itself carries the same Chromium runtime libraries, resolved b
- With sandboxing enabled the image pull and microVM boot happen at Manager startup, so commands normally pay neither. A command that runs before the warm-up finishes waits on that same boot, 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 slash-command shell templates while enforcement is on, and is bypassed for `!command` shell mode because that surface is routed into the microVM.
- A `shell` the user configured does not apply to the `shell` tool, `!command` shell mode, or the shell API while enforcement is on, because all three are routed into the microVM; 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](#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 `bash` sandboxing.
- Plugins and other configured host-process extensions are trusted and are not isolated by agent `shell` sandboxing.
+1 -1
View File
@@ -78,7 +78,7 @@ The **Skills** tab in the schedule dialog lets you:
- Select one or more **skill slugs** from a multi-select input
- Add free-form **notes** (max 2000 characters) that the agent receives as additional context
Skill metadata is passed to the OpenCode workspace config when the run starts, making the selected skills available to the agent for that run only.
When the run starts, the Manager resolves the selected skill slugs against the skills available in the run's location and attaches the matching skills directly to the submitted prompt, making them available to the agent for that run only. Skill slugs that are not available in the location are omitted, and if the available skills cannot be listed the run continues without any skill attachments.
## Worktree Isolation
+13 -14
View File
@@ -18,17 +18,17 @@ OpenCode Manager runs a supervised OpenCode server process to handle agent sessi
The panel also displays:
- **OpenCode version** — The installed version of the OpenCode server (e.g., `v1.17.11`)
- **OpenCode version** — The installed version of the OpenCode server (e.g., `v2.0.15`). OpenCode Manager requires OpenCode 2.x at 2.0.15 or newer; a 1.x, 3.x, or older 2.x binary fails to start.
- **Manager version** — The current OpenCode Manager version (e.g., `v0.14.5`)
## Health Monitoring
The Manager periodically polls the OpenCode server's health endpoint. If the server becomes unresponsive:
The Manager periodically polls the OpenCode server's health endpoint (`GET /api/info`, authenticated with the managed password). A 401 or a non-JSON response counts as unhealthy. If the server becomes unresponsive:
1. The Manager logs the failure and increments a failure counter
2. After a configurable number of consecutive failures (default: 2), automatic recovery begins
3. Recovery restarts the OpenCode server process
4. In-flight sessions are aborted and resumed once the server is healthy again
4. OpenCode 2 resumes interrupted executions natively on boot, so the Manager makes no abort or `continue` calls itself
### Configuration
@@ -42,7 +42,7 @@ Health monitoring is configured through environment variables:
## Configuration Recovery
The on-disk global configuration files in `.config/opencode/` are the source of truth. OpenCode merges up to three recognized sources in order — `config.json`, `opencode.json`, then `opencode.jsonc` — with later files overriding matching keys from earlier ones. The Manager reads and edits the same set: saves patch only the changed paths into the preferred existing source (`opencode.jsonc` > `opencode.json` > `config.json`), preserving comments and untouched keys, and a fresh installation is seeded with `opencode.jsonc`. When a source exists at boot but fails validation, the Manager logs a warning and starts with the files unchanged — an invalid config is never automatically replaced or rolled back during boot.
The on-disk global configuration files in `.config/opencode/` are the source of truth. OpenCode 2 reads the two recognized sources in order — `opencode.json`, then `opencode.jsonc` — with later files overriding matching keys from earlier ones. The Manager reads and edits the same set: saves patch only the changed paths into the preferred existing source (`opencode.jsonc` > `opencode.json`), preserving comments and untouched keys, and a fresh installation is seeded with `opencode.jsonc`. The schema accepts both V1-compatible keys and native OpenCode 2 fields, so a V2-native config is not flagged invalid. MCP servers are always written in the native OpenCode 2 shape under `mcp.servers.<name>` — `type` (`local` with `command`, optional `cwd` and `environment`; or `remote` with `url`, optional `headers` and `oauth` using `client_id`, `client_secret`, `scope`, and `redirect_uri`), plus optional `disabled` and `timeout` (`startup`, `catalog`, `execution` in milliseconds). Legacy flat `mcp.<name>` entries are never written; OpenCode 2 still normalizes them on load, so they appear in Settings → MCP from the running server's status but must be moved under `mcp.servers` to be edited or removed from the Manager. A legacy `config.json`, which OpenCode 2 ignores, is folded into the lowest-precedence source it does not override and archived on startup. When a source exists at boot but fails validation, the Manager logs a warning and starts with the files unchanged — an invalid config is never automatically replaced or rolled back during boot.
The health-watch ladder is the only automatic repair path. When the supervised OpenCode server fails repeated health checks, recovery runs these actions in order until the server is healthy:
@@ -61,10 +61,8 @@ Earlier releases stored named configuration profiles in the Manager database. On
When you restart the OpenCode server (manually or through an upgrade), active sessions are handled gracefully:
1. **Capture** — The Manager captures all active user sessions (excluding subagent and scheduled-run sessions)
2. **Abort** — Active sessions are aborted cleanly on the running server
3. **Restart** — The OpenCode server process is stopped and started fresh
4. **Resume** — Once healthy, a `continue` prompt is automatically sent to each previously active session
1. **Restart** — The OpenCode server process is stopped with a grace period so in-flight turns are suspended, then started fresh
2. **Resume** — OpenCode 2 resumes interrupted executions natively on boot and continues each turn in its transcript; the Manager makes no abort or `continue` calls itself and does not report individual sessions
### Confirmation
@@ -72,23 +70,24 @@ If there are active sessions when you click **Restart**, a confirmation dialog s
## Upgrading OpenCode
Click **Update** to check for and install the latest OpenCode version. The process:
Click **Update** to check for and install the newest supported OpenCode 2 version. The process:
1. Checks the currently installed version against the latest available release
2. Downloads and installs the update if available
1. Checks the currently installed version against the newest stable release of the `@opencode/cli` package on npm that is inside the supported range (at or above the pinned version, same major version); newer major versions are never selected
2. Downloads the matching binary from `https://opencode.ai/files/bin/<version>/` and verifies it before installing to `~/.opencode/bin/opencode`
3. Restarts the server using the same session-resume flow described above
4. The new version is displayed in the status panel after restart
If the upgrade fails but the server recovers to a usable state, a recovery notice is shown with the fallback version.
Installing a specific version from Settings → OpenCode works the same way; versions outside the supported range are rejected before any download. A failure before the installed binary is replaced (registry lookup, download, or extraction) returns an error without restarting the server. If the failure happens after the binary is replaced and the server recovers to a usable state, a recovery notice is shown with the fallback version.
When `OPENCODE_BIN` is set, the OpenCode binary is managed outside the Manager: **Update** and version installs are refused with `409` and nothing is downloaded or restarted.
## Manual Restart Triggers
Besides the explicit **Restart** button, the server is automatically restarted when:
- **Assistant workspace is reloaded** — Via the `POST /assistant/reload` internal API endpoint
- **Config import completes** — Importing a standalone OpenCode config into the workspace
- **Version upgrade** — After installing a new OpenCode version
Saving the OpenCode configuration never restarts the server on its own. Any change to the merged configuration is written to disk and flagged as **restart required**; the server keeps running on the previous configuration until you restart it. Two exceptions do not set the flag: comment-only edits, and changes limited to the `mcp` section, which the Settings UI applies to the running server directly. Saving a provider credential, or completing a provider OAuth flow, restarts the server through the same session-resume flow so newly configured providers are discovered.
Saving the OpenCode configuration never restarts the server. A change to the merged configuration is written to disk and applied immediately with an OpenCode location reload, which re-reads the configuration, agents, commands, skills, plugins, and `AGENTS.md` for every loaded location without interrupting running sessions. Comment-only edits do nothing, and changes limited to the `mcp` section are applied by the Settings UI through the MCP API. The change is flagged as **restart required** only when the reload fails, for example because the server is unavailable. Changes to how the server process is launched still need a restart: server environment variables, Git credentials and identity, sandbox enforcement, manager token rotation, the server password, and OpenCode version installs. Saving a provider credential, or completing a provider OAuth flow, applies to the running server immediately without a restart, because OpenCode 2 stores credentials in its database and broadcasts the change.
A save is rejected with `409` when the files changed since you loaded them (stale revision), or when it would remove a value that is defined only in a lower-priority source file — removing it from the preferred file would leave the inherited value in effect.