opencode-claude-code-acpbridge 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +314 -191
  2. package/LICENSE +21 -0
  3. package/README.md +596 -279
  4. package/dist/acp/claude-config.d.ts +52 -0
  5. package/dist/acp/claude-config.d.ts.map +1 -1
  6. package/dist/acp/claude-config.js +6 -2
  7. package/dist/acp/claude-config.js.map +1 -1
  8. package/dist/acp/mcp-host.d.ts +10 -0
  9. package/dist/acp/mcp-host.d.ts.map +1 -1
  10. package/dist/acp/mcp-host.js +17 -4
  11. package/dist/acp/mcp-host.js.map +1 -1
  12. package/dist/acp/mcp-runtime.js +21 -4
  13. package/dist/acp/mcp-runtime.js.map +1 -1
  14. package/dist/log.d.ts +11 -0
  15. package/dist/log.d.ts.map +1 -0
  16. package/dist/log.js +50 -0
  17. package/dist/log.js.map +1 -0
  18. package/dist/plugin/compat.d.ts +14 -0
  19. package/dist/plugin/compat.d.ts.map +1 -0
  20. package/dist/plugin/compat.js +45 -0
  21. package/dist/plugin/compat.js.map +1 -0
  22. package/dist/plugin/index.d.ts +3 -0
  23. package/dist/plugin/index.d.ts.map +1 -1
  24. package/dist/plugin/index.js +80 -14
  25. package/dist/plugin/index.js.map +1 -1
  26. package/dist/plugin/sessions.d.ts +11 -8
  27. package/dist/plugin/sessions.d.ts.map +1 -1
  28. package/dist/plugin/sessions.js +37 -4
  29. package/dist/plugin/sessions.js.map +1 -1
  30. package/dist/provider/factory.d.ts.map +1 -1
  31. package/dist/provider/factory.js +5 -3
  32. package/dist/provider/factory.js.map +1 -1
  33. package/dist/provider/history.d.ts +44 -0
  34. package/dist/provider/history.d.ts.map +1 -0
  35. package/dist/provider/history.js +145 -0
  36. package/dist/provider/history.js.map +1 -0
  37. package/dist/provider/model.d.ts +160 -23
  38. package/dist/provider/model.d.ts.map +1 -1
  39. package/dist/provider/model.js +1373 -480
  40. package/dist/provider/model.js.map +1 -1
  41. package/dist/provider/recorder.d.ts +5 -0
  42. package/dist/provider/recorder.d.ts.map +1 -0
  43. package/dist/provider/recorder.js +63 -0
  44. package/dist/provider/recorder.js.map +1 -0
  45. package/docs/DEVELOPMENT.md +413 -127
  46. package/examples/01-minimal.jsonc +12 -9
  47. package/examples/02-per-agent-permissions.jsonc +39 -0
  48. package/examples/03-opencode-fidelity.jsonc +21 -0
  49. package/examples/04-model-and-effort.jsonc +35 -0
  50. package/examples/05-custom-agents.jsonc +32 -0
  51. package/examples/06-claude-ecosystem.jsonc +28 -0
  52. package/examples/07-manual-provider.jsonc +55 -0
  53. package/examples/08-permission-bridge.jsonc +42 -0
  54. package/examples/README.md +35 -17
  55. package/package.json +35 -29
  56. package/examples/02-permisos-por-agente.jsonc +0 -34
  57. package/examples/03-fidelidad-opencode.jsonc +0 -21
  58. package/examples/04-modelo-y-esfuerzo.jsonc +0 -36
  59. package/examples/05-agentes-personalizados.jsonc +0 -29
  60. package/examples/06-ecosistema-claude.jsonc +0 -24
  61. package/examples/07-provider-manual.jsonc +0 -42
  62. package/examples/08-puente-permisos.jsonc +0 -50
package/README.md CHANGED
@@ -1,68 +1,124 @@
1
1
  # opencode-claude-code-acpbridge
2
2
 
3
- Plugin **exclusivo para usar [Claude Code](https://www.anthropic.com/claude-code) dentro de [OpenCode](https://opencode.ai)**. Es a la vez **provider de modelos** y **plugin**, y su backend es un **cliente ACP** ([Agent Client Protocol](https://agentclientprotocol.com)) que habla con `claude-agent-acp`. Claude Code aparece como un modelo más en OpenCode, ejecutándose con **tu suscripción de Claude**, y **OpenCode queda como orquestador**: el agente solo razona y **OpenCode ejecuta las herramientas** con sus permisos y su TUI.
3
+ **Use [Claude Code](https://www.anthropic.com/claude-code) inside [OpenCode](https://opencode.ai)**, on your Claude
4
+ subscription. Claude Code becomes one more model in OpenCode; Claude does the thinking, and
5
+ **OpenCode stays in charge**: it runs the tools, with its own permissions and TUI.
6
+
7
+ > [!IMPORTANT]
8
+ > **OpenCode V2 only.**
9
+ > - **Requires OpenCode ≥ 2.0.14.** This package uses the V2 plugin runtime: `Plugin.define`,
10
+ > the `plugins[]` config list and the `provider.transform` / `agent.transform` /
11
+ > `session.hook` APIs.
12
+ > - **Does not load in OpenCode V1.** For V1, stay on `0.8.x` (see
13
+ > [Upgrading from 0.8.x](#upgrading-from-08x-opencode-v1)).
14
+ > - **Tested with:**
15
+ > - OpenCode 2.1.1;
16
+ > - `@agentclientprotocol/claude-agent-acp` 0.31.x;
17
+ > - Claude Code CLI 2.1.119.
18
+ >
19
+ > Check your version with `opencode --version`.
20
+
21
+ One npm package registers itself both as an OpenCode **plugin** (`default Plugin.define(...)`)
22
+ and as a **model provider** (`createACPModelProvider`).
4
23
 
5
- > Un único paquete npm que se registra a la vez como **provider** (`createACPModelProvider`) y como **plugin** (`default Plugin.define({ id, setup })`, API V2) de OpenCode.
24
+ ---
6
25
 
7
- **Atajos:** [Inicio rápido](#configuración-en-opencode) · [Agentes](#agentes-claude-code-modos-esfuerzo-subagentes) · [Facturación](#system-prompt-y-facturación-suscripción-vs-extra-usage) · [Diagnóstico](#diagnóstico) · [Ejemplos de config](examples/) · [Desarrollo](docs/DEVELOPMENT.md) · [Cambios](CHANGELOG.md)
26
+ ## Contents
27
+
28
+ - [What is this, in plain words](#what-is-this-in-plain-words)
29
+ - [Requirements](#requirements)
30
+ - [Install](#install)
31
+ - [Update / reinstall](#update--reinstall)
32
+ - [First use: agents, models and effort](#first-use-agents-models-and-effort)
33
+ - [Billing: subscription vs extra usage](#billing-subscription-vs-extra-usage)
34
+ - [Configuration reference](#configuration-reference)
35
+ - [Agents and subagents](#agents-and-subagents)
36
+ - [Tools and the permission bridge](#tools-and-the-permission-bridge)
37
+ - [Switching models mid-session, and token cost](#switching-models-mid-session-and-token-cost)
38
+ - [Images, PDFs and other attachments](#images-pdfs-and-other-attachments)
39
+ - [Resuming a session in Claude Code](#resuming-a-session-in-claude-code)
40
+ - [Diagnostics and troubleshooting](#diagnostics-and-troubleshooting)
41
+ - [Status and limitations](#status-and-limitations)
42
+ - [Upgrading from 0.8.x (OpenCode V1)](#upgrading-from-08x-opencode-v1)
43
+ - [Development](#development)
44
+ - [License](#license)
8
45
 
9
46
  ---
10
47
 
11
- ## Cómo funciona
48
+ ## What is this, in plain words
49
+
50
+ | Term | What it means here |
51
+ | --- | --- |
52
+ | **OpenCode** | An open-source coding agent with a TUI, a desktop app and a CLI. They all talk to a local OpenCode **server**. |
53
+ | **Plugin** | A package the OpenCode server loads to add features. You list plugins in `opencode.json`, and OpenCode installs them from npm. |
54
+ | **Provider / model** | Where OpenCode sends prompts, e.g. `anthropic/claude-…`. This package adds a provider, `acp`, whose models (`acp/default`, `acp/sonnet`, …) are served by Claude Code. |
55
+ | **Agent** | A configured assistant in OpenCode (`build`, `plan`, …). This package adds two: `claude-code` and `claude-code-plan`. |
56
+ | **Tool** | Something the model can call: `read`, `edit`, `bash`, MCP tools… |
57
+ | **Claude Code** | Anthropic's coding agent (the `claude` CLI). Running through it keeps usage on your Pro/Max **subscription**. |
58
+ | **ACP** | The [Agent Client Protocol](https://agentclientprotocol.com), a standard way for an editor or client to drive a coding agent. |
59
+ | **`claude-agent-acp`** | The ACP adapter for Claude Code (`@agentclientprotocol/claude-agent-acp`). This package starts it and talks ACP to it. |
60
+
61
+ ### How it works
62
+
63
+ OpenCode talks to the provider through the Vercel AI SDK `LanguageModelV3` interface. The
64
+ provider then:
65
+ 1. starts `claude-agent-acp`;
66
+ 2. **turns off Claude Code's own built-in tools**;
67
+ 3. hands Claude **OpenCode's tools** instead, through a small internal MCP server.
12
68
 
13
- OpenCode habla con el provider por el interfaz `LanguageModelV3` del Vercel AI SDK. El provider spawnea el agente ACP, le **deshabilita sus herramientas nativas** y le expone **las herramientas de OpenCode** a través de un MCP server sintético. Cuando el agente llama una herramienta, el provider devuelve el control a OpenCode, que la ejecuta y reinyecta el resultado.
69
+ When Claude calls a tool, the provider hands control back to OpenCode. OpenCode runs the tool
70
+ (asking for permission if its rules say so) and sends the result back to Claude.
14
71
 
15
72
  ```
16
- OpenCode (orquestador) opencode-claude-code-acpbridge claude-agent-acp (agente)
17
- prompt + tools(read,bash,…) ─► doStream ─► sesión ACP (tools nativas OFF) ─► Claude razona
18
- + MCP server con las tools de OC ─►
19
- ◄──── tool-call (read) ────── finish(tool-calls) ◄── el agente llama read (MCP, diferido)
20
- ejecuta read (permiso+TUI)
21
- tool-result ──────────────► doStream ─► resuelve el tools/call diferido ──► el agente continúa
22
- ◄──── texto final ───────── finish(stop) ◄── end_turn
73
+ OpenCode (orchestrator) opencode-claude-code-acpbridge claude-agent-acp (agent)
74
+ prompt + tools (read, bash, …) ─► doStream ─► ACP session (native tools OFF) ─► Claude reasons
75
+ + MCP server with OpenCode's tools ─►
76
+ ◄──── tool-call (read) ─────── finish(tool-calls) ◄── agent calls read (MCP, deferred)
77
+ runs read (permissions + TUI)
78
+ tool-result ──────────────────► doStream ─► resolves the deferred tools/call ──► agent continues
79
+ ◄──── final text ───────────── finish(stop) ◄── end_turn
23
80
  ```
24
81
 
25
- Puntos clave:
26
-
27
- - **OpenCode ejecuta las herramientas** (nativas: `read`/`write`/`bash`/`edit`/… y las de los **MCP servers que tengas configurados en OpenCode**), con su sistema de permisos.
28
- - El agente arranca como **"cerebro limpio"**: sin sus herramientas nativas, sin los skills/hooks/agents/plugins/MCP de tu `~/.claude`, y sin los **connectors de tu cuenta claude.ai** (Gmail, Drive, Supabase…, vía `strictMcpConfig`).
29
- - **Sesión ACP persistente por conversación**: tras el primer turno se envía solo el último mensaje del usuario, así el agente reaprovecha el **prompt cache** de Claude Code y no re-procesa el historial.
82
+ - **OpenCode runs the tools**, with its permission system:
83
+ - its own (`read`, `write`, `bash`, `edit`, …);
84
+ - those of the **MCP servers configured in OpenCode**.
85
+ - **Claude starts with a "clean brain"**: none of its built-in tools, and none of the skills,
86
+ hooks, agents, plugins or MCP servers in your `~/.claude`. It also gets none of the
87
+ **connectors of your claude.ai account** (Gmail, Drive, …), thanks to `strictMcpConfig`. The
88
+ injected agents switch some native capabilities back on; see
89
+ [Tools and the permission bridge](#tools-and-the-permission-bridge).
90
+ - **One persistent Claude Code session per conversation.** After the first turn, only what
91
+ Claude hasn't seen yet is sent, so Claude Code's **prompt cache** is reused instead of
92
+ re-reading the whole history every turn.
30
93
 
31
94
  ---
32
95
 
33
- ## Requisitos
96
+ ## Requirements
97
+
98
+ | Requirement | Notes |
99
+ | --- | --- |
100
+ | **OpenCode V2 ≥ 2.0.14** | V1 is not supported by this version, see the banner above. |
101
+ | **The ACP agent** | `claude-agent-acp`, from `npm i -g @agentclientprotocol/claude-agent-acp`, on your `PATH`. The plugin runs whatever you put in `command`; the older names `claude-code-acp` / `@zed-industries/claude-agent-acp` also work. |
102
+ | **Claude Code CLI** | `claude` installed and **logged in**: run `claude` once and log in. The provider finds it with `command -v claude`. Set `claudeExecutable` if it isn't on the `PATH`. |
103
+ | **Node.js** | The internal MCP server runs with `node`, which must be on the `PATH`. Override it with `ACP_RUNTIME_NODE`. |
34
104
 
35
- | Requisito | Notas |
36
- |---|---|
37
- | **OpenCode** | V2 (`>= 2.0.14`). **0.9.x solo para OpenCode V2 — en V1 usa 0.8.x.** API de plugins `Plugin.define`, `plugins[]` en config, hooks `provider.transform`/`agent.transform`/`session.hook("context")`. |
38
- | **El agente ACP** | `@agentclientprotocol/claude-agent-acp` (binario `claude-agent-acp`) en el `PATH`. También sirve `claude-code-acp` / `@zed-industries/claude-agent-acp`. |
39
- | **Claude Code CLI** | El binario `claude` instalado y **autenticado** (`claude` lee `~/.claude/.credentials.json`). El provider lo detecta con `command -v claude`. |
40
- | **Node** | El runtime del MCP server interno se ejecuta con `node` (debe estar en el `PATH`). |
105
+ You do **not** `npm install` this package yourself: OpenCode installs plugins listed in its
106
+ config.
41
107
 
42
108
  ---
43
109
 
44
- ## Instalación
110
+ ## Install
45
111
 
46
112
  ```bash
47
- # 1. El agente ACP (una vez)
113
+ # 1. The ACP agent (once)
48
114
  npm i -g @agentclientprotocol/claude-agent-acp
49
- # y autentica Claude Code si no lo está:
50
- claude # (login interactivo)
51
-
52
- # 2. Este provider
53
- npm i opencode-claude-code-acpbridge
54
- # o, en desarrollo, apúntalo por ruta (ver nota abajo)
115
+ # 2. Log in to Claude Code if you haven't yet
116
+ claude
55
117
  ```
56
118
 
57
- ---
58
-
59
- ## Configuración en OpenCode
60
-
61
- La config de proyecto de OpenCode V2 va en **`<proyecto>/.opencode/opencode.json`** (V2 la descubre solo, subiendo desde el directorio de trabajo; también acepta `opencode.jsonc` en la raíz del proyecto y `.claude`/`.agents`).
62
-
63
- ### Recomendado: auto-registro (config mínima)
64
-
65
- Lista **solo el plugin** con las opciones del agente. Al iniciar, el plugin **descubre los modelos del agente** (con una conexión ACP efímera), rellena su metadata (coste, límites, modalidades) desde [models.dev](https://models.dev) e **inyecta el provider `acp` en runtime** (`provider.transform`):
119
+ 3. Add the plugin to your OpenCode config:
120
+ - global: `~/.config/opencode/opencode.json`;
121
+ - project: `opencode.json` or `.opencode/opencode.json` at the project root.
66
122
 
67
123
  ```jsonc
68
124
  {
@@ -73,177 +129,256 @@ Lista **solo el plugin** con las opciones del agente. Al iniciar, el plugin **de
73
129
  }
74
130
  ```
75
131
 
76
- > **Desarrollo local**: si `package` es una **ruta a un directorio** (repo clonado), OpenCode resuelve el entrypoint como `<dir>/index.*` — por eso la raíz del repo tiene un `index.js` que re-exporta `dist/` (compila antes con `npm run build`). Un destino de fichero (`…/dist/index.js`) está **rechazado** por V2 (solo admite directorios para plugins configurados).
132
+ 4. Restart OpenCode: close and reopen the app, or run `opencode service restart`.
77
133
 
78
- Con eso aparecen `acp/sonnet`, `acp/haiku`, etc. en el selector, ya poblados con contexto/coste/modalidades. **Tú mantienes el control total del agente** mediante esas mismas opciones del plugin (la tabla de abajo: `args`, `cwd`, `env`, `claudeExecutable`, `streamCloseTimeoutMs`, `claudeCode`…). El plugin solo auto-genera la **lista de modelos y su metadata**; no impone nada más.
134
+ On start, the plugin **asks the agent which models it offers**, using a short-lived ACP
135
+ connection. It fills in their metadata (context, cost, modalities) from
136
+ [models.dev](https://models.dev) and **registers the `acp` provider** at runtime. You'll see
137
+ `acp/default`, `acp/sonnet`, `acp/haiku`… in the model picker, and the agents `claude-code` and
138
+ `claude-code-plan` in the agent picker. Check from a terminal with `opencode models | grep acp/`.
79
139
 
80
- - El descubrimiento se **cachea** (~1 h) en `~/.acp-model-provider/`; solo el primer arranque (o tras expirar) gasta los ~3-5 s de spawn del agente.
81
- - La metadata sale del **mismo catálogo que usa OpenCode** (`~/.cache/opencode/models.json`, con `https://models.dev/api.json` como fallback). Los costes son informativos.
82
- - Opciones extra del plugin: `providerId` (por defecto `acp`) y `name`. Si ya declaras `provider.<id>` a mano, el plugin **lo respeta y no lo toca**.
83
- - Refresca tras un cambio de modelos con `npx opencode-claude-code-acpbridge sync` (ver [Diagnóstico](#diagnóstico)).
140
+ - **Discovery is cached for 1 hour** in `~/.acp-model-provider/`. Only the first start (or the
141
+ first after the cache expires) pays the 3–5 s it takes to start the agent. Force a refresh
142
+ with `npx opencode-claude-code-acpbridge sync claude-agent-acp`.
143
+ - **Metadata** comes from the same catalogue OpenCode uses, `~/.cache/opencode/models.json`,
144
+ falling back to `https://models.dev/api.json`. Costs are informational.
145
+ - **Your own provider entry wins.** If you already declare a provider with the same id
146
+ yourself, the plugin leaves it alone.
84
147
 
85
- ### Manual (avanzado / override)
148
+ ---
86
149
 
87
- Sin `command` (ni `ACP_COMMAND`) el plugin **no auto-registra** nada: queda para cuando quieras declarar el provider tú mismo con la config `provider` de V2 (el plugin no lo toca):
150
+ ## Update / reinstall
88
151
 
89
- ```jsonc
90
- {
91
- "$schema": "https://opencode.ai/config.json",
92
- "plugins": [{ "package": "opencode-claude-code-acpbridge" }],
93
- "provider": {
94
- "acp": {
95
- "npm": "opencode-claude-code-acpbridge",
96
- "name": "Claude Code (ACP)",
97
- "options": { "command": "claude-agent-acp" },
98
- "models": { "sonnet": { "id": "sonnet", "tool_call": true, "reasoning": true } }
99
- }
100
- }
101
- }
102
- ```
152
+ OpenCode caches installed plugins and **does not refresh them on its own**. In OpenCode 2.1,
153
+ `opencode plugin update` only handles TUI plugins, so to move to a new version:
103
154
 
104
- En desarrollo, apunta por ruta de directorio: `"package": "/ruta/a/acp-model-provider"` en `plugins` (ver nota arriba sobre `index.js`).
155
+ 1. Stop OpenCode (close the app, or `opencode service stop`).
156
+ 2. `rm -rf ~/.cache/opencode/npm/opencode-claude-code-acpbridge@*`
157
+ 3. Start OpenCode again. It installs the latest version.
105
158
 
106
- En V2 los permisos de tool son un **ruleset** por agente (`agents.<n>.permissions`, por eso los agentes inyectados llevan `question: allow`); p. ej. `"permissions": [{ "action": "edit", "resource": "*", "effect": "allow" }]`.
159
+ The first request after that can take a few extra seconds while the package installs.
107
160
 
108
- ### Cambiar el `providerID` (p. ej. para opencode-quota)
161
+ ---
109
162
 
110
- Por defecto el provider se registra como **`acp`**. Si necesitas otro ID —típicamente **`anthropic`** para que [opencode-quota](https://www.npmjs.com/package/@slkiser/opencode-quota) detecte y muestre la cuota de tu **suscripción**— pásalo en las opciones del **plugin** (no declares un provider a mano, así evitas un doble backend):
163
+ ## First use: agents, models and effort
111
164
 
112
- ```jsonc
113
- "plugins": [
114
- { "package": "opencode-claude-code-acpbridge",
115
- "options": { "command": "claude-agent-acp", "providerId": "anthropic" } }
116
- ]
117
- ```
165
+ Pick the **`claude-code`** agent (or `claude-code-plan`) in OpenCode, or choose an `acp/…` model
166
+ for any agent.
118
167
 
119
- Así el **auto-registro, el resume, el puente de permisos y los agentes** (`claude-code` → `anthropic/default`) usan ese ID de forma **coherente y con un solo backend**.
168
+ **Models.** The list comes from **your account**, not from this package: it's whatever the
169
+ agent reports. At the time of writing, on a Max account:
120
170
 
121
- > ⚠️ Usar `"anthropic"` **sobrescribe el provider oficial de Anthropic** de OpenCode. Es seguro **si no usas la API directa de Anthropic** (consumes de la suscripción vía ACP). A vigilar: OpenCode puede listar modelos "fantasma" de models.dev en el selector (usa solo `anthropic/default` y `anthropic/sonnet`); si algún día quieres la API directa, quita el `providerId`.
171
+ | Model | What it is |
172
+ | --- | --- |
173
+ | `acp/default` | Claude Code's default, recommended model (Opus) |
174
+ | `acp/sonnet` | Sonnet |
175
+ | `acp/haiku` | Haiku |
176
+ | `acp/sonnet[1m]` | Sonnet with a 1M-token context window, labelled "· extra usage": Anthropic bills the 1M window outside the subscription |
122
177
 
123
- ### De 0.8.x (V1) a 0.9.x (V2)
178
+ - `opus` works through `claudeCode.model` even though discovery doesn't list it.
179
+ - You can also use full ids such as `claude-sonnet-4-6`.
124
180
 
125
- 1. **Config del plugin**: `"plugin": [[pkg, {opts}]]` → `"plugins": [{ "package": pkg, "options": {…} }]`. Si declarabas `provider.acp` a mano, quítalo: el plugin lo auto-registra en runtime.
126
- 2. **Agentes**: la sección `agent:` pasa a `agents:`; `permission` (mapa) → `permissions` (ruleset: `[{ "action": "Bash", "resource": "git *", "effect": "allow" }]`); `disable` → `disabled`.
127
- 3. **Variantes**: `acp/opus:low` → `acp/opus#low` (sintaxis V2 `provider/model#variant`).
128
- 4. **Options por agente** (mode/effort/native*): de `agent.<n>.options` → `plugins[0].options.agents.<n>.options`.
129
- 5. **Quita `claude_permission`**: esa meta-tool ya no existe; el puente de permisos emite tool-calls de la tool `question` de OpenCode. Si tenías reglas `permission` para el puente, trasládalas a `agents.<n>.permissions` (el puente las evalúa fail-closed).
130
- 6. **`package` = directorio con build** en desarrollo: apunta a la ruta del repo (con `index.js` raíz que re-exporta `dist/`), no a un fichero — V2 rechaza ficheros. Compila con `npm run build`.
131
- 7. **CLI**: `opencode run` sin `-m` ignora `agent.model`; usa `opencode run -m acp/…`.
132
- 8. **Requisitos**: OpenCode `>= 2.0.14` y agente `@agentclientprotocol/claude-agent-acp`.
181
+ **All models share one agent process.** The model is applied per session with
182
+ `session/set_model`, so switching `opus` → `sonnet` mid-conversation keeps the session: no
183
+ replay, no new process.
133
184
 
134
- Detalle completo en [CHANGELOG 0.9.0](CHANGELOG.md#090--opencode-v2-2026-10-01) y plan del port en [MIGRATION_V2.md](MIGRATION_V2.md).
185
+ **Effort** (how hard Claude thinks) is exposed as model **variants**: `acp/sonnet#low` …
186
+ `#medium`, `#high`, `#xhigh`, `#max` (V2 syntax `provider/model#variant`). Pick one in the TUI,
187
+ or set it per agent (see [Agents and subagents](#agents-and-subagents)) or for the whole
188
+ provider:
135
189
 
136
- ---
190
+ ```jsonc
191
+ "options": { "command": "claude-agent-acp",
192
+ "claudeCode": { "model": "sonnet", "effort": "xhigh", "thinking": { "type": "enabled", "budgetTokens": 16000 } } }
193
+ ```
137
194
 
138
- ## Opciones del provider (`options`)
139
-
140
- Todas se resuelven primero desde `options` y luego desde la variable de entorno equivalente.
141
-
142
- | Opción | Tipo | Env var | Por defecto | Descripción |
143
- |---|---|---|---|---|
144
- | `command` | `string` | `ACP_COMMAND` | — (requerido) | Comando del agente ACP a spawnear. |
145
- | `args` | `string[]` | `ACP_ARGS` | — | Argumentos del comando. |
146
- | `cwd` | `string` | `ACP_CWD` | `process.cwd()` | Directorio de trabajo del agente. |
147
- | `env` | `Record<string,string>` | `ACP_ENV` (JSON) | — | Variables de entorno extra para el proceso del agente. |
148
- | `claudeExecutable` | `string` | `CLAUDE_CODE_EXECUTABLE` | autodetectado (`command -v claude`) | Ruta al binario nativo de Claude Code. |
149
- | `streamCloseTimeoutMs` | `number` | `ACP_STREAM_CLOSE_TIMEOUT_MS` | `600000` | `CLAUDE_CODE_STREAM_CLOSE_TIMEOUT` del agente. Permite que un `tools/call` diferido espere a OpenCode más de 60 s (p. ej. mientras apruebas un permiso). |
150
- | `claudeCode` | `object` | — | "cerebro limpio" | Control del ecosistema de Claude Code (ver abajo). |
151
-
152
- ### `claudeCode` — control del ecosistema de Claude Code
153
-
154
- Por defecto el agente arranca con el "cerebro limpio" (sin tus skills/hooks/agents/MCP),
155
- pero **usando tu configuración de Claude Code** (`~/.claude`) para que las sesiones sean
156
- reanudables. Puedes ajustarlo:
157
-
158
- | Campo | Tipo | Por defecto | Descripción |
159
- |---|---|---|---|
160
- | `model` | `string` | el modelId de OpenCode | Modelo de Claude (ver "Selección de modelo"). |
161
- | `fallbackModel` | `string` | — | Modelo de reserva si el primario falla. |
162
- | `effort` | `"low"\|"medium"\|"high"\|"xhigh"\|"max"` | `"high"` | Nivel de esfuerzo de razonamiento. |
163
- | `thinking` | `{type:"adaptive"\|"enabled"\|"disabled", display?:"summarized"\|"omitted", budgetTokens?}` | **`{type:"enabled", display:"summarized"}`** | Config de thinking/reasoning. El default muestra el **bloque de razonamiento** en OpenCode (`Thought: …`); usa `display:"omitted"` o `type:"disabled"` para ocultarlo, o `"adaptive"` para pensar solo cuando haga falta. |
164
- | `maxThinkingTokens` | `number` | — | (Deprecado; usa `thinking`.) |
165
- | `maxTurns` | `number` | — | Máximo de turnos del agente. |
166
- | `maxBudgetUsd` | `number` | — | Tope de gasto por turno. |
167
- | `mode` | `"default"\|"plan"\|"acceptEdits"\|"bypassPermissions"\|…` | — | **Modo de sesión ACP**, aplicado en caliente con `setSessionMode`. P. ej. `"plan"` (planifica) o `"bypassPermissions"` (deja que OpenCode sea la única autoridad de permisos). Configurable por agente vía `plugins[0].options.agents.<n>.options.mode`. |
168
- | `permissionMode` | `"default"\|"acceptEdits"\|…` | resuelto por el agente | (Heredado; el ACP lo ignora para el modo de sesión — usa `mode`.) |
169
- | `systemPromptMode` | `"preset"\|"append"\|"replace"` | **`"preset"`** | Cómo se traslada el system prompt de OpenCode (ver "System prompt y facturación"). **`preset` (default) = consume de tu suscripción; `append`/`replace` = extra usage.** |
170
- | `configDir` | `string \| "isolated" \| false` | **`false`** | `false` (default): hereda tu `~/.claude`, así las sesiones iniciadas en OpenCode **se retoman con `claude --resume <id>`** (ver "Retomar la sesión en Claude Code"). No reintroduce tu ecosistema: eso lo siguen mandando `settingSources`/`tools`/`strictMcpConfig`. `"isolated"`: dir limpio con tus credenciales enlazadas (sesiones invisibles para `claude --resume`). Ruta: úsala tal cual como `CLAUDE_CONFIG_DIR`. |
171
- | `forwardEnvContext` | `boolean` | **`true`** | Reenvía la parte **factual** del system prompt de OpenCode (bloque `<env>`: directorio de trabajo, raíz del workspace, git, plataforma, fecha; y `<available_references>`) como contexto de usuario. Con `systemPromptMode: "preset"` el system nunca llega al agente, así que sin esto trabaja sin saber dónde está. Solo viajan bloques factuales — nunca las instrucciones de OpenCode — así que la sesión sigue en suscripción. Se manda completo una vez por sesión y luego solo el delta. |
172
- | `settingSources` | `("user"\|"project"\|"local")[]` | `[]` | Settings de Claude Code a cargar (hooks/agents). |
173
- | `tools` | `string[]` | `[]` | Herramientas **nativas** del agente a habilitar. `[]` = ninguna. |
174
- | `disallowedTools` | `string[]` | — | Herramientas nativas a prohibir. |
175
- | `strictMcpConfig` | `boolean` | **`true`** | Usa **solo** el host de tools de OpenCode e ignora todo lo demás: el `.claude.json` y los **connectors de tu cuenta claude.ai** (Gmail, Drive, Supabase, Notion…). `false` para dejar pasar esos connectors. |
176
- | `allowedTools` | `string[]` | — | Tools auto-aprobadas (sin `requestPermission`). Con el **puente de permisos** activo se usa `["mcp__opencode"]` para que las tools de OpenCode no pidan doble permiso (ver "Puente de permisos"). |
177
- | `nativeTools` | `string[]` | — | Tools **nativas** de Claude que OpenCode no cubre. Los agentes inyectados usan `["NotebookEdit", "Read", "ExitPlanMode", "WebSearch"]`: `ExitPlanMode` es lo que permite **salir** del modo plan, y `WebSearch` cubre que OpenCode no registre su `websearch` cuando `providerId` no es `"opencode"`. Se añaden a `tools`. |
178
- | `resourceSearch` | `boolean` | — | Habilita `ListMcpResources`/`ReadMcpResource` (búsqueda de recursos MCP, superior a OpenCode). |
179
- | `nativeSubagents` | `boolean \| Record` | — | Subagentes nativos (`Task`). `true` añade un subagente "general" que **delega la ejecución a OpenCode**; un `Record` define subagentes a medida. |
180
- | `nativeSkills` | `boolean \| string[]` | — | Skills de Claude Code. `string[]` precarga solo esos (`settings.skills`, menor riesgo billing); `true` carga `~/.claude/skills` (`settingSources:"user"`, mayor riesgo). Añade la tool `Skill`. |
181
- | `projectMemory` | `boolean` | — | Carga `CLAUDE.md`/`AGENTS.md` del proyecto (`settingSources:"project"`). Convive con plugins de memoria de OpenCode (hindsight). |
182
- | `skillShell` | `boolean` | `false` | Permite que los skills ejecuten shell con la `Bash` nativa. Por defecto orquestan vía las tools de OpenCode. |
183
- | `agents`, `hooks`, `mcpServers`, `plugins`, `systemPrompt` | — | — | Inyectar subagents/hooks/MCP/plugins propios o un system prompt avanzado. |
184
- | `options` | `Record<string,unknown>` | — | Passthrough libre a `_meta.claudeCode.options` (cualquier campo del SDK). |
195
+ > [!NOTE]
196
+ > `opencode run` **without `-m` ignores an agent's `model`**: the V2 CLI uses the global
197
+ > model from config. In the CLI pass `-m acp/…`. In the TUI, the agent and model pickers do
198
+ > apply the model each agent declares.
185
199
 
186
200
  ---
187
201
 
188
- ## Selección de modelo y razonamiento
202
+ ## Billing: subscription vs extra usage
189
203
 
190
- Con el auto-registro **no necesitas declarar modelos**: el plugin publica los que descubre del agente — **`acp/default`** (= Opus 4.7, 1M ctx), **`acp/sonnet`**, **`acp/sonnet[1m]`**, **`acp/haiku`** — y los eliges en el selector de modelos de OpenCode. El `id` del modelo es el que se pasa al agente (vía `ANTHROPIC_MODEL`).
204
+ In plain ACP the client doesn't control the agent's system prompt. `claude-agent-acp` adds an
205
+ extension (`_meta.systemPrompt`) to pass OpenCode's system prompt along. **This matters for
206
+ billing:** Anthropic classifies the session by its system prompt. With OpenCode's system prompt
207
+ the session counts as a **third-party app** and is billed as **extra usage**; Claude Code's
208
+ official preset is billed to your **Pro/Max subscription**.
191
209
 
192
- También puedes fijarlo en el provider o por agente: `"options": { "claudeCode": { "model": "sonnet" } }`, o en tu config `"agents": { "claude-code": { "model": "acp/sonnet" } }`.
210
+ `claudeCode.systemPromptMode` sets that trade-off:
193
211
 
194
- > ⚠️ **`opencode run` sin `-m` ignora `agent.model`** (comportamiento del CLI V2: usa el model global de config). En CLI usa `-m acp/…`; en la TUI, el selector de agentes/modelos sí aplica el modelo declarado por agente.
212
+ | Value | Effect | Billing |
213
+ | --- | --- | --- |
214
+ | `"preset"` (**default**) | OpenCode's system prompt is **ignored**; Claude uses the official `claude_code` preset. OpenCode's tools are still orchestrated (through MCP); Claude behaves like native Claude Code instead of following OpenCode's instructions. | **Subscription** |
215
+ | `"append"` | Preset + OpenCode's system prompt appended: full OpenCode fidelity. | Extra usage |
216
+ | `"replace"` | OpenCode's system prompt replaces the preset. | Extra usage |
195
217
 
196
- Valores: aliases (`sonnet`, `haiku`, `opus`, `default`), variantes (`sonnet[1m]` = contexto 1M) o IDs completos (`claude-sonnet-4-6`).
218
+ With `preset`, `forwardEnvContext` (on by default) still passes the **factual** part of
219
+ OpenCode's system prompt to Claude as user context, so Claude knows where it is working:
220
+ - the `<env>` block: working directory, workspace root, git, platform, date;
221
+ - `<available_references>`.
197
222
 
198
- > **Importante — qué modelos están disponibles**: la lista **la define el backend de tu cuenta/suscripción**, no este provider ni un catálogo fijo. Para verla, arranca con `ACP_DEBUG=1` y busca `available models: …` en los logs (p. ej. `default, sonnet, sonnet[1m], haiku`).
199
- >
200
- > **Versiones**: los aliases resuelven a la versión actual del backend; para fijar una usa el ID completo o un sufijo (`sonnet[1m]`).
201
- >
202
- > **Modelos (jun-2026, cuenta Max)**: `sonnet` (claude-sonnet-4-6), `sonnet[1m]` (1M ctx, *extra usage*), `haiku` (claude-haiku-4-5), `opus` (claude-opus-4-7) y `default` (= **Opus 4.7**, 1M ctx, "más capaz") **responden**. `fable` salió de la suscripción el 22-jun-2026 (pasa a *usage credits*); `mythos` solo está en "Project Glasswing" → ambos dan `issue with the selected model`. El descubrimiento solo **lista** `default/sonnet/sonnet[1m]/haiku`, pero `opus` también funciona vía `ANTHROPIC_MODEL`.
223
+ OpenCode's behavioural instructions are never forwarded, so this stays on the subscription.
203
224
 
204
- El **esfuerzo (effort)** se expone como **variantes del modelo** (`acp/opus#low` … `#max`, sintaxis V2 `provider/model#variant`): elígelas en el selector de la TUI o fíjalas por agente con `variant`. También por agente vía `plugins[0].options.agents.<n>.options.effort`, o fijo en el provider:
205
-
206
- ```jsonc
207
- "options": { "claudeCode": { "model": "sonnet", "effort": "xhigh",
208
- "thinking": { "type": "enabled", "budgetTokens": 16000 } } }
209
- ```
225
+ > Tested empirically:
226
+ > - The switch to extra usage comes from an Anthropic classifier that reads the system
227
+ > prompt and recognises a third-party app. The name, the mode or the size don't trigger it.
228
+ > - With `preset`, `scripts/verify-billing.mjs` measures **0 extra usage**, including with
229
+ > the native features the injected agents enable.
210
230
 
211
231
  ---
212
232
 
213
- ## System prompt y facturación (suscripción vs extra usage)
233
+ ## Configuration reference
234
+
235
+ ### Plugin options
236
+
237
+ Everything goes in the plugin's `options`. Options not specific to the plugin are passed on to
238
+ the provider.
239
+
240
+ | Option | Type | Env var | Default | Description |
241
+ | --- | --- | --- | --- | --- |
242
+ | `command` | `string` | `ACP_COMMAND` | — | ACP agent command, e.g. `"claude-agent-acp"`. **Without it the plugin doesn't register anything** (manual setup, see below). |
243
+ | `args` | `string[]` | `ACP_ARGS` (JSON array or space-separated) | — | Arguments for `command`. |
244
+ | `cwd` | `string` | `ACP_CWD` | server's working directory | Working directory of the agent process. |
245
+ | `env` | `Record<string,string>` | — | — | Extra environment variables for the agent process. |
246
+ | `claudeExecutable` | `string` | `CLAUDE_CODE_EXECUTABLE` | `command -v claude` | Path to the `claude` binary. |
247
+ | `streamCloseTimeoutMs` | `number` | `ACP_STREAM_CLOSE_TIMEOUT_MS` | `600000` | Sets `CLAUDE_CODE_STREAM_CLOSE_TIMEOUT` for older agents. `claude-agent-acp` ≥ 0.31 doesn't read it: a pending tool call is bounded by `MCP_TOOL_TIMEOUT` (~27 h by default), so waiting for you to approve a permission never cuts the turn. |
248
+ | `providerId` | `string` | — | `"acp"` | Provider id the models are registered under (see [below](#changing-the-provider-id)). |
249
+ | `name` | `string` | — | `"Claude Code (ACP)"` | Provider display name. |
250
+ | `agents` | `false \| Record` | — | two agents | `false` injects no agents. A `Record` **replaces** the default `claude-code` / `claude-code-plan` definitions entirely, including their native toolset ([details](#agents-and-subagents)). |
251
+ | `agentModel` | `string` | — | `"default"` | Model of the injected agents. |
252
+ | `titleFromModel` | `boolean` | — | `false` | Let the model title sessions. By default the plugin titles them from the first user message, with no model call. |
253
+ | `npm` | `string` | — | auto | Package spec the provider is loaded from. Only needed in unusual setups. |
254
+ | `claudeCode` | `object` | — | "clean brain" | How Claude Code runs: the table below. |
255
+
256
+ ### `claudeCode` options
257
+
258
+ **Ecosystem: what Claude Code loads**
259
+
260
+ | Field | Type | Default | Description |
261
+ | --- | --- | --- | --- |
262
+ | `configDir` | `string \| "isolated" \| false` | `false` | `false` uses your `~/.claude`, so sessions started in OpenCode can be resumed with `claude --resume` ([details](#resuming-a-session-in-claude-code)). It doesn't load your ecosystem: `settingSources` / `tools` / `strictMcpConfig` decide that. `"isolated"`: a clean dir under `~/.acp-model-provider/` with your credentials linked in (sessions invisible to `claude --resume`). A path is used as `CLAUDE_CONFIG_DIR` as is. |
263
+ | `settingSources` | `("user"\|"project"\|"local")[]` | `[]` | Claude Code settings to load (hooks, agents…). |
264
+ | `tools` | `string[]` | `[]` | Built-in Claude Code tools to enable. `[]` = none. Overrides the toggles below. |
265
+ | `disallowedTools` | `string[]` | — | Built-in tools to forbid. |
266
+ | `allowedTools` | `string[]` | `["mcp__opencode"]` | Tools approved without asking. By default OpenCode's own tools, for **every** agent on this provider, subagents included: OpenCode already authorises them, so there's no double prompt. |
267
+ | `strictMcpConfig` | `boolean` | `true` | Use **only** OpenCode's tool host. Ignores `.claude.json` MCP servers and your **claude.ai account connectors** (Gmail, Drive, Supabase, Notion…). `false` lets those connectors through. |
268
+ | `nativeTools` | `string[]` | — | Native Claude tools that OpenCode doesn't cover, added to `tools`. The injected agents use `["NotebookEdit", "ExitPlanMode", "WebSearch"]`. `ExitPlanMode` is what lets a plan session *leave* plan mode. |
269
+ | `resourceSearch` | `boolean` | — | Enables `ListMcpResources` / `ReadMcpResource`. |
270
+ | `nativeSubagents` | `boolean \| Record` | — | Native subagents (`Task`). `true` adds a `general` subagent that works through OpenCode's tools; a `Record` defines your own. |
271
+ | `nativeSkills` | `boolean \| string[]` | — | Claude Code skills (adds the `Skill` tool). `true` loads `~/.claude/skills` and `~/.claude/agents` (`settingSources: "user"`) with your hooks disabled. A `string[]` preloads only those skills. |
272
+ | `skillShell` | `boolean` | `false` | Lets skills use the native `Bash`. By default they work through OpenCode's tools. |
273
+ | `projectMemory` | `boolean` | — | Loads the project's `CLAUDE.md` / `AGENTS.md` (`settingSources: "project"`). |
274
+ | `agents`, `hooks`, `mcpServers`, `plugins`, `systemPrompt` | — | — | Inject your own subagents, hooks, MCP servers, plugins or an advanced system prompt. |
275
+ | `options` | `Record<string,unknown>` | — | Free passthrough to `_meta.claudeCode.options`, for any Claude Agent SDK option. |
276
+
277
+ **Model and reasoning**
278
+
279
+ | Field | Type | Default | Description |
280
+ | --- | --- | --- | --- |
281
+ | `model` | `string` | the OpenCode model id | Claude model: alias (`sonnet`, `haiku`, `opus`, `default`), variant (`sonnet[1m]`) or full id. |
282
+ | `fallbackModel` | `string` | — | Model to use if the primary one fails. |
283
+ | `effort` | `"low"\|"medium"\|"high"\|"xhigh"\|"max"` | agent's default | Reasoning effort. The `#effort` model variants set it too. |
284
+ | `thinking` | `{type:"adaptive"\|"enabled"\|"disabled", display?:"summarized"\|"omitted", budgetTokens?}` | `{type:"enabled", display:"summarized"}` | Thinking config. The default shows Claude's **reasoning block** in OpenCode. `display:"omitted"` or `type:"disabled"` hides it; `"adaptive"` thinks only when needed. |
285
+ | `maxThinkingTokens` | `number` | — | Deprecated, use `thinking`. |
286
+
287
+ **Limits, mode and system prompt**
288
+
289
+ | Field | Type | Default | Description |
290
+ | --- | --- | --- | --- |
291
+ | `mode` | `"default"\|"plan"\|"acceptEdits"\|"bypassPermissions"\|"auto"\|"dontAsk"` | — | **ACP session mode**, applied live with `setSessionMode`. E.g. `"plan"` (plan only) or `"bypassPermissions"` (OpenCode is the only permission authority). Settable per agent. |
292
+ | `permissionMode` | same values | — | Legacy. The ACP agent ignores it for the session mode: use `mode`. |
293
+ | `maxTurns` | `number` | — | Max agent turns. |
294
+ | `maxBudgetUsd` | `number` | — | Spending cap per turn. |
295
+ | `systemPromptMode` | `"preset"\|"append"\|"replace"` | `"preset"` | See [Billing](#billing-subscription-vs-extra-usage). |
296
+ | `forwardEnvContext` | `boolean` | `true` | Forward OpenCode's factual `<env>` / `<available_references>` blocks: in full once per session, then as deltas. |
297
+
298
+ **Continuity, performance and sessions**
299
+
300
+ | Field | Type | Default | Description |
301
+ | --- | --- | --- | --- |
302
+ | `historyMode` | `"shadow"\|"v2"\|"legacy"` | `"shadow"` | How the provider tells what Claude already knows of the history ([details](#switching-models-mid-session-and-token-cost)). `"shadow"`: the classic fingerprint decides; the new one (user messages + tool-call ids) runs alongside and logs each disagreement. `"v2"`: the new one decides. It ignores OpenCode re-rendering old messages and plugins tagging text, and enables the compaction-related features. `"legacy"`: classic only. Env: `ACP_HISTORY_MODE`. |
303
+ | `catchupResultChars` | `number` | `8000` | Characters kept from each tool result of **another model** when Claude is caught up after a model switch. |
304
+ | `parallelTools` | `string[]` | `read, glob, grep, webfetch, websearch, skill, subagent` | OpenCode tools announced as read-only (`readOnlyHint`). Claude issues several at once, and OpenCode runs them in parallel in a single step. |
305
+ | `toolBatchMs` | `number` | `40` | How long a read-only call waits for parallel siblings before the step is closed. |
306
+ | `autoCompactPct` | `number` | `75` | Sets `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`. Claude compacts its own session at 75 % of the context, before OpenCode's threshold, so OpenCode's compaction rarely runs. `0` keeps Claude Code's default. |
307
+ | `nativeActivity` | `"text"\|"off"` | `"text"` | Native tools (Task/Agent, WebSearch, Skill, NotebookEdit…) leave a `⚙ …` line in the answer, with the result of Task / WebSearch / Skill. That way it stays in OpenCode's history, and any model that continues the session sees it. |
308
+ | `nativeActivityChars` | `number` | `2000` | Cap on the native result written into that line. |
309
+ | `smartRevert` | `boolean` | `true` | On a revert, forks the Claude session right before the reverted message (`resumeSessionAt`, located in its transcript) instead of starting a new session with a replay. If that isn't possible, it falls back to the replay. |
310
+ | `maxLiveSessions` | `number` | `6` | Conversations kept open at once (each is a `claude` process). The oldest idle ones are closed. |
311
+ | `idleSessionTtlMs` | `number` | `900000` (15 min) | Idle time after which a session is closed. It's resumed on the next message; coming back only costs starting the process, and Anthropic's cache lasts ~1 h on the subscription. |
312
+ | `childSessionTtlMs` | `number` | `120000` (2 min) | Same for OpenCode subagent sessions. |
313
+
314
+ ### Manual provider (advanced)
315
+
316
+ Without `command` (and without `ACP_COMMAND`) the plugin **doesn't register the provider**, so
317
+ you can declare it yourself. OpenCode V2 still accepts the classic `provider` key and migrates
318
+ it. The plugin keeps a provider you declared and still injects the agents and the per-call
319
+ hooks. A full example with costs and limits:
320
+ [examples/07-manual-provider.jsonc](examples/07-manual-provider.jsonc).
214
321
 
215
- En ACP "puro" el cliente **no** controla el system prompt del agente. `claude-agent-acp` añade una extensión (`_meta.systemPrompt`) para trasladar el system que arma OpenCode. **Hay un detalle de facturación clave:** Anthropic clasifica la sesión según el system prompt. Si reenvías el system de OpenCode, la sesión se considera **app de terceros** y se factura como **extra usage** (de pago); el preset oficial de Claude Code, en cambio, consume de tu **suscripción** Pro/Max.
322
+ ```jsonc
323
+ {
324
+ "$schema": "https://opencode.ai/config.json",
325
+ "plugins": [{ "package": "opencode-claude-code-acpbridge" }],
326
+ "provider": {
327
+ "acp": {
328
+ "npm": "opencode-claude-code-acpbridge",
329
+ "name": "Claude Code (ACP)",
330
+ "options": { "command": "claude-agent-acp" },
331
+ "models": { "sonnet": { "id": "sonnet", "tool_call": true, "reasoning": true } }
332
+ }
333
+ }
334
+ }
335
+ ```
216
336
 
217
- `systemPromptMode` controla ese equilibrio:
337
+ ### Changing the provider id
218
338
 
219
- - `"preset"` (**por defecto**): se **ignora** el system de OpenCode; el agente usa solo el preset oficial `claude_code`. → Consume de tu **SUSCRIPCIÓN**. Las tools de OpenCode se orquestan igual (vía MCP); el agente se comporta como **Claude Code nativo** en lugar de seguir las instrucciones/agentes de OpenCode.
220
- - `"append"`: preset oficial + el system de OpenCode añadido. Fidelidad total a OpenCode, **pero facturado como EXTRA USAGE**.
221
- - `"replace"`: el system de OpenCode pasa a ser todo el system prompt. También **extra usage**.
339
+ The provider registers as **`acp`**. To use another id (typically **`anthropic`**, so that
340
+ [opencode-quota](https://www.npmjs.com/package/@slkiser/opencode-quota) shows your
341
+ **subscription** quota), set it in the **plugin** options. Don't declare a second provider by
342
+ hand, so there is only one backend:
222
343
 
223
344
  ```jsonc
224
- // suscripción (por defecto — no hace falta declararlo):
225
- "options": { "claudeCode": { "systemPromptMode": "preset" } }
226
- // fidelidad total a OpenCode, a cambio de extra usage:
227
- "options": { "claudeCode": { "systemPromptMode": "append" } }
345
+ "plugins": [
346
+ { "package": "opencode-claude-code-acpbridge",
347
+ "options": { "command": "claude-agent-acp", "providerId": "anthropic" } }
348
+ ]
228
349
  ```
229
350
 
230
- > Verificado empíricamente: el desvío a *extra usage* lo dispara un clasificador de Anthropic sobre el system prompt (detecta el "carácter" de app de terceros); no depende del nombre, el modo ni el tamaño. Con `preset` el modelo responde con **0 extra usage**.
351
+ Auto-registration, resume, the permission bridge and the agents (`claude-code` →
352
+ `anthropic/default`) then all use that id.
353
+
354
+ > [!WARNING]
355
+ > `"anthropic"` **replaces OpenCode's official Anthropic provider**. That's fine if you don't
356
+ > use the Anthropic API directly. OpenCode may also list extra models from models.dev in the
357
+ > picker: use only the ones the agent reports (`anthropic/default`, `anthropic/sonnet`…). To
358
+ > use the API directly again, remove `providerId`.
231
359
 
232
360
  ---
233
361
 
234
- ## Agentes Claude Code (modos, esfuerzo, subagentes)
362
+ ## Agents and subagents
235
363
 
236
- Al auto-registrarse, el plugin **inyecta dos agentes** en OpenCode (selector de agentes), igual que otros plugins inyectan los suyos:
364
+ The plugin **injects two agents** into OpenCode:
237
365
 
238
- - **`claude-code`** — Claude Code nativo (modelo `acp/default`), modo ACP **`default`**: cada tool nativa pasa por el puente de permisos y **OpenCode es la única autoridad** (no añade prompts propios; ejecuta las tools con tu TUI/permisos).
239
- - **`claude-code-plan`** — modo **`plan`**: el agente **planifica** (investiga, lee, redacta el plan) sin hacer cambios destructivos. Variante de esfuerzo `high`.
366
+ - **`claude-code`**: native Claude Code (model `acp/default`), ACP mode **`default`**. Every
367
+ native tool goes through the [permission bridge](#tools-and-the-permission-bridge), so
368
+ **OpenCode stays the only authority**.
369
+ - **`claude-code-plan`**: mode **`plan`**. Claude **plans** (researches, reads, writes the
370
+ plan) without making destructive changes. Effort variant `high`.
240
371
 
241
- Cámbialos o desactívalos desde las opciones del plugin:
372
+ Both have the same native toolset and differ only in their starting mode.
373
+
374
+ To **adjust** them (permissions, model, description), use the `agents` section of your
375
+ OpenCode config, shown just below. To **replace** them with your own agents, use the plugin's
376
+ `agents` option:
242
377
 
243
378
  ```jsonc
244
379
  "plugins": [{ "package": "opencode-claude-code-acpbridge",
245
380
  "options": { "command": "claude-agent-acp",
246
- "agents": { // o "agents": false para no inyectar ninguno
381
+ "agents": { // or "agents": false to inject none
247
382
  "claude-code": { "model": "default", "options": { "mode": "default" } },
248
383
  "claude-code-plan": { "model": "default", "variant": "high", "options": { "mode": "plan" } }
249
384
  }
@@ -251,171 +386,353 @@ Cámbialos o desactívalos desde las opciones del plugin:
251
386
  }]
252
387
  ```
253
388
 
254
- Cada agente lleva `options` (modo ACP, esfuerzo…) que el `context` hook del plugin inyecta **por llamada** como `providerOptions.<providerID>` y se aplican **en caliente** (`setSessionMode` / `setSessionConfigOption`), sin recrear la sesión.
389
+ > [!WARNING]
390
+ > A plugin-level `agents` record **replaces** the built-in definitions. Your `options` are all
391
+ > those agents get, so the native toolset of the defaults is gone unless you list it:
392
+ > - `disallowedTools`;
393
+ > - `resourceSearch`, `nativeSubagents`;
394
+ > - `nativeTools: ["NotebookEdit", "ExitPlanMode", "WebSearch"]`;
395
+ > - `projectMemory`, `nativeSkills`.
396
+ >
397
+ > A plan agent without `ExitPlanMode` can't leave plan mode. See
398
+ > [examples/05-custom-agents.jsonc](examples/05-custom-agents.jsonc).
255
399
 
256
- > **Tu `opencode.json` manda.** En V2 los agentes viven en la sección `agents` de tu config: tus campos ganan sobre los del plugin (description/model solo se rellenan si no los declaras; options hacen merge profundo). Ideal para **filtrar tools por `permissions`** (ruleset) sin tocar el plugin:
400
+ Each agent's `options` (mode, effort, `claudeCode` fields…) reach the provider **per call**,
401
+ through the plugin's `context` hook. They are applied **live** (`setSessionMode` /
402
+ `setSessionConfigOption`), without recreating the session.
403
+
404
+ > **Your `opencode.json` wins.** In V2, agents live in the `agents` section of your config, and
405
+ > your fields beat the plugin's: `description` and `model` are only filled in if you don't set
406
+ > them. That's the place to restrict tools with a `permissions` ruleset, without touching the
407
+ > plugin:
257
408
  > ```jsonc
258
409
  > "agents": {
259
410
  > "claude-code": {
260
411
  > "permissions": [
261
412
  > { "action": "edit", "resource": "*", "effect": "deny" },
262
413
  > { "action": "bash", "resource": "*", "effect": "ask" }
263
- > ] // hereda model y options del plugin
414
+ > ]
264
415
  > }
265
416
  > }
266
417
  > ```
267
- > También `"disabled": true` para apagar un agente inyectado.
268
-
269
- - **Modos**: como OpenCode ejecuta las tools con sus permisos, los modos de permiso de Claude Code no cambian *quién* autoriza; `bypassPermissions` solo evita el round-trip de `requestPermission`. El útil con efecto propio es **`plan`**. Evita `dontAsk` (puede bloquear tools).
270
- - **Subagentes**: con "OpenCode orquesta" (`tools: []`) los subagentes nativos de Claude Code están deshabilitados; el agente usa la tool `task` de **OpenCode** → los subagentes son los de OpenCode.
271
- - **Reanudar sin reenviar historial**: el plugin guarda un registro `~/.acp-model-provider/sessions.json` (sessionID de OpenCode → sessionId de Claude Code). Al reabrir una sesión, el provider hace `resumeSession` en vez de reenviar todo el historial → **ahorra tokens**.
418
+ > `"disabled": true` turns an injected agent off.
419
+
420
+ - **Modes.** OpenCode runs the tools with its own permissions, so Claude Code's permission
421
+ modes don't change *who* authorises:
422
+ - `bypassPermissions` only skips the `requestPermission` round trip;
423
+ - `plan` is the one with a real effect of its own;
424
+ - avoid `dontAsk`, which can block tools.
425
+ - **Two ways to delegate.**
426
+ - **OpenCode's `subagent` tool** is preferred for real work. The child session is visible in
427
+ OpenCode, **any model** can continue it, and its result stays in the shared history.
428
+ - **Claude Code's native `Task`** (the `general` subagent plus your `~/.claude/agents`) is for
429
+ quick tasks or your specialised agents. Its result is written into the answer (see
430
+ `nativeActivity`).
431
+ - Both tools' descriptions steer Claude. If one of your agents relies on native
432
+ `Bash`/`Edit`, it uses OpenCode's tools instead.
433
+ - **OpenCode subagents on this provider.** A child session inherits its parent's model (`acp`).
434
+ Child sessions:
435
+ - get the base profile (`allowedTools: ["mcp__opencode"]`);
436
+ - get a native permission request denied with a reason if their agent can't use `question`
437
+ (OpenCode's `general` denies it), instead of hanging;
438
+ - are closed after 2 minutes idle.
439
+ - **Switching to an agent with a different native profile** (other native tools,
440
+ `allowedTools`…) **forks** the session (`session/fork`) with the new profile: same context,
441
+ no replay.
442
+ - **Approving a plan** (`ExitPlanMode`). The dialog offers Claude Code's real choices:
443
+ - auto;
444
+ - accept edits;
445
+ - approve each edit;
446
+ - keep planning.
447
+
448
+ If you **type** an answer instead, the plan is rejected and your text reaches Claude as
449
+ feedback. The mode you chose survives switching from the plan agent to `claude-code`.
450
+ - **Resuming without resending history.** `~/.acp-model-provider/sessions.json` maps each
451
+ OpenCode session to its Claude Code session. On reopening, the provider resumes it
452
+ (`resumeSession`) instead of replaying the whole history. Entries older than 30 days are
453
+ pruned automatically, and the file keeps at most 500.
454
+ - **Titles.** With `systemPromptMode: "preset"`, OpenCode's title instructions never reach
455
+ Claude, which would answer the message instead. So the plugin titles sessions from their
456
+ first message, with no model call. `titleFromModel: true` restores the model call.
272
457
 
273
458
  ---
274
459
 
275
- ## Manejo de las herramientas y puente de permisos
460
+ ## Tools and the permission bridge
461
+
462
+ The `claude-code` agent gets Claude Code's native power without bypassing OpenCode:
463
+
464
+ - **Common tools → OpenCode runs them.** Claude reaches every tool OpenCode exposes through
465
+ MCP: OpenCode's own (`read`, `write`, `bash`, `edit`, `grep`…) and those of your MCP servers.
466
+ They run in OpenCode, with its permissions, TUI and history.
467
+ - They're in `allowedTools: ["mcp__opencode"]`, so they **don't prompt twice**.
468
+ - Claude's own versions are disabled: `Bash`, `Read`, `Write`, `Edit`, `MultiEdit`, `Glob`,
469
+ `Grep`, `WebFetch`, `TodoWrite`. Whatever Claude reads lands in OpenCode's history, which
470
+ another model may need later.
471
+ - **Native capabilities OpenCode doesn't have**, on by default in the injected agents:
472
+ - skills (`Skill`);
473
+ - native subagents (`Task`, working through OpenCode's tools);
474
+ - MCP resource search (`ListMcpResources` / `ReadMcpResource`);
475
+ - `NotebookEdit`, `WebSearch`, `ExitPlanMode`;
476
+ - project memory (`CLAUDE.md` / `AGENTS.md`).
477
+
478
+ What they do is written into the answer as `⚙ …` (`nativeActivity`), so it isn't lost if
479
+ you switch models.
480
+ - **Parallel tools.** Read-only tools (`parallelTools`) are announced with `readOnlyHint`.
481
+ Claude issues them together, and OpenCode runs them in parallel in one step. Calls that
482
+ arrive while OpenCode is still running the previous step are queued for the next one, never
483
+ dropped; native subagents working in parallel do this, for example.
484
+ - **Context-pruning plugins** ([opencode-dcp](https://www.npmjs.com/package/@p4r4d0xb0x/opencode-dcp)).
485
+ The plugin denies `compress` to the `claude-code*` agents. DCP rewrites OpenCode's copy of
486
+ the history, but the Claude Code session keeps its own context, so pruning only caused
487
+ divergences and replays. DCP keeps working for your other agents.
488
+ - **The permission bridge.** When Claude (or a native subagent) wants a **native** tool,
489
+ Claude Code asks for permission over ACP (`requestPermission`). The provider turns that
490
+ request into a call to OpenCode's own **`question`** tool. The dialog appears **in your TUI**
491
+ (`Allow once` / `Always allow` / `Deny`), and **your answer** goes back to Claude.
492
+ - Rules are checked first and settle without a dialog. They come from your
493
+ `agents.<name>.permissions`; `action: "*"` defaults are ignored.
494
+ - Anything not covered opens the dialog: the bridge **fails closed**.
495
+ - `Always allow` answers are stored in `~/.acp-model-provider/always.json`.
496
+ - The bridge needs the agent **not** to be in `bypassPermissions`, which is why `claude-code`
497
+ uses `mode: "default"`.
498
+ - **The classic "clean brain"**, where OpenCode runs everything and there are no native tools:
499
+ use `mode: "bypassPermissions"` with no native toggles, or a manual provider with
500
+ `claudeCode.tools: []`.
276
501
 
277
- El agente `claude-code` combina **lo mejor de ambos mundos** — *potencia nativa sin estropear nada*:
502
+ ---
278
503
 
279
- - **Tools comunes → OpenCode las orquesta.** El provider captura todas las que OpenCode expone (nativas `read`/`write`/`bash`/`edit`/`grep`/… + las de tus MCP servers) y el agente las usa vía MCP: se ejecutan en OpenCode con sus permisos, su TUI y su registro (hindsight las ve). Van en `allowedTools: ["mcp__opencode"]` para que **no pidan doble permiso**.
280
- - **Capacidades nativas superiores de Claude Code** que OpenCode no replica, activas por defecto: **skills** (`Skill`), **subagentes** (`Task`, que delegan la ejecución a OpenCode), **búsqueda de recursos MCP** (`ListMcpResources`/`ReadMcpResource`) y tools de nicho (`NotebookEdit`). Más la **memoria del proyecto** (`CLAUDE.md`/`AGENTS.md`), que convive con hindsight.
281
- - **Puente de permisos.** Cuando el agente (o un subagente) quiere usar una tool **nativa**, Claude Code pide permiso vía ACP (`requestPermission`); el provider lo **camufla como un tool-call de la tool `question` nativa de OpenCode**, así **el diálogo aparece en tu TUI** (`Allow once` / `Always allow` / `Deny`) y **tu veredicto** vuelve al agente. Las reglas (`allow`/`deny`) se evalúan antes y resuelven sin diálogo — guardadas con `Always allow` en `~/.acp-model-provider/always.json`. El agente tiene toda su potencia nativa, pero **tú controlas cada acción** desde OpenCode.
282
- - Las reglas por agente salen de tus `agents.<n>.permissions` (el plugin las publica para el puente, ignorando `action: "*"`; cualquier cosa no cubierta → diálogo, fail-closed).
283
- - Requiere que el agente NO esté en `bypassPermissions` → el agente `claude-code` usa `mode: "default"`.
284
- - **Facturación**: todos estos features mantienen tu **suscripción** (verificado con `scripts/verify-billing.mjs`, 0 extra usage) — son nativos de Claude Code.
285
- - Para el modelo **clásico "cerebro limpio"** (sin nativas, OpenCode ejecuta todo) usa `mode: "bypassPermissions"` + sin toggles, o el provider manual con `claudeCode.tools: []`.
504
+ ## Switching models mid-session, and token cost
505
+
506
+ OpenCode sends the **full** history on every call, while an ACP session keeps **state**. The
507
+ provider keeps one Claude Code session per conversation and sends it **only what it hasn't
508
+ seen**. Claude's prompt cache lives with that session, so the session is recreated as rarely
509
+ as possible. You can switch between `acp` and any other OpenCode model in the same
510
+ conversation, in both directions, and carry on.
511
+
512
+ - **Claude's own answer isn't sent back.** OpenCode stores Claude's reply and resends it on the
513
+ next turn. The provider recognises it (by the text it emitted and its own tool ids) and
514
+ skips it.
515
+ - **Another model in between.** Say you switch to another provider and come back: the other
516
+ model's turns reach Claude wrapped in `<other_model_turn>`, so Claude doesn't believe it
517
+ wrote them. They include that model's tool calls and results (`catchupResultChars`). Same
518
+ prompt cache, no new session.
519
+ - **The other way round.** What Claude does with native tools is written into the answer
520
+ (`nativeActivity`), so the other model sees it.
521
+ - **Usage limit.** If your Claude quota runs out, the error says so plainly and isn't retried
522
+ in a loop:
523
+ `Claude Code: usage limit reached (resets: <when>). Switch to another model in OpenCode to
524
+ continue; the Claude Code session is kept for when you come back.`
525
+ - **Typing while Claude works** (*steer*), or **interrupting and typing something else**, both
526
+ work:
527
+ - your message reaches Claude, through Claude Code's own queue or together with the pending
528
+ tool result;
529
+ - an interrupted turn is cancelled on the agent before the new one starts.
530
+ - **Changing agent** (`claude-code` ↔ `claude-code-plan`) or **toolset** keeps the session,
531
+ live. Moving to an agent with **another native profile** forks the session.
532
+ - **Changing `acp` model** (opus ↔ sonnet) keeps the session (`session/set_model`).
533
+ - **Compaction.** Claude compacts its own session before OpenCode would (`autoCompactPct`). If
534
+ OpenCode compacts anyway, the summary is asked of the **live session**, with a warm cache,
535
+ not of a new session holding the whole history. With `historyMode: "v2"`, the session also
536
+ compacts natively and **adopts** OpenCode's checkpoint, or catches up on another model's
537
+ checkpoint, without a new session.
538
+ - **Reverting** forks the session just before the reverted message (`smartRevert`). Claude
539
+ "forgets" the undone part, with no replay and the prefix still cached. When there's no fork
540
+ point (e.g. after restarting the process), a new session is created. A full replay is
541
+ bounded (~400K characters) and labelled as history, with your current request apart.
542
+
543
+ Every decision is logged in `~/.acp-model-provider/logs/acp-YYYYMMDD.log`: reuse,
544
+ continuation, new session, `historyMode: "shadow"` disagreements… In a normal conversation
545
+ you'll see `"decision":"reuse"` on every turn, and `"drop"` only on reverts and compactions.
286
546
 
287
547
  ---
288
548
 
289
- ## Multimodalidad (imagen, PDF, audio, vídeo)
549
+ ## Images, PDFs and other attachments
290
550
 
291
- Lo que el agente acepta en el prompt lo anuncia en `promptCapabilities` (míralo con `ACP_DEBUG=1`). Con el `claude-agent-acp` actual es `{"image": true, "embeddedContext": true}`. Los adjuntos llegan como `file` parts del prompt de OpenCode y el provider los convierte a ContentBlocks ACP respetando esas capacidades:
551
+ What the agent accepts is announced in its `promptCapabilities`; see it with `ACP_DEBUG=1`.
552
+ With the current `claude-agent-acp` it's `{"image": true, "embeddedContext": true}`.
553
+ Attachments arrive as `file` parts of OpenCode's prompt, and the provider converts them to ACP
554
+ content blocks according to those capabilities:
292
555
 
293
- | Tipo | Soporte | Cómo |
294
- |---|---|---|
295
- | **Imagen** (`image/*`) | ✅ | ContentBlock `image` (base64). *Validado.* |
296
- | **PDF / documentos** (`application/pdf`, `text/*`, …) | ✅ | Recurso embebido (ContentBlock `resource`, requiere `embeddedContext`). |
297
- | **Audio** (`audio/*`) | ❌ hoy | El agente no anuncia `audio`; se omite con una nota. Si una versión futura lo soporta, se enviará automáticamente. |
298
- | **Vídeo** (`video/*`) | ❌ | No existe en ACP ni lo procesa Claude; se omite con una nota. |
556
+ | Type | Supported | How |
557
+ | --- | --- | --- |
558
+ | **Image** (`image/*`) | ✅ | `image` content block (base64). |
559
+ | **PDF / documents** (`application/pdf`, `text/*`, …) | ✅ | Embedded resource (`resource` block, needs `embeddedContext`). |
560
+ | **Audio** (`audio/*`) | ❌ today | The agent doesn't announce `audio`, so it's skipped with a note. It will be sent automatically once a version supports it. |
561
+ | **Video** (`video/*`) | ❌ | Not representable in ACP and not understood by Claude; skipped with a note. |
299
562
 
300
- Las URLs remotas (sin datos embebidos) se omiten — el agente recibe solo adjuntos con bytes (base64).
563
+ Remote URLs without embedded data are skipped: the agent only receives attachments with bytes.
301
564
 
302
- ## Retomar la sesión en Claude Code
565
+ ---
566
+
567
+ ## Resuming a session in Claude Code
303
568
 
304
- Por defecto (`configDir: false`) el agente usa **tu** `~/.claude`, así que toda conversación
305
- iniciada desde OpenCode queda en `~/.claude/projects/<proyecto>/<id>.jsonl` y se puede
306
- continuar en la terminal:
569
+ By default (`configDir: false`) the agent uses **your** `~/.claude`, so every conversation
570
+ started from OpenCode is stored in `~/.claude/projects/<project>/<id>.jsonl`. You can continue
571
+ it in a terminal:
307
572
 
308
573
  ```bash
309
- # el provider imprime el id al crear cada sesión, sin necesidad de ACP_DEBUG:
310
- # [acp] session 1c66e017-… — retomable con: claude --resume 1c66e017-…
574
+ # the provider prints the id whenever it creates a session (no debug flag needed):
575
+ # [acp] session 1c66e017-… — resumable with: claude --resume 1c66e017-…
311
576
  claude --resume 1c66e017-4536-4157-80aa-e451420520e0
312
577
  ```
313
578
 
314
- Debe ejecutarse en el **mismo directorio de trabajo**: Claude Code indexa las sesiones por
315
- `cwd`. Si prefieres el aislamiento anterior (sesiones fuera de tu `~/.claude` y por tanto
316
- invisibles para `--resume`), pon `"configDir": "isolated"`.
317
-
318
- Que se herede el directorio de configuración **no** significa que el agente cargue tu
319
- ecosistema: eso lo siguen decidiendo `settingSources` (por defecto `[]`), `tools` y
320
- `strictMcpConfig`. `configDir` solo decide **dónde vive el estado**.
321
-
322
- ---
323
-
324
- ## Continuidad de sesión y coste de tokens
325
-
326
- El prompt cache de Claude vive y muere **con la sesión del agente**, así que el bridge está
327
- diseñado para recrearla lo menos posible:
328
-
329
- - **Cambiar de agente no rompe nada.** Puedes empezar en `claude-code-plan`, aprobar el plan
330
- y seguir en build o en `claude-code` sobre la **misma** sesión ACP: el cambio de modo se
331
- aplica en caliente con `setSessionMode`. Los dos agentes comparten el mismo perfil de tools
332
- y permisos y difieren solo en el modo inicial.
333
- - **Cambiar el set de tools tampoco.** Se propaga en caliente a la sesión viva
334
- (`notifications/tools/list_changed`).
335
- - **Solo se envía lo que el agente no ha visto.** Sus propias tool-calls y resultados no se
336
- reenvían: ya los tiene. Los de un agente intercalado sí, resumidos.
337
- - **Revertir mensajes y compactar sí crean sesión nueva**, porque el agente no puede
338
- "desrecordar" — pero se parte del historial ya truncado, no del original.
579
+ Run it **in the same working directory**: Claude Code indexes sessions by `cwd`. For the old
580
+ isolation, set `"configDir": "isolated"`: sessions then live outside your `~/.claude` and are
581
+ invisible to `--resume`.
339
582
 
340
- Con `ACP_DEBUG=1` puedes comprobarlo: durante una conversación normal debes ver
341
- `reuse session <id>` en cada turno y un `cacheR` alto en `usage(turn)`.
583
+ Sharing the config directory **doesn't** load your ecosystem: `settingSources` (default `[]`),
584
+ `tools` and `strictMcpConfig` still decide that. `configDir` only decides **where the state
585
+ lives**.
342
586
 
343
587
  ---
344
588
 
345
- ## Diagnóstico
346
-
347
- Activa logs con `ACP_DEBUG=1` (verás `[acp-orchestrator]` y `[acp-mcp-host]` en stderr; con `opencode run … --print-logs`).
348
-
349
- | Síntoma | Causa / solución |
350
- |---|---|
351
- | `Model not found: acp/…` | OpenCode no cargó tu config o el auto-registro falló. La config debe estar en `<proyecto>/.opencode/opencode.json`; verifica las fuentes con `opencode debug config` (debe listar tu documento con `plugins`). Con `ACP_DEBUG=1` busca `[acp-plugin] auto-registered…` en el arranque. Si el plugin es un directorio local y no hay línea `loading plugin`, falta el `index.js` raíz (compila con `npm run build`). |
352
- | El auto-registro no añade modelos | Ejecuta `npx opencode-claude-code-acpbridge sync <command>` para ver qué descubre y forzar refresh del caché. Si el agente no halla el binario nativo de Claude, fija `claudeExecutable`. |
353
- | `API Error: 400 … extra usage` | El **system prompt** disparó el clasificador de Anthropic (lo trata como app de terceros). Usa `systemPromptMode: "preset"` (default) o el **agente `claude-code`** → consume de tu suscripción. Suele pasar con `append`/`replace`, o al usar un agente con system agresivo de otro plugin (p. ej. oh-my-opencode). Ver [System prompt y facturación](#system-prompt-y-facturación-suscripción-vs-extra-usage). |
354
- | `Authentication required` | El `CLAUDE_CONFIG_DIR` aislado no tiene credenciales. El provider enlaza `~/.claude/.credentials.json` automáticamente; asegúrate de que `claude` esté autenticado. |
355
- | El agente dice que no tiene `read` / no usa las tools | El runtime del MCP server debe ejecutarse con `node` (en el `PATH`). El provider ya usa `node` por defecto; overridea con `ACP_RUNTIME_NODE` si hace falta. |
356
- | Cuelgues > 60 s al aprobar permisos | Sube `streamCloseTimeoutMs` (por defecto ya 600000). |
357
- | Gasto de tokens desbocado / `cacheR` a 0 | Con `ACP_DEBUG=1` busca líneas `dropping session … —` en cada turno: si aparecen, algo está invalidando la identidad de sesión (mira el motivo que indica). Ver [Continuidad de sesión](#continuidad-de-sesión-y-coste-de-tokens). |
358
- | El contexto crece sin que OpenCode compacte | Los modelos `[1m]` declaran 1M de ventana a propósito, y OpenCode no compacta hasta acercarse a ese umbral. Usa la variante normal si quieres compactación temprana. |
359
- | No se ve el bloque de razonamiento | Comprueba que `thinking` no esté en `display:"omitted"`/`disabled` y que no aparezca `aviso: no se pudo aplicar effort=…` en stderr. |
360
- | El agente no pregunta, asume | Debe usar `mcp__opencode__question`. Esa tool solo la registra OpenCode en TUI (`client: "cli"`) o con `enableQuestionTool`. |
361
- | El agente no busca en la web | OpenCode solo registra su `websearch` con `providerId: "opencode"` o con exa/parallel activos. El perfil por defecto ya incluye la `WebSearch` **nativa** para cubrirlo. |
362
- | Lento con muchas tools | Con cientos de tools el agente tarda ~1 min por paso. Reduce las tools expuestas con el ruleset `permissions` del agente en tu config. |
363
-
364
- Comando de mantenimiento:
589
+ ## Diagnostics and troubleshooting
590
+
591
+ The provider always writes its log to `~/.acp-model-provider/logs/acp-YYYYMMDD.log`, because
592
+ OpenCode doesn't capture a plugin's stderr. The log holds the session lifecycle and one line
593
+ per turn decision.
594
+
595
+ | Variable | Effect |
596
+ | --- | --- |
597
+ | `ACP_DEBUG=1` | Debug lines too, on stderr and in the file. |
598
+ | `ACP_LOG=0` | No log file. |
599
+ | `ACP_LOG_DIR=<dir>` | Log file location. |
600
+ | `ACP_RECORD=<dir>` | Records every prompt exactly as OpenCode builds it, plus the decision taken. Use it to report history-sync problems. `node scripts/sanitize-recording.mjs <recording> <output> <cwd>` anonymises a recording into a test fixture. |
601
+
602
+ | Symptom | Cause / fix |
603
+ | --- | --- |
604
+ | `Model not found: acp/…` | OpenCode didn't load your config, or auto-registration failed. Run `opencode debug config`: it must list your document with `plugins`. With `ACP_DEBUG=1`, look for `[acp-plugin] auto-registered provider 'acp' … — models: …` at startup. For a local directory plugin with no `loading plugin` line, the root `index.js` is missing: run `npm run build`. |
605
+ | Auto-registration adds no models | Run `npx opencode-claude-code-acpbridge sync claude-agent-acp` to see what the agent reports and to refresh the cache. If the agent can't find the `claude` binary, set `claudeExecutable`. |
606
+ | `API Error: 400 … extra usage` | The system prompt triggered Anthropic's classifier. Use `systemPromptMode: "preset"` (the default) or the `claude-code` agent. Typical causes: `append`/`replace`, or an agent from another plugin with an aggressive system prompt. See [Billing](#billing-subscription-vs-extra-usage). |
607
+ | `Authentication required` | Claude Code isn't logged in, or the isolated config dir has no credentials. Run `claude` and log in; with `configDir: "isolated"` the provider links `~/.claude/.credentials.json` automatically. |
608
+ | Claude says it has no `read` / doesn't use the tools | The internal MCP server must run with `node` (on the `PATH`). Override with `ACP_RUNTIME_NODE`. |
609
+ | `Claude Code: usage limit reached …` | Your subscription limit. Switch to another model in OpenCode and come back later: the session is kept. |
610
+ | Many `shadow-diff` lines in the log | With `historyMode: "shadow"`, each one is a turn where the new fingerprint would have decided differently. If they're all `legacy: diverged` → `anchors: append`, `"v2"` would save those replays. |
611
+ | Token usage out of control / `cacheR` at 0 | With `ACP_DEBUG=1`, look for `dropping session … —` on every turn, which names the reason. See [Switching models](#switching-models-mid-session-and-token-cost). |
612
+ | Context keeps growing and OpenCode doesn't compact | Only the `[1m]` models advertise a 1M window, and OpenCode won't compact until close to it. Use the regular model for earlier compaction. |
613
+ | No reasoning block | Check that `thinking` isn't `display:"omitted"` / `type:"disabled"`, and look in the log for a note saying an `effort` value could not be applied. |
614
+ | Claude doesn't ask you, it assumes | It asks through OpenCode's `question` tool, so the agent must be allowed to use it (the injected agents are). |
615
+ | Claude doesn't search the web | The injected agents include the **native** `WebSearch`, in case OpenCode's `websearch` isn't available. |
616
+ | Slow with many tools | With hundreds of tools each step can take ~1 min. Reduce the tools exposed with the agent's `permissions` ruleset. |
617
+
618
+ Maintenance command:
365
619
 
366
620
  ```bash
367
- # Refresca los cachés de descubrimiento + models.dev y previsualiza los modelos
621
+ # Refresh the discovery and models.dev caches and preview the models
368
622
  npx opencode-claude-code-acpbridge sync claude-agent-acp
369
623
  ```
370
624
 
371
625
  ---
372
626
 
373
- ## Estado y limitaciones
627
+ ## Status and limitations
628
+
629
+ | Status | Feature |
630
+ | --- | --- |
631
+ | ✅ | Streaming chat, with Claude's **reasoning block** shown in OpenCode (summarized thinking by default). |
632
+ | ✅ | **Native capabilities plus permission bridge**: skills, subagents, MCP resource search and project memory, each native action approved through OpenCode's `question` dialog. All on the **subscription** (verified). |
633
+ | ✅ | **Clean-brain mode** (`mode: "bypassPermissions"`, no native toggles): no native tools, no claude.ai connectors, only OpenCode's tools. |
634
+ | ✅ | **Auto-registration** with models.dev metadata, refreshable with `npx opencode-claude-code-acpbridge sync`. |
635
+ | ✅ | **Persistent session per conversation** (prompt cache), **resume across restarts**, several conversations and subagents at once on one agent process, idle sessions closed automatically. |
636
+ | ✅ | **Token usage**: OpenCode sees the **real** context size, including on tool steps. |
637
+ | ✅ | **Model switching mid-session** in both directions (`acp` ↔ other providers) without losing context. |
638
+ | ℹ️ | Which models answer depends on your account. On a Max account (June 2026): `default` (Opus), `sonnet`, `sonnet[1m]`, `haiku`, plus `opus` though it isn't listed. |
639
+ | 🔜 | `historyMode: "v2"` as the default, once validated in real use (shadow mode). |
640
+
641
+ ---
374
642
 
375
- - ✅ Chat con streaming y **bloque de razonamiento** visible en OpenCode (`Thought: …`, vía `thinking` summarized por defecto).
376
- - ✅ **Capacidades nativas + puente de permisos**: el agente `claude-code` usa skills, subagentes (`Task`), búsqueda de recursos MCP y `NotebookEdit` nativos, con memoria de proyecto (`CLAUDE.md`); cada acción nativa pide permiso vía el diálogo **`question` de OpenCode** en la TUI (reglas `allow`/`deny` resuelven sin diálogo; `Always allow` persiste en `always.json`). Las tools comunes las orquesta OpenCode (`allowedTools: ["mcp__opencode"]`, sin doble permiso). Todo en **suscripción** (verificado). Ver [Manejo de las herramientas y puente de permisos](#manejo-de-las-herramientas-y-puente-de-permisos).
377
- - ✅ **Cerebro limpio** disponible (modo clásico): sin tools nativas ni connectors de claude.ai (`strictMcpConfig`); el agente solo usa las tools de OpenCode (`mode: "bypassPermissions"`).
378
- - ✅ Auto-registro: el plugin descubre los modelos del agente e inyecta el provider con metadata de models.dev (config mínima); refrescable con `npx opencode-claude-code-acpbridge sync`.
379
- - ✅ Sesión persistente por conversación (prompt cache) y **reanudación entre procesos** (`sessions.json` + `resumeSession` → no reenvía el historial al reabrir una sesión).
380
- - ✅ **Agentes inyectados** (`claude-code`, `claude-code-plan`) con modo/esfuerzo por agente aplicados en caliente; **tu `opencode.json` tiene precedencia** (merge).
381
- - ✅ **Consume de tu suscripción** con `systemPromptMode: "preset"` (por defecto): verificado **0 extra usage**. Con `append`/`replace` Anthropic lo factura como *extra usage* — ver [System prompt y facturación](#system-prompt-y-facturación-suscripción-vs-extra-usage).
382
- - ✅ **Consumo de tokens**: el provider mapea `PromptResponse.usage` del ACP → OpenCode muestra el consumo por turno. (`usage` es experimental en el ACP; el desglose en turnos delta puede variar.)
383
- - ℹ️ **Modelos** (cuenta Max, jun-2026): `default` (Opus 4.7), `sonnet` (4-6), `sonnet[1m]`, `haiku` (4-5) responden; `opus` también (aunque no se liste). `fable`/`mythos` no disponibles.
384
- - ⚠️ **Una conversación a la vez** por instancia del modelo (la concurrencia entre sesiones simultáneas no está soportada aún).
385
- - 🔜 Roadmap: modelo por-llamada, emitir el `plan` a OpenCode.
643
+ ## Upgrading from 0.8.x (OpenCode V1)
644
+
645
+ 1. **Plugin config**: `"plugin": [[pkg, {opts}]]` → `"plugins": [{ "package": pkg, "options": {…} }]`. If you
646
+ declared `provider.acp` by hand, remove it: the plugin registers it at runtime.
647
+ 2. **Agents**:
648
+ - the `agent:` section becomes `agents:`;
649
+ - `permission` (a map) becomes `permissions` (a ruleset: `[{ "action": "bash", "resource": "git *", "effect": "allow" }]`);
650
+ - `disable` becomes `disabled`.
651
+ 3. **Variants**: `acp/opus:low` → `acp/opus#low` (V2 syntax `provider/model#variant`).
652
+ 4. **Per-agent options** (mode, effort, native toggles): from `agent.<n>.options` to
653
+ `plugins[0].options.agents.<n>.options`.
654
+ 5. **`claude_permission` is gone.** The permission bridge now uses OpenCode's `question` tool.
655
+ Move any bridge rules to `agents.<n>.permissions`; the bridge evaluates them fail-closed.
656
+ 6. **Local development**: point `package` at the repository **directory**, which has a root
657
+ `index.js` re-exporting `dist/`. Don't point it at a file. Build with `npm run build`.
658
+ 7. **CLI**: `opencode run` without `-m` ignores `agent.model`, so use `opencode run -m acp/…`.
659
+
660
+ Details in [CHANGELOG.md](CHANGELOG.md) and the port plan in [MIGRATION_V2.md](MIGRATION_V2.md).
386
661
 
387
662
  ---
388
663
 
389
- ## Desarrollo
664
+ ## Development
390
665
 
391
- Arquitectura interna, flujos (tools diferidas, sesiones/resume, billing) y cómo extender: **[docs/DEVELOPMENT.md](docs/DEVELOPMENT.md)**. Ejemplos de `opencode.json` por caso de uso: **[examples/](examples/)**.
666
+ ```bash
667
+ git clone https://github.com/aorizondo/opencode-claude-code-acpbridge.git
668
+ cd opencode-claude-code-acpbridge
669
+ npm install
670
+ npm run build # → dist/
671
+ npm test # tsc + node --test
672
+ ```
673
+
674
+ - **Unit tests** (`npm test`) need no external services. An in-process fake ACP agent
675
+ (`test/fake-agent.mjs`: real ACP, plus real MCP against `mcp-runtime.js`) covers each
676
+ behaviour and each fixed bug. The prompts in `test/fixtures/v2/` are **real** OpenCode V2
677
+ prompts recorded with `ACP_RECORD`.
678
+ - **Against the real agent**: `VERIFY_MODEL=haiku node scripts/verify-<name>.mjs`. Scripts:
679
+ - `verify-session-continuity`;
680
+ - `verify-smart-revert`;
681
+ - `verify-interleave-fix`;
682
+ - `verify-stream-integrity`;
683
+ - `verify-billing`.
684
+ - **Run your checkout in OpenCode**: point the plugin at the repository directory,
685
+ `"plugins": [{ "package": "/path/to/opencode-claude-code-acpbridge", "options": { "command": "claude-agent-acp" } }]`.
686
+ OpenCode loads `<dir>/index.*`, and the root `index.js` re-exports `dist/`, so build first.
687
+ - **Smoke test**: `opencode run --standalone --agent claude-code -m acp/default "…"` in a test
688
+ project. The bridge's `question` dialog needs the interactive TUI.
689
+ - The package also exports `createACPProviderFromEnv`. It is the upstream
690
+ `@mcpc-tech/acp-ai-provider` without tool orchestration, if you only want plain chat.
691
+
692
+ Architecture, flows (deferred tools, sessions/resume, billing) and how to extend it are in
693
+ **[docs/DEVELOPMENT.md](docs/DEVELOPMENT.md)**. Example configs, one per use case, are in
694
+ **[examples/](examples/README.md)**:
695
+
696
+ | Example | Shows |
697
+ | --- | --- |
698
+ | [01-minimal.jsonc](examples/01-minimal.jsonc) | The smallest working config |
699
+ | [02-per-agent-permissions.jsonc](examples/02-per-agent-permissions.jsonc) | Permissions per agent |
700
+ | [03-opencode-fidelity.jsonc](examples/03-opencode-fidelity.jsonc) | Follow OpenCode's system prompt and agents (extra usage) |
701
+ | [04-model-and-effort.jsonc](examples/04-model-and-effort.jsonc) | Model and effort |
702
+ | [05-custom-agents.jsonc](examples/05-custom-agents.jsonc) | Your own injected agents, replacing the defaults |
703
+ | [06-claude-ecosystem.jsonc](examples/06-claude-ecosystem.jsonc) | Load more of your real Claude Code setup: settings, hooks and agents (`settingSources`), plus your own MCP servers and claude.ai connectors (`strictMcpConfig: false`) |
704
+ | [07-manual-provider.jsonc](examples/07-manual-provider.jsonc) | A manual provider |
705
+ | [08-permission-bridge.jsonc](examples/08-permission-bridge.jsonc) | The permission bridge |
392
706
 
393
707
  ```
394
- index.js # entrypoint de directorio local: re-exporta dist/ (Host.resolve busca <dir>/index.*)
708
+ index.js # local-directory entrypoint: re-exports dist/ (OpenCode loads <dir>/index.*)
395
709
  src/
396
- index.ts # re-exports: createACPModelProvider (provider) + default Plugin.define({ id, setup })
710
+ index.ts # exports createACPModelProvider (provider) + default Plugin.define (plugin)
397
711
  provider/
398
- factory.ts # createACPModelProvider (orquestador) + createACPProviderFromEnv (upstream sin orquestación)
399
- model.ts # ACPOrchestratorModel (LanguageModelV3): turnos, sesión persistente/resume, providerOptions, usage, puente question
400
- env.ts # config por variables de entorno
712
+ factory.ts # createACPModelProvider (orchestrator) + createACPProviderFromEnv (upstream, no orchestration)
713
+ model.ts # ACPOrchestratorModel (LanguageModelV3): turns, persistent session / resume / fork,
714
+ # tool-call queue and batching, steer/abort, question bridge, usage, compaction
715
+ history.ts # history fingerprint: legacy keys + anchors (historyMode), normalisation
716
+ recorder.ts # ACP_RECORD: records OpenCode's real prompts and every decision
717
+ env.ts # configuration from environment variables
401
718
  acp/
402
- mcp-host.ts # MCP server sintético (TCP): expone las tools de OpenCode y DIFIERE cada tools/call
403
- mcp-runtime.ts # runtime stdio que el agente spawnea (MCP a mano, sin deps) → TCP al host
404
- claude-config.ts # "cerebro limpio" + CLAUDE_CONFIG_DIR aislado con credenciales; modo/effort/systemPrompt
719
+ mcp-host.ts # internal MCP server (TCP): exposes OpenCode's tools and DEFERS each tools/call
720
+ mcp-runtime.ts # stdio runtime the agent spawns (hand-written MCP, no deps) → TCP to the host
721
+ claude-config.ts # clean brain + isolated CLAUDE_CONFIG_DIR with credentials; mode/effort/system prompt
405
722
  plugin/
406
- index.ts # Plugin.define setup: provider.transform (registro acp), agent.transform (claude-code + reglas),
407
- # session.hook("context") (ocSession/ocAgent/resume*), event: session.revert.* → clearLink
408
- bridge-rules.ts # store de reglas por agente + always.json; evaluate() fail-closed (ignora action:"*")
409
- discover.ts # conexión ACP efímera → modelos/modos/capabilities
410
- catalog.ts # metadata de models.dev + variants de effort + buildModelsInfo (→ Model.Info[])
411
- cache.ts · sessions.ts # cachés TTL / registro de sesiones OpenCode↔ACP
723
+ index.ts # Plugin.define: provider.transform (acp), agent.transform (claude-code + rules),
724
+ # context/compaction/generate hooks, title (no model), session.revert.* → clearLink
725
+ bridge-rules.ts # per-agent rule store + always.json; fail-closed evaluate() (ignores action:"*")
726
+ discover.ts # short-lived ACP connection → models / modes / capabilities
727
+ catalog.ts # models.dev metadata + effort variants → Model.Info[]
728
+ cache.ts · sessions.ts # TTL caches / OpenCode↔ACP session registry
729
+ log.ts # file log (~/.acp-model-provider/logs) + stderr
412
730
  bin/cli.ts # `opencode-claude-code-acpbridge sync`
731
+ test/ # node --test: fake-agent.mjs (in-process ACP agent), fixtures/v2 (recorded real prompts)
413
732
  ```
414
733
 
415
- Build: `npm run build` (genera `dist/`). El paquete exporta también `createACPProviderFromEnv` (provider upstream `@mcpc-tech/acp-ai-provider`, sin orquestación de tools) por si quieres el modo chat simple.
416
-
417
- **Smoke test V2**: proyecto de prueba con `.opencode/opencode.json` registrando el plugin por ruta de directorio, y `opencode --standalone run --agent claude-code -m acp/default "…"` (ver [docs/DEVELOPMENT.md §5](docs/DEVELOPMENT.md)). El diálogo `question` del puente requiere TUI interactiva.
734
+ Changes: [CHANGELOG.md](CHANGELOG.md).
418
735
 
419
- ## Licencia
736
+ ## License
420
737
 
421
- MIT
738
+ [MIT](LICENSE)