An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
feat(agents): OpenCode 2 runs a turn over ACP once the browser's tools have reached it, with a sign-in and database of Browsentic's own, beside OpenCode 1 unchanged
Shahriar455b81da63d2
diff --git a/docs/guide/agents.md b/docs/guide/agents.mdindex cf08b05..1fbea3f 100644--- a/docs/guide/agents.md+++ b/docs/guide/agents.md@@ -268,40 +268,69 @@ and please report them.### OpenCode is in beta-The OpenCode runner was checked against `opencode` 1.18.32 with a stand-in model provider: every+OpenCode ships in two lines, which both install an `opencode` command: OpenCode 1 (`npm i -g+opencode-ai`, what OpenCode's own docs install) and OpenCode 2 (`npm i -g @opencode/cli`, which also+installs `opencode2`). Browsentic reads which one it has from `opencode --version` and runs each its+own way. The runner was checked against 1.18.32 and 2.0.32 with a stand-in model provider: everyflag and setting it passes, the containment under a user config written to break it, the browsertools reaching a run, a follow-up turn resuming, and each error OpenCode reports. A real modeldriving a real page has not been tried yet, because OpenCode Zen's free models refuse a containedrun and no paid provider was signed in where it was built. Expect rough edges, and please reportthem.-- **Sign in to a provider first.** Run `opencode auth login`. Zen's free models answer only- requests that carry OpenCode's own built-in tools. A Browsentic run carries only the browser's, so- they refuse it with *free tier can only be used from within OpenCode*. Until OpenCode has a login,- or a provider in its config such as a local model, the agent picker shows *needs setup*.+What both lines share:++- **Zen's free models refuse a Browsentic run.** They answer only requests that carry OpenCode's+ own built-in tools. A Browsentic run carries only the browser's, so they refuse it with *free tier+ can only be used from within OpenCode*. Sign in to a provider first; until then the agent picker+ shows *needs setup*.- **Models are `provider/model`**, spelled as `opencode models` lists them.- **A key in the environment does not reach a run.** Only `OPENCODE_*` does; `ANTHROPIC_API_KEY`- and the like are sealed away. `opencode auth login` keeps the key in OpenCode's own file instead,- which a run reads as usual.+ and the like are sealed away. Sign in instead, which keeps the key in OpenCode's own store.- **Your OpenCode settings are read, and cannot widen a run.** Your providers, models and`~/.config/opencode/AGENTS.md` apply. The run uses an agent Browsentic defines, whose rules denyevery tool not named for it, so your permission rules, custom tools and the MCP servers you set up- in OpenCode itself are hidden from the model (those servers still start). External plugins and- project config are off for the run.+ in OpenCode itself are hidden from the model. Project config is off for the run.- **Sharing is off.** A `"share": "auto"` of your own would publish every browsing session to apublic link, so a run switches sharing off.-- **Run sessions are kept apart from yours.** Runs and one-shots go into a session store under- `~/.browsentic`, not into `opencode session list`.-- **Replies arrive a part at a time.** Like Vibe's, OpenCode's stream carries each finished part,- not tokens.+- **Replies arrive a part at a time**, not token by token.- **A tool result is cut at 100 KB**, not OpenCode's own 50 KB, which a whole-page snapshot canexceed. Past that, the prompt asks for smaller reads, because a run cannot open the saved copyOpenCode points to.-- **Effort is a variant.** `agents.opencode.effort` is passed as `--variant`, whose names each model- defines; a name the model lacks is ignored.- **The run is stopped if a local tool ran.** OpenCode reports every tool call, and one that ranoutside the browser ends the run with `AGENT_UNSAFE`.+**OpenCode 1:**++- **Sign in with `opencode auth login`.** A provider in your config, such as a local model, counts+ too.+- **Run sessions are kept apart from yours.** Runs and one-shots go into a session store under+ `~/.browsentic`, not into `opencode session list`. External plugins are off for the run, and the+ MCP servers you set up still start, with their tools hidden.+- **Effort is a variant.** `agents.opencode.effort` is passed as `--variant`, whose names each model+ defines; a name the model lacks is ignored.++**OpenCode 2:**++- **Browsentic has a sign-in of its own.** OpenCode 2 keeps sign-ins in the same database as its+ sessions, and Browsentic runs keep a database apart from yours, so your own sign-in does not carry+ over. The agent picker shows the one line to run, which signs that database in; on macOS and Linux+ it is `OPENCODE_DB="$HOME/.browsentic/agents/opencode/opencode-2.db" opencode auth login --standalone`.+ An `OPENCODE_API_KEY` in the environment, or a provider in your config, counts too.+- **Your sessions and your background service are never touched.** Every run starts its own private+ OpenCode server rather than the shared one, so a run is never added to your session list and your+ service never picks one up.+- **A turn waits for the browser tools.** OpenCode 2 connects MCP servers in the background, so a+ turn is held over its Agent Client Protocol (`opencode acp`) and the message goes once the browser's+ tools have reached it, which adds well under a second.+- **Your plugins and other MCP servers do not load.** A policy in the run's config keeps them off;+ one in your global or managed config outranks it.+- **Effort is set only where the model offers it.** OpenCode 2 refuses a run asking for an effort+ the model lacks, so `agents.opencode.effort` is applied when the model lists that level and+ otherwise left out.+- **Sessions do not carry over from OpenCode 1.** After switching lines, a conversation's next turn+ starts a fresh OpenCode session.+---## Per-agent settings@@ -343,7 +372,7 @@ Claude runner's settings.| Symptom | Fix || --- | --- || `AGENT_MISSING` | The Bridge's `PATH` differs from your shell's. Set `agents.<name>.bin` to an absolute path. |-| `AGENT_NEEDS_PERMISSION` | Antigravity has no rule for Browsentic's tools: press the button, or `browsentic agent fix antigravity`. Grok Build is not signed in: run `grok login`. Qwen Code has no model provider: run `qwen` and use `/auth`. OpenCode is signed in to no provider: run `opencode auth login`. |+| `AGENT_NEEDS_PERMISSION` | Antigravity has no rule for Browsentic's tools: press the button, or `browsentic agent fix antigravity`. Grok Build is not signed in: run `grok login`. Qwen Code has no model provider: run `qwen` and use `/auth`. OpenCode 1 is signed in to no provider: run `opencode auth login`. OpenCode 2 has no sign-in of its own for Browsentic: run the line the picker shows. || Codex: "not logged in" | The Bridge inherits no session. Run `codex login`, then retry. || Codex answers about the page without opening it, or from a web search | Update Browsentic. Codex hides the browser tools until the model searches for them, and an older Browsentic left Codex's own web search switched on, which the model reached for first. || Mistral Vibe: a follow-up turn says *this agent run is no longer active* | Update Browsentic, then start a new conversation. An older one gave each turn its own folder, and Vibe keeps re-reading the first turn's, so a conversation begun before the update stays broken. |@@ -359,11 +388,14 @@ Claude runner's settings.| Qwen Code: *No auth type is selected* | Qwen has no provider configured, and its OAuth free tier has ended. Run `qwen` and use `/auth`, or export `OPENAI_API_KEY` with `OPENAI_BASE_URL`. || Qwen Code cannot find a key you have exported | Only `QWEN_*`, `DASHSCOPE_*`, `BAILIAN_*` and `OPENAI_*` reach a run; `ANTHROPIC_*` and `GEMINI_*` are sealed away. Point Qwen at one of the first four. || `AGENT_UNSAFE`: *Qwen Code registered …* or *loaded the MCP server …* | Qwen's own `init` line named a tool or a server Browsentic denied, so the run was stopped. Update Qwen Code and Browsentic, and report it if it persists. |-| OpenCode: *free models refuse a run whose tools Browsentic has narrowed to the browser* | Zen's free tier serves only requests carrying OpenCode's own tools. Run `opencode auth login`, then pick that provider's model in the side panel's agent picker. |+| OpenCode: *free models refuse a run whose tools Browsentic has narrowed to the browser* | Zen's free tier serves only requests carrying OpenCode's own tools. Sign in to a provider (`opencode auth login` on OpenCode 1, the line in the message on OpenCode 2), then pick that provider's model in the side panel's agent picker. |+| OpenCode 2: *no model "…" here* | OpenCode 2 does not offer that model. Pick one of those the message lists, `provider/model`. |+| OpenCode 2: *could not start Browsentic's browser tools* | The run's browser tools did not reach OpenCode within 20 seconds. Run `browsentic restart`, then send the message again. |+| OpenCode: *changed version since Browsentic last checked it* | OpenCode 1 and 2 refuse each other's flags, which is what a swap while Browsentic runs looks like. Send the message again. || OpenCode: *could not start this turn* | Usually a model OpenCode does not know. Pick one as `opencode models` lists it, `provider/model`. || The model select says *built-in list*, with a reason | Browsentic could not read that CLI's own list, usually because it is signed out. Sign it in, then press *Recheck*. The shipped list works meanwhile. || A model shows *not listed* | You pinned it, and the CLI no longer lists it. It is still passed to the CLI; pick a listed one if runs start failing. |-| OpenCode cannot find a key you have exported | Only `OPENCODE_*` reaches a run. Run `opencode auth login` instead, which keeps the key in OpenCode's own file. |+| OpenCode cannot find a key you have exported | Only `OPENCODE_*` reaches a run. Sign in instead (`opencode auth login` on OpenCode 1, the picker's line on OpenCode 2), which keeps the key in OpenCode's own store. || `AGENT_UNSAFE`: *OpenCode ran its own … tool* | A tool outside the browser ran despite the run's rules, so the run was stopped. Update OpenCode and Browsentic, and report it. |---diff --git a/docs/guide/limits.md b/docs/guide/limits.mdindex 04eb8bb..b64154b 100644--- a/docs/guide/limits.md+++ b/docs/guide/limits.md@@ -67,7 +67,7 @@ contains it with whatever controls that CLI offers, and they are not equal:| Grok Build (beta) | A per-run tool list, approvals that refuse anything not granted up front, and a sandbox that keeps its writes in its own folder; MCP servers you set up in Grok itself still load || Cursor CLI (beta) | Per-run deny rules, where a deny beats every allow including your own; a kernel sandbox is asked for too, but it has no Windows backend and is not depended on || Qwen Code (beta) | `--safe-mode` drops every setting of your own (hooks, extensions, bundled skills, MCP servers, permission rules), and deny rules close the shell, the disk and the tools that reach either; because that mode also disables Qwen's own fail-closed tool allowlist, the run's startup line is read back and anything unexpected stops it |-| OpenCode (beta) | A per-run agent whose rules open on a deny for every tool, applied after your own rules, so the model is offered only the browser; external plugins and project config are off, and MCP servers you set up in OpenCode itself still start, with their tools hidden |+| OpenCode (beta) | A per-run agent whose rules open on a deny for every tool, applied after your own rules, so the model is offered only the browser; project config is off. On OpenCode 1 external plugins are off, and MCP servers you set up in OpenCode itself still start, with their tools hidden. On OpenCode 2 a policy keeps your plugins and other MCP servers from loading, though one in your global or managed config outranks it, and each run has a private server and database of its own |The environment is sealed for all of them: cloud keys, registry tokens and database URLs inheritedfrom your shell are removed before the spawn, keeping only what that agent needs to authenticate.@@ -86,7 +86,8 @@ end to end yet, so the agent picker, the docs and the release notes mark them *b- Qwen was written against its source, not a running binary (no provider was configured on themachine it was built on), and it needs a provider configured before it will answer at all;- OpenCode needs a provider signed in, because Zen's free models refuse a run narrowed to the- browser, and its replies arrive a part at a time;+ browser, and on OpenCode 2 that sign-in is one of Browsentic's own; its replies arrive a part at a+ time;- the other three agents are untouched: the hooks the five share are covered by the spawn anddrive tests.diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.mdindex 29e3242..ccf6e04 100644--- a/docs/guide/troubleshooting.md+++ b/docs/guide/troubleshooting.md@@ -86,9 +86,13 @@ Those three answer most questions. The Bridge's log is at `~/.browsentic/daemon.| Qwen Code fails with *No auth type is selected* | Qwen has no provider configured, and its OAuth free tier ended on 2026-04-15 | Run `qwen` and use `/auth`, or export `OPENAI_API_KEY` with `OPENAI_BASE_URL` || Qwen Code cannot see an API key you exported | Only `QWEN_*`, `DASHSCOPE_*`, `BAILIAN_*` and `OPENAI_*` reach a run; the rest are sealed away | Point Qwen at one of those four providers || `AGENT_UNSAFE`: *Qwen Code registered …* / *loaded the MCP server …* | Qwen's own startup line named a tool or a server Browsentic denied, so the run was stopped before the model saw it | Update Qwen Code and Browsentic, and report it if it persists |-| OpenCode fails with *free models refuse a run whose tools Browsentic has narrowed to the browser* | OpenCode Zen's free tier serves only requests carrying OpenCode's own built-in tools | Run `opencode auth login`, then pick that provider's model in the side panel's agent picker |+| OpenCode fails with *free models refuse a run whose tools Browsentic has narrowed to the browser* | OpenCode Zen's free tier serves only requests carrying OpenCode's own built-in tools | Sign in to a provider: `opencode auth login` on OpenCode 1, the line in the message on OpenCode 2. Then pick that provider's model in the side panel's agent picker |+| OpenCode 2 needs setup though you are signed in to OpenCode | Browsentic's runs keep an OpenCode database of their own, apart from yours, and OpenCode 2 keeps sign-ins in it | Run the line the agent picker shows, which signs that database in |+| OpenCode 2 fails with *no model "…" here* | OpenCode 2 does not offer that model to Browsentic's sign-in | Pick one of the models the message lists, `provider/model` |+| OpenCode 2 fails with *could not start Browsentic's browser tools* | The run's browser tools did not reach OpenCode within 20 seconds | Run `browsentic restart`, then send the message again |+| OpenCode fails with *changed version since Browsentic last checked it* | OpenCode 1 and 2 refuse each other's flags, which is what swapping one for the other while Browsentic runs looks like | Send the message again || OpenCode fails with *could not start this turn* | Usually a model OpenCode does not know | Pick a model exactly as `opencode models` lists it, `provider/model` |-| OpenCode cannot see an API key you exported | Only `OPENCODE_*` reaches a run; the rest are sealed away | Run `opencode auth login`, which keeps the key in OpenCode's own file |+| OpenCode cannot see an API key you exported | Only `OPENCODE_*` reaches a run; the rest are sealed away | Sign in instead (`opencode auth login` on OpenCode 1, the agent picker's line on OpenCode 2), which keeps the key in OpenCode's own store || `AGENT_UNSAFE`: *OpenCode ran its own … tool* | A tool outside the browser ran despite the run's rules, so the run was stopped | Update OpenCode and Browsentic, and report it |## Pages and tabsdiff --git a/docs/internals/agent-runs.md b/docs/internals/agent-runs.mdindex a8b81fe..ad352f2 100644--- a/docs/internals/agent-runs.md+++ b/docs/internals/agent-runs.md@@ -97,11 +97,11 @@ Each runner delivers the same five things, through whichever mechanism its CLI s| | Claude Code | Codex | Antigravity | Mistral Vibe | Grok Build | Cursor CLI | Qwen Code | OpenCode || --- | --- | --- | --- | --- | --- | --- | --- | --- |-| Run | `claude -p --output-format stream-json`, the message on stdin | `codex app-server`, held over stdin for the turn; `codex exec --json` when it is refused, when `agents.codex.transport` is `"exec"`, and for one-shots | `agy -p --output-format stream-json` | `vibe --prompt … --output streaming --trust --agent ask` | `grok -p --output-format streaming-json` | `cursor-agent -p --output-format stream-json --stream-partial-output` | `qwen -p --output-format stream-json --include-partial-messages` | `opencode run --format json --pure --agent browsentic-contained` |-| MCP server | `--mcp-config` + `--strict-mcp-config` | none: the tools go to `thread/start` as `dynamicTools`, and each of the user's servers is switched off in the thread's config. `exec`: `-c mcp_servers.browsentic.*` under `--ignore-user-config`, with `default_tools_approval_mode="approve"`, because headless Codex refuses any MCP call it would have prompted for | `.agents/mcp_config.json` in its cwd | `.vibe/config.toml` in a folder per conversation, every tool granted by name | `.grok/config.toml` in its cwd, loaded with `GROK_FOLDER_TRUST=0`, and approved with `--allow MCPTool(browsentic__*)` | `.cursor/mcp.json` in a folder per conversation, approved each turn with `cursor-agent mcp enable browsentic` (a set-up step the plan carries), allowed as `Mcp(browsentic:*)` with every other server denied by name and every plugin's as `Mcp(plugin-*:*)` | `--mcp-config` + `--allowed-mcp-server-names`, under `--safe-mode`, which drops the ones on disk | `mcp.browsentic` in `OPENCODE_CONFIG_CONTENT`, each tool allowed by name on the run's own agent |+| Run | `claude -p --output-format stream-json`, the message on stdin | `codex app-server`, held over stdin for the turn; `codex exec --json` when it is refused, when `agents.codex.transport` is `"exec"`, and for one-shots | `agy -p --output-format stream-json` | `vibe --prompt … --output streaming --trust --agent ask` | `grok -p --output-format streaming-json` | `cursor-agent -p --output-format stream-json --stream-partial-output` | `qwen -p --output-format stream-json --include-partial-messages` | `opencode run --format json --pure --agent browsentic-contained`; on OpenCode 2, `opencode acp` held over stdin for the turn, the message sent once the browser's tools have reached it (`opencode run --standalone` when it is refused, and for one-shots) |+| MCP server | `--mcp-config` + `--strict-mcp-config` | none: the tools go to `thread/start` as `dynamicTools`, and each of the user's servers is switched off in the thread's config. `exec`: `-c mcp_servers.browsentic.*` under `--ignore-user-config`, with `default_tools_approval_mode="approve"`, because headless Codex refuses any MCP call it would have prompted for | `.agents/mcp_config.json` in its cwd | `.vibe/config.toml` in a folder per conversation, every tool granted by name | `.grok/config.toml` in its cwd, loaded with `GROK_FOLDER_TRUST=0`, and approved with `--allow MCPTool(browsentic__*)` | `.cursor/mcp.json` in a folder per conversation, approved each turn with `cursor-agent mcp enable browsentic` (a set-up step the plan carries), allowed as `Mcp(browsentic:*)` with every other server denied by name and every plugin's as `Mcp(plugin-*:*)` | `--mcp-config` + `--allowed-mcp-server-names`, under `--safe-mode`, which drops the ones on disk | `mcp.browsentic` in `OPENCODE_CONFIG_CONTENT`, each tool allowed by name on the run's own agent; on OpenCode 2, `mcp.servers.browsentic` with `codemode: false` || System prompt | `--append-system-prompt-file`, a file per run, kept from the first turn ([below](#a-prompt-the-session-keeps)) | `developerInstructions` on `thread/start` (`-c developer_instructions` on `exec`), kept from the first turn | `AGENTS.md` in its cwd | `AGENTS.md` beside its config | `--rules` | `AGENTS.md` in its cwd, kept from the first turn | `--append-system-prompt` | a file in a folder per conversation, named in the config's `instructions` (never the config itself, which OpenCode expands `{file:…}` in) |-| Follow-up turns | `--resume <session>` | `thread/resume` (`exec resume <thread>`); either resumes a thread the other began | `--conversation <id>` | `--resume <session>`, re-read from the folder the session began in | `--session-id <uuid>` names it, `--resume <uuid>` continues it, in a folder named after it | `--resume <session>` | `--session-id <uuid>` names it, `--resume <uuid>` continues it | `--session <id>`, from a session store of Browsentic's own (`OPENCODE_DB`) |-| Kept off the machine by | `--allowedTools` + `--disallowedTools` | the user's MCP servers off (`--ignore-user-config` on `exec`), `-c sandbox_mode="read-only"`, `-c approval_policy="never"`, `-c features.shell_tool=false`, `-c features.view_image=false`, `-c features.multi_agent=false` | its own permission rules | `--enabled-tools`, which is an allowlist | `--tools`, `--permission-mode dontAsk`, `--deny`, `--sandbox workspace` | deny rules in `.cursor/cli.json`, plus `--sandbox enabled` | `--safe-mode`, `--exclude-tools`, `--approval-mode default` | an agent whose permission opens on `"*": "deny"`, `--pure`, `OPENCODE_DISABLE_PROJECT_CONFIG`, `OPENCODE_DISABLE_SHARE` |+| Follow-up turns | `--resume <session>` | `thread/resume` (`exec resume <thread>`); either resumes a thread the other began | `--conversation <id>` | `--resume <session>`, re-read from the folder the session began in | `--session-id <uuid>` names it, `--resume <uuid>` continues it, in a folder named after it | `--resume <session>` | `--session-id <uuid>` names it, `--resume <uuid>` continues it | `--session <id>`, from a session store of Browsentic's own (`OPENCODE_DB`); on OpenCode 2, `session/resume`, from a database of its own that also holds Browsentic's sign-in |+| Kept off the machine by | `--allowedTools` + `--disallowedTools` | the user's MCP servers off (`--ignore-user-config` on `exec`), `-c sandbox_mode="read-only"`, `-c approval_policy="never"`, `-c features.shell_tool=false`, `-c features.view_image=false`, `-c features.multi_agent=false` | its own permission rules | `--enabled-tools`, which is an allowlist | `--tools`, `--permission-mode dontAsk`, `--deny`, `--sandbox workspace` | deny rules in `.cursor/cli.json`, plus `--sandbox enabled` | `--safe-mode`, `--exclude-tools`, `--approval-mode default` | an agent whose permission opens on `"*": "deny"`, `--pure`, `OPENCODE_DISABLE_PROJECT_CONFIG`, `OPENCODE_DISABLE_SHARE`; on OpenCode 2, an agent whose `permissions` open on a deny for everything, a private server (`--standalone`, or `acp`'s own), `integration.use` policies denying `plugin:*` and `mcp:*`, and the session's agent checked before the message goes |**Three CLIs do not put the browser tools in the model's list, and the prompt tells each one so.**Cursor hands the model a tool's schema only through its own `GetMcpTools`, by pattern or by name, sodiff --git a/docs/internals/guardrails.md b/docs/internals/guardrails.mdindex c20f511..01e6956 100644--- a/docs/internals/guardrails.md+++ b/docs/internals/guardrails.md@@ -369,7 +369,7 @@ type LocalTools = 'allowlist' | 'sandbox' | 'host'| **Grok Build** | `allowlist` | A per-run built-in tool list, `--permission-mode dontAsk`, deny rules, and a kernel sandbox for writes. Reads are closed by the tool list and a `Read` deny rather than the sandbox, and MCP servers the user set up in Grok itself still load || **Qwen Code** | `allowlist` | `--allowed-tools mcp__browsentic` is what a run may call without being asked, and a headless turn refuses everything it would otherwise have prompted for. `--safe-mode` is what makes the rest hold: it drops the user's hooks, extensions, bundled skills, `settings.json` MCP servers, `.mcp.json` and permission rules, while keeping `--mcp-config`, an explicit per-invocation argument rather than ambient state. Its cost is that it also **silently ignores `--core-tools`**, the fail-closed allowlist over Qwen's twenty-one core tools, so the built-ins are closed with `--exclude-tools` deny rules instead. A deny list cannot be fail-closed, so the `init` line is read back: it names every tool and MCP server that actually registered, and the reader ends the run with `AGENT_UNSAFE` on anything Browsentic did not ask for, before the model has spoken || **Cursor CLI** | `allowlist` | Deny rules in a project `.cursor/cli.json`, where **a deny beats every allow**, including the user's own. Measured against 2026.09.18: a headless run asked to `echo` a marker got `permissionDenied`, twice, and gave up. `--sandbox enabled` is asked for as well but not depended on, and it has no Windows backend. This is the first runner whose containment lives in a file rather than in argv, which is why `vetPlan` checks file *content* and not only that the file was written. `--trust` is **required**, not forbidden: headless Cursor refuses to start in a folder nobody trusted, and the folder is one Browsentic created and wrote every file in; trusting it grants no tool permission of its own. The project's MCP server starts only once approved, keyed to its exact config, so each turn's plan carries one set-up step, `cursor-agent mcp enable browsentic`, run in its folder before the turn; `vetPlan` allows that step and no other, for a run and never a task, and `--approve-mcps`, which approves every server the user has, stays forbidden. Every plugin's MCP server loads in every run under `plugin-<plugin>-<server>`, so `Mcp(plugin-*:*)` is denied beside the user's own servers by name, and an answer from any server but `browsentic` ends the run with `AGENT_UNSAFE` |-| **OpenCode** | `allowlist` | The run is an agent the config defines, whose permission ruleset opens on `"*": "deny"` and then allows each browser tool by name. OpenCode applies the last rule that matches and puts an agent's rules after the user's, so every other tool (built-in, custom, another MCP server's, or one a later release adds) is denied, and a tool denied outright is never offered to the model. `--pure` keeps plugins out, which run inside OpenCode and can answer its permission prompts. MCP servers the user set up in OpenCode itself still start, with their tools hidden |+| **OpenCode** | `allowlist` | The run is an agent the config defines, whose permission ruleset opens on `"*": "deny"` and then allows each browser tool by name. OpenCode applies the last rule that matches and puts an agent's rules after the user's, so every other tool (built-in, custom, another MCP server's, or one a later release adds) is denied, and a tool denied outright is never offered to the model. `--pure` keeps plugins out, which run inside OpenCode and can answer its permission prompts. MCP servers the user set up in OpenCode itself still start, with their tools hidden. OpenCode 2 is held to a second rule set, below |**Windows is less measured.** Cursor's kernel sandbox has no Windows backend, so only its deny rulesapply there. Codex's `sandbox_mode="read-only"` and Grok's `--sandbox workspace` are asked for as on@@ -449,6 +449,43 @@ Three behaviours of OpenCode shaped the rest, each measured against 1.18.32:tools hidden from the model. And the user's own `~/.config/opencode/AGENTS.md` is read, as ClaudeCode reads the user's `CLAUDE.md`.+#### OpenCode 2: one of two ways of being contained++OpenCode 2 (`@opencode/cli`) installs the same `opencode` command as OpenCode 1 with other flags, config+and storage, so OpenCode has two rule sets in `CONTAINMENT`, and **a plan meets one of them in full**+or is held to the one it came closest to. Each line also refuses the other's flags at parsing (2.0.32:+*Unrecognized flag: --pure*; 1.19.3 prints its usage, and refuses 2.x's config with *V2 permissions are+not supported*), so a plan built for the wrong line never starts. What 2.x changed, measured against+2.0.32:++- **`opencode run` hands the turn to a shared background service** unless it is given+ `--standalone`, which starts a private server that inherits the run's environment and ends with it.+ Without it the run's config would be ignored, and a service not yet running would be started with+ the run's environment and keep it. Every 2.x plan carries `--standalone`, or is `opencode acp`, which+ always starts its own.+- **Its rules are a list where the last match wins**, so a later allow could sit beside the deny-all+ and a substring search would still find the deny. An `inspect` step parses `OPENCODE_CONFIG_CONTENT`+ instead: the agent's first rule denies everything; every later allow names a `browsentic_*` tool, a+ web tool, or (a one-shot) `read` on `tmp/*`; the browser's server is the only one, with+ `codemode: false`; `integration.use` policies end on denying `plugin:*` and `mcp:*`; a conversation+ starts in `browsentic-contained` (`default_agent`); sharing is off.+- **Code Mode is on by default**: an MCP server's tools are listed behind one `execute` tool, which runs+ a script with the network. The rules deny it, and the browser's server sets `codemode: false`.+- **`run` moves to `$PWD` before its own working directory**, so `envIsCwd` requires `PWD` to name the+ plan's folder. The project switch is `OPENCODE_CONFIG_PROJECT_DISABLE` (the old name is read only when+ the new one is unset, so both are set), and `OPENCODE_DISABLE_SHARE` is gone; `"share": "disabled"`+ remains.+- **Sign-ins and sessions share one database.** Runs keep their own (`opencode-2.db` under+ `~/.browsentic`), which the user signs in to once, so the user's background service never opens a+ run's session, which it would otherwise resume after a run killed mid-turn.+- **MCP servers connect in the background**, and each step's tools are fixed when it is sent, so a+ prompt sent at once reaches a model with no browser tools. A held `opencode acp` turn sends the+ message only once the daemon has answered the run's MCP server for its tool list, and checks that+ the session is in Browsentic's agent before it does.++**What remains on 2.x:** a policy in the user's global or managed config outranks the run's, so a user+who allows a plugin there gets it loaded; its tools are still denied by the agent's rules.+`localTools` records which case each runner is in, and the note is logged once per run, so the weakone is **visible in the log rather than assumed away**.@@ -458,7 +495,7 @@ one is **visible in the log rather than assumed away**.analyst reading an attached file, the captcha analyst looking at one round of a challenge, or turninga raw recording trace into steps. That is asserted by requiring `{"mcpServers":{}}` (or`mcp_servers={}`, or Grok's `--deny MCPTool`) in its argv, or OpenCode's `"mcp":{}` and `"*":"deny"`-in its config. `Read` is deliberately left out of `task`'s deny list, because some tasks are handed a+in its config (on OpenCode 2, no servers and a deny-all agent). `Read` is deliberately left out of `task`'s deny list, because some tasks are handed afile in the scratch workspace.The file analyst adds three things. A file is screened before anything spawns, so an archive, an@@ -466,7 +503,7 @@ executable or an oversized file never reaches an agent. The one-shot is stoppedis in rather than left to exit, and its copy of the file is deleted. And the session is not keptwhere the CLI allows that: Claude Code runs a task with `--no-session-persistence` and Codex with`--ephemeral`. OpenCode has no such switch, but its runs and tasks both go into a session store-under `~/.browsentic` (`OPENCODE_DB`) rather than the user's.+under `~/.browsentic` (`OPENCODE_DB`) rather than the user's, one per line of releases.Antigravity, Mistral Vibe, Grok Build, Cursor CLI and Qwen Code have neither, so a task's sessionstays in that CLI's own history, inside the per-mode task workspace it was started in.@@ -500,9 +537,11 @@ agent another vendor's key is what sealing exists to prevent, so `check()` repor`ANTHROPIC_API_KEY` set as *needs setup* rather than promising a login that cannot happen.OpenCode reads a dozen providers' keys from the environment, and keeping all of them would undo-sealing for it altogether. It keeps its own logins in a file instead (`opencode auth login` writes-it), so only `OPENCODE_` survives, and `check()` counts that file, a Zen key, or a provider declared-in its config as signed in.+sealing for it altogether. It keeps its own logins instead (`opencode auth login` writes them), so+only `OPENCODE_` survives. On OpenCode 1 `check()` counts its `auth.json`, a Zen key, or a provider+declared in its config as signed in. On OpenCode 2 it asks `opencode auth list --standalone` against+the runs' own database, in the environment a run gets, so a key counts exactly when a run would see+it; `--standalone` keeps the user's background service from being started with that environment.Sealing is not absolute for Qwen either. Qwen loads the first `.env` it finds walking up from itsworking directory, then `~/.qwen/.env` and `~/.env`, for variables not already present, so a keydiff --git a/docs/reference/errors.md b/docs/reference/errors.mdindex e14465e..c085881 100644--- a/docs/reference/errors.md+++ b/docs/reference/errors.md@@ -78,9 +78,9 @@ run, and the message carries the *fix*. In the **Origin** column, Daemon is Brow| Code | Origin | Meaning and next move || --- | --- | --- || `AGENT_MISSING` | Runner | The chosen agent's binary is not on the *daemon's* `PATH`. Set `agents.<name>.bin` to an absolute path |-| `AGENT_NEEDS_PERMISSION` | Runner | Antigravity has no rule allowing Browsentic's MCP tools (`browsentic agent fix antigravity`), Grok Build or Cursor CLI is not signed in (`grok login`, `cursor-agent login`), Qwen Code has no model provider configured (`qwen`, then `/auth`), or OpenCode is signed in to no provider (`opencode auth login`) |+| `AGENT_NEEDS_PERMISSION` | Runner | Antigravity has no rule allowing Browsentic's MCP tools (`browsentic agent fix antigravity`), Grok Build or Cursor CLI is not signed in (`grok login`, `cursor-agent login`), Qwen Code has no model provider configured (`qwen`, then `/auth`), or OpenCode 1 is signed in to no provider (`opencode auth login`), OpenCode 2 has no sign-in of Browsentic's own (the line the agent picker shows) || `AGENT_UNUSABLE` | Runner | The CLI is present but cannot run, usually because it is too old for the flags Browsentic passes. On Windows, also a batch file that is not an npm or pnpm shim: set `agents.<name>.bin` to the program it runs |-| `AGENT_UNSAFE` | Runner | The run was stopped before the agent could act on the machine: its plan had lost its containment, which is a bug in Browsentic, or the CLI itself said it had not applied it (Grok Build offering tools Browsentic never asks for, Qwen Code reporting a denied tool or a second MCP server as registered, OpenCode reporting that a tool outside the browser ran, Codex running a shell command or changing a file with both switched off, or Cursor CLI getting an answer from an MCP server the run denies). Update both, and report it |+| `AGENT_UNSAFE` | Runner | The run was stopped before the agent could act on the machine: its plan had lost its containment, which is a bug in Browsentic, or the CLI itself said it had not applied it (Grok Build offering tools Browsentic never asks for, Qwen Code reporting a denied tool or a second MCP server as registered, OpenCode reporting that a tool outside the browser ran or opening a session in an agent other than Browsentic's, Codex running a shell command or changing a file with both switched off, or Cursor CLI getting an answer from an MCP server the run denies). Update both, and report it |## Guardrailsdiff --git a/src/daemon/agent/runner.ts b/src/daemon/agent/runner.tsindex 5b827ac..4524e92 100644--- a/src/daemon/agent/runner.ts+++ b/src/daemon/agent/runner.ts@@ -6,7 +6,7 @@ import { RemoteBridge } from '../remote-bridge';import { toolHost, type ToolHost } from '../tool-host';import type { AgentConfig } from './config';import { runJson, runStream, type JsonOptions } from './runners/drive';-import { mcpServerFor, runnerFor } from './runners';+import { mcpServerFor, runnerFor, versionOf } from './runners';import { RunError, type RunOutcome } from './runners/types';export { RunError };@@ -24,6 +24,10 @@ export interface RunRequest {sessionId: string | null;/** The tools the run's MCP server will offer, by the names it lists them under. */mcpTools: string[];+ /** Settles once the run's MCP server has listed those tools to the CLI. */+ toolsListed: () => Promise<void>;+ /** The agent CLI's `--version` line, from the probe that found it ready. */+ version?: string;signal: AbortSignal;emit: (event: RunEvent) => void;}@@ -46,6 +50,8 @@ export async function runInstruction(request: RunRequest): Promise<RunOutcome> {mcp: mcpServerFor(request.runId, runner.limits),mcpTools: request.mcpTools,tools: tools.open,+ toolsListed: request.toolsListed,+ version: request.version,},request.signal,request.emit,@@ -75,14 +81,15 @@ function inProcessTools(runId: string, config: AgentConfig): { open: () => Promi}/** One-shot, no browser: summarize a file, name a conversation, read back a recording. */-export function runAgentJson(+export async function runAgentJson(prompt: string,config: AgentConfig,signal: AbortSignal,{ reads = false, image, ...options }: JsonOptions & { reads?: boolean; image?: string },): Promise<string> {const { runner, settings } = runnerFor(config);- return runJson(runner, { prompt, settings, reads, image, workspace: runner.workspace('task') }, signal, options);+ const version = await versionOf(runner.kind, settings.bin);+ return runJson(runner, { prompt, settings, version, reads, image, workspace: runner.workspace('task') }, signal, options);}/** Where a one-shot's scratch files go — inside the agent's own workspace, so it is allowed to read them. */diff --git a/src/daemon/agent/runners/fixtures/README.md b/src/daemon/agent/runners/fixtures/README.mdindex 4e61a95..a43af45 100644--- a/src/daemon/agent/runners/fixtures/README.md+++ b/src/daemon/agent/runners/fixtures/README.md@@ -10,7 +10,10 @@ What each agent CLI printed on stdout, one event per line, for the reader testscommands emptied. OpenCode's were recorded through the runner's own plan with the model providerreplaced by a local stand-in, so the model's words are scripted and its URL is 127.0.0.1 — all but`free-tier`, which the real Zen endpoint answered and which lost only its `cf-ray` and- `cf-placement` headers; paths became `/Users/you`. Codex's `web-search`, `shell` and `two-calls`+ `cf-placement` headers; paths became `/Users/you`. OpenCode 2.0.32's were recorded the same way,+ from `opencode run --standalone` and from `opencode acp`; the `acp-` ones keep only what the CLI+ printed, with its replies renumbered to the request ids the runner uses, and both `free-tier`+ recordings were answered by the real Zen endpoint. Codex's `web-search`, `shell` and `two-calls`and Claude Code's `mcp-failed` were recorded the same way, each saying so in its first line.- `<case>.hand-written.jsonl` was written from the reader code, for streams a contained run cannotproduce or a CLI that was not installed. Its first line says so.diff --git a/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-cancelled.jsonl b/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-cancelled.jsonlnew file mode 100644index 0000000..edbc015--- /dev/null+++ b/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-cancelled.jsonl@@ -0,0 +1,9 @@+# Printed by `opencode acp` 2.0.32 to a client speaking the runner's protocol, its request ids renumbered to the runner's own.+{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"resume":{}},"_meta":{"opencode/child-session-updates":true}},"authMethods":[{"description":"Run `opencode auth login` in the terminal","name":"Login with opencode","id":"opencode-login"}],"agentInfo":{"name":"OpenCode","version":"2.0.32"}}}+{"jsonrpc":"2.0","id":3,"result":{"sessionId":"ses_eb66d8899ffe4YnGsxL9MeYX0k","configOptions":[{"id":"model","name":"Model","category":"model","type":"select","currentValue":"mock/m1","options":[{"value":"mock/m1","name":"mock/Mock One"},{"value":"opencode/beam-free","name":"opencode/Beam Free"},{"value":"opencode/big-pickle","name":"opencode/Big Pickle"},{"value":"opencode/deepseek-v4.1-flash-free","name":"opencode/DeepSeek V4.1 Flash Free"},{"value":"opencode/glm-5.3-flash-free","name":"opencode/GLM-5.3-Flash Free"},{"value":"opencode/longcat-2.5-preview-free","name":"opencode/LongCat 2.5 Preview Free"},{"value":"opencode/mimo-v2.6-flash-free","name":"opencode/MiMo-V2.6-Flash Free"},{"value":"opencode/nemotron-3-ultra-free","name":"opencode/Nemotron 3 Ultra Free"},{"value":"opencode/nemotron-3.5-lightning-free","name":"opencode/Nemotron 3.5 Lightning Free"},{"value":"opencode/nemotron-3.5-super-vl-free","name":"opencode/Nemotron 3.5 Super VL Free"},{"value":"opencode/space-bunny-free","name":"opencode/Space Bunny Free"}]},{"id":"effort","name":"Effort","description":"Available effort levels for this model","category":"thought_level","type":"select","currentValue":"default","options":[{"value":"low","name":"Low"},{"value":"high","name":"High"},{"value":"default","name":"Default"}]},{"id":"mode","name":"Session Mode","category":"mode","type":"select","currentValue":"browsentic-contained","options":[{"value":"browsentic-contained","name":"browsentic-contained"},{"value":"build","name":"Build","description":"The default agent. Executes tools based on configured permissions."},{"value":"plan","name":"Plan","description":"Read-only agent for exploring the codebase and planning work before implementation."}]}]}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66d8899ffe4YnGsxL9MeYX0k","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"init","description":"guided AGENTS.md setup"},{"name":"review","description":"review changes [commit|branch|pr], defaults to uncommitted"},{"name":"compact","description":"Compact the session"}]}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66d8899ffe4YnGsxL9MeYX0k","update":{"sessionUpdate":"tool_call","toolCallId":"call_25_0","name":"browsentic_page_sleep","title":"browsentic_page_sleep","kind":"other","status":"pending","locations":[],"rawInput":{}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66d8899ffe4YnGsxL9MeYX0k","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_25_0","status":"in_progress","kind":"other","title":"browsentic_page_sleep","locations":[],"rawInput":{"seconds":30}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66d8899ffe4YnGsxL9MeYX0k","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_25_0","status":"failed","kind":"other","title":"browsentic_page_sleep","locations":[],"rawInput":{"seconds":30},"content":[{"type":"content","content":{"type":"text","text":"Tool execution interrupted"}}],"rawOutput":{"metadata":{},"error":"Tool execution interrupted"}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66d8899ffe4YnGsxL9MeYX0k","update":{"sessionUpdate":"usage_update","used":1230,"size":200000,"cost":{"amount":0,"currency":"USD"}}}}+{"jsonrpc":"2.0","id":6,"result":{"stopReason":"cancelled","usage":{"inputTokens":1200,"outputTokens":30,"totalTokens":1230},"_meta":{}}}diff --git a/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-free-tier.jsonl b/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-free-tier.jsonlnew file mode 100644index 0000000..04a6548--- /dev/null+++ b/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-free-tier.jsonl@@ -0,0 +1,5 @@+# Printed by `opencode acp` 2.0.32 to a client speaking the runner's protocol, its request ids renumbered to the runner's own.+{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"resume":{}},"_meta":{"opencode/child-session-updates":true}},"authMethods":[{"description":"Run `opencode auth login` in the terminal","name":"Login with opencode","id":"opencode-login"}],"agentInfo":{"name":"OpenCode","version":"2.0.32"}}}+{"jsonrpc":"2.0","id":3,"result":{"sessionId":"ses_eb66c8358ffea1P2YVfgTqXf8T","configOptions":[{"id":"model","name":"Model","category":"model","type":"select","currentValue":"opencode/big-pickle","options":[{"value":"mock/m1","name":"mock/Mock One"},{"value":"opencode/beam-free","name":"opencode/Beam Free"},{"value":"opencode/big-pickle","name":"opencode/Big Pickle"},{"value":"opencode/deepseek-v4.1-flash-free","name":"opencode/DeepSeek V4.1 Flash Free"},{"value":"opencode/glm-5.3-flash-free","name":"opencode/GLM-5.3-Flash Free"},{"value":"opencode/longcat-2.5-preview-free","name":"opencode/LongCat 2.5 Preview Free"},{"value":"opencode/mimo-v2.6-flash-free","name":"opencode/MiMo-V2.6-Flash Free"},{"value":"opencode/nemotron-3-ultra-free","name":"opencode/Nemotron 3 Ultra Free"},{"value":"opencode/nemotron-3.5-lightning-free","name":"opencode/Nemotron 3.5 Lightning Free"},{"value":"opencode/nemotron-3.5-super-vl-free","name":"opencode/Nemotron 3.5 Super VL Free"},{"value":"opencode/space-bunny-free","name":"opencode/Space Bunny Free"}]},{"id":"mode","name":"Session Mode","category":"mode","type":"select","currentValue":"browsentic-contained","options":[{"value":"browsentic-contained","name":"browsentic-contained"},{"value":"build","name":"Build","description":"The default agent. Executes tools based on configured permissions."},{"value":"plan","name":"Plan","description":"Read-only agent for exploring the codebase and planning work before implementation."}]}]}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66c8358ffea1P2YVfgTqXf8T","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"init","description":"guided AGENTS.md setup"},{"name":"review","description":"review changes [commit|branch|pr], defaults to uncommitted"},{"name":"compact","description":"Compact the session"}]}}}+{"jsonrpc":"2.0","id":6,"error":{"code":-32000,"message":"Authentication required: provider authentication required","data":{}}}diff --git a/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-refused-tool.jsonl b/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-refused-tool.jsonlnew file mode 100644index 0000000..556829f--- /dev/null+++ b/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-refused-tool.jsonl@@ -0,0 +1,10 @@+# Printed by `opencode acp` 2.0.32 to a client speaking the runner's protocol, its request ids renumbered to the runner's own.+{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"resume":{}},"_meta":{"opencode/child-session-updates":true}},"authMethods":[{"description":"Run `opencode auth login` in the terminal","name":"Login with opencode","id":"opencode-login"}],"agentInfo":{"name":"OpenCode","version":"2.0.32"}}}+{"jsonrpc":"2.0","id":3,"result":{"sessionId":"ses_eb66d50beffeuQA7eYDFVfYAvC","configOptions":[{"id":"model","name":"Model","category":"model","type":"select","currentValue":"mock/m1","options":[{"value":"mock/m1","name":"mock/Mock One"},{"value":"opencode/beam-free","name":"opencode/Beam Free"},{"value":"opencode/big-pickle","name":"opencode/Big Pickle"},{"value":"opencode/deepseek-v4.1-flash-free","name":"opencode/DeepSeek V4.1 Flash Free"},{"value":"opencode/glm-5.3-flash-free","name":"opencode/GLM-5.3-Flash Free"},{"value":"opencode/longcat-2.5-preview-free","name":"opencode/LongCat 2.5 Preview Free"},{"value":"opencode/mimo-v2.6-flash-free","name":"opencode/MiMo-V2.6-Flash Free"},{"value":"opencode/nemotron-3-ultra-free","name":"opencode/Nemotron 3 Ultra Free"},{"value":"opencode/nemotron-3.5-lightning-free","name":"opencode/Nemotron 3.5 Lightning Free"},{"value":"opencode/nemotron-3.5-super-vl-free","name":"opencode/Nemotron 3.5 Super VL Free"},{"value":"opencode/space-bunny-free","name":"opencode/Space Bunny Free"}]},{"id":"effort","name":"Effort","description":"Available effort levels for this model","category":"thought_level","type":"select","currentValue":"default","options":[{"value":"low","name":"Low"},{"value":"high","name":"High"},{"value":"default","name":"Default"}]},{"id":"mode","name":"Session Mode","category":"mode","type":"select","currentValue":"browsentic-contained","options":[{"value":"browsentic-contained","name":"browsentic-contained"},{"value":"build","name":"Build","description":"The default agent. Executes tools based on configured permissions."},{"value":"plan","name":"Plan","description":"Read-only agent for exploring the codebase and planning work before implementation."}]}]}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66d50beffeuQA7eYDFVfYAvC","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"init","description":"guided AGENTS.md setup"},{"name":"review","description":"review changes [commit|branch|pr], defaults to uncommitted"},{"name":"compact","description":"Compact the session"}]}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66d50beffeuQA7eYDFVfYAvC","update":{"sessionUpdate":"tool_call","toolCallId":"call_27_0","name":"shell","title":"shell","kind":"execute","status":"pending","locations":[{"path":"/Users/you/.browsentic/agents/opencode/run/conversation-1"}],"rawInput":{"cwd":"/Users/you/.browsentic/agents/opencode/run/conversation-1"}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66d50beffeuQA7eYDFVfYAvC","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_27_0","status":"in_progress","kind":"execute","title":"echo PWNED > /tmp/pwned-oc2","locations":[{"path":"/Users/you/.browsentic/agents/opencode/run/conversation-1"}],"rawInput":{"command":"echo PWNED > /tmp/pwned-oc2","cwd":"/Users/you/.browsentic/agents/opencode/run/conversation-1"}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66d50beffeuQA7eYDFVfYAvC","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_27_0","status":"failed","kind":"execute","title":"echo PWNED > /tmp/pwned-oc2","locations":[{"path":"/Users/you/.browsentic/agents/opencode/run/conversation-1"}],"rawInput":{"command":"echo PWNED > /tmp/pwned-oc2","cwd":"/Users/you/.browsentic/agents/opencode/run/conversation-1"},"content":[{"type":"content","content":{"type":"text","text":"No tool named \"shell\" is currently available. Please use a tool from the available tool list."}}],"rawOutput":{"metadata":{},"error":"No tool named \"shell\" is currently available. Please use a tool from the available tool list."}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66d50beffeuQA7eYDFVfYAvC","update":{"sessionUpdate":"agent_message_chunk","messageId":"msg_14992b1e0001xV5fqQ2i1CUcxz","content":{"type":"text","text":"ok"}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66d50beffeuQA7eYDFVfYAvC","update":{"sessionUpdate":"usage_update","used":1230,"size":200000,"cost":{"amount":0,"currency":"USD"}}}}+{"jsonrpc":"2.0","id":6,"result":{"stopReason":"end_turn","usage":{"inputTokens":2400,"outputTokens":60,"totalTokens":2460},"_meta":{}}}diff --git a/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-resume-missing.jsonl b/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-resume-missing.jsonlnew file mode 100644index 0000000..eb70fa1--- /dev/null+++ b/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-resume-missing.jsonl@@ -0,0 +1,4 @@+# Printed by `opencode acp` 2.0.32 to a client speaking the runner's protocol, its request ids renumbered to the runner's own.+{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"resume":{}},"_meta":{"opencode/child-session-updates":true}},"authMethods":[{"description":"Run `opencode auth login` in the terminal","name":"Login with opencode","id":"opencode-login"}],"agentInfo":{"name":"OpenCode","version":"2.0.32"}}}+{"jsonrpc":"2.0","id":2,"error":{"code":-32602,"message":"Invalid params: session not found: ses_0000000000000000000000000","data":{"sessionId":"ses_0000000000000000000000000"}}}+{"jsonrpc":"2.0","id":6,"error":{"code":-32602,"message":"Invalid params: session not found: ses_0000000000000000000000000","data":{"sessionId":"ses_0000000000000000000000000"}}}diff --git a/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-shell-ran.jsonl b/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-shell-ran.jsonlnew file mode 100644index 0000000..2beaae3--- /dev/null+++ b/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-shell-ran.jsonl@@ -0,0 +1,11 @@+# Printed by `opencode acp` 2.0.32 to a client speaking the runner's protocol, its request ids renumbered to the runner's own.+{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"resume":{}},"_meta":{"opencode/child-session-updates":true}},"authMethods":[{"description":"Run `opencode auth login` in the terminal","name":"Login with opencode","id":"opencode-login"}],"agentInfo":{"name":"OpenCode","version":"2.0.32"}}}+{"jsonrpc":"2.0","id":3,"result":{"sessionId":"ses_eb66cc1acffe44TrkD7NaXqtba","configOptions":[{"id":"model","name":"Model","category":"model","type":"select","currentValue":"mock/m1","options":[{"value":"mock/m1","name":"mock/Mock One"},{"value":"opencode/beam-free","name":"opencode/Beam Free"},{"value":"opencode/big-pickle","name":"opencode/Big Pickle"},{"value":"opencode/deepseek-v4.1-flash-free","name":"opencode/DeepSeek V4.1 Flash Free"},{"value":"opencode/glm-5.3-flash-free","name":"opencode/GLM-5.3-Flash Free"},{"value":"opencode/longcat-2.5-preview-free","name":"opencode/LongCat 2.5 Preview Free"},{"value":"opencode/mimo-v2.6-flash-free","name":"opencode/MiMo-V2.6-Flash Free"},{"value":"opencode/nemotron-3-ultra-free","name":"opencode/Nemotron 3 Ultra Free"},{"value":"opencode/nemotron-3.5-lightning-free","name":"opencode/Nemotron 3.5 Lightning Free"},{"value":"opencode/nemotron-3.5-super-vl-free","name":"opencode/Nemotron 3.5 Super VL Free"},{"value":"opencode/space-bunny-free","name":"opencode/Space Bunny Free"}]},{"id":"effort","name":"Effort","description":"Available effort levels for this model","category":"thought_level","type":"select","currentValue":"default","options":[{"value":"low","name":"Low"},{"value":"high","name":"High"},{"value":"default","name":"Default"}]},{"id":"mode","name":"Session Mode","category":"mode","type":"select","currentValue":"browsentic-contained","options":[{"value":"browsentic-contained","name":"browsentic-contained"},{"value":"build","name":"Build","description":"The default agent. Executes tools based on configured permissions."},{"value":"plan","name":"Plan","description":"Read-only agent for exploring the codebase and planning work before implementation."}]}]}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66cc1acffe44TrkD7NaXqtba","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"init","description":"guided AGENTS.md setup"},{"name":"review","description":"review changes [commit|branch|pr], defaults to uncommitted"},{"name":"compact","description":"Compact the session"}]}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66cc1acffe44TrkD7NaXqtba","update":{"sessionUpdate":"tool_call","toolCallId":"call_33_0","name":"shell","title":"shell","kind":"execute","status":"pending","locations":[{"path":"/Users/you/.browsentic/agents/opencode/run/conversation-1"}],"rawInput":{"cwd":"/Users/you/.browsentic/agents/opencode/run/conversation-1"}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66cc1acffe44TrkD7NaXqtba","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_33_0","status":"in_progress","kind":"execute","title":"echo ran > /tmp/oc2-ran","locations":[{"path":"/Users/you/.browsentic/agents/opencode/run/conversation-1"}],"rawInput":{"command":"echo ran > /tmp/oc2-ran","cwd":"/Users/you/.browsentic/agents/opencode/run/conversation-1"}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66cc1acffe44TrkD7NaXqtba","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_33_0","status":"in_progress","kind":"execute","title":"echo ran > /tmp/oc2-ran","locations":[{"path":"/Users/you/.browsentic/agents/opencode/run/conversation-1"}],"rawInput":{"command":"echo ran > /tmp/oc2-ran","cwd":"/Users/you/.browsentic/agents/opencode/run/conversation-1"}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66cc1acffe44TrkD7NaXqtba","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_33_0","status":"completed","locations":[{"path":"/Users/you/.browsentic/agents/opencode/run/conversation-1"}],"content":[{"type":"content","content":{"type":"text","text":"(no output)"}}],"rawOutput":{"metadata":{"status":"completed","truncated":false,"exit":0}}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66cc1acffe44TrkD7NaXqtba","update":{"sessionUpdate":"agent_message_chunk","messageId":"msg_149934102002JSO4gw6pDuNXcH","content":{"type":"text","text":"ok"}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66cc1acffe44TrkD7NaXqtba","update":{"sessionUpdate":"usage_update","used":1230,"size":200000,"cost":{"amount":0,"currency":"USD"}}}}+{"jsonrpc":"2.0","id":6,"result":{"stopReason":"end_turn","usage":{"inputTokens":2400,"outputTokens":60,"totalTokens":2460},"_meta":{}}}diff --git a/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-turn.jsonl b/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-turn.jsonlnew file mode 100644index 0000000..49509af--- /dev/null+++ b/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-turn.jsonl@@ -0,0 +1,10 @@+# Printed by `opencode acp` 2.0.32 to a client speaking the runner's protocol, its request ids renumbered to the runner's own.+{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"resume":{}},"_meta":{"opencode/child-session-updates":true}},"authMethods":[{"description":"Run `opencode auth login` in the terminal","name":"Login with opencode","id":"opencode-login"}],"agentInfo":{"name":"OpenCode","version":"2.0.32"}}}+{"jsonrpc":"2.0","id":3,"result":{"sessionId":"ses_eb66f4f81ffeKv3ZUQKMU5Z0Jv","configOptions":[{"id":"model","name":"Model","category":"model","type":"select","currentValue":"mock/m1","options":[{"value":"mock/m1","name":"mock/Mock One"},{"value":"opencode/beam-free","name":"opencode/Beam Free"},{"value":"opencode/big-pickle","name":"opencode/Big Pickle"},{"value":"opencode/deepseek-v4.1-flash-free","name":"opencode/DeepSeek V4.1 Flash Free"},{"value":"opencode/glm-5.3-flash-free","name":"opencode/GLM-5.3-Flash Free"},{"value":"opencode/longcat-2.5-preview-free","name":"opencode/LongCat 2.5 Preview Free"},{"value":"opencode/mimo-v2.6-flash-free","name":"opencode/MiMo-V2.6-Flash Free"},{"value":"opencode/nemotron-3-ultra-free","name":"opencode/Nemotron 3 Ultra Free"},{"value":"opencode/nemotron-3.5-lightning-free","name":"opencode/Nemotron 3.5 Lightning Free"},{"value":"opencode/nemotron-3.5-super-vl-free","name":"opencode/Nemotron 3.5 Super VL Free"},{"value":"opencode/space-bunny-free","name":"opencode/Space Bunny Free"}]},{"id":"effort","name":"Effort","description":"Available effort levels for this model","category":"thought_level","type":"select","currentValue":"default","options":[{"value":"low","name":"Low"},{"value":"high","name":"High"},{"value":"default","name":"Default"}]},{"id":"mode","name":"Session Mode","category":"mode","type":"select","currentValue":"browsentic-contained","options":[{"value":"browsentic-contained","name":"browsentic-contained"},{"value":"build","name":"Build","description":"The default agent. Executes tools based on configured permissions."},{"value":"plan","name":"Plan","description":"Read-only agent for exploring the codebase and planning work before implementation."}]}]}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66f4f81ffeKv3ZUQKMU5Z0Jv","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"init","description":"guided AGENTS.md setup"},{"name":"review","description":"review changes [commit|branch|pr], defaults to uncommitted"},{"name":"compact","description":"Compact the session"}]}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66f4f81ffeKv3ZUQKMU5Z0Jv","update":{"sessionUpdate":"tool_call","toolCallId":"call_8_0","name":"browsentic_page_getPageInfo","title":"browsentic_page_getPageInfo","kind":"other","status":"pending","locations":[],"rawInput":{}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66f4f81ffeKv3ZUQKMU5Z0Jv","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_8_0","status":"in_progress","kind":"other","title":"browsentic_page_getPageInfo","locations":[],"rawInput":{}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66f4f81ffeKv3ZUQKMU5Z0Jv","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_8_0","status":"completed","locations":[],"content":[{"type":"content","content":{"type":"text","text":"The page is Example Domain. run=a2"}}],"rawOutput":{"metadata":{"truncated":false}}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66f4f81ffeKv3ZUQKMU5Z0Jv","update":{"sessionUpdate":"agent_message_chunk","messageId":"msg_14990b1e1001V069vb27rxHxX8","content":{"type":"text","text":"The page is Example Domain."}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66f4f81ffeKv3ZUQKMU5Z0Jv","update":{"sessionUpdate":"usage_update","used":1230,"size":200000,"cost":{"amount":0,"currency":"USD"}}}}+{"jsonrpc":"2.0","id":6,"result":{"stopReason":"end_turn","usage":{"inputTokens":2400,"outputTokens":60,"totalTokens":2460},"_meta":{}}}diff --git a/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-web.jsonl b/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-web.jsonlnew file mode 100644index 0000000..8349a3d--- /dev/null+++ b/src/daemon/agent/runners/fixtures/opencode/2.0.32-acp-web.jsonl@@ -0,0 +1,10 @@+# Printed by `opencode acp` 2.0.32 to a client speaking the runner's protocol, its request ids renumbered to the runner's own.+{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":false},"promptCapabilities":{"embeddedContext":true,"image":true},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"resume":{}},"_meta":{"opencode/child-session-updates":true}},"authMethods":[{"description":"Run `opencode auth login` in the terminal","name":"Login with opencode","id":"opencode-login"}],"agentInfo":{"name":"OpenCode","version":"2.0.32"}}}+{"jsonrpc":"2.0","id":3,"result":{"sessionId":"ses_eb66cbd2cffegIpmsrNtES31xS","configOptions":[{"id":"model","name":"Model","category":"model","type":"select","currentValue":"mock/m1","options":[{"value":"mock/m1","name":"mock/Mock One"},{"value":"opencode/beam-free","name":"opencode/Beam Free"},{"value":"opencode/big-pickle","name":"opencode/Big Pickle"},{"value":"opencode/deepseek-v4.1-flash-free","name":"opencode/DeepSeek V4.1 Flash Free"},{"value":"opencode/glm-5.3-flash-free","name":"opencode/GLM-5.3-Flash Free"},{"value":"opencode/longcat-2.5-preview-free","name":"opencode/LongCat 2.5 Preview Free"},{"value":"opencode/mimo-v2.6-flash-free","name":"opencode/MiMo-V2.6-Flash Free"},{"value":"opencode/nemotron-3-ultra-free","name":"opencode/Nemotron 3 Ultra Free"},{"value":"opencode/nemotron-3.5-lightning-free","name":"opencode/Nemotron 3.5 Lightning Free"},{"value":"opencode/nemotron-3.5-super-vl-free","name":"opencode/Nemotron 3.5 Super VL Free"},{"value":"opencode/space-bunny-free","name":"opencode/Space Bunny Free"}]},{"id":"effort","name":"Effort","description":"Available effort levels for this model","category":"thought_level","type":"select","currentValue":"default","options":[{"value":"low","name":"Low"},{"value":"high","name":"High"},{"value":"default","name":"Default"}]},{"id":"mode","name":"Session Mode","category":"mode","type":"select","currentValue":"browsentic-contained","options":[{"value":"browsentic-contained","name":"browsentic-contained"},{"value":"build","name":"Build","description":"The default agent. Executes tools based on configured permissions."},{"value":"plan","name":"Plan","description":"Read-only agent for exploring the codebase and planning work before implementation."}]}]}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66cbd2cffegIpmsrNtES31xS","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"init","description":"guided AGENTS.md setup"},{"name":"review","description":"review changes [commit|branch|pr], defaults to uncommitted"},{"name":"compact","description":"Compact the session"}]}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66cbd2cffegIpmsrNtES31xS","update":{"sessionUpdate":"tool_call","toolCallId":"call_35_0","name":"webfetch","title":"webfetch","kind":"fetch","status":"pending","locations":[],"rawInput":{}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66cbd2cffegIpmsrNtES31xS","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_35_0","status":"in_progress","kind":"fetch","title":"webfetch","locations":[],"rawInput":{"url":"http://127.0.0.1:47311/v1/models","format":"text"}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66cbd2cffegIpmsrNtES31xS","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_35_0","status":"completed","locations":[],"content":[{"type":"content","content":{"type":"text","text":"{\"object\":\"list\",\"data\":[{\"id\":\"m1\",\"object\":\"model\"}]}"}}],"rawOutput":{"metadata":{"contentType":"application/json","truncated":false}}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66cbd2cffegIpmsrNtES31xS","update":{"sessionUpdate":"agent_message_chunk","messageId":"msg_149934580001mOR7jYJzfPutYh","content":{"type":"text","text":"fetched"}}}}+{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_eb66cbd2cffegIpmsrNtES31xS","update":{"sessionUpdate":"usage_update","used":1230,"size":200000,"cost":{"amount":0,"currency":"USD"}}}}+{"jsonrpc":"2.0","id":6,"result":{"stopReason":"end_turn","usage":{"inputTokens":2400,"outputTokens":60,"totalTokens":2460},"_meta":{}}}diff --git a/src/daemon/agent/runners/fixtures/opencode/2.0.32-auth-error.jsonl b/src/daemon/agent/runners/fixtures/opencode/2.0.32-auth-error.jsonlnew file mode 100644index 0000000..e5f0649--- /dev/null+++ b/src/daemon/agent/runners/fixtures/opencode/2.0.32-auth-error.jsonl@@ -0,0 +1,2 @@+{"type":"step_start","timestamp":1792236626003,"sessionID":"ses_eb65f6048ffeEBcJWXYi1KZz7m","part":{"id":"prt_149a0a053001Day3ABxW9VimNK","sessionID":"ses_eb65f6048ffeEBcJWXYi1KZz7m","messageID":"msg_149a0a046001k8QZ22wBFsQFXg","type":"step-start"}}+{"type":"error","timestamp":1792236626004,"sessionID":"ses_eb65f6048ffeEBcJWXYi1KZz7m","error":{"type":"provider.auth","message":"Invalid API key provided","status":401,"response":{"body":"{\"error\":{\"message\":\"Invalid API key provided\",\"type\":\"invalid_request_error\"}}"}}}diff --git a/src/daemon/agent/runners/fixtures/opencode/2.0.32-free-tier.jsonl b/src/daemon/agent/runners/fixtures/opencode/2.0.32-free-tier.jsonlnew file mode 100644index 0000000..ea58889--- /dev/null+++ b/src/daemon/agent/runners/fixtures/opencode/2.0.32-free-tier.jsonl@@ -0,0 +1 @@+{"type":"error","timestamp":1792236627562,"sessionID":"ses_eb65f5b53ffeVzWpc3WsmDAAY0","error":{"type":"provider.auth","message":"OpenCode's free tier can only be used from within OpenCode. Download it at https://opencode.ai and keep building.","status":403,"response":{"body":"{\"type\":\"error\",\"error\":{\"type\":\"FreeTierError\",\"message\":\"OpenCode's free tier can only be used from within OpenCode. Download it at https://opencode.ai and keep building.\"}}"}}}diff --git a/src/daemon/agent/runners/fixtures/opencode/2.0.32-resumed.jsonl b/src/daemon/agent/runners/fixtures/opencode/2.0.32-resumed.jsonlnew file mode 100644index 0000000..e720cea--- /dev/null+++ b/src/daemon/agent/runners/fixtures/opencode/2.0.32-resumed.jsonl@@ -0,0 +1,2 @@+{"type":"step_start","timestamp":1792236624669,"sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","part":{"id":"prt_149a09b1d001qiOgtteVdQzYQ4","sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","messageID":"msg_149a09b0f0011CxTK0bdUwyoJN","type":"step-start"}}+{"type":"text","timestamp":1792236624676,"sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","part":{"id":"prt_149a09b0f0011CxTK0bdUwyoJN_text-0","sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","messageID":"msg_149a09b0f0011CxTK0bdUwyoJN","type":"text","text":"Still Example Domain.","time":{"start":1792236624658,"end":1792236624676}}}diff --git a/src/daemon/agent/runners/fixtures/opencode/2.0.32-shell-ran.jsonl b/src/daemon/agent/runners/fixtures/opencode/2.0.32-shell-ran.jsonlnew file mode 100644index 0000000..0233086--- /dev/null+++ b/src/daemon/agent/runners/fixtures/opencode/2.0.32-shell-ran.jsonl@@ -0,0 +1,5 @@+{"type":"step_start","timestamp":1792236625539,"sessionID":"ses_eb65f6216ffevIdD9JDA0OKCxm","part":{"id":"prt_149a09e83001m9FNYkfrHbpM0B","sessionID":"ses_eb65f6216ffevIdD9JDA0OKCxm","messageID":"msg_149a09e74001Bj8F2eUJaA04rg","type":"step-start"}}+{"type":"tool_use","timestamp":1792236625565,"sessionID":"ses_eb65f6216ffevIdD9JDA0OKCxm","part":{"partID":"prt_149a09e84001nuv7NO8T6UOOqX","sessionID":"ses_eb65f6216ffevIdD9JDA0OKCxm","messageID":"msg_149a09e74001Bj8F2eUJaA04rg","type":"tool","id":"call_71_0","tool":"shell","state":{"status":"completed","input":{"command":"echo ran"},"output":"ran\n","title":"shell","metadata":{"metadata":{"status":"completed","truncated":false,"exit":0},"content":[{"type":"text","text":"ran\n"}],"providerCall":{"executed":false},"providerResult":{"executed":false},"rawInput":"{\"command\":\"echo ran\"}"},"time":{"start":1792236625540,"end":1792236625565}}}}+{"type":"step_finish","timestamp":1792236625566,"sessionID":"ses_eb65f6216ffevIdD9JDA0OKCxm","part":{"id":"prt_149a09e9e0015QRI7vu5AYsBpz","sessionID":"ses_eb65f6216ffevIdD9JDA0OKCxm","messageID":"msg_149a09e74001Bj8F2eUJaA04rg","type":"step-finish","reason":"tool-calls","cost":0,"tokens":{"input":1200,"output":30,"reasoning":0,"cache":{"read":0,"write":0}}}}+{"type":"step_start","timestamp":1792236625575,"sessionID":"ses_eb65f6216ffevIdD9JDA0OKCxm","part":{"id":"prt_149a09ea7001x4iRS6ovTjJtZG","sessionID":"ses_eb65f6216ffevIdD9JDA0OKCxm","messageID":"msg_149a09ea1001DFD6A15VN8BSjy","type":"step-start"}}+{"type":"text","timestamp":1792236625593,"sessionID":"ses_eb65f6216ffevIdD9JDA0OKCxm","part":{"id":"prt_149a09ea1001DFD6A15VN8BSjy_text-0","sessionID":"ses_eb65f6216ffevIdD9JDA0OKCxm","messageID":"msg_149a09ea1001DFD6A15VN8BSjy","type":"text","text":"ok","time":{"start":1792236625572,"end":1792236625593}}}diff --git a/src/daemon/agent/runners/fixtures/opencode/2.0.32-text-suffix.hand-written.jsonl b/src/daemon/agent/runners/fixtures/opencode/2.0.32-text-suffix.hand-written.jsonlnew file mode 100644index 0000000..c0bf3a6--- /dev/null+++ b/src/daemon/agent/runners/fixtures/opencode/2.0.32-text-suffix.hand-written.jsonl@@ -0,0 +1,6 @@+# Written from OpenCode 2.0.32's run/noninteractive.ts: a text block printed when it ended, then the reconcile pass+# sending the part of it the server had not printed yet, under the block's number, before a second block of its own.+{"type":"step_start","timestamp":1792235333924,"sessionID":"ses_eb6731d5effeUY30mRea760dHx","part":{"id":"prt_1498ce924001bOBF5r3EVFsXsL","sessionID":"ses_eb6731d5effeUY30mRea760dHx","messageID":"msg_1498ce95f0012chcB9TYehfVSO","type":"step-start"}}+{"type":"text","timestamp":1792235334004,"sessionID":"ses_eb6731d5effeUY30mRea760dHx","part":{"id":"prt_1498ce966001syNZNzhOevipLx","sessionID":"ses_eb6731d5effeUY30mRea760dHx","messageID":"msg_1498ce95f0012chcB9TYehfVSO","type":"text","text":"The page is Exam","time":{"start":1792235333987,"end":1792235334004}}}+{"type":"text","timestamp":1792235334010,"sessionID":"ses_eb6731d5effeUY30mRea760dHx","part":{"id":"prt_1498ce95f0012chcB9TYehfVSO_text-0","sessionID":"ses_eb6731d5effeUY30mRea760dHx","messageID":"msg_1498ce95f0012chcB9TYehfVSO","type":"text","text":"ple Domain.","time":{"start":1792235333987,"end":1792235334010}}}+{"type":"text","timestamp":1792235334011,"sessionID":"ses_eb6731d5effeUY30mRea760dHx","part":{"id":"prt_1498ce95f0012chcB9TYehfVSO_text-1","sessionID":"ses_eb6731d5effeUY30mRea760dHx","messageID":"msg_1498ce95f0012chcB9TYehfVSO","type":"text","text":"It has one link.","time":{"start":1792235333987,"end":1792235334011}}}diff --git a/src/daemon/agent/runners/fixtures/opencode/2.0.32-turn.jsonl b/src/daemon/agent/runners/fixtures/opencode/2.0.32-turn.jsonlnew file mode 100644index 0000000..b993499--- /dev/null+++ b/src/daemon/agent/runners/fixtures/opencode/2.0.32-turn.jsonl@@ -0,0 +1,8 @@+{"type":"step_start","timestamp":1792236624162,"sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","part":{"id":"prt_149a099220016pojBSegVVUxRY","sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","messageID":"msg_149a09911001oFzEdQRTAatTNs","type":"step-start"}}+{"type":"tool_use","timestamp":1792236624169,"sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","part":{"partID":"prt_149a09923001owa8bh4k0xx6K0","sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","messageID":"msg_149a09911001oFzEdQRTAatTNs","type":"tool","id":"call_64_0","tool":"browsentic_page_getPageInfo","state":{"status":"error","input":{},"error":"No tool named \"browsentic_page_getPageInfo\" is currently available. Please use a tool from the available tool list.","metadata":{"providerCall":{"executed":false},"providerResult":{"executed":false},"rawInput":"{}"},"time":{"start":1792236624163,"end":1792236624169}}}}+{"type":"step_finish","timestamp":1792236624170,"sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","part":{"id":"prt_149a0992a001nlWOnPWTfJfSae","sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","messageID":"msg_149a09911001oFzEdQRTAatTNs","type":"step-finish","reason":"tool-calls","cost":0,"tokens":{"input":1200,"output":30,"reasoning":0,"cache":{"read":0,"write":0}}}}+{"type":"step_start","timestamp":1792236624179,"sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","part":{"id":"prt_149a09933001lTBXVB3CkKfx6k","sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","messageID":"msg_149a0992d001Xoq4jE7tpp0Zst","type":"step-start"}}+{"type":"tool_use","timestamp":1792236624194,"sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","part":{"partID":"prt_149a099340010SULFHnIqCiuJ4","sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","messageID":"msg_149a0992d001Xoq4jE7tpp0Zst","type":"tool","id":"call_65_0","tool":"browsentic_page_getPageInfo","state":{"status":"error","input":{},"error":"No tool named \"browsentic_page_getPageInfo\" is currently available. Please use a tool from the available tool list.","metadata":{"providerCall":{"executed":false},"providerResult":{"executed":false},"rawInput":"{}"},"time":{"start":1792236624180,"end":1792236624194}}}}+{"type":"step_finish","timestamp":1792236624194,"sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","part":{"id":"prt_149a0994200204sIDlzRYko2UW","sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","messageID":"msg_149a0992d001Xoq4jE7tpp0Zst","type":"step-finish","reason":"tool-calls","cost":0,"tokens":{"input":1200,"output":30,"reasoning":0,"cache":{"read":0,"write":0}}}}+{"type":"step_start","timestamp":1792236624204,"sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","part":{"id":"prt_149a0994c0019kWtSqITEsQDJ4","sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","messageID":"msg_149a09944001xpl7xA8NlQYxMV","type":"step-start"}}+{"type":"text","timestamp":1792236624220,"sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","part":{"id":"prt_149a09944001xpl7xA8NlQYxMV_text-0","sessionID":"ses_eb65f6781ffezd6RAcEQYaQRJC","messageID":"msg_149a09944001xpl7xA8NlQYxMV","type":"text","text":"The page is Example Domain.","time":{"start":1792236624199,"end":1792236624220}}}diff --git a/src/daemon/agent/runners/fixtures/opencode/2.0.32-unknown-model.jsonl b/src/daemon/agent/runners/fixtures/opencode/2.0.32-unknown-model.jsonlnew file mode 100644index 0000000..720c97b--- /dev/null+++ b/src/daemon/agent/runners/fixtures/opencode/2.0.32-unknown-model.jsonl@@ -0,0 +1 @@+{"type":"error","timestamp":1792236626408,"sessionID":"ses_eb65f5ea0ffe90TeacFut3SDFQ","error":{"type":"provider.no-route","message":"Model unavailable: mock/zzz"}}diff --git a/src/daemon/agent/runners/fixtures/opencode/2.0.32-unknown-variant.jsonl b/src/daemon/agent/runners/fixtures/opencode/2.0.32-unknown-variant.jsonlnew file mode 100644index 0000000..06d620e--- /dev/null+++ b/src/daemon/agent/runners/fixtures/opencode/2.0.32-unknown-variant.jsonl@@ -0,0 +1 @@+{"type":"error","timestamp":1792236626831,"sessionID":"ses_eb65f5cfdfferjtVdyVO1Kvc48","error":{"type":"provider.no-route","message":"Variant unavailable for mock/m1: ludicrous"}}diff --git a/src/daemon/agent/runners/fixtures/opencode/2.0.32-web.jsonl b/src/daemon/agent/runners/fixtures/opencode/2.0.32-web.jsonlnew file mode 100644index 0000000..6e3ba25--- /dev/null+++ b/src/daemon/agent/runners/fixtures/opencode/2.0.32-web.jsonl@@ -0,0 +1,5 @@+{"type":"step_start","timestamp":1792236625093,"sessionID":"ses_eb65f63d4ffeQOecQz9KH1awbO","part":{"id":"prt_149a09cc5001fektVB5S6fZz7u","sessionID":"ses_eb65f63d4ffeQOecQz9KH1awbO","messageID":"msg_149a09cb6001peUC4hzEvy6CID","type":"step-start"}}+{"type":"tool_use","timestamp":1792236625103,"sessionID":"ses_eb65f63d4ffeQOecQz9KH1awbO","part":{"partID":"prt_149a09cc600147siaCEb765p6t","sessionID":"ses_eb65f63d4ffeQOecQz9KH1awbO","messageID":"msg_149a09cb6001peUC4hzEvy6CID","type":"tool","id":"call_68_0","tool":"webfetch","state":{"status":"completed","input":{"url":"http://127.0.0.1:47311/v1/models","format":"text"},"output":"{\"object\":\"list\",\"data\":[{\"id\":\"m1\",\"object\":\"model\"}]}","title":"webfetch","metadata":{"metadata":{"contentType":"application/json","truncated":false},"content":[{"type":"text","text":"{\"object\":\"list\",\"data\":[{\"id\":\"m1\",\"object\":\"model\"}]}"}],"providerCall":{"executed":false},"providerResult":{"executed":false},"rawInput":"{\"url\":\"http://127.0.0.1:47311/v1/models\",\"format\":\"text\"}"},"time":{"start":1792236625094,"end":1792236625103}}}}+{"type":"step_finish","timestamp":1792236625103,"sessionID":"ses_eb65f63d4ffeQOecQz9KH1awbO","part":{"id":"prt_149a09ccf002oDYP9ozidAOrkg","sessionID":"ses_eb65f63d4ffeQOecQz9KH1awbO","messageID":"msg_149a09cb6001peUC4hzEvy6CID","type":"step-finish","reason":"tool-calls","cost":0,"tokens":{"input":1200,"output":30,"reasoning":0,"cache":{"read":0,"write":0}}}}+{"type":"step_start","timestamp":1792236625113,"sessionID":"ses_eb65f63d4ffeQOecQz9KH1awbO","part":{"id":"prt_149a09cd9001Yc894NMU7fuKHP","sessionID":"ses_eb65f63d4ffeQOecQz9KH1awbO","messageID":"msg_149a09cd2001ro1t6tOUHlwU3w","type":"step-start"}}+{"type":"text","timestamp":1792236625127,"sessionID":"ses_eb65f63d4ffeQOecQz9KH1awbO","part":{"id":"prt_149a09cd2001ro1t6tOUHlwU3w_text-0","sessionID":"ses_eb65f63d4ffeQOecQz9KH1awbO","messageID":"msg_149a09cd2001ro1t6tOUHlwU3w","type":"text","text":"Fetched.","time":{"start":1792236625110,"end":1792236625127}}}diff --git a/src/daemon/agent/runners/fixtures/support.ts b/src/daemon/agent/runners/fixtures/support.tsindex 7fffa78..4470561 100644--- a/src/daemon/agent/runners/fixtures/support.ts+++ b/src/daemon/agent/runners/fixtures/support.ts@@ -86,6 +86,7 @@ export const streamContext = (settings: AgentSettings, overrides: Partial<Streammcp,mcpTools: ['page_getPageInfo', 'page_clickElement', 'browsentic_status'],tools: () => Promise.reject(new Error('no browser tools in a runner test')),+ toolsListed: () => Promise.resolve(),...overrides,});diff --git a/src/daemon/agent/runners/index.test.ts b/src/daemon/agent/runners/index.test.tsindex cce3f33..8a1883e 100644--- a/src/daemon/agent/runners/index.test.ts+++ b/src/daemon/agent/runners/index.test.ts@@ -7,7 +7,7 @@ import { stateDir } from '../../lockfile';import type { AgentConfig, AgentSettings } from '../config';import { MCP_RULE, settingsPath } from './antigravity';import { stubCli } from './fixtures/support';-import { agentState, grantRunner, mcpServerFor, refreshModelLists, RUNNERS, runnerFor } from './index';+import { agentState, grantRunner, mcpServerFor, refreshModelLists, RUNNERS, runnerFor, versionOf } from './index';const bin = join(stateDir, 'stub-bin');const probes = join(stateDir, 'probes.log');@@ -83,6 +83,7 @@ describe('readiness probes', () => {beforeAll(() => {mkdirSync(bin, { recursive: true });for (const name of ['claude', 'claude-next', 'codex', 'agy', 'vibe', 'grok', 'cursor-agent', 'qwen', 'opencode']) stub(name);+ stub('opencode2', { prints: 'opencode v2.0.32' });stub('codex-expired', { prints: 'licence expired', exit: 3 });});@@ -154,6 +155,23 @@ describe('readiness probes', () => {expect([withLogin?.ready, (await runner('grok', configWith({})))?.ready]).toEqual([true, true]);});+ // Its sign-ins moved into a database of Browsentic's own, which only a 2.x check knows to look in.+ test('the version an agent printed is the one its readiness is checked for', async () => {+ vi.stubEnv('OPENCODE_API_KEY', '');+ rmSync(join(stateDir, 'agents', 'opencode'), { recursive: true, force: true });+ const status = await runner('opencode', configWith({ opencode: { bin: join(bin, 'opencode2') } }));+ expect(status).toMatchObject({ version: 'opencode v2.0.32', ready: false, problem: { fix: expect.stringContaining('auth login --standalone') } });+ });++ test('a one-shot is built for the version last probed, and a binary never probed is probed once', async () => {+ await agentState(configWith({ opencode: { bin: join(bin, 'opencode2') } }), { refresh: true });+ expect(await versionOf('opencode', join(bin, 'opencode2'))).toBe('opencode v2.0.32');+ rmSync(probes, { force: true });+ expect(await versionOf('opencode', join(bin, 'opencode'))).toBe('opencode 1.0.0');+ expect(await versionOf('opencode', join(bin, 'opencode'))).toBe('opencode 1.0.0');+ expect(readFileSync(probes, 'utf8')).toBe('opencode\n');+ });+test('probes are reused for half a minute, even when only the active agent changed', async () => {await agentState(configWith({}), { refresh: true });const again = await agentState(configWith({}, 'antigravity'));diff --git a/src/daemon/agent/runners/index.ts b/src/daemon/agent/runners/index.tsindex f2d4eb3..6eebb11 100644--- a/src/daemon/agent/runners/index.ts+++ b/src/daemon/agent/runners/index.ts@@ -68,6 +68,19 @@ const PROBE_TTL_MS = 30_000;let cached: { at: number; signature: string; state: AgentState } | null = null;+/** Each agent's `--version` line as last probed, which outlives the cache a refresh or a grant clears. */+const probed = new Map<AgentKind, { bin: string; version?: string }>();++/** The version a plan is built for: the one last probed for this bin, or a fresh probe when there is none. */+export async function versionOf(kind: AgentKind, bin: string): Promise<string | undefined> {+ const known = probed.get(kind);+ if (known?.bin === bin) return known.version;+ const found = await version(bin, RUNNERS[kind].versionArgs);+ if (!found.ok) return undefined;+ probed.set(kind, { bin, version: found.detail });+ return found.detail;+}+export async function agentState(config: AgentConfig, { refresh = false } = {}): Promise<AgentState> {const signature = JSON.stringify(config.agents);if (!refresh && cached && cached.signature === signature && Date.now() - cached.at < PROBE_TTL_MS) {@@ -154,7 +167,8 @@ async function probe(runner: Runner, settings: AgentSettings): Promise<RunnerSta};}- const problem = (await runner.check?.(settings)) ?? null;+ probed.set(runner.kind, { bin: settings.bin, version: found.detail });+ const problem = (await runner.check?.(settings, found.detail)) ?? null;return {kind: runner.kind,bin: settings.bin,diff --git a/src/daemon/agent/runners/opencode-acp.test.ts b/src/daemon/agent/runners/opencode-acp.test.tsnew file mode 100644index 0000000..ed24d3b--- /dev/null+++ b/src/daemon/agent/runners/opencode-acp.test.ts@@ -0,0 +1,219 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { opencodeRunner } from './opencode';+import { streamContext, transcript, type Call } from './fixtures/support';+import type { Conversation, StreamContext, StreamSink } from './types';++const V2 = 'opencode v2.0.32';+const SESSION = 'ses_eb66f4f81ffeKv3ZUQKMU5Z0Jv';++interface Written {+ id?: number;+ method?: string;+ params?: Record<string, unknown>;+ result?: unknown;+ error?: { code: number };+}++const frames = (name: string) => transcript('opencode', `2.0.32-acp-${name}.jsonl`);+const answerTo = (name: string, id: number) => frames(name).find((line) => (JSON.parse(line) as Written).id === id) as string;+const notices = (name: string) => frames(name).filter((line) => (JSON.parse(line) as Written).method === 'session/update');++/** The session the `turn` recording opened, as a different `mode` or model would have it. */+function opened(change: (options: { id: string; currentValue: string; options: { value: string }[] }[]) => void, sessionId = SESSION): string {+ const message = JSON.parse(answerTo('turn', 3)) as { result: { sessionId: string; configOptions: Parameters<typeof change>[0] } };+ change(message.result.configOptions);+ message.result.sessionId = sessionId;+ return JSON.stringify(message);+}++function holding(overrides: Partial<StreamContext> = {}) {+ let listTools = () => {};+ const listed = new Promise<void>((resolve) => (listTools = resolve));+ const written: Written[] = [];+ const calls: Call[] = [];+ const record =+ (signal: keyof StreamSink) =>+ (...args: unknown[]) =>+ void calls.push([signal, ...args]);+ const sink: StreamSink = {+ text: record('text'),+ tool: record('tool'),+ toolResult: record('toolResult'),+ session: record('session'),+ usage: record('usage'),+ done: record('done'),+ fail: record('fail'),+ };+ const io = { write: (message: unknown) => void written.push(message as Written) };+ const conversation = opencodeRunner.converse?.(+ streamContext({ bin: 'opencode' }, { version: V2, toolsListed: () => listed, ...overrides }),+ ) as Conversation;+ conversation.open(io);+ return {+ conversation,+ written,+ calls,+ listTools,+ feed: (...lines: string[]) => lines.forEach((line) => conversation.read(line, sink, io)),+ asked: (method: string) => written.filter((message) => message.method === method),+ failed: () => calls.filter(([signal]) => signal === 'fail'),+ };+}++beforeEach(() => vi.useFakeTimers());+afterEach(() => vi.useRealTimers());++describe('opening a session', () => {+ test('a new session is asked for with no MCP server of its own, which the config already names', () => {+ const turn = holding();+ turn.feed(answerTo('turn', 1));+ expect(turn.asked('session/new')).toEqual([+ { jsonrpc: '2.0', id: 3, method: 'session/new', params: { cwd: turn.conversation.plan.cwd, mcpServers: [] } },+ ]);+ });++ // `session/load` would replay the whole history to the panel first.+ test('a held session is resumed, and one this database never had is opened afresh', () => {+ const turn = holding({ sessionId: 'ses_0000000000000000000000000' });+ turn.feed(answerTo('turn', 1));+ expect(turn.asked('session/resume')[0].params).toMatchObject({ sessionId: 'ses_0000000000000000000000000', mcpServers: [] });+ turn.feed(answerTo('resume-missing', 2));+ expect(turn.asked('session/new')).toHaveLength(1);+ expect(turn.failed()).toEqual([]);+ });++ test('a session opened in any agent but the contained one stops the run', () => {+ const turn = holding();+ const inBuild = opened((options) => {+ for (const option of options) if (option.id === 'mode') option.currentValue = 'build';+ });+ turn.feed(answerTo('turn', 1), inBuild);+ expect(turn.failed()).toEqual([['fail', 'AGENT_UNSAFE', expect.stringContaining('"build" agent')]]);+ expect(turn.conversation.holding).toBe(false);+ });++ test('an OpenCode with no ACP server is turned down, so later turns go through run', () => {+ const turn = holding({ settings: { bin: '/opt/opencode-no-acp' } });+ turn.feed(JSON.stringify({ jsonrpc: '2.0', id: 1, error: { code: -32601, message: 'Method not found' } }));+ expect(turn.failed()).toEqual([['fail', 'CONVERSATION_REFUSED', expect.stringContaining('Method not found')]]);+ expect(opencodeRunner.converse?.(streamContext({ bin: '/opt/opencode-no-acp' }, { version: V2 }))).toBeNull();+ });+});++describe('waiting for the browser tools', () => {+ // OpenCode connects MCP servers in the background and fixes each step's tools as it is sent.+ test('the prompt goes only once the run’s tools have reached OpenCode and it has had time to list them', async () => {+ const turn = holding();+ turn.feed(answerTo('turn', 1), answerTo('turn', 3));+ expect(turn.calls).toEqual([['session', SESSION]]);+ await vi.advanceTimersByTimeAsync(5_000);+ expect(turn.asked('session/prompt')).toEqual([]);+ turn.listTools();+ await vi.advanceTimersByTimeAsync(599);+ expect(turn.asked('session/prompt')).toEqual([]);+ await vi.advanceTimersByTimeAsync(1);+ expect(turn.asked('session/prompt')).toEqual([+ { jsonrpc: '2.0', id: 6, method: 'session/prompt', params: { sessionId: SESSION, prompt: [{ type: 'text', text: 'what does this page cost' }] } },+ ]);+ });++ test('tools that never arrive end the turn rather than leave the model without them', async () => {+ const turn = holding();+ turn.feed(answerTo('turn', 1), answerTo('turn', 3));+ await vi.advanceTimersByTimeAsync(20_000);+ expect(turn.failed()).toEqual([['fail', 'AGENT_FAILED', expect.stringContaining("could not start Browsentic's browser tools")]]);+ expect(turn.asked('session/prompt')).toEqual([]);+ });+});++describe('choosing the model and the effort', () => {+ // A model OpenCode does not know is swapped for another without a word.+ test('a pinned model it offers is asked for by name, and one it does not stops the turn with some it does', () => {+ const pinned = holding({ settings: { bin: 'opencode', model: 'opencode/big-pickle' } });+ pinned.feed(answerTo('turn', 1), answerTo('turn', 3));+ expect(pinned.asked('session/set_config_option')).toEqual([+ { jsonrpc: '2.0', id: 4, method: 'session/set_config_option', params: { sessionId: SESSION, configId: 'model', value: 'opencode/big-pickle' } },+ ]);+ const missing = holding({ settings: { bin: 'opencode', model: 'nowhere/model-x' } });+ missing.feed(answerTo('turn', 1), answerTo('turn', 3));+ expect(missing.failed()).toEqual([['fail', 'AGENT_FAILED', expect.stringMatching(/no model "nowhere\/model-x".*It offers mock\/m1, /)]]);+ });++ test('the model it already has is not asked for again', () => {+ const turn = holding({ settings: { bin: 'opencode', model: 'mock/m1' } });+ turn.feed(answerTo('turn', 1), answerTo('turn', 3));+ expect(turn.asked('session/set_config_option')).toEqual([]);+ });++ // 2.x refuses a run asking for an effort the model lacks, so only one it lists is asked for.+ test('an effort the model offers is set, and one it lacks is left out', async () => {+ const high = holding({ settings: { bin: 'opencode', effort: 'high' } });+ high.feed(answerTo('turn', 1), answerTo('turn', 3));+ expect(high.asked('session/set_config_option').map((message) => message.params)).toEqual([{ sessionId: SESSION, configId: 'effort', value: 'high' }]);+ const unknown = holding({ settings: { bin: 'opencode', effort: 'max' } });+ unknown.feed(answerTo('turn', 1), answerTo('turn', 3));+ unknown.listTools();+ await vi.advanceTimersByTimeAsync(600);+ expect([unknown.asked('session/set_config_option'), unknown.asked('session/prompt').length]).toEqual([[], 1]);+ });+});++describe('a turn', () => {+ const through = (name: string) => {+ const turn = holding();+ turn.feed(answerTo(name, 1), answerTo(name, 3), ...notices(name));+ const end = answerTo(name, 6);+ if (end) turn.feed(end);+ return turn.calls.filter(([signal]) => signal !== 'session');+ };++ test('says its words, leaves the browser call to the daemon, and ends with what it spent', () => {+ expect(through('turn')).toEqual([+ ['text', 'The page is Example Domain.'],+ ['usage', { contextTokens: 1230, outputTokens: 60 }],+ ['done', 'end_turn'],+ ]);+ });++ test("a research run's web fetch is drawn and closed", () => {+ expect(through('web').filter(([signal]) => signal === 'tool' || signal === 'toolResult')).toEqual([+ ['tool', 'call_35_0', 'webfetch'],+ ['toolResult', 'call_35_0', true],+ ]);+ });++ test('a tool the model was never offered is its mistake, and a built-in that ran stops the run', () => {+ expect(through('refused-tool').filter(([signal]) => signal === 'fail')).toEqual([]);+ expect(through('shell-ran').filter(([signal]) => signal === 'fail')).toEqual([['fail', 'AGENT_UNSAFE', expect.stringContaining('its own shell tool')]]);+ });++ test('a turn stopped from Browsentic is cancelled, not finished', () => {+ expect(through('cancelled').at(-1)).toEqual(['fail', 'CANCELLED', 'Run cancelled.']);+ });++ // Recorded against the real Zen endpoint with no sign-in: ACP passes on only "Authentication required".+ test('a model with no sign-in says how to sign Browsentic in', () => {+ expect(through('free-tier')).toEqual([['fail', 'AGENT_FAILED', expect.stringMatching(/narrowed to the browser.*OPENCODE_DB=.*auth login --standalone/)]]);+ });++ test("another session's updates are not this turn's", () => {+ const turn = holding();+ turn.feed(answerTo('turn', 1), answerTo('turn', 3));+ turn.feed(JSON.stringify({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: 'ses_other', update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'not ours' } } } }));+ expect(turn.calls).toEqual([['session', SESSION]]);+ });+});++describe('what OpenCode asks of Browsentic', () => {+ test('a permission is never granted, and nothing else it asks is answered', () => {+ const turn = holding();+ turn.feed(+ JSON.stringify({ jsonrpc: '2.0', id: 'p1', method: 'session/request_permission', params: { sessionId: SESSION, options: [] } }),+ JSON.stringify({ jsonrpc: '2.0', id: 'f1', method: 'fs/read_text_file', params: { path: '/etc/hosts' } }),+ );+ expect(turn.written.slice(-2)).toEqual([+ { jsonrpc: '2.0', id: 'p1', result: { outcome: { outcome: 'cancelled' } } },+ { jsonrpc: '2.0', id: 'f1', error: { code: -32601, message: 'Browsentic does not answer fs/read_text_file' } },+ ]);+ });+});diff --git a/src/daemon/agent/runners/opencode-acp.ts b/src/daemon/agent/runners/opencode-acp.tsnew file mode 100644index 0000000..643603a--- /dev/null+++ b/src/daemon/agent/runners/opencode-acp.ts@@ -0,0 +1,227 @@+import { MCP_SERVER_NAME } from './claude';+import { CONVERSATION_REFUSED, type Conversation, type ConversationIO, type Plan, type StreamContext, type StreamSink } from './types';+import { browserToolsDidNotStart } from './util';++const ASK = { initialize: 1, session: 2, fresh: 3, model: 4, effort: 5, prompt: 6 } as const;++/** JSON-RPC's own code for a method the agent does not know: an OpenCode without this protocol, not a failed turn. */+const UNKNOWN = -32601;++/** ACP's answer to a parameter it cannot use, which for `session/resume` is a session this database never held. */+const INVALID = -32602;++/**+ * OpenCode connects MCP servers in the background and reads its tool list afresh at each step, so a+ * prompt sent at once is answered by a model offered no browser tools. A run's tools are listed to+ * OpenCode when its server starts, and OpenCode registers them within a 100 ms debounce; this waits+ * out that debounce with room to spare. Measured on 2.0.32: 120 ms was always enough, 60 ms never.+ */+const SETTLE_MS = 600;++/** How long a run's browser tools may take to reach OpenCode before the turn is given up. */+const LISTED_WITHIN_MS = 20_000;++const WEB_TOOLS = ['webfetch', 'websearch'];++interface Message {+ id?: number | string;+ method?: string;+ params?: { sessionId?: string; update?: Update };+ result?: { sessionId?: string; configOptions?: ConfigOption[]; stopReason?: string; usage?: { outputTokens?: number } };+ error?: { code?: number; message?: string };+}++interface ConfigOption {+ id?: string;+ currentValue?: string;+ options?: { value?: string }[];+}++interface Update {+ sessionUpdate?: string;+ toolCallId?: string;+ name?: string;+ title?: string;+ status?: string;+ content?: { type?: string; text?: string };+ used?: number;+}++export interface AcpTurn {+ plan: Plan;+ /** The agent the config defines, which every session has to be in. */+ agent: string;+ declined: (reason: string) => void;+ explain: (message: string | undefined) => string;+ stoppedFor: (tool: string) => string;+}++/**+ * One turn with OpenCode 2 over the Agent Client Protocol, `opencode acp`, which keeps its own server+ * for as long as the turn holds it. The run's config comes from its environment as it would for+ * `opencode run`, but the prompt goes only once the browser tools have reached the session. A session+ * found in any agent but the run's own is refused, and a built-in that runs stops the run.+ */+export function acpTurn(context: StreamContext, turn: AcpTurn): Conversation {+ let session: string | undefined;+ let holding = false;+ let contextTokens = 0;+ const calls = new Map<string, string>();++ const refuse = (sink: StreamSink, reason: string) => {+ turn.declined(reason);+ sink.fail(CONVERSATION_REFUSED, reason);+ };++ const ask = (io: ConversationIO, id: number, method: string, params: Record<string, unknown>) => io.write({ jsonrpc: '2.0', id, method, params });++ const openSession = (io: ConversationIO, resuming: boolean) =>+ resuming+ ? ask(io, ASK.session, 'session/resume', { sessionId: context.sessionId, cwd: turn.plan.cwd, mcpServers: [] })+ : ask(io, ASK.fresh, 'session/new', { cwd: turn.plan.cwd, mcpServers: [] });++ const option = (options: ConfigOption[] | undefined, id: string) => options?.find((candidate) => candidate.id === id);+ const offers = (choice: ConfigOption | undefined, value: string) => choice?.options?.some((offered) => offered.value === value) === true;++ const prompt = (io: ConversationIO, sink: StreamSink) => {+ const late = new Promise<'late'>((resolve) => setTimeout(() => resolve('late'), LISTED_WITHIN_MS).unref());+ void Promise.race([context.toolsListed(), late]).then((listed) => {+ if (listed === 'late') return sink.fail('AGENT_FAILED', browserToolsDidNotStart('OpenCode'));+ setTimeout(() => ask(io, ASK.prompt, 'session/prompt', { sessionId: session, prompt: [{ type: 'text', text: context.instruction }] }), SETTLE_MS);+ });+ };++ // OpenCode lists each level of effort only for a model that has it, and refuses a run asking for one it lacks.+ const chooseEffort = (options: ConfigOption[] | undefined, io: ConversationIO, sink: StreamSink) => {+ const effort = context.settings.effort;+ const choice = option(options, 'effort');+ if (effort && choice?.currentValue !== effort && offers(choice, effort)) {+ return ask(io, ASK.effort, 'session/set_config_option', { sessionId: session, configId: 'effort', value: effort });+ }+ return prompt(io, sink);+ };++ // A model OpenCode does not know is swapped for another without a word, so a pinned one is asked for by name.+ const chooseModel = (options: ConfigOption[] | undefined, io: ConversationIO, sink: StreamSink) => {+ const model = context.settings.model;+ const choice = option(options, 'model');+ if (!model || choice?.currentValue === model) return chooseEffort(options, io, sink);+ if (!offers(choice, model)) {+ const some = (choice?.options ?? []).flatMap((offered) => (offered.value ? [offered.value] : [])).slice(0, 6);+ return sink.fail(+ 'AGENT_FAILED',+ `OpenCode offers no model "${model}" here.${some.length ? ` It offers ${some.join(', ')}, among others.` : ''} ` ++ 'Pick one in the Browsentic side panel, spelled provider/model, then try again.',+ );+ }+ return ask(io, ASK.model, 'session/set_config_option', { sessionId: session, configId: 'model', value: model });+ };++ const onSession = (message: Message, io: ConversationIO, sink: StreamSink) => {+ const options = message.result?.configOptions;+ const mode = option(options, 'mode')?.currentValue;+ if (mode !== turn.agent) {+ return sink.fail('AGENT_UNSAFE', `OpenCode opened this session as its "${mode ?? 'unnamed'}" agent rather than Browsentic's, so the run was stopped.`);+ }+ session = message.result?.sessionId ?? context.sessionId ?? undefined;+ if (!session) return sink.fail('AGENT_FAILED', 'OpenCode opened a session without naming it.');+ holding = true;+ sink.session(session);+ chooseModel(options, io, sink);+ };++ const onResponse = (message: Message, io: ConversationIO, sink: StreamSink) => {+ const failed = message.error;+ switch (message.id) {+ case ASK.initialize:+ if (failed) return refuse(sink, `its ACP server would not start: ${failed.message}`);+ return openSession(io, context.sessionId !== null);++ case ASK.session:+ case ASK.fresh:+ if (failed?.code === INVALID && message.id === ASK.session) return openSession(io, false);+ if (failed) {+ const reason = `OpenCode would not ${message.id === ASK.session ? 'resume' : 'start'} the session: ${failed.message}`;+ return failed.code === UNKNOWN ? refuse(sink, reason) : sink.fail('AGENT_FAILED', turn.explain(failed.message));+ }+ return onSession(message, io, sink);++ case ASK.model:+ if (failed) return sink.fail('AGENT_FAILED', turn.explain(failed.message));+ return chooseEffort(message.result?.configOptions, io, sink);++ case ASK.effort:+ return prompt(io, sink);++ case ASK.prompt: {+ if (failed) return sink.fail('AGENT_FAILED', turn.explain(failed.message));+ const output = message.result?.usage?.outputTokens;+ if (output !== undefined) sink.usage({ contextTokens, outputTokens: output });+ // Stopped from Browsentic, OpenCode ends the prompt itself before it exits.+ if (message.result?.stopReason === 'cancelled') return sink.fail('CANCELLED', 'Run cancelled.');+ return sink.done(message.result?.stopReason ?? 'end_turn');+ }+ }+ };++ const onToolCall = (update: Update, sink: StreamSink) => {+ const id = update.toolCallId;+ if (!id) return;+ const name = update.name ?? calls.get(id) ?? update.title ?? '';+ if (!calls.has(id)) {+ calls.set(id, name);+ if (WEB_TOOLS.includes(name)) sink.tool(id, name);+ }+ if (update.status !== 'completed' && update.status !== 'failed') return;+ if (WEB_TOOLS.includes(name)) return sink.toolResult(id, update.status === 'completed');+ // A refused call is the model reaching for a tool it was never offered; one that ran means the rules did not hold.+ if (update.status === 'completed' && !name.startsWith(`${MCP_SERVER_NAME}_`)) sink.fail('AGENT_UNSAFE', turn.stoppedFor(name));+ };++ const onUpdate = (update: Update | undefined, sink: StreamSink) => {+ switch (update?.sessionUpdate) {+ case 'agent_message_chunk':+ if (update.content?.type === 'text' && update.content.text) sink.text(update.content.text);+ return;+ case 'tool_call':+ case 'tool_call_update':+ return onToolCall(update, sink);+ case 'usage_update':+ if (typeof update.used === 'number') contextTokens = update.used;+ return;+ }+ };++ return {+ plan: turn.plan,+ get holding() {+ return holding;+ },+ declined: turn.declined,+ open(io) {+ ask(io, ASK.initialize, 'initialize', {+ protocolVersion: 1,+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },+ clientInfo: { name: 'browsentic', title: 'Browsentic', version: '1' },+ });+ },+ read(line, sink, io) {+ let message: Message;+ try {+ message = JSON.parse(line) as Message;+ } catch {+ return;+ }+ if (message.method && message.id !== undefined) {+ // Nobody is there to approve anything, and a denied tool is never asked about.+ if (message.method === 'session/request_permission') return io.write({ jsonrpc: '2.0', id: message.id, result: { outcome: { outcome: 'cancelled' } } });+ return io.write({ jsonrpc: '2.0', id: message.id, error: { code: UNKNOWN, message: `Browsentic does not answer ${message.method}` } });+ }+ if (message.method === 'session/update') {+ if (session && message.params?.sessionId === session) onUpdate(message.params.update, sink);+ return;+ }+ if (!message.method) onResponse(message, io, sink);+ },+ };+}diff --git a/src/daemon/agent/runners/opencode.test.ts b/src/daemon/agent/runners/opencode.test.tsindex af87863..ba1d2c3 100644--- a/src/daemon/agent/runners/opencode.test.ts+++ b/src/daemon/agent/runners/opencode.test.ts@@ -1,9 +1,9 @@-import { mkdirSync, rmSync, writeFileSync } from 'node:fs';-import { join, parse, relative, sep } from 'node:path';+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { dirname, join, parse, relative, sep } from 'node:path';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import { stateDir } from '../../lockfile';-import { opencodeRunner } from './opencode';-import { jsonContext, readThrough, shown, streamContext, transcript, valueOf } from './fixtures/support';+import { isOpenCode2, opencodeRunner, signInLine } from './opencode';+import { jsonContext, readThrough, shown, streamContext, stubCli, transcript, valueOf } from './fixtures/support';import type { Plan } from './types';const settings = { bin: 'opencode' };@@ -320,3 +320,295 @@ test('an XDG_CONFIG_HOME of the user’s own is honoured', () => {vi.stubEnv('XDG_CONFIG_HOME', '/elsewhere');expect(opencodeRunner.skillDirs?.()?.[0]).toBe(join('/elsewhere', 'opencode', 'skills'));});++const V2 = 'opencode v2.0.32';++describe('which OpenCode it is', () => {+ test.each([+ ['opencode v2.0.32', true],+ ['opencode v10.1.0', true],+ ['1.19.3', false],+ ['1.18.32', false],+ [undefined, false],+ // A notice printed ahead of the version is no version, and 1.x's plan fails safe on 2.x's parser.+ ['Update available: opencode v2.1.0', false],+ ])('%s is 2.x: %s', (version, expected) => {+ expect(isOpenCode2(version)).toBe(expected);+ });++ test('1.x holds no conversation, so its turns stay on run', () => {+ expect(opencodeRunner.converse?.(streamContext(settings, { version: '1.19.3' }))).toBeNull();+ });+});++interface Config2 {+ share: string;+ default_agent: string;+ instructions?: string[];+ policies: { action: string; resource: string; effect: string }[];+ mcp: { servers: Record<string, { type: string; command: string[]; environment: Record<string, string>; codemode: boolean; timeout: { execution: number } }> };+ agents: Record<string, { disabled?: boolean; permissions?: { action: string; resource: string; effect: string }[] }>;+}+const config2Of = (plan: Plan) => JSON.parse(plan.env?.OPENCODE_CONFIG_CONTENT ?? 'null') as Config2;+const rules2Of = (plan: Plan) => config2Of(plan).agents['browsentic-contained'].permissions ?? [];+const conversationOf = (overrides: Parameters<typeof streamContext>[1] = {}) => {+ const conversation = opencodeRunner.converse?.(streamContext(settings, { version: V2, ...overrides }));+ if (!conversation) throw new Error('OpenCode 2 held no conversation');+ return conversation;+};+const turn2 = (overrides: Parameters<typeof streamContext>[1] = {}) => conversationOf(overrides).plan;+const fallback2 = (overrides: Parameters<typeof streamContext>[1] = {}) => opencodeRunner.stream(streamContext(settings, { version: V2, ...overrides }));+const task2 = (overrides: Parameters<typeof jsonContext>[1] = {}) => opencodeRunner.json(jsonContext(settings, { version: V2, ...overrides }));++describe('an OpenCode 2 turn', () => {+ test('is one `opencode acp` held for the turn, its config in the environment and its prompt in a file', () => {+ const plan = shown(turn2());+ expect({ ...plan, env: { ...plan.env, OPENCODE_CONFIG_CONTENT: '<config>' } }).toMatchInlineSnapshot(`+ {+ "args": [+ "acp",+ ],+ "cwd": "<state>/agents/opencode/run/conversation-1",+ "env": {+ "BROWSENTIC_AGENT_RUN": "run-1",+ "OPENCODE_CONFIG_CONTENT": "<config>",+ "OPENCODE_CONFIG_PROJECT_DISABLE": "1",+ "OPENCODE_DB": "<state>/agents/opencode/opencode-2.db",+ "OPENCODE_DISABLE_AUTOUPDATE": "1",+ "OPENCODE_DISABLE_CLAUDE_CODE": "1",+ "OPENCODE_DISABLE_PROJECT_CONFIG": "1",+ "PWD": "<state>/agents/opencode/run/conversation-1",+ },+ "files": [+ {+ "content": "You are Browsentic.++ A tool result over 100 KB comes back cut, and the saved copy OpenCode points to cannot be opened in this run, so ask for less at a time — \`page_getPageInfo\` with a small \`maxPerKind\`, \`page_extractText\` with the cursor it hands back.+ ",+ "path": "instructions.md",+ },+ ],+ }+ `);+ });++ // 2.x reads `$PWD` before its own working directory, and the user's sessions are in a database Browsentic never opens.+ test('it runs in its conversation folder, against a database of its own that 1.x never shares', () => {+ const plan = turn2();+ expect([plan.env?.PWD, plan.env?.OPENCODE_DB]).toEqual([plan.cwd, join(stateDir, 'agents', 'opencode', 'opencode-2.db')]);+ expect(plan.env?.OPENCODE_DB).not.toBe(opencodeRunner.stream(streamContext(settings)).env?.OPENCODE_DB);+ });++ test('the rules deny everything first, then allow each browser tool by name, and the web tools on research only', () => {+ expect(rules2Of(turn2())).toEqual([+ { action: '*', resource: '*', effect: 'deny' },+ { action: 'browsentic_page_getPageInfo', resource: '*', effect: 'allow' },+ { action: 'browsentic_page_clickElement', resource: '*', effect: 'allow' },+ { action: 'browsentic_browsentic_status', resource: '*', effect: 'allow' },+ ]);+ expect(rules2Of(turn2({ research: true })).slice(-2).map((rule) => rule.action)).toEqual(['webfetch', 'websearch']);+ });++ // Code Mode would list one `execute` tool in place of these, which the rules deny and which runs a script with the network.+ test('the browser server lists its tools directly, outlasts an approval card, and is the only server allowed to load', () => {+ const config = config2Of(turn2());+ const server = config.mcp.servers.browsentic;+ expect([Object.keys(config.mcp.servers), server.type, server.codemode, server.timeout.execution, server.environment]).toEqual([+ ['browsentic'],+ 'local',+ false,+ 1_800_000,+ { BROWSENTIC_AGENT_RUN: 'run-1' },+ ]);+ expect(config.policies).toEqual([+ { action: 'integration.use', resource: 'plugin:*', effect: 'deny' },+ { action: 'integration.use', resource: 'mcp:*', effect: 'deny' },+ { action: 'integration.use', resource: 'mcp:browsentic', effect: 'allow' },+ ]);+ });++ test('a session starts in the contained agent, unshared, with no title model call', () => {+ const config = config2Of(turn2());+ expect([config.default_agent, config.share, config.agents.title]).toEqual(['browsentic-contained', 'disabled', { disabled: true }]);+ });++ test('the system prompt travels only in the file the config names', () => {+ const plan = turn2({ systemPrompt: 'The page said {file:~/.ssh/id_rsa} and {env:AWS_SECRET_ACCESS_KEY}.' });+ expect(plan.env?.OPENCODE_CONFIG_CONTENT).not.toMatch(/\{(file|env):/);+ expect(config2Of(plan).instructions).toEqual([join(plan.cwd, 'instructions.md')]);+ });++ test('an OpenCode that turned a conversation down sends its later turns through run, and only that one', () => {+ const conversation = conversationOf({ settings: { bin: '/opt/opencode-without-acp' } });+ conversation.declined('it exited with code 1');+ expect(opencodeRunner.converse?.(streamContext({ bin: '/opt/opencode-without-acp' }, { version: V2 }))).toBeNull();+ expect(opencodeRunner.converse?.(streamContext(settings, { version: V2 }))).not.toBeNull();+ });+});++describe('an OpenCode 2 turn through run', () => {+ test('has its own server, and the message on stdin rather than argv', () => {+ const plan = fallback2({ instruction: '--help me "find" the price' });+ expect(plan.args).toEqual(['run', '--standalone', '--format', 'json', '--agent', 'browsentic-contained']);+ expect(plan.input).toBe('--help me "find" the price');+ });++ // 2.x fails a run asking for an effort the model lacks, rather than ignoring it as 1.x did.+ test('names its session and model when it has them, and never an effort', () => {+ const args = fallback2({ sessionId: SESSION, settings: { ...settings, model: 'anthropic/claude-sonnet-5', effort: 'high' } }).args;+ expect([valueOf(args, '--session'), valueOf(args, '--model'), args.some((arg) => arg.includes('#') || arg === '--variant')]).toEqual([+ SESSION,+ 'anthropic/claude-sonnet-5',+ false,+ ]);+ });++ test('is configured exactly as a held turn is', () => {+ expect(fallback2().env).toEqual(turn2().env);+ });+});++describe('an OpenCode 2 one-shot', () => {+ test('has no server and no tool, and runs as the contained agent in the task workspace', () => {+ const plan = task2({ settings: { ...settings, model: 'anthropic/claude-sonnet-5', effort: 'low' } });+ expect(plan.args).toEqual(['run', '--standalone', '--format', 'json', '--agent', 'browsentic-contained', '--model', 'anthropic/claude-sonnet-5']);+ expect([plan.input, plan.cwd, plan.env?.PWD]).toEqual(['summarize this', opencodeRunner.workspace('task'), opencodeRunner.workspace('task')]);+ expect([config2Of(plan).mcp.servers, rules2Of(plan)]).toEqual([{}, [{ action: '*', resource: '*', effect: 'deny' }]]);+ });++ // Measured: tmp/* opens the scratch folder by either path, and /tmp, /etc/hosts and a ../ are an external directory the deny covers.+ test('a one-shot handed a file may read its scratch folder and nothing else', () => {+ expect(rules2Of(task2({ reads: true })).slice(1)).toEqual([{ action: 'read', resource: 'tmp/*', effect: 'allow' }]);+ });+});++describe('reading an OpenCode 2 stream', () => {+ const read2 = (name: string, only?: Parameters<typeof readThrough>[2]) => readThrough(opencodeRunner, transcript('opencode', name), only);++ // The first call reached for a tool before the run's server had connected, which a held turn waits out.+ test('a turn says its text and what it spent, and a call the model was not yet offered is no breach', () => {+ expect(read2('2.0.32-turn.jsonl').filter(([signal]) => signal !== 'session')).toEqual([+ ['usage', { contextTokens: 1230, outputTokens: 30 }],+ ['usage', { contextTokens: 1230, outputTokens: 60 }],+ ['text', 'The page is Example Domain.'],+ ]);+ });++ test('every line names the session, and a resumed turn names the same one', () => {+ const turn = new Set(read2('2.0.32-turn.jsonl', 'session').map(([, id]) => id));+ expect(turn.size).toBe(1);+ expect(new Set(read2('2.0.32-resumed.jsonl', 'session').map(([, id]) => id))).toEqual(turn);+ });++ test("a research run's web fetch is drawn by the call's own id", () => {+ expect(read2('2.0.32-web.jsonl', 'tool')).toEqual([['tool', expect.stringMatching(/^call_/), 'webfetch']]);+ });++ test('a built-in that ran stops the run', () => {+ expect(read2('2.0.32-shell-ran.jsonl', 'fail')).toEqual([['fail', 'AGENT_UNSAFE', expect.stringContaining('its own shell tool')]]);+ });++ test("a text block finished after it was first printed goes on where it stopped, and the next one starts a paragraph", () => {+ expect(read2('2.0.32-text-suffix.hand-written.jsonl', 'text')).toEqual([+ ['text', 'The page is Exam'],+ ['text', 'ple Domain.'],+ ['text', '\n\nIt has one link.'],+ ]);+ expect(opencodeRunner.answer(transcript('opencode', '2.0.32-text-suffix.hand-written.jsonl').join('\n'))).toEqual({+ text: 'The page is Example Domain.\n\nIt has one link.',+ });+ });++ test('a refused key says what the provider said, and how to sign Browsentic in', () => {+ const [[, code, message]] = read2('2.0.32-auth-error.jsonl', 'fail');+ expect([code, message]).toEqual(['AGENT_FAILED', expect.stringMatching(/^Invalid API key provided/)]);+ expect(message).toContain('auth login --standalone');+ });++ // Recorded against the real Zen endpoint, which still serves its free models only to OpenCode's own tools.+ test("Zen's free tier refusing a contained run says to sign Browsentic in to a provider", () => {+ const [[, , message]] = read2('2.0.32-free-tier.jsonl', 'fail');+ expect(message).toEqual(expect.stringContaining('narrowed to the browser'));+ expect(message).toContain(`OPENCODE_DB=`);+ });++ test('a model, or an effort, OpenCode does not have says which to change', () => {+ expect(read2('2.0.32-unknown-model.jsonl', 'fail')[0][2]).toContain('provider/model');+ expect(read2('2.0.32-unknown-variant.jsonl', 'fail')[0][2]).toContain('effort');+ });+});++describe('what an OpenCode 2 says when it cannot start', () => {+ // The other line's flags are what a swap under a running Browsentic looks like.+ test('a flag of the other line asks for the message again', () => {+ expect(opencodeRunner.hint?.('ERROR\n Unrecognized flag: --pure in command opencode run')).toContain('changed version');+ expect(opencodeRunner.hint?.('Configuration is invalid ↳ V2 permissions are not supported by OpenCode V1.')).toContain('changed version');+ });+});++describe('OpenCode 2 readiness', () => {+ const db = join(stateDir, 'agents', 'opencode', 'opencode-2.db');+ const bins = join(stateDir, 'opencode-bins');+ let seq = 0;+ /** A stand-in `opencode` that answers `auth list` with `stdout`, and keeps how it was asked. */+ const answering = (stdout: string, code = 0) => {+ mkdirSync(bins, { recursive: true });+ const asked = join(bins, `asked-${++seq}.json`);+ const bin = stubCli(+ join(bins, `opencode-${seq}`),+ `require('node:fs').writeFileSync(${JSON.stringify(asked)}, JSON.stringify({ args: process.argv.slice(2), db: process.env.OPENCODE_DB, pwd: process.env.PWD }));\n` ++ `process.stdout.write(${JSON.stringify(stdout)});\nprocess.exit(${code});\n`,+ );+ return { bin, asked: () => JSON.parse(readFileSync(asked, 'utf8')) as { args: string[]; db: string; pwd: string } };+ };+ const problem = (bin = 'opencode') => opencodeRunner.check?.({ bin }, V2);+ const created = () => {+ mkdirSync(dirname(db), { recursive: true });+ writeFileSync(db, '');+ };++ beforeEach(() => rmSync(dirname(db), { recursive: true, force: true }));+ afterEach(() => rmSync(bins, { recursive: true, force: true }));++ test('with no database of its own it needs signing in, which it says how to do, and the database has a folder to go in', async () => {+ expect(await problem()).toEqual({ code: 'AGENT_NEEDS_PERMISSION', message: expect.stringContaining('OpenCode 2'), fix: signInLine('opencode') });+ expect(existsSync(dirname(db))).toBe(true);+ });++ // Without --standalone, `auth list` would start the user's background service with this environment, on this database.+ test("the database is asked through OpenCode's own server, in Browsentic's environment", async () => {+ created();+ const { bin, asked } = answering('[]');+ expect((await problem(bin))?.code).toBe('AGENT_NEEDS_PERMISSION');+ expect(asked()).toEqual({ args: ['auth', 'list', '--standalone', '--format', 'json'], db, pwd: opencodeRunner.workspace('task') });+ }, 20_000);++ test('a stored sign-in or a working key is enough, and one that needs signing in again is not', async () => {+ created();+ expect(await problem(answering(JSON.stringify([{ id: 'anthropic', connections: [{ type: 'credential', label: 'Anthropic' }] }])).bin)).toBeNull();+ const stale = [{ id: 'opencode', connections: [{ type: 'env', name: 'OPENCODE_API_KEY', status: { status: 'needs_auth' } }] }];+ expect((await problem(answering(JSON.stringify(stale)).bin))?.code).toBe('AGENT_NEEDS_PERMISSION');+ }, 20_000);++ // A picker that wrongly says "needs setup" blocks a working agent; the run's own error catches the opposite case.+ test('an answer it cannot read is taken as signed in', async () => {+ created();+ expect(await problem(answering('Standalone server exited before reporting readiness', 1).bin)).toBeNull();+ expect(await problem(answering('not json').bin)).toBeNull();+ }, 20_000);++ test('a Zen key in the environment, or a provider of the user’s own config, is enough without asking', async () => {+ vi.stubEnv('OPENCODE_API_KEY', 'zen-key');+ expect(await problem('/nonexistent/opencode')).toBeNull();+ vi.stubEnv('OPENCODE_API_KEY', '');+ mkdirSync(join(home, '.config', 'opencode'), { recursive: true });+ writeFileSync(join(home, '.config', 'opencode', 'opencode.jsonc'), '{ "providers": { "ollama": {} } }');+ expect(await problem('/nonexistent/opencode')).toBeNull();+ });++ test('the sign-in line points OpenCode at that database, quoted for the shell it runs in', () => {+ expect(signInLine('opencode', 'darwin')).toBe(`OPENCODE_DB='${db}' opencode auth login --standalone`);+ expect(signInLine("/Users/o'neil/bin/opencode 2", 'darwin')).toBe(`OPENCODE_DB='${db}' '/Users/o'\\''neil/bin/opencode 2' auth login --standalone`);+ expect(signInLine('C:\\Program Files\\opencode.cmd', 'win32')).toBe(`$env:OPENCODE_DB='${db}'; & 'C:\\Program Files\\opencode.cmd' auth login --standalone`);+ });+});diff --git a/src/daemon/agent/runners/opencode.ts b/src/daemon/agent/runners/opencode.tsindex bd54845..8a1e796 100644--- a/src/daemon/agent/runners/opencode.ts+++ b/src/daemon/agent/runners/opencode.ts@@ -1,10 +1,14 @@import { randomUUID } from 'node:crypto';-import { readFileSync } from 'node:fs';+import { mkdirSync, readFileSync, statSync } from 'node:fs';import { homedir } from 'node:os';import { dirname, join, relative, sep } from 'node:path';import type { AgentProblem } from '@/lib/agents/catalog';import { stateDir } from '../../lockfile';+import type { AgentSettings } from '../config';import { MCP_SERVER_NAME } from './claude';+import { spawnCli, stopTree, type CliProcess } from './command';+import { childEnv } from './drive';+import { acpTurn } from './opencode-acp';import { conversationDir, effortOf, MCP_CALL_TIMEOUT_MS, parseJsonLine, sweepRunDirs } from './util';import type { JsonContext, McpServer, Plan, Runner, RunMode, StreamContext, StreamReader, StreamSink } from './types';@@ -18,6 +22,9 @@ import type { JsonContext, McpServer, Plan, Runner, RunMode, StreamContext, Stre* the system prompt is a file the config points at, and instruction files are read verbatim.** `opencode run` waits for stdin to close and appends it to the message; drive.ts spawns it ignored.+ *+ * OpenCode 2 is a second line of releases (`@opencode/cli`, beside 1's `opencode-ai`) with its own+ * flags, config, database and protocol; which one a plan is for comes from the `--version` probed.*//**@@ -38,26 +45,72 @@ const TRUNCATION = `A tool result over ${RESULT_BYTES / 1000} KB comes back cut,/** A user's `share: auto` would publish every browsing session; project config would load from folders above the workspace. */const SEALED = { OPENCODE_DISABLE_PROJECT_CONFIG: '1', OPENCODE_DISABLE_CLAUDE_CODE: '1', OPENCODE_DISABLE_SHARE: '1' };+/** OpenCode 2 renamed the project switch, reading the old name only when the new one is unset, and dropped the share one. */+const SEALED_2 = {+ OPENCODE_CONFIG_PROJECT_DISABLE: '1',+ OPENCODE_DISABLE_PROJECT_CONFIG: '1',+ OPENCODE_DISABLE_CLAUDE_CODE: '1',+ OPENCODE_DISABLE_AUTOUPDATE: '1',+};+/** Every folder outside git is one project to OpenCode, so runs kept in its own store would fill the user's session list. */const sessionsDb = () => join(stateDir, 'agents', 'opencode', 'sessions.db');+/**+ * OpenCode 2 keeps its logins in the same database as its sessions, and migrates one 1 cannot open+ * again. Runs keep their own, so the user's background service never sees one, and it holds the+ * sign-in the user gave Browsentic.+ */+const database2 = () => join(stateDir, 'agents', 'opencode', 'opencode-2.db');+const configHome = () => join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'opencode');const INSTALL = 'npm i -g opencode-ai';+/** `opencode v2.0.32` from 2.x, a bare `1.19.3` from 1.x. */+export const isOpenCode2 = (version?: string): boolean => Number(/^(?:opencode\s+)?v?(\d+)\./i.exec(version?.trim() ?? '')?.[1] ?? 0) >= 2;++/** Bins whose OpenCode would not hold a conversation, whose turns go through `opencode run` until the daemon restarts. */+const noConversation = new Set<string>();+type Permission = Record<string, string | Record<string, string>>;+interface Rule {+ action: string;+ resource: string;+ effect: 'allow' | 'deny';+}++const rule = (action: string, effect: Rule['effect'] = 'allow', resource = '*'): Rule => ({ action, resource, effect });++/**+ * Plugins run inside OpenCode, and another MCP server of the user's would start beside the run's own.+ * A policy in the user's global or managed config outranks these, which the containment note says.+ */+const POLICIES = [+ { action: 'integration.use', resource: 'plugin:*', effect: 'deny' },+ { action: 'integration.use', resource: 'mcp:*', effect: 'deny' },+ { action: 'integration.use', resource: `mcp:${MCP_SERVER_NAME}`, effect: 'allow' },+];+interface Part {type?: string;text?: string;tool?: string;callID?: string;+ id?: string;+ messageID?: string;state?: { status?: string };tokens?: { input?: number; output?: number; reasoning?: number; cache?: { read?: number; write?: number } };}+/** 1.x names an error and nests what the provider said; 2.x types it, `provider.auth` and the like. */interface Failure {name?: string;+ type?: string;+ message?: string;+ status?: number;+ response?: { body?: string };data?: { message?: string; statusCode?: number; responseBody?: string };}@@ -86,6 +139,7 @@ export const opencodeRunner: Runner = {],stream(context: StreamContext): Plan {+ if (isOpenCode2(context.version)) return standalone(context);const { settings, research } = context;const base = this.workspace('run');sweepRunDirs(base);@@ -117,9 +171,26 @@ export const opencodeRunner: Runner = {};},+ /**+ * OpenCode 2's `run` sends its first request before the run's MCP server has connected, and that+ * step's tool list is fixed when it is sent, so the turn is held over ACP until the tools are there.+ */+ converse(context: StreamContext) {+ const { bin } = context.settings;+ if (!isOpenCode2(context.version) || noConversation.has(bin)) return null;+ return acpTurn(context, {+ plan: { ...turn2(context), args: ['acp'] },+ agent: AGENT,+ declined: () => noConversation.add(bin),+ explain: (message) => explain({ message }, bin),+ stoppedFor: (tool) => stoppedFor(tool),+ });+ },+reader(): StreamReader {let spoke = false;let generated = 0;+ const continues = continuation();const report = (tokens: NonNullable<Part['tokens']>, sink: StreamSink) => {const made = (tokens.output ?? 0) + (tokens.reasoning ?? 0);@@ -135,23 +206,21 @@ export const opencodeRunner: Runner = {const part = event.part;switch (event.type) {- case 'text':+ case 'text': {if (!part?.text) return;- sink.text(spoke ? `\n\n${part.text}` : part.text);+ const goesOn = continues(part);+ sink.text(spoke && !goesOn ? `\n\n${part.text}` : part.text);spoke = true;return;+ }case 'tool_use': {const name = part?.tool;if (!name || ownTool(name)) return;- if (WEB_TOOLS.includes(name)) return sink.tool(part.callID ?? randomUUID(), name);+ if (WEB_TOOLS.includes(name)) return sink.tool(part.callID ?? part.id ?? randomUUID(), name);// A refused call is the model reaching for a tool it was never offered; one that ran means the ruleset did not hold.if (part.state?.status !== 'completed') return;- return sink.fail(- 'AGENT_UNSAFE',- `OpenCode ran its own ${name} tool in this run, which Browsentic denied, so the run was stopped. ` +- 'Update OpenCode and Browsentic; if it persists, please report it.',- );+ return sink.fail('AGENT_UNSAFE', stoppedFor(name));}case 'step_finish':@@ -167,6 +236,20 @@ export const opencodeRunner: Runner = {json(context: JsonContext): Plan {const { settings, reads } = context;const cwd = this.workspace('task');+ if (isOpenCode2(context.version)) {+ return {+ cwd,+ env: {+ ...SEALED_2,+ PWD: cwd,+ OPENCODE_DB: database2(),+ // A path inside the folder a run starts in is matched as seen from it, and anything outside is an external directory the deny covers.+ OPENCODE_CONFIG_CONTENT: config2({ servers: {}, allowed: reads ? [rule('read', 'allow', 'tmp/*')] : [] }),+ },+ args: [...invocation2(), ...(settings.model ? ['--model', settings.model] : [])],+ input: context.prompt,+ };+ }const permission: Permission = { '*': 'deny', ...(reads ? { read: scratchReads(cwd) } : {}) };return {cwd,@@ -182,11 +265,15 @@ export const opencodeRunner: Runner = {answer(stdout: string) {let said: string[] = [];+ const continues = continuation();for (const line of stdout.split('\n')) {const event = parseJsonLine<Event>(line);if (event?.type === 'error') return { error: explain(event.error) };if (event?.type === 'step_start') said = [];- if (event?.type === 'text' && event.part?.text) said.push(event.part.text);+ if (event?.type === 'text' && event.part?.text) {+ if (continues(event.part) && said.length) said[said.length - 1] += event.part.text;+ else said.push(event.part.text);+ }}return { text: said.length ? said.join('\n\n') : undefined };},@@ -195,10 +282,15 @@ export const opencodeRunner: Runner = {if (/Unknown arguments?|Not enough arguments|Invalid values/i.test(stderrTail)) {return `Your OpenCode does not understand the flags Browsentic uses. Update it (${INSTALL}), then try again. (${stderrTail.trim()})`;}+ // Each release line refuses the other's flags, which happens when OpenCode is swapped while Browsentic is running.+ if (/Unrecognized flag/i.test(stderrTail) || /V2 permissions are not supported/i.test(stderrTail)) {+ return `OpenCode changed version since Browsentic last checked it. Send the message again. (${oneLine(stderrTail)})`;+ }return null;},- async check(): Promise<AgentProblem | null> {+ async check(settings: AgentSettings, version?: string): Promise<AgentProblem | null> {+ if (isOpenCode2(version)) return check2(settings);if (process.env.OPENCODE_API_KEY || process.env.OPENCODE_AUTH_CONTENT || signedIn() || declaresProvider()) return null;return {code: 'AGENT_NEEDS_PERMISSION',@@ -211,8 +303,32 @@ export const opencodeRunner: Runner = {const invocation = () => ['run', '--format', 'json', '--pure', '--agent', AGENT];+/** No message on argv: 2.x quotes any word with a space in it, and appends what follows `--` a second time. */+const invocation2 = () => ['run', '--standalone', '--format', 'json', '--agent', AGENT];+const ownTool = (name: string) => name.startsWith(`${MCP_SERVER_NAME}_`);+/**+ * Whether a text part goes on with one already said. 2.x ends a turn by sending whatever of a text+ * block it had not yet printed, under that block's number in its message — `prt_<message>_text-<n>` —+ * and a block printed in part before goes on where it stopped. 1.x's parts never carry the number.+ */+function continuation(): (part: Part) => boolean {+ const blocks = new Map<string, number>();+ return (part) => {+ const message = part.messageID ?? '';+ const shown = blocks.get(message) ?? 0;+ const numbered = /_text-(\d+)$/.exec(part.id ?? '');+ if (numbered && Number(numbered[1]) < shown) return true;+ blocks.set(message, numbered ? Number(numbered[1]) + 1 : shown + 1);+ return false;+ };+}++const stoppedFor = (tool: string) =>+ `OpenCode ran its own ${tool} tool in this run, which Browsentic denied, so the run was stopped. ` ++ 'Update OpenCode and Browsentic; if it persists, please report it.';+const server = (mcp: McpServer) => ({type: 'local',command: [mcp.command, ...mcp.args],@@ -221,6 +337,15 @@ const server = (mcp: McpServer) => ({timeout: MCP_CALL_TIMEOUT_MS,});+/** Code Mode would hide the tools behind an `execute` tool the ruleset denies, and that tool is a script with the network. */+const server2 = (mcp: McpServer) => ({+ type: 'local',+ command: [mcp.command, ...mcp.args],+ environment: mcp.env,+ codemode: false,+ timeout: { execution: MCP_CALL_TIMEOUT_MS },+});+/** Title generation is a model call per new session that the panel already makes for itself. */function config({ mcp, instructions, permission }: { mcp: Record<string, unknown>; instructions?: string[]; permission: Permission }): string {return JSON.stringify({@@ -234,6 +359,60 @@ function config({ mcp, instructions, permission }: { mcp: Record<string, unknown});}+/** 2.x's own shape: the rules are a list where the last match wins, and an ACP session starts in `default_agent`. */+function config2({ servers, instructions, allowed }: { servers: Record<string, unknown>; instructions?: string[]; allowed: Rule[] }): string {+ return JSON.stringify({+ share: 'disabled',+ update: 'disable',+ snapshots: false,+ tool_output: { max_bytes: RESULT_BYTES, max_lines: RESULT_BYTES },+ ...(instructions ? { instructions } : {}),+ default_agent: AGENT,+ mcp: { servers },+ policies: POLICIES,+ agents: { title: { disabled: true }, [AGENT]: { mode: 'primary', permissions: [rule('*', 'deny'), ...allowed] } },+ });+}++/** What a 2.x turn starts from, however it is then spoken to. 2.x moves to `$PWD` before its own working directory. */+function turn2(context: StreamContext): Omit<Plan, 'args'> {+ const base = opencodeRunner.workspace('run');+ sweepRunDirs(base);+ const cwd = conversationDir(base, context.conversation ?? context.runId);+ const allowed = [...context.mcpTools.map((tool) => `${MCP_SERVER_NAME}_${tool}`), ...(context.research ? WEB_TOOLS : [])];+ return {+ cwd,+ env: {+ ...SEALED_2,+ PWD: cwd,+ OPENCODE_DB: database2(),+ OPENCODE_CONFIG_CONTENT: config2({+ servers: { [MCP_SERVER_NAME]: server2(context.mcp) },+ instructions: [join(cwd, INSTRUCTIONS)],+ allowed: allowed.map((action) => rule(action)),+ }),+ BROWSENTIC_AGENT_RUN: context.runId,+ },+ files: [{ path: INSTRUCTIONS, content: `${context.systemPrompt.trim()}\n\n${TRUNCATION}\n` }],+ };+}++/**+ * A 2.x turn through `opencode run`, for an OpenCode that would not hold a conversation. Its first step+ * may not see the browser tools yet. No effort: 2.x refuses the run when the model lacks that variant.+ */+function standalone(context: StreamContext): Plan {+ return {+ ...turn2(context),+ args: [+ ...invocation2(),+ ...(context.sessionId ? ['--session', context.sessionId] : []),+ ...(context.settings.model ? ['--model', context.settings.model] : []),+ ],+ input: context.instruction,+ };+}+/*** OpenCode matches a read against its path relative to the project root — `/` outside git, the* repository when the home directory is one — so the scratch folder is allowed as seen from every@@ -251,24 +430,53 @@ function scratchReads(workspace: string): Record<string, string> {}}-function explain(failure: Failure | undefined): string {- const message = oneLine(failure?.data?.message ?? failure?.name ?? 'OpenCode reported an error');- const status = failure?.data?.statusCode;+/** The command that signs Browsentic's own OpenCode 2 database in, in the user's shell. */+export function signInLine(bin: string, platform: NodeJS.Platform = process.platform): string {+ const db = database2();+ if (platform === 'win32') return `$env:OPENCODE_DB='${db.replaceAll("'", "''")}'; & '${bin.replaceAll("'", "''")}' auth login --standalone`;+ const quote = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`;+ return `OPENCODE_DB=${quote(db)} ${/^[\w./-]+$/.test(bin) ? bin : quote(bin)} auth login --standalone`;+}++function explain(failure: Failure | undefined, bin = 'opencode'): string {+ const message = oneLine(failure?.data?.message ?? failure?.message ?? failure?.name ?? failure?.type ?? 'OpenCode reported an error');+ const status = failure?.data?.statusCode ?? failure?.status;+ const body = failure?.data?.responseBody ?? failure?.response?.body ?? '';+ // 1.x names its errors and nests what the provider said; 2.x types them, and over ACP passes on only a message.+ const v1 = failure?.name !== undefined || failure?.data !== undefined;// Zen serves its free models only to requests carrying OpenCode's own built-in tools.- if (failure?.data?.responseBody?.includes('FreeTierError')) {+ if (v1 && body.includes('FreeTierError')) {return (`OpenCode Zen's free models refuse a run whose tools Browsentic has narrowed to the browser. Run "opencode auth login" ` +`to sign in to a provider, then pick one of its models in the Browsentic side panel. (${message})`);}- if (failure?.name === 'ProviderAuthError' || status === 401 || status === 403) {+ if (!v1 && body.includes('FreeTierError')) {+ return (+ `OpenCode Zen's free models refuse a run whose tools Browsentic has narrowed to the browser. Sign Browsentic's OpenCode in ` ++ `to a provider with ${signInLine(bin)}, then pick one of its models in the side panel. (${message})`+ );+ }+ // Over ACP, 2.x says only this, for a provider with no sign-in and for Zen's free tier alike.+ if (!v1 && /authentication required/i.test(message)) {+ return (+ `OpenCode has no sign-in for this model in Browsentic, and OpenCode Zen's free models refuse a run whose tools Browsentic ` ++ `has narrowed to the browser. Sign Browsentic's OpenCode in to a provider with ${signInLine(bin)}, then pick one of its models in the side panel. (${message})`+ );+ }+ if (failure?.name === 'ProviderAuthError' || failure?.type === 'provider.auth' || status === 401 || status === 403) {+ if (!v1) return `${message} If that is a login problem, sign Browsentic's OpenCode in with ${signInLine(bin)}.`;return (`${message} If that is a login problem, run "opencode auth login" — a key kept only in an environment ` +'variable is not passed to a Browsentic run.');}- if (status === 429) return `The provider behind OpenCode is rate-limiting this account. Wait and try again. (${message})`;- if (failure?.name === 'UnknownError') {+ if (status === 429 || failure?.type === 'provider.rate-limit') return `The provider behind OpenCode is rate-limiting this account. Wait and try again. (${message})`;+ if (failure?.type === 'provider.quota') return `The provider behind OpenCode says this account is out of credit or quota. Top it up, or pick another provider's model. (${message})`;+ if (/variant unavailable/i.test(message)) {+ return `The model OpenCode is using has no such level of effort. Clear the effort in Browsentic's settings, or pick another, then try again. (${message})`;+ }+ if (failure?.name === 'UnknownError' || /model unavailable|invalid model reference/i.test(message)) {return (`OpenCode could not start this turn, most often because it does not know the model. Pick one in the ` +`Browsentic side panel as "opencode models" lists it — provider/model — then try again. (${message})`@@ -291,12 +499,101 @@ function signedIn(): boolean {}/** A provider the user configured by hand — a local model needs no login. */-function declaresProvider(): boolean {+function declaresProvider(pattern = /"provider"\s*:/): boolean {return ['opencode.json', 'opencode.jsonc', 'config.json'].some((name) => {try {- return /"provider"\s*:/.test(readFileSync(join(configHome(), name), 'utf8'));+ return pattern.test(readFileSync(join(configHome(), name), 'utf8'));} catch {return false;}});}++const AUTH_TIMEOUT_MS = 5_000;++/** One answer per state of the database, and one question at a time. */+let lastAnswer: { key: string; problem: AgentProblem | null } | undefined;+let asking: Promise<AgentProblem | null> | undefined;++/**+ * OpenCode 2's sign-ins live in its database, so its own `auth list` is asked, against Browsentic's+ * database and in the environment a run gets: an exported key shows there exactly when a run sees it.+ * `--standalone` keeps the user's background service out of it — without it that service would be+ * started with this environment and run on Browsentic's database. Anything unexpected reads as signed+ * in, because a picker that wrongly says *needs setup* blocks a working agent.+ */+async function check2(settings: AgentSettings): Promise<AgentProblem | null> {+ if (process.env.OPENCODE_API_KEY || declaresProvider(/"providers?"\s*:/)) return null;+ const db = database2();+ // The sign-in line points OpenCode at this file, and its server will not start in a folder that is not there.+ mkdirSync(dirname(db), { recursive: true });+ const stamped = stamp(db);+ if (!stamped) return needsSignIn(settings.bin);+ const key = `${settings.bin}|${stamped}|${stamp(`${db}-wal`)}`;+ if (lastAnswer?.key === key) return lastAnswer.problem;+ asking ??= listSignIns(settings.bin)+ .then((signedIn) => {+ const problem = signedIn ? null : needsSignIn(settings.bin);+ lastAnswer = { key, problem };+ return problem;+ })+ .finally(() => (asking = undefined));+ return asking;+}++const stamp = (path: string) => {+ try {+ const { mtimeMs, size } = statSync(path);+ return `${mtimeMs}:${size}`;+ } catch {+ return '';+ }+};++const needsSignIn = (bin: string): AgentProblem => ({+ code: 'AGENT_NEEDS_PERMISSION',+ message:+ "This OpenCode 2 has no sign-in of its own for Browsentic, which keeps one apart from yours, and OpenCode Zen's free models refuse a run whose tools Browsentic has narrowed to the browser.",+ fix: signInLine(bin),+});++interface Integration {+ connections?: { status?: { status?: string } }[];+}++function listSignIns(bin: string): Promise<boolean> {+ const cwd = opencodeRunner.workspace('task');+ mkdirSync(cwd, { recursive: true });+ let child: CliProcess;+ try {+ child = spawnCli(bin, ['auth', 'list', '--standalone', '--format', 'json'], {+ cwd,+ env: { ...childEnv('opencode'), ...SEALED_2, PWD: cwd, OPENCODE_DB: database2(), OPENCODE_CONFIG_CONTENT: JSON.stringify({ policies: POLICIES }) },+ });+ } catch {+ return Promise.resolve(true);+ }+ return new Promise((resolve) => {+ let output = '';+ let settled = false;+ const done = (value: boolean) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ resolve(value);+ };+ const timer = setTimeout(() => {+ stopTree(child, 'SIGKILL');+ done(true);+ }, AUTH_TIMEOUT_MS);+ timer.unref();+ child.stdout.on('data', (chunk: Buffer) => void (output += chunk.toString()));+ child.stderr.on('data', () => {});+ child.on('error', () => done(true));+ child.on('close', (code) => {+ const integrations = code === 0 ? parseJsonLine<Integration[]>(output.trim()) : null;+ if (!Array.isArray(integrations)) return done(true);+ done(integrations.some((integration) => integration.connections?.some((connection) => !connection.status || connection.status.status === 'connected')));+ });+ });+}diff --git a/src/daemon/agent/runners/types.ts b/src/daemon/agent/runners/types.tsindex 859a43f..3f1f36d 100644--- a/src/daemon/agent/runners/types.ts+++ b/src/daemon/agent/runners/types.ts@@ -57,11 +57,16 @@ export interface StreamContext {mcpTools: string[];/** The run's browser tools served in this process, for a CLI that takes tools other than over MCP. */tools: () => Promise<ToolHost>;+ /** Settles once the run's MCP server has handed its tool list to the CLI, for a CLI that does not wait for it. */+ toolsListed: () => Promise<void>;+ /** The CLI's `--version` line as last probed, for a runner whose CLI changed its flags between releases. */+ version?: string;}export interface JsonContext {prompt: string;settings: AgentSettings;+ version?: string;workspace: string;/** The prompt names a file in the workspace that the agent has to open. */reads: boolean;@@ -150,8 +155,8 @@ export interface Runner {answer(stdout: string): { text?: string; error?: string };/** Turns a stderr tail into something more useful than "exited with code 1". */hint?(stderrTail: string): string | null;- /** Anything beyond "the binary is installed" that has to be true before a run. */- check?(settings: AgentSettings): Promise<AgentProblem | null>;+ /** Anything beyond "the binary is installed" that has to be true before a run, for the `--version` line just probed. */+ check?(settings: AgentSettings, version?: string): Promise<AgentProblem | null>;/** Repairs what `check` reported, when the user asks for it. */grant?(): Promise<AgentProblem | null>;}diff --git a/src/daemon/agent/service-tools-listed.test.ts b/src/daemon/agent/service-tools-listed.test.tsnew file mode 100644index 0000000..f990207--- /dev/null+++ b/src/daemon/agent/service-tools-listed.test.ts@@ -0,0 +1,50 @@+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { afterEach, describe, expect, test, vi } from 'vitest';+import type { RunEvent } from '@/lib/actions/protocol';+import { failure } from '@/lib/actions/protocol';+import { configPath } from './config';+import { stubCli } from './runners/fixtures/support';+import { AgentSession } from './service';++// OpenCode 2 connects MCP servers in the background and fixes each step's tool list as it sends it.+describe('a turn that waits for its tools', () => {+ afterEach(() => vi.unstubAllEnvs());++ test('an OpenCode 2 turn is prompted only once its MCP server has listed the tools to it', async () => {+ vi.stubEnv('OPENCODE_API_KEY', 'zen-key');+ mkdirSync(dirname(configPath), { recursive: true });+ const heard = join(dirname(configPath), 'acp-heard.log');+ rmSync(heard, { force: true });+ const bin = stubCli(+ join(dirname(configPath), 'opencode-acp'),+ `const fs = require('node:fs');+if (process.argv[2] === '--version') { console.log('opencode v2.0.32'); process.exit(0); }+const send = (message) => process.stdout.write(JSON.stringify(message) + '\\n');+require('node:readline').createInterface({ input: process.stdin }).on('line', (line) => {+ const message = JSON.parse(line);+ fs.appendFileSync(${JSON.stringify(heard)}, message.method + '\\n');+ if (message.method === 'initialize') send({ jsonrpc: '2.0', id: message.id, result: { protocolVersion: 1 } });+ if (message.method === 'session/new') send({ jsonrpc: '2.0', id: message.id, result: { sessionId: 'ses_1', configOptions: [{ id: 'mode', currentValue: 'browsentic-contained' }] } });+ if (message.method === 'session/prompt') send({ jsonrpc: '2.0', id: message.id, result: { stopReason: 'end_turn' } });+});`,+ );+ writeFileSync(configPath, JSON.stringify({ agent: 'opencode', agents: { opencode: { bin } } }));+ const events: RunEvent[] = [];+ const waiting = new AgentSession({+ invoke: async () => failure('EXTENSION_OFFLINE', 'no browser'),+ emit: (_runId: string, event: RunEvent) => void events.push(event),+ draft: () => {},+ actionNames: () => [],+ });+ waiting.handle({ t: 'instruct', id: 'r1', text: 'what is on this page', context: { sessionId: 's1' } });+ const said = () => readFileSync(heard, 'utf8').trim().split('\n');+ await vi.waitFor(() => expect(said()).toContain('session/new'), { timeout: 10_000 });+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(said()).toEqual(['initialize', 'session/new']);++ waiting.described('r1');+ await vi.waitFor(() => expect(events.some((event) => event.kind === 'done')).toBe(true), { timeout: 5_000 });+ expect(said()).toEqual(['initialize', 'session/new', 'session/prompt']);+ }, 20_000);+});diff --git a/src/daemon/agent/service.ts b/src/daemon/agent/service.tsindex c74fd68..e8cb7fc 100644--- a/src/daemon/agent/service.ts+++ b/src/daemon/agent/service.ts@@ -109,6 +109,9 @@ interface ActiveRun {limits?: CallLimits;/** An approval still on the user's screen after its call was handed back, until the agent calls again. */parked?: Waiting;+ /** Settles when the run's MCP server first lists its tools to the agent. */+ listed: Promise<void>;+ markListed: () => void;}const FOCUS_SHOT_TOOL_NAME = toolNameFor(FOCUS_SHOT_ACTION);@@ -195,6 +198,11 @@ export class AgentSession {return this.runs.has(runId);}+ /** The run's MCP server has just been told what its tools are, which a CLI that does not wait for them needs to know. */+ described(runId: string): void {+ this.runs.get(runId)?.markListed();+ }+/*** What a run's tool list should hold. A tool the run would only be refused is left* out: its schema is re-sent on every turn, and listing it invites the call.@@ -464,6 +472,8 @@ export class AgentSession {extraHosts: config.guardrails?.hosts,pinTab: true,});+ let markListed = () => {};+ const listed = new Promise<void>((resolve) => (markListed = resolve));const run: ActiveRun = {id: runId,sessionId,@@ -480,6 +490,8 @@ export class AgentSession {approved: new Set(),scheduled: context?.task !== undefined,limits: RUNNERS[config.agent].limits,+ listed,+ markListed,};this.runs.set(runId, run);if (run.liveTools && sessionId) this.codeListed.add(sessionId);@@ -577,6 +589,8 @@ export class AgentSession {config: run.config,sessionId: resuming,mcpTools: agentRunToolNames(this.deps.actionNames()),+ toolsListed: () => run.listed,+ version: runner.version,signal: run.abort.signal,emit,});diff --git a/src/daemon/daemon.ts b/src/daemon/daemon.tsindex cb758c1..5f389bc 100644--- a/src/daemon/daemon.ts+++ b/src/daemon/daemon.ts@@ -781,7 +781,8 @@ export async function startDaemon({ version, idleExit = true, android = androidOfunction describeFor(runId: string | undefined, binding: Binding): Described {const running = runId ? [...agents].find(([, agent]) => agent.owns(runId)) : undefined;const offer = running && runId ? running[1].offerFor(runId) : null;- if (offer && running) {+ if (offer && running && runId) {+ running[1].described(runId);const withheld = (name: string) => offer.withheld.includes(name);return {tools: running[0].tools.filter(({ name }) => !withheld(name)),diff --git a/src/daemon/guardrails/spawn.test.ts b/src/daemon/guardrails/spawn.test.tsindex 2e22ad8..8457122 100644--- a/src/daemon/guardrails/spawn.test.ts+++ b/src/daemon/guardrails/spawn.test.ts@@ -8,7 +8,7 @@ import { CONTAINMENT, sealEnv, sealedAway, vetPlan, within, type SpawnMode } froconst settingsFor = (kind: AgentKind) => ({ bin: AGENTS[kind].bin });-const contextFor = (kind: AgentKind, research: boolean): StreamContext => ({+const contextFor = (kind: AgentKind, research: boolean, version?: string): StreamContext => ({runId: 'run-1',conversation: 'conversation-1',instruction: 'what does this page cost',@@ -20,11 +20,13 @@ const contextFor = (kind: AgentKind, research: boolean): StreamContext => ({mcp: mcpServerFor('run-1'),mcpTools: ['page_getPageInfo', 'page_clickElement', 'browsentic_status'],tools: () => Promise.reject(new Error('no browser tools in a containment test')),+ toolsListed: () => Promise.resolve(),+ version,});-const planOf = (kind: AgentKind, mode: SpawnMode, { research = false, reads = false } = {}): Plan => {- if (mode === 'task') return RUNNERS[kind].json({ prompt: 'summarize this', settings: settingsFor(kind), workspace: stateDir, reads });- const context = contextFor(kind, research);+const planOf = (kind: AgentKind, mode: SpawnMode, { research = false, reads = false, version = undefined as string | undefined } = {}): Plan => {+ if (mode === 'task') return RUNNERS[kind].json({ prompt: 'summarize this', settings: settingsFor(kind), version, workspace: stateDir, reads });+ const context = contextFor(kind, research, version);if (mode === 'run') return RUNNERS[kind].stream(context);const conversation = RUNNERS[kind].converse?.(context);if (!conversation) throw new Error(`${kind} holds no conversation`);@@ -493,6 +495,94 @@ describe('spawn containment', () => {expect(vetPlan('opencode', 'run', { ...opencodeRun, files: [] }, stateDir)).toHaveLength(1);});+ describe('OpenCode 2', () => {+ const version = 'opencode v2.0.32';+ const turn = planOf('opencode', 'conversation', { version });+ const fallback = planOf('opencode', 'run', { version });+ const oneShot = planOf('opencode', 'task', { version });+ interface Statement {+ action: string;+ resource: string;+ effect: string;+ }+ const agentRules = (config: Record<string, unknown>) =>+ (config.agents as Record<string, { permissions: Statement[] }>)['browsentic-contained'].permissions;++ test('its turn, the plain run it falls back to, and its one-shots are contained, on research and reading a file too', () => {+ for (const [mode, plan] of [+ ['conversation', turn],+ ['conversation', planOf('opencode', 'conversation', { version, research: true })],+ ['run', fallback],+ ['task', oneShot],+ ['task', planOf('opencode', 'task', { version, reads: true })],+ ] as const) {+ expect(vetPlan('opencode', mode, plan, stateDir)).toEqual([]);+ }+ });++ // Without it, `run` hands the turn to the user's background service, which starts with this environment if it is not running.+ test('a run without its own server is caught', () => {+ expect(vetPlan('opencode', 'run', without(fallback, '--standalone'), stateDir)).not.toEqual([]);+ expect(vetPlan('opencode', 'task', without(oneShot, '--standalone'), stateDir)).not.toEqual([]);+ });++ test('a turn whose folder is not the one OpenCode moves to is caught', () => {+ expect(vetPlan('opencode', 'conversation', withEnv(turn, 'PWD', '/'), stateDir)).toHaveLength(1);+ expect(vetPlan('opencode', 'task', withEnv(oneShot, 'PWD'), stateDir)).toHaveLength(1);+ });++ // A list keeps the deny-all where it was, so only reading the rules shows a later allow.+ test('an allow added after the deny-all, or a deny-all that went, is caught', () => {+ const shell = reconfigured(turn, (config) => void agentRules(config).push({ action: 'shell', resource: '*', effect: 'allow' }));+ expect(vetPlan('opencode', 'conversation', shell, stateDir)).toEqual([expect.stringContaining('allow shell')]);+ expect(vetPlan('opencode', 'conversation', reconfigured(turn, (config) => void agentRules(config).shift()), stateDir)).not.toEqual([]);+ });++ test('a one-shot reading anything but its scratch folder is caught', () => {+ const reads = planOf('opencode', 'task', { version, reads: true });+ const everywhere = reconfigured(reads, (config) => void (agentRules(config)[1].resource = '*'));+ expect(vetPlan('opencode', 'task', everywhere, stateDir)).toHaveLength(1);+ });++ // Code Mode lists one `execute` tool in place of the server's, and it runs a script with the network.+ test("browser tools behind Code Mode, or a one-shot given a server, are caught", () => {+ const behind = reconfigured(turn, (config) => void ((config.mcp as { servers: Record<string, { codemode?: boolean }> }).servers.browsentic.codemode = true));+ expect(vetPlan('opencode', 'conversation', behind, stateDir)).toHaveLength(1);+ const reaching = reconfigured(oneShot, (config) => void (config.mcp = { servers: { browsentic: { type: 'local' } } }));+ expect(vetPlan('opencode', 'task', reaching, stateDir)).toHaveLength(1);+ });++ test("letting the user's plugins or other MCP servers load is caught", () => {+ const plugins = reconfigured(turn, (config) => void (config.policies as Statement[]).push({ action: 'integration.use', resource: 'plugin:*', effect: 'allow' }));+ expect(vetPlan('opencode', 'conversation', plugins, stateDir)).toHaveLength(1);+ expect(vetPlan('opencode', 'conversation', reconfigured(turn, (config) => void delete config.policies), stateDir)).toHaveLength(2);+ });++ test('a session started in another agent, or shared, is caught', () => {+ expect(vetPlan('opencode', 'conversation', reconfigured(turn, (config) => void (config.default_agent = 'build')), stateDir)).toHaveLength(1);+ expect(vetPlan('opencode', 'conversation', reconfigured(turn, (config) => void (config.share = 'auto')), stateDir)).toHaveLength(1);+ });++ test('project config switched back on under either name is caught', () => {+ expect(vetPlan('opencode', 'conversation', withEnv(turn, 'OPENCODE_CONFIG_PROJECT_DISABLE', '0'), stateDir)).toHaveLength(1);+ expect(vetPlan('opencode', 'conversation', withEnv(turn, 'OPENCODE_DISABLE_PROJECT_CONFIG'), stateDir)).toHaveLength(1);+ });++ // Each line refuses the other's flags, but the vet holds a plan to one line's rules in full.+ test("one line's flags with the other line's config are caught", () => {+ const v1 = planOf('opencode', 'run');+ expect(vetPlan('opencode', 'run', { ...fallback, env: v1.env }, stateDir)).not.toEqual([]);+ expect(vetPlan('opencode', 'run', { ...v1, env: fallback.env }, stateDir)).not.toEqual([]);+ });++ test('a turn sent to another server, handed a file, or given a model it could read as a flag is caught', () => {+ expect(vetPlan('opencode', 'run', plus(fallback, '--server', 'http://127.0.0.1:4096'), stateDir)).toHaveLength(1);+ expect(vetPlan('opencode', 'run', plus(fallback, '--file', '/etc/hosts'), stateDir)).toHaveLength(1);+ expect(vetPlan('opencode', 'run', plus(fallback, '--agent=build'), stateDir)).toHaveLength(1);+ expect(vetPlan('opencode', 'run', plus(fallback, '-m', '--auto'), stateDir)).not.toEqual([]);+ });+ });+test('running outside the state dir is caught', () => {expect(vetPlan('antigravity', 'run', { ...agyRun, cwd: '/tmp/anywhere' }, stateDir)).toHaveLength(1);});diff --git a/src/daemon/guardrails/spawn.ts b/src/daemon/guardrails/spawn.tsindex 523de6d..f68af42 100644--- a/src/daemon/guardrails/spawn.ts+++ b/src/daemon/guardrails/spawn.ts@@ -86,8 +86,15 @@ interface Requirements {readonly fileContains?: Readonly<Record<string, readonly string[]>>;/** The only set-up commands the plan may run before its turn, each exactly as written here. */readonly prepare?: readonly (readonly string[])[];+ /** Variables that must name the plan's own working directory, for a CLI that moves to one before using its cwd. */+ readonly envIsCwd?: readonly string[];+ /** What this shape cannot say, read out of the plan itself: each answer is a clause the label goes in front of. */+ readonly inspect?: (plan: SpawnPlan) => string[];}+/** One way of being contained, or several a CLI's releases each need, of which a plan has to meet one in full. */+type Rules = Requirements | readonly Requirements[];+interface Containment {readonly localTools: LocalTools;/** Env prefixes this agent needs to authenticate, kept when the rest is sealed. */@@ -105,10 +112,10 @@ interface Containment {readonly forbidden?: readonly RegExp[];/** Why this runner is only as contained as it is. Logged once per run. */readonly note: string;- readonly run: Requirements;- readonly task: Requirements;+ readonly run: Rules;+ readonly task: Rules;/** Only a runner that holds conversations has these; any other refuses to start one. */- readonly conversation?: Requirements;+ readonly conversation?: Rules;}/**@@ -160,6 +167,96 @@ const OPENCODE_SEALED = { OPENCODE_DISABLE_PROJECT_CONFIG: '1', OPENCODE_DISABLE/** The ruleset that denies every tool not named after it, and the switch that keeps a session off opncd.ai. */const OPENCODE_CONFIG = ['"*":"deny"', '"share":"disabled"'];+/**+ * OpenCode 2 renamed the project switch, keeping the old name only as a fallback the new one overrides+ * when set at all, and reads a global config folder `OPENCODE_DISABLE_PROJECT_CONFIG` never reaches.+ */+const OPENCODE2_SEALED = {+ OPENCODE_CONFIG_PROJECT_DISABLE: '1',+ OPENCODE_DISABLE_PROJECT_CONFIG: '1',+ OPENCODE_DISABLE_CLAUDE_CODE: '1',+ OPENCODE_DISABLE_AUTOUPDATE: '1',+};++const OPENCODE_AGENT = 'browsentic-contained';++const OPENCODE_WEB = ['webfetch', 'websearch'];++interface OpenCodeStatement {+ action?: unknown;+ resource?: unknown;+ effect?: unknown;+}++interface OpenCode2Config {+ share?: unknown;+ default_agent?: unknown;+ policies?: OpenCodeStatement[];+ agents?: Record<string, { permissions?: OpenCodeStatement[] } | undefined>;+ mcp?: { servers?: Record<string, { codemode?: unknown } | undefined> };+}++/**+ * OpenCode 2's config read rather than searched: its rules are a list, where an allow added after the+ * deny would sit beside it and still match. A run's agent opens on denying everything and then allows+ * the browser's tools, the web's on research, and a one-shot's scratch reads, nothing else; the+ * browser's server is the only one and lists its tools directly, outside Code Mode's `execute`; and+ * policies keep the user's plugins and other MCP servers from loading at all.+ */+const openCode2 =+ (mode: SpawnMode) =>+ (plan: SpawnPlan): string[] => {+ let config: OpenCode2Config;+ try {+ config = JSON.parse(plan.env?.OPENCODE_CONFIG_CONTENT ?? '') as OpenCode2Config;+ } catch {+ return ['is spawned without a readable OPENCODE_CONFIG_CONTENT'];+ }+ const problems: string[] = [];+ if (config.share !== 'disabled') problems.push('is spawned with sharing left on');+ if (mode === 'conversation' && config.default_agent !== OPENCODE_AGENT) problems.push(`starts its sessions in an agent other than ${OPENCODE_AGENT}`);++ const [first, ...rest] = config.agents?.[OPENCODE_AGENT]?.permissions ?? [];+ if (first?.action !== '*' || first.resource !== '*' || first.effect !== 'deny') {+ problems.push(`gives ${OPENCODE_AGENT} rules that do not open on denying everything`);+ }+ const mayAllow = ({ action, resource }: OpenCodeStatement) =>+ mode === 'task'+ ? action === 'read' && typeof resource === 'string' && resource !== '*'+ : typeof action === 'string' && (action.startsWith('browsentic_') || OPENCODE_WEB.includes(action));+ for (const rule of rest) {+ if (rule.effect !== 'deny' && !mayAllow(rule)) problems.push(`lets ${OPENCODE_AGENT} ${String(rule.effect)} ${String(rule.action)} on ${String(rule.resource)}`);+ }++ const servers = config.mcp?.servers ?? {};+ if (mode === 'task' && Object.keys(servers).length) problems.push('gives a one-shot an MCP server');+ if (mode !== 'task' && (Object.keys(servers).join() !== 'browsentic' || servers.browsentic?.codemode !== false)) {+ problems.push("serves the browser's tools other than directly, from its one server");+ }++ const policies = config.policies ?? [];+ for (const resource of ['plugin:*', 'mcp:*']) {+ const last = policies.filter((policy) => policy.action === 'integration.use' && policy.resource === resource).at(-1);+ if (last?.effect !== 'deny') problems.push(`does not keep ${resource} from loading`);+ }+ return problems;+ };++const openCode2Rules = (mode: SpawnMode): Requirements => ({+ required: mode === 'conversation' ? ['acp'] : ['--standalone'],+ pairs:+ mode === 'conversation'+ ? []+ : [+ ['--agent', OPENCODE_AGENT],+ ['--format', 'json'],+ ],+ env: OPENCODE2_SEALED,+ envIsCwd: ['PWD'],+ inspect: openCode2(mode),+ files: mode === 'task' ? [] : ['instructions.md'],+});+export const CONTAINMENT: Record<AgentKind, Containment> = {claude: {localTools: 'allowlist',@@ -378,35 +475,43 @@ export const CONTAINMENT: Record<AgentKind, Containment> = {localTools: 'allowlist',// A key in ANTHROPIC_* or OPENAI_* would be one of a dozen providers OpenCode reads; `opencode auth login` keeps them in a file.keepsEnv: ['OPENCODE_'],- // `--auto` approves whatever is not denied, `--attach` runs the turn in a server started with someone- // else's config, `--dir` moves it out of the workspace, and `--share` publishes it.- forbidden: [/^--auto$/i, /^--attach/i, /^--dir/i, /^--share$/i],+ // `--auto` approves whatever is not denied, `--attach` and `--server` run the turn in a server started with someone+ // else's config, `--dir` moves it out of the workspace, `--share` publishes it, and `--file` hands the model a file.+ forbidden: [/^--auto$/i, /^--attach/i, /^--server/i, /^--dir/i, /^--share$/i, /^--file/i, /^--(agent|format|model)=/i],note:- 'a per-run permission ruleset opening on "*": "deny", which OpenCode applies after the user’s own rules, ' ++ 'a per-run permission ruleset opening on denying everything, which OpenCode applies after the user’s own rules, ' +'so the model is offered no tool that was not named — built-in, custom, or another MCP server’s; ' +- 'external plugins and project config stay off, but MCP servers the user gave OpenCode itself still start, with their tools hidden',- run: {- // Plugins run inside OpenCode and can add tools or answer its permission prompts.- required: ['--pure'],- pairs: [- ['--agent', 'browsentic-contained'],- ['--format', 'json'],- ],- env: OPENCODE_SEALED,- envContains: { OPENCODE_CONFIG_CONTENT: OPENCODE_CONFIG },- files: ['instructions.md'],- },- task: {- required: ['--pure'],- pairs: [- ['--agent', 'browsentic-contained'],- ['--format', 'json'],- ],- env: OPENCODE_SEALED,- // An empty map adds no server of ours, so a one-shot has no way to the browser.- envContains: { OPENCODE_CONFIG_CONTENT: [...OPENCODE_CONFIG, '"mcp":{}'] },- files: [],- },+ 'on 1.x external plugins and project config stay off, but MCP servers the user gave OpenCode itself still start, with their tools hidden; ' ++ 'on 2.x a policy keeps the user’s plugins and other MCP servers from loading, though one in their global or managed config outranks it',+ run: [+ {+ // Plugins run inside OpenCode and can add tools or answer its permission prompts.+ required: ['--pure'],+ pairs: [+ ['--agent', OPENCODE_AGENT],+ ['--format', 'json'],+ ],+ env: OPENCODE_SEALED,+ envContains: { OPENCODE_CONFIG_CONTENT: OPENCODE_CONFIG },+ files: ['instructions.md'],+ },+ openCode2Rules('run'),+ ],+ task: [+ {+ required: ['--pure'],+ pairs: [+ ['--agent', OPENCODE_AGENT],+ ['--format', 'json'],+ ],+ env: OPENCODE_SEALED,+ // An empty map adds no server of ours, so a one-shot has no way to the browser.+ envContains: { OPENCODE_CONFIG_CONTENT: [...OPENCODE_CONFIG, '"mcp":{}'] },+ files: [],+ },+ openCode2Rules('task'),+ ],+ conversation: openCode2Rules('conversation'),},};@@ -419,6 +524,30 @@ export function vetPlan(kind: AgentKind, mode: SpawnMode, plan: SpawnPlan, home:const rules = CONTAINMENT[kind][mode];const label = `${AGENTS[kind].label} (${mode})`;if (!rules) return [`${label} has no containment written for it.`];+ // A plan meets one way of being contained in full, or is held to the way it came closest to.+ const shortfalls = alternativesOf(rules).map((alternative) => unmet(alternative, plan, label));+ const problems = [...(shortfalls.find((shortfall) => shortfall.length === 0) ?? shortfalls.reduce((a, b) => (b.length < a.length ? b : a)))];++ const banned = [...FORBIDDEN, ...(CONTAINMENT[kind].forbidden ?? [])];+ for (const arg of plan.args) {+ if (banned.some((pattern) => pattern.test(arg))) {+ problems.push(`${label} is spawned with ${arg}, which disables its own containment.`);+ }+ }++ for (const model of [...everyValueOf(plan.args, '--model'), ...everyValueOf(plan.args, '-m')]) {+ if (!isModelId(model)) problems.push(`${label} is spawned with the model ${JSON.stringify(model)}, which it could read as a flag.`);+ }++ if (!within(plan.cwd, home)) problems.push(`${label} would run in ${plan.cwd}, which is outside ${home}.`);++ return problems;+}++const alternativesOf = (rules: Rules): readonly Requirements[] => ('required' in rules ? [rules] : rules);++/** What a plan lacks of one way of being contained. */+function unmet(rules: Requirements, plan: SpawnPlan, label: string): string[] {const problems: string[] = [];for (const arg of rules.required) {@@ -449,6 +578,10 @@ export function vetPlan(kind: AgentKind, mode: SpawnMode, plan: SpawnPlan, home:if (plan.env?.[name] !== value) problems.push(`${label} is spawned without ${name}=${value}.`);}+ for (const name of rules.envIsCwd ?? []) {+ if (plan.env?.[name] !== plan.cwd) problems.push(`${label} is spawned with a ${name} other than the folder it runs in.`);+ }+for (const [name, needles] of Object.entries(rules.envContains ?? {})) {const missing = needles.filter((needle) => !plan.env?.[name]?.includes(needle));if (missing.length) problems.push(`${label} is spawned with a ${name} missing ${missing.join(', ')}.`);@@ -474,18 +607,7 @@ export function vetPlan(kind: AgentKind, mode: SpawnMode, plan: SpawnPlan, home:if (!allowed) problems.push(`${label} would run "${command.join(' ')}" before its turn, which is not a set-up step it is allowed.`);}- const banned = [...FORBIDDEN, ...(CONTAINMENT[kind].forbidden ?? [])];- for (const arg of plan.args) {- if (banned.some((pattern) => pattern.test(arg))) {- problems.push(`${label} is spawned with ${arg}, which disables its own containment.`);- }- }-- for (const model of everyValueOf(plan.args, '--model')) {- if (!isModelId(model)) problems.push(`${label} is spawned with the model ${JSON.stringify(model)}, which it could read as a flag.`);- }-- if (!within(plan.cwd, home)) problems.push(`${label} would run in ${plan.cwd}, which is outside ${home}.`);+ for (const clause of rules.inspect?.(plan) ?? []) problems.push(`${label} ${clause}.`);return problems;}