opencode-claude-code-acpbridge 0.10.0 → 0.11.0

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 (41) hide show
  1. package/CHANGELOG.md +335 -261
  2. package/LICENSE +21 -0
  3. package/README.md +633 -324
  4. package/dist/acp/claude-config.d.ts +1 -1
  5. package/dist/plugin/compat.d.ts +14 -0
  6. package/dist/plugin/compat.d.ts.map +1 -0
  7. package/dist/plugin/compat.js +45 -0
  8. package/dist/plugin/compat.js.map +1 -0
  9. package/dist/plugin/index.d.ts +8 -0
  10. package/dist/plugin/index.d.ts.map +1 -1
  11. package/dist/plugin/index.js +124 -30
  12. package/dist/plugin/index.js.map +1 -1
  13. package/dist/plugin/pairing.d.ts +66 -0
  14. package/dist/plugin/pairing.d.ts.map +1 -0
  15. package/dist/plugin/pairing.js +110 -0
  16. package/dist/plugin/pairing.js.map +1 -0
  17. package/dist/provider/factory.d.ts.map +1 -1
  18. package/dist/provider/factory.js +10 -1
  19. package/dist/provider/factory.js.map +1 -1
  20. package/dist/provider/model.d.ts +7 -1
  21. package/dist/provider/model.d.ts.map +1 -1
  22. package/dist/provider/model.js +54 -15
  23. package/dist/provider/model.js.map +1 -1
  24. package/docs/DEVELOPMENT.md +438 -138
  25. package/examples/01-minimal.jsonc +14 -9
  26. package/examples/02-per-agent-permissions.jsonc +39 -0
  27. package/examples/03-opencode-fidelity.jsonc +21 -0
  28. package/examples/04-model-and-effort.jsonc +36 -0
  29. package/examples/05-custom-agents.jsonc +32 -0
  30. package/examples/06-claude-ecosystem.jsonc +28 -0
  31. package/examples/07-manual-provider.jsonc +55 -0
  32. package/examples/08-permission-bridge.jsonc +42 -0
  33. package/examples/README.md +35 -17
  34. package/package.json +35 -30
  35. package/examples/02-permisos-por-agente.jsonc +0 -34
  36. package/examples/03-fidelidad-opencode.jsonc +0 -21
  37. package/examples/04-modelo-y-esfuerzo.jsonc +0 -36
  38. package/examples/05-agentes-personalizados.jsonc +0 -29
  39. package/examples/06-ecosistema-claude.jsonc +0 -24
  40. package/examples/07-provider-manual.jsonc +0 -42
  41. 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 one per Claude Code mode: `claude-default`, `claude-plan`, `claude-acceptedits`, `claude-auto`, `claude-dontask`, `claude-bypasspermissions`. |
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,390 +129,643 @@ 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 one `claude-<mode>` agent per
138
+ Claude Code mode (`claude-default`, `claude-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/opencode-claude-code-acpbridge"` 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 a **`claude-<mode>`** agent in OpenCode (`claude-default` to start). The `acp/…` models
166
+ belong to those agents only: see [Models are paired with the Claude Code agents](#models-are-paired-with-the-claude-code-agents).
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 and effort levels share one agent process.** The model is applied per session
182
+ with `session/set_model`, so switching `opus` → `sonnet` mid-conversation keeps the session: no
183
+ replay, no new process. The same goes for the agent's mode (`session/set_mode`) and effort.
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`). It is applied live
187
+ (`setSessionConfigOption`); the model **without** a variant goes back to the session's own
188
+ effort. Pick one in the TUI, or set it per agent (see [Agents and subagents](#agents-and-subagents)) or for the whole
189
+ provider:
135
190
 
136
- ---
191
+ ```jsonc
192
+ "options": { "command": "claude-agent-acp",
193
+ "claudeCode": { "model": "sonnet", "effort": "xhigh", "thinking": { "type": "enabled", "budgetTokens": 16000 } } }
194
+ ```
137
195
 
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` para agentes antiguos. `claude-agent-acp` ≥ 0.31 ya no lo lee: un `tools/call` diferido lo acota `MCP_TOOL_TIMEOUT` (≈ 27 h por defecto), así que esperar a que apruebes un permiso no corta nada. |
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[]` | **`["mcp__opencode"]`** | Tools auto-aprobadas (sin `requestPermission`). Por defecto las de OpenCode, para **todo** agente que use este provider (también los subagentes que heredan el modelo): OpenCode ya las autoriza, así no hay doble permiso. |
177
- | `nativeTools` | `string[]` | — | Tools **nativas** de Claude que OpenCode no cubre. Los agentes inyectados usan `["NotebookEdit", "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`. El `Read` nativo ya **no** va: lo que lee no queda en el historial de OpenCode (se perdía al cambiar de modelo) y el `read` de OpenCode V2 ya maneja imágenes y PDF. |
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). |
185
- | `historyMode` | `"shadow"\|"v2"\|"legacy"` | **`"shadow"`** | Cómo se reconoce lo que el agente ya sabe del historial (ver "Continuidad"). `shadow`: decide la huella clásica y la nueva (anclas: mensajes del usuario + ids de tools) corre en paralelo registrando cada discrepancia en el log. `v2`: deciden las anclas — inmune a que OpenCode re-renderice mensajes viejos o a que otros plugins etiqueten texto — y se activan la adopción del checkpoint tras compactar y el catch-up del checkpoint de otro modelo. Env: `ACP_HISTORY_MODE`. |
186
- | `catchupResultChars` | `number` | `8000` | Caracteres que se conservan de cada resultado de tool de **otro modelo** al ponerle al día tras un cambio de modelo. |
187
- | `parallelTools` | `string[]` | `read, glob, grep, webfetch, websearch, skill, subagent` | Tools de OpenCode anunciadas como de solo lectura (`readOnlyHint`): Claude Code las lanza a la vez y llegan a OpenCode en **un único paso**, que las ejecuta en paralelo. |
188
- | `toolBatchMs` | `number` | `40` | Espera de una tool paralela por sus hermanas antes de cerrar el paso. |
189
- | `autoCompactPct` | `number` | **`75`** | `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`: Claude compacta su propia sesión al 75 % del contexto, antes del umbral de OpenCode, así la compactación de OpenCode (que obliga a otra sesión) casi nunca salta. `0` deja el default de Claude Code. |
190
- | `nativeActivity` | `"text"\|"off"` | **`"text"`** | Las tools **nativas** (Task/Agent, WebSearch, Skill, NotebookEdit…) dejan una línea `⚙ …` en la respuesta, con el resultado de Task/WebSearch/Skill: así queda en el historial de OpenCode y la ve cualquier modelo que continúe la sesión. |
191
- | `nativeActivityChars` | `number` | `2000` | Tope del resultado nativo escrito en esa línea. |
192
- | `maxLiveSessions` | `number` | `6` | Conversaciones vivas a la vez (cada una es un proceso `claude`); las más antiguas inactivas se cierran. |
193
- | `idleSessionTtlMs` / `childSessionTtlMs` | `number` | `900000` / `120000` | Inactividad tras la que una sesión **reanudable** se cierra (subagentes: la segunda). Volver solo cuesta arrancar el proceso: la caché de Anthropic dura ~1 h en suscripción. |
194
- | `smartRevert` | `boolean` | **`true`** | En un revert, bifurca la sesión de Claude justo antes del mensaje revertido (`resumeSessionAt`, localizado en su transcripción) en vez de abrir otra con replay; si no puede, hace el replay de siempre. Verificado con el agente real (`scripts/verify-smart-revert.mjs`). `false` lo desactiva. |
196
+ > [!NOTE]
197
+ > `opencode run` **without `-m` ignores an agent's `model`**: the V2 CLI uses the global
198
+ > model from config. In the CLI pass `-m acp/…`. In the TUI, the agent and model pickers do
199
+ > apply the model each agent declares.
195
200
 
196
201
  ---
197
202
 
198
- ## Selección de modelo y razonamiento
203
+ ## Billing: subscription vs extra usage
199
204
 
200
- 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. Todos comparten **un solo proceso del agente**: el modelo se aplica por sesión con `session/set_model`, así que cambiar de `opus` a `sonnet` a mitad de conversación conserva la sesión (sin replay ni proceso nuevo).
205
+ In plain ACP the client doesn't control the agent's system prompt. `claude-agent-acp` adds an
206
+ extension (`_meta.systemPrompt`) to pass OpenCode's system prompt along. **This matters for
207
+ billing:** Anthropic classifies the session by its system prompt. With OpenCode's system prompt
208
+ the session counts as a **third-party app** and is billed as **extra usage**; Claude Code's
209
+ official preset is billed to your **Pro/Max subscription**.
201
210
 
202
- También puedes fijarlo en el provider o por agente: `"options": { "claudeCode": { "model": "sonnet" } }`, o en tu config `"agents": { "claude-code": { "model": "acp/sonnet" } }`.
211
+ `claudeCode.systemPromptMode` sets that trade-off:
203
212
 
204
- > ⚠️ **`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.
213
+ | Value | Effect | Billing |
214
+ | --- | --- | --- |
215
+ | `"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** |
216
+ | `"append"` | Preset + OpenCode's system prompt appended: full OpenCode fidelity. | Extra usage |
217
+ | `"replace"` | OpenCode's system prompt replaces the preset. | Extra usage |
205
218
 
206
- Valores: aliases (`sonnet`, `haiku`, `opus`, `default`), variantes (`sonnet[1m]` = contexto 1M) o IDs completos (`claude-sonnet-4-6`).
219
+ With `preset`, `forwardEnvContext` (on by default) still passes the **factual** part of
220
+ OpenCode's system prompt to Claude as user context, so Claude knows where it is working:
221
+ - the `<env>` block: working directory, workspace root, git, platform, date;
222
+ - `<available_references>`.
207
223
 
208
- > **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`).
209
- >
210
- > **Versiones**: los aliases resuelven a la versión actual del backend; para fijar una usa el ID completo o un sufijo (`sonnet[1m]`).
211
- >
212
- > **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`.
224
+ OpenCode's behavioural instructions are never forwarded, so this stays on the subscription.
213
225
 
214
- 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:
215
-
216
- ```jsonc
217
- "options": { "claudeCode": { "model": "sonnet", "effort": "xhigh",
218
- "thinking": { "type": "enabled", "budgetTokens": 16000 } } }
219
- ```
226
+ > Tested empirically:
227
+ > - The switch to extra usage comes from an Anthropic classifier that reads the system
228
+ > prompt and recognises a third-party app. The name, the mode or the size don't trigger it.
229
+ > - With `preset`, `scripts/verify-billing.mjs` measures **0 extra usage**, including with
230
+ > the native features the injected agents enable.
220
231
 
221
232
  ---
222
233
 
223
- ## System prompt y facturación (suscripción vs extra usage)
234
+ ## Configuration reference
235
+
236
+ ### Plugin options
237
+
238
+ Everything goes in the plugin's `options`. Options not specific to the plugin are passed on to
239
+ the provider.
240
+
241
+ | Option | Type | Env var | Default | Description |
242
+ | --- | --- | --- | --- | --- |
243
+ | `command` | `string` | `ACP_COMMAND` | — | ACP agent command, e.g. `"claude-agent-acp"`. **Without it the plugin doesn't register anything** (manual setup, see below). |
244
+ | `args` | `string[]` | `ACP_ARGS` (JSON array or space-separated) | — | Arguments for `command`. |
245
+ | `cwd` | `string` | `ACP_CWD` | server's working directory | Working directory of the agent process. |
246
+ | `env` | `Record<string,string>` | — | — | Extra environment variables for the agent process. |
247
+ | `claudeExecutable` | `string` | `CLAUDE_CODE_EXECUTABLE` | `command -v claude` | Path to the `claude` binary. |
248
+ | `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. |
249
+ | `providerId` | `string` | — | `"acp"` | Provider id the models are registered under (see [below](#changing-the-provider-id)). |
250
+ | `name` | `string` | — | `"Claude Code (ACP)"` | Provider display name. |
251
+ | `agents` | `false \| Record` | — | one per mode | `false` injects no agents. A `Record` **replaces** the default `claude-<mode>` definitions entirely, including their native toolset ([details](#agents-and-subagents)). |
252
+ | `agentModel` | `string` | — | `"default"` | Model of the injected agents. |
253
+ | `pairModels` | `boolean` | — | `true` | Reserve the provider's models for the injected agents, and those agents for the provider's models ([details](#models-are-paired-with-the-claude-code-agents)). `false` lets any agent use any model. |
254
+ | `titleFromModel` | `boolean` | — | `false` | Let the model title sessions. By default the plugin titles them from the first user message, with no model call. |
255
+ | `npm` | `string` | — | auto | Package spec the provider is loaded from. Only needed in unusual setups. |
256
+ | `claudeCode` | `object` | — | "clean brain" | How Claude Code runs: the table below. |
257
+
258
+ ### `claudeCode` options
259
+
260
+ **Ecosystem: what Claude Code loads**
261
+
262
+ | Field | Type | Default | Description |
263
+ | --- | --- | --- | --- |
264
+ | `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. |
265
+ | `settingSources` | `("user"\|"project"\|"local")[]` | `[]` | Claude Code settings to load (hooks, agents…). |
266
+ | `tools` | `string[]` | `[]` | Built-in Claude Code tools to enable. `[]` = none. Overrides the toggles below. |
267
+ | `disallowedTools` | `string[]` | — | Built-in tools to forbid. |
268
+ | `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. |
269
+ | `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. |
270
+ | `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. |
271
+ | `resourceSearch` | `boolean` | — | Enables `ListMcpResources` / `ReadMcpResource`. |
272
+ | `nativeSubagents` | `boolean \| Record` | — | Native subagents (`Task`). `true` adds a `general` subagent that works through OpenCode's tools; a `Record` defines your own. |
273
+ | `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. |
274
+ | `skillShell` | `boolean` | `false` | Lets skills use the native `Bash`. By default they work through OpenCode's tools. |
275
+ | `projectMemory` | `boolean` | — | Loads the project's `CLAUDE.md` / `AGENTS.md` (`settingSources: "project"`). |
276
+ | `agents`, `hooks`, `mcpServers`, `plugins`, `systemPrompt` | — | — | Inject your own subagents, hooks, MCP servers, plugins or an advanced system prompt. |
277
+ | `options` | `Record<string,unknown>` | — | Free passthrough to `_meta.claudeCode.options`, for any Claude Agent SDK option. |
278
+
279
+ **Model and reasoning**
280
+
281
+ | Field | Type | Default | Description |
282
+ | --- | --- | --- | --- |
283
+ | `model` | `string` | the OpenCode model id | Claude model: alias (`sonnet`, `haiku`, `opus`, `default`), variant (`sonnet[1m]`) or full id. |
284
+ | `fallbackModel` | `string` | — | Model to use if the primary one fails. |
285
+ | `effort` | `"low"\|"medium"\|"high"\|"xhigh"\|"max"` | agent's default | Reasoning effort. The `#effort` model variants set it too. |
286
+ | `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. |
287
+ | `maxThinkingTokens` | `number` | — | Deprecated, use `thinking`. |
288
+
289
+ **Limits, mode and system prompt**
290
+
291
+ | Field | Type | Default | Description |
292
+ | --- | --- | --- | --- |
293
+ | `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. |
294
+ | `permissionMode` | same values | — | Legacy. The ACP agent ignores it for the session mode: use `mode`. |
295
+ | `maxTurns` | `number` | — | Max agent turns. |
296
+ | `maxBudgetUsd` | `number` | — | Spending cap per turn. |
297
+ | `systemPromptMode` | `"preset"\|"append"\|"replace"` | `"preset"` | See [Billing](#billing-subscription-vs-extra-usage). |
298
+ | `forwardEnvContext` | `boolean` | `true` | Forward OpenCode's factual `<env>` / `<available_references>` blocks: in full once per session, then as deltas. |
299
+
300
+ **Continuity, performance and sessions**
301
+
302
+ | Field | Type | Default | Description |
303
+ | --- | --- | --- | --- |
304
+ | `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`. |
305
+ | `catchupResultChars` | `number` | `8000` | Characters kept from each tool result of **another model** when Claude is caught up after a model switch. |
306
+ | `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. |
307
+ | `toolBatchMs` | `number` | `40` | How long a read-only call waits for parallel siblings before the step is closed. |
308
+ | `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. |
309
+ | `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. |
310
+ | `nativeActivityChars` | `number` | `2000` | Cap on the native result written into that line. |
311
+ | `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. |
312
+ | `maxLiveSessions` | `number` | `6` | Conversations kept open at once (each is a `claude` process). The oldest idle ones are closed. |
313
+ | `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. |
314
+ | `childSessionTtlMs` | `number` | `120000` (2 min) | Same for OpenCode subagent sessions. |
315
+
316
+ ### Manual provider (advanced)
317
+
318
+ Without `command` (and without `ACP_COMMAND`) the plugin **doesn't register the provider**, so
319
+ you can declare it yourself. OpenCode V2 still accepts the classic `provider` key and migrates
320
+ it. The plugin keeps a provider you declared and still injects the agents and the per-call
321
+ hooks. A full example with costs and limits:
322
+ [examples/07-manual-provider.jsonc](examples/07-manual-provider.jsonc).
224
323
 
225
- 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.
324
+ ```jsonc
325
+ {
326
+ "$schema": "https://opencode.ai/config.json",
327
+ "plugins": [{ "package": "opencode-claude-code-acpbridge" }],
328
+ "provider": {
329
+ "acp": {
330
+ "npm": "opencode-claude-code-acpbridge",
331
+ "name": "Claude Code (ACP)",
332
+ "options": { "command": "claude-agent-acp" },
333
+ "models": { "sonnet": { "id": "sonnet", "tool_call": true, "reasoning": true } }
334
+ }
335
+ }
336
+ }
337
+ ```
226
338
 
227
- `systemPromptMode` controla ese equilibrio:
339
+ ### Changing the provider id
228
340
 
229
- - `"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.
230
- - `"append"`: preset oficial + el system de OpenCode añadido. Fidelidad total a OpenCode, **pero facturado como EXTRA USAGE**.
231
- - `"replace"`: el system de OpenCode pasa a ser todo el system prompt. También **extra usage**.
341
+ The provider registers as **`acp`**. To use another id (typically **`anthropic`**, so that
342
+ [opencode-quota](https://www.npmjs.com/package/@slkiser/opencode-quota) shows your
343
+ **subscription** quota), set it in the **plugin** options. Don't declare a second provider by
344
+ hand, so there is only one backend:
232
345
 
233
346
  ```jsonc
234
- // suscripción (por defecto — no hace falta declararlo):
235
- "options": { "claudeCode": { "systemPromptMode": "preset" } }
236
- // fidelidad total a OpenCode, a cambio de extra usage:
237
- "options": { "claudeCode": { "systemPromptMode": "append" } }
347
+ "plugins": [
348
+ { "package": "opencode-claude-code-acpbridge",
349
+ "options": { "command": "claude-agent-acp", "providerId": "anthropic" } }
350
+ ]
238
351
  ```
239
352
 
240
- > 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**.
353
+ Auto-registration, resume, the permission bridge and the agents (`claude-default` →
354
+ `anthropic/default`) then all use that id.
355
+
356
+ > [!WARNING]
357
+ > `"anthropic"` **replaces OpenCode's official Anthropic provider**. That's fine if you don't
358
+ > use the Anthropic API directly. OpenCode may also list extra models from models.dev in the
359
+ > picker: use only the ones the agent reports (`anthropic/default`, `anthropic/sonnet`…). To
360
+ > use the API directly again, remove `providerId`.
241
361
 
242
362
  ---
243
363
 
244
- ## Agentes Claude Code (modos, esfuerzo, subagentes)
364
+ ## Agents and subagents
365
+
366
+ The plugin **injects one agent per Claude Code session mode**, as the agent reports them on
367
+ start (model `acp/default`; `claude-default` comes first):
245
368
 
246
- Al auto-registrarse, el plugin **inyecta dos agentes** en OpenCode (selector de agentes), igual que otros plugins inyectan los suyos:
369
+ | Agent | Mode | Native tools (Skill, Task, WebSearch, NotebookEdit…) |
370
+ | --- | --- | --- |
371
+ | `claude-default` | `default` | Every one goes through the [permission bridge](#tools-and-the-permission-bridge): **OpenCode stays the only authority**. |
372
+ | `claude-plan` | `plan` | Claude **plans** (researches, reads, writes the plan) without making changes until you approve it. Effort variant `high`. |
373
+ | `claude-acceptedits` | `acceptEdits` | Native edits are accepted without asking. |
374
+ | `claude-auto` | `auto` | Claude Code's classifier approves or denies each native action. |
375
+ | `claude-dontask` | `dontAsk` | Native actions not pre-approved are denied, never asked. |
376
+ | `claude-bypasspermissions` | `bypassPermissions` | Never asks: the permission bridge is skipped. |
247
377
 
248
- - **`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).
249
- - **`claude-code-plan`** — modo **`plan`**: el agente **planifica** (investiga, lee, redacta el plan) sin hacer cambios destructivos. Variante de esfuerzo `high`.
378
+ They share the same native toolset and differ only in their starting mode. **The mode only
379
+ governs Claude's native tools.** OpenCode's own tools (`bash`, `edit`, `write`, MCP…) always
380
+ run with the OpenCode permissions of the agent, whatever its mode: restrict or open those in
381
+ the `agents` section of your config (below). **Effort** is picked as usual, as a variant of the
382
+ `acp/…` model.
250
383
 
251
- Cámbialos o desactívalos desde las opciones del plugin:
384
+ To **adjust** them (permissions, model, description), use the `agents` section of your
385
+ OpenCode config, shown just below. To **replace** them with your own agents, use the plugin's
386
+ `agents` option:
252
387
 
253
388
  ```jsonc
254
389
  "plugins": [{ "package": "opencode-claude-code-acpbridge",
255
390
  "options": { "command": "claude-agent-acp",
256
- "agents": { // o "agents": false para no inyectar ninguno
257
- "claude-code": { "model": "default", "options": { "mode": "default" } },
258
- "claude-code-plan": { "model": "default", "variant": "high", "options": { "mode": "plan" } }
391
+ "agents": { // or "agents": false to inject none
392
+ "claude-default": { "model": "default", "options": { "mode": "default" } },
393
+ "claude-plan": { "model": "default", "variant": "high", "options": { "mode": "plan" } }
259
394
  }
260
395
  }
261
396
  }]
262
397
  ```
263
398
 
264
- 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.
399
+ > [!WARNING]
400
+ > A plugin-level `agents` record **replaces** the built-in definitions (and the pairing then
401
+ > covers exactly the agents you list). Your `options` are all
402
+ > those agents get, so the native toolset of the defaults is gone unless you list it:
403
+ > - `disallowedTools`;
404
+ > - `resourceSearch`, `nativeSubagents`;
405
+ > - `nativeTools: ["NotebookEdit", "ExitPlanMode", "WebSearch"]`;
406
+ > - `projectMemory`, `nativeSkills`.
407
+ >
408
+ > A plan agent without `ExitPlanMode` can't leave plan mode. See
409
+ > [examples/05-custom-agents.jsonc](examples/05-custom-agents.jsonc).
410
+
411
+ Each agent's `options` (mode, effort, `claudeCode` fields…) reach the provider **per call**,
412
+ through the plugin's `context` hook. They are applied **live** (`setSessionMode` /
413
+ `setSessionConfigOption`), without recreating the session.
265
414
 
266
- > **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:
415
+ > **Your `opencode.json` wins.** In V2, agents live in the `agents` section of your config, and
416
+ > your fields beat the plugin's: `description` and `model` are only filled in if you don't set
417
+ > them. That's the place to restrict tools with a `permissions` ruleset, without touching the
418
+ > plugin:
267
419
  > ```jsonc
268
420
  > "agents": {
269
- > "claude-code": {
421
+ > "claude-default": {
270
422
  > "permissions": [
271
423
  > { "action": "edit", "resource": "*", "effect": "deny" },
272
424
  > { "action": "bash", "resource": "*", "effect": "ask" }
273
- > ] // hereda model y options del plugin
425
+ > ]
274
426
  > }
275
427
  > }
276
428
  > ```
277
- > También `"disabled": true` para apagar un agente inyectado.
278
-
279
- - **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).
280
- - **Subagentes — dos vías.** La tool **`subagent` de OpenCode** es la preferida para trabajo de verdad: la sesión hija se ve en OpenCode, **cualquier modelo** puede continuarla y su resultado queda en el historial compartido. El **`Task` nativo** de Claude Code (subagente `general` + tus `~/.claude/agents`, cargados vía `settingSources: user` de `nativeSkills`) queda para tareas rápidas o tus agentes especializados; su resultado se escribe en la respuesta (ver `nativeActivity`). Las descripciones de ambas tools guían al agente. Si un agente tuyo depende de `Bash`/`Edit` nativos, usará las tools de OpenCode.
281
- - **Subagentes de OpenCode sobre este provider**: un hijo hereda el modelo del padre (`acp`). Reciben el perfil base (`allowedTools: ["mcp__opencode"]`) y, si su agente no tiene `question` (el `general` de OpenCode la deniega), un permiso nativo se deniega con motivo en vez de colgar. Sus sesiones se cierran a los 2 min de inactividad.
282
- - **Cambiar a un agente con otro perfil nativo** (otras tools nativas, `allowedTools`…) **bifurca** la sesión (`session/fork`) con el perfil nuevo: mismo contexto, sin replay.
283
- - **Aprobar el plan** (`ExitPlanMode`): el diálogo ofrece las opciones reales de Claude Code — *auto*, *aceptar ediciones*, *aprobar cada edición*, *seguir planificando* — y, si **escribes** una respuesta, el plan se rechaza y tu texto le llega como feedback para revisarlo. El modo elegido se conserva aunque luego cambies del agente plan a `claude-code`.
284
- - **Reanudar sin reenviar historial**: el plugin guarda un registro `~/.acp-model-provider/sessions.json` (sessionID de OpenCode → sessionId de Claude Code, más los prefijos de id propios). Al reabrir una sesión, el provider hace `resumeSession` en vez de reenviar todo el historial → **ahorra tokens**. Entradas de más de 30 días se podan solas.
285
- - **Títulos**: el plugin pone el título de la sesión a partir del primer mensaje (sin llamar al modelo). Con `systemPromptMode: "preset"` las instrucciones de título de OpenCode no llegaban a Claude, que respondía al mensaje y el título salía basura. `titleFromModel: true` (opción del plugin) restaura la llamada.
429
+ > `"disabled": true` turns an injected agent off.
430
+
431
+ - **Modes.** OpenCode runs its tools with its own permissions, so Claude Code's permission
432
+ modes don't change *who* authorises them:
433
+ - `bypassPermissions` only skips the `requestPermission` round trip for native tools;
434
+ - `plan` is the one with a real effect of its own;
435
+ - `dontAsk` denies the native tools outright (skills, native subagents, web search).
436
+ - **Two ways to delegate.**
437
+ - **OpenCode's `subagent` tool** is preferred for real work. The child session is visible in
438
+ OpenCode, **any model** can continue it, and its result stays in the shared history.
439
+ - **Claude Code's native `Task`** (the `general` subagent plus your `~/.claude/agents`) is for
440
+ quick tasks or your specialised agents. Its result is written into the answer (see
441
+ `nativeActivity`).
442
+ - Both tools' descriptions steer Claude. If one of your agents relies on native
443
+ `Bash`/`Edit`, it uses OpenCode's tools instead.
444
+ - **OpenCode subagents run on another model.** OpenCode gives a child session its parent's model
445
+ unless the subagent has its own, and the `acp` models are reserved for the `claude-*` agents.
446
+ So when a `claude-*` agent launches `general`, `explore`…, the plugin passes the subagent its
447
+ own model, or OpenCode's default `model` when it has none. Without either (or with
448
+ `model: "acp/…"` in the call), the call fails with a message saying what to set. With
449
+ `pairModels: false`, child sessions inherit `acp` as before and:
450
+ - get the base profile (`allowedTools: ["mcp__opencode"]`);
451
+ - get a native permission request denied with a reason if their agent can't use `question`
452
+ (OpenCode's `general` denies it), instead of hanging;
453
+ - are closed after 2 minutes idle.
454
+ - **Switching to an agent with a different native profile** (other native tools,
455
+ `allowedTools`…) **forks** the session (`session/fork`) with the new profile: same context,
456
+ no replay.
457
+ - **Approving a plan** (`ExitPlanMode`). The dialog offers Claude Code's real choices:
458
+ - auto;
459
+ - accept edits;
460
+ - approve each edit;
461
+ - keep planning.
462
+
463
+ If you **type** an answer instead, the plan is rejected and your text reaches Claude as
464
+ feedback. The mode you chose survives switching from `claude-plan` to `claude-default`.
465
+ - **Resuming without resending history.** `~/.acp-model-provider/sessions.json` maps each
466
+ OpenCode session to its Claude Code session. On reopening, the provider resumes it
467
+ (`resumeSession`) instead of replaying the whole history. Entries older than 30 days are
468
+ pruned automatically, and the file keeps at most 500.
469
+ - **Titles.** With `systemPromptMode: "preset"`, OpenCode's title instructions never reach
470
+ Claude, which would answer the message instead. So the plugin titles sessions from their
471
+ first message, with no model call. `titleFromModel: true` restores the model call.
472
+
473
+
474
+ ### Models are paired with the Claude Code agents
475
+
476
+ The `acp/…` models are **only for the `claude-*` agents**, and those agents **only use `acp/…`
477
+ models** (`pairModels`, on by default):
478
+
479
+ - **Switching agent switches the model.** Picking a `claude-*` agent puts the session on that
480
+ agent's `acp` model; going back to `build` (or any other agent) puts it back on that agent's
481
+ model, or the last non-`acp` model the session used, or OpenCode's default `model`.
482
+ - **OpenCode's model picker still lists every model for every agent**: V2 has no per-agent model
483
+ list. If you pick a model that breaks the pair, the plugin moves the session back to a valid
484
+ one, and an `acp` request from another agent fails at once with
485
+ `Claude Code: the model … is reserved for the Claude Code agents (claude-*)…`.
486
+ - **Subagents** never inherit an `acp` model (see above).
487
+ - `pairModels: false` turns all of this off.
286
488
 
287
489
  ---
288
490
 
289
- ## Manejo de las herramientas y puente de permisos
491
+ ## Tools and the permission bridge
492
+
493
+ The `claude-*` agents get Claude Code's native power without bypassing OpenCode:
494
+
495
+ - **Common tools → OpenCode runs them.** Claude reaches every tool OpenCode exposes through
496
+ MCP: OpenCode's own (`read`, `write`, `bash`, `edit`, `grep`…) and those of your MCP servers.
497
+ They run in OpenCode, with its permissions, TUI and history.
498
+ - They're in `allowedTools: ["mcp__opencode"]`, so they **don't prompt twice**.
499
+ - Claude's own versions are disabled: `Bash`, `Read`, `Write`, `Edit`, `MultiEdit`, `Glob`,
500
+ `Grep`, `WebFetch`, `TodoWrite`. Whatever Claude reads lands in OpenCode's history, which
501
+ another model may need later.
502
+ - **Native capabilities OpenCode doesn't have**, on by default in the injected agents:
503
+ - skills (`Skill`);
504
+ - native subagents (`Task`, working through OpenCode's tools);
505
+ - MCP resource search (`ListMcpResources` / `ReadMcpResource`);
506
+ - `NotebookEdit`, `WebSearch`, `ExitPlanMode`;
507
+ - project memory (`CLAUDE.md` / `AGENTS.md`).
508
+
509
+ What they do is written into the answer as `⚙ …` (`nativeActivity`), so it isn't lost if
510
+ you switch models.
511
+ - **Parallel tools.** Read-only tools (`parallelTools`) are announced with `readOnlyHint`.
512
+ Claude issues them together, and OpenCode runs them in parallel in one step. Calls that
513
+ arrive while OpenCode is still running the previous step are queued for the next one, never
514
+ dropped; native subagents working in parallel do this, for example.
515
+ - **Context-pruning plugins** ([opencode-dcp](https://www.npmjs.com/package/@p4r4d0xb0x/opencode-dcp)).
516
+ The plugin denies `compress` to the `claude-*` agents. DCP rewrites OpenCode's copy of
517
+ the history, but the Claude Code session keeps its own context, so pruning only caused
518
+ divergences and replays. DCP keeps working for your other agents.
519
+ - **The permission bridge.** When Claude (or a native subagent) wants a **native** tool,
520
+ Claude Code asks for permission over ACP (`requestPermission`). The provider turns that
521
+ request into a call to OpenCode's own **`question`** tool. The dialog appears **in your TUI**
522
+ (`Allow once` / `Always allow` / `Deny`), and **your answer** goes back to Claude.
523
+ - Rules are checked first and settle without a dialog. They come from your
524
+ `agents.<name>.permissions`; `action: "*"` defaults are ignored.
525
+ - Anything not covered opens the dialog: the bridge **fails closed**.
526
+ - `Always allow` answers are stored in `~/.acp-model-provider/always.json`.
527
+ - The bridge needs the agent **not** to be in `bypassPermissions`: `claude-bypasspermissions`
528
+ runs native tools without asking anyone.
529
+ - **The classic "clean brain"**, where OpenCode runs everything and there are no native tools:
530
+ use `mode: "bypassPermissions"` with no native toggles, or a manual provider with
531
+ `claudeCode.tools: []`.
290
532
 
291
- El agente `claude-code` combina **lo mejor de ambos mundos** — *potencia nativa sin estropear nada*:
533
+ ---
292
534
 
293
- - **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**.
294
- - **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. Lo que hacen queda escrito en la respuesta como `⚙ …` (`nativeActivity`), para que no se pierda si cambias de modelo.
295
- - **Tools en paralelo**: las de solo lectura (`parallelTools`) se anuncian con `readOnlyHint`; Claude Code las lanza juntas y OpenCode las ejecuta en paralelo en un solo paso. Llamadas que llegan mientras OpenCode ejecuta el paso anterior (p. ej. subagentes nativos en paralelo) se encolan para el siguiente — nunca se pierden.
296
- - **Plugins de poda de contexto (opencode-dcp)**: el plugin deniega `compress` a los agentes `claude-code*`. DCP reescribe la copia del historial de OpenCode (resúmenes, etiquetas en cada mensaje); la sesión de Claude Code tiene su propio contexto, así que solo provocaba divergencias y replays. Para tus otros agentes DCP sigue activo.
297
- - **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.
298
- - 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).
299
- - Requiere que el agente NO esté en `bypassPermissions` → el agente `claude-code` usa `mode: "default"`.
300
- - **Facturación**: todos estos features mantienen tu **suscripción** (verificado con `scripts/verify-billing.mjs`, 0 extra usage) — son nativos de Claude Code.
301
- - Para el modelo **clásico "cerebro limpio"** (sin nativas, OpenCode ejecuta todo) usa `mode: "bypassPermissions"` + sin toggles, o el provider manual con `claudeCode.tools: []`.
535
+ ## Switching models mid-session, and token cost
536
+
537
+ OpenCode sends the **full** history on every call, while an ACP session keeps **state**. The
538
+ provider keeps one Claude Code session per conversation and sends it **only what it hasn't
539
+ seen**. Claude's prompt cache lives with that session, so the session is recreated as rarely
540
+ as possible. You can switch between a `claude-*` agent (on `acp`) and any other agent and
541
+ model in the same conversation, in both directions, and carry on.
542
+
543
+ - **Claude's own answer isn't sent back.** OpenCode stores Claude's reply and resends it on the
544
+ next turn. The provider recognises it (by the text it emitted and its own tool ids) and
545
+ skips it.
546
+ - **Another model in between.** Say you switch to another provider and come back: the other
547
+ model's turns reach Claude wrapped in `<other_model_turn>`, so Claude doesn't believe it
548
+ wrote them. They include that model's tool calls and results (`catchupResultChars`). Same
549
+ prompt cache, no new session.
550
+ - **The other way round.** What Claude does with native tools is written into the answer
551
+ (`nativeActivity`), so the other model sees it.
552
+ - **Usage limit.** If your Claude quota runs out, the error says so plainly and isn't retried
553
+ in a loop:
554
+ `Claude Code: usage limit reached (resets: <when>). Switch to another agent in OpenCode (not
555
+ claude-*) to continue with its model; the Claude Code session is kept for when you come back.`
556
+ - **Typing while Claude works** (*steer*), or **interrupting and typing something else**, both
557
+ work:
558
+ - your message reaches Claude, through Claude Code's own queue or together with the pending
559
+ tool result;
560
+ - an interrupted turn is cancelled on the agent before the new one starts.
561
+ - **Changing agent** (`claude-default` ↔ `claude-plan` …) or **toolset** keeps the session,
562
+ live. Moving to an agent with **another native profile** forks the session.
563
+ - **Changing `acp` model** (opus ↔ sonnet) keeps the session (`session/set_model`).
564
+ - **Compaction.** Claude compacts its own session before OpenCode would (`autoCompactPct`). If
565
+ OpenCode compacts anyway, the summary is asked of the **live session**, with a warm cache,
566
+ not of a new session holding the whole history. With `historyMode: "v2"`, the session also
567
+ compacts natively and **adopts** OpenCode's checkpoint, or catches up on another model's
568
+ checkpoint, without a new session.
569
+ - **Reverting** forks the session just before the reverted message (`smartRevert`). Claude
570
+ "forgets" the undone part, with no replay and the prefix still cached. When there's no fork
571
+ point (e.g. after restarting the process), a new session is created. A full replay is
572
+ bounded (~400K characters) and labelled as history, with your current request apart.
573
+
574
+ Every decision is logged in `~/.acp-model-provider/logs/acp-YYYYMMDD.log`: reuse,
575
+ continuation, new session, `historyMode: "shadow"` disagreements… In a normal conversation
576
+ you'll see `"decision":"reuse"` on every turn, and `"drop"` only on reverts and compactions.
302
577
 
303
578
  ---
304
579
 
305
- ## Multimodalidad (imagen, PDF, audio, vídeo)
580
+ ## Images, PDFs and other attachments
581
+
582
+ What the agent accepts is announced in its `promptCapabilities`; see it with `ACP_DEBUG=1`.
583
+ With the current `claude-agent-acp` it's `{"image": true, "embeddedContext": true}`.
584
+ Attachments arrive as `file` parts of OpenCode's prompt, and the provider converts them to ACP
585
+ content blocks according to those capabilities:
306
586
 
307
- 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:
587
+ | Type | Supported | How |
588
+ | --- | --- | --- |
589
+ | **Image** (`image/*`) | ✅ | `image` content block (base64). |
590
+ | **PDF / documents** (`application/pdf`, `text/*`, …) | ✅ | Embedded resource (`resource` block, needs `embeddedContext`). |
591
+ | **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. |
592
+ | **Video** (`video/*`) | ❌ | Not representable in ACP and not understood by Claude; skipped with a note. |
308
593
 
309
- | Tipo | Soporte | Cómo |
310
- |---|---|---|
311
- | **Imagen** (`image/*`) | ✅ | ContentBlock `image` (base64). *Validado.* |
312
- | **PDF / documentos** (`application/pdf`, `text/*`, …) | ✅ | Recurso embebido (ContentBlock `resource`, requiere `embeddedContext`). |
313
- | **Audio** (`audio/*`) | ❌ hoy | El agente no anuncia `audio`; se omite con una nota. Si una versión futura lo soporta, se enviará automáticamente. |
314
- | **Vídeo** (`video/*`) | ❌ | No existe en ACP ni lo procesa Claude; se omite con una nota. |
594
+ Remote URLs without embedded data are skipped: the agent only receives attachments with bytes.
315
595
 
316
- Las URLs remotas (sin datos embebidos) se omiten — el agente recibe solo adjuntos con bytes (base64).
596
+ ---
317
597
 
318
- ## Retomar la sesión en Claude Code
598
+ ## Resuming a session in Claude Code
319
599
 
320
- Por defecto (`configDir: false`) el agente usa **tu** `~/.claude`, así que toda conversación
321
- iniciada desde OpenCode queda en `~/.claude/projects/<proyecto>/<id>.jsonl` y se puede
322
- continuar en la terminal:
600
+ By default (`configDir: false`) the agent uses **your** `~/.claude`, so every conversation
601
+ started from OpenCode is stored in `~/.claude/projects/<project>/<id>.jsonl`. You can continue
602
+ it in a terminal:
323
603
 
324
604
  ```bash
325
- # el provider imprime el id al crear cada sesión, sin necesidad de ACP_DEBUG:
326
- # [acp] session 1c66e017-… — retomable con: claude --resume 1c66e017-…
605
+ # the provider prints the id whenever it creates a session (no debug flag needed):
606
+ # [acp] session 1c66e017-… — resumable with: claude --resume 1c66e017-…
327
607
  claude --resume 1c66e017-4536-4157-80aa-e451420520e0
328
608
  ```
329
609
 
330
- Debe ejecutarse en el **mismo directorio de trabajo**: Claude Code indexa las sesiones por
331
- `cwd`. Si prefieres el aislamiento anterior (sesiones fuera de tu `~/.claude` y por tanto
332
- invisibles para `--resume`), pon `"configDir": "isolated"`.
610
+ Run it **in the same working directory**: Claude Code indexes sessions by `cwd`. For the old
611
+ isolation, set `"configDir": "isolated"`: sessions then live outside your `~/.claude` and are
612
+ invisible to `--resume`.
333
613
 
334
- Que se herede el directorio de configuración **no** significa que el agente cargue tu
335
- ecosistema: eso lo siguen decidiendo `settingSources` (por defecto `[]`), `tools` y
336
- `strictMcpConfig`. `configDir` solo decide **dónde vive el estado**.
614
+ Sharing the config directory **doesn't** load your ecosystem: `settingSources` (default `[]`),
615
+ `tools` and `strictMcpConfig` still decide that. `configDir` only decides **where the state
616
+ lives**.
337
617
 
338
618
  ---
339
619
 
340
- ## Continuidad de sesión y coste de tokens
341
-
342
- OpenCode reenvía el historial **completo** en cada llamada; la sesión ACP es **con estado**.
343
- El provider mantiene una sesión de Claude Code por conversación y le manda **solo lo que no ha
344
- visto**. El prompt cache de Claude vive con esa sesión, así que se recrea lo menos posible:
345
-
346
- - **Tu propia respuesta no vuelve.** OpenCode guarda la respuesta del agente y la reenvía en
347
- el turno siguiente; el provider la reconoce (por los textos que emitió y los ids de sus
348
- tools) y no se la manda de vuelta.
349
- - **Otro modelo en medio** (cambiaste a Zen/OpenRouter y vuelves): sus turnos le llegan a
350
- Claude marcados como `<other_model_turn>` — no como si los hubiera escrito él — con sus
351
- tool-calls y resultados (`catchupResultChars`). Mismo prompt cache, sin sesión nueva.
352
- - **Al revés**: lo que Claude hace con tools nativas queda escrito en la respuesta
353
- (`nativeActivity`), así que el otro modelo lo ve. Si se te agota la cuota de Claude, el
354
- error lo dice claro y no se reintenta en bucle: cambia de modelo y sigue.
355
- - **Escribir mientras trabaja** (*steer*) o **interrumpir y escribir otra cosa**: el mensaje
356
- llega (cola nativa de Claude Code o, si no hay, junto al resultado de la tool); un turno
357
- interrumpido se cancela en el agente antes del nuevo.
358
- - **Cambiar de agente** (`claude-code` ↔ `claude-code-plan`) o de **set de tools**: misma
359
- sesión, en caliente. A un agente con **otro perfil nativo**: fork de la sesión.
360
- - **Cambiar de modelo acp** (opus ↔ sonnet): misma sesión, `session/set_model`.
361
- - **Compactación**: Claude compacta su propia sesión antes que OpenCode (`autoCompactPct`).
362
- Si OpenCode compacta igualmente, el resumen se pide a la **sesión viva** (caché caliente),
363
- no a una sesión nueva con todo el historial. Con `historyMode: "v2"`, además, la sesión se
364
- compacta en nativo y **adopta** el checkpoint de OpenCode, o se pone al día con el de otro
365
- modelo, sin sesión nueva.
366
- - **Revertir** bifurca la sesión justo antes del mensaje revertido (`smartRevert`): el agente
367
- "olvida" lo deshecho sin replay y con el prefijo en caché. Si no hay punto de bifurcación
368
- (p. ej. tras reiniciar el proceso), crea sesión nueva. Un replay completo es acotado
369
- (~400K caracteres) y va etiquetado como historia, con tu petición actual aparte.
370
-
371
- Cada decisión (reuso, continuación, sesión nueva, discrepancias de `historyMode: "shadow"`…)
372
- queda en `~/.acp-model-provider/logs/acp-AAAAMMDD.log`. En una conversación normal verás
373
- `"decision":"reuse"` en cada turno; `"drop"` solo en reverts y compactaciones.
374
-
375
- ---
376
-
377
- ## Diagnóstico
378
-
379
- El provider escribe siempre su log en `~/.acp-model-provider/logs/acp-AAAAMMDD.log` (OpenCode no recoge el stderr de los plugins): ciclo de vida de sesiones y una línea por decisión de turno. `ACP_DEBUG=1` añade el detalle; `ACP_LOG=0` lo desactiva; `ACP_LOG_DIR` lo reubica.
380
-
381
- Para reportar un problema de sincronía de historial: `ACP_RECORD=<dir>` vuelca cada prompt tal como lo construye OpenCode y la decisión tomada; `node scripts/sanitize-recording.mjs <grabación> <salida> <cwd>` lo anonimiza para convertirlo en fixture de test.
382
-
383
- | Síntoma | Causa / solución |
384
- |---|---|
385
- | `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`). |
386
- | 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`. |
387
- | `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). |
388
- | `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. |
389
- | 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. |
390
- | Muchas líneas `shadow-diff` en el log | Con `historyMode: "shadow"` son las veces que la huella nueva habría evitado (o provocado) un reset. Si solo ves `legacy: diverged` → `anchors: append`, `"v2"` te ahorra esos replays. |
391
- | 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). |
392
- | 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. |
393
- | 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. |
394
- | El agente no pregunta, asume | Debe usar `mcp__opencode__question`. Esa tool solo la registra OpenCode en TUI (`client: "cli"`) o con `enableQuestionTool`. |
395
- | 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. |
396
- | 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. |
397
-
398
- Comando de mantenimiento:
620
+ ## Diagnostics and troubleshooting
621
+
622
+ The provider always writes its log to `~/.acp-model-provider/logs/acp-YYYYMMDD.log`, because
623
+ OpenCode doesn't capture a plugin's stderr. The log holds the session lifecycle and one line
624
+ per turn decision.
625
+
626
+ | Variable | Effect |
627
+ | --- | --- |
628
+ | `ACP_DEBUG=1` | Debug lines too, on stderr and in the file. |
629
+ | `ACP_LOG=0` | No log file. |
630
+ | `ACP_LOG_DIR=<dir>` | Log file location. |
631
+ | `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. |
632
+
633
+ | Symptom | Cause / fix |
634
+ | --- | --- |
635
+ | `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`. |
636
+ | 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`. |
637
+ | `API Error: 400 … extra usage` | The system prompt triggered Anthropic's classifier. Use `systemPromptMode: "preset"` (the default) or a `claude-*` agent. Typical causes: `append`/`replace`, or an agent from another plugin with an aggressive system prompt. See [Billing](#billing-subscription-vs-extra-usage). |
638
+ | `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. |
639
+ | 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`. |
640
+ | `Claude Code: usage limit reached …` | Your subscription limit. Switch to another agent (not `claude-*`) and come back later: the session is kept. |
641
+ | `Claude Code: the model … is reserved for the Claude Code agents` | An `acp` model was used by another agent. Pick a `claude-*` agent, or another model for that agent. See [pairing](#models-are-paired-with-the-claude-code-agents). |
642
+ | 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. |
643
+ | 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). |
644
+ | 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. |
645
+ | 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. |
646
+ | 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). |
647
+ | Claude doesn't search the web | The injected agents include the **native** `WebSearch`, in case OpenCode's `websearch` isn't available. |
648
+ | Slow with many tools | With hundreds of tools each step can take ~1 min. Reduce the tools exposed with the agent's `permissions` ruleset. |
649
+
650
+ Maintenance command:
399
651
 
400
652
  ```bash
401
- # Refresca los cachés de descubrimiento + models.dev y previsualiza los modelos
653
+ # Refresh the discovery and models.dev caches and preview the models
402
654
  npx opencode-claude-code-acpbridge sync claude-agent-acp
403
655
  ```
404
656
 
405
657
  ---
406
658
 
407
- ## Estado y limitaciones
408
-
409
- - ✅ Chat con streaming y **bloque de razonamiento** visible en OpenCode (`Thought: …`, vía `thinking` summarized por defecto).
410
- - ✅ **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).
411
- - ✅ **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"`).
412
- - ✅ 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`.
413
- - ✅ 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).
414
- - ✅ **Agentes inyectados** (`claude-code`, `claude-code-plan`) con modo/esfuerzo por agente aplicados en caliente; **tu `opencode.json` tiene precedencia** (merge).
415
- - ✅ **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).
416
- - ✅ **Consumo de tokens**: OpenCode ve el tamaño **real** del contexto (`usage_update.used` del agente), también en los pasos con tools; el desglose de caché sale de los totales del turno. (`PromptResponse.usage` es la **suma** de todos los requests del turno: reportarla tal cual inflaba el contexto y disparaba compactaciones.)
417
- - ✅ **Varias conversaciones a la vez** (y subagentes), aisladas, con un solo proceso del agente; sesiones inactivas cerradas solas.
418
- - ✅ **Cambio de modelo a mitad de sesión** en ambos sentidos (acp ↔ otros providers), sin perder contexto — ver [Continuidad](#continuidad-de-sesión-y-coste-de-tokens).
419
- - ℹ️ **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.
420
- - 🔜 Roadmap: `historyMode: "v2"` por defecto tras validarlo en uso real (modo sombra).
659
+ ## Status and limitations
660
+
661
+ | Status | Feature |
662
+ | --- | --- |
663
+ | ✅ | Streaming chat, with Claude's **reasoning block** shown in OpenCode (summarized thinking by default). |
664
+ | ✅ | **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). |
665
+ | ✅ | **Clean-brain mode** (`mode: "bypassPermissions"`, no native toggles): no native tools, no claude.ai connectors, only OpenCode's tools. |
666
+ | ✅ | **Auto-registration** with models.dev metadata, refreshable with `npx opencode-claude-code-acpbridge sync`. |
667
+ | ✅ | **Persistent session per conversation** (prompt cache), **resume across restarts**, several conversations and subagents at once on one agent process, idle sessions closed automatically. |
668
+ | ✅ | **Token usage**: OpenCode sees the **real** context size, including on tool steps. |
669
+ | ✅ | **Model switching mid-session** in both directions (`acp` ↔ other providers) without losing context. |
670
+ | ℹ️ | 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. |
671
+ | 🔜 | `historyMode: "v2"` as the default, once validated in real use (shadow mode). |
672
+
673
+ ---
674
+
675
+ ## Upgrading from 0.8.x (OpenCode V1)
676
+
677
+ 1. **Plugin config**: `"plugin": [[pkg, {opts}]]` → `"plugins": [{ "package": pkg, "options": {…} }]`. If you
678
+ declared `provider.acp` by hand, remove it: the plugin registers it at runtime.
679
+ 2. **Agents**:
680
+ - the `agent:` section becomes `agents:`;
681
+ - `permission` (a map) becomes `permissions` (a ruleset: `[{ "action": "bash", "resource": "git *", "effect": "allow" }]`);
682
+ - `disable` becomes `disabled`.
683
+ 3. **Variants**: `acp/opus:low` → `acp/opus#low` (V2 syntax `provider/model#variant`).
684
+ 4. **Per-agent options** (mode, effort, native toggles): from `agent.<n>.options` to
685
+ `plugins[0].options.agents.<n>.options`.
686
+ 5. **`claude_permission` is gone.** The permission bridge now uses OpenCode's `question` tool.
687
+ Move any bridge rules to `agents.<n>.permissions`; the bridge evaluates them fail-closed.
688
+ 6. **Local development**: point `package` at the repository **directory**, which has a root
689
+ `index.js` re-exporting `dist/`. Don't point it at a file. Build with `npm run build`.
690
+ 7. **CLI**: `opencode run` without `-m` ignores `agent.model`, so use `opencode run -m acp/…`.
691
+
692
+ Details in [CHANGELOG.md](CHANGELOG.md) and the port plan in [MIGRATION_V2.md](MIGRATION_V2.md).
421
693
 
422
694
  ---
423
695
 
424
- ## Desarrollo
696
+ ## Development
425
697
 
426
- 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/)**.
698
+ ```bash
699
+ git clone https://github.com/aorizondo/opencode-claude-code-acpbridge.git
700
+ cd opencode-claude-code-acpbridge
701
+ npm install
702
+ npm run build # → dist/
703
+ npm test # tsc + node --test
704
+ ```
705
+
706
+ - **Unit tests** (`npm test`) need no external services. An in-process fake ACP agent
707
+ (`test/fake-agent.mjs`: real ACP, plus real MCP against `mcp-runtime.js`) covers each
708
+ behaviour and each fixed bug. The prompts in `test/fixtures/v2/` are **real** OpenCode V2
709
+ prompts recorded with `ACP_RECORD`.
710
+ - **Against the real agent**: `VERIFY_MODEL=haiku node scripts/verify-<name>.mjs`. Scripts:
711
+ - `verify-session-continuity`;
712
+ - `verify-smart-revert`;
713
+ - `verify-interleave-fix`;
714
+ - `verify-stream-integrity`;
715
+ - `verify-billing`.
716
+ - **Run your checkout in OpenCode**: point the plugin at the repository directory,
717
+ `"plugins": [{ "package": "/path/to/opencode-claude-code-acpbridge", "options": { "command": "claude-agent-acp" } }]`.
718
+ OpenCode loads `<dir>/index.*`, and the root `index.js` re-exports `dist/`, so build first.
719
+ - **Smoke test**: `opencode run --standalone --agent claude-default -m acp/default "…"` in a test
720
+ project. The bridge's `question` dialog needs the interactive TUI.
721
+ - The package also exports `createACPProviderFromEnv`. It is the upstream
722
+ `@mcpc-tech/acp-ai-provider` without tool orchestration, if you only want plain chat.
723
+
724
+ Architecture, flows (deferred tools, sessions/resume, billing) and how to extend it are in
725
+ **[docs/DEVELOPMENT.md](docs/DEVELOPMENT.md)**. Example configs, one per use case, are in
726
+ **[examples/](examples/README.md)**:
727
+
728
+ | Example | Shows |
729
+ | --- | --- |
730
+ | [01-minimal.jsonc](examples/01-minimal.jsonc) | The smallest working config |
731
+ | [02-per-agent-permissions.jsonc](examples/02-per-agent-permissions.jsonc) | Permissions per agent |
732
+ | [03-opencode-fidelity.jsonc](examples/03-opencode-fidelity.jsonc) | Follow OpenCode's system prompt and agents (extra usage) |
733
+ | [04-model-and-effort.jsonc](examples/04-model-and-effort.jsonc) | Model and effort |
734
+ | [05-custom-agents.jsonc](examples/05-custom-agents.jsonc) | Your own injected agents, replacing the defaults |
735
+ | [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`) |
736
+ | [07-manual-provider.jsonc](examples/07-manual-provider.jsonc) | A manual provider |
737
+ | [08-permission-bridge.jsonc](examples/08-permission-bridge.jsonc) | The permission bridge |
427
738
 
428
739
  ```
429
- index.js # entrypoint de directorio local: re-exporta dist/ (Host.resolve busca <dir>/index.*)
740
+ index.js # local-directory entrypoint: re-exports dist/ (OpenCode loads <dir>/index.*)
430
741
  src/
431
- index.ts # re-exports: createACPModelProvider (provider) + default Plugin.define({ id, setup })
742
+ index.ts # exports createACPModelProvider (provider) + default Plugin.define (plugin)
432
743
  provider/
433
- factory.ts # createACPModelProvider (orquestador) + createACPProviderFromEnv (upstream sin orquestación)
434
- model.ts # ACPOrchestratorModel (LanguageModelV3): turnos, sesión persistente/resume/fork, cola y lote de
435
- # tool-calls, steer/aborto, puente question, usage, compactación; ACPModelView (modelo por vista)
436
- history.ts # huella del historial: claves legacy + anclas (historyMode), normalización
437
- recorder.ts # ACP_RECORD: graba los prompts reales de OpenCode y cada decisión
438
- env.ts # config por variables de entorno
744
+ factory.ts # createACPModelProvider (orchestrator) + createACPProviderFromEnv (upstream, no orchestration)
745
+ model.ts # ACPOrchestratorModel (LanguageModelV3): turns, persistent session / resume / fork,
746
+ # tool-call queue and batching, steer/abort, question bridge, usage, compaction
747
+ history.ts # history fingerprint: legacy keys + anchors (historyMode), normalisation
748
+ recorder.ts # ACP_RECORD: records OpenCode's real prompts and every decision
749
+ env.ts # configuration from environment variables
439
750
  acp/
440
- mcp-host.ts # MCP server sintético (TCP): expone las tools de OpenCode y DIFIERE cada tools/call
441
- mcp-runtime.ts # runtime stdio que el agente spawnea (MCP a mano, sin deps) → TCP al host
442
- claude-config.ts # "cerebro limpio" + CLAUDE_CONFIG_DIR aislado con credenciales; modo/effort/systemPrompt
751
+ mcp-host.ts # internal MCP server (TCP): exposes OpenCode's tools and DEFERS each tools/call
752
+ mcp-runtime.ts # stdio runtime the agent spawns (hand-written MCP, no deps) → TCP to the host
753
+ claude-config.ts # clean brain + isolated CLAUDE_CONFIG_DIR with credentials; mode/effort/system prompt
443
754
  plugin/
444
- index.ts # Plugin.define setup: provider.transform (registro acp), agent.transform (claude-code + reglas),
445
- # hooks context/compaction/generate (ocSession/ocAgent/resume*/requestKind), title (sin modelo),
446
- # event: session.revert.* → clearLink
447
- bridge-rules.ts # store de reglas por agente + always.json; evaluate() fail-closed (ignora action:"*")
448
- discover.ts # conexión ACP efímera → modelos/modos/capabilities
449
- catalog.ts # metadata de models.dev + variants de effort + buildModelsInfo (→ Model.Info[])
450
- cache.ts · sessions.ts # cachés TTL / registro de sesiones OpenCode↔ACP
451
- log.ts # log a fichero (~/.acp-model-provider/logs) + stderr
755
+ index.ts # Plugin.define: provider.transform (acp), agent.transform (claude-<mode> + rules),
756
+ # context/compaction/generate hooks, title (no model), session.revert.* → clearLink
757
+ pairing.ts # one agent per mode; acp models ↔ claude-* agents (pairTarget, subagentDecision)
758
+ bridge-rules.ts # per-agent rule store + always.json; fail-closed evaluate() (ignores action:"*")
759
+ discover.ts # short-lived ACP connection → models / modes / capabilities
760
+ catalog.ts # models.dev metadata + effort variants → Model.Info[]
761
+ cache.ts · sessions.ts # TTL caches / OpenCode↔ACP session registry
762
+ log.ts # file log (~/.acp-model-provider/logs) + stderr
452
763
  bin/cli.ts # `opencode-claude-code-acpbridge sync`
453
- test/ # node --test: fake-agent.mjs (agente ACP en proceso), fixtures/v2 (prompts reales grabados)
764
+ test/ # node --test: fake-agent.mjs (in-process ACP agent), fixtures/v2 (recorded real prompts)
454
765
  ```
455
766
 
456
- Build: `npm run build` (genera `dist/`). **Tests**: `npm test` — sin dependencias nuevas (`node --test`): un agente ACP falso en proceso (`test/fake-agent.mjs`, ACP real + MCP real contra `mcp-runtime.js`) cubre cada comportamiento y cada fallo corregido, y `test/fixtures/v2/` son prompts **reales** de OpenCode V2 grabados con `ACP_RECORD`. Contra el agente real: `VERIFY_MODEL=haiku node scripts/verify-*.mjs`. 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.
457
-
458
- **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.
767
+ Changes: [CHANGELOG.md](CHANGELOG.md).
459
768
 
460
- ## Licencia
769
+ ## License
461
770
 
462
- MIT
771
+ [MIT](LICENSE)