opencode-claude-code-acpbridge 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +314 -191
  2. package/LICENSE +21 -0
  3. package/README.md +596 -279
  4. package/dist/acp/claude-config.d.ts +52 -0
  5. package/dist/acp/claude-config.d.ts.map +1 -1
  6. package/dist/acp/claude-config.js +6 -2
  7. package/dist/acp/claude-config.js.map +1 -1
  8. package/dist/acp/mcp-host.d.ts +10 -0
  9. package/dist/acp/mcp-host.d.ts.map +1 -1
  10. package/dist/acp/mcp-host.js +17 -4
  11. package/dist/acp/mcp-host.js.map +1 -1
  12. package/dist/acp/mcp-runtime.js +21 -4
  13. package/dist/acp/mcp-runtime.js.map +1 -1
  14. package/dist/log.d.ts +11 -0
  15. package/dist/log.d.ts.map +1 -0
  16. package/dist/log.js +50 -0
  17. package/dist/log.js.map +1 -0
  18. package/dist/plugin/compat.d.ts +14 -0
  19. package/dist/plugin/compat.d.ts.map +1 -0
  20. package/dist/plugin/compat.js +45 -0
  21. package/dist/plugin/compat.js.map +1 -0
  22. package/dist/plugin/index.d.ts +3 -0
  23. package/dist/plugin/index.d.ts.map +1 -1
  24. package/dist/plugin/index.js +80 -14
  25. package/dist/plugin/index.js.map +1 -1
  26. package/dist/plugin/sessions.d.ts +11 -8
  27. package/dist/plugin/sessions.d.ts.map +1 -1
  28. package/dist/plugin/sessions.js +37 -4
  29. package/dist/plugin/sessions.js.map +1 -1
  30. package/dist/provider/factory.d.ts.map +1 -1
  31. package/dist/provider/factory.js +5 -3
  32. package/dist/provider/factory.js.map +1 -1
  33. package/dist/provider/history.d.ts +44 -0
  34. package/dist/provider/history.d.ts.map +1 -0
  35. package/dist/provider/history.js +145 -0
  36. package/dist/provider/history.js.map +1 -0
  37. package/dist/provider/model.d.ts +160 -23
  38. package/dist/provider/model.d.ts.map +1 -1
  39. package/dist/provider/model.js +1373 -480
  40. package/dist/provider/model.js.map +1 -1
  41. package/dist/provider/recorder.d.ts +5 -0
  42. package/dist/provider/recorder.d.ts.map +1 -0
  43. package/dist/provider/recorder.js +63 -0
  44. package/dist/provider/recorder.js.map +1 -0
  45. package/docs/DEVELOPMENT.md +413 -127
  46. package/examples/01-minimal.jsonc +12 -9
  47. package/examples/02-per-agent-permissions.jsonc +39 -0
  48. package/examples/03-opencode-fidelity.jsonc +21 -0
  49. package/examples/04-model-and-effort.jsonc +35 -0
  50. package/examples/05-custom-agents.jsonc +32 -0
  51. package/examples/06-claude-ecosystem.jsonc +28 -0
  52. package/examples/07-manual-provider.jsonc +55 -0
  53. package/examples/08-permission-bridge.jsonc +42 -0
  54. package/examples/README.md +35 -17
  55. package/package.json +35 -29
  56. package/examples/02-permisos-por-agente.jsonc +0 -34
  57. package/examples/03-fidelidad-opencode.jsonc +0 -21
  58. package/examples/04-modelo-y-esfuerzo.jsonc +0 -36
  59. package/examples/05-agentes-personalizados.jsonc +0 -29
  60. package/examples/06-ecosistema-claude.jsonc +0 -24
  61. package/examples/07-provider-manual.jsonc +0 -42
  62. package/examples/08-puente-permisos.jsonc +0 -50
package/CHANGELOG.md CHANGED
@@ -1,244 +1,367 @@
1
1
  # Changelog
2
2
 
3
- Todas las versiones notables de `opencode-claude-code-acpbridge`. Formato basado en
4
- [Keep a Changelog](https://keepachangelog.com/); versionado [SemVer](https://semver.org/).
3
+ All notable changes to `opencode-claude-code-acpbridge`. The format is based on
4
+ [Keep a Changelog](https://keepachangelog.com/) and versions follow [SemVer](https://semver.org/).
5
5
 
6
- ## 0.9.0 — OpenCode V2 (2026-10-01)
6
+ > **OpenCode V2 only since 0.9.0.** Versions 0.9.0 and later load only in OpenCode V2. If you
7
+ > are still on OpenCode V1, stay on 0.8.x. See [MIGRATION_V2.md](MIGRATION_V2.md).
7
8
 
8
- > ⚠️ **0.9.0+ solo funciona con OpenCode V2; para OpenCode V1 conserva 0.8.x.**
9
+ ## [0.10.1] — 2026-10-23
10
+
11
+ ### Fixed
12
+
13
+ - **The usage-limit error was retried by OpenCode ≥ 2.1.** OpenCode 2.1 no longer decides
14
+ retries by the wording of the error message: any error it cannot classify is retried,
15
+ about 10 attempts over ~84 s, before the user can switch models. The error is now an
16
+ `APICallError` with HTTP 402 and `x-should-retry: false`. OpenCode classifies that as
17
+ `QuotaExceeded` and fails at once.
18
+
19
+ ### Changed
20
+
21
+ - Documentation translated to English and rewritten for newcomers; OpenCode V2 only stated
22
+ explicitly.
23
+ - Runtime messages (usage-limit error, session notes, mode-change notice) translated to English.
24
+ - `@opencode/plugin` peer range narrowed to `^2.0.14` (excludes a future 3.x).
25
+
26
+ ### Added
27
+
28
+ - MIT `LICENSE` file.
29
+ - Load-time compatibility warnings: OpenCode major version, and `claude-agent-acp` older than
30
+ the tested 0.31.
31
+ - `prepublishOnly` install check (`scripts/check-install.mjs`).
32
+
33
+ ## [0.10.0] — 2026-10-22 — history sync, concurrency and continuity across models
34
+
35
+ A full review of the bridge against the OpenCode V2 source, `claude-agent-acp` 0.31 and
36
+ **real** recorded sessions. The goal: switch between `acp` and other models in the same
37
+ session without losing anything, and reuse the Claude Code session whenever possible.
38
+ Everything below is covered by `npm test` (a fake ACP agent plus real V2 prompts) and by the
39
+ scripts that run against the real agent.
40
+
41
+ ### Fixed
42
+
43
+ - **Claude's own reply was resent every turn** as `"Assistant: …"` inside the user message
44
+ (seen in transcripts; the model once called it "a fake message"). The provider now
45
+ recognises its own output (emitted texts, ids carrying its prefix) and does not send it back.
46
+ - **Lost messages**: what you typed while the agent was working (a *steer*), and the message
47
+ sent after **interrupting** a tool, were treated as a continuation of the turn and never
48
+ arrived. Now a steer joins the running turn (Claude Code's native queue), and an
49
+ interruption cancels the turn before the new message is sent.
50
+ - **Turns by another model attributed to Claude**: they arrived as
51
+ `Assistant: [Called tool …]`, so Claude believed it had made them. They now come wrapped in
52
+ `<other_model_turn>`.
53
+ - **Concurrent tool calls dropped** (native subagents running in parallel): the second call
54
+ was lost and the turn hung. Calls are now queued; read-only ones (`readOnlyHint`) are batched
55
+ into one step that OpenCode runs in parallel.
56
+ - **Security**: the bridge's `perm_N` ids repeated across processes, so an old answer
57
+ ("Always allow") could approve a new permission. Ids now carry their own prefix and the last
58
+ match wins.
59
+ - An old prompt finishing (cancelled or merged) closed the stream of the following turn; text
60
+ from an aborted turn showed up at the start of the next one.
61
+ - Two simultaneous calls for the same conversation created two sessions (one orphaned).
62
+ - **Usage**: `PromptResponse.usage` is the sum of every request in the turn; reporting it as a
63
+ single request inflated the context size and triggered early compactions. The real context
64
+ occupancy (`usage_update.used`) is reported now, also on tool steps.
65
+ - **Sessions were never closed**: each one left a `claude` process running. Now
66
+ `session/close` is sent when a session is discarded, with an idle TTL (15 min; subagents
67
+ 2 min) and an LRU of 6.
68
+ - **Junk titles** (`<invoke name="Read">`): with `preset`, the title instructions never reached
69
+ Claude. The plugin now titles the session from its first message, without calling the model.
70
+ - **OpenCode subagents running on `acp`** (they inherit the parent's model): with no profile,
71
+ every OpenCode tool asked the bridge for permission, and `general` (which has no `question`
72
+ tool) got them denied. Now every agent auto-allows OpenCode's tools, and the bridge denies
73
+ with a reason when the agent cannot ask. Rules are published for every agent.
74
+ - Switching to an agent with a different native profile reused the session with the old
75
+ profile; it now **forks** it (`session/fork`), keeping the context.
76
+ - Going back from plan to `claude-code` downgraded to `default` the mode chosen when the plan
77
+ was approved.
78
+ - Resume after a restart resent the provider's own traffic, and happened even when the
79
+ registry entry belonged to another conversation; the registry is now also updated mid-turn.
80
+ - A session lost on the agent side (dead `claude` process) failed on every turn; it is now
81
+ dropped and resumed.
82
+ - `mcp-runtime` ignored SIGTERM (registering the handler disables the default exit).
83
+
84
+ ### Added
85
+
86
+ - **Native compaction**: `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=75` (`autoCompactPct`) makes Claude
87
+ compact before OpenCode does; if OpenCode compacts, the summary comes from the **live
88
+ session** (before: a full cold replay, 17K+ characters in the recording).
89
+ - **`historyMode`** (default `shadow`): a fingerprint made of anchors (user messages + tool ids)
90
+ that is immune to V2 re-rendering (reasoning→text, model switches), transient plan reminders
91
+ and DCP tags. In `shadow` it only logs disagreements; `v2` decides, and also adopts
92
+ OpenCode's checkpoint or catches up with another model's.
93
+ - **`smartRevert`** (on by default): a revert forks the session right before the reverted
94
+ message (`resumeSessionAt`) instead of replaying; `false` turns it off.
95
+ - **One agent process for every model** of the provider; switching models uses
96
+ `session/set_model` without losing the session.
97
+ - **Portable native activity** (`nativeActivity`): Task/WebSearch/Skill leave a `⚙ …` line
98
+ (with its result) in the reply, so any model can see it.
99
+ - **ExitPlanMode** with the real options (auto / accept edits / approve each edit / keep
100
+ planning); a typed answer comes back as feedback.
101
+ - Claude usage limit → a clear, non-retryable error ("switch models").
102
+ - Bounded (~400K characters) and labelled replay; the current request is sent separately.
103
+ - V2's initial **Code Mode** catalog is forwarded as context.
104
+ - Log file under `~/.acp-model-provider/logs/`, the `ACP_RECORD` recorder,
105
+ `scripts/sanitize-recording.mjs`, the `npm test` suite, `scripts/verify-smart-revert.mjs`.
106
+ - Options: `historyMode`, `catchupResultChars`, `parallelTools`, `toolBatchMs`,
107
+ `autoCompactPct`, `nativeActivity(Chars)`, `maxLiveSessions`, `idle/childSessionTtlMs`,
108
+ `smartRevert`; plugin: `titleFromModel`.
109
+
110
+ ### Changed
111
+
112
+ - Native `Read` is no longer in the default profile (what it read never reached OpenCode's
113
+ history); V2's `read` covers images and PDFs.
114
+ - `allowedTools` defaults to `["mcp__opencode"]` for every agent.
115
+ - The `claude-code*` agents deny `compress` (opencode-dcp).
116
+ - The session registry has an in-memory cache and pruning (30 days / 500 entries).
117
+
118
+ ## [0.9.0] — 2026-10-01 — OpenCode V2
119
+
120
+ > ⚠️ **0.9.0+ works only with OpenCode V2; for OpenCode V1 stay on 0.8.x.**
9
121
  >
10
- > El port es un **breaking change total de runtime**: el plugin V1
11
- > (`export default { id, server }`, hooks `config`/`chat.params`) no se carga en
12
- > OpenCode V2, y el plugin V2 (`Plugin.define`) no se carga en OpenCode V1.
122
+ > The port is a **complete runtime breaking change**: the V1 plugin
123
+ > (`export default { id, server }`, `config`/`chat.params` hooks) does not load in OpenCode V2,
124
+ > and the V2 plugin (`Plugin.define`) does not load in OpenCode V1.
13
125
 
14
- Port del plugin y del provider al runtime de plugins **V2** de OpenCode.
126
+ Port of the plugin and the provider to OpenCode's **V2** plugin runtime.
15
127
 
16
128
  ### Breaking changes
17
129
 
18
- | Área | V1 (0.8.x) | V2 (0.9.0) |
130
+ | Area | V1 (0.8.x) | V2 (0.9.0) |
19
131
  | :--- | :--- | :--- |
20
- | **Runtime de plugins** | `export default { id, server }`, hooks `config`/`chat.params` | `Plugin.define({ id, setup })` con API de promesas (`setup` retorna cleanup) |
21
- | **Config del plugin** | `"plugin": [[pkg, {opts}]]` | `"plugins": [{ "package", "options" }]` |
22
- | **Auto-registro del provider** | el hook `config` mutaba `cfg.provider.acp` | `provider.transform` lo registra como `aisdk:<spec>` (con `options.command`); si declaras `provider.<id>` a mano, no lo sobreescribe |
23
- | **Inyección por llamada** | hook `chat.params` → `providerOptions.acp.{ocSession, resumeId, resumeLen}` | `session.hook("context")` → `ocSession`, `ocAgent`, `resumeId`, `resumeLen`, `resumeLastUsage`, `resumeConvKey` + options del agente por llamada |
24
- | **Agentes (config)** | sección `agent:` con `permission` (mapa `{tool: "allow"\|"deny"\|"ask"\|glob}`) y `disable` | sección `agents:` con `permissions` (ruleset array `[{action, resource, effect}]`), `disabled` y `mode: "subagent"\|"primary"\|"all"` |
25
- | **Options por agente** | `agent.<n>.options` (mode/effort/native*) | `plugins[0].options.agents.<n>.options` (misma options, otra ruta) |
26
- | **Puente de permisos** | meta-tool `claude_permission` (prompt `ask` con `ctx.ask`) | emite un **tool-call de la tool nativa `question`** de OpenCode (diálogo `Allow once` / `Always allow` / `Deny`); reglas desde `agents.<n>.permissions` evaluadas en `src/plugin/bridge-rules.ts`, **fail-closed** (ignora `action:"*"` a propósito); `Always allow` persiste en `~/.acp-model-provider/always.json` |
27
- | **Variantes de esfuerzo** | `acp/opus:low` | `acp/opus#low` (`provider/model#variant`) |
28
- | **Revert / compactación** | fingerprint por `chat.params` | eventos `session.revert.committed\|cleared` → `clearLink` |
29
- | **Desarrollo local** | destino = fichero (`…/dist/index.js`) | destino = **ruta de directorio** con `index.js` raíz (V2 `Host.resolve` busca `<dir>/index.*`); los ficheros se rechazan |
30
- | **CLI** | `opencode run` aplicaba `agent.model` | `opencode run` **sin `-m` ignora `agent.model`** (usa el model global); usa `-m acp/…` |
31
- | **Requisitos** | OpenCode V1 | OpenCode **V2 (`>= 2.0.14`)** y agente `@agentclientprotocol/claude-agent-acp` (antes `@zed-industries/claude-agent-acp`) |
32
-
33
- Guía práctica de migración: ver [README § De 0.8.x (V1) a 0.9.x (V2)](README.md#de-08x-v1-a-09x-v2)
34
- y [MIGRATION_V2.md](MIGRATION_V2.md).
132
+ | **Plugin runtime** | `export default { id, server }`, `config`/`chat.params` hooks | `Plugin.define({ id, setup })` with the promise API (`setup` returns a cleanup) |
133
+ | **Plugin config** | `"plugin": [[pkg, {opts}]]` | `"plugins": [{ "package", "options" }]` |
134
+ | **Provider auto-registration** | the `config` hook mutated `cfg.provider.acp` | `provider.transform` registers it as `aisdk:<spec>` (with `options.command`); if you declare `provider.<id>` by hand, it is not overwritten |
135
+ | **Per-call injection** | `chat.params` hook → `providerOptions.acp.{ocSession, resumeId, resumeLen}` | `session.hook("context")` → `ocSession`, `ocAgent`, `resumeId`, `resumeLen`, `resumeLastUsage`, `resumeConvKey`, plus the agent's options, per call |
136
+ | **Agents (config)** | `agent:` section with `permission` (map `{tool: "allow"\|"deny"\|"ask"\|glob}`) and `disable` | `agents:` section with `permissions` (ruleset array `[{action, resource, effect}]`), `disabled` and `mode: "subagent"\|"primary"\|"all"` |
137
+ | **Per-agent options** | `agent.<n>.options` (mode/effort/native*) | `plugins[0].options.agents.<n>.options` (same options, different path) |
138
+ | **Permission bridge** | `claude_permission` meta-tool (an `ask` prompt via `ctx.ask`) | emits a **tool call to OpenCode's built-in `question` tool** (dialog `Allow once` / `Always allow` / `Deny`); rules from `agents.<n>.permissions` evaluated in `src/plugin/bridge-rules.ts`, **fail-closed** (deliberately ignores `action:"*"`); `Always allow` is saved in `~/.acp-model-provider/always.json` |
139
+ | **Effort variants** | `acp/opus:low` | `acp/opus#low` (`provider/model#variant`) |
140
+ | **Revert / compaction** | fingerprint via `chat.params` | `session.revert.committed\|cleared` events → `clearLink` |
141
+ | **Local development** | target = a file (`…/dist/index.js`) | target = a **directory path** with a root `index.js` (V2's `Host.resolve` looks for `<dir>/index.*`); files are rejected |
142
+ | **CLI** | `opencode run` applied `agent.model` | `opencode run` **without `-m` ignores `agent.model`** (uses the global model); use `-m acp/…` |
143
+ | **Requirements** | OpenCode V1 | OpenCode **V2 (`>= 2.0.14`)** and the `@agentclientprotocol/claude-agent-acp` agent (formerly `@zed-industries/claude-agent-acp`) |
144
+
145
+ Practical migration guide: [MIGRATION_V2.md](MIGRATION_V2.md) and the [README](README.md).
35
146
 
36
147
  ### Added
37
148
 
38
- - **Auto-registro del provider como `aisdk:<spec>`** (con `options.command`); si declaras
39
- `provider.<id>` a mano en config, el plugin ya no lo sobreescribe (guard nuevo).
40
- - **Revert/compactación**: el plugin escucha `session.revert.*` y limpia el enlace de
41
- sesión → replay completo cuando la historia diverge.
42
- - **Entrypoint de directorio local**: `index.js` en la raíz re-exporta `dist/`
43
- (`Host.resolve` de V2 busca `<dir>/index.*`); en dev, `package` = ruta de directorio.
149
+ - **Provider auto-registration as `aisdk:<spec>`** (with `options.command`); if you declare
150
+ `provider.<id>` by hand in config, the plugin no longer overwrites it (new guard).
151
+ - **Revert/compaction**: the plugin listens to `session.revert.*` and clears the session link
152
+ → a full replay when the history diverges.
153
+ - **Local directory entrypoint**: a root `index.js` re-exports `dist/` (V2's `Host.resolve`
154
+ looks for `<dir>/index.*`); in development, `package` = the directory path.
44
155
 
45
156
  ## [0.8.0] — 2026-08-21
46
157
 
47
- Versión centrada en el **coste de tokens** y en la **continuidad de sesión**. La causa
48
- común de casi todos los problemas era la misma: el provider recreaba la sesión ACP con
49
- demasiada facilidad, y cada recreación implica replay del historial completo y cache de
50
- prompt frío. Ahora una conversación sobrevive a cambios de agente, de tools y de system
51
- prompt manteniendo la misma sesión de Claude Code.
158
+ A release focused on **token cost** and **session continuity**. Almost every problem had the
159
+ same root cause: the provider recreated the ACP session far too easily, and each recreation
160
+ means a full history replay and a cold prompt cache. Now a conversation survives changes of
161
+ agent, tools and system prompt while keeping the same Claude Code session.
52
162
 
53
163
  ### ⚠️ Breaking
54
164
 
55
- - **`claudeCode.configDir` pasa a heredar `~/.claude` por defecto** (antes `"isolated"`).
56
- Las sesiones iniciadas desde OpenCode se guardan ahora en `~/.claude/projects/…`, así
57
- que **se pueden retomar nativamente con `claude --resume <id>`** (el provider imprime el
58
- id al crear cada sesión). Esto **no** reintroduce el ecosistema del usuario: `settingSources`,
59
- `tools` y `strictMcpConfig` siguen gobernando qué carga el agente; `configDir` solo decide
60
- dónde vive su estado. Para volver al comportamiento anterior: `"configDir": "isolated"`.
61
- Efecto colateral positivo: desaparece el symlink de credenciales y con él la clase de
62
- bugs de desincronización 401.
63
- - **El límite de contexto publicado deja de inflarse a 1M** para el modelo `default`; solo
64
- las variantes `[1m]` reales lo declaran. Anunciar 1M impedía que la auto-compactación de
65
- OpenCode se disparase nunca y la conversación crecía sin límite.
165
+ - **`claudeCode.configDir` now inherits `~/.claude` by default** (previously `"isolated"`).
166
+ Sessions started from OpenCode are now stored in `~/.claude/projects/…`, so **they can be
167
+ resumed natively with `claude --resume <id>`** (the provider prints the id when it creates
168
+ each session). This does **not** bring back the user's ecosystem: `settingSources`, `tools`
169
+ and `strictMcpConfig` still decide what the agent loads; `configDir` only decides where its
170
+ state lives. To get the old behaviour back: `"configDir": "isolated"`. A welcome side effect:
171
+ the credentials symlink is gone, and with it the class of 401 desync bugs.
172
+ - **The advertised context limit is no longer inflated to 1M** for the `default` model; only
173
+ the real `[1m]` variants declare it. Advertising 1M kept OpenCode's auto-compaction from ever
174
+ triggering, and the conversation grew without bound.
66
175
 
67
176
  ### Fixed
68
177
 
69
- - **Gasto de tokens desproporcionado (causa principal).** `sentLen` se fijaba al inicio del
70
- turno y no se actualizaba en la rama de continuación, así que en cada turno se reenviaban
71
- como texto plano **todos los `tool-call`/`tool-result` del turno anterior** — volcados
72
- íntegros de ficheros, salidas de shell, greps — que el agente **ya tenía** en su sesión.
73
- Además invalidaba el prompt cache en cada turno. Ahora el estado registra la huella del
74
- historial ya enviado y las llamadas propias (identificadas por el prefijo nonce del host)
75
- se omiten del catch-up; los resultados ajenos se truncan a 2000 caracteres.
76
- - **Cambiar de agente destruía la sesión y replayaba todo.** `systemKey` hasheaba el system
77
- prompt de OpenCode incluso con `systemPromptMode: "preset"`, modo en el que ese system
78
- **nunca se envía al agente**. Cualquier cambio de agente — o el vaivén de los bloques
79
- dinámicos de OpenCode (fecha, `AGENTS.md`, skills) — recreaba la sesión por un texto que
80
- el agente jamás vio. Ahora el system solo cuenta como identidad cuando de verdad viaja,
81
- y el flujo `claude-code-plan` → build → `claude-code` mantiene la misma sesión ACP.
82
- - **Un cambio en el set de tools ya no recrea la sesión.** Se aplica en caliente a la sesión
83
- viva mediante `notifications/tools/list_changed` por el canal MCP.
84
- - **La llamada del modelo de títulos/resúmenes ya no destruía la conversación.** Llega con
85
- `tools=0` sobre el mismo modelo y sesión; ahora se atiende en una sesión efímera aparte.
86
- - **Texto truncado y razonamiento invisible (misma causa).** Texto y thinking llegan por
87
- stdio ACP mientras las tool-calls llegan por el socket TCP del `McpHost`, sin orden
88
- garantizado. Al cerrar el stream por una tool-call, todo lo que seguía llegando se
89
- **descartaba en silencio** — y el thinking se emite justo antes de cada tool-call, por eso
90
- desaparecía casi entero aun con `effort: max`. Ahora esos chunks se **bufferizan** y se
91
- vuelcan en orden en el stream de continuación.
92
- - **Revertir mensajes dejaba las dos partes desincronizadas.** El provider solo guardaba un
93
- contador, así que un historial truncado caía en un fallback silencioso que reenviaba
94
- **todo** el historial encima de una sesión que ya lo tenía. Ahora se compara la huella del
95
- historial y se distingue *append* (envía solo lo nuevo) de *revert* / *divergencia por
96
- compactación* (sesión nueva desde el historial truncado). El plugin además escucha
97
- `session.updated` y descarta el enlace registrado en cuanto se mueve el punto de revert.
98
- - **Dos conversaciones simultáneas se destruían la sesión mutuamente.** Había un único
99
- `TurnState` por instancia de modelo, compartido por todos los chats y subagentes: cada
100
- turno alternaba de conversación y forzaba replay completo. Ahora hay **una sesión por
101
- conversación** (con cota LRU) y los callbacks del agente se enrutan por `sessionId`.
102
- - **`claude-code-plan` no tenía forma de salir de modo plan.** `ExitPlanMode` no estaba
103
- expuesta al agente, no veía el `plan_exit` de OpenCode, y el bridge le re-forzaba `plan`
104
- en cada turno: un ciclo cerrado que dejaba muerto todo el manejo de `switch_mode` ya
105
- escrito. Ahora se expone `ExitPlanMode`, y **volver a elegir el agente de plan a mano
106
- vuelve a aplicar `mode: "plan"`** (antes `modeChangedByAgent` no se reseteaba nunca).
107
- - **Aprobar un plan concedía `bypassPermissions`.** Se elegía la primera opción `allow_*`
108
- ofrecida por el agente, que es la más amplia. Ahora se prefiere `default` (aprobación
109
- manual de ediciones) para `switch_mode`.
110
- - **El agente no usaba la tool `question` de OpenCode.** Su instrucción vive en el system
111
- prompt de OpenCode, que con `preset` no se reenvía, y su `AskUserQuestion` nativa está
112
- deshabilitada por el propio agente ACP. Ahora la **descripción** de `question` lo indica
113
- explícitamente (una descripción de tool no es system prompt: no afecta a la facturación).
114
- - **El agente se quedaba sin búsqueda web.** OpenCode solo registra su `websearch` para
115
- `providerID: "opencode"` (o con exa/parallel), y `WebSearch` nativa estaba en
116
- `disallowedTools`. Ahora `WebSearch` nativa forma parte del perfil.
117
- - **Los resultados de tools llegaban aplanados a texto**, perdiendo imágenes y adjuntos.
118
- Ahora el contenido estructurado se mapea a bloques MCP.
119
- - **Un `effort` rechazado se tragaba en silencio**; ahora se avisa por stderr.
120
- - **Cancelar un turno ya no tira la sesión**: se cancela el turno y se conserva la sesión
121
- (y su cache) para el siguiente mensaje.
178
+ - **Disproportionate token spend (the main cause).** `sentLen` was set at the start of the
179
+ turn and not updated in the continuation branch, so every turn resent as plain text **all the
180
+ `tool-call`/`tool-result` pairs of the previous turn** (full file dumps, shell output, greps)
181
+ that the agent **already had** in its session. It also invalidated the prompt cache every
182
+ turn. The state now records the fingerprint of the history already sent, and the provider's
183
+ own calls (identified by the host's nonce prefix) are left out of the catch-up; other
184
+ models' results are truncated to 2000 characters.
185
+ - **Switching agents destroyed the session and replayed everything.** `systemKey` hashed
186
+ OpenCode's system prompt even with `systemPromptMode: "preset"`, a mode in which that system
187
+ prompt is **never sent to the agent**. Any agent switch, or the churn of OpenCode's dynamic
188
+ blocks (date, `AGENTS.md`, skills), recreated the session over text the agent never saw.
189
+ The system prompt now counts as identity only when it is actually sent, and the
190
+ `claude-code-plan` → build → `claude-code` flow keeps the same ACP session.
191
+ - **A change in the tool set no longer recreates the session.** It is applied live to the
192
+ running session through `notifications/tools/list_changed` over the MCP channel.
193
+ - **The title/summary model call no longer destroyed the conversation.** It arrives with
194
+ `tools=0` on the same model and session; it is now served by a separate throwaway session.
195
+ - **Truncated text and invisible reasoning (same cause).** Text and thinking arrive over ACP
196
+ stdio, while tool calls arrive over the `McpHost` TCP socket, with no guaranteed ordering.
197
+ When a tool call closed the stream, everything still arriving was **silently dropped**, and
198
+ since thinking is emitted right before each tool call, it vanished almost entirely even with
199
+ `effort: max`. Those chunks are now **buffered** and flushed in order into the continuation
200
+ stream.
201
+ - **Reverting messages left both sides out of sync.** The provider kept only a counter, so a
202
+ truncated history fell into a silent fallback that resent **the whole** history on top of a
203
+ session that already had it. The history fingerprint is now compared to tell an *append*
204
+ (send only what's new) from a *revert* / *compaction divergence* (new session from the
205
+ truncated history). The plugin also listens to `session.updated` and drops the registered
206
+ link as soon as the revert point moves.
207
+ - **Two simultaneous conversations destroyed each other's session.** There was a single
208
+ `TurnState` per model instance, shared by every chat and subagent: each turn switched
209
+ conversation and forced a full replay. There is now **one session per conversation** (with an
210
+ LRU bound), and the agent's callbacks are routed by `sessionId`.
211
+ - **`claude-code-plan` had no way out of plan mode.** `ExitPlanMode` was not exposed to the
212
+ agent, it did not see OpenCode's `plan_exit`, and the bridge forced `plan` again every turn:
213
+ a closed loop that left all the already-written `switch_mode` handling dead. `ExitPlanMode`
214
+ is now exposed, and **re-selecting the plan agent by hand re-applies `mode: "plan"`**
215
+ (before, `modeChangedByAgent` was never reset).
216
+ - **Approving a plan granted `bypassPermissions`.** The first `allow_*` option offered by the
217
+ agent was picked, and that is the broadest one. `default` (manual approval of edits) is now
218
+ preferred for `switch_mode`.
219
+ - **The agent did not use OpenCode's `question` tool.** Its instruction lives in OpenCode's
220
+ system prompt, which is not forwarded with `preset`, and its native `AskUserQuestion` is
221
+ disabled by the ACP agent itself. The `question` tool's **description** now says so
222
+ explicitly (a tool description is not a system prompt: it doesn't affect billing).
223
+ - **The agent had no web search.** OpenCode only registers its `websearch` for
224
+ `providerID: "opencode"` (or with exa/parallel), and native `WebSearch` was in
225
+ `disallowedTools`. Native `WebSearch` is now part of the profile.
226
+ - **Tool results arrived flattened to text**, losing images and attachments. Structured
227
+ content is now mapped to MCP blocks.
228
+ - **A rejected `effort` was silently swallowed**; a warning is now printed to stderr.
229
+ - **Cancelling a turn no longer tears down the session**: the turn is cancelled and the session
230
+ (and its cache) is kept for the next message.
122
231
 
123
232
  ### Changed
124
233
 
125
- - **`claude-code` y `claude-code-plan` comparten exactamente el mismo perfil de tools y
126
- permisos**, y difieren **solo** en el modo inicial. Antes diferían también en
127
- `nativeTools`, lo que dejaba un estado a medias: el agente salía de plan por su cuenta
128
- (OpenCode no cambia de agente por ello) y creía poder editar mientras OpenCode seguía
129
- dándole el perfil restringido.
130
- - **Nueva opción `claudeCode.forwardEnvContext`** (default `true`): reenvía la parte
131
- **factual** del system prompt de OpenCode (`<env>` — directorio de trabajo, raíz del
132
- workspace, git, plataforma, fecha — y `<available_references>`) como contexto de usuario.
133
- Con `preset` el system nunca llega al agente y trabajaba sin saber dónde estaba. Solo
134
- viajan bloques factuales, nunca las instrucciones de comportamiento de OpenCode, así que
135
- la sesión sigue en suscripción (verificado con `scripts/verify-billing.mjs`). Se envía
136
- completo una vez por sesión y después solo el delta de lo que cambió.
137
- - El id de sesión de Claude Code se registra por stderr al crearla, sin necesidad de
138
- `ACP_DEBUG`, junto al comando para retomarla.
234
+ - **`claude-code` and `claude-code-plan` share exactly the same tool and permission profile**,
235
+ and differ **only** in their initial mode. Before, they also differed in `nativeTools`, which
236
+ left a half-way state: the agent left plan mode on its own (OpenCode does not switch agents
237
+ because of it) and believed it could edit while OpenCode still gave it the restricted
238
+ profile.
239
+ - **New option `claudeCode.forwardEnvContext`** (default `true`): forwards the **factual** part
240
+ of OpenCode's system prompt (`<env>`: working directory, workspace root, git, platform, date;
241
+ and `<available_references>`) as user context. With `preset` the system prompt never reaches
242
+ the agent, so it worked without knowing where it was. Only factual blocks are sent, never
243
+ OpenCode's behavioural instructions, so the session stays on the subscription (verified with
244
+ `scripts/verify-billing.mjs`). It is sent in full once per session, then only the delta of
245
+ what changed.
246
+ - The Claude Code session id is logged to stderr when the session is created, without needing
247
+ `ACP_DEBUG`, together with the command to resume it.
139
248
 
140
249
  ### Known issues
141
250
 
142
- - El desglose de `usage` por turno lo reporta el agente ACP de forma acumulativa y algún
143
- turno puede aparecer con delta 0; el total de la sesión sí es correcto.
251
+ - The per-turn `usage` breakdown is reported cumulatively by the ACP agent, and some turns may
252
+ show a delta of 0; the session total is correct.
144
253
 
145
- ## [Unreleased]
254
+ ## Changes between 0.7.0 and 0.8.0
255
+
256
+ These entries were listed as "Unreleased" after 0.7.0 and shipped with 0.8.0.
146
257
 
147
258
  ### Added
148
- - **Manejo correcto de `ExitPlanMode`.** Cuando el agente sale de modo plan (llega como
149
- `requestPermission` con `toolCall.kind === "switch_mode"`):
150
- - el **plan** (markdown en `rawInput.plan`) ahora se **renderiza como texto** del
151
- asistente antes del prompt de aprobación, en vez de quedar enterrado en la metadata;
152
- - el permiso se etiqueta de forma estable como **`ExitPlanMode`** (regla
153
- `permission: { ExitPlanMode: "allow" }` posible; por defecto pregunta);
154
- - se escucha `current_mode_update` y, tras aprobar (plan → default/acceptEdits), el
155
- bridge **deja de re-forzar** el modo del agente, de modo que la implementación continúa
156
- en la misma sesión en lugar de volver a plan en el siguiente turno.
259
+
260
+ - **Proper `ExitPlanMode` handling.** When the agent leaves plan mode (it arrives as a
261
+ `requestPermission` with `toolCall.kind === "switch_mode"`):
262
+ - the **plan** (markdown in `rawInput.plan`) is now **rendered as assistant text** before the
263
+ approval prompt, instead of being buried in the metadata;
264
+ - the permission is labelled consistently as **`ExitPlanMode`** (a
265
+ `permission: { ExitPlanMode: "allow" }` rule is possible; by default it asks);
266
+ - `current_mode_update` is now handled and, once the plan is approved (plan →
267
+ default/acceptEdits), the bridge **stops forcing** the agent's mode again, so the
268
+ implementation continues in the same session instead of going back to plan on the next
269
+ turn.
157
270
 
158
271
  ### Fixed
159
- - **Cambiar de agente normal a `claude-code` (ACP) a mitad de sesión ignoraba todo
160
- el progreso previo.** Tanto la reutilización en caliente de una sesión ACP viva
161
- (`this.current`, que sobrevive intacta a un cambio de agente) como el `resume`
162
- tras un reinicio de proceso asumían que lo único nuevo desde el último turno ACP
163
- era el último mensaje de usuario (`lastUserBlocks`). Si entre medias otro agente
164
- (p. ej. un modelo distinto) corrió turnos sobre la misma conversación de
165
- OpenCode, esos turnos nunca llegaban a Claude Code: se resumía/reutilizaba con
166
- su historial antiguo y solo el mensaje más reciente, dando la impresión de una
167
- sesión nueva. Ahora `TurnState` guarda `sentLen` (hasta dónde llega el
168
- conocimiento del agente) y cada envío usa `catchUpBlocks`, que reconstruye como
169
- transcripción (con prefijo de rol) **todo** lo ocurrido desde `sentLen` en
170
- adelante — 1 mensaje en el caso normal, el tramo completo si hubo un agente
171
- intercalado.
172
- - **Corrupción de resultados de tools (resultados rancios/misruteados).** El `toolCallId`
173
- se acuñaba como `acp_${counter}` con un contador **por `McpHost`** que se **reinicia a 0**
174
- en cada reset de sesión ACP (cambio de tools/system prompt, nueva conversación, resume).
175
- Dentro de una misma conversación, OpenCode reenvía todo el historial; tras un reset una
176
- llamada nueva volvía a recibir `acp_1` y `detectContinuation` la casaba con un tool-result
177
- **viejo** del historial → glob devolvía un README, bash devolvía "background agent task
178
- launched", etc. Ahora cada host usa un **prefijo nonce aleatorio** (`acp_<hex>_${counter}`),
179
- así que los IDs nunca colisionan entre sesiones, reinicios de proceso ni resume.
180
- - **`claude-code-plan`: los subagentes (`Task`) fallaban.** El agente de plan no tenía
181
- `nativeSubagents`, así que su `Task` no era el nativo de Claude Code sino el `task`
182
- reenviado de OpenCode → OpenCode creaba subagentes (`explore`, …) enrutados a **otros
183
- providers** (`opencode-go`/`opencode`), que caían con *Bad Gateway* / *Insufficient
184
- Balance* / *ProviderModelNotFound*. Ahora `claude-code-plan` comparte la misma base de
185
- features nativos que `claude-code` (subagentes nativos que corren en la suscripción y
186
- delegan tools a OpenCode), con `mode: "plan"` y sin la tool de edición nativa
187
- (`NotebookEdit`) por ser modo de solo lectura.
272
+
273
+ - **Switching from a normal agent to `claude-code` (ACP) mid-session ignored all previous
274
+ progress.** Both the live reuse of an ACP session (`this.current`, which survives an agent
275
+ switch intact) and the `resume` after a process restart assumed that the only new thing
276
+ since the last ACP turn was the latest user message (`lastUserBlocks`). If another agent
277
+ (e.g. a different model) ran turns in the same OpenCode conversation in between, those turns
278
+ never reached Claude Code: it resumed/reused with its old history plus only the newest
279
+ message, which looked like a fresh session. `TurnState` now keeps `sentLen` (how far the
280
+ agent's knowledge goes), and each send uses `catchUpBlocks`, which rebuilds as a transcript
281
+ (with role prefixes) **everything** that happened from `sentLen` on: one message in the
282
+ normal case, the whole stretch if another agent ran in between.
283
+ - **Corrupted tool results (stale/misrouted results).** The `toolCallId` was minted as
284
+ `acp_${counter}` with a counter **per `McpHost`** that **reset to 0** on every ACP session
285
+ reset (tool/system prompt change, new conversation, resume). Within one conversation
286
+ OpenCode resends the whole history; after a reset a new call got `acp_1` again, and
287
+ `detectContinuation` matched it with an **old** tool result in the history: glob returned a
288
+ README, bash returned "background agent task launched", and so on. Each host now uses a
289
+ **random nonce prefix** (`acp_<hex>_${counter}`), so ids never collide across sessions,
290
+ process restarts or resumes.
291
+ - **`claude-code-plan`: subagents (`Task`) failed.** The plan agent had no `nativeSubagents`,
292
+ so its `Task` was not Claude Code's native one but OpenCode's forwarded `task`. OpenCode then
293
+ created subagents (`explore`, …) routed to **other providers** (`opencode-go`/`opencode`),
294
+ which failed with *Bad Gateway* / *Insufficient Balance* / *ProviderModelNotFound*.
295
+ `claude-code-plan` now shares the same native feature base as `claude-code` (native
296
+ subagents that run on the subscription and delegate tools to OpenCode), with `mode: "plan"`
297
+ and without the native editing tool (`NotebookEdit`), since plan mode is read-only.
188
298
 
189
299
  ## [0.7.0] — 2026-06-27
190
300
 
191
- Capacidades nativas de Claude Code dentro de OpenCode, con un **puente de permisos**
192
- que mantiene a OpenCode al mando de cada acción ("potencia nativa sin estropear nada").
301
+ Native Claude Code capabilities inside OpenCode, with a **permission bridge** that keeps
302
+ OpenCode in charge of every action ("native power without breaking anything").
193
303
 
194
304
  ### Added
195
- - **Puente de permisos**: cuando el agente usa una tool **nativa** de Claude (Skill, Read,
196
- NotebookEdit, Task, búsqueda de recursos MCP), su `requestPermission` (ACP) se enruta al
197
- **prompt `ask` de OpenCode** vía la meta-tool `claude_permission`. El prompt muestra la
198
- **tool nativa** y la acción; soporta **"Allow always"** y **reglas glob por tool**
305
+
306
+ - **Permission bridge**: when the agent uses a **native** Claude tool (Skill, Read,
307
+ NotebookEdit, Task, MCP resource search), its `requestPermission` (ACP) is routed to
308
+ **OpenCode's `ask` prompt** through the `claude_permission` meta-tool. The prompt shows the
309
+ **native tool** and the action; it supports **"Allow always"** and **per-tool glob rules**
199
310
  (`permission: { Bash: { "git *": "allow" }, Skill: { "*": "ask" } }`).
200
- - **Toggles de features nativos** en `claudeCode` (componen las options del SDK; con todos
201
- off = cerebro limpio): `nativeTools`, `resourceSearch`, `nativeSubagents` (subagente que
202
- delega a OpenCode), `nativeSkills`, `projectMemory`, `skillShell`, `allowedTools`.
203
- Verificado: **todos mantienen la suscripción** (0 extra usage).
204
- - **Modelo híbrido**: las tools comunes (bash/read/write/edit/grep/…) las orquesta OpenCode
205
- sin doble permiso (`allowedTools: ["mcp__opencode"]`); las nativas superiores van por el puente.
206
- - Tool nativa **`Read`** habilitada en el agente `claude-code` (lectura multimodal: imágenes/PDF/notebooks).
207
- - Scripts de verificación (`scripts/`): `verify-billing.mjs`, `spike-permission-bridge.mjs`.
311
+ - **Native feature toggles** in `claudeCode` (they compose the SDK options; with all of them
312
+ off you get the clean brain): `nativeTools`, `resourceSearch`, `nativeSubagents` (a subagent
313
+ that delegates to OpenCode), `nativeSkills`, `projectMemory`, `skillShell`, `allowedTools`.
314
+ Verified: **all of them keep the subscription** (0 extra usage).
315
+ - **Hybrid model**: common tools (bash/read/write/edit/grep/…) are orchestrated by OpenCode
316
+ without double permission prompts (`allowedTools: ["mcp__opencode"]`); the better native
317
+ tools go through the bridge.
318
+ - Native **`Read`** tool enabled in the `claude-code` agent (multimodal reading:
319
+ images/PDF/notebooks).
320
+ - Verification scripts (`scripts/`): `verify-billing.mjs`, `spike-permission-bridge.mjs`.
208
321
 
209
322
  ### Changed
210
- - El agente `claude-code` pasa de `mode: "bypassPermissions"` a **`mode: "default"`** (para que el
211
- puente actúe). El "cerebro limpio" clásico sigue disponible (`mode: "bypassPermissions"` + sin toggles).
323
+
324
+ - The `claude-code` agent moves from `mode: "bypassPermissions"` to **`mode: "default"`** (so
325
+ the bridge can act). The classic clean brain is still available (`mode: "bypassPermissions"`
326
+ with no toggles).
212
327
 
213
328
  ### Fixed
214
- - **`host closed`**: `onCancel` ya no derriba la sesión mientras hay un tool-call/permiso diferido en
215
- vuelo (OpenCode cancela el stream al pausar para el `ask`); un **watchdog** libera si la continuación
216
- no llega.
217
- - **Desincronización de auth (401)**: el symlink de credenciales del config dir aislado se **re-enlaza en
218
- cada arranque** (el agente podía reemplazarlo con un archivo obsoleto al refrescar el token).
219
- - El puente **falla cerrado** (deniega ante un veredicto ambiguo); `endTurn`/reuse **drenan** los permisos
220
- pendientes para que el agente nunca quede colgado.
221
- - `claude_permission` se **filtra del host** (el agente ya no la ve como `mcp__opencode__claude_permission`).
222
- - El agente ya no intenta tools nativas comunes que no puede ejecutar (`disallowedTools` Bash/Write/Edit/…).
329
+
330
+ - **`host closed`**: `onCancel` no longer tears down the session while a deferred tool call or
331
+ permission is in flight (OpenCode cancels the stream when it pauses for the `ask`); a
332
+ **watchdog** releases it if the continuation never arrives.
333
+ - **Auth desync (401)**: the credentials symlink of the isolated config dir is **re-linked on
334
+ every start** (the agent could replace it with a stale file when refreshing the token).
335
+ - The bridge **fails closed** (denies on an ambiguous verdict); `endTurn`/reuse **drain**
336
+ pending permissions so the agent is never left hanging.
337
+ - `claude_permission` is **filtered out of the host** (the agent no longer sees it as
338
+ `mcp__opencode__claude_permission`).
339
+ - The agent no longer tries common native tools it cannot run (`disallowedTools`
340
+ Bash/Write/Edit/…).
223
341
 
224
342
  ## [0.6.0]
225
343
 
226
344
  ### Changed
227
- - **Renombrado**: `acp-model-provider` → **`opencode-claude-code-acpbridge`** (plugin exclusivo para usar
228
- Claude Code en OpenCode).
345
+
346
+ - **Renamed**: `acp-model-provider` → **`opencode-claude-code-acpbridge`** (a plugin dedicated
347
+ to using Claude Code inside OpenCode).
229
348
 
230
349
  ### Added
231
- - `strictMcpConfig` (default `true`): ignora los connectors de la cuenta claude.ai (Gmail/Drive/Supabase/…).
232
- - `thinking` por defecto `{type:"enabled", display:"summarized"}`: el **bloque de razonamiento** se ve en OpenCode.
233
- - **Reanudación de sesión entre procesos** (registro `sessions.json` + `unstable_resumeSession`).
234
- - **Reporte de consumo de tokens** (mapeo de `PromptResponse.usage` del ACP).
350
+
351
+ - `strictMcpConfig` (default `true`): ignores the claude.ai account connectors
352
+ (Gmail/Drive/Supabase/…).
353
+ - `thinking` defaults to `{type:"enabled", display:"summarized"}`: the **reasoning block** is
354
+ visible in OpenCode.
355
+ - **Session resume across processes** (`sessions.json` registry + `unstable_resumeSession`).
356
+ - **Token usage reporting** (mapping of ACP's `PromptResponse.usage`).
235
357
 
236
358
  ## [0.5.x]
237
359
 
238
360
  ### Added
239
- - **Auto-registro** del provider (config mínima): descubre los modelos del agente e inyecta `provider.acp`
240
- con metadata de models.dev.
241
- - **Agentes inyectados** `claude-code` / `claude-code-plan`, con modo/esfuerzo por agente en caliente; la
242
- config del usuario en `opencode.json` tiene precedencia (merge).
243
- - **Facturación por suscripción** (`systemPromptMode: "preset"`): 0 extra usage.
244
- - Documentación completa (README + `docs/DEVELOPMENT.md` + `examples/`).
361
+
362
+ - **Provider auto-registration** (minimal config): discovers the agent's models and injects
363
+ `provider.acp` with models.dev metadata.
364
+ - **Injected agents** `claude-code` / `claude-code-plan`, with per-agent mode/effort changed
365
+ live; the user's config in `opencode.json` takes precedence (merge).
366
+ - **Subscription billing** (`systemPromptMode: "preset"`): 0 extra usage.
367
+ - Complete documentation (README + `docs/DEVELOPMENT.md` + `examples/`).